Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <mp.h>
4 #include <libsec.h>
6 typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
8 /* ANSI offsetof, backwards. */
9 #define OFFSETOF(a, b) offsetof(b, a)
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;
27 /* tag classes */
28 #define Universal 0
29 #define Context 0x80
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
58 struct Bytes {
59 int len;
60 uchar data[1];
61 };
63 struct Ints {
64 int len;
65 int data[1];
66 };
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 };
74 struct Tag {
75 int class;
76 int num;
77 };
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 };
98 struct Elem {
99 Tag tag;
100 Value val;
101 };
103 struct Elist {
104 Elist* tl;
105 Elem hd;
106 };
108 /* decoding errors */
109 enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
110 ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
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);
146 #define TAG_MASK 0x1F
147 #define CONSTR_MASK 0x20
148 #define CLASS_MASK 0xC0
149 #define MAXOBJIDLEN 20
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);
164 static void *
165 emalloc(int n)
167 void *p;
168 if(n==0)
169 n=1;
170 p = malloc(n);
171 if(p == nil){
172 exits("out of memory");
174 memset(p, 0, n);
175 return p;
178 static char*
179 estrdup(char *s)
181 char *d, *d0;
183 if(!s)
184 return 0;
185 d = d0 = emalloc(strlen(s)+1);
186 while(*d++ = *s++)
188 return d0;
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)
201 uchar* p = a;
203 return ber_decode(&p, &a[alen], pelem);
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)
213 uchar* p = a;
215 return seq_decode(&p, &a[alen], -1, 1, pelist);
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)
230 uchar* p = a;
232 return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
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.
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 */
248 /* Decode an ASN1 'Elem' (tag, length, value) */
249 static int
250 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
252 int err;
253 int isconstr;
254 int length;
255 Tag tag;
256 Value val;
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;
272 return err;
275 /* Decode a tag field */
276 static int
277 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
279 int err;
280 int v;
281 uchar* p;
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;
297 else
298 err = ASN_ESHORT;
299 *pp = p;
300 return err;
303 /* Decode a length field */
304 static int
305 length_decode(uchar** pp, uchar* pend, int* plength)
307 int err;
308 int num;
309 int v;
310 uchar* p;
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
320 num = v;
322 else
323 err = ASN_ESHORT;
324 *pp = p;
325 *plength = num;
326 return err;
329 /* Decode a value field */
330 static int
331 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
333 int err;
334 Bytes* va;
335 int num;
336 int bitsunused;
337 int subids[MAXOBJIDLEN];
338 int isubid;
339 Elist* vl;
340 uchar* p;
341 uchar* pe;
343 err = ASN_OK;
344 p = *pp;
345 if(length == -1) { /* "indefinite" length spec */
346 if(!isconstr)
347 err = ASN_EINVAL;
349 else if(p + length > pend)
350 err = ASN_EVALLEN;
351 if(err != ASN_OK)
352 return err;
354 switch(kind) {
355 case 0:
356 /* marker for end of indefinite constructions */
357 if(length == 0)
358 pval->tag = VNull;
359 else
360 err = ASN_EINVAL;
361 break;
363 case BOOLEAN:
364 if(isconstr)
365 err = ASN_ECONSTR;
366 else if(length != 1)
367 err = ASN_EVALLEN;
368 else {
369 pval->tag = VBool;
370 pval->u.boolval = (*p++ != 0);
372 break;
374 case INTEGER:
375 case ENUMERATED:
376 if(isconstr)
377 err = ASN_ECONSTR;
378 else if(length <= 4) {
379 err = int_decode(&p, pend, length, 0, &num);
380 if(err == ASN_OK) {
381 pval->tag = VInt;
382 pval->u.intval = num;
385 else {
386 pval->tag = VBigInt;
387 pval->u.bigintval = makebytes(p, length);
388 p += length;
390 break;
392 case BIT_STRING:
393 pval->tag = VBitString;
394 if(isconstr) {
395 if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
396 pval->u.bitstringval = makebits(0, 0, 0);
397 p += 2;
399 else
400 /* TODO: recurse and concat results */
401 err = ASN_EUNIMPL;
403 else {
404 if(length < 2) {
405 if(length == 1 && *p == 0) {
406 pval->u.bitstringval = makebits(0, 0, 0);
407 p++;
409 else
410 err = ASN_EINVAL;
412 else {
413 bitsunused = *p;
414 if(bitsunused > 7)
415 err = ASN_EINVAL;
416 else if(length > 0x0FFFFFFF)
417 err = ASN_ETOOBIG;
418 else {
419 pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
420 p += length;
424 break;
426 case OCTET_STRING:
427 case ObjectDescriptor:
428 err = octet_decode(&p, pend, length, isconstr, &va);
429 if(err == ASN_OK) {
430 pval->tag = VOctets;
431 pval->u.octetsval = va;
433 break;
435 case NULLTAG:
436 if(isconstr)
437 err = ASN_ECONSTR;
438 else if(length != 0)
439 err = ASN_EVALLEN;
440 else
441 pval->tag = VNull;
442 break;
444 case OBJECT_ID:
445 if(isconstr)
446 err = ASN_ECONSTR;
447 else if(length == 0)
448 err = ASN_EVALLEN;
449 else {
450 isubid = 0;
451 pe = p+length;
452 while(p < pe && isubid < MAXOBJIDLEN) {
453 err = uint7_decode(&p, pend, &num);
454 if(err != ASN_OK)
455 break;
456 if(isubid == 0) {
457 subids[isubid++] = num / 40;
458 subids[isubid++] = num % 40;
460 else
461 subids[isubid++] = num;
463 if(err == ASN_OK) {
464 if(p != pe)
465 err = ASN_EVALLEN;
466 else {
467 pval->tag = VObjId;
468 pval->u.objidval = makeints(subids, isubid);
472 break;
474 case EXTERNAL:
475 case EMBEDDED_PDV:
476 /* TODO: parse this internally */
477 if(p+length > pend)
478 err = ASN_EVALLEN;
479 else {
480 pval->tag = VOther;
481 pval->u.otherval = makebytes(p, length);
482 p += length;
484 break;
486 case REAL:
487 /* Let the application decode */
488 if(isconstr)
489 err = ASN_ECONSTR;
490 else if(p+length > pend)
491 err = ASN_EVALLEN;
492 else {
493 pval->tag = VReal;
494 pval->u.realval = makebytes(p, length);
495 p += length;
497 break;
499 case SEQUENCE:
500 err = seq_decode(&p, pend, length, isconstr, &vl);
501 if(err == ASN_OK) {
502 pval->tag = VSeq ;
503 pval->u.seqval = vl;
505 break;
507 case SETOF:
508 err = seq_decode(&p, pend, length, isconstr, &vl);
509 if(err == ASN_OK) {
510 pval->tag = VSet;
511 pval->u.setval = vl;
513 break;
515 case NumericString:
516 case PrintableString:
517 case TeletexString:
518 case VideotexString:
519 case IA5String:
520 case UTCTime:
521 case GeneralizedTime:
522 case GraphicString:
523 case VisibleString:
524 case GeneralString:
525 case UniversalString:
526 case BMPString:
527 /* TODO: figure out when character set conversion is necessary */
528 err = octet_decode(&p, pend, length, isconstr, &va);
529 if(err == ASN_OK) {
530 pval->tag = VString;
531 pval->u.stringval = (char*)emalloc(va->len+1);
532 memmove(pval->u.stringval, va->data, va->len);
533 pval->u.stringval[va->len] = 0;
534 free(va);
536 break;
538 default:
539 if(p+length > pend)
540 err = ASN_EVALLEN;
541 else {
542 pval->tag = VOther;
543 pval->u.otherval = makebytes(p, length);
544 p += length;
546 break;
548 *pp = p;
549 return err;
552 /*
553 * Decode an int in format where count bytes are
554 * concatenated to form value.
555 * Although ASN1 allows any size integer, we return
556 * an error if the result doesn't fit in a 32-bit int.
557 * If unsgned is not set, make sure to propagate sign bit.
558 */
559 static int
560 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
562 int err;
563 int num;
564 uchar* p;
566 p = *pp;
567 err = ASN_OK;
568 num = 0;
569 if(p+count <= pend) {
570 if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
571 err = ASN_ETOOBIG;
572 else {
573 if(!unsgned && count > 0 && count < 4 && (*p&0x80))
574 num = -1; // set all bits, initially
575 while(count--)
576 num = (num << 8)|(*p++);
579 else
580 err = ASN_ESHORT;
581 *pint = num;
582 *pp = p;
583 return err;
586 /*
587 * Decode an unsigned int in format where each
588 * byte except last has high bit set, and remaining
589 * seven bits of each byte are concatenated to form value.
590 * Although ASN1 allows any size integer, we return
591 * an error if the result doesn't fit in a 32 bit int.
592 */
593 static int
594 uint7_decode(uchar** pp, uchar* pend, int* pint)
596 int err;
597 int num;
598 int more;
599 int v;
600 uchar* p;
602 p = *pp;
603 err = ASN_OK;
604 num = 0;
605 more = 1;
606 while(more && p < pend) {
607 v = *p++;
608 if(num&0x7F000000) {
609 err = ASN_ETOOBIG;
610 break;
612 num <<= 7;
613 more = v&0x80;
614 num |= (v&0x7F);
616 if(p == pend)
617 err = ASN_ESHORT;
618 *pint = num;
619 *pp = p;
620 return err;
623 /*
624 * Decode an octet string, recursively if isconstr.
625 * We've already checked that length==-1 implies isconstr==1,
626 * and otherwise that specified length fits within (*pp..pend)
627 */
628 static int
629 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
631 int err;
632 uchar* p;
633 Bytes* ans;
634 Bytes* newans;
635 uchar* pstart;
636 uchar* pold;
637 Elem elem;
639 err = ASN_OK;
640 p = *pp;
641 ans = nil;
642 if(length >= 0 && !isconstr) {
643 ans = makebytes(p, length);
644 p += length;
646 else {
647 /* constructed, either definite or indefinite length */
648 pstart = p;
649 for(;;) {
650 if(length >= 0 && p >= pstart + length) {
651 if(p != pstart + length)
652 err = ASN_EVALLEN;
653 break;
655 pold = p;
656 err = ber_decode(&p, pend, &elem);
657 if(err != ASN_OK)
658 break;
659 switch(elem.val.tag) {
660 case VOctets:
661 newans = catbytes(ans, elem.val.u.octetsval);
662 freebytes(ans);
663 ans = newans;
664 break;
666 case VEOC:
667 if(length != -1) {
668 p = pold;
669 err = ASN_EINVAL;
671 goto cloop_done;
673 default:
674 p = pold;
675 err = ASN_EINVAL;
676 goto cloop_done;
679 cloop_done:
682 *pp = p;
683 *pbytes = ans;
684 return err;
687 /*
688 * Decode a sequence or set.
689 * We've already checked that length==-1 implies isconstr==1,
690 * and otherwise that specified length fits within (*p..pend)
691 */
692 static int
693 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
695 int err;
696 uchar* p;
697 uchar* pstart;
698 uchar* pold;
699 Elist* ans;
700 Elem elem;
701 Elist* lve;
702 Elist* lveold;
704 err = ASN_OK;
705 ans = nil;
706 p = *pp;
707 if(!isconstr)
708 err = ASN_EPRIM;
709 else {
710 /* constructed, either definite or indefinite length */
711 lve = nil;
712 pstart = p;
713 for(;;) {
714 if(length >= 0 && p >= pstart + length) {
715 if(p != pstart + length)
716 err = ASN_EVALLEN;
717 break;
719 pold = p;
720 err = ber_decode(&p, pend, &elem);
721 if(err != ASN_OK)
722 break;
723 if(elem.val.tag == VEOC) {
724 if(length != -1) {
725 p = pold;
726 err = ASN_EINVAL;
728 break;
730 else
731 lve = mkel(elem, lve);
733 if(err == ASN_OK) {
734 /* reverse back to original order */
735 while(lve != nil) {
736 lveold = lve;
737 lve = lve->tl;
738 lveold->tl = ans;
739 ans = lveold;
743 *pp = p;
744 *pelist = ans;
745 return err;
748 /*
749 * Encode e by BER rules, putting answer in *pbytes.
750 * This is done by first calling enc with lenonly==1
751 * to get the length of the needed buffer,
752 * then allocating the buffer and using enc again to fill it up.
753 */
754 static int
755 encode(Elem e, Bytes** pbytes)
757 uchar* p;
758 Bytes* ans;
759 int err;
760 uchar uc;
762 p = &uc;
763 err = enc(&p, e, 1);
764 if(err == ASN_OK) {
765 ans = newbytes(p-&uc);
766 p = ans->data;
767 err = enc(&p, e, 0);
768 *pbytes = ans;
770 return err;
773 /*
774 * The various enc functions take a pointer to a pointer
775 * into a buffer, and encode their entity starting there,
776 * updating the pointer afterwards.
777 * If lenonly is 1, only the pointer update is done,
778 * allowing enc to be called first to calculate the needed
779 * buffer length.
780 * If lenonly is 0, it is assumed that the answer will fit.
781 */
783 static int
784 enc(uchar** pp, Elem e, int lenonly)
786 int err;
787 int vlen;
788 int constr;
789 Tag tag;
790 int v;
791 int ilen;
792 uchar* p;
793 uchar* psave;
795 p = *pp;
796 err = val_enc(&p, e, &constr, 1);
797 if(err != ASN_OK)
798 return err;
799 vlen = p - *pp;
800 p = *pp;
801 tag = e.tag;
802 v = tag.class|constr;
803 if(tag.num < 31) {
804 if(!lenonly)
805 *p = (v|tag.num);
806 p++;
808 else {
809 if(!lenonly)
810 *p = (v|31);
811 p++;
812 if(tag.num < 0)
813 return ASN_EINVAL;
814 uint7_enc(&p, tag.num, lenonly);
816 if(vlen < 0x80) {
817 if(!lenonly)
818 *p = vlen;
819 p++;
821 else {
822 psave = p;
823 int_enc(&p, vlen, 1, 1);
824 ilen = p-psave;
825 p = psave;
826 if(!lenonly) {
827 *p++ = (0x80 | ilen);
828 int_enc(&p, vlen, 1, 0);
830 else
831 p += 1 + ilen;
833 if(!lenonly)
834 val_enc(&p, e, &constr, 0);
835 else
836 p += vlen;
837 *pp = p;
838 return err;
841 static int
842 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
844 int err;
845 uchar* p;
846 int kind;
847 int cl;
848 int v;
849 Bytes* bb = nil;
850 Bits* bits;
851 Ints* oid;
852 int k;
853 Elist* el;
854 char* s;
856 p = *pp;
857 err = ASN_OK;
858 kind = e.tag.num;
859 cl = e.tag.class;
860 *pconstr = 0;
861 if(cl != Universal) {
862 switch(e.val.tag) {
863 case VBool:
864 kind = BOOLEAN;
865 break;
866 case VInt:
867 kind = INTEGER;
868 break;
869 case VBigInt:
870 kind = INTEGER;
871 break;
872 case VOctets:
873 kind = OCTET_STRING;
874 break;
875 case VReal:
876 kind = REAL;
877 break;
878 case VOther:
879 kind = OCTET_STRING;
880 break;
881 case VBitString:
882 kind = BIT_STRING;
883 break;
884 case VNull:
885 kind = NULLTAG;
886 break;
887 case VObjId:
888 kind = OBJECT_ID;
889 break;
890 case VString:
891 kind = UniversalString;
892 break;
893 case VSeq:
894 kind = SEQUENCE;
895 break;
896 case VSet:
897 kind = SETOF;
898 break;
901 switch(kind) {
902 case BOOLEAN:
903 if(is_int(&e, &v)) {
904 if(v != 0)
905 v = 255;
906 int_enc(&p, v, 1, lenonly);
908 else
909 err = ASN_EINVAL;
910 break;
912 case INTEGER:
913 case ENUMERATED:
914 if(is_int(&e, &v))
915 int_enc(&p, v, 0, lenonly);
916 else {
917 if(is_bigint(&e, &bb)) {
918 if(!lenonly)
919 memmove(p, bb->data, bb->len);
920 p += bb->len;
922 else
923 err = ASN_EINVAL;
925 break;
927 case BIT_STRING:
928 if(is_bitstring(&e, &bits)) {
929 if(bits->len == 0) {
930 if(!lenonly)
931 *p = 0;
932 p++;
934 else {
935 v = bits->unusedbits;
936 if(v < 0 || v > 7)
937 err = ASN_EINVAL;
938 else {
939 if(!lenonly) {
940 *p = v;
941 memmove(p+1, bits->data, bits->len);
943 p += 1 + bits->len;
947 else
948 err = ASN_EINVAL;
949 break;
951 case OCTET_STRING:
952 case ObjectDescriptor:
953 case EXTERNAL:
954 case REAL:
955 case EMBEDDED_PDV:
956 bb = nil;
957 switch(e.val.tag) {
958 case VOctets:
959 bb = e.val.u.octetsval;
960 break;
961 case VReal:
962 bb = e.val.u.realval;
963 break;
964 case VOther:
965 bb = e.val.u.otherval;
966 break;
968 if(bb != nil) {
969 if(!lenonly)
970 memmove(p, bb->data, bb->len);
971 p += bb->len;
973 else
974 err = ASN_EINVAL;
975 break;
977 case NULLTAG:
978 break;
980 case OBJECT_ID:
981 if(is_oid(&e, &oid)) {
982 for(k = 0; k < oid->len; k++) {
983 v = oid->data[k];
984 if(k == 0) {
985 v *= 40;
986 if(oid->len > 1)
987 v += oid->data[++k];
989 uint7_enc(&p, v, lenonly);
992 else
993 err = ASN_EINVAL;
994 break;
996 case SEQUENCE:
997 case SETOF:
998 el = nil;
999 if(e.val.tag == VSeq)
1000 el = e.val.u.seqval;
1001 else if(e.val.tag == VSet)
1002 el = e.val.u.setval;
1003 else
1004 err = ASN_EINVAL;
1005 if(el != nil) {
1006 *pconstr = CONSTR_MASK;
1007 for(; el != nil; el = el->tl) {
1008 err = enc(&p, el->hd, lenonly);
1009 if(err != ASN_OK)
1010 break;
1013 break;
1015 case NumericString:
1016 case PrintableString:
1017 case TeletexString:
1018 case VideotexString:
1019 case IA5String:
1020 case UTCTime:
1021 case GeneralizedTime:
1022 case GraphicString:
1023 case VisibleString:
1024 case GeneralString:
1025 case UniversalString:
1026 case BMPString:
1027 if(e.val.tag == VString) {
1028 s = e.val.u.stringval;
1029 if(s != nil) {
1030 v = strlen(s);
1031 if(!lenonly)
1032 memmove(p, s, v);
1033 p += v;
1036 else
1037 err = ASN_EINVAL;
1038 break;
1040 default:
1041 err = ASN_EINVAL;
1043 *pp = p;
1044 return err;
1048 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1049 * except last, only putting in bytes if !lenonly.
1051 static void
1052 uint7_enc(uchar** pp, int num, int lenonly)
1054 int n;
1055 int v;
1056 int k;
1057 uchar* p;
1059 p = *pp;
1060 n = 1;
1061 v = num >> 7;
1062 while(v > 0) {
1063 v >>= 7;
1064 n++;
1066 if(lenonly)
1067 p += n;
1068 else {
1069 for(k = (n - 1)*7; k > 0; k -= 7)
1070 *p++= ((num >> k)|0x80);
1071 *p++ = (num&0x7F);
1073 *pp = p;
1077 * Encode num as unsigned or signed integer,
1078 * only putting in bytes if !lenonly.
1079 * Encoding is length followed by bytes to concatenate.
1081 static void
1082 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1084 int v;
1085 int n;
1086 int prevv;
1087 int k;
1088 uchar* p;
1090 p = *pp;
1091 v = num;
1092 if(v < 0)
1093 v = -(v + 1);
1094 n = 1;
1095 prevv = v;
1096 v >>= 8;
1097 while(v > 0) {
1098 prevv = v;
1099 v >>= 8;
1100 n++;
1102 if(!unsgned && (prevv&0x80))
1103 n++;
1104 if(lenonly)
1105 p += n;
1106 else {
1107 for(k = (n - 1)*8; k >= 0; k -= 8)
1108 *p++ = (num >> k);
1110 *pp = p;
1113 static int
1114 ints_eq(Ints* a, Ints* b)
1116 int alen;
1117 int i;
1119 alen = a->len;
1120 if(alen != b->len)
1121 return 0;
1122 for(i = 0; i < alen; i++)
1123 if(a->data[i] != b->data[i])
1124 return 0;
1125 return 1;
1129 * Look up o in tab (which must have nil entry to terminate).
1130 * Return index of matching entry, or -1 if none.
1132 static int
1133 oid_lookup(Ints* o, Ints** tab)
1135 int i;
1137 for(i = 0; tab[i] != nil; i++)
1138 if(ints_eq(o, tab[i]))
1139 return i;
1140 return -1;
1144 * Return true if *pe is a SEQUENCE, and set *pseq to
1145 * the value of the sequence if so.
1147 static int
1148 is_seq(Elem* pe, Elist** pseq)
1150 if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1151 *pseq = pe->val.u.seqval;
1152 return 1;
1154 return 0;
1157 static int
1158 is_set(Elem* pe, Elist** pset)
1160 if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1161 *pset = pe->val.u.setval;
1162 return 1;
1164 return 0;
1167 static int
1168 is_int(Elem* pe, int* pint)
1170 if(pe->tag.class == Universal) {
1171 if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1172 *pint = pe->val.u.intval;
1173 return 1;
1175 else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1176 *pint = pe->val.u.boolval;
1177 return 1;
1180 return 0;
1184 * for convience, all VInt's are readable via this routine,
1185 * as well as all VBigInt's
1187 static int
1188 is_bigint(Elem* pe, Bytes** pbigint)
1190 int v, n, i;
1192 if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
1193 if(pe->val.tag == VBigInt)
1194 *pbigint = pe->val.u.bigintval;
1195 else if(pe->val.tag == VInt){
1196 v = pe->val.u.intval;
1197 for(n = 1; n < 4; n++)
1198 if((1 << (8 * n)) > v)
1199 break;
1200 *pbigint = newbytes(n);
1201 for(i = 0; i < n; i++)
1202 (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1203 }else
1204 return 0;
1205 return 1;
1207 return 0;
1210 static int
1211 is_bitstring(Elem* pe, Bits** pbits)
1213 if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1214 *pbits = pe->val.u.bitstringval;
1215 return 1;
1217 return 0;
1220 static int
1221 is_octetstring(Elem* pe, Bytes** poctets)
1223 if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1224 *poctets = pe->val.u.octetsval;
1225 return 1;
1227 return 0;
1230 static int
1231 is_oid(Elem* pe, Ints** poid)
1233 if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1234 *poid = pe->val.u.objidval;
1235 return 1;
1237 return 0;
1240 static int
1241 is_string(Elem* pe, char** pstring)
1243 if(pe->tag.class == Universal) {
1244 switch(pe->tag.num) {
1245 case NumericString:
1246 case PrintableString:
1247 case TeletexString:
1248 case VideotexString:
1249 case IA5String:
1250 case GraphicString:
1251 case VisibleString:
1252 case GeneralString:
1253 case UniversalString:
1254 case BMPString:
1255 if(pe->val.tag == VString) {
1256 *pstring = pe->val.u.stringval;
1257 return 1;
1261 return 0;
1264 static int
1265 is_time(Elem* pe, char** ptime)
1267 if(pe->tag.class == Universal
1268 && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1269 && pe->val.tag == VString) {
1270 *ptime = pe->val.u.stringval;
1271 return 1;
1273 return 0;
1278 * malloc and return a new Bytes structure capable of
1279 * holding len bytes. (len >= 0)
1281 static Bytes*
1282 newbytes(int len)
1284 Bytes* ans;
1286 ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1287 ans->len = len;
1288 return ans;
1292 * newbytes(len), with data initialized from buf
1294 static Bytes*
1295 makebytes(uchar* buf, int len)
1297 Bytes* ans;
1299 ans = newbytes(len);
1300 memmove(ans->data, buf, len);
1301 return ans;
1304 static void
1305 freebytes(Bytes* b)
1307 if(b != nil)
1308 free(b);
1312 * Make a new Bytes, containing bytes of b1 followed by those of b2.
1313 * Either b1 or b2 or both can be nil.
1315 static Bytes*
1316 catbytes(Bytes* b1, Bytes* b2)
1318 Bytes* ans;
1319 int n;
1321 if(b1 == nil) {
1322 if(b2 == nil)
1323 ans = newbytes(0);
1324 else
1325 ans = makebytes(b2->data, b2->len);
1327 else if(b2 == nil) {
1328 ans = makebytes(b1->data, b1->len);
1330 else {
1331 n = b1->len + b2->len;
1332 ans = newbytes(n);
1333 ans->len = n;
1334 memmove(ans->data, b1->data, b1->len);
1335 memmove(ans->data+b1->len, b2->data, b2->len);
1337 return ans;
1340 /* len is number of ints */
1341 static Ints*
1342 newints(int len)
1344 Ints* ans;
1346 ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1347 ans->len = len;
1348 return ans;
1351 static Ints*
1352 makeints(int* buf, int len)
1354 Ints* ans;
1356 ans = newints(len);
1357 if(len > 0)
1358 memmove(ans->data, buf, len*sizeof(int));
1359 return ans;
1362 static void
1363 freeints(Ints* b)
1365 if(b != nil)
1366 free(b);
1369 /* len is number of bytes */
1370 static Bits*
1371 newbits(int len)
1373 Bits* ans;
1375 ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1376 ans->len = len;
1377 ans->unusedbits = 0;
1378 return ans;
1381 static Bits*
1382 makebits(uchar* buf, int len, int unusedbits)
1384 Bits* ans;
1386 ans = newbits(len);
1387 memmove(ans->data, buf, len);
1388 ans->unusedbits = unusedbits;
1389 return ans;
1392 static void
1393 freebits(Bits* b)
1395 if(b != nil)
1396 free(b);
1399 static Elist*
1400 mkel(Elem e, Elist* tail)
1402 Elist* el;
1404 el = (Elist*)emalloc(sizeof(Elist));
1405 el->hd = e;
1406 el->tl = tail;
1407 return el;
1410 static int
1411 elistlen(Elist* el)
1413 int ans = 0;
1414 while(el != nil) {
1415 ans++;
1416 el = el->tl;
1418 return ans;
1421 /* Frees elist, but not fields inside values of constituent elems */
1422 static void
1423 freeelist(Elist* el)
1425 Elist* next;
1427 while(el != nil) {
1428 next = el->tl;
1429 free(el);
1430 el = next;
1434 /* free any allocated structures inside v (recursively freeing Elists) */
1435 static void
1436 freevalfields(Value* v)
1438 Elist* el;
1439 Elist* l;
1440 if(v == nil)
1441 return;
1442 switch(v->tag) {
1443 case VOctets:
1444 freebytes(v->u.octetsval);
1445 break;
1446 case VBigInt:
1447 freebytes(v->u.bigintval);
1448 break;
1449 case VReal:
1450 freebytes(v->u.realval);
1451 break;
1452 case VOther:
1453 freebytes(v->u.otherval);
1454 break;
1455 case VBitString:
1456 freebits(v->u.bitstringval);
1457 break;
1458 case VObjId:
1459 freeints(v->u.objidval);
1460 break;
1461 case VString:
1462 if (v->u.stringval)
1463 free(v->u.stringval);
1464 break;
1465 case VSeq:
1466 el = v->u.seqval;
1467 for(l = el; l != nil; l = l->tl)
1468 freevalfields(&l->hd.val);
1469 if (el)
1470 freeelist(el);
1471 break;
1472 case VSet:
1473 el = v->u.setval;
1474 for(l = el; l != nil; l = l->tl)
1475 freevalfields(&l->hd.val);
1476 if (el)
1477 freeelist(el);
1478 break;
1482 /* end of general ASN1 functions */
1488 /*=============================================================*/
1490 * Decode and parse an X.509 Certificate, defined by this ASN1:
1491 * Certificate ::= SEQUENCE {
1492 * certificateInfo CertificateInfo,
1493 * signatureAlgorithm AlgorithmIdentifier,
1494 * signature BIT STRING }
1496 * CertificateInfo ::= SEQUENCE {
1497 * version [0] INTEGER DEFAULT v1 (0),
1498 * serialNumber INTEGER,
1499 * signature AlgorithmIdentifier,
1500 * issuer Name,
1501 * validity Validity,
1502 * subject Name,
1503 * subjectPublicKeyInfo SubjectPublicKeyInfo }
1504 * (version v2 has two more fields, optional unique identifiers for
1505 * issuer and subject; since we ignore these anyway, we won't parse them)
1507 * Validity ::= SEQUENCE {
1508 * notBefore UTCTime,
1509 * notAfter UTCTime }
1511 * SubjectPublicKeyInfo ::= SEQUENCE {
1512 * algorithm AlgorithmIdentifier,
1513 * subjectPublicKey BIT STRING }
1515 * AlgorithmIdentifier ::= SEQUENCE {
1516 * algorithm OBJECT IDENTIFER,
1517 * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1519 * Name ::= SEQUENCE OF RelativeDistinguishedName
1521 * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1523 * AttributeTypeAndValue ::= SEQUENCE {
1524 * type OBJECT IDENTIFER,
1525 * value DirectoryString }
1526 * (selected attributes have these Object Ids:
1527 * commonName {2 5 4 3}
1528 * countryName {2 5 4 6}
1529 * localityName {2 5 4 7}
1530 * stateOrProvinceName {2 5 4 8}
1531 * organizationName {2 5 4 10}
1532 * organizationalUnitName {2 5 4 11}
1533 * )
1535 * DirectoryString ::= CHOICE {
1536 * teletexString TeletexString,
1537 * printableString PrintableString,
1538 * universalString UniversalString }
1540 * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1542 * Not yet implemented:
1543 * CertificateRevocationList ::= SIGNED SEQUENCE{
1544 * signature AlgorithmIdentifier,
1545 * issuer Name,
1546 * lastUpdate UTCTime,
1547 * nextUpdate UTCTime,
1548 * revokedCertificates
1549 * SEQUENCE OF CRLEntry OPTIONAL}
1550 * CRLEntry ::= SEQUENCE{
1551 * userCertificate SerialNumber,
1552 * revocationDate UTCTime}
1555 typedef struct CertX509 {
1556 int serial;
1557 char* issuer;
1558 char* validity_start;
1559 char* validity_end;
1560 char* subject;
1561 int publickey_alg;
1562 Bytes* publickey;
1563 int signature_alg;
1564 Bytes* signature;
1565 } CertX509;
1567 /* Algorithm object-ids */
1568 enum {
1569 ALG_rsaEncryption,
1570 ALG_md2WithRSAEncryption,
1571 ALG_md4WithRSAEncryption,
1572 ALG_md5WithRSAEncryption,
1573 ALG_sha1WithRSAEncryption,
1574 ALG_md5,
1575 NUMALGS
1577 typedef struct Ints7 {
1578 int len;
1579 int data[7];
1580 } Ints7;
1581 static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1582 static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1583 static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1584 static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1585 static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1586 static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1587 static Ints *alg_oid_tab[NUMALGS+1] = {
1588 (Ints*)&oid_rsaEncryption,
1589 (Ints*)&oid_md2WithRSAEncryption,
1590 (Ints*)&oid_md4WithRSAEncryption,
1591 (Ints*)&oid_md5WithRSAEncryption,
1592 (Ints*)&oid_sha1WithRSAEncryption,
1593 (Ints*)&oid_md5,
1594 nil
1596 static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, 0 };
1598 static void
1599 freecert(CertX509* c)
1601 if (!c) return;
1602 if(c->issuer != nil)
1603 free(c->issuer);
1604 if(c->validity_start != nil)
1605 free(c->validity_start);
1606 if(c->validity_end != nil)
1607 free(c->validity_end);
1608 if(c->subject != nil)
1609 free(c->subject);
1610 freebytes(c->publickey);
1611 freebytes(c->signature);
1615 * Parse the Name ASN1 type.
1616 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1617 * from most general to most specific. Each element of the path can be
1618 * one or more (but usually just one) attribute-value pair, such as
1619 * countryName="US".
1620 * We'll just form a "postal-style" address string by concatenating the elements
1621 * from most specific to least specific, separated by commas.
1622 * Return name-as-string (which must be freed by caller).
1624 static char*
1625 parse_name(Elem* e)
1627 Elist* el;
1628 Elem* es;
1629 Elist* esetl;
1630 Elem* eat;
1631 Elist* eatl;
1632 char* s;
1633 enum { MAXPARTS = 100 };
1634 char* parts[MAXPARTS];
1635 int i;
1636 int plen;
1637 char* ans = nil;
1639 if(!is_seq(e, &el))
1640 goto errret;
1641 i = 0;
1642 plen = 0;
1643 while(el != nil) {
1644 es = &el->hd;
1645 if(!is_set(es, &esetl))
1646 goto errret;
1647 while(esetl != nil) {
1648 eat = &esetl->hd;
1649 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1650 goto errret;
1651 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1652 goto errret;
1653 parts[i++] = s;
1654 plen += strlen(s) + 2; /* room for ", " after */
1655 esetl = esetl->tl;
1657 el = el->tl;
1659 if(i > 0) {
1660 ans = (char*)emalloc(plen);
1661 *ans = '\0';
1662 while(--i >= 0) {
1663 s = parts[i];
1664 strcat(ans, s);
1665 if(i > 0)
1666 strcat(ans, ", ");
1670 errret:
1671 return ans;
1675 * Parse an AlgorithmIdentifer ASN1 type.
1676 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1677 * or -1 if not found.
1678 * For now, ignore parameters, since none of our algorithms need them.
1680 static int
1681 parse_alg(Elem* e)
1683 Elist* el;
1684 Ints* oid;
1686 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1687 return -1;
1688 return oid_lookup(oid, alg_oid_tab);
1691 static CertX509*
1692 decode_cert(Bytes* a)
1694 int ok = 0;
1695 int n;
1696 CertX509* c = nil;
1697 Elem ecert;
1698 Elem* ecertinfo;
1699 Elem* esigalg;
1700 Elem* esig;
1701 Elem* eserial;
1702 Elem* eissuer;
1703 Elem* evalidity;
1704 Elem* esubj;
1705 Elem* epubkey;
1706 Elist* el;
1707 Elist* elcert = nil;
1708 Elist* elcertinfo = nil;
1709 Elist* elvalidity = nil;
1710 Elist* elpubkey = nil;
1711 Bits* bits = nil;
1712 Bytes* b;
1713 Elem* e;
1715 if(decode(a->data, a->len, &ecert) != ASN_OK)
1716 goto errret;
1718 c = (CertX509*)emalloc(sizeof(CertX509));
1719 c->serial = -1;
1720 c->issuer = nil;
1721 c->validity_start = nil;
1722 c->validity_end = nil;
1723 c->subject = nil;
1724 c->publickey_alg = -1;
1725 c->publickey = nil;
1726 c->signature_alg = -1;
1727 c->signature = nil;
1729 /* Certificate */
1730 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1731 goto errret;
1732 ecertinfo = &elcert->hd;
1733 el = elcert->tl;
1734 esigalg = &el->hd;
1735 c->signature_alg = parse_alg(esigalg);
1736 el = el->tl;
1737 esig = &el->hd;
1739 /* Certificate Info */
1740 if(!is_seq(ecertinfo, &elcertinfo))
1741 goto errret;
1742 n = elistlen(elcertinfo);
1743 if(n < 6)
1744 goto errret;
1745 eserial =&elcertinfo->hd;
1746 el = elcertinfo->tl;
1747 /* check for optional version, marked by explicit context tag 0 */
1748 if(eserial->tag.class == Context && eserial->tag.num == 0) {
1749 eserial = &el->hd;
1750 if(n < 7)
1751 goto errret;
1752 el = el->tl;
1755 if(parse_alg(&el->hd) != c->signature_alg)
1756 goto errret;
1757 el = el->tl;
1758 eissuer = &el->hd;
1759 el = el->tl;
1760 evalidity = &el->hd;
1761 el = el->tl;
1762 esubj = &el->hd;
1763 el = el->tl;
1764 epubkey = &el->hd;
1765 if(!is_int(eserial, &c->serial)) {
1766 if(!is_bigint(eserial, &b))
1767 goto errret;
1768 c->serial = -1; /* else we have to change cert struct */
1770 c->issuer = parse_name(eissuer);
1771 if(c->issuer == nil)
1772 goto errret;
1773 /* Validity */
1774 if(!is_seq(evalidity, &elvalidity))
1775 goto errret;
1776 if(elistlen(elvalidity) != 2)
1777 goto errret;
1778 e = &elvalidity->hd;
1779 if(!is_time(e, &c->validity_start))
1780 goto errret;
1781 e->val.u.stringval = nil; /* string ownership transfer */
1782 e = &elvalidity->tl->hd;
1783 if(!is_time(e, &c->validity_end))
1784 goto errret;
1785 e->val.u.stringval = nil; /* string ownership transfer */
1787 /* resume CertificateInfo */
1788 c->subject = parse_name(esubj);
1789 if(c->subject == nil)
1790 goto errret;
1792 /* SubjectPublicKeyInfo */
1793 if(!is_seq(epubkey, &elpubkey))
1794 goto errret;
1795 if(elistlen(elpubkey) != 2)
1796 goto errret;
1798 c->publickey_alg = parse_alg(&elpubkey->hd);
1799 if(c->publickey_alg < 0)
1800 goto errret;
1801 if(!is_bitstring(&elpubkey->tl->hd, &bits))
1802 goto errret;
1803 if(bits->unusedbits != 0)
1804 goto errret;
1805 c->publickey = makebytes(bits->data, bits->len);
1807 /*resume Certificate */
1808 if(c->signature_alg < 0)
1809 goto errret;
1810 if(!is_bitstring(esig, &bits))
1811 goto errret;
1812 c->signature = makebytes(bits->data, bits->len);
1813 ok = 1;
1815 errret:
1816 freevalfields(&ecert.val); /* recurses through lists, too */
1817 if(!ok){
1818 freecert(c);
1819 c = nil;
1821 return c;
1825 * RSAPublickKey :: SEQUENCE {
1826 * modulus INTEGER,
1827 * publicExponent INTEGER
1828 * }
1830 static RSApub*
1831 decode_rsapubkey(Bytes* a)
1833 Elem e;
1834 Elist *el;
1835 mpint *mp;
1836 RSApub* key;
1838 key = rsapuballoc();
1839 if(decode(a->data, a->len, &e) != ASN_OK)
1840 goto errret;
1841 if(!is_seq(&e, &el) || elistlen(el) != 2)
1842 goto errret;
1844 key->n = mp = asn1mpint(&el->hd);
1845 if(mp == nil)
1846 goto errret;
1848 el = el->tl;
1849 key->ek = mp = asn1mpint(&el->hd);
1850 if(mp == nil)
1851 goto errret;
1852 return key;
1853 errret:
1854 rsapubfree(key);
1855 return nil;
1859 * RSAPrivateKey ::= SEQUENCE {
1860 * version Version,
1861 * modulus INTEGER, -- n
1862 * publicExponent INTEGER, -- e
1863 * privateExponent INTEGER, -- d
1864 * prime1 INTEGER, -- p
1865 * prime2 INTEGER, -- q
1866 * exponent1 INTEGER, -- d mod (p-1)
1867 * exponent2 INTEGER, -- d mod (q-1)
1868 * coefficient INTEGER -- (inverse of q) mod p }
1870 static RSApriv*
1871 decode_rsaprivkey(Bytes* a)
1873 int version;
1874 Elem e;
1875 Elist *el;
1876 mpint *mp;
1877 RSApriv* key;
1879 key = rsaprivalloc();
1880 if(decode(a->data, a->len, &e) != ASN_OK)
1881 goto errret;
1882 if(!is_seq(&e, &el) || elistlen(el) != 9)
1883 goto errret;
1884 if(!is_int(&el->hd, &version) || version != 0)
1885 goto errret;
1887 el = el->tl;
1888 key->pub.n = mp = asn1mpint(&el->hd);
1889 if(mp == nil)
1890 goto errret;
1892 el = el->tl;
1893 key->pub.ek = mp = asn1mpint(&el->hd);
1894 if(mp == nil)
1895 goto errret;
1897 el = el->tl;
1898 key->dk = mp = asn1mpint(&el->hd);
1899 if(mp == nil)
1900 goto errret;
1902 el = el->tl;
1903 key->q = mp = asn1mpint(&el->hd);
1904 if(mp == nil)
1905 goto errret;
1907 el = el->tl;
1908 key->p = mp = asn1mpint(&el->hd);
1909 if(mp == nil)
1910 goto errret;
1912 el = el->tl;
1913 key->kq = mp = asn1mpint(&el->hd);
1914 if(mp == nil)
1915 goto errret;
1917 el = el->tl;
1918 key->kp = mp = asn1mpint(&el->hd);
1919 if(mp == nil)
1920 goto errret;
1922 el = el->tl;
1923 key->c2 = mp = asn1mpint(&el->hd);
1924 if(mp == nil)
1925 goto errret;
1927 return key;
1928 errret:
1929 rsaprivfree(key);
1930 return nil;
1933 static mpint*
1934 asn1mpint(Elem *e)
1936 Bytes *b;
1937 mpint *mp;
1938 int v;
1940 if(is_int(e, &v))
1941 return itomp(v, nil);
1942 if(is_bigint(e, &b)) {
1943 mp = betomp(b->data, b->len, nil);
1944 freebytes(b);
1945 return mp;
1947 return nil;
1950 static mpint*
1951 pkcs1pad(Bytes *b, mpint *modulus)
1953 int n = (mpsignif(modulus)+7)/8;
1954 int pm1, i;
1955 uchar *p;
1956 mpint *mp;
1958 pm1 = n - 1 - b->len;
1959 p = (uchar*)emalloc(n);
1960 p[0] = 0;
1961 p[1] = 1;
1962 for(i = 2; i < pm1; i++)
1963 p[i] = 0xFF;
1964 p[pm1] = 0;
1965 memcpy(&p[pm1+1], b->data, b->len);
1966 mp = betomp(p, n, nil);
1967 free(p);
1968 return mp;
1971 RSApriv*
1972 asn1toRSApriv(uchar *kd, int kn)
1974 Bytes *b;
1975 RSApriv *key;
1977 b = makebytes(kd, kn);
1978 key = decode_rsaprivkey(b);
1979 freebytes(b);
1980 return key;
1984 * digest(CertificateInfo)
1985 * Our ASN.1 library doesn't return pointers into the original
1986 * data array, so we need to do a little hand decoding.
1988 static void
1989 digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
1991 uchar *info, *p, *pend;
1992 ulong infolen;
1993 int isconstr, length;
1994 Tag tag;
1995 Elem elem;
1997 p = cert->data;
1998 pend = cert->data + cert->len;
1999 if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2000 tag.class != Universal || tag.num != SEQUENCE ||
2001 length_decode(&p, pend, &length) != ASN_OK ||
2002 p+length > pend ||
2003 p+length < p)
2004 return;
2005 info = p;
2006 if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
2007 return;
2008 infolen = p - info;
2009 (*digestfun)(info, infolen, digest, nil);
2012 static char*
2013 verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2015 Elem e;
2016 Elist *el;
2017 Bytes *digest;
2018 uchar *pkcs1buf, *buf;
2019 int buflen;
2020 mpint *pkcs1;
2021 int nlen;
2023 /* one less than the byte length of the modulus */
2024 nlen = (mpsignif(pk->n)-1)/8;
2026 /* see 9.2.1 of rfc2437 */
2027 pkcs1 = betomp(signature->data, signature->len, nil);
2028 mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2029 pkcs1buf = nil;
2030 buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2031 buf = pkcs1buf;
2032 if(buflen != nlen || buf[0] != 1)
2033 return "expected 1";
2034 buf++;
2035 while(buf[0] == 0xff)
2036 buf++;
2037 if(buf[0] != 0)
2038 return "expected 0";
2039 buf++;
2040 buflen -= buf-pkcs1buf;
2041 if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2042 !is_octetstring(&el->tl->hd, &digest))
2043 return "signature parse error";
2044 *psigalg = &el->hd;
2045 if(memcmp(digest->data, edigest, digest->len) == 0)
2046 return nil;
2047 return "digests did not match";
2050 RSApub*
2051 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2053 char *e;
2054 Bytes *b;
2055 CertX509 *c;
2056 RSApub *pk;
2058 b = makebytes(cert, ncert);
2059 c = decode_cert(b);
2060 freebytes(b);
2061 if(c == nil)
2062 return nil;
2063 if(name != nil && c->subject != nil){
2064 e = strchr(c->subject, ',');
2065 if(e != nil)
2066 *e = 0; // take just CN part of Distinguished Name
2067 strncpy(name, c->subject, nname);
2069 pk = decode_rsapubkey(c->publickey);
2070 freecert(c);
2071 return pk;
2074 char*
2075 X509verify(uchar *cert, int ncert, RSApub *pk)
2077 char *e;
2078 Bytes *b;
2079 CertX509 *c;
2080 uchar digest[SHA1dlen];
2081 Elem *sigalg;
2083 b = makebytes(cert, ncert);
2084 c = decode_cert(b);
2085 if(c != nil)
2086 digest_certinfo(b, digestalg[c->signature_alg], digest);
2087 freebytes(b);
2088 if(c == nil)
2089 return "cannot decode cert";
2090 e = verify_signature(c->signature, pk, digest, &sigalg);
2091 freecert(c);
2092 return e;
2095 /* ------- Elem constructors ---------- */
2096 static Elem
2097 Null(void)
2099 Elem e;
2101 e.tag.class = Universal;
2102 e.tag.num = NULLTAG;
2103 e.val.tag = VNull;
2104 return e;
2107 static Elem
2108 mkint(int j)
2110 Elem e;
2112 e.tag.class = Universal;
2113 e.tag.num = INTEGER;
2114 e.val.tag = VInt;
2115 e.val.u.intval = j;
2116 return e;
2119 static Elem
2120 mkbigint(mpint *p)
2122 Elem e;
2123 uchar *buf;
2124 int buflen;
2126 e.tag.class = Universal;
2127 e.tag.num = INTEGER;
2128 e.val.tag = VBigInt;
2129 buflen = mptobe(p, nil, 0, &buf);
2130 e.val.u.bigintval = makebytes(buf, buflen);
2131 free(buf);
2132 return e;
2135 static Elem
2136 mkstring(char *s)
2138 Elem e;
2140 e.tag.class = Universal;
2141 e.tag.num = IA5String;
2142 e.val.tag = VString;
2143 e.val.u.stringval = estrdup(s);
2144 return e;
2147 static Elem
2148 mkoctet(uchar *buf, int buflen)
2150 Elem e;
2152 e.tag.class = Universal;
2153 e.tag.num = OCTET_STRING;
2154 e.val.tag = VOctets;
2155 e.val.u.octetsval = makebytes(buf, buflen);
2156 return e;
2159 static Elem
2160 mkbits(uchar *buf, int buflen)
2162 Elem e;
2164 e.tag.class = Universal;
2165 e.tag.num = BIT_STRING;
2166 e.val.tag = VBitString;
2167 e.val.u.bitstringval = makebits(buf, buflen, 0);
2168 return e;
2171 static Elem
2172 mkutc(long t)
2174 Elem e;
2175 char utc[50];
2176 Tm *tm = gmtime(t);
2178 e.tag.class = Universal;
2179 e.tag.num = UTCTime;
2180 e.val.tag = VString;
2181 snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2182 tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2183 e.val.u.stringval = estrdup(utc);
2184 return e;
2187 static Elem
2188 mkoid(Ints *oid)
2190 Elem e;
2192 e.tag.class = Universal;
2193 e.tag.num = OBJECT_ID;
2194 e.val.tag = VObjId;
2195 e.val.u.objidval = makeints(oid->data, oid->len);
2196 return e;
2199 static Elem
2200 mkseq(Elist *el)
2202 Elem e;
2204 e.tag.class = Universal;
2205 e.tag.num = SEQUENCE;
2206 e.val.tag = VSeq;
2207 e.val.u.seqval = el;
2208 return e;
2211 static Elem
2212 mkset(Elist *el)
2214 Elem e;
2216 e.tag.class = Universal;
2217 e.tag.num = SETOF;
2218 e.val.tag = VSet;
2219 e.val.u.setval = el;
2220 return e;
2223 static Elem
2224 mkalg(int alg)
2226 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2229 typedef struct Ints7pref {
2230 int len;
2231 int data[7];
2232 char prefix[4];
2233 } Ints7pref;
2234 Ints7pref DN_oid[] = {
2235 {4, 2, 5, 4, 6, 0, 0, 0, "C="},
2236 {4, 2, 5, 4, 8, 0, 0, 0, "ST="},
2237 {4, 2, 5, 4, 7, 0, 0, 0, "L="},
2238 {4, 2, 5, 4, 10, 0, 0, 0, "O="},
2239 {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2240 {4, 2, 5, 4, 3, 0, 0, 0, "CN="},
2241 {7, 1,2,840,113549,1,9,1, "E="},
2244 static Elem
2245 mkname(Ints7pref *oid, char *subj)
2247 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2250 static Elem
2251 mkDN(char *dn)
2253 int i, j, nf;
2254 char *f[20], *prefix, *d2 = estrdup(dn);
2255 Elist* el = nil;
2257 nf = tokenize(d2, f, nelem(f));
2258 for(i=nf-1; i>=0; i--){
2259 for(j=0; j<nelem(DN_oid); j++){
2260 prefix = DN_oid[j].prefix;
2261 if(strncmp(f[i],prefix,strlen(prefix))==0){
2262 el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2263 break;
2267 free(d2);
2268 return mkseq(el);
2272 uchar*
2273 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2275 int serial = 0;
2276 uchar *cert = nil;
2277 RSApub *pk = rsaprivtopub(priv);
2278 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2279 Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2280 uchar digest[MD5dlen], *buf;
2281 int buflen;
2282 mpint *pkcs1;
2284 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2285 issuer = mkDN(subj);
2286 subject = mkDN(subj);
2287 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2288 if(encode(pubkey, &pkbytes) != ASN_OK)
2289 goto errret;
2290 freevalfields(&pubkey.val);
2291 pubkey = mkseq(
2292 mkel(mkalg(ALG_rsaEncryption),
2293 mkel(mkbits(pkbytes->data, pkbytes->len),
2294 nil)));
2295 freebytes(pkbytes);
2296 validity = mkseq(
2297 mkel(mkutc(valid[0]),
2298 mkel(mkutc(valid[1]),
2299 nil)));
2300 certinfo = mkseq(
2301 mkel(mkint(serial),
2302 mkel(mkalg(ALG_md5WithRSAEncryption),
2303 mkel(issuer,
2304 mkel(validity,
2305 mkel(subject,
2306 mkel(pubkey,
2307 nil)))))));
2308 if(encode(certinfo, &certinfobytes) != ASN_OK)
2309 goto errret;
2310 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2311 freebytes(certinfobytes);
2312 sig = mkseq(
2313 mkel(mkalg(ALG_md5),
2314 mkel(mkoctet(digest, MD5dlen),
2315 nil)));
2316 if(encode(sig, &sigbytes) != ASN_OK)
2317 goto errret;
2318 pkcs1 = pkcs1pad(sigbytes, pk->n);
2319 freebytes(sigbytes);
2320 rsadecrypt(priv, pkcs1, pkcs1);
2321 buflen = mptobe(pkcs1, nil, 0, &buf);
2322 mpfree(pkcs1);
2323 e = mkseq(
2324 mkel(certinfo,
2325 mkel(mkalg(ALG_md5WithRSAEncryption),
2326 mkel(mkbits(buf, buflen),
2327 nil))));
2328 free(buf);
2329 if(encode(e, &certbytes) != ASN_OK)
2330 goto errret;
2331 if(certlen)
2332 *certlen = certbytes->len;
2333 cert = certbytes->data;
2334 errret:
2335 freevalfields(&e.val);
2336 return cert;
2339 uchar*
2340 X509req(RSApriv *priv, char *subj, int *certlen)
2342 /* RFC 2314, PKCS #10 Certification Request Syntax */
2343 int version = 0;
2344 uchar *cert = nil;
2345 RSApub *pk = rsaprivtopub(priv);
2346 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2347 Elem e, certinfo, subject, pubkey, sig;
2348 uchar digest[MD5dlen], *buf;
2349 int buflen;
2350 mpint *pkcs1;
2352 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2353 subject = mkDN(subj);
2354 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2355 if(encode(pubkey, &pkbytes) != ASN_OK)
2356 goto errret;
2357 freevalfields(&pubkey.val);
2358 pubkey = mkseq(
2359 mkel(mkalg(ALG_rsaEncryption),
2360 mkel(mkbits(pkbytes->data, pkbytes->len),
2361 nil)));
2362 freebytes(pkbytes);
2363 certinfo = mkseq(
2364 mkel(mkint(version),
2365 mkel(subject,
2366 mkel(pubkey,
2367 nil))));
2368 if(encode(certinfo, &certinfobytes) != ASN_OK)
2369 goto errret;
2370 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2371 freebytes(certinfobytes);
2372 sig = mkseq(
2373 mkel(mkalg(ALG_md5),
2374 mkel(mkoctet(digest, MD5dlen),
2375 nil)));
2376 if(encode(sig, &sigbytes) != ASN_OK)
2377 goto errret;
2378 pkcs1 = pkcs1pad(sigbytes, pk->n);
2379 freebytes(sigbytes);
2380 rsadecrypt(priv, pkcs1, pkcs1);
2381 buflen = mptobe(pkcs1, nil, 0, &buf);
2382 mpfree(pkcs1);
2383 e = mkseq(
2384 mkel(certinfo,
2385 mkel(mkalg(ALG_md5),
2386 mkel(mkbits(buf, buflen),
2387 nil))));
2388 free(buf);
2389 if(encode(e, &certbytes) != ASN_OK)
2390 goto errret;
2391 if(certlen)
2392 *certlen = certbytes->len;
2393 cert = certbytes->data;
2394 errret:
2395 freevalfields(&e.val);
2396 return cert;
2399 static char*
2400 tagdump(Tag tag)
2402 if(tag.class != Universal)
2403 return smprint("class%d,num%d", tag.class, tag.num);
2404 switch(tag.num){
2405 case BOOLEAN: return "BOOLEAN"; break;
2406 case INTEGER: return "INTEGER"; break;
2407 case BIT_STRING: return "BIT STRING"; break;
2408 case OCTET_STRING: return "OCTET STRING"; break;
2409 case NULLTAG: return "NULLTAG"; break;
2410 case OBJECT_ID: return "OID"; break;
2411 case ObjectDescriptor: return "OBJECT_DES"; break;
2412 case EXTERNAL: return "EXTERNAL"; break;
2413 case REAL: return "REAL"; break;
2414 case ENUMERATED: return "ENUMERATED"; break;
2415 case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
2416 case SEQUENCE: return "SEQUENCE"; break;
2417 case SETOF: return "SETOF"; break;
2418 case NumericString: return "NumericString"; break;
2419 case PrintableString: return "PrintableString"; break;
2420 case TeletexString: return "TeletexString"; break;
2421 case VideotexString: return "VideotexString"; break;
2422 case IA5String: return "IA5String"; break;
2423 case UTCTime: return "UTCTime"; break;
2424 case GeneralizedTime: return "GeneralizedTime"; break;
2425 case GraphicString: return "GraphicString"; break;
2426 case VisibleString: return "VisibleString"; break;
2427 case GeneralString: return "GeneralString"; break;
2428 case UniversalString: return "UniversalString"; break;
2429 case BMPString: return "BMPString"; break;
2430 default:
2431 return smprint("Universal,num%d", tag.num);
2435 static void
2436 edump(Elem e)
2438 Value v;
2439 Elist *el;
2440 int i;
2442 print("%s{", tagdump(e.tag));
2443 v = e.val;
2444 switch(v.tag){
2445 case VBool: print("Bool %d",v.u.boolval); break;
2446 case VInt: print("Int %d",v.u.intval); break;
2447 case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2448 case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2449 case VReal: print("Real..."); break;
2450 case VOther: print("Other..."); break;
2451 case VBitString: print("BitString..."); break;
2452 case VNull: print("Null"); break;
2453 case VEOC: print("EOC..."); break;
2454 case VObjId: print("ObjId");
2455 for(i = 0; i<v.u.objidval->len; i++)
2456 print(" %d", v.u.objidval->data[i]);
2457 break;
2458 case VString: print("String \"%s\"",v.u.stringval); break;
2459 case VSeq: print("Seq\n");
2460 for(el = v.u.seqval; el!=nil; el = el->tl)
2461 edump(el->hd);
2462 break;
2463 case VSet: print("Set\n");
2464 for(el = v.u.setval; el!=nil; el = el->tl)
2465 edump(el->hd);
2466 break;
2468 print("}\n");
2471 void
2472 asn1dump(uchar *der, int len)
2474 Elem e;
2476 if(decode(der, len, &e) != ASN_OK){
2477 print("didn't parse\n");
2478 exits("didn't parse");
2480 edump(e);
2483 void
2484 X509dump(uchar *cert, int ncert)
2486 char *e;
2487 Bytes *b;
2488 CertX509 *c;
2489 RSApub *pk;
2490 uchar digest[SHA1dlen];
2491 Elem *sigalg;
2493 print("begin X509dump\n");
2494 b = makebytes(cert, ncert);
2495 c = decode_cert(b);
2496 if(c != nil)
2497 digest_certinfo(b, digestalg[c->signature_alg], digest);
2498 freebytes(b);
2499 if(c == nil){
2500 print("cannot decode cert");
2501 return;
2504 print("serial %d\n", c->serial);
2505 print("issuer %s\n", c->issuer);
2506 print("validity %s %s\n", c->validity_start, c->validity_end);
2507 print("subject %s\n", c->subject);
2508 pk = decode_rsapubkey(c->publickey);
2509 print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2511 print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2512 e = verify_signature(c->signature, pk, digest, &sigalg);
2513 if(e==nil){
2514 e = "nil (meaning ok)";
2515 print("sigalg=\n");
2516 if(sigalg)
2517 edump(*sigalg);
2519 print("self-signed verify_signature returns: %s\n", e);
2521 rsapubfree(pk);
2522 freecert(c);
2523 print("end X509dump\n");