x509.c 51 KB

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