6 /*=============================================================*/
7 /* general ASN1 declarations and parsing
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.
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;
30 #define OCTET_STRING 4
33 #define ObjectDescriptor 7
37 #define EMBEDDED_PDV 11
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
47 #define GeneralizedTime 24
48 #define GraphicString 25
49 #define VisibleString 26
50 #define GeneralString 27
51 #define UniversalString 28
65 int len; /* number of bytes */
66 int unusedbits; /* unused bits in last byte */
67 uchar data[]; /* most-significant bit first */
75 enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
76 VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
78 int tag; /* VBool, etc. */
84 Bytes* realval; /* undecoded; hardly ever used */
91 } u; /* (Don't use anonymous unions, for ease of porting) */
104 /* decoding errors */
105 enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
106 ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
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);
139 #define TAG_MASK 0x1F
140 #define CONSTR_MASK 0x20
141 #define CLASS_MASK 0xC0
142 #define MAXOBJIDLEN 20
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);
165 sysfatal("out of memory");
167 setmalloctag(p, getcallerpc(&n));
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
191 decode(uchar* a, int alen, Elem* pelem)
196 err = ber_decode(&p, &a[alen], pelem);
197 if(err == ASN_OK && p != &a[alen])
203 * All of the following decoding routines take arguments:
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.
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.
215 /* Decode an ASN1 'Elem' (tag, length, value) */
217 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
225 memset(pelem, 0, sizeof(*pelem));
226 err = tag_decode(pp, pend, &tag, &isconstr);
228 err = length_decode(pp, pend, &length);
230 if(tag.class == Universal)
231 err = value_decode(pp, pend, length, tag.num, isconstr, &val);
233 err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
243 /* Decode a tag field */
245 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
255 ptag->class = v&CLASS_MASK;
262 err = uint7_decode(&p, pend, &v);
271 /* Decode a length field */
273 length_decode(uchar** pp, uchar* pend, int* plength)
286 err = int_decode(&p, pend, v&0x7F, 1, &num);
297 /* Decode a value field */
299 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
305 int subids[MAXOBJIDLEN];
313 if(length == -1) { /* "indefinite" length spec */
317 else if(p + length > pend)
324 /* marker for end of indefinite constructions */
338 pval->u.boolval = (*p++ != 0);
346 else if(length <= 4) {
347 err = int_decode(&p, pend, length, 0, &num);
350 pval->u.intval = num;
355 pval->u.bigintval = makebytes(p, length);
361 pval->tag = VBitString;
363 if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
364 pval->u.bitstringval = makebits(0, 0, 0);
367 else /* TODO: recurse and concat results */
372 if(length == 1 && *p == 0) {
373 pval->u.bitstringval = makebits(0, 0, 0);
383 else if(length > 0x0FFFFFFF)
386 pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
394 case ObjectDescriptor:
395 err = octet_decode(&p, pend, length, isconstr, &va);
398 pval->u.octetsval = va;
419 while(p < pe && isubid < MAXOBJIDLEN) {
420 err = uint7_decode(&p, pend, &num);
424 subids[isubid++] = num / 40;
425 subids[isubid++] = num % 40;
428 subids[isubid++] = num;
435 pval->u.objidval = makeints(subids, isubid);
443 /* TODO: parse this internally */
448 pval->u.otherval = makebytes(p, length);
454 /* Let the application decode */
457 else if(p+length > pend)
461 pval->u.realval = makebytes(p, length);
467 err = seq_decode(&p, pend, length, isconstr, &vl);
475 err = seq_decode(&p, pend, length, isconstr, &vl);
484 case PrintableString:
489 case GeneralizedTime:
493 case UniversalString:
495 err = octet_decode(&p, pend, length, isconstr, &va);
503 case UniversalString:
505 d = emalloc(n*UTFmax+1);
506 pval->u.stringval = d;
509 r = s[0]<<24 | s[1]<<16 | s[2]<<8 | s[3];
514 d += runetochar(d, &r);
520 d = emalloc(n*UTFmax+1);
521 pval->u.stringval = d;
529 d += runetochar(d, &r);
536 pval->u.stringval = d;
550 free(pval->u.stringval);
562 pval->u.otherval = makebytes(p, length);
572 * Decode an int in format where count bytes are
573 * concatenated to form value.
574 * Although ASN1 allows any size integer, we return
575 * an error if the result doesn't fit in a 32-bit int.
576 * If unsgned is not set, make sure to propagate sign bit.
579 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
588 if(p+count <= pend) {
589 if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
592 if(!unsgned && count > 0 && count < 4 && (*p&0x80))
593 num = -1; /* set all bits, initially */
595 num = (num << 8)|(*p++);
606 * Decode an unsigned int in format where each
607 * byte except last has high bit set, and remaining
608 * seven bits of each byte are concatenated to form value.
609 * Although ASN1 allows any size integer, we return
610 * an error if the result doesn't fit in a 32 bit int.
613 uint7_decode(uchar** pp, uchar* pend, int* pint)
625 while(more && p < pend) {
643 * Decode an octet string, recursively if isconstr.
644 * We've already checked that length==-1 implies isconstr==1,
645 * and otherwise that specified length fits within (*pp..pend)
648 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
661 if(length >= 0 && !isconstr) {
662 ans = makebytes(p, length);
666 /* constructed, either definite or indefinite length */
669 if(length >= 0 && p >= pstart + length) {
670 if(p != pstart + length)
675 err = ber_decode(&p, pend, &elem);
678 switch(elem.val.tag) {
680 newans = catbytes(ans, elem.val.u.octetsval);
681 freevalfields(&elem.val);
691 freevalfields(&elem.val);
709 * Decode a sequence or set.
710 * We've already checked that length==-1 implies isconstr==1,
711 * and otherwise that specified length fits within (*p..pend)
714 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
731 /* constructed, either definite or indefinite length */
735 if(length >= 0 && p >= pstart + length) {
736 if(p != pstart + length)
741 err = ber_decode(&p, pend, &elem);
744 if(elem.val.tag == VEOC) {
752 lve = mkel(elem, lve);
757 /* reverse back to original order */
772 * Encode e by BER rules, putting answer in *pbytes.
773 * This is done by first calling enc with lenonly==1
774 * to get the length of the needed buffer,
775 * then allocating the buffer and using enc again to fill it up.
778 encode(Elem e, Bytes** pbytes)
788 ans = newbytes(p-&uc);
797 * The various enc functions take a pointer to a pointer
798 * into a buffer, and encode their entity starting there,
799 * updating the pointer afterwards.
800 * If lenonly is 1, only the pointer update is done,
801 * allowing enc to be called first to calculate the needed
803 * If lenonly is 0, it is assumed that the answer will fit.
807 enc(uchar** pp, Elem e, int lenonly)
819 err = val_enc(&p, e, &constr, 1);
825 v = tag.class|constr;
837 uint7_enc(&p, tag.num, lenonly);
846 int_enc(&p, vlen, 1, 1);
850 *p++ = (0x80 | ilen);
851 int_enc(&p, vlen, 1, 0);
857 val_enc(&p, e, &constr, 0);
865 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
884 if(cl != Universal) {
914 kind = UniversalString;
929 int_enc(&p, v, 1, lenonly);
938 int_enc(&p, v, 0, lenonly);
940 if(is_bigint(&e, &bb)) {
942 memmove(p, bb->data, bb->len);
951 if(is_bitstring(&e, &bits)) {
958 v = bits->unusedbits;
964 memmove(p+1, bits->data, bits->len);
975 case ObjectDescriptor:
982 bb = e.val.u.octetsval;
985 bb = e.val.u.realval;
988 bb = e.val.u.otherval;
993 memmove(p, bb->data, bb->len);
1004 if(is_oid(&e, &oid)) {
1005 for(k = 0; k < oid->len; k++) {
1010 v += oid->data[++k];
1012 uint7_enc(&p, v, lenonly);
1022 if(e.val.tag == VSeq)
1023 el = e.val.u.seqval;
1024 else if(e.val.tag == VSet)
1025 el = e.val.u.setval;
1029 *pconstr = CONSTR_MASK;
1030 for(; el != nil; el = el->tl) {
1031 err = enc(&p, el->hd, lenonly);
1040 case PrintableString:
1042 case VideotexString:
1045 case GeneralizedTime:
1049 case UniversalString:
1051 if(e.val.tag == VString) {
1052 s = e.val.u.stringval;
1072 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1073 * except last, only putting in bytes if !lenonly.
1076 uint7_enc(uchar** pp, int num, int lenonly)
1093 for(k = (n - 1)*7; k > 0; k -= 7)
1094 *p++= ((num >> k)|0x80);
1101 * Encode num as unsigned or signed integer,
1102 * only putting in bytes if !lenonly.
1103 * Encoding is length followed by bytes to concatenate.
1106 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1126 if(!unsgned && (prevv&0x80))
1131 for(k = (n - 1)*8; k >= 0; k -= 8)
1138 ints_eq(Ints* a, Ints* b)
1146 for(i = 0; i < alen; i++)
1147 if(a->data[i] != b->data[i])
1153 * Look up o in tab (which must have nil entry to terminate).
1154 * Return index of matching entry, or -1 if none.
1157 oid_lookup(Ints* o, Ints** tab)
1161 for(i = 0; tab[i] != nil; i++)
1162 if(ints_eq(o, tab[i]))
1168 * Return true if *pe is a SEQUENCE, and set *pseq to
1169 * the value of the sequence if so.
1172 is_seq(Elem* pe, Elist** pseq)
1174 if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1175 *pseq = pe->val.u.seqval;
1182 is_set(Elem* pe, Elist** pset)
1184 if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1185 *pset = pe->val.u.setval;
1192 is_int(Elem* pe, int* pint)
1194 if(pe->tag.class == Universal) {
1195 if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1196 *pint = pe->val.u.intval;
1199 else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1200 *pint = pe->val.u.boolval;
1208 * for convience, all VInt's are readable via this routine,
1209 * as well as all VBigInt's
1212 is_bigint(Elem* pe, Bytes** pbigint)
1214 if(pe->tag.class == Universal && pe->tag.num == INTEGER && pe->val.tag == VBigInt) {
1215 *pbigint = pe->val.u.bigintval;
1222 is_bitstring(Elem* pe, Bits** pbits)
1224 if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1225 *pbits = pe->val.u.bitstringval;
1232 is_octetstring(Elem* pe, Bytes** poctets)
1234 if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1235 *poctets = pe->val.u.octetsval;
1242 is_oid(Elem* pe, Ints** poid)
1244 if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1245 *poid = pe->val.u.objidval;
1252 is_string(Elem* pe, char** pstring)
1254 if(pe->tag.class == Universal) {
1255 switch(pe->tag.num) {
1258 case PrintableString:
1260 case VideotexString:
1265 case UniversalString:
1267 if(pe->val.tag == VString) {
1268 *pstring = pe->val.u.stringval;
1277 is_time(Elem* pe, char** ptime)
1279 if(pe->tag.class == Universal
1280 && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1281 && pe->val.tag == VString) {
1282 *ptime = pe->val.u.stringval;
1290 * malloc and return a new Bytes structure capable of
1291 * holding len bytes. (len >= 0)
1300 ans = emalloc(sizeof(Bytes) + len);
1306 * newbytes(len), with data initialized from buf
1309 makebytes(uchar* buf, int len)
1313 ans = newbytes(len);
1314 memmove(ans->data, buf, len);
1325 * Make a new Bytes, containing bytes of b1 followed by those of b2.
1326 * Either b1 or b2 or both can be nil.
1329 catbytes(Bytes* b1, Bytes* b2)
1338 ans = makebytes(b2->data, b2->len);
1340 else if(b2 == nil) {
1341 ans = makebytes(b1->data, b1->len);
1344 n = b1->len + b2->len;
1347 memmove(ans->data, b1->data, b1->len);
1348 memmove(ans->data+b1->len, b2->data, b2->len);
1353 /* len is number of ints */
1359 if(len < 0 || len > ((uint)-1>>1)/sizeof(int))
1361 ans = emalloc(sizeof(Ints) + len*sizeof(int));
1367 makeints(int* buf, int len)
1372 memmove(ans->data, buf, len*sizeof(int));
1382 /* len is number of bytes */
1390 ans = emalloc(sizeof(Bits) + len);
1392 ans->unusedbits = 0;
1397 makebits(uchar* buf, int len, int unusedbits)
1402 memmove(ans->data, buf, len);
1403 ans->unusedbits = unusedbits;
1414 mkel(Elem e, Elist* tail)
1418 el = (Elist*)emalloc(sizeof(Elist));
1419 setmalloctag(el, getcallerpc(&e));
1436 /* Frees elist, but not fields inside values of constituent elems */
1438 freeelist(Elist* el)
1449 /* free any allocated structures inside v (recursively freeing Elists) */
1451 freevalfields(Value* v)
1459 freebytes(v->u.octetsval);
1462 freebytes(v->u.bigintval);
1465 freebytes(v->u.realval);
1468 freebytes(v->u.otherval);
1471 freebits(v->u.bitstringval);
1474 freeints(v->u.objidval);
1478 free(v->u.stringval);
1482 for(l = el; l != nil; l = l->tl)
1483 freevalfields(&l->hd.val);
1488 for(l = el; l != nil; l = l->tl)
1489 freevalfields(&l->hd.val);
1495 /* end of general ASN1 functions */
1501 /*=============================================================*/
1503 * Decode and parse an X.509 Certificate, defined by this ASN1:
1504 * Certificate ::= SEQUENCE {
1505 * certificateInfo CertificateInfo,
1506 * signatureAlgorithm AlgorithmIdentifier,
1507 * signature BIT STRING }
1509 * CertificateInfo ::= SEQUENCE {
1510 * version [0] INTEGER DEFAULT v1 (0),
1511 * serialNumber INTEGER,
1512 * signature AlgorithmIdentifier,
1514 * validity Validity,
1516 * subjectPublicKeyInfo SubjectPublicKeyInfo }
1517 * (version v2 has two more fields, optional unique identifiers for
1518 * issuer and subject; since we ignore these anyway, we won't parse them)
1520 * Validity ::= SEQUENCE {
1521 * notBefore UTCTime,
1522 * notAfter UTCTime }
1524 * SubjectPublicKeyInfo ::= SEQUENCE {
1525 * algorithm AlgorithmIdentifier,
1526 * subjectPublicKey BIT STRING }
1528 * AlgorithmIdentifier ::= SEQUENCE {
1529 * algorithm OBJECT IDENTIFER,
1530 * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1532 * Name ::= SEQUENCE OF RelativeDistinguishedName
1534 * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1536 * AttributeTypeAndValue ::= SEQUENCE {
1537 * type OBJECT IDENTIFER,
1538 * value DirectoryString }
1539 * (selected attributes have these Object Ids:
1540 * commonName {2 5 4 3}
1541 * countryName {2 5 4 6}
1542 * localityName {2 5 4 7}
1543 * stateOrProvinceName {2 5 4 8}
1544 * organizationName {2 5 4 10}
1545 * organizationalUnitName {2 5 4 11}
1548 * DirectoryString ::= CHOICE {
1549 * teletexString TeletexString,
1550 * printableString PrintableString,
1551 * universalString UniversalString }
1553 * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1555 * Not yet implemented:
1556 * CertificateRevocationList ::= SIGNED SEQUENCE{
1557 * signature AlgorithmIdentifier,
1559 * lastUpdate UTCTime,
1560 * nextUpdate UTCTime,
1561 * revokedCertificates
1562 * SEQUENCE OF CRLEntry OPTIONAL}
1563 * CRLEntry ::= SEQUENCE{
1564 * userCertificate SerialNumber,
1565 * revocationDate UTCTime}
1568 typedef struct CertX509 {
1571 char* validity_start;
1581 /* Algorithm object-ids */
1584 ALG_md2WithRSAEncryption,
1585 ALG_md4WithRSAEncryption,
1586 ALG_md5WithRSAEncryption,
1588 ALG_sha1WithRSAEncryption,
1589 ALG_sha1WithRSAEncryptionOiw,
1591 ALG_sha256WithRSAEncryption,
1592 ALG_sha384WithRSAEncryption,
1593 ALG_sha512WithRSAEncryption,
1594 ALG_sha224WithRSAEncryption,
1598 ALG_sha256WithECDSA,
1599 ALG_sha384WithECDSA,
1600 ALG_sha512WithECDSA,
1612 typedef struct Ints15 {
1617 typedef struct DigestAlg {
1619 DigestState* (*fun)(uchar*,ulong,uchar*,DigestState*);
1623 static DigestAlg alg_md5 = { ALG_md5, md5, MD5dlen};
1624 static DigestAlg alg_sha1 = { ALG_sha1, sha1, SHA1dlen };
1625 static DigestAlg alg_sha256 = { ALG_sha256, sha2_256, SHA2_256dlen };
1626 static DigestAlg alg_sha384 = { ALG_sha384, sha2_384, SHA2_384dlen };
1627 static DigestAlg alg_sha512 = { ALG_sha512, sha2_512, SHA2_512dlen };
1628 static DigestAlg alg_sha224 = { ALG_sha224, sha2_224, SHA2_224dlen };
1630 /* maximum length of digest output of the digest algs above */
1632 MAXdlen = SHA2_512dlen,
1635 static Ints15 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1637 static Ints15 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1638 static Ints15 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1639 static Ints15 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1640 static Ints15 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1641 static Ints15 oid_sha1WithRSAEncryptionOiw ={6, 1, 3, 14, 3, 2, 29 };
1642 static Ints15 oid_sha256WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 11 };
1643 static Ints15 oid_sha384WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 12 };
1644 static Ints15 oid_sha512WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 13 };
1645 static Ints15 oid_sha224WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 14 };
1647 static Ints15 oid_ecPublicKey = {6, 1, 2, 840, 10045, 2, 1 };
1648 static Ints15 oid_sha1WithECDSA = {6, 1, 2, 840, 10045, 4, 1 };
1649 static Ints15 oid_sha256WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 2 };
1650 static Ints15 oid_sha384WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 3 };
1651 static Ints15 oid_sha512WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 4 };
1653 static Ints15 oid_md5 = {6, 1, 2, 840, 113549, 2, 5 };
1654 static Ints15 oid_sha1 = {6, 1, 3, 14, 3, 2, 26 };
1655 static Ints15 oid_sha256= {9, 2, 16, 840, 1, 101, 3, 4, 2, 1 };
1656 static Ints15 oid_sha384= {9, 2, 16, 840, 1, 101, 3, 4, 2, 2 };
1657 static Ints15 oid_sha512= {9, 2, 16, 840, 1, 101, 3, 4, 2, 3 };
1658 static Ints15 oid_sha224= {9, 2, 16, 840, 1, 101, 3, 4, 2, 4 };
1660 static Ints *alg_oid_tab[NUMALGS+1] = {
1661 (Ints*)&oid_rsaEncryption,
1662 (Ints*)&oid_md2WithRSAEncryption,
1663 (Ints*)&oid_md4WithRSAEncryption,
1664 (Ints*)&oid_md5WithRSAEncryption,
1666 (Ints*)&oid_sha1WithRSAEncryption,
1667 (Ints*)&oid_sha1WithRSAEncryptionOiw,
1669 (Ints*)&oid_sha256WithRSAEncryption,
1670 (Ints*)&oid_sha384WithRSAEncryption,
1671 (Ints*)&oid_sha512WithRSAEncryption,
1672 (Ints*)&oid_sha224WithRSAEncryption,
1674 (Ints*)&oid_ecPublicKey,
1675 (Ints*)&oid_sha1WithECDSA,
1676 (Ints*)&oid_sha256WithECDSA,
1677 (Ints*)&oid_sha384WithECDSA,
1678 (Ints*)&oid_sha512WithECDSA,
1689 static DigestAlg *digestalg[NUMALGS+1] = {
1690 &alg_md5, &alg_md5, &alg_md5, &alg_md5,
1691 &alg_sha1, &alg_sha1,
1692 &alg_sha256, &alg_sha384, &alg_sha512, &alg_sha224,
1693 &alg_sha256, &alg_sha1, &alg_sha256, &alg_sha384, &alg_sha512,
1694 &alg_md5, &alg_sha1, &alg_sha256, &alg_sha384, &alg_sha512, &alg_sha224,
1698 static Ints15 oid_secp256r1 = {7, 1, 2, 840, 10045, 3, 1, 7};
1700 static Ints *namedcurves_oid_tab[] = {
1701 (Ints*)&oid_secp256r1,
1704 static void (*namedcurves[])(mpint *p, mpint *a, mpint *b, mpint *x, mpint *y, mpint *n, mpint *h) = {
1710 freecert(CertX509* c)
1715 free(c->validity_start);
1716 free(c->validity_end);
1718 freebytes(c->publickey);
1719 freebytes(c->signature);
1724 * Parse the Name ASN1 type.
1725 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1726 * from most general to most specific. Each element of the path can be
1727 * one or more (but usually just one) attribute-value pair, such as
1729 * We'll just form a "postal-style" address string by concatenating the elements
1730 * from most specific to least specific, separated by commas.
1731 * Return name-as-string (which must be freed by caller).
1742 enum { MAXPARTS = 100 };
1743 char* parts[MAXPARTS];
1754 if(!is_set(es, &esetl))
1756 while(esetl != nil) {
1758 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1760 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1763 plen += strlen(s) + 2; /* room for ", " after */
1769 ans = (char*)emalloc(plen);
1784 * Parse an AlgorithmIdentifer ASN1 type.
1785 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1786 * or -1 if not found.
1787 * For now, ignore parameters, since none of our algorithms need them.
1795 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1797 return oid_lookup(oid, alg_oid_tab);
1801 parse_curve(Elem* e)
1806 if(!is_seq(e, &el) || elistlen(el)<2 || !is_oid(&el->tl->hd, &oid))
1808 return oid_lookup(oid, namedcurves_oid_tab);
1812 decode_cert(Bytes* a)
1827 Elist* elcert = nil;
1828 Elist* elcertinfo = nil;
1829 Elist* elvalidity = nil;
1830 Elist* elpubkey = nil;
1835 if(decode(a->data, a->len, &ecert) != ASN_OK)
1838 c = (CertX509*)emalloc(sizeof(CertX509));
1841 c->validity_start = nil;
1842 c->validity_end = nil;
1844 c->publickey_alg = -1;
1846 c->signature_alg = -1;
1850 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1852 ecertinfo = &elcert->hd;
1855 c->signature_alg = parse_alg(esigalg);
1859 /* Certificate Info */
1860 if(!is_seq(ecertinfo, &elcertinfo))
1862 n = elistlen(elcertinfo);
1865 eserial =&elcertinfo->hd;
1866 el = elcertinfo->tl;
1867 /* check for optional version, marked by explicit context tag 0 */
1868 if(eserial->tag.class == Context && eserial->tag.num == 0) {
1875 if(parse_alg(&el->hd) != c->signature_alg)
1880 evalidity = &el->hd;
1885 if(!is_int(eserial, &c->serial)) {
1886 if(!is_bigint(eserial, &b))
1888 c->serial = -1; /* else we have to change cert struct */
1890 c->issuer = parse_name(eissuer);
1891 if(c->issuer == nil)
1894 if(!is_seq(evalidity, &elvalidity))
1896 if(elistlen(elvalidity) != 2)
1898 e = &elvalidity->hd;
1899 if(!is_time(e, &c->validity_start))
1901 e->val.u.stringval = nil; /* string ownership transfer */
1902 e = &elvalidity->tl->hd;
1903 if(!is_time(e, &c->validity_end))
1905 e->val.u.stringval = nil; /* string ownership transfer */
1907 /* resume CertificateInfo */
1908 c->subject = parse_name(esubj);
1909 if(c->subject == nil)
1912 /* SubjectPublicKeyInfo */
1913 if(!is_seq(epubkey, &elpubkey))
1915 if(elistlen(elpubkey) != 2)
1918 c->publickey_alg = parse_alg(&elpubkey->hd);
1919 if(c->publickey_alg < 0)
1922 if(c->publickey_alg == ALG_ecPublicKey){
1923 c->curve = parse_curve(&elpubkey->hd);
1927 if(!is_bitstring(&elpubkey->tl->hd, &bits))
1929 if(bits->unusedbits != 0)
1931 c->publickey = makebytes(bits->data, bits->len);
1933 /*resume Certificate */
1934 if(c->signature_alg < 0)
1936 if(!is_bitstring(esig, &bits))
1938 c->signature = makebytes(bits->data, bits->len);
1942 freevalfields(&ecert.val); /* recurses through lists, too */
1951 * RSAPublickKey ::= SEQUENCE {
1953 * publicExponent INTEGER
1957 decode_rsapubkey(Bytes* a)
1964 if(decode(a->data, a->len, &e) != ASN_OK)
1966 if(!is_seq(&e, &el) || elistlen(el) != 2)
1969 key = rsapuballoc();
1970 if((key->n = asn1mpint(&el->hd)) == nil)
1973 if((key->ek = asn1mpint(&el->hd)) == nil)
1976 freevalfields(&e.val);
1979 freevalfields(&e.val);
1985 * RSAPrivateKey ::= SEQUENCE {
1987 * modulus INTEGER, -- n
1988 * publicExponent INTEGER, -- e
1989 * privateExponent INTEGER, -- d
1990 * prime1 INTEGER, -- p
1991 * prime2 INTEGER, -- q
1992 * exponent1 INTEGER, -- d mod (p-1)
1993 * exponent2 INTEGER, -- d mod (q-1)
1994 * coefficient INTEGER -- (inverse of q) mod p }
1997 decode_rsaprivkey(Bytes* a)
2005 if(decode(a->data, a->len, &e) != ASN_OK)
2007 if(!is_seq(&e, &el))
2010 if(!is_int(&el->hd, &version) || version != 0)
2013 if(elistlen(el) != 9){
2014 if(elistlen(el) == 3
2015 && parse_alg(&el->tl->hd) == ALG_rsaEncryption
2016 && is_octetstring(&el->tl->tl->hd, &a)){
2017 key = decode_rsaprivkey(a);
2024 key = rsaprivalloc();
2026 if((key->pub.n = asn1mpint(&el->hd)) == nil)
2030 if((key->pub.ek = asn1mpint(&el->hd)) == nil)
2034 if((key->dk = asn1mpint(&el->hd)) == nil)
2038 if((key->q = asn1mpint(&el->hd)) == nil)
2042 if((key->p = asn1mpint(&el->hd)) == nil)
2046 if((key->kq = asn1mpint(&el->hd)) == nil)
2050 if((key->kp = asn1mpint(&el->hd)) == nil)
2054 if((key->c2 = asn1mpint(&el->hd)) == nil)
2058 freevalfields(&e.val);
2061 freevalfields(&e.val);
2067 * DSAPrivateKey ::= SEQUENCE{
2071 * g INTEGER, -- alpha
2072 * pub_key INTEGER, -- key
2073 * priv_key INTEGER, -- secret
2077 decode_dsaprivkey(Bytes* a)
2084 key = dsaprivalloc();
2085 if(decode(a->data, a->len, &e) != ASN_OK)
2087 if(!is_seq(&e, &el) || elistlen(el) != 6)
2090 if(!is_int(&el->hd, &version) || version != 0)
2094 if((key->pub.p = asn1mpint(&el->hd)) == nil)
2098 if((key->pub.q = asn1mpint(&el->hd)) == nil)
2102 if((key->pub.alpha = asn1mpint(&el->hd)) == nil)
2106 if((key->pub.key = asn1mpint(&el->hd)) == nil)
2110 if((key->secret = asn1mpint(&el->hd)) == nil)
2113 freevalfields(&e.val);
2116 freevalfields(&e.val);
2128 return itomp(v, nil);
2129 if(is_bigint(e, &b))
2130 return betomp(b->data, b->len, nil);
2135 pkcs1padbuf(uchar *buf, int len, mpint *modulus)
2137 int n = (mpsignif(modulus)+7)/8;
2143 p = (uchar*)emalloc(n);
2146 for(i = 2; i < pm1; i++)
2149 memcpy(&p[pm1+1], buf, len);
2150 mp = betomp(p, n, nil);
2156 pkcs1pad(Bytes *b, mpint *modulus)
2158 return pkcs1padbuf(b->data, b->len, modulus);
2162 asn1toRSApriv(uchar *kd, int kn)
2167 b = makebytes(kd, kn);
2168 key = decode_rsaprivkey(b);
2174 asn1toDSApriv(uchar *kd, int kn)
2179 b = makebytes(kd, kn);
2180 key = decode_dsaprivkey(b);
2186 * digest(CertificateInfo)
2187 * Our ASN.1 library doesn't return pointers into the original
2188 * data array, so we need to do a little hand decoding.
2191 digest_certinfo(Bytes *cert, DigestAlg *da, uchar *digest)
2193 uchar *info, *p, *pend;
2195 int isconstr, length;
2200 pend = cert->data + cert->len;
2201 if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2202 tag.class != Universal || tag.num != SEQUENCE ||
2203 length_decode(&p, pend, &length) != ASN_OK ||
2208 if(ber_decode(&p, pend, &elem) != ASN_OK)
2210 freevalfields(&elem.val);
2211 if(elem.tag.num != SEQUENCE)
2214 (*da->fun)(info, infolen, digest, nil);
2219 pkcs1decryptsignature(uchar *sig, int siglen, RSApub *pk, uchar **pbuf)
2227 /* one less than the byte length of the modulus */
2228 nlen = (mpsignif(pk->n)-1)/8;
2230 /* see 9.2.1 of rfc2437 */
2231 pkcs1 = betomp(sig, siglen, nil);
2232 mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2233 buflen = mptobe(pkcs1, nil, 0, pbuf);
2237 if(buflen != nlen || buf[0] != 1)
2240 while(buflen > 0 && buf[0] == 0xff)
2242 if(buflen < 1 || buf[0] != 0)
2245 memmove(*pbuf, buf, buflen);
2254 X509rsaverifydigest(uchar *sig, int siglen, uchar *edigest, int edigestlen, RSApub *pk)
2263 buflen = pkcs1decryptsignature(sig, siglen, pk, &buf);
2264 if(buflen == edigestlen && tsmemcmp(buf, edigest, edigestlen) == 0){
2269 memset(&e, 0, sizeof(e));
2270 if(buflen < 0 || decode(buf, buflen, &e) != ASN_OK
2271 || !is_seq(&e, &el) || elistlen(el) != 2 || !is_octetstring(&el->tl->hd, &digest)) {
2272 err = "signature parse error";
2275 alg = parse_alg(&el->hd);
2277 err = "unknown signature algorithm";
2280 if(digest->len != edigestlen || digest->len != digestalg[alg]->len){
2281 err = "bad digest length";
2284 if(tsmemcmp(digest->data, edigest, edigestlen) != 0){
2285 err = "digest did not match";
2290 freevalfields(&e.val);
2296 X509ecdsaverifydigest(uchar *sig, int siglen, uchar *edigest, int edigestlen, ECdomain *dom, ECpub *pub)
2304 err = "bad signature";
2305 if(decode(sig, siglen, &e) != ASN_OK)
2307 if(!is_seq(&e, &el) || elistlen(el) != 2)
2309 r = asn1mpint(&el->hd);
2313 s = asn1mpint(&el->hd);
2316 if(ecdsaverify(dom, pub, edigest, edigestlen, r, s))
2319 freevalfields(&e.val);
2326 X509toECpub(uchar *cert, int ncert, ECdomain *dom)
2332 b = makebytes(cert, ncert);
2338 if(c->publickey_alg == ALG_ecPublicKey){
2339 ecdominit(dom, namedcurves[c->curve]);
2340 pub = ecdecodepub(dom, c->publickey->data, c->publickey->len);
2349 X509ecdsaverify(uchar *cert, int ncert, ECdomain *dom, ECpub *pk)
2355 uchar digest[MAXdlen];
2357 b = makebytes(cert, ncert);
2361 return "cannot decode cert";
2363 digestlen = digest_certinfo(b, digestalg[c->signature_alg], digest);
2367 return "cannot decode certinfo";
2369 e = X509ecdsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, dom, pk);
2375 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2383 memset(name, 0, nname);
2385 b = makebytes(cert, ncert);
2390 if(name != nil && c->subject != nil){
2391 e = strchr(c->subject, ',');
2393 *e = 0; /* take just CN part of Distinguished Name */
2394 strncpy(name, c->subject, nname);
2397 if(c->publickey_alg == ALG_rsaEncryption)
2398 pub = decode_rsapubkey(c->publickey);
2404 X509rsaverify(uchar *cert, int ncert, RSApub *pk)
2410 uchar digest[MAXdlen];
2412 b = makebytes(cert, ncert);
2416 return "cannot decode cert";
2418 digestlen = digest_certinfo(b, digestalg[c->signature_alg], digest);
2422 return "cannot decode certinfo";
2424 e = X509rsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, pk);
2429 /* ------- Elem constructors ---------- */
2435 e.tag.class = Universal;
2436 e.tag.num = NULLTAG;
2446 e.tag.class = Universal;
2447 e.tag.num = INTEGER;
2460 e.tag.class = Universal;
2461 e.tag.num = INTEGER;
2462 e.val.tag = VBigInt;
2463 buflen = mptobe(p, nil, 0, &buf);
2464 e.val.u.bigintval = makebytes(buf, buflen);
2474 while((c = (uchar)*s++) != 0){
2475 if((c >= 'a' && c <= 'z')
2476 || (c >= 'A' && c <= 'Z')
2477 || (c >= '0' && c <= '9')
2478 || strchr("'=()+,-./:? ", c) != nil)
2485 #define DirectoryString 0
2488 mkstring(char *s, int t)
2492 if(t == DirectoryString)
2493 t = printable(s) ? PrintableString : UTF8String;
2494 e.tag.class = Universal;
2496 e.val.tag = VString;
2497 e.val.u.stringval = estrdup(s);
2502 mkoctet(uchar *buf, int buflen)
2506 e.tag.class = Universal;
2507 e.tag.num = OCTET_STRING;
2508 e.val.tag = VOctets;
2509 e.val.u.octetsval = makebytes(buf, buflen);
2514 mkbits(uchar *buf, int buflen)
2518 e.tag.class = Universal;
2519 e.tag.num = BIT_STRING;
2520 e.val.tag = VBitString;
2521 e.val.u.bitstringval = makebits(buf, buflen, 0);
2532 e.tag.class = Universal;
2533 e.tag.num = UTCTime;
2534 e.val.tag = VString;
2535 snprint(utc, sizeof(utc), "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2536 tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2537 e.val.u.stringval = estrdup(utc);
2546 e.tag.class = Universal;
2547 e.tag.num = OBJECT_ID;
2549 e.val.u.objidval = makeints(oid->data, oid->len);
2558 e.tag.class = Universal;
2559 e.tag.num = SEQUENCE;
2561 e.val.u.seqval = el;
2570 e.tag.class = Universal;
2573 e.val.u.setval = el;
2580 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2583 typedef struct Ints7pref {
2589 Ints7pref DN_oid[] = {
2590 {4, 2, 5, 4, 6, 0, 0, 0, "C=", PrintableString},
2591 {4, 2, 5, 4, 8, 0, 0, 0, "ST=",DirectoryString},
2592 {4, 2, 5, 4, 7, 0, 0, 0, "L=", DirectoryString},
2593 {4, 2, 5, 4, 10, 0, 0, 0, "O=", DirectoryString},
2594 {4, 2, 5, 4, 11, 0, 0, 0, "OU=",DirectoryString},
2595 {4, 2, 5, 4, 3, 0, 0, 0, "CN=",DirectoryString},
2596 {7, 1,2,840,113549,1,9,1, "E=", IA5String},
2597 {7, 0,9,2342,19200300,100,1,25, "DC=",IA5String},
2601 mkname(Ints7pref *oid, char *subj)
2603 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj, oid->stype), nil))), nil));
2610 char *f[20], *prefix, *d2 = estrdup(dn);
2613 nf = tokenize(d2, f, nelem(f));
2614 for(i=nf-1; i>=0; i--){
2615 for(j=0; j<nelem(DN_oid); j++){
2616 prefix = DN_oid[j].prefix;
2617 if(strncmp(f[i],prefix,strlen(prefix))==0){
2618 el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2628 * DigestInfo ::= SEQUENCE {
2629 * digestAlgorithm AlgorithmIdentifier,
2630 * digest OCTET STRING }
2633 encode_digest(DigestAlg *da, uchar *digest)
2640 mkel(mkalg(da->alg),
2641 mkel(mkoctet(digest, da->len),
2643 err = encode(e, &ans);
2644 freevalfields(&e.val);
2652 asn1encodedigest(DigestState* (*fun)(uchar*, ulong, uchar*, DigestState*), uchar *digest, uchar *buf, int len)
2657 for(dp = digestalg; *dp != nil; dp++){
2658 if((*dp)->fun != fun)
2660 bytes = encode_digest(*dp, digest);
2663 if(bytes->len > len){
2668 memmove(buf, bytes->data, len);
2681 for(i=0; i<nelem(DN_oid); i++){
2682 if(strstr(s, DN_oid[i].prefix) != nil){
2683 e = mkseq(mkel(mkDN(s),nil));
2684 e.tag.class = Context;
2685 e.tag.num = 4; /* DN */
2689 e = mkstring(s, IA5String);
2690 e.tag.class = Context;
2691 e.tag.num = strchr(s, '@') != nil ? 1 : 2; /* email : DNS */
2696 mkaltnames(char *alts)
2705 alts = estrdup(alts);
2706 for(s = alts; s != nil; s = p){
2711 if((p = strchr(s, ',')) != nil)
2713 el = mkel(mkaltname(s), el);
2720 mkextel(Elem e, Ints *oid, Elist *el)
2724 if(encode(e, &b) == ASN_OK){
2727 mkel(mkoctet(b->data, b->len),
2731 freevalfields(&e.val);
2735 static Ints15 oid_subjectAltName = {4, 2, 5, 29, 17 };
2738 mkextensions(char *alts)
2744 if((sl = mkaltnames(alts)) != nil)
2745 xl = mkextel(mkseq(sl), (Ints*)&oid_subjectAltName, xl);
2747 e = mkseq(mkel(mkseq(xl), nil));
2748 e.tag.class = Context;
2749 e.tag.num = 3; /* Extensions */
2750 return mkel(e, nil);
2760 for(q = 0; *s != '\0'; s++){
2763 else if(q == 0 && *s == ','){
2772 X509rsagen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2774 int serial = 0, sigalg = ALG_sha256WithRSAEncryption;
2776 RSApub *pk = rsaprivtopub(priv);
2777 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2780 uchar digest[MAXdlen], *buf;
2785 subj = estrdup(subj);
2786 alts = splitalts(subj);
2788 e = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2789 if(encode(e, &pkbytes) != ASN_OK)
2791 freevalfields(&e.val);
2798 mkel(mkutc(valid[0]),
2799 mkel(mkutc(valid[1]),
2803 mkel(mkalg(ALG_rsaEncryption),
2804 mkel(mkbits(pkbytes->data, pkbytes->len),
2806 mkextensions(alts))))))));
2808 if(encode(e, &certinfobytes) != ASN_OK)
2811 da = digestalg[sigalg];
2812 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2813 freebytes(certinfobytes);
2816 sigbytes = encode_digest(da, digest);
2819 pkcs1 = pkcs1pad(sigbytes, pk->n);
2820 freebytes(sigbytes);
2822 rsadecrypt(priv, pkcs1, pkcs1);
2823 buflen = mptobe(pkcs1, nil, 0, &buf);
2828 mkel(mkbits(buf, buflen),
2831 if(encode(e, &certbytes) != ASN_OK)
2834 *certlen = certbytes->len;
2835 cert = malloc(certbytes->len);
2837 memmove(cert, certbytes->data, certbytes->len);
2838 freebytes(certbytes);
2840 freevalfields(&e.val);
2846 X509rsareq(RSApriv *priv, char *subj, int *certlen)
2848 /* RFC 2314, PKCS #10 Certification Request Syntax */
2849 int version = 0, sigalg = ALG_sha256WithRSAEncryption;
2851 RSApub *pk = rsaprivtopub(priv);
2852 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2855 uchar digest[MAXdlen], *buf;
2860 subj = estrdup(subj);
2861 alts = splitalts(subj);
2863 e = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2864 if(encode(e, &pkbytes) != ASN_OK)
2866 freevalfields(&e.val);
2868 mkel(mkint(version),
2871 mkel(mkalg(ALG_rsaEncryption),
2872 mkel(mkbits(pkbytes->data, pkbytes->len),
2874 mkextensions(alts)))));
2876 if(encode(e, &certinfobytes) != ASN_OK)
2878 da = digestalg[sigalg];
2879 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2880 freebytes(certinfobytes);
2883 sigbytes = encode_digest(da, digest);
2886 pkcs1 = pkcs1pad(sigbytes, pk->n);
2887 freebytes(sigbytes);
2889 rsadecrypt(priv, pkcs1, pkcs1);
2890 buflen = mptobe(pkcs1, nil, 0, &buf);
2895 mkel(mkbits(buf, buflen),
2898 if(encode(e, &certbytes) != ASN_OK)
2901 *certlen = certbytes->len;
2902 cert = malloc(certbytes->len);
2904 memmove(cert, certbytes->data, certbytes->len);
2905 freebytes(certbytes);
2907 freevalfields(&e.val);
2915 static char buf[32];
2917 if(tag.class != Universal){
2918 snprint(buf, sizeof(buf), "class%d,num%d", tag.class, tag.num);
2922 case BOOLEAN: return "BOOLEAN";
2923 case INTEGER: return "INTEGER";
2924 case BIT_STRING: return "BIT STRING";
2925 case OCTET_STRING: return "OCTET STRING";
2926 case NULLTAG: return "NULLTAG";
2927 case OBJECT_ID: return "OID";
2928 case ObjectDescriptor: return "OBJECT_DES";
2929 case EXTERNAL: return "EXTERNAL";
2930 case REAL: return "REAL";
2931 case ENUMERATED: return "ENUMERATED";
2932 case EMBEDDED_PDV: return "EMBEDDED PDV";
2933 case SEQUENCE: return "SEQUENCE";
2934 case SETOF: return "SETOF";
2935 case UTF8String: return "UTF8String";
2936 case NumericString: return "NumericString";
2937 case PrintableString: return "PrintableString";
2938 case TeletexString: return "TeletexString";
2939 case VideotexString: return "VideotexString";
2940 case IA5String: return "IA5String";
2941 case UTCTime: return "UTCTime";
2942 case GeneralizedTime: return "GeneralizedTime";
2943 case GraphicString: return "GraphicString";
2944 case VisibleString: return "VisibleString";
2945 case GeneralString: return "GeneralString";
2946 case UniversalString: return "UniversalString";
2947 case BMPString: return "BMPString";
2949 snprint(buf, sizeof(buf), "Universal,num%d", tag.num);
2961 print("%s{", tagdump(e.tag));
2964 case VBool: print("Bool %d",v.u.boolval); break;
2965 case VInt: print("Int %d",v.u.intval); break;
2966 case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2967 case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2968 case VReal: print("Real..."); break;
2969 case VOther: print("Other..."); break;
2970 case VBitString: print("BitString[%d]...", v.u.bitstringval->len*8 - v.u.bitstringval->unusedbits); break;
2971 case VNull: print("Null"); break;
2972 case VEOC: print("EOC..."); break;
2973 case VObjId: print("ObjId");
2974 for(i = 0; i<v.u.objidval->len; i++)
2975 print(" %d", v.u.objidval->data[i]);
2977 case VString: print("String \"%s\"",v.u.stringval); break;
2978 case VSeq: print("Seq\n");
2979 for(el = v.u.seqval; el!=nil; el = el->tl)
2982 case VSet: print("Set\n");
2983 for(el = v.u.setval; el!=nil; el = el->tl)
2991 asn1dump(uchar *der, int len)
2995 if(decode(der, len, &e) != ASN_OK){
2996 print("didn't parse\n");
2997 exits("didn't parse");
3003 X509dump(uchar *cert, int ncert)
3012 uchar digest[MAXdlen];
3014 print("begin X509dump\n");
3015 b = makebytes(cert, ncert);
3019 print("cannot decode cert\n");
3022 digestlen = digest_certinfo(b, digestalg[c->signature_alg], digest);
3026 print("cannot decode certinfo\n");
3030 print("serial %d\n", c->serial);
3031 print("issuer %s\n", c->issuer);
3032 print("validity %s %s\n", c->validity_start, c->validity_end);
3033 print("subject %s\n", c->subject);
3034 print("sigalg=%d digest=%.*H\n", c->signature_alg, digestlen, digest);
3035 print("publickey_alg=%d pubkey[%d] %.*H\n", c->publickey_alg, c->publickey->len,
3036 c->publickey->len, c->publickey->data);
3038 switch(c->publickey_alg){
3039 case ALG_rsaEncryption:
3040 rsapub = decode_rsapubkey(c->publickey);
3042 print("rsa pubkey e=%B n(%d)=%B\n", rsapub->ek, mpsignif(rsapub->n), rsapub->n);
3043 e = X509rsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, rsapub);
3045 e = "nil (meaning ok)";
3046 print("self-signed X509rsaverifydigest returns: %s\n", e);
3050 case ALG_ecPublicKey:
3051 ecdominit(&ecdom, namedcurves[c->curve]);
3052 ecpub = ecdecodepub(&ecdom, c->publickey->data, c->publickey->len);
3054 e = X509ecdsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, &ecdom, ecpub);
3056 e = "nil (meaning ok)";
3057 print("self-signed X509ecdsaverifydigest returns: %s\n", e);
3064 print("end X509dump\n");