xref: /openbsd-src/lib/libtls/tls_verify.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /* $OpenBSD: tls_verify.c,v 1.28 2023/06/01 07:32:25 tb Exp $ */
2 /*
3  * Copyright (c) 2014 Jeremie Courreges-Anglas <jca@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/socket.h>
19 
20 #include <arpa/inet.h>
21 #include <netinet/in.h>
22 
23 #include <string.h>
24 
25 #include <openssl/x509v3.h>
26 
27 #include <tls.h>
28 #include "tls_internal.h"
29 
30 static int
31 tls_match_name(const char *cert_name, const char *name)
32 {
33 	const char *cert_domain, *domain, *next_dot;
34 
35 	if (strcasecmp(cert_name, name) == 0)
36 		return 0;
37 
38 	/* Wildcard match? */
39 	if (cert_name[0] == '*') {
40 		/*
41 		 * Valid wildcards:
42 		 * - "*.domain.tld"
43 		 * - "*.sub.domain.tld"
44 		 * - etc.
45 		 * Reject "*.tld".
46 		 * No attempt to prevent the use of eg. "*.co.uk".
47 		 */
48 		cert_domain = &cert_name[1];
49 		/* Disallow "*"  */
50 		if (cert_domain[0] == '\0')
51 			return -1;
52 		/* Disallow "*foo" */
53 		if (cert_domain[0] != '.')
54 			return -1;
55 		/* Disallow "*.." */
56 		if (cert_domain[1] == '.')
57 			return -1;
58 		next_dot = strchr(&cert_domain[1], '.');
59 		/* Disallow "*.bar" */
60 		if (next_dot == NULL)
61 			return -1;
62 		/* Disallow "*.bar.." */
63 		if (next_dot[1] == '.')
64 			return -1;
65 
66 		domain = strchr(name, '.');
67 
68 		/* No wildcard match against a name with no host part. */
69 		if (name[0] == '.')
70 			return -1;
71 		/* No wildcard match against a name with no domain part. */
72 		if (domain == NULL || strlen(domain) == 1)
73 			return -1;
74 
75 		if (strcasecmp(cert_domain, domain) == 0)
76 			return 0;
77 	}
78 
79 	return -1;
80 }
81 
82 /*
83  * See RFC 5280 section 4.2.1.6 for SubjectAltName details.
84  * alt_match is set to 1 if a matching alternate name is found.
85  * alt_exists is set to 1 if any known alternate name exists in the certificate.
86  */
87 static int
88 tls_check_subject_altname(struct tls *ctx, X509 *cert, const char *name,
89     int *alt_match, int *alt_exists)
90 {
91 	STACK_OF(GENERAL_NAME) *altname_stack = NULL;
92 	union tls_addr addrbuf;
93 	int addrlen, type;
94 	int count, i;
95 	int critical = 0;
96 	int rv = -1;
97 
98 	*alt_match = 0;
99 	*alt_exists = 0;
100 
101 	altname_stack = X509_get_ext_d2i(cert, NID_subject_alt_name, &critical,
102 	    NULL);
103 	if (altname_stack == NULL) {
104 		if (critical != -1) {
105 			tls_set_errorx(ctx, "error decoding subjectAltName");
106 			goto err;
107 		}
108 		goto done;
109 	}
110 
111 	if (inet_pton(AF_INET, name, &addrbuf) == 1) {
112 		type = GEN_IPADD;
113 		addrlen = 4;
114 	} else if (inet_pton(AF_INET6, name, &addrbuf) == 1) {
115 		type = GEN_IPADD;
116 		addrlen = 16;
117 	} else {
118 		type = GEN_DNS;
119 		addrlen = 0;
120 	}
121 
122 	count = sk_GENERAL_NAME_num(altname_stack);
123 	for (i = 0; i < count; i++) {
124 		GENERAL_NAME *altname;
125 
126 		altname = sk_GENERAL_NAME_value(altname_stack, i);
127 
128 		if (altname->type == GEN_DNS || altname->type == GEN_IPADD)
129 			*alt_exists = 1;
130 
131 		if (altname->type != type)
132 			continue;
133 
134 		if (type == GEN_DNS) {
135 			const unsigned char *data;
136 			int format, len;
137 
138 			format = ASN1_STRING_type(altname->d.dNSName);
139 			if (format == V_ASN1_IA5STRING) {
140 				data = ASN1_STRING_get0_data(altname->d.dNSName);
141 				len = ASN1_STRING_length(altname->d.dNSName);
142 
143 				if (len < 0 || (size_t)len != strlen(data)) {
144 					tls_set_errorx(ctx,
145 					    "error verifying name '%s': "
146 					    "NUL byte in subjectAltName, "
147 					    "probably a malicious certificate",
148 					    name);
149 					goto err;
150 				}
151 
152 				/*
153 				 * Per RFC 5280 section 4.2.1.6:
154 				 * " " is a legal domain name, but that
155 				 * dNSName must be rejected.
156 				 */
157 				if (strcmp(data, " ") == 0) {
158 					tls_set_errorx(ctx,
159 					    "error verifying name '%s': "
160 					    "a dNSName of \" \" must not be "
161 					    "used", name);
162 					goto err;
163 				}
164 
165 				if (tls_match_name(data, name) == 0) {
166 					*alt_match = 1;
167 					goto done;
168 				}
169 			} else {
170 #ifdef DEBUG
171 				fprintf(stdout, "%s: unhandled subjectAltName "
172 				    "dNSName encoding (%d)\n", getprogname(),
173 				    format);
174 #endif
175 			}
176 
177 		} else if (type == GEN_IPADD) {
178 			const unsigned char *data;
179 			int datalen;
180 
181 			datalen = ASN1_STRING_length(altname->d.iPAddress);
182 			data = ASN1_STRING_get0_data(altname->d.iPAddress);
183 
184 			if (datalen < 0) {
185 				tls_set_errorx(ctx,
186 				    "Unexpected negative length for an "
187 				    "IP address: %d", datalen);
188 				goto err;
189 			}
190 
191 			/*
192 			 * Per RFC 5280 section 4.2.1.6:
193 			 * IPv4 must use 4 octets and IPv6 must use 16 octets.
194 			 */
195 			if (datalen == addrlen &&
196 			    memcmp(data, &addrbuf, addrlen) == 0) {
197 				*alt_match = 1;
198 				goto done;
199 			}
200 		}
201 	}
202 
203  done:
204 	rv = 0;
205 
206  err:
207 	sk_GENERAL_NAME_pop_free(altname_stack, GENERAL_NAME_free);
208 	return rv;
209 }
210 
211 static int
212 tls_check_common_name(struct tls *ctx, X509 *cert, const char *name,
213     int *cn_match)
214 {
215 	unsigned char *utf8_bytes = NULL;
216 	X509_NAME *subject_name;
217 	char *common_name = NULL;
218 	union tls_addr addrbuf;
219 	int common_name_len;
220 	ASN1_STRING *data;
221 	int lastpos = -1;
222 	int rv = -1;
223 
224 	*cn_match = 0;
225 
226 	subject_name = X509_get_subject_name(cert);
227 	if (subject_name == NULL)
228 		goto done;
229 
230 	lastpos = X509_NAME_get_index_by_NID(subject_name,
231 	    NID_commonName, lastpos);
232 	if (lastpos == -1)
233 		goto done;
234 	if (lastpos < 0)
235 		goto err;
236 	if (X509_NAME_get_index_by_NID(subject_name, NID_commonName, lastpos)
237 	    != -1) {
238 		/*
239 		 * Having multiple CN's is possible, and even happened back in
240 		 * the glory days of mullets and Hammer pants. In anything like
241 		 * a modern TLS cert, CN is as close to deprecated as it gets,
242 		 * and having more than one is bad. We therefore fail if we have
243 		 * more than one CN fed to us in the subject, treating the
244 		 * certificate as hostile.
245 		 */
246 		tls_set_errorx(ctx, "error verifying name '%s': "
247 		    "Certificate subject contains mutiple Common Name fields, "
248 		    "probably a malicious or malformed certificate", name);
249 		goto err;
250 	}
251 
252 	data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name,
253 	    lastpos));
254 	/*
255 	 * Fail if we cannot encode the CN bytes as UTF-8.
256 	 */
257 	if ((common_name_len = ASN1_STRING_to_UTF8(&utf8_bytes, data)) < 0) {
258 		tls_set_errorx(ctx, "error verifying name '%s': "
259 		    "Common Name field cannot be encoded as a UTF-8 string, "
260 		    "probably a malicious certificate", name);
261 		goto err;
262 	}
263 	/*
264 	 * Fail if the CN is of invalid length. RFC 5280 specifies that a CN
265 	 * must be between 1 and 64 bytes long.
266 	 */
267 	if (common_name_len < 1 || common_name_len > 64) {
268 		tls_set_errorx(ctx, "error verifying name '%s': "
269 		    "Common Name field has invalid length, "
270 		    "probably a malicious certificate", name);
271 		goto err;
272 	}
273 	/*
274 	 * Fail if the resulting text contains a NUL byte.
275 	 */
276 	if (memchr(utf8_bytes, 0, common_name_len) != NULL) {
277 		tls_set_errorx(ctx, "error verifying name '%s': "
278 		    "NUL byte in Common Name field, "
279 		    "probably a malicious certificate", name);
280 		goto err;
281 	}
282 
283 	common_name = strndup(utf8_bytes, common_name_len);
284 	if (common_name == NULL) {
285 		tls_set_error(ctx, "out of memory");
286 		goto err;
287 	}
288 
289 	/*
290 	 * We don't want to attempt wildcard matching against IP addresses,
291 	 * so perform a simple comparison here.
292 	 */
293 	if (inet_pton(AF_INET,  name, &addrbuf) == 1 ||
294 	    inet_pton(AF_INET6, name, &addrbuf) == 1) {
295 		if (strcmp(common_name, name) == 0)
296 			*cn_match = 1;
297 		goto done;
298 	}
299 
300 	if (tls_match_name(common_name, name) == 0)
301 		*cn_match = 1;
302 
303  done:
304 	rv = 0;
305 
306  err:
307 	free(utf8_bytes);
308 	free(common_name);
309 	return rv;
310 }
311 
312 int
313 tls_check_name(struct tls *ctx, X509 *cert, const char *name, int *match)
314 {
315 	int alt_exists;
316 
317 	*match = 0;
318 
319 	if (tls_check_subject_altname(ctx, cert, name, match,
320 	    &alt_exists) == -1)
321 		return -1;
322 
323 	/*
324 	 * As per RFC 6125 section 6.4.4, if any known alternate name existed
325 	 * in the certificate, we do not attempt to match on the CN.
326 	 */
327 	if (*match || alt_exists)
328 		return 0;
329 
330 	return tls_check_common_name(ctx, cert, name, match);
331 }
332