2
0

easy-tls.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. /* -*- Mode: C; c-file-style: "bsd" -*- */
  2. /*-
  3. * easy-tls.c -- generic TLS proxy.
  4. * $Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $
  5. */
  6. /*-
  7. (c) Copyright 1999 Bodo Moeller. All rights reserved.
  8. This is free software; you can redistributed and/or modify it
  9. unter the terms of either
  10. - the GNU General Public License as published by the
  11. Free Software Foundation, version 1, or (at your option)
  12. any later version,
  13. or
  14. - the following license:
  15. */
  16. /*-
  17. * Redistribution and use in source and binary forms, with or without
  18. * modification, are permitted provided that each of the following
  19. * conditions is met:
  20. *
  21. * 1. Redistributions qualify as "freeware" or "Open Source Software" under
  22. * one of the following terms:
  23. *
  24. * (a) Redistributions are made at no charge beyond the reasonable cost of
  25. * materials and delivery.
  26. *
  27. * (b) Redistributions are accompanied by a copy of the Source Code
  28. * or by an irrevocable offer to provide a copy of the Source Code
  29. * for up to three years at the cost of materials and delivery.
  30. * Such redistributions must allow further use, modification, and
  31. * redistribution of the Source Code under substantially the same
  32. * terms as this license.
  33. *
  34. * 2. Redistributions of source code must retain the above copyright
  35. * notice, this list of conditions and the following disclaimer.
  36. *
  37. * 3. Redistributions in binary form must reproduce the above copyright
  38. * notice, this list of conditions and the following disclaimer in
  39. * the documentation and/or other materials provided with the
  40. * distribution.
  41. *
  42. * 4. All advertising materials mentioning features or use of this
  43. * software must display the following acknowledgment:
  44. * "This product includes software developed by Bodo Moeller."
  45. * (If available, substitute umlauted o for oe.)
  46. *
  47. * 5. Redistributions of any form whatsoever must retain the following
  48. * acknowledgment:
  49. * "This product includes software developed by Bodo Moeller."
  50. *
  51. * THIS SOFTWARE IS PROVIDED BY BODO MOELLER ``AS IS'' AND ANY
  52. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  53. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  54. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BODO MOELLER OR
  55. * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  56. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  57. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  58. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  59. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  60. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  61. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  62. * OF THE POSSIBILITY OF SUCH DAMAGE.
  63. */
  64. /*-
  65. * Attribution for OpenSSL library:
  66. *
  67. * This product includes cryptographic software written by Eric Young
  68. * (eay@cryptsoft.com). This product includes software written by Tim
  69. * Hudson (tjh@cryptsoft.com).
  70. * This product includes software developed by the OpenSSL Project
  71. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)
  72. */
  73. static char const rcsid[] =
  74. "$Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $";
  75. #include <assert.h>
  76. #include <errno.h>
  77. #include <fcntl.h>
  78. #include <limits.h>
  79. #include <stdarg.h>
  80. #include <stdio.h>
  81. #include <string.h>
  82. #include <sys/select.h>
  83. #include <sys/socket.h>
  84. #include <sys/stat.h>
  85. #include <sys/time.h>
  86. #include <sys/types.h>
  87. #include <sys/utsname.h>
  88. #include <unistd.h>
  89. #include <openssl/crypto.h>
  90. #include <openssl/dh.h>
  91. #include <openssl/dsa.h>
  92. #include <openssl/err.h>
  93. #include <openssl/evp.h>
  94. #include <openssl/opensslv.h>
  95. #include <openssl/pem.h>
  96. #include <openssl/rand.h>
  97. #ifndef NO_RSA
  98. # include <openssl/rsa.h>
  99. #endif
  100. #include <openssl/ssl.h>
  101. #include <openssl/x509.h>
  102. #include <openssl/x509_vfy.h>
  103. #if OPENSSL_VERSION_NUMBER < 0x00904000L /* 0.9.4-dev */
  104. # error "This program needs OpenSSL 0.9.4 or later."
  105. #endif
  106. #include "easy-tls.h" /* include after <openssl/ssl.h> if both are
  107. * needed */
  108. #if TLS_INFO_SIZE > PIPE_BUF
  109. # if PIPE_BUF < 512
  110. # error "PIPE_BUF < 512" /* non-POSIX */
  111. # endif
  112. # error "TLS_INFO_SIZE > PIPE_BUF"
  113. #endif
  114. /*****************************************************************************/
  115. #ifdef TLS_APP
  116. # include TLS_APP
  117. #endif
  118. /*-
  119. * Applications can define:
  120. * TLS_APP_PROCESS_INIT -- void ...(int fd, int client_p, void *apparg)
  121. * TLS_CUMULATE_ERRORS
  122. * TLS_ERROR_BUFSIZ
  123. * TLS_APP_ERRFLUSH -- void ...(int child_p, char *, size_t, void *apparg)
  124. */
  125. #ifndef TLS_APP_PROCESS_INIT
  126. # define TLS_APP_PROCESS_INIT(fd, client_p, apparg) ((void) 0)
  127. #endif
  128. #ifndef TLS_ERROR_BUFSIZ
  129. # define TLS_ERROR_BUFSIZ (10*160)
  130. #endif
  131. #if TLS_ERROR_BUFSIZ < 2 /* {'\n',0} */
  132. # error "TLS_ERROR_BUFSIZE is too small."
  133. #endif
  134. #ifndef TLS_APP_ERRFLUSH
  135. # define TLS_APP_ERRFLUSH tls_app_errflush
  136. static void
  137. tls_app_errflush(int child_p, char *errbuf, size_t num, void *apparg)
  138. {
  139. fputs(errbuf, stderr);
  140. }
  141. #endif
  142. /*****************************************************************************/
  143. #ifdef DEBUG_TLS
  144. # define DEBUG_MSG(x) fprintf(stderr," %s\n",x)
  145. # define DEBUG_MSG2(x,y) fprintf(stderr, " %s: %d\n",x,y)
  146. static int tls_loop_count = 0;
  147. static int tls_select_count = 0;
  148. #else
  149. # define DEBUG_MSG(x) (void)0
  150. # define DEBUG_MSG2(x,y) (void)0
  151. #endif
  152. static void tls_rand_seed_uniquely(void);
  153. static void tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx,
  154. int client_p);
  155. static int tls_socket_nonblocking(int fd);
  156. static int tls_child_p = 0;
  157. static void *tls_child_apparg;
  158. struct tls_start_proxy_args tls_start_proxy_defaultargs(void)
  159. {
  160. struct tls_start_proxy_args ret;
  161. ret.fd = -1;
  162. ret.client_p = -1;
  163. ret.ctx = NULL;
  164. ret.pid = NULL;
  165. ret.infofd = NULL;
  166. return ret;
  167. }
  168. /*-
  169. * Slice in TLS proxy process at fd.
  170. * Return value:
  171. * 0 ok (*pid is set to child's PID if pid != NULL),
  172. * < 0 look at errno
  173. * > 0 other error
  174. * (return value encodes place of error)
  175. *
  176. */
  177. int tls_start_proxy(struct tls_start_proxy_args a, void *apparg)
  178. {
  179. int fds[2] = { -1, -1 };
  180. int infofds[2] = { -1, -1 };
  181. int r, getfd, getfl;
  182. int ret;
  183. DEBUG_MSG2("tls_start_proxy fd", a.fd);
  184. DEBUG_MSG2("tls_start_proxy client_p", a.client_p);
  185. if (a.fd == -1 || a.client_p == -1 || a.ctx == NULL)
  186. return 1;
  187. if (a.pid != NULL) {
  188. *a.pid = 0;
  189. }
  190. if (a.infofd != NULL) {
  191. *a.infofd = -1;
  192. }
  193. r = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
  194. if (r == -1)
  195. return -1;
  196. if (a.fd >= FD_SETSIZE || fds[0] >= FD_SETSIZE) {
  197. ret = 2;
  198. goto err;
  199. }
  200. if (a.infofd != NULL) {
  201. r = pipe(infofds);
  202. if (r == -1) {
  203. ret = -3;
  204. goto err;
  205. }
  206. }
  207. r = fork();
  208. if (r == -1) {
  209. ret = -4;
  210. goto err;
  211. }
  212. if (r == 0) {
  213. DEBUG_MSG("fork");
  214. tls_child_p = 1;
  215. tls_child_apparg = apparg;
  216. close(fds[1]);
  217. if (infofds[0] != -1)
  218. close(infofds[0]);
  219. TLS_APP_PROCESS_INIT(a.fd, a.client_p, apparg);
  220. DEBUG_MSG("TLS_APP_PROCESS_INIT");
  221. tls_proxy(fds[0], a.fd, infofds[1], a.ctx, a.client_p);
  222. exit(0);
  223. }
  224. if (a.pid != NULL)
  225. *a.pid = r;
  226. if (infofds[1] != -1) {
  227. close(infofds[1]);
  228. infofds[1] = -1;
  229. }
  230. /* install fds[1] in place of fd: */
  231. close(fds[0]);
  232. fds[0] = -1;
  233. getfd = fcntl(a.fd, F_GETFD);
  234. getfl = fcntl(a.fd, F_GETFL);
  235. r = dup2(fds[1], a.fd);
  236. close(fds[1]);
  237. fds[1] = -1;
  238. if (r == -1) {
  239. ret = -5;
  240. goto err;
  241. }
  242. if (getfd != 1)
  243. fcntl(a.fd, F_SETFD, getfd);
  244. if (getfl & O_NONBLOCK)
  245. (void)tls_socket_nonblocking(a.fd);
  246. if (a.infofd != NULL)
  247. *a.infofd = infofds[0];
  248. return 0;
  249. err:
  250. if (fds[0] != -1)
  251. close(fds[0]);
  252. if (fds[1] != -1)
  253. close(fds[1]);
  254. if (infofds[0] != -1)
  255. close(infofds[0]);
  256. if (infofds[1] != -1)
  257. close(infofds[1]);
  258. return ret;
  259. }
  260. /*****************************************************************************/
  261. static char errbuf[TLS_ERROR_BUFSIZ];
  262. static size_t errbuf_i = 0;
  263. static void tls_errflush(void *apparg)
  264. {
  265. if (errbuf_i == 0)
  266. return;
  267. assert(errbuf_i < sizeof errbuf);
  268. assert(errbuf[errbuf_i] == 0);
  269. if (errbuf_i == sizeof errbuf - 1) {
  270. /* make sure we have a newline, even if string has been truncated */
  271. errbuf[errbuf_i - 1] = '\n';
  272. }
  273. /*
  274. * TLS_APP_ERRFLUSH may modify the string as needed, e.g. substitute
  275. * other characters for \n for convenience
  276. */
  277. TLS_APP_ERRFLUSH(tls_child_p, errbuf, errbuf_i, apparg);
  278. errbuf_i = 0;
  279. }
  280. static void tls_errprintf(int flush, void *apparg, const char *fmt, ...)
  281. {
  282. va_list args;
  283. int r;
  284. if (errbuf_i < sizeof errbuf - 1) {
  285. size_t n;
  286. va_start(args, fmt);
  287. n = (sizeof errbuf) - errbuf_i;
  288. r = vsnprintf(errbuf + errbuf_i, n, fmt, args);
  289. if (r >= n)
  290. r = n - 1;
  291. if (r >= 0) {
  292. errbuf_i += r;
  293. } else {
  294. errbuf_i = sizeof errbuf - 1;
  295. errbuf[errbuf_i] = '\0';
  296. }
  297. assert(errbuf_i < sizeof errbuf);
  298. assert(errbuf[errbuf_i] == 0);
  299. }
  300. #ifndef TLS_CUMULATE_ERRORS
  301. tls_errflush(apparg);
  302. #else
  303. if (flush)
  304. tls_errflush(apparg);
  305. #endif
  306. }
  307. /*
  308. * app_prefix.. are for additional information provided by caller. If OpenSSL
  309. * error queue is empty, print default_text ("???" if NULL).
  310. */
  311. static char *tls_openssl_errors(const char *app_prefix_1,
  312. const char *app_prefix_2,
  313. const char *default_text, void *apparg)
  314. {
  315. static char reasons[255];
  316. size_t reasons_i;
  317. unsigned long err;
  318. const char *file;
  319. int line;
  320. const char *data;
  321. int flags;
  322. char *errstring;
  323. int printed_something = 0;
  324. reasons_i = 0;
  325. assert(app_prefix_1 != NULL);
  326. assert(app_prefix_2 != NULL);
  327. if (default_text == NULL)
  328. default_text = "?" "?" "?";
  329. while ((err = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
  330. if (reasons_i < sizeof reasons) {
  331. size_t n;
  332. int r;
  333. n = (sizeof reasons) - reasons_i;
  334. r = snprintf(reasons + reasons_i, n, "%s%s",
  335. (reasons_i > 0 ? ", " : ""),
  336. ERR_reason_error_string(err));
  337. if (r >= n)
  338. r = n - 1;
  339. if (r >= 0) {
  340. reasons_i += r;
  341. } else {
  342. reasons_i = sizeof reasons;
  343. }
  344. assert(reasons_i <= sizeof reasons);
  345. }
  346. errstring = ERR_error_string(err, NULL);
  347. assert(errstring != NULL);
  348. tls_errprintf(0, apparg, "OpenSSL error%s%s: %s:%s:%d:%s\n",
  349. app_prefix_1, app_prefix_2, errstring, file, line,
  350. (flags & ERR_TXT_STRING) ? data : "");
  351. printed_something = 1;
  352. }
  353. if (!printed_something) {
  354. assert(reasons_i == 0);
  355. snprintf(reasons, sizeof reasons, "%s", default_text);
  356. tls_errprintf(0, apparg, "OpenSSL error%s%s: %s\n", app_prefix_1,
  357. app_prefix_2, default_text);
  358. }
  359. #ifdef TLS_CUMULATE_ERRORS
  360. tls_errflush(apparg);
  361. #endif
  362. assert(errbuf_i == 0);
  363. return reasons;
  364. }
  365. /*****************************************************************************/
  366. static int tls_init_done = 0;
  367. static int tls_init(void *apparg)
  368. {
  369. if (tls_init_done)
  370. return 0;
  371. SSL_load_error_strings();
  372. if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) {
  373. tls_errprintf(1, apparg, "SSL_library_init failed.\n");
  374. return -1;
  375. }
  376. tls_init_done = 1;
  377. tls_rand_seed();
  378. return 0;
  379. }
  380. /*****************************************************************************/
  381. static void tls_rand_seed_uniquely(void)
  382. {
  383. struct {
  384. pid_t pid;
  385. time_t time;
  386. void *stack;
  387. } data;
  388. data.pid = getpid();
  389. data.time = time(NULL);
  390. data.stack = (void *)&data;
  391. RAND_seed((const void *)&data, sizeof data);
  392. }
  393. void tls_rand_seed(void)
  394. {
  395. struct {
  396. struct utsname uname;
  397. int uname_1;
  398. int uname_2;
  399. uid_t uid;
  400. uid_t euid;
  401. gid_t gid;
  402. gid_t egid;
  403. } data;
  404. data.uname_1 = uname(&data.uname);
  405. data.uname_2 = errno; /* Let's hope that uname fails randomly :-) */
  406. data.uid = getuid();
  407. data.euid = geteuid();
  408. data.gid = getgid();
  409. data.egid = getegid();
  410. RAND_seed((const void *)&data, sizeof data);
  411. tls_rand_seed_uniquely();
  412. }
  413. static int tls_rand_seeded_p = 0;
  414. #define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */
  415. int tls_rand_seed_from_file(const char *filename, size_t n, void *apparg)
  416. {
  417. /*
  418. * Seed OpenSSL's random number generator from file. Try to read n bytes
  419. * if n > 0, whole file if n == 0.
  420. */
  421. int r;
  422. if (tls_init(apparg) == -1)
  423. return -1;
  424. tls_rand_seed();
  425. r = RAND_load_file(filename,
  426. (n > 0 && n < LONG_MAX) ? (long)n : LONG_MAX);
  427. /*
  428. * r is the number of bytes filled into the random number generator,
  429. * which are taken from "stat(filename, ...)" in addition to the file
  430. * contents.
  431. */
  432. assert(1 < my_MIN_SEED_BYTES);
  433. /*
  434. * We need to detect at least those cases when the file does not exist at
  435. * all. With current versions of OpenSSL, this should do it:
  436. */
  437. if (n == 0)
  438. n = my_MIN_SEED_BYTES;
  439. if (r < n) {
  440. tls_errprintf(1, apparg,
  441. "rand_seed_from_file: could not read %d bytes from %s.\n",
  442. n, filename);
  443. return -1;
  444. } else {
  445. tls_rand_seeded_p = 1;
  446. return 0;
  447. }
  448. }
  449. void tls_rand_seed_from_memory(const void *buf, size_t n)
  450. {
  451. size_t i = 0;
  452. while (i < n) {
  453. size_t rest = n - i;
  454. int chunk = rest < INT_MAX ? (int)rest : INT_MAX;
  455. RAND_seed((const char *)buf + i, chunk);
  456. i += chunk;
  457. }
  458. tls_rand_seeded_p = 1;
  459. }
  460. /*****************************************************************************/
  461. struct tls_x509_name_string {
  462. char str[100];
  463. };
  464. static void
  465. tls_get_x509_subject_name_oneline(X509 *cert,
  466. struct tls_x509_name_string *namestring)
  467. {
  468. X509_NAME *name;
  469. if (cert == NULL) {
  470. namestring->str[0] = '\0';
  471. return;
  472. }
  473. name = X509_get_subject_name(cert); /* does not increment any reference
  474. * counter */
  475. assert(sizeof namestring->str >= 4); /* "?" or "...", plus 0 */
  476. if (name == NULL) {
  477. namestring->str[0] = '?';
  478. namestring->str[1] = 0;
  479. } else {
  480. size_t len;
  481. X509_NAME_oneline(name, namestring->str, sizeof namestring->str);
  482. len = strlen(namestring->str);
  483. assert(namestring->str[len] == 0);
  484. assert(len < sizeof namestring->str);
  485. if (len + 1 == sizeof namestring->str) {
  486. /*
  487. * (Probably something was cut off.) Does not really work --
  488. * X509_NAME_oneline truncates after name components, we cannot
  489. * tell from the result whether anything is missing.
  490. */
  491. assert(namestring->str[len] == 0);
  492. namestring->str[--len] = '.';
  493. namestring->str[--len] = '.';
  494. namestring->str[--len] = '.';
  495. }
  496. }
  497. }
  498. /*****************************************************************************/
  499. /* to hinder OpenSSL from asking for passphrases */
  500. static int no_passphrase_callback(char *buf, int num, int w, void *arg)
  501. {
  502. return -1;
  503. }
  504. #if OPENSSL_VERSION_NUMBER >= 0x00907000L
  505. static int verify_dont_fail_cb(X509_STORE_CTX *c, void *unused_arg)
  506. #else
  507. static int verify_dont_fail_cb(X509_STORE_CTX *c)
  508. #endif
  509. {
  510. int i;
  511. i = X509_verify_cert(c); /* sets c->error */
  512. #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
  513. * certificates -- they could
  514. * survive session reuse, but
  515. * OpenSSL < 0.9.5-dev does not
  516. * preserve their verify_result */
  517. if (i == 0)
  518. return 1;
  519. else
  520. #endif
  521. return i;
  522. }
  523. static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it
  524. * just once */
  525. void tls_set_dhe1024(int i, void *apparg)
  526. {
  527. DSA *dsaparams;
  528. DH *dhparams;
  529. const char *seed[] = { ";-) :-( :-) :-( ",
  530. ";-) :-( :-) :-( ",
  531. "Random String no. 12",
  532. ";-) :-( :-) :-( ",
  533. "hackers have even mo", /* from jargon file */
  534. };
  535. unsigned char seedbuf[20];
  536. tls_init(apparg);
  537. if (i >= 0) {
  538. i %= sizeof seed / sizeof seed[0];
  539. assert(strlen(seed[i]) == 20);
  540. memcpy(seedbuf, seed[i], 20);
  541. dsaparams =
  542. DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL);
  543. } else {
  544. /* random parameters (may take a while) */
  545. dsaparams =
  546. DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL);
  547. }
  548. if (dsaparams == NULL) {
  549. tls_openssl_errors("", "", NULL, apparg);
  550. return;
  551. }
  552. dhparams = DSA_dup_DH(dsaparams);
  553. DSA_free(dsaparams);
  554. if (dhparams == NULL) {
  555. tls_openssl_errors("", "", NULL, apparg);
  556. return;
  557. }
  558. if (tls_dhe1024 != NULL)
  559. DH_free(tls_dhe1024);
  560. tls_dhe1024 = dhparams;
  561. }
  562. struct tls_create_ctx_args tls_create_ctx_defaultargs(void)
  563. {
  564. struct tls_create_ctx_args ret;
  565. ret.client_p = 0;
  566. ret.certificate_file = NULL;
  567. ret.key_file = NULL;
  568. ret.ca_file = NULL;
  569. ret.verify_depth = -1;
  570. ret.fail_unless_verified = 0;
  571. ret.export_p = 0;
  572. return ret;
  573. }
  574. SSL_CTX *tls_create_ctx(struct tls_create_ctx_args a, void *apparg)
  575. {
  576. int r;
  577. static long context_num = 0;
  578. SSL_CTX *ret;
  579. const char *err_pref_1 = "", *err_pref_2 = "";
  580. if (tls_init(apparg) == -1)
  581. return NULL;
  582. ret =
  583. SSL_CTX_new((a.client_p ? SSLv23_client_method :
  584. SSLv23_server_method) ());
  585. if (ret == NULL)
  586. goto err;
  587. SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback);
  588. SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE);
  589. if ((a.certificate_file != NULL) || (a.key_file != NULL)) {
  590. if (a.key_file == NULL) {
  591. tls_errprintf(1, apparg, "Need a key file.\n");
  592. goto err_return;
  593. }
  594. if (a.certificate_file == NULL) {
  595. tls_errprintf(1, apparg, "Need a certificate chain file.\n");
  596. goto err_return;
  597. }
  598. if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM))
  599. goto err;
  600. if (!tls_rand_seeded_p) {
  601. /*
  602. * particularly paranoid people may not like this -- so provide
  603. * your own random seeding before calling this
  604. */
  605. if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1)
  606. goto err_return;
  607. }
  608. if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file))
  609. goto err;
  610. if (!SSL_CTX_check_private_key(ret)) {
  611. tls_errprintf(1, apparg,
  612. "Private key \"%s\" does not match certificate \"%s\".\n",
  613. a.key_file, a.certificate_file);
  614. goto err_peek;
  615. }
  616. }
  617. if ((a.ca_file != NULL) || (a.verify_depth > 0)) {
  618. context_num++;
  619. r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num,
  620. (unsigned int)sizeof context_num);
  621. if (!r)
  622. goto err;
  623. SSL_CTX_set_verify(ret,
  624. SSL_VERIFY_PEER | (a.fail_unless_verified ?
  625. SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  626. : 0), 0);
  627. if (!a.fail_unless_verified)
  628. SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL);
  629. if (a.verify_depth > 0)
  630. SSL_CTX_set_verify_depth(ret, a.verify_depth);
  631. if (a.ca_file != NULL) {
  632. /* does not report failure if file does not exist ... */
  633. /* NULL argument means no CA-directory */
  634. r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL);
  635. if (!r) {
  636. err_pref_1 = " while processing certificate file ";
  637. err_pref_2 = a.ca_file;
  638. goto err;
  639. }
  640. if (!a.client_p) {
  641. /*
  642. * SSL_load_client_CA_file is a misnomer, it just creates a
  643. * list of CNs.
  644. */
  645. SSL_CTX_set_client_CA_list(ret,
  646. SSL_load_client_CA_file
  647. (a.ca_file));
  648. /*
  649. * SSL_CTX_set_client_CA_list does not have a return value;
  650. * it does not really need one, but make sure (we really test
  651. * if SSL_load_client_CA_file worked)
  652. */
  653. if (SSL_CTX_get_client_CA_list(ret) == NULL) {
  654. tls_errprintf(1, apparg,
  655. "Could not set client CA list from \"%s\".\n",
  656. a.ca_file);
  657. goto err_peek;
  658. }
  659. }
  660. }
  661. }
  662. if (!a.client_p) {
  663. if (tls_dhe1024 == NULL) {
  664. int i;
  665. RAND_bytes((unsigned char *)&i, sizeof i);
  666. /*
  667. * make sure that i is non-negative -- pick one of the provided
  668. * seeds
  669. */
  670. if (i < 0)
  671. i = -i;
  672. if (i < 0)
  673. i = 0;
  674. tls_set_dhe1024(i, apparg);
  675. if (tls_dhe1024 == NULL)
  676. goto err_return;
  677. }
  678. if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
  679. goto err;
  680. /* avoid small subgroup attacks: */
  681. SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
  682. }
  683. #ifndef NO_RSA
  684. if (!a.client_p && a.export_p) {
  685. RSA *tmpkey;
  686. tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
  687. if (tmpkey == NULL)
  688. goto err;
  689. if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
  690. RSA_free(tmpkey);
  691. goto err;
  692. }
  693. RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
  694. }
  695. #endif
  696. return ret;
  697. err_peek:
  698. if (!ERR_peek_error())
  699. goto err_return;
  700. err:
  701. tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
  702. err_return:
  703. if (ret != NULL)
  704. SSL_CTX_free(ret);
  705. return NULL;
  706. }
  707. /*****************************************************************************/
  708. static int tls_socket_nonblocking(int fd)
  709. {
  710. int v, r;
  711. v = fcntl(fd, F_GETFL, 0);
  712. if (v == -1) {
  713. if (errno == EINVAL)
  714. return 0; /* already shut down -- ignore */
  715. return -1;
  716. }
  717. r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
  718. if (r == -1) {
  719. if (errno == EINVAL)
  720. return 0; /* already shut down -- ignore */
  721. return -1;
  722. }
  723. return 0;
  724. }
  725. static int max(int a, int b)
  726. {
  727. return a > b ? a : b;
  728. }
  729. /* timeout, -1 means no timeout */
  730. static void
  731. tls_sockets_select(int read_select_1, int read_select_2, int write_select_1,
  732. int write_select_2, int seconds)
  733. {
  734. int maxfd, n;
  735. fd_set reads, writes;
  736. struct timeval timeout;
  737. struct timeval *timeout_p;
  738. assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1
  739. && write_select_2 >= -1);
  740. assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE - 1
  741. && write_select_1 < FD_SETSIZE - 1
  742. && write_select_2 < FD_SETSIZE - 1);
  743. maxfd =
  744. max(max(read_select_1, read_select_2),
  745. max(write_select_1, write_select_2));
  746. assert(maxfd >= 0);
  747. FD_ZERO(&reads);
  748. FD_ZERO(&writes);
  749. for (n = 0; n < 4; ++n) {
  750. int i = n % 2;
  751. int w = n >= 2;
  752. /* loop over all (i, w) in {0,1}x{0,1} */
  753. int fd;
  754. if (i == 0 && w == 0)
  755. fd = read_select_1;
  756. else if (i == 1 && w == 0)
  757. fd = read_select_2;
  758. else if (i == 0 && w == 1)
  759. fd = write_select_1;
  760. else {
  761. assert(i == 1 && w == 1);
  762. fd = write_select_2;
  763. }
  764. if (fd >= 0) {
  765. if (w == 0)
  766. FD_SET(fd, &reads);
  767. else /* w == 1 */
  768. FD_SET(fd, &writes);
  769. }
  770. }
  771. if (seconds >= 0) {
  772. timeout.tv_sec = seconds;
  773. timeout.tv_usec = 0;
  774. timeout_p = &timeout;
  775. } else
  776. timeout_p = NULL;
  777. DEBUG_MSG2("select no.", ++tls_select_count);
  778. select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
  779. DEBUG_MSG("cont.");
  780. }
  781. /*****************************************************************************/
  782. #define TUNNELBUFSIZE (16*1024)
  783. struct tunnelbuf {
  784. char buf[TUNNELBUFSIZE];
  785. size_t len;
  786. size_t offset;
  787. };
  788. static int tls_connect_attempt(SSL *, int *write_select, int *read_select,
  789. int *closed, int *progress,
  790. const char **err_pref);
  791. static int tls_accept_attempt(SSL *, int *write_select, int *read_select,
  792. int *closed, int *progress,
  793. const char **err_pref);
  794. static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select,
  795. int *read_select, int *closed, int *progress,
  796. const char **err_pref);
  797. static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select,
  798. int *read_select, int *closed, int *progress,
  799. const char **err_pref);
  800. static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed,
  801. int *progress);
  802. static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed,
  803. int *progress);
  804. static void write_info(SSL *ssl, int *info_fd)
  805. {
  806. if (*info_fd != -1) {
  807. long v;
  808. int v_ok;
  809. struct tls_x509_name_string peer;
  810. char infobuf[TLS_INFO_SIZE];
  811. int r;
  812. DEBUG_MSG("write_info");
  813. v = SSL_get_verify_result(ssl);
  814. v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
  815. {
  816. X509 *peercert;
  817. peercert = SSL_get_peer_certificate(ssl);
  818. tls_get_x509_subject_name_oneline(peercert, &peer);
  819. if (peercert != NULL)
  820. X509_free(peercert);
  821. }
  822. if (peer.str[0] == '\0')
  823. v_ok = '0'; /* no cert at all */
  824. else if (strchr(peer.str, '\n')) {
  825. /* should not happen, but make sure */
  826. *strchr(peer.str, '\n') = '\0';
  827. }
  828. r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok,
  829. X509_verify_cert_error_string(v), peer.str);
  830. DEBUG_MSG2("snprintf", r);
  831. if (r == -1 || r >= sizeof infobuf)
  832. r = sizeof infobuf - 1;
  833. write(*info_fd, infobuf, r);
  834. close(*info_fd);
  835. *info_fd = -1;
  836. }
  837. }
  838. /* tls_proxy expects that all fds are closed after return */
  839. static void
  840. tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
  841. {
  842. struct tunnelbuf clear_to_tls, tls_to_clear;
  843. SSL *ssl;
  844. BIO *rbio, *wbio;
  845. int closed, in_handshake;
  846. const char *err_pref_1 = "", *err_pref_2 = "";
  847. const char *err_def = NULL;
  848. assert(clear_fd != -1);
  849. assert(tls_fd != -1);
  850. assert(clear_fd < FD_SETSIZE);
  851. assert(tls_fd < FD_SETSIZE);
  852. /* info_fd may be -1 */
  853. assert(ctx != NULL);
  854. tls_rand_seed_uniquely();
  855. tls_socket_nonblocking(clear_fd);
  856. DEBUG_MSG2("clear_fd", clear_fd);
  857. tls_socket_nonblocking(tls_fd);
  858. DEBUG_MSG2("tls_fd", tls_fd);
  859. ssl = SSL_new(ctx);
  860. if (ssl == NULL)
  861. goto err;
  862. DEBUG_MSG("SSL_new");
  863. if (!SSL_set_fd(ssl, tls_fd))
  864. goto err;
  865. rbio = SSL_get_rbio(ssl);
  866. wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
  867. assert(rbio != NULL);
  868. assert(wbio != NULL);
  869. if (client_p)
  870. SSL_set_connect_state(ssl);
  871. else
  872. SSL_set_accept_state(ssl);
  873. closed = 0;
  874. in_handshake = 1;
  875. tls_to_clear.len = 0;
  876. tls_to_clear.offset = 0;
  877. clear_to_tls.len = 0;
  878. clear_to_tls.offset = 0;
  879. err_def = "I/O error";
  880. /*
  881. * loop finishes as soon as we detect that one side closed; when all
  882. * (program and OS) buffers have enough space, the data from the last
  883. * succesful read in each direction is transferred before close
  884. */
  885. do {
  886. int clear_read_select = 0, clear_write_select = 0,
  887. tls_read_select = 0, tls_write_select = 0, progress = 0;
  888. int r;
  889. unsigned long num_read = BIO_number_read(rbio),
  890. num_written = BIO_number_written(wbio);
  891. DEBUG_MSG2("loop iteration", ++tls_loop_count);
  892. if (in_handshake) {
  893. DEBUG_MSG("in_handshake");
  894. if (client_p)
  895. r = tls_connect_attempt(ssl, &tls_write_select,
  896. &tls_read_select, &closed, &progress,
  897. &err_pref_1);
  898. else
  899. r = tls_accept_attempt(ssl, &tls_write_select,
  900. &tls_read_select, &closed, &progress,
  901. &err_pref_1);
  902. if (r != 0) {
  903. write_info(ssl, &info_fd);
  904. goto err;
  905. }
  906. if (closed)
  907. goto err_return;
  908. if (!SSL_in_init(ssl)) {
  909. in_handshake = 0;
  910. write_info(ssl, &info_fd);
  911. }
  912. }
  913. if (clear_to_tls.len != 0 && !in_handshake) {
  914. assert(!closed);
  915. r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select,
  916. &tls_read_select, &closed, &progress,
  917. &err_pref_1);
  918. if (r != 0)
  919. goto err;
  920. if (closed) {
  921. assert(progress);
  922. tls_to_clear.offset = 0;
  923. tls_to_clear.len = 0;
  924. }
  925. }
  926. if (tls_to_clear.len != 0) {
  927. assert(!closed);
  928. r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select,
  929. &closed, &progress);
  930. if (r != 0)
  931. goto err_return;
  932. if (closed) {
  933. assert(progress);
  934. clear_to_tls.offset = 0;
  935. clear_to_tls.len = 0;
  936. }
  937. }
  938. if (!closed) {
  939. if (clear_to_tls.offset + clear_to_tls.len <
  940. sizeof clear_to_tls.buf) {
  941. r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select,
  942. &closed, &progress);
  943. if (r != 0)
  944. goto err_return;
  945. if (closed) {
  946. r = SSL_shutdown(ssl);
  947. DEBUG_MSG2("SSL_shutdown", r);
  948. }
  949. }
  950. }
  951. if (!closed && !in_handshake) {
  952. if (tls_to_clear.offset + tls_to_clear.len <
  953. sizeof tls_to_clear.buf) {
  954. r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select,
  955. &tls_read_select, &closed, &progress,
  956. &err_pref_1);
  957. if (r != 0)
  958. goto err;
  959. if (closed) {
  960. r = SSL_shutdown(ssl);
  961. DEBUG_MSG2("SSL_shutdown", r);
  962. }
  963. }
  964. }
  965. if (!progress) {
  966. DEBUG_MSG("!progress?");
  967. if (num_read != BIO_number_read(rbio)
  968. || num_written != BIO_number_written(wbio))
  969. progress = 1;
  970. if (!progress) {
  971. DEBUG_MSG("!progress");
  972. assert(clear_read_select || tls_read_select
  973. || clear_write_select || tls_write_select);
  974. tls_sockets_select(clear_read_select ? clear_fd : -1,
  975. tls_read_select ? tls_fd : -1,
  976. clear_write_select ? clear_fd : -1,
  977. tls_write_select ? tls_fd : -1, -1);
  978. }
  979. }
  980. } while (!closed);
  981. return;
  982. err:
  983. tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
  984. err_return:
  985. return;
  986. }
  987. static int
  988. tls_get_error(SSL *ssl, int r, int *write_select, int *read_select,
  989. int *closed, int *progress)
  990. {
  991. int err = SSL_get_error(ssl, r);
  992. if (err == SSL_ERROR_NONE) {
  993. assert(r > 0);
  994. *progress = 1;
  995. return 0;
  996. }
  997. assert(r <= 0);
  998. switch (err) {
  999. case SSL_ERROR_ZERO_RETURN:
  1000. assert(r == 0);
  1001. *closed = 1;
  1002. *progress = 1;
  1003. return 0;
  1004. case SSL_ERROR_WANT_WRITE:
  1005. *write_select = 1;
  1006. return 0;
  1007. case SSL_ERROR_WANT_READ:
  1008. *read_select = 1;
  1009. return 0;
  1010. }
  1011. return -1;
  1012. }
  1013. static int
  1014. tls_connect_attempt(SSL *ssl, int *write_select, int *read_select,
  1015. int *closed, int *progress, const char **err_pref)
  1016. {
  1017. int n, r;
  1018. DEBUG_MSG("tls_connect_attempt");
  1019. n = SSL_connect(ssl);
  1020. DEBUG_MSG2("SSL_connect", n);
  1021. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1022. if (r == -1)
  1023. *err_pref = " during SSL_connect";
  1024. return r;
  1025. }
  1026. static int
  1027. tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed,
  1028. int *progress, const char **err_pref)
  1029. {
  1030. int n, r;
  1031. DEBUG_MSG("tls_accept_attempt");
  1032. n = SSL_accept(ssl);
  1033. DEBUG_MSG2("SSL_accept", n);
  1034. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1035. if (r == -1)
  1036. *err_pref = " during SSL_accept";
  1037. return r;
  1038. }
  1039. static int
  1040. tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select,
  1041. int *read_select, int *closed, int *progress,
  1042. const char **err_pref)
  1043. {
  1044. int n, r;
  1045. DEBUG_MSG("tls_write_attempt");
  1046. n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
  1047. DEBUG_MSG2("SSL_write", n);
  1048. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1049. if (n > 0) {
  1050. buf->len -= n;
  1051. assert(buf->len >= 0);
  1052. if (buf->len == 0)
  1053. buf->offset = 0;
  1054. else
  1055. buf->offset += n;
  1056. }
  1057. if (r == -1)
  1058. *err_pref = " during SSL_write";
  1059. return r;
  1060. }
  1061. static int
  1062. tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select,
  1063. int *read_select, int *closed, int *progress,
  1064. const char **err_pref)
  1065. {
  1066. int n, r;
  1067. size_t total;
  1068. DEBUG_MSG("tls_read_attempt");
  1069. total = buf->offset + buf->len;
  1070. assert(total < sizeof buf->buf);
  1071. n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
  1072. DEBUG_MSG2("SSL_read", n);
  1073. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1074. if (n > 0) {
  1075. buf->len += n;
  1076. assert(buf->offset + buf->len <= sizeof buf->buf);
  1077. }
  1078. if (r == -1)
  1079. *err_pref = " during SSL_read";
  1080. return r;
  1081. }
  1082. static int get_error(int r, int *select, int *closed, int *progress)
  1083. {
  1084. if (r >= 0) {
  1085. *progress = 1;
  1086. if (r == 0)
  1087. *closed = 1;
  1088. return 0;
  1089. } else {
  1090. assert(r == -1);
  1091. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1092. *select = 1;
  1093. return 0;
  1094. } else if (errno == EPIPE) {
  1095. *progress = 1;
  1096. *closed = 1;
  1097. return 0;
  1098. } else
  1099. return -1;
  1100. }
  1101. }
  1102. static int write_attempt(int fd, struct tunnelbuf *buf, int *select,
  1103. int *closed, int *progress)
  1104. {
  1105. int n, r;
  1106. DEBUG_MSG("write_attempt");
  1107. n = write(fd, buf->buf + buf->offset, buf->len);
  1108. DEBUG_MSG2("write", n);
  1109. r = get_error(n, select, closed, progress);
  1110. if (n > 0) {
  1111. buf->len -= n;
  1112. assert(buf->len >= 0);
  1113. if (buf->len == 0)
  1114. buf->offset = 0;
  1115. else
  1116. buf->offset += n;
  1117. }
  1118. if (r == -1)
  1119. tls_errprintf(1, tls_child_apparg, "write error: %s\n",
  1120. strerror(errno));
  1121. return r;
  1122. }
  1123. static int
  1124. read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed,
  1125. int *progress)
  1126. {
  1127. int n, r;
  1128. size_t total;
  1129. DEBUG_MSG("read_attempt");
  1130. total = buf->offset + buf->len;
  1131. assert(total < sizeof buf->buf);
  1132. n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
  1133. DEBUG_MSG2("read", n);
  1134. r = get_error(n, select, closed, progress);
  1135. if (n > 0) {
  1136. buf->len += n;
  1137. assert(buf->offset + buf->len <= sizeof buf->buf);
  1138. }
  1139. if (r == -1)
  1140. tls_errprintf(1, tls_child_apparg, "read error: %s\n",
  1141. strerror(errno));
  1142. return r;
  1143. }