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