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);
138 static int decode_seq(uchar* a, int alen, Elist** pelist);
139 static int decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
141 static int encode(Elem e, Bytes** pbytes);
142 static int oid_lookup(Ints* o, Ints** tab);
143 static void freevalfields(Value* v);
144 static mpint *asn1mpint(Elem *e);
148 #define TAG_MASK 0x1F
149 #define CONSTR_MASK 0x20
150 #define CLASS_MASK 0xC0
151 #define MAXOBJIDLEN 20
153 static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
154 static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
155 static int length_decode(uchar** pp, uchar* pend, int* plength);
156 static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
157 static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
158 static int uint7_decode(uchar** pp, uchar* pend, int* pint);
159 static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
160 static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
161 static int enc(uchar** pp, Elem e, int lenonly);
162 static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
163 static void uint7_enc(uchar** pp, int num, int lenonly);
164 static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
174 exits("out of memory");
187 d = d0 = emalloc(strlen(s)+1);
195 * Decode a[0..len] as a BER encoding of an ASN1 type.
196 * The return value is one of ASN_OK, etc.
197 * Depending on the error, the returned elem may or may not
201 decode(uchar* a, int alen, Elem* pelem)
205 return ber_decode(&p, &a[alen], pelem);
209 * Like decode, but continue decoding after first element
213 decode_seq(uchar* a, int alen, Elist** pelist)
217 return seq_decode(&p, &a[alen], -1, 1, pelist);
222 * Decode the whole array as a BER encoding of an ASN1 value,
223 * (i.e., the part after the tag and length).
224 * Assume the value is encoded as universal tag "kind".
225 * The constr arg is 1 if the value is constructed, 0 if primitive.
226 * If there's an error, the return string will contain the error.
227 * Depending on the error, the returned value may or may not
231 decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
235 return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
240 * All of the following decoding routines take arguments:
243 * Where parsing is supposed to start at **pp, and when parsing
244 * is done, *pp is updated to point at next char to be parsed.
245 * The pend pointer is just past end of string; an error should
246 * be returned parsing hasn't finished by then.
248 * The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
249 * The remaining argument(s) are pointers to where parsed entity goes.
252 /* Decode an ASN1 'Elem' (tag, length, value) */
254 ber_decode(uchar** pp, uchar* pend, Elem* pelem)
262 err = tag_decode(pp, pend, &tag, &isconstr);
264 err = length_decode(pp, pend, &length);
266 if(tag.class == Universal)
267 err = value_decode(pp, pend, length, tag.num, isconstr, &val);
269 err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
279 /* Decode a tag field */
281 tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
291 ptag->class = v&CLASS_MASK;
298 err = uint7_decode(&p, pend, &v);
307 /* Decode a length field */
309 length_decode(uchar** pp, uchar* pend, int* plength)
322 err = int_decode(&p, pend, v&0x7F, 1, &num);
333 /* Decode a value field */
335 value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
341 int subids[MAXOBJIDLEN];
349 if(length == -1) { /* "indefinite" length spec */
353 else if(p + length > pend)
360 /* marker for end of indefinite constructions */
374 pval->u.boolval = (*p++ != 0);
382 else if(length <= 4) {
383 err = int_decode(&p, pend, length, 0, &num);
386 pval->u.intval = num;
391 pval->u.bigintval = makebytes(p, length);
397 pval->tag = VBitString;
399 if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
400 pval->u.bitstringval = makebits(0, 0, 0);
404 /* TODO: recurse and concat results */
409 if(length == 1 && *p == 0) {
410 pval->u.bitstringval = makebits(0, 0, 0);
420 else if(length > 0x0FFFFFFF)
423 pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
431 case ObjectDescriptor:
432 err = octet_decode(&p, pend, length, isconstr, &va);
435 pval->u.octetsval = va;
456 while(p < pe && isubid < MAXOBJIDLEN) {
457 err = uint7_decode(&p, pend, &num);
461 subids[isubid++] = num / 40;
462 subids[isubid++] = num % 40;
465 subids[isubid++] = num;
472 pval->u.objidval = makeints(subids, isubid);
480 /* TODO: parse this internally */
485 pval->u.otherval = makebytes(p, length);
491 /* Let the application decode */
494 else if(p+length > pend)
498 pval->u.realval = makebytes(p, length);
504 err = seq_decode(&p, pend, length, isconstr, &vl);
512 err = seq_decode(&p, pend, length, isconstr, &vl);
520 case PrintableString:
525 case GeneralizedTime:
529 case UniversalString:
531 /* TODO: figure out when character set conversion is necessary */
532 err = octet_decode(&p, pend, length, isconstr, &va);
535 pval->u.stringval = (char*)emalloc(va->len+1);
536 memmove(pval->u.stringval, va->data, va->len);
537 pval->u.stringval[va->len] = 0;
547 pval->u.otherval = makebytes(p, length);
557 * Decode an int in format where count bytes are
558 * concatenated to form value.
559 * Although ASN1 allows any size integer, we return
560 * an error if the result doesn't fit in a 32-bit int.
561 * If unsgned is not set, make sure to propagate sign bit.
564 int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
573 if(p+count <= pend) {
574 if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
577 if(!unsgned && count > 0 && count < 4 && (*p&0x80))
578 num = -1; // set all bits, initially
580 num = (num << 8)|(*p++);
591 * Decode an unsigned int in format where each
592 * byte except last has high bit set, and remaining
593 * seven bits of each byte are concatenated to form value.
594 * Although ASN1 allows any size integer, we return
595 * an error if the result doesn't fit in a 32 bit int.
598 uint7_decode(uchar** pp, uchar* pend, int* pint)
610 while(more && p < pend) {
628 * Decode an octet string, recursively if isconstr.
629 * We've already checked that length==-1 implies isconstr==1,
630 * and otherwise that specified length fits within (*pp..pend)
633 octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
646 if(length >= 0 && !isconstr) {
647 ans = makebytes(p, length);
651 /* constructed, either definite or indefinite length */
654 if(length >= 0 && p >= pstart + length) {
655 if(p != pstart + length)
660 err = ber_decode(&p, pend, &elem);
663 switch(elem.val.tag) {
665 newans = catbytes(ans, elem.val.u.octetsval);
692 * Decode a sequence or set.
693 * We've already checked that length==-1 implies isconstr==1,
694 * and otherwise that specified length fits within (*p..pend)
697 seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
714 /* constructed, either definite or indefinite length */
718 if(length >= 0 && p >= pstart + length) {
719 if(p != pstart + length)
724 err = ber_decode(&p, pend, &elem);
727 if(elem.val.tag == VEOC) {
735 lve = mkel(elem, lve);
738 /* reverse back to original order */
753 * Encode e by BER rules, putting answer in *pbytes.
754 * This is done by first calling enc with lenonly==1
755 * to get the length of the needed buffer,
756 * then allocating the buffer and using enc again to fill it up.
759 encode(Elem e, Bytes** pbytes)
769 ans = newbytes(p-&uc);
778 * The various enc functions take a pointer to a pointer
779 * into a buffer, and encode their entity starting there,
780 * updating the pointer afterwards.
781 * If lenonly is 1, only the pointer update is done,
782 * allowing enc to be called first to calculate the needed
784 * If lenonly is 0, it is assumed that the answer will fit.
788 enc(uchar** pp, Elem e, int lenonly)
800 err = val_enc(&p, e, &constr, 1);
806 v = tag.class|constr;
818 uint7_enc(&p, tag.num, lenonly);
827 int_enc(&p, vlen, 1, 1);
831 *p++ = (0x80 | ilen);
832 int_enc(&p, vlen, 1, 0);
838 val_enc(&p, e, &constr, 0);
846 val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
865 if(cl != Universal) {
895 kind = UniversalString;
910 int_enc(&p, v, 1, lenonly);
919 int_enc(&p, v, 0, lenonly);
921 if(is_bigint(&e, &bb)) {
923 memmove(p, bb->data, bb->len);
932 if(is_bitstring(&e, &bits)) {
939 v = bits->unusedbits;
945 memmove(p+1, bits->data, bits->len);
956 case ObjectDescriptor:
963 bb = e.val.u.octetsval;
966 bb = e.val.u.realval;
969 bb = e.val.u.otherval;
974 memmove(p, bb->data, bb->len);
985 if(is_oid(&e, &oid)) {
986 for(k = 0; k < oid->len; k++) {
993 uint7_enc(&p, v, lenonly);
1003 if(e.val.tag == VSeq)
1004 el = e.val.u.seqval;
1005 else if(e.val.tag == VSet)
1006 el = e.val.u.setval;
1010 *pconstr = CONSTR_MASK;
1011 for(; el != nil; el = el->tl) {
1012 err = enc(&p, el->hd, lenonly);
1020 case PrintableString:
1022 case VideotexString:
1025 case GeneralizedTime:
1029 case UniversalString:
1031 if(e.val.tag == VString) {
1032 s = e.val.u.stringval;
1052 * Encode num as unsigned 7 bit values with top bit 1 on all bytes
1053 * except last, only putting in bytes if !lenonly.
1056 uint7_enc(uchar** pp, int num, int lenonly)
1073 for(k = (n - 1)*7; k > 0; k -= 7)
1074 *p++= ((num >> k)|0x80);
1081 * Encode num as unsigned or signed integer,
1082 * only putting in bytes if !lenonly.
1083 * Encoding is length followed by bytes to concatenate.
1086 int_enc(uchar** pp, int num, int unsgned, int lenonly)
1106 if(!unsgned && (prevv&0x80))
1111 for(k = (n - 1)*8; k >= 0; k -= 8)
1118 ints_eq(Ints* a, Ints* b)
1126 for(i = 0; i < alen; i++)
1127 if(a->data[i] != b->data[i])
1133 * Look up o in tab (which must have nil entry to terminate).
1134 * Return index of matching entry, or -1 if none.
1137 oid_lookup(Ints* o, Ints** tab)
1141 for(i = 0; tab[i] != nil; i++)
1142 if(ints_eq(o, tab[i]))
1148 * Return true if *pe is a SEQUENCE, and set *pseq to
1149 * the value of the sequence if so.
1152 is_seq(Elem* pe, Elist** pseq)
1154 if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
1155 *pseq = pe->val.u.seqval;
1162 is_set(Elem* pe, Elist** pset)
1164 if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
1165 *pset = pe->val.u.setval;
1172 is_int(Elem* pe, int* pint)
1174 if(pe->tag.class == Universal) {
1175 if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
1176 *pint = pe->val.u.intval;
1179 else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
1180 *pint = pe->val.u.boolval;
1188 * for convience, all VInt's are readable via this routine,
1189 * as well as all VBigInt's
1192 is_bigint(Elem* pe, Bytes** pbigint)
1196 if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
1197 if(pe->val.tag == VBigInt)
1198 *pbigint = pe->val.u.bigintval;
1199 else if(pe->val.tag == VInt){
1200 v = pe->val.u.intval;
1201 for(n = 1; n < 4; n++)
1202 if((1 << (8 * n)) > v)
1204 *pbigint = newbytes(n);
1205 for(i = 0; i < n; i++)
1206 (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
1215 is_bitstring(Elem* pe, Bits** pbits)
1217 if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
1218 *pbits = pe->val.u.bitstringval;
1225 is_octetstring(Elem* pe, Bytes** poctets)
1227 if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
1228 *poctets = pe->val.u.octetsval;
1235 is_oid(Elem* pe, Ints** poid)
1237 if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
1238 *poid = pe->val.u.objidval;
1245 is_string(Elem* pe, char** pstring)
1247 if(pe->tag.class == Universal) {
1248 switch(pe->tag.num) {
1250 case PrintableString:
1252 case VideotexString:
1257 case UniversalString:
1259 if(pe->val.tag == VString) {
1260 *pstring = pe->val.u.stringval;
1269 is_time(Elem* pe, char** ptime)
1271 if(pe->tag.class == Universal
1272 && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
1273 && pe->val.tag == VString) {
1274 *ptime = pe->val.u.stringval;
1282 * malloc and return a new Bytes structure capable of
1283 * holding len bytes. (len >= 0)
1290 ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
1296 * newbytes(len), with data initialized from buf
1299 makebytes(uchar* buf, int len)
1303 ans = newbytes(len);
1304 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 ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
1356 makeints(int* buf, int len)
1362 memmove(ans->data, buf, len*sizeof(int));
1373 /* len is number of bytes */
1379 ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
1381 ans->unusedbits = 0;
1386 makebits(uchar* buf, int len, int unusedbits)
1391 memmove(ans->data, buf, len);
1392 ans->unusedbits = unusedbits;
1404 mkel(Elem e, Elist* tail)
1408 el = (Elist*)emalloc(sizeof(Elist));
1425 /* Frees elist, but not fields inside values of constituent elems */
1427 freeelist(Elist* el)
1438 /* free any allocated structures inside v (recursively freeing Elists) */
1440 freevalfields(Value* v)
1448 freebytes(v->u.octetsval);
1451 freebytes(v->u.bigintval);
1454 freebytes(v->u.realval);
1457 freebytes(v->u.otherval);
1460 freebits(v->u.bitstringval);
1463 freeints(v->u.objidval);
1467 free(v->u.stringval);
1471 for(l = el; l != nil; l = l->tl)
1472 freevalfields(&l->hd.val);
1478 for(l = el; l != nil; l = l->tl)
1479 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,
1577 ALG_sha1WithRSAEncryption,
1581 typedef struct Ints7 {
1585 static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
1586 static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
1587 static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
1588 static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
1589 static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
1590 static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
1591 static Ints *alg_oid_tab[NUMALGS+1] = {
1592 (Ints*)(void*)&oid_rsaEncryption,
1593 (Ints*)(void*)&oid_md2WithRSAEncryption,
1594 (Ints*)(void*)&oid_md4WithRSAEncryption,
1595 (Ints*)(void*)&oid_md5WithRSAEncryption,
1596 (Ints*)(void*)&oid_sha1WithRSAEncryption,
1597 (Ints*)(void*)&oid_md5,
1600 static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, 0 };
1603 freecert(CertX509* c)
1606 if(c->issuer != nil)
1608 if(c->validity_start != nil)
1609 free(c->validity_start);
1610 if(c->validity_end != nil)
1611 free(c->validity_end);
1612 if(c->subject != nil)
1614 freebytes(c->publickey);
1615 freebytes(c->signature);
1619 * Parse the Name ASN1 type.
1620 * The sequence of RelativeDistinguishedName's gives a sort of pathname,
1621 * from most general to most specific. Each element of the path can be
1622 * one or more (but usually just one) attribute-value pair, such as
1624 * We'll just form a "postal-style" address string by concatenating the elements
1625 * from most specific to least specific, separated by commas.
1626 * Return name-as-string (which must be freed by caller).
1637 enum { MAXPARTS = 100 };
1638 char* parts[MAXPARTS];
1649 if(!is_set(es, &esetl))
1651 while(esetl != nil) {
1653 if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
1655 if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
1658 plen += strlen(s) + 2; /* room for ", " after */
1664 ans = (char*)emalloc(plen);
1679 * Parse an AlgorithmIdentifer ASN1 type.
1680 * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
1681 * or -1 if not found.
1682 * For now, ignore parameters, since none of our algorithms need them.
1690 if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
1692 return oid_lookup(oid, alg_oid_tab);
1696 decode_cert(Bytes* a)
1711 Elist* elcert = nil;
1712 Elist* elcertinfo = nil;
1713 Elist* elvalidity = nil;
1714 Elist* elpubkey = nil;
1719 if(decode(a->data, a->len, &ecert) != ASN_OK)
1722 c = (CertX509*)emalloc(sizeof(CertX509));
1725 c->validity_start = nil;
1726 c->validity_end = nil;
1728 c->publickey_alg = -1;
1730 c->signature_alg = -1;
1734 if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
1736 ecertinfo = &elcert->hd;
1739 c->signature_alg = parse_alg(esigalg);
1743 /* Certificate Info */
1744 if(!is_seq(ecertinfo, &elcertinfo))
1746 n = elistlen(elcertinfo);
1749 eserial =&elcertinfo->hd;
1750 el = elcertinfo->tl;
1751 /* check for optional version, marked by explicit context tag 0 */
1752 if(eserial->tag.class == Context && eserial->tag.num == 0) {
1759 if(parse_alg(&el->hd) != c->signature_alg)
1764 evalidity = &el->hd;
1769 if(!is_int(eserial, &c->serial)) {
1770 if(!is_bigint(eserial, &b))
1772 c->serial = -1; /* else we have to change cert struct */
1774 c->issuer = parse_name(eissuer);
1775 if(c->issuer == nil)
1778 if(!is_seq(evalidity, &elvalidity))
1780 if(elistlen(elvalidity) != 2)
1782 e = &elvalidity->hd;
1783 if(!is_time(e, &c->validity_start))
1785 e->val.u.stringval = nil; /* string ownership transfer */
1786 e = &elvalidity->tl->hd;
1787 if(!is_time(e, &c->validity_end))
1789 e->val.u.stringval = nil; /* string ownership transfer */
1791 /* resume CertificateInfo */
1792 c->subject = parse_name(esubj);
1793 if(c->subject == nil)
1796 /* SubjectPublicKeyInfo */
1797 if(!is_seq(epubkey, &elpubkey))
1799 if(elistlen(elpubkey) != 2)
1802 c->publickey_alg = parse_alg(&elpubkey->hd);
1803 if(c->publickey_alg < 0)
1805 if(!is_bitstring(&elpubkey->tl->hd, &bits))
1807 if(bits->unusedbits != 0)
1809 c->publickey = makebytes(bits->data, bits->len);
1811 /*resume Certificate */
1812 if(c->signature_alg < 0)
1814 if(!is_bitstring(esig, &bits))
1816 c->signature = makebytes(bits->data, bits->len);
1820 freevalfields(&ecert.val); /* recurses through lists, too */
1829 * RSAPublickKey :: SEQUENCE {
1831 * publicExponent INTEGER
1835 decode_rsapubkey(Bytes* a)
1842 key = rsapuballoc();
1843 if(decode(a->data, a->len, &e) != ASN_OK)
1845 if(!is_seq(&e, &el) || elistlen(el) != 2)
1848 key->n = mp = asn1mpint(&el->hd);
1853 key->ek = mp = asn1mpint(&el->hd);
1863 * RSAPrivateKey ::= SEQUENCE {
1865 * modulus INTEGER, -- n
1866 * publicExponent INTEGER, -- e
1867 * privateExponent INTEGER, -- d
1868 * prime1 INTEGER, -- p
1869 * prime2 INTEGER, -- q
1870 * exponent1 INTEGER, -- d mod (p-1)
1871 * exponent2 INTEGER, -- d mod (q-1)
1872 * coefficient INTEGER -- (inverse of q) mod p }
1875 decode_rsaprivkey(Bytes* a)
1883 key = rsaprivalloc();
1884 if(decode(a->data, a->len, &e) != ASN_OK)
1886 if(!is_seq(&e, &el) || elistlen(el) != 9)
1888 if(!is_int(&el->hd, &version) || version != 0)
1892 key->pub.n = mp = asn1mpint(&el->hd);
1897 key->pub.ek = mp = asn1mpint(&el->hd);
1902 key->dk = mp = asn1mpint(&el->hd);
1907 key->q = mp = asn1mpint(&el->hd);
1912 key->p = mp = asn1mpint(&el->hd);
1917 key->kq = mp = asn1mpint(&el->hd);
1922 key->kp = mp = asn1mpint(&el->hd);
1927 key->c2 = mp = asn1mpint(&el->hd);
1945 return itomp(v, nil);
1946 if(is_bigint(e, &b)) {
1947 mp = betomp(b->data, b->len, nil);
1955 pkcs1pad(Bytes *b, mpint *modulus)
1957 int n = (mpsignif(modulus)+7)/8;
1962 pm1 = n - 1 - b->len;
1963 p = (uchar*)emalloc(n);
1966 for(i = 2; i < pm1; i++)
1969 memcpy(&p[pm1+1], b->data, b->len);
1970 mp = betomp(p, n, nil);
1976 asn1toRSApriv(uchar *kd, int kn)
1981 b = makebytes(kd, kn);
1982 key = decode_rsaprivkey(b);
1988 * digest(CertificateInfo)
1989 * Our ASN.1 library doesn't return pointers into the original
1990 * data array, so we need to do a little hand decoding.
1993 digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
1995 uchar *info, *p, *pend;
1997 int isconstr, length;
2002 pend = cert->data + cert->len;
2003 if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
2004 tag.class != Universal || tag.num != SEQUENCE ||
2005 length_decode(&p, pend, &length) != ASN_OK ||
2010 if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
2013 (*digestfun)(info, infolen, digest, nil);
2017 verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
2022 uchar *pkcs1buf, *buf;
2027 /* one less than the byte length of the modulus */
2028 nlen = (mpsignif(pk->n)-1)/8;
2030 /* see 9.2.1 of rfc2437 */
2031 pkcs1 = betomp(signature->data, signature->len, nil);
2032 mpexp(pkcs1, pk->ek, pk->n, pkcs1);
2034 buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
2036 if(buflen != nlen || buf[0] != 1)
2037 return "expected 1";
2039 while(buf[0] == 0xff)
2042 return "expected 0";
2044 buflen -= buf-pkcs1buf;
2045 if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
2046 !is_octetstring(&el->tl->hd, &digest))
2047 return "signature parse error";
2049 if(memcmp(digest->data, edigest, digest->len) == 0)
2051 return "digests did not match";
2055 X509toRSApub(uchar *cert, int ncert, char *name, int nname)
2062 b = makebytes(cert, ncert);
2067 if(name != nil && c->subject != nil){
2068 e = strchr(c->subject, ',');
2070 *e = 0; // take just CN part of Distinguished Name
2071 strncpy(name, c->subject, nname);
2073 pk = decode_rsapubkey(c->publickey);
2079 X509verify(uchar *cert, int ncert, RSApub *pk)
2084 uchar digest[SHA1dlen];
2087 b = makebytes(cert, ncert);
2090 digest_certinfo(b, digestalg[c->signature_alg], digest);
2093 return "cannot decode cert";
2094 e = verify_signature(c->signature, pk, digest, &sigalg);
2099 /* ------- Elem constructors ---------- */
2105 e.tag.class = Universal;
2106 e.tag.num = NULLTAG;
2116 e.tag.class = Universal;
2117 e.tag.num = INTEGER;
2130 e.tag.class = Universal;
2131 e.tag.num = INTEGER;
2132 e.val.tag = VBigInt;
2133 buflen = mptobe(p, nil, 0, &buf);
2134 e.val.u.bigintval = makebytes(buf, buflen);
2144 e.tag.class = Universal;
2145 e.tag.num = IA5String;
2146 e.val.tag = VString;
2147 e.val.u.stringval = estrdup(s);
2152 mkoctet(uchar *buf, int buflen)
2156 e.tag.class = Universal;
2157 e.tag.num = OCTET_STRING;
2158 e.val.tag = VOctets;
2159 e.val.u.octetsval = makebytes(buf, buflen);
2164 mkbits(uchar *buf, int buflen)
2168 e.tag.class = Universal;
2169 e.tag.num = BIT_STRING;
2170 e.val.tag = VBitString;
2171 e.val.u.bitstringval = makebits(buf, buflen, 0);
2182 e.tag.class = Universal;
2183 e.tag.num = UTCTime;
2184 e.val.tag = VString;
2185 snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
2186 tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
2187 e.val.u.stringval = estrdup(utc);
2196 e.tag.class = Universal;
2197 e.tag.num = OBJECT_ID;
2199 e.val.u.objidval = makeints(oid->data, oid->len);
2208 e.tag.class = Universal;
2209 e.tag.num = SEQUENCE;
2211 e.val.u.seqval = el;
2220 e.tag.class = Universal;
2223 e.val.u.setval = el;
2230 return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
2233 typedef struct Ints7pref {
2238 Ints7pref DN_oid[] = {
2239 {4, 2, 5, 4, 6, 0, 0, 0, "C="},
2240 {4, 2, 5, 4, 8, 0, 0, 0, "ST="},
2241 {4, 2, 5, 4, 7, 0, 0, 0, "L="},
2242 {4, 2, 5, 4, 10, 0, 0, 0, "O="},
2243 {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
2244 {4, 2, 5, 4, 3, 0, 0, 0, "CN="},
2245 {7, 1,2,840,113549,1,9,1, "E="},
2249 mkname(Ints7pref *oid, char *subj)
2251 return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
2258 char *f[20], *prefix, *d2 = estrdup(dn);
2261 nf = tokenize(d2, f, nelem(f));
2262 for(i=nf-1; i>=0; i--){
2263 for(j=0; j<nelem(DN_oid); j++){
2264 prefix = DN_oid[j].prefix;
2265 if(strncmp(f[i],prefix,strlen(prefix))==0){
2266 el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
2277 X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
2281 RSApub *pk = rsaprivtopub(priv);
2282 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2283 Elem e, certinfo, issuer, subject, pubkey, validity, sig;
2284 uchar digest[MD5dlen], *buf;
2288 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2289 issuer = mkDN(subj);
2290 subject = mkDN(subj);
2291 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2292 if(encode(pubkey, &pkbytes) != ASN_OK)
2294 freevalfields(&pubkey.val);
2296 mkel(mkalg(ALG_rsaEncryption),
2297 mkel(mkbits(pkbytes->data, pkbytes->len),
2301 mkel(mkutc(valid[0]),
2302 mkel(mkutc(valid[1]),
2306 mkel(mkalg(ALG_md5WithRSAEncryption),
2312 if(encode(certinfo, &certinfobytes) != ASN_OK)
2314 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2315 freebytes(certinfobytes);
2317 mkel(mkalg(ALG_md5),
2318 mkel(mkoctet(digest, MD5dlen),
2320 if(encode(sig, &sigbytes) != ASN_OK)
2322 pkcs1 = pkcs1pad(sigbytes, pk->n);
2323 freebytes(sigbytes);
2324 rsadecrypt(priv, pkcs1, pkcs1);
2325 buflen = mptobe(pkcs1, nil, 0, &buf);
2329 mkel(mkalg(ALG_md5WithRSAEncryption),
2330 mkel(mkbits(buf, buflen),
2333 if(encode(e, &certbytes) != ASN_OK)
2336 *certlen = certbytes->len;
2337 cert = certbytes->data;
2339 freevalfields(&e.val);
2344 X509req(RSApriv *priv, char *subj, int *certlen)
2346 /* RFC 2314, PKCS #10 Certification Request Syntax */
2349 RSApub *pk = rsaprivtopub(priv);
2350 Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
2351 Elem e, certinfo, subject, pubkey, sig;
2352 uchar digest[MD5dlen], *buf;
2356 e.val.tag = VInt; /* so freevalfields at errret is no-op */
2357 subject = mkDN(subj);
2358 pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
2359 if(encode(pubkey, &pkbytes) != ASN_OK)
2361 freevalfields(&pubkey.val);
2363 mkel(mkalg(ALG_rsaEncryption),
2364 mkel(mkbits(pkbytes->data, pkbytes->len),
2368 mkel(mkint(version),
2372 if(encode(certinfo, &certinfobytes) != ASN_OK)
2374 md5(certinfobytes->data, certinfobytes->len, digest, 0);
2375 freebytes(certinfobytes);
2377 mkel(mkalg(ALG_md5),
2378 mkel(mkoctet(digest, MD5dlen),
2380 if(encode(sig, &sigbytes) != ASN_OK)
2382 pkcs1 = pkcs1pad(sigbytes, pk->n);
2383 freebytes(sigbytes);
2384 rsadecrypt(priv, pkcs1, pkcs1);
2385 buflen = mptobe(pkcs1, nil, 0, &buf);
2389 mkel(mkalg(ALG_md5),
2390 mkel(mkbits(buf, buflen),
2393 if(encode(e, &certbytes) != ASN_OK)
2396 *certlen = certbytes->len;
2397 cert = certbytes->data;
2399 freevalfields(&e.val);
2406 if(tag.class != Universal)
2407 return smprint("class%d,num%d", tag.class, tag.num);
2409 case BOOLEAN: return "BOOLEAN"; break;
2410 case INTEGER: return "INTEGER"; break;
2411 case BIT_STRING: return "BIT STRING"; break;
2412 case OCTET_STRING: return "OCTET STRING"; break;
2413 case NULLTAG: return "NULLTAG"; break;
2414 case OBJECT_ID: return "OID"; break;
2415 case ObjectDescriptor: return "OBJECT_DES"; break;
2416 case EXTERNAL: return "EXTERNAL"; break;
2417 case REAL: return "REAL"; break;
2418 case ENUMERATED: return "ENUMERATED"; break;
2419 case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
2420 case SEQUENCE: return "SEQUENCE"; break;
2421 case SETOF: return "SETOF"; break;
2422 case NumericString: return "NumericString"; break;
2423 case PrintableString: return "PrintableString"; break;
2424 case TeletexString: return "TeletexString"; break;
2425 case VideotexString: return "VideotexString"; break;
2426 case IA5String: return "IA5String"; break;
2427 case UTCTime: return "UTCTime"; break;
2428 case GeneralizedTime: return "GeneralizedTime"; break;
2429 case GraphicString: return "GraphicString"; break;
2430 case VisibleString: return "VisibleString"; break;
2431 case GeneralString: return "GeneralString"; break;
2432 case UniversalString: return "UniversalString"; break;
2433 case BMPString: return "BMPString"; break;
2435 return smprint("Universal,num%d", tag.num);
2446 print("%s{", tagdump(e.tag));
2449 case VBool: print("Bool %d",v.u.boolval); break;
2450 case VInt: print("Int %d",v.u.intval); break;
2451 case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
2452 case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
2453 case VReal: print("Real..."); break;
2454 case VOther: print("Other..."); break;
2455 case VBitString: print("BitString..."); break;
2456 case VNull: print("Null"); break;
2457 case VEOC: print("EOC..."); break;
2458 case VObjId: print("ObjId");
2459 for(i = 0; i<v.u.objidval->len; i++)
2460 print(" %d", v.u.objidval->data[i]);
2462 case VString: print("String \"%s\"",v.u.stringval); break;
2463 case VSeq: print("Seq\n");
2464 for(el = v.u.seqval; el!=nil; el = el->tl)
2467 case VSet: print("Set\n");
2468 for(el = v.u.setval; el!=nil; el = el->tl)
2476 asn1dump(uchar *der, int len)
2480 if(decode(der, len, &e) != ASN_OK){
2481 print("didn't parse\n");
2482 exits("didn't parse");
2488 X509dump(uchar *cert, int ncert)
2494 uchar digest[SHA1dlen];
2497 print("begin X509dump\n");
2498 b = makebytes(cert, ncert);
2501 digest_certinfo(b, digestalg[c->signature_alg], digest);
2504 print("cannot decode cert");
2508 print("serial %d\n", c->serial);
2509 print("issuer %s\n", c->issuer);
2510 print("validity %s %s\n", c->validity_start, c->validity_end);
2511 print("subject %s\n", c->subject);
2512 pk = decode_rsapubkey(c->publickey);
2513 print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
2515 print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
2516 e = verify_signature(c->signature, pk, digest, &sigalg);
2518 e = "nil (meaning ok)";
2523 print("self-signed verify_signature returns: %s\n", e);
2527 print("end X509dump\n");