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