plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

x509.c (51561B)


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