apps.c 89 KB

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