apps.c 96 KB

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