apps.c 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400
  1. /*
  2. * Copyright 1995-2023 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. #ifndef OPENSSL_NO_ENGINE
  17. /* We need to use some deprecated APIs */
  18. # define OPENSSL_SUPPRESS_DEPRECATED
  19. # include <openssl/engine.h>
  20. #endif
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <sys/types.h>
  25. #ifndef OPENSSL_NO_POSIX_IO
  26. # include <sys/stat.h>
  27. # include <fcntl.h>
  28. #endif
  29. #include <ctype.h>
  30. #include <errno.h>
  31. #include <openssl/err.h>
  32. #include <openssl/x509.h>
  33. #include <openssl/x509v3.h>
  34. #include <openssl/http.h>
  35. #include <openssl/pem.h>
  36. #include <openssl/store.h>
  37. #include <openssl/pkcs12.h>
  38. #include <openssl/ui.h>
  39. #include <openssl/safestack.h>
  40. #include <openssl/rsa.h>
  41. #include <openssl/rand.h>
  42. #include <openssl/bn.h>
  43. #include <openssl/ssl.h>
  44. #include <openssl/store.h>
  45. #include <openssl/core_names.h>
  46. #include "s_apps.h"
  47. #include "apps.h"
  48. #ifdef _WIN32
  49. static int WIN32_rename(const char *from, const char *to);
  50. # define rename(from,to) WIN32_rename((from),(to))
  51. #endif
  52. #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
  53. # include <conio.h>
  54. #endif
  55. #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
  56. # define _kbhit kbhit
  57. #endif
  58. static BIO *bio_open_default_(const char *filename, char mode, int format,
  59. int quiet);
  60. #define PASS_SOURCE_SIZE_MAX 4
  61. DEFINE_STACK_OF(CONF)
  62. typedef struct {
  63. const char *name;
  64. unsigned long flag;
  65. unsigned long mask;
  66. } NAME_EX_TBL;
  67. static int set_table_opts(unsigned long *flags, const char *arg,
  68. const NAME_EX_TBL * in_tbl);
  69. static int set_multi_opts(unsigned long *flags, const char *arg,
  70. const NAME_EX_TBL * in_tbl);
  71. static
  72. int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
  73. const char *pass, const char *desc,
  74. EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
  75. EVP_PKEY **pparams,
  76. X509 **pcert, STACK_OF(X509) **pcerts,
  77. X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
  78. int suppress_decode_errors);
  79. int app_init(long mesgwin);
  80. int chopup_args(ARGS *arg, char *buf)
  81. {
  82. int quoted;
  83. char c = '\0', *p = NULL;
  84. arg->argc = 0;
  85. if (arg->size == 0) {
  86. arg->size = 20;
  87. arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
  88. }
  89. for (p = buf;;) {
  90. /* Skip whitespace. */
  91. while (*p && isspace(_UC(*p)))
  92. p++;
  93. if (*p == '\0')
  94. break;
  95. /* The start of something good :-) */
  96. if (arg->argc >= arg->size) {
  97. char **tmp;
  98. arg->size += 20;
  99. tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
  100. if (tmp == NULL)
  101. return 0;
  102. arg->argv = tmp;
  103. }
  104. quoted = *p == '\'' || *p == '"';
  105. if (quoted)
  106. c = *p++;
  107. arg->argv[arg->argc++] = p;
  108. /* now look for the end of this */
  109. if (quoted) {
  110. while (*p && *p != c)
  111. p++;
  112. *p++ = '\0';
  113. } else {
  114. while (*p && !isspace(_UC(*p)))
  115. p++;
  116. if (*p)
  117. *p++ = '\0';
  118. }
  119. }
  120. arg->argv[arg->argc] = NULL;
  121. return 1;
  122. }
  123. #ifndef APP_INIT
  124. int app_init(long mesgwin)
  125. {
  126. return 1;
  127. }
  128. #endif
  129. int ctx_set_verify_locations(SSL_CTX *ctx,
  130. const char *CAfile, int noCAfile,
  131. const char *CApath, int noCApath,
  132. const char *CAstore, int noCAstore)
  133. {
  134. if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
  135. if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
  136. return 0;
  137. if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
  138. return 0;
  139. if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
  140. return 0;
  141. return 1;
  142. }
  143. if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
  144. return 0;
  145. if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
  146. return 0;
  147. if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
  148. return 0;
  149. return 1;
  150. }
  151. #ifndef OPENSSL_NO_CT
  152. int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
  153. {
  154. if (path == NULL)
  155. return SSL_CTX_set_default_ctlog_list_file(ctx);
  156. return SSL_CTX_set_ctlog_list_file(ctx, path);
  157. }
  158. #endif
  159. static unsigned long nmflag = 0;
  160. static char nmflag_set = 0;
  161. int set_nameopt(const char *arg)
  162. {
  163. int ret = set_name_ex(&nmflag, arg);
  164. if (ret)
  165. nmflag_set = 1;
  166. return ret;
  167. }
  168. unsigned long get_nameopt(void)
  169. {
  170. return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
  171. }
  172. void dump_cert_text(BIO *out, X509 *x)
  173. {
  174. print_name(out, "subject=", X509_get_subject_name(x));
  175. print_name(out, "issuer=", X509_get_issuer_name(x));
  176. }
  177. int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
  178. {
  179. return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
  180. }
  181. static char *app_get_pass(const char *arg, int keepbio);
  182. char *get_passwd(const char *pass, const char *desc)
  183. {
  184. char *result = NULL;
  185. if (desc == NULL)
  186. desc = "<unknown>";
  187. if (!app_passwd(pass, NULL, &result, NULL))
  188. BIO_printf(bio_err, "Error getting password for %s\n", desc);
  189. if (pass != NULL && result == NULL) {
  190. BIO_printf(bio_err,
  191. "Trying plain input string (better precede with 'pass:')\n");
  192. result = OPENSSL_strdup(pass);
  193. if (result == NULL)
  194. BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
  195. }
  196. return result;
  197. }
  198. int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
  199. {
  200. int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
  201. if (arg1 != NULL) {
  202. *pass1 = app_get_pass(arg1, same);
  203. if (*pass1 == NULL)
  204. return 0;
  205. } else if (pass1 != NULL) {
  206. *pass1 = NULL;
  207. }
  208. if (arg2 != NULL) {
  209. *pass2 = app_get_pass(arg2, same ? 2 : 0);
  210. if (*pass2 == NULL)
  211. return 0;
  212. } else if (pass2 != NULL) {
  213. *pass2 = NULL;
  214. }
  215. return 1;
  216. }
  217. static char *app_get_pass(const char *arg, int keepbio)
  218. {
  219. static BIO *pwdbio = NULL;
  220. char *tmp, tpass[APP_PASS_LEN];
  221. int i;
  222. /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
  223. if (strncmp(arg, "pass:", 5) == 0)
  224. return OPENSSL_strdup(arg + 5);
  225. if (strncmp(arg, "env:", 4) == 0) {
  226. tmp = getenv(arg + 4);
  227. if (tmp == NULL) {
  228. BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
  229. return NULL;
  230. }
  231. return OPENSSL_strdup(tmp);
  232. }
  233. if (!keepbio || pwdbio == NULL) {
  234. if (strncmp(arg, "file:", 5) == 0) {
  235. pwdbio = BIO_new_file(arg + 5, "r");
  236. if (pwdbio == NULL) {
  237. BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
  238. return NULL;
  239. }
  240. #if !defined(_WIN32)
  241. /*
  242. * Under _WIN32, which covers even Win64 and CE, file
  243. * descriptors referenced by BIO_s_fd are not inherited
  244. * by child process and therefore below is not an option.
  245. * It could have been an option if bss_fd.c was operating
  246. * on real Windows descriptors, such as those obtained
  247. * with CreateFile.
  248. */
  249. } else if (strncmp(arg, "fd:", 3) == 0) {
  250. BIO *btmp;
  251. i = atoi(arg + 3);
  252. if (i >= 0)
  253. pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
  254. if ((i < 0) || pwdbio == NULL) {
  255. BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
  256. return NULL;
  257. }
  258. /*
  259. * Can't do BIO_gets on an fd BIO so add a buffering BIO
  260. */
  261. btmp = BIO_new(BIO_f_buffer());
  262. if (btmp == NULL) {
  263. BIO_free_all(pwdbio);
  264. pwdbio = NULL;
  265. BIO_printf(bio_err, "Out of memory\n");
  266. return NULL;
  267. }
  268. pwdbio = BIO_push(btmp, pwdbio);
  269. #endif
  270. } else if (strcmp(arg, "stdin") == 0) {
  271. unbuffer(stdin);
  272. pwdbio = dup_bio_in(FORMAT_TEXT);
  273. if (pwdbio == NULL) {
  274. BIO_printf(bio_err, "Can't open BIO for stdin\n");
  275. return NULL;
  276. }
  277. } else {
  278. /* argument syntax error; do not reveal too much about arg */
  279. tmp = strchr(arg, ':');
  280. if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
  281. BIO_printf(bio_err,
  282. "Invalid password argument, missing ':' within the first %d chars\n",
  283. PASS_SOURCE_SIZE_MAX + 1);
  284. else
  285. BIO_printf(bio_err,
  286. "Invalid password argument, starting with \"%.*s\"\n",
  287. (int)(tmp - arg + 1), arg);
  288. return NULL;
  289. }
  290. }
  291. i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
  292. if (keepbio != 1) {
  293. BIO_free_all(pwdbio);
  294. pwdbio = NULL;
  295. }
  296. if (i <= 0) {
  297. BIO_printf(bio_err, "Error reading password from BIO\n");
  298. return NULL;
  299. }
  300. tmp = strchr(tpass, '\n');
  301. if (tmp != NULL)
  302. *tmp = 0;
  303. return OPENSSL_strdup(tpass);
  304. }
  305. CONF *app_load_config_bio(BIO *in, const char *filename)
  306. {
  307. long errorline = -1;
  308. CONF *conf;
  309. int i;
  310. conf = NCONF_new_ex(app_get0_libctx(), NULL);
  311. i = NCONF_load_bio(conf, in, &errorline);
  312. if (i > 0)
  313. return conf;
  314. if (errorline <= 0) {
  315. BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
  316. } else {
  317. BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
  318. errorline);
  319. }
  320. if (filename != NULL)
  321. BIO_printf(bio_err, "config file \"%s\"\n", filename);
  322. else
  323. BIO_printf(bio_err, "config input");
  324. NCONF_free(conf);
  325. return NULL;
  326. }
  327. CONF *app_load_config_verbose(const char *filename, int verbose)
  328. {
  329. if (verbose) {
  330. if (*filename == '\0')
  331. BIO_printf(bio_err, "No configuration used\n");
  332. else
  333. BIO_printf(bio_err, "Using configuration from %s\n", filename);
  334. }
  335. return app_load_config_internal(filename, 0);
  336. }
  337. CONF *app_load_config_internal(const char *filename, int quiet)
  338. {
  339. BIO *in;
  340. CONF *conf;
  341. if (filename == NULL || *filename != '\0') {
  342. if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
  343. return NULL;
  344. conf = app_load_config_bio(in, filename);
  345. BIO_free(in);
  346. } else {
  347. /* Return empty config if filename is empty string. */
  348. conf = NCONF_new_ex(app_get0_libctx(), NULL);
  349. }
  350. return conf;
  351. }
  352. int app_load_modules(const CONF *config)
  353. {
  354. CONF *to_free = NULL;
  355. if (config == NULL)
  356. config = to_free = app_load_config_quiet(default_config_file);
  357. if (config == NULL)
  358. return 1;
  359. if (CONF_modules_load(config, NULL, 0) <= 0) {
  360. BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
  361. ERR_print_errors(bio_err);
  362. NCONF_free(to_free);
  363. return 0;
  364. }
  365. NCONF_free(to_free);
  366. return 1;
  367. }
  368. int add_oid_section(CONF *conf)
  369. {
  370. char *p;
  371. STACK_OF(CONF_VALUE) *sktmp;
  372. CONF_VALUE *cnf;
  373. int i;
  374. if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
  375. ERR_clear_error();
  376. return 1;
  377. }
  378. if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
  379. BIO_printf(bio_err, "problem loading oid section %s\n", p);
  380. return 0;
  381. }
  382. for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
  383. cnf = sk_CONF_VALUE_value(sktmp, i);
  384. if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
  385. BIO_printf(bio_err, "problem creating object %s=%s\n",
  386. cnf->name, cnf->value);
  387. return 0;
  388. }
  389. }
  390. return 1;
  391. }
  392. CONF *app_load_config_modules(const char *configfile)
  393. {
  394. CONF *conf = NULL;
  395. if (configfile != NULL) {
  396. if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
  397. return NULL;
  398. if (configfile != default_config_file && !app_load_modules(conf)) {
  399. NCONF_free(conf);
  400. conf = NULL;
  401. }
  402. }
  403. return conf;
  404. }
  405. #define IS_HTTP(uri) ((uri) != NULL \
  406. && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
  407. #define IS_HTTPS(uri) ((uri) != NULL \
  408. && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
  409. X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
  410. const char *pass, const char *desc)
  411. {
  412. X509 *cert = NULL;
  413. if (desc == NULL)
  414. desc = "certificate";
  415. if (IS_HTTPS(uri))
  416. BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
  417. else if (IS_HTTP(uri))
  418. cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
  419. else
  420. (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
  421. NULL, NULL, NULL, &cert, NULL, NULL, NULL);
  422. if (cert == NULL) {
  423. BIO_printf(bio_err, "Unable to load %s\n", desc);
  424. ERR_print_errors(bio_err);
  425. }
  426. return cert;
  427. }
  428. X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
  429. const char *desc)
  430. {
  431. X509_CRL *crl = NULL;
  432. if (desc == NULL)
  433. desc = "CRL";
  434. if (IS_HTTPS(uri))
  435. BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
  436. else if (IS_HTTP(uri))
  437. crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
  438. else
  439. (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
  440. NULL, NULL, NULL, NULL, NULL, &crl, NULL);
  441. if (crl == NULL) {
  442. BIO_printf(bio_err, "Unable to load %s\n", desc);
  443. ERR_print_errors(bio_err);
  444. }
  445. return crl;
  446. }
  447. X509_REQ *load_csr(const char *file, int format, const char *desc)
  448. {
  449. X509_REQ *req = NULL;
  450. BIO *in;
  451. if (format == FORMAT_UNDEF)
  452. format = FORMAT_PEM;
  453. if (desc == NULL)
  454. desc = "CSR";
  455. in = bio_open_default(file, 'r', format);
  456. if (in == NULL)
  457. goto end;
  458. if (format == FORMAT_ASN1)
  459. req = d2i_X509_REQ_bio(in, NULL);
  460. else if (format == FORMAT_PEM)
  461. req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
  462. else
  463. print_format_error(format, OPT_FMT_PEMDER);
  464. end:
  465. if (req == NULL) {
  466. BIO_printf(bio_err, "Unable to load %s\n", desc);
  467. ERR_print_errors(bio_err);
  468. }
  469. BIO_free(in);
  470. return req;
  471. }
  472. void cleanse(char *str)
  473. {
  474. if (str != NULL)
  475. OPENSSL_cleanse(str, strlen(str));
  476. }
  477. void clear_free(char *str)
  478. {
  479. if (str != NULL)
  480. OPENSSL_clear_free(str, strlen(str));
  481. }
  482. EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
  483. const char *pass, ENGINE *e, const char *desc)
  484. {
  485. EVP_PKEY *pkey = NULL;
  486. char *allocated_uri = NULL;
  487. if (desc == NULL)
  488. desc = "private key";
  489. if (format == FORMAT_ENGINE) {
  490. uri = allocated_uri = make_engine_uri(e, uri, desc);
  491. }
  492. (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
  493. &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
  494. OPENSSL_free(allocated_uri);
  495. return pkey;
  496. }
  497. EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
  498. const char *pass, ENGINE *e, const char *desc)
  499. {
  500. EVP_PKEY *pkey = NULL;
  501. char *allocated_uri = NULL;
  502. if (desc == NULL)
  503. desc = "public key";
  504. if (format == FORMAT_ENGINE) {
  505. uri = allocated_uri = make_engine_uri(e, uri, desc);
  506. }
  507. (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
  508. NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
  509. OPENSSL_free(allocated_uri);
  510. return pkey;
  511. }
  512. EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
  513. const char *keytype, const char *desc,
  514. int suppress_decode_errors)
  515. {
  516. EVP_PKEY *params = NULL;
  517. if (desc == NULL)
  518. desc = "key parameters";
  519. (void)load_key_certs_crls_suppress(uri, format, maybe_stdin, NULL, desc,
  520. NULL, NULL, &params, NULL, NULL, NULL,
  521. NULL, suppress_decode_errors);
  522. if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
  523. if (!suppress_decode_errors) {
  524. BIO_printf(bio_err,
  525. "Unable to load %s from %s (unexpected parameters type)\n",
  526. desc, uri);
  527. ERR_print_errors(bio_err);
  528. }
  529. EVP_PKEY_free(params);
  530. params = NULL;
  531. }
  532. return params;
  533. }
  534. EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
  535. const char *keytype, const char *desc)
  536. {
  537. return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
  538. }
  539. void app_bail_out(char *fmt, ...)
  540. {
  541. va_list args;
  542. va_start(args, fmt);
  543. BIO_vprintf(bio_err, fmt, args);
  544. va_end(args);
  545. ERR_print_errors(bio_err);
  546. exit(EXIT_FAILURE);
  547. }
  548. void *app_malloc(size_t sz, const char *what)
  549. {
  550. void *vp = OPENSSL_malloc(sz);
  551. if (vp == NULL)
  552. app_bail_out("%s: Could not allocate %zu bytes for %s\n",
  553. opt_getprog(), sz, what);
  554. return vp;
  555. }
  556. char *next_item(char *opt) /* in list separated by comma and/or space */
  557. {
  558. /* advance to separator (comma or whitespace), if any */
  559. while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0')
  560. opt++;
  561. if (*opt != '\0') {
  562. /* terminate current item */
  563. *opt++ = '\0';
  564. /* skip over any whitespace after separator */
  565. while (isspace(_UC(*opt)))
  566. opt++;
  567. }
  568. return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
  569. }
  570. static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
  571. {
  572. char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
  573. BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
  574. uri, subj, msg);
  575. OPENSSL_free(subj);
  576. }
  577. static void warn_cert(const char *uri, X509 *cert, int warn_EE,
  578. X509_VERIFY_PARAM *vpm)
  579. {
  580. uint32_t ex_flags = X509_get_extension_flags(cert);
  581. int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
  582. X509_get0_notAfter(cert));
  583. if (res != 0)
  584. warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
  585. if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
  586. warn_cert_msg(uri, cert, "is not a CA cert");
  587. }
  588. static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
  589. X509_VERIFY_PARAM *vpm)
  590. {
  591. int i;
  592. for (i = 0; i < sk_X509_num(certs); i++)
  593. warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
  594. }
  595. int load_cert_certs(const char *uri,
  596. X509 **pcert, STACK_OF(X509) **pcerts,
  597. int exclude_http, const char *pass, const char *desc,
  598. X509_VERIFY_PARAM *vpm)
  599. {
  600. int ret = 0;
  601. char *pass_string;
  602. if (exclude_http && (OPENSSL_strncasecmp(uri, "http://", 7) == 0
  603. || OPENSSL_strncasecmp(uri, "https://", 8) == 0)) {
  604. BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
  605. return ret;
  606. }
  607. pass_string = get_passwd(pass, desc);
  608. ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
  609. NULL, NULL, NULL,
  610. pcert, pcerts, NULL, NULL);
  611. clear_free(pass_string);
  612. if (ret) {
  613. if (pcert != NULL)
  614. warn_cert(uri, *pcert, 0, vpm);
  615. if (pcerts != NULL)
  616. warn_certs(uri, *pcerts, 1, vpm);
  617. } else {
  618. if (pcerts != NULL) {
  619. sk_X509_pop_free(*pcerts, X509_free);
  620. *pcerts = NULL;
  621. }
  622. }
  623. return ret;
  624. }
  625. STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
  626. const char *desc, X509_VERIFY_PARAM *vpm)
  627. {
  628. STACK_OF(X509) *certs = NULL;
  629. STACK_OF(X509) *result = sk_X509_new_null();
  630. if (files == NULL)
  631. goto err;
  632. if (result == NULL)
  633. goto oom;
  634. while (files != NULL) {
  635. char *next = next_item(files);
  636. if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
  637. goto err;
  638. if (!X509_add_certs(result, certs,
  639. X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
  640. goto oom;
  641. sk_X509_pop_free(certs, X509_free);
  642. certs = NULL;
  643. files = next;
  644. }
  645. return result;
  646. oom:
  647. BIO_printf(bio_err, "out of memory\n");
  648. err:
  649. sk_X509_pop_free(certs, X509_free);
  650. sk_X509_pop_free(result, X509_free);
  651. return NULL;
  652. }
  653. static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
  654. const STACK_OF(X509) *certs /* may NULL */)
  655. {
  656. int i;
  657. if (store == NULL)
  658. store = X509_STORE_new();
  659. if (store == NULL)
  660. return NULL;
  661. for (i = 0; i < sk_X509_num(certs); i++) {
  662. if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
  663. X509_STORE_free(store);
  664. return NULL;
  665. }
  666. }
  667. return store;
  668. }
  669. /*
  670. * Create cert store structure with certificates read from given file(s).
  671. * Returns pointer to created X509_STORE on success, NULL on error.
  672. */
  673. X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
  674. X509_VERIFY_PARAM *vpm)
  675. {
  676. X509_STORE *store = NULL;
  677. STACK_OF(X509) *certs = NULL;
  678. while (input != NULL) {
  679. char *next = next_item(input);
  680. int ok;
  681. if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
  682. X509_STORE_free(store);
  683. return NULL;
  684. }
  685. ok = (store = sk_X509_to_store(store, certs)) != NULL;
  686. sk_X509_pop_free(certs, X509_free);
  687. certs = NULL;
  688. if (!ok)
  689. return NULL;
  690. input = next;
  691. }
  692. return store;
  693. }
  694. /*
  695. * Initialize or extend, if *certs != NULL, a certificate stack.
  696. * The caller is responsible for freeing *certs if its value is left not NULL.
  697. */
  698. int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
  699. const char *pass, const char *desc)
  700. {
  701. int was_NULL = *certs == NULL;
  702. int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin,
  703. pass, desc, NULL, NULL,
  704. NULL, NULL, certs, NULL, NULL);
  705. if (!ret && was_NULL) {
  706. sk_X509_pop_free(*certs, X509_free);
  707. *certs = NULL;
  708. }
  709. return ret;
  710. }
  711. /*
  712. * Initialize or extend, if *crls != NULL, a certificate stack.
  713. * The caller is responsible for freeing *crls if its value is left not NULL.
  714. */
  715. int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
  716. const char *pass, const char *desc)
  717. {
  718. int was_NULL = *crls == NULL;
  719. int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
  720. NULL, NULL, NULL,
  721. NULL, NULL, NULL, crls);
  722. if (!ret && was_NULL) {
  723. sk_X509_CRL_pop_free(*crls, X509_CRL_free);
  724. *crls = NULL;
  725. }
  726. return ret;
  727. }
  728. static const char *format2string(int format)
  729. {
  730. switch(format) {
  731. case FORMAT_PEM:
  732. return "PEM";
  733. case FORMAT_ASN1:
  734. return "DER";
  735. }
  736. return NULL;
  737. }
  738. /* Set type expectation, but clear it if objects of different types expected. */
  739. #define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0))
  740. /*
  741. * Load those types of credentials for which the result pointer is not NULL.
  742. * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
  743. * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
  744. * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
  745. * If pcerts is non-NULL then all available certificates are appended to *pcerts
  746. * except any certificate assigned to *pcert.
  747. * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
  748. * If pcrls is non-NULL then all available CRLs are appended to *pcerts
  749. * except any CRL assigned to *pcrl.
  750. * In any case (also on error) the caller is responsible for freeing all members
  751. * of *pcerts and *pcrls (as far as they are not NULL).
  752. */
  753. static
  754. int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
  755. const char *pass, const char *desc,
  756. EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
  757. EVP_PKEY **pparams,
  758. X509 **pcert, STACK_OF(X509) **pcerts,
  759. X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
  760. int suppress_decode_errors)
  761. {
  762. PW_CB_DATA uidata;
  763. OSSL_STORE_CTX *ctx = NULL;
  764. OSSL_LIB_CTX *libctx = app_get0_libctx();
  765. const char *propq = app_get0_propq();
  766. int ncerts = 0;
  767. int ncrls = 0;
  768. const char *failed =
  769. ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
  770. pparams != NULL ? "params" : pcert != NULL ? "cert" :
  771. pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" :
  772. pcrls != NULL ? "CRLs" : NULL;
  773. int cnt_expectations = 0;
  774. int expect = -1;
  775. const char *input_type;
  776. OSSL_PARAM itp[2];
  777. const OSSL_PARAM *params = NULL;
  778. if (ppkey != NULL) {
  779. *ppkey = NULL;
  780. cnt_expectations++;
  781. SET_EXPECT(expect, OSSL_STORE_INFO_PKEY);
  782. }
  783. if (ppubkey != NULL) {
  784. *ppubkey = NULL;
  785. cnt_expectations++;
  786. SET_EXPECT(expect, OSSL_STORE_INFO_PUBKEY);
  787. }
  788. if (pparams != NULL) {
  789. *pparams = NULL;
  790. cnt_expectations++;
  791. SET_EXPECT(expect, OSSL_STORE_INFO_PARAMS);
  792. }
  793. if (pcert != NULL) {
  794. *pcert = NULL;
  795. cnt_expectations++;
  796. SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
  797. }
  798. if (pcerts != NULL) {
  799. if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
  800. BIO_printf(bio_err, "Out of memory loading");
  801. goto end;
  802. }
  803. cnt_expectations++;
  804. SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
  805. }
  806. if (pcrl != NULL) {
  807. *pcrl = NULL;
  808. cnt_expectations++;
  809. SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
  810. }
  811. if (pcrls != NULL) {
  812. if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
  813. BIO_printf(bio_err, "Out of memory loading");
  814. goto end;
  815. }
  816. cnt_expectations++;
  817. SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
  818. }
  819. if (cnt_expectations == 0) {
  820. BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
  821. uri != NULL ? uri : "<stdin>");
  822. return 0;
  823. }
  824. uidata.password = pass;
  825. uidata.prompt_info = uri;
  826. if ((input_type = format2string(format)) != NULL) {
  827. itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
  828. (char *)input_type, 0);
  829. itp[1] = OSSL_PARAM_construct_end();
  830. params = itp;
  831. }
  832. if (uri == NULL) {
  833. BIO *bio;
  834. if (!maybe_stdin) {
  835. BIO_printf(bio_err, "No filename or uri specified for loading\n");
  836. goto end;
  837. }
  838. uri = "<stdin>";
  839. unbuffer(stdin);
  840. bio = BIO_new_fp(stdin, 0);
  841. if (bio != NULL) {
  842. ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
  843. get_ui_method(), &uidata, params,
  844. NULL, NULL);
  845. BIO_free(bio);
  846. }
  847. } else {
  848. ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
  849. params, NULL, NULL);
  850. }
  851. if (ctx == NULL) {
  852. BIO_printf(bio_err, "Could not open file or uri for loading");
  853. goto end;
  854. }
  855. if (expect > 0 && !OSSL_STORE_expect(ctx, expect)) {
  856. BIO_printf(bio_err, "Internal error trying to load");
  857. goto end;
  858. }
  859. failed = NULL;
  860. while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) {
  861. OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
  862. int type, ok = 1;
  863. /*
  864. * This can happen (for example) if we attempt to load a file with
  865. * multiple different types of things in it - but the thing we just
  866. * tried to load wasn't one of the ones we wanted, e.g. if we're trying
  867. * to load a certificate but the file has both the private key and the
  868. * certificate in it. We just retry until eof.
  869. */
  870. if (info == NULL) {
  871. continue;
  872. }
  873. type = OSSL_STORE_INFO_get_type(info);
  874. switch (type) {
  875. case OSSL_STORE_INFO_PKEY:
  876. if (ppkey != NULL && *ppkey == NULL) {
  877. ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
  878. cnt_expectations -= ok;
  879. }
  880. /*
  881. * An EVP_PKEY with private parts also holds the public parts,
  882. * so if the caller asked for a public key, and we got a private
  883. * key, we can still pass it back.
  884. */
  885. if (ok && ppubkey != NULL && *ppubkey == NULL) {
  886. ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
  887. cnt_expectations -= ok;
  888. }
  889. break;
  890. case OSSL_STORE_INFO_PUBKEY:
  891. if (ppubkey != NULL && *ppubkey == NULL) {
  892. ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
  893. cnt_expectations -= ok;
  894. }
  895. break;
  896. case OSSL_STORE_INFO_PARAMS:
  897. if (pparams != NULL && *pparams == NULL) {
  898. ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL);
  899. cnt_expectations -= ok;
  900. }
  901. break;
  902. case OSSL_STORE_INFO_CERT:
  903. if (pcert != NULL && *pcert == NULL) {
  904. ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
  905. cnt_expectations -= ok;
  906. }
  907. else if (pcerts != NULL)
  908. ok = X509_add_cert(*pcerts,
  909. OSSL_STORE_INFO_get1_CERT(info),
  910. X509_ADD_FLAG_DEFAULT);
  911. ncerts += ok;
  912. break;
  913. case OSSL_STORE_INFO_CRL:
  914. if (pcrl != NULL && *pcrl == NULL) {
  915. ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
  916. cnt_expectations -= ok;
  917. }
  918. else if (pcrls != NULL)
  919. ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
  920. ncrls += ok;
  921. break;
  922. default:
  923. /* skip any other type */
  924. break;
  925. }
  926. OSSL_STORE_INFO_free(info);
  927. if (!ok) {
  928. failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
  929. BIO_printf(bio_err, "Error reading");
  930. break;
  931. }
  932. }
  933. end:
  934. OSSL_STORE_close(ctx);
  935. if (failed == NULL) {
  936. int any = 0;
  937. if ((ppkey != NULL && *ppkey == NULL)
  938. || (ppubkey != NULL && *ppubkey == NULL)) {
  939. failed = "key";
  940. } else if (pparams != NULL && *pparams == NULL) {
  941. failed = "params";
  942. } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
  943. if (pcert == NULL)
  944. any = 1;
  945. failed = "cert";
  946. } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
  947. if (pcrl == NULL)
  948. any = 1;
  949. failed = "CRL";
  950. }
  951. if (!suppress_decode_errors) {
  952. if (failed != NULL)
  953. BIO_printf(bio_err, "Could not read");
  954. if (any)
  955. BIO_printf(bio_err, " any");
  956. }
  957. }
  958. if (!suppress_decode_errors && failed != NULL) {
  959. if (desc != NULL && strstr(desc, failed) != NULL) {
  960. BIO_printf(bio_err, " %s", desc);
  961. } else {
  962. BIO_printf(bio_err, " %s", failed);
  963. if (desc != NULL)
  964. BIO_printf(bio_err, " of %s", desc);
  965. }
  966. if (uri != NULL)
  967. BIO_printf(bio_err, " from %s", uri);
  968. BIO_printf(bio_err, "\n");
  969. ERR_print_errors(bio_err);
  970. }
  971. if (suppress_decode_errors || failed == NULL)
  972. /* clear any spurious errors */
  973. ERR_clear_error();
  974. return failed == NULL;
  975. }
  976. int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
  977. const char *pass, const char *desc,
  978. EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
  979. EVP_PKEY **pparams,
  980. X509 **pcert, STACK_OF(X509) **pcerts,
  981. X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
  982. {
  983. return load_key_certs_crls_suppress(uri, format, maybe_stdin, pass, desc,
  984. ppkey, ppubkey, pparams, pcert, pcerts,
  985. pcrl, pcrls, 0);
  986. }
  987. #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
  988. /* Return error for unknown extensions */
  989. #define X509V3_EXT_DEFAULT 0
  990. /* Print error for unknown extensions */
  991. #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
  992. /* ASN1 parse unknown extensions */
  993. #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
  994. /* BIO_dump unknown extensions */
  995. #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
  996. #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
  997. X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
  998. int set_cert_ex(unsigned long *flags, const char *arg)
  999. {
  1000. static const NAME_EX_TBL cert_tbl[] = {
  1001. {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
  1002. {"ca_default", X509_FLAG_CA, 0xffffffffl},
  1003. {"no_header", X509_FLAG_NO_HEADER, 0},
  1004. {"no_version", X509_FLAG_NO_VERSION, 0},
  1005. {"no_serial", X509_FLAG_NO_SERIAL, 0},
  1006. {"no_signame", X509_FLAG_NO_SIGNAME, 0},
  1007. {"no_validity", X509_FLAG_NO_VALIDITY, 0},
  1008. {"no_subject", X509_FLAG_NO_SUBJECT, 0},
  1009. {"no_issuer", X509_FLAG_NO_ISSUER, 0},
  1010. {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
  1011. {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
  1012. {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
  1013. {"no_aux", X509_FLAG_NO_AUX, 0},
  1014. {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
  1015. {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
  1016. {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1017. {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1018. {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  1019. {NULL, 0, 0}
  1020. };
  1021. return set_multi_opts(flags, arg, cert_tbl);
  1022. }
  1023. int set_name_ex(unsigned long *flags, const char *arg)
  1024. {
  1025. static const NAME_EX_TBL ex_tbl[] = {
  1026. {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
  1027. {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
  1028. {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
  1029. {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
  1030. {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
  1031. {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
  1032. {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
  1033. {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
  1034. {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
  1035. {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
  1036. {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
  1037. {"compat", XN_FLAG_COMPAT, 0xffffffffL},
  1038. {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
  1039. {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
  1040. {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
  1041. {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
  1042. {"dn_rev", XN_FLAG_DN_REV, 0},
  1043. {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
  1044. {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
  1045. {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
  1046. {"align", XN_FLAG_FN_ALIGN, 0},
  1047. {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
  1048. {"space_eq", XN_FLAG_SPC_EQ, 0},
  1049. {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
  1050. {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
  1051. {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
  1052. {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
  1053. {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
  1054. {NULL, 0, 0}
  1055. };
  1056. if (set_multi_opts(flags, arg, ex_tbl) == 0)
  1057. return 0;
  1058. if (*flags != XN_FLAG_COMPAT
  1059. && (*flags & XN_FLAG_SEP_MASK) == 0)
  1060. *flags |= XN_FLAG_SEP_CPLUS_SPC;
  1061. return 1;
  1062. }
  1063. int set_dateopt(unsigned long *dateopt, const char *arg)
  1064. {
  1065. if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
  1066. *dateopt = ASN1_DTFLGS_RFC822;
  1067. else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
  1068. *dateopt = ASN1_DTFLGS_ISO8601;
  1069. else
  1070. return 0;
  1071. return 1;
  1072. }
  1073. int set_ext_copy(int *copy_type, const char *arg)
  1074. {
  1075. if (OPENSSL_strcasecmp(arg, "none") == 0)
  1076. *copy_type = EXT_COPY_NONE;
  1077. else if (OPENSSL_strcasecmp(arg, "copy") == 0)
  1078. *copy_type = EXT_COPY_ADD;
  1079. else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
  1080. *copy_type = EXT_COPY_ALL;
  1081. else
  1082. return 0;
  1083. return 1;
  1084. }
  1085. int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
  1086. {
  1087. STACK_OF(X509_EXTENSION) *exts;
  1088. int i, ret = 0;
  1089. if (x == NULL || req == NULL)
  1090. return 0;
  1091. if (copy_type == EXT_COPY_NONE)
  1092. return 1;
  1093. exts = X509_REQ_get_extensions(req);
  1094. for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
  1095. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
  1096. ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
  1097. int idx = X509_get_ext_by_OBJ(x, obj, -1);
  1098. /* Does extension exist in target? */
  1099. if (idx != -1) {
  1100. /* If normal copy don't override existing extension */
  1101. if (copy_type == EXT_COPY_ADD)
  1102. continue;
  1103. /* Delete all extensions of same type */
  1104. do {
  1105. X509_EXTENSION_free(X509_delete_ext(x, idx));
  1106. idx = X509_get_ext_by_OBJ(x, obj, -1);
  1107. } while (idx != -1);
  1108. }
  1109. if (!X509_add_ext(x, ext, -1))
  1110. goto end;
  1111. }
  1112. ret = 1;
  1113. end:
  1114. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  1115. return ret;
  1116. }
  1117. static int set_multi_opts(unsigned long *flags, const char *arg,
  1118. const NAME_EX_TBL * in_tbl)
  1119. {
  1120. STACK_OF(CONF_VALUE) *vals;
  1121. CONF_VALUE *val;
  1122. int i, ret = 1;
  1123. if (!arg)
  1124. return 0;
  1125. vals = X509V3_parse_list(arg);
  1126. for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
  1127. val = sk_CONF_VALUE_value(vals, i);
  1128. if (!set_table_opts(flags, val->name, in_tbl))
  1129. ret = 0;
  1130. }
  1131. sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
  1132. return ret;
  1133. }
  1134. static int set_table_opts(unsigned long *flags, const char *arg,
  1135. const NAME_EX_TBL * in_tbl)
  1136. {
  1137. char c;
  1138. const NAME_EX_TBL *ptbl;
  1139. c = arg[0];
  1140. if (c == '-') {
  1141. c = 0;
  1142. arg++;
  1143. } else if (c == '+') {
  1144. c = 1;
  1145. arg++;
  1146. } else {
  1147. c = 1;
  1148. }
  1149. for (ptbl = in_tbl; ptbl->name; ptbl++) {
  1150. if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
  1151. *flags &= ~ptbl->mask;
  1152. if (c)
  1153. *flags |= ptbl->flag;
  1154. else
  1155. *flags &= ~ptbl->flag;
  1156. return 1;
  1157. }
  1158. }
  1159. return 0;
  1160. }
  1161. void print_name(BIO *out, const char *title, const X509_NAME *nm)
  1162. {
  1163. char *buf;
  1164. char mline = 0;
  1165. int indent = 0;
  1166. unsigned long lflags = get_nameopt();
  1167. if (out == NULL)
  1168. return;
  1169. if (title != NULL)
  1170. BIO_puts(out, title);
  1171. if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
  1172. mline = 1;
  1173. indent = 4;
  1174. }
  1175. if (lflags == XN_FLAG_COMPAT) {
  1176. buf = X509_NAME_oneline(nm, 0, 0);
  1177. BIO_puts(out, buf);
  1178. BIO_puts(out, "\n");
  1179. OPENSSL_free(buf);
  1180. } else {
  1181. if (mline)
  1182. BIO_puts(out, "\n");
  1183. X509_NAME_print_ex(out, nm, indent, lflags);
  1184. BIO_puts(out, "\n");
  1185. }
  1186. }
  1187. void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
  1188. int len, unsigned char *buffer)
  1189. {
  1190. BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
  1191. if (BN_is_zero(in)) {
  1192. BIO_printf(out, "\n 0x00");
  1193. } else {
  1194. int i, l;
  1195. l = BN_bn2bin(in, buffer);
  1196. for (i = 0; i < l; i++) {
  1197. BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
  1198. if (i < l - 1)
  1199. BIO_printf(out, "0x%02X,", buffer[i]);
  1200. else
  1201. BIO_printf(out, "0x%02X", buffer[i]);
  1202. }
  1203. }
  1204. BIO_printf(out, "\n };\n");
  1205. }
  1206. void print_array(BIO *out, const char* title, int len, const unsigned char* d)
  1207. {
  1208. int i;
  1209. BIO_printf(out, "unsigned char %s[%d] = {", title, len);
  1210. for (i = 0; i < len; i++) {
  1211. if ((i % 10) == 0)
  1212. BIO_printf(out, "\n ");
  1213. if (i < len - 1)
  1214. BIO_printf(out, "0x%02X, ", d[i]);
  1215. else
  1216. BIO_printf(out, "0x%02X", d[i]);
  1217. }
  1218. BIO_printf(out, "\n};\n");
  1219. }
  1220. X509_STORE *setup_verify(const char *CAfile, int noCAfile,
  1221. const char *CApath, int noCApath,
  1222. const char *CAstore, int noCAstore)
  1223. {
  1224. X509_STORE *store = X509_STORE_new();
  1225. X509_LOOKUP *lookup;
  1226. OSSL_LIB_CTX *libctx = app_get0_libctx();
  1227. const char *propq = app_get0_propq();
  1228. if (store == NULL)
  1229. goto end;
  1230. if (CAfile != NULL || !noCAfile) {
  1231. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1232. if (lookup == NULL)
  1233. goto end;
  1234. if (CAfile != NULL) {
  1235. if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
  1236. libctx, propq) <= 0) {
  1237. BIO_printf(bio_err, "Error loading file %s\n", CAfile);
  1238. goto end;
  1239. }
  1240. } else {
  1241. X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
  1242. libctx, propq);
  1243. }
  1244. }
  1245. if (CApath != NULL || !noCApath) {
  1246. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1247. if (lookup == NULL)
  1248. goto end;
  1249. if (CApath != NULL) {
  1250. if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) {
  1251. BIO_printf(bio_err, "Error loading directory %s\n", CApath);
  1252. goto end;
  1253. }
  1254. } else {
  1255. X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
  1256. }
  1257. }
  1258. if (CAstore != NULL || !noCAstore) {
  1259. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
  1260. if (lookup == NULL)
  1261. goto end;
  1262. if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
  1263. if (CAstore != NULL)
  1264. BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
  1265. goto end;
  1266. }
  1267. }
  1268. ERR_clear_error();
  1269. return store;
  1270. end:
  1271. ERR_print_errors(bio_err);
  1272. X509_STORE_free(store);
  1273. return NULL;
  1274. }
  1275. static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
  1276. {
  1277. const char *n;
  1278. n = a[DB_serial];
  1279. while (*n == '0')
  1280. n++;
  1281. return OPENSSL_LH_strhash(n);
  1282. }
  1283. static int index_serial_cmp(const OPENSSL_CSTRING *a,
  1284. const OPENSSL_CSTRING *b)
  1285. {
  1286. const char *aa, *bb;
  1287. for (aa = a[DB_serial]; *aa == '0'; aa++) ;
  1288. for (bb = b[DB_serial]; *bb == '0'; bb++) ;
  1289. return strcmp(aa, bb);
  1290. }
  1291. static int index_name_qual(char **a)
  1292. {
  1293. return (a[0][0] == 'V');
  1294. }
  1295. static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
  1296. {
  1297. return OPENSSL_LH_strhash(a[DB_name]);
  1298. }
  1299. int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
  1300. {
  1301. return strcmp(a[DB_name], b[DB_name]);
  1302. }
  1303. static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
  1304. static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
  1305. static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
  1306. static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
  1307. #undef BSIZE
  1308. #define BSIZE 256
  1309. BIGNUM *load_serial(const char *serialfile, int *exists, int create,
  1310. ASN1_INTEGER **retai)
  1311. {
  1312. BIO *in = NULL;
  1313. BIGNUM *ret = NULL;
  1314. char buf[1024];
  1315. ASN1_INTEGER *ai = NULL;
  1316. ai = ASN1_INTEGER_new();
  1317. if (ai == NULL)
  1318. goto err;
  1319. in = BIO_new_file(serialfile, "r");
  1320. if (exists != NULL)
  1321. *exists = in != NULL;
  1322. if (in == NULL) {
  1323. if (!create) {
  1324. perror(serialfile);
  1325. goto err;
  1326. }
  1327. ERR_clear_error();
  1328. ret = BN_new();
  1329. if (ret == NULL) {
  1330. BIO_printf(bio_err, "Out of memory\n");
  1331. } else if (!rand_serial(ret, ai)) {
  1332. BIO_printf(bio_err, "Error creating random number to store in %s\n",
  1333. serialfile);
  1334. BN_free(ret);
  1335. ret = NULL;
  1336. }
  1337. } else {
  1338. if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
  1339. BIO_printf(bio_err, "Unable to load number from %s\n",
  1340. serialfile);
  1341. goto err;
  1342. }
  1343. ret = ASN1_INTEGER_to_BN(ai, NULL);
  1344. if (ret == NULL) {
  1345. BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
  1346. goto err;
  1347. }
  1348. }
  1349. if (ret != NULL && retai != NULL) {
  1350. *retai = ai;
  1351. ai = NULL;
  1352. }
  1353. err:
  1354. if (ret == NULL)
  1355. ERR_print_errors(bio_err);
  1356. BIO_free(in);
  1357. ASN1_INTEGER_free(ai);
  1358. return ret;
  1359. }
  1360. int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
  1361. ASN1_INTEGER **retai)
  1362. {
  1363. char buf[1][BSIZE];
  1364. BIO *out = NULL;
  1365. int ret = 0;
  1366. ASN1_INTEGER *ai = NULL;
  1367. int j;
  1368. if (suffix == NULL)
  1369. j = strlen(serialfile);
  1370. else
  1371. j = strlen(serialfile) + strlen(suffix) + 1;
  1372. if (j >= BSIZE) {
  1373. BIO_printf(bio_err, "File name too long\n");
  1374. goto err;
  1375. }
  1376. if (suffix == NULL)
  1377. OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
  1378. else {
  1379. #ifndef OPENSSL_SYS_VMS
  1380. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
  1381. #else
  1382. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
  1383. #endif
  1384. }
  1385. out = BIO_new_file(buf[0], "w");
  1386. if (out == NULL) {
  1387. goto err;
  1388. }
  1389. if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
  1390. BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
  1391. goto err;
  1392. }
  1393. i2a_ASN1_INTEGER(out, ai);
  1394. BIO_puts(out, "\n");
  1395. ret = 1;
  1396. if (retai) {
  1397. *retai = ai;
  1398. ai = NULL;
  1399. }
  1400. err:
  1401. if (!ret)
  1402. ERR_print_errors(bio_err);
  1403. BIO_free_all(out);
  1404. ASN1_INTEGER_free(ai);
  1405. return ret;
  1406. }
  1407. int rotate_serial(const char *serialfile, const char *new_suffix,
  1408. const char *old_suffix)
  1409. {
  1410. char buf[2][BSIZE];
  1411. int i, j;
  1412. i = strlen(serialfile) + strlen(old_suffix);
  1413. j = strlen(serialfile) + strlen(new_suffix);
  1414. if (i > j)
  1415. j = i;
  1416. if (j + 1 >= BSIZE) {
  1417. BIO_printf(bio_err, "File name too long\n");
  1418. goto err;
  1419. }
  1420. #ifndef OPENSSL_SYS_VMS
  1421. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
  1422. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
  1423. #else
  1424. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
  1425. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
  1426. #endif
  1427. if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
  1428. #ifdef ENOTDIR
  1429. && errno != ENOTDIR
  1430. #endif
  1431. ) {
  1432. BIO_printf(bio_err,
  1433. "Unable to rename %s to %s\n", serialfile, buf[1]);
  1434. perror("reason");
  1435. goto err;
  1436. }
  1437. if (rename(buf[0], serialfile) < 0) {
  1438. BIO_printf(bio_err,
  1439. "Unable to rename %s to %s\n", buf[0], serialfile);
  1440. perror("reason");
  1441. rename(buf[1], serialfile);
  1442. goto err;
  1443. }
  1444. return 1;
  1445. err:
  1446. ERR_print_errors(bio_err);
  1447. return 0;
  1448. }
  1449. int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
  1450. {
  1451. BIGNUM *btmp;
  1452. int ret = 0;
  1453. btmp = b == NULL ? BN_new() : b;
  1454. if (btmp == NULL)
  1455. return 0;
  1456. if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
  1457. goto error;
  1458. if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
  1459. goto error;
  1460. ret = 1;
  1461. error:
  1462. if (btmp != b)
  1463. BN_free(btmp);
  1464. return ret;
  1465. }
  1466. CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
  1467. {
  1468. CA_DB *retdb = NULL;
  1469. TXT_DB *tmpdb = NULL;
  1470. BIO *in;
  1471. CONF *dbattr_conf = NULL;
  1472. char buf[BSIZE];
  1473. #ifndef OPENSSL_NO_POSIX_IO
  1474. FILE *dbfp;
  1475. struct stat dbst;
  1476. #endif
  1477. in = BIO_new_file(dbfile, "r");
  1478. if (in == NULL)
  1479. goto err;
  1480. #ifndef OPENSSL_NO_POSIX_IO
  1481. BIO_get_fp(in, &dbfp);
  1482. if (fstat(fileno(dbfp), &dbst) == -1) {
  1483. ERR_raise_data(ERR_LIB_SYS, errno,
  1484. "calling fstat(%s)", dbfile);
  1485. goto err;
  1486. }
  1487. #endif
  1488. if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
  1489. goto err;
  1490. #ifndef OPENSSL_SYS_VMS
  1491. BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
  1492. #else
  1493. BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
  1494. #endif
  1495. dbattr_conf = app_load_config_quiet(buf);
  1496. retdb = app_malloc(sizeof(*retdb), "new DB");
  1497. retdb->db = tmpdb;
  1498. tmpdb = NULL;
  1499. if (db_attr)
  1500. retdb->attributes = *db_attr;
  1501. else {
  1502. retdb->attributes.unique_subject = 1;
  1503. }
  1504. if (dbattr_conf) {
  1505. char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
  1506. if (p) {
  1507. retdb->attributes.unique_subject = parse_yesno(p, 1);
  1508. } else {
  1509. ERR_clear_error();
  1510. }
  1511. }
  1512. retdb->dbfname = OPENSSL_strdup(dbfile);
  1513. #ifndef OPENSSL_NO_POSIX_IO
  1514. retdb->dbst = dbst;
  1515. #endif
  1516. err:
  1517. ERR_print_errors(bio_err);
  1518. NCONF_free(dbattr_conf);
  1519. TXT_DB_free(tmpdb);
  1520. BIO_free_all(in);
  1521. return retdb;
  1522. }
  1523. /*
  1524. * Returns > 0 on success, <= 0 on error
  1525. */
  1526. int index_index(CA_DB *db)
  1527. {
  1528. if (!TXT_DB_create_index(db->db, DB_serial, NULL,
  1529. LHASH_HASH_FN(index_serial),
  1530. LHASH_COMP_FN(index_serial))) {
  1531. BIO_printf(bio_err,
  1532. "Error creating serial number index:(%ld,%ld,%ld)\n",
  1533. db->db->error, db->db->arg1, db->db->arg2);
  1534. goto err;
  1535. }
  1536. if (db->attributes.unique_subject
  1537. && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
  1538. LHASH_HASH_FN(index_name),
  1539. LHASH_COMP_FN(index_name))) {
  1540. BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
  1541. db->db->error, db->db->arg1, db->db->arg2);
  1542. goto err;
  1543. }
  1544. return 1;
  1545. err:
  1546. ERR_print_errors(bio_err);
  1547. return 0;
  1548. }
  1549. int save_index(const char *dbfile, const char *suffix, CA_DB *db)
  1550. {
  1551. char buf[3][BSIZE];
  1552. BIO *out;
  1553. int j;
  1554. j = strlen(dbfile) + strlen(suffix);
  1555. if (j + 6 >= BSIZE) {
  1556. BIO_printf(bio_err, "File name too long\n");
  1557. goto err;
  1558. }
  1559. #ifndef OPENSSL_SYS_VMS
  1560. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
  1561. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
  1562. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
  1563. #else
  1564. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
  1565. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
  1566. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
  1567. #endif
  1568. out = BIO_new_file(buf[0], "w");
  1569. if (out == NULL) {
  1570. perror(dbfile);
  1571. BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
  1572. goto err;
  1573. }
  1574. j = TXT_DB_write(out, db->db);
  1575. BIO_free(out);
  1576. if (j <= 0)
  1577. goto err;
  1578. out = BIO_new_file(buf[1], "w");
  1579. if (out == NULL) {
  1580. perror(buf[2]);
  1581. BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
  1582. goto err;
  1583. }
  1584. BIO_printf(out, "unique_subject = %s\n",
  1585. db->attributes.unique_subject ? "yes" : "no");
  1586. BIO_free(out);
  1587. return 1;
  1588. err:
  1589. ERR_print_errors(bio_err);
  1590. return 0;
  1591. }
  1592. int rotate_index(const char *dbfile, const char *new_suffix,
  1593. const char *old_suffix)
  1594. {
  1595. char buf[5][BSIZE];
  1596. int i, j;
  1597. i = strlen(dbfile) + strlen(old_suffix);
  1598. j = strlen(dbfile) + strlen(new_suffix);
  1599. if (i > j)
  1600. j = i;
  1601. if (j + 6 >= BSIZE) {
  1602. BIO_printf(bio_err, "File name too long\n");
  1603. goto err;
  1604. }
  1605. #ifndef OPENSSL_SYS_VMS
  1606. j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
  1607. j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
  1608. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
  1609. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
  1610. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
  1611. #else
  1612. j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
  1613. j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
  1614. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
  1615. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
  1616. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
  1617. #endif
  1618. if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
  1619. #ifdef ENOTDIR
  1620. && errno != ENOTDIR
  1621. #endif
  1622. ) {
  1623. BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
  1624. perror("reason");
  1625. goto err;
  1626. }
  1627. if (rename(buf[0], dbfile) < 0) {
  1628. BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
  1629. perror("reason");
  1630. rename(buf[1], dbfile);
  1631. goto err;
  1632. }
  1633. if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
  1634. #ifdef ENOTDIR
  1635. && errno != ENOTDIR
  1636. #endif
  1637. ) {
  1638. BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
  1639. perror("reason");
  1640. rename(dbfile, buf[0]);
  1641. rename(buf[1], dbfile);
  1642. goto err;
  1643. }
  1644. if (rename(buf[2], buf[4]) < 0) {
  1645. BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
  1646. perror("reason");
  1647. rename(buf[3], buf[4]);
  1648. rename(dbfile, buf[0]);
  1649. rename(buf[1], dbfile);
  1650. goto err;
  1651. }
  1652. return 1;
  1653. err:
  1654. ERR_print_errors(bio_err);
  1655. return 0;
  1656. }
  1657. void free_index(CA_DB *db)
  1658. {
  1659. if (db) {
  1660. TXT_DB_free(db->db);
  1661. OPENSSL_free(db->dbfname);
  1662. OPENSSL_free(db);
  1663. }
  1664. }
  1665. int parse_yesno(const char *str, int def)
  1666. {
  1667. if (str) {
  1668. switch (*str) {
  1669. case 'f': /* false */
  1670. case 'F': /* FALSE */
  1671. case 'n': /* no */
  1672. case 'N': /* NO */
  1673. case '0': /* 0 */
  1674. return 0;
  1675. case 't': /* true */
  1676. case 'T': /* TRUE */
  1677. case 'y': /* yes */
  1678. case 'Y': /* YES */
  1679. case '1': /* 1 */
  1680. return 1;
  1681. }
  1682. }
  1683. return def;
  1684. }
  1685. /*
  1686. * name is expected to be in the format /type0=value0/type1=value1/type2=...
  1687. * where + can be used instead of / to form multi-valued RDNs if canmulti
  1688. * and characters may be escaped by \
  1689. */
  1690. X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
  1691. const char *desc)
  1692. {
  1693. int nextismulti = 0;
  1694. char *work;
  1695. X509_NAME *n;
  1696. if (*cp++ != '/') {
  1697. BIO_printf(bio_err,
  1698. "%s: %s name is expected to be in the format "
  1699. "/type0=value0/type1=value1/type2=... where characters may "
  1700. "be escaped by \\. This name is not in that format: '%s'\n",
  1701. opt_getprog(), desc, --cp);
  1702. return NULL;
  1703. }
  1704. n = X509_NAME_new();
  1705. if (n == NULL) {
  1706. BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
  1707. return NULL;
  1708. }
  1709. work = OPENSSL_strdup(cp);
  1710. if (work == NULL) {
  1711. BIO_printf(bio_err, "%s: Error copying %s name input\n",
  1712. opt_getprog(), desc);
  1713. goto err;
  1714. }
  1715. while (*cp != '\0') {
  1716. char *bp = work;
  1717. char *typestr = bp;
  1718. unsigned char *valstr;
  1719. int nid;
  1720. int ismulti = nextismulti;
  1721. nextismulti = 0;
  1722. /* Collect the type */
  1723. while (*cp != '\0' && *cp != '=')
  1724. *bp++ = *cp++;
  1725. *bp++ = '\0';
  1726. if (*cp == '\0') {
  1727. BIO_printf(bio_err,
  1728. "%s: Missing '=' after RDN type string '%s' in %s name string\n",
  1729. opt_getprog(), typestr, desc);
  1730. goto err;
  1731. }
  1732. ++cp;
  1733. /* Collect the value. */
  1734. valstr = (unsigned char *)bp;
  1735. for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
  1736. /* unescaped '+' symbol string signals further member of multiRDN */
  1737. if (canmulti && *cp == '+') {
  1738. nextismulti = 1;
  1739. break;
  1740. }
  1741. if (*cp == '\\' && *++cp == '\0') {
  1742. BIO_printf(bio_err,
  1743. "%s: Escape character at end of %s name string\n",
  1744. opt_getprog(), desc);
  1745. goto err;
  1746. }
  1747. }
  1748. *bp++ = '\0';
  1749. /* If not at EOS (must be + or /), move forward. */
  1750. if (*cp != '\0')
  1751. ++cp;
  1752. /* Parse */
  1753. nid = OBJ_txt2nid(typestr);
  1754. if (nid == NID_undef) {
  1755. BIO_printf(bio_err,
  1756. "%s warning: Skipping unknown %s name attribute \"%s\"\n",
  1757. opt_getprog(), desc, typestr);
  1758. if (ismulti)
  1759. BIO_printf(bio_err,
  1760. "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n",
  1761. opt_getprog());
  1762. continue;
  1763. }
  1764. if (*valstr == '\0') {
  1765. BIO_printf(bio_err,
  1766. "%s warning: No value provided for %s name attribute \"%s\", skipped\n",
  1767. opt_getprog(), desc, typestr);
  1768. continue;
  1769. }
  1770. if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
  1771. valstr, strlen((char *)valstr),
  1772. -1, ismulti ? -1 : 0)) {
  1773. ERR_print_errors(bio_err);
  1774. BIO_printf(bio_err,
  1775. "%s: Error adding %s name attribute \"/%s=%s\"\n",
  1776. opt_getprog(), desc, typestr ,valstr);
  1777. goto err;
  1778. }
  1779. }
  1780. OPENSSL_free(work);
  1781. return n;
  1782. err:
  1783. X509_NAME_free(n);
  1784. OPENSSL_free(work);
  1785. return NULL;
  1786. }
  1787. /*
  1788. * Read whole contents of a BIO into an allocated memory buffer and return
  1789. * it.
  1790. */
  1791. int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
  1792. {
  1793. BIO *mem;
  1794. int len, ret;
  1795. unsigned char tbuf[1024];
  1796. mem = BIO_new(BIO_s_mem());
  1797. if (mem == NULL)
  1798. return -1;
  1799. for (;;) {
  1800. if ((maxlen != -1) && maxlen < 1024)
  1801. len = maxlen;
  1802. else
  1803. len = 1024;
  1804. len = BIO_read(in, tbuf, len);
  1805. if (len < 0) {
  1806. BIO_free(mem);
  1807. return -1;
  1808. }
  1809. if (len == 0)
  1810. break;
  1811. if (BIO_write(mem, tbuf, len) != len) {
  1812. BIO_free(mem);
  1813. return -1;
  1814. }
  1815. if (maxlen != -1)
  1816. maxlen -= len;
  1817. if (maxlen == 0)
  1818. break;
  1819. }
  1820. ret = BIO_get_mem_data(mem, (char **)out);
  1821. BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
  1822. BIO_free(mem);
  1823. return ret;
  1824. }
  1825. int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
  1826. {
  1827. int rv = 0;
  1828. char *stmp, *vtmp = NULL;
  1829. stmp = OPENSSL_strdup(value);
  1830. if (stmp == NULL)
  1831. return -1;
  1832. vtmp = strchr(stmp, ':');
  1833. if (vtmp == NULL)
  1834. goto err;
  1835. *vtmp = 0;
  1836. vtmp++;
  1837. rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
  1838. err:
  1839. OPENSSL_free(stmp);
  1840. return rv;
  1841. }
  1842. static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
  1843. {
  1844. X509_POLICY_NODE *node;
  1845. int i;
  1846. BIO_printf(bio_err, "%s Policies:", name);
  1847. if (nodes) {
  1848. BIO_puts(bio_err, "\n");
  1849. for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
  1850. node = sk_X509_POLICY_NODE_value(nodes, i);
  1851. X509_POLICY_NODE_print(bio_err, node, 2);
  1852. }
  1853. } else {
  1854. BIO_puts(bio_err, " <empty>\n");
  1855. }
  1856. }
  1857. void policies_print(X509_STORE_CTX *ctx)
  1858. {
  1859. X509_POLICY_TREE *tree;
  1860. int explicit_policy;
  1861. tree = X509_STORE_CTX_get0_policy_tree(ctx);
  1862. explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
  1863. BIO_printf(bio_err, "Require explicit Policy: %s\n",
  1864. explicit_policy ? "True" : "False");
  1865. nodes_print("Authority", X509_policy_tree_get0_policies(tree));
  1866. nodes_print("User", X509_policy_tree_get0_user_policies(tree));
  1867. }
  1868. /*-
  1869. * next_protos_parse parses a comma separated list of strings into a string
  1870. * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
  1871. * outlen: (output) set to the length of the resulting buffer on success.
  1872. * err: (maybe NULL) on failure, an error message line is written to this BIO.
  1873. * in: a NUL terminated string like "abc,def,ghi"
  1874. *
  1875. * returns: a malloc'd buffer or NULL on failure.
  1876. */
  1877. unsigned char *next_protos_parse(size_t *outlen, const char *in)
  1878. {
  1879. size_t len;
  1880. unsigned char *out;
  1881. size_t i, start = 0;
  1882. size_t skipped = 0;
  1883. len = strlen(in);
  1884. if (len == 0 || len >= 65535)
  1885. return NULL;
  1886. out = app_malloc(len + 1, "NPN buffer");
  1887. for (i = 0; i <= len; ++i) {
  1888. if (i == len || in[i] == ',') {
  1889. /*
  1890. * Zero-length ALPN elements are invalid on the wire, we could be
  1891. * strict and reject the entire string, but just ignoring extra
  1892. * commas seems harmless and more friendly.
  1893. *
  1894. * Every comma we skip in this way puts the input buffer another
  1895. * byte ahead of the output buffer, so all stores into the output
  1896. * buffer need to be decremented by the number commas skipped.
  1897. */
  1898. if (i == start) {
  1899. ++start;
  1900. ++skipped;
  1901. continue;
  1902. }
  1903. if (i - start > 255) {
  1904. OPENSSL_free(out);
  1905. return NULL;
  1906. }
  1907. out[start-skipped] = (unsigned char)(i - start);
  1908. start = i + 1;
  1909. } else {
  1910. out[i + 1 - skipped] = in[i];
  1911. }
  1912. }
  1913. if (len <= skipped) {
  1914. OPENSSL_free(out);
  1915. return NULL;
  1916. }
  1917. *outlen = len + 1 - skipped;
  1918. return out;
  1919. }
  1920. void print_cert_checks(BIO *bio, X509 *x,
  1921. const char *checkhost,
  1922. const char *checkemail, const char *checkip)
  1923. {
  1924. if (x == NULL)
  1925. return;
  1926. if (checkhost) {
  1927. BIO_printf(bio, "Hostname %s does%s match certificate\n",
  1928. checkhost,
  1929. X509_check_host(x, checkhost, 0, 0, NULL) == 1
  1930. ? "" : " NOT");
  1931. }
  1932. if (checkemail) {
  1933. BIO_printf(bio, "Email %s does%s match certificate\n",
  1934. checkemail, X509_check_email(x, checkemail, 0, 0)
  1935. ? "" : " NOT");
  1936. }
  1937. if (checkip) {
  1938. BIO_printf(bio, "IP %s does%s match certificate\n",
  1939. checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
  1940. }
  1941. }
  1942. static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
  1943. {
  1944. int i;
  1945. if (opts == NULL)
  1946. return 1;
  1947. for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
  1948. char *opt = sk_OPENSSL_STRING_value(opts, i);
  1949. if (pkey_ctrl_string(pkctx, opt) <= 0) {
  1950. BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
  1951. ERR_print_errors(bio_err);
  1952. return 0;
  1953. }
  1954. }
  1955. return 1;
  1956. }
  1957. static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
  1958. {
  1959. int i;
  1960. if (opts == NULL)
  1961. return 1;
  1962. for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
  1963. char *opt = sk_OPENSSL_STRING_value(opts, i);
  1964. if (x509_ctrl_string(x, opt) <= 0) {
  1965. BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
  1966. ERR_print_errors(bio_err);
  1967. return 0;
  1968. }
  1969. }
  1970. return 1;
  1971. }
  1972. static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
  1973. {
  1974. int i;
  1975. if (opts == NULL)
  1976. return 1;
  1977. for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
  1978. char *opt = sk_OPENSSL_STRING_value(opts, i);
  1979. if (x509_req_ctrl_string(x, opt) <= 0) {
  1980. BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
  1981. ERR_print_errors(bio_err);
  1982. return 0;
  1983. }
  1984. }
  1985. return 1;
  1986. }
  1987. static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
  1988. const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
  1989. {
  1990. EVP_PKEY_CTX *pkctx = NULL;
  1991. char def_md[80];
  1992. if (ctx == NULL)
  1993. return 0;
  1994. /*
  1995. * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
  1996. * for this algorithm.
  1997. */
  1998. if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
  1999. && strcmp(def_md, "UNDEF") == 0) {
  2000. /* The signing algorithm requires there to be no digest */
  2001. md = NULL;
  2002. }
  2003. return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
  2004. app_get0_propq(), pkey, NULL)
  2005. && do_pkey_ctx_init(pkctx, sigopts);
  2006. }
  2007. static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
  2008. const char *name, const char *value, int add_default)
  2009. {
  2010. const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
  2011. X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
  2012. int idx, rv = 0;
  2013. if (new_ext == NULL)
  2014. return rv;
  2015. idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
  2016. if (idx >= 0) {
  2017. X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
  2018. ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(found_ext);
  2019. int disabled = ASN1_STRING_length(data) <= 2; /* config said "none" */
  2020. if (disabled) {
  2021. X509_delete_ext(cert, idx);
  2022. X509_EXTENSION_free(found_ext);
  2023. } /* else keep existing key identifier, which might be outdated */
  2024. rv = 1;
  2025. } else {
  2026. rv = !add_default || X509_add_ext(cert, new_ext, -1);
  2027. }
  2028. X509_EXTENSION_free(new_ext);
  2029. return rv;
  2030. }
  2031. /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
  2032. int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
  2033. STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
  2034. {
  2035. const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
  2036. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  2037. int self_sign;
  2038. int rv = 0;
  2039. if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
  2040. /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
  2041. if (!X509_set_version(cert, X509_VERSION_3))
  2042. goto end;
  2043. /*
  2044. * Add default SKID before such that default AKID can make use of it
  2045. * in case the certificate is self-signed
  2046. */
  2047. /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
  2048. if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
  2049. goto end;
  2050. /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
  2051. ERR_set_mark();
  2052. self_sign = X509_check_private_key(cert, pkey);
  2053. ERR_pop_to_mark();
  2054. if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
  2055. "keyid, issuer", !self_sign))
  2056. goto end;
  2057. }
  2058. if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
  2059. rv = (X509_sign_ctx(cert, mctx) > 0);
  2060. end:
  2061. EVP_MD_CTX_free(mctx);
  2062. return rv;
  2063. }
  2064. /* Sign the certificate request info */
  2065. int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
  2066. STACK_OF(OPENSSL_STRING) *sigopts)
  2067. {
  2068. int rv = 0;
  2069. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  2070. if (do_sign_init(mctx, pkey, md, sigopts) > 0)
  2071. rv = (X509_REQ_sign_ctx(x, mctx) > 0);
  2072. EVP_MD_CTX_free(mctx);
  2073. return rv;
  2074. }
  2075. /* Sign the CRL info */
  2076. int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
  2077. STACK_OF(OPENSSL_STRING) *sigopts)
  2078. {
  2079. int rv = 0;
  2080. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  2081. if (do_sign_init(mctx, pkey, md, sigopts) > 0)
  2082. rv = (X509_CRL_sign_ctx(x, mctx) > 0);
  2083. EVP_MD_CTX_free(mctx);
  2084. return rv;
  2085. }
  2086. /*
  2087. * do_X509_verify returns 1 if the signature is valid,
  2088. * 0 if the signature check fails, or -1 if error occurs.
  2089. */
  2090. int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
  2091. {
  2092. int rv = 0;
  2093. if (do_x509_init(x, vfyopts) > 0)
  2094. rv = X509_verify(x, pkey);
  2095. else
  2096. rv = -1;
  2097. return rv;
  2098. }
  2099. /*
  2100. * do_X509_REQ_verify returns 1 if the signature is valid,
  2101. * 0 if the signature check fails, or -1 if error occurs.
  2102. */
  2103. int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
  2104. STACK_OF(OPENSSL_STRING) *vfyopts)
  2105. {
  2106. int rv = 0;
  2107. if (do_x509_req_init(x, vfyopts) > 0)
  2108. rv = X509_REQ_verify_ex(x, pkey,
  2109. app_get0_libctx(), app_get0_propq());
  2110. else
  2111. rv = -1;
  2112. return rv;
  2113. }
  2114. /* Get first http URL from a DIST_POINT structure */
  2115. static const char *get_dp_url(DIST_POINT *dp)
  2116. {
  2117. GENERAL_NAMES *gens;
  2118. GENERAL_NAME *gen;
  2119. int i, gtype;
  2120. ASN1_STRING *uri;
  2121. if (!dp->distpoint || dp->distpoint->type != 0)
  2122. return NULL;
  2123. gens = dp->distpoint->name.fullname;
  2124. for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
  2125. gen = sk_GENERAL_NAME_value(gens, i);
  2126. uri = GENERAL_NAME_get0_value(gen, &gtype);
  2127. if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
  2128. const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
  2129. if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
  2130. return uptr;
  2131. }
  2132. }
  2133. return NULL;
  2134. }
  2135. /*
  2136. * Look through a CRLDP structure and attempt to find an http URL to
  2137. * downloads a CRL from.
  2138. */
  2139. static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
  2140. {
  2141. int i;
  2142. const char *urlptr = NULL;
  2143. for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
  2144. DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
  2145. urlptr = get_dp_url(dp);
  2146. if (urlptr != NULL)
  2147. return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
  2148. }
  2149. return NULL;
  2150. }
  2151. /*
  2152. * Example of downloading CRLs from CRLDP:
  2153. * not usable for real world as it always downloads and doesn't cache anything.
  2154. */
  2155. static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
  2156. const X509_NAME *nm)
  2157. {
  2158. X509 *x;
  2159. STACK_OF(X509_CRL) *crls = NULL;
  2160. X509_CRL *crl;
  2161. STACK_OF(DIST_POINT) *crldp;
  2162. crls = sk_X509_CRL_new_null();
  2163. if (!crls)
  2164. return NULL;
  2165. x = X509_STORE_CTX_get_current_cert(ctx);
  2166. crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
  2167. crl = load_crl_crldp(crldp);
  2168. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  2169. if (!crl) {
  2170. sk_X509_CRL_free(crls);
  2171. return NULL;
  2172. }
  2173. sk_X509_CRL_push(crls, crl);
  2174. /* Try to download delta CRL */
  2175. crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
  2176. crl = load_crl_crldp(crldp);
  2177. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  2178. if (crl)
  2179. sk_X509_CRL_push(crls, crl);
  2180. return crls;
  2181. }
  2182. void store_setup_crl_download(X509_STORE *st)
  2183. {
  2184. X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
  2185. }
  2186. #ifndef OPENSSL_NO_SOCK
  2187. static const char *tls_error_hint(void)
  2188. {
  2189. unsigned long err = ERR_peek_error();
  2190. if (ERR_GET_LIB(err) != ERR_LIB_SSL)
  2191. err = ERR_peek_last_error();
  2192. if (ERR_GET_LIB(err) != ERR_LIB_SSL)
  2193. return NULL;
  2194. switch (ERR_GET_REASON(err)) {
  2195. case SSL_R_WRONG_VERSION_NUMBER:
  2196. return "The server does not support (a suitable version of) TLS";
  2197. case SSL_R_UNKNOWN_PROTOCOL:
  2198. return "The server does not support HTTPS";
  2199. case SSL_R_CERTIFICATE_VERIFY_FAILED:
  2200. return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
  2201. case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
  2202. return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
  2203. case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
  2204. return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
  2205. default: /* no error or no hint available for error */
  2206. return NULL;
  2207. }
  2208. }
  2209. /* HTTP callback function that supports TLS connection also via HTTPS proxy */
  2210. BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
  2211. {
  2212. APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
  2213. SSL_CTX *ssl_ctx = info->ssl_ctx;
  2214. if (ssl_ctx == NULL) /* not using TLS */
  2215. return bio;
  2216. if (connect) {
  2217. SSL *ssl;
  2218. BIO *sbio = NULL;
  2219. X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx);
  2220. X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
  2221. const char *host = vpm == NULL ? NULL :
  2222. X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */);
  2223. /* adapt after fixing callback design flaw, see #17088 */
  2224. if ((info->use_proxy
  2225. && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
  2226. NULL, NULL, /* no proxy credentials */
  2227. info->timeout, bio_err, opt_getprog()))
  2228. || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
  2229. return NULL;
  2230. }
  2231. if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
  2232. BIO_free(sbio);
  2233. return NULL;
  2234. }
  2235. if (vpm != NULL)
  2236. SSL_set_tlsext_host_name(ssl, host /* may be NULL */);
  2237. SSL_set_connect_state(ssl);
  2238. BIO_set_ssl(sbio, ssl, BIO_CLOSE);
  2239. bio = BIO_push(sbio, bio);
  2240. }
  2241. if (!connect) {
  2242. const char *hint;
  2243. BIO *cbio;
  2244. if (!detail) { /* disconnecting after error */
  2245. hint = tls_error_hint();
  2246. if (hint != NULL)
  2247. ERR_add_error_data(2, " : ", hint);
  2248. }
  2249. if (ssl_ctx != NULL) {
  2250. (void)ERR_set_mark();
  2251. BIO_ssl_shutdown(bio);
  2252. cbio = BIO_pop(bio); /* connect+HTTP BIO */
  2253. BIO_free(bio); /* SSL BIO */
  2254. (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
  2255. bio = cbio;
  2256. }
  2257. }
  2258. return bio;
  2259. }
  2260. void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
  2261. {
  2262. if (info != NULL) {
  2263. SSL_CTX_free(info->ssl_ctx);
  2264. OPENSSL_free(info);
  2265. }
  2266. }
  2267. ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
  2268. const char *no_proxy, SSL_CTX *ssl_ctx,
  2269. const STACK_OF(CONF_VALUE) *headers,
  2270. long timeout, const char *expected_content_type,
  2271. const ASN1_ITEM *it)
  2272. {
  2273. APP_HTTP_TLS_INFO info;
  2274. char *server;
  2275. char *port;
  2276. int use_ssl;
  2277. BIO *mem;
  2278. ASN1_VALUE *resp = NULL;
  2279. if (url == NULL || it == NULL) {
  2280. ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
  2281. return NULL;
  2282. }
  2283. if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
  2284. NULL /* port_num, */, NULL, NULL, NULL))
  2285. return NULL;
  2286. if (use_ssl && ssl_ctx == NULL) {
  2287. ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
  2288. "missing SSL_CTX");
  2289. goto end;
  2290. }
  2291. if (!use_ssl && ssl_ctx != NULL) {
  2292. ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT,
  2293. "SSL_CTX given but use_ssl == 0");
  2294. goto end;
  2295. }
  2296. info.server = server;
  2297. info.port = port;
  2298. info.use_proxy = /* workaround for callback design flaw, see #17088 */
  2299. OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
  2300. info.timeout = timeout;
  2301. info.ssl_ctx = ssl_ctx;
  2302. mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
  2303. app_http_tls_cb, &info, 0 /* buf_size */, headers,
  2304. expected_content_type, 1 /* expect_asn1 */,
  2305. OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
  2306. resp = ASN1_item_d2i_bio(it, mem, NULL);
  2307. BIO_free(mem);
  2308. end:
  2309. OPENSSL_free(server);
  2310. OPENSSL_free(port);
  2311. return resp;
  2312. }
  2313. ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
  2314. const char *path, const char *proxy,
  2315. const char *no_proxy, SSL_CTX *ssl_ctx,
  2316. const STACK_OF(CONF_VALUE) *headers,
  2317. const char *content_type,
  2318. ASN1_VALUE *req, const ASN1_ITEM *req_it,
  2319. const char *expected_content_type,
  2320. long timeout, const ASN1_ITEM *rsp_it)
  2321. {
  2322. int use_ssl = ssl_ctx != NULL;
  2323. APP_HTTP_TLS_INFO info;
  2324. BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
  2325. ASN1_VALUE *res;
  2326. if (req_mem == NULL)
  2327. return NULL;
  2328. info.server = host;
  2329. info.port = port;
  2330. info.use_proxy = /* workaround for callback design flaw, see #17088 */
  2331. OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
  2332. info.timeout = timeout;
  2333. info.ssl_ctx = ssl_ctx;
  2334. rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
  2335. proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
  2336. app_http_tls_cb, &info,
  2337. 0 /* buf_size */, headers, content_type, req_mem,
  2338. expected_content_type, 1 /* expect_asn1 */,
  2339. OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
  2340. 0 /* keep_alive */);
  2341. BIO_free(req_mem);
  2342. res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
  2343. BIO_free(rsp);
  2344. return res;
  2345. }
  2346. #endif
  2347. /*
  2348. * Platform-specific sections
  2349. */
  2350. #if defined(_WIN32)
  2351. # ifdef fileno
  2352. # undef fileno
  2353. # define fileno(a) (int)_fileno(a)
  2354. # endif
  2355. # include <windows.h>
  2356. # include <tchar.h>
  2357. static int WIN32_rename(const char *from, const char *to)
  2358. {
  2359. TCHAR *tfrom = NULL, *tto;
  2360. DWORD err;
  2361. int ret = 0;
  2362. if (sizeof(TCHAR) == 1) {
  2363. tfrom = (TCHAR *)from;
  2364. tto = (TCHAR *)to;
  2365. } else { /* UNICODE path */
  2366. size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
  2367. tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
  2368. if (tfrom == NULL)
  2369. goto err;
  2370. tto = tfrom + flen;
  2371. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2372. if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
  2373. # endif
  2374. for (i = 0; i < flen; i++)
  2375. tfrom[i] = (TCHAR)from[i];
  2376. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2377. if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
  2378. # endif
  2379. for (i = 0; i < tlen; i++)
  2380. tto[i] = (TCHAR)to[i];
  2381. }
  2382. if (MoveFile(tfrom, tto))
  2383. goto ok;
  2384. err = GetLastError();
  2385. if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
  2386. if (DeleteFile(tto) && MoveFile(tfrom, tto))
  2387. goto ok;
  2388. err = GetLastError();
  2389. }
  2390. if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
  2391. errno = ENOENT;
  2392. else if (err == ERROR_ACCESS_DENIED)
  2393. errno = EACCES;
  2394. else
  2395. errno = EINVAL; /* we could map more codes... */
  2396. err:
  2397. ret = -1;
  2398. ok:
  2399. if (tfrom != NULL && tfrom != (TCHAR *)from)
  2400. free(tfrom);
  2401. return ret;
  2402. }
  2403. #endif
  2404. /* app_tminterval section */
  2405. #if defined(_WIN32)
  2406. double app_tminterval(int stop, int usertime)
  2407. {
  2408. FILETIME now;
  2409. double ret = 0;
  2410. static ULARGE_INTEGER tmstart;
  2411. static int warning = 1;
  2412. # ifdef _WIN32_WINNT
  2413. static HANDLE proc = NULL;
  2414. if (proc == NULL) {
  2415. if (check_winnt())
  2416. proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
  2417. GetCurrentProcessId());
  2418. if (proc == NULL)
  2419. proc = (HANDLE) - 1;
  2420. }
  2421. if (usertime && proc != (HANDLE) - 1) {
  2422. FILETIME junk;
  2423. GetProcessTimes(proc, &junk, &junk, &junk, &now);
  2424. } else
  2425. # endif
  2426. {
  2427. SYSTEMTIME systime;
  2428. if (usertime && warning) {
  2429. BIO_printf(bio_err, "To get meaningful results, run "
  2430. "this program on idle system.\n");
  2431. warning = 0;
  2432. }
  2433. GetSystemTime(&systime);
  2434. SystemTimeToFileTime(&systime, &now);
  2435. }
  2436. if (stop == TM_START) {
  2437. tmstart.u.LowPart = now.dwLowDateTime;
  2438. tmstart.u.HighPart = now.dwHighDateTime;
  2439. } else {
  2440. ULARGE_INTEGER tmstop;
  2441. tmstop.u.LowPart = now.dwLowDateTime;
  2442. tmstop.u.HighPart = now.dwHighDateTime;
  2443. ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
  2444. }
  2445. return ret;
  2446. }
  2447. #elif defined(OPENSSL_SYS_VXWORKS)
  2448. # include <time.h>
  2449. double app_tminterval(int stop, int usertime)
  2450. {
  2451. double ret = 0;
  2452. # ifdef CLOCK_REALTIME
  2453. static struct timespec tmstart;
  2454. struct timespec now;
  2455. # else
  2456. static unsigned long tmstart;
  2457. unsigned long now;
  2458. # endif
  2459. static int warning = 1;
  2460. if (usertime && warning) {
  2461. BIO_printf(bio_err, "To get meaningful results, run "
  2462. "this program on idle system.\n");
  2463. warning = 0;
  2464. }
  2465. # ifdef CLOCK_REALTIME
  2466. clock_gettime(CLOCK_REALTIME, &now);
  2467. if (stop == TM_START)
  2468. tmstart = now;
  2469. else
  2470. ret = ((now.tv_sec + now.tv_nsec * 1e-9)
  2471. - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
  2472. # else
  2473. now = tickGet();
  2474. if (stop == TM_START)
  2475. tmstart = now;
  2476. else
  2477. ret = (now - tmstart) / (double)sysClkRateGet();
  2478. # endif
  2479. return ret;
  2480. }
  2481. #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
  2482. # include <sys/times.h>
  2483. double app_tminterval(int stop, int usertime)
  2484. {
  2485. double ret = 0;
  2486. struct tms rus;
  2487. clock_t now = times(&rus);
  2488. static clock_t tmstart;
  2489. if (usertime)
  2490. now = rus.tms_utime;
  2491. if (stop == TM_START) {
  2492. tmstart = now;
  2493. } else {
  2494. long int tck = sysconf(_SC_CLK_TCK);
  2495. ret = (now - tmstart) / (double)tck;
  2496. }
  2497. return ret;
  2498. }
  2499. #else
  2500. # include <sys/time.h>
  2501. # include <sys/resource.h>
  2502. double app_tminterval(int stop, int usertime)
  2503. {
  2504. double ret = 0;
  2505. struct rusage rus;
  2506. struct timeval now;
  2507. static struct timeval tmstart;
  2508. if (usertime)
  2509. getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
  2510. else
  2511. gettimeofday(&now, NULL);
  2512. if (stop == TM_START)
  2513. tmstart = now;
  2514. else
  2515. ret = ((now.tv_sec + now.tv_usec * 1e-6)
  2516. - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
  2517. return ret;
  2518. }
  2519. #endif
  2520. int app_access(const char* name, int flag)
  2521. {
  2522. #ifdef _WIN32
  2523. return _access(name, flag);
  2524. #else
  2525. return access(name, flag);
  2526. #endif
  2527. }
  2528. int app_isdir(const char *name)
  2529. {
  2530. return opt_isdir(name);
  2531. }
  2532. /* raw_read|write section */
  2533. #if defined(__VMS)
  2534. # include "vms_term_sock.h"
  2535. static int stdin_sock = -1;
  2536. static void close_stdin_sock(void)
  2537. {
  2538. TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
  2539. }
  2540. int fileno_stdin(void)
  2541. {
  2542. if (stdin_sock == -1) {
  2543. TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
  2544. atexit(close_stdin_sock);
  2545. }
  2546. return stdin_sock;
  2547. }
  2548. #else
  2549. int fileno_stdin(void)
  2550. {
  2551. return fileno(stdin);
  2552. }
  2553. #endif
  2554. int fileno_stdout(void)
  2555. {
  2556. return fileno(stdout);
  2557. }
  2558. #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
  2559. int raw_read_stdin(void *buf, int siz)
  2560. {
  2561. DWORD n;
  2562. if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
  2563. return n;
  2564. else
  2565. return -1;
  2566. }
  2567. #elif defined(__VMS)
  2568. # include <sys/socket.h>
  2569. int raw_read_stdin(void *buf, int siz)
  2570. {
  2571. return recv(fileno_stdin(), buf, siz, 0);
  2572. }
  2573. #else
  2574. # if defined(__TANDEM)
  2575. # if defined(OPENSSL_TANDEM_FLOSS)
  2576. # include <floss.h(floss_read)>
  2577. # endif
  2578. # endif
  2579. int raw_read_stdin(void *buf, int siz)
  2580. {
  2581. return read(fileno_stdin(), buf, siz);
  2582. }
  2583. #endif
  2584. #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
  2585. int raw_write_stdout(const void *buf, int siz)
  2586. {
  2587. DWORD n;
  2588. if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
  2589. return n;
  2590. else
  2591. return -1;
  2592. }
  2593. #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
  2594. # if defined(__TANDEM)
  2595. # if defined(OPENSSL_TANDEM_FLOSS)
  2596. # include <floss.h(floss_write)>
  2597. # endif
  2598. # endif
  2599. int raw_write_stdout(const void *buf,int siz)
  2600. {
  2601. return write(fileno(stdout),(void*)buf,siz);
  2602. }
  2603. #else
  2604. # if defined(__TANDEM)
  2605. # if defined(OPENSSL_TANDEM_FLOSS)
  2606. # include <floss.h(floss_write)>
  2607. # endif
  2608. # endif
  2609. int raw_write_stdout(const void *buf, int siz)
  2610. {
  2611. return write(fileno_stdout(), buf, siz);
  2612. }
  2613. #endif
  2614. /*
  2615. * Centralized handling of input and output files with format specification
  2616. * The format is meant to show what the input and output is supposed to be,
  2617. * and is therefore a show of intent more than anything else. However, it
  2618. * does impact behavior on some platforms, such as differentiating between
  2619. * text and binary input/output on non-Unix platforms
  2620. */
  2621. BIO *dup_bio_in(int format)
  2622. {
  2623. return BIO_new_fp(stdin,
  2624. BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
  2625. }
  2626. BIO *dup_bio_out(int format)
  2627. {
  2628. BIO *b = BIO_new_fp(stdout,
  2629. BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
  2630. void *prefix = NULL;
  2631. if (b == NULL)
  2632. return NULL;
  2633. #ifdef OPENSSL_SYS_VMS
  2634. if (FMT_istext(format))
  2635. b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
  2636. #endif
  2637. if (FMT_istext(format)
  2638. && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
  2639. b = BIO_push(BIO_new(BIO_f_prefix()), b);
  2640. BIO_set_prefix(b, prefix);
  2641. }
  2642. return b;
  2643. }
  2644. BIO *dup_bio_err(int format)
  2645. {
  2646. BIO *b = BIO_new_fp(stderr,
  2647. BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
  2648. #ifdef OPENSSL_SYS_VMS
  2649. if (b != NULL && FMT_istext(format))
  2650. b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
  2651. #endif
  2652. return b;
  2653. }
  2654. void unbuffer(FILE *fp)
  2655. {
  2656. /*
  2657. * On VMS, setbuf() will only take 32-bit pointers, and a compilation
  2658. * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
  2659. * However, we trust that the C RTL will never give us a FILE pointer
  2660. * above the first 4 GB of memory, so we simply turn off the warning
  2661. * temporarily.
  2662. */
  2663. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  2664. # pragma environment save
  2665. # pragma message disable maylosedata2
  2666. #endif
  2667. setbuf(fp, NULL);
  2668. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  2669. # pragma environment restore
  2670. #endif
  2671. }
  2672. static const char *modestr(char mode, int format)
  2673. {
  2674. OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
  2675. switch (mode) {
  2676. case 'a':
  2677. return FMT_istext(format) ? "a" : "ab";
  2678. case 'r':
  2679. return FMT_istext(format) ? "r" : "rb";
  2680. case 'w':
  2681. return FMT_istext(format) ? "w" : "wb";
  2682. }
  2683. /* The assert above should make sure we never reach this point */
  2684. return NULL;
  2685. }
  2686. static const char *modeverb(char mode)
  2687. {
  2688. switch (mode) {
  2689. case 'a':
  2690. return "appending";
  2691. case 'r':
  2692. return "reading";
  2693. case 'w':
  2694. return "writing";
  2695. }
  2696. return "(doing something)";
  2697. }
  2698. /*
  2699. * Open a file for writing, owner-read-only.
  2700. */
  2701. BIO *bio_open_owner(const char *filename, int format, int private)
  2702. {
  2703. FILE *fp = NULL;
  2704. BIO *b = NULL;
  2705. int textmode, bflags;
  2706. #ifndef OPENSSL_NO_POSIX_IO
  2707. int fd = -1, mode;
  2708. #endif
  2709. if (!private || filename == NULL || strcmp(filename, "-") == 0)
  2710. return bio_open_default(filename, 'w', format);
  2711. textmode = FMT_istext(format);
  2712. #ifndef OPENSSL_NO_POSIX_IO
  2713. mode = O_WRONLY;
  2714. # ifdef O_CREAT
  2715. mode |= O_CREAT;
  2716. # endif
  2717. # ifdef O_TRUNC
  2718. mode |= O_TRUNC;
  2719. # endif
  2720. if (!textmode) {
  2721. # ifdef O_BINARY
  2722. mode |= O_BINARY;
  2723. # elif defined(_O_BINARY)
  2724. mode |= _O_BINARY;
  2725. # endif
  2726. }
  2727. # ifdef OPENSSL_SYS_VMS
  2728. /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
  2729. * it still needs to know that we're going binary, or fdopen()
  2730. * will fail with "invalid argument"... so we tell VMS what the
  2731. * context is.
  2732. */
  2733. if (!textmode)
  2734. fd = open(filename, mode, 0600, "ctx=bin");
  2735. else
  2736. # endif
  2737. fd = open(filename, mode, 0600);
  2738. if (fd < 0)
  2739. goto err;
  2740. fp = fdopen(fd, modestr('w', format));
  2741. #else /* OPENSSL_NO_POSIX_IO */
  2742. /* Have stdio but not Posix IO, do the best we can */
  2743. fp = fopen(filename, modestr('w', format));
  2744. #endif /* OPENSSL_NO_POSIX_IO */
  2745. if (fp == NULL)
  2746. goto err;
  2747. bflags = BIO_CLOSE;
  2748. if (textmode)
  2749. bflags |= BIO_FP_TEXT;
  2750. b = BIO_new_fp(fp, bflags);
  2751. if (b != NULL)
  2752. return b;
  2753. err:
  2754. BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
  2755. opt_getprog(), filename, strerror(errno));
  2756. ERR_print_errors(bio_err);
  2757. /* If we have fp, then fdopen took over fd, so don't close both. */
  2758. if (fp != NULL)
  2759. fclose(fp);
  2760. #ifndef OPENSSL_NO_POSIX_IO
  2761. else if (fd >= 0)
  2762. close(fd);
  2763. #endif
  2764. return NULL;
  2765. }
  2766. static BIO *bio_open_default_(const char *filename, char mode, int format,
  2767. int quiet)
  2768. {
  2769. BIO *ret;
  2770. if (filename == NULL || strcmp(filename, "-") == 0) {
  2771. ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
  2772. if (quiet) {
  2773. ERR_clear_error();
  2774. return ret;
  2775. }
  2776. if (ret != NULL)
  2777. return ret;
  2778. BIO_printf(bio_err,
  2779. "Can't open %s, %s\n",
  2780. mode == 'r' ? "stdin" : "stdout", strerror(errno));
  2781. } else {
  2782. ret = BIO_new_file(filename, modestr(mode, format));
  2783. if (quiet) {
  2784. ERR_clear_error();
  2785. return ret;
  2786. }
  2787. if (ret != NULL)
  2788. return ret;
  2789. BIO_printf(bio_err,
  2790. "Can't open \"%s\" for %s, %s\n",
  2791. filename, modeverb(mode), strerror(errno));
  2792. }
  2793. ERR_print_errors(bio_err);
  2794. return NULL;
  2795. }
  2796. BIO *bio_open_default(const char *filename, char mode, int format)
  2797. {
  2798. return bio_open_default_(filename, mode, format, 0);
  2799. }
  2800. BIO *bio_open_default_quiet(const char *filename, char mode, int format)
  2801. {
  2802. return bio_open_default_(filename, mode, format, 1);
  2803. }
  2804. void wait_for_async(SSL *s)
  2805. {
  2806. /* On Windows select only works for sockets, so we simply don't wait */
  2807. #ifndef OPENSSL_SYS_WINDOWS
  2808. int width = 0;
  2809. fd_set asyncfds;
  2810. OSSL_ASYNC_FD *fds;
  2811. size_t numfds;
  2812. size_t i;
  2813. if (!SSL_get_all_async_fds(s, NULL, &numfds))
  2814. return;
  2815. if (numfds == 0)
  2816. return;
  2817. fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
  2818. if (!SSL_get_all_async_fds(s, fds, &numfds)) {
  2819. OPENSSL_free(fds);
  2820. return;
  2821. }
  2822. FD_ZERO(&asyncfds);
  2823. for (i = 0; i < numfds; i++) {
  2824. if (width <= (int)fds[i])
  2825. width = (int)fds[i] + 1;
  2826. openssl_fdset((int)fds[i], &asyncfds);
  2827. }
  2828. select(width, (void *)&asyncfds, NULL, NULL, NULL);
  2829. OPENSSL_free(fds);
  2830. #endif
  2831. }
  2832. /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
  2833. #if defined(OPENSSL_SYS_MSDOS)
  2834. int has_stdin_waiting(void)
  2835. {
  2836. # if defined(OPENSSL_SYS_WINDOWS)
  2837. HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
  2838. DWORD events = 0;
  2839. INPUT_RECORD inputrec;
  2840. DWORD insize = 1;
  2841. BOOL peeked;
  2842. if (inhand == INVALID_HANDLE_VALUE) {
  2843. return 0;
  2844. }
  2845. peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
  2846. if (!peeked) {
  2847. /* Probably redirected input? _kbhit() does not work in this case */
  2848. if (!feof(stdin)) {
  2849. return 1;
  2850. }
  2851. return 0;
  2852. }
  2853. # endif
  2854. return _kbhit();
  2855. }
  2856. #endif
  2857. /* Corrupt a signature by modifying final byte */
  2858. void corrupt_signature(const ASN1_STRING *signature)
  2859. {
  2860. unsigned char *s = signature->data;
  2861. s[signature->length - 1] ^= 0x1;
  2862. }
  2863. int set_cert_times(X509 *x, const char *startdate, const char *enddate,
  2864. int days)
  2865. {
  2866. if (startdate == NULL || strcmp(startdate, "today") == 0) {
  2867. if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
  2868. return 0;
  2869. } else {
  2870. if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
  2871. return 0;
  2872. }
  2873. if (enddate == NULL) {
  2874. if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
  2875. == NULL)
  2876. return 0;
  2877. } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
  2878. return 0;
  2879. }
  2880. return 1;
  2881. }
  2882. int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
  2883. {
  2884. int ret = 0;
  2885. ASN1_TIME *tm = ASN1_TIME_new();
  2886. if (tm == NULL)
  2887. goto end;
  2888. if (lastupdate == NULL) {
  2889. if (X509_gmtime_adj(tm, 0) == NULL)
  2890. goto end;
  2891. } else {
  2892. if (!ASN1_TIME_set_string_X509(tm, lastupdate))
  2893. goto end;
  2894. }
  2895. if (!X509_CRL_set1_lastUpdate(crl, tm))
  2896. goto end;
  2897. ret = 1;
  2898. end:
  2899. ASN1_TIME_free(tm);
  2900. return ret;
  2901. }
  2902. int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
  2903. long days, long hours, long secs)
  2904. {
  2905. int ret = 0;
  2906. ASN1_TIME *tm = ASN1_TIME_new();
  2907. if (tm == NULL)
  2908. goto end;
  2909. if (nextupdate == NULL) {
  2910. if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
  2911. goto end;
  2912. } else {
  2913. if (!ASN1_TIME_set_string_X509(tm, nextupdate))
  2914. goto end;
  2915. }
  2916. if (!X509_CRL_set1_nextUpdate(crl, tm))
  2917. goto end;
  2918. ret = 1;
  2919. end:
  2920. ASN1_TIME_free(tm);
  2921. return ret;
  2922. }
  2923. void make_uppercase(char *string)
  2924. {
  2925. int i;
  2926. for (i = 0; string[i] != '\0'; i++)
  2927. string[i] = toupper((unsigned char)string[i]);
  2928. }
  2929. /* This function is defined here due to visibility of bio_err */
  2930. int opt_printf_stderr(const char *fmt, ...)
  2931. {
  2932. va_list ap;
  2933. int ret;
  2934. va_start(ap, fmt);
  2935. ret = BIO_vprintf(bio_err, fmt, ap);
  2936. va_end(ap);
  2937. return ret;
  2938. }
  2939. OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
  2940. const OSSL_PARAM *paramdefs)
  2941. {
  2942. OSSL_PARAM *params = NULL;
  2943. size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
  2944. size_t params_n;
  2945. char *opt = "", *stmp, *vtmp = NULL;
  2946. int found = 1;
  2947. if (opts == NULL)
  2948. return NULL;
  2949. params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
  2950. if (params == NULL)
  2951. return NULL;
  2952. for (params_n = 0; params_n < sz; params_n++) {
  2953. opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
  2954. if ((stmp = OPENSSL_strdup(opt)) == NULL
  2955. || (vtmp = strchr(stmp, ':')) == NULL)
  2956. goto err;
  2957. /* Replace ':' with 0 to terminate the string pointed to by stmp */
  2958. *vtmp = 0;
  2959. /* Skip over the separator so that vmtp points to the value */
  2960. vtmp++;
  2961. if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
  2962. stmp, vtmp, strlen(vtmp), &found))
  2963. goto err;
  2964. OPENSSL_free(stmp);
  2965. }
  2966. params[params_n] = OSSL_PARAM_construct_end();
  2967. return params;
  2968. err:
  2969. OPENSSL_free(stmp);
  2970. BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
  2971. opt);
  2972. ERR_print_errors(bio_err);
  2973. app_params_free(params);
  2974. return NULL;
  2975. }
  2976. void app_params_free(OSSL_PARAM *params)
  2977. {
  2978. int i;
  2979. if (params != NULL) {
  2980. for (i = 0; params[i].key != NULL; ++i)
  2981. OPENSSL_free(params[i].data);
  2982. OPENSSL_free(params);
  2983. }
  2984. }
  2985. EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
  2986. {
  2987. EVP_PKEY *res = NULL;
  2988. if (verbose && alg != NULL) {
  2989. BIO_printf(bio_err, "Generating %s key", alg);
  2990. if (bits > 0)
  2991. BIO_printf(bio_err, " with %d bits\n", bits);
  2992. else
  2993. BIO_printf(bio_err, "\n");
  2994. }
  2995. if (!RAND_status())
  2996. BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
  2997. "if the system has a poor entropy source\n");
  2998. if (EVP_PKEY_keygen(ctx, &res) <= 0)
  2999. BIO_printf(bio_err, "%s: Error generating %s key\n", opt_getprog(),
  3000. alg != NULL ? alg : "asymmetric");
  3001. return res;
  3002. }
  3003. EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
  3004. {
  3005. EVP_PKEY *res = NULL;
  3006. if (!RAND_status())
  3007. BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
  3008. "if the system has a poor entropy source\n");
  3009. if (EVP_PKEY_paramgen(ctx, &res) <= 0)
  3010. BIO_printf(bio_err, "%s: Generating %s key parameters failed\n",
  3011. opt_getprog(), alg != NULL ? alg : "asymmetric");
  3012. return res;
  3013. }
  3014. /*
  3015. * Return non-zero if the legacy path is still an option.
  3016. * This decision is based on the global command line operations and the
  3017. * behaviour thus far.
  3018. */
  3019. int opt_legacy_okay(void)
  3020. {
  3021. int provider_options = opt_provider_option_given();
  3022. int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
  3023. /*
  3024. * Having a provider option specified or a custom library context or
  3025. * property query, is a sure sign we're not using legacy.
  3026. */
  3027. if (provider_options || libctx)
  3028. return 0;
  3029. return 1;
  3030. }