apps.c 74 KB

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