1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.] */
56
57 #include <openssl/asn1.h>
58
59 #include <assert.h>
60 #include <ctype.h>
61 #include <inttypes.h>
62 #include <limits.h>
63 #include <string.h>
64 #include <time.h>
65
66 #include <openssl/bio.h>
67 #include <openssl/bytestring.h>
68 #include <openssl/mem.h>
69
70 #include "../bytestring/internal.h"
71 #include "internal.h"
72
73
74 #define ESC_FLAGS \
75 (ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE | ASN1_STRFLGS_ESC_CTRL | \
76 ASN1_STRFLGS_ESC_MSB)
77
maybe_write(BIO * out,const void * buf,int len)78 static int maybe_write(BIO *out, const void *buf, int len) {
79 // If |out| is NULL, ignore the output but report the length.
80 return out == NULL || BIO_write(out, buf, len) == len;
81 }
82
is_control_character(unsigned char c)83 static int is_control_character(unsigned char c) { return c < 32 || c == 127; }
84
do_esc_char(uint32_t c,unsigned long flags,char * do_quotes,BIO * out,int is_first,int is_last)85 static int do_esc_char(uint32_t c, unsigned long flags, char *do_quotes,
86 BIO *out, int is_first, int is_last) {
87 // |c| is a |uint32_t| because, depending on |ASN1_STRFLGS_UTF8_CONVERT|,
88 // we may be escaping bytes or Unicode codepoints.
89 char buf[16]; // Large enough for "\\W01234567".
90 unsigned char u8 = (unsigned char)c;
91 if (c > 0xffff) {
92 snprintf(buf, sizeof(buf), "\\W%08" PRIX32, c);
93 } else if (c > 0xff) {
94 snprintf(buf, sizeof(buf), "\\U%04" PRIX32, c);
95 } else if ((flags & ASN1_STRFLGS_ESC_MSB) && c > 0x7f) {
96 snprintf(buf, sizeof(buf), "\\%02X", c);
97 } else if ((flags & ASN1_STRFLGS_ESC_CTRL) && is_control_character(c)) {
98 snprintf(buf, sizeof(buf), "\\%02X", c);
99 } else if (flags & ASN1_STRFLGS_ESC_2253) {
100 // See RFC 2253, sections 2.4 and 4.
101 if (c == '\\' || c == '"') {
102 // Quotes and backslashes are always escaped, quoted or not.
103 snprintf(buf, sizeof(buf), "\\%c", (int)c);
104 } else if (c == ',' || c == '+' || c == '<' || c == '>' || c == ';' ||
105 (is_first && (c == ' ' || c == '#')) ||
106 (is_last && (c == ' '))) {
107 if (flags & ASN1_STRFLGS_ESC_QUOTE) {
108 // No need to escape, just tell the caller to quote.
109 if (do_quotes != NULL) {
110 *do_quotes = 1;
111 }
112 return maybe_write(out, &u8, 1) ? 1 : -1;
113 }
114 snprintf(buf, sizeof(buf), "\\%c", (int)c);
115 } else {
116 return maybe_write(out, &u8, 1) ? 1 : -1;
117 }
118 } else if ((flags & ESC_FLAGS) && c == '\\') {
119 // If any escape flags are set, also escape backslashes.
120 snprintf(buf, sizeof(buf), "\\%c", (int)c);
121 } else {
122 return maybe_write(out, &u8, 1) ? 1 : -1;
123 }
124
125 static_assert(sizeof(buf) < INT_MAX, "len may not fit in int");
126 int len = (int)strlen(buf);
127 return maybe_write(out, buf, len) ? len : -1;
128 }
129
130 // This function sends each character in a buffer to do_esc_char(). It
131 // interprets the content formats and converts to or from UTF8 as
132 // appropriate.
133
do_buf(const unsigned char * buf,int buflen,int encoding,unsigned long flags,char * quotes,BIO * out)134 static int do_buf(const unsigned char *buf, int buflen, int encoding,
135 unsigned long flags, char *quotes, BIO *out) {
136 int (*get_char)(CBS *cbs, uint32_t *out);
137 int get_char_error;
138 switch (encoding) {
139 case MBSTRING_UNIV:
140 get_char = CBS_get_utf32_be;
141 get_char_error = ASN1_R_INVALID_UNIVERSALSTRING;
142 break;
143 case MBSTRING_BMP:
144 get_char = CBS_get_ucs2_be;
145 get_char_error = ASN1_R_INVALID_BMPSTRING;
146 break;
147 case MBSTRING_ASC:
148 get_char = CBS_get_latin1;
149 get_char_error = ERR_R_INTERNAL_ERROR; // Should not be possible.
150 break;
151 case MBSTRING_UTF8:
152 get_char = CBS_get_utf8;
153 get_char_error = ASN1_R_INVALID_UTF8STRING;
154 break;
155 default:
156 assert(0);
157 return -1;
158 }
159
160 CBS cbs;
161 CBS_init(&cbs, buf, buflen);
162 int outlen = 0;
163 while (CBS_len(&cbs) != 0) {
164 const int is_first = CBS_data(&cbs) == buf;
165 uint32_t c;
166 if (!get_char(&cbs, &c)) {
167 OPENSSL_PUT_ERROR(ASN1, get_char_error);
168 return -1;
169 }
170 const int is_last = CBS_len(&cbs) == 0;
171 if (flags & ASN1_STRFLGS_UTF8_CONVERT) {
172 uint8_t utf8_buf[6];
173 CBB utf8_cbb;
174 CBB_init_fixed(&utf8_cbb, utf8_buf, sizeof(utf8_buf));
175 if (!CBB_add_utf8(&utf8_cbb, c)) {
176 OPENSSL_PUT_ERROR(ASN1, ERR_R_INTERNAL_ERROR);
177 return 1;
178 }
179 size_t utf8_len = CBB_len(&utf8_cbb);
180 for (size_t i = 0; i < utf8_len; i++) {
181 int len = do_esc_char(utf8_buf[i], flags, quotes, out,
182 is_first && i == 0, is_last && i == utf8_len - 1);
183 if (len < 0) {
184 return -1;
185 }
186 outlen += len;
187 }
188 } else {
189 int len = do_esc_char(c, flags, quotes, out, is_first, is_last);
190 if (len < 0) {
191 return -1;
192 }
193 outlen += len;
194 }
195 }
196 return outlen;
197 }
198
199 // This function hex dumps a buffer of characters
200
do_hex_dump(BIO * out,unsigned char * buf,int buflen)201 static int do_hex_dump(BIO *out, unsigned char *buf, int buflen) {
202 static const char hexdig[] = "0123456789ABCDEF";
203 unsigned char *p, *q;
204 char hextmp[2];
205 if (out) {
206 p = buf;
207 q = buf + buflen;
208 while (p != q) {
209 hextmp[0] = hexdig[*p >> 4];
210 hextmp[1] = hexdig[*p & 0xf];
211 if (!maybe_write(out, hextmp, 2)) {
212 return -1;
213 }
214 p++;
215 }
216 }
217 return buflen << 1;
218 }
219
220 // "dump" a string. This is done when the type is unknown, or the flags
221 // request it. We can either dump the content octets or the entire DER
222 // encoding. This uses the RFC 2253 #01234 format.
223
do_dump(unsigned long flags,BIO * out,const ASN1_STRING * str)224 static int do_dump(unsigned long flags, BIO *out, const ASN1_STRING *str) {
225 if (!maybe_write(out, "#", 1)) {
226 return -1;
227 }
228
229 // If we don't dump DER encoding just dump content octets
230 if (!(flags & ASN1_STRFLGS_DUMP_DER)) {
231 int outlen = do_hex_dump(out, str->data, str->length);
232 if (outlen < 0) {
233 return -1;
234 }
235 return outlen + 1;
236 }
237
238 // Placing the ASN1_STRING in a temporary ASN1_TYPE allows the DER encoding
239 // to readily obtained.
240 ASN1_TYPE t;
241 t.type = str->type;
242 // Negative INTEGER and ENUMERATED values are the only case where
243 // |ASN1_STRING| and |ASN1_TYPE| types do not match.
244 //
245 // TODO(davidben): There are also some type fields which, in |ASN1_TYPE|, do
246 // not correspond to |ASN1_STRING|. It is unclear whether those are allowed
247 // in |ASN1_STRING| at all, or what the space of allowed types is.
248 // |ASN1_item_ex_d2i| will never produce such a value so, for now, we say
249 // this is an invalid input. But this corner of the library in general
250 // should be more robust.
251 if (t.type == V_ASN1_NEG_INTEGER) {
252 t.type = V_ASN1_INTEGER;
253 } else if (t.type == V_ASN1_NEG_ENUMERATED) {
254 t.type = V_ASN1_ENUMERATED;
255 }
256 t.value.asn1_string = (ASN1_STRING *)str;
257 unsigned char *der_buf = NULL;
258 int der_len = i2d_ASN1_TYPE(&t, &der_buf);
259 if (der_len < 0) {
260 return -1;
261 }
262 int outlen = do_hex_dump(out, der_buf, der_len);
263 OPENSSL_free(der_buf);
264 if (outlen < 0) {
265 return -1;
266 }
267 return outlen + 1;
268 }
269
270 // string_type_to_encoding returns the |MBSTRING_*| constant for the encoding
271 // used by the |ASN1_STRING| type |type|, or -1 if |tag| is not a string
272 // type.
string_type_to_encoding(int type)273 static int string_type_to_encoding(int type) {
274 // This function is sometimes passed ASN.1 universal types and sometimes
275 // passed |ASN1_STRING| type values
276 switch (type) {
277 case V_ASN1_UTF8STRING:
278 return MBSTRING_UTF8;
279 case V_ASN1_NUMERICSTRING:
280 case V_ASN1_PRINTABLESTRING:
281 case V_ASN1_T61STRING:
282 case V_ASN1_IA5STRING:
283 case V_ASN1_UTCTIME:
284 case V_ASN1_GENERALIZEDTIME:
285 case V_ASN1_ISO64STRING:
286 // |MBSTRING_ASC| refers to Latin-1, not ASCII.
287 return MBSTRING_ASC;
288 case V_ASN1_UNIVERSALSTRING:
289 return MBSTRING_UNIV;
290 case V_ASN1_BMPSTRING:
291 return MBSTRING_BMP;
292 }
293 return -1;
294 }
295
296 // This is the main function, print out an ASN1_STRING taking note of various
297 // escape and display options. Returns number of characters written or -1 if
298 // an error occurred.
299
ASN1_STRING_print_ex(BIO * out,const ASN1_STRING * str,unsigned long flags)300 int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str,
301 unsigned long flags) {
302 int type = str->type;
303 int outlen = 0;
304 if (flags & ASN1_STRFLGS_SHOW_TYPE) {
305 const char *tagname = ASN1_tag2str(type);
306 outlen += strlen(tagname);
307 if (!maybe_write(out, tagname, outlen) || !maybe_write(out, ":", 1)) {
308 return -1;
309 }
310 outlen++;
311 }
312
313 // Decide what to do with |str|, either dump the contents or display it.
314 int encoding;
315 if (flags & ASN1_STRFLGS_DUMP_ALL) {
316 // Dump everything.
317 encoding = -1;
318 } else if (flags & ASN1_STRFLGS_IGNORE_TYPE) {
319 // Ignore the string type and interpret the contents as Latin-1.
320 encoding = MBSTRING_ASC;
321 } else {
322 encoding = string_type_to_encoding(type);
323 if (encoding == -1 && (flags & ASN1_STRFLGS_DUMP_UNKNOWN) == 0) {
324 encoding = MBSTRING_ASC;
325 }
326 }
327
328 if (encoding == -1) {
329 int len = do_dump(flags, out, str);
330 if (len < 0) {
331 return -1;
332 }
333 outlen += len;
334 return outlen;
335 }
336
337 // Measure the length.
338 char quotes = 0;
339 int len = do_buf(str->data, str->length, encoding, flags, "es, NULL);
340 if (len < 0) {
341 return -1;
342 }
343 outlen += len;
344 if (quotes) {
345 outlen += 2;
346 }
347 if (!out) {
348 return outlen;
349 }
350
351 // Encode the value.
352 if ((quotes && !maybe_write(out, "\"", 1)) ||
353 do_buf(str->data, str->length, encoding, flags, NULL, out) < 0 ||
354 (quotes && !maybe_write(out, "\"", 1))) {
355 return -1;
356 }
357 return outlen;
358 }
359
ASN1_STRING_print_ex_fp(FILE * fp,const ASN1_STRING * str,unsigned long flags)360 int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str,
361 unsigned long flags) {
362 BIO *bio = NULL;
363 if (fp != NULL) {
364 // If |fp| is NULL, this function returns the number of bytes without
365 // writing.
366 bio = BIO_new_fp(fp, BIO_NOCLOSE);
367 if (bio == NULL) {
368 return -1;
369 }
370 }
371 int ret = ASN1_STRING_print_ex(bio, str, flags);
372 BIO_free(bio);
373 return ret;
374 }
375
ASN1_STRING_to_UTF8(unsigned char ** out,const ASN1_STRING * in)376 int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in) {
377 if (!in) {
378 return -1;
379 }
380 int mbflag = string_type_to_encoding(in->type);
381 if (mbflag == -1) {
382 OPENSSL_PUT_ERROR(ASN1, ASN1_R_UNKNOWN_TAG);
383 return -1;
384 }
385 ASN1_STRING stmp, *str = &stmp;
386 stmp.data = NULL;
387 stmp.length = 0;
388 stmp.flags = 0;
389 int ret =
390 ASN1_mbstring_copy(&str, in->data, in->length, mbflag, B_ASN1_UTF8STRING);
391 if (ret < 0) {
392 return ret;
393 }
394 *out = stmp.data;
395 return stmp.length;
396 }
397
ASN1_STRING_print(BIO * bp,const ASN1_STRING * v)398 int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) {
399 int i, n;
400 char buf[80];
401 const char *p;
402
403 if (v == NULL) {
404 return 0;
405 }
406 n = 0;
407 p = (const char *)v->data;
408 for (i = 0; i < v->length; i++) {
409 if ((p[i] > '~') || ((p[i] < ' ') && (p[i] != '\n') && (p[i] != '\r'))) {
410 buf[n] = '.';
411 } else {
412 buf[n] = p[i];
413 }
414 n++;
415 if (n >= 80) {
416 if (BIO_write(bp, buf, n) <= 0) {
417 return 0;
418 }
419 n = 0;
420 }
421 }
422 if (n > 0) {
423 if (BIO_write(bp, buf, n) <= 0) {
424 return 0;
425 }
426 }
427 return 1;
428 }
429
ASN1_TIME_print(BIO * bp,const ASN1_TIME * tm)430 int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm) {
431 if (tm->type == V_ASN1_UTCTIME) {
432 return ASN1_UTCTIME_print(bp, tm);
433 }
434 if (tm->type == V_ASN1_GENERALIZEDTIME) {
435 return ASN1_GENERALIZEDTIME_print(bp, tm);
436 }
437 BIO_puts(bp, "Bad time value");
438 return 0;
439 }
440
441 static const char *const mon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
442 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
443
ASN1_GENERALIZEDTIME_print(BIO * bp,const ASN1_GENERALIZEDTIME * tm)444 int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) {
445 CBS cbs;
446 CBS_init(&cbs, tm->data, tm->length);
447 struct tm utc;
448 if (!CBS_parse_generalized_time(&cbs, &utc, /*allow_timezone_offset=*/0)) {
449 BIO_puts(bp, "Bad time value");
450 return 0;
451 }
452
453 return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon],
454 utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec,
455 utc.tm_year + 1900) > 0;
456 }
457
ASN1_UTCTIME_print(BIO * bp,const ASN1_UTCTIME * tm)458 int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) {
459 CBS cbs;
460 CBS_init(&cbs, tm->data, tm->length);
461 struct tm utc;
462 if (!CBS_parse_utc_time(&cbs, &utc, /*allow_timezone_offset=*/0)) {
463 BIO_puts(bp, "Bad time value");
464 return 0;
465 }
466
467 return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d GMT", mon[utc.tm_mon],
468 utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec,
469 utc.tm_year + 1900) > 0;
470 }
471