2
0

apps.c 79 KB

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