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