apps.c 72 KB

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