Subversion Repositories planix.SVN

Rev

Rev 2 | Details | Compare with Previous | Last modification | View Log | RSS feed

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