apps.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  1. /* apps/apps.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* ====================================================================
  59. * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
  60. *
  61. * Redistribution and use in source and binary forms, with or without
  62. * modification, are permitted provided that the following conditions
  63. * are met:
  64. *
  65. * 1. Redistributions of source code must retain the above copyright
  66. * notice, this list of conditions and the following disclaimer.
  67. *
  68. * 2. Redistributions in binary form must reproduce the above copyright
  69. * notice, this list of conditions and the following disclaimer in
  70. * the documentation and/or other materials provided with the
  71. * distribution.
  72. *
  73. * 3. All advertising materials mentioning features or use of this
  74. * software must display the following acknowledgment:
  75. * "This product includes software developed by the OpenSSL Project
  76. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  77. *
  78. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  79. * endorse or promote products derived from this software without
  80. * prior written permission. For written permission, please contact
  81. * openssl-core@openssl.org.
  82. *
  83. * 5. Products derived from this software may not be called "OpenSSL"
  84. * nor may "OpenSSL" appear in their names without prior written
  85. * permission of the OpenSSL Project.
  86. *
  87. * 6. Redistributions of any form whatsoever must retain the following
  88. * acknowledgment:
  89. * "This product includes software developed by the OpenSSL Project
  90. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  91. *
  92. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  93. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  95. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  96. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  97. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  98. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  99. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  100. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  101. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  102. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  103. * OF THE POSSIBILITY OF SUCH DAMAGE.
  104. * ====================================================================
  105. *
  106. * This product includes cryptographic software written by Eric Young
  107. * (eay@cryptsoft.com). This product includes software written by Tim
  108. * Hudson (tjh@cryptsoft.com).
  109. *
  110. */
  111. #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
  112. /*
  113. * On VMS, you need to define this to get the declaration of fileno(). The
  114. * value 2 is to make sure no function defined in POSIX-2 is left undefined.
  115. */
  116. # define _POSIX_C_SOURCE 2
  117. #endif
  118. #include <stdio.h>
  119. #include <stdlib.h>
  120. #include <string.h>
  121. #include <sys/types.h>
  122. #include <ctype.h>
  123. #include <errno.h>
  124. #include <assert.h>
  125. #include <openssl/err.h>
  126. #include <openssl/x509.h>
  127. #include <openssl/x509v3.h>
  128. #include <openssl/pem.h>
  129. #include <openssl/pkcs12.h>
  130. #include <openssl/ui.h>
  131. #include <openssl/safestack.h>
  132. #ifndef OPENSSL_NO_ENGINE
  133. # include <openssl/engine.h>
  134. #endif
  135. #ifndef OPENSSL_NO_RSA
  136. # include <openssl/rsa.h>
  137. #endif
  138. #include <openssl/bn.h>
  139. #ifndef OPENSSL_NO_JPAKE
  140. # include <openssl/jpake.h>
  141. #endif
  142. #define NON_MAIN
  143. #include "apps.h"
  144. #undef NON_MAIN
  145. #ifdef _WIN32
  146. static int WIN32_rename(const char *from, const char *to);
  147. # define rename(from,to) WIN32_rename((from),(to))
  148. #endif
  149. typedef struct {
  150. const char *name;
  151. unsigned long flag;
  152. unsigned long mask;
  153. } NAME_EX_TBL;
  154. static UI_METHOD *ui_method = NULL;
  155. static int set_table_opts(unsigned long *flags, const char *arg,
  156. const NAME_EX_TBL * in_tbl);
  157. static int set_multi_opts(unsigned long *flags, const char *arg,
  158. const NAME_EX_TBL * in_tbl);
  159. #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
  160. /* Looks like this stuff is worth moving into separate function */
  161. static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
  162. const char *key_descrip, int format);
  163. #endif
  164. int app_init(long mesgwin);
  165. #ifdef undef /* never finished - probably never will be
  166. * :-) */
  167. int args_from_file(char *file, int *argc, char **argv[])
  168. {
  169. FILE *fp;
  170. int num, i;
  171. unsigned int len;
  172. static char *buf = NULL;
  173. static char **arg = NULL;
  174. char *p;
  175. fp = fopen(file, "r");
  176. if (fp == NULL)
  177. return (0);
  178. if (fseek(fp, 0, SEEK_END) == 0)
  179. len = ftell(fp), rewind(fp);
  180. else
  181. len = -1;
  182. if (len <= 0) {
  183. fclose(fp);
  184. return (0);
  185. }
  186. *argc = 0;
  187. *argv = NULL;
  188. if (buf != NULL)
  189. OPENSSL_free(buf);
  190. buf = (char *)OPENSSL_malloc(len + 1);
  191. if (buf == NULL)
  192. return (0);
  193. len = fread(buf, 1, len, fp);
  194. if (len <= 1)
  195. return (0);
  196. buf[len] = '\0';
  197. i = 0;
  198. for (p = buf; *p; p++)
  199. if (*p == '\n')
  200. i++;
  201. if (arg != NULL)
  202. OPENSSL_free(arg);
  203. arg = (char **)OPENSSL_malloc(sizeof(char *) * (i * 2));
  204. *argv = arg;
  205. num = 0;
  206. p = buf;
  207. for (;;) {
  208. if (!*p)
  209. break;
  210. if (*p == '#') { /* comment line */
  211. while (*p && (*p != '\n'))
  212. p++;
  213. continue;
  214. }
  215. /* else we have a line */
  216. *(arg++) = p;
  217. num++;
  218. while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
  219. p++;
  220. if (!*p)
  221. break;
  222. if (*p == '\n') {
  223. *(p++) = '\0';
  224. continue;
  225. }
  226. /* else it is a tab or space */
  227. p++;
  228. while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
  229. p++;
  230. if (!*p)
  231. break;
  232. if (*p == '\n') {
  233. p++;
  234. continue;
  235. }
  236. *(arg++) = p++;
  237. num++;
  238. while (*p && (*p != '\n'))
  239. p++;
  240. if (!*p)
  241. break;
  242. /* else *p == '\n' */
  243. *(p++) = '\0';
  244. }
  245. *argc = num;
  246. return (1);
  247. }
  248. #endif
  249. int str2fmt(char *s)
  250. {
  251. if (s == NULL)
  252. return FORMAT_UNDEF;
  253. if ((*s == 'D') || (*s == 'd'))
  254. return (FORMAT_ASN1);
  255. else if ((*s == 'T') || (*s == 't'))
  256. return (FORMAT_TEXT);
  257. else if ((*s == 'N') || (*s == 'n'))
  258. return (FORMAT_NETSCAPE);
  259. else if ((*s == 'S') || (*s == 's'))
  260. return (FORMAT_SMIME);
  261. else if ((*s == 'M') || (*s == 'm'))
  262. return (FORMAT_MSBLOB);
  263. else if ((*s == '1')
  264. || (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
  265. || (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
  266. return (FORMAT_PKCS12);
  267. else if ((*s == 'E') || (*s == 'e'))
  268. return (FORMAT_ENGINE);
  269. else if ((*s == 'H') || (*s == 'h'))
  270. return FORMAT_HTTP;
  271. else if ((*s == 'P') || (*s == 'p')) {
  272. if (s[1] == 'V' || s[1] == 'v')
  273. return FORMAT_PVK;
  274. else
  275. return (FORMAT_PEM);
  276. } else
  277. return (FORMAT_UNDEF);
  278. }
  279. #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
  280. void program_name(char *in, char *out, int size)
  281. {
  282. int i, n;
  283. char *p = NULL;
  284. n = strlen(in);
  285. /* find the last '/', '\' or ':' */
  286. for (i = n - 1; i > 0; i--) {
  287. if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':')) {
  288. p = &(in[i + 1]);
  289. break;
  290. }
  291. }
  292. if (p == NULL)
  293. p = in;
  294. n = strlen(p);
  295. # if defined(OPENSSL_SYS_NETWARE)
  296. /* strip off trailing .nlm if present. */
  297. if ((n > 4) && (p[n - 4] == '.') &&
  298. ((p[n - 3] == 'n') || (p[n - 3] == 'N')) &&
  299. ((p[n - 2] == 'l') || (p[n - 2] == 'L')) &&
  300. ((p[n - 1] == 'm') || (p[n - 1] == 'M')))
  301. n -= 4;
  302. # else
  303. /* strip off trailing .exe if present. */
  304. if ((n > 4) && (p[n - 4] == '.') &&
  305. ((p[n - 3] == 'e') || (p[n - 3] == 'E')) &&
  306. ((p[n - 2] == 'x') || (p[n - 2] == 'X')) &&
  307. ((p[n - 1] == 'e') || (p[n - 1] == 'E')))
  308. n -= 4;
  309. # endif
  310. if (n > size - 1)
  311. n = size - 1;
  312. for (i = 0; i < n; i++) {
  313. if ((p[i] >= 'A') && (p[i] <= 'Z'))
  314. out[i] = p[i] - 'A' + 'a';
  315. else
  316. out[i] = p[i];
  317. }
  318. out[n] = '\0';
  319. }
  320. #else
  321. # ifdef OPENSSL_SYS_VMS
  322. void program_name(char *in, char *out, int size)
  323. {
  324. char *p = in, *q;
  325. char *chars = ":]>";
  326. while (*chars != '\0') {
  327. q = strrchr(p, *chars);
  328. if (q > p)
  329. p = q + 1;
  330. chars++;
  331. }
  332. q = strrchr(p, '.');
  333. if (q == NULL)
  334. q = p + strlen(p);
  335. strncpy(out, p, size - 1);
  336. if (q - p >= size) {
  337. out[size - 1] = '\0';
  338. } else {
  339. out[q - p] = '\0';
  340. }
  341. }
  342. # else
  343. void program_name(char *in, char *out, int size)
  344. {
  345. char *p;
  346. p = strrchr(in, '/');
  347. if (p != NULL)
  348. p++;
  349. else
  350. p = in;
  351. BUF_strlcpy(out, p, size);
  352. }
  353. # endif
  354. #endif
  355. int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
  356. {
  357. int num, i;
  358. char *p;
  359. *argc = 0;
  360. *argv = NULL;
  361. i = 0;
  362. if (arg->count == 0) {
  363. arg->count = 20;
  364. arg->data = (char **)OPENSSL_malloc(sizeof(char *) * arg->count);
  365. if (arg->data == NULL)
  366. return 0;
  367. }
  368. for (i = 0; i < arg->count; i++)
  369. arg->data[i] = NULL;
  370. num = 0;
  371. p = buf;
  372. for (;;) {
  373. /* first scan over white space */
  374. if (!*p)
  375. break;
  376. while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
  377. p++;
  378. if (!*p)
  379. break;
  380. /* The start of something good :-) */
  381. if (num >= arg->count) {
  382. char **tmp_p;
  383. int tlen = arg->count + 20;
  384. tmp_p = (char **)OPENSSL_realloc(arg->data,
  385. sizeof(char *) * tlen);
  386. if (tmp_p == NULL)
  387. return 0;
  388. arg->data = tmp_p;
  389. arg->count = tlen;
  390. /* initialize newly allocated data */
  391. for (i = num; i < arg->count; i++)
  392. arg->data[i] = NULL;
  393. }
  394. arg->data[num++] = p;
  395. /* now look for the end of this */
  396. if ((*p == '\'') || (*p == '\"')) { /* scan for closing quote */
  397. i = *(p++);
  398. arg->data[num - 1]++; /* jump over quote */
  399. while (*p && (*p != i))
  400. p++;
  401. *p = '\0';
  402. } else {
  403. while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
  404. p++;
  405. if (*p == '\0')
  406. p--;
  407. else
  408. *p = '\0';
  409. }
  410. p++;
  411. }
  412. *argc = num;
  413. *argv = arg->data;
  414. return (1);
  415. }
  416. #ifndef APP_INIT
  417. int app_init(long mesgwin)
  418. {
  419. return (1);
  420. }
  421. #endif
  422. int dump_cert_text(BIO *out, X509 *x)
  423. {
  424. char *p;
  425. p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
  426. BIO_puts(out, "subject=");
  427. BIO_puts(out, p);
  428. OPENSSL_free(p);
  429. p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
  430. BIO_puts(out, "\nissuer=");
  431. BIO_puts(out, p);
  432. BIO_puts(out, "\n");
  433. OPENSSL_free(p);
  434. return 0;
  435. }
  436. static int ui_open(UI *ui)
  437. {
  438. return UI_method_get_opener(UI_OpenSSL())(ui);
  439. }
  440. static int ui_read(UI *ui, UI_STRING *uis)
  441. {
  442. if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
  443. && UI_get0_user_data(ui)) {
  444. switch (UI_get_string_type(uis)) {
  445. case UIT_PROMPT:
  446. case UIT_VERIFY:
  447. {
  448. const char *password =
  449. ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
  450. if (password && password[0] != '\0') {
  451. UI_set_result(ui, uis, password);
  452. return 1;
  453. }
  454. }
  455. default:
  456. break;
  457. }
  458. }
  459. return UI_method_get_reader(UI_OpenSSL())(ui, uis);
  460. }
  461. static int ui_write(UI *ui, UI_STRING *uis)
  462. {
  463. if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
  464. && UI_get0_user_data(ui)) {
  465. switch (UI_get_string_type(uis)) {
  466. case UIT_PROMPT:
  467. case UIT_VERIFY:
  468. {
  469. const char *password =
  470. ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
  471. if (password && password[0] != '\0')
  472. return 1;
  473. }
  474. default:
  475. break;
  476. }
  477. }
  478. return UI_method_get_writer(UI_OpenSSL())(ui, uis);
  479. }
  480. static int ui_close(UI *ui)
  481. {
  482. return UI_method_get_closer(UI_OpenSSL())(ui);
  483. }
  484. int setup_ui_method(void)
  485. {
  486. ui_method = UI_create_method("OpenSSL application user interface");
  487. UI_method_set_opener(ui_method, ui_open);
  488. UI_method_set_reader(ui_method, ui_read);
  489. UI_method_set_writer(ui_method, ui_write);
  490. UI_method_set_closer(ui_method, ui_close);
  491. return 0;
  492. }
  493. void destroy_ui_method(void)
  494. {
  495. if (ui_method) {
  496. UI_destroy_method(ui_method);
  497. ui_method = NULL;
  498. }
  499. }
  500. int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
  501. {
  502. UI *ui = NULL;
  503. int res = 0;
  504. const char *prompt_info = NULL;
  505. const char *password = NULL;
  506. PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
  507. if (cb_data) {
  508. if (cb_data->password)
  509. password = cb_data->password;
  510. if (cb_data->prompt_info)
  511. prompt_info = cb_data->prompt_info;
  512. }
  513. if (password) {
  514. res = strlen(password);
  515. if (res > bufsiz)
  516. res = bufsiz;
  517. memcpy(buf, password, res);
  518. return res;
  519. }
  520. ui = UI_new_method(ui_method);
  521. if (ui) {
  522. int ok = 0;
  523. char *buff = NULL;
  524. int ui_flags = 0;
  525. char *prompt = NULL;
  526. prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
  527. if (!prompt) {
  528. BIO_printf(bio_err, "Out of memory\n");
  529. UI_free(ui);
  530. return 0;
  531. }
  532. ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
  533. UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
  534. if (ok >= 0)
  535. ok = UI_add_input_string(ui, prompt, ui_flags, buf,
  536. PW_MIN_LENGTH, bufsiz - 1);
  537. if (ok >= 0 && verify) {
  538. buff = (char *)OPENSSL_malloc(bufsiz);
  539. if (!buff) {
  540. BIO_printf(bio_err, "Out of memory\n");
  541. UI_free(ui);
  542. OPENSSL_free(prompt);
  543. return 0;
  544. }
  545. ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
  546. PW_MIN_LENGTH, bufsiz - 1, buf);
  547. }
  548. if (ok >= 0)
  549. do {
  550. ok = UI_process(ui);
  551. }
  552. while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
  553. if (buff) {
  554. OPENSSL_cleanse(buff, (unsigned int)bufsiz);
  555. OPENSSL_free(buff);
  556. }
  557. if (ok >= 0)
  558. res = strlen(buf);
  559. if (ok == -1) {
  560. BIO_printf(bio_err, "User interface error\n");
  561. ERR_print_errors(bio_err);
  562. OPENSSL_cleanse(buf, (unsigned int)bufsiz);
  563. res = 0;
  564. }
  565. if (ok == -2) {
  566. BIO_printf(bio_err, "aborted!\n");
  567. OPENSSL_cleanse(buf, (unsigned int)bufsiz);
  568. res = 0;
  569. }
  570. UI_free(ui);
  571. OPENSSL_free(prompt);
  572. }
  573. return res;
  574. }
  575. static char *app_get_pass(BIO *err, char *arg, int keepbio);
  576. int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
  577. {
  578. int same;
  579. if (!arg2 || !arg1 || strcmp(arg1, arg2))
  580. same = 0;
  581. else
  582. same = 1;
  583. if (arg1) {
  584. *pass1 = app_get_pass(err, arg1, same);
  585. if (!*pass1)
  586. return 0;
  587. } else if (pass1)
  588. *pass1 = NULL;
  589. if (arg2) {
  590. *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
  591. if (!*pass2)
  592. return 0;
  593. } else if (pass2)
  594. *pass2 = NULL;
  595. return 1;
  596. }
  597. static char *app_get_pass(BIO *err, char *arg, int keepbio)
  598. {
  599. char *tmp, tpass[APP_PASS_LEN];
  600. static BIO *pwdbio = NULL;
  601. int i;
  602. if (!strncmp(arg, "pass:", 5))
  603. return BUF_strdup(arg + 5);
  604. if (!strncmp(arg, "env:", 4)) {
  605. tmp = getenv(arg + 4);
  606. if (!tmp) {
  607. BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
  608. return NULL;
  609. }
  610. return BUF_strdup(tmp);
  611. }
  612. if (!keepbio || !pwdbio) {
  613. if (!strncmp(arg, "file:", 5)) {
  614. pwdbio = BIO_new_file(arg + 5, "r");
  615. if (!pwdbio) {
  616. BIO_printf(err, "Can't open file %s\n", arg + 5);
  617. return NULL;
  618. }
  619. #if !defined(_WIN32)
  620. /*
  621. * Under _WIN32, which covers even Win64 and CE, file
  622. * descriptors referenced by BIO_s_fd are not inherited
  623. * by child process and therefore below is not an option.
  624. * It could have been an option if bss_fd.c was operating
  625. * on real Windows descriptors, such as those obtained
  626. * with CreateFile.
  627. */
  628. } else if (!strncmp(arg, "fd:", 3)) {
  629. BIO *btmp;
  630. i = atoi(arg + 3);
  631. if (i >= 0)
  632. pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
  633. if ((i < 0) || !pwdbio) {
  634. BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
  635. return NULL;
  636. }
  637. /*
  638. * Can't do BIO_gets on an fd BIO so add a buffering BIO
  639. */
  640. btmp = BIO_new(BIO_f_buffer());
  641. pwdbio = BIO_push(btmp, pwdbio);
  642. #endif
  643. } else if (!strcmp(arg, "stdin")) {
  644. pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
  645. if (!pwdbio) {
  646. BIO_printf(err, "Can't open BIO for stdin\n");
  647. return NULL;
  648. }
  649. } else {
  650. BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
  651. return NULL;
  652. }
  653. }
  654. i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
  655. if (keepbio != 1) {
  656. BIO_free_all(pwdbio);
  657. pwdbio = NULL;
  658. }
  659. if (i <= 0) {
  660. BIO_printf(err, "Error reading password from BIO\n");
  661. return NULL;
  662. }
  663. tmp = strchr(tpass, '\n');
  664. if (tmp)
  665. *tmp = 0;
  666. return BUF_strdup(tpass);
  667. }
  668. int add_oid_section(BIO *err, CONF *conf)
  669. {
  670. char *p;
  671. STACK_OF(CONF_VALUE) *sktmp;
  672. CONF_VALUE *cnf;
  673. int i;
  674. if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
  675. ERR_clear_error();
  676. return 1;
  677. }
  678. if (!(sktmp = NCONF_get_section(conf, p))) {
  679. BIO_printf(err, "problem loading oid section %s\n", p);
  680. return 0;
  681. }
  682. for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
  683. cnf = sk_CONF_VALUE_value(sktmp, i);
  684. if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
  685. BIO_printf(err, "problem creating object %s=%s\n",
  686. cnf->name, cnf->value);
  687. return 0;
  688. }
  689. }
  690. return 1;
  691. }
  692. static int load_pkcs12(BIO *err, BIO *in, const char *desc,
  693. pem_password_cb *pem_cb, void *cb_data,
  694. EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
  695. {
  696. const char *pass;
  697. char tpass[PEM_BUFSIZE];
  698. int len, ret = 0;
  699. PKCS12 *p12;
  700. p12 = d2i_PKCS12_bio(in, NULL);
  701. if (p12 == NULL) {
  702. BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
  703. goto die;
  704. }
  705. /* See if an empty password will do */
  706. if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
  707. pass = "";
  708. else {
  709. if (!pem_cb)
  710. pem_cb = (pem_password_cb *)password_callback;
  711. len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
  712. if (len < 0) {
  713. BIO_printf(err, "Passpharse callback error for %s\n", desc);
  714. goto die;
  715. }
  716. if (len < PEM_BUFSIZE)
  717. tpass[len] = 0;
  718. if (!PKCS12_verify_mac(p12, tpass, len)) {
  719. BIO_printf(err,
  720. "Mac verify error (wrong password?) in PKCS12 file for %s\n",
  721. desc);
  722. goto die;
  723. }
  724. pass = tpass;
  725. }
  726. ret = PKCS12_parse(p12, pass, pkey, cert, ca);
  727. die:
  728. if (p12)
  729. PKCS12_free(p12);
  730. return ret;
  731. }
  732. int load_cert_crl_http(const char *url, BIO *err,
  733. X509 **pcert, X509_CRL **pcrl)
  734. {
  735. char *host = NULL, *port = NULL, *path = NULL;
  736. BIO *bio = NULL;
  737. OCSP_REQ_CTX *rctx = NULL;
  738. int use_ssl, rv = 0;
  739. if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
  740. goto err;
  741. if (use_ssl) {
  742. if (err)
  743. BIO_puts(err, "https not supported\n");
  744. goto err;
  745. }
  746. bio = BIO_new_connect(host);
  747. if (!bio || !BIO_set_conn_port(bio, port))
  748. goto err;
  749. rctx = OCSP_REQ_CTX_new(bio, 1024);
  750. if (!rctx)
  751. goto err;
  752. if (!OCSP_REQ_CTX_http(rctx, "GET", path))
  753. goto err;
  754. if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
  755. goto err;
  756. if (pcert) {
  757. do {
  758. rv = X509_http_nbio(rctx, pcert);
  759. }
  760. while (rv == -1);
  761. } else {
  762. do {
  763. rv = X509_CRL_http_nbio(rctx, pcrl);
  764. } while (rv == -1);
  765. }
  766. err:
  767. if (host)
  768. OPENSSL_free(host);
  769. if (path)
  770. OPENSSL_free(path);
  771. if (port)
  772. OPENSSL_free(port);
  773. if (bio)
  774. BIO_free_all(bio);
  775. if (rctx)
  776. OCSP_REQ_CTX_free(rctx);
  777. if (rv != 1) {
  778. if (bio && err)
  779. BIO_printf(bio_err, "Error loading %s from %s\n",
  780. pcert ? "certificate" : "CRL", url);
  781. ERR_print_errors(bio_err);
  782. }
  783. return rv;
  784. }
  785. X509 *load_cert(BIO *err, const char *file, int format,
  786. const char *pass, ENGINE *e, const char *cert_descrip)
  787. {
  788. X509 *x = NULL;
  789. BIO *cert;
  790. if (format == FORMAT_HTTP) {
  791. load_cert_crl_http(file, err, &x, NULL);
  792. return x;
  793. }
  794. if ((cert = BIO_new(BIO_s_file())) == NULL) {
  795. ERR_print_errors(err);
  796. goto end;
  797. }
  798. if (file == NULL) {
  799. #ifdef _IONBF
  800. # ifndef OPENSSL_NO_SETVBUF_IONBF
  801. setvbuf(stdin, NULL, _IONBF, 0);
  802. # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
  803. #endif
  804. BIO_set_fp(cert, stdin, BIO_NOCLOSE);
  805. } else {
  806. if (BIO_read_filename(cert, file) <= 0) {
  807. BIO_printf(err, "Error opening %s %s\n", cert_descrip, file);
  808. ERR_print_errors(err);
  809. goto end;
  810. }
  811. }
  812. if (format == FORMAT_ASN1)
  813. x = d2i_X509_bio(cert, NULL);
  814. else if (format == FORMAT_NETSCAPE) {
  815. NETSCAPE_X509 *nx;
  816. nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
  817. if (nx == NULL)
  818. goto end;
  819. if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
  820. nx->header->length) != 0)) {
  821. NETSCAPE_X509_free(nx);
  822. BIO_printf(err, "Error reading header on certificate\n");
  823. goto end;
  824. }
  825. x = nx->cert;
  826. nx->cert = NULL;
  827. NETSCAPE_X509_free(nx);
  828. } else if (format == FORMAT_PEM)
  829. x = PEM_read_bio_X509_AUX(cert, NULL,
  830. (pem_password_cb *)password_callback, NULL);
  831. else if (format == FORMAT_PKCS12) {
  832. if (!load_pkcs12(err, cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
  833. goto end;
  834. } else {
  835. BIO_printf(err, "bad input format specified for %s\n", cert_descrip);
  836. goto end;
  837. }
  838. end:
  839. if (x == NULL) {
  840. BIO_printf(err, "unable to load certificate\n");
  841. ERR_print_errors(err);
  842. }
  843. if (cert != NULL)
  844. BIO_free(cert);
  845. return (x);
  846. }
  847. X509_CRL *load_crl(const char *infile, int format)
  848. {
  849. X509_CRL *x = NULL;
  850. BIO *in = NULL;
  851. if (format == FORMAT_HTTP) {
  852. load_cert_crl_http(infile, bio_err, NULL, &x);
  853. return x;
  854. }
  855. in = BIO_new(BIO_s_file());
  856. if (in == NULL) {
  857. ERR_print_errors(bio_err);
  858. goto end;
  859. }
  860. if (infile == NULL)
  861. BIO_set_fp(in, stdin, BIO_NOCLOSE);
  862. else {
  863. if (BIO_read_filename(in, infile) <= 0) {
  864. perror(infile);
  865. goto end;
  866. }
  867. }
  868. if (format == FORMAT_ASN1)
  869. x = d2i_X509_CRL_bio(in, NULL);
  870. else if (format == FORMAT_PEM)
  871. x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
  872. else {
  873. BIO_printf(bio_err, "bad input format specified for input crl\n");
  874. goto end;
  875. }
  876. if (x == NULL) {
  877. BIO_printf(bio_err, "unable to load CRL\n");
  878. ERR_print_errors(bio_err);
  879. goto end;
  880. }
  881. end:
  882. BIO_free(in);
  883. return (x);
  884. }
  885. EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
  886. const char *pass, ENGINE *e, const char *key_descrip)
  887. {
  888. BIO *key = NULL;
  889. EVP_PKEY *pkey = NULL;
  890. PW_CB_DATA cb_data;
  891. cb_data.password = pass;
  892. cb_data.prompt_info = file;
  893. if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
  894. BIO_printf(err, "no keyfile specified\n");
  895. goto end;
  896. }
  897. #ifndef OPENSSL_NO_ENGINE
  898. if (format == FORMAT_ENGINE) {
  899. if (!e)
  900. BIO_printf(err, "no engine specified\n");
  901. else {
  902. pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
  903. if (!pkey) {
  904. BIO_printf(err, "cannot load %s from engine\n", key_descrip);
  905. ERR_print_errors(err);
  906. }
  907. }
  908. goto end;
  909. }
  910. #endif
  911. key = BIO_new(BIO_s_file());
  912. if (key == NULL) {
  913. ERR_print_errors(err);
  914. goto end;
  915. }
  916. if (file == NULL && maybe_stdin) {
  917. #ifdef _IONBF
  918. # ifndef OPENSSL_NO_SETVBUF_IONBF
  919. setvbuf(stdin, NULL, _IONBF, 0);
  920. # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
  921. #endif
  922. BIO_set_fp(key, stdin, BIO_NOCLOSE);
  923. } else if (BIO_read_filename(key, file) <= 0) {
  924. BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
  925. ERR_print_errors(err);
  926. goto end;
  927. }
  928. if (format == FORMAT_ASN1) {
  929. pkey = d2i_PrivateKey_bio(key, NULL);
  930. } else if (format == FORMAT_PEM) {
  931. pkey = PEM_read_bio_PrivateKey(key, NULL,
  932. (pem_password_cb *)password_callback,
  933. &cb_data);
  934. }
  935. #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
  936. else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
  937. pkey = load_netscape_key(err, key, file, key_descrip, format);
  938. #endif
  939. else if (format == FORMAT_PKCS12) {
  940. if (!load_pkcs12(err, key, key_descrip,
  941. (pem_password_cb *)password_callback, &cb_data,
  942. &pkey, NULL, NULL))
  943. goto end;
  944. }
  945. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
  946. else if (format == FORMAT_MSBLOB)
  947. pkey = b2i_PrivateKey_bio(key);
  948. else if (format == FORMAT_PVK)
  949. pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
  950. &cb_data);
  951. #endif
  952. else {
  953. BIO_printf(err, "bad input format specified for key file\n");
  954. goto end;
  955. }
  956. end:
  957. if (key != NULL)
  958. BIO_free(key);
  959. if (pkey == NULL) {
  960. BIO_printf(err, "unable to load %s\n", key_descrip);
  961. ERR_print_errors(err);
  962. }
  963. return (pkey);
  964. }
  965. EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
  966. const char *pass, ENGINE *e, const char *key_descrip)
  967. {
  968. BIO *key = NULL;
  969. EVP_PKEY *pkey = NULL;
  970. PW_CB_DATA cb_data;
  971. cb_data.password = pass;
  972. cb_data.prompt_info = file;
  973. if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
  974. BIO_printf(err, "no keyfile specified\n");
  975. goto end;
  976. }
  977. #ifndef OPENSSL_NO_ENGINE
  978. if (format == FORMAT_ENGINE) {
  979. if (!e)
  980. BIO_printf(bio_err, "no engine specified\n");
  981. else
  982. pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
  983. goto end;
  984. }
  985. #endif
  986. key = BIO_new(BIO_s_file());
  987. if (key == NULL) {
  988. ERR_print_errors(err);
  989. goto end;
  990. }
  991. if (file == NULL && maybe_stdin) {
  992. #ifdef _IONBF
  993. # ifndef OPENSSL_NO_SETVBUF_IONBF
  994. setvbuf(stdin, NULL, _IONBF, 0);
  995. # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
  996. #endif
  997. BIO_set_fp(key, stdin, BIO_NOCLOSE);
  998. } else if (BIO_read_filename(key, file) <= 0) {
  999. BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
  1000. ERR_print_errors(err);
  1001. goto end;
  1002. }
  1003. if (format == FORMAT_ASN1) {
  1004. pkey = d2i_PUBKEY_bio(key, NULL);
  1005. }
  1006. #ifndef OPENSSL_NO_RSA
  1007. else if (format == FORMAT_ASN1RSA) {
  1008. RSA *rsa;
  1009. rsa = d2i_RSAPublicKey_bio(key, NULL);
  1010. if (rsa) {
  1011. pkey = EVP_PKEY_new();
  1012. if (pkey)
  1013. EVP_PKEY_set1_RSA(pkey, rsa);
  1014. RSA_free(rsa);
  1015. } else
  1016. pkey = NULL;
  1017. } else if (format == FORMAT_PEMRSA) {
  1018. RSA *rsa;
  1019. rsa = PEM_read_bio_RSAPublicKey(key, NULL,
  1020. (pem_password_cb *)password_callback,
  1021. &cb_data);
  1022. if (rsa) {
  1023. pkey = EVP_PKEY_new();
  1024. if (pkey)
  1025. EVP_PKEY_set1_RSA(pkey, rsa);
  1026. RSA_free(rsa);
  1027. } else
  1028. pkey = NULL;
  1029. }
  1030. #endif
  1031. else if (format == FORMAT_PEM) {
  1032. pkey = PEM_read_bio_PUBKEY(key, NULL,
  1033. (pem_password_cb *)password_callback,
  1034. &cb_data);
  1035. }
  1036. #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
  1037. else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
  1038. pkey = load_netscape_key(err, key, file, key_descrip, format);
  1039. #endif
  1040. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
  1041. else if (format == FORMAT_MSBLOB)
  1042. pkey = b2i_PublicKey_bio(key);
  1043. #endif
  1044. else {
  1045. BIO_printf(err, "bad input format specified for key file\n");
  1046. goto end;
  1047. }
  1048. end:
  1049. if (key != NULL)
  1050. BIO_free(key);
  1051. if (pkey == NULL)
  1052. BIO_printf(err, "unable to load %s\n", key_descrip);
  1053. return (pkey);
  1054. }
  1055. #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
  1056. static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
  1057. const char *key_descrip, int format)
  1058. {
  1059. EVP_PKEY *pkey;
  1060. BUF_MEM *buf;
  1061. RSA *rsa;
  1062. const unsigned char *p;
  1063. int size, i;
  1064. buf = BUF_MEM_new();
  1065. pkey = EVP_PKEY_new();
  1066. size = 0;
  1067. if (buf == NULL || pkey == NULL)
  1068. goto error;
  1069. for (;;) {
  1070. if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
  1071. goto error;
  1072. i = BIO_read(key, &(buf->data[size]), 1024 * 10);
  1073. size += i;
  1074. if (i == 0)
  1075. break;
  1076. if (i < 0) {
  1077. BIO_printf(err, "Error reading %s %s", key_descrip, file);
  1078. goto error;
  1079. }
  1080. }
  1081. p = (unsigned char *)buf->data;
  1082. rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL,
  1083. (format == FORMAT_IISSGC ? 1 : 0));
  1084. if (rsa == NULL)
  1085. goto error;
  1086. BUF_MEM_free(buf);
  1087. EVP_PKEY_set1_RSA(pkey, rsa);
  1088. return pkey;
  1089. error:
  1090. BUF_MEM_free(buf);
  1091. EVP_PKEY_free(pkey);
  1092. return NULL;
  1093. }
  1094. #endif /* ndef OPENSSL_NO_RC4 */
  1095. static int load_certs_crls(BIO *err, const char *file, int format,
  1096. const char *pass, ENGINE *e, const char *desc,
  1097. STACK_OF(X509) **pcerts,
  1098. STACK_OF(X509_CRL) **pcrls)
  1099. {
  1100. int i;
  1101. BIO *bio;
  1102. STACK_OF(X509_INFO) *xis = NULL;
  1103. X509_INFO *xi;
  1104. PW_CB_DATA cb_data;
  1105. int rv = 0;
  1106. cb_data.password = pass;
  1107. cb_data.prompt_info = file;
  1108. if (format != FORMAT_PEM) {
  1109. BIO_printf(err, "bad input format specified for %s\n", desc);
  1110. return 0;
  1111. }
  1112. if (file == NULL)
  1113. bio = BIO_new_fp(stdin, BIO_NOCLOSE);
  1114. else
  1115. bio = BIO_new_file(file, "r");
  1116. if (bio == NULL) {
  1117. BIO_printf(err, "Error opening %s %s\n", desc, file ? file : "stdin");
  1118. ERR_print_errors(err);
  1119. return 0;
  1120. }
  1121. xis = PEM_X509_INFO_read_bio(bio, NULL,
  1122. (pem_password_cb *)password_callback,
  1123. &cb_data);
  1124. BIO_free(bio);
  1125. if (pcerts) {
  1126. *pcerts = sk_X509_new_null();
  1127. if (!*pcerts)
  1128. goto end;
  1129. }
  1130. if (pcrls) {
  1131. *pcrls = sk_X509_CRL_new_null();
  1132. if (!*pcrls)
  1133. goto end;
  1134. }
  1135. for (i = 0; i < sk_X509_INFO_num(xis); i++) {
  1136. xi = sk_X509_INFO_value(xis, i);
  1137. if (xi->x509 && pcerts) {
  1138. if (!sk_X509_push(*pcerts, xi->x509))
  1139. goto end;
  1140. xi->x509 = NULL;
  1141. }
  1142. if (xi->crl && pcrls) {
  1143. if (!sk_X509_CRL_push(*pcrls, xi->crl))
  1144. goto end;
  1145. xi->crl = NULL;
  1146. }
  1147. }
  1148. if (pcerts && sk_X509_num(*pcerts) > 0)
  1149. rv = 1;
  1150. if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
  1151. rv = 1;
  1152. end:
  1153. if (xis)
  1154. sk_X509_INFO_pop_free(xis, X509_INFO_free);
  1155. if (rv == 0) {
  1156. if (pcerts) {
  1157. sk_X509_pop_free(*pcerts, X509_free);
  1158. *pcerts = NULL;
  1159. }
  1160. if (pcrls) {
  1161. sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
  1162. *pcrls = NULL;
  1163. }
  1164. BIO_printf(err, "unable to load %s\n",
  1165. pcerts ? "certificates" : "CRLs");
  1166. ERR_print_errors(err);
  1167. }
  1168. return rv;
  1169. }
  1170. STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
  1171. const char *pass, ENGINE *e, const char *desc)
  1172. {
  1173. STACK_OF(X509) *certs;
  1174. if (!load_certs_crls(err, file, format, pass, e, desc, &certs, NULL))
  1175. return NULL;
  1176. return certs;
  1177. }
  1178. STACK_OF(X509_CRL) *load_crls(BIO *err, const char *file, int format,
  1179. const char *pass, ENGINE *e, const char *desc)
  1180. {
  1181. STACK_OF(X509_CRL) *crls;
  1182. if (!load_certs_crls(err, file, format, pass, e, desc, NULL, &crls))
  1183. return NULL;
  1184. return crls;
  1185. }
  1186. #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
  1187. /* Return error for unknown extensions */
  1188. #define X509V3_EXT_DEFAULT 0
  1189. /* Print error for unknown extensions */
  1190. #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
  1191. /* ASN1 parse unknown extensions */
  1192. #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
  1193. /* BIO_dump unknown extensions */
  1194. #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
  1195. #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
  1196. X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
  1197. int set_cert_ex(unsigned long *flags, const char *arg)
  1198. {
  1199. static const NAME_EX_TBL cert_tbl[] = {
  1200. {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
  1201. {"ca_default", X509_FLAG_CA, 0xffffffffl},
  1202. {"no_header", X509_FLAG_NO_HEADER, 0},
  1203. {"no_version", X509_FLAG_NO_VERSION, 0},
  1204. {"no_serial", X509_FLAG_NO_SERIAL, 0},
  1205. {"no_signame", X509_FLAG_NO_SIGNAME, 0},
  1206. {"no_validity", X509_FLAG_NO_VALIDITY, 0},
  1207. {"no_subject", X509_FLAG_NO_SUBJECT, 0},
  1208. {"no_issuer", X509_FLAG_NO_ISSUER, 0},
  1209. {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
  1210. {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
  1211. {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
  1212. {"no_aux", X509_FLAG_NO_AUX, 0},
  1213. {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
  1214. {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
  1215. {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1216. {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1217. {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1218. {NULL, 0, 0}
  1219. };
  1220. return set_multi_opts(flags, arg, cert_tbl);
  1221. }
  1222. int set_name_ex(unsigned long *flags, const char *arg)
  1223. {
  1224. static const NAME_EX_TBL ex_tbl[] = {
  1225. {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
  1226. {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
  1227. {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
  1228. {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
  1229. {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
  1230. {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
  1231. {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
  1232. {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
  1233. {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
  1234. {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
  1235. {"compat", XN_FLAG_COMPAT, 0xffffffffL},
  1236. {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
  1237. {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
  1238. {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
  1239. {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
  1240. {"dn_rev", XN_FLAG_DN_REV, 0},
  1241. {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
  1242. {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
  1243. {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
  1244. {"align", XN_FLAG_FN_ALIGN, 0},
  1245. {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
  1246. {"space_eq", XN_FLAG_SPC_EQ, 0},
  1247. {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
  1248. {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
  1249. {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
  1250. {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
  1251. {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
  1252. {NULL, 0, 0}
  1253. };
  1254. if (set_multi_opts(flags, arg, ex_tbl) == 0)
  1255. return 0;
  1256. if ((*flags & XN_FLAG_SEP_MASK) == 0)
  1257. *flags |= XN_FLAG_SEP_CPLUS_SPC;
  1258. return 1;
  1259. }
  1260. int set_ext_copy(int *copy_type, const char *arg)
  1261. {
  1262. if (!strcasecmp(arg, "none"))
  1263. *copy_type = EXT_COPY_NONE;
  1264. else if (!strcasecmp(arg, "copy"))
  1265. *copy_type = EXT_COPY_ADD;
  1266. else if (!strcasecmp(arg, "copyall"))
  1267. *copy_type = EXT_COPY_ALL;
  1268. else
  1269. return 0;
  1270. return 1;
  1271. }
  1272. int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
  1273. {
  1274. STACK_OF(X509_EXTENSION) *exts = NULL;
  1275. X509_EXTENSION *ext, *tmpext;
  1276. ASN1_OBJECT *obj;
  1277. int i, idx, ret = 0;
  1278. if (!x || !req || (copy_type == EXT_COPY_NONE))
  1279. return 1;
  1280. exts = X509_REQ_get_extensions(req);
  1281. for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
  1282. ext = sk_X509_EXTENSION_value(exts, i);
  1283. obj = X509_EXTENSION_get_object(ext);
  1284. idx = X509_get_ext_by_OBJ(x, obj, -1);
  1285. /* Does extension exist? */
  1286. if (idx != -1) {
  1287. /* If normal copy don't override existing extension */
  1288. if (copy_type == EXT_COPY_ADD)
  1289. continue;
  1290. /* Delete all extensions of same type */
  1291. do {
  1292. tmpext = X509_get_ext(x, idx);
  1293. X509_delete_ext(x, idx);
  1294. X509_EXTENSION_free(tmpext);
  1295. idx = X509_get_ext_by_OBJ(x, obj, -1);
  1296. } while (idx != -1);
  1297. }
  1298. if (!X509_add_ext(x, ext, -1))
  1299. goto end;
  1300. }
  1301. ret = 1;
  1302. end:
  1303. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  1304. return ret;
  1305. }
  1306. static int set_multi_opts(unsigned long *flags, const char *arg,
  1307. const NAME_EX_TBL * in_tbl)
  1308. {
  1309. STACK_OF(CONF_VALUE) *vals;
  1310. CONF_VALUE *val;
  1311. int i, ret = 1;
  1312. if (!arg)
  1313. return 0;
  1314. vals = X509V3_parse_list(arg);
  1315. for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
  1316. val = sk_CONF_VALUE_value(vals, i);
  1317. if (!set_table_opts(flags, val->name, in_tbl))
  1318. ret = 0;
  1319. }
  1320. sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
  1321. return ret;
  1322. }
  1323. static int set_table_opts(unsigned long *flags, const char *arg,
  1324. const NAME_EX_TBL * in_tbl)
  1325. {
  1326. char c;
  1327. const NAME_EX_TBL *ptbl;
  1328. c = arg[0];
  1329. if (c == '-') {
  1330. c = 0;
  1331. arg++;
  1332. } else if (c == '+') {
  1333. c = 1;
  1334. arg++;
  1335. } else
  1336. c = 1;
  1337. for (ptbl = in_tbl; ptbl->name; ptbl++) {
  1338. if (!strcasecmp(arg, ptbl->name)) {
  1339. *flags &= ~ptbl->mask;
  1340. if (c)
  1341. *flags |= ptbl->flag;
  1342. else
  1343. *flags &= ~ptbl->flag;
  1344. return 1;
  1345. }
  1346. }
  1347. return 0;
  1348. }
  1349. void print_name(BIO *out, const char *title, X509_NAME *nm,
  1350. unsigned long lflags)
  1351. {
  1352. char *buf;
  1353. char mline = 0;
  1354. int indent = 0;
  1355. if (title)
  1356. BIO_puts(out, title);
  1357. if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
  1358. mline = 1;
  1359. indent = 4;
  1360. }
  1361. if (lflags == XN_FLAG_COMPAT) {
  1362. buf = X509_NAME_oneline(nm, 0, 0);
  1363. BIO_puts(out, buf);
  1364. BIO_puts(out, "\n");
  1365. OPENSSL_free(buf);
  1366. } else {
  1367. if (mline)
  1368. BIO_puts(out, "\n");
  1369. X509_NAME_print_ex(out, nm, indent, lflags);
  1370. BIO_puts(out, "\n");
  1371. }
  1372. }
  1373. X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
  1374. {
  1375. X509_STORE *store;
  1376. X509_LOOKUP *lookup;
  1377. if (!(store = X509_STORE_new()))
  1378. goto end;
  1379. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1380. if (lookup == NULL)
  1381. goto end;
  1382. if (CAfile) {
  1383. if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
  1384. BIO_printf(bp, "Error loading file %s\n", CAfile);
  1385. goto end;
  1386. }
  1387. } else
  1388. X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
  1389. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1390. if (lookup == NULL)
  1391. goto end;
  1392. if (CApath) {
  1393. if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
  1394. BIO_printf(bp, "Error loading directory %s\n", CApath);
  1395. goto end;
  1396. }
  1397. } else
  1398. X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
  1399. ERR_clear_error();
  1400. return store;
  1401. end:
  1402. X509_STORE_free(store);
  1403. return NULL;
  1404. }
  1405. #ifndef OPENSSL_NO_ENGINE
  1406. /* Try to load an engine in a shareable library */
  1407. static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
  1408. {
  1409. ENGINE *e = ENGINE_by_id("dynamic");
  1410. if (e) {
  1411. if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
  1412. || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  1413. ENGINE_free(e);
  1414. e = NULL;
  1415. }
  1416. }
  1417. return e;
  1418. }
  1419. ENGINE *setup_engine(BIO *err, const char *engine, int debug)
  1420. {
  1421. ENGINE *e = NULL;
  1422. if (engine) {
  1423. if (strcmp(engine, "auto") == 0) {
  1424. BIO_printf(err, "enabling auto ENGINE support\n");
  1425. ENGINE_register_all_complete();
  1426. return NULL;
  1427. }
  1428. if ((e = ENGINE_by_id(engine)) == NULL
  1429. && (e = try_load_engine(err, engine, debug)) == NULL) {
  1430. BIO_printf(err, "invalid engine \"%s\"\n", engine);
  1431. ERR_print_errors(err);
  1432. return NULL;
  1433. }
  1434. if (debug) {
  1435. ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, err, 0);
  1436. }
  1437. ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
  1438. if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
  1439. BIO_printf(err, "can't use that engine\n");
  1440. ERR_print_errors(err);
  1441. ENGINE_free(e);
  1442. return NULL;
  1443. }
  1444. BIO_printf(err, "engine \"%s\" set.\n", ENGINE_get_id(e));
  1445. /* Free our "structural" reference. */
  1446. ENGINE_free(e);
  1447. }
  1448. return e;
  1449. }
  1450. #endif
  1451. int load_config(BIO *err, CONF *cnf)
  1452. {
  1453. static int load_config_called = 0;
  1454. if (load_config_called)
  1455. return 1;
  1456. load_config_called = 1;
  1457. if (!cnf)
  1458. cnf = config;
  1459. if (!cnf)
  1460. return 1;
  1461. OPENSSL_load_builtin_modules();
  1462. if (CONF_modules_load(cnf, NULL, 0) <= 0) {
  1463. BIO_printf(err, "Error configuring OpenSSL\n");
  1464. ERR_print_errors(err);
  1465. return 0;
  1466. }
  1467. return 1;
  1468. }
  1469. char *make_config_name()
  1470. {
  1471. const char *t = X509_get_default_cert_area();
  1472. size_t len;
  1473. char *p;
  1474. len = strlen(t) + strlen(OPENSSL_CONF) + 2;
  1475. p = OPENSSL_malloc(len);
  1476. if (p == NULL)
  1477. return NULL;
  1478. BUF_strlcpy(p, t, len);
  1479. #ifndef OPENSSL_SYS_VMS
  1480. BUF_strlcat(p, "/", len);
  1481. #endif
  1482. BUF_strlcat(p, OPENSSL_CONF, len);
  1483. return p;
  1484. }
  1485. static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
  1486. {
  1487. const char *n;
  1488. n = a[DB_serial];
  1489. while (*n == '0')
  1490. n++;
  1491. return (lh_strhash(n));
  1492. }
  1493. static int index_serial_cmp(const OPENSSL_CSTRING *a,
  1494. const OPENSSL_CSTRING *b)
  1495. {
  1496. const char *aa, *bb;
  1497. for (aa = a[DB_serial]; *aa == '0'; aa++) ;
  1498. for (bb = b[DB_serial]; *bb == '0'; bb++) ;
  1499. return (strcmp(aa, bb));
  1500. }
  1501. static int index_name_qual(char **a)
  1502. {
  1503. return (a[0][0] == 'V');
  1504. }
  1505. static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
  1506. {
  1507. return (lh_strhash(a[DB_name]));
  1508. }
  1509. int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
  1510. {
  1511. return (strcmp(a[DB_name], b[DB_name]));
  1512. }
  1513. static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
  1514. static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
  1515. static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
  1516. static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
  1517. #undef BSIZE
  1518. #define BSIZE 256
  1519. BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
  1520. {
  1521. BIO *in = NULL;
  1522. BIGNUM *ret = NULL;
  1523. MS_STATIC char buf[1024];
  1524. ASN1_INTEGER *ai = NULL;
  1525. ai = ASN1_INTEGER_new();
  1526. if (ai == NULL)
  1527. goto err;
  1528. if ((in = BIO_new(BIO_s_file())) == NULL) {
  1529. ERR_print_errors(bio_err);
  1530. goto err;
  1531. }
  1532. if (BIO_read_filename(in, serialfile) <= 0) {
  1533. if (!create) {
  1534. perror(serialfile);
  1535. goto err;
  1536. } else {
  1537. ret = BN_new();
  1538. if (ret == NULL || !rand_serial(ret, ai))
  1539. BIO_printf(bio_err, "Out of memory\n");
  1540. }
  1541. } else {
  1542. if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
  1543. BIO_printf(bio_err, "unable to load number from %s\n",
  1544. serialfile);
  1545. goto err;
  1546. }
  1547. ret = ASN1_INTEGER_to_BN(ai, NULL);
  1548. if (ret == NULL) {
  1549. BIO_printf(bio_err,
  1550. "error converting number from bin to BIGNUM\n");
  1551. goto err;
  1552. }
  1553. }
  1554. if (ret && retai) {
  1555. *retai = ai;
  1556. ai = NULL;
  1557. }
  1558. err:
  1559. if (in != NULL)
  1560. BIO_free(in);
  1561. if (ai != NULL)
  1562. ASN1_INTEGER_free(ai);
  1563. return (ret);
  1564. }
  1565. int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
  1566. ASN1_INTEGER **retai)
  1567. {
  1568. char buf[1][BSIZE];
  1569. BIO *out = NULL;
  1570. int ret = 0;
  1571. ASN1_INTEGER *ai = NULL;
  1572. int j;
  1573. if (suffix == NULL)
  1574. j = strlen(serialfile);
  1575. else
  1576. j = strlen(serialfile) + strlen(suffix) + 1;
  1577. if (j >= BSIZE) {
  1578. BIO_printf(bio_err, "file name too long\n");
  1579. goto err;
  1580. }
  1581. if (suffix == NULL)
  1582. BUF_strlcpy(buf[0], serialfile, BSIZE);
  1583. else {
  1584. #ifndef OPENSSL_SYS_VMS
  1585. j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
  1586. #else
  1587. j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
  1588. #endif
  1589. }
  1590. #ifdef RL_DEBUG
  1591. BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
  1592. #endif
  1593. out = BIO_new(BIO_s_file());
  1594. if (out == NULL) {
  1595. ERR_print_errors(bio_err);
  1596. goto err;
  1597. }
  1598. if (BIO_write_filename(out, buf[0]) <= 0) {
  1599. perror(serialfile);
  1600. goto err;
  1601. }
  1602. if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
  1603. BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
  1604. goto err;
  1605. }
  1606. i2a_ASN1_INTEGER(out, ai);
  1607. BIO_puts(out, "\n");
  1608. ret = 1;
  1609. if (retai) {
  1610. *retai = ai;
  1611. ai = NULL;
  1612. }
  1613. err:
  1614. if (out != NULL)
  1615. BIO_free_all(out);
  1616. if (ai != NULL)
  1617. ASN1_INTEGER_free(ai);
  1618. return (ret);
  1619. }
  1620. int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
  1621. {
  1622. char buf[5][BSIZE];
  1623. int i, j;
  1624. i = strlen(serialfile) + strlen(old_suffix);
  1625. j = strlen(serialfile) + strlen(new_suffix);
  1626. if (i > j)
  1627. j = i;
  1628. if (j + 1 >= BSIZE) {
  1629. BIO_printf(bio_err, "file name too long\n");
  1630. goto err;
  1631. }
  1632. #ifndef OPENSSL_SYS_VMS
  1633. j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
  1634. #else
  1635. j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
  1636. #endif
  1637. #ifndef OPENSSL_SYS_VMS
  1638. j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
  1639. #else
  1640. j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
  1641. #endif
  1642. #ifdef RL_DEBUG
  1643. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
  1644. serialfile, buf[1]);
  1645. #endif
  1646. if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
  1647. #ifdef ENOTDIR
  1648. && errno != ENOTDIR
  1649. #endif
  1650. ) {
  1651. BIO_printf(bio_err,
  1652. "unable to rename %s to %s\n", serialfile, buf[1]);
  1653. perror("reason");
  1654. goto err;
  1655. }
  1656. #ifdef RL_DEBUG
  1657. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
  1658. buf[0], serialfile);
  1659. #endif
  1660. if (rename(buf[0], serialfile) < 0) {
  1661. BIO_printf(bio_err,
  1662. "unable to rename %s to %s\n", buf[0], serialfile);
  1663. perror("reason");
  1664. rename(buf[1], serialfile);
  1665. goto err;
  1666. }
  1667. return 1;
  1668. err:
  1669. return 0;
  1670. }
  1671. int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
  1672. {
  1673. BIGNUM *btmp;
  1674. int ret = 0;
  1675. if (b)
  1676. btmp = b;
  1677. else
  1678. btmp = BN_new();
  1679. if (!btmp)
  1680. return 0;
  1681. if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
  1682. goto error;
  1683. if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
  1684. goto error;
  1685. ret = 1;
  1686. error:
  1687. if (!b)
  1688. BN_free(btmp);
  1689. return ret;
  1690. }
  1691. CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
  1692. {
  1693. CA_DB *retdb = NULL;
  1694. TXT_DB *tmpdb = NULL;
  1695. BIO *in = BIO_new(BIO_s_file());
  1696. CONF *dbattr_conf = NULL;
  1697. char buf[1][BSIZE];
  1698. long errorline = -1;
  1699. if (in == NULL) {
  1700. ERR_print_errors(bio_err);
  1701. goto err;
  1702. }
  1703. if (BIO_read_filename(in, dbfile) <= 0) {
  1704. perror(dbfile);
  1705. BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
  1706. goto err;
  1707. }
  1708. if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
  1709. goto err;
  1710. #ifndef OPENSSL_SYS_VMS
  1711. BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
  1712. #else
  1713. BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
  1714. #endif
  1715. dbattr_conf = NCONF_new(NULL);
  1716. if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
  1717. if (errorline > 0) {
  1718. BIO_printf(bio_err,
  1719. "error on line %ld of db attribute file '%s'\n",
  1720. errorline, buf[0]);
  1721. goto err;
  1722. } else {
  1723. NCONF_free(dbattr_conf);
  1724. dbattr_conf = NULL;
  1725. }
  1726. }
  1727. if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL) {
  1728. fprintf(stderr, "Out of memory\n");
  1729. goto err;
  1730. }
  1731. retdb->db = tmpdb;
  1732. tmpdb = NULL;
  1733. if (db_attr)
  1734. retdb->attributes = *db_attr;
  1735. else {
  1736. retdb->attributes.unique_subject = 1;
  1737. }
  1738. if (dbattr_conf) {
  1739. char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
  1740. if (p) {
  1741. #ifdef RL_DEBUG
  1742. BIO_printf(bio_err,
  1743. "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
  1744. #endif
  1745. retdb->attributes.unique_subject = parse_yesno(p, 1);
  1746. }
  1747. }
  1748. err:
  1749. if (dbattr_conf)
  1750. NCONF_free(dbattr_conf);
  1751. if (tmpdb)
  1752. TXT_DB_free(tmpdb);
  1753. if (in)
  1754. BIO_free_all(in);
  1755. return retdb;
  1756. }
  1757. int index_index(CA_DB *db)
  1758. {
  1759. if (!TXT_DB_create_index(db->db, DB_serial, NULL,
  1760. LHASH_HASH_FN(index_serial),
  1761. LHASH_COMP_FN(index_serial))) {
  1762. BIO_printf(bio_err,
  1763. "error creating serial number index:(%ld,%ld,%ld)\n",
  1764. db->db->error, db->db->arg1, db->db->arg2);
  1765. return 0;
  1766. }
  1767. if (db->attributes.unique_subject
  1768. && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
  1769. LHASH_HASH_FN(index_name),
  1770. LHASH_COMP_FN(index_name))) {
  1771. BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
  1772. db->db->error, db->db->arg1, db->db->arg2);
  1773. return 0;
  1774. }
  1775. return 1;
  1776. }
  1777. int save_index(const char *dbfile, const char *suffix, CA_DB *db)
  1778. {
  1779. char buf[3][BSIZE];
  1780. BIO *out = BIO_new(BIO_s_file());
  1781. int j;
  1782. if (out == NULL) {
  1783. ERR_print_errors(bio_err);
  1784. goto err;
  1785. }
  1786. j = strlen(dbfile) + strlen(suffix);
  1787. if (j + 6 >= BSIZE) {
  1788. BIO_printf(bio_err, "file name too long\n");
  1789. goto err;
  1790. }
  1791. #ifndef OPENSSL_SYS_VMS
  1792. j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
  1793. #else
  1794. j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
  1795. #endif
  1796. #ifndef OPENSSL_SYS_VMS
  1797. j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
  1798. #else
  1799. j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
  1800. #endif
  1801. #ifndef OPENSSL_SYS_VMS
  1802. j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
  1803. #else
  1804. j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
  1805. #endif
  1806. #ifdef RL_DEBUG
  1807. BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
  1808. #endif
  1809. if (BIO_write_filename(out, buf[0]) <= 0) {
  1810. perror(dbfile);
  1811. BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
  1812. goto err;
  1813. }
  1814. j = TXT_DB_write(out, db->db);
  1815. if (j <= 0)
  1816. goto err;
  1817. BIO_free(out);
  1818. out = BIO_new(BIO_s_file());
  1819. #ifdef RL_DEBUG
  1820. BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
  1821. #endif
  1822. if (BIO_write_filename(out, buf[1]) <= 0) {
  1823. perror(buf[2]);
  1824. BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
  1825. goto err;
  1826. }
  1827. BIO_printf(out, "unique_subject = %s\n",
  1828. db->attributes.unique_subject ? "yes" : "no");
  1829. BIO_free(out);
  1830. return 1;
  1831. err:
  1832. return 0;
  1833. }
  1834. int rotate_index(const char *dbfile, const char *new_suffix,
  1835. const char *old_suffix)
  1836. {
  1837. char buf[5][BSIZE];
  1838. int i, j;
  1839. i = strlen(dbfile) + strlen(old_suffix);
  1840. j = strlen(dbfile) + strlen(new_suffix);
  1841. if (i > j)
  1842. j = i;
  1843. if (j + 6 >= BSIZE) {
  1844. BIO_printf(bio_err, "file name too long\n");
  1845. goto err;
  1846. }
  1847. #ifndef OPENSSL_SYS_VMS
  1848. j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
  1849. #else
  1850. j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
  1851. #endif
  1852. #ifndef OPENSSL_SYS_VMS
  1853. j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
  1854. #else
  1855. j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
  1856. #endif
  1857. #ifndef OPENSSL_SYS_VMS
  1858. j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
  1859. #else
  1860. j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
  1861. #endif
  1862. #ifndef OPENSSL_SYS_VMS
  1863. j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
  1864. #else
  1865. j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
  1866. #endif
  1867. #ifndef OPENSSL_SYS_VMS
  1868. j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
  1869. #else
  1870. j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
  1871. #endif
  1872. #ifdef RL_DEBUG
  1873. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", dbfile, buf[1]);
  1874. #endif
  1875. if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
  1876. #ifdef ENOTDIR
  1877. && errno != ENOTDIR
  1878. #endif
  1879. ) {
  1880. BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
  1881. perror("reason");
  1882. goto err;
  1883. }
  1884. #ifdef RL_DEBUG
  1885. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[0], dbfile);
  1886. #endif
  1887. if (rename(buf[0], dbfile) < 0) {
  1888. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
  1889. perror("reason");
  1890. rename(buf[1], dbfile);
  1891. goto err;
  1892. }
  1893. #ifdef RL_DEBUG
  1894. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[4], buf[3]);
  1895. #endif
  1896. if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
  1897. #ifdef ENOTDIR
  1898. && errno != ENOTDIR
  1899. #endif
  1900. ) {
  1901. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
  1902. perror("reason");
  1903. rename(dbfile, buf[0]);
  1904. rename(buf[1], dbfile);
  1905. goto err;
  1906. }
  1907. #ifdef RL_DEBUG
  1908. BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[2], buf[4]);
  1909. #endif
  1910. if (rename(buf[2], buf[4]) < 0) {
  1911. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
  1912. perror("reason");
  1913. rename(buf[3], buf[4]);
  1914. rename(dbfile, buf[0]);
  1915. rename(buf[1], dbfile);
  1916. goto err;
  1917. }
  1918. return 1;
  1919. err:
  1920. return 0;
  1921. }
  1922. void free_index(CA_DB *db)
  1923. {
  1924. if (db) {
  1925. if (db->db)
  1926. TXT_DB_free(db->db);
  1927. OPENSSL_free(db);
  1928. }
  1929. }
  1930. int parse_yesno(const char *str, int def)
  1931. {
  1932. int ret = def;
  1933. if (str) {
  1934. switch (*str) {
  1935. case 'f': /* false */
  1936. case 'F': /* FALSE */
  1937. case 'n': /* no */
  1938. case 'N': /* NO */
  1939. case '0': /* 0 */
  1940. ret = 0;
  1941. break;
  1942. case 't': /* true */
  1943. case 'T': /* TRUE */
  1944. case 'y': /* yes */
  1945. case 'Y': /* YES */
  1946. case '1': /* 1 */
  1947. ret = 1;
  1948. break;
  1949. default:
  1950. ret = def;
  1951. break;
  1952. }
  1953. }
  1954. return ret;
  1955. }
  1956. /*
  1957. * subject is expected to be in the format /type0=value0/type1=value1/type2=...
  1958. * where characters may be escaped by \
  1959. */
  1960. X509_NAME *parse_name(char *subject, long chtype, int multirdn)
  1961. {
  1962. size_t buflen = strlen(subject) + 1; /* to copy the types and values
  1963. * into. due to escaping, the copy
  1964. * can only become shorter */
  1965. char *buf = OPENSSL_malloc(buflen);
  1966. size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
  1967. char **ne_types = OPENSSL_malloc(max_ne * sizeof(char *));
  1968. char **ne_values = OPENSSL_malloc(max_ne * sizeof(char *));
  1969. int *mval = OPENSSL_malloc(max_ne * sizeof(int));
  1970. char *sp = subject, *bp = buf;
  1971. int i, ne_num = 0;
  1972. X509_NAME *n = NULL;
  1973. int nid;
  1974. if (!buf || !ne_types || !ne_values || !mval) {
  1975. BIO_printf(bio_err, "malloc error\n");
  1976. goto error;
  1977. }
  1978. if (*subject != '/') {
  1979. BIO_printf(bio_err, "Subject does not start with '/'.\n");
  1980. goto error;
  1981. }
  1982. sp++; /* skip leading / */
  1983. /* no multivalued RDN by default */
  1984. mval[ne_num] = 0;
  1985. while (*sp) {
  1986. /* collect type */
  1987. ne_types[ne_num] = bp;
  1988. while (*sp) {
  1989. if (*sp == '\\') { /* is there anything to escape in the
  1990. * type...? */
  1991. if (*++sp)
  1992. *bp++ = *sp++;
  1993. else {
  1994. BIO_printf(bio_err,
  1995. "escape character at end of string\n");
  1996. goto error;
  1997. }
  1998. } else if (*sp == '=') {
  1999. sp++;
  2000. *bp++ = '\0';
  2001. break;
  2002. } else
  2003. *bp++ = *sp++;
  2004. }
  2005. if (!*sp) {
  2006. BIO_printf(bio_err,
  2007. "end of string encountered while processing type of subject name element #%d\n",
  2008. ne_num);
  2009. goto error;
  2010. }
  2011. ne_values[ne_num] = bp;
  2012. while (*sp) {
  2013. if (*sp == '\\') {
  2014. if (*++sp)
  2015. *bp++ = *sp++;
  2016. else {
  2017. BIO_printf(bio_err,
  2018. "escape character at end of string\n");
  2019. goto error;
  2020. }
  2021. } else if (*sp == '/') {
  2022. sp++;
  2023. /* no multivalued RDN by default */
  2024. mval[ne_num + 1] = 0;
  2025. break;
  2026. } else if (*sp == '+' && multirdn) {
  2027. /*
  2028. * a not escaped + signals a mutlivalued RDN
  2029. */
  2030. sp++;
  2031. mval[ne_num + 1] = -1;
  2032. break;
  2033. } else
  2034. *bp++ = *sp++;
  2035. }
  2036. *bp++ = '\0';
  2037. ne_num++;
  2038. }
  2039. if (!(n = X509_NAME_new()))
  2040. goto error;
  2041. for (i = 0; i < ne_num; i++) {
  2042. if ((nid = OBJ_txt2nid(ne_types[i])) == NID_undef) {
  2043. BIO_printf(bio_err,
  2044. "Subject Attribute %s has no known NID, skipped\n",
  2045. ne_types[i]);
  2046. continue;
  2047. }
  2048. if (!*ne_values[i]) {
  2049. BIO_printf(bio_err,
  2050. "No value provided for Subject Attribute %s, skipped\n",
  2051. ne_types[i]);
  2052. continue;
  2053. }
  2054. if (!X509_NAME_add_entry_by_NID
  2055. (n, nid, chtype, (unsigned char *)ne_values[i], -1, -1, mval[i]))
  2056. goto error;
  2057. }
  2058. OPENSSL_free(ne_values);
  2059. OPENSSL_free(ne_types);
  2060. OPENSSL_free(buf);
  2061. OPENSSL_free(mval);
  2062. return n;
  2063. error:
  2064. X509_NAME_free(n);
  2065. if (ne_values)
  2066. OPENSSL_free(ne_values);
  2067. if (ne_types)
  2068. OPENSSL_free(ne_types);
  2069. if (mval)
  2070. OPENSSL_free(mval);
  2071. if (buf)
  2072. OPENSSL_free(buf);
  2073. return NULL;
  2074. }
  2075. int args_verify(char ***pargs, int *pargc,
  2076. int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
  2077. {
  2078. ASN1_OBJECT *otmp = NULL;
  2079. unsigned long flags = 0;
  2080. int i;
  2081. int purpose = 0, depth = -1;
  2082. char **oldargs = *pargs;
  2083. char *arg = **pargs, *argn = (*pargs)[1];
  2084. time_t at_time = 0;
  2085. char *hostname = NULL;
  2086. char *email = NULL;
  2087. char *ipasc = NULL;
  2088. if (!strcmp(arg, "-policy")) {
  2089. if (!argn)
  2090. *badarg = 1;
  2091. else {
  2092. otmp = OBJ_txt2obj(argn, 0);
  2093. if (!otmp) {
  2094. BIO_printf(err, "Invalid Policy \"%s\"\n", argn);
  2095. *badarg = 1;
  2096. }
  2097. }
  2098. (*pargs)++;
  2099. } else if (strcmp(arg, "-purpose") == 0) {
  2100. X509_PURPOSE *xptmp;
  2101. if (!argn)
  2102. *badarg = 1;
  2103. else {
  2104. i = X509_PURPOSE_get_by_sname(argn);
  2105. if (i < 0) {
  2106. BIO_printf(err, "unrecognized purpose\n");
  2107. *badarg = 1;
  2108. } else {
  2109. xptmp = X509_PURPOSE_get0(i);
  2110. purpose = X509_PURPOSE_get_id(xptmp);
  2111. }
  2112. }
  2113. (*pargs)++;
  2114. } else if (strcmp(arg, "-verify_depth") == 0) {
  2115. if (!argn)
  2116. *badarg = 1;
  2117. else {
  2118. depth = atoi(argn);
  2119. if (depth < 0) {
  2120. BIO_printf(err, "invalid depth\n");
  2121. *badarg = 1;
  2122. }
  2123. }
  2124. (*pargs)++;
  2125. } else if (strcmp(arg, "-attime") == 0) {
  2126. if (!argn)
  2127. *badarg = 1;
  2128. else {
  2129. long timestamp;
  2130. /*
  2131. * interpret the -attime argument as seconds since Epoch
  2132. */
  2133. if (sscanf(argn, "%li", &timestamp) != 1) {
  2134. BIO_printf(bio_err, "Error parsing timestamp %s\n", argn);
  2135. *badarg = 1;
  2136. }
  2137. /* on some platforms time_t may be a float */
  2138. at_time = (time_t)timestamp;
  2139. }
  2140. (*pargs)++;
  2141. } else if (strcmp(arg, "-verify_hostname") == 0) {
  2142. if (!argn)
  2143. *badarg = 1;
  2144. hostname = argn;
  2145. (*pargs)++;
  2146. } else if (strcmp(arg, "-verify_email") == 0) {
  2147. if (!argn)
  2148. *badarg = 1;
  2149. email = argn;
  2150. (*pargs)++;
  2151. } else if (strcmp(arg, "-verify_ip") == 0) {
  2152. if (!argn)
  2153. *badarg = 1;
  2154. ipasc = argn;
  2155. (*pargs)++;
  2156. } else if (!strcmp(arg, "-ignore_critical"))
  2157. flags |= X509_V_FLAG_IGNORE_CRITICAL;
  2158. else if (!strcmp(arg, "-issuer_checks"))
  2159. flags |= X509_V_FLAG_CB_ISSUER_CHECK;
  2160. else if (!strcmp(arg, "-crl_check"))
  2161. flags |= X509_V_FLAG_CRL_CHECK;
  2162. else if (!strcmp(arg, "-crl_check_all"))
  2163. flags |= X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
  2164. else if (!strcmp(arg, "-policy_check"))
  2165. flags |= X509_V_FLAG_POLICY_CHECK;
  2166. else if (!strcmp(arg, "-explicit_policy"))
  2167. flags |= X509_V_FLAG_EXPLICIT_POLICY;
  2168. else if (!strcmp(arg, "-inhibit_any"))
  2169. flags |= X509_V_FLAG_INHIBIT_ANY;
  2170. else if (!strcmp(arg, "-inhibit_map"))
  2171. flags |= X509_V_FLAG_INHIBIT_MAP;
  2172. else if (!strcmp(arg, "-x509_strict"))
  2173. flags |= X509_V_FLAG_X509_STRICT;
  2174. else if (!strcmp(arg, "-extended_crl"))
  2175. flags |= X509_V_FLAG_EXTENDED_CRL_SUPPORT;
  2176. else if (!strcmp(arg, "-use_deltas"))
  2177. flags |= X509_V_FLAG_USE_DELTAS;
  2178. else if (!strcmp(arg, "-policy_print"))
  2179. flags |= X509_V_FLAG_NOTIFY_POLICY;
  2180. else if (!strcmp(arg, "-check_ss_sig"))
  2181. flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
  2182. else if (!strcmp(arg, "-trusted_first"))
  2183. flags |= X509_V_FLAG_TRUSTED_FIRST;
  2184. else if (!strcmp(arg, "-suiteB_128_only"))
  2185. flags |= X509_V_FLAG_SUITEB_128_LOS_ONLY;
  2186. else if (!strcmp(arg, "-suiteB_128"))
  2187. flags |= X509_V_FLAG_SUITEB_128_LOS;
  2188. else if (!strcmp(arg, "-suiteB_192"))
  2189. flags |= X509_V_FLAG_SUITEB_192_LOS;
  2190. else if (!strcmp(arg, "-partial_chain"))
  2191. flags |= X509_V_FLAG_PARTIAL_CHAIN;
  2192. else if (!strcmp(arg, "-no_alt_chains"))
  2193. flags |= X509_V_FLAG_NO_ALT_CHAINS;
  2194. else
  2195. return 0;
  2196. if (*badarg) {
  2197. if (*pm)
  2198. X509_VERIFY_PARAM_free(*pm);
  2199. *pm = NULL;
  2200. goto end;
  2201. }
  2202. if (!*pm && !(*pm = X509_VERIFY_PARAM_new())) {
  2203. *badarg = 1;
  2204. goto end;
  2205. }
  2206. if (otmp)
  2207. X509_VERIFY_PARAM_add0_policy(*pm, otmp);
  2208. if (flags)
  2209. X509_VERIFY_PARAM_set_flags(*pm, flags);
  2210. if (purpose)
  2211. X509_VERIFY_PARAM_set_purpose(*pm, purpose);
  2212. if (depth >= 0)
  2213. X509_VERIFY_PARAM_set_depth(*pm, depth);
  2214. if (at_time)
  2215. X509_VERIFY_PARAM_set_time(*pm, at_time);
  2216. if (hostname && !X509_VERIFY_PARAM_set1_host(*pm, hostname, 0))
  2217. *badarg = 1;
  2218. if (email && !X509_VERIFY_PARAM_set1_email(*pm, email, 0))
  2219. *badarg = 1;
  2220. if (ipasc && !X509_VERIFY_PARAM_set1_ip_asc(*pm, ipasc))
  2221. *badarg = 1;
  2222. end:
  2223. (*pargs)++;
  2224. if (pargc)
  2225. *pargc -= *pargs - oldargs;
  2226. return 1;
  2227. }
  2228. /*
  2229. * Read whole contents of a BIO into an allocated memory buffer and return
  2230. * it.
  2231. */
  2232. int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
  2233. {
  2234. BIO *mem;
  2235. int len, ret;
  2236. unsigned char tbuf[1024];
  2237. mem = BIO_new(BIO_s_mem());
  2238. if (!mem)
  2239. return -1;
  2240. for (;;) {
  2241. if ((maxlen != -1) && maxlen < 1024)
  2242. len = maxlen;
  2243. else
  2244. len = 1024;
  2245. len = BIO_read(in, tbuf, len);
  2246. if (len < 0) {
  2247. BIO_free(mem);
  2248. return -1;
  2249. }
  2250. if (len == 0)
  2251. break;
  2252. if (BIO_write(mem, tbuf, len) != len) {
  2253. BIO_free(mem);
  2254. return -1;
  2255. }
  2256. maxlen -= len;
  2257. if (maxlen == 0)
  2258. break;
  2259. }
  2260. ret = BIO_get_mem_data(mem, (char **)out);
  2261. BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
  2262. BIO_free(mem);
  2263. return ret;
  2264. }
  2265. int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
  2266. {
  2267. int rv;
  2268. char *stmp, *vtmp = NULL;
  2269. stmp = BUF_strdup(value);
  2270. if (!stmp)
  2271. return -1;
  2272. vtmp = strchr(stmp, ':');
  2273. if (vtmp) {
  2274. *vtmp = 0;
  2275. vtmp++;
  2276. }
  2277. rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
  2278. OPENSSL_free(stmp);
  2279. return rv;
  2280. }
  2281. static void nodes_print(BIO *out, const char *name,
  2282. STACK_OF(X509_POLICY_NODE) *nodes)
  2283. {
  2284. X509_POLICY_NODE *node;
  2285. int i;
  2286. BIO_printf(out, "%s Policies:", name);
  2287. if (nodes) {
  2288. BIO_puts(out, "\n");
  2289. for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
  2290. node = sk_X509_POLICY_NODE_value(nodes, i);
  2291. X509_POLICY_NODE_print(out, node, 2);
  2292. }
  2293. } else
  2294. BIO_puts(out, " <empty>\n");
  2295. }
  2296. void policies_print(BIO *out, X509_STORE_CTX *ctx)
  2297. {
  2298. X509_POLICY_TREE *tree;
  2299. int explicit_policy;
  2300. int free_out = 0;
  2301. if (out == NULL) {
  2302. out = BIO_new_fp(stderr, BIO_NOCLOSE);
  2303. free_out = 1;
  2304. }
  2305. tree = X509_STORE_CTX_get0_policy_tree(ctx);
  2306. explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
  2307. BIO_printf(out, "Require explicit Policy: %s\n",
  2308. explicit_policy ? "True" : "False");
  2309. nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
  2310. nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
  2311. if (free_out)
  2312. BIO_free(out);
  2313. }
  2314. #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
  2315. static JPAKE_CTX *jpake_init(const char *us, const char *them,
  2316. const char *secret)
  2317. {
  2318. BIGNUM *p = NULL;
  2319. BIGNUM *g = NULL;
  2320. BIGNUM *q = NULL;
  2321. BIGNUM *bnsecret = BN_new();
  2322. JPAKE_CTX *ctx;
  2323. /* Use a safe prime for p (that we found earlier) */
  2324. BN_hex2bn(&p,
  2325. "F9E5B365665EA7A05A9C534502780FEE6F1AB5BD4F49947FD036DBD7E905269AF46EF28B0FC07487EE4F5D20FB3C0AF8E700F3A2FA3414970CBED44FEDFF80CE78D800F184BB82435D137AADA2C6C16523247930A63B85661D1FC817A51ACD96168E95898A1F83A79FFB529368AA7833ABD1B0C3AEDDB14D2E1A2F71D99F763F");
  2326. g = BN_new();
  2327. BN_set_word(g, 2);
  2328. q = BN_new();
  2329. BN_rshift1(q, p);
  2330. BN_bin2bn((const unsigned char *)secret, strlen(secret), bnsecret);
  2331. ctx = JPAKE_CTX_new(us, them, p, g, q, bnsecret);
  2332. BN_free(bnsecret);
  2333. BN_free(q);
  2334. BN_free(g);
  2335. BN_free(p);
  2336. return ctx;
  2337. }
  2338. static void jpake_send_part(BIO *conn, const JPAKE_STEP_PART *p)
  2339. {
  2340. BN_print(conn, p->gx);
  2341. BIO_puts(conn, "\n");
  2342. BN_print(conn, p->zkpx.gr);
  2343. BIO_puts(conn, "\n");
  2344. BN_print(conn, p->zkpx.b);
  2345. BIO_puts(conn, "\n");
  2346. }
  2347. static void jpake_send_step1(BIO *bconn, JPAKE_CTX *ctx)
  2348. {
  2349. JPAKE_STEP1 s1;
  2350. JPAKE_STEP1_init(&s1);
  2351. JPAKE_STEP1_generate(&s1, ctx);
  2352. jpake_send_part(bconn, &s1.p1);
  2353. jpake_send_part(bconn, &s1.p2);
  2354. (void)BIO_flush(bconn);
  2355. JPAKE_STEP1_release(&s1);
  2356. }
  2357. static void jpake_send_step2(BIO *bconn, JPAKE_CTX *ctx)
  2358. {
  2359. JPAKE_STEP2 s2;
  2360. JPAKE_STEP2_init(&s2);
  2361. JPAKE_STEP2_generate(&s2, ctx);
  2362. jpake_send_part(bconn, &s2);
  2363. (void)BIO_flush(bconn);
  2364. JPAKE_STEP2_release(&s2);
  2365. }
  2366. static void jpake_send_step3a(BIO *bconn, JPAKE_CTX *ctx)
  2367. {
  2368. JPAKE_STEP3A s3a;
  2369. JPAKE_STEP3A_init(&s3a);
  2370. JPAKE_STEP3A_generate(&s3a, ctx);
  2371. BIO_write(bconn, s3a.hhk, sizeof s3a.hhk);
  2372. (void)BIO_flush(bconn);
  2373. JPAKE_STEP3A_release(&s3a);
  2374. }
  2375. static void jpake_send_step3b(BIO *bconn, JPAKE_CTX *ctx)
  2376. {
  2377. JPAKE_STEP3B s3b;
  2378. JPAKE_STEP3B_init(&s3b);
  2379. JPAKE_STEP3B_generate(&s3b, ctx);
  2380. BIO_write(bconn, s3b.hk, sizeof s3b.hk);
  2381. (void)BIO_flush(bconn);
  2382. JPAKE_STEP3B_release(&s3b);
  2383. }
  2384. static void readbn(BIGNUM **bn, BIO *bconn)
  2385. {
  2386. char buf[10240];
  2387. int l;
  2388. l = BIO_gets(bconn, buf, sizeof buf);
  2389. assert(l > 0);
  2390. assert(buf[l - 1] == '\n');
  2391. buf[l - 1] = '\0';
  2392. BN_hex2bn(bn, buf);
  2393. }
  2394. static void jpake_receive_part(JPAKE_STEP_PART *p, BIO *bconn)
  2395. {
  2396. readbn(&p->gx, bconn);
  2397. readbn(&p->zkpx.gr, bconn);
  2398. readbn(&p->zkpx.b, bconn);
  2399. }
  2400. static void jpake_receive_step1(JPAKE_CTX *ctx, BIO *bconn)
  2401. {
  2402. JPAKE_STEP1 s1;
  2403. JPAKE_STEP1_init(&s1);
  2404. jpake_receive_part(&s1.p1, bconn);
  2405. jpake_receive_part(&s1.p2, bconn);
  2406. if (!JPAKE_STEP1_process(ctx, &s1)) {
  2407. ERR_print_errors(bio_err);
  2408. exit(1);
  2409. }
  2410. JPAKE_STEP1_release(&s1);
  2411. }
  2412. static void jpake_receive_step2(JPAKE_CTX *ctx, BIO *bconn)
  2413. {
  2414. JPAKE_STEP2 s2;
  2415. JPAKE_STEP2_init(&s2);
  2416. jpake_receive_part(&s2, bconn);
  2417. if (!JPAKE_STEP2_process(ctx, &s2)) {
  2418. ERR_print_errors(bio_err);
  2419. exit(1);
  2420. }
  2421. JPAKE_STEP2_release(&s2);
  2422. }
  2423. static void jpake_receive_step3a(JPAKE_CTX *ctx, BIO *bconn)
  2424. {
  2425. JPAKE_STEP3A s3a;
  2426. int l;
  2427. JPAKE_STEP3A_init(&s3a);
  2428. l = BIO_read(bconn, s3a.hhk, sizeof s3a.hhk);
  2429. assert(l == sizeof s3a.hhk);
  2430. if (!JPAKE_STEP3A_process(ctx, &s3a)) {
  2431. ERR_print_errors(bio_err);
  2432. exit(1);
  2433. }
  2434. JPAKE_STEP3A_release(&s3a);
  2435. }
  2436. static void jpake_receive_step3b(JPAKE_CTX *ctx, BIO *bconn)
  2437. {
  2438. JPAKE_STEP3B s3b;
  2439. int l;
  2440. JPAKE_STEP3B_init(&s3b);
  2441. l = BIO_read(bconn, s3b.hk, sizeof s3b.hk);
  2442. assert(l == sizeof s3b.hk);
  2443. if (!JPAKE_STEP3B_process(ctx, &s3b)) {
  2444. ERR_print_errors(bio_err);
  2445. exit(1);
  2446. }
  2447. JPAKE_STEP3B_release(&s3b);
  2448. }
  2449. void jpake_client_auth(BIO *out, BIO *conn, const char *secret)
  2450. {
  2451. JPAKE_CTX *ctx;
  2452. BIO *bconn;
  2453. BIO_puts(out, "Authenticating with JPAKE\n");
  2454. ctx = jpake_init("client", "server", secret);
  2455. bconn = BIO_new(BIO_f_buffer());
  2456. BIO_push(bconn, conn);
  2457. jpake_send_step1(bconn, ctx);
  2458. jpake_receive_step1(ctx, bconn);
  2459. jpake_send_step2(bconn, ctx);
  2460. jpake_receive_step2(ctx, bconn);
  2461. jpake_send_step3a(bconn, ctx);
  2462. jpake_receive_step3b(ctx, bconn);
  2463. BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
  2464. if (psk_key)
  2465. OPENSSL_free(psk_key);
  2466. psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
  2467. BIO_pop(bconn);
  2468. BIO_free(bconn);
  2469. JPAKE_CTX_free(ctx);
  2470. }
  2471. void jpake_server_auth(BIO *out, BIO *conn, const char *secret)
  2472. {
  2473. JPAKE_CTX *ctx;
  2474. BIO *bconn;
  2475. BIO_puts(out, "Authenticating with JPAKE\n");
  2476. ctx = jpake_init("server", "client", secret);
  2477. bconn = BIO_new(BIO_f_buffer());
  2478. BIO_push(bconn, conn);
  2479. jpake_receive_step1(ctx, bconn);
  2480. jpake_send_step1(bconn, ctx);
  2481. jpake_receive_step2(ctx, bconn);
  2482. jpake_send_step2(bconn, ctx);
  2483. jpake_receive_step3a(ctx, bconn);
  2484. jpake_send_step3b(bconn, ctx);
  2485. BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
  2486. if (psk_key)
  2487. OPENSSL_free(psk_key);
  2488. psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
  2489. BIO_pop(bconn);
  2490. BIO_free(bconn);
  2491. JPAKE_CTX_free(ctx);
  2492. }
  2493. #endif
  2494. #ifndef OPENSSL_NO_TLSEXT
  2495. /*-
  2496. * next_protos_parse parses a comma separated list of strings into a string
  2497. * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
  2498. * outlen: (output) set to the length of the resulting buffer on success.
  2499. * err: (maybe NULL) on failure, an error message line is written to this BIO.
  2500. * in: a NUL termianted string like "abc,def,ghi"
  2501. *
  2502. * returns: a malloced buffer or NULL on failure.
  2503. */
  2504. unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
  2505. {
  2506. size_t len;
  2507. unsigned char *out;
  2508. size_t i, start = 0;
  2509. len = strlen(in);
  2510. if (len >= 65535)
  2511. return NULL;
  2512. out = OPENSSL_malloc(strlen(in) + 1);
  2513. if (!out)
  2514. return NULL;
  2515. for (i = 0; i <= len; ++i) {
  2516. if (i == len || in[i] == ',') {
  2517. if (i - start > 255) {
  2518. OPENSSL_free(out);
  2519. return NULL;
  2520. }
  2521. out[start] = i - start;
  2522. start = i + 1;
  2523. } else
  2524. out[i + 1] = in[i];
  2525. }
  2526. *outlen = len + 1;
  2527. return out;
  2528. }
  2529. #endif /* ndef OPENSSL_NO_TLSEXT */
  2530. void print_cert_checks(BIO *bio, X509 *x,
  2531. const char *checkhost,
  2532. const char *checkemail, const char *checkip)
  2533. {
  2534. if (x == NULL)
  2535. return;
  2536. if (checkhost) {
  2537. BIO_printf(bio, "Hostname %s does%s match certificate\n",
  2538. checkhost, X509_check_host(x, checkhost, 0, 0, NULL) == 1
  2539. ? "" : " NOT");
  2540. }
  2541. if (checkemail) {
  2542. BIO_printf(bio, "Email %s does%s match certificate\n",
  2543. checkemail, X509_check_email(x, checkemail, 0,
  2544. 0) ? "" : " NOT");
  2545. }
  2546. if (checkip) {
  2547. BIO_printf(bio, "IP %s does%s match certificate\n",
  2548. checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
  2549. }
  2550. }
  2551. /* Get first http URL from a DIST_POINT structure */
  2552. static const char *get_dp_url(DIST_POINT *dp)
  2553. {
  2554. GENERAL_NAMES *gens;
  2555. GENERAL_NAME *gen;
  2556. int i, gtype;
  2557. ASN1_STRING *uri;
  2558. if (!dp->distpoint || dp->distpoint->type != 0)
  2559. return NULL;
  2560. gens = dp->distpoint->name.fullname;
  2561. for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
  2562. gen = sk_GENERAL_NAME_value(gens, i);
  2563. uri = GENERAL_NAME_get0_value(gen, &gtype);
  2564. if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
  2565. char *uptr = (char *)ASN1_STRING_data(uri);
  2566. if (!strncmp(uptr, "http://", 7))
  2567. return uptr;
  2568. }
  2569. }
  2570. return NULL;
  2571. }
  2572. /*
  2573. * Look through a CRLDP structure and attempt to find an http URL to
  2574. * downloads a CRL from.
  2575. */
  2576. static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
  2577. {
  2578. int i;
  2579. const char *urlptr = NULL;
  2580. for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
  2581. DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
  2582. urlptr = get_dp_url(dp);
  2583. if (urlptr)
  2584. return load_crl(urlptr, FORMAT_HTTP);
  2585. }
  2586. return NULL;
  2587. }
  2588. /*
  2589. * Example of downloading CRLs from CRLDP: not usable for real world as it
  2590. * always downloads, doesn't support non-blocking I/O and doesn't cache
  2591. * anything.
  2592. */
  2593. static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
  2594. {
  2595. X509 *x;
  2596. STACK_OF(X509_CRL) *crls = NULL;
  2597. X509_CRL *crl;
  2598. STACK_OF(DIST_POINT) *crldp;
  2599. x = X509_STORE_CTX_get_current_cert(ctx);
  2600. crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
  2601. crl = load_crl_crldp(crldp);
  2602. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  2603. if (!crl)
  2604. return NULL;
  2605. crls = sk_X509_CRL_new_null();
  2606. sk_X509_CRL_push(crls, crl);
  2607. /* Try to download delta CRL */
  2608. crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
  2609. crl = load_crl_crldp(crldp);
  2610. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  2611. if (crl)
  2612. sk_X509_CRL_push(crls, crl);
  2613. return crls;
  2614. }
  2615. void store_setup_crl_download(X509_STORE *st)
  2616. {
  2617. X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
  2618. }
  2619. /*
  2620. * Platform-specific sections
  2621. */
  2622. #if defined(_WIN32)
  2623. # ifdef fileno
  2624. # undef fileno
  2625. # define fileno(a) (int)_fileno(a)
  2626. # endif
  2627. # include <windows.h>
  2628. # include <tchar.h>
  2629. static int WIN32_rename(const char *from, const char *to)
  2630. {
  2631. TCHAR *tfrom = NULL, *tto;
  2632. DWORD err;
  2633. int ret = 0;
  2634. if (sizeof(TCHAR) == 1) {
  2635. tfrom = (TCHAR *)from;
  2636. tto = (TCHAR *)to;
  2637. } else { /* UNICODE path */
  2638. size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
  2639. tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
  2640. if (tfrom == NULL)
  2641. goto err;
  2642. tto = tfrom + flen;
  2643. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2644. if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
  2645. # endif
  2646. for (i = 0; i < flen; i++)
  2647. tfrom[i] = (TCHAR)from[i];
  2648. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2649. if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
  2650. # endif
  2651. for (i = 0; i < tlen; i++)
  2652. tto[i] = (TCHAR)to[i];
  2653. }
  2654. if (MoveFile(tfrom, tto))
  2655. goto ok;
  2656. err = GetLastError();
  2657. if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
  2658. if (DeleteFile(tto) && MoveFile(tfrom, tto))
  2659. goto ok;
  2660. err = GetLastError();
  2661. }
  2662. if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
  2663. errno = ENOENT;
  2664. else if (err == ERROR_ACCESS_DENIED)
  2665. errno = EACCES;
  2666. else
  2667. errno = EINVAL; /* we could map more codes... */
  2668. err:
  2669. ret = -1;
  2670. ok:
  2671. if (tfrom != NULL && tfrom != (TCHAR *)from)
  2672. free(tfrom);
  2673. return ret;
  2674. }
  2675. #endif
  2676. /* app_tminterval section */
  2677. #if defined(_WIN32)
  2678. double app_tminterval(int stop, int usertime)
  2679. {
  2680. FILETIME now;
  2681. double ret = 0;
  2682. static ULARGE_INTEGER tmstart;
  2683. static int warning = 1;
  2684. # ifdef _WIN32_WINNT
  2685. static HANDLE proc = NULL;
  2686. if (proc == NULL) {
  2687. if (check_winnt())
  2688. proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
  2689. GetCurrentProcessId());
  2690. if (proc == NULL)
  2691. proc = (HANDLE) - 1;
  2692. }
  2693. if (usertime && proc != (HANDLE) - 1) {
  2694. FILETIME junk;
  2695. GetProcessTimes(proc, &junk, &junk, &junk, &now);
  2696. } else
  2697. # endif
  2698. {
  2699. SYSTEMTIME systime;
  2700. if (usertime && warning) {
  2701. BIO_printf(bio_err, "To get meaningful results, run "
  2702. "this program on idle system.\n");
  2703. warning = 0;
  2704. }
  2705. GetSystemTime(&systime);
  2706. SystemTimeToFileTime(&systime, &now);
  2707. }
  2708. if (stop == TM_START) {
  2709. tmstart.u.LowPart = now.dwLowDateTime;
  2710. tmstart.u.HighPart = now.dwHighDateTime;
  2711. } else {
  2712. ULARGE_INTEGER tmstop;
  2713. tmstop.u.LowPart = now.dwLowDateTime;
  2714. tmstop.u.HighPart = now.dwHighDateTime;
  2715. ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
  2716. }
  2717. return (ret);
  2718. }
  2719. #elif defined(OPENSSL_SYS_NETWARE)
  2720. # include <time.h>
  2721. double app_tminterval(int stop, int usertime)
  2722. {
  2723. double ret = 0;
  2724. static clock_t tmstart;
  2725. static int warning = 1;
  2726. if (usertime && warning) {
  2727. BIO_printf(bio_err, "To get meaningful results, run "
  2728. "this program on idle system.\n");
  2729. warning = 0;
  2730. }
  2731. if (stop == TM_START)
  2732. tmstart = clock();
  2733. else
  2734. ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
  2735. return (ret);
  2736. }
  2737. #elif defined(OPENSSL_SYSTEM_VXWORKS)
  2738. # include <time.h>
  2739. double app_tminterval(int stop, int usertime)
  2740. {
  2741. double ret = 0;
  2742. # ifdef CLOCK_REALTIME
  2743. static struct timespec tmstart;
  2744. struct timespec now;
  2745. # else
  2746. static unsigned long tmstart;
  2747. unsigned long now;
  2748. # endif
  2749. static int warning = 1;
  2750. if (usertime && warning) {
  2751. BIO_printf(bio_err, "To get meaningful results, run "
  2752. "this program on idle system.\n");
  2753. warning = 0;
  2754. }
  2755. # ifdef CLOCK_REALTIME
  2756. clock_gettime(CLOCK_REALTIME, &now);
  2757. if (stop == TM_START)
  2758. tmstart = now;
  2759. else
  2760. ret = ((now.tv_sec + now.tv_nsec * 1e-9)
  2761. - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
  2762. # else
  2763. now = tickGet();
  2764. if (stop == TM_START)
  2765. tmstart = now;
  2766. else
  2767. ret = (now - tmstart) / (double)sysClkRateGet();
  2768. # endif
  2769. return (ret);
  2770. }
  2771. #elif defined(OPENSSL_SYSTEM_VMS)
  2772. # include <time.h>
  2773. # include <times.h>
  2774. double app_tminterval(int stop, int usertime)
  2775. {
  2776. static clock_t tmstart;
  2777. double ret = 0;
  2778. clock_t now;
  2779. # ifdef __TMS
  2780. struct tms rus;
  2781. now = times(&rus);
  2782. if (usertime)
  2783. now = rus.tms_utime;
  2784. # else
  2785. if (usertime)
  2786. now = clock(); /* sum of user and kernel times */
  2787. else {
  2788. struct timeval tv;
  2789. gettimeofday(&tv, NULL);
  2790. now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
  2791. (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
  2792. );
  2793. }
  2794. # endif
  2795. if (stop == TM_START)
  2796. tmstart = now;
  2797. else
  2798. ret = (now - tmstart) / (double)(CLK_TCK);
  2799. return (ret);
  2800. }
  2801. #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
  2802. # include <sys/times.h>
  2803. double app_tminterval(int stop, int usertime)
  2804. {
  2805. double ret = 0;
  2806. struct tms rus;
  2807. clock_t now = times(&rus);
  2808. static clock_t tmstart;
  2809. if (usertime)
  2810. now = rus.tms_utime;
  2811. if (stop == TM_START)
  2812. tmstart = now;
  2813. else {
  2814. long int tck = sysconf(_SC_CLK_TCK);
  2815. ret = (now - tmstart) / (double)tck;
  2816. }
  2817. return (ret);
  2818. }
  2819. #else
  2820. # include <sys/time.h>
  2821. # include <sys/resource.h>
  2822. double app_tminterval(int stop, int usertime)
  2823. {
  2824. double ret = 0;
  2825. struct rusage rus;
  2826. struct timeval now;
  2827. static struct timeval tmstart;
  2828. if (usertime)
  2829. getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
  2830. else
  2831. gettimeofday(&now, NULL);
  2832. if (stop == TM_START)
  2833. tmstart = now;
  2834. else
  2835. ret = ((now.tv_sec + now.tv_usec * 1e-6)
  2836. - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
  2837. return ret;
  2838. }
  2839. #endif
  2840. /* app_isdir section */
  2841. #ifdef _WIN32
  2842. int app_isdir(const char *name)
  2843. {
  2844. HANDLE hList;
  2845. WIN32_FIND_DATA FileData;
  2846. # if defined(UNICODE) || defined(_UNICODE)
  2847. size_t i, len_0 = strlen(name) + 1;
  2848. if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
  2849. return -1;
  2850. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2851. if (!MultiByteToWideChar
  2852. (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
  2853. # endif
  2854. for (i = 0; i < len_0; i++)
  2855. FileData.cFileName[i] = (WCHAR)name[i];
  2856. hList = FindFirstFile(FileData.cFileName, &FileData);
  2857. # else
  2858. hList = FindFirstFile(name, &FileData);
  2859. # endif
  2860. if (hList == INVALID_HANDLE_VALUE)
  2861. return -1;
  2862. FindClose(hList);
  2863. return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  2864. }
  2865. #else
  2866. # include <sys/stat.h>
  2867. # ifndef S_ISDIR
  2868. # if defined(_S_IFMT) && defined(_S_IFDIR)
  2869. # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
  2870. # else
  2871. # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
  2872. # endif
  2873. # endif
  2874. int app_isdir(const char *name)
  2875. {
  2876. # if defined(S_ISDIR)
  2877. struct stat st;
  2878. if (stat(name, &st) == 0)
  2879. return S_ISDIR(st.st_mode);
  2880. else
  2881. return -1;
  2882. # else
  2883. return -1;
  2884. # endif
  2885. }
  2886. #endif
  2887. /* raw_read|write section */
  2888. #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
  2889. int raw_read_stdin(void *buf, int siz)
  2890. {
  2891. DWORD n;
  2892. if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
  2893. return (n);
  2894. else
  2895. return (-1);
  2896. }
  2897. #else
  2898. int raw_read_stdin(void *buf, int siz)
  2899. {
  2900. return read(fileno(stdin), buf, siz);
  2901. }
  2902. #endif
  2903. #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
  2904. int raw_write_stdout(const void *buf, int siz)
  2905. {
  2906. DWORD n;
  2907. if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
  2908. return (n);
  2909. else
  2910. return (-1);
  2911. }
  2912. #else
  2913. int raw_write_stdout(const void *buf, int siz)
  2914. {
  2915. return write(fileno(stdout), buf, siz);
  2916. }
  2917. #endif