util.x509: Return sets of services per identity
[prosody.git] / util / x509.lua
blobfe6e4b7920ca21aef2c06e13f2390b5e58f82300
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 --
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.
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
21 local nameprep = require "util.encodings".stringprep.nameprep;
22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local idna_to_unicode = require "util.encodings".idna.to_unicode;
24 local base64 = require "util.encodings".base64;
25 local log = require "util.logger".init("x509");
26 local mt = require "util.multitable";
27 local s_format = string.format;
28 local ipairs = ipairs;
30 local _ENV = nil;
31 -- luacheck: std none
33 local oid_commonname = "2.5.4.3"; -- [LDAP] 2.3
34 local oid_subjectaltname = "2.5.29.17"; -- [PKIX] 4.2.1.6
35 local oid_xmppaddr = "1.3.6.1.5.5.7.8.5"; -- [XMPP-CORE]
36 local oid_dnssrv = "1.3.6.1.5.5.7.8.7"; -- [SRV-ID]
38 -- Compare a hostname (possibly international) with asserted names
39 -- extracted from a certificate.
40 -- This function follows the rules laid out in
41 -- sections 6.4.1 and 6.4.2 of [TLS-CERTS]
43 -- A wildcard ("*") all by itself is allowed only as the left-most label
44 local function compare_dnsname(host, asserted_names)
45 -- TODO: Sufficient normalization? Review relevant specs.
46 local norm_host = idna_to_ascii(host)
47 if norm_host == nil then
48 log("info", "Host %s failed IDNA ToASCII operation", host)
49 return false
50 end
52 norm_host = norm_host:lower()
54 local host_chopped = norm_host:gsub("^[^.]+%.", "") -- everything after the first label
56 for i=1,#asserted_names do
57 local name = asserted_names[i]
58 if norm_host == name:lower() then
59 log("debug", "Cert dNSName %s matched hostname", name);
60 return true
61 end
63 -- Allow the left most label to be a "*"
64 if name:match("^%*%.") then
65 local rest_name = name:gsub("^[^.]+%.", "")
66 if host_chopped == rest_name:lower() then
67 log("debug", "Cert dNSName %s matched hostname", name);
68 return true
69 end
70 end
71 end
73 return false
74 end
76 -- Compare an XMPP domain name with the asserted id-on-xmppAddr
77 -- identities extracted from a certificate. Both are UTF8 strings.
79 -- Per [XMPP-CORE], matches against asserted identities don't include
80 -- wildcards, so we just do a normalize on both and then a string comparison
82 -- TODO: Support for full JIDs?
83 local function compare_xmppaddr(host, asserted_names)
84 local norm_host = nameprep(host)
86 for i=1,#asserted_names do
87 local name = asserted_names[i]
89 -- We only want to match against bare domains right now, not
90 -- those crazy full-er JIDs.
91 if name:match("[@/]") then
92 log("debug", "Ignoring xmppAddr %s because it's not a bare domain", name)
93 else
94 local norm_name = nameprep(name)
95 if norm_name == nil then
96 log("info", "Ignoring xmppAddr %s, failed nameprep!", name)
97 else
98 if norm_host == norm_name then
99 log("debug", "Cert xmppAddr %s matched hostname", name)
100 return true
106 return false
109 -- Compare a host + service against the asserted id-on-dnsSRV (SRV-ID)
110 -- identities extracted from a certificate.
112 -- Per [SRV-ID], the asserted identities will be encoded in ASCII via ToASCII.
113 -- Comparison is done case-insensitively, and a wildcard ("*") all by itself
114 -- is allowed only as the left-most non-service label.
115 local function compare_srvname(host, service, asserted_names)
116 local norm_host = idna_to_ascii(host)
117 if norm_host == nil then
118 log("info", "Host %s failed IDNA ToASCII operation", host);
119 return false
122 -- Service names start with a "_"
123 if service:match("^_") == nil then service = "_"..service end
125 norm_host = norm_host:lower();
126 local host_chopped = norm_host:gsub("^[^.]+%.", "") -- everything after the first label
128 for i=1,#asserted_names do
129 local asserted_service, name = asserted_names[i]:match("^(_[^.]+)%.(.*)");
130 if service == asserted_service then
131 if norm_host == name:lower() then
132 log("debug", "Cert SRVName %s matched hostname", name);
133 return true;
136 -- Allow the left most label to be a "*"
137 if name:match("^%*%.") then
138 local rest_name = name:gsub("^[^.]+%.", "")
139 if host_chopped == rest_name:lower() then
140 log("debug", "Cert SRVName %s matched hostname", name)
141 return true
144 if norm_host == name:lower() then
145 log("debug", "Cert SRVName %s matched hostname", name);
146 return true
151 return false
154 local function verify_identity(host, service, cert)
155 if cert.setencode then
156 cert:setencode("utf8");
158 local ext = cert:extensions()
159 if ext[oid_subjectaltname] then
160 local sans = ext[oid_subjectaltname];
162 -- Per [TLS-CERTS] 6.3, 6.4.4, "a client MUST NOT seek a match for a
163 -- reference identifier if the presented identifiers include a DNS-ID
164 -- SRV-ID, URI-ID, or any application-specific identifier types"
165 local had_supported_altnames = false
167 if sans[oid_xmppaddr] then
168 had_supported_altnames = true
169 if service == "_xmpp-client" or service == "_xmpp-server" then
170 if compare_xmppaddr(host, sans[oid_xmppaddr]) then return true end
174 if sans[oid_dnssrv] then
175 had_supported_altnames = true
176 -- Only check srvNames if the caller specified a service
177 if service and compare_srvname(host, service, sans[oid_dnssrv]) then return true end
180 if sans["dNSName"] then
181 had_supported_altnames = true
182 if compare_dnsname(host, sans["dNSName"]) then return true end
185 -- We don't need URIs, but [TLS-CERTS] is clear.
186 if sans["uniformResourceIdentifier"] then
187 had_supported_altnames = true
190 if had_supported_altnames then return false end
193 -- Extract a common name from the certificate, and check it as if it were
194 -- a dNSName subjectAltName (wildcards may apply for, and receive,
195 -- cat treats)
197 -- Per [TLS-CERTS] 1.8, a CN-ID is the Common Name from a cert subject
198 -- which has one and only one Common Name
199 local subject = cert:subject()
200 local cn = nil
201 for i=1,#subject do
202 local dn = subject[i]
203 if dn["oid"] == oid_commonname then
204 if cn then
205 log("info", "Certificate has multiple common names")
206 return false
209 cn = dn["value"];
213 if cn then
214 -- Per [TLS-CERTS] 6.4.4, follow the comparison rules for dNSName SANs.
215 return compare_dnsname(host, { cn })
218 -- If all else fails, well, why should we be any different?
219 return false
222 -- TODO Support other SANs
223 local function get_identities(cert) --> map of names to sets of services
224 if cert.setencode then
225 cert:setencode("utf8");
228 local names = mt.new();
230 local ext = cert:extensions();
231 local sans = ext[oid_subjectaltname];
232 if sans then
233 if sans["dNSName"] then -- Valid for any service
234 for _, name in ipairs(sans["dNSName"]) do
235 name = idna_to_unicode(nameprep(name));
236 if name then
237 names:set(name, "*", true);
241 if sans[oid_xmppaddr] then
242 for _, name in ipairs(sans[oid_xmppaddr]) do
243 name = nameprep(name);
244 if name then
245 names:set(name, "xmpp-client", true);
246 names:set(name, "xmpp-server", true);
250 if sans[oid_dnssrv] then
251 for _, srvname in ipairs(sans[oid_dnssrv]) do
252 local srv, name = srvname:match("^_([^.]+)%.(.*)");
253 if srv then
254 name = nameprep(name);
255 if name then
256 names:set(name, srv, true);
263 local subject = cert:subject();
264 for i = 1, #subject do
265 local dn = subject[i];
266 if dn.oid == oid_commonname then
267 local name = nameprep(dn.value);
268 if name and idna_to_ascii(name) then
269 names:set("*", name, true);
273 return names.data;
276 local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
277 "([0-9A-Za-z+/=\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
279 local function pem2der(pem)
280 local typ, data = pem:match(pat);
281 if typ and data then
282 return base64.decode(data), typ;
286 local wrap = ('.'):rep(64);
287 local envelope = "-----BEGIN %s-----\n%s\n-----END %s-----\n"
289 local function der2pem(data, typ)
290 typ = typ and typ:upper() or "CERTIFICATE";
291 data = base64.encode(data);
292 return s_format(envelope, typ, data:gsub(wrap, '%0\n', (#data-1)/64), typ);
295 return {
296 verify_identity = verify_identity;
297 get_identities = get_identities;
298 pem2der = pem2der;
299 der2pem = der2pem;