apps.c 97 KB

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