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