6 typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
8 /* ANSI offsetof, backwards. */
9 #define OFFSETOF(a, b) offsetof(b, a)
11 /*=============================================================*/
12 /* general ASN1 declarations and parsing
14 * For now, this is used only for extracting the key from an
15 * X509 certificate, so the entire collection is hidden. But
16 * someday we should probably make the functions visible and
17 * give them their own man page.
19 typedef struct Elem Elem;
20 typedef struct Tag Tag;
21 typedef struct Value Value;
22 typedef struct Bytes Bytes;
23 typedef struct Ints Ints;
24 typedef struct Bits Bits;
25 typedef struct Elist Elist;
35 #define OCTET_STRING 4
38 #define ObjectDescriptor 7
42 #define EMBEDDED_PDV 11
43 #define SEQUENCE 16 /* also SEQUENCE OF */
44 #define SETOF 17 /* also SETOF OF */
45 #define NumericString 18
46 #define PrintableString 19
47 #define TeletexString 20
48 #define VideotexString 21
51 #define GeneralizedTime 24
52 #define GraphicString 25
53 #define VisibleString 26
54 #define GeneralString 27
55 #define UniversalString 28
69 int len; /* number of bytes */
70 int unusedbits; /* unused bits in last byte */
71 uchar data[1]; /* most-significant bit first */
79 enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
80 VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
82 int tag; /* VBool, etc. */
88 Bytes* realval; /* undecoded; hardly ever used */
95 } u; /* (Don't use anonymous unions, for ease of porting) */
108 /* decoding errors */
109 enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
110 ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
113 /* here are the functions to consider making extern someday */
114 static Bytes* newbytes(int len);
115 static Bytes* makebytes(uchar* buf, int len);
116 static void freebytes(Bytes* b);
117 static Bytes* catbytes(Bytes* b1, Bytes* b2);
118 static Ints* newints(int len);
119 static Ints* makeints(int* buf, int len);
120 static void freeints(Ints* b);
121 static Bits* newbits(int len);
122 static Bits* makebits(uchar* buf, int len, int unusedbits);
123 static void freebits(Bits* b);
124 static Elist* mkel(Elem e, Elist* tail);
125 static void freeelist(Elist* el);
126 static int elistlen(Elist* el);
127 static int is_seq(Elem* pe, Elist** pseq);
128 static int is_set(Elem* pe, Elist** pset);
129 static int is_int(Elem* pe, int* pint);
130 static int is_bigint(Elem* pe, Bytes** pbigint);
131 static int is_bitstring(Elem* pe, Bits** pbits);
132 static int is_octetstring(Elem* pe, Bytes** poctets);
133 static int is_oid(Elem* pe, Ints** poid);
134 static int is_string(Elem* pe, char** pstring);
135 static int is_time(Elem* pe, char** ptime);
136 static int decode(uchar* a, int alen, Elem* pelem);
137 static int decode_seq(uchar* a, int alen, Elist** pelist);
138 static int decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
139 static int encode(Elem e, Bytes** pbytes);
140 static int oid_lookup(Ints* o, Ints** tab);
141 static void freevalfields(Value* v);
142 static mpint *asn1mpint(Elem *e);
146 #define TAG_MASK 0x1F
147 #define CONSTR_MASK 0x20
148 #define CLASS_MASK 0xC0
149 #define MAXOBJIDLEN 20
151 static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
152 static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
153 static int length_decode(uchar** pp, uchar* pend, int* plength);
154 static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
155 static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
156 static int uint7_decode(uchar** pp, uchar* pend, int* pint);
157 static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
158 static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
159 static int enc(uchar** pp, Elem e, int lenonly);
160 static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
161 static void uint7_enc(uchar** pp, int num, int lenonly);
162 static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
172 exits("out of memory");
185 d = d0 = emalloc(strlen(s)+1);
193 * Decode a[0..len] as a BER encoding of an ASN1 type.
194 * The return value is one of ASN_OK, etc.
195 * Depending on the error, the returned elem may or may not
199 decode(uchar* a, int alen, Elem* pelem)
203 return ber_decode(&p, &a[alen], pelem);
207 * Like decode, but continue decoding after first element
211 decode_seq(uchar* a, int alen, Elist** pelist)
215 return seq_decode(&p, &a[alen], -1, 1, pelist);
219 * Decode the whole array as a BER encoding of an ASN1 value,
220 * (i.e., the part after the tag and length).
221 * Assume the value is encoded as universal tag "kind".
222 * The constr arg is 1 if the value is constructed, 0 if primitive.
223 * If there's an error, the return string will contain the error.
224 * Depending on the error, the returned value may or may not
228 decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
232 return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
236 * All of the following decoding routines take arguments:
239 * Where parsing is supposed to start at **pp, and when parsing
240 * is done, *pp is updated to point at next char to be parsed.
241 * The pend pointer is just past end of string; an error should
242 * be returned parsing hasn't finished by then.
244 * The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
245 * The remaining argument(s) are pointers to where parsed entity goes.
248 /* Decode an ASN1 'Elem' (tag, length, value) */
250 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
258 err = tag_decode(pp, pend, &tag, &isconstr);
260 err = length_decode(pp, pend, &length);
262 if(tag.class == Universal)
263 err = value_decode(pp, pend, length, tag.num, isconstr, &val);
265 err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
275 /* Decode a tag field */
277 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
287 ptag->class = v&CLASS_MASK;
294 err = uint7_decode(&p, pend, &v);
303 /* Decode a length field */
305 length_decode(uchar** pp, uchar* pend, int* plength)
318 err = int_decode(&p, pend, v&0x7F, 1, &num);
329 /* Decode a value field */
331 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
337 int subids[MAXOBJIDLEN];
345 if(length == -1) { /* "indefinite" length spec */
349 else if(p + length > pend)
356 /* marker for end of indefinite constructions */
370 pval->u.boolval = (*p++ != 0);
378 else if(length <= 4) {
379 err = int_decode(&p, pend, length, 0, &num);
382 pval->u.intval = num;
387 pval->u.bigintval = makebytes(p, length);
393 pval->tag = VBitString;
395 if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
396 pval->u.bitstringval = makebits(0, 0, 0);
400 /* TODO: recurse and concat results */
405 if(length == 1 && *p == 0) {
406 pval->u.bitstringval = makebits(0, 0, 0);
416 else if(length > 0x0FFFFFFF)
419 pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
427 case ObjectDescriptor:
428 err = octet_decode(&p, pend, length, isconstr, &va);
431 pval->u.octetsval = va;
452 while(p < pe && isubid < MAXOBJIDLEN) {
453 err = uint7_decode(&p, pend, &num);
457 subids[isubid++] = num / 40;
458 subids[isubid++] = num % 40;
461 subids[isubid++] = num;
468 pval->u.objidval = makeints(subids, isubid);
476 /* TODO: parse this internally */
481 pval->u.otherval = makebytes(p, length);
487 /* Let the application decode */
490 else if(p+length > pend)
494 pval->u.realval = makebytes(p, length);
500 err = seq_decode(&p, pend, length, isconstr, &vl);
508 err = seq_decode(&p, pend, length, isconstr, &vl);
516 case PrintableString:
521 case GeneralizedTime:
525 case UniversalString:
527 /* TODO: figure out when character set conversion is necessary */
528 err = octet_decode(&p, pend, length, isconstr, &va);
531 pval->u.stringval = (char*)emalloc(va->len+1);
532 memmove(pval->u.stringval, va->data, va->len);
533 pval->u.stringval[va->len] = 0;
543 pval->u.otherval = makebytes(p, length);
553 * Decode an int in format where count bytes are
554 * concatenated to form value.
555 * Although ASN1 allows any size integer, we return
556 * an error if the result doesn't fit in a 32-bit int.
557 * If unsgned is not set, make sure to propagate sign bit.
560 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
569 if(p+count <= pend) {
570 if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
573 if(!unsgned && count > 0 && count < 4 && (*p&0x80))
574 num = -1; // set all bits, initially
576 num = (num << 8)|(*p++);
587 * Decode an unsigned int in format where each
588 * byte except last has high bit set, and remaining
589 * seven bits of each byte are concatenated to form value.
590 * Although ASN1 allows any size integer, we return
591 * an error if the result doesn't fit in a 32 bit int.
594 uint7_decode(uchar** pp, uchar* pend, int* pint)
606 while(more && p < pend) {
624 * Decode an octet string, recursively if isconstr.
625 * We've already checked that length==-1 implies isconstr==1,
626 * and otherwise that specified length fits within (*pp..pend)
629 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
642 if(length >= 0 && !isconstr) {
643 ans = makebytes(p, length);
647 /* constructed, either definite or indefinite length */
650 if(length >= 0 && p >= pstart + length) {
651 if(p != pstart + length)
656 err = ber_decode(&p, pend, &elem);
659 switch(elem.val.tag) {
661 newans = catbytes(ans, elem.val.u.octetsval);
688 * Decode a sequence or set.
689 * We've already checked that length==-1 implies isconstr==1,
690 * and otherwise that specified length fits within (*p..pend)
693 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
710 /* constructed, either definite or indefinite length */
714 if(length >= 0 && p >= pstart + length) {
715 if(p != pstart + length)
720 err = ber_decode(&p, pend, &elem);
723 if(elem.val.tag == VEOC) {
731 lve = mkel(elem, lve);
734 /* reverse back to original order */
749 * Encode e by BER rules, putting answer in *pbytes.
750 * This is done by first calling enc with lenonly==1
751 * to get the length of the needed buffer,
752 * then allocating the buffer and using enc again to fill it up.
755 encode(Elem e, Bytes** pbytes)
765 ans = newbytes(p-&uc);
774 * The various enc functions take a pointer to a pointer
775 * into a buffer, and encode their entity starting there,
776 * updating the pointer afterwards.
777 * If lenonly is 1, only the pointer update is done,
778 * allowing enc to be called first to calculate the needed
780 * If lenonly is 0, it is assumed that the answer will fit.
784 enc(uchar** pp, Elem e, int lenonly)
796 err = val_enc(&p, e, &constr, 1);
802 v = tag.class|constr;
814 uint7_enc(&p, tag.num, lenonly);
823 int_enc(&p, vlen, 1, 1);
827 *p++ = (0x80 | ilen);
828 int_enc(&p, vlen, 1, 0);
834 val_enc(&p, e, &constr, 0);
842 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
861 if(cl != Universal) {
891 kind = UniversalString;
906 int_enc(&p, v, 1, lenonly);
915 int_enc(&p, v, 0, lenonly);
917 if(is_bigint(&e, &bb)) {
919 memmove(p, bb->data, bb->len);
928 if(is_bitstring(&e, &bits)) {
935 v = bits->unusedbits;
941 memmove(p+1, bits->data, bits->len);
952 case ObjectDescriptor:
959 bb = e.val.u.octetsval;
962 bb = e.val.u.realval;
965 bb = e.val.u.otherval;
970 memmove(p, bb->data, bb->len);
981 if(is_oid(&e, &oid)) {
982 for(k = 0; k < oid->len; k++) {
989 uint7_enc(&p, v, lenonly);
999 if(e.val.tag == VSeq)
1000 el = e.val.u.seqval;
1001 else if(e.val.tag == VSet)
1002 el = e.val.u.setval;
1006 *pconstr = CONSTR_MASK;
1007 for(; el != nil; el = el->tl) {
1008 err = enc(&p, el->hd, lenonly);
1016 case PrintableString:
1018 case VideotexString:
1021 case GeneralizedTime:
1025 case UniversalString:
1027 if(e.val.tag == VString) {
1028 s = e.val.u.stringval;
1048 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1049 * except last, only putting in bytes if !lenonly.
1052 uint7_enc(uchar** pp, int num, int lenonly)
1069 for(k = (n - 1)*7; k > 0; k -= 7)
1070 *p++= ((num >> k)|0x80);
1077 * Encode num as unsigned or signed integer,
1078 * only putting in bytes if !lenonly.
1079 * Encoding is length followed by bytes to concatenate.
1082 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1102 if(!unsgned && (prevv&0x80))
1107 for(k = (n - 1)*8; k >= 0; k -= 8)
1114 ints_eq(Ints* a, Ints* b)
1122 for(i = 0; i < alen; i++)
1123 if(a->data[i] != b->data[i])
1129 * Look up o in tab (which must have nil entry to terminate).
1130 * Return index of matching entry, or -1 if none.
1133 oid_lookup(Ints* o, Ints** tab)
1137 for(i = 0; tab[i] != nil; i++)
1138 if(ints_eq(o, tab[i]))
1144 * Return true if *pe is a SEQUENCE, and set *pseq to
1145 * the value of the sequence if so.
1148 is_seq(Elem* pe, Elist** pseq)
1150 if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1151 *pseq = pe->val.u.seqval;
1158 is_set(Elem* pe, Elist** pset)
1160 if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1161 *pset = pe->val.u.setval;
1168 is_int(Elem* pe, int* pint)
1170 if(pe->tag.class == Universal) {
1171 if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1172 *pint = pe->val.u.intval;
1175 else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1176 *pint = pe->val.u.boolval;
1184 * for convience, all VInt's are readable via this routine,
1185 * as well as all VBigInt's
1188 is_bigint(Elem* pe, Bytes** pbigint)
1192 if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
1193 if(pe->val.tag == VBigInt)
1194 *pbigint = pe->val.u.bigintval;
1195 else if(pe->val.tag == VInt){
1196 v = pe->val.u.intval;
1197 for(n = 1; n < 4; n++)
1198 if((1 << (8 * n)) > v)
1200 *pbigint = newbytes(n);
1201 for(i = 0; i < n; i++)
1202 (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1211 is_bitstring(Elem* pe, Bits** pbits)
1213 if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1214 *pbits = pe->val.u.bitstringval;
1221 is_octetstring(Elem* pe, Bytes** poctets)
1223 if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1224 *poctets = pe->val.u.octetsval;
1231 is_oid(Elem* pe, Ints** poid)
1233 if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1234 *poid = pe->val.u.objidval;
1241 is_string(Elem* pe, char** pstring)
1243 if(pe->tag.class == Universal) {
1244 switch(pe->tag.num) {
1246 case PrintableString:
1248 case VideotexString:
1253 case UniversalString:
1255 if(pe->val.tag == VString) {
1256 *pstring = pe->val.u.stringval;
1265 is_time(Elem* pe, char** ptime)
1267 if(pe->tag.class == Universal
1268 && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1269 && pe->val.tag == VString) {
1270 *ptime = pe->val.u.stringval;
1278 * malloc and return a new Bytes structure capable of
1279 * holding len bytes. (len >= 0)
1286 ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1292 * newbytes(len), with data initialized from buf
1295 makebytes(uchar* buf, int len)
1299 ans = newbytes(len);
1300 memmove(ans->data, buf, len);
1312 * Make a new Bytes, containing bytes of b1 followed by those of b2.
1313 * Either b1 or b2 or both can be nil.
1316 catbytes(Bytes* b1, Bytes* b2)
1325 ans = makebytes(b2->data, b2->len);
1327 else if(b2 == nil) {
1328 ans = makebytes(b1->data, b1->len);
1331 n = b1->len + b2->len;
1334 memmove(ans->data, b1->data, b1->len);
1335 memmove(ans->data+b1->len, b2->data, b2->len);
1340 /* len is number of ints */
1346 ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1352 makeints(int* buf, int len)
1358 memmove(ans->data, buf, len*sizeof(int));
1369 /* len is number of bytes */
1375 ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1377 ans->unusedbits = 0;
1382 makebits(uchar* buf, int len, int unusedbits)
1387 memmove(ans->data, buf, len);
1388 ans->unusedbits = unusedbits;
1400 mkel(Elem e, Elist* tail)
1404 el = (Elist*)emalloc(sizeof(Elist));
1421 /* Frees elist, but not fields inside values of constituent elems */
1423 freeelist(Elist* el)
1434 /* free any allocated structures inside v (recursively freeing Elists) */
1436 freevalfields(Value* v)
1444 freebytes(v->u.octetsval);
1447 freebytes(v->u.bigintval);
1450 freebytes(v->u.realval);
1453 freebytes(v->u.otherval);
1456 freebits(v->u.bitstringval);
1459 freeints(v->u.objidval);
1463 free(v->u.stringval);
1467 for(l = el; l != nil; l = l->tl)
1468 freevalfields(&l->hd.val);
1474 for(l = el; l != nil; l = l->tl)
1475 freevalfields(&l->hd.val);
1482 /* end of general ASN1 functions */
1488 /*=============================================================*/
1490 * Decode and parse an X.509 Certificate, defined by this ASN1:
1491 * Certificate ::= SEQUENCE {
1492 * certificateInfo CertificateInfo,
1493 * signatureAlgorithm AlgorithmIdentifier,
1494 * signature BIT STRING }
1496 * CertificateInfo ::= SEQUENCE {
1497 * version [0] INTEGER DEFAULT v1 (0),
1498 * serialNumber INTEGER,
1499 * signature AlgorithmIdentifier,
1501 * validity Validity,
1503 * subjectPublicKeyInfo SubjectPublicKeyInfo }
1504 * (version v2 has two more fields, optional unique identifiers for
1505 * issuer and subject; since we ignore these anyway, we won't parse them)
1507 * Validity ::= SEQUENCE {
1508 * notBefore UTCTime,
1509 * notAfter UTCTime }
1511 * SubjectPublicKeyInfo ::= SEQUENCE {
1512 * algorithm AlgorithmIdentifier,
1513 * subjectPublicKey BIT STRING }
1515 * AlgorithmIdentifier ::= SEQUENCE {
1516 * algorithm OBJECT IDENTIFER,
1517 * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
1519 * Name ::= SEQUENCE OF RelativeDistinguishedName
1521 * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
1523 * AttributeTypeAndValue ::= SEQUENCE {
1524 * type OBJECT IDENTIFER,
1525 * value DirectoryString }
1526 * (selected attributes have these Object Ids:
1527 * commonName {2 5 4 3}
1528 * countryName {2 5 4 6}
1529 * localityName {2 5 4 7}
1530 * stateOrProvinceName {2 5 4 8}
1531 * organizationName {2 5 4 10}
1532 * organizationalUnitName {2 5 4 11}
1535 * DirectoryString ::= CHOICE {
1536 * teletexString TeletexString,
1537 * printableString PrintableString,
1538 * universalString UniversalString }
1540 * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
1542 * Not yet implemented:
1543 * CertificateRevocationList ::= SIGNED SEQUENCE{
1544 * signature AlgorithmIdentifier,
1546 * lastUpdate UTCTime,
1547 * nextUpdate UTCTime,
1548 * revokedCertificates
1549 * SEQUENCE OF CRLEntry OPTIONAL}
1550 * CRLEntry ::= SEQUENCE{
1551 * userCertificate SerialNumber,
1552 * revocationDate UTCTime}
1555 typedef struct CertX509 {
1558 char* validity_start;
1567 /* Algorithm object-ids */
1570 ALG_md2WithRSAEncryption,
1571 ALG_md4WithRSAEncryption,
1572 ALG_md5WithRSAEncryption,
1573 ALG_sha1WithRSAEncryption,
1577 typedef struct Ints7 {
1581 static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1582 static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1583 static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1584 static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1585 static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1586 static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1587 static Ints *alg_oid_tab[NUMALGS+1] = {
1588 (Ints*)&oid_rsaEncryption,
1589 (Ints*)&oid_md2WithRSAEncryption,
1590 (Ints*)&oid_md4WithRSAEncryption,
1591 (Ints*)&oid_md5WithRSAEncryption,
1592 (Ints*)&oid_sha1WithRSAEncryption,
1596 static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, 0 };
1599 freecert(CertX509* c)
1602 if(c->issuer != nil)
1604 if(c->validity_start != nil)
1605 free(c->validity_start);
1606 if(c->validity_end != nil)
1607 free(c->validity_end);
1608 if(c->subject != nil)
1610 freebytes(c->publickey);
1611 freebytes(c->signature);
1615 * Parse the Name ASN1 type.
1616 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1617 * from most general to most specific. Each element of the path can be
1618 * one or more (but usually just one) attribute-value pair, such as
1620 * We'll just form a "postal-style" address string by concatenating the elements
1621 * from most specific to least specific, separated by commas.
1622 * Return name-as-string (which must be freed by caller).
1633 enum { MAXPARTS = 100 };
1634 char* parts[MAXPARTS];
1645 if(!is_set(es, &esetl))
1647 while(esetl != nil) {
1649 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1651 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1654 plen += strlen(s) + 2; /* room for ", " after */
1660 ans = (char*)emalloc(plen);
1675 * Parse an AlgorithmIdentifer ASN1 type.
1676 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1677 * or -1 if not found.
1678 * For now, ignore parameters, since none of our algorithms need them.
1686 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1688 return oid_lookup(oid, alg_oid_tab);
1692 decode_cert(Bytes* a)
1707 Elist* elcert = nil;
1708 Elist* elcertinfo = nil;
1709 Elist* elvalidity = nil;
1710 Elist* elpubkey = nil;
1715 if(decode(a->data, a->len, &ecert) != ASN_OK)
1718 c = (CertX509*)emalloc(sizeof(CertX509));
1721 c->validity_start = nil;
1722 c->validity_end = nil;
1724 c->publickey_alg = -1;
1726 c->signature_alg = -1;
1730 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1732 ecertinfo = &elcert->hd;
1735 c->signature_alg = parse_alg(esigalg);
1739 /* Certificate Info */
1740 if(!is_seq(ecertinfo, &elcertinfo))
1742 n = elistlen(elcertinfo);
1745 eserial =&elcertinfo->hd;
1746 el = elcertinfo->tl;
1747 /* check for optional version, marked by explicit context tag 0 */
1748 if(eserial->tag.class == Context && eserial->tag.num == 0) {
1755 if(parse_alg(&el->hd) != c->signature_alg)
1760 evalidity = &el->hd;
1765 if(!is_int(eserial, &c->serial)) {
1766 if(!is_bigint(eserial, &b))
1768 c->serial = -1; /* else we have to change cert struct */
1770 c->issuer = parse_name(eissuer);
1771 if(c->issuer == nil)
1774 if(!is_seq(evalidity, &elvalidity))
1776 if(elistlen(elvalidity) != 2)
1778 e = &elvalidity->hd;
1779 if(!is_time(e, &c->validity_start))
1781 e->val.u.stringval = nil; /* string ownership transfer */
1782 e = &elvalidity->tl->hd;
1783 if(!is_time(e, &c->validity_end))
1785 e->val.u.stringval = nil; /* string ownership transfer */
1787 /* resume CertificateInfo */
1788 c->subject = parse_name(esubj);
1789 if(c->subject == nil)
1792 /* SubjectPublicKeyInfo */
1793 if(!is_seq(epubkey, &elpubkey))
1795 if(elistlen(elpubkey) != 2)
1798 c->publickey_alg = parse_alg(&elpubkey->hd);
1799 if(c->publickey_alg < 0)
1801 if(!is_bitstring(&elpubkey->tl->hd, &bits))
1803 if(bits->unusedbits != 0)
1805 c->publickey = makebytes(bits->data, bits->len);
1807 /*resume Certificate */
1808 if(c->signature_alg < 0)
1810 if(!is_bitstring(esig, &bits))
1812 c->signature = makebytes(bits->data, bits->len);
1816 freevalfields(&ecert.val); /* recurses through lists, too */
1825 * RSAPublickKey :: SEQUENCE {
1827 * publicExponent INTEGER
1831 decode_rsapubkey(Bytes* a)
1838 key = rsapuballoc();
1839 if(decode(a->data, a->len, &e) != ASN_OK)
1841 if(!is_seq(&e, &el) || elistlen(el) != 2)
1844 key->n = mp = asn1mpint(&el->hd);
1849 key->ek = mp = asn1mpint(&el->hd);
1859 * RSAPrivateKey ::= SEQUENCE {
1861 * modulus INTEGER, -- n
1862 * publicExponent INTEGER, -- e
1863 * privateExponent INTEGER, -- d
1864 * prime1 INTEGER, -- p
1865 * prime2 INTEGER, -- q
1866 * exponent1 INTEGER, -- d mod (p-1)
1867 * exponent2 INTEGER, -- d mod (q-1)
1868 * coefficient INTEGER -- (inverse of q) mod p }
1871 decode_rsaprivkey(Bytes* a)
1879 key = rsaprivalloc();
1880 if(decode(a->data, a->len, &e) != ASN_OK)
1882 if(!is_seq(&e, &el) || elistlen(el) != 9)
1884 if(!is_int(&el->hd, &version) || version != 0)
1888 key->pub.n = mp = asn1mpint(&el->hd);
1893 key->pub.ek = mp = asn1mpint(&el->hd);
1898 key->dk = mp = asn1mpint(&el->hd);
1903 key->q = mp = asn1mpint(&el->hd);
1908 key->p = mp = asn1mpint(&el->hd);
1913 key->kq = mp = asn1mpint(&el->hd);
1918 key->kp = mp = asn1mpint(&el->hd);
1923 key->c2 = mp = asn1mpint(&el->hd);
1941 return itomp(v, nil);
1942 if(is_bigint(e, &b)) {
1943 mp = betomp(b->data, b->len, nil);
1951 pkcs1pad(Bytes *b, mpint *modulus)
1953 int n = (mpsignif(modulus)+7)/8;
1958 pm1 = n - 1 - b->len;
1959 p = (uchar*)emalloc(n);
1962 for(i = 2; i < pm1; i++)
1965 memcpy(&p[pm1+1], b->data, b->len);
1966 mp = betomp(p, n, nil);
1972 asn1toRSApriv(uchar *kd, int kn)
1977 b = makebytes(kd, kn);
1978 key = decode_rsaprivkey(b);
1984 * digest(CertificateInfo)
1985 * Our ASN.1 library doesn't return pointers into the original
1986 * data array, so we need to do a little hand decoding.
1989 digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
1991 uchar *info, *p, *pend;
1993 int isconstr, length;
1998 pend = cert->data + cert->len;
1999 if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2000 tag.class != Universal || tag.num != SEQUENCE ||
2001 length_decode(&p, pend, &length) != ASN_OK ||
2006 if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
2009 (*digestfun)(info, infolen, digest, nil);
2013 verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2018 uchar *pkcs1buf, *buf;
2023 /* one less than the byte length of the modulus */
2024 nlen = (mpsignif(pk->n)-1)/8;
2026 /* see 9.2.1 of rfc2437 */
2027 pkcs1 = betomp(signature->data, signature->len, nil);
2028 mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2030 buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2032 if(buflen != nlen || buf[0] != 1)
2033 return "expected 1";
2035 while(buf[0] == 0xff)
2038 return "expected 0";
2040 buflen -= buf-pkcs1buf;
2041 if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2042 !is_octetstring(&el->tl->hd, &digest))
2043 return "signature parse error";
2045 if(memcmp(digest->data, edigest, digest->len) == 0)
2047 return "digests did not match";
2051 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2058 b = makebytes(cert, ncert);
2063 if(name != nil && c->subject != nil){
2064 e = strchr(c->subject, ',');
2066 *e = 0; // take just CN part of Distinguished Name
2067 strncpy(name, c->subject, nname);
2069 pk = decode_rsapubkey(c->publickey);
2075 X509verify(uchar *cert, int ncert, RSApub *pk)
2080 uchar digest[SHA1dlen];
2083 b = makebytes(cert, ncert);
2086 digest_certinfo(b, digestalg[c->signature_alg], digest);
2089 return "cannot decode cert";
2090 e = verify_signature(c->signature, pk, digest, &sigalg);
2095 /* ------- Elem constructors ---------- */
2101 e.tag.class = Universal;
2102 e.tag.num = NULLTAG;
2112 e.tag.class = Universal;
2113 e.tag.num = INTEGER;
2126 e.tag.class = Universal;
2127 e.tag.num = INTEGER;
2128 e.val.tag = VBigInt;
2129 buflen = mptobe(p, nil, 0, &buf);
2130 e.val.u.bigintval = makebytes(buf, buflen);
2140 e.tag.class = Universal;
2141 e.tag.num = IA5String;
2142 e.val.tag = VString;
2143 e.val.u.stringval = estrdup(s);
2148 mkoctet(uchar *buf, int buflen)
2152 e.tag.class = Universal;
2153 e.tag.num = OCTET_STRING;
2154 e.val.tag = VOctets;
2155 e.val.u.octetsval = makebytes(buf, buflen);
2160 mkbits(uchar *buf, int buflen)
2164 e.tag.class = Universal;
2165 e.tag.num = BIT_STRING;
2166 e.val.tag = VBitString;
2167 e.val.u.bitstringval = makebits(buf, buflen, 0);
2178 e.tag.class = Universal;
2179 e.tag.num = UTCTime;
2180 e.val.tag = VString;
2181 snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2182 tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2183 e.val.u.stringval = estrdup(utc);
2192 e.tag.class = Universal;
2193 e.tag.num = OBJECT_ID;
2195 e.val.u.objidval = makeints(oid->data, oid->len);
2204 e.tag.class = Universal;
2205 e.tag.num = SEQUENCE;
2207 e.val.u.seqval = el;
2216 e.tag.class = Universal;
2219 e.val.u.setval = el;
2226 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2229 typedef struct Ints7pref {
2234 Ints7pref DN_oid[] = {
2235 {4, 2, 5, 4, 6, 0, 0, 0, "C="},
2236 {4, 2, 5, 4, 8, 0, 0, 0, "ST="},
2237 {4, 2, 5, 4, 7, 0, 0, 0, "L="},
2238 {4, 2, 5, 4, 10, 0, 0, 0, "O="},
2239 {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2240 {4, 2, 5, 4, 3, 0, 0, 0, "CN="},
2241 {7, 1,2,840,113549,1,9,1, "E="},
2245 mkname(Ints7pref *oid, char *subj)
2247 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2254 char *f[20], *prefix, *d2 = estrdup(dn);
2257 nf = tokenize(d2, f, nelem(f));
2258 for(i=nf-1; i>=0; i--){
2259 for(j=0; j<nelem(DN_oid); j++){
2260 prefix = DN_oid[j].prefix;
2261 if(strncmp(f[i],prefix,strlen(prefix))==0){
2262 el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2273 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2277 RSApub *pk = rsaprivtopub(priv);
2278 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2279 Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2280 uchar digest[MD5dlen], *buf;
2284 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2285 issuer = mkDN(subj);
2286 subject = mkDN(subj);
2287 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2288 if(encode(pubkey, &pkbytes) != ASN_OK)
2290 freevalfields(&pubkey.val);
2292 mkel(mkalg(ALG_rsaEncryption),
2293 mkel(mkbits(pkbytes->data, pkbytes->len),
2297 mkel(mkutc(valid[0]),
2298 mkel(mkutc(valid[1]),
2302 mkel(mkalg(ALG_md5WithRSAEncryption),
2308 if(encode(certinfo, &certinfobytes) != ASN_OK)
2310 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2311 freebytes(certinfobytes);
2313 mkel(mkalg(ALG_md5),
2314 mkel(mkoctet(digest, MD5dlen),
2316 if(encode(sig, &sigbytes) != ASN_OK)
2318 pkcs1 = pkcs1pad(sigbytes, pk->n);
2319 freebytes(sigbytes);
2320 rsadecrypt(priv, pkcs1, pkcs1);
2321 buflen = mptobe(pkcs1, nil, 0, &buf);
2325 mkel(mkalg(ALG_md5WithRSAEncryption),
2326 mkel(mkbits(buf, buflen),
2329 if(encode(e, &certbytes) != ASN_OK)
2332 *certlen = certbytes->len;
2333 cert = certbytes->data;
2335 freevalfields(&e.val);
2340 X509req(RSApriv *priv, char *subj, int *certlen)
2342 /* RFC 2314, PKCS #10 Certification Request Syntax */
2345 RSApub *pk = rsaprivtopub(priv);
2346 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2347 Elem e, certinfo, subject, pubkey, sig;
2348 uchar digest[MD5dlen], *buf;
2352 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2353 subject = mkDN(subj);
2354 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2355 if(encode(pubkey, &pkbytes) != ASN_OK)
2357 freevalfields(&pubkey.val);
2359 mkel(mkalg(ALG_rsaEncryption),
2360 mkel(mkbits(pkbytes->data, pkbytes->len),
2364 mkel(mkint(version),
2368 if(encode(certinfo, &certinfobytes) != ASN_OK)
2370 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2371 freebytes(certinfobytes);
2373 mkel(mkalg(ALG_md5),
2374 mkel(mkoctet(digest, MD5dlen),
2376 if(encode(sig, &sigbytes) != ASN_OK)
2378 pkcs1 = pkcs1pad(sigbytes, pk->n);
2379 freebytes(sigbytes);
2380 rsadecrypt(priv, pkcs1, pkcs1);
2381 buflen = mptobe(pkcs1, nil, 0, &buf);
2385 mkel(mkalg(ALG_md5),
2386 mkel(mkbits(buf, buflen),
2389 if(encode(e, &certbytes) != ASN_OK)
2392 *certlen = certbytes->len;
2393 cert = certbytes->data;
2395 freevalfields(&e.val);
2402 if(tag.class != Universal)
2403 return smprint("class%d,num%d", tag.class, tag.num);
2405 case BOOLEAN: return "BOOLEAN"; break;
2406 case INTEGER: return "INTEGER"; break;
2407 case BIT_STRING: return "BIT STRING"; break;
2408 case OCTET_STRING: return "OCTET STRING"; break;
2409 case NULLTAG: return "NULLTAG"; break;
2410 case OBJECT_ID: return "OID"; break;
2411 case ObjectDescriptor: return "OBJECT_DES"; break;
2412 case EXTERNAL: return "EXTERNAL"; break;
2413 case REAL: return "REAL"; break;
2414 case ENUMERATED: return "ENUMERATED"; break;
2415 case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
2416 case SEQUENCE: return "SEQUENCE"; break;
2417 case SETOF: return "SETOF"; break;
2418 case NumericString: return "NumericString"; break;
2419 case PrintableString: return "PrintableString"; break;
2420 case TeletexString: return "TeletexString"; break;
2421 case VideotexString: return "VideotexString"; break;
2422 case IA5String: return "IA5String"; break;
2423 case UTCTime: return "UTCTime"; break;
2424 case GeneralizedTime: return "GeneralizedTime"; break;
2425 case GraphicString: return "GraphicString"; break;
2426 case VisibleString: return "VisibleString"; break;
2427 case GeneralString: return "GeneralString"; break;
2428 case UniversalString: return "UniversalString"; break;
2429 case BMPString: return "BMPString"; break;
2431 return smprint("Universal,num%d", tag.num);
2442 print("%s{", tagdump(e.tag));
2445 case VBool: print("Bool %d",v.u.boolval); break;
2446 case VInt: print("Int %d",v.u.intval); break;
2447 case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2448 case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2449 case VReal: print("Real..."); break;
2450 case VOther: print("Other..."); break;
2451 case VBitString: print("BitString..."); break;
2452 case VNull: print("Null"); break;
2453 case VEOC: print("EOC..."); break;
2454 case VObjId: print("ObjId");
2455 for(i = 0; i<v.u.objidval->len; i++)
2456 print(" %d", v.u.objidval->data[i]);
2458 case VString: print("String \"%s\"",v.u.stringval); break;
2459 case VSeq: print("Seq\n");
2460 for(el = v.u.seqval; el!=nil; el = el->tl)
2463 case VSet: print("Set\n");
2464 for(el = v.u.setval; el!=nil; el = el->tl)
2472 asn1dump(uchar *der, int len)
2476 if(decode(der, len, &e) != ASN_OK){
2477 print("didn't parse\n");
2478 exits("didn't parse");
2484 X509dump(uchar *cert, int ncert)
2490 uchar digest[SHA1dlen];
2493 print("begin X509dump\n");
2494 b = makebytes(cert, ncert);
2497 digest_certinfo(b, digestalg[c->signature_alg], digest);
2500 print("cannot decode cert");
2504 print("serial %d\n", c->serial);
2505 print("issuer %s\n", c->issuer);
2506 print("validity %s %s\n", c->validity_start, c->validity_end);
2507 print("subject %s\n", c->subject);
2508 pk = decode_rsapubkey(c->publickey);
2509 print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2511 print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2512 e = verify_signature(c->signature, pk, digest, &sigalg);
2514 e = "nil (meaning ok)";
2519 print("self-signed verify_signature returns: %s\n", e);
2523 print("end X509dump\n");