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