apps.c 74 KB

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