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