apps.c 73 KB

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