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