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);
1477 free(v->u.stringval);
1481 for(l = el; l != nil; l = l->tl)
1482 freevalfields(&l->hd.val);
1487 for(l = el; l != nil; l = l->tl)
1488 freevalfields(&l->hd.val);
1492 memset(v, 0, sizeof(*v));
1502 return itomp(v, nil);
1503 if(is_bigint(e, &b))
1504 return betomp(b->data, b->len, nil);
1508 /* end of general ASN1 functions */
1514 /*=============================================================*/
1516 * Decode and parse an X.509 Certificate, defined by this ASN1:
1517 * Certificate ::= SEQUENCE {
1518 * certificateInfo CertificateInfo,
1519 * signatureAlgorithm AlgorithmIdentifier,
1520 * signature BIT STRING }
1522 * CertificateInfo ::= SEQUENCE {
1523 * version [0] INTEGER DEFAULT v1 (0),
1524 * serialNumber INTEGER,
1525 * signature AlgorithmIdentifier,
1527 * validity Validity,
1529 * subjectPublicKeyInfo SubjectPublicKeyInfo }
1530 * (version v2 has two more fields, optional unique identifiers for
1531 * issuer and subject; since we ignore these anyway, we won't parse them)
1533 * Validity ::= SEQUENCE {
1534 * notBefore UTCTime,
1535 * notAfter UTCTime }
1537 * SubjectPublicKeyInfo ::= SEQUENCE {
1538 * algorithm AlgorithmIdentifier,
1539 * subjectPublicKey BIT STRING }
1541 * AlgorithmIdentifier ::= SEQUENCE {
1542 * algorithm OBJECT IDENTIFER,
1543 * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1545 * Name ::= SEQUENCE OF RelativeDistinguishedName
1547 * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1549 * AttributeTypeAndValue ::= SEQUENCE {
1550 * type OBJECT IDENTIFER,
1551 * value DirectoryString }
1552 * (selected attributes have these Object Ids:
1553 * commonName {2 5 4 3}
1554 * countryName {2 5 4 6}
1555 * localityName {2 5 4 7}
1556 * stateOrProvinceName {2 5 4 8}
1557 * organizationName {2 5 4 10}
1558 * organizationalUnitName {2 5 4 11}
1561 * DirectoryString ::= CHOICE {
1562 * teletexString TeletexString,
1563 * printableString PrintableString,
1564 * universalString UniversalString }
1566 * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1568 * Not yet implemented:
1569 * CertificateRevocationList ::= SIGNED SEQUENCE{
1570 * signature AlgorithmIdentifier,
1572 * lastUpdate UTCTime,
1573 * nextUpdate UTCTime,
1574 * revokedCertificates
1575 * SEQUENCE OF CRLEntry OPTIONAL}
1576 * CRLEntry ::= SEQUENCE{
1577 * userCertificate SerialNumber,
1578 * revocationDate UTCTime}
1581 typedef struct CertX509 {
1584 char* validity_start;
1595 /* Algorithm object-ids */
1598 ALG_md2WithRSAEncryption,
1599 ALG_md4WithRSAEncryption,
1600 ALG_md5WithRSAEncryption,
1602 ALG_sha1WithRSAEncryption,
1603 ALG_sha1WithRSAEncryptionOiw,
1605 ALG_sha256WithRSAEncryption,
1606 ALG_sha384WithRSAEncryption,
1607 ALG_sha512WithRSAEncryption,
1608 ALG_sha224WithRSAEncryption,
1612 ALG_sha256WithECDSA,
1613 ALG_sha384WithECDSA,
1614 ALG_sha512WithECDSA,
1626 typedef struct Ints15 {
1631 typedef struct DigestAlg {
1633 DigestState* (*fun)(uchar*,ulong,uchar*,DigestState*);
1637 static DigestAlg alg_md5 = { ALG_md5, md5, MD5dlen};
1638 static DigestAlg alg_sha1 = { ALG_sha1, sha1, SHA1dlen };
1639 static DigestAlg alg_sha256 = { ALG_sha256, sha2_256, SHA2_256dlen };
1640 static DigestAlg alg_sha384 = { ALG_sha384, sha2_384, SHA2_384dlen };
1641 static DigestAlg alg_sha512 = { ALG_sha512, sha2_512, SHA2_512dlen };
1642 static DigestAlg alg_sha224 = { ALG_sha224, sha2_224, SHA2_224dlen };
1644 /* maximum length of digest output of the digest algs above */
1646 MAXdlen = SHA2_512dlen,
1649 static Ints15 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1651 static Ints15 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1652 static Ints15 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1653 static Ints15 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1654 static Ints15 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1655 static Ints15 oid_sha1WithRSAEncryptionOiw ={6, 1, 3, 14, 3, 2, 29 };
1656 static Ints15 oid_sha256WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 11 };
1657 static Ints15 oid_sha384WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 12 };
1658 static Ints15 oid_sha512WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 13 };
1659 static Ints15 oid_sha224WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 14 };
1661 static Ints15 oid_ecPublicKey = {6, 1, 2, 840, 10045, 2, 1 };
1662 static Ints15 oid_sha1WithECDSA = {6, 1, 2, 840, 10045, 4, 1 };
1663 static Ints15 oid_sha256WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 2 };
1664 static Ints15 oid_sha384WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 3 };
1665 static Ints15 oid_sha512WithECDSA = {7, 1, 2, 840, 10045, 4, 3, 4 };
1667 static Ints15 oid_md5 = {6, 1, 2, 840, 113549, 2, 5 };
1668 static Ints15 oid_sha1 = {6, 1, 3, 14, 3, 2, 26 };
1669 static Ints15 oid_sha256= {9, 2, 16, 840, 1, 101, 3, 4, 2, 1 };
1670 static Ints15 oid_sha384= {9, 2, 16, 840, 1, 101, 3, 4, 2, 2 };
1671 static Ints15 oid_sha512= {9, 2, 16, 840, 1, 101, 3, 4, 2, 3 };
1672 static Ints15 oid_sha224= {9, 2, 16, 840, 1, 101, 3, 4, 2, 4 };
1674 static Ints *alg_oid_tab[NUMALGS+1] = {
1675 (Ints*)&oid_rsaEncryption,
1676 (Ints*)&oid_md2WithRSAEncryption,
1677 (Ints*)&oid_md4WithRSAEncryption,
1678 (Ints*)&oid_md5WithRSAEncryption,
1680 (Ints*)&oid_sha1WithRSAEncryption,
1681 (Ints*)&oid_sha1WithRSAEncryptionOiw,
1683 (Ints*)&oid_sha256WithRSAEncryption,
1684 (Ints*)&oid_sha384WithRSAEncryption,
1685 (Ints*)&oid_sha512WithRSAEncryption,
1686 (Ints*)&oid_sha224WithRSAEncryption,
1688 (Ints*)&oid_ecPublicKey,
1689 (Ints*)&oid_sha1WithECDSA,
1690 (Ints*)&oid_sha256WithECDSA,
1691 (Ints*)&oid_sha384WithECDSA,
1692 (Ints*)&oid_sha512WithECDSA,
1703 static DigestAlg *digestalg[NUMALGS+1] = {
1704 &alg_md5, &alg_md5, &alg_md5, &alg_md5,
1705 &alg_sha1, &alg_sha1,
1706 &alg_sha256, &alg_sha384, &alg_sha512, &alg_sha224,
1707 &alg_sha256, &alg_sha1, &alg_sha256, &alg_sha384, &alg_sha512,
1708 &alg_md5, &alg_sha1, &alg_sha256, &alg_sha384, &alg_sha512, &alg_sha224,
1712 static Bytes* encode_digest(DigestAlg *da, uchar *digest);
1714 static Ints15 oid_secp256r1 = {7, 1, 2, 840, 10045, 3, 1, 7};
1715 static Ints15 oid_secp384r1 = {5, 1, 3, 132, 0, 34};
1717 static Ints *namedcurves_oid_tab[] = {
1718 (Ints*)&oid_secp256r1,
1719 (Ints*)&oid_secp384r1,
1722 static void (*namedcurves[])(mpint *p, mpint *a, mpint *b, mpint *x, mpint *y, mpint *n, mpint *h) = {
1728 static void appendaltnames(char *name, int nname, Bytes *ext, int req);
1731 freecert(CertX509* c)
1736 free(c->validity_start);
1737 free(c->validity_end);
1739 freebits(c->publickey);
1740 freebits(c->signature);
1746 * Parse the Name ASN1 type.
1747 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1748 * from most general to most specific. Each element of the path can be
1749 * one or more (but usually just one) attribute-value pair, such as
1751 * We'll just form a "postal-style" address string by concatenating the elements
1752 * from most specific to least specific, separated by commas.
1753 * Return name-as-string (which must be freed by caller).
1764 enum { MAXPARTS = 100 };
1765 char* parts[MAXPARTS];
1776 if(!is_set(es, &esetl))
1778 while(esetl != nil) {
1780 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1782 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1785 plen += strlen(s) + 2; /* room for ", " after */
1791 ans = (char*)emalloc(plen);
1806 * Parse an AlgorithmIdentifer ASN1 type.
1807 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1808 * or -1 if not found.
1809 * For now, ignore parameters, since none of our algorithms need them.
1817 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1819 return oid_lookup(oid, alg_oid_tab);
1823 parse_curve(Elem* e)
1828 if(!is_seq(e, &el) || elistlen(el)<2 || !is_oid(&el->tl->hd, &oid))
1830 return oid_lookup(oid, namedcurves_oid_tab);
1834 decode_cert(uchar *buf, int len)
1848 Elist* elcert = nil;
1849 Elist* elcertinfo = nil;
1850 Elist* elvalidity = nil;
1851 Elist* elpubkey = nil;
1857 if(decode(buf, len, &ecert) != ASN_OK)
1860 c = (CertX509*)emalloc(sizeof(CertX509));
1863 c->validity_start = nil;
1864 c->validity_end = nil;
1866 c->publickey_alg = -1;
1868 c->signature_alg = -1;
1873 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1875 ecertinfo = &elcert->hd;
1878 c->signature_alg = parse_alg(esigalg);
1882 /* Certificate Info */
1883 if(!is_seq(ecertinfo, &elcertinfo))
1885 n = elistlen(elcertinfo);
1888 eserial =&elcertinfo->hd;
1889 el = elcertinfo->tl;
1890 /* check for optional version, marked by explicit context tag 0 */
1891 if(eserial->tag.class == Context && eserial->tag.num == 0) {
1898 if(parse_alg(&el->hd) != c->signature_alg)
1903 evalidity = &el->hd;
1908 if(el->tl != nil && el->tl->hd.tag.class == Context && el->tl->hd.tag.num == 3){
1909 c->ext = el->tl->hd.val.u.octetsval;
1910 el->tl->hd.val.u.octetsval = nil; /* transfer ownership */
1912 if(!is_int(eserial, &c->serial)) {
1913 if(!is_bigint(eserial, &b))
1915 c->serial = -1; /* else we have to change cert struct */
1917 c->issuer = parse_name(eissuer);
1918 if(c->issuer == nil)
1921 if(!is_seq(evalidity, &elvalidity))
1923 if(elistlen(elvalidity) != 2)
1925 e = &elvalidity->hd;
1926 if(!is_time(e, &c->validity_start))
1928 e->val.u.stringval = nil; /* string ownership transfer */
1929 e = &elvalidity->tl->hd;
1930 if(!is_time(e, &c->validity_end))
1932 e->val.u.stringval = nil; /* string ownership transfer */
1934 /* resume CertificateInfo */
1935 c->subject = parse_name(esubj);
1936 if(c->subject == nil)
1939 /* SubjectPublicKeyInfo */
1940 if(!is_seq(epubkey, &elpubkey))
1942 if(elistlen(elpubkey) != 2)
1945 c->publickey_alg = parse_alg(&elpubkey->hd);
1946 if(c->publickey_alg < 0)
1949 if(c->publickey_alg == ALG_ecPublicKey){
1950 c->curve = parse_curve(&elpubkey->hd);
1954 elpubkey = elpubkey->tl;
1955 if(!is_bitstring(&elpubkey->hd, &bits))
1957 elpubkey->hd.val.u.bitstringval = nil; /* transfer ownership */
1958 c->publickey = bits;
1960 /*resume Certificate */
1961 if(c->signature_alg < 0)
1963 if(!is_bitstring(esig, &bits))
1965 esig->val.u.bitstringval = nil; /* transfer ownership */
1966 c->signature = bits;
1970 freevalfields(&ecert.val); /* recurses through lists, too */
1979 * RSAPublickKey ::= SEQUENCE {
1981 * publicExponent INTEGER
1985 asn1toRSApub(uchar *buf, int len)
1992 if(decode(buf, len, &e) != ASN_OK)
1994 if(!is_seq(&e, &el) || elistlen(el) != 2)
1997 key = rsapuballoc();
1998 if((key->n = asn1mpint(&el->hd)) == nil)
2001 if((key->ek = asn1mpint(&el->hd)) == nil)
2004 freevalfields(&e.val);
2007 freevalfields(&e.val);
2014 * RSAPrivateKey ::= SEQUENCE {
2016 * modulus INTEGER, -- n
2017 * publicExponent INTEGER, -- e
2018 * privateExponent INTEGER, -- d
2019 * prime1 INTEGER, -- p
2020 * prime2 INTEGER, -- q
2021 * exponent1 INTEGER, -- d mod (p-1)
2022 * exponent2 INTEGER, -- d mod (q-1)
2023 * coefficient INTEGER -- (inverse of q) mod p }
2026 asn1toRSApriv(uchar *buf, int len)
2034 if(decode(buf, len, &e) != ASN_OK)
2036 if(!is_seq(&e, &el))
2039 if(!is_int(&el->hd, &version) || version != 0)
2042 if(elistlen(el) != 9){
2043 if(elistlen(el) == 3
2044 && parse_alg(&el->tl->hd) == ALG_rsaEncryption
2045 && is_octetstring(&el->tl->tl->hd, &b)){
2046 key = asn1toRSApriv(b->data, b->len);
2053 key = rsaprivalloc();
2055 if((key->pub.n = asn1mpint(&el->hd)) == nil)
2059 if((key->pub.ek = asn1mpint(&el->hd)) == nil)
2063 if((key->dk = asn1mpint(&el->hd)) == nil)
2067 if((key->q = asn1mpint(&el->hd)) == nil)
2071 if((key->p = asn1mpint(&el->hd)) == nil)
2075 if((key->kq = asn1mpint(&el->hd)) == nil)
2079 if((key->kp = asn1mpint(&el->hd)) == nil)
2083 if((key->c2 = asn1mpint(&el->hd)) == nil)
2087 freevalfields(&e.val);
2090 freevalfields(&e.val);
2096 * digest(CertificateInfo)
2097 * Our ASN.1 library doesn't return pointers into the original
2098 * data array, so we need to do a little hand decoding.
2101 digest_certinfo(uchar *cert, int ncert, DigestAlg *da, uchar *digest)
2103 uchar *info, *p, *pend;
2104 int isconstr, length;
2109 pend = cert + ncert;
2110 if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2111 tag.class != Universal || tag.num != SEQUENCE ||
2112 length_decode(&p, pend, &length) != ASN_OK ||
2117 if(ber_decode(&p, pend, &elem) != ASN_OK)
2119 freevalfields(&elem.val);
2120 if(elem.tag.num != SEQUENCE)
2122 (*da->fun)(info, p - info, digest, nil);
2127 pkcs1padbuf(uchar *buf, int len, mpint *modulus, int blocktype)
2129 int i, n = (mpsignif(modulus)-1)/8;
2130 int pad = n - 2 - len;
2135 werrstr("rsa modulus too small");
2138 if((p = malloc(n)) == nil)
2144 memset(p+1, 0xFF, pad);
2147 for(i=1; i <= pad; i++)
2148 p[i] = 1 + nfastrand(255);
2152 memmove(p+2+pad, buf, len);
2153 mp = betomp(p, n, nil);
2159 pkcs1unpadbuf(uchar *buf, int len, mpint *modulus, int blocktype)
2161 uchar *p = buf + 1, *e = buf + len;
2163 if(len < 1 || len != (mpsignif(modulus)-1)/8 || buf[0] != blocktype)
2168 while(p < e && *p == 0xFF)
2172 while(p < e && *p != 0x00)
2176 if(p - buf <= 8 || p >= e || *p++ != 0x00)
2178 memmove(buf, p, len = e - p);
2182 static char Ebadsig[] = "bad signature";
2185 X509rsaverifydigest(uchar *sig, int siglen, uchar *edigest, int edigestlen, RSApub *pk)
2194 x = betomp(sig, siglen, nil);
2195 y = rsaencrypt(pk, x, nil);
2197 len = mptobe(y, nil, 0, &buf);
2201 len = pkcs1unpadbuf(buf, len, pk->n, 1);
2202 if(len == edigestlen && tsmemcmp(buf, edigest, edigestlen) == 0)
2204 for(dp = digestalg; err != nil && *dp != nil; dp++){
2205 if((*dp)->len != edigestlen)
2207 digest = encode_digest(*dp, edigest);
2208 if(digest->len == len && tsmemcmp(digest->data, buf, len) == 0)
2217 X509ecdsaverifydigest(uchar *sig, int siglen, uchar *edigest, int edigestlen, ECdomain *dom, ECpub *pub)
2226 if(decode(sig, siglen, &e) != ASN_OK)
2228 if(!is_seq(&e, &el) || elistlen(el) != 2)
2230 r = asn1mpint(&el->hd);
2234 s = asn1mpint(&el->hd);
2237 if(ecdsaverify(dom, pub, edigest, edigestlen, r, s))
2240 freevalfields(&e.val);
2247 copysubject(char *name, int nname, char *subject)
2253 memset(name, 0, nname);
2256 strncpy(name, subject, nname-1);
2257 e = strchr(name, ',');
2259 *e = 0; /* take just CN part of Distinguished Name */
2263 X509toECpub(uchar *cert, int ncert, char *name, int nname, ECdomain *dom)
2268 c = decode_cert(cert, ncert);
2271 copysubject(name, nname, c->subject);
2272 appendaltnames(name, nname, c->ext, 0);
2274 if(c->publickey_alg == ALG_ecPublicKey){
2275 ecdominit(dom, namedcurves[c->curve]);
2276 pub = ecdecodepub(dom, c->publickey->data, c->publickey->len);
2285 X509ecdsaverify(uchar *cert, int ncert, ECdomain *dom, ECpub *pk)
2290 uchar digest[MAXdlen];
2292 c = decode_cert(cert, ncert);
2294 return "cannot decode cert";
2295 digestlen = digest_certinfo(cert, ncert, digestalg[c->signature_alg], digest);
2298 return "cannot decode certinfo";
2300 e = X509ecdsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, dom, pk);
2306 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2311 c = decode_cert(cert, ncert);
2314 copysubject(name, nname, c->subject);
2315 appendaltnames(name, nname, c->ext, 0);
2317 if(c->publickey_alg == ALG_rsaEncryption)
2318 pub = asn1toRSApub(c->publickey->data, c->publickey->len);
2324 X509rsaverify(uchar *cert, int ncert, RSApub *pk)
2329 uchar digest[MAXdlen];
2331 c = decode_cert(cert, ncert);
2333 return "cannot decode cert";
2334 digestlen = digest_certinfo(cert, ncert, digestalg[c->signature_alg], digest);
2337 return "cannot decode certinfo";
2339 e = X509rsaverifydigest(c->signature->data, c->signature->len, digest, digestlen, pk);
2344 /* ------- Elem constructors ---------- */
2350 e.tag.class = Universal;
2351 e.tag.num = NULLTAG;
2361 e.tag.class = Universal;
2362 e.tag.num = INTEGER;
2373 e.tag.class = Universal;
2374 e.tag.num = INTEGER;
2375 e.val.tag = VBigInt;
2376 e.val.u.bigintval = newbytes((mpsignif(p)+8)/8);
2378 mpint *s = mpnew(e.val.u.bigintval->len*8+1);
2379 mpleft(mpone, e.val.u.bigintval->len*8, s);
2381 mptober(s, e.val.u.bigintval->data, e.val.u.bigintval->len);
2384 mptober(p, e.val.u.bigintval->data, e.val.u.bigintval->len);
2394 while((c = (uchar)*s++) != 0){
2395 if((c >= 'a' && c <= 'z')
2396 || (c >= 'A' && c <= 'Z')
2397 || (c >= '0' && c <= '9')
2398 || strchr("'=()+,-./:? ", c) != nil)
2405 #define DirectoryString 0
2408 mkstring(char *s, int t)
2412 if(t == DirectoryString)
2413 t = printable(s) ? PrintableString : UTF8String;
2414 e.tag.class = Universal;
2416 e.val.tag = VString;
2417 e.val.u.stringval = estrdup(s);
2422 mkoctet(uchar *buf, int buflen)
2426 e.tag.class = Universal;
2427 e.tag.num = OCTET_STRING;
2428 e.val.tag = VOctets;
2429 e.val.u.octetsval = makebytes(buf, buflen);
2434 mkbits(uchar *buf, int buflen)
2438 e.tag.class = Universal;
2439 e.tag.num = BIT_STRING;
2440 e.val.tag = VBitString;
2441 e.val.u.bitstringval = makebits(buf, buflen, 0);
2452 e.tag.class = Universal;
2453 e.tag.num = UTCTime;
2454 e.val.tag = VString;
2455 snprint(utc, sizeof(utc), "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2456 tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2457 e.val.u.stringval = estrdup(utc);
2466 e.tag.class = Universal;
2467 e.tag.num = OBJECT_ID;
2469 e.val.u.objidval = makeints(oid->data, oid->len);
2478 e.tag.class = Universal;
2479 e.tag.num = SEQUENCE;
2481 e.val.u.seqval = el;
2490 e.tag.class = Universal;
2493 e.val.u.setval = el;
2500 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2503 typedef struct Ints7pref {
2509 Ints7pref DN_oid[] = {
2510 {4, 2, 5, 4, 6, 0, 0, 0, "C=", PrintableString},
2511 {4, 2, 5, 4, 8, 0, 0, 0, "ST=",DirectoryString},
2512 {4, 2, 5, 4, 7, 0, 0, 0, "L=", DirectoryString},
2513 {4, 2, 5, 4, 10, 0, 0, 0, "O=", DirectoryString},
2514 {4, 2, 5, 4, 11, 0, 0, 0, "OU=",DirectoryString},
2515 {4, 2, 5, 4, 3, 0, 0, 0, "CN=",DirectoryString},
2516 {7, 1,2,840,113549,1,9,1, "E=", IA5String},
2517 {7, 0,9,2342,19200300,100,1,25, "DC=",IA5String},
2521 mkname(Ints7pref *oid, char *subj)
2523 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj, oid->stype), nil))), nil));
2530 char *f[20], *prefix, *d2 = estrdup(dn);
2533 nf = tokenize(d2, f, nelem(f));
2534 for(i=nf-1; i>=0; i--){
2535 for(j=0; j<nelem(DN_oid); j++){
2536 prefix = DN_oid[j].prefix;
2537 if(strncmp(f[i],prefix,strlen(prefix))==0){
2538 el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2548 * DigestInfo ::= SEQUENCE {
2549 * digestAlgorithm AlgorithmIdentifier,
2550 * digest OCTET STRING }
2553 encode_digest(DigestAlg *da, uchar *digest)
2557 mkel(mkalg(da->alg),
2558 mkel(mkoctet(digest, da->len),
2561 freevalfields(&e.val);
2566 asn1encodedigest(DigestState* (*fun)(uchar*, ulong, uchar*, DigestState*), uchar *digest, uchar *buf, int len)
2571 for(dp = digestalg; *dp != nil; dp++){
2572 if((*dp)->fun != fun)
2574 bytes = encode_digest(*dp, digest);
2577 if(bytes->len > len){
2582 memmove(buf, bytes->data, len);
2590 mkcont(int num, Elist *l)
2593 e.tag.class = Context;
2604 for(i=0; i<nelem(DN_oid); i++){
2605 if(strstr(s, DN_oid[i].prefix) != nil)
2606 return mkcont(4, mkel(mkDN(s), nil)); /* DN */
2608 e = mkstring(s, IA5String);
2609 e.tag.class = Context;
2610 e.tag.num = strchr(s, '@') != nil ? 1 : 2; /* email : DNS */
2615 mkaltnames(char *alts)
2624 alts = estrdup(alts);
2625 for(s = alts; s != nil; s = p){
2630 if((p = strchr(s, ',')) != nil)
2632 el = mkel(mkaltname(s), el);
2639 mkextel(Elem e, Ints *oid, Elist *el)
2643 if(encode(e, &b) == ASN_OK){
2646 mkel(mkoctet(b->data, b->len),
2650 freevalfields(&e.val);
2654 static Ints15 oid_subjectAltName = {4, 2, 5, 29, 17 };
2655 static Ints15 oid_extensionRequest = { 7, 1, 2, 840, 113549, 1, 9, 14};
2658 mkextensions(char *alts, int isreq)
2663 if((sl = mkaltnames(alts)) != nil)
2664 xl = mkextel(mkseq(sl), (Ints*)&oid_subjectAltName, xl);
2666 xl = mkel(mkseq(xl), nil);
2669 mkel(mkoid((Ints*)&oid_extensionRequest),
2670 mkel(mkset(xl), nil))), nil);
2673 xl = mkel(mkcont(0, xl), nil);
2675 xl = mkel(mkcont(3, xl), nil);
2684 for(q = 0; *s != '\0'; s++){
2687 else if(q == 0 && *s == ','){
2696 appendaltnames(char *name, int nname, Bytes *ext, int isreq)
2698 Elem eext, ealt, edn;
2704 if(name == nil || ext == nil)
2706 if(decode(ext->data, ext->len, &eext) != ASN_OK)
2709 if(!is_seq(&eext, &el) || elistlen(el) != 2)
2711 if(!is_oid(&el->hd, &oid) || !ints_eq(oid, (Ints*)&oid_extensionRequest))
2714 if(!is_set(&el->hd, &el))
2716 if(!is_seq(&el->hd, &el))
2719 if(!is_seq(&eext, &el))
2722 for(; el != nil; el = el->tl){
2723 if(!is_seq(&el->hd, &l) || elistlen(l) != 2)
2725 if(!is_oid(&l->hd, &oid) || !ints_eq(oid, (Ints*)&oid_subjectAltName))
2732 if(!is_octetstring(&el->hd, &ext))
2734 if(decode(ext->data, ext->len, &ealt) != ASN_OK)
2736 if(!is_seq(&ealt, &el))
2738 for(; el != nil; el = el->tl){
2739 ext = el->hd.val.u.octetsval;
2740 switch(el->hd.tag.num){
2747 alt = smprint("%.*s", ext->len, (char*)ext->data);
2750 if(ext == nil || decode(ext->data, ext->len, &edn) != ASN_OK)
2752 alt = parse_name(&edn);
2753 freevalfields(&edn.val);
2759 if(strncmp(name, alt, len) == 0 && strchr(",", name[len]) == nil){
2760 free(alt); /* same as the subject */
2764 strncat(name, ", ", nname-1);
2765 strncat(name, alt, nname-1);
2769 freevalfields(&ealt.val);
2771 freevalfields(&eext.val);
2775 encode_rsapubkey(RSApub *pk)
2779 mkel(mkbigint(pk->n),
2780 mkel(mpsignif(pk->ek)<32 ? mkint(mptoi(pk->ek)) : mkbigint(pk->ek),
2783 freevalfields(&e.val);
2788 encode_rsaprivkey(RSApriv *k)
2791 RSApub *pk = &k->pub;
2794 mkel(mkbigint(pk->n),
2795 mkel(mpsignif(pk->ek)<32 ? mkint(mptoi(pk->ek)) : mkbigint(pk->ek),
2796 mkel(mkbigint(k->dk),
2797 mkel(mkbigint(k->p),
2798 mkel(mkbigint(k->q),
2799 mkel(mkbigint(k->kp),
2800 mkel(mkbigint(k->kq),
2801 mkel(mkbigint(k->c2),
2804 freevalfields(&e.val);
2809 asn1encodeRSApub(RSApub *pk, uchar *buf, int len)
2811 Bytes *b = encode_rsapubkey(pk);
2816 werrstr("buffer too small");
2819 memmove(buf, b->data, len = b->len);
2825 asn1encodeRSApriv(RSApriv *k, uchar *buf, int len)
2828 b = encode_rsaprivkey(k);
2833 werrstr("buffer too small");
2836 memmove(buf, b->data, len = b->len);
2842 X509rsagen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2844 int serial = 0, sigalg = ALG_sha256WithRSAEncryption;
2846 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2849 uchar digest[MAXdlen], *buf;
2854 if((pkbytes = encode_rsapubkey(&priv->pub)) == nil)
2857 subj = estrdup(subj);
2858 alts = splitalts(subj);
2861 mkel(mkcont(0, mkel(mkint(2), nil)),
2866 mkel(mkutc(valid[0]),
2867 mkel(mkutc(valid[1]),
2871 mkel(mkalg(ALG_rsaEncryption),
2872 mkel(mkbits(pkbytes->data, pkbytes->len),
2874 mkextensions(alts, 0)))))))));
2876 if(encode(e, &certinfobytes) != ASN_OK)
2879 da = digestalg[sigalg];
2880 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2881 freebytes(certinfobytes);
2884 sigbytes = encode_digest(da, digest);
2887 pkcs1 = pkcs1padbuf(sigbytes->data, sigbytes->len, priv->pub.n, 1);
2888 freebytes(sigbytes);
2892 rsadecrypt(priv, pkcs1, pkcs1);
2893 buflen = mptobe(pkcs1, nil, 0, &buf);
2898 mkel(mkbits(buf, buflen),
2901 if(encode(e, &certbytes) != ASN_OK)
2904 *certlen = certbytes->len;
2905 cert = (uchar*)certbytes;
2906 memmove(cert, certbytes->data, certbytes->len);
2908 freevalfields(&e.val);
2914 X509rsareq(RSApriv *priv, char *subj, int *certlen)
2916 /* RFC 2314, PKCS #10 Certification Request Syntax */
2917 int version = 0, sigalg = ALG_sha256WithRSAEncryption;
2919 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2922 uchar digest[MAXdlen], *buf;
2927 if((pkbytes = encode_rsapubkey(&priv->pub)) == nil)
2930 subj = estrdup(subj);
2931 alts = splitalts(subj);
2934 mkel(mkint(version),
2937 mkel(mkalg(ALG_rsaEncryption),
2938 mkel(mkbits(pkbytes->data, pkbytes->len),
2940 mkextensions(alts, 1)))));
2942 if(encode(e, &certinfobytes) != ASN_OK)
2944 da = digestalg[sigalg];
2945 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2946 freebytes(certinfobytes);
2949 sigbytes = encode_digest(da, digest);
2952 pkcs1 = pkcs1padbuf(sigbytes->data, sigbytes->len, priv->pub.n, 1);
2953 freebytes(sigbytes);
2957 rsadecrypt(priv, pkcs1, pkcs1);
2958 buflen = mptobe(pkcs1, nil, 0, &buf);
2963 mkel(mkbits(buf, buflen),
2966 if(encode(e, &certbytes) != ASN_OK)
2969 *certlen = certbytes->len;
2970 cert = (uchar*)certbytes;
2971 memmove(cert, certbytes->data, certbytes->len);
2973 freevalfields(&e.val);
2979 X509reqtoRSApub(uchar *req, int nreq, char *name, int nname)
2988 if(decode(req, nreq, &ereq) != ASN_OK)
2990 if(!is_seq(&ereq, &el) || elistlen(el) != 3)
2992 if(!is_seq(&el->hd, &el) || elistlen(el) < 3)
2995 subject = parse_name(&el->hd);
2998 copysubject(name, nname, subject);
3001 if(el->tl != nil && el->tl->hd.tag.class == Context && el->tl->hd.tag.num == 0)
3002 appendaltnames(name, nname, el->tl->hd.val.u.octetsval, 1);
3003 if(!is_seq(&el->hd, &el) || elistlen(el) != 2)
3005 if(parse_alg(&el->hd) != ALG_rsaEncryption)
3008 if(!is_bitstring(&el->hd, &bits))
3010 pub = asn1toRSApub(bits->data, bits->len);
3014 freevalfields(&ereq.val);
3019 digestSPKI(int alg, uchar *pubkey, int npubkey, DigestState* (*fun)(uchar*, ulong, uchar*, DigestState*), uchar *digest)
3022 Elem e = mkseq(mkel(mkalg(alg), mkel(mkbits(pubkey, npubkey), nil)));
3024 freevalfields(&e.val);
3025 (*fun)(b->data, b->len, digest, nil);
3030 X509digestSPKI(uchar *cert, int ncert, DigestState* (*fun)(uchar*, ulong, uchar*, DigestState*), uchar *digest)
3034 c = decode_cert(cert, ncert);
3036 werrstr("cannot decode cert");
3039 digestSPKI(c->publickey_alg, c->publickey->data, c->publickey->len, fun, digest);
3047 static char buf[32];
3049 if(tag.class != Universal){
3050 snprint(buf, sizeof(buf), "class%d,num%d", tag.class, tag.num);
3054 case BOOLEAN: return "BOOLEAN";
3055 case INTEGER: return "INTEGER";
3056 case BIT_STRING: return "BIT STRING";
3057 case OCTET_STRING: return "OCTET STRING";
3058 case NULLTAG: return "NULLTAG";
3059 case OBJECT_ID: return "OID";
3060 case ObjectDescriptor: return "OBJECT_DES";
3061 case EXTERNAL: return "EXTERNAL";
3062 case REAL: return "REAL";
3063 case ENUMERATED: return "ENUMERATED";
3064 case EMBEDDED_PDV: return "EMBEDDED PDV";
3065 case SEQUENCE: return "SEQUENCE";
3066 case SETOF: return "SETOF";
3067 case UTF8String: return "UTF8String";
3068 case NumericString: return "NumericString";
3069 case PrintableString: return "PrintableString";
3070 case TeletexString: return "TeletexString";
3071 case VideotexString: return "VideotexString";
3072 case IA5String: return "IA5String";
3073 case UTCTime: return "UTCTime";
3074 case GeneralizedTime: return "GeneralizedTime";
3075 case GraphicString: return "GraphicString";
3076 case VisibleString: return "VisibleString";
3077 case GeneralString: return "GeneralString";
3078 case UniversalString: return "UniversalString";
3079 case BMPString: return "BMPString";
3081 snprint(buf, sizeof(buf), "Universal,num%d", tag.num);
3093 print("%s{", tagdump(e.tag));
3096 case VBool: print("Bool %d",v.u.boolval); break;
3097 case VInt: print("Int %d",v.u.intval); break;
3098 case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
3099 case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
3100 case VReal: print("Real..."); break;
3101 case VOther: print("Other..."); break;
3102 case VBitString: print("BitString[%d]...", v.u.bitstringval->len*8 - v.u.bitstringval->unusedbits); break;
3103 case VNull: print("Null"); break;
3104 case VEOC: print("EOC..."); break;
3105 case VObjId: print("ObjId");
3106 for(i = 0; i<v.u.objidval->len; i++)
3107 print(" %d", v.u.objidval->data[i]);
3109 case VString: print("String \"%s\"",v.u.stringval); break;
3110 case VSeq: print("Seq\n");
3111 for(el = v.u.seqval; el!=nil; el = el->tl)
3114 case VSet: print("Set\n");
3115 for(el = v.u.setval; el!=nil; el = el->tl)
3123 asn1dump(uchar *der, int len)
3127 if(decode(der, len, &e) != ASN_OK){
3128 print("didn't parse\n");
3129 exits("didn't parse");
3135 X509dump(uchar *cert, int ncert)
3143 uchar digest[MAXdlen];
3145 print("begin X509dump\n");
3146 c = decode_cert(cert, ncert);
3148 print("cannot decode cert\n");
3152 digestlen = digest_certinfo(cert, ncert, digestalg[c->signature_alg], digest);
3155 print("cannot decode certinfo\n");
3159 print("serial %d\n", c->serial);
3160 print("issuer %s\n", c->issuer);
3161 print("validity %s %s\n", c->validity_start, c->validity_end);
3162 print("subject %s\n", c->subject);
3163 print("sigalg=%d digest=%.*H\n", c->signature_alg, digestlen, digest);
3164 print("publickey_alg=%d pubkey[%d] %.*H\n", c->publickey_alg, c->publickey->len,
3165 c->publickey->len, c->publickey->data);
3167 switch(c->publickey_alg){
3168 case ALG_rsaEncryption:
3169 rsapub = asn1toRSApub(c->publickey->data, c->publickey->len);
3171 print("rsa pubkey e=%B n(%d)=%B\n", rsapub->ek, mpsignif(rsapub->n), rsapub->n);
3172 e = X509rsaverifydigest(c->signature->data, c->signature->len,
3173 digest, digestlen, rsapub);
3175 e = "nil (meaning ok)";
3176 print("self-signed X509rsaverifydigest returns: %s\n", e);
3180 case ALG_ecPublicKey:
3181 ecdominit(&ecdom, namedcurves[c->curve]);
3182 ecpub = ecdecodepub(&ecdom, c->publickey->data, c->publickey->len);
3184 e = X509ecdsaverifydigest(c->signature->data, c->signature->len,
3185 digest, digestlen, &ecdom, ecpub);
3187 e = "nil (meaning ok)";
3188 print("self-signed X509ecdsaverifydigest returns: %s\n", e);
3195 digestSPKI(c->publickey_alg, c->publickey->data, c->publickey->len, sha2_256, digest);
3196 print("publickey_thumbprint sha256=%.*[\n", SHA2_256dlen, digest);
3198 sha2_256(cert, ncert, digest, nil);
3199 print("cert_thumbprint sha256=%.*[\n", SHA2_256dlen, digest);
3201 sha1(cert, ncert, digest, nil);
3202 print("cert_thumbprint sha1=%.*H\n", SHA1dlen, digest);
3205 print("end X509dump\n");