2 * Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "internal/cryptlib.h"
11 #include "internal/numbers.h"
13 #include "crypto/asn1.h"
14 #include <openssl/asn1t.h>
15 #include <openssl/conf.h>
16 #include <openssl/x509v3.h>
18 #include "crypto/x509.h"
21 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
23 STACK_OF(CONF_VALUE) *nval);
24 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
26 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
27 STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp,
28 int ind, const char *name);
29 static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip);
31 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
32 static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen);
33 static int nc_dn(X509_NAME *sub, X509_NAME *nm);
34 static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns);
35 static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml);
36 static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base);
37 static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base);
39 const X509V3_EXT_METHOD v3_name_constraints = {
40 NID_name_constraints, 0,
41 ASN1_ITEM_ref(NAME_CONSTRAINTS),
44 0, v2i_NAME_CONSTRAINTS,
45 i2r_NAME_CONSTRAINTS, 0,
49 ASN1_SEQUENCE(GENERAL_SUBTREE) = {
50 ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME),
51 ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0),
52 ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1)
53 } ASN1_SEQUENCE_END(GENERAL_SUBTREE)
55 ASN1_SEQUENCE(NAME_CONSTRAINTS) = {
56 ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees,
58 ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees,
60 } ASN1_SEQUENCE_END(NAME_CONSTRAINTS)
63 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
64 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
67 #define IA5_OFFSET_LEN(ia5base, offset) \
68 ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
70 /* Like memchr but for ASN1_IA5STRING. Additionally you can specify the
71 * starting point to search from
73 # define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start))
75 /* Like memrrchr but for ASN1_IA5STRING */
76 static char *ia5memrchr(ASN1_IA5STRING *str, int c)
80 for (i = str->length; i > 0 && str->data[i - 1] != c; i--);
85 return (char *)&str->data[i - 1];
89 * We cannot use strncasecmp here because that applies locale specific rules. It
90 * also doesn't work with ASN1_STRINGs that may have embedded NUL characters.
91 * For example in Turkish 'I' is not the uppercase character for 'i'. We need to
92 * do a simple ASCII case comparison ignoring the locale (that is why we use
93 * numeric constants below).
95 static int ia5ncasecmp(const char *s1, const char *s2, size_t n)
97 for (; n > 0; n--, s1++, s2++) {
99 unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2;
101 /* Convert to lower case */
102 if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */)
104 if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */)
121 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
122 X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
125 CONF_VALUE tval, *val;
126 STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
127 NAME_CONSTRAINTS *ncons = NULL;
128 GENERAL_SUBTREE *sub = NULL;
130 ncons = NAME_CONSTRAINTS_new();
133 for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
134 val = sk_CONF_VALUE_value(nval, i);
135 if (strncmp(val->name, "permitted", 9) == 0 && val->name[9]) {
136 ptree = &ncons->permittedSubtrees;
137 tval.name = val->name + 10;
138 } else if (strncmp(val->name, "excluded", 8) == 0 && val->name[8]) {
139 ptree = &ncons->excludedSubtrees;
140 tval.name = val->name + 9;
142 X509V3err(X509V3_F_V2I_NAME_CONSTRAINTS, X509V3_R_INVALID_SYNTAX);
145 tval.value = val->value;
146 sub = GENERAL_SUBTREE_new();
149 if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1))
152 *ptree = sk_GENERAL_SUBTREE_new_null();
153 if (*ptree == NULL || !sk_GENERAL_SUBTREE_push(*ptree, sub))
161 X509V3err(X509V3_F_V2I_NAME_CONSTRAINTS, ERR_R_MALLOC_FAILURE);
163 NAME_CONSTRAINTS_free(ncons);
164 GENERAL_SUBTREE_free(sub);
169 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
172 NAME_CONSTRAINTS *ncons = a;
173 do_i2r_name_constraints(method, ncons->permittedSubtrees,
174 bp, ind, "Permitted");
175 do_i2r_name_constraints(method, ncons->excludedSubtrees,
176 bp, ind, "Excluded");
180 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
181 STACK_OF(GENERAL_SUBTREE) *trees,
182 BIO *bp, int ind, const char *name)
184 GENERAL_SUBTREE *tree;
186 if (sk_GENERAL_SUBTREE_num(trees) > 0)
187 BIO_printf(bp, "%*s%s:\n", ind, "", name);
188 for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
189 tree = sk_GENERAL_SUBTREE_value(trees, i);
190 BIO_printf(bp, "%*s", ind + 2, "");
191 if (tree->base->type == GEN_IPADD)
192 print_nc_ipadd(bp, tree->base->d.ip);
194 GENERAL_NAME_print(bp, tree->base);
200 static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip)
208 BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d",
209 p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
210 } else if (len == 32) {
211 for (i = 0; i < 16; i++) {
212 BIO_printf(bp, "%X", p[0] << 8 | p[1]);
220 BIO_printf(bp, "IP Address:<invalid>");
224 #define NAME_CHECK_MAX (1 << 20)
226 static int add_lengths(int *out, int a, int b)
228 /* sk_FOO_num(NULL) returns -1 but is effectively 0 when iterating. */
241 * Check a certificate conforms to a specified set of constraints.
243 * X509_V_OK: All constraints obeyed.
244 * X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
245 * X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
246 * X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
247 * X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type.
248 * X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax.
249 * X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name
252 int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc)
254 int r, i, name_count, constraint_count;
257 nm = X509_get_subject_name(x);
260 * Guard against certificates with an excessive number of names or
261 * constraints causing a computationally expensive name constraints check.
263 if (!add_lengths(&name_count, X509_NAME_entry_count(nm),
264 sk_GENERAL_NAME_num(x->altname))
265 || !add_lengths(&constraint_count,
266 sk_GENERAL_SUBTREE_num(nc->permittedSubtrees),
267 sk_GENERAL_SUBTREE_num(nc->excludedSubtrees))
268 || (name_count > 0 && constraint_count > NAME_CHECK_MAX / name_count))
269 return X509_V_ERR_UNSPECIFIED;
271 if (X509_NAME_entry_count(nm) > 0) {
273 gntmp.type = GEN_DIRNAME;
274 gntmp.d.directoryName = nm;
276 r = nc_match(&gntmp, nc);
281 gntmp.type = GEN_EMAIL;
283 /* Process any email address attributes in subject name */
286 const X509_NAME_ENTRY *ne;
288 i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i);
291 ne = X509_NAME_get_entry(nm, i);
292 gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
293 if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING)
294 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
296 r = nc_match(&gntmp, nc);
304 for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) {
305 GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i);
306 r = nc_match(gen, nc);
315 static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen)
318 unsigned char *utf8_value;
322 /* Don't leave outputs uninitialized */
327 * Per RFC 6125, DNS-IDs representing internationalized domain names appear
328 * in certificates in A-label encoded form:
330 * https://tools.ietf.org/html/rfc6125#section-6.4.2
332 * The same applies to CNs which are intended to represent DNS names.
333 * However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be
334 * needlessly encoded in 16-bit Unicode. We perform a conversion to UTF-8
335 * to ensure that we get an ASCII representation of any CNs that are
336 * representable as ASCII, but just not encoded as ASCII. The UTF-8 form
337 * may contain some non-ASCII octets, and that's fine, such CNs are not
338 * valid legacy DNS names.
340 * Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what
341 * we must use for 'utf8_length'.
343 if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn)) < 0)
344 return X509_V_ERR_OUT_OF_MEM;
347 * Some certificates have had names that include a *trailing* NUL byte.
348 * Remove these harmless NUL characters. They would otherwise yield false
349 * alarms with the following embedded NUL check.
351 while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0')
354 /* Reject *embedded* NULs */
355 if (memchr(utf8_value, 0, utf8_length) != NULL) {
356 OPENSSL_free(utf8_value);
357 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
361 * XXX: Deviation from strict DNS name syntax, also check names with '_'
362 * Check DNS name syntax, any '-' or '.' must be internal,
363 * and on either side of each '.' we can't have a '-' or '.'.
365 * If the name has just one label, we don't consider it a DNS name. This
366 * means that "CN=sometld" cannot be precluded by DNS name constraints, but
367 * that is not a problem.
369 for (i = 0; i < utf8_length; ++i) {
370 unsigned char c = utf8_value[i];
372 if ((c >= 'a' && c <= 'z')
373 || (c >= 'A' && c <= 'Z')
374 || (c >= '0' && c <= '9')
378 /* Dot and hyphen cannot be first or last. */
379 if (i > 0 && i < utf8_length - 1) {
383 * Next to a dot the preceding and following characters must not be
384 * another dot or a hyphen. Otherwise, record that the name is
385 * plausible, since it has two or more labels.
388 && utf8_value[i + 1] != '.'
389 && utf8_value[i - 1] != '-'
390 && utf8_value[i + 1] != '-') {
401 *idlen = (size_t)utf8_length;
404 OPENSSL_free(utf8_value);
409 * Check CN against DNS-ID name constraints.
411 int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc)
414 X509_NAME *nm = X509_get_subject_name(x);
419 stmp.type = V_ASN1_IA5STRING;
420 gntmp.type = GEN_DNS;
421 gntmp.d.dNSName = &stmp;
423 /* Process any commonName attributes in subject name */
428 unsigned char *idval;
431 i = X509_NAME_get_index_by_NID(nm, NID_commonName, i);
434 ne = X509_NAME_get_entry(nm, i);
435 cn = X509_NAME_ENTRY_get_data(ne);
437 /* Only process attributes that look like host names */
438 if ((r = cn2dnsid(cn, &idval, &idlen)) != X509_V_OK)
445 r = nc_match(&gntmp, nc);
453 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc)
455 GENERAL_SUBTREE *sub;
459 * Permitted subtrees: if any subtrees exist of matching the type at
460 * least one subtree must match.
463 for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
464 sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
465 if (gen->type != sub->base->type)
467 if (sub->minimum || sub->maximum)
468 return X509_V_ERR_SUBTREE_MINMAX;
469 /* If we already have a match don't bother trying any more */
474 r = nc_match_single(gen, sub->base);
477 else if (r != X509_V_ERR_PERMITTED_VIOLATION)
482 return X509_V_ERR_PERMITTED_VIOLATION;
484 /* Excluded subtrees: must not match any of these */
486 for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
487 sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
488 if (gen->type != sub->base->type)
490 if (sub->minimum || sub->maximum)
491 return X509_V_ERR_SUBTREE_MINMAX;
493 r = nc_match_single(gen, sub->base);
495 return X509_V_ERR_EXCLUDED_VIOLATION;
496 else if (r != X509_V_ERR_PERMITTED_VIOLATION)
505 static int nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base)
507 switch (base->type) {
509 return nc_dn(gen->d.directoryName, base->d.directoryName);
512 return nc_dns(gen->d.dNSName, base->d.dNSName);
515 return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
518 return nc_uri(gen->d.uniformResourceIdentifier,
519 base->d.uniformResourceIdentifier);
522 return nc_ip(gen->d.iPAddress, base->d.iPAddress);
525 return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
531 * directoryName name constraint matching. The canonical encoding of
532 * X509_NAME makes this comparison easy. It is matched if the subtree is a
533 * subset of the name.
536 static int nc_dn(X509_NAME *nm, X509_NAME *base)
538 /* Ensure canonical encodings are up to date. */
539 if (nm->modified && i2d_X509_NAME(nm, NULL) < 0)
540 return X509_V_ERR_OUT_OF_MEM;
541 if (base->modified && i2d_X509_NAME(base, NULL) < 0)
542 return X509_V_ERR_OUT_OF_MEM;
543 if (base->canon_enclen > nm->canon_enclen)
544 return X509_V_ERR_PERMITTED_VIOLATION;
545 if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen))
546 return X509_V_ERR_PERMITTED_VIOLATION;
550 static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
552 char *baseptr = (char *)base->data;
553 char *dnsptr = (char *)dns->data;
555 /* Empty matches everything */
556 if (base->length == 0)
559 if (dns->length < base->length)
560 return X509_V_ERR_PERMITTED_VIOLATION;
563 * Otherwise can add zero or more components on the left so compare RHS
564 * and if dns is longer and expect '.' as preceding character.
566 if (dns->length > base->length) {
567 dnsptr += dns->length - base->length;
568 if (*baseptr != '.' && dnsptr[-1] != '.')
569 return X509_V_ERR_PERMITTED_VIOLATION;
572 if (ia5ncasecmp(baseptr, dnsptr, base->length))
573 return X509_V_ERR_PERMITTED_VIOLATION;
579 static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
581 const char *baseptr = (char *)base->data;
582 const char *emlptr = (char *)eml->data;
583 const char *baseat = ia5memrchr(base, '@');
584 const char *emlat = ia5memrchr(eml, '@');
585 size_t basehostlen, emlhostlen;
588 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
589 /* Special case: initial '.' is RHS match */
590 if (!baseat && base->length > 0 && (*baseptr == '.')) {
591 if (eml->length > base->length) {
592 emlptr += eml->length - base->length;
593 if (ia5ncasecmp(baseptr, emlptr, base->length) == 0)
596 return X509_V_ERR_PERMITTED_VIOLATION;
599 /* If we have anything before '@' match local part */
602 if (baseat != baseptr) {
603 if ((baseat - baseptr) != (emlat - emlptr))
604 return X509_V_ERR_PERMITTED_VIOLATION;
605 /* Case sensitive match of local part */
606 if (strncmp(baseptr, emlptr, emlat - emlptr))
607 return X509_V_ERR_PERMITTED_VIOLATION;
609 /* Position base after '@' */
610 baseptr = baseat + 1;
613 basehostlen = IA5_OFFSET_LEN(base, baseptr);
614 emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
615 /* Just have hostname left to match: case insensitive */
616 if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen))
617 return X509_V_ERR_PERMITTED_VIOLATION;
623 static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
625 const char *baseptr = (char *)base->data;
626 const char *hostptr = (char *)uri->data;
627 const char *p = ia5memchr(uri, (char *)uri->data, ':');
630 /* Check for foo:// and skip past it */
632 || IA5_OFFSET_LEN(uri, p) < 3
635 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
638 /* Determine length of hostname part of URI */
640 /* Look for a port indicator as end of hostname first */
642 p = ia5memchr(uri, hostptr, ':');
643 /* Otherwise look for trailing slash */
645 p = ia5memchr(uri, hostptr, '/');
648 hostlen = IA5_OFFSET_LEN(uri, hostptr);
650 hostlen = p - hostptr;
653 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
655 /* Special case: initial '.' is RHS match */
656 if (base->length > 0 && *baseptr == '.') {
657 if (hostlen > base->length) {
658 p = hostptr + hostlen - base->length;
659 if (ia5ncasecmp(p, baseptr, base->length) == 0)
662 return X509_V_ERR_PERMITTED_VIOLATION;
665 if ((base->length != (int)hostlen)
666 || ia5ncasecmp(hostptr, baseptr, hostlen))
667 return X509_V_ERR_PERMITTED_VIOLATION;
673 static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base)
675 int hostlen, baselen, i;
676 unsigned char *hostptr, *baseptr, *maskptr;
678 hostlen = ip->length;
679 baseptr = base->data;
680 baselen = base->length;
682 /* Invalid if not IPv4 or IPv6 */
683 if (!((hostlen == 4) || (hostlen == 16)))
684 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
685 if (!((baselen == 8) || (baselen == 32)))
686 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
688 /* Do not match IPv4 with IPv6 */
689 if (hostlen * 2 != baselen)
690 return X509_V_ERR_PERMITTED_VIOLATION;
692 maskptr = base->data + hostlen;
694 /* Considering possible not aligned base ipAddress */
695 /* Not checking for wrong mask definition: i.e.: 255.0.255.0 */
696 for (i = 0; i < hostlen; i++)
697 if ((hostptr[i] & maskptr[i]) != (baseptr[i] & maskptr[i]))
698 return X509_V_ERR_PERMITTED_VIOLATION;