xref: /openbsd/lib/libtls/tls_verify.c (revision 5dea098c)
1 /* $OpenBSD: tls_verify.c,v 1.30 2024/03/26 06:24:52 joshua 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, TLS_ERROR_UNKNOWN,
106 			    "error decoding subjectAltName");
107 			goto err;
108 		}
109 		goto done;
110 	}
111 
112 	if (inet_pton(AF_INET, name, &addrbuf) == 1) {
113 		type = GEN_IPADD;
114 		addrlen = 4;
115 	} else if (inet_pton(AF_INET6, name, &addrbuf) == 1) {
116 		type = GEN_IPADD;
117 		addrlen = 16;
118 	} else {
119 		type = GEN_DNS;
120 		addrlen = 0;
121 	}
122 
123 	count = sk_GENERAL_NAME_num(altname_stack);
124 	for (i = 0; i < count; i++) {
125 		GENERAL_NAME *altname;
126 
127 		altname = sk_GENERAL_NAME_value(altname_stack, i);
128 
129 		if (altname->type == GEN_DNS || altname->type == GEN_IPADD)
130 			*alt_exists = 1;
131 
132 		if (altname->type != type)
133 			continue;
134 
135 		if (type == GEN_DNS) {
136 			const unsigned char *data;
137 			int format, len;
138 
139 			format = ASN1_STRING_type(altname->d.dNSName);
140 			if (format == V_ASN1_IA5STRING) {
141 				data = ASN1_STRING_get0_data(altname->d.dNSName);
142 				len = ASN1_STRING_length(altname->d.dNSName);
143 
144 				if (len < 0 || (size_t)len != strlen(data)) {
145 					tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
146 					    "error verifying name '%s': "
147 					    "NUL byte in subjectAltName, "
148 					    "probably a malicious certificate",
149 					    name);
150 					goto err;
151 				}
152 
153 				/*
154 				 * Per RFC 5280 section 4.2.1.6:
155 				 * " " is a legal domain name, but that
156 				 * dNSName must be rejected.
157 				 */
158 				if (strcmp(data, " ") == 0) {
159 					tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
160 					    "error verifying name '%s': "
161 					    "a dNSName of \" \" must not be "
162 					    "used", name);
163 					goto err;
164 				}
165 
166 				if (tls_match_name(data, name) == 0) {
167 					*alt_match = 1;
168 					goto done;
169 				}
170 			} else {
171 #ifdef DEBUG
172 				fprintf(stdout, "%s: unhandled subjectAltName "
173 				    "dNSName encoding (%d)\n", getprogname(),
174 				    format);
175 #endif
176 			}
177 
178 		} else if (type == GEN_IPADD) {
179 			const unsigned char *data;
180 			int datalen;
181 
182 			datalen = ASN1_STRING_length(altname->d.iPAddress);
183 			data = ASN1_STRING_get0_data(altname->d.iPAddress);
184 
185 			if (datalen < 0) {
186 				tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
187 				    "Unexpected negative length for an "
188 				    "IP address: %d", datalen);
189 				goto err;
190 			}
191 
192 			/*
193 			 * Per RFC 5280 section 4.2.1.6:
194 			 * IPv4 must use 4 octets and IPv6 must use 16 octets.
195 			 */
196 			if (datalen == addrlen &&
197 			    memcmp(data, &addrbuf, addrlen) == 0) {
198 				*alt_match = 1;
199 				goto done;
200 			}
201 		}
202 	}
203 
204  done:
205 	rv = 0;
206 
207  err:
208 	sk_GENERAL_NAME_pop_free(altname_stack, GENERAL_NAME_free);
209 	return rv;
210 }
211 
212 static int
213 tls_check_common_name(struct tls *ctx, X509 *cert, const char *name,
214     int *cn_match)
215 {
216 	unsigned char *utf8_bytes = NULL;
217 	X509_NAME *subject_name;
218 	char *common_name = NULL;
219 	union tls_addr addrbuf;
220 	int common_name_len;
221 	ASN1_STRING *data;
222 	int lastpos = -1;
223 	int rv = -1;
224 
225 	*cn_match = 0;
226 
227 	subject_name = X509_get_subject_name(cert);
228 	if (subject_name == NULL)
229 		goto done;
230 
231 	lastpos = X509_NAME_get_index_by_NID(subject_name,
232 	    NID_commonName, lastpos);
233 	if (lastpos == -1)
234 		goto done;
235 	if (lastpos < 0)
236 		goto err;
237 	if (X509_NAME_get_index_by_NID(subject_name, NID_commonName, lastpos)
238 	    != -1) {
239 		/*
240 		 * Having multiple CN's is possible, and even happened back in
241 		 * the glory days of mullets and Hammer pants. In anything like
242 		 * a modern TLS cert, CN is as close to deprecated as it gets,
243 		 * and having more than one is bad. We therefore fail if we have
244 		 * more than one CN fed to us in the subject, treating the
245 		 * certificate as hostile.
246 		 */
247 		tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
248 		    "error verifying name '%s': "
249 		    "Certificate subject contains multiple Common Name fields, "
250 		    "probably a malicious or malformed certificate", name);
251 		goto err;
252 	}
253 
254 	data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name,
255 	    lastpos));
256 	/*
257 	 * Fail if we cannot encode the CN bytes as UTF-8.
258 	 */
259 	if ((common_name_len = ASN1_STRING_to_UTF8(&utf8_bytes, data)) < 0) {
260 		tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
261 		    "error verifying name '%s': "
262 		    "Common Name field cannot be encoded as a UTF-8 string, "
263 		    "probably a malicious certificate", name);
264 		goto err;
265 	}
266 	/*
267 	 * Fail if the CN is of invalid length. RFC 5280 specifies that a CN
268 	 * must be between 1 and 64 bytes long.
269 	 */
270 	if (common_name_len < 1 || common_name_len > 64) {
271 		tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
272 		    "error verifying name '%s': "
273 		    "Common Name field has invalid length, "
274 		    "probably a malicious certificate", name);
275 		goto err;
276 	}
277 	/*
278 	 * Fail if the resulting text contains a NUL byte.
279 	 */
280 	if (memchr(utf8_bytes, 0, common_name_len) != NULL) {
281 		tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
282 		    "error verifying name '%s': "
283 		    "NUL byte in Common Name field, "
284 		    "probably a malicious certificate", name);
285 		goto err;
286 	}
287 
288 	common_name = strndup(utf8_bytes, common_name_len);
289 	if (common_name == NULL) {
290 		tls_set_error(ctx, TLS_ERROR_OUT_OF_MEMORY,
291 		    "out of memory");
292 		goto err;
293 	}
294 
295 	/*
296 	 * We don't want to attempt wildcard matching against IP addresses,
297 	 * so perform a simple comparison here.
298 	 */
299 	if (inet_pton(AF_INET,  name, &addrbuf) == 1 ||
300 	    inet_pton(AF_INET6, name, &addrbuf) == 1) {
301 		if (strcmp(common_name, name) == 0)
302 			*cn_match = 1;
303 		goto done;
304 	}
305 
306 	if (tls_match_name(common_name, name) == 0)
307 		*cn_match = 1;
308 
309  done:
310 	rv = 0;
311 
312  err:
313 	free(utf8_bytes);
314 	free(common_name);
315 	return rv;
316 }
317 
318 int
319 tls_check_name(struct tls *ctx, X509 *cert, const char *name, int *match)
320 {
321 	int alt_exists;
322 
323 	*match = 0;
324 
325 	if (tls_check_subject_altname(ctx, cert, name, match,
326 	    &alt_exists) == -1)
327 		return -1;
328 
329 	/*
330 	 * As per RFC 6125 section 6.4.4, if any known alternate name existed
331 	 * in the certificate, we do not attempt to match on the CN.
332 	 */
333 	if (*match || alt_exists)
334 		return 0;
335 
336 	return tls_check_common_name(ctx, cert, name, match);
337 }
338