Fix name length limit check.
[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         len = X509_NAME_MAX;
199     q = p;
200
201     /* Get internal representation of Name */
202     ret = ASN1_item_ex_d2i(&intname.a,
203                            &p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
204                            tag, aclass, opt, ctx);
205
206     if (ret <= 0)
207         return ret;
208
209     if (*val)
210         x509_name_ex_free(val, NULL);
211     if (!x509_name_ex_new(&nm.a, NULL))
212         goto err;
213     /* We've decoded it: now cache encoding */
214     if (!BUF_MEM_grow(nm.x->bytes, p - q))
215         goto err;
216     memcpy(nm.x->bytes->data, q, p - q);
217
218     /* Convert internal representation to X509_NAME structure */
219     for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
220         entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
221         for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
222             entry = sk_X509_NAME_ENTRY_value(entries, j);
223             entry->set = i;
224             if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
225                 goto err;
226         }
227         sk_X509_NAME_ENTRY_free(entries);
228     }
229     sk_STACK_OF_X509_NAME_ENTRY_free(intname.s);
230     ret = x509_name_canon(nm.x);
231     if (!ret)
232         goto err;
233     nm.x->modified = 0;
234     *val = nm.a;
235     *in = p;
236     return ret;
237  err:
238     X509_NAME_free(nm.x);
239     ASN1err(ASN1_F_X509_NAME_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
240     return 0;
241 }
242
243 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
244                             const ASN1_ITEM *it, int tag, int aclass)
245 {
246     int ret;
247     X509_NAME *a = (X509_NAME *)*val;
248     if (a->modified) {
249         ret = x509_name_encode(a);
250         if (ret < 0)
251             return ret;
252         ret = x509_name_canon(a);
253         if (ret < 0)
254             return ret;
255     }
256     ret = a->bytes->length;
257     if (out != NULL) {
258         memcpy(*out, a->bytes->data, ret);
259         *out += ret;
260     }
261     return ret;
262 }
263
264 static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
265 {
266     sk_X509_NAME_ENTRY_free(ne);
267 }
268
269 static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
270 {
271     sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
272 }
273
274 static int x509_name_encode(X509_NAME *a)
275 {
276     union {
277         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
278         ASN1_VALUE *a;
279     } intname = {
280         NULL
281     };
282     int len;
283     unsigned char *p;
284     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
285     X509_NAME_ENTRY *entry;
286     int i, set = -1;
287     intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
288     if (!intname.s)
289         goto memerr;
290     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
291         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
292         if (entry->set != set) {
293             entries = sk_X509_NAME_ENTRY_new_null();
294             if (!entries)
295                 goto memerr;
296             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries))
297                 goto memerr;
298             set = entry->set;
299         }
300         if (!sk_X509_NAME_ENTRY_push(entries, entry))
301             goto memerr;
302     }
303     len = ASN1_item_ex_i2d(&intname.a, NULL,
304                            ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
305     if (!BUF_MEM_grow(a->bytes, len))
306         goto memerr;
307     p = (unsigned char *)a->bytes->data;
308     ASN1_item_ex_i2d(&intname.a,
309                      &p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
310     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
311                                          local_sk_X509_NAME_ENTRY_free);
312     a->modified = 0;
313     return len;
314  memerr:
315     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
316                                          local_sk_X509_NAME_ENTRY_free);
317     ASN1err(ASN1_F_X509_NAME_ENCODE, ERR_R_MALLOC_FAILURE);
318     return -1;
319 }
320
321 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
322                               int indent,
323                               const char *fname, const ASN1_PCTX *pctx)
324 {
325     if (X509_NAME_print_ex(out, (X509_NAME *)*pval,
326                            indent, pctx->nm_flags) <= 0)
327         return 0;
328     return 2;
329 }
330
331 /*
332  * This function generates the canonical encoding of the Name structure. In
333  * it all strings are converted to UTF8, leading, trailing and multiple
334  * spaces collapsed, converted to lower case and the leading SEQUENCE header
335  * removed. In future we could also normalize the UTF8 too. By doing this
336  * comparison of Name structures can be rapidly performed by just using
337  * memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
338  * constraints of type dirName can also be checked with a simple memcmp().
339  */
340
341 static int x509_name_canon(X509_NAME *a)
342 {
343     unsigned char *p;
344     STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
345     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
346     X509_NAME_ENTRY *entry, *tmpentry = NULL;
347     int i, set = -1, ret = 0, len;
348
349     OPENSSL_free(a->canon_enc);
350     a->canon_enc = NULL;
351     /* Special case: empty X509_NAME => null encoding */
352     if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
353         a->canon_enclen = 0;
354         return 1;
355     }
356     intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
357     if (!intname)
358         goto err;
359     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
360         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
361         if (entry->set != set) {
362             entries = sk_X509_NAME_ENTRY_new_null();
363             if (!entries)
364                 goto err;
365             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries))
366                 goto err;
367             set = entry->set;
368         }
369         tmpentry = X509_NAME_ENTRY_new();
370         if (tmpentry == NULL)
371             goto err;
372         tmpentry->object = OBJ_dup(entry->object);
373         if (!asn1_string_canon(tmpentry->value, entry->value))
374             goto err;
375         if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
376             goto err;
377         tmpentry = NULL;
378     }
379
380     /* Finally generate encoding */
381
382     len = i2d_name_canon(intname, NULL);
383     if (len < 0)
384         goto err;
385     a->canon_enclen = len;
386
387     p = OPENSSL_malloc(a->canon_enclen);
388
389     if (p == NULL)
390         goto err;
391
392     a->canon_enc = p;
393
394     i2d_name_canon(intname, &p);
395
396     ret = 1;
397
398  err:
399
400     X509_NAME_ENTRY_free(tmpentry);
401     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
402                                          local_sk_X509_NAME_ENTRY_pop_free);
403     return ret;
404 }
405
406 /* Bitmap of all the types of string that will be canonicalized. */
407
408 #define ASN1_MASK_CANON \
409         (B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
410         | B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
411         | B_ASN1_VISIBLESTRING)
412
413 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
414 {
415     unsigned char *to, *from;
416     int len, i;
417
418     /* If type not in bitmask just copy string across */
419     if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
420         if (!ASN1_STRING_copy(out, in))
421             return 0;
422         return 1;
423     }
424
425     out->type = V_ASN1_UTF8STRING;
426     out->length = ASN1_STRING_to_UTF8(&out->data, in);
427     if (out->length == -1)
428         return 0;
429
430     to = out->data;
431     from = to;
432
433     len = out->length;
434
435     /*
436      * Convert string in place to canonical form. Ultimately we may need to
437      * handle a wider range of characters but for now ignore anything with
438      * MSB set and rely on the isspace() and tolower() functions.
439      */
440
441     /* Ignore leading spaces */
442     while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
443         from++;
444         len--;
445     }
446
447     to = from + len - 1;
448
449     /* Ignore trailing spaces */
450     while ((len > 0) && !(*to & 0x80) && isspace(*to)) {
451         to--;
452         len--;
453     }
454
455     to = out->data;
456
457     i = 0;
458     while (i < len) {
459         /* If MSB set just copy across */
460         if (*from & 0x80) {
461             *to++ = *from++;
462             i++;
463         }
464         /* Collapse multiple spaces */
465         else if (isspace(*from)) {
466             /* Copy one space across */
467             *to++ = ' ';
468             /*
469              * Ignore subsequent spaces. Note: don't need to check len here
470              * because we know the last character is a non-space so we can't
471              * overflow.
472              */
473             do {
474                 from++;
475                 i++;
476             }
477             while (!(*from & 0x80) && isspace(*from));
478         } else {
479             *to++ = tolower(*from);
480             from++;
481             i++;
482         }
483     }
484
485     out->length = to - out->data;
486
487     return 1;
488
489 }
490
491 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
492                           unsigned char **in)
493 {
494     int i, len, ltmp;
495     ASN1_VALUE *v;
496     STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
497
498     len = 0;
499     for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
500         v = sk_ASN1_VALUE_value(intname, i);
501         ltmp = ASN1_item_ex_i2d(&v, in,
502                                 ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
503         if (ltmp < 0)
504             return ltmp;
505         len += ltmp;
506     }
507     return len;
508 }
509
510 int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
511 {
512     X509_NAME *in;
513
514     if (!xn || !name)
515         return (0);
516
517     if (*xn != name) {
518         in = X509_NAME_dup(name);
519         if (in != NULL) {
520             X509_NAME_free(*xn);
521             *xn = in;
522         }
523     }
524     return (*xn != NULL);
525 }
526
527 int X509_NAME_print(BIO *bp, X509_NAME *name, int obase)
528 {
529     char *s, *c, *b;
530     int l, i;
531
532     l = 80 - 2 - obase;
533
534     b = X509_NAME_oneline(name, NULL, 0);
535     if (!b)
536         return 0;
537     if (!*b) {
538         OPENSSL_free(b);
539         return 1;
540     }
541     s = b + 1;                  /* skip the first slash */
542
543     c = s;
544     for (;;) {
545 #ifndef CHARSET_EBCDIC
546         if (((*s == '/') &&
547              ((s[1] >= 'A') && (s[1] <= 'Z') && ((s[2] == '=') ||
548                                                  ((s[2] >= 'A')
549                                                   && (s[2] <= 'Z')
550                                                   && (s[3] == '='))
551               ))) || (*s == '\0'))
552 #else
553         if (((*s == '/') &&
554              (isupper(s[1]) && ((s[2] == '=') ||
555                                 (isupper(s[2]) && (s[3] == '='))
556               ))) || (*s == '\0'))
557 #endif
558         {
559             i = s - c;
560             if (BIO_write(bp, c, i) != i)
561                 goto err;
562             c = s + 1;          /* skip following slash */
563             if (*s != '\0') {
564                 if (BIO_write(bp, ", ", 2) != 2)
565                     goto err;
566             }
567             l--;
568         }
569         if (*s == '\0')
570             break;
571         s++;
572         l--;
573     }
574
575     OPENSSL_free(b);
576     return 1;
577  err:
578     X509err(X509_F_X509_NAME_PRINT, ERR_R_BUF_LIB);
579     OPENSSL_free(b);
580     return 0;
581 }
582
583 int X509_NAME_get0_der(const unsigned char **pder, size_t *pderlen,
584                        X509_NAME *nm)
585 {
586     /* Make sure encoding is valid */
587     if (i2d_X509_NAME(nm, NULL) <= 0)
588         return 0;
589     if (pder != NULL)
590         *pder = (unsigned char *)nm->bytes->data;
591     if (pderlen != NULL)
592         *pderlen = nm->bytes->length;
593     return 1;
594 }