Properly own the duplicated string
[openssl.git] / crypto / x509 / x_name.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include <ctype.h>
60 #include "internal/cryptlib.h"
61 #include <openssl/asn1t.h>
62 #include <openssl/x509.h>
63 #include "internal/x509_int.h"
64 #include "internal/asn1_int.h"
65 #include "x509_lcl.h"
66
67 /*
68  * Maximum length of X509_NAME: much larger than anything we should
69  * ever see in practice.
70  */
71
72 #define X509_NAME_MAX (1024 * 1024)
73
74 static int x509_name_ex_d2i(ASN1_VALUE **val,
75                             const unsigned char **in, long len,
76                             const ASN1_ITEM *it,
77                             int tag, int aclass, char opt, ASN1_TLC *ctx);
78
79 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
80                             const ASN1_ITEM *it, int tag, int aclass);
81 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
82 static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
83
84 static int x509_name_encode(X509_NAME *a);
85 static int x509_name_canon(X509_NAME *a);
86 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in);
87 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
88                           unsigned char **in);
89
90 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
91                               int indent,
92                               const char *fname, const ASN1_PCTX *pctx);
93
94 ASN1_SEQUENCE(X509_NAME_ENTRY) = {
95         ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
96         ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
97 } ASN1_SEQUENCE_END(X509_NAME_ENTRY)
98
99 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
100 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
101
102 /*
103  * For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
104  * declare two template wrappers for this
105  */
106
107 ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
108         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
109 static_ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
110
111 ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
112         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
113 static_ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
114
115 /*
116  * Normally that's where it would end: we'd have two nested STACK structures
117  * representing the ASN1. Unfortunately X509_NAME uses a completely different
118  * form and caches encodings so we have to process the internal form and
119  * convert to the external form.
120  */
121
122 static const ASN1_EXTERN_FUNCS x509_name_ff = {
123     NULL,
124     x509_name_ex_new,
125     x509_name_ex_free,
126     0,                          /* Default clear behaviour is OK */
127     x509_name_ex_d2i,
128     x509_name_ex_i2d,
129     x509_name_ex_print
130 };
131
132 IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
133
134 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
135
136 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
137
138 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
139 {
140     X509_NAME *ret = OPENSSL_zalloc(sizeof(*ret));
141
142     if (ret == NULL)
143         goto memerr;
144     if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
145         goto memerr;
146     if ((ret->bytes = BUF_MEM_new()) == NULL)
147         goto memerr;
148     ret->modified = 1;
149     *val = (ASN1_VALUE *)ret;
150     return 1;
151
152  memerr:
153     ASN1err(ASN1_F_X509_NAME_EX_NEW, ERR_R_MALLOC_FAILURE);
154     if (ret) {
155         sk_X509_NAME_ENTRY_free(ret->entries);
156         OPENSSL_free(ret);
157     }
158     return 0;
159 }
160
161 static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
162 {
163     X509_NAME *a;
164
165     if (!pval || !*pval)
166         return;
167     a = (X509_NAME *)*pval;
168
169     BUF_MEM_free(a->bytes);
170     sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
171     OPENSSL_free(a->canon_enc);
172     OPENSSL_free(a);
173     *pval = NULL;
174 }
175
176 static int x509_name_ex_d2i(ASN1_VALUE **val,
177                             const unsigned char **in, long len,
178                             const ASN1_ITEM *it, int tag, int aclass,
179                             char opt, ASN1_TLC *ctx)
180 {
181     const unsigned char *p = *in, *q;
182     union {
183         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
184         ASN1_VALUE *a;
185     } intname = {
186         NULL
187     };
188     union {
189         X509_NAME *x;
190         ASN1_VALUE *a;
191     } nm = {
192         NULL
193     };
194     int i, j, ret;
195     STACK_OF(X509_NAME_ENTRY) *entries;
196     X509_NAME_ENTRY *entry;
197     if (len > X509_NAME_MAX) {
198         ASN1err(ASN1_F_X509_NAME_EX_D2I, ASN1_R_TOO_LONG);
199         return 0;
200     }
201     q = p;
202
203     /* Get internal representation of Name */
204     ret = ASN1_item_ex_d2i(&intname.a,
205                            &p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
206                            tag, aclass, opt, ctx);
207
208     if (ret <= 0)
209         return ret;
210
211     if (*val)
212         x509_name_ex_free(val, NULL);
213     if (!x509_name_ex_new(&nm.a, NULL))
214         goto err;
215     /* We've decoded it: now cache encoding */
216     if (!BUF_MEM_grow(nm.x->bytes, p - q))
217         goto err;
218     memcpy(nm.x->bytes->data, q, p - q);
219
220     /* Convert internal representation to X509_NAME structure */
221     for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
222         entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
223         for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
224             entry = sk_X509_NAME_ENTRY_value(entries, j);
225             entry->set = i;
226             if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
227                 goto err;
228         }
229         sk_X509_NAME_ENTRY_free(entries);
230     }
231     sk_STACK_OF_X509_NAME_ENTRY_free(intname.s);
232     ret = x509_name_canon(nm.x);
233     if (!ret)
234         goto err;
235     nm.x->modified = 0;
236     *val = nm.a;
237     *in = p;
238     return ret;
239  err:
240     X509_NAME_free(nm.x);
241     ASN1err(ASN1_F_X509_NAME_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
242     return 0;
243 }
244
245 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
246                             const ASN1_ITEM *it, int tag, int aclass)
247 {
248     int ret;
249     X509_NAME *a = (X509_NAME *)*val;
250     if (a->modified) {
251         ret = x509_name_encode(a);
252         if (ret < 0)
253             return ret;
254         ret = x509_name_canon(a);
255         if (ret < 0)
256             return ret;
257     }
258     ret = a->bytes->length;
259     if (out != NULL) {
260         memcpy(*out, a->bytes->data, ret);
261         *out += ret;
262     }
263     return ret;
264 }
265
266 static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
267 {
268     sk_X509_NAME_ENTRY_free(ne);
269 }
270
271 static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
272 {
273     sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
274 }
275
276 static int x509_name_encode(X509_NAME *a)
277 {
278     union {
279         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
280         ASN1_VALUE *a;
281     } intname = {
282         NULL
283     };
284     int len;
285     unsigned char *p;
286     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
287     X509_NAME_ENTRY *entry;
288     int i, set = -1;
289     intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
290     if (!intname.s)
291         goto memerr;
292     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
293         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
294         if (entry->set != set) {
295             entries = sk_X509_NAME_ENTRY_new_null();
296             if (!entries)
297                 goto memerr;
298             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries))
299                 goto memerr;
300             set = entry->set;
301         }
302         if (!sk_X509_NAME_ENTRY_push(entries, entry))
303             goto memerr;
304     }
305     len = ASN1_item_ex_i2d(&intname.a, NULL,
306                            ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
307     if (!BUF_MEM_grow(a->bytes, len))
308         goto memerr;
309     p = (unsigned char *)a->bytes->data;
310     ASN1_item_ex_i2d(&intname.a,
311                      &p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
312     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
313                                          local_sk_X509_NAME_ENTRY_free);
314     a->modified = 0;
315     return len;
316  memerr:
317     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
318                                          local_sk_X509_NAME_ENTRY_free);
319     ASN1err(ASN1_F_X509_NAME_ENCODE, ERR_R_MALLOC_FAILURE);
320     return -1;
321 }
322
323 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
324                               int indent,
325                               const char *fname, const ASN1_PCTX *pctx)
326 {
327     if (X509_NAME_print_ex(out, (X509_NAME *)*pval,
328                            indent, pctx->nm_flags) <= 0)
329         return 0;
330     return 2;
331 }
332
333 /*
334  * This function generates the canonical encoding of the Name structure. In
335  * it all strings are converted to UTF8, leading, trailing and multiple
336  * spaces collapsed, converted to lower case and the leading SEQUENCE header
337  * removed. In future we could also normalize the UTF8 too. By doing this
338  * comparison of Name structures can be rapidly performed by just using
339  * memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
340  * constraints of type dirName can also be checked with a simple memcmp().
341  */
342
343 static int x509_name_canon(X509_NAME *a)
344 {
345     unsigned char *p;
346     STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
347     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
348     X509_NAME_ENTRY *entry, *tmpentry = NULL;
349     int i, set = -1, ret = 0, len;
350
351     OPENSSL_free(a->canon_enc);
352     a->canon_enc = NULL;
353     /* Special case: empty X509_NAME => null encoding */
354     if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
355         a->canon_enclen = 0;
356         return 1;
357     }
358     intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
359     if (!intname)
360         goto err;
361     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
362         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
363         if (entry->set != set) {
364             entries = sk_X509_NAME_ENTRY_new_null();
365             if (!entries)
366                 goto err;
367             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries))
368                 goto err;
369             set = entry->set;
370         }
371         tmpentry = X509_NAME_ENTRY_new();
372         if (tmpentry == NULL)
373             goto err;
374         tmpentry->object = OBJ_dup(entry->object);
375         if (!asn1_string_canon(tmpentry->value, entry->value))
376             goto err;
377         if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
378             goto err;
379         tmpentry = NULL;
380     }
381
382     /* Finally generate encoding */
383
384     len = i2d_name_canon(intname, NULL);
385     if (len < 0)
386         goto err;
387     a->canon_enclen = len;
388
389     p = OPENSSL_malloc(a->canon_enclen);
390
391     if (p == NULL)
392         goto err;
393
394     a->canon_enc = p;
395
396     i2d_name_canon(intname, &p);
397
398     ret = 1;
399
400  err:
401
402     X509_NAME_ENTRY_free(tmpentry);
403     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
404                                          local_sk_X509_NAME_ENTRY_pop_free);
405     return ret;
406 }
407
408 /* Bitmap of all the types of string that will be canonicalized. */
409
410 #define ASN1_MASK_CANON \
411         (B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
412         | B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
413         | B_ASN1_VISIBLESTRING)
414
415 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
416 {
417     unsigned char *to, *from;
418     int len, i;
419
420     /* If type not in bitmask just copy string across */
421     if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
422         if (!ASN1_STRING_copy(out, in))
423             return 0;
424         return 1;
425     }
426
427     out->type = V_ASN1_UTF8STRING;
428     out->length = ASN1_STRING_to_UTF8(&out->data, in);
429     if (out->length == -1)
430         return 0;
431
432     to = out->data;
433     from = to;
434
435     len = out->length;
436
437     /*
438      * Convert string in place to canonical form. Ultimately we may need to
439      * handle a wider range of characters but for now ignore anything with
440      * MSB set and rely on the isspace() and tolower() functions.
441      */
442
443     /* Ignore leading spaces */
444     while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
445         from++;
446         len--;
447     }
448
449     to = from + len - 1;
450
451     /* Ignore trailing spaces */
452     while ((len > 0) && !(*to & 0x80) && isspace(*to)) {
453         to--;
454         len--;
455     }
456
457     to = out->data;
458
459     i = 0;
460     while (i < len) {
461         /* If MSB set just copy across */
462         if (*from & 0x80) {
463             *to++ = *from++;
464             i++;
465         }
466         /* Collapse multiple spaces */
467         else if (isspace(*from)) {
468             /* Copy one space across */
469             *to++ = ' ';
470             /*
471              * Ignore subsequent spaces. Note: don't need to check len here
472              * because we know the last character is a non-space so we can't
473              * overflow.
474              */
475             do {
476                 from++;
477                 i++;
478             }
479             while (!(*from & 0x80) && isspace(*from));
480         } else {
481             *to++ = tolower(*from);
482             from++;
483             i++;
484         }
485     }
486
487     out->length = to - out->data;
488
489     return 1;
490
491 }
492
493 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
494                           unsigned char **in)
495 {
496     int i, len, ltmp;
497     ASN1_VALUE *v;
498     STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
499
500     len = 0;
501     for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
502         v = sk_ASN1_VALUE_value(intname, i);
503         ltmp = ASN1_item_ex_i2d(&v, in,
504                                 ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
505         if (ltmp < 0)
506             return ltmp;
507         len += ltmp;
508     }
509     return len;
510 }
511
512 int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
513 {
514     X509_NAME *in;
515
516     if (!xn || !name)
517         return (0);
518
519     if (*xn != name) {
520         in = X509_NAME_dup(name);
521         if (in != NULL) {
522             X509_NAME_free(*xn);
523             *xn = in;
524         }
525     }
526     return (*xn != NULL);
527 }
528
529 int X509_NAME_print(BIO *bp, X509_NAME *name, int obase)
530 {
531     char *s, *c, *b;
532     int l, i;
533
534     l = 80 - 2 - obase;
535
536     b = X509_NAME_oneline(name, NULL, 0);
537     if (!b)
538         return 0;
539     if (!*b) {
540         OPENSSL_free(b);
541         return 1;
542     }
543     s = b + 1;                  /* skip the first slash */
544
545     c = s;
546     for (;;) {
547 #ifndef CHARSET_EBCDIC
548         if (((*s == '/') &&
549              ((s[1] >= 'A') && (s[1] <= 'Z') && ((s[2] == '=') ||
550                                                  ((s[2] >= 'A')
551                                                   && (s[2] <= 'Z')
552                                                   && (s[3] == '='))
553               ))) || (*s == '\0'))
554 #else
555         if (((*s == '/') &&
556              (isupper(s[1]) && ((s[2] == '=') ||
557                                 (isupper(s[2]) && (s[3] == '='))
558               ))) || (*s == '\0'))
559 #endif
560         {
561             i = s - c;
562             if (BIO_write(bp, c, i) != i)
563                 goto err;
564             c = s + 1;          /* skip following slash */
565             if (*s != '\0') {
566                 if (BIO_write(bp, ", ", 2) != 2)
567                     goto err;
568             }
569             l--;
570         }
571         if (*s == '\0')
572             break;
573         s++;
574         l--;
575     }
576
577     OPENSSL_free(b);
578     return 1;
579  err:
580     X509err(X509_F_X509_NAME_PRINT, ERR_R_BUF_LIB);
581     OPENSSL_free(b);
582     return 0;
583 }
584
585 int X509_NAME_get0_der(const unsigned char **pder, size_t *pderlen,
586                        X509_NAME *nm)
587 {
588     /* Make sure encoding is valid */
589     if (i2d_X509_NAME(nm, NULL) <= 0)
590         return 0;
591     if (pder != NULL)
592         *pder = (unsigned char *)nm->bytes->data;
593     if (pderlen != NULL)
594         *pderlen = nm->bytes->length;
595     return 1;
596 }