easy-tls.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. 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. if (RAND_bytes((unsigned char *)&i, sizeof i) <= 0)
  666. goto err_return;
  667. /*
  668. * make sure that i is non-negative -- pick one of the provided
  669. * seeds
  670. */
  671. if (i < 0)
  672. i = -i;
  673. if (i < 0)
  674. i = 0;
  675. tls_set_dhe1024(i, apparg);
  676. if (tls_dhe1024 == NULL)
  677. goto err_return;
  678. }
  679. if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
  680. goto err;
  681. /* avoid small subgroup attacks: */
  682. SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
  683. }
  684. #ifndef NO_RSA
  685. if (!a.client_p && a.export_p) {
  686. RSA *tmpkey;
  687. tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
  688. if (tmpkey == NULL)
  689. goto err;
  690. if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
  691. RSA_free(tmpkey);
  692. goto err;
  693. }
  694. RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
  695. }
  696. #endif
  697. return ret;
  698. err_peek:
  699. if (!ERR_peek_error())
  700. goto err_return;
  701. err:
  702. tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
  703. err_return:
  704. if (ret != NULL)
  705. SSL_CTX_free(ret);
  706. return NULL;
  707. }
  708. /*****************************************************************************/
  709. static int tls_socket_nonblocking(int fd)
  710. {
  711. int v, r;
  712. v = fcntl(fd, F_GETFL, 0);
  713. if (v == -1) {
  714. if (errno == EINVAL)
  715. return 0; /* already shut down -- ignore */
  716. return -1;
  717. }
  718. r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
  719. if (r == -1) {
  720. if (errno == EINVAL)
  721. return 0; /* already shut down -- ignore */
  722. return -1;
  723. }
  724. return 0;
  725. }
  726. static int max(int a, int b)
  727. {
  728. return a > b ? a : b;
  729. }
  730. /* timeout, -1 means no timeout */
  731. static void
  732. tls_sockets_select(int read_select_1, int read_select_2, int write_select_1,
  733. int write_select_2, int seconds)
  734. {
  735. int maxfd, n;
  736. fd_set reads, writes;
  737. struct timeval timeout;
  738. struct timeval *timeout_p;
  739. assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1
  740. && write_select_2 >= -1);
  741. assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE - 1
  742. && write_select_1 < FD_SETSIZE - 1
  743. && write_select_2 < FD_SETSIZE - 1);
  744. maxfd =
  745. max(max(read_select_1, read_select_2),
  746. max(write_select_1, write_select_2));
  747. assert(maxfd >= 0);
  748. FD_ZERO(&reads);
  749. FD_ZERO(&writes);
  750. for (n = 0; n < 4; ++n) {
  751. int i = n % 2;
  752. int w = n >= 2;
  753. /* loop over all (i, w) in {0,1}x{0,1} */
  754. int fd;
  755. if (i == 0 && w == 0)
  756. fd = read_select_1;
  757. else if (i == 1 && w == 0)
  758. fd = read_select_2;
  759. else if (i == 0 && w == 1)
  760. fd = write_select_1;
  761. else {
  762. assert(i == 1 && w == 1);
  763. fd = write_select_2;
  764. }
  765. if (fd >= 0) {
  766. if (w == 0)
  767. FD_SET(fd, &reads);
  768. else /* w == 1 */
  769. FD_SET(fd, &writes);
  770. }
  771. }
  772. if (seconds >= 0) {
  773. timeout.tv_sec = seconds;
  774. timeout.tv_usec = 0;
  775. timeout_p = &timeout;
  776. } else
  777. timeout_p = NULL;
  778. DEBUG_MSG2("select no.", ++tls_select_count);
  779. select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
  780. DEBUG_MSG("cont.");
  781. }
  782. /*****************************************************************************/
  783. #define TUNNELBUFSIZE (16*1024)
  784. struct tunnelbuf {
  785. char buf[TUNNELBUFSIZE];
  786. size_t len;
  787. size_t offset;
  788. };
  789. static int tls_connect_attempt(SSL *, int *write_select, int *read_select,
  790. int *closed, int *progress,
  791. const char **err_pref);
  792. static int tls_accept_attempt(SSL *, int *write_select, int *read_select,
  793. int *closed, int *progress,
  794. const char **err_pref);
  795. static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select,
  796. int *read_select, int *closed, int *progress,
  797. const char **err_pref);
  798. static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select,
  799. int *read_select, int *closed, int *progress,
  800. const char **err_pref);
  801. static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed,
  802. int *progress);
  803. static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed,
  804. int *progress);
  805. static void write_info(SSL *ssl, int *info_fd)
  806. {
  807. if (*info_fd != -1) {
  808. long v;
  809. int v_ok;
  810. struct tls_x509_name_string peer;
  811. char infobuf[TLS_INFO_SIZE];
  812. int r;
  813. DEBUG_MSG("write_info");
  814. v = SSL_get_verify_result(ssl);
  815. v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
  816. {
  817. X509 *peercert;
  818. peercert = SSL_get_peer_certificate(ssl);
  819. tls_get_x509_subject_name_oneline(peercert, &peer);
  820. if (peercert != NULL)
  821. X509_free(peercert);
  822. }
  823. if (peer.str[0] == '\0')
  824. v_ok = '0'; /* no cert at all */
  825. else if (strchr(peer.str, '\n')) {
  826. /* should not happen, but make sure */
  827. *strchr(peer.str, '\n') = '\0';
  828. }
  829. r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok,
  830. X509_verify_cert_error_string(v), peer.str);
  831. DEBUG_MSG2("snprintf", r);
  832. if (r == -1 || r >= sizeof infobuf)
  833. r = sizeof infobuf - 1;
  834. write(*info_fd, infobuf, r);
  835. close(*info_fd);
  836. *info_fd = -1;
  837. }
  838. }
  839. /* tls_proxy expects that all fds are closed after return */
  840. static void
  841. tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
  842. {
  843. struct tunnelbuf clear_to_tls, tls_to_clear;
  844. SSL *ssl;
  845. BIO *rbio, *wbio;
  846. int closed, in_handshake;
  847. const char *err_pref_1 = "", *err_pref_2 = "";
  848. const char *err_def = NULL;
  849. assert(clear_fd != -1);
  850. assert(tls_fd != -1);
  851. assert(clear_fd < FD_SETSIZE);
  852. assert(tls_fd < FD_SETSIZE);
  853. /* info_fd may be -1 */
  854. assert(ctx != NULL);
  855. tls_rand_seed_uniquely();
  856. tls_socket_nonblocking(clear_fd);
  857. DEBUG_MSG2("clear_fd", clear_fd);
  858. tls_socket_nonblocking(tls_fd);
  859. DEBUG_MSG2("tls_fd", tls_fd);
  860. ssl = SSL_new(ctx);
  861. if (ssl == NULL)
  862. goto err;
  863. DEBUG_MSG("SSL_new");
  864. if (!SSL_set_fd(ssl, tls_fd))
  865. goto err;
  866. rbio = SSL_get_rbio(ssl);
  867. wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
  868. assert(rbio != NULL);
  869. assert(wbio != NULL);
  870. if (client_p)
  871. SSL_set_connect_state(ssl);
  872. else
  873. SSL_set_accept_state(ssl);
  874. closed = 0;
  875. in_handshake = 1;
  876. tls_to_clear.len = 0;
  877. tls_to_clear.offset = 0;
  878. clear_to_tls.len = 0;
  879. clear_to_tls.offset = 0;
  880. err_def = "I/O error";
  881. /*
  882. * loop finishes as soon as we detect that one side closed; when all
  883. * (program and OS) buffers have enough space, the data from the last
  884. * succesful read in each direction is transferred before close
  885. */
  886. do {
  887. int clear_read_select = 0, clear_write_select = 0,
  888. tls_read_select = 0, tls_write_select = 0, progress = 0;
  889. int r;
  890. unsigned long num_read = BIO_number_read(rbio),
  891. num_written = BIO_number_written(wbio);
  892. DEBUG_MSG2("loop iteration", ++tls_loop_count);
  893. if (in_handshake) {
  894. DEBUG_MSG("in_handshake");
  895. if (client_p)
  896. r = tls_connect_attempt(ssl, &tls_write_select,
  897. &tls_read_select, &closed, &progress,
  898. &err_pref_1);
  899. else
  900. r = tls_accept_attempt(ssl, &tls_write_select,
  901. &tls_read_select, &closed, &progress,
  902. &err_pref_1);
  903. if (r != 0) {
  904. write_info(ssl, &info_fd);
  905. goto err;
  906. }
  907. if (closed)
  908. goto err_return;
  909. if (!SSL_in_init(ssl)) {
  910. in_handshake = 0;
  911. write_info(ssl, &info_fd);
  912. }
  913. }
  914. if (clear_to_tls.len != 0 && !in_handshake) {
  915. assert(!closed);
  916. r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select,
  917. &tls_read_select, &closed, &progress,
  918. &err_pref_1);
  919. if (r != 0)
  920. goto err;
  921. if (closed) {
  922. assert(progress);
  923. tls_to_clear.offset = 0;
  924. tls_to_clear.len = 0;
  925. }
  926. }
  927. if (tls_to_clear.len != 0) {
  928. assert(!closed);
  929. r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select,
  930. &closed, &progress);
  931. if (r != 0)
  932. goto err_return;
  933. if (closed) {
  934. assert(progress);
  935. clear_to_tls.offset = 0;
  936. clear_to_tls.len = 0;
  937. }
  938. }
  939. if (!closed) {
  940. if (clear_to_tls.offset + clear_to_tls.len <
  941. sizeof clear_to_tls.buf) {
  942. r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select,
  943. &closed, &progress);
  944. if (r != 0)
  945. goto err_return;
  946. if (closed) {
  947. r = SSL_shutdown(ssl);
  948. DEBUG_MSG2("SSL_shutdown", r);
  949. }
  950. }
  951. }
  952. if (!closed && !in_handshake) {
  953. if (tls_to_clear.offset + tls_to_clear.len <
  954. sizeof tls_to_clear.buf) {
  955. r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select,
  956. &tls_read_select, &closed, &progress,
  957. &err_pref_1);
  958. if (r != 0)
  959. goto err;
  960. if (closed) {
  961. r = SSL_shutdown(ssl);
  962. DEBUG_MSG2("SSL_shutdown", r);
  963. }
  964. }
  965. }
  966. if (!progress) {
  967. DEBUG_MSG("!progress?");
  968. if (num_read != BIO_number_read(rbio)
  969. || num_written != BIO_number_written(wbio))
  970. progress = 1;
  971. if (!progress) {
  972. DEBUG_MSG("!progress");
  973. assert(clear_read_select || tls_read_select
  974. || clear_write_select || tls_write_select);
  975. tls_sockets_select(clear_read_select ? clear_fd : -1,
  976. tls_read_select ? tls_fd : -1,
  977. clear_write_select ? clear_fd : -1,
  978. tls_write_select ? tls_fd : -1, -1);
  979. }
  980. }
  981. } while (!closed);
  982. return;
  983. err:
  984. tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
  985. err_return:
  986. return;
  987. }
  988. static int
  989. tls_get_error(SSL *ssl, int r, int *write_select, int *read_select,
  990. int *closed, int *progress)
  991. {
  992. int err = SSL_get_error(ssl, r);
  993. if (err == SSL_ERROR_NONE) {
  994. assert(r > 0);
  995. *progress = 1;
  996. return 0;
  997. }
  998. assert(r <= 0);
  999. switch (err) {
  1000. case SSL_ERROR_ZERO_RETURN:
  1001. assert(r == 0);
  1002. *closed = 1;
  1003. *progress = 1;
  1004. return 0;
  1005. case SSL_ERROR_WANT_WRITE:
  1006. *write_select = 1;
  1007. return 0;
  1008. case SSL_ERROR_WANT_READ:
  1009. *read_select = 1;
  1010. return 0;
  1011. }
  1012. return -1;
  1013. }
  1014. static int
  1015. tls_connect_attempt(SSL *ssl, int *write_select, int *read_select,
  1016. int *closed, int *progress, const char **err_pref)
  1017. {
  1018. int n, r;
  1019. DEBUG_MSG("tls_connect_attempt");
  1020. n = SSL_connect(ssl);
  1021. DEBUG_MSG2("SSL_connect", n);
  1022. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1023. if (r == -1)
  1024. *err_pref = " during SSL_connect";
  1025. return r;
  1026. }
  1027. static int
  1028. tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed,
  1029. int *progress, const char **err_pref)
  1030. {
  1031. int n, r;
  1032. DEBUG_MSG("tls_accept_attempt");
  1033. n = SSL_accept(ssl);
  1034. DEBUG_MSG2("SSL_accept", n);
  1035. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1036. if (r == -1)
  1037. *err_pref = " during SSL_accept";
  1038. return r;
  1039. }
  1040. static int
  1041. tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select,
  1042. int *read_select, int *closed, int *progress,
  1043. const char **err_pref)
  1044. {
  1045. int n, r;
  1046. DEBUG_MSG("tls_write_attempt");
  1047. n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
  1048. DEBUG_MSG2("SSL_write", n);
  1049. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1050. if (n > 0) {
  1051. buf->len -= n;
  1052. assert(buf->len >= 0);
  1053. if (buf->len == 0)
  1054. buf->offset = 0;
  1055. else
  1056. buf->offset += n;
  1057. }
  1058. if (r == -1)
  1059. *err_pref = " during SSL_write";
  1060. return r;
  1061. }
  1062. static int
  1063. tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select,
  1064. int *read_select, int *closed, int *progress,
  1065. const char **err_pref)
  1066. {
  1067. int n, r;
  1068. size_t total;
  1069. DEBUG_MSG("tls_read_attempt");
  1070. total = buf->offset + buf->len;
  1071. assert(total < sizeof buf->buf);
  1072. n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
  1073. DEBUG_MSG2("SSL_read", n);
  1074. r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
  1075. if (n > 0) {
  1076. buf->len += n;
  1077. assert(buf->offset + buf->len <= sizeof buf->buf);
  1078. }
  1079. if (r == -1)
  1080. *err_pref = " during SSL_read";
  1081. return r;
  1082. }
  1083. static int get_error(int r, int *select, int *closed, int *progress)
  1084. {
  1085. if (r >= 0) {
  1086. *progress = 1;
  1087. if (r == 0)
  1088. *closed = 1;
  1089. return 0;
  1090. } else {
  1091. assert(r == -1);
  1092. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1093. *select = 1;
  1094. return 0;
  1095. } else if (errno == EPIPE) {
  1096. *progress = 1;
  1097. *closed = 1;
  1098. return 0;
  1099. } else
  1100. return -1;
  1101. }
  1102. }
  1103. static int write_attempt(int fd, struct tunnelbuf *buf, int *select,
  1104. int *closed, int *progress)
  1105. {
  1106. int n, r;
  1107. DEBUG_MSG("write_attempt");
  1108. n = write(fd, buf->buf + buf->offset, buf->len);
  1109. DEBUG_MSG2("write", n);
  1110. r = get_error(n, select, closed, progress);
  1111. if (n > 0) {
  1112. buf->len -= n;
  1113. assert(buf->len >= 0);
  1114. if (buf->len == 0)
  1115. buf->offset = 0;
  1116. else
  1117. buf->offset += n;
  1118. }
  1119. if (r == -1)
  1120. tls_errprintf(1, tls_child_apparg, "write error: %s\n",
  1121. strerror(errno));
  1122. return r;
  1123. }
  1124. static int
  1125. read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed,
  1126. int *progress)
  1127. {
  1128. int n, r;
  1129. size_t total;
  1130. DEBUG_MSG("read_attempt");
  1131. total = buf->offset + buf->len;
  1132. assert(total < sizeof buf->buf);
  1133. n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
  1134. DEBUG_MSG2("read", n);
  1135. r = get_error(n, select, closed, progress);
  1136. if (n > 0) {
  1137. buf->len += n;
  1138. assert(buf->offset + buf->len <= sizeof buf->buf);
  1139. }
  1140. if (r == -1)
  1141. tls_errprintf(1, tls_child_apparg, "read error: %s\n",
  1142. strerror(errno));
  1143. return r;
  1144. }