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