Fix function name in ECerr call
[openssl.git] / crypto / x509v3 / v3_utl.c
1 /*
2  * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9
10 /* X509 v3 extension utilities */
11
12 #include "e_os.h"
13 #include "internal/cryptlib.h"
14 #include <stdio.h>
15 #include "internal/ctype.h"
16 #include <openssl/conf.h>
17 #include <openssl/x509v3.h>
18 #include "internal/x509_int.h"
19 #include <openssl/bn.h>
20 #include "ext_dat.h"
21
22 static char *strip_spaces(char *name);
23 static int sk_strcmp(const char *const *a, const char *const *b);
24 static STACK_OF(OPENSSL_STRING) *get_email(X509_NAME *name,
25                                            GENERAL_NAMES *gens);
26 static void str_free(OPENSSL_STRING str);
27 static int append_ia5(STACK_OF(OPENSSL_STRING) **sk, const ASN1_IA5STRING *email);
28
29 static int ipv4_from_asc(unsigned char *v4, const char *in);
30 static int ipv6_from_asc(unsigned char *v6, const char *in);
31 static int ipv6_cb(const char *elem, int len, void *usr);
32 static int ipv6_hex(unsigned char *out, const char *in, int inlen);
33
34 /* Add a CONF_VALUE name value pair to stack */
35
36 int X509V3_add_value(const char *name, const char *value,
37                      STACK_OF(CONF_VALUE) **extlist)
38 {
39     CONF_VALUE *vtmp = NULL;
40     char *tname = NULL, *tvalue = NULL;
41
42     if (name && (tname = OPENSSL_strdup(name)) == NULL)
43         goto err;
44     if (value && (tvalue = OPENSSL_strdup(value)) == NULL)
45         goto err;
46     if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
47         goto err;
48     if (*extlist == NULL && (*extlist = sk_CONF_VALUE_new_null()) == NULL)
49         goto err;
50     vtmp->section = NULL;
51     vtmp->name = tname;
52     vtmp->value = tvalue;
53     if (!sk_CONF_VALUE_push(*extlist, vtmp))
54         goto err;
55     return 1;
56  err:
57     X509V3err(X509V3_F_X509V3_ADD_VALUE, ERR_R_MALLOC_FAILURE);
58     OPENSSL_free(vtmp);
59     OPENSSL_free(tname);
60     OPENSSL_free(tvalue);
61     return 0;
62 }
63
64 int X509V3_add_value_uchar(const char *name, const unsigned char *value,
65                            STACK_OF(CONF_VALUE) **extlist)
66 {
67     return X509V3_add_value(name, (const char *)value, extlist);
68 }
69
70 /* Free function for STACK_OF(CONF_VALUE) */
71
72 void X509V3_conf_free(CONF_VALUE *conf)
73 {
74     if (!conf)
75         return;
76     OPENSSL_free(conf->name);
77     OPENSSL_free(conf->value);
78     OPENSSL_free(conf->section);
79     OPENSSL_free(conf);
80 }
81
82 int X509V3_add_value_bool(const char *name, int asn1_bool,
83                           STACK_OF(CONF_VALUE) **extlist)
84 {
85     if (asn1_bool)
86         return X509V3_add_value(name, "TRUE", extlist);
87     return X509V3_add_value(name, "FALSE", extlist);
88 }
89
90 int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
91                              STACK_OF(CONF_VALUE) **extlist)
92 {
93     if (asn1_bool)
94         return X509V3_add_value(name, "TRUE", extlist);
95     return 1;
96 }
97
98 char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *a)
99 {
100     BIGNUM *bntmp = NULL;
101     char *strtmp = NULL;
102
103     if (!a)
104         return NULL;
105     if ((bntmp = ASN1_ENUMERATED_to_BN(a, NULL)) == NULL
106         || (strtmp = BN_bn2dec(bntmp)) == NULL)
107         X509V3err(X509V3_F_I2S_ASN1_ENUMERATED, ERR_R_MALLOC_FAILURE);
108     BN_free(bntmp);
109     return strtmp;
110 }
111
112 char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *method, const ASN1_INTEGER *a)
113 {
114     BIGNUM *bntmp = NULL;
115     char *strtmp = NULL;
116
117     if (!a)
118         return NULL;
119     if ((bntmp = ASN1_INTEGER_to_BN(a, NULL)) == NULL
120         || (strtmp = BN_bn2dec(bntmp)) == NULL)
121         X509V3err(X509V3_F_I2S_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
122     BN_free(bntmp);
123     return strtmp;
124 }
125
126 ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, const char *value)
127 {
128     BIGNUM *bn = NULL;
129     ASN1_INTEGER *aint;
130     int isneg, ishex;
131     int ret;
132     if (value == NULL) {
133         X509V3err(X509V3_F_S2I_ASN1_INTEGER, X509V3_R_INVALID_NULL_VALUE);
134         return NULL;
135     }
136     bn = BN_new();
137     if (bn == NULL) {
138         X509V3err(X509V3_F_S2I_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
139         return NULL;
140     }
141     if (value[0] == '-') {
142         value++;
143         isneg = 1;
144     } else
145         isneg = 0;
146
147     if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) {
148         value += 2;
149         ishex = 1;
150     } else
151         ishex = 0;
152
153     if (ishex)
154         ret = BN_hex2bn(&bn, value);
155     else
156         ret = BN_dec2bn(&bn, value);
157
158     if (!ret || value[ret]) {
159         BN_free(bn);
160         X509V3err(X509V3_F_S2I_ASN1_INTEGER, X509V3_R_BN_DEC2BN_ERROR);
161         return NULL;
162     }
163
164     if (isneg && BN_is_zero(bn))
165         isneg = 0;
166
167     aint = BN_to_ASN1_INTEGER(bn, NULL);
168     BN_free(bn);
169     if (!aint) {
170         X509V3err(X509V3_F_S2I_ASN1_INTEGER,
171                   X509V3_R_BN_TO_ASN1_INTEGER_ERROR);
172         return NULL;
173     }
174     if (isneg)
175         aint->type |= V_ASN1_NEG;
176     return aint;
177 }
178
179 int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
180                          STACK_OF(CONF_VALUE) **extlist)
181 {
182     char *strtmp;
183     int ret;
184
185     if (!aint)
186         return 1;
187     if ((strtmp = i2s_ASN1_INTEGER(NULL, aint)) == NULL)
188         return 0;
189     ret = X509V3_add_value(name, strtmp, extlist);
190     OPENSSL_free(strtmp);
191     return ret;
192 }
193
194 int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool)
195 {
196     const char *btmp;
197
198     if ((btmp = value->value) == NULL)
199         goto err;
200     if (strcmp(btmp, "TRUE") == 0
201         || strcmp(btmp, "true") == 0
202         || strcmp(btmp, "Y") == 0
203         || strcmp(btmp, "y") == 0
204         || strcmp(btmp, "YES") == 0
205         || strcmp(btmp, "yes") == 0) {
206         *asn1_bool = 0xff;
207         return 1;
208     }
209     if (strcmp(btmp, "FALSE") == 0
210         || strcmp(btmp, "false") == 0
211         || strcmp(btmp, "N") == 0
212         || strcmp(btmp, "n") == 0
213         || strcmp(btmp, "NO") == 0
214         || strcmp(btmp, "no") == 0) {
215         *asn1_bool = 0;
216         return 1;
217     }
218  err:
219     X509V3err(X509V3_F_X509V3_GET_VALUE_BOOL,
220               X509V3_R_INVALID_BOOLEAN_STRING);
221     X509V3_conf_err(value);
222     return 0;
223 }
224
225 int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint)
226 {
227     ASN1_INTEGER *itmp;
228
229     if ((itmp = s2i_ASN1_INTEGER(NULL, value->value)) == NULL) {
230         X509V3_conf_err(value);
231         return 0;
232     }
233     *aint = itmp;
234     return 1;
235 }
236
237 #define HDR_NAME        1
238 #define HDR_VALUE       2
239
240 /*
241  * #define DEBUG
242  */
243
244 STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line)
245 {
246     char *p, *q, c;
247     char *ntmp, *vtmp;
248     STACK_OF(CONF_VALUE) *values = NULL;
249     char *linebuf;
250     int state;
251     /* We are going to modify the line so copy it first */
252     linebuf = OPENSSL_strdup(line);
253     if (linebuf == NULL) {
254         X509V3err(X509V3_F_X509V3_PARSE_LIST, ERR_R_MALLOC_FAILURE);
255         goto err;
256     }
257     state = HDR_NAME;
258     ntmp = NULL;
259     /* Go through all characters */
260     for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
261          p++) {
262
263         switch (state) {
264         case HDR_NAME:
265             if (c == ':') {
266                 state = HDR_VALUE;
267                 *p = 0;
268                 ntmp = strip_spaces(q);
269                 if (!ntmp) {
270                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
271                               X509V3_R_INVALID_NULL_NAME);
272                     goto err;
273                 }
274                 q = p + 1;
275             } else if (c == ',') {
276                 *p = 0;
277                 ntmp = strip_spaces(q);
278                 q = p + 1;
279                 if (!ntmp) {
280                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
281                               X509V3_R_INVALID_NULL_NAME);
282                     goto err;
283                 }
284                 X509V3_add_value(ntmp, NULL, &values);
285             }
286             break;
287
288         case HDR_VALUE:
289             if (c == ',') {
290                 state = HDR_NAME;
291                 *p = 0;
292                 vtmp = strip_spaces(q);
293                 if (!vtmp) {
294                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
295                               X509V3_R_INVALID_NULL_VALUE);
296                     goto err;
297                 }
298                 X509V3_add_value(ntmp, vtmp, &values);
299                 ntmp = NULL;
300                 q = p + 1;
301             }
302
303         }
304     }
305
306     if (state == HDR_VALUE) {
307         vtmp = strip_spaces(q);
308         if (!vtmp) {
309             X509V3err(X509V3_F_X509V3_PARSE_LIST,
310                       X509V3_R_INVALID_NULL_VALUE);
311             goto err;
312         }
313         X509V3_add_value(ntmp, vtmp, &values);
314     } else {
315         ntmp = strip_spaces(q);
316         if (!ntmp) {
317             X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME);
318             goto err;
319         }
320         X509V3_add_value(ntmp, NULL, &values);
321     }
322     OPENSSL_free(linebuf);
323     return values;
324
325  err:
326     OPENSSL_free(linebuf);
327     sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
328     return NULL;
329
330 }
331
332 /* Delete leading and trailing spaces from a string */
333 static char *strip_spaces(char *name)
334 {
335     char *p, *q;
336     /* Skip over leading spaces */
337     p = name;
338     while (*p && ossl_isspace(*p))
339         p++;
340     if (!*p)
341         return NULL;
342     q = p + strlen(p) - 1;
343     while ((q != p) && ossl_isspace(*q))
344         q--;
345     if (p != q)
346         q[1] = 0;
347     if (!*p)
348         return NULL;
349     return p;
350 }
351
352
353 /*
354  * V2I name comparison function: returns zero if 'name' matches cmp or cmp.*
355  */
356
357 int name_cmp(const char *name, const char *cmp)
358 {
359     int len, ret;
360     char c;
361     len = strlen(cmp);
362     if ((ret = strncmp(name, cmp, len)))
363         return ret;
364     c = name[len];
365     if (!c || (c == '.'))
366         return 0;
367     return 1;
368 }
369
370 static int sk_strcmp(const char *const *a, const char *const *b)
371 {
372     return strcmp(*a, *b);
373 }
374
375 STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x)
376 {
377     GENERAL_NAMES *gens;
378     STACK_OF(OPENSSL_STRING) *ret;
379
380     gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
381     ret = get_email(X509_get_subject_name(x), gens);
382     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
383     return ret;
384 }
385
386 STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x)
387 {
388     AUTHORITY_INFO_ACCESS *info;
389     STACK_OF(OPENSSL_STRING) *ret = NULL;
390     int i;
391
392     info = X509_get_ext_d2i(x, NID_info_access, NULL, NULL);
393     if (!info)
394         return NULL;
395     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
396         ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
397         if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
398             if (ad->location->type == GEN_URI) {
399                 if (!append_ia5
400                     (&ret, ad->location->d.uniformResourceIdentifier))
401                     break;
402             }
403         }
404     }
405     AUTHORITY_INFO_ACCESS_free(info);
406     return ret;
407 }
408
409 STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x)
410 {
411     GENERAL_NAMES *gens;
412     STACK_OF(X509_EXTENSION) *exts;
413     STACK_OF(OPENSSL_STRING) *ret;
414
415     exts = X509_REQ_get_extensions(x);
416     gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
417     ret = get_email(X509_REQ_get_subject_name(x), gens);
418     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
419     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
420     return ret;
421 }
422
423 static STACK_OF(OPENSSL_STRING) *get_email(X509_NAME *name,
424                                            GENERAL_NAMES *gens)
425 {
426     STACK_OF(OPENSSL_STRING) *ret = NULL;
427     X509_NAME_ENTRY *ne;
428     const ASN1_IA5STRING *email;
429     GENERAL_NAME *gen;
430     int i = -1;
431
432     /* Now add any email address(es) to STACK */
433     /* First supplied X509_NAME */
434     while ((i = X509_NAME_get_index_by_NID(name,
435                                            NID_pkcs9_emailAddress, i)) >= 0) {
436         ne = X509_NAME_get_entry(name, i);
437         email = X509_NAME_ENTRY_get_data(ne);
438         if (!append_ia5(&ret, email))
439             return NULL;
440     }
441     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
442         gen = sk_GENERAL_NAME_value(gens, i);
443         if (gen->type != GEN_EMAIL)
444             continue;
445         if (!append_ia5(&ret, gen->d.ia5))
446             return NULL;
447     }
448     return ret;
449 }
450
451 static void str_free(OPENSSL_STRING str)
452 {
453     OPENSSL_free(str);
454 }
455
456 static int append_ia5(STACK_OF(OPENSSL_STRING) **sk, const ASN1_IA5STRING *email)
457 {
458     char *emtmp;
459     /* First some sanity checks */
460     if (email->type != V_ASN1_IA5STRING)
461         return 1;
462     if (!email->data || !email->length)
463         return 1;
464     if (*sk == NULL)
465         *sk = sk_OPENSSL_STRING_new(sk_strcmp);
466     if (*sk == NULL)
467         return 0;
468     /* Don't add duplicates */
469     if (sk_OPENSSL_STRING_find(*sk, (char *)email->data) != -1)
470         return 1;
471     emtmp = OPENSSL_strdup((char *)email->data);
472     if (emtmp == NULL || !sk_OPENSSL_STRING_push(*sk, emtmp)) {
473         OPENSSL_free(emtmp);    /* free on push failure */
474         X509_email_free(*sk);
475         *sk = NULL;
476         return 0;
477     }
478     return 1;
479 }
480
481 void X509_email_free(STACK_OF(OPENSSL_STRING) *sk)
482 {
483     sk_OPENSSL_STRING_pop_free(sk, str_free);
484 }
485
486 typedef int (*equal_fn) (const unsigned char *pattern, size_t pattern_len,
487                          const unsigned char *subject, size_t subject_len,
488                          unsigned int flags);
489
490 /* Skip pattern prefix to match "wildcard" subject */
491 static void skip_prefix(const unsigned char **p, size_t *plen,
492                         size_t subject_len,
493                         unsigned int flags)
494 {
495     const unsigned char *pattern = *p;
496     size_t pattern_len = *plen;
497
498     /*
499      * If subject starts with a leading '.' followed by more octets, and
500      * pattern is longer, compare just an equal-length suffix with the
501      * full subject (starting at the '.'), provided the prefix contains
502      * no NULs.
503      */
504     if ((flags & _X509_CHECK_FLAG_DOT_SUBDOMAINS) == 0)
505         return;
506
507     while (pattern_len > subject_len && *pattern) {
508         if ((flags & X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS) &&
509             *pattern == '.')
510             break;
511         ++pattern;
512         --pattern_len;
513     }
514
515     /* Skip if entire prefix acceptable */
516     if (pattern_len == subject_len) {
517         *p = pattern;
518         *plen = pattern_len;
519     }
520 }
521
522 /* Compare while ASCII ignoring case. */
523 static int equal_nocase(const unsigned char *pattern, size_t pattern_len,
524                         const unsigned char *subject, size_t subject_len,
525                         unsigned int flags)
526 {
527     skip_prefix(&pattern, &pattern_len, subject_len, flags);
528     if (pattern_len != subject_len)
529         return 0;
530     while (pattern_len) {
531         unsigned char l = *pattern;
532         unsigned char r = *subject;
533         /* The pattern must not contain NUL characters. */
534         if (l == 0)
535             return 0;
536         if (l != r) {
537             if ('A' <= l && l <= 'Z')
538                 l = (l - 'A') + 'a';
539             if ('A' <= r && r <= 'Z')
540                 r = (r - 'A') + 'a';
541             if (l != r)
542                 return 0;
543         }
544         ++pattern;
545         ++subject;
546         --pattern_len;
547     }
548     return 1;
549 }
550
551 /* Compare using memcmp. */
552 static int equal_case(const unsigned char *pattern, size_t pattern_len,
553                       const unsigned char *subject, size_t subject_len,
554                       unsigned int flags)
555 {
556     skip_prefix(&pattern, &pattern_len, subject_len, flags);
557     if (pattern_len != subject_len)
558         return 0;
559     return !memcmp(pattern, subject, pattern_len);
560 }
561
562 /*
563  * RFC 5280, section 7.5, requires that only the domain is compared in a
564  * case-insensitive manner.
565  */
566 static int equal_email(const unsigned char *a, size_t a_len,
567                        const unsigned char *b, size_t b_len,
568                        unsigned int unused_flags)
569 {
570     size_t i = a_len;
571     if (a_len != b_len)
572         return 0;
573     /*
574      * We search backwards for the '@' character, so that we do not have to
575      * deal with quoted local-parts.  The domain part is compared in a
576      * case-insensitive manner.
577      */
578     while (i > 0) {
579         --i;
580         if (a[i] == '@' || b[i] == '@') {
581             if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0))
582                 return 0;
583             break;
584         }
585     }
586     if (i == 0)
587         i = a_len;
588     return equal_case(a, i, b, i, 0);
589 }
590
591 /*
592  * Compare the prefix and suffix with the subject, and check that the
593  * characters in-between are valid.
594  */
595 static int wildcard_match(const unsigned char *prefix, size_t prefix_len,
596                           const unsigned char *suffix, size_t suffix_len,
597                           const unsigned char *subject, size_t subject_len,
598                           unsigned int flags)
599 {
600     const unsigned char *wildcard_start;
601     const unsigned char *wildcard_end;
602     const unsigned char *p;
603     int allow_multi = 0;
604     int allow_idna = 0;
605
606     if (subject_len < prefix_len + suffix_len)
607         return 0;
608     if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags))
609         return 0;
610     wildcard_start = subject + prefix_len;
611     wildcard_end = subject + (subject_len - suffix_len);
612     if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags))
613         return 0;
614     /*
615      * If the wildcard makes up the entire first label, it must match at
616      * least one character.
617      */
618     if (prefix_len == 0 && *suffix == '.') {
619         if (wildcard_start == wildcard_end)
620             return 0;
621         allow_idna = 1;
622         if (flags & X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS)
623             allow_multi = 1;
624     }
625     /* IDNA labels cannot match partial wildcards */
626     if (!allow_idna &&
627         subject_len >= 4 && strncasecmp((char *)subject, "xn--", 4) == 0)
628         return 0;
629     /* The wildcard may match a literal '*' */
630     if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
631         return 1;
632     /*
633      * Check that the part matched by the wildcard contains only
634      * permitted characters and only matches a single label unless
635      * allow_multi is set.
636      */
637     for (p = wildcard_start; p != wildcard_end; ++p)
638         if (!(('0' <= *p && *p <= '9') ||
639               ('A' <= *p && *p <= 'Z') ||
640               ('a' <= *p && *p <= 'z') ||
641               *p == '-' || (allow_multi && *p == '.')))
642             return 0;
643     return 1;
644 }
645
646 #define LABEL_START     (1 << 0)
647 #define LABEL_END       (1 << 1)
648 #define LABEL_HYPHEN    (1 << 2)
649 #define LABEL_IDNA      (1 << 3)
650
651 static const unsigned char *valid_star(const unsigned char *p, size_t len,
652                                        unsigned int flags)
653 {
654     const unsigned char *star = 0;
655     size_t i;
656     int state = LABEL_START;
657     int dots = 0;
658     for (i = 0; i < len; ++i) {
659         /*
660          * Locate first and only legal wildcard, either at the start
661          * or end of a non-IDNA first and not final label.
662          */
663         if (p[i] == '*') {
664             int atstart = (state & LABEL_START);
665             int atend = (i == len - 1 || p[i + 1] == '.');
666             /*-
667              * At most one wildcard per pattern.
668              * No wildcards in IDNA labels.
669              * No wildcards after the first label.
670              */
671             if (star != NULL || (state & LABEL_IDNA) != 0 || dots)
672                 return NULL;
673             /* Only full-label '*.example.com' wildcards? */
674             if ((flags & X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS)
675                 && (!atstart || !atend))
676                 return NULL;
677             /* No 'foo*bar' wildcards */
678             if (!atstart && !atend)
679                 return NULL;
680             star = &p[i];
681             state &= ~LABEL_START;
682         } else if (('a' <= p[i] && p[i] <= 'z')
683                    || ('A' <= p[i] && p[i] <= 'Z')
684                    || ('0' <= p[i] && p[i] <= '9')) {
685             if ((state & LABEL_START) != 0
686                 && len - i >= 4 && strncasecmp((char *)&p[i], "xn--", 4) == 0)
687                 state |= LABEL_IDNA;
688             state &= ~(LABEL_HYPHEN | LABEL_START);
689         } else if (p[i] == '.') {
690             if ((state & (LABEL_HYPHEN | LABEL_START)) != 0)
691                 return NULL;
692             state = LABEL_START;
693             ++dots;
694         } else if (p[i] == '-') {
695             /* no domain/subdomain starts with '-' */
696             if ((state & LABEL_START) != 0)
697                 return NULL;
698             state |= LABEL_HYPHEN;
699         } else
700             return NULL;
701     }
702
703     /*
704      * The final label must not end in a hyphen or ".", and
705      * there must be at least two dots after the star.
706      */
707     if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2)
708         return NULL;
709     return star;
710 }
711
712 /* Compare using wildcards. */
713 static int equal_wildcard(const unsigned char *pattern, size_t pattern_len,
714                           const unsigned char *subject, size_t subject_len,
715                           unsigned int flags)
716 {
717     const unsigned char *star = NULL;
718
719     /*
720      * Subject names starting with '.' can only match a wildcard pattern
721      * via a subject sub-domain pattern suffix match.
722      */
723     if (!(subject_len > 1 && subject[0] == '.'))
724         star = valid_star(pattern, pattern_len, flags);
725     if (star == NULL)
726         return equal_nocase(pattern, pattern_len,
727                             subject, subject_len, flags);
728     return wildcard_match(pattern, star - pattern,
729                           star + 1, (pattern + pattern_len) - star - 1,
730                           subject, subject_len, flags);
731 }
732
733 /*
734  * Compare an ASN1_STRING to a supplied string. If they match return 1. If
735  * cmp_type > 0 only compare if string matches the type, otherwise convert it
736  * to UTF8.
737  */
738
739 static int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal,
740                            unsigned int flags, const char *b, size_t blen,
741                            char **peername)
742 {
743     int rv = 0;
744
745     if (!a->data || !a->length)
746         return 0;
747     if (cmp_type > 0) {
748         if (cmp_type != a->type)
749             return 0;
750         if (cmp_type == V_ASN1_IA5STRING)
751             rv = equal(a->data, a->length, (unsigned char *)b, blen, flags);
752         else if (a->length == (int)blen && !memcmp(a->data, b, blen))
753             rv = 1;
754         if (rv > 0 && peername)
755             *peername = OPENSSL_strndup((char *)a->data, a->length);
756     } else {
757         int astrlen;
758         unsigned char *astr;
759         astrlen = ASN1_STRING_to_UTF8(&astr, a);
760         if (astrlen < 0) {
761             /*
762              * -1 could be an internal malloc failure or a decoding error from
763              * malformed input; we can't distinguish.
764              */
765             return -1;
766         }
767         rv = equal(astr, astrlen, (unsigned char *)b, blen, flags);
768         if (rv > 0 && peername)
769             *peername = OPENSSL_strndup((char *)astr, astrlen);
770         OPENSSL_free(astr);
771     }
772     return rv;
773 }
774
775 static int do_x509_check(X509 *x, const char *chk, size_t chklen,
776                          unsigned int flags, int check_type, char **peername)
777 {
778     GENERAL_NAMES *gens = NULL;
779     X509_NAME *name = NULL;
780     int i;
781     int cnid = NID_undef;
782     int alt_type;
783     int san_present = 0;
784     int rv = 0;
785     equal_fn equal;
786
787     /* See below, this flag is internal-only */
788     flags &= ~_X509_CHECK_FLAG_DOT_SUBDOMAINS;
789     if (check_type == GEN_EMAIL) {
790         cnid = NID_pkcs9_emailAddress;
791         alt_type = V_ASN1_IA5STRING;
792         equal = equal_email;
793     } else if (check_type == GEN_DNS) {
794         cnid = NID_commonName;
795         /* Implicit client-side DNS sub-domain pattern */
796         if (chklen > 1 && chk[0] == '.')
797             flags |= _X509_CHECK_FLAG_DOT_SUBDOMAINS;
798         alt_type = V_ASN1_IA5STRING;
799         if (flags & X509_CHECK_FLAG_NO_WILDCARDS)
800             equal = equal_nocase;
801         else
802             equal = equal_wildcard;
803     } else {
804         alt_type = V_ASN1_OCTET_STRING;
805         equal = equal_case;
806     }
807
808     if (chklen == 0)
809         chklen = strlen(chk);
810
811     gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
812     if (gens) {
813         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
814             GENERAL_NAME *gen;
815             ASN1_STRING *cstr;
816             gen = sk_GENERAL_NAME_value(gens, i);
817             if (gen->type != check_type)
818                 continue;
819             san_present = 1;
820             if (check_type == GEN_EMAIL)
821                 cstr = gen->d.rfc822Name;
822             else if (check_type == GEN_DNS)
823                 cstr = gen->d.dNSName;
824             else
825                 cstr = gen->d.iPAddress;
826             /* Positive on success, negative on error! */
827             if ((rv = do_check_string(cstr, alt_type, equal, flags,
828                                       chk, chklen, peername)) != 0)
829                 break;
830         }
831         GENERAL_NAMES_free(gens);
832         if (rv != 0)
833             return rv;
834         if (san_present && !(flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT))
835             return 0;
836     }
837
838     /* We're done if CN-ID is not pertinent */
839     if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT))
840         return 0;
841
842     i = -1;
843     name = X509_get_subject_name(x);
844     while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) {
845         const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
846         const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne);
847
848         /* Positive on success, negative on error! */
849         if ((rv = do_check_string(str, -1, equal, flags,
850                                   chk, chklen, peername)) != 0)
851             return rv;
852     }
853     return 0;
854 }
855
856 int X509_check_host(X509 *x, const char *chk, size_t chklen,
857                     unsigned int flags, char **peername)
858 {
859     if (chk == NULL)
860         return -2;
861     /*
862      * Embedded NULs are disallowed, except as the last character of a
863      * string of length 2 or more (tolerate caller including terminating
864      * NUL in string length).
865      */
866     if (chklen == 0)
867         chklen = strlen(chk);
868     else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
869         return -2;
870     if (chklen > 1 && chk[chklen - 1] == '\0')
871         --chklen;
872     return do_x509_check(x, chk, chklen, flags, GEN_DNS, peername);
873 }
874
875 int X509_check_email(X509 *x, const char *chk, size_t chklen,
876                      unsigned int flags)
877 {
878     if (chk == NULL)
879         return -2;
880     /*
881      * Embedded NULs are disallowed, except as the last character of a
882      * string of length 2 or more (tolerate caller including terminating
883      * NUL in string length).
884      */
885     if (chklen == 0)
886         chklen = strlen((char *)chk);
887     else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
888         return -2;
889     if (chklen > 1 && chk[chklen - 1] == '\0')
890         --chklen;
891     return do_x509_check(x, chk, chklen, flags, GEN_EMAIL, NULL);
892 }
893
894 int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
895                   unsigned int flags)
896 {
897     if (chk == NULL)
898         return -2;
899     return do_x509_check(x, (char *)chk, chklen, flags, GEN_IPADD, NULL);
900 }
901
902 int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags)
903 {
904     unsigned char ipout[16];
905     size_t iplen;
906
907     if (ipasc == NULL)
908         return -2;
909     iplen = (size_t)a2i_ipadd(ipout, ipasc);
910     if (iplen == 0)
911         return -2;
912     return do_x509_check(x, (char *)ipout, iplen, flags, GEN_IPADD, NULL);
913 }
914
915 /*
916  * Convert IP addresses both IPv4 and IPv6 into an OCTET STRING compatible
917  * with RFC3280.
918  */
919
920 ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
921 {
922     unsigned char ipout[16];
923     ASN1_OCTET_STRING *ret;
924     int iplen;
925
926     /* If string contains a ':' assume IPv6 */
927
928     iplen = a2i_ipadd(ipout, ipasc);
929
930     if (!iplen)
931         return NULL;
932
933     ret = ASN1_OCTET_STRING_new();
934     if (ret == NULL)
935         return NULL;
936     if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) {
937         ASN1_OCTET_STRING_free(ret);
938         return NULL;
939     }
940     return ret;
941 }
942
943 ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
944 {
945     ASN1_OCTET_STRING *ret = NULL;
946     unsigned char ipout[32];
947     char *iptmp = NULL, *p;
948     int iplen1, iplen2;
949     p = strchr(ipasc, '/');
950     if (!p)
951         return NULL;
952     iptmp = OPENSSL_strdup(ipasc);
953     if (!iptmp)
954         return NULL;
955     p = iptmp + (p - ipasc);
956     *p++ = 0;
957
958     iplen1 = a2i_ipadd(ipout, iptmp);
959
960     if (!iplen1)
961         goto err;
962
963     iplen2 = a2i_ipadd(ipout + iplen1, p);
964
965     OPENSSL_free(iptmp);
966     iptmp = NULL;
967
968     if (!iplen2 || (iplen1 != iplen2))
969         goto err;
970
971     ret = ASN1_OCTET_STRING_new();
972     if (ret == NULL)
973         goto err;
974     if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
975         goto err;
976
977     return ret;
978
979  err:
980     OPENSSL_free(iptmp);
981     ASN1_OCTET_STRING_free(ret);
982     return NULL;
983 }
984
985 int a2i_ipadd(unsigned char *ipout, const char *ipasc)
986 {
987     /* If string contains a ':' assume IPv6 */
988
989     if (strchr(ipasc, ':')) {
990         if (!ipv6_from_asc(ipout, ipasc))
991             return 0;
992         return 16;
993     } else {
994         if (!ipv4_from_asc(ipout, ipasc))
995             return 0;
996         return 4;
997     }
998 }
999
1000 static int ipv4_from_asc(unsigned char *v4, const char *in)
1001 {
1002     int a0, a1, a2, a3;
1003     if (sscanf(in, "%d.%d.%d.%d", &a0, &a1, &a2, &a3) != 4)
1004         return 0;
1005     if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255)
1006         || (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255))
1007         return 0;
1008     v4[0] = a0;
1009     v4[1] = a1;
1010     v4[2] = a2;
1011     v4[3] = a3;
1012     return 1;
1013 }
1014
1015 typedef struct {
1016     /* Temporary store for IPV6 output */
1017     unsigned char tmp[16];
1018     /* Total number of bytes in tmp */
1019     int total;
1020     /* The position of a zero (corresponding to '::') */
1021     int zero_pos;
1022     /* Number of zeroes */
1023     int zero_cnt;
1024 } IPV6_STAT;
1025
1026 static int ipv6_from_asc(unsigned char *v6, const char *in)
1027 {
1028     IPV6_STAT v6stat;
1029     v6stat.total = 0;
1030     v6stat.zero_pos = -1;
1031     v6stat.zero_cnt = 0;
1032     /*
1033      * Treat the IPv6 representation as a list of values separated by ':'.
1034      * The presence of a '::' will parse as one, two or three zero length
1035      * elements.
1036      */
1037     if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
1038         return 0;
1039
1040     /* Now for some sanity checks */
1041
1042     if (v6stat.zero_pos == -1) {
1043         /* If no '::' must have exactly 16 bytes */
1044         if (v6stat.total != 16)
1045             return 0;
1046     } else {
1047         /* If '::' must have less than 16 bytes */
1048         if (v6stat.total == 16)
1049             return 0;
1050         /* More than three zeroes is an error */
1051         if (v6stat.zero_cnt > 3)
1052             return 0;
1053         /* Can only have three zeroes if nothing else present */
1054         else if (v6stat.zero_cnt == 3) {
1055             if (v6stat.total > 0)
1056                 return 0;
1057         }
1058         /* Can only have two zeroes if at start or end */
1059         else if (v6stat.zero_cnt == 2) {
1060             if ((v6stat.zero_pos != 0)
1061                 && (v6stat.zero_pos != v6stat.total))
1062                 return 0;
1063         } else
1064             /* Can only have one zero if *not* start or end */
1065         {
1066             if ((v6stat.zero_pos == 0)
1067                 || (v6stat.zero_pos == v6stat.total))
1068                 return 0;
1069         }
1070     }
1071
1072     /* Format result */
1073
1074     if (v6stat.zero_pos >= 0) {
1075         /* Copy initial part */
1076         memcpy(v6, v6stat.tmp, v6stat.zero_pos);
1077         /* Zero middle */
1078         memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
1079         /* Copy final part */
1080         if (v6stat.total != v6stat.zero_pos)
1081             memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
1082                    v6stat.tmp + v6stat.zero_pos,
1083                    v6stat.total - v6stat.zero_pos);
1084     } else
1085         memcpy(v6, v6stat.tmp, 16);
1086
1087     return 1;
1088 }
1089
1090 static int ipv6_cb(const char *elem, int len, void *usr)
1091 {
1092     IPV6_STAT *s = usr;
1093     /* Error if 16 bytes written */
1094     if (s->total == 16)
1095         return 0;
1096     if (len == 0) {
1097         /* Zero length element, corresponds to '::' */
1098         if (s->zero_pos == -1)
1099             s->zero_pos = s->total;
1100         /* If we've already got a :: its an error */
1101         else if (s->zero_pos != s->total)
1102             return 0;
1103         s->zero_cnt++;
1104     } else {
1105         /* If more than 4 characters could be final a.b.c.d form */
1106         if (len > 4) {
1107             /* Need at least 4 bytes left */
1108             if (s->total > 12)
1109                 return 0;
1110             /* Must be end of string */
1111             if (elem[len])
1112                 return 0;
1113             if (!ipv4_from_asc(s->tmp + s->total, elem))
1114                 return 0;
1115             s->total += 4;
1116         } else {
1117             if (!ipv6_hex(s->tmp + s->total, elem, len))
1118                 return 0;
1119             s->total += 2;
1120         }
1121     }
1122     return 1;
1123 }
1124
1125 /*
1126  * Convert a string of up to 4 hex digits into the corresponding IPv6 form.
1127  */
1128
1129 static int ipv6_hex(unsigned char *out, const char *in, int inlen)
1130 {
1131     unsigned char c;
1132     unsigned int num = 0;
1133     int x;
1134
1135     if (inlen > 4)
1136         return 0;
1137     while (inlen--) {
1138         c = *in++;
1139         num <<= 4;
1140         x = OPENSSL_hexchar2int(c);
1141         if (x < 0)
1142             return 0;
1143         num |= (char)x;
1144     }
1145     out[0] = num >> 8;
1146     out[1] = num & 0xff;
1147     return 1;
1148 }
1149
1150 int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
1151                              unsigned long chtype)
1152 {
1153     CONF_VALUE *v;
1154     int i, mval, spec_char, plus_char;
1155     char *p, *type;
1156     if (!nm)
1157         return 0;
1158
1159     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1160         v = sk_CONF_VALUE_value(dn_sk, i);
1161         type = v->name;
1162         /*
1163          * Skip past any leading X. X: X, etc to allow for multiple instances
1164          */
1165         for (p = type; *p; p++) {
1166 #ifndef CHARSET_EBCDIC
1167             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1168 #else
1169             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1170                     || (*p == os_toascii['.']));
1171 #endif
1172             if (spec_char) {
1173                 p++;
1174                 if (*p)
1175                     type = p;
1176                 break;
1177             }
1178         }
1179 #ifndef CHARSET_EBCDIC
1180         plus_char = (*type == '+');
1181 #else
1182         plus_char = (*type == os_toascii['+']);
1183 #endif
1184         if (plus_char) {
1185             mval = -1;
1186             type++;
1187         } else
1188             mval = 0;
1189         if (!X509_NAME_add_entry_by_txt(nm, type, chtype,
1190                                         (unsigned char *)v->value, -1, -1,
1191                                         mval))
1192             return 0;
1193
1194     }
1195     return 1;
1196 }