apps.c 78 KB

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