util.x509: And functions for converting between DER and PEM
[prosody.git] / util / x509.lua
1 -- Prosody IM
2 -- Copyright (C) 2010 Matthew Wild
3 -- Copyright (C) 2010 Paul Aurich
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 -- TODO: I feel a fair amount of this logic should be integrated into Luasec,
10 -- so that everyone isn't re-inventing the wheel.  Dependencies on
11 -- IDN libraries complicate that.
12
13
14 -- [TLS-CERTS] - http://tools.ietf.org/html/rfc6125
15 -- [XMPP-CORE] - http://tools.ietf.org/html/rfc6120
16 -- [SRV-ID]    - http://tools.ietf.org/html/rfc4985
17 -- [IDNA]      - http://tools.ietf.org/html/rfc5890
18 -- [LDAP]      - http://tools.ietf.org/html/rfc4519
19 -- [PKIX]      - http://tools.ietf.org/html/rfc5280
20
21 local nameprep = require "util.encodings".stringprep.nameprep;
22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local base64 = require "util.encodings".base64;
24 local log = require "util.logger".init("x509");
25 local pairs, ipairs = pairs, ipairs;
26 local s_format = string.format;
27 local t_insert = table.insert;
28 local t_concat = table.concat;
29
30 module "x509"
31
32 local oid_commonname = "2.5.4.3"; -- [LDAP] 2.3
33 local oid_subjectaltname = "2.5.29.17"; -- [PKIX] 4.2.1.6
34 local oid_xmppaddr = "1.3.6.1.5.5.7.8.5"; -- [XMPP-CORE]
35 local oid_dnssrv   = "1.3.6.1.5.5.7.8.7"; -- [SRV-ID]
36
37 -- Compare a hostname (possibly international) with asserted names
38 -- extracted from a certificate.
39 -- This function follows the rules laid out in
40 -- sections 6.4.1 and 6.4.2 of [TLS-CERTS]
41 --
42 -- A wildcard ("*") all by itself is allowed only as the left-most label
43 local function compare_dnsname(host, asserted_names)
44         -- TODO: Sufficient normalization?  Review relevant specs.
45         local norm_host = idna_to_ascii(host)
46         if norm_host == nil then
47                 log("info", "Host %s failed IDNA ToASCII operation", host)
48                 return false
49         end
50
51         norm_host = norm_host:lower()
52
53         local host_chopped = norm_host:gsub("^[^.]+%.", "") -- everything after the first label
54
55         for i=1,#asserted_names do
56                 local name = asserted_names[i]
57                 if norm_host == name:lower() then
58                         log("debug", "Cert dNSName %s matched hostname", name);
59                         return true
60                 end
61
62                 -- Allow the left most label to be a "*"
63                 if name:match("^%*%.") then
64                         local rest_name = name:gsub("^[^.]+%.", "")
65                         if host_chopped == rest_name:lower() then
66                                 log("debug", "Cert dNSName %s matched hostname", name);
67                                 return true
68                         end
69                 end
70         end
71
72         return false
73 end
74
75 -- Compare an XMPP domain name with the asserted id-on-xmppAddr
76 -- identities extracted from a certificate.  Both are UTF8 strings.
77 --
78 -- Per [XMPP-CORE], matches against asserted identities don't include
79 -- wildcards, so we just do a normalize on both and then a string comparison
80 --
81 -- TODO: Support for full JIDs?
82 local function compare_xmppaddr(host, asserted_names)
83         local norm_host = nameprep(host)
84
85         for i=1,#asserted_names do
86                 local name = asserted_names[i]
87
88                 -- We only want to match against bare domains right now, not
89                 -- those crazy full-er JIDs.
90                 if name:match("[@/]") then
91                         log("debug", "Ignoring xmppAddr %s because it's not a bare domain", name)
92                 else
93                         local norm_name = nameprep(name)
94                         if norm_name == nil then
95                                 log("info", "Ignoring xmppAddr %s, failed nameprep!", name)
96                         else
97                                 if norm_host == norm_name then
98                                         log("debug", "Cert xmppAddr %s matched hostname", name)
99                                         return true
100                                 end
101                         end
102                 end
103         end
104
105         return false
106 end
107
108 -- Compare a host + service against the asserted id-on-dnsSRV (SRV-ID)
109 -- identities extracted from a certificate.
110 --
111 -- Per [SRV-ID], the asserted identities will be encoded in ASCII via ToASCII.
112 -- Comparison is done case-insensitively, and a wildcard ("*") all by itself
113 -- is allowed only as the left-most non-service label.
114 local function compare_srvname(host, service, asserted_names)
115         local norm_host = idna_to_ascii(host)
116         if norm_host == nil then
117                 log("info", "Host %s failed IDNA ToASCII operation", host);
118                 return false
119         end
120
121         -- Service names start with a "_"
122         if service:match("^_") == nil then service = "_"..service end
123
124         norm_host = norm_host:lower();
125         local host_chopped = norm_host:gsub("^[^.]+%.", "") -- everything after the first label
126
127         for i=1,#asserted_names do
128                 local asserted_service, name = asserted_names[i]:match("^(_[^.]+)%.(.*)");
129                 if service == asserted_service then
130                         if norm_host == name:lower() then
131                                 log("debug", "Cert SRVName %s matched hostname", name);
132                                 return true;
133                         end
134
135                         -- Allow the left most label to be a "*"
136                         if name:match("^%*%.") then
137                                 local rest_name = name:gsub("^[^.]+%.", "")
138                                 if host_chopped == rest_name:lower() then
139                                         log("debug", "Cert SRVName %s matched hostname", name)
140                                         return true
141                                 end
142                         end
143                         if norm_host == name:lower() then
144                                 log("debug", "Cert SRVName %s matched hostname", name);
145                                 return true
146                         end
147                 end
148         end
149
150         return false
151 end
152
153 function verify_identity(host, service, cert)
154         local ext = cert:extensions()
155         if ext[oid_subjectaltname] then
156                 local sans = ext[oid_subjectaltname];
157
158                 -- Per [TLS-CERTS] 6.3, 6.4.4, "a client MUST NOT seek a match for a
159                 -- reference identifier if the presented identifiers include a DNS-ID
160                 -- SRV-ID, URI-ID, or any application-specific identifier types"
161                 local had_supported_altnames = false
162
163                 if sans[oid_xmppaddr] then
164                         had_supported_altnames = true
165                         if service == "_xmpp-client" or service == "_xmpp-server" then
166                                 if compare_xmppaddr(host, sans[oid_xmppaddr]) then return true end
167                         end
168                 end
169
170                 if sans[oid_dnssrv] then
171                         had_supported_altnames = true
172                         -- Only check srvNames if the caller specified a service
173                         if service and compare_srvname(host, service, sans[oid_dnssrv]) then return true end
174                 end
175
176                 if sans["dNSName"] then
177                         had_supported_altnames = true
178                         if compare_dnsname(host, sans["dNSName"]) then return true end
179                 end
180
181                 -- We don't need URIs, but [TLS-CERTS] is clear.
182                 if sans["uniformResourceIdentifier"] then
183                         had_supported_altnames = true
184                 end
185
186                 if had_supported_altnames then return false end
187         end
188
189         -- Extract a common name from the certificate, and check it as if it were
190         -- a dNSName subjectAltName (wildcards may apply for, and receive,
191         -- cat treats)
192         --
193         -- Per [TLS-CERTS] 1.8, a CN-ID is the Common Name from a cert subject
194         -- which has one and only one Common Name
195         local subject = cert:subject()
196         local cn = nil
197         for i=1,#subject do
198                 local dn = subject[i]
199                 if dn["oid"] == oid_commonname then
200                         if cn then
201                                 log("info", "Certificate has multiple common names")
202                                 return false
203                         end
204
205                         cn = dn["value"];
206                 end
207         end
208
209         if cn then
210                 -- Per [TLS-CERTS] 6.4.4, follow the comparison rules for dNSName SANs.
211                 return compare_dnsname(host, { cn })
212         end
213
214         -- If all else fails, well, why should we be any different?
215         return false
216 end
217
218 local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
219 "([0-9A-Za-z+/=\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
220
221 function pem2der(pem)
222         local typ, data = pem:match(pat);
223         if typ and data then
224                 return base64.decode(data), typ;
225         end
226 end
227
228 local wrap = ('.'):rep(64);
229 local envelope = "-----BEGIN %s-----\n%s\n-----END %s-----\n"
230
231 function der2pem(data, typ)
232         typ = typ and typ:upper() or "CERTIFICATE";
233         data = base64.encode(data);
234         return s_format(envelope, typ, data:gsub(wrap, '%0\n', (#data-1)/64), typ);
235 end
236
237 return _M;