PageRenderTime 56ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/src/libsec/port/x509.c

https://bitbucket.org/vcgomes/plan9port
C | 2602 lines | 2102 code | 221 blank | 279 comment | 481 complexity | 018d66dd793d38e97628267f9b12ad01 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, Unlicense, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. #include <u.h>
  2. #include <libc.h>
  3. #include <mp.h>
  4. #include <libsec.h>
  5. typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
  6. /* ANSI offsetof, backwards. */
  7. #define OFFSETOF(a, b) offsetof(b, a)
  8. /*=============================================================*/
  9. /* general ASN1 declarations and parsing
  10. *
  11. * For now, this is used only for extracting the key from an
  12. * X509 certificate, so the entire collection is hidden. But
  13. * someday we should probably make the functions visible and
  14. * give them their own man page.
  15. */
  16. typedef struct Elem Elem;
  17. typedef struct Tag Tag;
  18. typedef struct Value Value;
  19. typedef struct Bytes Bytes;
  20. typedef struct Ints Ints;
  21. typedef struct Bits Bits;
  22. typedef struct Elist Elist;
  23. /* tag classes */
  24. #define Universal 0
  25. #define Context 0x80
  26. /* universal tags */
  27. #define BOOLEAN 1
  28. #define INTEGER 2
  29. #define BIT_STRING 3
  30. #define OCTET_STRING 4
  31. #define NULLTAG 5
  32. #define OBJECT_ID 6
  33. #define ObjectDescriptor 7
  34. #define EXTERNAL 8
  35. #define REAL 9
  36. #define ENUMERATED 10
  37. #define EMBEDDED_PDV 11
  38. #define SEQUENCE 16 /* also SEQUENCE OF */
  39. #define SETOF 17 /* also SETOF OF */
  40. #define NumericString 18
  41. #define PrintableString 19
  42. #define TeletexString 20
  43. #define VideotexString 21
  44. #define IA5String 22
  45. #define UTCTime 23
  46. #define GeneralizedTime 24
  47. #define GraphicString 25
  48. #define VisibleString 26
  49. #define GeneralString 27
  50. #define UniversalString 28
  51. #define BMPString 30
  52. struct Bytes {
  53. int len;
  54. uchar data[1];
  55. };
  56. struct Ints {
  57. int len;
  58. int data[1];
  59. };
  60. struct Bits {
  61. int len; /* number of bytes */
  62. int unusedbits; /* unused bits in last byte */
  63. uchar data[1]; /* most-significant bit first */
  64. };
  65. struct Tag {
  66. int class;
  67. int num;
  68. };
  69. enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
  70. VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
  71. struct Value {
  72. int tag; /* VBool, etc. */
  73. union {
  74. int boolval;
  75. int intval;
  76. Bytes* octetsval;
  77. Bytes* bigintval;
  78. Bytes* realval; /* undecoded; hardly ever used */
  79. Bytes* otherval;
  80. Bits* bitstringval;
  81. Ints* objidval;
  82. char* stringval;
  83. Elist* seqval;
  84. Elist* setval;
  85. } u; /* (Don't use anonymous unions, for ease of porting) */
  86. };
  87. struct Elem {
  88. Tag tag;
  89. Value val;
  90. };
  91. struct Elist {
  92. Elist* tl;
  93. Elem hd;
  94. };
  95. /* decoding errors */
  96. enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
  97. ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
  98. /* here are the functions to consider making extern someday */
  99. static Bytes* newbytes(int len);
  100. static Bytes* makebytes(uchar* buf, int len);
  101. static void freebytes(Bytes* b);
  102. static Bytes* catbytes(Bytes* b1, Bytes* b2);
  103. static Ints* newints(int len);
  104. static Ints* makeints(int* buf, int len);
  105. static void freeints(Ints* b);
  106. static Bits* newbits(int len);
  107. static Bits* makebits(uchar* buf, int len, int unusedbits);
  108. static void freebits(Bits* b);
  109. static Elist* mkel(Elem e, Elist* tail);
  110. static void freeelist(Elist* el);
  111. static int elistlen(Elist* el);
  112. static int is_seq(Elem* pe, Elist** pseq);
  113. static int is_set(Elem* pe, Elist** pset);
  114. static int is_int(Elem* pe, int* pint);
  115. static int is_bigint(Elem* pe, Bytes** pbigint);
  116. static int is_bitstring(Elem* pe, Bits** pbits);
  117. static int is_octetstring(Elem* pe, Bytes** poctets);
  118. static int is_oid(Elem* pe, Ints** poid);
  119. static int is_string(Elem* pe, char** pstring);
  120. static int is_time(Elem* pe, char** ptime);
  121. static int decode(uchar* a, int alen, Elem* pelem);
  122. /*
  123. static int decode_seq(uchar* a, int alen, Elist** pelist);
  124. static int decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
  125. */
  126. static int encode(Elem e, Bytes** pbytes);
  127. static int oid_lookup(Ints* o, Ints** tab);
  128. static void freevalfields(Value* v);
  129. static mpint *asn1mpint(Elem *e);
  130. #define TAG_MASK 0x1F
  131. #define CONSTR_MASK 0x20
  132. #define CLASS_MASK 0xC0
  133. #define MAXOBJIDLEN 20
  134. static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
  135. static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
  136. static int length_decode(uchar** pp, uchar* pend, int* plength);
  137. static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
  138. static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
  139. static int uint7_decode(uchar** pp, uchar* pend, int* pint);
  140. static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
  141. static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
  142. static int enc(uchar** pp, Elem e, int lenonly);
  143. static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
  144. static void uint7_enc(uchar** pp, int num, int lenonly);
  145. static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
  146. static void *
  147. emalloc(int n)
  148. {
  149. void *p;
  150. if(n==0)
  151. n=1;
  152. p = malloc(n);
  153. if(p == nil){
  154. exits("out of memory");
  155. }
  156. memset(p, 0, n);
  157. return p;
  158. }
  159. static char*
  160. estrdup(char *s)
  161. {
  162. char *d, *d0;
  163. if(!s)
  164. return 0;
  165. d = d0 = emalloc(strlen(s)+1);
  166. while(*d++ = *s++)
  167. ;
  168. return d0;
  169. }
  170. /*
  171. * Decode a[0..len] as a BER encoding of an ASN1 type.
  172. * The return value is one of ASN_OK, etc.
  173. * Depending on the error, the returned elem may or may not
  174. * be nil.
  175. */
  176. static int
  177. decode(uchar* a, int alen, Elem* pelem)
  178. {
  179. uchar* p = a;
  180. return ber_decode(&p, &a[alen], pelem);
  181. }
  182. /*
  183. * Like decode, but continue decoding after first element
  184. * of array ends.
  185. *
  186. static int
  187. decode_seq(uchar* a, int alen, Elist** pelist)
  188. {
  189. uchar* p = a;
  190. return seq_decode(&p, &a[alen], -1, 1, pelist);
  191. }
  192. */
  193. /*
  194. * Decode the whole array as a BER encoding of an ASN1 value,
  195. * (i.e., the part after the tag and length).
  196. * Assume the value is encoded as universal tag "kind".
  197. * The constr arg is 1 if the value is constructed, 0 if primitive.
  198. * If there's an error, the return string will contain the error.
  199. * Depending on the error, the returned value may or may not
  200. * be nil.
  201. *
  202. static int
  203. decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
  204. {
  205. uchar* p = a;
  206. return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
  207. }
  208. */
  209. /*
  210. * All of the following decoding routines take arguments:
  211. * uchar **pp;
  212. * uchar *pend;
  213. * Where parsing is supposed to start at **pp, and when parsing
  214. * is done, *pp is updated to point at next char to be parsed.
  215. * The pend pointer is just past end of string; an error should
  216. * be returned parsing hasn't finished by then.
  217. *
  218. * The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
  219. * The remaining argument(s) are pointers to where parsed entity goes.
  220. */
  221. /* Decode an ASN1 'Elem' (tag, length, value) */
  222. static int
  223. ber_decode(uchar** pp, uchar* pend, Elem* pelem)
  224. {
  225. int err;
  226. int isconstr;
  227. int length;
  228. Tag tag;
  229. Value val;
  230. err = tag_decode(pp, pend, &tag, &isconstr);
  231. if(err == ASN_OK) {
  232. err = length_decode(pp, pend, &length);
  233. if(err == ASN_OK) {
  234. if(tag.class == Universal)
  235. err = value_decode(pp, pend, length, tag.num, isconstr, &val);
  236. else
  237. err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
  238. if(err == ASN_OK) {
  239. pelem->tag = tag;
  240. pelem->val = val;
  241. }
  242. }
  243. }
  244. return err;
  245. }
  246. /* Decode a tag field */
  247. static int
  248. tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
  249. {
  250. int err;
  251. int v;
  252. uchar* p;
  253. err = ASN_OK;
  254. p = *pp;
  255. if(pend-p >= 2) {
  256. v = *p++;
  257. ptag->class = v&CLASS_MASK;
  258. if(v&CONSTR_MASK)
  259. *pisconstr = 1;
  260. else
  261. *pisconstr = 0;
  262. v &= TAG_MASK;
  263. if(v == TAG_MASK)
  264. err = uint7_decode(&p, pend, &v);
  265. ptag->num = v;
  266. }
  267. else
  268. err = ASN_ESHORT;
  269. *pp = p;
  270. return err;
  271. }
  272. /* Decode a length field */
  273. static int
  274. length_decode(uchar** pp, uchar* pend, int* plength)
  275. {
  276. int err;
  277. int num;
  278. int v;
  279. uchar* p;
  280. err = ASN_OK;
  281. num = 0;
  282. p = *pp;
  283. if(p < pend) {
  284. v = *p++;
  285. if(v&0x80)
  286. err = int_decode(&p, pend, v&0x7F, 1, &num);
  287. else
  288. num = v;
  289. }
  290. else
  291. err = ASN_ESHORT;
  292. *pp = p;
  293. *plength = num;
  294. return err;
  295. }
  296. /* Decode a value field */
  297. static int
  298. value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
  299. {
  300. int err;
  301. Bytes* va;
  302. int num;
  303. int bitsunused;
  304. int subids[MAXOBJIDLEN];
  305. int isubid;
  306. Elist* vl;
  307. uchar* p;
  308. uchar* pe;
  309. err = ASN_OK;
  310. p = *pp;
  311. if(length == -1) { /* "indefinite" length spec */
  312. if(!isconstr)
  313. err = ASN_EINVAL;
  314. }
  315. else if(p + length > pend)
  316. err = ASN_EVALLEN;
  317. if(err != ASN_OK)
  318. return err;
  319. switch(kind) {
  320. case 0:
  321. /* marker for end of indefinite constructions */
  322. if(length == 0)
  323. pval->tag = VNull;
  324. else
  325. err = ASN_EINVAL;
  326. break;
  327. case BOOLEAN:
  328. if(isconstr)
  329. err = ASN_ECONSTR;
  330. else if(length != 1)
  331. err = ASN_EVALLEN;
  332. else {
  333. pval->tag = VBool;
  334. pval->u.boolval = (*p++ != 0);
  335. }
  336. break;
  337. case INTEGER:
  338. case ENUMERATED:
  339. if(isconstr)
  340. err = ASN_ECONSTR;
  341. else if(length <= 4) {
  342. err = int_decode(&p, pend, length, 0, &num);
  343. if(err == ASN_OK) {
  344. pval->tag = VInt;
  345. pval->u.intval = num;
  346. }
  347. }
  348. else {
  349. pval->tag = VBigInt;
  350. pval->u.bigintval = makebytes(p, length);
  351. p += length;
  352. }
  353. break;
  354. case BIT_STRING:
  355. pval->tag = VBitString;
  356. if(isconstr) {
  357. if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
  358. pval->u.bitstringval = makebits(0, 0, 0);
  359. p += 2;
  360. }
  361. else
  362. /* TODO: recurse and concat results */
  363. err = ASN_EUNIMPL;
  364. }
  365. else {
  366. if(length < 2) {
  367. if(length == 1 && *p == 0) {
  368. pval->u.bitstringval = makebits(0, 0, 0);
  369. p++;
  370. }
  371. else
  372. err = ASN_EINVAL;
  373. }
  374. else {
  375. bitsunused = *p;
  376. if(bitsunused > 7)
  377. err = ASN_EINVAL;
  378. else if(length > 0x0FFFFFFF)
  379. err = ASN_ETOOBIG;
  380. else {
  381. pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
  382. p += length;
  383. }
  384. }
  385. }
  386. break;
  387. case OCTET_STRING:
  388. case ObjectDescriptor:
  389. err = octet_decode(&p, pend, length, isconstr, &va);
  390. if(err == ASN_OK) {
  391. pval->tag = VOctets;
  392. pval->u.octetsval = va;
  393. }
  394. break;
  395. case NULLTAG:
  396. if(isconstr)
  397. err = ASN_ECONSTR;
  398. else if(length != 0)
  399. err = ASN_EVALLEN;
  400. else
  401. pval->tag = VNull;
  402. break;
  403. case OBJECT_ID:
  404. if(isconstr)
  405. err = ASN_ECONSTR;
  406. else if(length == 0)
  407. err = ASN_EVALLEN;
  408. else {
  409. isubid = 0;
  410. pe = p+length;
  411. while(p < pe && isubid < MAXOBJIDLEN) {
  412. err = uint7_decode(&p, pend, &num);
  413. if(err != ASN_OK)
  414. break;
  415. if(isubid == 0) {
  416. subids[isubid++] = num / 40;
  417. subids[isubid++] = num % 40;
  418. }
  419. else
  420. subids[isubid++] = num;
  421. }
  422. if(err == ASN_OK) {
  423. if(p != pe)
  424. err = ASN_EVALLEN;
  425. else {
  426. pval->tag = VObjId;
  427. pval->u.objidval = makeints(subids, isubid);
  428. }
  429. }
  430. }
  431. break;
  432. case EXTERNAL:
  433. case EMBEDDED_PDV:
  434. /* TODO: parse this internally */
  435. if(p+length > pend)
  436. err = ASN_EVALLEN;
  437. else {
  438. pval->tag = VOther;
  439. pval->u.otherval = makebytes(p, length);
  440. p += length;
  441. }
  442. break;
  443. case REAL:
  444. /* Let the application decode */
  445. if(isconstr)
  446. err = ASN_ECONSTR;
  447. else if(p+length > pend)
  448. err = ASN_EVALLEN;
  449. else {
  450. pval->tag = VReal;
  451. pval->u.realval = makebytes(p, length);
  452. p += length;
  453. }
  454. break;
  455. case SEQUENCE:
  456. err = seq_decode(&p, pend, length, isconstr, &vl);
  457. if(err == ASN_OK) {
  458. pval->tag = VSeq ;
  459. pval->u.seqval = vl;
  460. }
  461. break;
  462. case SETOF:
  463. err = seq_decode(&p, pend, length, isconstr, &vl);
  464. if(err == ASN_OK) {
  465. pval->tag = VSet;
  466. pval->u.setval = vl;
  467. }
  468. break;
  469. case NumericString:
  470. case PrintableString:
  471. case TeletexString:
  472. case VideotexString:
  473. case IA5String:
  474. case UTCTime:
  475. case GeneralizedTime:
  476. case GraphicString:
  477. case VisibleString:
  478. case GeneralString:
  479. case UniversalString:
  480. case BMPString:
  481. /* TODO: figure out when character set conversion is necessary */
  482. err = octet_decode(&p, pend, length, isconstr, &va);
  483. if(err == ASN_OK) {
  484. pval->tag = VString;
  485. pval->u.stringval = (char*)emalloc(va->len+1);
  486. memmove(pval->u.stringval, va->data, va->len);
  487. pval->u.stringval[va->len] = 0;
  488. free(va);
  489. }
  490. break;
  491. default:
  492. if(p+length > pend)
  493. err = ASN_EVALLEN;
  494. else {
  495. pval->tag = VOther;
  496. pval->u.otherval = makebytes(p, length);
  497. p += length;
  498. }
  499. break;
  500. }
  501. *pp = p;
  502. return err;
  503. }
  504. /*
  505. * Decode an int in format where count bytes are
  506. * concatenated to form value.
  507. * Although ASN1 allows any size integer, we return
  508. * an error if the result doesn't fit in a 32-bit int.
  509. * If unsgned is not set, make sure to propagate sign bit.
  510. */
  511. static int
  512. int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
  513. {
  514. int err;
  515. int num;
  516. uchar* p;
  517. p = *pp;
  518. err = ASN_OK;
  519. num = 0;
  520. if(p+count <= pend) {
  521. if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
  522. err = ASN_ETOOBIG;
  523. else {
  524. if(!unsgned && count > 0 && count < 4 && (*p&0x80))
  525. num = -1; /* set all bits, initially */
  526. while(count--)
  527. num = (num << 8)|(*p++);
  528. }
  529. }
  530. else
  531. err = ASN_ESHORT;
  532. *pint = num;
  533. *pp = p;
  534. return err;
  535. }
  536. /*
  537. * Decode an unsigned int in format where each
  538. * byte except last has high bit set, and remaining
  539. * seven bits of each byte are concatenated to form value.
  540. * Although ASN1 allows any size integer, we return
  541. * an error if the result doesn't fit in a 32 bit int.
  542. */
  543. static int
  544. uint7_decode(uchar** pp, uchar* pend, int* pint)
  545. {
  546. int err;
  547. int num;
  548. int more;
  549. int v;
  550. uchar* p;
  551. p = *pp;
  552. err = ASN_OK;
  553. num = 0;
  554. more = 1;
  555. while(more && p < pend) {
  556. v = *p++;
  557. if(num&0x7F000000) {
  558. err = ASN_ETOOBIG;
  559. break;
  560. }
  561. num <<= 7;
  562. more = v&0x80;
  563. num |= (v&0x7F);
  564. }
  565. if(p == pend)
  566. err = ASN_ESHORT;
  567. *pint = num;
  568. *pp = p;
  569. return err;
  570. }
  571. /*
  572. * Decode an octet string, recursively if isconstr.
  573. * We've already checked that length==-1 implies isconstr==1,
  574. * and otherwise that specified length fits within (*pp..pend)
  575. */
  576. static int
  577. octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
  578. {
  579. int err;
  580. uchar* p;
  581. Bytes* ans;
  582. Bytes* newans;
  583. uchar* pstart;
  584. uchar* pold;
  585. Elem elem;
  586. err = ASN_OK;
  587. p = *pp;
  588. ans = nil;
  589. if(length >= 0 && !isconstr) {
  590. ans = makebytes(p, length);
  591. p += length;
  592. }
  593. else {
  594. /* constructed, either definite or indefinite length */
  595. pstart = p;
  596. for(;;) {
  597. if(length >= 0 && p >= pstart + length) {
  598. if(p != pstart + length)
  599. err = ASN_EVALLEN;
  600. break;
  601. }
  602. pold = p;
  603. err = ber_decode(&p, pend, &elem);
  604. if(err != ASN_OK)
  605. break;
  606. switch(elem.val.tag) {
  607. case VOctets:
  608. newans = catbytes(ans, elem.val.u.octetsval);
  609. freebytes(ans);
  610. ans = newans;
  611. break;
  612. case VEOC:
  613. if(length != -1) {
  614. p = pold;
  615. err = ASN_EINVAL;
  616. }
  617. goto cloop_done;
  618. default:
  619. p = pold;
  620. err = ASN_EINVAL;
  621. goto cloop_done;
  622. }
  623. }
  624. cloop_done:
  625. ;
  626. }
  627. *pp = p;
  628. *pbytes = ans;
  629. return err;
  630. }
  631. /*
  632. * Decode a sequence or set.
  633. * We've already checked that length==-1 implies isconstr==1,
  634. * and otherwise that specified length fits within (*p..pend)
  635. */
  636. static int
  637. seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
  638. {
  639. int err;
  640. uchar* p;
  641. uchar* pstart;
  642. uchar* pold;
  643. Elist* ans;
  644. Elem elem;
  645. Elist* lve;
  646. Elist* lveold;
  647. err = ASN_OK;
  648. ans = nil;
  649. p = *pp;
  650. if(!isconstr)
  651. err = ASN_EPRIM;
  652. else {
  653. /* constructed, either definite or indefinite length */
  654. lve = nil;
  655. pstart = p;
  656. for(;;) {
  657. if(length >= 0 && p >= pstart + length) {
  658. if(p != pstart + length)
  659. err = ASN_EVALLEN;
  660. break;
  661. }
  662. pold = p;
  663. err = ber_decode(&p, pend, &elem);
  664. if(err != ASN_OK)
  665. break;
  666. if(elem.val.tag == VEOC) {
  667. if(length != -1) {
  668. p = pold;
  669. err = ASN_EINVAL;
  670. }
  671. break;
  672. }
  673. else
  674. lve = mkel(elem, lve);
  675. }
  676. if(err == ASN_OK) {
  677. /* reverse back to original order */
  678. while(lve != nil) {
  679. lveold = lve;
  680. lve = lve->tl;
  681. lveold->tl = ans;
  682. ans = lveold;
  683. }
  684. }
  685. }
  686. *pp = p;
  687. *pelist = ans;
  688. return err;
  689. }
  690. /*
  691. * Encode e by BER rules, putting answer in *pbytes.
  692. * This is done by first calling enc with lenonly==1
  693. * to get the length of the needed buffer,
  694. * then allocating the buffer and using enc again to fill it up.
  695. */
  696. static int
  697. encode(Elem e, Bytes** pbytes)
  698. {
  699. uchar* p;
  700. Bytes* ans;
  701. int err;
  702. uchar uc;
  703. p = &uc;
  704. err = enc(&p, e, 1);
  705. if(err == ASN_OK) {
  706. ans = newbytes(p-&uc);
  707. p = ans->data;
  708. err = enc(&p, e, 0);
  709. *pbytes = ans;
  710. }
  711. return err;
  712. }
  713. /*
  714. * The various enc functions take a pointer to a pointer
  715. * into a buffer, and encode their entity starting there,
  716. * updating the pointer afterwards.
  717. * If lenonly is 1, only the pointer update is done,
  718. * allowing enc to be called first to calculate the needed
  719. * buffer length.
  720. * If lenonly is 0, it is assumed that the answer will fit.
  721. */
  722. static int
  723. enc(uchar** pp, Elem e, int lenonly)
  724. {
  725. int err;
  726. int vlen;
  727. int constr;
  728. Tag tag;
  729. int v;
  730. int ilen;
  731. uchar* p;
  732. uchar* psave;
  733. p = *pp;
  734. err = val_enc(&p, e, &constr, 1);
  735. if(err != ASN_OK)
  736. return err;
  737. vlen = p - *pp;
  738. p = *pp;
  739. tag = e.tag;
  740. v = tag.class|constr;
  741. if(tag.num < 31) {
  742. if(!lenonly)
  743. *p = (v|tag.num);
  744. p++;
  745. }
  746. else {
  747. if(!lenonly)
  748. *p = (v|31);
  749. p++;
  750. if(tag.num < 0)
  751. return ASN_EINVAL;
  752. uint7_enc(&p, tag.num, lenonly);
  753. }
  754. if(vlen < 0x80) {
  755. if(!lenonly)
  756. *p = vlen;
  757. p++;
  758. }
  759. else {
  760. psave = p;
  761. int_enc(&p, vlen, 1, 1);
  762. ilen = p-psave;
  763. p = psave;
  764. if(!lenonly) {
  765. *p++ = (0x80 | ilen);
  766. int_enc(&p, vlen, 1, 0);
  767. }
  768. else
  769. p += 1 + ilen;
  770. }
  771. if(!lenonly)
  772. val_enc(&p, e, &constr, 0);
  773. else
  774. p += vlen;
  775. *pp = p;
  776. return err;
  777. }
  778. static int
  779. val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
  780. {
  781. int err;
  782. uchar* p;
  783. int kind;
  784. int cl;
  785. int v;
  786. Bytes* bb = nil;
  787. Bits* bits;
  788. Ints* oid;
  789. int k;
  790. Elist* el;
  791. char* s;
  792. p = *pp;
  793. err = ASN_OK;
  794. kind = e.tag.num;
  795. cl = e.tag.class;
  796. *pconstr = 0;
  797. if(cl != Universal) {
  798. switch(e.val.tag) {
  799. case VBool:
  800. kind = BOOLEAN;
  801. break;
  802. case VInt:
  803. kind = INTEGER;
  804. break;
  805. case VBigInt:
  806. kind = INTEGER;
  807. break;
  808. case VOctets:
  809. kind = OCTET_STRING;
  810. break;
  811. case VReal:
  812. kind = REAL;
  813. break;
  814. case VOther:
  815. kind = OCTET_STRING;
  816. break;
  817. case VBitString:
  818. kind = BIT_STRING;
  819. break;
  820. case VNull:
  821. kind = NULLTAG;
  822. break;
  823. case VObjId:
  824. kind = OBJECT_ID;
  825. break;
  826. case VString:
  827. kind = UniversalString;
  828. break;
  829. case VSeq:
  830. kind = SEQUENCE;
  831. break;
  832. case VSet:
  833. kind = SETOF;
  834. break;
  835. }
  836. }
  837. switch(kind) {
  838. case BOOLEAN:
  839. if(is_int(&e, &v)) {
  840. if(v != 0)
  841. v = 255;
  842. int_enc(&p, v, 1, lenonly);
  843. }
  844. else
  845. err = ASN_EINVAL;
  846. break;
  847. case INTEGER:
  848. case ENUMERATED:
  849. if(is_int(&e, &v))
  850. int_enc(&p, v, 0, lenonly);
  851. else {
  852. if(is_bigint(&e, &bb)) {
  853. if(!lenonly)
  854. memmove(p, bb->data, bb->len);
  855. p += bb->len;
  856. }
  857. else
  858. err = ASN_EINVAL;
  859. }
  860. break;
  861. case BIT_STRING:
  862. if(is_bitstring(&e, &bits)) {
  863. if(bits->len == 0) {
  864. if(!lenonly)
  865. *p = 0;
  866. p++;
  867. }
  868. else {
  869. v = bits->unusedbits;
  870. if(v < 0 || v > 7)
  871. err = ASN_EINVAL;
  872. else {
  873. if(!lenonly) {
  874. *p = v;
  875. memmove(p+1, bits->data, bits->len);
  876. }
  877. p += 1 + bits->len;
  878. }
  879. }
  880. }
  881. else
  882. err = ASN_EINVAL;
  883. break;
  884. case OCTET_STRING:
  885. case ObjectDescriptor:
  886. case EXTERNAL:
  887. case REAL:
  888. case EMBEDDED_PDV:
  889. bb = nil;
  890. switch(e.val.tag) {
  891. case VOctets:
  892. bb = e.val.u.octetsval;
  893. break;
  894. case VReal:
  895. bb = e.val.u.realval;
  896. break;
  897. case VOther:
  898. bb = e.val.u.otherval;
  899. break;
  900. }
  901. if(bb != nil) {
  902. if(!lenonly)
  903. memmove(p, bb->data, bb->len);
  904. p += bb->len;
  905. }
  906. else
  907. err = ASN_EINVAL;
  908. break;
  909. case NULLTAG:
  910. break;
  911. case OBJECT_ID:
  912. if(is_oid(&e, &oid)) {
  913. for(k = 0; k < oid->len; k++) {
  914. v = oid->data[k];
  915. if(k == 0) {
  916. v *= 40;
  917. if(oid->len > 1)
  918. v += oid->data[++k];
  919. }
  920. uint7_enc(&p, v, lenonly);
  921. }
  922. }
  923. else
  924. err = ASN_EINVAL;
  925. break;
  926. case SEQUENCE:
  927. case SETOF:
  928. el = nil;
  929. if(e.val.tag == VSeq)
  930. el = e.val.u.seqval;
  931. else if(e.val.tag == VSet)
  932. el = e.val.u.setval;
  933. else
  934. err = ASN_EINVAL;
  935. if(el != nil) {
  936. *pconstr = CONSTR_MASK;
  937. for(; el != nil; el = el->tl) {
  938. err = enc(&p, el->hd, lenonly);
  939. if(err != ASN_OK)
  940. break;
  941. }
  942. }
  943. break;
  944. case NumericString:
  945. case PrintableString:
  946. case TeletexString:
  947. case VideotexString:
  948. case IA5String:
  949. case UTCTime:
  950. case GeneralizedTime:
  951. case GraphicString:
  952. case VisibleString:
  953. case GeneralString:
  954. case UniversalString:
  955. case BMPString:
  956. if(e.val.tag == VString) {
  957. s = e.val.u.stringval;
  958. if(s != nil) {
  959. v = strlen(s);
  960. if(!lenonly)
  961. memmove(p, s, v);
  962. p += v;
  963. }
  964. }
  965. else
  966. err = ASN_EINVAL;
  967. break;
  968. default:
  969. err = ASN_EINVAL;
  970. }
  971. *pp = p;
  972. return err;
  973. }
  974. /*
  975. * Encode num as unsigned 7 bit values with top bit 1 on all bytes
  976. * except last, only putting in bytes if !lenonly.
  977. */
  978. static void
  979. uint7_enc(uchar** pp, int num, int lenonly)
  980. {
  981. int n;
  982. int v;
  983. int k;
  984. uchar* p;
  985. p = *pp;
  986. n = 1;
  987. v = num >> 7;
  988. while(v > 0) {
  989. v >>= 7;
  990. n++;
  991. }
  992. if(lenonly)
  993. p += n;
  994. else {
  995. for(k = (n - 1)*7; k > 0; k -= 7)
  996. *p++= ((num >> k)|0x80);
  997. *p++ = (num&0x7F);
  998. }
  999. *pp = p;
  1000. }
  1001. /*
  1002. * Encode num as unsigned or signed integer,
  1003. * only putting in bytes if !lenonly.
  1004. * Encoding is length followed by bytes to concatenate.
  1005. */
  1006. static void
  1007. int_enc(uchar** pp, int num, int unsgned, int lenonly)
  1008. {
  1009. int v;
  1010. int n;
  1011. int prevv;
  1012. int k;
  1013. uchar* p;
  1014. p = *pp;
  1015. v = num;
  1016. if(v < 0)
  1017. v = -(v + 1);
  1018. n = 1;
  1019. prevv = v;
  1020. v >>= 8;
  1021. while(v > 0) {
  1022. prevv = v;
  1023. v >>= 8;
  1024. n++;
  1025. }
  1026. if(!unsgned && (prevv&0x80))
  1027. n++;
  1028. if(lenonly)
  1029. p += n;
  1030. else {
  1031. for(k = (n - 1)*8; k >= 0; k -= 8)
  1032. *p++ = (num >> k);
  1033. }
  1034. *pp = p;
  1035. }
  1036. static int
  1037. ints_eq(Ints* a, Ints* b)
  1038. {
  1039. int alen;
  1040. int i;
  1041. alen = a->len;
  1042. if(alen != b->len)
  1043. return 0;
  1044. for(i = 0; i < alen; i++)
  1045. if(a->data[i] != b->data[i])
  1046. return 0;
  1047. return 1;
  1048. }
  1049. /*
  1050. * Look up o in tab (which must have nil entry to terminate).
  1051. * Return index of matching entry, or -1 if none.
  1052. */
  1053. static int
  1054. oid_lookup(Ints* o, Ints** tab)
  1055. {
  1056. int i;
  1057. for(i = 0; tab[i] != nil; i++)
  1058. if(ints_eq(o, tab[i]))
  1059. return i;
  1060. return -1;
  1061. }
  1062. /*
  1063. * Return true if *pe is a SEQUENCE, and set *pseq to
  1064. * the value of the sequence if so.
  1065. */
  1066. static int
  1067. is_seq(Elem* pe, Elist** pseq)
  1068. {
  1069. if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
  1070. *pseq = pe->val.u.seqval;
  1071. return 1;
  1072. }
  1073. return 0;
  1074. }
  1075. static int
  1076. is_set(Elem* pe, Elist** pset)
  1077. {
  1078. if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
  1079. *pset = pe->val.u.setval;
  1080. return 1;
  1081. }
  1082. return 0;
  1083. }
  1084. static int
  1085. is_int(Elem* pe, int* pint)
  1086. {
  1087. if(pe->tag.class == Universal) {
  1088. if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
  1089. *pint = pe->val.u.intval;
  1090. return 1;
  1091. }
  1092. else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
  1093. *pint = pe->val.u.boolval;
  1094. return 1;
  1095. }
  1096. }
  1097. return 0;
  1098. }
  1099. /*
  1100. * for convience, all VInt's are readable via this routine,
  1101. * as well as all VBigInt's
  1102. */
  1103. static int
  1104. is_bigint(Elem* pe, Bytes** pbigint)
  1105. {
  1106. int v, n, i;
  1107. if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
  1108. if(pe->val.tag == VBigInt)
  1109. *pbigint = pe->val.u.bigintval;
  1110. else if(pe->val.tag == VInt){
  1111. v = pe->val.u.intval;
  1112. for(n = 1; n < 4; n++)
  1113. if((1 << (8 * n)) > v)
  1114. break;
  1115. *pbigint = newbytes(n);
  1116. for(i = 0; i < n; i++)
  1117. (*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
  1118. }else
  1119. return 0;
  1120. return 1;
  1121. }
  1122. return 0;
  1123. }
  1124. static int
  1125. is_bitstring(Elem* pe, Bits** pbits)
  1126. {
  1127. if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
  1128. *pbits = pe->val.u.bitstringval;
  1129. return 1;
  1130. }
  1131. return 0;
  1132. }
  1133. static int
  1134. is_octetstring(Elem* pe, Bytes** poctets)
  1135. {
  1136. if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
  1137. *poctets = pe->val.u.octetsval;
  1138. return 1;
  1139. }
  1140. return 0;
  1141. }
  1142. static int
  1143. is_oid(Elem* pe, Ints** poid)
  1144. {
  1145. if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
  1146. *poid = pe->val.u.objidval;
  1147. return 1;
  1148. }
  1149. return 0;
  1150. }
  1151. static int
  1152. is_string(Elem* pe, char** pstring)
  1153. {
  1154. if(pe->tag.class == Universal) {
  1155. switch(pe->tag.num) {
  1156. case NumericString:
  1157. case PrintableString:
  1158. case TeletexString:
  1159. case VideotexString:
  1160. case IA5String:
  1161. case GraphicString:
  1162. case VisibleString:
  1163. case GeneralString:
  1164. case UniversalString:
  1165. case BMPString:
  1166. if(pe->val.tag == VString) {
  1167. *pstring = pe->val.u.stringval;
  1168. return 1;
  1169. }
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. static int
  1175. is_time(Elem* pe, char** ptime)
  1176. {
  1177. if(pe->tag.class == Universal
  1178. && (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
  1179. && pe->val.tag == VString) {
  1180. *ptime = pe->val.u.stringval;
  1181. return 1;
  1182. }
  1183. return 0;
  1184. }
  1185. /*
  1186. * malloc and return a new Bytes structure capable of
  1187. * holding len bytes. (len >= 0)
  1188. */
  1189. static Bytes*
  1190. newbytes(int len)
  1191. {
  1192. Bytes* ans;
  1193. ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
  1194. ans->len = len;
  1195. return ans;
  1196. }
  1197. /*
  1198. * newbytes(len), with data initialized from buf
  1199. */
  1200. static Bytes*
  1201. makebytes(uchar* buf, int len)
  1202. {
  1203. Bytes* ans;
  1204. ans = newbytes(len);
  1205. memmove(ans->data, buf, len);
  1206. return ans;
  1207. }
  1208. static void
  1209. freebytes(Bytes* b)
  1210. {
  1211. if(b != nil)
  1212. free(b);
  1213. }
  1214. /*
  1215. * Make a new Bytes, containing bytes of b1 followed by those of b2.
  1216. * Either b1 or b2 or both can be nil.
  1217. */
  1218. static Bytes*
  1219. catbytes(Bytes* b1, Bytes* b2)
  1220. {
  1221. Bytes* ans;
  1222. int n;
  1223. if(b1 == nil) {
  1224. if(b2 == nil)
  1225. ans = newbytes(0);
  1226. else
  1227. ans = makebytes(b2->data, b2->len);
  1228. }
  1229. else if(b2 == nil) {
  1230. ans = makebytes(b1->data, b1->len);
  1231. }
  1232. else {
  1233. n = b1->len + b2->len;
  1234. ans = newbytes(n);
  1235. ans->len = n;
  1236. memmove(ans->data, b1->data, b1->len);
  1237. memmove(ans->data+b1->len, b2->data, b2->len);
  1238. }
  1239. return ans;
  1240. }
  1241. /* len is number of ints */
  1242. static Ints*
  1243. newints(int len)
  1244. {
  1245. Ints* ans;
  1246. ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
  1247. ans->len = len;
  1248. return ans;
  1249. }
  1250. static Ints*
  1251. makeints(int* buf, int len)
  1252. {
  1253. Ints* ans;
  1254. ans = newints(len);
  1255. if(len > 0)
  1256. memmove(ans->data, buf, len*sizeof(int));
  1257. return ans;
  1258. }
  1259. static void
  1260. freeints(Ints* b)
  1261. {
  1262. if(b != nil)
  1263. free(b);
  1264. }
  1265. /* len is number of bytes */
  1266. static Bits*
  1267. newbits(int len)
  1268. {
  1269. Bits* ans;
  1270. ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
  1271. ans->len = len;
  1272. ans->unusedbits = 0;
  1273. return ans;
  1274. }
  1275. static Bits*
  1276. makebits(uchar* buf, int len, int unusedbits)
  1277. {
  1278. Bits* ans;
  1279. ans = newbits(len);
  1280. memmove(ans->data, buf, len);
  1281. ans->unusedbits = unusedbits;
  1282. return ans;
  1283. }
  1284. static void
  1285. freebits(Bits* b)
  1286. {
  1287. if(b != nil)
  1288. free(b);
  1289. }
  1290. static Elist*
  1291. mkel(Elem e, Elist* tail)
  1292. {
  1293. Elist* el;
  1294. el = (Elist*)emalloc(sizeof(Elist));
  1295. el->hd = e;
  1296. el->tl = tail;
  1297. return el;
  1298. }
  1299. static int
  1300. elistlen(Elist* el)
  1301. {
  1302. int ans = 0;
  1303. while(el != nil) {
  1304. ans++;
  1305. el = el->tl;
  1306. }
  1307. return ans;
  1308. }
  1309. /* Frees elist, but not fields inside values of constituent elems */
  1310. static void
  1311. freeelist(Elist* el)
  1312. {
  1313. Elist* next;
  1314. while(el != nil) {
  1315. next = el->tl;
  1316. free(el);
  1317. el = next;
  1318. }
  1319. }
  1320. /* free any allocated structures inside v (recursively freeing Elists) */
  1321. static void
  1322. freevalfields(Value* v)
  1323. {
  1324. Elist* el;
  1325. Elist* l;
  1326. if(v == nil)
  1327. return;
  1328. switch(v->tag) {
  1329. case VOctets:
  1330. freebytes(v->u.octetsval);
  1331. break;
  1332. case VBigInt:
  1333. freebytes(v->u.bigintval);
  1334. break;
  1335. case VReal:
  1336. freebytes(v->u.realval);
  1337. break;
  1338. case VOther:
  1339. freebytes(v->u.otherval);
  1340. break;
  1341. case VBitString:
  1342. freebits(v->u.bitstringval);
  1343. break;
  1344. case VObjId:
  1345. freeints(v->u.objidval);
  1346. break;
  1347. case VString:
  1348. if (v->u.stringval)
  1349. free(v->u.stringval);
  1350. break;
  1351. case VSeq:
  1352. el = v->u.seqval;
  1353. for(l = el; l != nil; l = l->tl)
  1354. freevalfields(&l->hd.val);
  1355. if (el)
  1356. freeelist(el);
  1357. break;
  1358. case VSet:
  1359. el = v->u.setval;
  1360. for(l = el; l != nil; l = l->tl)
  1361. freevalfields(&l->hd.val);
  1362. if (el)
  1363. freeelist(el);
  1364. break;
  1365. }
  1366. }
  1367. /* end of general ASN1 functions */
  1368. /*=============================================================*/
  1369. /*
  1370. * Decode and parse an X.509 Certificate, defined by this ASN1:
  1371. * Certificate ::= SEQUENCE {
  1372. * certificateInfo CertificateInfo,
  1373. * signatureAlgorithm AlgorithmIdentifier,
  1374. * signature BIT STRING }
  1375. *
  1376. * CertificateInfo ::= SEQUENCE {
  1377. * version [0] INTEGER DEFAULT v1 (0),
  1378. * serialNumber INTEGER,
  1379. * signature AlgorithmIdentifier,
  1380. * issuer Name,
  1381. * validity Validity,
  1382. * subject Name,
  1383. * subjectPublicKeyInfo SubjectPublicKeyInfo }
  1384. * (version v2 has two more fields, optional unique identifiers for
  1385. * issuer and subject; since we ignore these anyway, we won't parse them)
  1386. *
  1387. * Validity ::= SEQUENCE {
  1388. * notBefore UTCTime,
  1389. * notAfter UTCTime }
  1390. *
  1391. * SubjectPublicKeyInfo ::= SEQUENCE {
  1392. * algorithm AlgorithmIdentifier,
  1393. * subjectPublicKey BIT STRING }
  1394. *
  1395. * AlgorithmIdentifier ::= SEQUENCE {
  1396. * algorithm OBJECT IDENTIFER,
  1397. * parameters ANY DEFINED BY ALGORITHM OPTIONAL }
  1398. *
  1399. * Name ::= SEQUENCE OF RelativeDistinguishedName
  1400. *
  1401. * RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
  1402. *
  1403. * AttributeTypeAndValue ::= SEQUENCE {
  1404. * type OBJECT IDENTIFER,
  1405. * value DirectoryString }
  1406. * (selected attributes have these Object Ids:
  1407. * commonName {2 5 4 3}
  1408. * countryName {2 5 4 6}
  1409. * localityName {2 5 4 7}
  1410. * stateOrProvinceName {2 5 4 8}
  1411. * organizationName {2 5 4 10}
  1412. * organizationalUnitName {2 5 4 11}
  1413. * )
  1414. *
  1415. * DirectoryString ::= CHOICE {
  1416. * teletexString TeletexString,
  1417. * printableString PrintableString,
  1418. * universalString UniversalString }
  1419. *
  1420. * See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
  1421. *
  1422. * Not yet implemented:
  1423. * CertificateRevocationList ::= SIGNED SEQUENCE{
  1424. * signature AlgorithmIdentifier,
  1425. * issuer Name,
  1426. * lastUpdate UTCTime,
  1427. * nextUpdate UTCTime,
  1428. * revokedCertificates
  1429. * SEQUENCE OF CRLEntry OPTIONAL}
  1430. * CRLEntry ::= SEQUENCE{
  1431. * userCertificate SerialNumber,
  1432. * revocationDate UTCTime}
  1433. */
  1434. typedef struct CertX509 {
  1435. int serial;
  1436. char* issuer;
  1437. char* validity_start;
  1438. char* validity_end;
  1439. char* subject;
  1440. int publickey_alg;
  1441. Bytes* publickey;
  1442. int signature_alg;
  1443. Bytes* signature;
  1444. } CertX509;
  1445. /* Algorithm object-ids */
  1446. enum {
  1447. ALG_rsaEncryption,
  1448. ALG_md2WithRSAEncryption,
  1449. ALG_md4WithRSAEncryption,
  1450. ALG_md5WithRSAEncryption,
  1451. ALG_sha1WithRSAEncryption,
  1452. ALG_md5,
  1453. NUMALGS
  1454. };
  1455. typedef struct Ints7 {
  1456. int len;
  1457. int data[7];
  1458. } Ints7;
  1459. static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
  1460. static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
  1461. static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
  1462. static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
  1463. static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
  1464. static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
  1465. static Ints *alg_oid_tab[NUMALGS+1] = {
  1466. (Ints*)(void*)&oid_rsaEncryption,
  1467. (Ints*)(void*)&oid_md2WithRSAEncryption,
  1468. (Ints*)(void*)&oid_md4WithRSAEncryption,
  1469. (Ints*)(void*)&oid_md5WithRSAEncryption,
  1470. (Ints*)(void*)&oid_sha1WithRSAEncryption,
  1471. (Ints*)(void*)&oid_md5,
  1472. nil
  1473. };
  1474. static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, 0 };
  1475. static void
  1476. freecert(CertX509* c)
  1477. {
  1478. if (!c) return;
  1479. if(c->issuer != nil)
  1480. free(c->issuer);
  1481. if(c->validity_start != nil)
  1482. free(c->validity_start);
  1483. if(c->validity_end != nil)
  1484. free(c->validity_end);
  1485. if(c->subject != nil)
  1486. free(c->subject);
  1487. freebytes(c->publickey);
  1488. freebytes(c->signature);
  1489. }
  1490. /*
  1491. * Parse the Name ASN1 type.
  1492. * The sequence of RelativeDistinguishedName's gives a sort of pathname,
  1493. * from most general to most specific. Each element of the path can be
  1494. * one or more (but usually just one) attribute-value pair, such as
  1495. * countryName="US".
  1496. * We'll just form a "postal-style" address string by concatenating the elements
  1497. * from most specific to least specific, separated by commas.
  1498. * Return name-as-string (which must be freed by caller).
  1499. */
  1500. static char*
  1501. parse_name(Elem* e)
  1502. {
  1503. Elist* el;
  1504. Elem* es;
  1505. Elist* esetl;
  1506. Elem* eat;
  1507. Elist* eatl;
  1508. char* s;
  1509. enum { MAXPARTS = 100 };
  1510. char* parts[MAXPARTS];
  1511. int i;
  1512. int plen;
  1513. char* ans = nil;
  1514. if(!is_seq(e, &el))
  1515. goto errret;
  1516. i = 0;
  1517. plen = 0;
  1518. while(el != nil) {
  1519. es = &el->hd;
  1520. if(!is_set(es, &esetl))
  1521. goto errret;
  1522. while(esetl != nil) {
  1523. eat = &esetl->hd;
  1524. if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
  1525. goto errret;
  1526. if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
  1527. goto errret;
  1528. parts[i++] = s;
  1529. plen += strlen(s) + 2; /* room for ", " after */
  1530. esetl = esetl->tl;
  1531. }
  1532. el = el->tl;
  1533. }
  1534. if(i > 0) {
  1535. ans = (char*)emalloc(plen);
  1536. *ans = '\0';
  1537. while(--i >= 0) {
  1538. s = parts[i];
  1539. strcat(ans, s);
  1540. if(i > 0)
  1541. strcat(ans, ", ");
  1542. }
  1543. }
  1544. errret:
  1545. return ans;
  1546. }
  1547. /*
  1548. * Parse an AlgorithmIdentifer ASN1 type.
  1549. * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
  1550. * or -1 if not found.
  1551. * For now, ignore parameters, since none of our algorithms need them.
  1552. */
  1553. static int
  1554. parse_alg(Elem* e)
  1555. {
  1556. Elist* el;
  1557. Ints* oid;
  1558. if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
  1559. return -1;
  1560. return oid_lookup(oid, alg_oid_tab);
  1561. }
  1562. static CertX509*
  1563. decode_cert(Bytes* a)
  1564. {
  1565. int ok = 0;
  1566. int n;
  1567. CertX509* c = nil;
  1568. Elem ecert;
  1569. Elem* ecertinfo;
  1570. Elem* esigalg;
  1571. Elem* esig;
  1572. Elem* eserial;
  1573. Elem* eissuer;
  1574. Elem* evalidity;
  1575. Elem* esubj;
  1576. Elem* epubkey;
  1577. Elist* el;
  1578. Elist* elcert = nil;
  1579. Elist* elcertinfo = nil;
  1580. Elist* elvalidity = nil;
  1581. Elist* elpubkey = nil;
  1582. Bits* bits = nil;
  1583. Bytes* b;
  1584. Elem* e;
  1585. if(decode(a->data, a->len, &ecert) != ASN_OK)
  1586. goto errret;
  1587. c = (CertX509*)emalloc(sizeof(CertX509));
  1588. c->serial = -1;
  1589. c->issuer = nil;
  1590. c->validity_start = nil;
  1591. c->validity_end = nil;
  1592. c->subject = nil;
  1593. c->publickey_alg = -1;
  1594. c->publickey = nil;
  1595. c->signature_alg = -1;
  1596. c->signature = nil;
  1597. /* Certificate */
  1598. if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
  1599. goto errret;
  1600. ecertinfo = &elcert->hd;
  1601. el = elcert->tl;
  1602. esigalg = &el->hd;
  1603. c->signature_alg = parse_alg(esigalg);
  1604. el = el->tl;
  1605. esig = &el->hd;
  1606. /* Certificate Info */
  1607. if(!is_seq(ecertinfo, &elcertinfo))
  1608. goto errret;
  1609. n = elistlen(elcertinfo);
  1610. if(n < 6)
  1611. goto errret;
  1612. eserial =&elcertinfo->hd;
  1613. el = elcertinfo->tl;
  1614. /* check for optional version, marked by explicit context tag 0 */
  1615. if(eserial->tag.class == Context && eserial->tag.num == 0) {
  1616. eserial = &el->hd;
  1617. if(n < 7)
  1618. goto errret;
  1619. el = el->tl;
  1620. }
  1621. if(parse_alg(&el->hd) != c->signature_alg)
  1622. goto errret;
  1623. el = el->tl;
  1624. eissuer = &el->hd;
  1625. el = el->tl;
  1626. evalidity = &el->hd;
  1627. el = el->tl;
  1628. esubj = &el->hd;
  1629. el = el->tl;
  1630. epubkey = &el->hd;
  1631. if(!is_int(eserial, &c->serial)) {
  1632. if(!is_bigint(eserial, &b))
  1633. goto errret;
  1634. c->serial = -1; /* else we have to change cert struct */
  1635. }
  1636. c->issuer = parse_name(eissuer);
  1637. if(c->issuer == nil)
  1638. goto errret;
  1639. /* Validity */
  1640. if(!is_seq(evalidity, &elvalidity))
  1641. goto errret;
  1642. if(elistlen(elvalidity) != 2)
  1643. goto errret;
  1644. e = &elvalidity->hd;
  1645. if(!is_time(e, &c->validity_start))
  1646. goto errret;
  1647. e->val.u.stringval = nil; /* string ownership transfer */
  1648. e = &elvalidity->tl->hd;
  1649. if(!is_time(e, &c->validity_end))
  1650. goto errret;
  1651. e->val.u.stringval = nil; /* string ownership transfer */
  1652. /* resume CertificateInfo */
  1653. c->subject = parse_name(esubj);
  1654. if(c->subject == nil)
  1655. goto errret;
  1656. /* SubjectPublicKeyInfo */
  1657. if(!is_seq(epubkey, &elpubkey))
  1658. goto errret;
  1659. if(elistlen(elpubkey) != 2)
  1660. goto errret;
  1661. c->publickey_alg = parse_alg(&elpubkey->hd);
  1662. if(c->publickey_alg < 0)
  1663. goto errret;
  1664. if(!is_bitstring(&elpubkey->tl->hd, &bits))
  1665. goto errret;
  1666. if(bits->unusedbits != 0)
  1667. goto errret;
  1668. c->publickey = makebytes(bits->data, bits->len);
  1669. /*resume Certificate */
  1670. if(c->signature_alg < 0)
  1671. goto errret;
  1672. if(!is_bitstring(esig, &bits))
  1673. goto errret;
  1674. c->signature = makebytes(bits->data, bits->len);
  1675. ok = 1;
  1676. errret:
  1677. freevalfields(&ecert.val); /* recurses through lists, too */
  1678. if(!ok){
  1679. freecert(c);
  1680. c = nil;
  1681. }
  1682. return c;
  1683. }
  1684. /*
  1685. * RSAPublickKey :: SEQUENCE {
  1686. * modulus INTEGER,
  1687. * publicExponent INTEGER
  1688. * }
  1689. */
  1690. static RSApub*
  1691. decode_rsapubkey(Bytes* a)
  1692. {
  1693. Elem e;
  1694. Elist *el;
  1695. mpint *mp;
  1696. RSApub* key;
  1697. key = rsapuballoc();
  1698. if(decode(a->data, a->len, &e) != ASN_OK)
  1699. goto errret;
  1700. if(!is_seq(&e, &el) || elistlen(el) != 2)
  1701. goto errret;
  1702. key->n = mp = asn1mpint(&el->hd);
  1703. if(mp == nil)
  1704. goto errret;
  1705. el = el->tl;
  1706. key->ek = mp = asn1mpint(&el->hd);
  1707. if(mp == nil)
  1708. goto errret;
  1709. return key;
  1710. errret:
  1711. rsapubfree(key);
  1712. return nil;
  1713. }
  1714. /*
  1715. * RSAPrivateKey ::= SEQUENCE {
  1716. * version Version,
  1717. * modulus INTEGER, -- n
  1718. * publicExponent INTEGER, -- e
  1719. * privateExponent INTEGER, -- d
  1720. * prime1 INTEGER, -- p
  1721. * prime2 INTEGER, -- q
  1722. * exponent1 INTEGER, -- d mod (p-1)
  1723. * exponent2 INTEGER, -- d mod (q-1)
  1724. * coefficient INTEGER -- (inverse of q) mod p }
  1725. */
  1726. static RSApriv*
  1727. decode_rsaprivkey(Bytes* a)
  1728. {
  1729. int version;
  1730. Elem e;
  1731. Elist *el;
  1732. mpint *mp;
  1733. RSApriv* key;
  1734. key = rsaprivalloc();
  1735. if(decode(a->data, a->len, &e) != ASN_OK)
  1736. goto errret;
  1737. if(!is_seq(&e, &el) || elistlen(el) != 9)
  1738. goto errret;
  1739. if(!is_int(&el->hd, &version) || version != 0)
  1740. goto errret;
  1741. el = el->tl;
  1742. key->pub.n = mp = asn1mpint(&el->hd);
  1743. if(mp == nil)
  1744. goto errret;
  1745. el = el->tl;
  1746. key->pub.ek = mp = asn1mpint(&el->hd);
  1747. if(mp == nil)
  1748. goto errret;
  1749. el = el->tl;
  1750. key->dk = mp = asn1mpint(&el->hd);
  1751. if(mp == nil)
  1752. goto errret;
  1753. el = el->tl;
  1754. key->q = mp = asn1mpint(&el->hd);
  1755. if(mp == nil)
  1756. goto errret;
  1757. el = el->tl;
  1758. key->p = mp = asn1mpint(&el->hd);
  1759. if(mp == nil)
  1760. goto errret;
  1761. el = el->tl;
  1762. key->kq = mp = asn1mpint(&el->hd);
  1763. if(mp == nil)
  1764. goto errret;
  1765. el = el->tl;
  1766. key->kp = mp = asn1mpint(&el->hd);
  1767. if(mp == nil)
  1768. goto errret;
  1769. el = el->tl;
  1770. key->c2 = mp = asn1mpint(&el->hd);
  1771. if(mp == nil)
  1772. goto errret;
  1773. return key;
  1774. errret:
  1775. rsaprivfree(key);
  1776. return nil;
  1777. }
  1778. /*
  1779. * DSAPrivateKey ::= SEQUENCE{
  1780. * version Version,
  1781. * p INTEGER,
  1782. * q INTEGER,
  1783. * g INTEGER, -- alpha
  1784. * pub_key INTEGER, -- key
  1785. * priv_key INTEGER, -- secret
  1786. * }
  1787. */
  1788. static DSApriv*
  1789. decode_dsaprivkey(Bytes* a)
  1790. {
  1791. int version;
  1792. Elem e;
  1793. Elist *el;
  1794. mpint *mp;
  1795. DSApriv* key;
  1796. key = dsaprivalloc();
  1797. if(decode(a->data, a->len, &e) != ASN_OK)
  1798. goto errret;
  1799. if(!is_seq(&e, &el) || elistlen(el) != 6)
  1800. goto errret;
  1801. version=-1;
  1802. if(!is_int(&el->hd, &version) || version != 0)
  1803. {
  1804. fprint(2, "version %d\n", version);
  1805. goto errret;
  1806. }
  1807. el = el->tl;
  1808. key->pub.p = mp = asn1mpint(&el->hd);
  1809. if(mp == nil)
  1810. goto errret;
  1811. el = el->tl;
  1812. key->pub.q = mp = asn1mpint(&el->hd);
  1813. if(mp == nil)
  1814. goto errret;
  1815. el = el->tl;
  1816. key->pub.alpha = mp = asn1mpint(&el->hd);
  1817. if(mp == nil)
  1818. goto errret;
  1819. el = el->tl;
  1820. key->pub.key = mp = asn1mpint(&el->hd);
  1821. if(mp == nil)
  1822. goto errret;
  1823. el = el->tl;
  1824. key->secret = mp = asn1mpint(&el->hd);
  1825. if(mp == nil)
  1826. goto errret;
  1827. return key;
  1828. errret:
  1829. dsaprivfree(key);
  1830. return nil;
  1831. }
  1832. static mpint*
  1833. asn1mpint(Elem *e)
  1834. {
  1835. Bytes *b;
  1836. mpint *mp;
  1837. int v;
  1838. if(is_int(e, &v))
  1839. return itomp(v, nil);
  1840. if(is_bigint(e, &b)) {
  1841. mp = betomp(b->data, b->len, nil);
  1842. freebytes(b);
  1843. return mp;
  1844. }
  1845. return nil;
  1846. }
  1847. static mpint*
  1848. pkcs1pad(Bytes *b, mpint *modulus)
  1849. {
  1850. int n = (mpsignif(modulus)+7)/8;
  1851. int pm1, i;
  1852. uchar *p;
  1853. mpint *mp;
  1854. pm1 = n - 1 - b->len;
  1855. p = (uchar*)emalloc(n);
  1856. p[0] = 0;
  1857. p[1] = 1;
  1858. for(i = 2; i < pm1; i++)
  1859. p[i] = 0xFF;
  1860. p[pm1] = 0;
  1861. memcpy(&p[pm1+1], b->data, b->len);
  1862. mp = betomp(p, n, nil);
  1863. free(p);
  1864. return mp;
  1865. }
  1866. RSApriv*
  1867. asn1toRSApriv(uchar *kd, int kn)
  1868. {
  1869. Bytes *b;
  1870. RSApriv *key;
  1871. b = makebytes(kd, kn);
  1872. key = decode_rsaprivkey(b);
  1873. freebytes(b);
  1874. return key;
  1875. }
  1876. DSApriv*
  1877. asn1toDSApriv(uchar *kd, int kn)
  1878. {
  1879. Bytes *b;
  1880. DSApriv *key;
  1881. b = makebytes(kd, kn);
  1882. key = decode_dsaprivkey(b);
  1883. freebytes(b);
  1884. return key;
  1885. }
  1886. /*
  1887. * digest(CertificateInfo)
  1888. * Our ASN.1 library doesn't return pointers into the original
  1889. * data array, so we need to do a little hand decoding.
  1890. */
  1891. static void
  1892. digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
  1893. {
  1894. uchar *info, *p, *pend;
  1895. ulong infolen;
  1896. int isconstr, length;
  1897. Tag tag;
  1898. Elem elem;
  1899. p = cert->data;
  1900. pend = cert->data + cert->len;
  1901. if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
  1902. tag.class != Universal || tag.num != SEQUENCE ||
  1903. length_decode(&p, pend, &length) != ASN_OK ||
  1904. p+length > pend ||
  1905. p+length < p)
  1906. return;
  1907. info = p;
  1908. if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
  1909. return;
  1910. infolen = p - info;
  1911. (*digestfun)(info, infolen, digest, nil);
  1912. }
  1913. static char*
  1914. verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
  1915. {
  1916. Elem e;
  1917. Elist *el;
  1918. Bytes *digest;
  1919. uchar *pkcs1buf, *buf;
  1920. int buflen;
  1921. mpint *pkcs1;
  1922. int nlen;
  1923. /* one less than the byte length of the modulus */
  1924. nlen = (mpsignif(pk->n)-1)/8;
  1925. /* see 9.2.1 of rfc2437 */
  1926. pkcs1 = betomp(signature->data, signature->len, nil);
  1927. mpexp(pkcs1, pk->ek, pk->n, pkcs1);
  1928. pkcs1buf = nil;
  1929. buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
  1930. buf = pkcs1buf;
  1931. if(buflen != nlen || buf[0] != 1)
  1932. return "expected 1";
  1933. buf++;
  1934. while(buf[0] == 0xff)
  1935. buf++;
  1936. if(buf[0] != 0)
  1937. return "expected 0";
  1938. buf++;
  1939. buflen -= buf-pkcs1buf;
  1940. if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
  1941. !is_octetstring(&el->tl->hd, &digest))
  1942. return "signature parse error";
  1943. *psigalg = &el->hd;
  1944. if(memcmp(digest->data, edigest, digest->len) == 0)
  1945. return nil;
  1946. return "digests did not match";
  1947. }
  1948. RSApub*
  1949. X509toRSApub(uchar *cert, int ncert, char *name, int nname)
  1950. {
  1951. char *e;
  1952. Bytes *b;
  1953. CertX509 *c;
  1954. RSApub *pk;
  1955. b = makebytes(cert, ncert);
  1956. c = decode_cert(b);
  1957. freebytes(b);
  1958. if(c == nil)
  1959. return nil;
  1960. if(name != nil && c->subject != nil){
  1961. e = strchr(c->subject, ',');
  1962. if(e != nil)
  1963. *e = 0; /* take just CN part of Distinguished Name */
  1964. strncpy(name, c->subject, nname);
  1965. }
  1966. pk = decode_rsapubkey(c->publickey);
  1967. freecert(c);
  1968. return pk;
  1969. }
  1970. char*
  1971. X509verify(uchar *cert, int ncert, RSApub *pk)
  1972. {
  1973. char *e;
  1974. Bytes *b;
  1975. CertX509 *c;
  1976. uchar digest[SHA1dlen];
  1977. Elem *sigalg;
  1978. b = makebytes(cert, ncert);
  1979. c = decode_cert(b);
  1980. if(c != nil)
  1981. digest_certinfo(b, digestalg[c->signature_alg], digest);
  1982. freebytes(b);
  1983. if(c == nil)
  1984. return "cannot decode cert";
  1985. e = verify_signature(c->signature, pk, digest, &sigalg);
  1986. freecert(c);
  1987. return e;
  1988. }
  1989. /* ------- Elem constructors ---------- */
  1990. static Elem
  1991. Null(void)
  1992. {
  1993. Elem e;
  1994. e.tag.class = Universal;
  1995. e.tag.num = NULLTAG;
  1996. e.val.tag = VNull;
  1997. return e;
  1998. }
  1999. static Elem
  2000. mkint(int j)
  2001. {
  2002. Elem e;
  2003. e.tag.class = Universal;
  2004. e.tag.num = INTEGER;
  2005. e.val.tag = VInt;
  2006. e.val.u.intval = j;
  2007. return e;
  2008. }
  2009. static Elem
  2010. mkbigint(mpint *p)
  2011. {
  2012. Elem e;
  2013. uchar *buf;
  2014. int buflen;
  2015. e.tag.class = Universal;
  2016. e.tag.num = INTEGER;
  2017. e.val.tag = VBigInt;
  2018. buflen = mptobe(p, nil, 0, &buf);
  2019. e.val.u.bigintval = makebytes(buf, buflen);
  2020. free(buf);
  2021. return e;
  2022. }
  2023. static Elem
  2024. mkstring(char *s)
  2025. {
  2026. Elem e;
  2027. e.tag.class = Universal;
  2028. e.tag.num = IA5String;
  2029. e.val.tag = VString;
  2030. e.val.u.stringval = estrdup(s);
  2031. return e;
  2032. }
  2033. static Elem
  2034. mkoctet(uchar *buf, int buflen)
  2035. {
  2036. Elem e;
  2037. e.tag.class = Universal;
  2038. e.tag.num = OCTET_STRING;
  2039. e.val.tag = VOctets;
  2040. e.val.u.octetsval = makebytes(buf, buflen);
  2041. return e;
  2042. }
  2043. static Elem
  2044. mkbits(uchar *buf, int buflen)
  2045. {
  2046. Elem e;
  2047. e.tag.class = Universal;
  2048. e.tag.num = BIT_STRING;
  2049. e.val.tag = VBitString;
  2050. e.val.u.bitstringval = makebits(buf, buflen, 0);
  2051. return e;
  2052. }
  2053. static Elem
  2054. mkutc(long t)
  2055. {
  2056. Elem e;
  2057. char utc[50];
  2058. Tm *tm = gmtime(t);
  2059. e.tag.class = Universal;
  2060. e.tag.num = UTCTime;
  2061. e.val.tag = VString;
  2062. snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
  2063. tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
  2064. e.val.u.stringval = estrdup(utc);
  2065. return e;
  2066. }
  2067. static Elem
  2068. mkoid(Ints *oid)
  2069. {
  2070. Elem e;
  2071. e.tag.class = Universal;
  2072. e.tag.num = OBJECT_ID;
  2073. e.val.tag = VObjId;
  2074. e.val.u.objidval = makeints(oid->data, oid->len);
  2075. return e;
  2076. }
  2077. static Elem
  2078. mkseq(Elist *el)
  2079. {
  2080. Elem e;
  2081. e.tag.class = Universal;
  2082. e.tag.num = SEQUENCE;
  2083. e.val.tag = VSeq;
  2084. e.val.u.seqval = el;
  2085. return e;
  2086. }
  2087. static Elem
  2088. mkset(Elist *el)
  2089. {
  2090. Elem e;
  2091. e.tag.class = Universal;
  2092. e.tag.num = SETOF;
  2093. e.val.tag = VSet;
  2094. e.val.u.setval = el;
  2095. return e;
  2096. }
  2097. static Elem
  2098. mkalg(int alg)
  2099. {
  2100. return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
  2101. }
  2102. typedef struct Ints7pref {
  2103. int len;
  2104. int data[7];
  2105. char prefix[4];
  2106. } Ints7pref;
  2107. Ints7pref DN_oid[] = {
  2108. {4, 2, 5, 4, 6, 0, 0, 0, "C="},
  2109. {4, 2, 5, 4, 8, 0, 0, 0, "ST="},
  2110. {4, 2, 5, 4, 7, 0, 0, 0, "L="},
  2111. {4, 2, 5, 4, 10, 0, 0, 0, "O="},
  2112. {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
  2113. {4, 2, 5, 4, 3, 0, 0, 0, "CN="},
  2114. {7, 1,2,840,113549,1,9,1, "E="},
  2115. };
  2116. static Elem
  2117. mkname(Ints7pref *oid, char *subj)
  2118. {
  2119. return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
  2120. }
  2121. static Elem
  2122. mkDN(char *dn)
  2123. {
  2124. int i, j, nf;
  2125. char *f[20], *prefix, *d2 = estrdup(dn);
  2126. Elist* el = nil;
  2127. nf = tokenize(d2, f, nelem(f));
  2128. for(i=nf-1; i>=0; i--){
  2129. for(j=0; j<nelem(DN_oid); j++){
  2130. prefix = DN_oid[j].prefix;
  2131. if(strncmp(f[i],prefix,strlen(prefix))==0){
  2132. el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
  2133. break;
  2134. }
  2135. }
  2136. }
  2137. free(d2);
  2138. return mkseq(el);
  2139. }
  2140. uchar*
  2141. X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
  2142. {
  2143. int serial = 0;
  2144. uchar *cert = nil;
  2145. RSApub *pk = rsaprivtopub(priv);
  2146. Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
  2147. Elem e, certinfo, issuer, subject, pubkey, validity, sig;
  2148. uchar digest[MD5dlen], *buf;
  2149. int buflen;
  2150. mpint *pkcs1;
  2151. e.val.tag = VInt; /* so freevalfields at errret is no-op */
  2152. issuer = mkDN(subj);
  2153. subject = mkDN(subj);
  2154. pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
  2155. if(encode(pubkey, &pkbytes) != ASN_OK)
  2156. goto errret;
  2157. freevalfields(&pubkey.val);
  2158. pubkey = mkseq(
  2159. mkel(mkalg(ALG_rsaEncryption),
  2160. mkel(mkbits(pkbytes->data, pkbytes->len),
  2161. nil)));
  2162. freebytes(pkbytes);
  2163. validity = mkseq(
  2164. mkel(mkutc(valid[0]),
  2165. mkel(mkutc(valid[1]),
  2166. nil)));
  2167. certinfo = mkseq(
  2168. mkel(mkint(serial),
  2169. mkel(mkalg(ALG_md5WithRSAEncryption),
  2170. mkel(issuer,
  2171. mkel(validity,
  2172. mkel(subject,
  2173. mkel(pubkey,
  2174. nil)))))));
  2175. if(encode(certinfo, &certinfobytes) != ASN_OK)
  2176. goto errret;
  2177. md5(certinfobytes->data, certinfobytes->len, digest, 0);
  2178. freebytes(certinfobytes);
  2179. sig = mkseq(
  2180. mkel(mkalg(ALG_md5),
  2181. mkel(mkoctet(digest, MD5dlen),
  2182. nil)));
  2183. if(encode(sig, &sigbytes) != ASN_OK)
  2184. goto errret;
  2185. pkcs1 = pkcs1pad(sigbytes, pk->n);
  2186. freebytes(sigbytes);
  2187. rsadecrypt(priv, pkcs1, pkcs1);
  2188. buflen = mptobe(pkcs1, nil, 0, &buf);
  2189. mpfree(pkcs1);
  2190. e = mkseq(
  2191. mkel(certinfo,
  2192. mkel(mkalg(ALG_md5WithRSAEncryption),
  2193. mkel(mkbits(buf, buflen),
  2194. nil))));
  2195. free(buf);
  2196. if(encode(e, &certbytes) != ASN_OK)
  2197. goto errret;
  2198. if(certlen)
  2199. *certlen = certbytes->len;
  2200. cert = certbytes->data;
  2201. errret:
  2202. freevalfields(&e.val);
  2203. return cert;
  2204. }
  2205. uchar*
  2206. X509req(RSApriv *priv, char *subj, int *certlen)
  2207. {
  2208. /* RFC 2314, PKCS #10 Certification Request Syntax */
  2209. int version = 0;
  2210. uchar *cert = nil;
  2211. RSApub *pk = rsaprivtopub(priv);
  2212. Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
  2213. Elem e, certinfo, subject, pubkey, sig;
  2214. uchar digest[MD5dlen], *buf;
  2215. int buflen;
  2216. mpint *pkcs1;
  2217. e.val.tag = VInt; /* so freevalfields at errret is no-op */
  2218. subject = mkDN(subj);
  2219. pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
  2220. if(encode(pubkey, &pkbytes) != ASN_OK)
  2221. goto errret;
  2222. freevalfields(&pubkey.val);
  2223. pubkey = mkseq(
  2224. mkel(mkalg(ALG_rsaEncryption),
  2225. mkel(mkbits(pkbytes->data, pkbytes->len),
  2226. nil)));
  2227. freebytes(pkbytes);
  2228. certinfo = mkseq(
  2229. mkel(mkint(version),
  2230. mkel(subject,
  2231. mkel(pubkey,
  2232. nil))));
  2233. if(encode(certinfo, &certinfobytes) != ASN_OK)
  2234. goto errret;
  2235. md5(certinfobytes->data, certinfobytes->len, digest, 0);
  2236. freebytes(certinfobytes);
  2237. sig = mkseq(
  2238. mkel(mkalg(ALG_md5),
  2239. mkel(mkoctet(digest, MD5dlen),
  2240. nil)));
  2241. if(encode(sig, &sigbytes) != ASN_OK)
  2242. goto errret;
  2243. pkcs1 = pkcs1pad(sigbytes, pk->n);
  2244. freebytes(sigbytes);
  2245. rsadecrypt(priv, pkcs1, pkcs1);
  2246. buflen = mptobe(pkcs1, nil, 0, &buf);
  2247. mpfree(pkcs1);
  2248. e = mkseq(
  2249. mkel(certinfo,
  2250. mkel(mkalg(ALG_md5),
  2251. mkel(mkbits(buf, buflen),
  2252. nil))));
  2253. free(buf);
  2254. if(encode(e, &certbytes) != ASN_OK)
  2255. goto errret;
  2256. if(certlen)
  2257. *certlen = certbytes->len;
  2258. cert = certbytes->data;
  2259. errret:
  2260. freevalfields(&e.val);
  2261. return cert;
  2262. }
  2263. static char*
  2264. tagdump(Tag tag)
  2265. {
  2266. if(tag.class != Universal)
  2267. return smprint("class%d,num%d", tag.class, tag.num);
  2268. switch(tag.num){
  2269. case BOOLEAN: return "BOOLEAN"; break;
  2270. case INTEGER: return "INTEGER"; break;
  2271. case BIT_STRING: return "BIT STRING"; break;
  2272. case OCTET_STRING: return "OCTET STRING"; break;
  2273. case NULLTAG: return "NULLTAG"; break;
  2274. case OBJECT_ID: return "OID"; break;
  2275. case ObjectDescriptor: return "OBJECT_DES"; break;
  2276. case EXTERNAL: return "EXTERNAL"; break;
  2277. case REAL: return "REAL"; break;
  2278. case ENUMERATED: return "ENUMERATED"; break;
  2279. case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
  2280. case SEQUENCE: return "SEQUENCE"; break;
  2281. case SETOF: return "SETOF"; break;
  2282. case NumericString: return "NumericString"; break;
  2283. case PrintableString: return "PrintableString"; break;
  2284. case TeletexString: return "TeletexString"; break;
  2285. case VideotexString: return "VideotexString"; break;
  2286. case IA5String: return "IA5String"; break;
  2287. case UTCTime: return "UTCTime"; break;
  2288. case GeneralizedTime: return "GeneralizedTime"; break;
  2289. case GraphicString: return "GraphicString"; break;
  2290. case VisibleString: return "VisibleString"; break;
  2291. case GeneralString: return "GeneralString"; break;
  2292. case UniversalString: return "UniversalString"; break;
  2293. case BMPString: return "BMPString"; break;
  2294. default:
  2295. return smprint("Universal,num%d", tag.num);
  2296. }
  2297. }
  2298. static void
  2299. edump(Elem e)
  2300. {
  2301. Value v;
  2302. Elist *el;
  2303. int i;
  2304. print("%s{", tagdump(e.tag));
  2305. v = e.val;
  2306. switch(v.tag){
  2307. case VBool: print("Bool %d",v.u.boolval); break;
  2308. case VInt: print("Int %d",v.u.intval); break;
  2309. case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
  2310. case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
  2311. case VReal: print("Real..."); break;
  2312. case VOther: print("Other..."); break;
  2313. case VBitString: print("BitString..."); break;
  2314. case VNull:

Large files files are truncated, but you can click here to view the full file