apps.c 71 KB

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