The x509_name_canon function doesn't check for an error return
[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 static int x509_name_ex_d2i(ASN1_VALUE **val,
68                             const unsigned char **in, long len,
69                             const ASN1_ITEM *it,
70                             int tag, int aclass, char opt, ASN1_TLC *ctx);
71
72 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
73                             const ASN1_ITEM *it, int tag, int aclass);
74 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
75 static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
76
77 static int x509_name_encode(X509_NAME *a);
78 static int x509_name_canon(X509_NAME *a);
79 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in);
80 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
81                           unsigned char **in);
82
83 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
84                               int indent,
85                               const char *fname, const ASN1_PCTX *pctx);
86
87 ASN1_SEQUENCE(X509_NAME_ENTRY) = {
88         ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
89         ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
90 } ASN1_SEQUENCE_END(X509_NAME_ENTRY)
91
92 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
93 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
94
95 /*
96  * For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
97  * declare two template wrappers for this
98  */
99
100 ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
101         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
102 static_ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
103
104 ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
105         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
106 static_ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
107
108 /*
109  * Normally that's where it would end: we'd have two nested STACK structures
110  * representing the ASN1. Unfortunately X509_NAME uses a completely different
111  * form and caches encodings so we have to process the internal form and
112  * convert to the external form.
113  */
114
115 static const ASN1_EXTERN_FUNCS x509_name_ff = {
116     NULL,
117     x509_name_ex_new,
118     x509_name_ex_free,
119     0,                          /* Default clear behaviour is OK */
120     x509_name_ex_d2i,
121     x509_name_ex_i2d,
122     x509_name_ex_print
123 };
124
125 IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
126
127 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
128
129 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
130
131 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
132 {
133     X509_NAME *ret = OPENSSL_zalloc(sizeof(*ret));
134
135     if (ret == NULL)
136         goto memerr;
137     if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
138         goto memerr;
139     if ((ret->bytes = BUF_MEM_new()) == NULL)
140         goto memerr;
141     ret->modified = 1;
142     *val = (ASN1_VALUE *)ret;
143     return 1;
144
145  memerr:
146     ASN1err(ASN1_F_X509_NAME_EX_NEW, ERR_R_MALLOC_FAILURE);
147     if (ret) {
148         sk_X509_NAME_ENTRY_free(ret->entries);
149         OPENSSL_free(ret);
150     }
151     return 0;
152 }
153
154 static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
155 {
156     X509_NAME *a;
157
158     if (!pval || !*pval)
159         return;
160     a = (X509_NAME *)*pval;
161
162     BUF_MEM_free(a->bytes);
163     sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
164     OPENSSL_free(a->canon_enc);
165     OPENSSL_free(a);
166     *pval = NULL;
167 }
168
169 static int x509_name_ex_d2i(ASN1_VALUE **val,
170                             const unsigned char **in, long len,
171                             const ASN1_ITEM *it, int tag, int aclass,
172                             char opt, ASN1_TLC *ctx)
173 {
174     const unsigned char *p = *in, *q;
175     union {
176         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
177         ASN1_VALUE *a;
178     } intname = {
179         NULL
180     };
181     union {
182         X509_NAME *x;
183         ASN1_VALUE *a;
184     } nm = {
185         NULL
186     };
187     int i, j, ret;
188     STACK_OF(X509_NAME_ENTRY) *entries;
189     X509_NAME_ENTRY *entry;
190     q = p;
191
192     /* Get internal representation of Name */
193     ret = ASN1_item_ex_d2i(&intname.a,
194                            &p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
195                            tag, aclass, opt, ctx);
196
197     if (ret <= 0)
198         return ret;
199
200     if (*val)
201         x509_name_ex_free(val, NULL);
202     if (!x509_name_ex_new(&nm.a, NULL))
203         goto err;
204     /* We've decoded it: now cache encoding */
205     if (!BUF_MEM_grow(nm.x->bytes, p - q))
206         goto err;
207     memcpy(nm.x->bytes->data, q, p - q);
208
209     /* Convert internal representation to X509_NAME structure */
210     for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
211         entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
212         for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
213             entry = sk_X509_NAME_ENTRY_value(entries, j);
214             entry->set = i;
215             if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
216                 goto err;
217         }
218         sk_X509_NAME_ENTRY_free(entries);
219     }
220     sk_STACK_OF_X509_NAME_ENTRY_free(intname.s);
221     ret = x509_name_canon(nm.x);
222     if (!ret)
223         goto err;
224     nm.x->modified = 0;
225     *val = nm.a;
226     *in = p;
227     return ret;
228  err:
229     X509_NAME_free(nm.x);
230     ASN1err(ASN1_F_X509_NAME_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
231     return 0;
232 }
233
234 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
235                             const ASN1_ITEM *it, int tag, int aclass)
236 {
237     int ret;
238     X509_NAME *a = (X509_NAME *)*val;
239     if (a->modified) {
240         ret = x509_name_encode(a);
241         if (ret < 0)
242             return ret;
243         ret = x509_name_canon(a);
244         if (ret < 0)
245             return ret;
246     }
247     ret = a->bytes->length;
248     if (out != NULL) {
249         memcpy(*out, a->bytes->data, ret);
250         *out += ret;
251     }
252     return ret;
253 }
254
255 static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
256 {
257     sk_X509_NAME_ENTRY_free(ne);
258 }
259
260 static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
261 {
262     sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
263 }
264
265 static int x509_name_encode(X509_NAME *a)
266 {
267     union {
268         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
269         ASN1_VALUE *a;
270     } intname = {
271         NULL
272     };
273     int len;
274     unsigned char *p;
275     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
276     X509_NAME_ENTRY *entry;
277     int i, set = -1;
278     intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
279     if (!intname.s)
280         goto memerr;
281     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
282         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
283         if (entry->set != set) {
284             entries = sk_X509_NAME_ENTRY_new_null();
285             if (!entries)
286                 goto memerr;
287             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries))
288                 goto memerr;
289             set = entry->set;
290         }
291         if (!sk_X509_NAME_ENTRY_push(entries, entry))
292             goto memerr;
293     }
294     len = ASN1_item_ex_i2d(&intname.a, NULL,
295                            ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
296     if (!BUF_MEM_grow(a->bytes, len))
297         goto memerr;
298     p = (unsigned char *)a->bytes->data;
299     ASN1_item_ex_i2d(&intname.a,
300                      &p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
301     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
302                                          local_sk_X509_NAME_ENTRY_free);
303     a->modified = 0;
304     return len;
305  memerr:
306     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
307                                          local_sk_X509_NAME_ENTRY_free);
308     ASN1err(ASN1_F_X509_NAME_ENCODE, ERR_R_MALLOC_FAILURE);
309     return -1;
310 }
311
312 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
313                               int indent,
314                               const char *fname, const ASN1_PCTX *pctx)
315 {
316     if (X509_NAME_print_ex(out, (X509_NAME *)*pval,
317                            indent, pctx->nm_flags) <= 0)
318         return 0;
319     return 2;
320 }
321
322 /*
323  * This function generates the canonical encoding of the Name structure. In
324  * it all strings are converted to UTF8, leading, trailing and multiple
325  * spaces collapsed, converted to lower case and the leading SEQUENCE header
326  * removed. In future we could also normalize the UTF8 too. By doing this
327  * comparison of Name structures can be rapidly performed by just using
328  * memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
329  * constraints of type dirName can also be checked with a simple memcmp().
330  */
331
332 static int x509_name_canon(X509_NAME *a)
333 {
334     unsigned char *p;
335     STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
336     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
337     X509_NAME_ENTRY *entry, *tmpentry = NULL;
338     int i, set = -1, ret = 0, len;
339
340     OPENSSL_free(a->canon_enc);
341     a->canon_enc = NULL;
342     /* Special case: empty X509_NAME => null encoding */
343     if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
344         a->canon_enclen = 0;
345         return 1;
346     }
347     intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
348     if (!intname)
349         goto err;
350     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
351         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
352         if (entry->set != set) {
353             entries = sk_X509_NAME_ENTRY_new_null();
354             if (!entries)
355                 goto err;
356             if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries))
357                 goto err;
358             set = entry->set;
359         }
360         tmpentry = X509_NAME_ENTRY_new();
361         if (tmpentry == NULL)
362             goto err;
363         tmpentry->object = OBJ_dup(entry->object);
364         if (!asn1_string_canon(tmpentry->value, entry->value))
365             goto err;
366         if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
367             goto err;
368         tmpentry = NULL;
369     }
370
371     /* Finally generate encoding */
372
373     len = i2d_name_canon(intname, NULL);
374     if (len < 0)
375         goto err;
376     a->canon_enclen = len;
377
378     p = OPENSSL_malloc(a->canon_enclen);
379
380     if (p == NULL)
381         goto err;
382
383     a->canon_enc = p;
384
385     i2d_name_canon(intname, &p);
386
387     ret = 1;
388
389  err:
390
391     X509_NAME_ENTRY_free(tmpentry);
392     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
393                                          local_sk_X509_NAME_ENTRY_pop_free);
394     return ret;
395 }
396
397 /* Bitmap of all the types of string that will be canonicalized. */
398
399 #define ASN1_MASK_CANON \
400         (B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
401         | B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
402         | B_ASN1_VISIBLESTRING)
403
404 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
405 {
406     unsigned char *to, *from;
407     int len, i;
408
409     /* If type not in bitmask just copy string across */
410     if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
411         if (!ASN1_STRING_copy(out, in))
412             return 0;
413         return 1;
414     }
415
416     out->type = V_ASN1_UTF8STRING;
417     out->length = ASN1_STRING_to_UTF8(&out->data, in);
418     if (out->length == -1)
419         return 0;
420
421     to = out->data;
422     from = to;
423
424     len = out->length;
425
426     /*
427      * Convert string in place to canonical form. Ultimately we may need to
428      * handle a wider range of characters but for now ignore anything with
429      * MSB set and rely on the isspace() and tolower() functions.
430      */
431
432     /* Ignore leading spaces */
433     while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
434         from++;
435         len--;
436     }
437
438     to = from + len - 1;
439
440     /* Ignore trailing spaces */
441     while ((len > 0) && !(*to & 0x80) && isspace(*to)) {
442         to--;
443         len--;
444     }
445
446     to = out->data;
447
448     i = 0;
449     while (i < len) {
450         /* If MSB set just copy across */
451         if (*from & 0x80) {
452             *to++ = *from++;
453             i++;
454         }
455         /* Collapse multiple spaces */
456         else if (isspace(*from)) {
457             /* Copy one space across */
458             *to++ = ' ';
459             /*
460              * Ignore subsequent spaces. Note: don't need to check len here
461              * because we know the last character is a non-space so we can't
462              * overflow.
463              */
464             do {
465                 from++;
466                 i++;
467             }
468             while (!(*from & 0x80) && isspace(*from));
469         } else {
470             *to++ = tolower(*from);
471             from++;
472             i++;
473         }
474     }
475
476     out->length = to - out->data;
477
478     return 1;
479
480 }
481
482 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
483                           unsigned char **in)
484 {
485     int i, len, ltmp;
486     ASN1_VALUE *v;
487     STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
488
489     len = 0;
490     for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
491         v = sk_ASN1_VALUE_value(intname, i);
492         ltmp = ASN1_item_ex_i2d(&v, in,
493                                 ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
494         if (ltmp < 0)
495             return ltmp;
496         len += ltmp;
497     }
498     return len;
499 }
500
501 int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
502 {
503     X509_NAME *in;
504
505     if (!xn || !name)
506         return (0);
507
508     if (*xn != name) {
509         in = X509_NAME_dup(name);
510         if (in != NULL) {
511             X509_NAME_free(*xn);
512             *xn = in;
513         }
514     }
515     return (*xn != NULL);
516 }
517
518 int X509_NAME_print(BIO *bp, X509_NAME *name, int obase)
519 {
520     char *s, *c, *b;
521     int l, i;
522
523     l = 80 - 2 - obase;
524
525     b = X509_NAME_oneline(name, NULL, 0);
526     if (!b)
527         return 0;
528     if (!*b) {
529         OPENSSL_free(b);
530         return 1;
531     }
532     s = b + 1;                  /* skip the first slash */
533
534     c = s;
535     for (;;) {
536 #ifndef CHARSET_EBCDIC
537         if (((*s == '/') &&
538              ((s[1] >= 'A') && (s[1] <= 'Z') && ((s[2] == '=') ||
539                                                  ((s[2] >= 'A')
540                                                   && (s[2] <= 'Z')
541                                                   && (s[3] == '='))
542               ))) || (*s == '\0'))
543 #else
544         if (((*s == '/') &&
545              (isupper(s[1]) && ((s[2] == '=') ||
546                                 (isupper(s[2]) && (s[3] == '='))
547               ))) || (*s == '\0'))
548 #endif
549         {
550             i = s - c;
551             if (BIO_write(bp, c, i) != i)
552                 goto err;
553             c = s + 1;          /* skip following slash */
554             if (*s != '\0') {
555                 if (BIO_write(bp, ", ", 2) != 2)
556                     goto err;
557             }
558             l--;
559         }
560         if (*s == '\0')
561             break;
562         s++;
563         l--;
564     }
565
566     OPENSSL_free(b);
567     return 1;
568  err:
569     X509err(X509_F_X509_NAME_PRINT, ERR_R_BUF_LIB);
570     OPENSSL_free(b);
571     return 0;
572 }
573
574 int X509_NAME_get0_der(const unsigned char **pder, size_t *pderlen,
575                        X509_NAME *nm)
576 {
577     /* Make sure encoding is valid */
578     if (i2d_X509_NAME(nm, NULL) <= 0)
579         return 0;
580     if (pder != NULL)
581         *pder = (unsigned char *)nm->bytes->data;
582     if (pderlen != NULL)
583         *pderlen = nm->bytes->length;
584     return 1;
585 }