apps.c 78 KB

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