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