fix potential memory leak + improved error checking
[openssl.git] / crypto / x509v3 / v3_utl.c
1 /* v3_utl.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) 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
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 *get_email(X509_NAME *name, GENERAL_NAMES *gens);
71 static void str_free(void *str);
72 static int append_ia5(STACK **sk, ASN1_IA5STRING *email);
73
74 static int a2i_ipadd(unsigned char *ipout, const char *ipasc);
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))) goto err;
88         if(value && !(tvalue = BUF_strdup(value))) goto err;;
89         if(!(vtmp = (CONF_VALUE *)OPENSSL_malloc(sizeof(CONF_VALUE)))) goto err;
90         if(!*extlist && !(*extlist = sk_CONF_VALUE_new_null())) goto err;
91         vtmp->section = NULL;
92         vtmp->name = tname;
93         vtmp->value = tvalue;
94         if(!sk_CONF_VALUE_push(*extlist, vtmp)) goto err;
95         return 1;
96         err:
97         X509V3err(X509V3_F_X509V3_ADD_VALUE,ERR_R_MALLOC_FAILURE);
98         if(vtmp) OPENSSL_free(vtmp);
99         if(tname) OPENSSL_free(tname);
100         if(tvalue) OPENSSL_free(tvalue);
101         return 0;
102 }
103
104 int X509V3_add_value_uchar(const char *name, const unsigned char *value,
105                            STACK_OF(CONF_VALUE) **extlist)
106     {
107     return X509V3_add_value(name,(const char *)value,extlist);
108     }
109
110 /* Free function for STACK_OF(CONF_VALUE) */
111
112 void X509V3_conf_free(CONF_VALUE *conf)
113 {
114         if(!conf) return;
115         if(conf->name) OPENSSL_free(conf->name);
116         if(conf->value) OPENSSL_free(conf->value);
117         if(conf->section) OPENSSL_free(conf->section);
118         OPENSSL_free(conf);
119 }
120
121 int X509V3_add_value_bool(const char *name, int asn1_bool,
122                                                 STACK_OF(CONF_VALUE) **extlist)
123 {
124         if(asn1_bool) return X509V3_add_value(name, "TRUE", extlist);
125         return X509V3_add_value(name, "FALSE", extlist);
126 }
127
128 int X509V3_add_value_bool_nf(char *name, int asn1_bool,
129                                                 STACK_OF(CONF_VALUE) **extlist)
130 {
131         if(asn1_bool) return X509V3_add_value(name, "TRUE", extlist);
132         return 1;
133 }
134
135
136 char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *method, ASN1_ENUMERATED *a)
137 {
138         BIGNUM *bntmp = NULL;
139         char *strtmp = NULL;
140         if(!a) return NULL;
141         if(!(bntmp = ASN1_ENUMERATED_to_BN(a, NULL)) ||
142             !(strtmp = BN_bn2dec(bntmp)) )
143                 X509V3err(X509V3_F_I2S_ASN1_ENUMERATED,ERR_R_MALLOC_FAILURE);
144         BN_free(bntmp);
145         return strtmp;
146 }
147
148 char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *method, ASN1_INTEGER *a)
149 {
150         BIGNUM *bntmp = NULL;
151         char *strtmp = NULL;
152         if(!a) return NULL;
153         if(!(bntmp = ASN1_INTEGER_to_BN(a, NULL)) ||
154             !(strtmp = BN_bn2dec(bntmp)) )
155                 X509V3err(X509V3_F_I2S_ASN1_INTEGER,ERR_R_MALLOC_FAILURE);
156         BN_free(bntmp);
157         return strtmp;
158 }
159
160 ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, char *value)
161 {
162         BIGNUM *bn = NULL;
163         ASN1_INTEGER *aint;
164         int isneg, ishex;
165         int ret;
166         if (!value) {
167                 X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_INVALID_NULL_VALUE);
168                 return 0;
169         }
170         bn = BN_new();
171         if (value[0] == '-') {
172                 value++;
173                 isneg = 1;
174         } else isneg = 0;
175
176         if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) {
177                 value += 2;
178                 ishex = 1;
179         } else ishex = 0;
180
181         if (ishex) ret = BN_hex2bn(&bn, value);
182         else ret = BN_dec2bn(&bn, value);
183
184         if (!ret || value[ret]) {
185                 BN_free(bn);
186                 X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_BN_DEC2BN_ERROR);
187                 return 0;
188         }
189
190         if (isneg && BN_is_zero(bn)) isneg = 0;
191
192         aint = BN_to_ASN1_INTEGER(bn, NULL);
193         BN_free(bn);
194         if (!aint) {
195                 X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_BN_TO_ASN1_INTEGER_ERROR);
196                 return 0;
197         }
198         if (isneg) aint->type |= V_ASN1_NEG;
199         return aint;
200 }
201
202 int X509V3_add_value_int(const char *name, ASN1_INTEGER *aint,
203              STACK_OF(CONF_VALUE) **extlist)
204 {
205         char *strtmp;
206         int ret;
207         if(!aint) return 1;
208         if(!(strtmp = i2s_ASN1_INTEGER(NULL, aint))) return 0;
209         ret = X509V3_add_value(name, strtmp, extlist);
210         OPENSSL_free(strtmp);
211         return ret;
212 }
213
214 int X509V3_get_value_bool(CONF_VALUE *value, int *asn1_bool)
215 {
216         char *btmp;
217         if(!(btmp = value->value)) goto err;
218         if(!strcmp(btmp, "TRUE") || !strcmp(btmp, "true")
219                  || !strcmp(btmp, "Y") || !strcmp(btmp, "y")
220                 || !strcmp(btmp, "YES") || !strcmp(btmp, "yes")) {
221                 *asn1_bool = 0xff;
222                 return 1;
223         } else if(!strcmp(btmp, "FALSE") || !strcmp(btmp, "false")
224                  || !strcmp(btmp, "N") || !strcmp(btmp, "n")
225                 || !strcmp(btmp, "NO") || !strcmp(btmp, "no")) {
226                 *asn1_bool = 0;
227                 return 1;
228         }
229         err:
230         X509V3err(X509V3_F_X509V3_GET_VALUE_BOOL,X509V3_R_INVALID_BOOLEAN_STRING);
231         X509V3_conf_err(value);
232         return 0;
233 }
234
235 int X509V3_get_value_int(CONF_VALUE *value, ASN1_INTEGER **aint)
236 {
237         ASN1_INTEGER *itmp;
238         if(!(itmp = s2i_ASN1_INTEGER(NULL, value->value))) {
239                 X509V3_conf_err(value);
240                 return 0;
241         }
242         *aint = itmp;
243         return 1;
244 }
245
246 #define HDR_NAME        1
247 #define HDR_VALUE       2
248
249 /*#define DEBUG*/
250
251 STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line)
252 {
253         char *p, *q, c;
254         char *ntmp, *vtmp;
255         STACK_OF(CONF_VALUE) *values = NULL;
256         char *linebuf;
257         int state;
258         /* We are going to modify the line so copy it first */
259         linebuf = BUF_strdup(line);
260         state = HDR_NAME;
261         ntmp = NULL;
262         /* Go through all characters */
263         for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) {
264
265                 switch(state) {
266                         case HDR_NAME:
267                         if(c == ':') {
268                                 state = HDR_VALUE;
269                                 *p = 0;
270                                 ntmp = strip_spaces(q);
271                                 if(!ntmp) {
272                                         X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME);
273                                         goto err;
274                                 }
275                                 q = p + 1;
276                         } else if(c == ',') {
277                                 *p = 0;
278                                 ntmp = strip_spaces(q);
279                                 q = p + 1;
280 #if 0
281                                 printf("%s\n", ntmp);
282 #endif
283                                 if(!ntmp) {
284                                         X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME);
285                                         goto err;
286                                 }
287                                 X509V3_add_value(ntmp, NULL, &values);
288                         }
289                         break ;
290
291                         case HDR_VALUE:
292                         if(c == ',') {
293                                 state = HDR_NAME;
294                                 *p = 0;
295                                 vtmp = strip_spaces(q);
296 #if 0
297                                 printf("%s\n", ntmp);
298 #endif
299                                 if(!vtmp) {
300                                         X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_VALUE);
301                                         goto err;
302                                 }
303                                 X509V3_add_value(ntmp, vtmp, &values);
304                                 ntmp = NULL;
305                                 q = p + 1;
306                         }
307
308                 }
309         }
310
311         if(state == HDR_VALUE) {
312                 vtmp = strip_spaces(q);
313 #if 0
314                 printf("%s=%s\n", ntmp, vtmp);
315 #endif
316                 if(!vtmp) {
317                         X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_VALUE);
318                         goto err;
319                 }
320                 X509V3_add_value(ntmp, vtmp, &values);
321         } else {
322                 ntmp = strip_spaces(q);
323 #if 0
324                 printf("%s\n", ntmp);
325 #endif
326                 if(!ntmp) {
327                         X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME);
328                         goto err;
329                 }
330                 X509V3_add_value(ntmp, NULL, &values);
331         }
332 OPENSSL_free(linebuf);
333 return values;
334
335 err:
336 OPENSSL_free(linebuf);
337 sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
338 return NULL;
339
340 }
341
342 /* Delete leading and trailing spaces from a string */
343 static char *strip_spaces(char *name)
344 {
345         char *p, *q;
346         /* Skip over leading spaces */
347         p = name;
348         while(*p && isspace((unsigned char)*p)) p++;
349         if(!*p) return NULL;
350         q = p + strlen(p) - 1;
351         while((q != p) && isspace((unsigned char)*q)) q--;
352         if(p != q) q[1] = 0;
353         if(!*p) return NULL;
354         return p;
355 }
356
357 /* hex string utilities */
358
359 /* Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its
360  * hex representation
361  * @@@ (Contents of buffer are always kept in ASCII, also on EBCDIC machines)
362  */
363
364 char *hex_to_string(unsigned char *buffer, long len)
365 {
366         char *tmp, *q;
367         unsigned char *p;
368         int i;
369         static char hexdig[] = "0123456789ABCDEF";
370         if(!buffer || !len) return NULL;
371         if(!(tmp = OPENSSL_malloc(len * 3 + 1))) {
372                 X509V3err(X509V3_F_HEX_TO_STRING,ERR_R_MALLOC_FAILURE);
373                 return NULL;
374         }
375         q = tmp;
376         for(i = 0, p = buffer; i < len; i++,p++) {
377                 *q++ = hexdig[(*p >> 4) & 0xf];
378                 *q++ = hexdig[*p & 0xf];
379                 *q++ = ':';
380         }
381         q[-1] = 0;
382 #ifdef CHARSET_EBCDIC
383         ebcdic2ascii(tmp, tmp, q - tmp - 1);
384 #endif
385
386         return tmp;
387 }
388
389 /* Give a string of hex digits convert to
390  * a buffer
391  */
392
393 unsigned char *string_to_hex(char *str, long *len)
394 {
395         unsigned char *hexbuf, *q;
396         unsigned char ch, cl, *p;
397         if(!str) {
398                 X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_INVALID_NULL_ARGUMENT);
399                 return NULL;
400         }
401         if(!(hexbuf = OPENSSL_malloc(strlen(str) >> 1))) goto err;
402         for(p = (unsigned char *)str, q = hexbuf; *p;) {
403                 ch = *p++;
404 #ifdef CHARSET_EBCDIC
405                 ch = os_toebcdic[ch];
406 #endif
407                 if(ch == ':') continue;
408                 cl = *p++;
409 #ifdef CHARSET_EBCDIC
410                 cl = os_toebcdic[cl];
411 #endif
412                 if(!cl) {
413                         X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_ODD_NUMBER_OF_DIGITS);
414                         OPENSSL_free(hexbuf);
415                         return NULL;
416                 }
417                 if(isupper(ch)) ch = tolower(ch);
418                 if(isupper(cl)) cl = tolower(cl);
419
420                 if((ch >= '0') && (ch <= '9')) ch -= '0';
421                 else if ((ch >= 'a') && (ch <= 'f')) ch -= 'a' - 10;
422                 else goto badhex;
423
424                 if((cl >= '0') && (cl <= '9')) cl -= '0';
425                 else if ((cl >= 'a') && (cl <= 'f')) cl -= 'a' - 10;
426                 else goto badhex;
427
428                 *q++ = (ch << 4) | cl;
429         }
430
431         if(len) *len = q - hexbuf;
432
433         return hexbuf;
434
435         err:
436         if(hexbuf) OPENSSL_free(hexbuf);
437         X509V3err(X509V3_F_STRING_TO_HEX,ERR_R_MALLOC_FAILURE);
438         return NULL;
439
440         badhex:
441         OPENSSL_free(hexbuf);
442         X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_ILLEGAL_HEX_DIGIT);
443         return NULL;
444
445 }
446
447 /* V2I name comparison function: returns zero if 'name' matches
448  * cmp or cmp.*
449  */
450
451 int name_cmp(const char *name, const char *cmp)
452 {
453         int len, ret;
454         char c;
455         len = strlen(cmp);
456         if((ret = strncmp(name, cmp, len))) return ret;
457         c = name[len];
458         if(!c || (c=='.')) return 0;
459         return 1;
460 }
461
462 static int sk_strcmp(const char * const *a, const char * const *b)
463 {
464         return strcmp(*a, *b);
465 }
466
467 STACK *X509_get1_email(X509 *x)
468 {
469         GENERAL_NAMES *gens;
470         STACK *ret;
471         gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
472         ret = get_email(X509_get_subject_name(x), gens);
473         sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
474         return ret;
475 }
476
477 STACK *X509_REQ_get1_email(X509_REQ *x)
478 {
479         GENERAL_NAMES *gens;
480         STACK_OF(X509_EXTENSION) *exts;
481         STACK *ret;
482         exts = X509_REQ_get_extensions(x);
483         gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
484         ret = get_email(X509_REQ_get_subject_name(x), gens);
485         sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
486         sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
487         return ret;
488 }
489
490
491 static STACK *get_email(X509_NAME *name, GENERAL_NAMES *gens)
492 {
493         STACK *ret = NULL;
494         X509_NAME_ENTRY *ne;
495         ASN1_IA5STRING *email;
496         GENERAL_NAME *gen;
497         int i;
498         /* Now add any email address(es) to STACK */
499         i = -1;
500         /* First supplied X509_NAME */
501         while((i = X509_NAME_get_index_by_NID(name,
502                                          NID_pkcs9_emailAddress, i)) >= 0) {
503                 ne = X509_NAME_get_entry(name, i);
504                 email = X509_NAME_ENTRY_get_data(ne);
505                 if(!append_ia5(&ret, email)) return NULL;
506         }
507         for(i = 0; i < sk_GENERAL_NAME_num(gens); i++)
508         {
509                 gen = sk_GENERAL_NAME_value(gens, i);
510                 if(gen->type != GEN_EMAIL) continue;
511                 if(!append_ia5(&ret, gen->d.ia5)) return NULL;
512         }
513         return ret;
514 }
515
516 static void str_free(void *str)
517 {
518         OPENSSL_free(str);
519 }
520
521 static int append_ia5(STACK **sk, ASN1_IA5STRING *email)
522 {
523         char *emtmp;
524         /* First some sanity checks */
525         if(email->type != V_ASN1_IA5STRING) return 1;
526         if(!email->data || !email->length) return 1;
527         if(!*sk) *sk = sk_new(sk_strcmp);
528         if(!*sk) return 0;
529         /* Don't add duplicates */
530         if(sk_find(*sk, (char *)email->data) != -1) return 1;
531         emtmp = BUF_strdup((char *)email->data);
532         if(!emtmp || !sk_push(*sk, emtmp)) {
533                 X509_email_free(*sk);
534                 *sk = NULL;
535                 return 0;
536         }
537         return 1;
538 }
539
540 void X509_email_free(STACK *sk)
541 {
542         sk_pop_free(sk, str_free);
543 }
544
545 /* Convert IP addresses both IPv4 and IPv6 into an 
546  * OCTET STRING compatible with RFC3280.
547  */
548
549 ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
550         {
551         unsigned char ipout[16];
552         ASN1_OCTET_STRING *ret;
553         int iplen;
554
555         /* If string contains a ':' assume IPv6 */
556
557         iplen = a2i_ipadd(ipout, ipasc);
558
559         if (!iplen)
560                 return NULL;
561
562         ret = ASN1_OCTET_STRING_new();
563         if (!ret)
564                 return NULL;
565         if (!ASN1_OCTET_STRING_set(ret, ipout, iplen))
566                 {
567                 ASN1_OCTET_STRING_free(ret);
568                 return NULL;
569                 }
570         return ret;
571         }
572
573 ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
574         {
575         ASN1_OCTET_STRING *ret = NULL;
576         unsigned char ipout[32];
577         char *iptmp = NULL, *p;
578         int iplen1, iplen2;
579         p = strchr(ipasc,'/');
580         if (!p)
581                 return NULL;
582         iptmp = BUF_strdup(ipasc);
583         if (!iptmp)
584                 return NULL;
585         p = iptmp + (p - ipasc);
586         *p++ = 0;
587
588         iplen1 = a2i_ipadd(ipout, iptmp);
589
590         if (!iplen1)
591                 goto err;
592
593         iplen2 = a2i_ipadd(ipout + iplen1, p);
594
595         OPENSSL_free(iptmp);
596         iptmp = NULL;
597
598         if (!iplen2 || (iplen1 != iplen2))
599                 goto err;
600
601         ret = ASN1_OCTET_STRING_new();
602         if (!ret)
603                 goto err;
604         if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
605                 goto err;
606
607         return ret;
608
609         err:
610         if (iptmp)
611                 OPENSSL_free(iptmp);
612         if (ret)
613                 ASN1_OCTET_STRING_free(ret);
614         return NULL;
615         }
616         
617
618 static int a2i_ipadd(unsigned char *ipout, const char *ipasc)
619         {
620         /* If string contains a ':' assume IPv6 */
621
622         if (strchr(ipasc, ':'))
623                 {
624                 if (!ipv6_from_asc(ipout, ipasc))
625                         return 0;
626                 return 16;
627                 }
628         else
629                 {
630                 if (!ipv4_from_asc(ipout, ipasc))
631                         return 0;
632                 return 4;
633                 }
634         }
635
636 static int ipv4_from_asc(unsigned char *v4, const char *in)
637         {
638         int a0, a1, a2, a3;
639         if (sscanf(in, "%d.%d.%d.%d", &a0, &a1, &a2, &a3) != 4)
640                 return 0;
641         if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255)
642                 || (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255))
643                 return 0;
644         v4[0] = a0;
645         v4[1] = a1;
646         v4[2] = a2;
647         v4[3] = a3;
648         return 1;
649         }
650
651 typedef struct {
652                 /* Temporary store for IPV6 output */
653                 unsigned char tmp[16];
654                 /* Total number of bytes in tmp */
655                 int total;
656                 /* The position of a zero (corresponding to '::') */
657                 int zero_pos;
658                 /* Number of zeroes */
659                 int zero_cnt;
660         } IPV6_STAT;
661
662
663 static int ipv6_from_asc(unsigned char *v6, const char *in)
664         {
665         IPV6_STAT v6stat;
666         v6stat.total = 0;
667         v6stat.zero_pos = -1;
668         v6stat.zero_cnt = 0;
669         /* Treat the IPv6 representation as a list of values
670          * separated by ':'. The presence of a '::' will parse
671          * as one, two or three zero length elements.
672          */
673         if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
674                 return 0;
675
676         /* Now for some sanity checks */
677
678         if (v6stat.zero_pos == -1)
679                 {
680                 /* If no '::' must have exactly 16 bytes */
681                 if (v6stat.total != 16)
682                         return 0;
683                 }
684         else 
685                 {
686                 /* If '::' must have less than 16 bytes */
687                 if (v6stat.total == 16)
688                         return 0;
689                 /* More than three zeroes is an error */
690                 if (v6stat.zero_cnt > 3)
691                         return 0;
692                 /* Can only have three zeroes if nothing else present */
693                 else if (v6stat.zero_cnt == 3)
694                         {
695                         if (v6stat.total > 0)
696                                 return 0;
697                         }
698                 /* Can only have two zeroes if at start or end */
699                 else if (v6stat.zero_cnt == 2)
700                         {
701                         if ((v6stat.zero_pos != 0)
702                                 && (v6stat.zero_pos != v6stat.total))
703                                 return 0;
704                         }
705                 else 
706                 /* Can only have one zero if *not* start or end */
707                         {
708                         if ((v6stat.zero_pos == 0)
709                                 || (v6stat.zero_pos == v6stat.total))
710                                 return 0;
711                         }
712                 }
713
714         /* Format result */
715
716         /* Copy initial part */
717         if (v6stat.zero_pos > 0)
718                 memcpy(v6, v6stat.tmp, v6stat.zero_pos);
719         /* Zero middle */
720         if (v6stat.total != 16)
721                 memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
722         /* Copy final part */
723         if (v6stat.total != v6stat.zero_pos)
724                 memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
725                         v6stat.tmp + v6stat.zero_pos,
726                         v6stat.total - v6stat.zero_pos);
727
728         return 1;
729         }
730
731 static int ipv6_cb(const char *elem, int len, void *usr)
732         {
733         IPV6_STAT *s = usr;
734         /* Error if 16 bytes written */
735         if (s->total == 16)
736                 return 0;
737         if (len == 0)
738                 {
739                 /* Zero length element, corresponds to '::' */
740                 if (s->zero_pos == -1)
741                         s->zero_pos = s->total;
742                 /* If we've already got a :: its an error */
743                 else if (s->zero_pos != s->total)
744                         return 0;
745                 s->zero_cnt++;
746                 }
747         else 
748                 {
749                 /* If more than 4 characters could be final a.b.c.d form */
750                 if (len > 4)
751                         {
752                         /* Need at least 4 bytes left */
753                         if (s->total > 12)
754                                 return 0;
755                         /* Must be end of string */
756                         if (elem[len])
757                                 return 0;
758                         if (!ipv4_from_asc(s->tmp + s->total, elem))
759                                 return 0;
760                         s->total += 4;
761                         }
762                 else
763                         {
764                         if (!ipv6_hex(s->tmp + s->total, elem, len))
765                                 return 0;
766                         s->total += 2;
767                         }
768                 }
769         return 1;
770         }
771
772 /* Convert a string of up to 4 hex digits into the corresponding
773  * IPv6 form.
774  */
775
776 static int ipv6_hex(unsigned char *out, const char *in, int inlen)
777         {
778         unsigned char c;
779         unsigned int num = 0;
780         if (inlen > 4)
781                 return 0;
782         while(inlen--)
783                 {
784                 c = *in++;
785                 num <<= 4;
786                 if ((c >= '0') && (c <= '9'))
787                         num |= c - '0';
788                 else if ((c >= 'A') && (c <= 'F'))
789                         num |= c - 'A' + 10;
790                 else if ((c >= 'a') && (c <= 'f'))
791                         num |=  c - 'a' + 10;
792                 else
793                         return 0;
794                 }
795         out[0] = num >> 8;
796         out[1] = num & 0xff;
797         return 1;
798         }
799
800
801 int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE)*dn_sk,
802                                                 unsigned long chtype)
803         {
804         CONF_VALUE *v;
805         int i, mval;
806         char *p, *type;
807         if (!nm)
808                 return 0;
809
810         for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++)
811                 {
812                 v=sk_CONF_VALUE_value(dn_sk,i);
813                 type=v->name;
814                 /* Skip past any leading X. X: X, etc to allow for
815                  * multiple instances 
816                  */
817                 for(p = type; *p ; p++) 
818 #ifndef CHARSET_EBCDIC
819                         if ((*p == ':') || (*p == ',') || (*p == '.'))
820 #else
821                         if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.']))
822 #endif
823                                 {
824                                 p++;
825                                 if(*p) type = p;
826                                 break;
827                                 }
828 #ifndef CHARSET_EBCDIC
829                 if (*type == '+')
830 #else
831                 if (*type == os_toascii['+'])
832 #endif
833                         {
834                         mval = -1;
835                         type++;
836                         }
837                 else
838                         mval = 0;
839                 if (!X509_NAME_add_entry_by_txt(nm,type, chtype,
840                                 (unsigned char *) v->value,-1,-1,mval))
841                                         return 0;
842
843                 }
844         return 1;
845         }