apps.c 94 KB

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