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