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