x509.c 50 KB

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