Add missing NULL check in X509V3_parse_list()
[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     if (linebuf == NULL) {
290         X509V3err(X509V3_F_X509V3_PARSE_LIST, ERR_R_MALLOC_FAILURE);
291         goto err;
292     }
293     state = HDR_NAME;
294     ntmp = NULL;
295     /* Go through all characters */
296     for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
297          p++) {
298
299         switch (state) {
300         case HDR_NAME:
301             if (c == ':') {
302                 state = HDR_VALUE;
303                 *p = 0;
304                 ntmp = strip_spaces(q);
305                 if (!ntmp) {
306                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
307                               X509V3_R_INVALID_NULL_NAME);
308                     goto err;
309                 }
310                 q = p + 1;
311             } else if (c == ',') {
312                 *p = 0;
313                 ntmp = strip_spaces(q);
314                 q = p + 1;
315                 if (!ntmp) {
316                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
317                               X509V3_R_INVALID_NULL_NAME);
318                     goto err;
319                 }
320                 X509V3_add_value(ntmp, NULL, &values);
321             }
322             break;
323
324         case HDR_VALUE:
325             if (c == ',') {
326                 state = HDR_NAME;
327                 *p = 0;
328                 vtmp = strip_spaces(q);
329                 if (!vtmp) {
330                     X509V3err(X509V3_F_X509V3_PARSE_LIST,
331                               X509V3_R_INVALID_NULL_VALUE);
332                     goto err;
333                 }
334                 X509V3_add_value(ntmp, vtmp, &values);
335                 ntmp = NULL;
336                 q = p + 1;
337             }
338
339         }
340     }
341
342     if (state == HDR_VALUE) {
343         vtmp = strip_spaces(q);
344         if (!vtmp) {
345             X509V3err(X509V3_F_X509V3_PARSE_LIST,
346                       X509V3_R_INVALID_NULL_VALUE);
347             goto err;
348         }
349         X509V3_add_value(ntmp, vtmp, &values);
350     } else {
351         ntmp = strip_spaces(q);
352         if (!ntmp) {
353             X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME);
354             goto err;
355         }
356         X509V3_add_value(ntmp, NULL, &values);
357     }
358     OPENSSL_free(linebuf);
359     return values;
360
361  err:
362     OPENSSL_free(linebuf);
363     sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
364     return NULL;
365
366 }
367
368 /* Delete leading and trailing spaces from a string */
369 static char *strip_spaces(char *name)
370 {
371     char *p, *q;
372     /* Skip over leading spaces */
373     p = name;
374     while (*p && isspace((unsigned char)*p))
375         p++;
376     if (!*p)
377         return NULL;
378     q = p + strlen(p) - 1;
379     while ((q != p) && isspace((unsigned char)*q))
380         q--;
381     if (p != q)
382         q[1] = 0;
383     if (!*p)
384         return NULL;
385     return p;
386 }
387
388 /* hex string utilities */
389
390 /*
391  * Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its
392  * hex representation @@@ (Contents of buffer are always kept in ASCII, also
393  * on EBCDIC machines)
394  */
395
396 char *hex_to_string(const unsigned char *buffer, long len)
397 {
398     char *tmp, *q;
399     const unsigned char *p;
400     int i;
401     const static char hexdig[] = "0123456789ABCDEF";
402     if (!buffer || !len)
403         return NULL;
404     if (!(tmp = OPENSSL_malloc(len * 3 + 1))) {
405         X509V3err(X509V3_F_HEX_TO_STRING, ERR_R_MALLOC_FAILURE);
406         return NULL;
407     }
408     q = tmp;
409     for (i = 0, p = buffer; i < len; i++, p++) {
410         *q++ = hexdig[(*p >> 4) & 0xf];
411         *q++ = hexdig[*p & 0xf];
412         *q++ = ':';
413     }
414     q[-1] = 0;
415 #ifdef CHARSET_EBCDIC
416     ebcdic2ascii(tmp, tmp, q - tmp - 1);
417 #endif
418
419     return tmp;
420 }
421
422 /*
423  * Give a string of hex digits convert to a buffer
424  */
425
426 unsigned char *string_to_hex(const char *str, long *len)
427 {
428     unsigned char *hexbuf, *q;
429     unsigned char ch, cl, *p;
430     if (!str) {
431         X509V3err(X509V3_F_STRING_TO_HEX, X509V3_R_INVALID_NULL_ARGUMENT);
432         return NULL;
433     }
434     if (!(hexbuf = OPENSSL_malloc(strlen(str) >> 1)))
435         goto err;
436     for (p = (unsigned char *)str, q = hexbuf; *p;) {
437         ch = *p++;
438 #ifdef CHARSET_EBCDIC
439         ch = os_toebcdic[ch];
440 #endif
441         if (ch == ':')
442             continue;
443         cl = *p++;
444 #ifdef CHARSET_EBCDIC
445         cl = os_toebcdic[cl];
446 #endif
447         if (!cl) {
448             X509V3err(X509V3_F_STRING_TO_HEX, X509V3_R_ODD_NUMBER_OF_DIGITS);
449             OPENSSL_free(hexbuf);
450             return NULL;
451         }
452         if (isupper(ch))
453             ch = tolower(ch);
454         if (isupper(cl))
455             cl = tolower(cl);
456
457         if ((ch >= '0') && (ch <= '9'))
458             ch -= '0';
459         else if ((ch >= 'a') && (ch <= 'f'))
460             ch -= 'a' - 10;
461         else
462             goto badhex;
463
464         if ((cl >= '0') && (cl <= '9'))
465             cl -= '0';
466         else if ((cl >= 'a') && (cl <= 'f'))
467             cl -= 'a' - 10;
468         else
469             goto badhex;
470
471         *q++ = (ch << 4) | cl;
472     }
473
474     if (len)
475         *len = q - hexbuf;
476
477     return hexbuf;
478
479  err:
480     OPENSSL_free(hexbuf);
481     X509V3err(X509V3_F_STRING_TO_HEX, ERR_R_MALLOC_FAILURE);
482     return NULL;
483
484  badhex:
485     OPENSSL_free(hexbuf);
486     X509V3err(X509V3_F_STRING_TO_HEX, X509V3_R_ILLEGAL_HEX_DIGIT);
487     return NULL;
488
489 }
490
491 /*
492  * V2I name comparison function: returns zero if 'name' matches cmp or cmp.*
493  */
494
495 int name_cmp(const char *name, const char *cmp)
496 {
497     int len, ret;
498     char c;
499     len = strlen(cmp);
500     if ((ret = strncmp(name, cmp, len)))
501         return ret;
502     c = name[len];
503     if (!c || (c == '.'))
504         return 0;
505     return 1;
506 }
507
508 static int sk_strcmp(const char *const *a, const char *const *b)
509 {
510     return strcmp(*a, *b);
511 }
512
513 STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x)
514 {
515     GENERAL_NAMES *gens;
516     STACK_OF(OPENSSL_STRING) *ret;
517
518     gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
519     ret = get_email(X509_get_subject_name(x), gens);
520     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
521     return ret;
522 }
523
524 STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x)
525 {
526     AUTHORITY_INFO_ACCESS *info;
527     STACK_OF(OPENSSL_STRING) *ret = NULL;
528     int i;
529
530     info = X509_get_ext_d2i(x, NID_info_access, NULL, NULL);
531     if (!info)
532         return NULL;
533     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
534         ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
535         if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
536             if (ad->location->type == GEN_URI) {
537                 if (!append_ia5
538                     (&ret, ad->location->d.uniformResourceIdentifier))
539                     break;
540             }
541         }
542     }
543     AUTHORITY_INFO_ACCESS_free(info);
544     return ret;
545 }
546
547 STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x)
548 {
549     GENERAL_NAMES *gens;
550     STACK_OF(X509_EXTENSION) *exts;
551     STACK_OF(OPENSSL_STRING) *ret;
552
553     exts = X509_REQ_get_extensions(x);
554     gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
555     ret = get_email(X509_REQ_get_subject_name(x), gens);
556     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
557     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
558     return ret;
559 }
560
561 static STACK_OF(OPENSSL_STRING) *get_email(X509_NAME *name,
562                                            GENERAL_NAMES *gens)
563 {
564     STACK_OF(OPENSSL_STRING) *ret = NULL;
565     X509_NAME_ENTRY *ne;
566     ASN1_IA5STRING *email;
567     GENERAL_NAME *gen;
568     int i;
569     /* Now add any email address(es) to STACK */
570     i = -1;
571     /* First supplied X509_NAME */
572     while ((i = X509_NAME_get_index_by_NID(name,
573                                            NID_pkcs9_emailAddress, i)) >= 0) {
574         ne = X509_NAME_get_entry(name, i);
575         email = X509_NAME_ENTRY_get_data(ne);
576         if (!append_ia5(&ret, email))
577             return NULL;
578     }
579     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
580         gen = sk_GENERAL_NAME_value(gens, i);
581         if (gen->type != GEN_EMAIL)
582             continue;
583         if (!append_ia5(&ret, gen->d.ia5))
584             return NULL;
585     }
586     return ret;
587 }
588
589 static void str_free(OPENSSL_STRING str)
590 {
591     OPENSSL_free(str);
592 }
593
594 static int append_ia5(STACK_OF(OPENSSL_STRING) **sk, ASN1_IA5STRING *email)
595 {
596     char *emtmp;
597     /* First some sanity checks */
598     if (email->type != V_ASN1_IA5STRING)
599         return 1;
600     if (!email->data || !email->length)
601         return 1;
602     if (!*sk)
603         *sk = sk_OPENSSL_STRING_new(sk_strcmp);
604     if (!*sk)
605         return 0;
606     /* Don't add duplicates */
607     if (sk_OPENSSL_STRING_find(*sk, (char *)email->data) != -1)
608         return 1;
609     emtmp = BUF_strdup((char *)email->data);
610     if (!emtmp || !sk_OPENSSL_STRING_push(*sk, emtmp)) {
611         X509_email_free(*sk);
612         *sk = NULL;
613         return 0;
614     }
615     return 1;
616 }
617
618 void X509_email_free(STACK_OF(OPENSSL_STRING) *sk)
619 {
620     sk_OPENSSL_STRING_pop_free(sk, str_free);
621 }
622
623 typedef int (*equal_fn) (const unsigned char *pattern, size_t pattern_len,
624                          const unsigned char *subject, size_t subject_len,
625                          unsigned int flags);
626
627 /* Skip pattern prefix to match "wildcard" subject */
628 static void skip_prefix(const unsigned char **p, size_t *plen,
629                         const unsigned char *subject, size_t subject_len,
630                         unsigned int flags)
631 {
632     const unsigned char *pattern = *p;
633     size_t pattern_len = *plen;
634
635     /*
636      * If subject starts with a leading '.' followed by more octets, and
637      * pattern is longer, compare just an equal-length suffix with the
638      * full subject (starting at the '.'), provided the prefix contains
639      * no NULs.
640      */
641     if ((flags & _X509_CHECK_FLAG_DOT_SUBDOMAINS) == 0)
642         return;
643
644     while (pattern_len > subject_len && *pattern) {
645         if ((flags & X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS) &&
646             *pattern == '.')
647             break;
648         ++pattern;
649         --pattern_len;
650     }
651
652     /* Skip if entire prefix acceptable */
653     if (pattern_len == subject_len) {
654         *p = pattern;
655         *plen = pattern_len;
656     }
657 }
658
659 /* Compare while ASCII ignoring case. */
660 static int equal_nocase(const unsigned char *pattern, size_t pattern_len,
661                         const unsigned char *subject, size_t subject_len,
662                         unsigned int flags)
663 {
664     skip_prefix(&pattern, &pattern_len, subject, subject_len, flags);
665     if (pattern_len != subject_len)
666         return 0;
667     while (pattern_len) {
668         unsigned char l = *pattern;
669         unsigned char r = *subject;
670         /* The pattern must not contain NUL characters. */
671         if (l == 0)
672             return 0;
673         if (l != r) {
674             if ('A' <= l && l <= 'Z')
675                 l = (l - 'A') + 'a';
676             if ('A' <= r && r <= 'Z')
677                 r = (r - 'A') + 'a';
678             if (l != r)
679                 return 0;
680         }
681         ++pattern;
682         ++subject;
683         --pattern_len;
684     }
685     return 1;
686 }
687
688 /* Compare using memcmp. */
689 static int equal_case(const unsigned char *pattern, size_t pattern_len,
690                       const unsigned char *subject, size_t subject_len,
691                       unsigned int flags)
692 {
693     skip_prefix(&pattern, &pattern_len, subject, subject_len, flags);
694     if (pattern_len != subject_len)
695         return 0;
696     return !memcmp(pattern, subject, pattern_len);
697 }
698
699 /*
700  * RFC 5280, section 7.5, requires that only the domain is compared in a
701  * case-insensitive manner.
702  */
703 static int equal_email(const unsigned char *a, size_t a_len,
704                        const unsigned char *b, size_t b_len,
705                        unsigned int unused_flags)
706 {
707     size_t i = a_len;
708     if (a_len != b_len)
709         return 0;
710     /*
711      * We search backwards for the '@' character, so that we do not have to
712      * deal with quoted local-parts.  The domain part is compared in a
713      * case-insensitive manner.
714      */
715     while (i > 0) {
716         --i;
717         if (a[i] == '@' || b[i] == '@') {
718             if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0))
719                 return 0;
720             break;
721         }
722     }
723     if (i == 0)
724         i = a_len;
725     return equal_case(a, i, b, i, 0);
726 }
727
728 /*
729  * Compare the prefix and suffix with the subject, and check that the
730  * characters in-between are valid.
731  */
732 static int wildcard_match(const unsigned char *prefix, size_t prefix_len,
733                           const unsigned char *suffix, size_t suffix_len,
734                           const unsigned char *subject, size_t subject_len,
735                           unsigned int flags)
736 {
737     const unsigned char *wildcard_start;
738     const unsigned char *wildcard_end;
739     const unsigned char *p;
740     int allow_multi = 0;
741     int allow_idna = 0;
742
743     if (subject_len < prefix_len + suffix_len)
744         return 0;
745     if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags))
746         return 0;
747     wildcard_start = subject + prefix_len;
748     wildcard_end = subject + (subject_len - suffix_len);
749     if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags))
750         return 0;
751     /*
752      * If the wildcard makes up the entire first label, it must match at
753      * least one character.
754      */
755     if (prefix_len == 0 && *suffix == '.') {
756         if (wildcard_start == wildcard_end)
757             return 0;
758         allow_idna = 1;
759         if (flags & X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS)
760             allow_multi = 1;
761     }
762     /* IDNA labels cannot match partial wildcards */
763     if (!allow_idna &&
764         subject_len >= 4 && strncasecmp((char *)subject, "xn--", 4) == 0)
765         return 0;
766     /* The wildcard may match a literal '*' */
767     if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
768         return 1;
769     /*
770      * Check that the part matched by the wildcard contains only
771      * permitted characters and only matches a single label unless
772      * allow_multi is set.
773      */
774     for (p = wildcard_start; p != wildcard_end; ++p)
775         if (!(('0' <= *p && *p <= '9') ||
776               ('A' <= *p && *p <= 'Z') ||
777               ('a' <= *p && *p <= 'z') ||
778               *p == '-' || (allow_multi && *p == '.')))
779             return 0;
780     return 1;
781 }
782
783 #define LABEL_START     (1 << 0)
784 #define LABEL_END       (1 << 1)
785 #define LABEL_HYPHEN    (1 << 2)
786 #define LABEL_IDNA      (1 << 3)
787
788 static const unsigned char *valid_star(const unsigned char *p, size_t len,
789                                        unsigned int flags)
790 {
791     const unsigned char *star = 0;
792     size_t i;
793     int state = LABEL_START;
794     int dots = 0;
795     for (i = 0; i < len; ++i) {
796         /*
797          * Locate first and only legal wildcard, either at the start
798          * or end of a non-IDNA first and not final label.
799          */
800         if (p[i] == '*') {
801             int atstart = (state & LABEL_START);
802             int atend = (i == len - 1 || p[i + 1] == '.');
803             /*-
804              * At most one wildcard per pattern.
805              * No wildcards in IDNA labels.
806              * No wildcards after the first label.
807              */
808             if (star != NULL || (state & LABEL_IDNA) != 0 || dots)
809                 return NULL;
810             /* Only full-label '*.example.com' wildcards? */
811             if ((flags & X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS)
812                 && (!atstart || !atend))
813                 return NULL;
814             /* No 'foo*bar' wildcards */
815             if (!atstart && !atend)
816                 return NULL;
817             star = &p[i];
818             state &= ~LABEL_START;
819         } else if (('a' <= p[i] && p[i] <= 'z')
820                    || ('A' <= p[i] && p[i] <= 'Z')
821                    || ('0' <= p[i] && p[i] <= '9')) {
822             if ((state & LABEL_START) != 0
823                 && len - i >= 4 && strncasecmp((char *)&p[i], "xn--", 4) == 0)
824                 state |= LABEL_IDNA;
825             state &= ~(LABEL_HYPHEN | LABEL_START);
826         } else if (p[i] == '.') {
827             if ((state & (LABEL_HYPHEN | LABEL_START)) != 0)
828                 return NULL;
829             state = LABEL_START;
830             ++dots;
831         } else if (p[i] == '-') {
832             if ((state & LABEL_HYPHEN) != 0)
833                 return NULL;
834             state |= LABEL_HYPHEN;
835         } else
836             return NULL;
837     }
838
839     /*
840      * The final label must not end in a hyphen or ".", and
841      * there must be at least two dots after the star.
842      */
843     if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2)
844         return NULL;
845     return star;
846 }
847
848 /* Compare using wildcards. */
849 static int equal_wildcard(const unsigned char *pattern, size_t pattern_len,
850                           const unsigned char *subject, size_t subject_len,
851                           unsigned int flags)
852 {
853     const unsigned char *star = NULL;
854
855     /*
856      * Subject names starting with '.' can only match a wildcard pattern
857      * via a subject sub-domain pattern suffix match.
858      */
859     if (!(subject_len > 1 && subject[0] == '.'))
860         star = valid_star(pattern, pattern_len, flags);
861     if (star == NULL)
862         return equal_nocase(pattern, pattern_len,
863                             subject, subject_len, flags);
864     return wildcard_match(pattern, star - pattern,
865                           star + 1, (pattern + pattern_len) - star - 1,
866                           subject, subject_len, flags);
867 }
868
869 /*
870  * Compare an ASN1_STRING to a supplied string. If they match return 1. If
871  * cmp_type > 0 only compare if string matches the type, otherwise convert it
872  * to UTF8.
873  */
874
875 static int do_check_string(ASN1_STRING *a, int cmp_type, equal_fn equal,
876                            unsigned int flags, const char *b, size_t blen,
877                            char **peername)
878 {
879     int rv = 0;
880
881     if (!a->data || !a->length)
882         return 0;
883     if (cmp_type > 0) {
884         if (cmp_type != a->type)
885             return 0;
886         if (cmp_type == V_ASN1_IA5STRING)
887             rv = equal(a->data, a->length, (unsigned char *)b, blen, flags);
888         else if (a->length == (int)blen && !memcmp(a->data, b, blen))
889             rv = 1;
890         if (rv > 0 && peername)
891             *peername = BUF_strndup((char *)a->data, a->length);
892     } else {
893         int astrlen;
894         unsigned char *astr;
895         astrlen = ASN1_STRING_to_UTF8(&astr, a);
896         if (astrlen < 0) {
897             /*
898              * -1 could be an internal malloc failure or a decoding error from
899              * malformed input; we can't distinguish.
900              */
901             return -1;
902         }
903         rv = equal(astr, astrlen, (unsigned char *)b, blen, flags);
904         if (rv > 0 && peername)
905             *peername = BUF_strndup((char *)astr, astrlen);
906         OPENSSL_free(astr);
907     }
908     return rv;
909 }
910
911 static int do_x509_check(X509 *x, const char *chk, size_t chklen,
912                          unsigned int flags, int check_type, char **peername)
913 {
914     GENERAL_NAMES *gens = NULL;
915     X509_NAME *name = NULL;
916     int i;
917     int cnid;
918     int alt_type;
919     int san_present = 0;
920     int rv = 0;
921     equal_fn equal;
922
923     /* See below, this flag is internal-only */
924     flags &= ~_X509_CHECK_FLAG_DOT_SUBDOMAINS;
925     if (check_type == GEN_EMAIL) {
926         cnid = NID_pkcs9_emailAddress;
927         alt_type = V_ASN1_IA5STRING;
928         equal = equal_email;
929     } else if (check_type == GEN_DNS) {
930         cnid = NID_commonName;
931         /* Implicit client-side DNS sub-domain pattern */
932         if (chklen > 1 && chk[0] == '.')
933             flags |= _X509_CHECK_FLAG_DOT_SUBDOMAINS;
934         alt_type = V_ASN1_IA5STRING;
935         if (flags & X509_CHECK_FLAG_NO_WILDCARDS)
936             equal = equal_nocase;
937         else
938             equal = equal_wildcard;
939     } else {
940         cnid = 0;
941         alt_type = V_ASN1_OCTET_STRING;
942         equal = equal_case;
943     }
944
945     if (chklen == 0)
946         chklen = strlen(chk);
947
948     gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
949     if (gens) {
950         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
951             GENERAL_NAME *gen;
952             ASN1_STRING *cstr;
953             gen = sk_GENERAL_NAME_value(gens, i);
954             if (gen->type != check_type)
955                 continue;
956             san_present = 1;
957             if (check_type == GEN_EMAIL)
958                 cstr = gen->d.rfc822Name;
959             else if (check_type == GEN_DNS)
960                 cstr = gen->d.dNSName;
961             else
962                 cstr = gen->d.iPAddress;
963             /* Positive on success, negative on error! */
964             if ((rv = do_check_string(cstr, alt_type, equal, flags,
965                                       chk, chklen, peername)) != 0)
966                 break;
967         }
968         GENERAL_NAMES_free(gens);
969         if (rv != 0)
970             return rv;
971         if (!cnid
972             || (san_present
973                 && !(flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT)))
974             return 0;
975     }
976     i = -1;
977     name = X509_get_subject_name(x);
978     while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) {
979         X509_NAME_ENTRY *ne;
980         ASN1_STRING *str;
981         ne = X509_NAME_get_entry(name, i);
982         str = X509_NAME_ENTRY_get_data(ne);
983         /* Positive on success, negative on error! */
984         if ((rv = do_check_string(str, -1, equal, flags,
985                                   chk, chklen, peername)) != 0)
986             return rv;
987     }
988     return 0;
989 }
990
991 int X509_check_host(X509 *x, const char *chk, size_t chklen,
992                     unsigned int flags, char **peername)
993 {
994     if (chk == NULL)
995         return -2;
996     /*
997      * Embedded NULs are disallowed, except as the last character of a
998      * string of length 2 or more (tolerate caller including terminating
999      * NUL in string length).
1000      */
1001     if (chklen == 0)
1002         chklen = strlen(chk);
1003     else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
1004         return -2;
1005     if (chklen > 1 && chk[chklen - 1] == '\0')
1006         --chklen;
1007     return do_x509_check(x, chk, chklen, flags, GEN_DNS, peername);
1008 }
1009
1010 int X509_check_email(X509 *x, const char *chk, size_t chklen,
1011                      unsigned int flags)
1012 {
1013     if (chk == NULL)
1014         return -2;
1015     /*
1016      * Embedded NULs are disallowed, except as the last character of a
1017      * string of length 2 or more (tolerate caller including terminating
1018      * NUL in string length).
1019      */
1020     if (chklen == 0)
1021         chklen = strlen((char *)chk);
1022     else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
1023         return -2;
1024     if (chklen > 1 && chk[chklen - 1] == '\0')
1025         --chklen;
1026     return do_x509_check(x, chk, chklen, flags, GEN_EMAIL, NULL);
1027 }
1028
1029 int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
1030                   unsigned int flags)
1031 {
1032     if (chk == NULL)
1033         return -2;
1034     return do_x509_check(x, (char *)chk, chklen, flags, GEN_IPADD, NULL);
1035 }
1036
1037 int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags)
1038 {
1039     unsigned char ipout[16];
1040     size_t iplen;
1041
1042     if (ipasc == NULL)
1043         return -2;
1044     iplen = (size_t)a2i_ipadd(ipout, ipasc);
1045     if (iplen == 0)
1046         return -2;
1047     return do_x509_check(x, (char *)ipout, iplen, flags, GEN_IPADD, NULL);
1048 }
1049
1050 /*
1051  * Convert IP addresses both IPv4 and IPv6 into an OCTET STRING compatible
1052  * with RFC3280.
1053  */
1054
1055 ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
1056 {
1057     unsigned char ipout[16];
1058     ASN1_OCTET_STRING *ret;
1059     int iplen;
1060
1061     /* If string contains a ':' assume IPv6 */
1062
1063     iplen = a2i_ipadd(ipout, ipasc);
1064
1065     if (!iplen)
1066         return NULL;
1067
1068     ret = ASN1_OCTET_STRING_new();
1069     if (!ret)
1070         return NULL;
1071     if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) {
1072         ASN1_OCTET_STRING_free(ret);
1073         return NULL;
1074     }
1075     return ret;
1076 }
1077
1078 ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
1079 {
1080     ASN1_OCTET_STRING *ret = NULL;
1081     unsigned char ipout[32];
1082     char *iptmp = NULL, *p;
1083     int iplen1, iplen2;
1084     p = strchr(ipasc, '/');
1085     if (!p)
1086         return NULL;
1087     iptmp = BUF_strdup(ipasc);
1088     if (!iptmp)
1089         return NULL;
1090     p = iptmp + (p - ipasc);
1091     *p++ = 0;
1092
1093     iplen1 = a2i_ipadd(ipout, iptmp);
1094
1095     if (!iplen1)
1096         goto err;
1097
1098     iplen2 = a2i_ipadd(ipout + iplen1, p);
1099
1100     OPENSSL_free(iptmp);
1101     iptmp = NULL;
1102
1103     if (!iplen2 || (iplen1 != iplen2))
1104         goto err;
1105
1106     ret = ASN1_OCTET_STRING_new();
1107     if (!ret)
1108         goto err;
1109     if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
1110         goto err;
1111
1112     return ret;
1113
1114  err:
1115     OPENSSL_free(iptmp);
1116     ASN1_OCTET_STRING_free(ret);
1117     return NULL;
1118 }
1119
1120 int a2i_ipadd(unsigned char *ipout, const char *ipasc)
1121 {
1122     /* If string contains a ':' assume IPv6 */
1123
1124     if (strchr(ipasc, ':')) {
1125         if (!ipv6_from_asc(ipout, ipasc))
1126             return 0;
1127         return 16;
1128     } else {
1129         if (!ipv4_from_asc(ipout, ipasc))
1130             return 0;
1131         return 4;
1132     }
1133 }
1134
1135 static int ipv4_from_asc(unsigned char *v4, const char *in)
1136 {
1137     int a0, a1, a2, a3;
1138     if (sscanf(in, "%d.%d.%d.%d", &a0, &a1, &a2, &a3) != 4)
1139         return 0;
1140     if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255)
1141         || (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255))
1142         return 0;
1143     v4[0] = a0;
1144     v4[1] = a1;
1145     v4[2] = a2;
1146     v4[3] = a3;
1147     return 1;
1148 }
1149
1150 typedef struct {
1151     /* Temporary store for IPV6 output */
1152     unsigned char tmp[16];
1153     /* Total number of bytes in tmp */
1154     int total;
1155     /* The position of a zero (corresponding to '::') */
1156     int zero_pos;
1157     /* Number of zeroes */
1158     int zero_cnt;
1159 } IPV6_STAT;
1160
1161 static int ipv6_from_asc(unsigned char *v6, const char *in)
1162 {
1163     IPV6_STAT v6stat;
1164     v6stat.total = 0;
1165     v6stat.zero_pos = -1;
1166     v6stat.zero_cnt = 0;
1167     /*
1168      * Treat the IPv6 representation as a list of values separated by ':'.
1169      * The presence of a '::' will parse as one, two or three zero length
1170      * elements.
1171      */
1172     if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
1173         return 0;
1174
1175     /* Now for some sanity checks */
1176
1177     if (v6stat.zero_pos == -1) {
1178         /* If no '::' must have exactly 16 bytes */
1179         if (v6stat.total != 16)
1180             return 0;
1181     } else {
1182         /* If '::' must have less than 16 bytes */
1183         if (v6stat.total == 16)
1184             return 0;
1185         /* More than three zeroes is an error */
1186         if (v6stat.zero_cnt > 3)
1187             return 0;
1188         /* Can only have three zeroes if nothing else present */
1189         else if (v6stat.zero_cnt == 3) {
1190             if (v6stat.total > 0)
1191                 return 0;
1192         }
1193         /* Can only have two zeroes if at start or end */
1194         else if (v6stat.zero_cnt == 2) {
1195             if ((v6stat.zero_pos != 0)
1196                 && (v6stat.zero_pos != v6stat.total))
1197                 return 0;
1198         } else
1199             /* Can only have one zero if *not* start or end */
1200         {
1201             if ((v6stat.zero_pos == 0)
1202                 || (v6stat.zero_pos == v6stat.total))
1203                 return 0;
1204         }
1205     }
1206
1207     /* Format result */
1208
1209     if (v6stat.zero_pos >= 0) {
1210         /* Copy initial part */
1211         memcpy(v6, v6stat.tmp, v6stat.zero_pos);
1212         /* Zero middle */
1213         memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
1214         /* Copy final part */
1215         if (v6stat.total != v6stat.zero_pos)
1216             memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
1217                    v6stat.tmp + v6stat.zero_pos,
1218                    v6stat.total - v6stat.zero_pos);
1219     } else
1220         memcpy(v6, v6stat.tmp, 16);
1221
1222     return 1;
1223 }
1224
1225 static int ipv6_cb(const char *elem, int len, void *usr)
1226 {
1227     IPV6_STAT *s = usr;
1228     /* Error if 16 bytes written */
1229     if (s->total == 16)
1230         return 0;
1231     if (len == 0) {
1232         /* Zero length element, corresponds to '::' */
1233         if (s->zero_pos == -1)
1234             s->zero_pos = s->total;
1235         /* If we've already got a :: its an error */
1236         else if (s->zero_pos != s->total)
1237             return 0;
1238         s->zero_cnt++;
1239     } else {
1240         /* If more than 4 characters could be final a.b.c.d form */
1241         if (len > 4) {
1242             /* Need at least 4 bytes left */
1243             if (s->total > 12)
1244                 return 0;
1245             /* Must be end of string */
1246             if (elem[len])
1247                 return 0;
1248             if (!ipv4_from_asc(s->tmp + s->total, elem))
1249                 return 0;
1250             s->total += 4;
1251         } else {
1252             if (!ipv6_hex(s->tmp + s->total, elem, len))
1253                 return 0;
1254             s->total += 2;
1255         }
1256     }
1257     return 1;
1258 }
1259
1260 /*
1261  * Convert a string of up to 4 hex digits into the corresponding IPv6 form.
1262  */
1263
1264 static int ipv6_hex(unsigned char *out, const char *in, int inlen)
1265 {
1266     unsigned char c;
1267     unsigned int num = 0;
1268     if (inlen > 4)
1269         return 0;
1270     while (inlen--) {
1271         c = *in++;
1272         num <<= 4;
1273         if ((c >= '0') && (c <= '9'))
1274             num |= c - '0';
1275         else if ((c >= 'A') && (c <= 'F'))
1276             num |= c - 'A' + 10;
1277         else if ((c >= 'a') && (c <= 'f'))
1278             num |= c - 'a' + 10;
1279         else
1280             return 0;
1281     }
1282     out[0] = num >> 8;
1283     out[1] = num & 0xff;
1284     return 1;
1285 }
1286
1287 int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
1288                              unsigned long chtype)
1289 {
1290     CONF_VALUE *v;
1291     int i, mval;
1292     char *p, *type;
1293     if (!nm)
1294         return 0;
1295
1296     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1297         v = sk_CONF_VALUE_value(dn_sk, i);
1298         type = v->name;
1299         /*
1300          * Skip past any leading X. X: X, etc to allow for multiple instances
1301          */
1302         for (p = type; *p; p++)
1303 #ifndef CHARSET_EBCDIC
1304             if ((*p == ':') || (*p == ',') || (*p == '.'))
1305 #else
1306             if ((*p == os_toascii[':']) || (*p == os_toascii[','])
1307                 || (*p == os_toascii['.']))
1308 #endif
1309             {
1310                 p++;
1311                 if (*p)
1312                     type = p;
1313                 break;
1314             }
1315 #ifndef CHARSET_EBCDIC
1316         if (*type == '+')
1317 #else
1318         if (*type == os_toascii['+'])
1319 #endif
1320         {
1321             mval = -1;
1322             type++;
1323         } else
1324             mval = 0;
1325         if (!X509_NAME_add_entry_by_txt(nm, type, chtype,
1326                                         (unsigned char *)v->value, -1, -1,
1327                                         mval))
1328             return 0;
1329
1330     }
1331     return 1;
1332 }