x509.c 50 KB

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