x509.c 49 KB

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