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