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