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