xref: /plan9/sys/src/libsec/port/x509.c (revision ec59a3ddbfceee0efe34584c2c9981a5e5ff1ec4)
1 #include <u.h>
2 #include <libc.h>
3 #include <mp.h>
4 #include <libsec.h>
5 
6 typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
7 
8 /* ANSI offsetof, backwards. */
9 #define	OFFSETOF(a, b)	offsetof(b, a)
10 
11 /*=============================================================*/
12 /*  general ASN1 declarations and parsing
13  *
14  *  For now, this is used only for extracting the key from an
15  *  X509 certificate, so the entire collection is hidden.  But
16  *  someday we should probably make the functions visible and
17  *  give them their own man page.
18  */
19 typedef struct Elem Elem;
20 typedef struct Tag Tag;
21 typedef struct Value Value;
22 typedef struct Bytes Bytes;
23 typedef struct Ints Ints;
24 typedef struct Bits Bits;
25 typedef struct Elist Elist;
26 
27 /* tag classes */
28 #define Universal 0
29 #define Context 0x80
30 
31 /* universal tags */
32 #define BOOLEAN 1
33 #define INTEGER 2
34 #define BIT_STRING 3
35 #define OCTET_STRING 4
36 #define NULLTAG 5
37 #define OBJECT_ID 6
38 #define ObjectDescriptor 7
39 #define EXTERNAL 8
40 #define REAL 9
41 #define ENUMERATED 10
42 #define EMBEDDED_PDV 11
43 #define SEQUENCE 16		/* also SEQUENCE OF */
44 #define SETOF 17				/* also SETOF OF */
45 #define NumericString 18
46 #define PrintableString 19
47 #define TeletexString 20
48 #define VideotexString 21
49 #define IA5String 22
50 #define UTCTime 23
51 #define GeneralizedTime 24
52 #define GraphicString 25
53 #define VisibleString 26
54 #define GeneralString 27
55 #define UniversalString 28
56 #define BMPString 30
57 
58 struct Bytes {
59 	int	len;
60 	uchar	data[1];
61 };
62 
63 struct Ints {
64 	int	len;
65 	int	data[1];
66 };
67 
68 struct Bits {
69 	int	len;		/* number of bytes */
70 	int	unusedbits;	/* unused bits in last byte */
71 	uchar	data[1];	/* most-significant bit first */
72 };
73 
74 struct Tag {
75 	int	class;
76 	int	num;
77 };
78 
79 enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
80 	VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
81 struct Value {
82 	int	tag;		/* VBool, etc. */
83 	union {
84 		int	boolval;
85 		int	intval;
86 		Bytes*	octetsval;
87 		Bytes*	bigintval;
88 		Bytes*	realval;	/* undecoded; hardly ever used */
89 		Bytes*	otherval;
90 		Bits*	bitstringval;
91 		Ints*	objidval;
92 		char*	stringval;
93 		Elist*	seqval;
94 		Elist*	setval;
95 	} u;  /* (Don't use anonymous unions, for ease of porting) */
96 };
97 
98 struct Elem {
99 	Tag	tag;
100 	Value	val;
101 };
102 
103 struct Elist {
104 	Elist*	tl;
105 	Elem	hd;
106 };
107 
108 /* decoding errors */
109 enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
110 		ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
111 
112 
113 /* here are the functions to consider making extern someday */
114 static Bytes*	newbytes(int len);
115 static Bytes*	makebytes(uchar* buf, int len);
116 static void	freebytes(Bytes* b);
117 static Bytes*	catbytes(Bytes* b1, Bytes* b2);
118 static Ints*	newints(int len);
119 static Ints*	makeints(int* buf, int len);
120 static void	freeints(Ints* b);
121 static Bits*	newbits(int len);
122 static Bits*	makebits(uchar* buf, int len, int unusedbits);
123 static void	freebits(Bits* b);
124 static Elist*	mkel(Elem e, Elist* tail);
125 static void	freeelist(Elist* el);
126 static int	elistlen(Elist* el);
127 static int	is_seq(Elem* pe, Elist** pseq);
128 static int	is_set(Elem* pe, Elist** pset);
129 static int	is_int(Elem* pe, int* pint);
130 static int	is_bigint(Elem* pe, Bytes** pbigint);
131 static int	is_bitstring(Elem* pe, Bits** pbits);
132 static int	is_octetstring(Elem* pe, Bytes** poctets);
133 static int	is_oid(Elem* pe, Ints** poid);
134 static int	is_string(Elem* pe, char** pstring);
135 static int	is_time(Elem* pe, char** ptime);
136 static int	decode(uchar* a, int alen, Elem* pelem);
137 static int	decode_seq(uchar* a, int alen, Elist** pelist);
138 static int	decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
139 static int	encode(Elem e, Bytes** pbytes);
140 static int	oid_lookup(Ints* o, Ints** tab);
141 static void	freevalfields(Value* v);
142 static mpint	*asn1mpint(Elem *e);
143 
144 
145 
146 #define TAG_MASK 0x1F
147 #define CONSTR_MASK 0x20
148 #define CLASS_MASK 0xC0
149 #define MAXOBJIDLEN 20
150 
151 static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
152 static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
153 static int length_decode(uchar** pp, uchar* pend, int* plength);
154 static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
155 static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
156 static int uint7_decode(uchar** pp, uchar* pend, int* pint);
157 static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
158 static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
159 static int enc(uchar** pp, Elem e, int lenonly);
160 static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
161 static void uint7_enc(uchar** pp, int num, int lenonly);
162 static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
163 
164 static void *
165 emalloc(int n)
166 {
167 	void *p;
168 	if(n==0)
169 		n=1;
170 	p = malloc(n);
171 	if(p == nil){
172 		exits("out of memory");
173 	}
174 	memset(p, 0, n);
175 	setmalloctag(p, getcallerpc(&n));
176 	return p;
177 }
178 
179 static char*
180 estrdup(char *s)
181 {
182 	char *d, *d0;
183 
184 	if(!s)
185 		return 0;
186 	d = d0 = emalloc(strlen(s)+1);
187 	while(*d++ = *s++)
188 		;
189 	return d0;
190 }
191 
192 
193 /*
194  * Decode a[0..len] as a BER encoding of an ASN1 type.
195  * The return value is one of ASN_OK, etc.
196  * Depending on the error, the returned elem may or may not
197  * be nil.
198  */
199 static int
200 decode(uchar* a, int alen, Elem* pelem)
201 {
202 	uchar* p = a;
203 
204 	return  ber_decode(&p, &a[alen], pelem);
205 }
206 
207 /*
208  * Like decode, but continue decoding after first element
209  * of array ends.
210  */
211 static int
212 decode_seq(uchar* a, int alen, Elist** pelist)
213 {
214 	uchar* p = a;
215 
216 	return seq_decode(&p, &a[alen], -1, 1, pelist);
217 }
218 
219 /*
220  * Decode the whole array as a BER encoding of an ASN1 value,
221  * (i.e., the part after the tag and length).
222  * Assume the value is encoded as universal tag "kind".
223  * The constr arg is 1 if the value is constructed, 0 if primitive.
224  * If there's an error, the return string will contain the error.
225  * Depending on the error, the returned value may or may not
226  * be nil.
227  */
228 static int
229 decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
230 {
231 	uchar* p = a;
232 
233 	return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
234 }
235 
236 /*
237  * All of the following decoding routines take arguments:
238  *	uchar **pp;
239  *	uchar *pend;
240  * Where parsing is supposed to start at **pp, and when parsing
241  * is done, *pp is updated to point at next char to be parsed.
242  * The pend pointer is just past end of string; an error should
243  * be returned parsing hasn't finished by then.
244  *
245  * The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
246  * The remaining argument(s) are pointers to where parsed entity goes.
247  */
248 
249 /* Decode an ASN1 'Elem' (tag, length, value) */
250 static int
251 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
252 {
253 	int err;
254 	int isconstr;
255 	int length;
256 	Tag tag;
257 	Value val;
258 
259 	err = tag_decode(pp, pend, &tag, &isconstr);
260 	if(err == ASN_OK) {
261 		err = length_decode(pp, pend, &length);
262 		if(err == ASN_OK) {
263 			if(tag.class == Universal) {
264 				err = value_decode(pp, pend, length, tag.num, isconstr, &val);
265 				if(val.tag == VSeq || val.tag == VSet)
266 					setmalloctag(val.u.seqval, getcallerpc(&pp));
267 			}else
268 				err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
269 			if(err == ASN_OK) {
270 				pelem->tag = tag;
271 				pelem->val = val;
272 			}
273 		}
274 	}
275 	return err;
276 }
277 
278 /* Decode a tag field */
279 static int
280 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
281 {
282 	int err;
283 	int v;
284 	uchar* p;
285 
286 	err = ASN_OK;
287 	p = *pp;
288 	if(pend-p >= 2) {
289 		v = *p++;
290 		ptag->class = v&CLASS_MASK;
291 		if(v&CONSTR_MASK)
292 			*pisconstr = 1;
293 		else
294 			*pisconstr = 0;
295 		v &= TAG_MASK;
296 		if(v == TAG_MASK)
297 			err = uint7_decode(&p, pend, &v);
298 		ptag->num = v;
299 	}
300 	else
301 		err = ASN_ESHORT;
302 	*pp = p;
303 	return err;
304 }
305 
306 /* Decode a length field */
307 static int
308 length_decode(uchar** pp, uchar* pend, int* plength)
309 {
310 	int err;
311 	int num;
312 	int v;
313 	uchar* p;
314 
315 	err = ASN_OK;
316 	num = 0;
317 	p = *pp;
318 	if(p < pend) {
319 		v = *p++;
320 		if(v&0x80)
321 			err = int_decode(&p, pend, v&0x7F, 1, &num);
322 		else
323 			num = v;
324 	}
325 	else
326 		err = ASN_ESHORT;
327 	*pp = p;
328 	*plength = num;
329 	return err;
330 }
331 
332 /* Decode a value field  */
333 static int
334 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
335 {
336 	int err;
337 	Bytes* va;
338 	int num;
339 	int bitsunused;
340 	int subids[MAXOBJIDLEN];
341 	int isubid;
342 	Elist*	vl;
343 	uchar* p;
344 	uchar* pe;
345 
346 	err = ASN_OK;
347 	p = *pp;
348 	if(length == -1) {	/* "indefinite" length spec */
349 		if(!isconstr)
350 			err = ASN_EINVAL;
351 	}
352 	else if(p + length > pend)
353 		err = ASN_EVALLEN;
354 	if(err != ASN_OK)
355 		return err;
356 
357 	switch(kind) {
358 	case 0:
359 		/* marker for end of indefinite constructions */
360 		if(length == 0)
361 			pval->tag = VNull;
362 		else
363 			err = ASN_EINVAL;
364 		break;
365 
366 	case BOOLEAN:
367 		if(isconstr)
368 			err = ASN_ECONSTR;
369 		else if(length != 1)
370 			err = ASN_EVALLEN;
371 		else {
372 			pval->tag = VBool;
373 			pval->u.boolval = (*p++ != 0);
374 		}
375 		break;
376 
377 	case INTEGER:
378 	case ENUMERATED:
379 		if(isconstr)
380 			err = ASN_ECONSTR;
381 		else if(length <= 4) {
382 			err = int_decode(&p, pend, length, 0, &num);
383 			if(err == ASN_OK) {
384 				pval->tag = VInt;
385 				pval->u.intval = num;
386 			}
387 		}
388 		else {
389 			pval->tag = VBigInt;
390 			pval->u.bigintval = makebytes(p, length);
391 			p += length;
392 		}
393 		break;
394 
395 	case BIT_STRING:
396 		pval->tag = VBitString;
397 		if(isconstr) {
398 			if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
399 				pval->u.bitstringval = makebits(0, 0, 0);
400 				p += 2;
401 			}
402 			else
403 				/* TODO: recurse and concat results */
404 				err = ASN_EUNIMPL;
405 		}
406 		else {
407 			if(length < 2) {
408 				if(length == 1 && *p == 0) {
409 					pval->u.bitstringval = makebits(0, 0, 0);
410 					p++;
411 				}
412 				else
413 					err = ASN_EINVAL;
414 			}
415 			else {
416 				bitsunused = *p;
417 				if(bitsunused > 7)
418 					err = ASN_EINVAL;
419 				else if(length > 0x0FFFFFFF)
420 					err = ASN_ETOOBIG;
421 				else {
422 					pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
423 					p += length;
424 				}
425 			}
426 		}
427 		break;
428 
429 	case OCTET_STRING:
430 	case ObjectDescriptor:
431 		err = octet_decode(&p, pend, length, isconstr, &va);
432 		if(err == ASN_OK) {
433 			pval->tag = VOctets;
434 			pval->u.octetsval = va;
435 		}
436 		break;
437 
438 	case NULLTAG:
439 		if(isconstr)
440 			err = ASN_ECONSTR;
441 		else if(length != 0)
442 			err = ASN_EVALLEN;
443 		else
444 			pval->tag = VNull;
445 		break;
446 
447 	case OBJECT_ID:
448 		if(isconstr)
449 			err = ASN_ECONSTR;
450 		else if(length == 0)
451 			err = ASN_EVALLEN;
452 		else {
453 			isubid = 0;
454 			pe = p+length;
455 			while(p < pe && isubid < MAXOBJIDLEN) {
456 				err = uint7_decode(&p, pend, &num);
457 				if(err != ASN_OK)
458 					break;
459 				if(isubid == 0) {
460 					subids[isubid++] = num / 40;
461 					subids[isubid++] = num % 40;
462 				}
463 				else
464 					subids[isubid++] = num;
465 			}
466 			if(err == ASN_OK) {
467 				if(p != pe)
468 					err = ASN_EVALLEN;
469 				else {
470 					pval->tag = VObjId;
471 					pval->u.objidval = makeints(subids, isubid);
472 				}
473 			}
474 		}
475 		break;
476 
477 	case EXTERNAL:
478 	case EMBEDDED_PDV:
479 		/* TODO: parse this internally */
480 		if(p+length > pend)
481 			err = ASN_EVALLEN;
482 		else {
483 			pval->tag = VOther;
484 			pval->u.otherval = makebytes(p, length);
485 			p += length;
486 		}
487 		break;
488 
489 	case REAL:
490 		/* Let the application decode */
491 		if(isconstr)
492 			err = ASN_ECONSTR;
493 		else if(p+length > pend)
494 			err = ASN_EVALLEN;
495 		else {
496 			pval->tag = VReal;
497 			pval->u.realval = makebytes(p, length);
498 			p += length;
499 		}
500 		break;
501 
502 	case SEQUENCE:
503 		err = seq_decode(&p, pend, length, isconstr, &vl);
504 		setmalloctag(vl, getcallerpc(&pp));
505 		if(err == ASN_OK) {
506 			pval->tag = VSeq ;
507 			pval->u.seqval = vl;
508 		}
509 		break;
510 
511 	case SETOF:
512 		err = seq_decode(&p, pend, length, isconstr, &vl);
513 		setmalloctag(vl, getcallerpc(&pp));
514 		if(err == ASN_OK) {
515 			pval->tag = VSet;
516 			pval->u.setval = vl;
517 		}
518 		break;
519 
520 	case NumericString:
521 	case PrintableString:
522 	case TeletexString:
523 	case VideotexString:
524 	case IA5String:
525 	case UTCTime:
526 	case GeneralizedTime:
527 	case GraphicString:
528 	case VisibleString:
529 	case GeneralString:
530 	case UniversalString:
531 	case BMPString:
532 		/* TODO: figure out when character set conversion is necessary */
533 		err = octet_decode(&p, pend, length, isconstr, &va);
534 		if(err == ASN_OK) {
535 			pval->tag = VString;
536 			pval->u.stringval = (char*)emalloc(va->len+1);
537 			memmove(pval->u.stringval, va->data, va->len);
538 			pval->u.stringval[va->len] = 0;
539 			free(va);
540 		}
541 		break;
542 
543 	default:
544 		if(p+length > pend)
545 			err = ASN_EVALLEN;
546 		else {
547 			pval->tag = VOther;
548 			pval->u.otherval = makebytes(p, length);
549 			p += length;
550 		}
551 		break;
552 	}
553 	*pp = p;
554 	return err;
555 }
556 
557 /*
558  * Decode an int in format where count bytes are
559  * concatenated to form value.
560  * Although ASN1 allows any size integer, we return
561  * an error if the result doesn't fit in a 32-bit int.
562  * If unsgned is not set, make sure to propagate sign bit.
563  */
564 static int
565 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
566 {
567 	int err;
568 	int num;
569 	uchar* p;
570 
571 	p = *pp;
572 	err = ASN_OK;
573 	num = 0;
574 	if(p+count <= pend) {
575 		if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
576 			err = ASN_ETOOBIG;
577 		else {
578 			if(!unsgned && count > 0 && count < 4 && (*p&0x80))
579 				num = -1;		// set all bits, initially
580 			while(count--)
581 				num = (num << 8)|(*p++);
582 		}
583 	}
584 	else
585 		err = ASN_ESHORT;
586 	*pint = num;
587 	*pp = p;
588 	return err;
589 }
590 
591 /*
592  * Decode an unsigned int in format where each
593  * byte except last has high bit set, and remaining
594  * seven bits of each byte are concatenated to form value.
595  * Although ASN1 allows any size integer, we return
596  * an error if the result doesn't fit in a 32 bit int.
597  */
598 static int
599 uint7_decode(uchar** pp, uchar* pend, int* pint)
600 {
601 	int err;
602 	int num;
603 	int more;
604 	int v;
605 	uchar* p;
606 
607 	p = *pp;
608 	err = ASN_OK;
609 	num = 0;
610 	more = 1;
611 	while(more && p < pend) {
612 		v = *p++;
613 		if(num&0x7F000000) {
614 			err = ASN_ETOOBIG;
615 			break;
616 		}
617 		num <<= 7;
618 		more = v&0x80;
619 		num |= (v&0x7F);
620 	}
621 	if(p == pend)
622 		err = ASN_ESHORT;
623 	*pint = num;
624 	*pp = p;
625 	return err;
626 }
627 
628 /*
629  * Decode an octet string, recursively if isconstr.
630  * We've already checked that length==-1 implies isconstr==1,
631  * and otherwise that specified length fits within (*pp..pend)
632  */
633 static int
634 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
635 {
636 	int err;
637 	uchar* p;
638 	Bytes* ans;
639 	Bytes* newans;
640 	uchar* pstart;
641 	uchar* pold;
642 	Elem	elem;
643 
644 	err = ASN_OK;
645 	p = *pp;
646 	ans = nil;
647 	if(length >= 0 && !isconstr) {
648 		ans = makebytes(p, length);
649 		p += length;
650 	}
651 	else {
652 		/* constructed, either definite or indefinite length */
653 		pstart = p;
654 		for(;;) {
655 			if(length >= 0 && p >= pstart + length) {
656 				if(p != pstart + length)
657 					err = ASN_EVALLEN;
658 				break;
659 			}
660 			pold = p;
661 			err = ber_decode(&p, pend, &elem);
662 			if(err != ASN_OK)
663 				break;
664 			switch(elem.val.tag) {
665 			case VOctets:
666 				newans = catbytes(ans, elem.val.u.octetsval);
667 				freebytes(ans);
668 				ans = newans;
669 				break;
670 
671 			case VEOC:
672 				if(length != -1) {
673 					p = pold;
674 					err = ASN_EINVAL;
675 				}
676 				goto cloop_done;
677 
678 			default:
679 				p = pold;
680 				err = ASN_EINVAL;
681 				goto cloop_done;
682 			}
683 		}
684 cloop_done:
685 		;
686 	}
687 	*pp = p;
688 	*pbytes = ans;
689 	return err;
690 }
691 
692 /*
693  * Decode a sequence or set.
694  * We've already checked that length==-1 implies isconstr==1,
695  * and otherwise that specified length fits within (*p..pend)
696  */
697 static int
698 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
699 {
700 	int err;
701 	uchar* p;
702 	uchar* pstart;
703 	uchar* pold;
704 	Elist* ans;
705 	Elem elem;
706 	Elist* lve;
707 	Elist* lveold;
708 
709 	err = ASN_OK;
710 	ans = nil;
711 	p = *pp;
712 	if(!isconstr)
713 		err = ASN_EPRIM;
714 	else {
715 		/* constructed, either definite or indefinite length */
716 		lve = nil;
717 		pstart = p;
718 		for(;;) {
719 			if(length >= 0 && p >= pstart + length) {
720 				if(p != pstart + length)
721 					err = ASN_EVALLEN;
722 				break;
723 			}
724 			pold = p;
725 			err = ber_decode(&p, pend, &elem);
726 			if(err != ASN_OK)
727 				break;
728 			if(elem.val.tag == VEOC) {
729 				if(length != -1) {
730 					p = pold;
731 					err = ASN_EINVAL;
732 				}
733 				break;
734 			}
735 			else
736 				lve = mkel(elem, lve);
737 		}
738 		if(err == ASN_OK) {
739 			/* reverse back to original order */
740 			while(lve != nil) {
741 				lveold = lve;
742 				lve = lve->tl;
743 				lveold->tl = ans;
744 				ans = lveold;
745 			}
746 		}
747 	}
748 	*pp = p;
749 	*pelist = ans;
750 	setmalloctag(ans, getcallerpc(&pp));
751 	return err;
752 }
753 
754 /*
755  * Encode e by BER rules, putting answer in *pbytes.
756  * This is done by first calling enc with lenonly==1
757  * to get the length of the needed buffer,
758  * then allocating the buffer and using enc again to fill it up.
759  */
760 static int
761 encode(Elem e, Bytes** pbytes)
762 {
763 	uchar* p;
764 	Bytes* ans;
765 	int err;
766 	uchar uc;
767 
768 	p = &uc;
769 	err = enc(&p, e, 1);
770 	if(err == ASN_OK) {
771 		ans = newbytes(p-&uc);
772 		p = ans->data;
773 		err = enc(&p, e, 0);
774 		*pbytes = ans;
775 	}
776 	return err;
777 }
778 
779 /*
780  * The various enc functions take a pointer to a pointer
781  * into a buffer, and encode their entity starting there,
782  * updating the pointer afterwards.
783  * If lenonly is 1, only the pointer update is done,
784  * allowing enc to be called first to calculate the needed
785  * buffer length.
786  * If lenonly is 0, it is assumed that the answer will fit.
787  */
788 
789 static int
790 enc(uchar** pp, Elem e, int lenonly)
791 {
792 	int err;
793 	int vlen;
794 	int constr;
795 	Tag tag;
796 	int v;
797 	int ilen;
798 	uchar* p;
799 	uchar* psave;
800 
801 	p = *pp;
802 	err = val_enc(&p, e, &constr, 1);
803 	if(err != ASN_OK)
804 		return err;
805 	vlen = p - *pp;
806 	p = *pp;
807 	tag = e.tag;
808 	v = tag.class|constr;
809 	if(tag.num < 31) {
810 		if(!lenonly)
811 			*p = (v|tag.num);
812 		p++;
813 	}
814 	else {
815 		if(!lenonly)
816 			*p = (v|31);
817 		p++;
818 		if(tag.num < 0)
819 			return ASN_EINVAL;
820 		uint7_enc(&p, tag.num, lenonly);
821 	}
822 	if(vlen < 0x80) {
823 		if(!lenonly)
824 			*p = vlen;
825 		p++;
826 	}
827 	else {
828 		psave = p;
829 		int_enc(&p, vlen, 1, 1);
830 		ilen = p-psave;
831 		p = psave;
832 		if(!lenonly) {
833 			*p++ = (0x80 | ilen);
834 			int_enc(&p, vlen, 1, 0);
835 		}
836 		else
837 			p += 1 + ilen;
838 	}
839 	if(!lenonly)
840 		val_enc(&p, e, &constr, 0);
841 	else
842 		p += vlen;
843 	*pp = p;
844 	return err;
845 }
846 
847 static int
848 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
849 {
850 	int err;
851 	uchar* p;
852 	int kind;
853 	int cl;
854 	int v;
855 	Bytes* bb = nil;
856 	Bits* bits;
857 	Ints* oid;
858 	int k;
859 	Elist* el;
860 	char* s;
861 
862 	p = *pp;
863 	err = ASN_OK;
864 	kind = e.tag.num;
865 	cl = e.tag.class;
866 	*pconstr = 0;
867 	if(cl != Universal) {
868 		switch(e.val.tag) {
869 		case VBool:
870 			kind = BOOLEAN;
871 			break;
872 		case VInt:
873 			kind = INTEGER;
874 			break;
875 		case VBigInt:
876 			kind = INTEGER;
877 			break;
878 		case VOctets:
879 			kind = OCTET_STRING;
880 			break;
881 		case VReal:
882 			kind = REAL;
883 			break;
884 		case VOther:
885 			kind = OCTET_STRING;
886 			break;
887 		case VBitString:
888 			kind = BIT_STRING;
889 			break;
890 		case VNull:
891 			kind = NULLTAG;
892 			break;
893 		case VObjId:
894 			kind = OBJECT_ID;
895 			break;
896 		case VString:
897 			kind = UniversalString;
898 			break;
899 		case VSeq:
900 			kind = SEQUENCE;
901 			break;
902 		case VSet:
903 			kind = SETOF;
904 			break;
905 		}
906 	}
907 	switch(kind) {
908 	case BOOLEAN:
909 		if(is_int(&e, &v)) {
910 			if(v != 0)
911 				v = 255;
912 			 int_enc(&p, v, 1, lenonly);
913 		}
914 		else
915 			err = ASN_EINVAL;
916 		break;
917 
918 	case INTEGER:
919 	case ENUMERATED:
920 		if(is_int(&e, &v))
921 			int_enc(&p, v, 0, lenonly);
922 		else {
923 			if(is_bigint(&e, &bb)) {
924 				if(!lenonly)
925 					memmove(p, bb->data, bb->len);
926 				p += bb->len;
927 			}
928 			else
929 				err = ASN_EINVAL;
930 		}
931 		break;
932 
933 	case BIT_STRING:
934 		if(is_bitstring(&e, &bits)) {
935 			if(bits->len == 0) {
936 				if(!lenonly)
937 					*p = 0;
938 				p++;
939 			}
940 			else {
941 				v = bits->unusedbits;
942 				if(v < 0 || v > 7)
943 					err = ASN_EINVAL;
944 				else {
945 					if(!lenonly) {
946 						*p = v;
947 						memmove(p+1, bits->data, bits->len);
948 					}
949 					p += 1 + bits->len;
950 				}
951 			}
952 		}
953 		else
954 			err = ASN_EINVAL;
955 		break;
956 
957 	case OCTET_STRING:
958 	case ObjectDescriptor:
959 	case EXTERNAL:
960 	case REAL:
961 	case EMBEDDED_PDV:
962 		bb = nil;
963 		switch(e.val.tag) {
964 		case VOctets:
965 			bb = e.val.u.octetsval;
966 			break;
967 		case VReal:
968 			bb = e.val.u.realval;
969 			break;
970 		case VOther:
971 			bb = e.val.u.otherval;
972 			break;
973 		}
974 		if(bb != nil) {
975 			if(!lenonly)
976 				memmove(p, bb->data, bb->len);
977 			p += bb->len;
978 		}
979 			else
980 				err = ASN_EINVAL;
981 		break;
982 
983 	case NULLTAG:
984 		break;
985 
986 	case OBJECT_ID:
987 		if(is_oid(&e, &oid)) {
988 			for(k = 0; k < oid->len; k++) {
989 				v = oid->data[k];
990 				if(k == 0) {
991 					v *= 40;
992 					if(oid->len > 1)
993 						v += oid->data[++k];
994 				}
995 				uint7_enc(&p, v, lenonly);
996 			}
997 		}
998 		else
999 			err = ASN_EINVAL;
1000 		break;
1001 
1002 	case SEQUENCE:
1003 	case SETOF:
1004 		el = nil;
1005 		if(e.val.tag == VSeq)
1006 			el = e.val.u.seqval;
1007 		else if(e.val.tag == VSet)
1008 			el = e.val.u.setval;
1009 		else
1010 			err = ASN_EINVAL;
1011 		if(el != nil) {
1012 			*pconstr = CONSTR_MASK;
1013 			for(; el != nil; el = el->tl) {
1014 				err = enc(&p, el->hd, lenonly);
1015 				if(err != ASN_OK)
1016 					break;
1017 			}
1018 		}
1019 		break;
1020 
1021 	case NumericString:
1022 	case PrintableString:
1023 	case TeletexString:
1024 	case VideotexString:
1025 	case IA5String:
1026 	case UTCTime:
1027 	case GeneralizedTime:
1028 	case GraphicString:
1029 	case VisibleString:
1030 	case GeneralString:
1031 	case UniversalString:
1032 	case BMPString:
1033 		if(e.val.tag == VString) {
1034 			s = e.val.u.stringval;
1035 			if(s != nil) {
1036 				v = strlen(s);
1037 				if(!lenonly)
1038 					memmove(p, s, v);
1039 				p += v;
1040 			}
1041 		}
1042 		else
1043 			err = ASN_EINVAL;
1044 		break;
1045 
1046 	default:
1047 		err = ASN_EINVAL;
1048 	}
1049 	*pp = p;
1050 	return err;
1051 }
1052 
1053 /*
1054  * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1055  * except last, only putting in bytes if !lenonly.
1056  */
1057 static void
1058 uint7_enc(uchar** pp, int num, int lenonly)
1059 {
1060 	int n;
1061 	int v;
1062 	int k;
1063 	uchar* p;
1064 
1065 	p = *pp;
1066 	n = 1;
1067 	v = num >> 7;
1068 	while(v > 0) {
1069 		v >>= 7;
1070 		n++;
1071 	}
1072 	if(lenonly)
1073 		p += n;
1074 	else {
1075 		for(k = (n - 1)*7; k > 0; k -= 7)
1076 			*p++= ((num >> k)|0x80);
1077 		*p++ = (num&0x7F);
1078 	}
1079 	*pp = p;
1080 }
1081 
1082 /*
1083  * Encode num as unsigned or signed integer,
1084  * only putting in bytes if !lenonly.
1085  * Encoding is length followed by bytes to concatenate.
1086  */
1087 static void
1088 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1089 {
1090 	int v;
1091 	int n;
1092 	int prevv;
1093 	int k;
1094 	uchar* p;
1095 
1096 	p = *pp;
1097 	v = num;
1098 	if(v < 0)
1099 		v = -(v + 1);
1100 	n = 1;
1101 	prevv = v;
1102 	v >>= 8;
1103 	while(v > 0) {
1104 		prevv = v;
1105 		v >>= 8;
1106 		n++;
1107 	}
1108 	if(!unsgned && (prevv&0x80))
1109 		n++;
1110 	if(lenonly)
1111 		p += n;
1112 	else {
1113 		for(k = (n - 1)*8; k >= 0; k -= 8)
1114 			*p++ = (num >> k);
1115 	}
1116 	*pp = p;
1117 }
1118 
1119 static int
1120 ints_eq(Ints* a, Ints* b)
1121 {
1122 	int	alen;
1123 	int	i;
1124 
1125 	alen = a->len;
1126 	if(alen != b->len)
1127 		return 0;
1128 	for(i = 0; i < alen; i++)
1129 		if(a->data[i] != b->data[i])
1130 			return 0;
1131 	return 1;
1132 }
1133 
1134 /*
1135  * Look up o in tab (which must have nil entry to terminate).
1136  * Return index of matching entry, or -1 if none.
1137  */
1138 static int
1139 oid_lookup(Ints* o, Ints** tab)
1140 {
1141 	int i;
1142 
1143 	for(i = 0; tab[i] != nil; i++)
1144 		if(ints_eq(o, tab[i]))
1145 			return  i;
1146 	return -1;
1147 }
1148 
1149 /*
1150  * Return true if *pe is a SEQUENCE, and set *pseq to
1151  * the value of the sequence if so.
1152  */
1153 static int
1154 is_seq(Elem* pe, Elist** pseq)
1155 {
1156 	if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1157 		*pseq = pe->val.u.seqval;
1158 		return 1;
1159 	}
1160 	return 0;
1161 }
1162 
1163 static int
1164 is_set(Elem* pe, Elist** pset)
1165 {
1166 	if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1167 		*pset = pe->val.u.setval;
1168 		return 1;
1169 	}
1170 	return 0;
1171 }
1172 
1173 static int
1174 is_int(Elem* pe, int* pint)
1175 {
1176 	if(pe->tag.class == Universal) {
1177 		if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1178 			*pint = pe->val.u.intval;
1179 			return 1;
1180 		}
1181 		else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1182 			*pint = pe->val.u.boolval;
1183 			return 1;
1184 		}
1185 	}
1186 	return 0;
1187 }
1188 
1189 /*
1190  * for convience, all VInt's are readable via this routine,
1191  * as well as all VBigInt's
1192  */
1193 static int
1194 is_bigint(Elem* pe, Bytes** pbigint)
1195 {
1196 	int v, n, i;
1197 
1198 	if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
1199 		if(pe->val.tag == VBigInt)
1200 			*pbigint = pe->val.u.bigintval;
1201 		else if(pe->val.tag == VInt){
1202 			v = pe->val.u.intval;
1203 			for(n = 1; n < 4; n++)
1204 				if((1 << (8 * n)) > v)
1205 					break;
1206 			*pbigint = newbytes(n);
1207 			for(i = 0; i < n; i++)
1208 				(*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1209 		}else
1210 			return 0;
1211 		return 1;
1212 	}
1213 	return 0;
1214 }
1215 
1216 static int
1217 is_bitstring(Elem* pe, Bits** pbits)
1218 {
1219 	if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1220 		*pbits = pe->val.u.bitstringval;
1221 		return 1;
1222 	}
1223 	return 0;
1224 }
1225 
1226 static int
1227 is_octetstring(Elem* pe, Bytes** poctets)
1228 {
1229 	if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1230 		*poctets = pe->val.u.octetsval;
1231 		return 1;
1232 	}
1233 	return 0;
1234 }
1235 
1236 static int
1237 is_oid(Elem* pe, Ints** poid)
1238 {
1239 	if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1240 		*poid = pe->val.u.objidval;
1241 		return 1;
1242 	}
1243 	return 0;
1244 }
1245 
1246 static int
1247 is_string(Elem* pe, char** pstring)
1248 {
1249 	if(pe->tag.class == Universal) {
1250 		switch(pe->tag.num) {
1251 		case NumericString:
1252 		case PrintableString:
1253 		case TeletexString:
1254 		case VideotexString:
1255 		case IA5String:
1256 		case GraphicString:
1257 		case VisibleString:
1258 		case GeneralString:
1259 		case UniversalString:
1260 		case BMPString:
1261 			if(pe->val.tag == VString) {
1262 				*pstring = pe->val.u.stringval;
1263 				return 1;
1264 			}
1265 		}
1266 	}
1267 	return 0;
1268 }
1269 
1270 static int
1271 is_time(Elem* pe, char** ptime)
1272 {
1273 	if(pe->tag.class == Universal
1274 	   && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1275 	   && pe->val.tag == VString) {
1276 		*ptime = pe->val.u.stringval;
1277 		return 1;
1278 	}
1279 	return 0;
1280 }
1281 
1282 
1283 /*
1284  * malloc and return a new Bytes structure capable of
1285  * holding len bytes. (len >= 0)
1286  */
1287 static Bytes*
1288 newbytes(int len)
1289 {
1290 	Bytes* ans;
1291 
1292 	ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1293 	ans->len = len;
1294 	return ans;
1295 }
1296 
1297 /*
1298  * newbytes(len), with data initialized from buf
1299  */
1300 static Bytes*
1301 makebytes(uchar* buf, int len)
1302 {
1303 	Bytes* ans;
1304 
1305 	ans = newbytes(len);
1306 	memmove(ans->data, buf, len);
1307 	return ans;
1308 }
1309 
1310 static void
1311 freebytes(Bytes* b)
1312 {
1313 	if(b != nil)
1314 		free(b);
1315 }
1316 
1317 /*
1318  * Make a new Bytes, containing bytes of b1 followed by those of b2.
1319  * Either b1 or b2 or both can be nil.
1320  */
1321 static Bytes*
1322 catbytes(Bytes* b1, Bytes* b2)
1323 {
1324 	Bytes* ans;
1325 	int n;
1326 
1327 	if(b1 == nil) {
1328 		if(b2 == nil)
1329 			ans = newbytes(0);
1330 		else
1331 			ans = makebytes(b2->data, b2->len);
1332 	}
1333 	else if(b2 == nil) {
1334 		ans = makebytes(b1->data, b1->len);
1335 	}
1336 	else {
1337 		n = b1->len + b2->len;
1338 		ans = newbytes(n);
1339 		ans->len = n;
1340 		memmove(ans->data, b1->data, b1->len);
1341 		memmove(ans->data+b1->len, b2->data, b2->len);
1342 	}
1343 	return ans;
1344 }
1345 
1346 /* len is number of ints */
1347 static Ints*
1348 newints(int len)
1349 {
1350 	Ints* ans;
1351 
1352 	ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1353 	ans->len = len;
1354 	return ans;
1355 }
1356 
1357 static Ints*
1358 makeints(int* buf, int len)
1359 {
1360 	Ints* ans;
1361 
1362 	ans = newints(len);
1363 	if(len > 0)
1364 		memmove(ans->data, buf, len*sizeof(int));
1365 	return ans;
1366 }
1367 
1368 static void
1369 freeints(Ints* b)
1370 {
1371 	if(b != nil)
1372 		free(b);
1373 }
1374 
1375 /* len is number of bytes */
1376 static Bits*
1377 newbits(int len)
1378 {
1379 	Bits* ans;
1380 
1381 	ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1382 	ans->len = len;
1383 	ans->unusedbits = 0;
1384 	return ans;
1385 }
1386 
1387 static Bits*
1388 makebits(uchar* buf, int len, int unusedbits)
1389 {
1390 	Bits* ans;
1391 
1392 	ans = newbits(len);
1393 	memmove(ans->data, buf, len);
1394 	ans->unusedbits = unusedbits;
1395 	return ans;
1396 }
1397 
1398 static void
1399 freebits(Bits* b)
1400 {
1401 	if(b != nil)
1402 		free(b);
1403 }
1404 
1405 static Elist*
1406 mkel(Elem e, Elist* tail)
1407 {
1408 	Elist* el;
1409 
1410 	el = (Elist*)emalloc(sizeof(Elist));
1411 	setmalloctag(el, getcallerpc(&e));
1412 	el->hd = e;
1413 	el->tl = tail;
1414 	return el;
1415 }
1416 
1417 static int
1418 elistlen(Elist* el)
1419 {
1420 	int ans = 0;
1421 	while(el != nil) {
1422 		ans++;
1423 		el = el->tl;
1424 	}
1425 	return ans;
1426 }
1427 
1428 /* Frees elist, but not fields inside values of constituent elems */
1429 static void
1430 freeelist(Elist* el)
1431 {
1432 	Elist* next;
1433 
1434 	while(el != nil) {
1435 		next = el->tl;
1436 		free(el);
1437 		el = next;
1438 	}
1439 }
1440 
1441 /* free any allocated structures inside v (recursively freeing Elists) */
1442 static void
1443 freevalfields(Value* v)
1444 {
1445 	Elist* el;
1446 	Elist* l;
1447 	if(v == nil)
1448 		return;
1449 	switch(v->tag) {
1450  	case VOctets:
1451 		freebytes(v->u.octetsval);
1452 		break;
1453 	case VBigInt:
1454 		freebytes(v->u.bigintval);
1455 		break;
1456 	case VReal:
1457 		freebytes(v->u.realval);
1458 		break;
1459 	case VOther:
1460 		freebytes(v->u.otherval);
1461 		break;
1462 	case VBitString:
1463 		freebits(v->u.bitstringval);
1464 		break;
1465 	case VObjId:
1466 		freeints(v->u.objidval);
1467 		break;
1468 	case VString:
1469 		if(v->u.stringval)
1470 			free(v->u.stringval);
1471 		break;
1472 	case VSeq:
1473 		el = v->u.seqval;
1474 		for(l = el; l != nil; l = l->tl)
1475 			freevalfields(&l->hd.val);
1476 		if(el)
1477 			freeelist(el);
1478 		break;
1479 	case VSet:
1480 		el = v->u.setval;
1481 		for(l = el; l != nil; l = l->tl)
1482 			freevalfields(&l->hd.val);
1483 		if(el)
1484 			freeelist(el);
1485 		break;
1486 	}
1487 }
1488 
1489 /* end of general ASN1 functions */
1490 
1491 
1492 
1493 
1494 
1495 /*=============================================================*/
1496 /*
1497  * Decode and parse an X.509 Certificate, defined by this ASN1:
1498  *	Certificate ::= SEQUENCE {
1499  *		certificateInfo CertificateInfo,
1500  *		signatureAlgorithm AlgorithmIdentifier,
1501  *		signature BIT STRING }
1502  *
1503  *	CertificateInfo ::= SEQUENCE {
1504  *		version [0] INTEGER DEFAULT v1 (0),
1505  *		serialNumber INTEGER,
1506  *		signature AlgorithmIdentifier,
1507  *		issuer Name,
1508  *		validity Validity,
1509  *		subject Name,
1510  *		subjectPublicKeyInfo SubjectPublicKeyInfo }
1511  *	(version v2 has two more fields, optional unique identifiers for
1512  *  issuer and subject; since we ignore these anyway, we won't parse them)
1513  *
1514  *	Validity ::= SEQUENCE {
1515  *		notBefore UTCTime,
1516  *		notAfter UTCTime }
1517  *
1518  *	SubjectPublicKeyInfo ::= SEQUENCE {
1519  *		algorithm AlgorithmIdentifier,
1520  *		subjectPublicKey BIT STRING }
1521  *
1522  *	AlgorithmIdentifier ::= SEQUENCE {
1523  *		algorithm OBJECT IDENTIFER,
1524  *		parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1525  *
1526  *	Name ::= SEQUENCE OF RelativeDistinguishedName
1527  *
1528  *	RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1529  *
1530  *	AttributeTypeAndValue ::= SEQUENCE {
1531  *		type OBJECT IDENTIFER,
1532  *		value DirectoryString }
1533  *	(selected attributes have these Object Ids:
1534  *		commonName {2 5 4 3}
1535  *		countryName {2 5 4 6}
1536  *		localityName {2 5 4 7}
1537  *		stateOrProvinceName {2 5 4 8}
1538  *		organizationName {2 5 4 10}
1539  *		organizationalUnitName {2 5 4 11}
1540  *	)
1541  *
1542  *	DirectoryString ::= CHOICE {
1543  *		teletexString TeletexString,
1544  *		printableString PrintableString,
1545  *		universalString UniversalString }
1546  *
1547  *  See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1548  *
1549  *  Not yet implemented:
1550  *   CertificateRevocationList ::= SIGNED SEQUENCE{
1551  *           signature       AlgorithmIdentifier,
1552  *           issuer          Name,
1553  *           lastUpdate      UTCTime,
1554  *           nextUpdate      UTCTime,
1555  *           revokedCertificates
1556  *                           SEQUENCE OF CRLEntry OPTIONAL}
1557  *   CRLEntry ::= SEQUENCE{
1558  *           userCertificate SerialNumber,
1559  *           revocationDate UTCTime}
1560  */
1561 
1562 typedef struct CertX509 {
1563 	int	serial;
1564 	char*	issuer;
1565 	char*	validity_start;
1566 	char*	validity_end;
1567 	char*	subject;
1568 	int	publickey_alg;
1569 	Bytes*	publickey;
1570 	int	signature_alg;
1571 	Bytes*	signature;
1572 } CertX509;
1573 
1574 /* Algorithm object-ids */
1575 enum {
1576 	ALG_rsaEncryption,
1577 	ALG_md2WithRSAEncryption,
1578 	ALG_md4WithRSAEncryption,
1579 	ALG_md5WithRSAEncryption,
1580 	ALG_sha1WithRSAEncryption,
1581 	ALG_md5,
1582 	NUMALGS
1583 };
1584 typedef struct Ints7 {
1585 	int		len;
1586 	int		data[7];
1587 } Ints7;
1588 static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1589 static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1590 static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1591 static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1592 static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1593 static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1594 static Ints *alg_oid_tab[NUMALGS+1] = {
1595 	(Ints*)&oid_rsaEncryption,
1596 	(Ints*)&oid_md2WithRSAEncryption,
1597 	(Ints*)&oid_md4WithRSAEncryption,
1598 	(Ints*)&oid_md5WithRSAEncryption,
1599 	(Ints*)&oid_sha1WithRSAEncryption,
1600 	(Ints*)&oid_md5,
1601 	nil
1602 };
1603 static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, nil };
1604 
1605 static void
1606 freecert(CertX509* c)
1607 {
1608 	if(!c) return;
1609 	if(c->issuer != nil)
1610 		free(c->issuer);
1611 	if(c->validity_start != nil)
1612 		free(c->validity_start);
1613 	if(c->validity_end != nil)
1614 		free(c->validity_end);
1615 	if(c->subject != nil)
1616 		free(c->subject);
1617 	freebytes(c->publickey);
1618 	freebytes(c->signature);
1619 	free(c);
1620 }
1621 
1622 /*
1623  * Parse the Name ASN1 type.
1624  * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1625  * from most general to most specific.  Each element of the path can be
1626  * one or more (but usually just one) attribute-value pair, such as
1627  * countryName="US".
1628  * We'll just form a "postal-style" address string by concatenating the elements
1629  * from most specific to least specific, separated by commas.
1630  * Return name-as-string (which must be freed by caller).
1631  */
1632 static char*
1633 parse_name(Elem* e)
1634 {
1635 	Elist* el;
1636 	Elem* es;
1637 	Elist* esetl;
1638 	Elem* eat;
1639 	Elist* eatl;
1640 	char* s;
1641 	enum { MAXPARTS = 100 };
1642 	char* parts[MAXPARTS];
1643 	int i;
1644 	int plen;
1645 	char* ans = nil;
1646 
1647 	if(!is_seq(e, &el))
1648 		goto errret;
1649 	i = 0;
1650 	plen = 0;
1651 	while(el != nil) {
1652 		es = &el->hd;
1653 		if(!is_set(es, &esetl))
1654 			goto errret;
1655 		while(esetl != nil) {
1656 			eat = &esetl->hd;
1657 			if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1658 				goto errret;
1659 			if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1660 				goto errret;
1661 			parts[i++] = s;
1662 			plen += strlen(s) + 2;		/* room for ", " after */
1663 			esetl = esetl->tl;
1664 		}
1665 		el = el->tl;
1666 	}
1667 	if(i > 0) {
1668 		ans = (char*)emalloc(plen);
1669 		*ans = '\0';
1670 		while(--i >= 0) {
1671 			s = parts[i];
1672 			strcat(ans, s);
1673 			if(i > 0)
1674 				strcat(ans, ", ");
1675 		}
1676 	}
1677 
1678 errret:
1679 	return ans;
1680 }
1681 
1682 /*
1683  * Parse an AlgorithmIdentifer ASN1 type.
1684  * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1685  * or -1 if not found.
1686  * For now, ignore parameters, since none of our algorithms need them.
1687  */
1688 static int
1689 parse_alg(Elem* e)
1690 {
1691 	Elist* el;
1692 	Ints* oid;
1693 
1694 	if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1695 		return -1;
1696 	return oid_lookup(oid, alg_oid_tab);
1697 }
1698 
1699 static CertX509*
1700 decode_cert(Bytes* a)
1701 {
1702 	int ok = 0;
1703 	int n;
1704 	CertX509* c = nil;
1705 	Elem  ecert;
1706 	Elem* ecertinfo;
1707 	Elem* esigalg;
1708 	Elem* esig;
1709 	Elem* eserial;
1710 	Elem* eissuer;
1711 	Elem* evalidity;
1712 	Elem* esubj;
1713 	Elem* epubkey;
1714 	Elist* el;
1715 	Elist* elcert = nil;
1716 	Elist* elcertinfo = nil;
1717 	Elist* elvalidity = nil;
1718 	Elist* elpubkey = nil;
1719 	Bits* bits = nil;
1720 	Bytes* b;
1721 	Elem* e;
1722 
1723 	if(decode(a->data, a->len, &ecert) != ASN_OK)
1724 		goto errret;
1725 
1726 	c = (CertX509*)emalloc(sizeof(CertX509));
1727 	c->serial = -1;
1728 	c->issuer = nil;
1729 	c->validity_start = nil;
1730 	c->validity_end = nil;
1731 	c->subject = nil;
1732 	c->publickey_alg = -1;
1733 	c->publickey = nil;
1734 	c->signature_alg = -1;
1735 	c->signature = nil;
1736 
1737 	/* Certificate */
1738  	if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1739 		goto errret;
1740  	ecertinfo = &elcert->hd;
1741  	el = elcert->tl;
1742  	esigalg = &el->hd;
1743 	c->signature_alg = parse_alg(esigalg);
1744  	el = el->tl;
1745  	esig = &el->hd;
1746 
1747 	/* Certificate Info */
1748 	if(!is_seq(ecertinfo, &elcertinfo))
1749 		goto errret;
1750 	n = elistlen(elcertinfo);
1751   	if(n < 6)
1752 		goto errret;
1753 	eserial =&elcertinfo->hd;
1754  	el = elcertinfo->tl;
1755  	/* check for optional version, marked by explicit context tag 0 */
1756 	if(eserial->tag.class == Context && eserial->tag.num == 0) {
1757  		eserial = &el->hd;
1758  		if(n < 7)
1759  			goto errret;
1760  		el = el->tl;
1761  	}
1762 
1763 	if(parse_alg(&el->hd) != c->signature_alg)
1764 		goto errret;
1765  	el = el->tl;
1766  	eissuer = &el->hd;
1767  	el = el->tl;
1768  	evalidity = &el->hd;
1769  	el = el->tl;
1770  	esubj = &el->hd;
1771  	el = el->tl;
1772  	epubkey = &el->hd;
1773  	if(!is_int(eserial, &c->serial)) {
1774 		if(!is_bigint(eserial, &b))
1775 			goto errret;
1776 		c->serial = -1;	/* else we have to change cert struct */
1777   	}
1778 	c->issuer = parse_name(eissuer);
1779 	if(c->issuer == nil)
1780 		goto errret;
1781 	/* Validity */
1782   	if(!is_seq(evalidity, &elvalidity))
1783 		goto errret;
1784 	if(elistlen(elvalidity) != 2)
1785 		goto errret;
1786 	e = &elvalidity->hd;
1787 	if(!is_time(e, &c->validity_start))
1788 		goto errret;
1789 	e->val.u.stringval = nil;	/* string ownership transfer */
1790 	e = &elvalidity->tl->hd;
1791  	if(!is_time(e, &c->validity_end))
1792 		goto errret;
1793 	e->val.u.stringval = nil;	/* string ownership transfer */
1794 
1795 	/* resume CertificateInfo */
1796  	c->subject = parse_name(esubj);
1797 	if(c->subject == nil)
1798 		goto errret;
1799 
1800 	/* SubjectPublicKeyInfo */
1801  	if(!is_seq(epubkey, &elpubkey))
1802 		goto errret;
1803 	if(elistlen(elpubkey) != 2)
1804 		goto errret;
1805 
1806 	c->publickey_alg = parse_alg(&elpubkey->hd);
1807 	if(c->publickey_alg < 0)
1808 		goto errret;
1809   	if(!is_bitstring(&elpubkey->tl->hd, &bits))
1810 		goto errret;
1811 	if(bits->unusedbits != 0)
1812 		goto errret;
1813  	c->publickey = makebytes(bits->data, bits->len);
1814 
1815 	/*resume Certificate */
1816 	if(c->signature_alg < 0)
1817 		goto errret;
1818  	if(!is_bitstring(esig, &bits))
1819 		goto errret;
1820  	c->signature = makebytes(bits->data, bits->len);
1821 	ok = 1;
1822 
1823 errret:
1824 	freevalfields(&ecert.val);	/* recurses through lists, too */
1825 	if(!ok){
1826 		freecert(c);
1827 		c = nil;
1828 	}
1829 	return c;
1830 }
1831 
1832 /*
1833  *	RSAPublickKey :: SEQUENCE {
1834  *		modulus INTEGER,
1835  *		publicExponent INTEGER
1836  *	}
1837  */
1838 static RSApub*
1839 decode_rsapubkey(Bytes* a)
1840 {
1841 	Elem e;
1842 	Elist *el, *l;
1843 	mpint *mp;
1844 	RSApub* key;
1845 
1846 	l = nil;
1847 	key = rsapuballoc();
1848 	if(decode(a->data, a->len, &e) != ASN_OK)
1849 		goto errret;
1850 	if(!is_seq(&e, &el) || elistlen(el) != 2)
1851 		goto errret;
1852 
1853 	l = el;
1854 
1855 	key->n = mp = asn1mpint(&el->hd);
1856 	if(mp == nil)
1857 		goto errret;
1858 
1859 	el = el->tl;
1860 	key->ek = mp = asn1mpint(&el->hd);
1861 	if(mp == nil)
1862 		goto errret;
1863 
1864 	if(l != nil)
1865 		freeelist(l);
1866 	return key;
1867 errret:
1868 	if(l != nil)
1869 		freeelist(l);
1870 	rsapubfree(key);
1871 	return nil;
1872 }
1873 
1874 /*
1875  *	RSAPrivateKey ::= SEQUENCE {
1876  *		version Version,
1877  *		modulus INTEGER, -- n
1878  *		publicExponent INTEGER, -- e
1879  *		privateExponent INTEGER, -- d
1880  *		prime1 INTEGER, -- p
1881  *		prime2 INTEGER, -- q
1882  *		exponent1 INTEGER, -- d mod (p-1)
1883  *		exponent2 INTEGER, -- d mod (q-1)
1884  *		coefficient INTEGER -- (inverse of q) mod p }
1885  */
1886 static RSApriv*
1887 decode_rsaprivkey(Bytes* a)
1888 {
1889 	int version;
1890 	Elem e;
1891 	Elist *el;
1892 	mpint *mp;
1893 	RSApriv* key;
1894 
1895 	key = rsaprivalloc();
1896 	if(decode(a->data, a->len, &e) != ASN_OK)
1897 		goto errret;
1898 	if(!is_seq(&e, &el) || elistlen(el) != 9)
1899 		goto errret;
1900 	if(!is_int(&el->hd, &version) || version != 0)
1901 		goto errret;
1902 
1903 	el = el->tl;
1904 	key->pub.n = mp = asn1mpint(&el->hd);
1905 	if(mp == nil)
1906 		goto errret;
1907 
1908 	el = el->tl;
1909 	key->pub.ek = mp = asn1mpint(&el->hd);
1910 	if(mp == nil)
1911 		goto errret;
1912 
1913 	el = el->tl;
1914 	key->dk = mp = asn1mpint(&el->hd);
1915 	if(mp == nil)
1916 		goto errret;
1917 
1918 	el = el->tl;
1919 	key->q = mp = asn1mpint(&el->hd);
1920 	if(mp == nil)
1921 		goto errret;
1922 
1923 	el = el->tl;
1924 	key->p = mp = asn1mpint(&el->hd);
1925 	if(mp == nil)
1926 		goto errret;
1927 
1928 	el = el->tl;
1929 	key->kq = mp = asn1mpint(&el->hd);
1930 	if(mp == nil)
1931 		goto errret;
1932 
1933 	el = el->tl;
1934 	key->kp = mp = asn1mpint(&el->hd);
1935 	if(mp == nil)
1936 		goto errret;
1937 
1938 	el = el->tl;
1939 	key->c2 = mp = asn1mpint(&el->hd);
1940 	if(mp == nil)
1941 		goto errret;
1942 
1943 	return key;
1944 errret:
1945 	rsaprivfree(key);
1946 	return nil;
1947 }
1948 
1949 static mpint*
1950 asn1mpint(Elem *e)
1951 {
1952 	Bytes *b;
1953 	mpint *mp;
1954 	int v;
1955 
1956 	if(is_int(e, &v))
1957 		return itomp(v, nil);
1958 	if(is_bigint(e, &b)) {
1959 		mp = betomp(b->data, b->len, nil);
1960 		freebytes(b);
1961 		return mp;
1962 	}
1963 	return nil;
1964 }
1965 
1966 static mpint*
1967 pkcs1pad(Bytes *b, mpint *modulus)
1968 {
1969 	int n = (mpsignif(modulus)+7)/8;
1970 	int pm1, i;
1971 	uchar *p;
1972 	mpint *mp;
1973 
1974 	pm1 = n - 1 - b->len;
1975 	p = (uchar*)emalloc(n);
1976 	p[0] = 0;
1977 	p[1] = 1;
1978 	for(i = 2; i < pm1; i++)
1979 		p[i] = 0xFF;
1980 	p[pm1] = 0;
1981 	memcpy(&p[pm1+1], b->data, b->len);
1982 	mp = betomp(p, n, nil);
1983 	free(p);
1984 	return mp;
1985 }
1986 
1987 RSApriv*
1988 asn1toRSApriv(uchar *kd, int kn)
1989 {
1990 	Bytes *b;
1991 	RSApriv *key;
1992 
1993 	b = makebytes(kd, kn);
1994 	key = decode_rsaprivkey(b);
1995 	freebytes(b);
1996 	return key;
1997 }
1998 
1999 /*
2000  * digest(CertificateInfo)
2001  * Our ASN.1 library doesn't return pointers into the original
2002  * data array, so we need to do a little hand decoding.
2003  */
2004 static void
2005 digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
2006 {
2007 	uchar *info, *p, *pend;
2008 	ulong infolen;
2009 	int isconstr, length;
2010 	Tag tag;
2011 	Elem elem;
2012 
2013 	p = cert->data;
2014 	pend = cert->data + cert->len;
2015 	if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2016 	   tag.class != Universal || tag.num != SEQUENCE ||
2017 	   length_decode(&p, pend, &length) != ASN_OK ||
2018 	   p+length > pend ||
2019 	   p+length < p)
2020 		return;
2021 	info = p;
2022 	if(ber_decode(&p, pend, &elem) != ASN_OK)
2023 		return;
2024 	freevalfields(&elem.val);
2025 	if(elem.tag.num != SEQUENCE)
2026 		return;
2027 	infolen = p - info;
2028 	(*digestfun)(info, infolen, digest, nil);
2029 }
2030 
2031 static char*
2032 verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2033 {
2034 	Elem e;
2035 	Elist *el;
2036 	Bytes *digest;
2037 	uchar *pkcs1buf, *buf;
2038 	int buflen;
2039 	mpint *pkcs1;
2040 	int nlen;
2041 	char *err;
2042 
2043 	err = nil;
2044 	pkcs1buf = nil;
2045 
2046 	/* one less than the byte length of the modulus */
2047 	nlen = (mpsignif(pk->n)-1)/8;
2048 
2049 	/* see 9.2.1 of rfc2437 */
2050 	pkcs1 = betomp(signature->data, signature->len, nil);
2051 	mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2052 	buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2053 	buf = pkcs1buf;
2054 	if(buflen != nlen || buf[0] != 1) {
2055 		err = "expected 1";
2056 		goto end;
2057 	}
2058 	buf++;
2059 	while(buf[0] == 0xff)
2060 		buf++;
2061 	if(buf[0] != 0) {
2062 		err = "expected 0";
2063 		goto end;
2064 	}
2065 	buf++;
2066 	buflen -= buf-pkcs1buf;
2067 	if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2068 			!is_octetstring(&el->tl->hd, &digest)) {
2069 		err = "signature parse error";
2070 		goto end;
2071 	}
2072 	*psigalg = &el->hd;
2073 	if(memcmp(digest->data, edigest, digest->len) == 0)
2074 		goto end;
2075 	err = "digests did not match";
2076 
2077 end:
2078 	if(pkcs1 != nil)
2079 		mpfree(pkcs1);
2080 	if(pkcs1buf != nil)
2081 		free(pkcs1buf);
2082 	return err;
2083 }
2084 
2085 RSApub*
2086 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2087 {
2088 	char *e;
2089 	Bytes *b;
2090 	CertX509 *c;
2091 	RSApub *pk;
2092 
2093 	b = makebytes(cert, ncert);
2094 	c = decode_cert(b);
2095 	freebytes(b);
2096 	if(c == nil)
2097 		return nil;
2098 	if(name != nil && c->subject != nil){
2099 		e = strchr(c->subject, ',');
2100 		if(e != nil)
2101 			*e = 0;  // take just CN part of Distinguished Name
2102 		strncpy(name, c->subject, nname);
2103 	}
2104 	pk = decode_rsapubkey(c->publickey);
2105 	freecert(c);
2106 	return pk;
2107 }
2108 
2109 char*
2110 X509verify(uchar *cert, int ncert, RSApub *pk)
2111 {
2112 	char *e;
2113 	Bytes *b;
2114 	CertX509 *c;
2115 	uchar digest[SHA1dlen];
2116 	Elem *sigalg;
2117 
2118 	b = makebytes(cert, ncert);
2119 	c = decode_cert(b);
2120 	if(c != nil)
2121 		digest_certinfo(b, digestalg[c->signature_alg], digest);
2122 	freebytes(b);
2123 	if(c == nil)
2124 		return "cannot decode cert";
2125 	e = verify_signature(c->signature, pk, digest, &sigalg);
2126 	freecert(c);
2127 	return e;
2128 }
2129 
2130 /* ------- Elem constructors ---------- */
2131 static Elem
2132 Null(void)
2133 {
2134 	Elem e;
2135 
2136 	e.tag.class = Universal;
2137 	e.tag.num = NULLTAG;
2138 	e.val.tag = VNull;
2139 	return e;
2140 }
2141 
2142 static Elem
2143 mkint(int j)
2144 {
2145 	Elem e;
2146 
2147 	e.tag.class = Universal;
2148 	e.tag.num = INTEGER;
2149 	e.val.tag = VInt;
2150 	e.val.u.intval = j;
2151 	return e;
2152 }
2153 
2154 static Elem
2155 mkbigint(mpint *p)
2156 {
2157 	Elem e;
2158 	uchar *buf;
2159 	int buflen;
2160 
2161 	e.tag.class = Universal;
2162 	e.tag.num = INTEGER;
2163 	e.val.tag = VBigInt;
2164 	buflen = mptobe(p, nil, 0, &buf);
2165 	e.val.u.bigintval = makebytes(buf, buflen);
2166 	free(buf);
2167 	return e;
2168 }
2169 
2170 static Elem
2171 mkstring(char *s)
2172 {
2173 	Elem e;
2174 
2175 	e.tag.class = Universal;
2176 	e.tag.num = IA5String;
2177 	e.val.tag = VString;
2178 	e.val.u.stringval = estrdup(s);
2179 	return e;
2180 }
2181 
2182 static Elem
2183 mkoctet(uchar *buf, int buflen)
2184 {
2185 	Elem e;
2186 
2187 	e.tag.class = Universal;
2188 	e.tag.num = OCTET_STRING;
2189 	e.val.tag = VOctets;
2190 	e.val.u.octetsval = makebytes(buf, buflen);
2191 	return e;
2192 }
2193 
2194 static Elem
2195 mkbits(uchar *buf, int buflen)
2196 {
2197 	Elem e;
2198 
2199 	e.tag.class = Universal;
2200 	e.tag.num = BIT_STRING;
2201 	e.val.tag = VBitString;
2202 	e.val.u.bitstringval = makebits(buf, buflen, 0);
2203 	return e;
2204 }
2205 
2206 static Elem
2207 mkutc(long t)
2208 {
2209 	Elem e;
2210 	char utc[50];
2211 	Tm *tm = gmtime(t);
2212 
2213 	e.tag.class = Universal;
2214 	e.tag.num = UTCTime;
2215 	e.val.tag = VString;
2216 	snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2217 		tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2218 	e.val.u.stringval = estrdup(utc);
2219 	return e;
2220 }
2221 
2222 static Elem
2223 mkoid(Ints *oid)
2224 {
2225 	Elem e;
2226 
2227 	e.tag.class = Universal;
2228 	e.tag.num = OBJECT_ID;
2229 	e.val.tag = VObjId;
2230 	e.val.u.objidval = makeints(oid->data, oid->len);
2231 	return e;
2232 }
2233 
2234 static Elem
2235 mkseq(Elist *el)
2236 {
2237 	Elem e;
2238 
2239 	e.tag.class = Universal;
2240 	e.tag.num = SEQUENCE;
2241 	e.val.tag = VSeq;
2242 	e.val.u.seqval = el;
2243 	return e;
2244 }
2245 
2246 static Elem
2247 mkset(Elist *el)
2248 {
2249 	Elem e;
2250 
2251 	e.tag.class = Universal;
2252 	e.tag.num = SETOF;
2253 	e.val.tag = VSet;
2254 	e.val.u.setval = el;
2255 	return e;
2256 }
2257 
2258 static Elem
2259 mkalg(int alg)
2260 {
2261 	return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2262 }
2263 
2264 typedef struct Ints7pref {
2265 	int		len;
2266 	int		data[7];
2267 	char	prefix[4];
2268 } Ints7pref;
2269 Ints7pref DN_oid[] = {
2270 	{4, 2, 5, 4, 6, 0, 0, 0,  "C="},
2271 	{4, 2, 5, 4, 8, 0, 0, 0,  "ST="},
2272 	{4, 2, 5, 4, 7, 0, 0, 0,  "L="},
2273 	{4, 2, 5, 4, 10, 0, 0, 0, "O="},
2274 	{4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2275 	{4, 2, 5, 4, 3, 0, 0, 0,  "CN="},
2276  	{7, 1,2,840,113549,1,9,1, "E="},
2277 };
2278 
2279 static Elem
2280 mkname(Ints7pref *oid, char *subj)
2281 {
2282 	return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2283 }
2284 
2285 static Elem
2286 mkDN(char *dn)
2287 {
2288 	int i, j, nf;
2289 	char *f[20], *prefix, *d2 = estrdup(dn);
2290 	Elist* el = nil;
2291 
2292 	nf = tokenize(d2, f, nelem(f));
2293 	for(i=nf-1; i>=0; i--){
2294 		for(j=0; j<nelem(DN_oid); j++){
2295 			prefix = DN_oid[j].prefix;
2296 			if(strncmp(f[i],prefix,strlen(prefix))==0){
2297 				el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2298 				break;
2299 			}
2300 		}
2301 	}
2302 	free(d2);
2303 	return mkseq(el);
2304 }
2305 
2306 
2307 uchar*
2308 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2309 {
2310 	int serial = 0;
2311 	uchar *cert = nil;
2312 	RSApub *pk = rsaprivtopub(priv);
2313 	Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2314 	Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2315 	uchar digest[MD5dlen], *buf;
2316 	int buflen;
2317 	mpint *pkcs1;
2318 
2319 	e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2320 	issuer = mkDN(subj);
2321 	subject = mkDN(subj);
2322 	pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2323 	if(encode(pubkey, &pkbytes) != ASN_OK)
2324 		goto errret;
2325 	freevalfields(&pubkey.val);
2326 	pubkey = mkseq(
2327 		mkel(mkalg(ALG_rsaEncryption),
2328 		mkel(mkbits(pkbytes->data, pkbytes->len),
2329 		nil)));
2330 	freebytes(pkbytes);
2331 	validity = mkseq(
2332 		mkel(mkutc(valid[0]),
2333 		mkel(mkutc(valid[1]),
2334 		nil)));
2335 	certinfo = mkseq(
2336 		mkel(mkint(serial),
2337 		mkel(mkalg(ALG_md5WithRSAEncryption),
2338 		mkel(issuer,
2339 		mkel(validity,
2340 		mkel(subject,
2341 		mkel(pubkey,
2342 		nil)))))));
2343 	if(encode(certinfo, &certinfobytes) != ASN_OK)
2344 		goto errret;
2345 	md5(certinfobytes->data, certinfobytes->len, digest, 0);
2346 	freebytes(certinfobytes);
2347 	sig = mkseq(
2348 		mkel(mkalg(ALG_md5),
2349 		mkel(mkoctet(digest, MD5dlen),
2350 		nil)));
2351 	if(encode(sig, &sigbytes) != ASN_OK)
2352 		goto errret;
2353 	pkcs1 = pkcs1pad(sigbytes, pk->n);
2354 	freebytes(sigbytes);
2355 	rsadecrypt(priv, pkcs1, pkcs1);
2356 	buflen = mptobe(pkcs1, nil, 0, &buf);
2357 	mpfree(pkcs1);
2358 	e = mkseq(
2359 		mkel(certinfo,
2360 		mkel(mkalg(ALG_md5WithRSAEncryption),
2361 		mkel(mkbits(buf, buflen),
2362 		nil))));
2363 	free(buf);
2364 	if(encode(e, &certbytes) != ASN_OK)
2365 		goto errret;
2366 	if(certlen)
2367 		*certlen = certbytes->len;
2368 	cert = certbytes->data;
2369 errret:
2370 	freevalfields(&e.val);
2371 	return cert;
2372 }
2373 
2374 uchar*
2375 X509req(RSApriv *priv, char *subj, int *certlen)
2376 {
2377 	/* RFC 2314, PKCS #10 Certification Request Syntax */
2378 	int version = 0;
2379 	uchar *cert = nil;
2380 	RSApub *pk = rsaprivtopub(priv);
2381 	Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2382 	Elem e, certinfo, subject, pubkey, sig;
2383 	uchar digest[MD5dlen], *buf;
2384 	int buflen;
2385 	mpint *pkcs1;
2386 
2387 	e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2388 	subject = mkDN(subj);
2389 	pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2390 	if(encode(pubkey, &pkbytes) != ASN_OK)
2391 		goto errret;
2392 	freevalfields(&pubkey.val);
2393 	pubkey = mkseq(
2394 		mkel(mkalg(ALG_rsaEncryption),
2395 		mkel(mkbits(pkbytes->data, pkbytes->len),
2396 		nil)));
2397 	freebytes(pkbytes);
2398 	certinfo = mkseq(
2399 		mkel(mkint(version),
2400 		mkel(subject,
2401 		mkel(pubkey,
2402 		nil))));
2403 	if(encode(certinfo, &certinfobytes) != ASN_OK)
2404 		goto errret;
2405 	md5(certinfobytes->data, certinfobytes->len, digest, 0);
2406 	freebytes(certinfobytes);
2407 	sig = mkseq(
2408 		mkel(mkalg(ALG_md5),
2409 		mkel(mkoctet(digest, MD5dlen),
2410 		nil)));
2411 	if(encode(sig, &sigbytes) != ASN_OK)
2412 		goto errret;
2413 	pkcs1 = pkcs1pad(sigbytes, pk->n);
2414 	freebytes(sigbytes);
2415 	rsadecrypt(priv, pkcs1, pkcs1);
2416 	buflen = mptobe(pkcs1, nil, 0, &buf);
2417 	mpfree(pkcs1);
2418 	e = mkseq(
2419 		mkel(certinfo,
2420 		mkel(mkalg(ALG_md5),
2421 		mkel(mkbits(buf, buflen),
2422 		nil))));
2423 	free(buf);
2424 	if(encode(e, &certbytes) != ASN_OK)
2425 		goto errret;
2426 	if(certlen)
2427 		*certlen = certbytes->len;
2428 	cert = certbytes->data;
2429 errret:
2430 	freevalfields(&e.val);
2431 	return cert;
2432 }
2433 
2434 static char*
2435 tagdump(Tag tag)
2436 {
2437 	if(tag.class != Universal)
2438 		return smprint("class%d,num%d", tag.class, tag.num);
2439 	switch(tag.num){
2440 	case BOOLEAN: return "BOOLEAN";
2441 	case INTEGER: return "INTEGER";
2442 	case BIT_STRING: return "BIT STRING";
2443 	case OCTET_STRING: return "OCTET STRING";
2444 	case NULLTAG: return "NULLTAG";
2445 	case OBJECT_ID: return "OID";
2446 	case ObjectDescriptor: return "OBJECT_DES";
2447 	case EXTERNAL: return "EXTERNAL";
2448 	case REAL: return "REAL";
2449 	case ENUMERATED: return "ENUMERATED";
2450 	case EMBEDDED_PDV: return "EMBEDDED PDV";
2451 	case SEQUENCE: return "SEQUENCE";
2452 	case SETOF: return "SETOF";
2453 	case NumericString: return "NumericString";
2454 	case PrintableString: return "PrintableString";
2455 	case TeletexString: return "TeletexString";
2456 	case VideotexString: return "VideotexString";
2457 	case IA5String: return "IA5String";
2458 	case UTCTime: return "UTCTime";
2459 	case GeneralizedTime: return "GeneralizedTime";
2460 	case GraphicString: return "GraphicString";
2461 	case VisibleString: return "VisibleString";
2462 	case GeneralString: return "GeneralString";
2463 	case UniversalString: return "UniversalString";
2464 	case BMPString: return "BMPString";
2465 	default:
2466 		return smprint("Universal,num%d", tag.num);
2467 	}
2468 }
2469 
2470 static void
2471 edump(Elem e)
2472 {
2473 	Value v;
2474 	Elist *el;
2475 	int i;
2476 
2477 	print("%s{", tagdump(e.tag));
2478 	v = e.val;
2479 	switch(v.tag){
2480 	case VBool: print("Bool %d",v.u.boolval); break;
2481 	case VInt: print("Int %d",v.u.intval); break;
2482 	case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2483 	case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2484 	case VReal: print("Real..."); break;
2485 	case VOther: print("Other..."); break;
2486 	case VBitString: print("BitString..."); break;
2487 	case VNull: print("Null"); break;
2488 	case VEOC: print("EOC..."); break;
2489 	case VObjId: print("ObjId");
2490 		for(i = 0; i<v.u.objidval->len; i++)
2491 			print(" %d", v.u.objidval->data[i]);
2492 		break;
2493 	case VString: print("String \"%s\"",v.u.stringval); break;
2494 	case VSeq: print("Seq\n");
2495 		for(el = v.u.seqval; el!=nil; el = el->tl)
2496 			edump(el->hd);
2497 		break;
2498 	case VSet: print("Set\n");
2499 		for(el = v.u.setval; el!=nil; el = el->tl)
2500 			edump(el->hd);
2501 		break;
2502 	}
2503 	print("}\n");
2504 }
2505 
2506 void
2507 asn1dump(uchar *der, int len)
2508 {
2509 	Elem e;
2510 
2511 	if(decode(der, len, &e) != ASN_OK){
2512 		print("didn't parse\n");
2513 		exits("didn't parse");
2514 	}
2515 	edump(e);
2516 }
2517 
2518 void
2519 X509dump(uchar *cert, int ncert)
2520 {
2521 	char *e;
2522 	Bytes *b;
2523 	CertX509 *c;
2524 	RSApub *pk;
2525 	uchar digest[SHA1dlen];
2526 	Elem *sigalg;
2527 
2528 	print("begin X509dump\n");
2529 	b = makebytes(cert, ncert);
2530 	c = decode_cert(b);
2531 	if(c != nil)
2532 		digest_certinfo(b, digestalg[c->signature_alg], digest);
2533 	freebytes(b);
2534 	if(c == nil){
2535 		print("cannot decode cert");
2536 		return;
2537 	}
2538 
2539 	print("serial %d\n", c->serial);
2540 	print("issuer %s\n", c->issuer);
2541 	print("validity %s %s\n", c->validity_start, c->validity_end);
2542 	print("subject %s\n", c->subject);
2543 	pk = decode_rsapubkey(c->publickey);
2544 	print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2545 
2546 	print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2547 	e = verify_signature(c->signature, pk, digest, &sigalg);
2548 	if(e==nil){
2549 		e = "nil (meaning ok)";
2550 		print("sigalg=\n");
2551 		if(sigalg)
2552 			edump(*sigalg);
2553 	}
2554 	print("self-signed verify_signature returns: %s\n", e);
2555 
2556 	rsapubfree(pk);
2557 	freecert(c);
2558 	print("end X509dump\n");
2559 }
2560