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