apps.c 97 KB

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