apps.c 96 KB

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