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