xref: /openssl/crypto/x509/v3_ncons.c (revision a7ed61ce)
1 /*
2  * Copyright 2003-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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
8  */
9 
10 #include "internal/cryptlib.h"
11 #include "internal/numbers.h"
12 #include "internal/safe_math.h"
13 #include <stdio.h>
14 #include "crypto/asn1.h"
15 #include <openssl/asn1t.h>
16 #include <openssl/conf.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/bn.h>
19 
20 #include "crypto/x509.h"
21 #include "crypto/punycode.h"
22 #include "ext_dat.h"
23 
24 OSSL_SAFE_MATH_SIGNED(int, int)
25 
26 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
27                                   X509V3_CTX *ctx,
28                                   STACK_OF(CONF_VALUE) *nval);
29 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
30                                 BIO *bp, int ind);
31 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
32                                    STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp,
33                                    int ind, const char *name);
34 static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip);
35 
36 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
37 static int nc_match_single(int effective_type, GENERAL_NAME *sub,
38                            GENERAL_NAME *gen);
39 static int nc_dn(const X509_NAME *sub, const X509_NAME *nm);
40 static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns);
41 static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml);
42 static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base);
43 static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base);
44 static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base);
45 
46 const X509V3_EXT_METHOD ossl_v3_name_constraints = {
47     NID_name_constraints, 0,
48     ASN1_ITEM_ref(NAME_CONSTRAINTS),
49     0, 0, 0, 0,
50     0, 0,
51     0, v2i_NAME_CONSTRAINTS,
52     i2r_NAME_CONSTRAINTS, 0,
53     NULL
54 };
55 
56 const X509V3_EXT_METHOD ossl_v3_holder_name_constraints = {
57     NID_holder_name_constraints, 0,
58     ASN1_ITEM_ref(NAME_CONSTRAINTS),
59     0, 0, 0, 0,
60     0, 0,
61     0, v2i_NAME_CONSTRAINTS,
62     i2r_NAME_CONSTRAINTS, 0,
63     NULL
64 };
65 
66 const X509V3_EXT_METHOD ossl_v3_delegated_name_constraints = {
67     NID_delegated_name_constraints, 0,
68     ASN1_ITEM_ref(NAME_CONSTRAINTS),
69     0, 0, 0, 0,
70     0, 0,
71     0, v2i_NAME_CONSTRAINTS,
72     i2r_NAME_CONSTRAINTS, 0,
73     NULL
74 };
75 
76 ASN1_SEQUENCE(GENERAL_SUBTREE) = {
77         ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME),
78         ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0),
79         ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1)
80 } ASN1_SEQUENCE_END(GENERAL_SUBTREE)
81 
82 ASN1_SEQUENCE(NAME_CONSTRAINTS) = {
83         ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees,
84                                                         GENERAL_SUBTREE, 0),
85         ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees,
86                                                         GENERAL_SUBTREE, 1),
87 } ASN1_SEQUENCE_END(NAME_CONSTRAINTS)
88 
89 
90 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
91 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
92 
93 
94 #define IA5_OFFSET_LEN(ia5base, offset) \
95     ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
96 
97 /* Like memchr but for ASN1_IA5STRING. Additionally you can specify the
98  * starting point to search from
99  */
100 # define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start))
101 
102 /* Like memrrchr but for ASN1_IA5STRING */
103 static char *ia5memrchr(ASN1_IA5STRING *str, int c)
104 {
105     int i;
106 
107     for (i = str->length; i > 0 && str->data[i - 1] != c; i--);
108 
109     if (i == 0)
110         return NULL;
111 
112     return (char *)&str->data[i - 1];
113 }
114 
115 /*
116  * We cannot use strncasecmp here because that applies locale specific rules. It
117  * also doesn't work with ASN1_STRINGs that may have embedded NUL characters.
118  * For example in Turkish 'I' is not the uppercase character for 'i'. We need to
119  * do a simple ASCII case comparison ignoring the locale (that is why we use
120  * numeric constants below).
121  */
ia5ncasecmp(const char * s1,const char * s2,size_t n)122 static int ia5ncasecmp(const char *s1, const char *s2, size_t n)
123 {
124     for (; n > 0; n--, s1++, s2++) {
125         if (*s1 != *s2) {
126             unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2;
127 
128             /* Convert to lower case */
129             if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */)
130                 c1 += 0x20;
131             if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */)
132                 c2 += 0x20;
133 
134             if (c1 == c2)
135                 continue;
136 
137             if (c1 < c2)
138                 return -1;
139 
140             /* c1 > c2 */
141             return 1;
142         }
143     }
144 
145     return 0;
146 }
147 
v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD * method,X509V3_CTX * ctx,STACK_OF (CONF_VALUE)* nval)148 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
149                                   X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
150 {
151     int i;
152     CONF_VALUE tval, *val;
153     STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
154     NAME_CONSTRAINTS *ncons = NULL;
155     GENERAL_SUBTREE *sub = NULL;
156 
157     ncons = NAME_CONSTRAINTS_new();
158     if (ncons == NULL) {
159         ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
160         goto err;
161     }
162     for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
163         val = sk_CONF_VALUE_value(nval, i);
164         if (HAS_PREFIX(val->name, "permitted") && val->name[9]) {
165             ptree = &ncons->permittedSubtrees;
166             tval.name = val->name + 10;
167         } else if (HAS_PREFIX(val->name, "excluded") && val->name[8]) {
168             ptree = &ncons->excludedSubtrees;
169             tval.name = val->name + 9;
170         } else {
171             ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX);
172             goto err;
173         }
174         tval.value = val->value;
175         sub = GENERAL_SUBTREE_new();
176         if (sub == NULL) {
177             ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
178             goto err;
179         }
180         if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) {
181             ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
182             goto err;
183         }
184         if (*ptree == NULL)
185             *ptree = sk_GENERAL_SUBTREE_new_null();
186         if (*ptree == NULL || !sk_GENERAL_SUBTREE_push(*ptree, sub)) {
187             ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
188             goto err;
189         }
190         sub = NULL;
191     }
192 
193     return ncons;
194 
195  err:
196     NAME_CONSTRAINTS_free(ncons);
197     GENERAL_SUBTREE_free(sub);
198 
199     return NULL;
200 }
201 
i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD * method,void * a,BIO * bp,int ind)202 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
203                                 BIO *bp, int ind)
204 {
205     NAME_CONSTRAINTS *ncons = a;
206     do_i2r_name_constraints(method, ncons->permittedSubtrees,
207                             bp, ind, "Permitted");
208     if (ncons->permittedSubtrees && ncons->excludedSubtrees)
209         BIO_puts(bp, "\n");
210     do_i2r_name_constraints(method, ncons->excludedSubtrees,
211                             bp, ind, "Excluded");
212     return 1;
213 }
214 
do_i2r_name_constraints(const X509V3_EXT_METHOD * method,STACK_OF (GENERAL_SUBTREE)* trees,BIO * bp,int ind,const char * name)215 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
216                                    STACK_OF(GENERAL_SUBTREE) *trees,
217                                    BIO *bp, int ind, const char *name)
218 {
219     GENERAL_SUBTREE *tree;
220     int i;
221     if (sk_GENERAL_SUBTREE_num(trees) > 0)
222         BIO_printf(bp, "%*s%s:\n", ind, "", name);
223     for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
224         if (i > 0)
225             BIO_puts(bp, "\n");
226         tree = sk_GENERAL_SUBTREE_value(trees, i);
227         BIO_printf(bp, "%*s", ind + 2, "");
228         if (tree->base->type == GEN_IPADD)
229             print_nc_ipadd(bp, tree->base->d.ip);
230         else
231             GENERAL_NAME_print(bp, tree->base);
232     }
233     return 1;
234 }
235 
print_nc_ipadd(BIO * bp,ASN1_OCTET_STRING * ip)236 static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip)
237 {
238     /* ip->length should be 8 or 32 and len1 == len2 == 4 or len1 == len2 == 16 */
239     int len1 = ip->length >= 16 ? 16 : ip->length >= 4 ? 4 : ip->length;
240     int len2 = ip->length - len1;
241     char *ip1 = ossl_ipaddr_to_asc(ip->data, len1);
242     char *ip2 = ossl_ipaddr_to_asc(ip->data + len1, len2);
243     int ret = ip1 != NULL && ip2 != NULL
244         && BIO_printf(bp, "IP:%s/%s", ip1, ip2) > 0;
245 
246     OPENSSL_free(ip1);
247     OPENSSL_free(ip2);
248     return ret;
249 }
250 
251 #define NAME_CHECK_MAX (1 << 20)
252 
add_lengths(int * out,int a,int b)253 static int add_lengths(int *out, int a, int b)
254 {
255     int err = 0;
256 
257     /* sk_FOO_num(NULL) returns -1 but is effectively 0 when iterating. */
258     if (a < 0)
259         a = 0;
260     if (b < 0)
261         b = 0;
262 
263     *out = safe_add_int(a, b, &err);
264     return !err;
265 }
266 
267 /*-
268  * Check a certificate conforms to a specified set of constraints.
269  * Return values:
270  *  X509_V_OK: All constraints obeyed.
271  *  X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
272  *  X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
273  *  X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
274  *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE:  Unsupported constraint type.
275  *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax.
276  *  X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name
277  */
278 
NAME_CONSTRAINTS_check(X509 * x,NAME_CONSTRAINTS * nc)279 int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc)
280 {
281     int r, i, name_count, constraint_count;
282     X509_NAME *nm;
283 
284     nm = X509_get_subject_name(x);
285 
286     /*
287      * Guard against certificates with an excessive number of names or
288      * constraints causing a computationally expensive name constraints check.
289      */
290     if (!add_lengths(&name_count, X509_NAME_entry_count(nm),
291                      sk_GENERAL_NAME_num(x->altname))
292         || !add_lengths(&constraint_count,
293                         sk_GENERAL_SUBTREE_num(nc->permittedSubtrees),
294                         sk_GENERAL_SUBTREE_num(nc->excludedSubtrees))
295         || (name_count > 0 && constraint_count > NAME_CHECK_MAX / name_count))
296         return X509_V_ERR_UNSPECIFIED;
297 
298     if (X509_NAME_entry_count(nm) > 0) {
299         GENERAL_NAME gntmp;
300         gntmp.type = GEN_DIRNAME;
301         gntmp.d.directoryName = nm;
302 
303         r = nc_match(&gntmp, nc);
304 
305         if (r != X509_V_OK)
306             return r;
307 
308         gntmp.type = GEN_EMAIL;
309 
310         /* Process any email address attributes in subject name */
311 
312         for (i = -1;;) {
313             const X509_NAME_ENTRY *ne;
314 
315             i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i);
316             if (i == -1)
317                 break;
318             ne = X509_NAME_get_entry(nm, i);
319             gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
320             if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING)
321                 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
322 
323             r = nc_match(&gntmp, nc);
324 
325             if (r != X509_V_OK)
326                 return r;
327         }
328 
329     }
330 
331     for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) {
332         GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i);
333         r = nc_match(gen, nc);
334         if (r != X509_V_OK)
335             return r;
336     }
337 
338     return X509_V_OK;
339 
340 }
341 
cn2dnsid(ASN1_STRING * cn,unsigned char ** dnsid,size_t * idlen)342 static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen)
343 {
344     int utf8_length;
345     unsigned char *utf8_value;
346     int i;
347     int isdnsname = 0;
348 
349     /* Don't leave outputs uninitialized */
350     *dnsid = NULL;
351     *idlen = 0;
352 
353     /*-
354      * Per RFC 6125, DNS-IDs representing internationalized domain names appear
355      * in certificates in A-label encoded form:
356      *
357      *   https://tools.ietf.org/html/rfc6125#section-6.4.2
358      *
359      * The same applies to CNs which are intended to represent DNS names.
360      * However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be
361      * needlessly encoded in 16-bit Unicode.  We perform a conversion to UTF-8
362      * to ensure that we get an ASCII representation of any CNs that are
363      * representable as ASCII, but just not encoded as ASCII.  The UTF-8 form
364      * may contain some non-ASCII octets, and that's fine, such CNs are not
365      * valid legacy DNS names.
366      *
367      * Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what
368      * we must use for 'utf8_length'.
369      */
370     if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn)) < 0)
371         return X509_V_ERR_OUT_OF_MEM;
372 
373     /*
374      * Some certificates have had names that include a *trailing* NUL byte.
375      * Remove these harmless NUL characters. They would otherwise yield false
376      * alarms with the following embedded NUL check.
377      */
378     while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0')
379         --utf8_length;
380 
381     /* Reject *embedded* NULs */
382     if (memchr(utf8_value, 0, utf8_length) != NULL) {
383         OPENSSL_free(utf8_value);
384         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
385     }
386 
387     /*
388      * XXX: Deviation from strict DNS name syntax, also check names with '_'
389      * Check DNS name syntax, any '-' or '.' must be internal,
390      * and on either side of each '.' we can't have a '-' or '.'.
391      *
392      * If the name has just one label, we don't consider it a DNS name.  This
393      * means that "CN=sometld" cannot be precluded by DNS name constraints, but
394      * that is not a problem.
395      */
396     for (i = 0; i < utf8_length; ++i) {
397         unsigned char c = utf8_value[i];
398 
399         if ((c >= 'a' && c <= 'z')
400             || (c >= 'A' && c <= 'Z')
401             || (c >= '0' && c <= '9')
402             || c == '_')
403             continue;
404 
405         /* Dot and hyphen cannot be first or last. */
406         if (i > 0 && i < utf8_length - 1) {
407             if (c == '-')
408                 continue;
409             /*
410              * Next to a dot the preceding and following characters must not be
411              * another dot or a hyphen.  Otherwise, record that the name is
412              * plausible, since it has two or more labels.
413              */
414             if (c == '.'
415                 && utf8_value[i + 1] != '.'
416                 && utf8_value[i - 1] != '-'
417                 && utf8_value[i + 1] != '-') {
418                 isdnsname = 1;
419                 continue;
420             }
421         }
422         isdnsname = 0;
423         break;
424     }
425 
426     if (isdnsname) {
427         *dnsid = utf8_value;
428         *idlen = (size_t)utf8_length;
429         return X509_V_OK;
430     }
431     OPENSSL_free(utf8_value);
432     return X509_V_OK;
433 }
434 
435 /*
436  * Check CN against DNS-ID name constraints.
437  */
NAME_CONSTRAINTS_check_CN(X509 * x,NAME_CONSTRAINTS * nc)438 int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc)
439 {
440     int r, i;
441     const X509_NAME *nm = X509_get_subject_name(x);
442     ASN1_STRING stmp;
443     GENERAL_NAME gntmp;
444 
445     stmp.flags = 0;
446     stmp.type = V_ASN1_IA5STRING;
447     gntmp.type = GEN_DNS;
448     gntmp.d.dNSName = &stmp;
449 
450     /* Process any commonName attributes in subject name */
451 
452     for (i = -1;;) {
453         X509_NAME_ENTRY *ne;
454         ASN1_STRING *cn;
455         unsigned char *idval;
456         size_t idlen;
457 
458         i = X509_NAME_get_index_by_NID(nm, NID_commonName, i);
459         if (i == -1)
460             break;
461         ne = X509_NAME_get_entry(nm, i);
462         cn = X509_NAME_ENTRY_get_data(ne);
463 
464         /* Only process attributes that look like hostnames */
465         if ((r = cn2dnsid(cn, &idval, &idlen)) != X509_V_OK)
466             return r;
467         if (idlen == 0)
468             continue;
469 
470         stmp.length = idlen;
471         stmp.data = idval;
472         r = nc_match(&gntmp, nc);
473         OPENSSL_free(idval);
474         if (r != X509_V_OK)
475             return r;
476     }
477     return X509_V_OK;
478 }
479 
480 /*
481  * Return nonzero if the GeneralSubtree has valid 'minimum' field
482  * (must be absent or 0) and valid 'maximum' field (must be absent).
483  */
nc_minmax_valid(GENERAL_SUBTREE * sub)484 static int nc_minmax_valid(GENERAL_SUBTREE *sub) {
485     BIGNUM *bn = NULL;
486     int ok = 1;
487 
488     if (sub->maximum)
489         ok = 0;
490 
491     if (sub->minimum) {
492         bn = ASN1_INTEGER_to_BN(sub->minimum, NULL);
493         if (bn == NULL || !BN_is_zero(bn))
494             ok = 0;
495         BN_free(bn);
496     }
497 
498     return ok;
499 }
500 
nc_match(GENERAL_NAME * gen,NAME_CONSTRAINTS * nc)501 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc)
502 {
503     GENERAL_SUBTREE *sub;
504     int i, r, match = 0;
505     int effective_type = gen->type;
506 
507     /*
508      * We need to compare not gen->type field but an "effective" type because
509      * the otherName field may contain EAI email address treated specially
510      * according to RFC 8398, section 6
511      */
512     if (effective_type == GEN_OTHERNAME &&
513         (OBJ_obj2nid(gen->d.otherName->type_id) == NID_id_on_SmtpUTF8Mailbox)) {
514         effective_type = GEN_EMAIL;
515     }
516 
517     /*
518      * Permitted subtrees: if any subtrees exist of matching the type at
519      * least one subtree must match.
520      */
521 
522     for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
523         sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
524         if (effective_type != sub->base->type
525             || (effective_type == GEN_OTHERNAME &&
526                 OBJ_cmp(gen->d.otherName->type_id,
527                         sub->base->d.otherName->type_id) != 0))
528             continue;
529         if (!nc_minmax_valid(sub))
530             return X509_V_ERR_SUBTREE_MINMAX;
531         /* If we already have a match don't bother trying any more */
532         if (match == 2)
533             continue;
534         if (match == 0)
535             match = 1;
536         r = nc_match_single(effective_type, gen, sub->base);
537         if (r == X509_V_OK)
538             match = 2;
539         else if (r != X509_V_ERR_PERMITTED_VIOLATION)
540             return r;
541     }
542 
543     if (match == 1)
544         return X509_V_ERR_PERMITTED_VIOLATION;
545 
546     /* Excluded subtrees: must not match any of these */
547 
548     for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
549         sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
550         if (effective_type != sub->base->type
551             || (effective_type == GEN_OTHERNAME &&
552                 OBJ_cmp(gen->d.otherName->type_id,
553                         sub->base->d.otherName->type_id) != 0))
554             continue;
555         if (!nc_minmax_valid(sub))
556             return X509_V_ERR_SUBTREE_MINMAX;
557 
558         r = nc_match_single(effective_type, gen, sub->base);
559         if (r == X509_V_OK)
560             return X509_V_ERR_EXCLUDED_VIOLATION;
561         else if (r != X509_V_ERR_PERMITTED_VIOLATION)
562             return r;
563 
564     }
565 
566     return X509_V_OK;
567 
568 }
569 
nc_match_single(int effective_type,GENERAL_NAME * gen,GENERAL_NAME * base)570 static int nc_match_single(int effective_type, GENERAL_NAME *gen,
571                            GENERAL_NAME *base)
572 {
573     switch (gen->type) {
574     case GEN_OTHERNAME:
575         switch (effective_type) {
576         case GEN_EMAIL:
577             /*
578              * We are here only when we have SmtpUTF8 name,
579              * so we match the value of othername with base->d.rfc822Name
580              */
581             return nc_email_eai(gen->d.otherName->value, base->d.rfc822Name);
582 
583         default:
584             return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
585         }
586 
587     case GEN_DIRNAME:
588         return nc_dn(gen->d.directoryName, base->d.directoryName);
589 
590     case GEN_DNS:
591         return nc_dns(gen->d.dNSName, base->d.dNSName);
592 
593     case GEN_EMAIL:
594         return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
595 
596     case GEN_URI:
597         return nc_uri(gen->d.uniformResourceIdentifier,
598                       base->d.uniformResourceIdentifier);
599 
600     case GEN_IPADD:
601         return nc_ip(gen->d.iPAddress, base->d.iPAddress);
602 
603     default:
604         return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
605     }
606 
607 }
608 
609 /*
610  * directoryName name constraint matching. The canonical encoding of
611  * X509_NAME makes this comparison easy. It is matched if the subtree is a
612  * subset of the name.
613  */
614 
nc_dn(const X509_NAME * nm,const X509_NAME * base)615 static int nc_dn(const X509_NAME *nm, const X509_NAME *base)
616 {
617     /* Ensure canonical encodings are up to date.  */
618     if (nm->modified && i2d_X509_NAME(nm, NULL) < 0)
619         return X509_V_ERR_OUT_OF_MEM;
620     if (base->modified && i2d_X509_NAME(base, NULL) < 0)
621         return X509_V_ERR_OUT_OF_MEM;
622     if (base->canon_enclen > nm->canon_enclen)
623         return X509_V_ERR_PERMITTED_VIOLATION;
624     if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen))
625         return X509_V_ERR_PERMITTED_VIOLATION;
626     return X509_V_OK;
627 }
628 
nc_dns(ASN1_IA5STRING * dns,ASN1_IA5STRING * base)629 static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
630 {
631     char *baseptr = (char *)base->data;
632     char *dnsptr = (char *)dns->data;
633 
634     /* Empty matches everything */
635     if (base->length == 0)
636         return X509_V_OK;
637 
638     if (dns->length < base->length)
639         return X509_V_ERR_PERMITTED_VIOLATION;
640 
641     /*
642      * Otherwise can add zero or more components on the left so compare RHS
643      * and if dns is longer and expect '.' as preceding character.
644      */
645     if (dns->length > base->length) {
646         dnsptr += dns->length - base->length;
647         if (*baseptr != '.' && dnsptr[-1] != '.')
648             return X509_V_ERR_PERMITTED_VIOLATION;
649     }
650 
651     if (ia5ncasecmp(baseptr, dnsptr, base->length))
652         return X509_V_ERR_PERMITTED_VIOLATION;
653 
654     return X509_V_OK;
655 
656 }
657 
658 /*
659  * This function implements comparison between ASCII/U-label in emltype
660  * and A-label in base according to RFC 8398, section 6.
661  * Convert base to U-label and ASCII-parts of domain names, for base
662  * Octet-to-octet comparison of `emltype` and `base` hostname parts
663  * (ASCII-parts should be compared in case-insensitive manner)
664  */
nc_email_eai(ASN1_TYPE * emltype,ASN1_IA5STRING * base)665 static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base)
666 {
667     ASN1_UTF8STRING *eml;
668     char *baseptr = NULL;
669     const char *emlptr;
670     const char *emlat;
671     char ulabel[256];
672     size_t size = sizeof(ulabel);
673     int ret = X509_V_OK;
674     size_t emlhostlen;
675 
676     /* We do not accept embedded NUL characters */
677     if (base->length > 0 && memchr(base->data, 0, base->length) != NULL)
678         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
679 
680     /* 'base' may not be NUL terminated. Create a copy that is */
681     baseptr = OPENSSL_strndup((char *)base->data, base->length);
682     if (baseptr == NULL)
683         return X509_V_ERR_OUT_OF_MEM;
684 
685     if (emltype->type != V_ASN1_UTF8STRING) {
686         ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
687         goto end;
688     }
689 
690     eml = emltype->value.utf8string;
691     emlptr = (char *)eml->data;
692     emlat = ia5memrchr(eml, '@');
693 
694     if (emlat == NULL) {
695         ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
696         goto end;
697     }
698 
699     /* Special case: initial '.' is RHS match */
700     if (*baseptr == '.') {
701         ulabel[0] = '.';
702         if (ossl_a2ulabel(baseptr, ulabel + 1, size - 1) <= 0) {
703             ret = X509_V_ERR_UNSPECIFIED;
704             goto end;
705         }
706 
707         if ((size_t)eml->length > strlen(ulabel)) {
708             emlptr += eml->length - strlen(ulabel);
709             /* X509_V_OK */
710             if (ia5ncasecmp(ulabel, emlptr, strlen(ulabel)) == 0)
711                 goto end;
712         }
713         ret = X509_V_ERR_PERMITTED_VIOLATION;
714         goto end;
715     }
716 
717     if (ossl_a2ulabel(baseptr, ulabel, size) <= 0) {
718         ret = X509_V_ERR_UNSPECIFIED;
719         goto end;
720     }
721     /* Just have hostname left to match: case insensitive */
722     emlptr = emlat + 1;
723     emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
724     if (emlhostlen != strlen(ulabel)
725             || ia5ncasecmp(ulabel, emlptr, emlhostlen) != 0) {
726         ret = X509_V_ERR_PERMITTED_VIOLATION;
727         goto end;
728     }
729 
730  end:
731     OPENSSL_free(baseptr);
732     return ret;
733 }
734 
nc_email(ASN1_IA5STRING * eml,ASN1_IA5STRING * base)735 static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
736 {
737     const char *baseptr = (char *)base->data;
738     const char *emlptr = (char *)eml->data;
739     const char *baseat = ia5memrchr(base, '@');
740     const char *emlat = ia5memrchr(eml, '@');
741     size_t basehostlen, emlhostlen;
742 
743     if (!emlat)
744         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
745     /* Special case: initial '.' is RHS match */
746     if (!baseat && base->length > 0 && (*baseptr == '.')) {
747         if (eml->length > base->length) {
748             emlptr += eml->length - base->length;
749             if (ia5ncasecmp(baseptr, emlptr, base->length) == 0)
750                 return X509_V_OK;
751         }
752         return X509_V_ERR_PERMITTED_VIOLATION;
753     }
754 
755     /* If we have anything before '@' match local part */
756 
757     if (baseat) {
758         if (baseat != baseptr) {
759             if ((baseat - baseptr) != (emlat - emlptr))
760                 return X509_V_ERR_PERMITTED_VIOLATION;
761             if (memchr(baseptr, 0, baseat - baseptr) ||
762                 memchr(emlptr, 0, emlat - emlptr))
763                 return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
764             /* Case sensitive match of local part */
765             if (strncmp(baseptr, emlptr, emlat - emlptr))
766                 return X509_V_ERR_PERMITTED_VIOLATION;
767         }
768         /* Position base after '@' */
769         baseptr = baseat + 1;
770     }
771     emlptr = emlat + 1;
772     basehostlen = IA5_OFFSET_LEN(base, baseptr);
773     emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
774     /* Just have hostname left to match: case insensitive */
775     if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen))
776         return X509_V_ERR_PERMITTED_VIOLATION;
777 
778     return X509_V_OK;
779 
780 }
781 
nc_uri(ASN1_IA5STRING * uri,ASN1_IA5STRING * base)782 static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
783 {
784     const char *baseptr = (char *)base->data;
785     const char *hostptr = (char *)uri->data;
786     const char *p = ia5memchr(uri, (char *)uri->data, ':');
787     int hostlen;
788 
789     /* Check for foo:// and skip past it */
790     if (p == NULL
791             || IA5_OFFSET_LEN(uri, p) < 3
792             || p[1] != '/'
793             || p[2] != '/')
794         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
795     hostptr = p + 3;
796 
797     /* Determine length of hostname part of URI */
798 
799     /* Look for a port indicator as end of hostname first */
800 
801     p = ia5memchr(uri, hostptr, ':');
802     /* Otherwise look for trailing slash */
803     if (p == NULL)
804         p = ia5memchr(uri, hostptr, '/');
805 
806     if (p == NULL)
807         hostlen = IA5_OFFSET_LEN(uri, hostptr);
808     else
809         hostlen = p - hostptr;
810 
811     if (hostlen == 0)
812         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
813 
814     /* Special case: initial '.' is RHS match */
815     if (base->length > 0 && *baseptr == '.') {
816         if (hostlen > base->length) {
817             p = hostptr + hostlen - base->length;
818             if (ia5ncasecmp(p, baseptr, base->length) == 0)
819                 return X509_V_OK;
820         }
821         return X509_V_ERR_PERMITTED_VIOLATION;
822     }
823 
824     if ((base->length != (int)hostlen)
825         || ia5ncasecmp(hostptr, baseptr, hostlen))
826         return X509_V_ERR_PERMITTED_VIOLATION;
827 
828     return X509_V_OK;
829 
830 }
831 
nc_ip(ASN1_OCTET_STRING * ip,ASN1_OCTET_STRING * base)832 static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base)
833 {
834     int hostlen, baselen, i;
835     unsigned char *hostptr, *baseptr, *maskptr;
836     hostptr = ip->data;
837     hostlen = ip->length;
838     baseptr = base->data;
839     baselen = base->length;
840 
841     /* Invalid if not IPv4 or IPv6 */
842     if (!((hostlen == 4) || (hostlen == 16)))
843         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
844     if (!((baselen == 8) || (baselen == 32)))
845         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
846 
847     /* Do not match IPv4 with IPv6 */
848     if (hostlen * 2 != baselen)
849         return X509_V_ERR_PERMITTED_VIOLATION;
850 
851     maskptr = base->data + hostlen;
852 
853     /* Considering possible not aligned base ipAddress */
854     /* Not checking for wrong mask definition: i.e.: 255.0.255.0 */
855     for (i = 0; i < hostlen; i++)
856         if ((hostptr[i] & maskptr[i]) != (baseptr[i] & maskptr[i]))
857             return X509_V_ERR_PERMITTED_VIOLATION;
858 
859     return X509_V_OK;
860 
861 }
862