2
0

apps.c 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  1. /*
  2. * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
  10. /*
  11. * On VMS, you need to define this to get the declaration of fileno(). The
  12. * value 2 is to make sure no function defined in POSIX-2 is left undefined.
  13. */
  14. # define _POSIX_C_SOURCE 2
  15. #endif
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <sys/types.h>
  20. #ifndef OPENSSL_NO_POSIX_IO
  21. # include <sys/stat.h>
  22. # include <fcntl.h>
  23. #endif
  24. #include <ctype.h>
  25. #include <errno.h>
  26. #include <openssl/err.h>
  27. #include <openssl/x509.h>
  28. #include <openssl/x509v3.h>
  29. #include <openssl/pem.h>
  30. #include <openssl/pkcs12.h>
  31. #include <openssl/ui.h>
  32. #include <openssl/safestack.h>
  33. #ifndef OPENSSL_NO_ENGINE
  34. # include <openssl/engine.h>
  35. #endif
  36. #ifndef OPENSSL_NO_RSA
  37. # include <openssl/rsa.h>
  38. #endif
  39. #include <openssl/bn.h>
  40. #include <openssl/ssl.h>
  41. #include "s_apps.h"
  42. #include "apps.h"
  43. #ifdef _WIN32
  44. static int WIN32_rename(const char *from, const char *to);
  45. # define rename(from,to) WIN32_rename((from),(to))
  46. #endif
  47. typedef struct {
  48. const char *name;
  49. unsigned long flag;
  50. unsigned long mask;
  51. } NAME_EX_TBL;
  52. static UI_METHOD *ui_method = NULL;
  53. static const UI_METHOD *ui_fallback_method = NULL;
  54. static int set_table_opts(unsigned long *flags, const char *arg,
  55. const NAME_EX_TBL * in_tbl);
  56. static int set_multi_opts(unsigned long *flags, const char *arg,
  57. const NAME_EX_TBL * in_tbl);
  58. int app_init(long mesgwin);
  59. int chopup_args(ARGS *arg, char *buf)
  60. {
  61. int quoted;
  62. char c = '\0', *p = NULL;
  63. arg->argc = 0;
  64. if (arg->size == 0) {
  65. arg->size = 20;
  66. arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
  67. }
  68. for (p = buf;;) {
  69. /* Skip whitespace. */
  70. while (*p && isspace(_UC(*p)))
  71. p++;
  72. if (!*p)
  73. break;
  74. /* The start of something good :-) */
  75. if (arg->argc >= arg->size) {
  76. char **tmp;
  77. arg->size += 20;
  78. tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
  79. if (tmp == NULL)
  80. return 0;
  81. arg->argv = tmp;
  82. }
  83. quoted = *p == '\'' || *p == '"';
  84. if (quoted)
  85. c = *p++;
  86. arg->argv[arg->argc++] = p;
  87. /* now look for the end of this */
  88. if (quoted) {
  89. while (*p && *p != c)
  90. p++;
  91. *p++ = '\0';
  92. } else {
  93. while (*p && !isspace(_UC(*p)))
  94. p++;
  95. if (*p)
  96. *p++ = '\0';
  97. }
  98. }
  99. arg->argv[arg->argc] = NULL;
  100. return 1;
  101. }
  102. #ifndef APP_INIT
  103. int app_init(long mesgwin)
  104. {
  105. return 1;
  106. }
  107. #endif
  108. int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile,
  109. const char *CApath, int noCAfile, int noCApath)
  110. {
  111. if (CAfile == NULL && CApath == NULL) {
  112. if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
  113. return 0;
  114. if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
  115. return 0;
  116. return 1;
  117. }
  118. return SSL_CTX_load_verify_locations(ctx, CAfile, CApath);
  119. }
  120. #ifndef OPENSSL_NO_CT
  121. int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
  122. {
  123. if (path == NULL)
  124. return SSL_CTX_set_default_ctlog_list_file(ctx);
  125. return SSL_CTX_set_ctlog_list_file(ctx, path);
  126. }
  127. #endif
  128. static unsigned long nmflag = 0;
  129. static char nmflag_set = 0;
  130. int set_nameopt(const char *arg)
  131. {
  132. int ret = set_name_ex(&nmflag, arg);
  133. if (ret)
  134. nmflag_set = 1;
  135. return ret;
  136. }
  137. unsigned long get_nameopt(void)
  138. {
  139. return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
  140. }
  141. int dump_cert_text(BIO *out, X509 *x)
  142. {
  143. print_name(out, "subject=", X509_get_subject_name(x), get_nameopt());
  144. BIO_puts(out, "\n");
  145. print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
  146. BIO_puts(out, "\n");
  147. return 0;
  148. }
  149. static int ui_open(UI *ui)
  150. {
  151. int (*opener)(UI *ui) = UI_method_get_opener(ui_fallback_method);
  152. if (opener)
  153. return opener(ui);
  154. return 1;
  155. }
  156. static int ui_read(UI *ui, UI_STRING *uis)
  157. {
  158. int (*reader)(UI *ui, UI_STRING *uis) = NULL;
  159. if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
  160. && UI_get0_user_data(ui)) {
  161. switch (UI_get_string_type(uis)) {
  162. case UIT_PROMPT:
  163. case UIT_VERIFY:
  164. {
  165. const char *password =
  166. ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
  167. if (password && password[0] != '\0') {
  168. UI_set_result(ui, uis, password);
  169. return 1;
  170. }
  171. }
  172. break;
  173. case UIT_NONE:
  174. case UIT_BOOLEAN:
  175. case UIT_INFO:
  176. case UIT_ERROR:
  177. break;
  178. }
  179. }
  180. reader = UI_method_get_reader(ui_fallback_method);
  181. if (reader)
  182. return reader(ui, uis);
  183. return 1;
  184. }
  185. static int ui_write(UI *ui, UI_STRING *uis)
  186. {
  187. int (*writer)(UI *ui, UI_STRING *uis) = NULL;
  188. if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
  189. && UI_get0_user_data(ui)) {
  190. switch (UI_get_string_type(uis)) {
  191. case UIT_PROMPT:
  192. case UIT_VERIFY:
  193. {
  194. const char *password =
  195. ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
  196. if (password && password[0] != '\0')
  197. return 1;
  198. }
  199. break;
  200. case UIT_NONE:
  201. case UIT_BOOLEAN:
  202. case UIT_INFO:
  203. case UIT_ERROR:
  204. break;
  205. }
  206. }
  207. writer = UI_method_get_writer(ui_fallback_method);
  208. if (writer)
  209. return writer(ui, uis);
  210. return 1;
  211. }
  212. static int ui_close(UI *ui)
  213. {
  214. int (*closer)(UI *ui) = UI_method_get_closer(ui_fallback_method);
  215. if (closer)
  216. return closer(ui);
  217. return 1;
  218. }
  219. int setup_ui_method(void)
  220. {
  221. ui_fallback_method = UI_null();
  222. #ifndef OPENSSL_NO_UI_CONSOLE
  223. ui_fallback_method = UI_OpenSSL();
  224. #endif
  225. ui_method = UI_create_method("OpenSSL application user interface");
  226. UI_method_set_opener(ui_method, ui_open);
  227. UI_method_set_reader(ui_method, ui_read);
  228. UI_method_set_writer(ui_method, ui_write);
  229. UI_method_set_closer(ui_method, ui_close);
  230. return 0;
  231. }
  232. void destroy_ui_method(void)
  233. {
  234. if (ui_method) {
  235. UI_destroy_method(ui_method);
  236. ui_method = NULL;
  237. }
  238. }
  239. const UI_METHOD *get_ui_method(void)
  240. {
  241. return ui_method;
  242. }
  243. int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
  244. {
  245. int res = 0;
  246. UI *ui = NULL;
  247. PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
  248. ui = UI_new_method(ui_method);
  249. if (ui) {
  250. int ok = 0;
  251. char *buff = NULL;
  252. int ui_flags = 0;
  253. const char *prompt_info = NULL;
  254. char *prompt;
  255. if (cb_data != NULL && cb_data->prompt_info != NULL)
  256. prompt_info = cb_data->prompt_info;
  257. prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
  258. if (!prompt) {
  259. BIO_printf(bio_err, "Out of memory\n");
  260. UI_free(ui);
  261. return 0;
  262. }
  263. ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
  264. UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
  265. /* We know that there is no previous user data to return to us */
  266. (void)UI_add_user_data(ui, cb_data);
  267. ok = UI_add_input_string(ui, prompt, ui_flags, buf,
  268. PW_MIN_LENGTH, bufsiz - 1);
  269. if (ok >= 0 && verify) {
  270. buff = app_malloc(bufsiz, "password buffer");
  271. ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
  272. PW_MIN_LENGTH, bufsiz - 1, buf);
  273. }
  274. if (ok >= 0)
  275. do {
  276. ok = UI_process(ui);
  277. } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
  278. OPENSSL_clear_free(buff, (unsigned int)bufsiz);
  279. if (ok >= 0)
  280. res = strlen(buf);
  281. if (ok == -1) {
  282. BIO_printf(bio_err, "User interface error\n");
  283. ERR_print_errors(bio_err);
  284. OPENSSL_cleanse(buf, (unsigned int)bufsiz);
  285. res = 0;
  286. }
  287. if (ok == -2) {
  288. BIO_printf(bio_err, "aborted!\n");
  289. OPENSSL_cleanse(buf, (unsigned int)bufsiz);
  290. res = 0;
  291. }
  292. UI_free(ui);
  293. OPENSSL_free(prompt);
  294. }
  295. return res;
  296. }
  297. static char *app_get_pass(const char *arg, int keepbio);
  298. int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
  299. {
  300. int same;
  301. if (arg2 == NULL || arg1 == NULL || strcmp(arg1, arg2))
  302. same = 0;
  303. else
  304. same = 1;
  305. if (arg1 != NULL) {
  306. *pass1 = app_get_pass(arg1, same);
  307. if (*pass1 == NULL)
  308. return 0;
  309. } else if (pass1 != NULL) {
  310. *pass1 = NULL;
  311. }
  312. if (arg2 != NULL) {
  313. *pass2 = app_get_pass(arg2, same ? 2 : 0);
  314. if (*pass2 == NULL)
  315. return 0;
  316. } else if (pass2 != NULL) {
  317. *pass2 = NULL;
  318. }
  319. return 1;
  320. }
  321. static char *app_get_pass(const char *arg, int keepbio)
  322. {
  323. char *tmp, tpass[APP_PASS_LEN];
  324. static BIO *pwdbio = NULL;
  325. int i;
  326. if (strncmp(arg, "pass:", 5) == 0)
  327. return OPENSSL_strdup(arg + 5);
  328. if (strncmp(arg, "env:", 4) == 0) {
  329. tmp = getenv(arg + 4);
  330. if (tmp == NULL) {
  331. BIO_printf(bio_err, "Can't read environment variable %s\n", arg + 4);
  332. return NULL;
  333. }
  334. return OPENSSL_strdup(tmp);
  335. }
  336. if (!keepbio || pwdbio == NULL) {
  337. if (strncmp(arg, "file:", 5) == 0) {
  338. pwdbio = BIO_new_file(arg + 5, "r");
  339. if (pwdbio == NULL) {
  340. BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
  341. return NULL;
  342. }
  343. #if !defined(_WIN32)
  344. /*
  345. * Under _WIN32, which covers even Win64 and CE, file
  346. * descriptors referenced by BIO_s_fd are not inherited
  347. * by child process and therefore below is not an option.
  348. * It could have been an option if bss_fd.c was operating
  349. * on real Windows descriptors, such as those obtained
  350. * with CreateFile.
  351. */
  352. } else if (strncmp(arg, "fd:", 3) == 0) {
  353. BIO *btmp;
  354. i = atoi(arg + 3);
  355. if (i >= 0)
  356. pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
  357. if ((i < 0) || !pwdbio) {
  358. BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
  359. return NULL;
  360. }
  361. /*
  362. * Can't do BIO_gets on an fd BIO so add a buffering BIO
  363. */
  364. btmp = BIO_new(BIO_f_buffer());
  365. pwdbio = BIO_push(btmp, pwdbio);
  366. #endif
  367. } else if (strcmp(arg, "stdin") == 0) {
  368. pwdbio = dup_bio_in(FORMAT_TEXT);
  369. if (!pwdbio) {
  370. BIO_printf(bio_err, "Can't open BIO for stdin\n");
  371. return NULL;
  372. }
  373. } else {
  374. BIO_printf(bio_err, "Invalid password argument \"%s\"\n", arg);
  375. return NULL;
  376. }
  377. }
  378. i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
  379. if (keepbio != 1) {
  380. BIO_free_all(pwdbio);
  381. pwdbio = NULL;
  382. }
  383. if (i <= 0) {
  384. BIO_printf(bio_err, "Error reading password from BIO\n");
  385. return NULL;
  386. }
  387. tmp = strchr(tpass, '\n');
  388. if (tmp != NULL)
  389. *tmp = 0;
  390. return OPENSSL_strdup(tpass);
  391. }
  392. CONF *app_load_config_bio(BIO *in, const char *filename)
  393. {
  394. long errorline = -1;
  395. CONF *conf;
  396. int i;
  397. conf = NCONF_new(NULL);
  398. i = NCONF_load_bio(conf, in, &errorline);
  399. if (i > 0)
  400. return conf;
  401. if (errorline <= 0) {
  402. BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
  403. } else {
  404. BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
  405. errorline);
  406. }
  407. if (filename != NULL)
  408. BIO_printf(bio_err, "config file \"%s\"\n", filename);
  409. else
  410. BIO_printf(bio_err, "config input");
  411. NCONF_free(conf);
  412. return NULL;
  413. }
  414. CONF *app_load_config(const char *filename)
  415. {
  416. BIO *in;
  417. CONF *conf;
  418. in = bio_open_default(filename, 'r', FORMAT_TEXT);
  419. if (in == NULL)
  420. return NULL;
  421. conf = app_load_config_bio(in, filename);
  422. BIO_free(in);
  423. return conf;
  424. }
  425. CONF *app_load_config_quiet(const char *filename)
  426. {
  427. BIO *in;
  428. CONF *conf;
  429. in = bio_open_default_quiet(filename, 'r', FORMAT_TEXT);
  430. if (in == NULL)
  431. return NULL;
  432. conf = app_load_config_bio(in, filename);
  433. BIO_free(in);
  434. return conf;
  435. }
  436. int app_load_modules(const CONF *config)
  437. {
  438. CONF *to_free = NULL;
  439. if (config == NULL)
  440. config = to_free = app_load_config_quiet(default_config_file);
  441. if (config == NULL)
  442. return 1;
  443. if (CONF_modules_load(config, NULL, 0) <= 0) {
  444. BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
  445. ERR_print_errors(bio_err);
  446. NCONF_free(to_free);
  447. return 0;
  448. }
  449. NCONF_free(to_free);
  450. return 1;
  451. }
  452. int add_oid_section(CONF *conf)
  453. {
  454. char *p;
  455. STACK_OF(CONF_VALUE) *sktmp;
  456. CONF_VALUE *cnf;
  457. int i;
  458. if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
  459. ERR_clear_error();
  460. return 1;
  461. }
  462. if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
  463. BIO_printf(bio_err, "problem loading oid section %s\n", p);
  464. return 0;
  465. }
  466. for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
  467. cnf = sk_CONF_VALUE_value(sktmp, i);
  468. if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
  469. BIO_printf(bio_err, "problem creating object %s=%s\n",
  470. cnf->name, cnf->value);
  471. return 0;
  472. }
  473. }
  474. return 1;
  475. }
  476. static int load_pkcs12(BIO *in, const char *desc,
  477. pem_password_cb *pem_cb, void *cb_data,
  478. EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
  479. {
  480. const char *pass;
  481. char tpass[PEM_BUFSIZE];
  482. int len, ret = 0;
  483. PKCS12 *p12;
  484. p12 = d2i_PKCS12_bio(in, NULL);
  485. if (p12 == NULL) {
  486. BIO_printf(bio_err, "Error loading PKCS12 file for %s\n", desc);
  487. goto die;
  488. }
  489. /* See if an empty password will do */
  490. if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
  491. pass = "";
  492. } else {
  493. if (!pem_cb)
  494. pem_cb = (pem_password_cb *)password_callback;
  495. len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
  496. if (len < 0) {
  497. BIO_printf(bio_err, "Passphrase callback error for %s\n", desc);
  498. goto die;
  499. }
  500. if (len < PEM_BUFSIZE)
  501. tpass[len] = 0;
  502. if (!PKCS12_verify_mac(p12, tpass, len)) {
  503. BIO_printf(bio_err,
  504. "Mac verify error (wrong password?) in PKCS12 file for %s\n",
  505. desc);
  506. goto die;
  507. }
  508. pass = tpass;
  509. }
  510. ret = PKCS12_parse(p12, pass, pkey, cert, ca);
  511. die:
  512. PKCS12_free(p12);
  513. return ret;
  514. }
  515. #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
  516. static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl)
  517. {
  518. char *host = NULL, *port = NULL, *path = NULL;
  519. BIO *bio = NULL;
  520. OCSP_REQ_CTX *rctx = NULL;
  521. int use_ssl, rv = 0;
  522. if (!OCSP_parse_url(url, &host, &port, &path, &use_ssl))
  523. goto err;
  524. if (use_ssl) {
  525. BIO_puts(bio_err, "https not supported\n");
  526. goto err;
  527. }
  528. bio = BIO_new_connect(host);
  529. if (!bio || !BIO_set_conn_port(bio, port))
  530. goto err;
  531. rctx = OCSP_REQ_CTX_new(bio, 1024);
  532. if (rctx == NULL)
  533. goto err;
  534. if (!OCSP_REQ_CTX_http(rctx, "GET", path))
  535. goto err;
  536. if (!OCSP_REQ_CTX_add1_header(rctx, "Host", host))
  537. goto err;
  538. if (pcert) {
  539. do {
  540. rv = X509_http_nbio(rctx, pcert);
  541. } while (rv == -1);
  542. } else {
  543. do {
  544. rv = X509_CRL_http_nbio(rctx, pcrl);
  545. } while (rv == -1);
  546. }
  547. err:
  548. OPENSSL_free(host);
  549. OPENSSL_free(path);
  550. OPENSSL_free(port);
  551. BIO_free_all(bio);
  552. OCSP_REQ_CTX_free(rctx);
  553. if (rv != 1) {
  554. BIO_printf(bio_err, "Error loading %s from %s\n",
  555. pcert ? "certificate" : "CRL", url);
  556. ERR_print_errors(bio_err);
  557. }
  558. return rv;
  559. }
  560. #endif
  561. X509 *load_cert(const char *file, int format, const char *cert_descrip)
  562. {
  563. X509 *x = NULL;
  564. BIO *cert;
  565. if (format == FORMAT_HTTP) {
  566. #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
  567. load_cert_crl_http(file, &x, NULL);
  568. #endif
  569. return x;
  570. }
  571. if (file == NULL) {
  572. unbuffer(stdin);
  573. cert = dup_bio_in(format);
  574. } else {
  575. cert = bio_open_default(file, 'r', format);
  576. }
  577. if (cert == NULL)
  578. goto end;
  579. if (format == FORMAT_ASN1) {
  580. x = d2i_X509_bio(cert, NULL);
  581. } else if (format == FORMAT_PEM) {
  582. x = PEM_read_bio_X509_AUX(cert, NULL,
  583. (pem_password_cb *)password_callback, NULL);
  584. } else if (format == FORMAT_PKCS12) {
  585. if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
  586. goto end;
  587. } else {
  588. BIO_printf(bio_err, "bad input format specified for %s\n", cert_descrip);
  589. goto end;
  590. }
  591. end:
  592. if (x == NULL) {
  593. BIO_printf(bio_err, "unable to load certificate\n");
  594. ERR_print_errors(bio_err);
  595. }
  596. BIO_free(cert);
  597. return x;
  598. }
  599. X509_CRL *load_crl(const char *infile, int format)
  600. {
  601. X509_CRL *x = NULL;
  602. BIO *in = NULL;
  603. if (format == FORMAT_HTTP) {
  604. #if !defined(OPENSSL_NO_OCSP) && !defined(OPENSSL_NO_SOCK)
  605. load_cert_crl_http(infile, NULL, &x);
  606. #endif
  607. return x;
  608. }
  609. in = bio_open_default(infile, 'r', format);
  610. if (in == NULL)
  611. goto end;
  612. if (format == FORMAT_ASN1) {
  613. x = d2i_X509_CRL_bio(in, NULL);
  614. } else if (format == FORMAT_PEM) {
  615. x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
  616. } else {
  617. BIO_printf(bio_err, "bad input format specified for input crl\n");
  618. goto end;
  619. }
  620. if (x == NULL) {
  621. BIO_printf(bio_err, "unable to load CRL\n");
  622. ERR_print_errors(bio_err);
  623. goto end;
  624. }
  625. end:
  626. BIO_free(in);
  627. return x;
  628. }
  629. EVP_PKEY *load_key(const char *file, int format, int maybe_stdin,
  630. const char *pass, ENGINE *e, const char *key_descrip)
  631. {
  632. BIO *key = NULL;
  633. EVP_PKEY *pkey = NULL;
  634. PW_CB_DATA cb_data;
  635. cb_data.password = pass;
  636. cb_data.prompt_info = file;
  637. if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
  638. BIO_printf(bio_err, "no keyfile specified\n");
  639. goto end;
  640. }
  641. if (format == FORMAT_ENGINE) {
  642. if (e == NULL) {
  643. BIO_printf(bio_err, "no engine specified\n");
  644. } else {
  645. #ifndef OPENSSL_NO_ENGINE
  646. if (ENGINE_init(e)) {
  647. pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
  648. ENGINE_finish(e);
  649. }
  650. if (pkey == NULL) {
  651. BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
  652. ERR_print_errors(bio_err);
  653. }
  654. #else
  655. BIO_printf(bio_err, "engines not supported\n");
  656. #endif
  657. }
  658. goto end;
  659. }
  660. if (file == NULL && maybe_stdin) {
  661. unbuffer(stdin);
  662. key = dup_bio_in(format);
  663. } else {
  664. key = bio_open_default(file, 'r', format);
  665. }
  666. if (key == NULL)
  667. goto end;
  668. if (format == FORMAT_ASN1) {
  669. pkey = d2i_PrivateKey_bio(key, NULL);
  670. } else if (format == FORMAT_PEM) {
  671. pkey = PEM_read_bio_PrivateKey(key, NULL,
  672. (pem_password_cb *)password_callback,
  673. &cb_data);
  674. } else if (format == FORMAT_PKCS12) {
  675. if (!load_pkcs12(key, key_descrip,
  676. (pem_password_cb *)password_callback, &cb_data,
  677. &pkey, NULL, NULL))
  678. goto end;
  679. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
  680. } else if (format == FORMAT_MSBLOB) {
  681. pkey = b2i_PrivateKey_bio(key);
  682. } else if (format == FORMAT_PVK) {
  683. pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
  684. &cb_data);
  685. #endif
  686. } else {
  687. BIO_printf(bio_err, "bad input format specified for key file\n");
  688. goto end;
  689. }
  690. end:
  691. BIO_free(key);
  692. if (pkey == NULL) {
  693. BIO_printf(bio_err, "unable to load %s\n", key_descrip);
  694. ERR_print_errors(bio_err);
  695. }
  696. return pkey;
  697. }
  698. EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin,
  699. const char *pass, ENGINE *e, const char *key_descrip)
  700. {
  701. BIO *key = NULL;
  702. EVP_PKEY *pkey = NULL;
  703. PW_CB_DATA cb_data;
  704. cb_data.password = pass;
  705. cb_data.prompt_info = file;
  706. if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
  707. BIO_printf(bio_err, "no keyfile specified\n");
  708. goto end;
  709. }
  710. if (format == FORMAT_ENGINE) {
  711. if (e == NULL) {
  712. BIO_printf(bio_err, "no engine specified\n");
  713. } else {
  714. #ifndef OPENSSL_NO_ENGINE
  715. pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
  716. if (pkey == NULL) {
  717. BIO_printf(bio_err, "cannot load %s from engine\n", key_descrip);
  718. ERR_print_errors(bio_err);
  719. }
  720. #else
  721. BIO_printf(bio_err, "engines not supported\n");
  722. #endif
  723. }
  724. goto end;
  725. }
  726. if (file == NULL && maybe_stdin) {
  727. unbuffer(stdin);
  728. key = dup_bio_in(format);
  729. } else {
  730. key = bio_open_default(file, 'r', format);
  731. }
  732. if (key == NULL)
  733. goto end;
  734. if (format == FORMAT_ASN1) {
  735. pkey = d2i_PUBKEY_bio(key, NULL);
  736. } else if (format == FORMAT_ASN1RSA) {
  737. #ifndef OPENSSL_NO_RSA
  738. RSA *rsa;
  739. rsa = d2i_RSAPublicKey_bio(key, NULL);
  740. if (rsa) {
  741. pkey = EVP_PKEY_new();
  742. if (pkey != NULL)
  743. EVP_PKEY_set1_RSA(pkey, rsa);
  744. RSA_free(rsa);
  745. } else
  746. #else
  747. BIO_printf(bio_err, "RSA keys not supported\n");
  748. #endif
  749. pkey = NULL;
  750. } else if (format == FORMAT_PEMRSA) {
  751. #ifndef OPENSSL_NO_RSA
  752. RSA *rsa;
  753. rsa = PEM_read_bio_RSAPublicKey(key, NULL,
  754. (pem_password_cb *)password_callback,
  755. &cb_data);
  756. if (rsa != NULL) {
  757. pkey = EVP_PKEY_new();
  758. if (pkey != NULL)
  759. EVP_PKEY_set1_RSA(pkey, rsa);
  760. RSA_free(rsa);
  761. } else
  762. #else
  763. BIO_printf(bio_err, "RSA keys not supported\n");
  764. #endif
  765. pkey = NULL;
  766. } else if (format == FORMAT_PEM) {
  767. pkey = PEM_read_bio_PUBKEY(key, NULL,
  768. (pem_password_cb *)password_callback,
  769. &cb_data);
  770. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
  771. } else if (format == FORMAT_MSBLOB) {
  772. pkey = b2i_PublicKey_bio(key);
  773. #endif
  774. }
  775. end:
  776. BIO_free(key);
  777. if (pkey == NULL)
  778. BIO_printf(bio_err, "unable to load %s\n", key_descrip);
  779. return pkey;
  780. }
  781. static int load_certs_crls(const char *file, int format,
  782. const char *pass, const char *desc,
  783. STACK_OF(X509) **pcerts,
  784. STACK_OF(X509_CRL) **pcrls)
  785. {
  786. int i;
  787. BIO *bio;
  788. STACK_OF(X509_INFO) *xis = NULL;
  789. X509_INFO *xi;
  790. PW_CB_DATA cb_data;
  791. int rv = 0;
  792. cb_data.password = pass;
  793. cb_data.prompt_info = file;
  794. if (format != FORMAT_PEM) {
  795. BIO_printf(bio_err, "bad input format specified for %s\n", desc);
  796. return 0;
  797. }
  798. bio = bio_open_default(file, 'r', FORMAT_PEM);
  799. if (bio == NULL)
  800. return 0;
  801. xis = PEM_X509_INFO_read_bio(bio, NULL,
  802. (pem_password_cb *)password_callback,
  803. &cb_data);
  804. BIO_free(bio);
  805. if (pcerts != NULL && *pcerts == NULL) {
  806. *pcerts = sk_X509_new_null();
  807. if (*pcerts == NULL)
  808. goto end;
  809. }
  810. if (pcrls != NULL && *pcrls == NULL) {
  811. *pcrls = sk_X509_CRL_new_null();
  812. if (*pcrls == NULL)
  813. goto end;
  814. }
  815. for (i = 0; i < sk_X509_INFO_num(xis); i++) {
  816. xi = sk_X509_INFO_value(xis, i);
  817. if (xi->x509 != NULL && pcerts != NULL) {
  818. if (!sk_X509_push(*pcerts, xi->x509))
  819. goto end;
  820. xi->x509 = NULL;
  821. }
  822. if (xi->crl != NULL && pcrls != NULL) {
  823. if (!sk_X509_CRL_push(*pcrls, xi->crl))
  824. goto end;
  825. xi->crl = NULL;
  826. }
  827. }
  828. if (pcerts != NULL && sk_X509_num(*pcerts) > 0)
  829. rv = 1;
  830. if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0)
  831. rv = 1;
  832. end:
  833. sk_X509_INFO_pop_free(xis, X509_INFO_free);
  834. if (rv == 0) {
  835. if (pcerts != NULL) {
  836. sk_X509_pop_free(*pcerts, X509_free);
  837. *pcerts = NULL;
  838. }
  839. if (pcrls != NULL) {
  840. sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
  841. *pcrls = NULL;
  842. }
  843. BIO_printf(bio_err, "unable to load %s\n",
  844. pcerts ? "certificates" : "CRLs");
  845. ERR_print_errors(bio_err);
  846. }
  847. return rv;
  848. }
  849. void* app_malloc(int sz, const char *what)
  850. {
  851. void *vp = OPENSSL_malloc(sz);
  852. if (vp == NULL) {
  853. BIO_printf(bio_err, "%s: Could not allocate %d bytes for %s\n",
  854. opt_getprog(), sz, what);
  855. ERR_print_errors(bio_err);
  856. exit(1);
  857. }
  858. return vp;
  859. }
  860. /*
  861. * Initialize or extend, if *certs != NULL, a certificate stack.
  862. */
  863. int load_certs(const char *file, STACK_OF(X509) **certs, int format,
  864. const char *pass, const char *desc)
  865. {
  866. return load_certs_crls(file, format, pass, desc, certs, NULL);
  867. }
  868. /*
  869. * Initialize or extend, if *crls != NULL, a certificate stack.
  870. */
  871. int load_crls(const char *file, STACK_OF(X509_CRL) **crls, int format,
  872. const char *pass, const char *desc)
  873. {
  874. return load_certs_crls(file, format, pass, desc, NULL, crls);
  875. }
  876. #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
  877. /* Return error for unknown extensions */
  878. #define X509V3_EXT_DEFAULT 0
  879. /* Print error for unknown extensions */
  880. #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
  881. /* ASN1 parse unknown extensions */
  882. #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
  883. /* BIO_dump unknown extensions */
  884. #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
  885. #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
  886. X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
  887. int set_cert_ex(unsigned long *flags, const char *arg)
  888. {
  889. static const NAME_EX_TBL cert_tbl[] = {
  890. {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
  891. {"ca_default", X509_FLAG_CA, 0xffffffffl},
  892. {"no_header", X509_FLAG_NO_HEADER, 0},
  893. {"no_version", X509_FLAG_NO_VERSION, 0},
  894. {"no_serial", X509_FLAG_NO_SERIAL, 0},
  895. {"no_signame", X509_FLAG_NO_SIGNAME, 0},
  896. {"no_validity", X509_FLAG_NO_VALIDITY, 0},
  897. {"no_subject", X509_FLAG_NO_SUBJECT, 0},
  898. {"no_issuer", X509_FLAG_NO_ISSUER, 0},
  899. {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
  900. {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
  901. {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
  902. {"no_aux", X509_FLAG_NO_AUX, 0},
  903. {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
  904. {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
  905. {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  906. {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  907. {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
  908. {NULL, 0, 0}
  909. };
  910. return set_multi_opts(flags, arg, cert_tbl);
  911. }
  912. int set_name_ex(unsigned long *flags, const char *arg)
  913. {
  914. static const NAME_EX_TBL ex_tbl[] = {
  915. {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
  916. {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
  917. {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
  918. {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
  919. {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
  920. {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
  921. {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
  922. {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
  923. {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
  924. {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
  925. {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
  926. {"compat", XN_FLAG_COMPAT, 0xffffffffL},
  927. {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
  928. {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
  929. {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
  930. {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
  931. {"dn_rev", XN_FLAG_DN_REV, 0},
  932. {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
  933. {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
  934. {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
  935. {"align", XN_FLAG_FN_ALIGN, 0},
  936. {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
  937. {"space_eq", XN_FLAG_SPC_EQ, 0},
  938. {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
  939. {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
  940. {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
  941. {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
  942. {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
  943. {NULL, 0, 0}
  944. };
  945. if (set_multi_opts(flags, arg, ex_tbl) == 0)
  946. return 0;
  947. if (*flags != XN_FLAG_COMPAT
  948. && (*flags & XN_FLAG_SEP_MASK) == 0)
  949. *flags |= XN_FLAG_SEP_CPLUS_SPC;
  950. return 1;
  951. }
  952. int set_ext_copy(int *copy_type, const char *arg)
  953. {
  954. if (strcasecmp(arg, "none") == 0)
  955. *copy_type = EXT_COPY_NONE;
  956. else if (strcasecmp(arg, "copy") == 0)
  957. *copy_type = EXT_COPY_ADD;
  958. else if (strcasecmp(arg, "copyall") == 0)
  959. *copy_type = EXT_COPY_ALL;
  960. else
  961. return 0;
  962. return 1;
  963. }
  964. int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
  965. {
  966. STACK_OF(X509_EXTENSION) *exts = NULL;
  967. X509_EXTENSION *ext, *tmpext;
  968. ASN1_OBJECT *obj;
  969. int i, idx, ret = 0;
  970. if (!x || !req || (copy_type == EXT_COPY_NONE))
  971. return 1;
  972. exts = X509_REQ_get_extensions(req);
  973. for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
  974. ext = sk_X509_EXTENSION_value(exts, i);
  975. obj = X509_EXTENSION_get_object(ext);
  976. idx = X509_get_ext_by_OBJ(x, obj, -1);
  977. /* Does extension exist? */
  978. if (idx != -1) {
  979. /* If normal copy don't override existing extension */
  980. if (copy_type == EXT_COPY_ADD)
  981. continue;
  982. /* Delete all extensions of same type */
  983. do {
  984. tmpext = X509_get_ext(x, idx);
  985. X509_delete_ext(x, idx);
  986. X509_EXTENSION_free(tmpext);
  987. idx = X509_get_ext_by_OBJ(x, obj, -1);
  988. } while (idx != -1);
  989. }
  990. if (!X509_add_ext(x, ext, -1))
  991. goto end;
  992. }
  993. ret = 1;
  994. end:
  995. sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
  996. return ret;
  997. }
  998. static int set_multi_opts(unsigned long *flags, const char *arg,
  999. const NAME_EX_TBL * in_tbl)
  1000. {
  1001. STACK_OF(CONF_VALUE) *vals;
  1002. CONF_VALUE *val;
  1003. int i, ret = 1;
  1004. if (!arg)
  1005. return 0;
  1006. vals = X509V3_parse_list(arg);
  1007. for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
  1008. val = sk_CONF_VALUE_value(vals, i);
  1009. if (!set_table_opts(flags, val->name, in_tbl))
  1010. ret = 0;
  1011. }
  1012. sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
  1013. return ret;
  1014. }
  1015. static int set_table_opts(unsigned long *flags, const char *arg,
  1016. const NAME_EX_TBL * in_tbl)
  1017. {
  1018. char c;
  1019. const NAME_EX_TBL *ptbl;
  1020. c = arg[0];
  1021. if (c == '-') {
  1022. c = 0;
  1023. arg++;
  1024. } else if (c == '+') {
  1025. c = 1;
  1026. arg++;
  1027. } else {
  1028. c = 1;
  1029. }
  1030. for (ptbl = in_tbl; ptbl->name; ptbl++) {
  1031. if (strcasecmp(arg, ptbl->name) == 0) {
  1032. *flags &= ~ptbl->mask;
  1033. if (c)
  1034. *flags |= ptbl->flag;
  1035. else
  1036. *flags &= ~ptbl->flag;
  1037. return 1;
  1038. }
  1039. }
  1040. return 0;
  1041. }
  1042. void print_name(BIO *out, const char *title, X509_NAME *nm,
  1043. unsigned long lflags)
  1044. {
  1045. char *buf;
  1046. char mline = 0;
  1047. int indent = 0;
  1048. if (title)
  1049. BIO_puts(out, title);
  1050. if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
  1051. mline = 1;
  1052. indent = 4;
  1053. }
  1054. if (lflags == XN_FLAG_COMPAT) {
  1055. buf = X509_NAME_oneline(nm, 0, 0);
  1056. BIO_puts(out, buf);
  1057. BIO_puts(out, "\n");
  1058. OPENSSL_free(buf);
  1059. } else {
  1060. if (mline)
  1061. BIO_puts(out, "\n");
  1062. X509_NAME_print_ex(out, nm, indent, lflags);
  1063. BIO_puts(out, "\n");
  1064. }
  1065. }
  1066. void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
  1067. int len, unsigned char *buffer)
  1068. {
  1069. BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
  1070. if (BN_is_zero(in)) {
  1071. BIO_printf(out, "\n\t0x00");
  1072. } else {
  1073. int i, l;
  1074. l = BN_bn2bin(in, buffer);
  1075. for (i = 0; i < l; i++) {
  1076. if ((i % 10) == 0)
  1077. BIO_printf(out, "\n\t");
  1078. if (i < l - 1)
  1079. BIO_printf(out, "0x%02X, ", buffer[i]);
  1080. else
  1081. BIO_printf(out, "0x%02X", buffer[i]);
  1082. }
  1083. }
  1084. BIO_printf(out, "\n };\n");
  1085. }
  1086. void print_array(BIO *out, const char* title, int len, const unsigned char* d)
  1087. {
  1088. int i;
  1089. BIO_printf(out, "unsigned char %s[%d] = {", title, len);
  1090. for (i = 0; i < len; i++) {
  1091. if ((i % 10) == 0)
  1092. BIO_printf(out, "\n ");
  1093. if (i < len - 1)
  1094. BIO_printf(out, "0x%02X, ", d[i]);
  1095. else
  1096. BIO_printf(out, "0x%02X", d[i]);
  1097. }
  1098. BIO_printf(out, "\n};\n");
  1099. }
  1100. X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, int noCApath)
  1101. {
  1102. X509_STORE *store = X509_STORE_new();
  1103. X509_LOOKUP *lookup;
  1104. if (store == NULL)
  1105. goto end;
  1106. if (CAfile != NULL || !noCAfile) {
  1107. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1108. if (lookup == NULL)
  1109. goto end;
  1110. if (CAfile) {
  1111. if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
  1112. BIO_printf(bio_err, "Error loading file %s\n", CAfile);
  1113. goto end;
  1114. }
  1115. } else {
  1116. X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
  1117. }
  1118. }
  1119. if (CApath != NULL || !noCApath) {
  1120. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1121. if (lookup == NULL)
  1122. goto end;
  1123. if (CApath) {
  1124. if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
  1125. BIO_printf(bio_err, "Error loading directory %s\n", CApath);
  1126. goto end;
  1127. }
  1128. } else {
  1129. X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
  1130. }
  1131. }
  1132. ERR_clear_error();
  1133. return store;
  1134. end:
  1135. X509_STORE_free(store);
  1136. return NULL;
  1137. }
  1138. #ifndef OPENSSL_NO_ENGINE
  1139. /* Try to load an engine in a shareable library */
  1140. static ENGINE *try_load_engine(const char *engine)
  1141. {
  1142. ENGINE *e = ENGINE_by_id("dynamic");
  1143. if (e) {
  1144. if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
  1145. || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  1146. ENGINE_free(e);
  1147. e = NULL;
  1148. }
  1149. }
  1150. return e;
  1151. }
  1152. #endif
  1153. ENGINE *setup_engine(const char *engine, int debug)
  1154. {
  1155. ENGINE *e = NULL;
  1156. #ifndef OPENSSL_NO_ENGINE
  1157. if (engine != NULL) {
  1158. if (strcmp(engine, "auto") == 0) {
  1159. BIO_printf(bio_err, "enabling auto ENGINE support\n");
  1160. ENGINE_register_all_complete();
  1161. return NULL;
  1162. }
  1163. if ((e = ENGINE_by_id(engine)) == NULL
  1164. && (e = try_load_engine(engine)) == NULL) {
  1165. BIO_printf(bio_err, "invalid engine \"%s\"\n", engine);
  1166. ERR_print_errors(bio_err);
  1167. return NULL;
  1168. }
  1169. if (debug) {
  1170. ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0);
  1171. }
  1172. ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
  1173. if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
  1174. BIO_printf(bio_err, "can't use that engine\n");
  1175. ERR_print_errors(bio_err);
  1176. ENGINE_free(e);
  1177. return NULL;
  1178. }
  1179. BIO_printf(bio_err, "engine \"%s\" set.\n", ENGINE_get_id(e));
  1180. }
  1181. #endif
  1182. return e;
  1183. }
  1184. void release_engine(ENGINE *e)
  1185. {
  1186. #ifndef OPENSSL_NO_ENGINE
  1187. if (e != NULL)
  1188. /* Free our "structural" reference. */
  1189. ENGINE_free(e);
  1190. #endif
  1191. }
  1192. static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
  1193. {
  1194. const char *n;
  1195. n = a[DB_serial];
  1196. while (*n == '0')
  1197. n++;
  1198. return OPENSSL_LH_strhash(n);
  1199. }
  1200. static int index_serial_cmp(const OPENSSL_CSTRING *a,
  1201. const OPENSSL_CSTRING *b)
  1202. {
  1203. const char *aa, *bb;
  1204. for (aa = a[DB_serial]; *aa == '0'; aa++) ;
  1205. for (bb = b[DB_serial]; *bb == '0'; bb++) ;
  1206. return strcmp(aa, bb);
  1207. }
  1208. static int index_name_qual(char **a)
  1209. {
  1210. return (a[0][0] == 'V');
  1211. }
  1212. static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
  1213. {
  1214. return OPENSSL_LH_strhash(a[DB_name]);
  1215. }
  1216. int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
  1217. {
  1218. return strcmp(a[DB_name], b[DB_name]);
  1219. }
  1220. static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
  1221. static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
  1222. static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
  1223. static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
  1224. #undef BSIZE
  1225. #define BSIZE 256
  1226. BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
  1227. {
  1228. BIO *in = NULL;
  1229. BIGNUM *ret = NULL;
  1230. char buf[1024];
  1231. ASN1_INTEGER *ai = NULL;
  1232. ai = ASN1_INTEGER_new();
  1233. if (ai == NULL)
  1234. goto err;
  1235. in = BIO_new_file(serialfile, "r");
  1236. if (in == NULL) {
  1237. if (!create) {
  1238. perror(serialfile);
  1239. goto err;
  1240. }
  1241. ERR_clear_error();
  1242. ret = BN_new();
  1243. if (ret == NULL || !rand_serial(ret, ai))
  1244. BIO_printf(bio_err, "Out of memory\n");
  1245. } else {
  1246. if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
  1247. BIO_printf(bio_err, "unable to load number from %s\n",
  1248. serialfile);
  1249. goto err;
  1250. }
  1251. ret = ASN1_INTEGER_to_BN(ai, NULL);
  1252. if (ret == NULL) {
  1253. BIO_printf(bio_err,
  1254. "error converting number from bin to BIGNUM\n");
  1255. goto err;
  1256. }
  1257. }
  1258. if (ret && retai) {
  1259. *retai = ai;
  1260. ai = NULL;
  1261. }
  1262. err:
  1263. BIO_free(in);
  1264. ASN1_INTEGER_free(ai);
  1265. return ret;
  1266. }
  1267. int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
  1268. ASN1_INTEGER **retai)
  1269. {
  1270. char buf[1][BSIZE];
  1271. BIO *out = NULL;
  1272. int ret = 0;
  1273. ASN1_INTEGER *ai = NULL;
  1274. int j;
  1275. if (suffix == NULL)
  1276. j = strlen(serialfile);
  1277. else
  1278. j = strlen(serialfile) + strlen(suffix) + 1;
  1279. if (j >= BSIZE) {
  1280. BIO_printf(bio_err, "file name too long\n");
  1281. goto err;
  1282. }
  1283. if (suffix == NULL)
  1284. OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
  1285. else {
  1286. #ifndef OPENSSL_SYS_VMS
  1287. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
  1288. #else
  1289. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
  1290. #endif
  1291. }
  1292. out = BIO_new_file(buf[0], "w");
  1293. if (out == NULL) {
  1294. ERR_print_errors(bio_err);
  1295. goto err;
  1296. }
  1297. if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
  1298. BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
  1299. goto err;
  1300. }
  1301. i2a_ASN1_INTEGER(out, ai);
  1302. BIO_puts(out, "\n");
  1303. ret = 1;
  1304. if (retai) {
  1305. *retai = ai;
  1306. ai = NULL;
  1307. }
  1308. err:
  1309. BIO_free_all(out);
  1310. ASN1_INTEGER_free(ai);
  1311. return ret;
  1312. }
  1313. int rotate_serial(const char *serialfile, const char *new_suffix,
  1314. const char *old_suffix)
  1315. {
  1316. char buf[2][BSIZE];
  1317. int i, j;
  1318. i = strlen(serialfile) + strlen(old_suffix);
  1319. j = strlen(serialfile) + strlen(new_suffix);
  1320. if (i > j)
  1321. j = i;
  1322. if (j + 1 >= BSIZE) {
  1323. BIO_printf(bio_err, "file name too long\n");
  1324. goto err;
  1325. }
  1326. #ifndef OPENSSL_SYS_VMS
  1327. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
  1328. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
  1329. #else
  1330. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
  1331. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
  1332. #endif
  1333. if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
  1334. #ifdef ENOTDIR
  1335. && errno != ENOTDIR
  1336. #endif
  1337. ) {
  1338. BIO_printf(bio_err,
  1339. "unable to rename %s to %s\n", serialfile, buf[1]);
  1340. perror("reason");
  1341. goto err;
  1342. }
  1343. if (rename(buf[0], serialfile) < 0) {
  1344. BIO_printf(bio_err,
  1345. "unable to rename %s to %s\n", buf[0], serialfile);
  1346. perror("reason");
  1347. rename(buf[1], serialfile);
  1348. goto err;
  1349. }
  1350. return 1;
  1351. err:
  1352. return 0;
  1353. }
  1354. int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
  1355. {
  1356. BIGNUM *btmp;
  1357. int ret = 0;
  1358. btmp = b == NULL ? BN_new() : b;
  1359. if (btmp == NULL)
  1360. return 0;
  1361. if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
  1362. goto error;
  1363. if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
  1364. goto error;
  1365. ret = 1;
  1366. error:
  1367. if (btmp != b)
  1368. BN_free(btmp);
  1369. return ret;
  1370. }
  1371. CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
  1372. {
  1373. CA_DB *retdb = NULL;
  1374. TXT_DB *tmpdb = NULL;
  1375. BIO *in;
  1376. CONF *dbattr_conf = NULL;
  1377. char buf[BSIZE];
  1378. #ifndef OPENSSL_NO_POSIX_IO
  1379. FILE *dbfp;
  1380. struct stat dbst;
  1381. #endif
  1382. in = BIO_new_file(dbfile, "r");
  1383. if (in == NULL) {
  1384. ERR_print_errors(bio_err);
  1385. goto err;
  1386. }
  1387. #ifndef OPENSSL_NO_POSIX_IO
  1388. BIO_get_fp(in, &dbfp);
  1389. if (fstat(fileno(dbfp), &dbst) == -1) {
  1390. SYSerr(SYS_F_FSTAT, errno);
  1391. ERR_add_error_data(3, "fstat('", dbfile, "')");
  1392. ERR_print_errors(bio_err);
  1393. goto err;
  1394. }
  1395. #endif
  1396. if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
  1397. goto err;
  1398. #ifndef OPENSSL_SYS_VMS
  1399. BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
  1400. #else
  1401. BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
  1402. #endif
  1403. dbattr_conf = app_load_config(buf);
  1404. retdb = app_malloc(sizeof(*retdb), "new DB");
  1405. retdb->db = tmpdb;
  1406. tmpdb = NULL;
  1407. if (db_attr)
  1408. retdb->attributes = *db_attr;
  1409. else {
  1410. retdb->attributes.unique_subject = 1;
  1411. }
  1412. if (dbattr_conf) {
  1413. char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
  1414. if (p) {
  1415. retdb->attributes.unique_subject = parse_yesno(p, 1);
  1416. }
  1417. }
  1418. retdb->dbfname = OPENSSL_strdup(dbfile);
  1419. #ifndef OPENSSL_NO_POSIX_IO
  1420. retdb->dbst = dbst;
  1421. #endif
  1422. err:
  1423. NCONF_free(dbattr_conf);
  1424. TXT_DB_free(tmpdb);
  1425. BIO_free_all(in);
  1426. return retdb;
  1427. }
  1428. /*
  1429. * Returns > 0 on success, <= 0 on error
  1430. */
  1431. int index_index(CA_DB *db)
  1432. {
  1433. if (!TXT_DB_create_index(db->db, DB_serial, NULL,
  1434. LHASH_HASH_FN(index_serial),
  1435. LHASH_COMP_FN(index_serial))) {
  1436. BIO_printf(bio_err,
  1437. "error creating serial number index:(%ld,%ld,%ld)\n",
  1438. db->db->error, db->db->arg1, db->db->arg2);
  1439. return 0;
  1440. }
  1441. if (db->attributes.unique_subject
  1442. && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
  1443. LHASH_HASH_FN(index_name),
  1444. LHASH_COMP_FN(index_name))) {
  1445. BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
  1446. db->db->error, db->db->arg1, db->db->arg2);
  1447. return 0;
  1448. }
  1449. return 1;
  1450. }
  1451. int save_index(const char *dbfile, const char *suffix, CA_DB *db)
  1452. {
  1453. char buf[3][BSIZE];
  1454. BIO *out;
  1455. int j;
  1456. j = strlen(dbfile) + strlen(suffix);
  1457. if (j + 6 >= BSIZE) {
  1458. BIO_printf(bio_err, "file name too long\n");
  1459. goto err;
  1460. }
  1461. #ifndef OPENSSL_SYS_VMS
  1462. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
  1463. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
  1464. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
  1465. #else
  1466. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
  1467. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
  1468. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
  1469. #endif
  1470. out = BIO_new_file(buf[0], "w");
  1471. if (out == NULL) {
  1472. perror(dbfile);
  1473. BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
  1474. goto err;
  1475. }
  1476. j = TXT_DB_write(out, db->db);
  1477. BIO_free(out);
  1478. if (j <= 0)
  1479. goto err;
  1480. out = BIO_new_file(buf[1], "w");
  1481. if (out == NULL) {
  1482. perror(buf[2]);
  1483. BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
  1484. goto err;
  1485. }
  1486. BIO_printf(out, "unique_subject = %s\n",
  1487. db->attributes.unique_subject ? "yes" : "no");
  1488. BIO_free(out);
  1489. return 1;
  1490. err:
  1491. return 0;
  1492. }
  1493. int rotate_index(const char *dbfile, const char *new_suffix,
  1494. const char *old_suffix)
  1495. {
  1496. char buf[5][BSIZE];
  1497. int i, j;
  1498. i = strlen(dbfile) + strlen(old_suffix);
  1499. j = strlen(dbfile) + strlen(new_suffix);
  1500. if (i > j)
  1501. j = i;
  1502. if (j + 6 >= BSIZE) {
  1503. BIO_printf(bio_err, "file name too long\n");
  1504. goto err;
  1505. }
  1506. #ifndef OPENSSL_SYS_VMS
  1507. j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
  1508. j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
  1509. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
  1510. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
  1511. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
  1512. #else
  1513. j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
  1514. j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
  1515. j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
  1516. j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
  1517. j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
  1518. #endif
  1519. if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
  1520. #ifdef ENOTDIR
  1521. && errno != ENOTDIR
  1522. #endif
  1523. ) {
  1524. BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
  1525. perror("reason");
  1526. goto err;
  1527. }
  1528. if (rename(buf[0], dbfile) < 0) {
  1529. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
  1530. perror("reason");
  1531. rename(buf[1], dbfile);
  1532. goto err;
  1533. }
  1534. if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
  1535. #ifdef ENOTDIR
  1536. && errno != ENOTDIR
  1537. #endif
  1538. ) {
  1539. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
  1540. perror("reason");
  1541. rename(dbfile, buf[0]);
  1542. rename(buf[1], dbfile);
  1543. goto err;
  1544. }
  1545. if (rename(buf[2], buf[4]) < 0) {
  1546. BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
  1547. perror("reason");
  1548. rename(buf[3], buf[4]);
  1549. rename(dbfile, buf[0]);
  1550. rename(buf[1], dbfile);
  1551. goto err;
  1552. }
  1553. return 1;
  1554. err:
  1555. return 0;
  1556. }
  1557. void free_index(CA_DB *db)
  1558. {
  1559. if (db) {
  1560. TXT_DB_free(db->db);
  1561. OPENSSL_free(db->dbfname);
  1562. OPENSSL_free(db);
  1563. }
  1564. }
  1565. int parse_yesno(const char *str, int def)
  1566. {
  1567. if (str) {
  1568. switch (*str) {
  1569. case 'f': /* false */
  1570. case 'F': /* FALSE */
  1571. case 'n': /* no */
  1572. case 'N': /* NO */
  1573. case '0': /* 0 */
  1574. return 0;
  1575. case 't': /* true */
  1576. case 'T': /* TRUE */
  1577. case 'y': /* yes */
  1578. case 'Y': /* YES */
  1579. case '1': /* 1 */
  1580. return 1;
  1581. }
  1582. }
  1583. return def;
  1584. }
  1585. /*
  1586. * name is expected to be in the format /type0=value0/type1=value1/type2=...
  1587. * where characters may be escaped by \
  1588. */
  1589. X509_NAME *parse_name(const char *cp, long chtype, int canmulti)
  1590. {
  1591. int nextismulti = 0;
  1592. char *work;
  1593. X509_NAME *n;
  1594. if (*cp++ != '/')
  1595. return NULL;
  1596. n = X509_NAME_new();
  1597. if (n == NULL)
  1598. return NULL;
  1599. work = OPENSSL_strdup(cp);
  1600. if (work == NULL)
  1601. goto err;
  1602. while (*cp) {
  1603. char *bp = work;
  1604. char *typestr = bp;
  1605. unsigned char *valstr;
  1606. int nid;
  1607. int ismulti = nextismulti;
  1608. nextismulti = 0;
  1609. /* Collect the type */
  1610. while (*cp && *cp != '=')
  1611. *bp++ = *cp++;
  1612. if (*cp == '\0') {
  1613. BIO_printf(bio_err,
  1614. "%s: Hit end of string before finding the equals.\n",
  1615. opt_getprog());
  1616. goto err;
  1617. }
  1618. *bp++ = '\0';
  1619. ++cp;
  1620. /* Collect the value. */
  1621. valstr = (unsigned char *)bp;
  1622. for (; *cp && *cp != '/'; *bp++ = *cp++) {
  1623. if (canmulti && *cp == '+') {
  1624. nextismulti = 1;
  1625. break;
  1626. }
  1627. if (*cp == '\\' && *++cp == '\0') {
  1628. BIO_printf(bio_err,
  1629. "%s: escape character at end of string\n",
  1630. opt_getprog());
  1631. goto err;
  1632. }
  1633. }
  1634. *bp++ = '\0';
  1635. /* If not at EOS (must be + or /), move forward. */
  1636. if (*cp)
  1637. ++cp;
  1638. /* Parse */
  1639. nid = OBJ_txt2nid(typestr);
  1640. if (nid == NID_undef) {
  1641. BIO_printf(bio_err, "%s: Skipping unknown attribute \"%s\"\n",
  1642. opt_getprog(), typestr);
  1643. continue;
  1644. }
  1645. if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
  1646. valstr, strlen((char *)valstr),
  1647. -1, ismulti ? -1 : 0))
  1648. goto err;
  1649. }
  1650. OPENSSL_free(work);
  1651. return n;
  1652. err:
  1653. X509_NAME_free(n);
  1654. OPENSSL_free(work);
  1655. return NULL;
  1656. }
  1657. /*
  1658. * Read whole contents of a BIO into an allocated memory buffer and return
  1659. * it.
  1660. */
  1661. int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
  1662. {
  1663. BIO *mem;
  1664. int len, ret;
  1665. unsigned char tbuf[1024];
  1666. mem = BIO_new(BIO_s_mem());
  1667. if (mem == NULL)
  1668. return -1;
  1669. for (;;) {
  1670. if ((maxlen != -1) && maxlen < 1024)
  1671. len = maxlen;
  1672. else
  1673. len = 1024;
  1674. len = BIO_read(in, tbuf, len);
  1675. if (len < 0) {
  1676. BIO_free(mem);
  1677. return -1;
  1678. }
  1679. if (len == 0)
  1680. break;
  1681. if (BIO_write(mem, tbuf, len) != len) {
  1682. BIO_free(mem);
  1683. return -1;
  1684. }
  1685. maxlen -= len;
  1686. if (maxlen == 0)
  1687. break;
  1688. }
  1689. ret = BIO_get_mem_data(mem, (char **)out);
  1690. BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
  1691. BIO_free(mem);
  1692. return ret;
  1693. }
  1694. int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
  1695. {
  1696. int rv;
  1697. char *stmp, *vtmp = NULL;
  1698. stmp = OPENSSL_strdup(value);
  1699. if (!stmp)
  1700. return -1;
  1701. vtmp = strchr(stmp, ':');
  1702. if (vtmp) {
  1703. *vtmp = 0;
  1704. vtmp++;
  1705. }
  1706. rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
  1707. OPENSSL_free(stmp);
  1708. return rv;
  1709. }
  1710. static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
  1711. {
  1712. X509_POLICY_NODE *node;
  1713. int i;
  1714. BIO_printf(bio_err, "%s Policies:", name);
  1715. if (nodes) {
  1716. BIO_puts(bio_err, "\n");
  1717. for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
  1718. node = sk_X509_POLICY_NODE_value(nodes, i);
  1719. X509_POLICY_NODE_print(bio_err, node, 2);
  1720. }
  1721. } else {
  1722. BIO_puts(bio_err, " <empty>\n");
  1723. }
  1724. }
  1725. void policies_print(X509_STORE_CTX *ctx)
  1726. {
  1727. X509_POLICY_TREE *tree;
  1728. int explicit_policy;
  1729. tree = X509_STORE_CTX_get0_policy_tree(ctx);
  1730. explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
  1731. BIO_printf(bio_err, "Require explicit Policy: %s\n",
  1732. explicit_policy ? "True" : "False");
  1733. nodes_print("Authority", X509_policy_tree_get0_policies(tree));
  1734. nodes_print("User", X509_policy_tree_get0_user_policies(tree));
  1735. }
  1736. /*-
  1737. * next_protos_parse parses a comma separated list of strings into a string
  1738. * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
  1739. * outlen: (output) set to the length of the resulting buffer on success.
  1740. * err: (maybe NULL) on failure, an error message line is written to this BIO.
  1741. * in: a NUL terminated string like "abc,def,ghi"
  1742. *
  1743. * returns: a malloc'd buffer or NULL on failure.
  1744. */
  1745. unsigned char *next_protos_parse(size_t *outlen, const char *in)
  1746. {
  1747. size_t len;
  1748. unsigned char *out;
  1749. size_t i, start = 0;
  1750. len = strlen(in);
  1751. if (len >= 65535)
  1752. return NULL;
  1753. out = app_malloc(strlen(in) + 1, "NPN buffer");
  1754. for (i = 0; i <= len; ++i) {
  1755. if (i == len || in[i] == ',') {
  1756. if (i - start > 255) {
  1757. OPENSSL_free(out);
  1758. return NULL;
  1759. }
  1760. out[start] = (unsigned char)(i - start);
  1761. start = i + 1;
  1762. } else {
  1763. out[i + 1] = in[i];
  1764. }
  1765. }
  1766. *outlen = len + 1;
  1767. return out;
  1768. }
  1769. void print_cert_checks(BIO *bio, X509 *x,
  1770. const char *checkhost,
  1771. const char *checkemail, const char *checkip)
  1772. {
  1773. if (x == NULL)
  1774. return;
  1775. if (checkhost) {
  1776. BIO_printf(bio, "Hostname %s does%s match certificate\n",
  1777. checkhost,
  1778. X509_check_host(x, checkhost, 0, 0, NULL) == 1
  1779. ? "" : " NOT");
  1780. }
  1781. if (checkemail) {
  1782. BIO_printf(bio, "Email %s does%s match certificate\n",
  1783. checkemail, X509_check_email(x, checkemail, 0, 0)
  1784. ? "" : " NOT");
  1785. }
  1786. if (checkip) {
  1787. BIO_printf(bio, "IP %s does%s match certificate\n",
  1788. checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
  1789. }
  1790. }
  1791. /* Get first http URL from a DIST_POINT structure */
  1792. static const char *get_dp_url(DIST_POINT *dp)
  1793. {
  1794. GENERAL_NAMES *gens;
  1795. GENERAL_NAME *gen;
  1796. int i, gtype;
  1797. ASN1_STRING *uri;
  1798. if (!dp->distpoint || dp->distpoint->type != 0)
  1799. return NULL;
  1800. gens = dp->distpoint->name.fullname;
  1801. for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
  1802. gen = sk_GENERAL_NAME_value(gens, i);
  1803. uri = GENERAL_NAME_get0_value(gen, &gtype);
  1804. if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
  1805. const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
  1806. if (strncmp(uptr, "http://", 7) == 0)
  1807. return uptr;
  1808. }
  1809. }
  1810. return NULL;
  1811. }
  1812. /*
  1813. * Look through a CRLDP structure and attempt to find an http URL to
  1814. * downloads a CRL from.
  1815. */
  1816. static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
  1817. {
  1818. int i;
  1819. const char *urlptr = NULL;
  1820. for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
  1821. DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
  1822. urlptr = get_dp_url(dp);
  1823. if (urlptr)
  1824. return load_crl(urlptr, FORMAT_HTTP);
  1825. }
  1826. return NULL;
  1827. }
  1828. /*
  1829. * Example of downloading CRLs from CRLDP: not usable for real world as it
  1830. * always downloads, doesn't support non-blocking I/O and doesn't cache
  1831. * anything.
  1832. */
  1833. static STACK_OF(X509_CRL) *crls_http_cb(X509_STORE_CTX *ctx, X509_NAME *nm)
  1834. {
  1835. X509 *x;
  1836. STACK_OF(X509_CRL) *crls = NULL;
  1837. X509_CRL *crl;
  1838. STACK_OF(DIST_POINT) *crldp;
  1839. crls = sk_X509_CRL_new_null();
  1840. if (!crls)
  1841. return NULL;
  1842. x = X509_STORE_CTX_get_current_cert(ctx);
  1843. crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
  1844. crl = load_crl_crldp(crldp);
  1845. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  1846. if (!crl) {
  1847. sk_X509_CRL_free(crls);
  1848. return NULL;
  1849. }
  1850. sk_X509_CRL_push(crls, crl);
  1851. /* Try to download delta CRL */
  1852. crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
  1853. crl = load_crl_crldp(crldp);
  1854. sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
  1855. if (crl)
  1856. sk_X509_CRL_push(crls, crl);
  1857. return crls;
  1858. }
  1859. void store_setup_crl_download(X509_STORE *st)
  1860. {
  1861. X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
  1862. }
  1863. /*
  1864. * Platform-specific sections
  1865. */
  1866. #if defined(_WIN32)
  1867. # ifdef fileno
  1868. # undef fileno
  1869. # define fileno(a) (int)_fileno(a)
  1870. # endif
  1871. # include <windows.h>
  1872. # include <tchar.h>
  1873. static int WIN32_rename(const char *from, const char *to)
  1874. {
  1875. TCHAR *tfrom = NULL, *tto;
  1876. DWORD err;
  1877. int ret = 0;
  1878. if (sizeof(TCHAR) == 1) {
  1879. tfrom = (TCHAR *)from;
  1880. tto = (TCHAR *)to;
  1881. } else { /* UNICODE path */
  1882. size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
  1883. tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
  1884. if (tfrom == NULL)
  1885. goto err;
  1886. tto = tfrom + flen;
  1887. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  1888. if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
  1889. # endif
  1890. for (i = 0; i < flen; i++)
  1891. tfrom[i] = (TCHAR)from[i];
  1892. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  1893. if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
  1894. # endif
  1895. for (i = 0; i < tlen; i++)
  1896. tto[i] = (TCHAR)to[i];
  1897. }
  1898. if (MoveFile(tfrom, tto))
  1899. goto ok;
  1900. err = GetLastError();
  1901. if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
  1902. if (DeleteFile(tto) && MoveFile(tfrom, tto))
  1903. goto ok;
  1904. err = GetLastError();
  1905. }
  1906. if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
  1907. errno = ENOENT;
  1908. else if (err == ERROR_ACCESS_DENIED)
  1909. errno = EACCES;
  1910. else
  1911. errno = EINVAL; /* we could map more codes... */
  1912. err:
  1913. ret = -1;
  1914. ok:
  1915. if (tfrom != NULL && tfrom != (TCHAR *)from)
  1916. free(tfrom);
  1917. return ret;
  1918. }
  1919. #endif
  1920. /* app_tminterval section */
  1921. #if defined(_WIN32)
  1922. double app_tminterval(int stop, int usertime)
  1923. {
  1924. FILETIME now;
  1925. double ret = 0;
  1926. static ULARGE_INTEGER tmstart;
  1927. static int warning = 1;
  1928. # ifdef _WIN32_WINNT
  1929. static HANDLE proc = NULL;
  1930. if (proc == NULL) {
  1931. if (check_winnt())
  1932. proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
  1933. GetCurrentProcessId());
  1934. if (proc == NULL)
  1935. proc = (HANDLE) - 1;
  1936. }
  1937. if (usertime && proc != (HANDLE) - 1) {
  1938. FILETIME junk;
  1939. GetProcessTimes(proc, &junk, &junk, &junk, &now);
  1940. } else
  1941. # endif
  1942. {
  1943. SYSTEMTIME systime;
  1944. if (usertime && warning) {
  1945. BIO_printf(bio_err, "To get meaningful results, run "
  1946. "this program on idle system.\n");
  1947. warning = 0;
  1948. }
  1949. GetSystemTime(&systime);
  1950. SystemTimeToFileTime(&systime, &now);
  1951. }
  1952. if (stop == TM_START) {
  1953. tmstart.u.LowPart = now.dwLowDateTime;
  1954. tmstart.u.HighPart = now.dwHighDateTime;
  1955. } else {
  1956. ULARGE_INTEGER tmstop;
  1957. tmstop.u.LowPart = now.dwLowDateTime;
  1958. tmstop.u.HighPart = now.dwHighDateTime;
  1959. ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
  1960. }
  1961. return ret;
  1962. }
  1963. #elif defined(OPENSSL_SYSTEM_VXWORKS)
  1964. # include <time.h>
  1965. double app_tminterval(int stop, int usertime)
  1966. {
  1967. double ret = 0;
  1968. # ifdef CLOCK_REALTIME
  1969. static struct timespec tmstart;
  1970. struct timespec now;
  1971. # else
  1972. static unsigned long tmstart;
  1973. unsigned long now;
  1974. # endif
  1975. static int warning = 1;
  1976. if (usertime && warning) {
  1977. BIO_printf(bio_err, "To get meaningful results, run "
  1978. "this program on idle system.\n");
  1979. warning = 0;
  1980. }
  1981. # ifdef CLOCK_REALTIME
  1982. clock_gettime(CLOCK_REALTIME, &now);
  1983. if (stop == TM_START)
  1984. tmstart = now;
  1985. else
  1986. ret = ((now.tv_sec + now.tv_nsec * 1e-9)
  1987. - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
  1988. # else
  1989. now = tickGet();
  1990. if (stop == TM_START)
  1991. tmstart = now;
  1992. else
  1993. ret = (now - tmstart) / (double)sysClkRateGet();
  1994. # endif
  1995. return ret;
  1996. }
  1997. #elif defined(OPENSSL_SYSTEM_VMS)
  1998. # include <time.h>
  1999. # include <times.h>
  2000. double app_tminterval(int stop, int usertime)
  2001. {
  2002. static clock_t tmstart;
  2003. double ret = 0;
  2004. clock_t now;
  2005. # ifdef __TMS
  2006. struct tms rus;
  2007. now = times(&rus);
  2008. if (usertime)
  2009. now = rus.tms_utime;
  2010. # else
  2011. if (usertime)
  2012. now = clock(); /* sum of user and kernel times */
  2013. else {
  2014. struct timeval tv;
  2015. gettimeofday(&tv, NULL);
  2016. now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
  2017. (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
  2018. );
  2019. }
  2020. # endif
  2021. if (stop == TM_START)
  2022. tmstart = now;
  2023. else
  2024. ret = (now - tmstart) / (double)(CLK_TCK);
  2025. return ret;
  2026. }
  2027. #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
  2028. # include <sys/times.h>
  2029. double app_tminterval(int stop, int usertime)
  2030. {
  2031. double ret = 0;
  2032. struct tms rus;
  2033. clock_t now = times(&rus);
  2034. static clock_t tmstart;
  2035. if (usertime)
  2036. now = rus.tms_utime;
  2037. if (stop == TM_START) {
  2038. tmstart = now;
  2039. } else {
  2040. long int tck = sysconf(_SC_CLK_TCK);
  2041. ret = (now - tmstart) / (double)tck;
  2042. }
  2043. return ret;
  2044. }
  2045. #else
  2046. # include <sys/time.h>
  2047. # include <sys/resource.h>
  2048. double app_tminterval(int stop, int usertime)
  2049. {
  2050. double ret = 0;
  2051. struct rusage rus;
  2052. struct timeval now;
  2053. static struct timeval tmstart;
  2054. if (usertime)
  2055. getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
  2056. else
  2057. gettimeofday(&now, NULL);
  2058. if (stop == TM_START)
  2059. tmstart = now;
  2060. else
  2061. ret = ((now.tv_sec + now.tv_usec * 1e-6)
  2062. - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
  2063. return ret;
  2064. }
  2065. #endif
  2066. int app_access(const char* name, int flag)
  2067. {
  2068. #ifdef _WIN32
  2069. return _access(name, flag);
  2070. #else
  2071. return access(name, flag);
  2072. #endif
  2073. }
  2074. /* app_isdir section */
  2075. #ifdef _WIN32
  2076. int app_isdir(const char *name)
  2077. {
  2078. DWORD attr;
  2079. # if defined(UNICODE) || defined(_UNICODE)
  2080. size_t i, len_0 = strlen(name) + 1;
  2081. WCHAR tempname[MAX_PATH];
  2082. if (len_0 > MAX_PATH)
  2083. return -1;
  2084. # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
  2085. if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH))
  2086. # endif
  2087. for (i = 0; i < len_0; i++)
  2088. tempname[i] = (WCHAR)name[i];
  2089. attr = GetFileAttributes(tempname);
  2090. # else
  2091. attr = GetFileAttributes(name);
  2092. # endif
  2093. if (attr == INVALID_FILE_ATTRIBUTES)
  2094. return -1;
  2095. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  2096. }
  2097. #else
  2098. # include <sys/stat.h>
  2099. # ifndef S_ISDIR
  2100. # if defined(_S_IFMT) && defined(_S_IFDIR)
  2101. # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
  2102. # else
  2103. # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
  2104. # endif
  2105. # endif
  2106. int app_isdir(const char *name)
  2107. {
  2108. # if defined(S_ISDIR)
  2109. struct stat st;
  2110. if (stat(name, &st) == 0)
  2111. return S_ISDIR(st.st_mode);
  2112. else
  2113. return -1;
  2114. # else
  2115. return -1;
  2116. # endif
  2117. }
  2118. #endif
  2119. /* raw_read|write section */
  2120. #if defined(__VMS)
  2121. # include "vms_term_sock.h"
  2122. static int stdin_sock = -1;
  2123. static void close_stdin_sock(void)
  2124. {
  2125. TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
  2126. }
  2127. int fileno_stdin(void)
  2128. {
  2129. if (stdin_sock == -1) {
  2130. TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
  2131. atexit(close_stdin_sock);
  2132. }
  2133. return stdin_sock;
  2134. }
  2135. #else
  2136. int fileno_stdin(void)
  2137. {
  2138. return fileno(stdin);
  2139. }
  2140. #endif
  2141. int fileno_stdout(void)
  2142. {
  2143. return fileno(stdout);
  2144. }
  2145. #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
  2146. int raw_read_stdin(void *buf, int siz)
  2147. {
  2148. DWORD n;
  2149. if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
  2150. return n;
  2151. else
  2152. return -1;
  2153. }
  2154. #elif defined(__VMS)
  2155. # include <sys/socket.h>
  2156. int raw_read_stdin(void *buf, int siz)
  2157. {
  2158. return recv(fileno_stdin(), buf, siz, 0);
  2159. }
  2160. #else
  2161. int raw_read_stdin(void *buf, int siz)
  2162. {
  2163. return read(fileno_stdin(), buf, siz);
  2164. }
  2165. #endif
  2166. #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
  2167. int raw_write_stdout(const void *buf, int siz)
  2168. {
  2169. DWORD n;
  2170. if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
  2171. return n;
  2172. else
  2173. return -1;
  2174. }
  2175. #else
  2176. int raw_write_stdout(const void *buf, int siz)
  2177. {
  2178. return write(fileno_stdout(), buf, siz);
  2179. }
  2180. #endif
  2181. /*
  2182. * Centralized handling if input and output files with format specification
  2183. * The format is meant to show what the input and output is supposed to be,
  2184. * and is therefore a show of intent more than anything else. However, it
  2185. * does impact behavior on some platform, such as differentiating between
  2186. * text and binary input/output on non-Unix platforms
  2187. */
  2188. static int istext(int format)
  2189. {
  2190. return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT;
  2191. }
  2192. BIO *dup_bio_in(int format)
  2193. {
  2194. return BIO_new_fp(stdin,
  2195. BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
  2196. }
  2197. static BIO_METHOD *prefix_method = NULL;
  2198. BIO *dup_bio_out(int format)
  2199. {
  2200. BIO *b = BIO_new_fp(stdout,
  2201. BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
  2202. void *prefix = NULL;
  2203. #ifdef OPENSSL_SYS_VMS
  2204. if (istext(format))
  2205. b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
  2206. #endif
  2207. if (istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
  2208. if (prefix_method == NULL)
  2209. prefix_method = apps_bf_prefix();
  2210. b = BIO_push(BIO_new(prefix_method), b);
  2211. BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix);
  2212. }
  2213. return b;
  2214. }
  2215. BIO *dup_bio_err(int format)
  2216. {
  2217. BIO *b = BIO_new_fp(stderr,
  2218. BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0));
  2219. #ifdef OPENSSL_SYS_VMS
  2220. if (istext(format))
  2221. b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
  2222. #endif
  2223. return b;
  2224. }
  2225. void destroy_prefix_method(void)
  2226. {
  2227. BIO_meth_free(prefix_method);
  2228. prefix_method = NULL;
  2229. }
  2230. void unbuffer(FILE *fp)
  2231. {
  2232. /*
  2233. * On VMS, setbuf() will only take 32-bit pointers, and a compilation
  2234. * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
  2235. * However, we trust that the C RTL will never give us a FILE pointer
  2236. * above the first 4 GB of memory, so we simply turn off the warning
  2237. * temporarily.
  2238. */
  2239. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  2240. # pragma environment save
  2241. # pragma message disable maylosedata2
  2242. #endif
  2243. setbuf(fp, NULL);
  2244. #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
  2245. # pragma environment restore
  2246. #endif
  2247. }
  2248. static const char *modestr(char mode, int format)
  2249. {
  2250. OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
  2251. switch (mode) {
  2252. case 'a':
  2253. return istext(format) ? "a" : "ab";
  2254. case 'r':
  2255. return istext(format) ? "r" : "rb";
  2256. case 'w':
  2257. return istext(format) ? "w" : "wb";
  2258. }
  2259. /* The assert above should make sure we never reach this point */
  2260. return NULL;
  2261. }
  2262. static const char *modeverb(char mode)
  2263. {
  2264. switch (mode) {
  2265. case 'a':
  2266. return "appending";
  2267. case 'r':
  2268. return "reading";
  2269. case 'w':
  2270. return "writing";
  2271. }
  2272. return "(doing something)";
  2273. }
  2274. /*
  2275. * Open a file for writing, owner-read-only.
  2276. */
  2277. BIO *bio_open_owner(const char *filename, int format, int private)
  2278. {
  2279. FILE *fp = NULL;
  2280. BIO *b = NULL;
  2281. int fd = -1, bflags, mode, textmode;
  2282. if (!private || filename == NULL || strcmp(filename, "-") == 0)
  2283. return bio_open_default(filename, 'w', format);
  2284. mode = O_WRONLY;
  2285. #ifdef O_CREAT
  2286. mode |= O_CREAT;
  2287. #endif
  2288. #ifdef O_TRUNC
  2289. mode |= O_TRUNC;
  2290. #endif
  2291. textmode = istext(format);
  2292. if (!textmode) {
  2293. #ifdef O_BINARY
  2294. mode |= O_BINARY;
  2295. #elif defined(_O_BINARY)
  2296. mode |= _O_BINARY;
  2297. #endif
  2298. }
  2299. #ifdef OPENSSL_SYS_VMS
  2300. /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
  2301. * it still needs to know that we're going binary, or fdopen()
  2302. * will fail with "invalid argument"... so we tell VMS what the
  2303. * context is.
  2304. */
  2305. if (!textmode)
  2306. fd = open(filename, mode, 0600, "ctx=bin");
  2307. else
  2308. #endif
  2309. fd = open(filename, mode, 0600);
  2310. if (fd < 0)
  2311. goto err;
  2312. fp = fdopen(fd, modestr('w', format));
  2313. if (fp == NULL)
  2314. goto err;
  2315. bflags = BIO_CLOSE;
  2316. if (textmode)
  2317. bflags |= BIO_FP_TEXT;
  2318. b = BIO_new_fp(fp, bflags);
  2319. if (b)
  2320. return b;
  2321. err:
  2322. BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
  2323. opt_getprog(), filename, strerror(errno));
  2324. ERR_print_errors(bio_err);
  2325. /* If we have fp, then fdopen took over fd, so don't close both. */
  2326. if (fp)
  2327. fclose(fp);
  2328. else if (fd >= 0)
  2329. close(fd);
  2330. return NULL;
  2331. }
  2332. static BIO *bio_open_default_(const char *filename, char mode, int format,
  2333. int quiet)
  2334. {
  2335. BIO *ret;
  2336. if (filename == NULL || strcmp(filename, "-") == 0) {
  2337. ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
  2338. if (quiet) {
  2339. ERR_clear_error();
  2340. return ret;
  2341. }
  2342. if (ret != NULL)
  2343. return ret;
  2344. BIO_printf(bio_err,
  2345. "Can't open %s, %s\n",
  2346. mode == 'r' ? "stdin" : "stdout", strerror(errno));
  2347. } else {
  2348. ret = BIO_new_file(filename, modestr(mode, format));
  2349. if (quiet) {
  2350. ERR_clear_error();
  2351. return ret;
  2352. }
  2353. if (ret != NULL)
  2354. return ret;
  2355. BIO_printf(bio_err,
  2356. "Can't open %s for %s, %s\n",
  2357. filename, modeverb(mode), strerror(errno));
  2358. }
  2359. ERR_print_errors(bio_err);
  2360. return NULL;
  2361. }
  2362. BIO *bio_open_default(const char *filename, char mode, int format)
  2363. {
  2364. return bio_open_default_(filename, mode, format, 0);
  2365. }
  2366. BIO *bio_open_default_quiet(const char *filename, char mode, int format)
  2367. {
  2368. return bio_open_default_(filename, mode, format, 1);
  2369. }
  2370. void wait_for_async(SSL *s)
  2371. {
  2372. /* On Windows select only works for sockets, so we simply don't wait */
  2373. #ifndef OPENSSL_SYS_WINDOWS
  2374. int width = 0;
  2375. fd_set asyncfds;
  2376. OSSL_ASYNC_FD *fds;
  2377. size_t numfds;
  2378. size_t i;
  2379. if (!SSL_get_all_async_fds(s, NULL, &numfds))
  2380. return;
  2381. if (numfds == 0)
  2382. return;
  2383. fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
  2384. if (!SSL_get_all_async_fds(s, fds, &numfds)) {
  2385. OPENSSL_free(fds);
  2386. return;
  2387. }
  2388. FD_ZERO(&asyncfds);
  2389. for (i = 0; i < numfds; i++) {
  2390. if (width <= (int)fds[i])
  2391. width = (int)fds[i] + 1;
  2392. openssl_fdset((int)fds[i], &asyncfds);
  2393. }
  2394. select(width, (void *)&asyncfds, NULL, NULL, NULL);
  2395. OPENSSL_free(fds);
  2396. #endif
  2397. }
  2398. /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
  2399. #if defined(OPENSSL_SYS_MSDOS)
  2400. int has_stdin_waiting(void)
  2401. {
  2402. # if defined(OPENSSL_SYS_WINDOWS)
  2403. HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
  2404. DWORD events = 0;
  2405. INPUT_RECORD inputrec;
  2406. DWORD insize = 1;
  2407. BOOL peeked;
  2408. if (inhand == INVALID_HANDLE_VALUE) {
  2409. return 0;
  2410. }
  2411. peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
  2412. if (!peeked) {
  2413. /* Probably redirected input? _kbhit() does not work in this case */
  2414. if (!feof(stdin)) {
  2415. return 1;
  2416. }
  2417. return 0;
  2418. }
  2419. # endif
  2420. return _kbhit();
  2421. }
  2422. #endif
  2423. /* Corrupt a signature by modifying final byte */
  2424. void corrupt_signature(const ASN1_STRING *signature)
  2425. {
  2426. unsigned char *s = signature->data;
  2427. s[signature->length - 1] ^= 0x1;
  2428. }
  2429. int set_cert_times(X509 *x, const char *startdate, const char *enddate,
  2430. int days)
  2431. {
  2432. if (startdate == NULL || strcmp(startdate, "today") == 0) {
  2433. if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
  2434. return 0;
  2435. } else {
  2436. if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
  2437. return 0;
  2438. }
  2439. if (enddate == NULL) {
  2440. if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
  2441. == NULL)
  2442. return 0;
  2443. } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
  2444. return 0;
  2445. }
  2446. return 1;
  2447. }
  2448. void make_uppercase(char *string)
  2449. {
  2450. int i;
  2451. for (i = 0; string[i] != '\0'; i++)
  2452. string[i] = toupper((unsigned char)string[i]);
  2453. }