xref: /plan9/sys/src/ape/lib/sec/port/x509-ape.c (revision f591d9710fae2220cec09da2812fd6db952f1a27)
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 *
emalloc(int n)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*
estrdup(char * s)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
decode(uchar * a,int alen,Elem * pelem)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
decode_seq(uchar * a,int alen,Elist ** pelist)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
decode_value(uchar * a,int alen,int kind,int isconstr,Value * pval)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
ber_decode(uchar ** pp,uchar * pend,Elem * pelem)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
tag_decode(uchar ** pp,uchar * pend,Tag * ptag,int * pisconstr)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
length_decode(uchar ** pp,uchar * pend,int * plength)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
value_decode(uchar ** pp,uchar * pend,int length,int kind,int isconstr,Value * pval)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
int_decode(uchar ** pp,uchar * pend,int count,int unsgned,int * pint)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
uint7_decode(uchar ** pp,uchar * pend,int * pint)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
octet_decode(uchar ** pp,uchar * pend,int length,int isconstr,Bytes ** pbytes)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
seq_decode(uchar ** pp,uchar * pend,int length,int isconstr,Elist ** pelist)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
encode(Elem e,Bytes ** pbytes)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
enc(uchar ** pp,Elem e,int lenonly)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
val_enc(uchar ** pp,Elem e,int * pconstr,int lenonly)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
uint7_enc(uchar ** pp,int num,int lenonly)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
int_enc(uchar ** pp,int num,int unsgned,int lenonly)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
ints_eq(Ints * a,Ints * b)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
oid_lookup(Ints * o,Ints ** tab)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
is_seq(Elem * pe,Elist ** pseq)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
is_set(Elem * pe,Elist ** pset)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
is_int(Elem * pe,int * pint)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
is_bigint(Elem * pe,Bytes ** pbigint)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
is_bitstring(Elem * pe,Bits ** pbits)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
is_octetstring(Elem * pe,Bytes ** poctets)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
is_oid(Elem * pe,Ints ** poid)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
is_string(Elem * pe,char ** pstring)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
is_time(Elem * pe,char ** ptime)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*
newbytes(int len)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*
makebytes(uchar * buf,int len)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
freebytes(Bytes * b)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*
catbytes(Bytes * b1,Bytes * b2)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*
newints(int len)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*
makeints(int * buf,int len)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
freeints(Ints * b)1372 freeints(Ints* b)
1373 {
1374 	if(b != nil)
1375 		free(b);
1376 }
1377 
1378 /* len is number of bytes */
1379 static Bits*
newbits(int len)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*
makebits(uchar * buf,int len,int unusedbits)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
freebits(Bits * b)1402 freebits(Bits* b)
1403 {
1404 	if(b != nil)
1405 		free(b);
1406 }
1407 
1408 static Elist*
mkel(Elem e,Elist * tail)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
elistlen(Elist * el)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
freeelist(Elist * el)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
freevalfields(Value * v)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_sha1WithRSAEncryptionOiw,
1585 	ALG_md5,
1586 	NUMALGS
1587 };
1588 typedef struct Ints7 {
1589 	int		len;
1590 	int		data[7];
1591 } Ints7;
1592 static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1593 static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1594 static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1595 static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1596 static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1597 static Ints7 oid_sha1WithRSAEncryptionOiw ={6, 1, 3, 14, 3, 2, 29 };
1598 static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1599 static Ints *alg_oid_tab[NUMALGS+1] = {
1600 	(Ints*)&oid_rsaEncryption,
1601 	(Ints*)&oid_md2WithRSAEncryption,
1602 	(Ints*)&oid_md4WithRSAEncryption,
1603 	(Ints*)&oid_md5WithRSAEncryption,
1604 	(Ints*)&oid_sha1WithRSAEncryption,
1605 	(Ints*)&oid_sha1WithRSAEncryptionOiw,
1606 	(Ints*)&oid_md5,
1607 	nil
1608 };
1609 static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, sha1, md5, nil };
1610 
1611 static void
freecert(CertX509 * c)1612 freecert(CertX509* c)
1613 {
1614 	if(!c) return;
1615 	if(c->issuer != nil)
1616 		free(c->issuer);
1617 	if(c->validity_start != nil)
1618 		free(c->validity_start);
1619 	if(c->validity_end != nil)
1620 		free(c->validity_end);
1621 	if(c->subject != nil)
1622 		free(c->subject);
1623 	freebytes(c->publickey);
1624 	freebytes(c->signature);
1625 	free(c);
1626 }
1627 
1628 /*
1629  * Parse the Name ASN1 type.
1630  * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1631  * from most general to most specific.  Each element of the path can be
1632  * one or more (but usually just one) attribute-value pair, such as
1633  * countryName="US".
1634  * We'll just form a "postal-style" address string by concatenating the elements
1635  * from most specific to least specific, separated by commas.
1636  * Return name-as-string (which must be freed by caller).
1637  */
1638 static char*
parse_name(Elem * e)1639 parse_name(Elem* e)
1640 {
1641 	Elist* el;
1642 	Elem* es;
1643 	Elist* esetl;
1644 	Elem* eat;
1645 	Elist* eatl;
1646 	char* s;
1647 	enum { MAXPARTS = 100 };
1648 	char* parts[MAXPARTS];
1649 	int i;
1650 	int plen;
1651 	char* ans = nil;
1652 
1653 	if(!is_seq(e, &el))
1654 		goto errret;
1655 	i = 0;
1656 	plen = 0;
1657 	while(el != nil) {
1658 		es = &el->hd;
1659 		if(!is_set(es, &esetl))
1660 			goto errret;
1661 		while(esetl != nil) {
1662 			eat = &esetl->hd;
1663 			if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1664 				goto errret;
1665 			if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1666 				goto errret;
1667 			parts[i++] = s;
1668 			plen += strlen(s) + 2;		/* room for ", " after */
1669 			esetl = esetl->tl;
1670 		}
1671 		el = el->tl;
1672 	}
1673 	if(i > 0) {
1674 		ans = (char*)emalloc(plen);
1675 		*ans = '\0';
1676 		while(--i >= 0) {
1677 			s = parts[i];
1678 			strcat(ans, s);
1679 			if(i > 0)
1680 				strcat(ans, ", ");
1681 		}
1682 	}
1683 
1684 errret:
1685 	return ans;
1686 }
1687 
1688 /*
1689  * Parse an AlgorithmIdentifer ASN1 type.
1690  * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1691  * or -1 if not found.
1692  * For now, ignore parameters, since none of our algorithms need them.
1693  */
1694 static int
parse_alg(Elem * e)1695 parse_alg(Elem* e)
1696 {
1697 	Elist* el;
1698 	Ints* oid;
1699 
1700 	if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1701 		return -1;
1702 	return oid_lookup(oid, alg_oid_tab);
1703 }
1704 
1705 static CertX509*
decode_cert(Bytes * a)1706 decode_cert(Bytes* a)
1707 {
1708 	int ok = 0;
1709 	int n;
1710 	CertX509* c = nil;
1711 	Elem  ecert;
1712 	Elem* ecertinfo;
1713 	Elem* esigalg;
1714 	Elem* esig;
1715 	Elem* eserial;
1716 	Elem* eissuer;
1717 	Elem* evalidity;
1718 	Elem* esubj;
1719 	Elem* epubkey;
1720 	Elist* el;
1721 	Elist* elcert = nil;
1722 	Elist* elcertinfo = nil;
1723 	Elist* elvalidity = nil;
1724 	Elist* elpubkey = nil;
1725 	Bits* bits = nil;
1726 	Bytes* b;
1727 	Elem* e;
1728 
1729 	if(decode(a->data, a->len, &ecert) != ASN_OK)
1730 		goto errret;
1731 
1732 	c = (CertX509*)emalloc(sizeof(CertX509));
1733 	c->serial = -1;
1734 	c->issuer = nil;
1735 	c->validity_start = nil;
1736 	c->validity_end = nil;
1737 	c->subject = nil;
1738 	c->publickey_alg = -1;
1739 	c->publickey = nil;
1740 	c->signature_alg = -1;
1741 	c->signature = nil;
1742 
1743 	/* Certificate */
1744  	if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1745 		goto errret;
1746  	ecertinfo = &elcert->hd;
1747  	el = elcert->tl;
1748  	esigalg = &el->hd;
1749 	c->signature_alg = parse_alg(esigalg);
1750  	el = el->tl;
1751  	esig = &el->hd;
1752 
1753 	/* Certificate Info */
1754 	if(!is_seq(ecertinfo, &elcertinfo))
1755 		goto errret;
1756 	n = elistlen(elcertinfo);
1757   	if(n < 6)
1758 		goto errret;
1759 	eserial =&elcertinfo->hd;
1760  	el = elcertinfo->tl;
1761  	/* check for optional version, marked by explicit context tag 0 */
1762 	if(eserial->tag.class == Context && eserial->tag.num == 0) {
1763  		eserial = &el->hd;
1764  		if(n < 7)
1765  			goto errret;
1766  		el = el->tl;
1767  	}
1768 
1769 	if(parse_alg(&el->hd) != c->signature_alg)
1770 		goto errret;
1771  	el = el->tl;
1772  	eissuer = &el->hd;
1773  	el = el->tl;
1774  	evalidity = &el->hd;
1775  	el = el->tl;
1776  	esubj = &el->hd;
1777  	el = el->tl;
1778  	epubkey = &el->hd;
1779  	if(!is_int(eserial, &c->serial)) {
1780 		if(!is_bigint(eserial, &b))
1781 			goto errret;
1782 		c->serial = -1;	/* else we have to change cert struct */
1783   	}
1784 	c->issuer = parse_name(eissuer);
1785 	if(c->issuer == nil)
1786 		goto errret;
1787 	/* Validity */
1788   	if(!is_seq(evalidity, &elvalidity))
1789 		goto errret;
1790 	if(elistlen(elvalidity) != 2)
1791 		goto errret;
1792 	e = &elvalidity->hd;
1793 	if(!is_time(e, &c->validity_start))
1794 		goto errret;
1795 	e->val.u.stringval = nil;	/* string ownership transfer */
1796 	e = &elvalidity->tl->hd;
1797  	if(!is_time(e, &c->validity_end))
1798 		goto errret;
1799 	e->val.u.stringval = nil;	/* string ownership transfer */
1800 
1801 	/* resume CertificateInfo */
1802  	c->subject = parse_name(esubj);
1803 	if(c->subject == nil)
1804 		goto errret;
1805 
1806 	/* SubjectPublicKeyInfo */
1807  	if(!is_seq(epubkey, &elpubkey))
1808 		goto errret;
1809 	if(elistlen(elpubkey) != 2)
1810 		goto errret;
1811 
1812 	c->publickey_alg = parse_alg(&elpubkey->hd);
1813 	if(c->publickey_alg < 0)
1814 		goto errret;
1815   	if(!is_bitstring(&elpubkey->tl->hd, &bits))
1816 		goto errret;
1817 	if(bits->unusedbits != 0)
1818 		goto errret;
1819  	c->publickey = makebytes(bits->data, bits->len);
1820 
1821 	/*resume Certificate */
1822 	if(c->signature_alg < 0)
1823 		goto errret;
1824  	if(!is_bitstring(esig, &bits))
1825 		goto errret;
1826  	c->signature = makebytes(bits->data, bits->len);
1827 	ok = 1;
1828 
1829 errret:
1830 	freevalfields(&ecert.val);	/* recurses through lists, too */
1831 	if(!ok){
1832 		freecert(c);
1833 		c = nil;
1834 	}
1835 	return c;
1836 }
1837 
1838 /*
1839  *	RSAPublickKey :: SEQUENCE {
1840  *		modulus INTEGER,
1841  *		publicExponent INTEGER
1842  *	}
1843  */
1844 static RSApub*
decode_rsapubkey(Bytes * a)1845 decode_rsapubkey(Bytes* a)
1846 {
1847 	Elem e;
1848 	Elist *el, *l;
1849 	mpint *mp;
1850 	RSApub* key;
1851 
1852 	l = nil;
1853 	key = rsapuballoc();
1854 	if(decode(a->data, a->len, &e) != ASN_OK)
1855 		goto errret;
1856 	if(!is_seq(&e, &el) || elistlen(el) != 2)
1857 		goto errret;
1858 
1859 	l = el;
1860 
1861 	key->n = mp = asn1mpint(&el->hd);
1862 	if(mp == nil)
1863 		goto errret;
1864 
1865 	el = el->tl;
1866 	key->ek = mp = asn1mpint(&el->hd);
1867 	if(mp == nil)
1868 		goto errret;
1869 
1870 	if(l != nil)
1871 		freeelist(l);
1872 	return key;
1873 errret:
1874 	if(l != nil)
1875 		freeelist(l);
1876 	rsapubfree(key);
1877 	return nil;
1878 }
1879 
1880 /*
1881  *	RSAPrivateKey ::= SEQUENCE {
1882  *		version Version,
1883  *		modulus INTEGER, -- n
1884  *		publicExponent INTEGER, -- e
1885  *		privateExponent INTEGER, -- d
1886  *		prime1 INTEGER, -- p
1887  *		prime2 INTEGER, -- q
1888  *		exponent1 INTEGER, -- d mod (p-1)
1889  *		exponent2 INTEGER, -- d mod (q-1)
1890  *		coefficient INTEGER -- (inverse of q) mod p }
1891  */
1892 static RSApriv*
decode_rsaprivkey(Bytes * a)1893 decode_rsaprivkey(Bytes* a)
1894 {
1895 	int version;
1896 	Elem e;
1897 	Elist *el;
1898 	mpint *mp;
1899 	RSApriv* key;
1900 
1901 	key = rsaprivalloc();
1902 	if(decode(a->data, a->len, &e) != ASN_OK)
1903 		goto errret;
1904 	if(!is_seq(&e, &el) || elistlen(el) != 9)
1905 		goto errret;
1906 	if(!is_int(&el->hd, &version) || version != 0)
1907 		goto errret;
1908 
1909 	el = el->tl;
1910 	key->pub.n = mp = asn1mpint(&el->hd);
1911 	if(mp == nil)
1912 		goto errret;
1913 
1914 	el = el->tl;
1915 	key->pub.ek = mp = asn1mpint(&el->hd);
1916 	if(mp == nil)
1917 		goto errret;
1918 
1919 	el = el->tl;
1920 	key->dk = mp = asn1mpint(&el->hd);
1921 	if(mp == nil)
1922 		goto errret;
1923 
1924 	el = el->tl;
1925 	key->q = mp = asn1mpint(&el->hd);
1926 	if(mp == nil)
1927 		goto errret;
1928 
1929 	el = el->tl;
1930 	key->p = mp = asn1mpint(&el->hd);
1931 	if(mp == nil)
1932 		goto errret;
1933 
1934 	el = el->tl;
1935 	key->kq = mp = asn1mpint(&el->hd);
1936 	if(mp == nil)
1937 		goto errret;
1938 
1939 	el = el->tl;
1940 	key->kp = mp = asn1mpint(&el->hd);
1941 	if(mp == nil)
1942 		goto errret;
1943 
1944 	el = el->tl;
1945 	key->c2 = mp = asn1mpint(&el->hd);
1946 	if(mp == nil)
1947 		goto errret;
1948 
1949 	return key;
1950 errret:
1951 	rsaprivfree(key);
1952 	return nil;
1953 }
1954 
1955 /*
1956  * 	DSAPrivateKey ::= SEQUENCE{
1957  *		version Version,
1958  *		p INTEGER,
1959  *		q INTEGER,
1960  *		g INTEGER, -- alpha
1961  *		pub_key INTEGER, -- key
1962  *		priv_key INTEGER, -- secret
1963  *	}
1964  */
1965 static DSApriv*
decode_dsaprivkey(Bytes * a)1966 decode_dsaprivkey(Bytes* a)
1967 {
1968 	int version;
1969 	Elem e;
1970 	Elist *el;
1971 	mpint *mp;
1972 	DSApriv* key;
1973 
1974 	key = dsaprivalloc();
1975 	if(decode(a->data, a->len, &e) != ASN_OK)
1976 		goto errret;
1977 	if(!is_seq(&e, &el) || elistlen(el) != 6)
1978 		goto errret;
1979 version = -1;
1980 	if(!is_int(&el->hd, &version) || version != 0)
1981 {
1982 fprint(2, "version %d\n", version);
1983 		goto errret;
1984 }
1985 
1986 	el = el->tl;
1987 	key->pub.p = mp = asn1mpint(&el->hd);
1988 	if(mp == nil)
1989 		goto errret;
1990 
1991 	el = el->tl;
1992 	key->pub.q = mp = asn1mpint(&el->hd);
1993 	if(mp == nil)
1994 		goto errret;
1995 
1996 	el = el->tl;
1997 	key->pub.alpha = mp = asn1mpint(&el->hd);
1998 	if(mp == nil)
1999 		goto errret;
2000 
2001 	el = el->tl;
2002 	key->pub.key = mp = asn1mpint(&el->hd);
2003 	if(mp == nil)
2004 		goto errret;
2005 
2006 	el = el->tl;
2007 	key->secret = mp = asn1mpint(&el->hd);
2008 	if(mp == nil)
2009 		goto errret;
2010 
2011 	return key;
2012 errret:
2013 	dsaprivfree(key);
2014 	return nil;
2015 }
2016 
2017 static mpint*
asn1mpint(Elem * e)2018 asn1mpint(Elem *e)
2019 {
2020 	Bytes *b;
2021 	mpint *mp;
2022 	int v;
2023 
2024 	if(is_int(e, &v))
2025 		return itomp(v, nil);
2026 	if(is_bigint(e, &b)) {
2027 		mp = betomp(b->data, b->len, nil);
2028 		freebytes(b);
2029 		return mp;
2030 	}
2031 	return nil;
2032 }
2033 
2034 static mpint*
pkcs1pad(Bytes * b,mpint * modulus)2035 pkcs1pad(Bytes *b, mpint *modulus)
2036 {
2037 	int n = (mpsignif(modulus)+7)/8;
2038 	int pm1, i;
2039 	uchar *p;
2040 	mpint *mp;
2041 
2042 	pm1 = n - 1 - b->len;
2043 	p = (uchar*)emalloc(n);
2044 	p[0] = 0;
2045 	p[1] = 1;
2046 	for(i = 2; i < pm1; i++)
2047 		p[i] = 0xFF;
2048 	p[pm1] = 0;
2049 	memcpy(&p[pm1+1], b->data, b->len);
2050 	mp = betomp(p, n, nil);
2051 	free(p);
2052 	return mp;
2053 }
2054 
2055 RSApriv*
asn1toRSApriv(uchar * kd,int kn)2056 asn1toRSApriv(uchar *kd, int kn)
2057 {
2058 	Bytes *b;
2059 	RSApriv *key;
2060 
2061 	b = makebytes(kd, kn);
2062 	key = decode_rsaprivkey(b);
2063 	freebytes(b);
2064 	return key;
2065 }
2066 
2067 DSApriv*
asn1toDSApriv(uchar * kd,int kn)2068 asn1toDSApriv(uchar *kd, int kn)
2069 {
2070 	Bytes *b;
2071 	DSApriv *key;
2072 
2073 	b = makebytes(kd, kn);
2074 	key = decode_dsaprivkey(b);
2075 	freebytes(b);
2076 	return key;
2077 }
2078 
2079 /*
2080  * digest(CertificateInfo)
2081  * Our ASN.1 library doesn't return pointers into the original
2082  * data array, so we need to do a little hand decoding.
2083  */
2084 static void
digest_certinfo(Bytes * cert,DigestFun digestfun,uchar * digest)2085 digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
2086 {
2087 	uchar *info, *p, *pend;
2088 	ulong infolen;
2089 	int isconstr, length;
2090 	Tag tag;
2091 	Elem elem;
2092 
2093 	p = cert->data;
2094 	pend = cert->data + cert->len;
2095 	if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2096 	   tag.class != Universal || tag.num != SEQUENCE ||
2097 	   length_decode(&p, pend, &length) != ASN_OK ||
2098 	   p+length > pend ||
2099 	   p+length < p)
2100 		return;
2101 	info = p;
2102 	if(ber_decode(&p, pend, &elem) != ASN_OK)
2103 		return;
2104 	freevalfields(&elem.val);
2105 	if(elem.tag.num != SEQUENCE)
2106 		return;
2107 	infolen = p - info;
2108 	(*digestfun)(info, infolen, digest, nil);
2109 }
2110 
2111 static char*
verify_signature(Bytes * signature,RSApub * pk,uchar * edigest,Elem ** psigalg)2112 verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2113 {
2114 	Elem e;
2115 	Elist *el;
2116 	Bytes *digest;
2117 	uchar *pkcs1buf, *buf;
2118 	int buflen;
2119 	mpint *pkcs1;
2120 	int nlen;
2121 	char *err;
2122 
2123 	err = nil;
2124 	pkcs1buf = nil;
2125 
2126 	/* one less than the byte length of the modulus */
2127 	nlen = (mpsignif(pk->n)-1)/8;
2128 
2129 	/* see 9.2.1 of rfc2437 */
2130 	pkcs1 = betomp(signature->data, signature->len, nil);
2131 	mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2132 	buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2133 	buf = pkcs1buf;
2134 	if(buflen != nlen || buf[0] != 1) {
2135 		err = "expected 1";
2136 		goto end;
2137 	}
2138 	buf++;
2139 	while(buf[0] == 0xff)
2140 		buf++;
2141 	if(buf[0] != 0) {
2142 		err = "expected 0";
2143 		goto end;
2144 	}
2145 	buf++;
2146 	buflen -= buf-pkcs1buf;
2147 	if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2148 			!is_octetstring(&el->tl->hd, &digest)) {
2149 		err = "signature parse error";
2150 		goto end;
2151 	}
2152 	*psigalg = &el->hd;
2153 	if(memcmp(digest->data, edigest, digest->len) == 0)
2154 		goto end;
2155 	err = "digests did not match";
2156 
2157 end:
2158 	if(pkcs1 != nil)
2159 		mpfree(pkcs1);
2160 	if(pkcs1buf != nil)
2161 		free(pkcs1buf);
2162 	return err;
2163 }
2164 
2165 RSApub*
X509toRSApub(uchar * cert,int ncert,char * name,int nname)2166 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2167 {
2168 	char *e;
2169 	Bytes *b;
2170 	CertX509 *c;
2171 	RSApub *pk;
2172 
2173 	b = makebytes(cert, ncert);
2174 	c = decode_cert(b);
2175 	freebytes(b);
2176 	if(c == nil)
2177 		return nil;
2178 	if(name != nil && c->subject != nil){
2179 		e = strchr(c->subject, ',');
2180 		if(e != nil)
2181 			*e = 0;	/* take just CN part of Distinguished Name */
2182 		strncpy(name, c->subject, nname);
2183 	}
2184 	pk = decode_rsapubkey(c->publickey);
2185 	freecert(c);
2186 	return pk;
2187 }
2188 
2189 int
getalgo(Elem * e)2190 getalgo(Elem *e)
2191 {
2192 	Value *v;
2193 	Elist *el;
2194 	int a;
2195 
2196 	if((a = parse_alg(e)) >= 0)
2197 		return a;
2198 	v = &e->val;
2199 	if(v->tag == VSeq){
2200 		print("Seq\n");
2201 		for(el = v->u.seqval; el!=nil; el = el->tl){
2202 			if((a = getalgo(&el->hd)) >= 0)
2203 				return a;
2204 		}
2205 	}
2206 	return -1;
2207 }
2208 
2209 static void edump(Elem e);
2210 
2211 RSApub*
asn1toRSApub(uchar * der,int nder)2212 asn1toRSApub(uchar *der, int nder)
2213 {
2214 	Elem e;
2215 	Elist *el, *l;
2216 	int n;
2217 	Bits *b;
2218 	RSApub *key;
2219 	mpint *mp;
2220 
2221 	if(decode(der, nder, &e) != ASN_OK){
2222 		print("didn't parse\n");
2223 		return nil;
2224 	}
2225 	if(!is_seq(&e, &el)){
2226 		print("no seq");
2227 		return nil;
2228 	}
2229 	if((n = elistlen(el)) != 2){
2230 		print("bad length %d\n", n);
2231 		return nil;
2232 	}
2233 	if((n = getalgo(&el->hd)) < 0){
2234 		print("no algo\n");
2235 		return nil;
2236 	}
2237 	if(n != 0){
2238 		print("cant do algorithm %d\n", n);
2239 		return nil;
2240 	}
2241 	if(!is_bitstring(&el->tl->hd, &b)){
2242 		print("no bits\n");
2243 		return nil;
2244 	}
2245 	if(decode(b->data, b->len, &e) != ASN_OK){
2246 		print("no second decode\n");
2247 		return nil;
2248 	}
2249 	if(!is_seq(&e, &el)){
2250 		print("no second seq\n");
2251 		return nil;
2252 	}
2253 	if(elistlen(el) != 2){
2254 		print("no second length\n");
2255 		return nil;
2256 	}
2257 	key = rsapuballoc();
2258 
2259 	l = el;
2260 
2261 	key->n = mp = asn1mpint(&el->hd);
2262 	if(mp == nil)
2263 		goto errret;
2264 
2265 	el = el->tl;
2266 	key->ek = mp = asn1mpint(&el->hd);
2267 	if(mp == nil)
2268 		goto errret;
2269 
2270 	if(l != nil)
2271 		freeelist(l);
2272 	return key;
2273 errret:
2274 	if(l != nil)
2275 		freeelist(l);
2276 	rsapubfree(key);
2277 	return nil;
2278 }
2279 
2280 char*
X509verify(uchar * cert,int ncert,RSApub * pk)2281 X509verify(uchar *cert, int ncert, RSApub *pk)
2282 {
2283 	char *e;
2284 	Bytes *b;
2285 	CertX509 *c;
2286 	uchar digest[SHA1dlen];
2287 	Elem *sigalg;
2288 
2289 	b = makebytes(cert, ncert);
2290 	c = decode_cert(b);
2291 	if(c != nil)
2292 		digest_certinfo(b, digestalg[c->signature_alg], digest);
2293 	freebytes(b);
2294 	if(c == nil)
2295 		return "cannot decode cert";
2296 	e = verify_signature(c->signature, pk, digest, &sigalg);
2297 	freecert(c);
2298 	return e;
2299 }
2300 
2301 /* ------- Elem constructors ---------- */
2302 static Elem
Null(void)2303 Null(void)
2304 {
2305 	Elem e;
2306 
2307 	e.tag.class = Universal;
2308 	e.tag.num = NULLTAG;
2309 	e.val.tag = VNull;
2310 	return e;
2311 }
2312 
2313 static Elem
mkint(int j)2314 mkint(int j)
2315 {
2316 	Elem e;
2317 
2318 	e.tag.class = Universal;
2319 	e.tag.num = INTEGER;
2320 	e.val.tag = VInt;
2321 	e.val.u.intval = j;
2322 	return e;
2323 }
2324 
2325 static Elem
mkbigint(mpint * p)2326 mkbigint(mpint *p)
2327 {
2328 	Elem e;
2329 	uchar *buf;
2330 	int buflen;
2331 
2332 	e.tag.class = Universal;
2333 	e.tag.num = INTEGER;
2334 	e.val.tag = VBigInt;
2335 	buflen = mptobe(p, nil, 0, &buf);
2336 	e.val.u.bigintval = makebytes(buf, buflen);
2337 	free(buf);
2338 	return e;
2339 }
2340 
2341 static Elem
mkstring(char * s)2342 mkstring(char *s)
2343 {
2344 	Elem e;
2345 
2346 	e.tag.class = Universal;
2347 	e.tag.num = IA5String;
2348 	e.val.tag = VString;
2349 	e.val.u.stringval = estrdup(s);
2350 	return e;
2351 }
2352 
2353 static Elem
mkoctet(uchar * buf,int buflen)2354 mkoctet(uchar *buf, int buflen)
2355 {
2356 	Elem e;
2357 
2358 	e.tag.class = Universal;
2359 	e.tag.num = OCTET_STRING;
2360 	e.val.tag = VOctets;
2361 	e.val.u.octetsval = makebytes(buf, buflen);
2362 	return e;
2363 }
2364 
2365 static Elem
mkbits(uchar * buf,int buflen)2366 mkbits(uchar *buf, int buflen)
2367 {
2368 	Elem e;
2369 
2370 	e.tag.class = Universal;
2371 	e.tag.num = BIT_STRING;
2372 	e.val.tag = VBitString;
2373 	e.val.u.bitstringval = makebits(buf, buflen, 0);
2374 	return e;
2375 }
2376 
2377 static Elem
mkutc(long t)2378 mkutc(long t)
2379 {
2380 	Elem e;
2381 	char utc[50];
2382 	Tm *tm = gmtime(t);
2383 
2384 	e.tag.class = Universal;
2385 	e.tag.num = UTCTime;
2386 	e.val.tag = VString;
2387 	snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2388 		tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2389 	e.val.u.stringval = estrdup(utc);
2390 	return e;
2391 }
2392 
2393 static Elem
mkoid(Ints * oid)2394 mkoid(Ints *oid)
2395 {
2396 	Elem e;
2397 
2398 	e.tag.class = Universal;
2399 	e.tag.num = OBJECT_ID;
2400 	e.val.tag = VObjId;
2401 	e.val.u.objidval = makeints(oid->data, oid->len);
2402 	return e;
2403 }
2404 
2405 static Elem
mkseq(Elist * el)2406 mkseq(Elist *el)
2407 {
2408 	Elem e;
2409 
2410 	e.tag.class = Universal;
2411 	e.tag.num = SEQUENCE;
2412 	e.val.tag = VSeq;
2413 	e.val.u.seqval = el;
2414 	return e;
2415 }
2416 
2417 static Elem
mkset(Elist * el)2418 mkset(Elist *el)
2419 {
2420 	Elem e;
2421 
2422 	e.tag.class = Universal;
2423 	e.tag.num = SETOF;
2424 	e.val.tag = VSet;
2425 	e.val.u.setval = el;
2426 	return e;
2427 }
2428 
2429 static Elem
mkalg(int alg)2430 mkalg(int alg)
2431 {
2432 	return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2433 }
2434 
2435 typedef struct Ints7pref {
2436 	int		len;
2437 	int		data[7];
2438 	char	prefix[4];
2439 } Ints7pref;
2440 Ints7pref DN_oid[] = {
2441 	{4, 2, 5, 4, 6, 0, 0, 0,  "C="},
2442 	{4, 2, 5, 4, 8, 0, 0, 0,  "ST="},
2443 	{4, 2, 5, 4, 7, 0, 0, 0,  "L="},
2444 	{4, 2, 5, 4, 10, 0, 0, 0, "O="},
2445 	{4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2446 	{4, 2, 5, 4, 3, 0, 0, 0,  "CN="},
2447  	{7, 1,2,840,113549,1,9,1, "E="},
2448 };
2449 
2450 static Elem
mkname(Ints7pref * oid,char * subj)2451 mkname(Ints7pref *oid, char *subj)
2452 {
2453 	return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2454 }
2455 
2456 static Elem
mkDN(char * dn)2457 mkDN(char *dn)
2458 {
2459 	int i, j, nf;
2460 	char *f[20], *prefix, *d2 = estrdup(dn);
2461 	Elist* el = nil;
2462 
2463 	nf = tokenize(d2, f, nelem(f));
2464 	for(i=nf-1; i>=0; i--){
2465 		for(j=0; j<nelem(DN_oid); j++){
2466 			prefix = DN_oid[j].prefix;
2467 			if(strncmp(f[i],prefix,strlen(prefix))==0){
2468 				el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2469 				break;
2470 			}
2471 		}
2472 	}
2473 	free(d2);
2474 	return mkseq(el);
2475 }
2476 
2477 uchar*
RSApubtoasn1(RSApub * pub,int * keylen)2478 RSApubtoasn1(RSApub *pub, int *keylen)
2479 {
2480 	Elem pubkey;
2481 	Bytes *pkbytes;
2482 	uchar *key;
2483 
2484 	key = nil;
2485 	pubkey = mkseq(mkel(mkbigint(pub->n),mkel(mkint(mptoi(pub->ek)),nil)));
2486 	if(encode(pubkey, &pkbytes) != ASN_OK)
2487 		goto errret;
2488 	freevalfields(&pubkey.val);
2489 	pubkey = mkseq(
2490 		mkel(mkalg(ALG_rsaEncryption),
2491 		mkel(mkbits(pkbytes->data, pkbytes->len),
2492 		nil)));
2493 	freebytes(pkbytes);
2494 	if(encode(pubkey, &pkbytes) != ASN_OK)
2495 		goto errret;
2496 	if(keylen)
2497 		*keylen = pkbytes->len;
2498 	key = malloc(pkbytes->len);
2499 	memmove(key, pkbytes->data, pkbytes->len);
2500 	free(pkbytes);
2501 errret:
2502 	freevalfields(&pubkey.val);
2503 	return key;
2504 }
2505 
2506 uchar*
X509gen(RSApriv * priv,char * subj,ulong valid[2],int * certlen)2507 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2508 {
2509 	int serial = 0;
2510 	uchar *cert = nil;
2511 	RSApub *pk = rsaprivtopub(priv);
2512 	Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2513 	Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2514 	uchar digest[MD5dlen], *buf;
2515 	int buflen;
2516 	mpint *pkcs1;
2517 
2518 	e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2519 	issuer = mkDN(subj);
2520 	subject = mkDN(subj);
2521 	pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2522 	if(encode(pubkey, &pkbytes) != ASN_OK)
2523 		goto errret;
2524 	freevalfields(&pubkey.val);
2525 	pubkey = mkseq(
2526 		mkel(mkalg(ALG_rsaEncryption),
2527 		mkel(mkbits(pkbytes->data, pkbytes->len),
2528 		nil)));
2529 	freebytes(pkbytes);
2530 	validity = mkseq(
2531 		mkel(mkutc(valid[0]),
2532 		mkel(mkutc(valid[1]),
2533 		nil)));
2534 	certinfo = mkseq(
2535 		mkel(mkint(serial),
2536 		mkel(mkalg(ALG_md5WithRSAEncryption),
2537 		mkel(issuer,
2538 		mkel(validity,
2539 		mkel(subject,
2540 		mkel(pubkey,
2541 		nil)))))));
2542 	if(encode(certinfo, &certinfobytes) != ASN_OK)
2543 		goto errret;
2544 	md5(certinfobytes->data, certinfobytes->len, digest, 0);
2545 	freebytes(certinfobytes);
2546 	sig = mkseq(
2547 		mkel(mkalg(ALG_md5),
2548 		mkel(mkoctet(digest, MD5dlen),
2549 		nil)));
2550 	if(encode(sig, &sigbytes) != ASN_OK)
2551 		goto errret;
2552 	pkcs1 = pkcs1pad(sigbytes, pk->n);
2553 	freebytes(sigbytes);
2554 	rsadecrypt(priv, pkcs1, pkcs1);
2555 	buflen = mptobe(pkcs1, nil, 0, &buf);
2556 	mpfree(pkcs1);
2557 	e = mkseq(
2558 		mkel(certinfo,
2559 		mkel(mkalg(ALG_md5WithRSAEncryption),
2560 		mkel(mkbits(buf, buflen),
2561 		nil))));
2562 	free(buf);
2563 	if(encode(e, &certbytes) != ASN_OK)
2564 		goto errret;
2565 	if(certlen)
2566 		*certlen = certbytes->len;
2567 	cert = certbytes->data;
2568 errret:
2569 	freevalfields(&e.val);
2570 	return cert;
2571 }
2572 
2573 uchar*
X509req(RSApriv * priv,char * subj,int * certlen)2574 X509req(RSApriv *priv, char *subj, int *certlen)
2575 {
2576 	/* RFC 2314, PKCS #10 Certification Request Syntax */
2577 	int version = 0;
2578 	uchar *cert = nil;
2579 	RSApub *pk = rsaprivtopub(priv);
2580 	Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2581 	Elem e, certinfo, subject, pubkey, sig;
2582 	uchar digest[MD5dlen], *buf;
2583 	int buflen;
2584 	mpint *pkcs1;
2585 
2586 	e.val.tag = VInt;  /* so freevalfields at errret is no-op */
2587 	subject = mkDN(subj);
2588 	pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2589 	if(encode(pubkey, &pkbytes) != ASN_OK)
2590 		goto errret;
2591 	freevalfields(&pubkey.val);
2592 	pubkey = mkseq(
2593 		mkel(mkalg(ALG_rsaEncryption),
2594 		mkel(mkbits(pkbytes->data, pkbytes->len),
2595 		nil)));
2596 	freebytes(pkbytes);
2597 	certinfo = mkseq(
2598 		mkel(mkint(version),
2599 		mkel(subject,
2600 		mkel(pubkey,
2601 		nil))));
2602 	if(encode(certinfo, &certinfobytes) != ASN_OK)
2603 		goto errret;
2604 	md5(certinfobytes->data, certinfobytes->len, digest, 0);
2605 	freebytes(certinfobytes);
2606 	sig = mkseq(
2607 		mkel(mkalg(ALG_md5),
2608 		mkel(mkoctet(digest, MD5dlen),
2609 		nil)));
2610 	if(encode(sig, &sigbytes) != ASN_OK)
2611 		goto errret;
2612 	pkcs1 = pkcs1pad(sigbytes, pk->n);
2613 	freebytes(sigbytes);
2614 	rsadecrypt(priv, pkcs1, pkcs1);
2615 	buflen = mptobe(pkcs1, nil, 0, &buf);
2616 	mpfree(pkcs1);
2617 	e = mkseq(
2618 		mkel(certinfo,
2619 		mkel(mkalg(ALG_md5),
2620 		mkel(mkbits(buf, buflen),
2621 		nil))));
2622 	free(buf);
2623 	if(encode(e, &certbytes) != ASN_OK)
2624 		goto errret;
2625 	if(certlen)
2626 		*certlen = certbytes->len;
2627 	cert = certbytes->data;
2628 errret:
2629 	freevalfields(&e.val);
2630 	return cert;
2631 }
2632 
2633 static char*
tagdump(Tag tag)2634 tagdump(Tag tag)
2635 {
2636 	if(tag.class != Universal)
2637 		return smprint("class%d,num%d", tag.class, tag.num);
2638 	switch(tag.num){
2639 	case BOOLEAN: return "BOOLEAN";
2640 	case INTEGER: return "INTEGER";
2641 	case BIT_STRING: return "BIT STRING";
2642 	case OCTET_STRING: return "OCTET STRING";
2643 	case NULLTAG: return "NULLTAG";
2644 	case OBJECT_ID: return "OID";
2645 	case ObjectDescriptor: return "OBJECT_DES";
2646 	case EXTERNAL: return "EXTERNAL";
2647 	case REAL: return "REAL";
2648 	case ENUMERATED: return "ENUMERATED";
2649 	case EMBEDDED_PDV: return "EMBEDDED PDV";
2650 	case SEQUENCE: return "SEQUENCE";
2651 	case SETOF: return "SETOF";
2652 	case UTF8String: return "UTF8String";
2653 	case NumericString: return "NumericString";
2654 	case PrintableString: return "PrintableString";
2655 	case TeletexString: return "TeletexString";
2656 	case VideotexString: return "VideotexString";
2657 	case IA5String: return "IA5String";
2658 	case UTCTime: return "UTCTime";
2659 	case GeneralizedTime: return "GeneralizedTime";
2660 	case GraphicString: return "GraphicString";
2661 	case VisibleString: return "VisibleString";
2662 	case GeneralString: return "GeneralString";
2663 	case UniversalString: return "UniversalString";
2664 	case BMPString: return "BMPString";
2665 	default:
2666 		return smprint("Universal,num%d", tag.num);
2667 	}
2668 }
2669 
2670 static void
edump(Elem e)2671 edump(Elem e)
2672 {
2673 	Value v;
2674 	Elist *el;
2675 	int i;
2676 
2677 	print("%s{", tagdump(e.tag));
2678 	v = e.val;
2679 	switch(v.tag){
2680 	case VBool: print("Bool %d",v.u.boolval); break;
2681 	case VInt: print("Int %d",v.u.intval); break;
2682 	case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2683 	case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2684 	case VReal: print("Real..."); break;
2685 	case VOther: print("Other..."); break;
2686 	case VBitString: print("BitString");
2687 		for(i = 0; i<v.u.bitstringval->len; i++)
2688 			print(" %02x", v.u.bitstringval->data[i]);
2689 		break;
2690 	case VNull: print("Null"); break;
2691 	case VEOC: print("EOC..."); break;
2692 	case VObjId: print("ObjId");
2693 		for(i = 0; i<v.u.objidval->len; i++)
2694 			print(" %d", v.u.objidval->data[i]);
2695 		break;
2696 	case VString: print("String \"%s\"",v.u.stringval); break;
2697 	case VSeq: print("Seq\n");
2698 		for(el = v.u.seqval; el!=nil; el = el->tl)
2699 			edump(el->hd);
2700 		break;
2701 	case VSet: print("Set\n");
2702 		for(el = v.u.setval; el!=nil; el = el->tl)
2703 			edump(el->hd);
2704 		break;
2705 	}
2706 	print("}\n");
2707 }
2708 
2709 void
asn1dump(uchar * der,int len)2710 asn1dump(uchar *der, int len)
2711 {
2712 	Elem e;
2713 
2714 	if(decode(der, len, &e) != ASN_OK){
2715 		print("didn't parse\n");
2716 		exits("didn't parse");
2717 	}
2718 	edump(e);
2719 }
2720 
2721 void
X509dump(uchar * cert,int ncert)2722 X509dump(uchar *cert, int ncert)
2723 {
2724 	char *e;
2725 	Bytes *b;
2726 	CertX509 *c;
2727 	RSApub *pk;
2728 	uchar digest[SHA1dlen];
2729 	Elem *sigalg;
2730 
2731 	print("begin X509dump\n");
2732 	b = makebytes(cert, ncert);
2733 	c = decode_cert(b);
2734 	if(c != nil)
2735 		digest_certinfo(b, digestalg[c->signature_alg], digest);
2736 	freebytes(b);
2737 	if(c == nil){
2738 		print("cannot decode cert");
2739 		return;
2740 	}
2741 
2742 	print("serial %d\n", c->serial);
2743 	print("issuer %s\n", c->issuer);
2744 	print("validity %s %s\n", c->validity_start, c->validity_end);
2745 	print("subject %s\n", c->subject);
2746 	pk = decode_rsapubkey(c->publickey);
2747 	print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2748 
2749 	print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2750 	e = verify_signature(c->signature, pk, digest, &sigalg);
2751 	if(e==nil){
2752 		e = "nil (meaning ok)";
2753 		print("sigalg=\n");
2754 		if(sigalg)
2755 			edump(*sigalg);
2756 	}
2757 	print("self-signed verify_signature returns: %s\n", e);
2758 
2759 	rsapubfree(pk);
2760 	freecert(c);
2761 	print("end X509dump\n");
2762 }
2763