6 /* ANSI offsetof, backwards. */
7 #define OFFSETOF(a, b) offsetof(b, a)
9 /*=============================================================*/
10 /* general ASN1 declarations and parsing
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.
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;
33 #define OCTET_STRING 4
36 #define ObjectDescriptor 7
40 #define EMBEDDED_PDV 11
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
50 #define GeneralizedTime 24
51 #define GraphicString 25
52 #define VisibleString 26
53 #define GeneralString 27
54 #define UniversalString 28
68 int len; /* number of bytes */
69 int unusedbits; /* unused bits in last byte */
70 uchar data[1]; /* most-significant bit first */
78 enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
79 VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
81 int tag; /* VBool, etc. */
87 Bytes* realval; /* undecoded; hardly ever used */
94 } u; /* (Don't use anonymous unions, for ease of porting) */
107 /* decoding errors */
108 enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
109 ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
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);
145 #define TAG_MASK 0x1F
146 #define CONSTR_MASK 0x20
147 #define CLASS_MASK 0xC0
148 #define MAXOBJIDLEN 20
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);
171 sysfatal("out of memory");
173 setmalloctag(p, getcallerpc(&n));
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
197 decode(uchar* a, int alen, Elem* pelem)
201 return ber_decode(&p, &a[alen], pelem);
205 * Like decode, but continue decoding after first element
209 decode_seq(uchar* a, int alen, Elist** pelist)
213 return seq_decode(&p, &a[alen], -1, 1, pelist);
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
226 decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
230 return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
234 * All of the following decoding routines take arguments:
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.
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.
246 /* Decode an ASN1 'Elem' (tag, length, value) */
248 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
256 err = tag_decode(pp, pend, &tag, &isconstr);
258 err = length_decode(pp, pend, &length);
260 if(tag.class == Universal)
261 err = value_decode(pp, pend, length, tag.num, isconstr, &val);
263 err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
273 /* Decode a tag field */
275 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
285 ptag->class = v&CLASS_MASK;
292 err = uint7_decode(&p, pend, &v);
301 /* Decode a length field */
303 length_decode(uchar** pp, uchar* pend, int* plength)
316 err = int_decode(&p, pend, v&0x7F, 1, &num);
327 /* Decode a value field */
329 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
335 int subids[MAXOBJIDLEN];
343 if(length == -1) { /* "indefinite" length spec */
347 else if(p + length > pend)
354 /* marker for end of indefinite constructions */
368 pval->u.boolval = (*p++ != 0);
376 else if(length <= 4) {
377 err = int_decode(&p, pend, length, 0, &num);
380 pval->u.intval = num;
385 pval->u.bigintval = makebytes(p, length);
391 pval->tag = VBitString;
393 if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
394 pval->u.bitstringval = makebits(0, 0, 0);
397 else /* TODO: recurse and concat results */
402 if(length == 1 && *p == 0) {
403 pval->u.bitstringval = makebits(0, 0, 0);
413 else if(length > 0x0FFFFFFF)
416 pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
424 case ObjectDescriptor:
425 err = octet_decode(&p, pend, length, isconstr, &va);
428 pval->u.octetsval = va;
449 while(p < pe && isubid < MAXOBJIDLEN) {
450 err = uint7_decode(&p, pend, &num);
454 subids[isubid++] = num / 40;
455 subids[isubid++] = num % 40;
458 subids[isubid++] = num;
465 pval->u.objidval = makeints(subids, isubid);
473 /* TODO: parse this internally */
478 pval->u.otherval = makebytes(p, length);
484 /* Let the application decode */
487 else if(p+length > pend)
491 pval->u.realval = makebytes(p, length);
497 err = seq_decode(&p, pend, length, isconstr, &vl);
505 err = seq_decode(&p, pend, length, isconstr, &vl);
513 case PrintableString:
518 case GeneralizedTime:
522 case UniversalString:
524 /* TODO: figure out when character set conversion is necessary */
525 err = octet_decode(&p, pend, length, isconstr, &va);
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;
540 pval->u.otherval = makebytes(p, length);
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.
557 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
566 if(p+count <= pend) {
567 if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
570 if(!unsgned && count > 0 && count < 4 && (*p&0x80))
571 num = -1; /* set all bits, initially */
573 num = (num << 8)|(*p++);
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.
591 uint7_decode(uchar** pp, uchar* pend, int* pint)
603 while(more && p < pend) {
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)
626 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
639 if(length >= 0 && !isconstr) {
640 ans = makebytes(p, length);
644 /* constructed, either definite or indefinite length */
647 if(length >= 0 && p >= pstart + length) {
648 if(p != pstart + length)
653 err = ber_decode(&p, pend, &elem);
656 switch(elem.val.tag) {
658 newans = catbytes(ans, elem.val.u.octetsval);
659 freevalfields(&elem.val);
669 freevalfields(&elem.val);
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)
692 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
709 /* constructed, either definite or indefinite length */
713 if(length >= 0 && p >= pstart + length) {
714 if(p != pstart + length)
719 err = ber_decode(&p, pend, &elem);
722 if(elem.val.tag == VEOC) {
730 lve = mkel(elem, lve);
735 /* reverse back to original order */
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.
756 encode(Elem e, Bytes** pbytes)
766 ans = newbytes(p-&uc);
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
781 * If lenonly is 0, it is assumed that the answer will fit.
785 enc(uchar** pp, Elem e, int lenonly)
797 err = val_enc(&p, e, &constr, 1);
803 v = tag.class|constr;
815 uint7_enc(&p, tag.num, lenonly);
824 int_enc(&p, vlen, 1, 1);
828 *p++ = (0x80 | ilen);
829 int_enc(&p, vlen, 1, 0);
835 val_enc(&p, e, &constr, 0);
843 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
862 if(cl != Universal) {
892 kind = UniversalString;
907 int_enc(&p, v, 1, lenonly);
916 int_enc(&p, v, 0, lenonly);
918 if(is_bigint(&e, &bb)) {
920 memmove(p, bb->data, bb->len);
929 if(is_bitstring(&e, &bits)) {
936 v = bits->unusedbits;
942 memmove(p+1, bits->data, bits->len);
953 case ObjectDescriptor:
960 bb = e.val.u.octetsval;
963 bb = e.val.u.realval;
966 bb = e.val.u.otherval;
971 memmove(p, bb->data, bb->len);
982 if(is_oid(&e, &oid)) {
983 for(k = 0; k < oid->len; k++) {
990 uint7_enc(&p, v, lenonly);
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;
1007 *pconstr = CONSTR_MASK;
1008 for(; el != nil; el = el->tl) {
1009 err = enc(&p, el->hd, lenonly);
1018 case PrintableString:
1020 case VideotexString:
1023 case GeneralizedTime:
1027 case UniversalString:
1029 if(e.val.tag == VString) {
1030 s = e.val.u.stringval;
1050 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1051 * except last, only putting in bytes if !lenonly.
1054 uint7_enc(uchar** pp, int num, int lenonly)
1071 for(k = (n - 1)*7; k > 0; k -= 7)
1072 *p++= ((num >> k)|0x80);
1079 * Encode num as unsigned or signed integer,
1080 * only putting in bytes if !lenonly.
1081 * Encoding is length followed by bytes to concatenate.
1084 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1104 if(!unsgned && (prevv&0x80))
1109 for(k = (n - 1)*8; k >= 0; k -= 8)
1116 ints_eq(Ints* a, Ints* b)
1124 for(i = 0; i < alen; i++)
1125 if(a->data[i] != b->data[i])
1131 * Look up o in tab (which must have nil entry to terminate).
1132 * Return index of matching entry, or -1 if none.
1135 oid_lookup(Ints* o, Ints** tab)
1139 for(i = 0; tab[i] != nil; i++)
1140 if(ints_eq(o, tab[i]))
1146 * Return true if *pe is a SEQUENCE, and set *pseq to
1147 * the value of the sequence if so.
1150 is_seq(Elem* pe, Elist** pseq)
1152 if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1153 *pseq = pe->val.u.seqval;
1160 is_set(Elem* pe, Elist** pset)
1162 if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1163 *pset = pe->val.u.setval;
1170 is_int(Elem* pe, int* pint)
1172 if(pe->tag.class == Universal) {
1173 if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1174 *pint = pe->val.u.intval;
1177 else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1178 *pint = pe->val.u.boolval;
1186 * for convience, all VInt's are readable via this routine,
1187 * as well as all VBigInt's
1190 is_bigint(Elem* pe, Bytes** pbigint)
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)
1202 *pbigint = newbytes(n);
1203 for(i = 0; i < n; i++)
1204 (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1213 is_bitstring(Elem* pe, Bits** pbits)
1215 if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1216 *pbits = pe->val.u.bitstringval;
1223 is_octetstring(Elem* pe, Bytes** poctets)
1225 if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1226 *poctets = pe->val.u.octetsval;
1233 is_oid(Elem* pe, Ints** poid)
1235 if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1236 *poid = pe->val.u.objidval;
1243 is_string(Elem* pe, char** pstring)
1245 if(pe->tag.class == Universal) {
1246 switch(pe->tag.num) {
1249 case PrintableString:
1251 case VideotexString:
1256 case UniversalString:
1258 if(pe->val.tag == VString) {
1259 *pstring = pe->val.u.stringval;
1268 is_time(Elem* pe, char** ptime)
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;
1281 * malloc and return a new Bytes structure capable of
1282 * holding len bytes. (len >= 0)
1291 ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1297 * newbytes(len), with data initialized from buf
1300 makebytes(uchar* buf, int len)
1304 ans = newbytes(len);
1305 memmove(ans->data, buf, len);
1316 * Make a new Bytes, containing bytes of b1 followed by those of b2.
1317 * Either b1 or b2 or both can be nil.
1320 catbytes(Bytes* b1, Bytes* b2)
1329 ans = makebytes(b2->data, b2->len);
1331 else if(b2 == nil) {
1332 ans = makebytes(b1->data, b1->len);
1335 n = b1->len + b2->len;
1338 memmove(ans->data, b1->data, b1->len);
1339 memmove(ans->data+b1->len, b2->data, b2->len);
1344 /* len is number of ints */
1350 if(len < 0 || len > ((uint)-1>>1)/sizeof(int))
1352 ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1358 makeints(int* buf, int len)
1363 memmove(ans->data, buf, len*sizeof(int));
1373 /* len is number of bytes */
1381 ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1383 ans->unusedbits = 0;
1388 makebits(uchar* buf, int len, int unusedbits)
1393 memmove(ans->data, buf, len);
1394 ans->unusedbits = unusedbits;
1405 mkel(Elem e, Elist* tail)
1409 el = (Elist*)emalloc(sizeof(Elist));
1410 setmalloctag(el, getcallerpc(&e));
1427 /* Frees elist, but not fields inside values of constituent elems */
1429 freeelist(Elist* el)
1440 /* free any allocated structures inside v (recursively freeing Elists) */
1442 freevalfields(Value* v)
1450 freebytes(v->u.octetsval);
1453 freebytes(v->u.bigintval);
1456 freebytes(v->u.realval);
1459 freebytes(v->u.otherval);
1462 freebits(v->u.bitstringval);
1465 freeints(v->u.objidval);
1469 free(v->u.stringval);
1473 for(l = el; l != nil; l = l->tl)
1474 freevalfields(&l->hd.val);
1479 for(l = el; l != nil; l = l->tl)
1480 freevalfields(&l->hd.val);
1486 /* end of general ASN1 functions */
1492 /*=============================================================*/
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 }
1500 * CertificateInfo ::= SEQUENCE {
1501 * version [0] INTEGER DEFAULT v1 (0),
1502 * serialNumber INTEGER,
1503 * signature AlgorithmIdentifier,
1505 * validity Validity,
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)
1511 * Validity ::= SEQUENCE {
1512 * notBefore UTCTime,
1513 * notAfter UTCTime }
1515 * SubjectPublicKeyInfo ::= SEQUENCE {
1516 * algorithm AlgorithmIdentifier,
1517 * subjectPublicKey BIT STRING }
1519 * AlgorithmIdentifier ::= SEQUENCE {
1520 * algorithm OBJECT IDENTIFER,
1521 * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1523 * Name ::= SEQUENCE OF RelativeDistinguishedName
1525 * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
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}
1539 * DirectoryString ::= CHOICE {
1540 * teletexString TeletexString,
1541 * printableString PrintableString,
1542 * universalString UniversalString }
1544 * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1546 * Not yet implemented:
1547 * CertificateRevocationList ::= SIGNED SEQUENCE{
1548 * signature AlgorithmIdentifier,
1550 * lastUpdate UTCTime,
1551 * nextUpdate UTCTime,
1552 * revokedCertificates
1553 * SEQUENCE OF CRLEntry OPTIONAL}
1554 * CRLEntry ::= SEQUENCE{
1555 * userCertificate SerialNumber,
1556 * revocationDate UTCTime}
1559 typedef struct CertX509 {
1562 char* validity_start;
1571 /* Algorithm object-ids */
1574 ALG_md2WithRSAEncryption,
1575 ALG_md4WithRSAEncryption,
1576 ALG_md5WithRSAEncryption,
1578 ALG_sha1WithRSAEncryption,
1579 ALG_sha1WithRSAEncryptionOiw,
1581 ALG_sha256WithRSAEncryption,
1582 ALG_sha384WithRSAEncryption,
1583 ALG_sha512WithRSAEncryption,
1584 ALG_sha224WithRSAEncryption,
1596 typedef struct Ints15 {
1601 typedef struct DigestAlg {
1603 DigestState* (*fun)(uchar*,ulong,uchar*,DigestState*);
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 };
1614 /* maximum length of digest output of the digest algs above */
1616 MAXdlen = SHA2_512dlen,
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 };
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 };
1637 static Ints *alg_oid_tab[NUMALGS+1] = {
1638 (Ints*)&oid_rsaEncryption,
1639 (Ints*)&oid_md2WithRSAEncryption,
1640 (Ints*)&oid_md4WithRSAEncryption,
1641 (Ints*)&oid_md5WithRSAEncryption,
1643 (Ints*)&oid_sha1WithRSAEncryption,
1644 (Ints*)&oid_sha1WithRSAEncryptionOiw,
1646 (Ints*)&oid_sha256WithRSAEncryption,
1647 (Ints*)&oid_sha384WithRSAEncryption,
1648 (Ints*)&oid_sha512WithRSAEncryption,
1649 (Ints*)&oid_sha224WithRSAEncryption,
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,
1669 freecert(CertX509* c)
1674 free(c->validity_start);
1675 free(c->validity_end);
1677 freebytes(c->publickey);
1678 freebytes(c->signature);
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
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).
1701 enum { MAXPARTS = 100 };
1702 char* parts[MAXPARTS];
1713 if(!is_set(es, &esetl))
1715 while(esetl != nil) {
1717 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1719 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1722 plen += strlen(s) + 2; /* room for ", " after */
1728 ans = (char*)emalloc(plen);
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.
1754 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1756 return oid_lookup(oid, alg_oid_tab);
1760 decode_cert(Bytes* a)
1775 Elist* elcert = nil;
1776 Elist* elcertinfo = nil;
1777 Elist* elvalidity = nil;
1778 Elist* elpubkey = nil;
1783 if(decode(a->data, a->len, &ecert) != ASN_OK)
1786 c = (CertX509*)emalloc(sizeof(CertX509));
1789 c->validity_start = nil;
1790 c->validity_end = nil;
1792 c->publickey_alg = -1;
1794 c->signature_alg = -1;
1798 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1800 ecertinfo = &elcert->hd;
1803 c->signature_alg = parse_alg(esigalg);
1807 /* Certificate Info */
1808 if(!is_seq(ecertinfo, &elcertinfo))
1810 n = elistlen(elcertinfo);
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) {
1823 if(parse_alg(&el->hd) != c->signature_alg)
1828 evalidity = &el->hd;
1833 if(!is_int(eserial, &c->serial)) {
1834 if(!is_bigint(eserial, &b))
1836 c->serial = -1; /* else we have to change cert struct */
1838 c->issuer = parse_name(eissuer);
1839 if(c->issuer == nil)
1842 if(!is_seq(evalidity, &elvalidity))
1844 if(elistlen(elvalidity) != 2)
1846 e = &elvalidity->hd;
1847 if(!is_time(e, &c->validity_start))
1849 e->val.u.stringval = nil; /* string ownership transfer */
1850 e = &elvalidity->tl->hd;
1851 if(!is_time(e, &c->validity_end))
1853 e->val.u.stringval = nil; /* string ownership transfer */
1855 /* resume CertificateInfo */
1856 c->subject = parse_name(esubj);
1857 if(c->subject == nil)
1860 /* SubjectPublicKeyInfo */
1861 if(!is_seq(epubkey, &elpubkey))
1863 if(elistlen(elpubkey) != 2)
1866 c->publickey_alg = parse_alg(&elpubkey->hd);
1867 if(c->publickey_alg < 0)
1869 if(!is_bitstring(&elpubkey->tl->hd, &bits))
1871 if(bits->unusedbits != 0)
1873 c->publickey = makebytes(bits->data, bits->len);
1875 /*resume Certificate */
1876 if(c->signature_alg < 0)
1878 if(!is_bitstring(esig, &bits))
1880 c->signature = makebytes(bits->data, bits->len);
1884 freevalfields(&ecert.val); /* recurses through lists, too */
1893 * RSAPublickKey :: SEQUENCE {
1895 * publicExponent INTEGER
1899 decode_rsapubkey(Bytes* a)
1907 key = rsapuballoc();
1908 if(decode(a->data, a->len, &e) != ASN_OK)
1910 if(!is_seq(&e, &el) || elistlen(el) != 2)
1915 key->n = mp = asn1mpint(&el->hd);
1920 key->ek = mp = asn1mpint(&el->hd);
1933 * RSAPrivateKey ::= SEQUENCE {
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 }
1945 decode_rsaprivkey(Bytes* a)
1953 key = rsaprivalloc();
1954 if(decode(a->data, a->len, &e) != ASN_OK)
1956 if(!is_seq(&e, &el) || elistlen(el) != 9)
1958 if(!is_int(&el->hd, &version) || version != 0)
1962 key->pub.n = mp = asn1mpint(&el->hd);
1967 key->pub.ek = mp = asn1mpint(&el->hd);
1972 key->dk = mp = asn1mpint(&el->hd);
1977 key->q = mp = asn1mpint(&el->hd);
1982 key->p = mp = asn1mpint(&el->hd);
1987 key->kq = mp = asn1mpint(&el->hd);
1992 key->kp = mp = asn1mpint(&el->hd);
1997 key->c2 = mp = asn1mpint(&el->hd);
2008 * DSAPrivateKey ::= SEQUENCE{
2012 * g INTEGER, -- alpha
2013 * pub_key INTEGER, -- key
2014 * priv_key INTEGER, -- secret
2018 decode_dsaprivkey(Bytes* a)
2026 key = dsaprivalloc();
2027 if(decode(a->data, a->len, &e) != ASN_OK)
2029 if(!is_seq(&e, &el) || elistlen(el) != 6)
2032 if(!is_int(&el->hd, &version) || version != 0)
2034 fprint(2, "version %d\n", version);
2039 key->pub.p = mp = asn1mpint(&el->hd);
2044 key->pub.q = mp = asn1mpint(&el->hd);
2049 key->pub.alpha = mp = asn1mpint(&el->hd);
2054 key->pub.key = mp = asn1mpint(&el->hd);
2059 key->secret = mp = asn1mpint(&el->hd);
2077 return itomp(v, nil);
2078 if(is_bigint(e, &b)) {
2079 mp = betomp(b->data, b->len, nil);
2087 pkcs1padbuf(uchar *buf, int len, mpint *modulus)
2089 int n = (mpsignif(modulus)+7)/8;
2095 p = (uchar*)emalloc(n);
2098 for(i = 2; i < pm1; i++)
2101 memcpy(&p[pm1+1], buf, len);
2102 mp = betomp(p, n, nil);
2108 pkcs1pad(Bytes *b, mpint *modulus)
2110 return pkcs1padbuf(b->data, b->len, modulus);
2114 asn1toRSApriv(uchar *kd, int kn)
2119 b = makebytes(kd, kn);
2120 key = decode_rsaprivkey(b);
2126 asn1toDSApriv(uchar *kd, int kn)
2131 b = makebytes(kd, kn);
2132 key = decode_dsaprivkey(b);
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.
2143 digest_certinfo(Bytes *cert, DigestAlg *da, uchar *digest)
2145 uchar *info, *p, *pend;
2147 int isconstr, length;
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 ||
2160 if(ber_decode(&p, pend, &elem) != ASN_OK)
2162 freevalfields(&elem.val);
2163 if(elem.tag.num != SEQUENCE)
2166 (*da->fun)(info, infolen, digest, nil);
2171 pkcs1decryptsignature(uchar *sig, int siglen, RSApub *pk, uchar **pbuf)
2179 /* one less than the byte length of the modulus */
2180 nlen = (mpsignif(pk->n)-1)/8;
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);
2189 if(buflen != nlen || buf[0] != 1)
2192 while(buflen > 0 && buf[0] == 0xff)
2194 if(buflen < 1 || buf[0] != 0)
2197 memmove(*pbuf, buf, buflen);
2206 verify_digestinfo(uchar *sig, int siglen, RSApub *pk, uchar *pdigest, int *psigalg)
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";
2223 *psigalg = parse_alg(&el->hd);
2225 err = "unknown signature algorithm";
2228 if(digest->len != digestalg[*psigalg]->len){
2229 err = "bad digest length";
2232 memmove(pdigest, digest->data, digest->len);
2235 freevalfields(&e.val);
2241 X509verifydigest(uchar *sig, int siglen, uchar *edigest, int edigestlen, RSApub *pk)
2243 uchar digest[MAXdlen];
2247 e = verify_digestinfo(sig, siglen, pk, digest, &sigalg);
2250 if(digestalg[sigalg]->len != edigestlen)
2251 return "bad digest length";
2252 if(memcmp(digest, edigest, edigestlen) != 0)
2253 return "digests did not match";
2258 X509verifydata(uchar *sig, int siglen, uchar *data, int datalen, RSApub *pk)
2260 uchar digest[MAXdlen], edigest[MAXdlen];
2264 e = verify_digestinfo(sig, siglen, pk, digest, &sigalg);
2267 (*digestalg[sigalg]->fun)(data, datalen, edigest, nil);
2268 if(memcmp(digest, edigest, digestalg[sigalg]->len) != 0)
2269 return "digests did not match";
2274 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2281 b = makebytes(cert, ncert);
2286 if(name != nil && c->subject != nil){
2287 e = strchr(c->subject, ',');
2289 *e = 0; /* take just CN part of Distinguished Name */
2290 strncpy(name, c->subject, nname);
2292 pk = decode_rsapubkey(c->publickey);
2298 X509verify(uchar *cert, int ncert, RSApub *pk)
2304 uchar digest[MAXdlen];
2306 b = makebytes(cert, ncert);
2310 return "cannot decode cert";
2312 digestlen = digest_certinfo(b, digestalg[c->signature_alg], digest);
2316 return "cannot decode certinfo";
2318 e = X509verifydigest(c->signature->data, c->signature->len, digest, digestlen, pk);
2323 /* ------- Elem constructors ---------- */
2329 e.tag.class = Universal;
2330 e.tag.num = NULLTAG;
2340 e.tag.class = Universal;
2341 e.tag.num = INTEGER;
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);
2368 e.tag.class = Universal;
2369 e.tag.num = IA5String;
2370 e.val.tag = VString;
2371 e.val.u.stringval = estrdup(s);
2376 mkoctet(uchar *buf, int buflen)
2380 e.tag.class = Universal;
2381 e.tag.num = OCTET_STRING;
2382 e.val.tag = VOctets;
2383 e.val.u.octetsval = makebytes(buf, buflen);
2388 mkbits(uchar *buf, int buflen)
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);
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);
2420 e.tag.class = Universal;
2421 e.tag.num = OBJECT_ID;
2423 e.val.u.objidval = makeints(oid->data, oid->len);
2432 e.tag.class = Universal;
2433 e.tag.num = SEQUENCE;
2435 e.val.u.seqval = el;
2444 e.tag.class = Universal;
2447 e.val.u.setval = el;
2454 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2457 typedef struct 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="},
2473 mkname(Ints7pref *oid, char *subj)
2475 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2482 char *f[20], *prefix, *d2 = estrdup(dn);
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);
2500 X509encodesignature_sha256(uchar digest[SHA2_256dlen], uchar *buf, int len)
2507 mkel(mkalg(ALG_sha256),
2508 mkel(mkoctet(digest, SHA2_256dlen),
2510 err = encode(sig, &sigbytes);
2511 freevalfields(&sig.val);
2514 if(len < sigbytes->len){
2515 freebytes(sigbytes);
2518 len = sigbytes->len;
2519 memmove(buf, sigbytes->data, len);
2520 freebytes(sigbytes);
2526 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2528 int serial = 0, sigalg = ALG_sha256WithRSAEncryption;
2530 RSApub *pk = rsaprivtopub(priv);
2531 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2534 uchar digest[MAXdlen], *buf;
2538 e = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2539 if(encode(e, &pkbytes) != ASN_OK)
2541 freevalfields(&e.val);
2547 mkel(mkutc(valid[0]),
2548 mkel(mkutc(valid[1]),
2552 mkel(mkalg(ALG_rsaEncryption),
2553 mkel(mkbits(pkbytes->data, pkbytes->len),
2557 if(encode(e, &certinfobytes) != ASN_OK)
2559 da = digestalg[sigalg];
2560 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2561 freebytes(certinfobytes);
2564 mkel(mkalg(da->alg),
2565 mkel(mkoctet(digest, da->len),
2567 if(encode(e, &sigbytes) != ASN_OK){
2568 freevalfields(&certinfo.val);
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);
2580 mkel(mkbits(buf, buflen),
2583 if(encode(e, &certbytes) != ASN_OK)
2586 *certlen = certbytes->len;
2587 cert = malloc(certbytes->len);
2589 memmove(cert, certbytes->data, certbytes->len);
2590 freebytes(certbytes);
2592 freevalfields(&e.val);
2597 X509req(RSApriv *priv, char *subj, int *certlen)
2599 /* RFC 2314, PKCS #10 Certification Request Syntax */
2600 int version = 0, sigalg = ALG_sha256WithRSAEncryption;
2602 RSApub *pk = rsaprivtopub(priv);
2603 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2606 uchar digest[MAXdlen], *buf;
2610 e = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2611 if(encode(e, &pkbytes) != ASN_OK)
2613 freevalfields(&e.val);
2615 mkel(mkint(version),
2618 mkel(mkalg(ALG_rsaEncryption),
2619 mkel(mkbits(pkbytes->data, pkbytes->len),
2623 if(encode(e, &certinfobytes) != ASN_OK)
2625 da = digestalg[sigalg];
2626 (*da->fun)(certinfobytes->data, certinfobytes->len, digest, 0);
2627 freebytes(certinfobytes);
2630 mkel(mkalg(da->alg),
2631 mkel(mkoctet(digest, da->len),
2633 if(encode(e, &sigbytes) != ASN_OK){
2634 freevalfields(&certinfo.val);
2637 pkcs1 = pkcs1pad(sigbytes, pk->n);
2638 freebytes(sigbytes);
2639 rsadecrypt(priv, pkcs1, pkcs1);
2640 buflen = mptobe(pkcs1, nil, 0, &buf);
2645 mkel(mkbits(buf, buflen),
2648 if(encode(e, &certbytes) != ASN_OK)
2651 *certlen = certbytes->len;
2652 cert = malloc(certbytes->len);
2654 memmove(cert, certbytes->data, certbytes->len);
2655 freebytes(certbytes);
2657 freevalfields(&e.val);
2664 if(tag.class != Universal)
2665 return smprint("class%d,num%d", tag.class, 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";
2694 return smprint("Universal,num%d", tag.num);
2705 print("%s{", tagdump(e.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]);
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)
2726 case VSet: print("Set\n");
2727 for(el = v.u.setval; el!=nil; el = el->tl)
2735 asn1dump(uchar *der, int len)
2739 if(decode(der, len, &e) != ASN_OK){
2740 print("didn't parse\n");
2741 exits("didn't parse");
2747 X509dump(uchar *cert, int ncert)
2754 uchar digest[MAXdlen];
2756 print("begin X509dump\n");
2757 b = makebytes(cert, ncert);
2761 print("cannot decode cert\n");
2764 digestlen = digest_certinfo(b, digestalg[c->signature_alg], digest);
2768 print("cannot decode certinfo\n");
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);
2779 print("sigalg=%d digest=%.*H\n", c->signature_alg, digestlen, digest);
2780 e = X509verifydigest(c->signature->data, c->signature->len, digest, digestlen, pk);
2782 e = "nil (meaning ok)";
2783 print("self-signed X509verifydigest returns: %s\n", e);
2787 print("end X509dump\n");