apps.c 73 KB

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