apps.c 73 KB

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