easy-tls.c 37 KB

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