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