2
0

apps.c 98 KB

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