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