Copyright consolidation 09/10
[oweals/openssl.git] / crypto / asn1 / a_strex.c
1 /*
2  * Copyright 2000-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 <string.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/crypto.h>
14 #include <openssl/x509.h>
15 #include <openssl/asn1.h>
16
17 #include "charmap.h"
18
19 /*
20  * ASN1_STRING_print_ex() and X509_NAME_print_ex(). Enhanced string and name
21  * printing routines handling multibyte characters, RFC2253 and a host of
22  * other options.
23  */
24
25 #define CHARTYPE_BS_ESC         (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
26
27 #define ESC_FLAGS (ASN1_STRFLGS_ESC_2253 | \
28                   ASN1_STRFLGS_ESC_QUOTE | \
29                   ASN1_STRFLGS_ESC_CTRL | \
30                   ASN1_STRFLGS_ESC_MSB)
31
32 /*
33  * Three IO functions for sending data to memory, a BIO and and a FILE
34  * pointer.
35  */
36 static int send_bio_chars(void *arg, const void *buf, int len)
37 {
38     if (!arg)
39         return 1;
40     if (BIO_write(arg, buf, len) != len)
41         return 0;
42     return 1;
43 }
44
45 #ifndef OPENSSL_NO_STDIO
46 static int send_fp_chars(void *arg, const void *buf, int len)
47 {
48     if (!arg)
49         return 1;
50     if (fwrite(buf, 1, len, arg) != (unsigned int)len)
51         return 0;
52     return 1;
53 }
54 #endif
55
56 typedef int char_io (void *arg, const void *buf, int len);
57
58 /*
59  * This function handles display of strings, one character at a time. It is
60  * passed an unsigned long for each character because it could come from 2 or
61  * even 4 byte forms.
62  */
63
64 static int do_esc_char(unsigned long c, unsigned char flags, char *do_quotes,
65                        char_io *io_ch, void *arg)
66 {
67     unsigned char chflgs, chtmp;
68     char tmphex[HEX_SIZE(long) + 3];
69
70     if (c > 0xffffffffL)
71         return -1;
72     if (c > 0xffff) {
73         BIO_snprintf(tmphex, sizeof tmphex, "\\W%08lX", c);
74         if (!io_ch(arg, tmphex, 10))
75             return -1;
76         return 10;
77     }
78     if (c > 0xff) {
79         BIO_snprintf(tmphex, sizeof tmphex, "\\U%04lX", c);
80         if (!io_ch(arg, tmphex, 6))
81             return -1;
82         return 6;
83     }
84     chtmp = (unsigned char)c;
85     if (chtmp > 0x7f)
86         chflgs = flags & ASN1_STRFLGS_ESC_MSB;
87     else
88         chflgs = char_type[chtmp] & flags;
89     if (chflgs & CHARTYPE_BS_ESC) {
90         /* If we don't escape with quotes, signal we need quotes */
91         if (chflgs & ASN1_STRFLGS_ESC_QUOTE) {
92             if (do_quotes)
93                 *do_quotes = 1;
94             if (!io_ch(arg, &chtmp, 1))
95                 return -1;
96             return 1;
97         }
98         if (!io_ch(arg, "\\", 1))
99             return -1;
100         if (!io_ch(arg, &chtmp, 1))
101             return -1;
102         return 2;
103     }
104     if (chflgs & (ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB)) {
105         BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
106         if (!io_ch(arg, tmphex, 3))
107             return -1;
108         return 3;
109     }
110     /*
111      * If we get this far and do any escaping at all must escape the escape
112      * character itself: backslash.
113      */
114     if (chtmp == '\\' && flags & ESC_FLAGS) {
115         if (!io_ch(arg, "\\\\", 2))
116             return -1;
117         return 2;
118     }
119     if (!io_ch(arg, &chtmp, 1))
120         return -1;
121     return 1;
122 }
123
124 #define BUF_TYPE_WIDTH_MASK     0x7
125 #define BUF_TYPE_CONVUTF8       0x8
126
127 /*
128  * This function sends each character in a buffer to do_esc_char(). It
129  * interprets the content formats and converts to or from UTF8 as
130  * appropriate.
131  */
132
133 static int do_buf(unsigned char *buf, int buflen,
134                   int type, unsigned char flags, char *quotes, char_io *io_ch,
135                   void *arg)
136 {
137     int i, outlen, len;
138     unsigned char orflags, *p, *q;
139     unsigned long c;
140     p = buf;
141     q = buf + buflen;
142     outlen = 0;
143     while (p != q) {
144         if (p == buf && flags & ASN1_STRFLGS_ESC_2253)
145             orflags = CHARTYPE_FIRST_ESC_2253;
146         else
147             orflags = 0;
148         switch (type & BUF_TYPE_WIDTH_MASK) {
149         case 4:
150             c = ((unsigned long)*p++) << 24;
151             c |= ((unsigned long)*p++) << 16;
152             c |= ((unsigned long)*p++) << 8;
153             c |= *p++;
154             break;
155
156         case 2:
157             c = ((unsigned long)*p++) << 8;
158             c |= *p++;
159             break;
160
161         case 1:
162             c = *p++;
163             break;
164
165         case 0:
166             i = UTF8_getc(p, buflen, &c);
167             if (i < 0)
168                 return -1;      /* Invalid UTF8String */
169             p += i;
170             break;
171         default:
172             return -1;          /* invalid width */
173         }
174         if (p == q && flags & ASN1_STRFLGS_ESC_2253)
175             orflags = CHARTYPE_LAST_ESC_2253;
176         if (type & BUF_TYPE_CONVUTF8) {
177             unsigned char utfbuf[6];
178             int utflen;
179             utflen = UTF8_putc(utfbuf, sizeof utfbuf, c);
180             for (i = 0; i < utflen; i++) {
181                 /*
182                  * We don't need to worry about setting orflags correctly
183                  * because if utflen==1 its value will be correct anyway
184                  * otherwise each character will be > 0x7f and so the
185                  * character will never be escaped on first and last.
186                  */
187                 len =
188                     do_esc_char(utfbuf[i], (unsigned char)(flags | orflags),
189                                 quotes, io_ch, arg);
190                 if (len < 0)
191                     return -1;
192                 outlen += len;
193             }
194         } else {
195             len =
196                 do_esc_char(c, (unsigned char)(flags | orflags), quotes,
197                             io_ch, arg);
198             if (len < 0)
199                 return -1;
200             outlen += len;
201         }
202     }
203     return outlen;
204 }
205
206 /* This function hex dumps a buffer of characters */
207
208 static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
209                        int buflen)
210 {
211     static const char hexdig[] = "0123456789ABCDEF";
212     unsigned char *p, *q;
213     char hextmp[2];
214     if (arg) {
215         p = buf;
216         q = buf + buflen;
217         while (p != q) {
218             hextmp[0] = hexdig[*p >> 4];
219             hextmp[1] = hexdig[*p & 0xf];
220             if (!io_ch(arg, hextmp, 2))
221                 return -1;
222             p++;
223         }
224     }
225     return buflen << 1;
226 }
227
228 /*
229  * "dump" a string. This is done when the type is unknown, or the flags
230  * request it. We can either dump the content octets or the entire DER
231  * encoding. This uses the RFC2253 #01234 format.
232  */
233
234 static int do_dump(unsigned long lflags, char_io *io_ch, void *arg,
235                    ASN1_STRING *str)
236 {
237     /*
238      * Placing the ASN1_STRING in a temp ASN1_TYPE allows the DER encoding to
239      * readily obtained
240      */
241     ASN1_TYPE t;
242     unsigned char *der_buf, *p;
243     int outlen, der_len;
244
245     if (!io_ch(arg, "#", 1))
246         return -1;
247     /* If we don't dump DER encoding just dump content octets */
248     if (!(lflags & ASN1_STRFLGS_DUMP_DER)) {
249         outlen = do_hex_dump(io_ch, arg, str->data, str->length);
250         if (outlen < 0)
251             return -1;
252         return outlen + 1;
253     }
254     t.type = str->type;
255     t.value.ptr = (char *)str;
256     der_len = i2d_ASN1_TYPE(&t, NULL);
257     der_buf = OPENSSL_malloc(der_len);
258     if (der_buf == NULL)
259         return -1;
260     p = der_buf;
261     i2d_ASN1_TYPE(&t, &p);
262     outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
263     OPENSSL_free(der_buf);
264     if (outlen < 0)
265         return -1;
266     return outlen + 1;
267 }
268
269 /*
270  * Lookup table to convert tags to character widths, 0 = UTF8 encoded, -1 is
271  * used for non string types otherwise it is the number of bytes per
272  * character
273  */
274
275 static const signed char tag2nbyte[] = {
276     -1, -1, -1, -1, -1,         /* 0-4 */
277     -1, -1, -1, -1, -1,         /* 5-9 */
278     -1, -1, 0, -1,              /* 10-13 */
279     -1, -1, -1, -1,             /* 15-17 */
280     -1, 1, 1,                   /* 18-20 */
281     -1, 1, 1, 1,                /* 21-24 */
282     -1, 1, -1,                  /* 25-27 */
283     4, -1, 2                    /* 28-30 */
284 };
285
286 /*
287  * This is the main function, print out an ASN1_STRING taking note of various
288  * escape and display options. Returns number of characters written or -1 if
289  * an error occurred.
290  */
291
292 static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
293                        ASN1_STRING *str)
294 {
295     int outlen, len;
296     int type;
297     char quotes;
298     unsigned char flags;
299     quotes = 0;
300     /* Keep a copy of escape flags */
301     flags = (unsigned char)(lflags & ESC_FLAGS);
302
303     type = str->type;
304
305     outlen = 0;
306
307     if (lflags & ASN1_STRFLGS_SHOW_TYPE) {
308         const char *tagname;
309         tagname = ASN1_tag2str(type);
310         outlen += strlen(tagname);
311         if (!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1))
312             return -1;
313         outlen++;
314     }
315
316     /* Decide what to do with type, either dump content or display it */
317
318     /* Dump everything */
319     if (lflags & ASN1_STRFLGS_DUMP_ALL)
320         type = -1;
321     /* Ignore the string type */
322     else if (lflags & ASN1_STRFLGS_IGNORE_TYPE)
323         type = 1;
324     else {
325         /* Else determine width based on type */
326         if ((type > 0) && (type < 31))
327             type = tag2nbyte[type];
328         else
329             type = -1;
330         if ((type == -1) && !(lflags & ASN1_STRFLGS_DUMP_UNKNOWN))
331             type = 1;
332     }
333
334     if (type == -1) {
335         len = do_dump(lflags, io_ch, arg, str);
336         if (len < 0)
337             return -1;
338         outlen += len;
339         return outlen;
340     }
341
342     if (lflags & ASN1_STRFLGS_UTF8_CONVERT) {
343         /*
344          * Note: if string is UTF8 and we want to convert to UTF8 then we
345          * just interpret it as 1 byte per character to avoid converting
346          * twice.
347          */
348         if (!type)
349             type = 1;
350         else
351             type |= BUF_TYPE_CONVUTF8;
352     }
353
354     len = do_buf(str->data, str->length, type, flags, &quotes, io_ch, NULL);
355     if (len < 0)
356         return -1;
357     outlen += len;
358     if (quotes)
359         outlen += 2;
360     if (!arg)
361         return outlen;
362     if (quotes && !io_ch(arg, "\"", 1))
363         return -1;
364     if (do_buf(str->data, str->length, type, flags, NULL, io_ch, arg) < 0)
365         return -1;
366     if (quotes && !io_ch(arg, "\"", 1))
367         return -1;
368     return outlen;
369 }
370
371 /* Used for line indenting: print 'indent' spaces */
372
373 static int do_indent(char_io *io_ch, void *arg, int indent)
374 {
375     int i;
376     for (i = 0; i < indent; i++)
377         if (!io_ch(arg, " ", 1))
378             return 0;
379     return 1;
380 }
381
382 #define FN_WIDTH_LN     25
383 #define FN_WIDTH_SN     10
384
385 static int do_name_ex(char_io *io_ch, void *arg, X509_NAME *n,
386                       int indent, unsigned long flags)
387 {
388     int i, prev = -1, orflags, cnt;
389     int fn_opt, fn_nid;
390     ASN1_OBJECT *fn;
391     ASN1_STRING *val;
392     X509_NAME_ENTRY *ent;
393     char objtmp[80];
394     const char *objbuf;
395     int outlen, len;
396     char *sep_dn, *sep_mv, *sep_eq;
397     int sep_dn_len, sep_mv_len, sep_eq_len;
398     if (indent < 0)
399         indent = 0;
400     outlen = indent;
401     if (!do_indent(io_ch, arg, indent))
402         return -1;
403     switch (flags & XN_FLAG_SEP_MASK) {
404     case XN_FLAG_SEP_MULTILINE:
405         sep_dn = "\n";
406         sep_dn_len = 1;
407         sep_mv = " + ";
408         sep_mv_len = 3;
409         break;
410
411     case XN_FLAG_SEP_COMMA_PLUS:
412         sep_dn = ",";
413         sep_dn_len = 1;
414         sep_mv = "+";
415         sep_mv_len = 1;
416         indent = 0;
417         break;
418
419     case XN_FLAG_SEP_CPLUS_SPC:
420         sep_dn = ", ";
421         sep_dn_len = 2;
422         sep_mv = " + ";
423         sep_mv_len = 3;
424         indent = 0;
425         break;
426
427     case XN_FLAG_SEP_SPLUS_SPC:
428         sep_dn = "; ";
429         sep_dn_len = 2;
430         sep_mv = " + ";
431         sep_mv_len = 3;
432         indent = 0;
433         break;
434
435     default:
436         return -1;
437     }
438
439     if (flags & XN_FLAG_SPC_EQ) {
440         sep_eq = " = ";
441         sep_eq_len = 3;
442     } else {
443         sep_eq = "=";
444         sep_eq_len = 1;
445     }
446
447     fn_opt = flags & XN_FLAG_FN_MASK;
448
449     cnt = X509_NAME_entry_count(n);
450     for (i = 0; i < cnt; i++) {
451         if (flags & XN_FLAG_DN_REV)
452             ent = X509_NAME_get_entry(n, cnt - i - 1);
453         else
454             ent = X509_NAME_get_entry(n, i);
455         if (prev != -1) {
456             if (prev == X509_NAME_ENTRY_set(ent)) {
457                 if (!io_ch(arg, sep_mv, sep_mv_len))
458                     return -1;
459                 outlen += sep_mv_len;
460             } else {
461                 if (!io_ch(arg, sep_dn, sep_dn_len))
462                     return -1;
463                 outlen += sep_dn_len;
464                 if (!do_indent(io_ch, arg, indent))
465                     return -1;
466                 outlen += indent;
467             }
468         }
469         prev = X509_NAME_ENTRY_set(ent);
470         fn = X509_NAME_ENTRY_get_object(ent);
471         val = X509_NAME_ENTRY_get_data(ent);
472         fn_nid = OBJ_obj2nid(fn);
473         if (fn_opt != XN_FLAG_FN_NONE) {
474             int objlen, fld_len;
475             if ((fn_opt == XN_FLAG_FN_OID) || (fn_nid == NID_undef)) {
476                 OBJ_obj2txt(objtmp, sizeof objtmp, fn, 1);
477                 fld_len = 0;    /* XXX: what should this be? */
478                 objbuf = objtmp;
479             } else {
480                 if (fn_opt == XN_FLAG_FN_SN) {
481                     fld_len = FN_WIDTH_SN;
482                     objbuf = OBJ_nid2sn(fn_nid);
483                 } else if (fn_opt == XN_FLAG_FN_LN) {
484                     fld_len = FN_WIDTH_LN;
485                     objbuf = OBJ_nid2ln(fn_nid);
486                 } else {
487                     fld_len = 0; /* XXX: what should this be? */
488                     objbuf = "";
489                 }
490             }
491             objlen = strlen(objbuf);
492             if (!io_ch(arg, objbuf, objlen))
493                 return -1;
494             if ((objlen < fld_len) && (flags & XN_FLAG_FN_ALIGN)) {
495                 if (!do_indent(io_ch, arg, fld_len - objlen))
496                     return -1;
497                 outlen += fld_len - objlen;
498             }
499             if (!io_ch(arg, sep_eq, sep_eq_len))
500                 return -1;
501             outlen += objlen + sep_eq_len;
502         }
503         /*
504          * If the field name is unknown then fix up the DER dump flag. We
505          * might want to limit this further so it will DER dump on anything
506          * other than a few 'standard' fields.
507          */
508         if ((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS))
509             orflags = ASN1_STRFLGS_DUMP_ALL;
510         else
511             orflags = 0;
512
513         len = do_print_ex(io_ch, arg, flags | orflags, val);
514         if (len < 0)
515             return -1;
516         outlen += len;
517     }
518     return outlen;
519 }
520
521 /* Wrappers round the main functions */
522
523 int X509_NAME_print_ex(BIO *out, X509_NAME *nm, int indent,
524                        unsigned long flags)
525 {
526     if (flags == XN_FLAG_COMPAT)
527         return X509_NAME_print(out, nm, indent);
528     return do_name_ex(send_bio_chars, out, nm, indent, flags);
529 }
530
531 #ifndef OPENSSL_NO_STDIO
532 int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent,
533                           unsigned long flags)
534 {
535     if (flags == XN_FLAG_COMPAT) {
536         BIO *btmp;
537         int ret;
538         btmp = BIO_new_fp(fp, BIO_NOCLOSE);
539         if (!btmp)
540             return -1;
541         ret = X509_NAME_print(btmp, nm, indent);
542         BIO_free(btmp);
543         return ret;
544     }
545     return do_name_ex(send_fp_chars, fp, nm, indent, flags);
546 }
547 #endif
548
549 int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags)
550 {
551     return do_print_ex(send_bio_chars, out, flags, str);
552 }
553
554 #ifndef OPENSSL_NO_STDIO
555 int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags)
556 {
557     return do_print_ex(send_fp_chars, fp, flags, str);
558 }
559 #endif
560
561 /*
562  * Utility function: convert any string type to UTF8, returns number of bytes
563  * in output string or a negative error code
564  */
565
566 int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in)
567 {
568     ASN1_STRING stmp, *str = &stmp;
569     int mbflag, type, ret;
570     if (!in)
571         return -1;
572     type = in->type;
573     if ((type < 0) || (type > 30))
574         return -1;
575     mbflag = tag2nbyte[type];
576     if (mbflag == -1)
577         return -1;
578     mbflag |= MBSTRING_FLAG;
579     stmp.data = NULL;
580     stmp.length = 0;
581     stmp.flags = 0;
582     ret =
583         ASN1_mbstring_copy(&str, in->data, in->length, mbflag,
584                            B_ASN1_UTF8STRING);
585     if (ret < 0)
586         return ret;
587     *out = stmp.data;
588     return stmp.length;
589 }