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