summaryrefslogtreecommitdiff
path: root/src/xmpp_stream_pkix.erl
blob: 59f5d820eaa6d730c05bdb540b3e6dee7b6fc859 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
%%%-------------------------------------------------------------------
%%% @author Evgeny Khramtsov <ekhramtsov@process-one.net>
%%% @copyright (C) 2016, Evgeny Khramtsov
%%% @doc
%%%
%%% @end
%%% Created : 13 Dec 2016 by Evgeny Khramtsov <ekhramtsov@process-one.net>
%%%-------------------------------------------------------------------
-module(xmpp_stream_pkix).

%% API
-export([authenticate/1, authenticate/2]).

-include("xmpp.hrl").
-include_lib("public_key/include/public_key.hrl").
-include("XmppAddr.hrl").

%%%===================================================================
%%% API
%%%===================================================================
-spec authenticate(xmpp_stream_in:state() | xmpp_stream_out:state())
      -> {ok, binary()} | {error, binary(), binary()}.
authenticate(State) ->
    authenticate(State, <<"">>).

-spec authenticate(xmpp_stream_in:state() | xmpp_stream_out:state(), binary())
      -> {ok, binary()} | {error, binary(), binary()}.
authenticate(#{xmlns := ?NS_SERVER, remote_server := Peer,
	       sockmod := SockMod, socket := Socket}, _Authzid) ->
    case SockMod:get_peer_certificate(Socket) of
	{ok, Cert} ->
	    case SockMod:get_verify_result(Socket) of
		0 ->
		    case ejabberd_idna:domain_utf8_to_ascii(Peer) of
			false ->
			    {error, <<"Cannot decode remote server name">>, Peer};
			AsciiPeer ->
			    case lists:any(
				   fun(D) -> match_domain(AsciiPeer, D) end,
				   get_cert_domains(Cert)) of
				true ->
				    {ok, Peer};
				false ->
				    {error, <<"Certificate host name mismatch">>, Peer}
			    end
		    end;
		VerifyRes ->
		    {error, fast_tls:get_cert_verify_string(VerifyRes, Cert), Peer}
	    end;
	{error, _Reason} ->
	    {error, <<"Cannot get peer certificate">>, Peer};
	error ->
	    {error, <<"Cannot get peer certificate">>, Peer}
    end;
authenticate(_State, _Authzid) ->
    %% TODO: client PKIX authentication
    {error, <<"Client certificate verification not implemented">>, <<"">>}.

%%%===================================================================
%%% Internal functions
%%%===================================================================
get_cert_domains(Cert) ->
    TBSCert = Cert#'Certificate'.tbsCertificate,
    Subject = case TBSCert#'TBSCertificate'.subject of
		  {rdnSequence, Subj} -> lists:flatten(Subj);
		  _ -> []
	      end,
    Extensions = case TBSCert#'TBSCertificate'.extensions of
		     Exts when is_list(Exts) -> Exts;
		     _ -> []
		 end,
    lists:flatmap(
      fun(#'AttributeTypeAndValue'{type = ?'id-at-commonName',value = Val}) ->
	      case 'OTP-PUB-KEY':decode('X520CommonName', Val) of
		  {ok, {_, D1}} ->
		      D = if is_binary(D1) -> D1;
			     is_list(D1) -> list_to_binary(D1);
			     true -> error
			  end,
		      if D /= error ->
			      case jid:from_string(D) of
				  #jid{luser = <<"">>, lserver = LD,
				       lresource = <<"">>} ->
				      [LD];
				  _ -> []
			      end;
			 true -> []
		      end;
		  _ -> []
	      end;
	 (_) -> []
      end, Subject) ++
	lists:flatmap(
	  fun(#'Extension'{extnID = ?'id-ce-subjectAltName',
			   extnValue = Val}) ->
		  BVal = if is_list(Val) -> list_to_binary(Val);
			    true -> Val
			 end,
		  case 'OTP-PUB-KEY':decode('SubjectAltName', BVal) of
		      {ok, SANs} ->
			  lists:flatmap(
			    fun({otherName, #'AnotherName'{'type-id' = ?'id-on-xmppAddr',
							   value = XmppAddr}}) ->
				    case 'XmppAddr':decode('XmppAddr', XmppAddr) of
					{ok, D} when is_binary(D) ->
					    case jid:from_string(D) of
						#jid{luser = <<"">>,
						     lserver = LD,
						     lresource = <<"">>} ->
						    case ejabberd_idna:domain_utf8_to_ascii(LD) of
							false ->
							    [];
							PCLD ->
							    [PCLD]
						    end;
						_ -> []
					    end;
					_ -> []
				    end;
			       ({dNSName, D}) when is_list(D) ->
				    case jid:from_string(list_to_binary(D)) of
					#jid{luser = <<"">>,
					     lserver = LD,
					     lresource = <<"">>} ->
					    [LD];
					_ -> []
				    end;
			       (_) -> []
			    end, SANs);
		      _ -> []
		  end;
	     (_) -> []
	  end, Extensions).

match_domain(Domain, Domain) -> true;
match_domain(Domain, Pattern) ->
    DLabels = str:tokens(Domain, <<".">>),
    PLabels = str:tokens(Pattern, <<".">>),
    match_labels(DLabels, PLabels).

match_labels([], []) -> true;
match_labels([], [_ | _]) -> false;
match_labels([_ | _], []) -> false;
match_labels([DL | DLabels], [PL | PLabels]) ->
    case lists:all(fun (C) ->
			   $a =< C andalso C =< $z orelse
			     $0 =< C andalso C =< $9 orelse
			       C == $- orelse C == $*
		   end,
		   binary_to_list(PL))
	of
      true ->
	  Regexp = ejabberd_regexp:sh_to_awk(PL),
	  case ejabberd_regexp:run(DL, Regexp) of
	    match -> match_labels(DLabels, PLabels);
	    nomatch -> false
	  end;
      false -> false
    end.