x509.c 61 KB

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