Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/x509/v3_ncons.c

raw
1 // Written by Dr Stephen N Henson ([email protected]) for the OpenSSL project.
2 // Copyright (c) 2003 The OpenSSL Project. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
4
5 #include <stdio.h>
6 #include <string.h>
7
8 #include <openssl/asn1t.h>
9 #include <openssl/bytestring.h>
10 #include <openssl/conf.h>
11 #include <openssl/err.h>
12 #include <openssl/mem.h>
13 #include <openssl/obj.h>
14 #include <openssl/x509.h>
15
16 #include "../internal.h"
17 #include "internal.h"
18
19
20 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
21 const X509V3_CTX *ctx,
22 const STACK_OF(CONF_VALUE) *nval);
23 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
24 BIO *bp, int ind);
25 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
26 STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp,
27 int ind, const char *name);
28 static int print_nc_ipadd(BIO *bp, const ASN1_OCTET_STRING *ip);
29
30 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
31 static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen,
32 int excluding);
33 static int nc_dn(X509_NAME *sub, X509_NAME *nm);
34 static int nc_dns(const ASN1_IA5STRING *sub, const ASN1_IA5STRING *dns,
35 int excluding);
36 static int nc_email(const ASN1_IA5STRING *sub, const ASN1_IA5STRING *eml);
37 static int nc_uri(const ASN1_IA5STRING *uri, const ASN1_IA5STRING *base);
38 static int nc_ip(const ASN1_OCTET_STRING *ip, const ASN1_OCTET_STRING *base);
39
40 const X509V3_EXT_METHOD v3_name_constraints = {
41 NID_name_constraints,
42 0,
43 ASN1_ITEM_ref(NAME_CONSTRAINTS),
44 0,
45 0,
46 0,
47 0,
48 0,
49 0,
50 0,
51 v2i_NAME_CONSTRAINTS,
52 i2r_NAME_CONSTRAINTS,
53 0,
54 NULL,
55 };
56
57 ASN1_SEQUENCE(GENERAL_SUBTREE) = {
58 ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME),
59 ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0),
60 ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1),
61 } ASN1_SEQUENCE_END(GENERAL_SUBTREE)
62
63 ASN1_SEQUENCE(NAME_CONSTRAINTS) = {
64 ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees,
65 GENERAL_SUBTREE, 0),
66 ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees,
67 GENERAL_SUBTREE, 1),
68 } ASN1_SEQUENCE_END(NAME_CONSTRAINTS)
69
70
71 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
72 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
73
74 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
75 const X509V3_CTX *ctx,
76 const STACK_OF(CONF_VALUE) *nval) {
77 STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
78 NAME_CONSTRAINTS *ncons = NULL;
79 GENERAL_SUBTREE *sub = NULL;
80 ncons = NAME_CONSTRAINTS_new();
81 if (!ncons) {
82 goto err;
83 }
84 for (size_t i = 0; i < sk_CONF_VALUE_num(nval); i++) {
85 const CONF_VALUE *val = sk_CONF_VALUE_value(nval, i);
86 CONF_VALUE tval;
87 if (!strncmp(val->name, "permitted", 9) && val->name[9]) {
88 ptree = &ncons->permittedSubtrees;
89 tval.name = val->name + 10;
90 } else if (!strncmp(val->name, "excluded", 8) && val->name[8]) {
91 ptree = &ncons->excludedSubtrees;
92 tval.name = val->name + 9;
93 } else {
94 OPENSSL_PUT_ERROR(X509V3, X509V3_R_INVALID_SYNTAX);
95 goto err;
96 }
97 tval.value = val->value;
98 sub = GENERAL_SUBTREE_new();
99 if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) {
100 goto err;
101 }
102 if (!*ptree) {
103 *ptree = sk_GENERAL_SUBTREE_new_null();
104 }
105 if (!*ptree || !sk_GENERAL_SUBTREE_push(*ptree, sub)) {
106 goto err;
107 }
108 sub = NULL;
109 }
110
111 return ncons;
112
113 err:
114 NAME_CONSTRAINTS_free(ncons);
115 GENERAL_SUBTREE_free(sub);
116 return NULL;
117 }
118
119 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
120 BIO *bp, int ind) {
121 NAME_CONSTRAINTS *ncons = a;
122 do_i2r_name_constraints(method, ncons->permittedSubtrees, bp, ind,
123 "Permitted");
124 do_i2r_name_constraints(method, ncons->excludedSubtrees, bp, ind, "Excluded");
125 return 1;
126 }
127
128 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
129 STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp,
130 int ind, const char *name) {
131 GENERAL_SUBTREE *tree;
132 size_t i;
133 if (sk_GENERAL_SUBTREE_num(trees) > 0) {
134 BIO_printf(bp, "%*s%s:\n", ind, "", name);
135 }
136 for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
137 tree = sk_GENERAL_SUBTREE_value(trees, i);
138 BIO_printf(bp, "%*s", ind + 2, "");
139 if (tree == NULL) {
140 return 0;
141 }
142 if (tree->base->type == GEN_IPADD) {
143 print_nc_ipadd(bp, tree->base->d.ip);
144 } else {
145 GENERAL_NAME_print(bp, tree->base);
146 }
147 BIO_puts(bp, "\n");
148 }
149 return 1;
150 }
151
152 static int print_nc_ipadd(BIO *bp, const ASN1_OCTET_STRING *ip) {
153 int i, len;
154 unsigned char *p;
155 p = ip->data;
156 len = ip->length;
157 BIO_puts(bp, "IP:");
158 if (len == 8) {
159 BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d", p[0], p[1], p[2], p[3], p[4],
160 p[5], p[6], p[7]);
161 } else if (len == 32) {
162 for (i = 0; i < 16; i++) {
163 uint16_t v = ((uint16_t)p[0] << 8) | p[1];
164 BIO_printf(bp, "%X", v);
165 p += 2;
166 if (i == 7) {
167 BIO_puts(bp, "/");
168 } else if (i != 15) {
169 BIO_puts(bp, ":");
170 }
171 }
172 } else {
173 BIO_printf(bp, "IP Address:<invalid>");
174 }
175 return 1;
176 }
177
178 //-
179 // Check a certificate conforms to a specified set of constraints.
180 // Return values:
181 // X509_V_OK: All constraints obeyed.
182 // X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
183 // X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
184 // X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
185 // X509_V_ERR_UNSPECIFIED: Unspecified error.
186 // X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type.
187 // X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: Bad or unsupported constraint
188 // syntax.
189 // X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: Bad or unsupported syntax of name.
190
191 int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc) {
192 int r, i;
193 size_t j;
194 X509_NAME *nm;
195
196 nm = X509_get_subject_name(x);
197
198 // Guard against certificates with an excessive number of names or
199 // constraints causing a computationally expensive name constraints
200 // check.
201 size_t name_count =
202 X509_NAME_entry_count(nm) + sk_GENERAL_NAME_num(x->altname);
203 size_t constraint_count = sk_GENERAL_SUBTREE_num(nc->permittedSubtrees) +
204 sk_GENERAL_SUBTREE_num(nc->excludedSubtrees);
205 size_t check_count = constraint_count * name_count;
206 if (name_count < (size_t)X509_NAME_entry_count(nm) ||
207 constraint_count < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees) ||
208 (constraint_count && check_count / constraint_count != name_count) ||
209 check_count > 1 << 20) {
210 return X509_V_ERR_UNSPECIFIED;
211 }
212
213 if (X509_NAME_entry_count(nm) > 0) {
214 GENERAL_NAME gntmp;
215 gntmp.type = GEN_DIRNAME;
216 gntmp.d.directoryName = nm;
217
218 r = nc_match(&gntmp, nc);
219
220 if (r != X509_V_OK) {
221 return r;
222 }
223
224 gntmp.type = GEN_EMAIL;
225
226 // Process any email address attributes in subject name
227
228 for (i = -1;;) {
229 i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i);
230 if (i == -1) {
231 break;
232 }
233 const X509_NAME_ENTRY *ne = X509_NAME_get_entry(nm, i);
234 gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
235 if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING) {
236 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
237 }
238
239 r = nc_match(&gntmp, nc);
240
241 if (r != X509_V_OK) {
242 return r;
243 }
244 }
245 }
246
247 for (j = 0; j < sk_GENERAL_NAME_num(x->altname); j++) {
248 GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, j);
249 r = nc_match(gen, nc);
250 if (r != X509_V_OK) {
251 return r;
252 }
253 }
254
255 return X509_V_OK;
256 }
257
258 int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen) {
259 assert(dnsid != NULL && idlen != NULL);
260
261 // Don't leave outputs uninitialized
262 *dnsid = NULL;
263 *idlen = 0;
264
265 // Per RFC 6125, DNS-IDs representing internationalized domain names appear
266 // in certificates in A-label encoded form:
267 //
268 // https://tools.ietf.org/html/rfc6125#section-6.4.2
269 //
270 // The same applies to CNs which are intended to represent DNS names.
271 // However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be
272 // needlessly encoded in 16-bit Unicode. We perform a conversion to UTF-8
273 // to ensure that we get an ASCII representation of any CNs that are
274 // representable as ASCII, but just not encoded as ASCII. The UTF-8 form
275 // may contain some non-ASCII octets, and that's fine, such CNs are not
276 // valid legacy DNS names.
277 //
278 // Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what
279 // we must use for 'utf8_length'.
280 unsigned char *utf8_value = NULL;
281 int utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn);
282 if (utf8_length < 0) {
283 return X509_V_ERR_OUT_OF_MEM;
284 }
285
286 // Some certificates have had names that include a *trailing* NUL byte.
287 // Remove these harmless NUL characters. They would otherwise yield false
288 // alarms with the following embedded NUL check.
289 while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0') {
290 --utf8_length;
291 }
292
293 // Reject *embedded* NULs
294 if (OPENSSL_memchr(utf8_value, 0, utf8_length) != NULL) {
295 OPENSSL_free(utf8_value);
296 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
297 }
298
299 int isdnsname = 0;
300 int has_non_dns_char = 0;
301
302 // Per RFC 6125 Section 6.4.3, a wildcard DNS-ID uses a leading "*." covering
303 // the first label. Skip past it for validation, but return the full value so
304 // |nc_dns| can match it against name constraints.
305 int check_start = 0;
306 if (utf8_length > 2 && utf8_value[0] == '*' && utf8_value[1] == '.') {
307 check_start = 2;
308 }
309
310 // Check DNS name syntax. Any '-' or '.' must be internal, and on either side
311 // of each '.' we can't have a '-' or '.'. Names with '_' are also accepted
312 // as a deviation from strict DNS syntax.
313 //
314 // If the name has just one label, we don't consider it a DNS name. This
315 // means that "CN=sometld" cannot be precluded by DNS name constraints, but
316 // that is not a problem. Single-label CNs may contain non-ASCII characters
317 // (e.g. "CN=Ünternehmen") and are silently skipped.
318 //
319 // Multi-label CNs that resemble DNS names must be ASCII-only. Per RFC 6125
320 // Section 6.4.2, internationalized domain names should appear in A-label
321 // (punycode) form. A multi-label CN containing non-ASCII bytes or control
322 // characters is rejected with |X509_V_ERR_UNSUPPORTED_NAME_SYNTAX| to
323 // prevent it from bypassing name constraints while still being accepted by
324 // hostname verification.
325 for (int i = check_start; i < utf8_length; ++i) {
326 const unsigned char c = utf8_value[i];
327
328 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
329 (c >= '0' && c <= '9') || c == '_') {
330 continue;
331 }
332
333 if (c >= 0x80 || c <= 0x20 || c == 0x7F) {
334 has_non_dns_char = 1;
335 continue;
336 }
337
338 // Dot and hyphen cannot be first or last.
339 if (i > check_start && i < utf8_length - 1) {
340 if (c == '-') {
341 continue;
342 }
343
344 // Next to a dot the preceding and following characters must not be
345 // another dot or a hyphen. Otherwise, record that the name is
346 // plausible, since it has two or more labels.
347 if (c == '.' && utf8_value[i + 1] != '.' && utf8_value[i - 1] != '-' &&
348 utf8_value[i + 1] != '-') {
349 isdnsname = 1;
350 continue;
351 }
352 }
353 isdnsname = 0;
354 break;
355 }
356
357 if (isdnsname && has_non_dns_char) {
358 // Multi-label CN with non-ASCII bytes or control characters. This
359 // resembles a DNS name but contains characters not permitted in DNS.
360 OPENSSL_free(utf8_value);
361 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
362 }
363
364 if (isdnsname) {
365 *dnsid = utf8_value;
366 *idlen = (size_t)utf8_length;
367 return X509_V_OK;
368 }
369 OPENSSL_free(utf8_value);
370 return X509_V_OK;
371 }
372
373 // Check CN against DNS-ID name constraints.
374 int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc) {
375 int ret = 0;
376 const X509_NAME *nm = X509_get_subject_name(x);
377 ASN1_STRING stmp = {.length = 0, .type = V_ASN1_IA5STRING, .data = NULL, .flags = 0};
378 GENERAL_NAME gntmp = {.type = GEN_DNS, .d = {.dNSName = &stmp}};
379
380 // Process any commonName attributes in subject name
381 for (int i = -1;;) {
382 X509_NAME_ENTRY *ne = NULL;
383 ASN1_STRING *cn = NULL;
384 unsigned char *idval = NULL;
385 size_t idlen = 0;
386
387 i = X509_NAME_get_index_by_NID(nm, NID_commonName, i);
388 if (i == -1) {
389 break;
390 }
391 ne = X509_NAME_get_entry(nm, i);
392 cn = X509_NAME_ENTRY_get_data(ne);
393
394 // Only process attributes that look like host names
395 if ((ret = cn2dnsid(cn, &idval, &idlen)) != X509_V_OK) {
396 return ret;
397 }
398 if (idlen == 0) {
399 continue;
400 }
401
402 stmp.length = idlen;
403 stmp.data = idval;
404 ret = nc_match(&gntmp, nc);
405 OPENSSL_free(idval);
406 if (ret != X509_V_OK) {
407 return ret;
408 }
409 }
410 return X509_V_OK;
411 }
412
413 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc) {
414 GENERAL_SUBTREE *sub;
415 int r, match = 0;
416 size_t i;
417
418 // Permitted subtrees: if any subtrees exist of matching the type at
419 // least one subtree must match.
420
421 for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
422 sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
423 if (gen->type != sub->base->type) {
424 continue;
425 }
426 if (sub->minimum || sub->maximum) {
427 return X509_V_ERR_SUBTREE_MINMAX;
428 }
429 // If we already have a match don't bother trying any more
430 if (match == 2) {
431 continue;
432 }
433 if (match == 0) {
434 match = 1;
435 }
436 r = nc_match_single(gen, sub->base, /*excluding=*/0);
437 if (r == X509_V_OK) {
438 match = 2;
439 } else if (r != X509_V_ERR_PERMITTED_VIOLATION) {
440 return r;
441 }
442 }
443
444 if (match == 1) {
445 return X509_V_ERR_PERMITTED_VIOLATION;
446 }
447
448 // Excluded subtrees: must not match any of these
449
450 for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
451 sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
452 if (gen->type != sub->base->type) {
453 continue;
454 }
455 if (sub->minimum || sub->maximum) {
456 return X509_V_ERR_SUBTREE_MINMAX;
457 }
458
459 r = nc_match_single(gen, sub->base, /*excluding=*/1);
460 if (r == X509_V_OK) {
461 return X509_V_ERR_EXCLUDED_VIOLATION;
462 } else if (r != X509_V_ERR_PERMITTED_VIOLATION) {
463 return r;
464 }
465 }
466
467 return X509_V_OK;
468 }
469
470 static int nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base,
471 int excluding) {
472 switch (base->type) {
473 case GEN_DIRNAME:
474 return nc_dn(gen->d.directoryName, base->d.directoryName);
475
476 case GEN_DNS:
477 return nc_dns(gen->d.dNSName, base->d.dNSName, excluding);
478
479 case GEN_EMAIL:
480 return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
481
482 case GEN_URI:
483 return nc_uri(gen->d.uniformResourceIdentifier,
484 base->d.uniformResourceIdentifier);
485
486 case GEN_IPADD:
487 return nc_ip(gen->d.iPAddress, base->d.iPAddress);
488
489 default:
490 return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
491 }
492 }
493
494 // directoryName name constraint matching. The canonical encoding of
495 // X509_NAME makes this comparison easy. It is matched if the subtree is a
496 // subset of the name.
497
498 static int nc_dn(X509_NAME *nm, X509_NAME *base) {
499 // Ensure canonical encodings are up to date.
500 if (nm->modified && i2d_X509_NAME(nm, NULL) < 0) {
501 return X509_V_ERR_OUT_OF_MEM;
502 }
503 if (base->modified && i2d_X509_NAME(base, NULL) < 0) {
504 return X509_V_ERR_OUT_OF_MEM;
505 }
506 if (base->canon_enclen > nm->canon_enclen) {
507 return X509_V_ERR_PERMITTED_VIOLATION;
508 }
509 if (OPENSSL_memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen)) {
510 return X509_V_ERR_PERMITTED_VIOLATION;
511 }
512 return X509_V_OK;
513 }
514
515 static int starts_with(const CBS *cbs, uint8_t c) {
516 return CBS_len(cbs) > 0 && CBS_data(cbs)[0] == c;
517 }
518
519 static int starts_with_str(const CBS *cbs, const char *str, size_t str_len) {
520 return CBS_len(cbs) >= str_len &&
521 !OPENSSL_memcmp(CBS_data(cbs), str, str_len);
522 }
523
524 static int ends_with_byte(const CBS *cbs, uint8_t c) {
525 return CBS_len(cbs) > 0 && CBS_data(cbs)[CBS_len(cbs) - 1] == c;
526 }
527
528 static int equal_case(const CBS *a, const CBS *b) {
529 if (CBS_len(a) != CBS_len(b)) {
530 return 0;
531 }
532 // Note we cannot use |OPENSSL_strncasecmp| because that would stop
533 // iterating at NUL.
534 const uint8_t *a_data = CBS_data(a), *b_data = CBS_data(b);
535 for (size_t i = 0; i < CBS_len(a); i++) {
536 if (OPENSSL_tolower(a_data[i]) != OPENSSL_tolower(b_data[i])) {
537 return 0;
538 }
539 }
540 return 1;
541 }
542
543 static int has_suffix_case(const CBS *a, const CBS *b) {
544 if (CBS_len(a) < CBS_len(b)) {
545 return 0;
546 }
547 CBS copy = *a;
548 CBS_skip(&copy, CBS_len(a) - CBS_len(b));
549 return equal_case(&copy, b);
550 }
551
552 static int nc_dns(const ASN1_IA5STRING *dns, const ASN1_IA5STRING *base,
553 int excluding) {
554 CBS dns_cbs, base_cbs;
555 CBS_init(&dns_cbs, dns->data, dns->length);
556 CBS_init(&base_cbs, base->data, base->length);
557
558 // Empty matches everything
559 if (CBS_len(&base_cbs) == 0) {
560 return X509_V_OK;
561 }
562
563 // Normalize absolute DNS names by removing the trailing dot, if any.
564 if (ends_with_byte(&dns_cbs, '.')) {
565 uint8_t unused;
566 CBS_get_last_u8(&dns_cbs, &unused);
567 }
568 if (ends_with_byte(&base_cbs, '.')) {
569 uint8_t unused;
570 CBS_get_last_u8(&base_cbs, &unused);
571 }
572
573 // Wildcard partial-match handling ("*.bar.com" matching name constraint
574 // "foo.bar.com"). This only handles the case where the dnsname and the
575 // constraint match after removing the leftmost label, otherwise it is handled
576 // by falling through to the check of whether the dnsname is fully within or
577 // fully outside of the constraint.
578 if (excluding && starts_with_str(&dns_cbs, "*.", 2)) {
579 CBS unused;
580 CBS base_parent_cbs = base_cbs;
581 CBS dns_parent_cbs = dns_cbs;
582 CBS_skip(&dns_parent_cbs, 2);
583 if (CBS_get_until_first(&base_parent_cbs, &unused, '.') &&
584 CBS_skip(&base_parent_cbs, 1)) {
585 if (equal_case(&dns_parent_cbs, &base_parent_cbs)) {
586 return X509_V_OK;
587 }
588 }
589 }
590
591 // If |base_cbs| begins with a '.', do a simple suffix comparison. This is
592 // not part of RFC5280, but is part of OpenSSL's original behavior.
593 if (starts_with(&base_cbs, '.')) {
594 if (has_suffix_case(&dns_cbs, &base_cbs)) {
595 return X509_V_OK;
596 }
597 return X509_V_ERR_PERMITTED_VIOLATION;
598 }
599
600 // Otherwise can add zero or more components on the left so compare RHS
601 // and if dns is longer and expect '.' as preceding character.
602 if (CBS_len(&dns_cbs) > CBS_len(&base_cbs)) {
603 uint8_t dot;
604 if (!CBS_skip(&dns_cbs, CBS_len(&dns_cbs) - CBS_len(&base_cbs) - 1) ||
605 !CBS_get_u8(&dns_cbs, &dot) || dot != '.') {
606 return X509_V_ERR_PERMITTED_VIOLATION;
607 }
608 }
609
610 if (!equal_case(&dns_cbs, &base_cbs)) {
611 return X509_V_ERR_PERMITTED_VIOLATION;
612 }
613
614 return X509_V_OK;
615 }
616
617 static int nc_email(const ASN1_IA5STRING *eml, const ASN1_IA5STRING *base) {
618 CBS eml_cbs, base_cbs;
619 CBS_init(&eml_cbs, eml->data, eml->length);
620 CBS_init(&base_cbs, base->data, base->length);
621
622 // TODO(davidben): In OpenSSL 1.1.1, this switched from the first '@' to the
623 // last one. Match them here, or perhaps do an actual parse. Looks like
624 // multiple '@'s may be allowed in quoted strings.
625 CBS eml_local, base_local;
626 if (!CBS_get_until_first(&eml_cbs, &eml_local, '@')) {
627 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
628 }
629 int base_has_at = CBS_get_until_first(&base_cbs, &base_local, '@');
630
631 // Special case: initial '.' is RHS match
632 if (!base_has_at && starts_with(&base_cbs, '.')) {
633 if (has_suffix_case(&eml_cbs, &base_cbs)) {
634 return X509_V_OK;
635 }
636 return X509_V_ERR_PERMITTED_VIOLATION;
637 }
638
639 // If we have anything before '@' match local part
640 if (base_has_at) {
641 // TODO(davidben): This interprets a constraint of "@example.com" as
642 // "example.com", which is not part of RFC5280.
643 if (CBS_len(&base_local) > 0) {
644 // Case sensitive match of local part
645 if (!CBS_mem_equal(&base_local, CBS_data(&eml_local),
646 CBS_len(&eml_local))) {
647 return X509_V_ERR_PERMITTED_VIOLATION;
648 }
649 }
650 // Position base after '@'
651 assert(starts_with(&base_cbs, '@'));
652 CBS_skip(&base_cbs, 1);
653 }
654
655 // Just have hostname left to match: case insensitive
656 assert(starts_with(&eml_cbs, '@'));
657 CBS_skip(&eml_cbs, 1);
658 if (!equal_case(&base_cbs, &eml_cbs)) {
659 return X509_V_ERR_PERMITTED_VIOLATION;
660 }
661
662 return X509_V_OK;
663 }
664
665 static int nc_uri(const ASN1_IA5STRING *uri, const ASN1_IA5STRING *base) {
666 CBS uri_cbs, base_cbs;
667 CBS_init(&uri_cbs, uri->data, uri->length);
668 CBS_init(&base_cbs, base->data, base->length);
669
670 // Check for foo:// and skip past it
671 CBS scheme;
672 uint8_t byte;
673 if (!CBS_get_until_first(&uri_cbs, &scheme, ':') ||
674 !CBS_skip(&uri_cbs, 1) || // Skip the colon
675 !CBS_get_u8(&uri_cbs, &byte) || byte != '/' ||
676 !CBS_get_u8(&uri_cbs, &byte) || byte != '/') {
677 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
678 }
679
680 // RFC 5280 §4.2.1.10 specifies that URI name constraints "MUST be specified
681 // as a fully qualified domain name". IPv6 literal URIs (e.g.
682 // "https://[2001:db8::1]/") are not domain names, and matching them by string
683 // comparison would be unreliable because IPv6 addresses have many equivalent
684 // textual representations. Reject them as unsupported.
685 if (starts_with(&uri_cbs, '[')) {
686 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
687 }
688
689 // RFC 3986 §3.2 defines authority = [userinfo "@"] host [":" port].
690 // Certificate SAN URIs have no standards-defined use for userinfo. If present,
691 // the '@' delimiter would cause the host extraction below to parse the
692 // userinfo as the host, matching against attacker-chosen bytes instead of
693 // the URI's actual host.
694 for (size_t i = 0; i < CBS_len(&uri_cbs); i++) {
695 uint8_t c = CBS_data(&uri_cbs)[i];
696 if (c == '/' || c == '?' || c == '#') {
697 break;
698 }
699 if (c == '@') {
700 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
701 }
702 }
703
704 // Look for a port indicator as end of hostname first. Otherwise look for
705 // trailing slash, or the end of the string.
706 CBS host;
707 if (!CBS_get_until_first(&uri_cbs, &host, ':') &&
708 !CBS_get_until_first(&uri_cbs, &host, '/')) {
709 host = uri_cbs;
710 }
711
712 if (CBS_len(&host) == 0) {
713 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
714 }
715
716 // Normalize absolute DNS names by removing the trailing dot, if any.
717 // RFC 1034 §3.1 defines that a trailing dot denotes the DNS root; names with
718 // and without it refer to the same host. This matches the normalization in
719 // nc_dns().
720 if (ends_with_byte(&host, '.')) {
721 uint8_t unused;
722 CBS_get_last_u8(&host, &unused);
723 }
724 if (ends_with_byte(&base_cbs, '.')) {
725 uint8_t unused;
726 CBS_get_last_u8(&base_cbs, &unused);
727 }
728
729 // RFC 5280 §4.2.1.10 requires the host to be a fully qualified domain name.
730 // Validate that the host contains only characters valid in a DNS name
731 // (RFC 1034 §3.5): letters, digits, hyphens, and dots. This rejects
732 // percent-encoded hosts and any other non-FQDN syntax, preventing
733 // equivalence bypasses (e.g., "b%61d.com" evading ".bad.com").
734 if (CBS_len(&host) == 0) {
735 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
736 }
737 for (size_t i = 0; i < CBS_len(&host); i++) {
738 uint8_t c = CBS_data(&host)[i];
739 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
740 (c >= '0' && c <= '9') || c == '-' || c == '.')) {
741 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
742 }
743 }
744
745 // Special case: initial '.' is RHS match
746 if (starts_with(&base_cbs, '.')) {
747 if (has_suffix_case(&host, &base_cbs)) {
748 return X509_V_OK;
749 }
750 return X509_V_ERR_PERMITTED_VIOLATION;
751 }
752
753 if (!equal_case(&base_cbs, &host)) {
754 return X509_V_ERR_PERMITTED_VIOLATION;
755 }
756
757 return X509_V_OK;
758 }
759
760 #define IPV4_ADDR_LEN 4
761 #define IPV4_CIDR_LEN (IPV4_ADDR_LEN * 2)
762 #define IPV6_ADDR_LEN 16
763 #define IPV6_CIDR_LEN (IPV6_ADDR_LEN * 2)
764
765 static int validate_ipv4_cidr_mask(const uint8_t *mask_ptr, size_t mask_len) {
766 assert(mask_len == IPV4_ADDR_LEN);
767
768 uint32_t mask = ((uint32_t)mask_ptr[0] << 24) |
769 ((uint32_t)mask_ptr[1] << 16) | ((uint32_t)mask_ptr[2] << 8) |
770 ((uint32_t)mask_ptr[3]);
771
772 if (mask != 0 && ((~mask + 1) & ~mask)) {
773 return 0;
774 }
775
776 return 1;
777 }
778
779 static int validate_ipv6_cidr_mask(const uint8_t *mask_ptr, size_t mask_len) {
780 assert(mask_len == IPV6_ADDR_LEN);
781
782 uint64_t mask_high =
783 (((uint64_t)mask_ptr[0]) << 56) | ((uint64_t)mask_ptr[1] << 48) |
784 ((uint64_t)mask_ptr[2] << 40) | ((uint64_t)mask_ptr[3] << 32) |
785 ((uint64_t)mask_ptr[4] << 24) | ((uint64_t)mask_ptr[5] << 16) |
786 ((uint64_t)mask_ptr[6] << 8) | ((uint64_t)mask_ptr[7]);
787
788 uint64_t mask_low =
789 (((uint64_t)mask_ptr[8]) << 56) | ((uint64_t)mask_ptr[9] << 48) |
790 ((uint64_t)mask_ptr[10] << 40) | ((uint64_t)mask_ptr[11] << 32) |
791 ((uint64_t)mask_ptr[12] << 24) | ((uint64_t)mask_ptr[13] << 16) |
792 ((uint64_t)mask_ptr[14] << 8) | ((uint64_t)mask_ptr[15]);
793
794 if(mask_high == 0) {
795 // if the high bits are all 0, then low bits must be all 0.
796 return mask_low == 0;
797 }
798
799 // Check that all the 1's are contiguous from left to right
800 uint64_t inv_mask_high = ~mask_high;
801 if ((inv_mask_high + 1) & inv_mask_high) {
802 return 0;
803 }
804
805 // If there was one or more 0's then low has to be all zeros
806 if(inv_mask_high) {
807 return mask_low == 0;
808 }
809
810 // Otherwise low may be all zero's, and if not then the 1's must be contiguous
811 // from left to right
812 return (mask_low == 0 || ((~mask_low + 1) & ~mask_low) == 0);
813 }
814
815 int validate_cidr_mask(CBS *cidr_mask) {
816 size_t mask_len = CBS_len(cidr_mask);
817 switch (mask_len) {
818 case IPV4_ADDR_LEN:
819 return validate_ipv4_cidr_mask(CBS_data(cidr_mask), mask_len);
820 case IPV6_ADDR_LEN:
821 return validate_ipv6_cidr_mask(CBS_data(cidr_mask), mask_len);
822 default:
823 return 0;
824 }
825 }
826
827 static int nc_ip(const ASN1_OCTET_STRING *ip, const ASN1_OCTET_STRING *base) {
828 CBS ip_cbs, cidr_cbs, cidr_addr, cidr_mask;
829
830 CBS_init(&ip_cbs, ip->data, ip->length);
831 CBS_init(&cidr_cbs, base->data, base->length);
832
833 size_t ip_len = CBS_len(&ip_cbs);
834 size_t cidr_len = CBS_len(&cidr_cbs);
835
836 // Next the IP length should be either the length of an IPv4 or IPv6 address.
837 // Finally the CIDR length should either be the length of an IPv4 address+mask
838 // or IPv6 address+mask.
839 if (!((ip_len == IPV4_ADDR_LEN) || (ip_len == IPV6_ADDR_LEN)) ||
840 !((cidr_len == IPV4_CIDR_LEN) || (cidr_len == IPV6_CIDR_LEN))) {
841 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
842 }
843
844 // Validate that the CIDR length is twice the size of the provided IP (address
845 // + mask).
846 if (ip_len * 2 != cidr_len) {
847 return X509_V_ERR_PERMITTED_VIOLATION;
848 }
849
850 if (!CBS_get_bytes(&cidr_cbs, &cidr_addr, ip_len) ||
851 !CBS_get_bytes(&cidr_cbs, &cidr_mask, ip_len) || CBS_len(&cidr_cbs) > 0) {
852 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
853 }
854
855 // Checking for wrong mask definition that are not valid CIDR prefixes.
856 // For example: 255.0.255.0
857 if (!validate_cidr_mask(&cidr_mask)) {
858 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
859 }
860
861 uint8_t ip_byte = 0, cidr_addr_byte = 0, cidr_mask_byte = 0;
862
863 for (size_t i = 0; i < ip_len; i++) {
864 if (!CBS_get_u8(&ip_cbs, &ip_byte) ||
865 !CBS_get_u8(&cidr_addr, &cidr_addr_byte) ||
866 !CBS_get_u8(&cidr_mask, &cidr_mask_byte) ||
867 ((ip_byte & cidr_mask_byte) != (cidr_addr_byte & cidr_mask_byte))) {
868 return X509_V_ERR_PERMITTED_VIOLATION;
869 }
870 }
871
872 return X509_V_OK;
873 }