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