easy-tls.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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 needed */
  107. #if TLS_INFO_SIZE > PIPE_BUF
  108. # if PIPE_BUF < 512
  109. # error "PIPE_BUF < 512" /* non-POSIX */
  110. # endif
  111. # error "TLS_INFO_SIZE > PIPE_BUF"
  112. #endif
  113. /*****************************************************************************/
  114. #ifdef TLS_APP
  115. # include TLS_APP
  116. #endif
  117. /* Applications can define:
  118. * TLS_APP_PROCESS_INIT -- void ...(int fd, int client_p, void *apparg)
  119. * TLS_CUMULATE_ERRORS
  120. * TLS_ERROR_BUFSIZ
  121. * TLS_APP_ERRFLUSH -- void ...(int child_p, char *, size_t, void *apparg)
  122. */
  123. #ifndef TLS_APP_PROCESS_INIT
  124. # define TLS_APP_PROCESS_INIT(fd, client_p, apparg) ((void) 0)
  125. #endif
  126. #ifndef TLS_ERROR_BUFSIZ
  127. # define TLS_ERROR_BUFSIZ (10*160)
  128. #endif
  129. #if TLS_ERROR_BUFSIZ < 2 /* {'\n',0} */
  130. # error "TLS_ERROR_BUFSIZE is too small."
  131. #endif
  132. #ifndef TLS_APP_ERRFLUSH
  133. # define TLS_APP_ERRFLUSH tls_app_errflush
  134. static void
  135. tls_app_errflush(int child_p, char *errbuf, size_t num, void *apparg)
  136. {
  137. fputs(errbuf, stderr);
  138. }
  139. #endif
  140. /*****************************************************************************/
  141. #ifdef DEBUG_TLS
  142. # define DEBUG_MSG(x) fprintf(stderr," %s\n",x)
  143. # define DEBUG_MSG2(x,y) fprintf(stderr, " %s: %d\n",x,y)
  144. static int tls_loop_count = 0;
  145. static int tls_select_count = 0;
  146. #else
  147. # define DEBUG_MSG(x) (void)0
  148. # define DEBUG_MSG2(x,y) (void)0
  149. #endif
  150. static void tls_rand_seed_uniquely(void);
  151. static void tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p);
  152. static int tls_socket_nonblocking(int fd);
  153. static int tls_child_p = 0;
  154. static void *tls_child_apparg;
  155. struct tls_start_proxy_args
  156. tls_start_proxy_defaultargs(void)
  157. {
  158. struct tls_start_proxy_args ret;
  159. ret.fd = -1;
  160. ret.client_p = -1;
  161. ret.ctx = NULL;
  162. ret.pid = NULL;
  163. ret.infofd = NULL;
  164. return ret;
  165. }
  166. /* Slice in TLS proxy process at fd.
  167. * Return value:
  168. * 0 ok (*pid is set to child's PID if pid != NULL),
  169. * < 0 look at errno
  170. * > 0 other error
  171. * (return value encodes place of error)
  172. *
  173. */
  174. int
  175. tls_start_proxy(struct tls_start_proxy_args a, void *apparg)
  176. {
  177. int fds[2] = {-1, -1};
  178. int infofds[2] = {-1, -1};
  179. int r, getfd, getfl;
  180. int ret;
  181. DEBUG_MSG2("tls_start_proxy fd", a.fd);
  182. DEBUG_MSG2("tls_start_proxy client_p", a.client_p);
  183. if (a.fd == -1 || a.client_p == -1 || a.ctx == NULL)
  184. return 1;
  185. if (a.pid != NULL) {
  186. *a.pid = 0;
  187. }
  188. if (a.infofd != NULL) {
  189. *a.infofd = -1;
  190. }
  191. r = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
  192. if (r == -1)
  193. return -1;
  194. if (a.fd >= FD_SETSIZE || fds[0] >= FD_SETSIZE) {
  195. ret = 2;
  196. goto err;
  197. }
  198. if (a.infofd != NULL) {
  199. r = pipe(infofds);
  200. if (r == -1) {
  201. ret = -3;
  202. goto err;
  203. }
  204. }
  205. r = fork();
  206. if (r == -1) {
  207. ret = -4;
  208. goto err;
  209. }
  210. if (r == 0) {
  211. DEBUG_MSG("fork");
  212. tls_child_p = 1;
  213. tls_child_apparg = apparg;
  214. close(fds[1]);
  215. if (infofds[0] != -1)
  216. close(infofds[0]);
  217. TLS_APP_PROCESS_INIT(a.fd, a.client_p, apparg);
  218. DEBUG_MSG("TLS_APP_PROCESS_INIT");
  219. tls_proxy(fds[0], a.fd, infofds[1], a.ctx, a.client_p);
  220. exit(0);
  221. }
  222. if (a.pid != NULL)
  223. *a.pid = r;
  224. if (infofds[1] != -1) {
  225. close(infofds[1]);
  226. infofds[1] = -1;
  227. }
  228. /* install fds[1] in place of fd: */
  229. close(fds[0]);
  230. fds[0] = -1;
  231. getfd = fcntl(a.fd, F_GETFD);
  232. getfl = fcntl(a.fd, F_GETFL);
  233. r = dup2(fds[1], a.fd);
  234. close(fds[1]);
  235. fds[1] = -1;
  236. if (r == -1) {
  237. ret = -5;
  238. goto err;
  239. }
  240. if (getfd != 1)
  241. fcntl(a.fd, F_SETFD, getfd);
  242. if (getfl & O_NONBLOCK)
  243. (void)tls_socket_nonblocking(a.fd);
  244. if (a.infofd != NULL)
  245. *a.infofd = infofds[0];
  246. return 0;
  247. err:
  248. if (fds[0] != -1)
  249. close(fds[0]);
  250. if (fds[1] != -1)
  251. close(fds[1]);
  252. if (infofds[0] != -1)
  253. close(infofds[0]);
  254. if (infofds[1] != -1)
  255. close(infofds[1]);
  256. return ret;
  257. }
  258. /*****************************************************************************/
  259. static char errbuf[TLS_ERROR_BUFSIZ];
  260. static size_t errbuf_i = 0;
  261. static void
  262. tls_errflush(void *apparg)
  263. {
  264. if (errbuf_i == 0)
  265. return;
  266. assert(errbuf_i < sizeof errbuf);
  267. assert(errbuf[errbuf_i] == 0);
  268. if (errbuf_i == sizeof errbuf - 1) {
  269. /* make sure we have a newline, even if string has been truncated */
  270. errbuf[errbuf_i - 1] = '\n';
  271. }
  272. /* TLS_APP_ERRFLUSH may modify the string as needed,
  273. * e.g. substitute other characters for \n for convenience */
  274. TLS_APP_ERRFLUSH(tls_child_p, errbuf, errbuf_i, apparg);
  275. errbuf_i = 0;
  276. }
  277. static void
  278. tls_errprintf(int flush, void *apparg, const char *fmt, ...)
  279. {
  280. va_list args;
  281. int r;
  282. if (errbuf_i < sizeof errbuf - 1) {
  283. size_t n;
  284. va_start(args, fmt);
  285. n = (sizeof errbuf) - errbuf_i;
  286. r = vsnprintf(errbuf + errbuf_i, n, fmt, args);
  287. if (r >= n)
  288. r = n - 1;
  289. if (r >= 0) {
  290. errbuf_i += r;
  291. } else {
  292. errbuf_i = sizeof errbuf - 1;
  293. errbuf[errbuf_i] = '\0';
  294. }
  295. assert(errbuf_i < sizeof errbuf);
  296. assert(errbuf[errbuf_i] == 0);
  297. }
  298. #ifndef TLS_CUMULATE_ERRORS
  299. tls_errflush(apparg);
  300. #else
  301. if (flush)
  302. tls_errflush(apparg);
  303. #endif
  304. }
  305. /* app_prefix.. are for additional information provided by caller.
  306. * If OpenSSL error queue is empty, print default_text ("???" if NULL).
  307. */
  308. static char *
  309. tls_openssl_errors(const char *app_prefix_1, const char *app_prefix_2, const char *default_text, void *apparg)
  310. {
  311. static char reasons[255];
  312. size_t reasons_i;
  313. unsigned long err;
  314. const char *file;
  315. int line;
  316. const char *data;
  317. int flags;
  318. char *errstring;
  319. int printed_something = 0;
  320. reasons_i = 0;
  321. assert(app_prefix_1 != NULL);
  322. assert(app_prefix_2 != NULL);
  323. if (default_text == NULL)
  324. default_text = "?""?""?";
  325. while ((err = ERR_get_error_line_data(&file,&line,&data,&flags)) != 0) {
  326. if (reasons_i < sizeof reasons) {
  327. size_t n;
  328. int r;
  329. n = (sizeof reasons) - reasons_i;
  330. r = snprintf(reasons + reasons_i, n, "%s%s", (reasons_i > 0 ? ", " : ""), ERR_reason_error_string(err));
  331. if (r >= n)
  332. r = n - 1;
  333. if (r >= 0) {
  334. reasons_i += r;
  335. } else {
  336. reasons_i = sizeof reasons;
  337. }
  338. assert(reasons_i <= sizeof reasons);
  339. }
  340. errstring = ERR_error_string(err, NULL);
  341. assert(errstring != NULL);
  342. tls_errprintf(0, apparg, "OpenSSL error%s%s: %s:%s:%d:%s\n", app_prefix_1, app_prefix_2, errstring, file, line, (flags & ERR_TXT_STRING) ? data : "");
  343. printed_something = 1;
  344. }
  345. if (!printed_something) {
  346. assert(reasons_i == 0);
  347. snprintf(reasons, sizeof reasons, "%s", default_text);
  348. tls_errprintf(0, apparg, "OpenSSL error%s%s: %s\n", app_prefix_1, app_prefix_2, default_text);
  349. }
  350. #ifdef TLS_CUMULATE_ERRORS
  351. tls_errflush(apparg);
  352. #endif
  353. assert(errbuf_i == 0);
  354. return reasons;
  355. }
  356. /*****************************************************************************/
  357. static int tls_init_done = 0;
  358. static int
  359. tls_init(void *apparg)
  360. {
  361. if (tls_init_done)
  362. return 0;
  363. SSL_load_error_strings();
  364. if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) {
  365. tls_errprintf(1, apparg, "SSL_library_init failed.\n");
  366. return -1;
  367. }
  368. tls_init_done = 1;
  369. tls_rand_seed();
  370. return 0;
  371. }
  372. /*****************************************************************************/
  373. static void
  374. tls_rand_seed_uniquely(void)
  375. {
  376. struct {
  377. pid_t pid;
  378. time_t time;
  379. void *stack;
  380. } data;
  381. data.pid = getpid();
  382. data.time = time(NULL);
  383. data.stack = (void *)&data;
  384. RAND_seed((const void *)&data, sizeof data);
  385. }
  386. void
  387. tls_rand_seed(void)
  388. {
  389. struct {
  390. struct utsname uname;
  391. int uname_1;
  392. int uname_2;
  393. uid_t uid;
  394. uid_t euid;
  395. gid_t gid;
  396. gid_t egid;
  397. } data;
  398. data.uname_1 = uname(&data.uname);
  399. data.uname_2 = errno; /* Let's hope that uname fails randomly :-) */
  400. data.uid = getuid();
  401. data.euid = geteuid();
  402. data.gid = getgid();
  403. data.egid = getegid();
  404. RAND_seed((const void *)&data, sizeof data);
  405. tls_rand_seed_uniquely();
  406. }
  407. static int tls_rand_seeded_p = 0;
  408. #define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */
  409. int
  410. tls_rand_seed_from_file(const char *filename, size_t n, void *apparg)
  411. {
  412. /* Seed OpenSSL's random number generator from file.
  413. Try to read n bytes if n > 0, whole file if n == 0. */
  414. int r;
  415. if (tls_init(apparg) == -1)
  416. return -1;
  417. tls_rand_seed();
  418. r = RAND_load_file(filename, (n > 0 && n < LONG_MAX) ? (long)n : LONG_MAX);
  419. /* r is the number of bytes filled into the random number generator,
  420. * which are taken from "stat(filename, ...)" in addition to the
  421. * file contents.
  422. */
  423. assert(1 < my_MIN_SEED_BYTES);
  424. /* We need to detect at least those cases when the file does not exist
  425. * at all. With current versions of OpenSSL, this should do it: */
  426. if (n == 0)
  427. n = my_MIN_SEED_BYTES;
  428. if (r < n) {
  429. tls_errprintf(1, apparg, "rand_seed_from_file: could not read %d bytes from %s.\n", n, filename);
  430. return -1;
  431. } else {
  432. tls_rand_seeded_p = 1;
  433. return 0;
  434. }
  435. }
  436. void
  437. tls_rand_seed_from_memory(const void *buf, size_t n)
  438. {
  439. size_t i = 0;
  440. while (i < n) {
  441. size_t rest = n - i;
  442. int chunk = rest < INT_MAX ? (int)rest : INT_MAX;
  443. RAND_seed((const char *)buf + i, chunk);
  444. i += chunk;
  445. }
  446. tls_rand_seeded_p = 1;
  447. }
  448. /*****************************************************************************/
  449. struct tls_x509_name_string {
  450. char str[100];
  451. };
  452. static void
  453. tls_get_x509_subject_name_oneline(X509 *cert, struct tls_x509_name_string *namestring)
  454. {
  455. X509_NAME *name;
  456. if (cert == NULL) {
  457. namestring->str[0] = '\0';
  458. return;
  459. }
  460. name = X509_get_subject_name(cert); /* does not increment any reference counter */
  461. assert(sizeof namestring->str >= 4); /* "?" or "...", plus 0 */
  462. if (name == NULL) {
  463. namestring->str[0] = '?';
  464. namestring->str[1] = 0;
  465. } else {
  466. size_t len;
  467. X509_NAME_oneline(name, namestring->str, sizeof namestring->str);
  468. len = strlen(namestring->str);
  469. assert(namestring->str[len] == 0);
  470. assert(len < sizeof namestring->str);
  471. if (len+1 == sizeof namestring->str) {
  472. /* (Probably something was cut off.)
  473. * Does not really work -- X509_NAME_oneline truncates after
  474. * name components, we cannot tell from the result whether
  475. * anything is missing. */
  476. assert(namestring->str[len] == 0);
  477. namestring->str[--len] = '.';
  478. namestring->str[--len] = '.';
  479. namestring->str[--len] = '.';
  480. }
  481. }
  482. }
  483. /*****************************************************************************/
  484. /* to hinder OpenSSL from asking for passphrases */
  485. static int
  486. no_passphrase_callback(char *buf, int num, int w, void *arg)
  487. {
  488. return -1;
  489. }
  490. #if OPENSSL_VERSION_NUMBER >= 0x00907000L
  491. static int
  492. verify_dont_fail_cb(X509_STORE_CTX *c, void *unused_arg)
  493. #else
  494. static int
  495. verify_dont_fail_cb(X509_STORE_CTX *c)
  496. #endif
  497. {
  498. int i;
  499. i = X509_verify_cert(c); /* sets c->error */
  500. #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
  501. * certificates -- they could
  502. * survive session reuse, but
  503. * OpenSSL < 0.9.5-dev does not
  504. * preserve their verify_result */
  505. if (i == 0)
  506. return 1;
  507. else
  508. #endif
  509. return i;
  510. }
  511. static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it just once */
  512. void
  513. tls_set_dhe1024(int i, void *apparg)
  514. {
  515. DSA *dsaparams;
  516. DH *dhparams;
  517. const char *seed[] = { ";-) :-( :-) :-( ",
  518. ";-) :-( :-) :-( ",
  519. "Random String no. 12",
  520. ";-) :-( :-) :-( ",
  521. "hackers have even mo", /* from jargon file */
  522. };
  523. unsigned char seedbuf[20];
  524. tls_init(apparg);
  525. if (i >= 0) {
  526. i %= sizeof seed / sizeof seed[0];
  527. assert(strlen(seed[i]) == 20);
  528. memcpy(seedbuf, seed[i], 20);
  529. dsaparams = DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL);
  530. } else {
  531. /* random parameters (may take a while) */
  532. dsaparams = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL);
  533. }
  534. if (dsaparams == NULL) {
  535. tls_openssl_errors("", "", NULL, apparg);
  536. return;
  537. }
  538. dhparams = DSA_dup_DH(dsaparams);
  539. DSA_free(dsaparams);
  540. if (dhparams == NULL) {
  541. tls_openssl_errors("", "", NULL, apparg);
  542. return;
  543. }
  544. if (tls_dhe1024 != NULL)
  545. DH_free(tls_dhe1024);
  546. tls_dhe1024 = dhparams;
  547. }
  548. struct tls_create_ctx_args
  549. tls_create_ctx_defaultargs(void)
  550. {
  551. struct tls_create_ctx_args ret;
  552. ret.client_p = 0;
  553. ret.certificate_file = NULL;
  554. ret.key_file = NULL;
  555. ret.ca_file = NULL;
  556. ret.verify_depth = -1;
  557. ret.fail_unless_verified = 0;
  558. ret.export_p = 0;
  559. return ret;
  560. }
  561. SSL_CTX *
  562. tls_create_ctx(struct tls_create_ctx_args a, void *apparg)
  563. {
  564. int r;
  565. static long context_num = 0;
  566. SSL_CTX *ret;
  567. const char *err_pref_1 = "", *err_pref_2 = "";
  568. if (tls_init(apparg) == -1)
  569. return NULL;
  570. ret = SSL_CTX_new((a.client_p? SSLv23_client_method:SSLv23_server_method)());
  571. if (ret == NULL)
  572. goto err;
  573. SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback);
  574. SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE);
  575. if ((a.certificate_file != NULL) || (a.key_file != NULL)) {
  576. if (a.key_file == NULL) {
  577. tls_errprintf(1, apparg, "Need a key file.\n");
  578. goto err_return;
  579. }
  580. if (a.certificate_file == NULL) {
  581. tls_errprintf(1, apparg, "Need a certificate chain file.\n");
  582. goto err_return;
  583. }
  584. if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM))
  585. goto err;
  586. if (!tls_rand_seeded_p) {
  587. /* particularly paranoid people may not like this --
  588. * so provide your own random seeding before calling this */
  589. if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1)
  590. goto err_return;
  591. }
  592. if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file))
  593. goto err;
  594. if (!SSL_CTX_check_private_key(ret)) {
  595. tls_errprintf(1, apparg, "Private key \"%s\" does not match certificate \"%s\".\n", a.key_file, a.certificate_file);
  596. goto err_peek;
  597. }
  598. }
  599. if ((a.ca_file != NULL) || (a.verify_depth > 0)) {
  600. context_num++;
  601. r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num, (unsigned int)sizeof context_num);
  602. if (!r)
  603. goto err;
  604. SSL_CTX_set_verify(ret, SSL_VERIFY_PEER | (a.fail_unless_verified ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 0);
  605. if (!a.fail_unless_verified)
  606. SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL);
  607. if (a.verify_depth > 0)
  608. SSL_CTX_set_verify_depth(ret, a.verify_depth);
  609. if (a.ca_file != NULL) {
  610. r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL /* no CA-directory */); /* does not report failure if file does not exist ... */
  611. if (!r) {
  612. err_pref_1 = " while processing certificate file ";
  613. err_pref_2 = a.ca_file;
  614. goto err;
  615. }
  616. if (!a.client_p) {
  617. /* SSL_load_client_CA_file is a misnomer, it just creates a list of CNs. */
  618. SSL_CTX_set_client_CA_list(ret, SSL_load_client_CA_file(a.ca_file));
  619. /* SSL_CTX_set_client_CA_list does not have a return value;
  620. * it does not really need one, but make sure
  621. * (we really test if SSL_load_client_CA_file worked) */
  622. if (SSL_CTX_get_client_CA_list(ret) == NULL) {
  623. tls_errprintf(1, apparg, "Could not set client CA list from \"%s\".\n", a.ca_file);
  624. goto err_peek;
  625. }
  626. }
  627. }
  628. }
  629. if (!a.client_p) {
  630. if (tls_dhe1024 == NULL) {
  631. int i;
  632. RAND_bytes((unsigned char *) &i, sizeof i);
  633. /* make sure that i is non-negative -- pick one of the provided
  634. * seeds */
  635. if (i < 0)
  636. i = -i;
  637. if (i < 0)
  638. i = 0;
  639. tls_set_dhe1024(i, apparg);
  640. if (tls_dhe1024 == NULL)
  641. goto err_return;
  642. }
  643. if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
  644. goto err;
  645. /* avoid small subgroup attacks: */
  646. SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
  647. }
  648. #ifndef NO_RSA
  649. if (!a.client_p && a.export_p) {
  650. RSA *tmpkey;
  651. tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
  652. if (tmpkey == NULL)
  653. goto err;
  654. if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
  655. RSA_free(tmpkey);
  656. goto err;
  657. }
  658. RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
  659. }
  660. #endif
  661. return ret;
  662. err_peek:
  663. if (!ERR_peek_error())
  664. goto err_return;
  665. err:
  666. tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
  667. err_return:
  668. if (ret != NULL)
  669. SSL_CTX_free(ret);
  670. return NULL;
  671. }
  672. /*****************************************************************************/
  673. static int
  674. tls_socket_nonblocking(int fd)
  675. {
  676. int v, r;
  677. v = fcntl(fd, F_GETFL, 0);
  678. if (v == -1) {
  679. if (errno == EINVAL)
  680. return 0; /* already shut down -- ignore */
  681. return -1;
  682. }
  683. r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
  684. if (r == -1) {
  685. if (errno == EINVAL)
  686. return 0; /* already shut down -- ignore */
  687. return -1;
  688. }
  689. return 0;
  690. }
  691. static int
  692. max(int a, int b)
  693. {
  694. return a > b ? a : b;
  695. }
  696. static void
  697. tls_sockets_select(int read_select_1, int read_select_2, int write_select_1, int write_select_2, int seconds /* timeout, -1 means no timeout */)
  698. {
  699. int maxfd, n;
  700. fd_set reads, writes;
  701. struct timeval timeout;
  702. struct timeval *timeout_p;
  703. assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1 && write_select_2 >= -1);
  704. assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE -1 && write_select_1 < FD_SETSIZE -1 && write_select_2 < FD_SETSIZE -1);
  705. maxfd = max(max(read_select_1, read_select_2), max(write_select_1, write_select_2));
  706. assert(maxfd >= 0);
  707. FD_ZERO(&reads);
  708. FD_ZERO(&writes);
  709. for(n = 0; n < 4; ++n) {
  710. int i = n % 2;
  711. int w = n >= 2;
  712. /* loop over all (i, w) in {0,1}x{0,1} */
  713. int fd;
  714. if (i == 0 && w == 0)
  715. fd = read_select_1;
  716. else if (i == 1 && w == 0)
  717. fd = read_select_2;
  718. else if (i == 0 && w == 1)
  719. fd = write_select_1;
  720. else {
  721. assert(i == 1 && w == 1);
  722. fd = write_select_2;
  723. }
  724. if (fd >= 0) {
  725. if (w == 0)
  726. FD_SET(fd, &reads);
  727. else /* w == 1 */
  728. FD_SET(fd, &writes);
  729. }
  730. }
  731. if (seconds >= 0) {
  732. timeout.tv_sec = seconds;
  733. timeout.tv_usec = 0;
  734. timeout_p = &timeout;
  735. } else
  736. timeout_p = NULL;
  737. DEBUG_MSG2("select no.", ++tls_select_count);
  738. select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
  739. DEBUG_MSG("cont.");
  740. }
  741. /*****************************************************************************/
  742. #define TUNNELBUFSIZE (16*1024)
  743. struct tunnelbuf {
  744. char buf[TUNNELBUFSIZE];
  745. size_t len;
  746. size_t offset;
  747. };
  748. static int tls_connect_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
  749. static int tls_accept_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
  750. static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
  751. static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
  752. static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
  753. static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
  754. static void write_info(SSL *ssl, int *info_fd)
  755. {
  756. if (*info_fd != -1) {
  757. long v;
  758. int v_ok;
  759. struct tls_x509_name_string peer;
  760. char infobuf[TLS_INFO_SIZE];
  761. int r;
  762. DEBUG_MSG("write_info");
  763. v = SSL_get_verify_result(ssl);
  764. v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
  765. {
  766. X509 *peercert;
  767. peercert = SSL_get_peer_certificate(ssl);
  768. tls_get_x509_subject_name_oneline(peercert, &peer);
  769. if (peercert != NULL)
  770. X509_free(peercert);
  771. }
  772. if (peer.str[0] == '\0')
  773. v_ok = '0'; /* no cert at all */
  774. else
  775. if (strchr(peer.str, '\n')) {
  776. /* should not happen, but make sure */
  777. *strchr(peer.str, '\n') = '\0';
  778. }
  779. r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok, X509_verify_cert_error_string(v), peer.str);
  780. DEBUG_MSG2("snprintf", r);
  781. if (r == -1 || r >= sizeof infobuf)
  782. r = sizeof infobuf - 1;
  783. write(*info_fd, infobuf, r);
  784. close (*info_fd);
  785. *info_fd = -1;
  786. }
  787. }
  788. /* tls_proxy expects that all fds are closed after return */
  789. static void
  790. tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
  791. {
  792. struct tunnelbuf clear_to_tls, tls_to_clear;
  793. SSL *ssl;
  794. BIO *rbio, *wbio;
  795. int closed, in_handshake;
  796. const char *err_pref_1 = "", *err_pref_2 = "";
  797. const char *err_def = NULL;
  798. assert(clear_fd != -1);
  799. assert(tls_fd != -1);
  800. assert(clear_fd < FD_SETSIZE);
  801. assert(tls_fd < FD_SETSIZE);
  802. /* info_fd may be -1 */
  803. assert(ctx != NULL);
  804. tls_rand_seed_uniquely();
  805. tls_socket_nonblocking(clear_fd);
  806. DEBUG_MSG2("clear_fd", clear_fd);
  807. tls_socket_nonblocking(tls_fd);
  808. DEBUG_MSG2("tls_fd", tls_fd);
  809. ssl = SSL_new(ctx);
  810. if (ssl == NULL)
  811. goto err;
  812. DEBUG_MSG("SSL_new");
  813. if (!SSL_set_fd(ssl, tls_fd))
  814. goto err;
  815. rbio = SSL_get_rbio(ssl);
  816. wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
  817. assert(rbio != NULL);
  818. assert(wbio != NULL);
  819. if (client_p)
  820. SSL_set_connect_state(ssl);
  821. else
  822. SSL_set_accept_state(ssl);
  823. closed = 0;
  824. in_handshake = 1;
  825. tls_to_clear.len = 0;
  826. tls_to_clear.offset = 0;
  827. clear_to_tls.len = 0;
  828. clear_to_tls.offset = 0;
  829. err_def = "I/O error";
  830. /* loop finishes as soon as we detect that one side closed;
  831. * when all (program and OS) buffers have enough space,
  832. * the data from the last succesful read in each direction is transferred
  833. * before close */
  834. do {
  835. int clear_read_select = 0, clear_write_select = 0,
  836. tls_read_select = 0, tls_write_select = 0,
  837. progress = 0;
  838. int r;
  839. unsigned long num_read = BIO_number_read(rbio),
  840. num_written = BIO_number_written(wbio);
  841. DEBUG_MSG2("loop iteration", ++tls_loop_count);
  842. if (in_handshake) {
  843. DEBUG_MSG("in_handshake");
  844. if (client_p)
  845. r = tls_connect_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
  846. else
  847. r = tls_accept_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
  848. if (r != 0) {
  849. write_info(ssl, &info_fd);
  850. goto err;
  851. }
  852. if (closed)
  853. goto err_return;
  854. if (!SSL_in_init(ssl)) {
  855. in_handshake = 0;
  856. write_info(ssl, &info_fd);
  857. }
  858. }
  859. if (clear_to_tls.len != 0 && !in_handshake) {
  860. assert(!closed);
  861. r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
  862. if (r != 0)
  863. goto err;
  864. if (closed) {
  865. assert(progress);
  866. tls_to_clear.offset = 0;
  867. tls_to_clear.len = 0;
  868. }
  869. }
  870. if (tls_to_clear.len != 0) {
  871. assert(!closed);
  872. r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select, &closed, &progress);
  873. if (r != 0)
  874. goto err_return;
  875. if (closed) {
  876. assert(progress);
  877. clear_to_tls.offset = 0;
  878. clear_to_tls.len = 0;
  879. }
  880. }
  881. if (!closed) {
  882. if (clear_to_tls.offset + clear_to_tls.len < sizeof clear_to_tls.buf) {
  883. r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select, &closed, &progress);
  884. if (r != 0)
  885. goto err_return;
  886. if (closed) {
  887. r = SSL_shutdown(ssl);
  888. DEBUG_MSG2("SSL_shutdown", r);
  889. }
  890. }
  891. }
  892. if (!closed && !in_handshake) {
  893. if (tls_to_clear.offset + tls_to_clear.len < sizeof tls_to_clear.buf) {
  894. r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
  895. if (r != 0)
  896. goto err;
  897. if (closed) {
  898. r = SSL_shutdown(ssl);
  899. DEBUG_MSG2("SSL_shutdown", r);
  900. }
  901. }
  902. }
  903. if (!progress) {
  904. DEBUG_MSG("!progress?");
  905. if (num_read != BIO_number_read(rbio) || num_written != BIO_number_written(wbio))
  906. progress = 1;
  907. if (!progress) {
  908. DEBUG_MSG("!progress");
  909. assert(clear_read_select || tls_read_select || clear_write_select || tls_write_select);
  910. tls_sockets_select(clear_read_select ? clear_fd : -1, tls_read_select ? tls_fd : -1, clear_write_select ? clear_fd : -1, tls_write_select ? tls_fd : -1, -1);
  911. }
  912. }
  913. } while (!closed);
  914. return;
  915. err:
  916. tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
  917. err_return:
  918. return;
  919. }
  920. static int
  921. tls_get_error(SSL *ssl, int r, int *write_select, int *read_select, int *closed, int *progress)
  922. {
  923. int err = SSL_get_error(ssl, r);
  924. if (err == SSL_ERROR_NONE) {
  925. assert(r > 0);
  926. *progress = 1;
  927. return 0;
  928. }
  929. assert(r <= 0);
  930. switch (err) {
  931. case SSL_ERROR_ZERO_RETURN:
  932. assert(r == 0);
  933. *closed = 1;
  934. *progress = 1;
  935. return 0;
  936. case SSL_ERROR_WANT_WRITE:
  937. *write_select = 1;
  938. return 0;
  939. case SSL_ERROR_WANT_READ:
  940. *read_select = 1;
  941. return 0;
  942. }
  943. return -1;
  944. }
  945. static int
  946. tls_connect_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
  947. {
  948. int n, r;
  949. DEBUG_MSG("tls_connect_attempt");
  950. n = SSL_connect(ssl);
  951. DEBUG_MSG2("SSL_connect",n);
  952. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  953. if (r == -1)
  954. *err_pref = " during SSL_connect";
  955. return r;
  956. }
  957. static int
  958. tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
  959. {
  960. int n, r;
  961. DEBUG_MSG("tls_accept_attempt");
  962. n = SSL_accept(ssl);
  963. DEBUG_MSG2("SSL_accept",n);
  964. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  965. if (r == -1)
  966. *err_pref = " during SSL_accept";
  967. return r;
  968. }
  969. static int
  970. tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
  971. {
  972. int n, r;
  973. DEBUG_MSG("tls_write_attempt");
  974. n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
  975. DEBUG_MSG2("SSL_write",n);
  976. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  977. if (n > 0) {
  978. buf->len -= n;
  979. assert(buf->len >= 0);
  980. if (buf->len == 0)
  981. buf->offset = 0;
  982. else
  983. buf->offset += n;
  984. }
  985. if (r == -1)
  986. *err_pref = " during SSL_write";
  987. return r;
  988. }
  989. static int
  990. tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
  991. {
  992. int n, r;
  993. size_t total;
  994. DEBUG_MSG("tls_read_attempt");
  995. total = buf->offset + buf->len;
  996. assert(total < sizeof buf->buf);
  997. n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
  998. DEBUG_MSG2("SSL_read",n);
  999. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1000. if (n > 0) {
  1001. buf->len += n;
  1002. assert(buf->offset + buf->len <= sizeof buf->buf);
  1003. }
  1004. if (r == -1)
  1005. *err_pref = " during SSL_read";
  1006. return r;
  1007. }
  1008. static int
  1009. get_error(int r, int *select, int *closed, int *progress)
  1010. {
  1011. if (r >= 0) {
  1012. *progress = 1;
  1013. if (r == 0)
  1014. *closed = 1;
  1015. return 0;
  1016. } else {
  1017. assert(r == -1);
  1018. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1019. *select = 1;
  1020. return 0;
  1021. } else if (errno == EPIPE) {
  1022. *progress = 1;
  1023. *closed = 1;
  1024. return 0;
  1025. } else
  1026. return -1;
  1027. }
  1028. }
  1029. static int write_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
  1030. {
  1031. int n, r;
  1032. DEBUG_MSG("write_attempt");
  1033. n = write(fd, buf->buf + buf->offset, buf->len);
  1034. DEBUG_MSG2("write",n);
  1035. r = get_error(n, select, closed, progress);
  1036. if (n > 0) {
  1037. buf->len -= n;
  1038. assert(buf->len >= 0);
  1039. if (buf->len == 0)
  1040. buf->offset = 0;
  1041. else
  1042. buf->offset += n;
  1043. }
  1044. if (r == -1)
  1045. tls_errprintf(1, tls_child_apparg, "write error: %s\n", strerror(errno));
  1046. return r;
  1047. }
  1048. static int
  1049. read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
  1050. {
  1051. int n, r;
  1052. size_t total;
  1053. DEBUG_MSG("read_attempt");
  1054. total = buf->offset + buf->len;
  1055. assert(total < sizeof buf->buf);
  1056. n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
  1057. DEBUG_MSG2("read",n);
  1058. r = get_error(n, select, closed, progress);
  1059. if (n > 0) {
  1060. buf->len += n;
  1061. assert(buf->offset + buf->len <= sizeof buf->buf);
  1062. }
  1063. if (r == -1)
  1064. tls_errprintf(1, tls_child_apparg, "read error: %s\n", strerror(errno));
  1065. return r;
  1066. }