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