x509.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762
  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_sha1WithRSAEncryptionOiw,
  1460. ALG_md5,
  1461. NUMALGS
  1462. };
  1463. typedef struct Ints7 {
  1464. int len;
  1465. int data[7];
  1466. } Ints7;
  1467. static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
  1468. static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
  1469. static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
  1470. static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
  1471. static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
  1472. static Ints7 oid_sha1WithRSAEncryptionOiw ={6, 1, 3, 14, 3, 2, 29 };
  1473. static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
  1474. static Ints *alg_oid_tab[NUMALGS+1] = {
  1475. (Ints*)&oid_rsaEncryption,
  1476. (Ints*)&oid_md2WithRSAEncryption,
  1477. (Ints*)&oid_md4WithRSAEncryption,
  1478. (Ints*)&oid_md5WithRSAEncryption,
  1479. (Ints*)&oid_sha1WithRSAEncryption,
  1480. (Ints*)&oid_sha1WithRSAEncryptionOiw,
  1481. (Ints*)&oid_md5,
  1482. nil
  1483. };
  1484. static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, sha1, md5, nil };
  1485. static void
  1486. freecert(CertX509* c)
  1487. {
  1488. if(!c) return;
  1489. if(c->issuer != nil)
  1490. free(c->issuer);
  1491. if(c->validity_start != nil)
  1492. free(c->validity_start);
  1493. if(c->validity_end != nil)
  1494. free(c->validity_end);
  1495. if(c->subject != nil)
  1496. free(c->subject);
  1497. freebytes(c->publickey);
  1498. freebytes(c->signature);
  1499. free(c);
  1500. }
  1501. /*
  1502. * Parse the Name ASN1 type.
  1503. * The sequence of RelativeDistinguishedName's gives a sort of pathname,
  1504. * from most general to most specific. Each element of the path can be
  1505. * one or more (but usually just one) attribute-value pair, such as
  1506. * countryName="US".
  1507. * We'll just form a "postal-style" address string by concatenating the elements
  1508. * from most specific to least specific, separated by commas.
  1509. * Return name-as-string (which must be freed by caller).
  1510. */
  1511. static char*
  1512. parse_name(Elem* e)
  1513. {
  1514. Elist* el;
  1515. Elem* es;
  1516. Elist* esetl;
  1517. Elem* eat;
  1518. Elist* eatl;
  1519. char* s;
  1520. enum { MAXPARTS = 100 };
  1521. char* parts[MAXPARTS];
  1522. int i;
  1523. int plen;
  1524. char* ans = nil;
  1525. if(!is_seq(e, &el))
  1526. goto errret;
  1527. i = 0;
  1528. plen = 0;
  1529. while(el != nil) {
  1530. es = &el->hd;
  1531. if(!is_set(es, &esetl))
  1532. goto errret;
  1533. while(esetl != nil) {
  1534. eat = &esetl->hd;
  1535. if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
  1536. goto errret;
  1537. if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
  1538. goto errret;
  1539. parts[i++] = s;
  1540. plen += strlen(s) + 2; /* room for ", " after */
  1541. esetl = esetl->tl;
  1542. }
  1543. el = el->tl;
  1544. }
  1545. if(i > 0) {
  1546. ans = (char*)emalloc(plen);
  1547. *ans = '\0';
  1548. while(--i >= 0) {
  1549. s = parts[i];
  1550. strcat(ans, s);
  1551. if(i > 0)
  1552. strcat(ans, ", ");
  1553. }
  1554. }
  1555. errret:
  1556. return ans;
  1557. }
  1558. /*
  1559. * Parse an AlgorithmIdentifer ASN1 type.
  1560. * Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
  1561. * or -1 if not found.
  1562. * For now, ignore parameters, since none of our algorithms need them.
  1563. */
  1564. static int
  1565. parse_alg(Elem* e)
  1566. {
  1567. Elist* el;
  1568. Ints* oid;
  1569. if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
  1570. return -1;
  1571. return oid_lookup(oid, alg_oid_tab);
  1572. }
  1573. static CertX509*
  1574. decode_cert(Bytes* a)
  1575. {
  1576. int ok = 0;
  1577. int n;
  1578. CertX509* c = nil;
  1579. Elem ecert;
  1580. Elem* ecertinfo;
  1581. Elem* esigalg;
  1582. Elem* esig;
  1583. Elem* eserial;
  1584. Elem* eissuer;
  1585. Elem* evalidity;
  1586. Elem* esubj;
  1587. Elem* epubkey;
  1588. Elist* el;
  1589. Elist* elcert = nil;
  1590. Elist* elcertinfo = nil;
  1591. Elist* elvalidity = nil;
  1592. Elist* elpubkey = nil;
  1593. Bits* bits = nil;
  1594. Bytes* b;
  1595. Elem* e;
  1596. if(decode(a->data, a->len, &ecert) != ASN_OK)
  1597. goto errret;
  1598. c = (CertX509*)emalloc(sizeof(CertX509));
  1599. c->serial = -1;
  1600. c->issuer = nil;
  1601. c->validity_start = nil;
  1602. c->validity_end = nil;
  1603. c->subject = nil;
  1604. c->publickey_alg = -1;
  1605. c->publickey = nil;
  1606. c->signature_alg = -1;
  1607. c->signature = nil;
  1608. /* Certificate */
  1609. if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
  1610. goto errret;
  1611. ecertinfo = &elcert->hd;
  1612. el = elcert->tl;
  1613. esigalg = &el->hd;
  1614. c->signature_alg = parse_alg(esigalg);
  1615. el = el->tl;
  1616. esig = &el->hd;
  1617. /* Certificate Info */
  1618. if(!is_seq(ecertinfo, &elcertinfo))
  1619. goto errret;
  1620. n = elistlen(elcertinfo);
  1621. if(n < 6)
  1622. goto errret;
  1623. eserial =&elcertinfo->hd;
  1624. el = elcertinfo->tl;
  1625. /* check for optional version, marked by explicit context tag 0 */
  1626. if(eserial->tag.class == Context && eserial->tag.num == 0) {
  1627. eserial = &el->hd;
  1628. if(n < 7)
  1629. goto errret;
  1630. el = el->tl;
  1631. }
  1632. if(parse_alg(&el->hd) != c->signature_alg)
  1633. goto errret;
  1634. el = el->tl;
  1635. eissuer = &el->hd;
  1636. el = el->tl;
  1637. evalidity = &el->hd;
  1638. el = el->tl;
  1639. esubj = &el->hd;
  1640. el = el->tl;
  1641. epubkey = &el->hd;
  1642. if(!is_int(eserial, &c->serial)) {
  1643. if(!is_bigint(eserial, &b))
  1644. goto errret;
  1645. c->serial = -1; /* else we have to change cert struct */
  1646. }
  1647. c->issuer = parse_name(eissuer);
  1648. if(c->issuer == nil)
  1649. goto errret;
  1650. /* Validity */
  1651. if(!is_seq(evalidity, &elvalidity))
  1652. goto errret;
  1653. if(elistlen(elvalidity) != 2)
  1654. goto errret;
  1655. e = &elvalidity->hd;
  1656. if(!is_time(e, &c->validity_start))
  1657. goto errret;
  1658. e->val.u.stringval = nil; /* string ownership transfer */
  1659. e = &elvalidity->tl->hd;
  1660. if(!is_time(e, &c->validity_end))
  1661. goto errret;
  1662. e->val.u.stringval = nil; /* string ownership transfer */
  1663. /* resume CertificateInfo */
  1664. c->subject = parse_name(esubj);
  1665. if(c->subject == nil)
  1666. goto errret;
  1667. /* SubjectPublicKeyInfo */
  1668. if(!is_seq(epubkey, &elpubkey))
  1669. goto errret;
  1670. if(elistlen(elpubkey) != 2)
  1671. goto errret;
  1672. c->publickey_alg = parse_alg(&elpubkey->hd);
  1673. if(c->publickey_alg < 0)
  1674. goto errret;
  1675. if(!is_bitstring(&elpubkey->tl->hd, &bits))
  1676. goto errret;
  1677. if(bits->unusedbits != 0)
  1678. goto errret;
  1679. c->publickey = makebytes(bits->data, bits->len);
  1680. /*resume Certificate */
  1681. if(c->signature_alg < 0)
  1682. goto errret;
  1683. if(!is_bitstring(esig, &bits))
  1684. goto errret;
  1685. c->signature = makebytes(bits->data, bits->len);
  1686. ok = 1;
  1687. errret:
  1688. freevalfields(&ecert.val); /* recurses through lists, too */
  1689. if(!ok){
  1690. freecert(c);
  1691. c = nil;
  1692. }
  1693. return c;
  1694. }
  1695. /*
  1696. * RSAPublickKey :: SEQUENCE {
  1697. * modulus INTEGER,
  1698. * publicExponent INTEGER
  1699. * }
  1700. */
  1701. static RSApub*
  1702. decode_rsapubkey(Bytes* a)
  1703. {
  1704. Elem e;
  1705. Elist *el, *l;
  1706. mpint *mp;
  1707. RSApub* key;
  1708. l = nil;
  1709. key = rsapuballoc();
  1710. if(decode(a->data, a->len, &e) != ASN_OK)
  1711. goto errret;
  1712. if(!is_seq(&e, &el) || elistlen(el) != 2)
  1713. goto errret;
  1714. l = el;
  1715. key->n = mp = asn1mpint(&el->hd);
  1716. if(mp == nil)
  1717. goto errret;
  1718. el = el->tl;
  1719. key->ek = mp = asn1mpint(&el->hd);
  1720. if(mp == nil)
  1721. goto errret;
  1722. if(l != nil)
  1723. freeelist(l);
  1724. return key;
  1725. errret:
  1726. if(l != nil)
  1727. freeelist(l);
  1728. rsapubfree(key);
  1729. return nil;
  1730. }
  1731. /*
  1732. * RSAPrivateKey ::= SEQUENCE {
  1733. * version Version,
  1734. * modulus INTEGER, -- n
  1735. * publicExponent INTEGER, -- e
  1736. * privateExponent INTEGER, -- d
  1737. * prime1 INTEGER, -- p
  1738. * prime2 INTEGER, -- q
  1739. * exponent1 INTEGER, -- d mod (p-1)
  1740. * exponent2 INTEGER, -- d mod (q-1)
  1741. * coefficient INTEGER -- (inverse of q) mod p }
  1742. */
  1743. static RSApriv*
  1744. decode_rsaprivkey(Bytes* a)
  1745. {
  1746. int version;
  1747. Elem e;
  1748. Elist *el;
  1749. mpint *mp;
  1750. RSApriv* key;
  1751. key = rsaprivalloc();
  1752. if(decode(a->data, a->len, &e) != ASN_OK)
  1753. goto errret;
  1754. if(!is_seq(&e, &el) || elistlen(el) != 9)
  1755. goto errret;
  1756. if(!is_int(&el->hd, &version) || version != 0)
  1757. goto errret;
  1758. el = el->tl;
  1759. key->pub.n = mp = asn1mpint(&el->hd);
  1760. if(mp == nil)
  1761. goto errret;
  1762. el = el->tl;
  1763. key->pub.ek = mp = asn1mpint(&el->hd);
  1764. if(mp == nil)
  1765. goto errret;
  1766. el = el->tl;
  1767. key->dk = mp = asn1mpint(&el->hd);
  1768. if(mp == nil)
  1769. goto errret;
  1770. el = el->tl;
  1771. key->q = mp = asn1mpint(&el->hd);
  1772. if(mp == nil)
  1773. goto errret;
  1774. el = el->tl;
  1775. key->p = mp = asn1mpint(&el->hd);
  1776. if(mp == nil)
  1777. goto errret;
  1778. el = el->tl;
  1779. key->kq = mp = asn1mpint(&el->hd);
  1780. if(mp == nil)
  1781. goto errret;
  1782. el = el->tl;
  1783. key->kp = mp = asn1mpint(&el->hd);
  1784. if(mp == nil)
  1785. goto errret;
  1786. el = el->tl;
  1787. key->c2 = mp = asn1mpint(&el->hd);
  1788. if(mp == nil)
  1789. goto errret;
  1790. return key;
  1791. errret:
  1792. rsaprivfree(key);
  1793. return nil;
  1794. }
  1795. /*
  1796. * DSAPrivateKey ::= SEQUENCE{
  1797. * version Version,
  1798. * p INTEGER,
  1799. * q INTEGER,
  1800. * g INTEGER, -- alpha
  1801. * pub_key INTEGER, -- key
  1802. * priv_key INTEGER, -- secret
  1803. * }
  1804. */
  1805. static DSApriv*
  1806. decode_dsaprivkey(Bytes* a)
  1807. {
  1808. int version;
  1809. Elem e;
  1810. Elist *el;
  1811. mpint *mp;
  1812. DSApriv* key;
  1813. key = dsaprivalloc();
  1814. if(decode(a->data, a->len, &e) != ASN_OK)
  1815. goto errret;
  1816. if(!is_seq(&e, &el) || elistlen(el) != 6)
  1817. goto errret;
  1818. version = -1;
  1819. if(!is_int(&el->hd, &version) || version != 0)
  1820. {
  1821. fprint(2, "version %d\n", version);
  1822. goto errret;
  1823. }
  1824. el = el->tl;
  1825. key->pub.p = mp = asn1mpint(&el->hd);
  1826. if(mp == nil)
  1827. goto errret;
  1828. el = el->tl;
  1829. key->pub.q = mp = asn1mpint(&el->hd);
  1830. if(mp == nil)
  1831. goto errret;
  1832. el = el->tl;
  1833. key->pub.alpha = mp = asn1mpint(&el->hd);
  1834. if(mp == nil)
  1835. goto errret;
  1836. el = el->tl;
  1837. key->pub.key = mp = asn1mpint(&el->hd);
  1838. if(mp == nil)
  1839. goto errret;
  1840. el = el->tl;
  1841. key->secret = mp = asn1mpint(&el->hd);
  1842. if(mp == nil)
  1843. goto errret;
  1844. return key;
  1845. errret:
  1846. dsaprivfree(key);
  1847. return nil;
  1848. }
  1849. static mpint*
  1850. asn1mpint(Elem *e)
  1851. {
  1852. Bytes *b;
  1853. mpint *mp;
  1854. int v;
  1855. if(is_int(e, &v))
  1856. return itomp(v, nil);
  1857. if(is_bigint(e, &b)) {
  1858. mp = betomp(b->data, b->len, nil);
  1859. freebytes(b);
  1860. return mp;
  1861. }
  1862. return nil;
  1863. }
  1864. static mpint*
  1865. pkcs1pad(Bytes *b, mpint *modulus)
  1866. {
  1867. int n = (mpsignif(modulus)+7)/8;
  1868. int pm1, i;
  1869. uchar *p;
  1870. mpint *mp;
  1871. pm1 = n - 1 - b->len;
  1872. p = (uchar*)emalloc(n);
  1873. p[0] = 0;
  1874. p[1] = 1;
  1875. for(i = 2; i < pm1; i++)
  1876. p[i] = 0xFF;
  1877. p[pm1] = 0;
  1878. memcpy(&p[pm1+1], b->data, b->len);
  1879. mp = betomp(p, n, nil);
  1880. free(p);
  1881. return mp;
  1882. }
  1883. RSApriv*
  1884. asn1toRSApriv(uchar *kd, int kn)
  1885. {
  1886. Bytes *b;
  1887. RSApriv *key;
  1888. b = makebytes(kd, kn);
  1889. key = decode_rsaprivkey(b);
  1890. freebytes(b);
  1891. return key;
  1892. }
  1893. DSApriv*
  1894. asn1toDSApriv(uchar *kd, int kn)
  1895. {
  1896. Bytes *b;
  1897. DSApriv *key;
  1898. b = makebytes(kd, kn);
  1899. key = decode_dsaprivkey(b);
  1900. freebytes(b);
  1901. return key;
  1902. }
  1903. /*
  1904. * digest(CertificateInfo)
  1905. * Our ASN.1 library doesn't return pointers into the original
  1906. * data array, so we need to do a little hand decoding.
  1907. */
  1908. static void
  1909. digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
  1910. {
  1911. uchar *info, *p, *pend;
  1912. ulong infolen;
  1913. int isconstr, length;
  1914. Tag tag;
  1915. Elem elem;
  1916. p = cert->data;
  1917. pend = cert->data + cert->len;
  1918. if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
  1919. tag.class != Universal || tag.num != SEQUENCE ||
  1920. length_decode(&p, pend, &length) != ASN_OK ||
  1921. p+length > pend ||
  1922. p+length < p)
  1923. return;
  1924. info = p;
  1925. if(ber_decode(&p, pend, &elem) != ASN_OK)
  1926. return;
  1927. freevalfields(&elem.val);
  1928. if(elem.tag.num != SEQUENCE)
  1929. return;
  1930. infolen = p - info;
  1931. (*digestfun)(info, infolen, digest, nil);
  1932. }
  1933. static char*
  1934. verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
  1935. {
  1936. Elem e;
  1937. Elist *el;
  1938. Bytes *digest;
  1939. uchar *pkcs1buf, *buf;
  1940. int buflen;
  1941. mpint *pkcs1;
  1942. int nlen;
  1943. char *err;
  1944. err = nil;
  1945. pkcs1buf = nil;
  1946. /* one less than the byte length of the modulus */
  1947. nlen = (mpsignif(pk->n)-1)/8;
  1948. /* see 9.2.1 of rfc2437 */
  1949. pkcs1 = betomp(signature->data, signature->len, nil);
  1950. mpexp(pkcs1, pk->ek, pk->n, pkcs1);
  1951. buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
  1952. buf = pkcs1buf;
  1953. if(buflen != nlen || buf[0] != 1) {
  1954. err = "expected 1";
  1955. goto end;
  1956. }
  1957. buf++;
  1958. while(buf[0] == 0xff)
  1959. buf++;
  1960. if(buf[0] != 0) {
  1961. err = "expected 0";
  1962. goto end;
  1963. }
  1964. buf++;
  1965. buflen -= buf-pkcs1buf;
  1966. if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
  1967. !is_octetstring(&el->tl->hd, &digest)) {
  1968. err = "signature parse error";
  1969. goto end;
  1970. }
  1971. *psigalg = &el->hd;
  1972. if(memcmp(digest->data, edigest, digest->len) == 0)
  1973. goto end;
  1974. err = "digests did not match";
  1975. end:
  1976. if(pkcs1 != nil)
  1977. mpfree(pkcs1);
  1978. if(pkcs1buf != nil)
  1979. free(pkcs1buf);
  1980. return err;
  1981. }
  1982. RSApub*
  1983. X509toRSApub(uchar *cert, int ncert, char *name, int nname)
  1984. {
  1985. char *e;
  1986. Bytes *b;
  1987. CertX509 *c;
  1988. RSApub *pk;
  1989. b = makebytes(cert, ncert);
  1990. c = decode_cert(b);
  1991. freebytes(b);
  1992. if(c == nil)
  1993. return nil;
  1994. if(name != nil && c->subject != nil){
  1995. e = strchr(c->subject, ',');
  1996. if(e != nil)
  1997. *e = 0; /* take just CN part of Distinguished Name */
  1998. strncpy(name, c->subject, nname);
  1999. }
  2000. pk = decode_rsapubkey(c->publickey);
  2001. freecert(c);
  2002. return pk;
  2003. }
  2004. int
  2005. getalgo(Elem *e)
  2006. {
  2007. Value *v;
  2008. Elist *el;
  2009. int a;
  2010. if((a = parse_alg(e)) >= 0)
  2011. return a;
  2012. v = &e->val;
  2013. if(v->tag == VSeq){
  2014. print("Seq\n");
  2015. for(el = v->u.seqval; el!=nil; el = el->tl){
  2016. if((a = getalgo(&el->hd)) >= 0)
  2017. return a;
  2018. }
  2019. }
  2020. return -1;
  2021. }
  2022. static void edump(Elem e);
  2023. RSApub*
  2024. asn1toRSApub(uchar *der, int nder)
  2025. {
  2026. Elem e;
  2027. Elist *el, *l;
  2028. int n;
  2029. Bits *b;
  2030. RSApub *key;
  2031. mpint *mp;
  2032. if(decode(der, nder, &e) != ASN_OK){
  2033. print("didn't parse\n");
  2034. return nil;
  2035. }
  2036. if(!is_seq(&e, &el)){
  2037. print("no seq");
  2038. return nil;
  2039. }
  2040. if((n = elistlen(el)) != 2){
  2041. print("bad length %d\n", n);
  2042. return nil;
  2043. }
  2044. if((n = getalgo(&el->hd)) < 0){
  2045. print("no algo\n");
  2046. return nil;
  2047. }
  2048. if(n != 0){
  2049. print("cant do algorithm %d\n", n);
  2050. return nil;
  2051. }
  2052. if(!is_bitstring(&el->tl->hd, &b)){
  2053. print("no bits\n");
  2054. return nil;
  2055. }
  2056. if(decode(b->data, b->len, &e) != ASN_OK){
  2057. print("no second decode\n");
  2058. return nil;
  2059. }
  2060. if(!is_seq(&e, &el)){
  2061. print("no second seq\n");
  2062. return nil;
  2063. }
  2064. if(elistlen(el) != 2){
  2065. print("no second length\n");
  2066. return nil;
  2067. }
  2068. key = rsapuballoc();
  2069. l = el;
  2070. key->n = mp = asn1mpint(&el->hd);
  2071. if(mp == nil)
  2072. goto errret;
  2073. el = el->tl;
  2074. key->ek = mp = asn1mpint(&el->hd);
  2075. if(mp == nil)
  2076. goto errret;
  2077. if(l != nil)
  2078. freeelist(l);
  2079. return key;
  2080. errret:
  2081. if(l != nil)
  2082. freeelist(l);
  2083. rsapubfree(key);
  2084. return nil;
  2085. }
  2086. char*
  2087. X509verify(uchar *cert, int ncert, RSApub *pk)
  2088. {
  2089. char *e;
  2090. Bytes *b;
  2091. CertX509 *c;
  2092. uchar digest[SHA1dlen];
  2093. Elem *sigalg;
  2094. b = makebytes(cert, ncert);
  2095. c = decode_cert(b);
  2096. if(c != nil)
  2097. digest_certinfo(b, digestalg[c->signature_alg], digest);
  2098. freebytes(b);
  2099. if(c == nil)
  2100. return "cannot decode cert";
  2101. e = verify_signature(c->signature, pk, digest, &sigalg);
  2102. freecert(c);
  2103. return e;
  2104. }
  2105. /* ------- Elem constructors ---------- */
  2106. static Elem
  2107. Null(void)
  2108. {
  2109. Elem e;
  2110. e.tag.class = Universal;
  2111. e.tag.num = NULLTAG;
  2112. e.val.tag = VNull;
  2113. return e;
  2114. }
  2115. static Elem
  2116. mkint(int j)
  2117. {
  2118. Elem e;
  2119. e.tag.class = Universal;
  2120. e.tag.num = INTEGER;
  2121. e.val.tag = VInt;
  2122. e.val.u.intval = j;
  2123. return e;
  2124. }
  2125. static Elem
  2126. mkbigint(mpint *p)
  2127. {
  2128. Elem e;
  2129. uchar *buf;
  2130. int buflen;
  2131. e.tag.class = Universal;
  2132. e.tag.num = INTEGER;
  2133. e.val.tag = VBigInt;
  2134. buflen = mptobe(p, nil, 0, &buf);
  2135. e.val.u.bigintval = makebytes(buf, buflen);
  2136. free(buf);
  2137. return e;
  2138. }
  2139. static Elem
  2140. mkstring(char *s)
  2141. {
  2142. Elem e;
  2143. e.tag.class = Universal;
  2144. e.tag.num = IA5String;
  2145. e.val.tag = VString;
  2146. e.val.u.stringval = estrdup(s);
  2147. return e;
  2148. }
  2149. static Elem
  2150. mkoctet(uchar *buf, int buflen)
  2151. {
  2152. Elem e;
  2153. e.tag.class = Universal;
  2154. e.tag.num = OCTET_STRING;
  2155. e.val.tag = VOctets;
  2156. e.val.u.octetsval = makebytes(buf, buflen);
  2157. return e;
  2158. }
  2159. static Elem
  2160. mkbits(uchar *buf, int buflen)
  2161. {
  2162. Elem e;
  2163. e.tag.class = Universal;
  2164. e.tag.num = BIT_STRING;
  2165. e.val.tag = VBitString;
  2166. e.val.u.bitstringval = makebits(buf, buflen, 0);
  2167. return e;
  2168. }
  2169. static Elem
  2170. mkutc(long t)
  2171. {
  2172. Elem e;
  2173. char utc[50];
  2174. Tm *tm = gmtime(t);
  2175. e.tag.class = Universal;
  2176. e.tag.num = UTCTime;
  2177. e.val.tag = VString;
  2178. snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
  2179. tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
  2180. e.val.u.stringval = estrdup(utc);
  2181. return e;
  2182. }
  2183. static Elem
  2184. mkoid(Ints *oid)
  2185. {
  2186. Elem e;
  2187. e.tag.class = Universal;
  2188. e.tag.num = OBJECT_ID;
  2189. e.val.tag = VObjId;
  2190. e.val.u.objidval = makeints(oid->data, oid->len);
  2191. return e;
  2192. }
  2193. static Elem
  2194. mkseq(Elist *el)
  2195. {
  2196. Elem e;
  2197. e.tag.class = Universal;
  2198. e.tag.num = SEQUENCE;
  2199. e.val.tag = VSeq;
  2200. e.val.u.seqval = el;
  2201. return e;
  2202. }
  2203. static Elem
  2204. mkset(Elist *el)
  2205. {
  2206. Elem e;
  2207. e.tag.class = Universal;
  2208. e.tag.num = SETOF;
  2209. e.val.tag = VSet;
  2210. e.val.u.setval = el;
  2211. return e;
  2212. }
  2213. static Elem
  2214. mkalg(int alg)
  2215. {
  2216. return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
  2217. }
  2218. typedef struct Ints7pref {
  2219. int len;
  2220. int data[7];
  2221. char prefix[4];
  2222. } Ints7pref;
  2223. Ints7pref DN_oid[] = {
  2224. {4, 2, 5, 4, 6, 0, 0, 0, "C="},
  2225. {4, 2, 5, 4, 8, 0, 0, 0, "ST="},
  2226. {4, 2, 5, 4, 7, 0, 0, 0, "L="},
  2227. {4, 2, 5, 4, 10, 0, 0, 0, "O="},
  2228. {4, 2, 5, 4, 11, 0, 0, 0, "OU="},
  2229. {4, 2, 5, 4, 3, 0, 0, 0, "CN="},
  2230. {7, 1,2,840,113549,1,9,1, "E="},
  2231. };
  2232. static Elem
  2233. mkname(Ints7pref *oid, char *subj)
  2234. {
  2235. return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
  2236. }
  2237. static Elem
  2238. mkDN(char *dn)
  2239. {
  2240. int i, j, nf;
  2241. char *f[20], *prefix, *d2 = estrdup(dn);
  2242. Elist* el = nil;
  2243. nf = tokenize(d2, f, nelem(f));
  2244. for(i=nf-1; i>=0; i--){
  2245. for(j=0; j<nelem(DN_oid); j++){
  2246. prefix = DN_oid[j].prefix;
  2247. if(strncmp(f[i],prefix,strlen(prefix))==0){
  2248. el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
  2249. break;
  2250. }
  2251. }
  2252. }
  2253. free(d2);
  2254. return mkseq(el);
  2255. }
  2256. uchar*
  2257. RSApubtoasn1(RSApub *pub, int *keylen)
  2258. {
  2259. Elem pubkey;
  2260. Bytes *pkbytes;
  2261. uchar *key;
  2262. key = nil;
  2263. pubkey = mkseq(mkel(mkbigint(pub->n),mkel(mkint(mptoi(pub->ek)),nil)));
  2264. if(encode(pubkey, &pkbytes) != ASN_OK)
  2265. goto errret;
  2266. freevalfields(&pubkey.val);
  2267. pubkey = mkseq(
  2268. mkel(mkalg(ALG_rsaEncryption),
  2269. mkel(mkbits(pkbytes->data, pkbytes->len),
  2270. nil)));
  2271. freebytes(pkbytes);
  2272. if(encode(pubkey, &pkbytes) != ASN_OK)
  2273. goto errret;
  2274. if(keylen)
  2275. *keylen = pkbytes->len;
  2276. key = malloc(pkbytes->len);
  2277. memmove(key, pkbytes->data, pkbytes->len);
  2278. free(pkbytes);
  2279. errret:
  2280. freevalfields(&pubkey.val);
  2281. return key;
  2282. }
  2283. uchar*
  2284. X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
  2285. {
  2286. int serial = 0;
  2287. uchar *cert = nil;
  2288. RSApub *pk = rsaprivtopub(priv);
  2289. Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
  2290. Elem e, certinfo, issuer, subject, pubkey, validity, sig;
  2291. uchar digest[MD5dlen], *buf;
  2292. int buflen;
  2293. mpint *pkcs1;
  2294. e.val.tag = VInt; /* so freevalfields at errret is no-op */
  2295. issuer = mkDN(subj);
  2296. subject = mkDN(subj);
  2297. pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
  2298. if(encode(pubkey, &pkbytes) != ASN_OK)
  2299. goto errret;
  2300. freevalfields(&pubkey.val);
  2301. pubkey = mkseq(
  2302. mkel(mkalg(ALG_rsaEncryption),
  2303. mkel(mkbits(pkbytes->data, pkbytes->len),
  2304. nil)));
  2305. freebytes(pkbytes);
  2306. validity = mkseq(
  2307. mkel(mkutc(valid[0]),
  2308. mkel(mkutc(valid[1]),
  2309. nil)));
  2310. certinfo = mkseq(
  2311. mkel(mkint(serial),
  2312. mkel(mkalg(ALG_md5WithRSAEncryption),
  2313. mkel(issuer,
  2314. mkel(validity,
  2315. mkel(subject,
  2316. mkel(pubkey,
  2317. nil)))))));
  2318. if(encode(certinfo, &certinfobytes) != ASN_OK)
  2319. goto errret;
  2320. md5(certinfobytes->data, certinfobytes->len, digest, 0);
  2321. freebytes(certinfobytes);
  2322. sig = mkseq(
  2323. mkel(mkalg(ALG_md5),
  2324. mkel(mkoctet(digest, MD5dlen),
  2325. nil)));
  2326. if(encode(sig, &sigbytes) != ASN_OK)
  2327. goto errret;
  2328. pkcs1 = pkcs1pad(sigbytes, pk->n);
  2329. freebytes(sigbytes);
  2330. rsadecrypt(priv, pkcs1, pkcs1);
  2331. buflen = mptobe(pkcs1, nil, 0, &buf);
  2332. mpfree(pkcs1);
  2333. e = mkseq(
  2334. mkel(certinfo,
  2335. mkel(mkalg(ALG_md5WithRSAEncryption),
  2336. mkel(mkbits(buf, buflen),
  2337. nil))));
  2338. free(buf);
  2339. if(encode(e, &certbytes) != ASN_OK)
  2340. goto errret;
  2341. if(certlen)
  2342. *certlen = certbytes->len;
  2343. cert = certbytes->data;
  2344. errret:
  2345. freevalfields(&e.val);
  2346. return cert;
  2347. }
  2348. uchar*
  2349. X509req(RSApriv *priv, char *subj, int *certlen)
  2350. {
  2351. /* RFC 2314, PKCS #10 Certification Request Syntax */
  2352. int version = 0;
  2353. uchar *cert = nil;
  2354. RSApub *pk = rsaprivtopub(priv);
  2355. Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
  2356. Elem e, certinfo, subject, pubkey, sig;
  2357. uchar digest[MD5dlen], *buf;
  2358. int buflen;
  2359. mpint *pkcs1;
  2360. e.val.tag = VInt; /* so freevalfields at errret is no-op */
  2361. subject = mkDN(subj);
  2362. pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
  2363. if(encode(pubkey, &pkbytes) != ASN_OK)
  2364. goto errret;
  2365. freevalfields(&pubkey.val);
  2366. pubkey = mkseq(
  2367. mkel(mkalg(ALG_rsaEncryption),
  2368. mkel(mkbits(pkbytes->data, pkbytes->len),
  2369. nil)));
  2370. freebytes(pkbytes);
  2371. certinfo = mkseq(
  2372. mkel(mkint(version),
  2373. mkel(subject,
  2374. mkel(pubkey,
  2375. nil))));
  2376. if(encode(certinfo, &certinfobytes) != ASN_OK)
  2377. goto errret;
  2378. md5(certinfobytes->data, certinfobytes->len, digest, 0);
  2379. freebytes(certinfobytes);
  2380. sig = mkseq(
  2381. mkel(mkalg(ALG_md5),
  2382. mkel(mkoctet(digest, MD5dlen),
  2383. nil)));
  2384. if(encode(sig, &sigbytes) != ASN_OK)
  2385. goto errret;
  2386. pkcs1 = pkcs1pad(sigbytes, pk->n);
  2387. freebytes(sigbytes);
  2388. rsadecrypt(priv, pkcs1, pkcs1);
  2389. buflen = mptobe(pkcs1, nil, 0, &buf);
  2390. mpfree(pkcs1);
  2391. e = mkseq(
  2392. mkel(certinfo,
  2393. mkel(mkalg(ALG_md5),
  2394. mkel(mkbits(buf, buflen),
  2395. nil))));
  2396. free(buf);
  2397. if(encode(e, &certbytes) != ASN_OK)
  2398. goto errret;
  2399. if(certlen)
  2400. *certlen = certbytes->len;
  2401. cert = certbytes->data;
  2402. errret:
  2403. freevalfields(&e.val);
  2404. return cert;
  2405. }
  2406. static char*
  2407. tagdump(Tag tag)
  2408. {
  2409. if(tag.class != Universal)
  2410. return smprint("class%d,num%d", tag.class, tag.num);
  2411. switch(tag.num){
  2412. case BOOLEAN: return "BOOLEAN";
  2413. case INTEGER: return "INTEGER";
  2414. case BIT_STRING: return "BIT STRING";
  2415. case OCTET_STRING: return "OCTET STRING";
  2416. case NULLTAG: return "NULLTAG";
  2417. case OBJECT_ID: return "OID";
  2418. case ObjectDescriptor: return "OBJECT_DES";
  2419. case EXTERNAL: return "EXTERNAL";
  2420. case REAL: return "REAL";
  2421. case ENUMERATED: return "ENUMERATED";
  2422. case EMBEDDED_PDV: return "EMBEDDED PDV";
  2423. case SEQUENCE: return "SEQUENCE";
  2424. case SETOF: return "SETOF";
  2425. case UTF8String: return "UTF8String";
  2426. case NumericString: return "NumericString";
  2427. case PrintableString: return "PrintableString";
  2428. case TeletexString: return "TeletexString";
  2429. case VideotexString: return "VideotexString";
  2430. case IA5String: return "IA5String";
  2431. case UTCTime: return "UTCTime";
  2432. case GeneralizedTime: return "GeneralizedTime";
  2433. case GraphicString: return "GraphicString";
  2434. case VisibleString: return "VisibleString";
  2435. case GeneralString: return "GeneralString";
  2436. case UniversalString: return "UniversalString";
  2437. case BMPString: return "BMPString";
  2438. default:
  2439. return smprint("Universal,num%d", tag.num);
  2440. }
  2441. }
  2442. static void
  2443. edump(Elem e)
  2444. {
  2445. Value v;
  2446. Elist *el;
  2447. int i;
  2448. print("%s{", tagdump(e.tag));
  2449. v = e.val;
  2450. switch(v.tag){
  2451. case VBool: print("Bool %d",v.u.boolval); break;
  2452. case VInt: print("Int %d",v.u.intval); break;
  2453. case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
  2454. case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
  2455. case VReal: print("Real..."); break;
  2456. case VOther: print("Other..."); break;
  2457. case VBitString: print("BitString");
  2458. for(i = 0; i<v.u.bitstringval->len; i++)
  2459. print(" %02x", v.u.bitstringval->data[i]);
  2460. break;
  2461. case VNull: print("Null"); break;
  2462. case VEOC: print("EOC..."); break;
  2463. case VObjId: print("ObjId");
  2464. for(i = 0; i<v.u.objidval->len; i++)
  2465. print(" %d", v.u.objidval->data[i]);
  2466. break;
  2467. case VString: print("String \"%s\"",v.u.stringval); break;
  2468. case VSeq: print("Seq\n");
  2469. for(el = v.u.seqval; el!=nil; el = el->tl)
  2470. edump(el->hd);
  2471. break;
  2472. case VSet: print("Set\n");
  2473. for(el = v.u.setval; el!=nil; el = el->tl)
  2474. edump(el->hd);
  2475. break;
  2476. }
  2477. print("}\n");
  2478. }
  2479. void
  2480. asn1dump(uchar *der, int len)
  2481. {
  2482. Elem e;
  2483. if(decode(der, len, &e) != ASN_OK){
  2484. print("didn't parse\n");
  2485. exits("didn't parse");
  2486. }
  2487. edump(e);
  2488. }
  2489. void
  2490. X509dump(uchar *cert, int ncert)
  2491. {
  2492. char *e;
  2493. Bytes *b;
  2494. CertX509 *c;
  2495. RSApub *pk;
  2496. uchar digest[SHA1dlen];
  2497. Elem *sigalg;
  2498. print("begin X509dump\n");
  2499. b = makebytes(cert, ncert);
  2500. c = decode_cert(b);
  2501. if(c != nil)
  2502. digest_certinfo(b, digestalg[c->signature_alg], digest);
  2503. freebytes(b);
  2504. if(c == nil){
  2505. print("cannot decode cert");
  2506. return;
  2507. }
  2508. print("serial %d\n", c->serial);
  2509. print("issuer %s\n", c->issuer);
  2510. print("validity %s %s\n", c->validity_start, c->validity_end);
  2511. print("subject %s\n", c->subject);
  2512. pk = decode_rsapubkey(c->publickey);
  2513. print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
  2514. print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
  2515. e = verify_signature(c->signature, pk, digest, &sigalg);
  2516. if(e==nil){
  2517. e = "nil (meaning ok)";
  2518. print("sigalg=\n");
  2519. if(sigalg)
  2520. edump(*sigalg);
  2521. }
  2522. print("self-signed verify_signature returns: %s\n", e);
  2523. rsapubfree(pk);
  2524. freecert(c);
  2525. print("end X509dump\n");
  2526. }