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