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