conn-ssl.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. * ngIRCd -- The Next Generation IRC Daemon
  3. * Copyright (c)2005-2008 Florian Westphal (fw@strlen.de).
  4. * Copyright (c)2008-2014 Alexander Barton (alex@barton.de) and Contributors.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. * Please read the file COPYING, README and AUTHORS for more information.
  11. */
  12. #include "portab.h"
  13. /**
  14. * @file
  15. * SSL wrapper functions
  16. */
  17. #include "conf-ssl.h"
  18. #ifdef SSL_SUPPORT
  19. #include "io.h"
  20. #include <assert.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #include <errno.h>
  25. #define CONN_MODULE
  26. #include "conn.h"
  27. #include "conf.h"
  28. #include "conn-func.h"
  29. #include "conn-ssl.h"
  30. #include "log.h"
  31. #include "defines.h"
  32. extern struct SSLOptions Conf_SSLOptions;
  33. #ifdef HAVE_LIBSSL
  34. #include <openssl/err.h>
  35. #include <openssl/rand.h>
  36. static SSL_CTX * ssl_ctx;
  37. static DH *dh_params;
  38. static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
  39. #endif
  40. #ifdef HAVE_LIBGNUTLS
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #include <fcntl.h>
  44. #include <unistd.h>
  45. #include <gnutls/x509.h>
  46. #define DH_BITS 2048
  47. #define DH_BITS_MIN 1024
  48. #define MAX_HASH_SIZE 64 /* from gnutls-int.h */
  49. static gnutls_certificate_credentials_t x509_cred;
  50. static gnutls_dh_params_t dh_params;
  51. static gnutls_priority_t priorities_cache;
  52. static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
  53. #endif
  54. #define SHA256_STRING_LEN (32 * 2 + 1)
  55. static bool ConnSSL_Init_SSL PARAMS(( CONNECTION *c ));
  56. static int ConnectAccept PARAMS(( CONNECTION *c, bool connect ));
  57. static int ConnSSL_HandleError PARAMS(( CONNECTION *c, const int code, const char *fname ));
  58. #ifdef HAVE_LIBGNUTLS
  59. static char * openreadclose(const char *name, size_t *len)
  60. {
  61. char *buf = NULL;
  62. struct stat s;
  63. ssize_t br;
  64. int fd = open(name, O_RDONLY);
  65. if (fd < 0) {
  66. Log(LOG_ERR, "Could not open %s: %s", name, strerror(errno));
  67. return NULL;
  68. }
  69. if (fstat(fd, &s)) {
  70. Log(LOG_ERR, "Could not fstat %s: %s", name, strerror(errno));
  71. goto out;
  72. }
  73. if (!S_ISREG(s.st_mode)) {
  74. Log(LOG_ERR, "%s: Not a regular file", name);
  75. goto out;
  76. }
  77. if (s.st_size <= 0) {
  78. Log(LOG_ERR, "%s: invalid file length (size %ld <= 0)", name, (long) s.st_size);
  79. goto out;
  80. }
  81. buf = malloc(s.st_size);
  82. if (!buf) {
  83. Log(LOG_ERR, "Could not malloc %lu bytes for file %s: %s", s.st_size, name, strerror(errno));
  84. goto out;
  85. }
  86. br = read(fd, buf, s.st_size);
  87. if (br != (ssize_t)s.st_size) {
  88. Log(LOG_ERR, "Could not read file %s: read returned %ld, expected %ld: %s",
  89. name, (long) br, (long) s.st_size, br == -1 ? strerror(errno):"short read?!");
  90. memset(buf, 0, s.st_size);
  91. free(buf);
  92. buf = NULL;
  93. } else {
  94. *len = br;
  95. }
  96. out:
  97. close(fd);
  98. return buf;
  99. }
  100. #endif
  101. #ifdef HAVE_LIBSSL
  102. /**
  103. * Log OpenSSL error message.
  104. *
  105. * @param msg The error message.
  106. * @param info Additional information text or NULL.
  107. */
  108. static void
  109. LogOpenSSLError(const char *error, const char *info)
  110. {
  111. unsigned long err = ERR_get_error();
  112. char * errmsg = err
  113. ? ERR_error_string(err, NULL)
  114. : "Unable to determine error";
  115. assert(error != NULL);
  116. if (info)
  117. Log(LOG_ERR, "%s: %s (%s)", error, info, errmsg);
  118. else
  119. Log(LOG_ERR, "%s: %s", error, errmsg);
  120. }
  121. static int
  122. pem_passwd_cb(char *buf, int size, int rwflag, void *password)
  123. {
  124. array *pass = password;
  125. int passlen;
  126. (void)rwflag; /* rwflag is unused if DEBUG is not set. */
  127. assert(rwflag == 0); /* 0 -> callback used for decryption.
  128. * See SSL_CTX_set_default_passwd_cb(3) */
  129. passlen = (int) array_bytes(pass);
  130. LogDebug("pem_passwd_cb buf size %d, array size %d", size, passlen);
  131. assert(passlen >= 0);
  132. if (passlen <= 0) {
  133. Log(LOG_ERR, "PEM password required but not set [in pem_passwd_cb()]!");
  134. return 0;
  135. }
  136. size = passlen > size ? size : passlen;
  137. memcpy(buf, (char *)(array_start(pass)), size);
  138. return size;
  139. }
  140. static int
  141. Verify_openssl(UNUSED int preverify_ok, UNUSED X509_STORE_CTX *x509_ctx)
  142. {
  143. return 1;
  144. }
  145. #endif
  146. static bool
  147. Load_DH_params(void)
  148. {
  149. #ifdef HAVE_LIBSSL
  150. FILE *fp;
  151. bool ret = true;
  152. if (!Conf_SSLOptions.DHFile) {
  153. Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
  154. return false;
  155. }
  156. fp = fopen(Conf_SSLOptions.DHFile, "r");
  157. if (!fp) {
  158. Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
  159. return false;
  160. }
  161. dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
  162. if (!dh_params) {
  163. Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
  164. Conf_SSLOptions.DHFile);
  165. ret = false;
  166. }
  167. fclose(fp);
  168. return ret;
  169. #endif
  170. #ifdef HAVE_LIBGNUTLS
  171. bool need_dhgenerate = true;
  172. int err;
  173. gnutls_dh_params_t tmp_dh_params;
  174. err = gnutls_dh_params_init(&tmp_dh_params);
  175. if (err < 0) {
  176. Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
  177. gnutls_strerror(err));
  178. return false;
  179. }
  180. if (Conf_SSLOptions.DHFile) {
  181. gnutls_datum_t dhparms;
  182. size_t size;
  183. dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
  184. if (dhparms.data) {
  185. dhparms.size = size;
  186. err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
  187. if (err == 0)
  188. need_dhgenerate = false;
  189. else
  190. Log(LOG_ERR,
  191. "Failed to initialize SSL DH parameters: %s",
  192. gnutls_strerror(err));
  193. memset(dhparms.data, 0, size);
  194. free(dhparms.data);
  195. }
  196. }
  197. if (need_dhgenerate) {
  198. Log(LOG_WARNING,
  199. "DHFile not set, generating %u bit DH parameters. This may take a while ...",
  200. DH_BITS);
  201. err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
  202. if (err < 0) {
  203. Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
  204. gnutls_strerror(err));
  205. return false;
  206. }
  207. }
  208. dh_params = tmp_dh_params;
  209. return true;
  210. #endif
  211. }
  212. void ConnSSL_Free(CONNECTION *c)
  213. {
  214. #ifdef HAVE_LIBSSL
  215. SSL *ssl = c->ssl_state.ssl;
  216. if (ssl) {
  217. SSL_shutdown(ssl);
  218. SSL_free(ssl);
  219. c->ssl_state.ssl = NULL;
  220. if (c->ssl_state.fingerprint) {
  221. free(c->ssl_state.fingerprint);
  222. c->ssl_state.fingerprint = NULL;
  223. }
  224. }
  225. #endif
  226. #ifdef HAVE_LIBGNUTLS
  227. gnutls_session_t sess = c->ssl_state.gnutls_session;
  228. if (Conn_OPTION_ISSET(c, CONN_SSL)) {
  229. gnutls_bye(sess, GNUTLS_SHUT_RDWR);
  230. gnutls_deinit(sess);
  231. }
  232. #endif
  233. assert(Conn_OPTION_ISSET(c, CONN_SSL));
  234. /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
  235. Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
  236. }
  237. bool
  238. ConnSSL_InitLibrary( void )
  239. {
  240. if (!Conf_SSLInUse()) {
  241. LogDebug("SSL not in use, skipping initialization.");
  242. return true;
  243. }
  244. #ifdef HAVE_LIBSSL
  245. SSL_CTX *newctx;
  246. #if OPENSSL_API_COMPAT < 0x10100000L
  247. if (!ssl_ctx) {
  248. SSL_library_init();
  249. SSL_load_error_strings();
  250. }
  251. #endif
  252. if (!RAND_status()) {
  253. Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
  254. /*
  255. * it is probably best to fail and let the user install EGD or
  256. * a similar program if no kernel random device is available.
  257. * According to OpenSSL RAND_egd(3): "The automatic query of
  258. * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
  259. * so it makes little sense to deal with PRNGD seeding ourselves.
  260. */
  261. array_free(&Conf_SSLOptions.ListenPorts);
  262. return false;
  263. }
  264. newctx = SSL_CTX_new(SSLv23_method());
  265. if (!newctx) {
  266. LogOpenSSLError("Failed to create SSL context", NULL);
  267. array_free(&Conf_SSLOptions.ListenPorts);
  268. return false;
  269. }
  270. if (!ConnSSL_LoadServerKey_openssl(newctx))
  271. goto out;
  272. if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
  273. Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
  274. Conf_SSLOptions.CipherList);
  275. goto out;
  276. }
  277. SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
  278. SSL_CTX_set_options(newctx, SSL_OP_SINGLE_DH_USE|SSL_OP_NO_SSLv2);
  279. SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
  280. SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
  281. Verify_openssl);
  282. SSL_CTX_free(ssl_ctx);
  283. ssl_ctx = newctx;
  284. Log(LOG_INFO, "%s initialized.", SSLeay_version(SSLEAY_VERSION));
  285. return true;
  286. out:
  287. SSL_CTX_free(newctx);
  288. array_free(&Conf_SSLOptions.ListenPorts);
  289. return false;
  290. #endif
  291. #ifdef HAVE_LIBGNUTLS
  292. int err;
  293. static bool initialized;
  294. if (initialized) {
  295. /* TODO: cannot reload gnutls keys: can't simply free x509
  296. * context -- it may still be in use */
  297. return false;
  298. }
  299. err = gnutls_global_init();
  300. if (err) {
  301. Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
  302. gnutls_strerror(err));
  303. goto out;
  304. }
  305. if (!ConnSSL_LoadServerKey_gnutls())
  306. goto out;
  307. if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
  308. NULL) != GNUTLS_E_SUCCESS) {
  309. Log(LOG_ERR,
  310. "Failed to apply GnuTLS cipher list \"%s\"!",
  311. Conf_SSLOptions.CipherList);
  312. goto out;
  313. }
  314. Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
  315. initialized = true;
  316. return true;
  317. out:
  318. array_free(&Conf_SSLOptions.ListenPorts);
  319. return false;
  320. #endif
  321. }
  322. #ifdef HAVE_LIBGNUTLS
  323. static bool
  324. ConnSSL_LoadServerKey_gnutls(void)
  325. {
  326. int err;
  327. const char *cert_file;
  328. err = gnutls_certificate_allocate_credentials(&x509_cred);
  329. if (err < 0) {
  330. Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
  331. gnutls_strerror(err));
  332. return false;
  333. }
  334. cert_file = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
  335. if (!cert_file) {
  336. Log(LOG_ERR, "No SSL server key configured!");
  337. return false;
  338. }
  339. if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
  340. Log(LOG_WARNING,
  341. "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
  342. if (!Load_DH_params())
  343. return false;
  344. gnutls_certificate_set_dh_params(x509_cred, dh_params);
  345. err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file, Conf_SSLOptions.KeyFile, GNUTLS_X509_FMT_PEM);
  346. if (err < 0) {
  347. Log(LOG_ERR,
  348. "Failed to set certificate key file (cert %s, key %s): %s",
  349. cert_file,
  350. Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
  351. gnutls_strerror(err));
  352. return false;
  353. }
  354. return true;
  355. }
  356. #endif
  357. #ifdef HAVE_LIBSSL
  358. static bool
  359. ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
  360. {
  361. char *cert_key;
  362. assert(ctx);
  363. if (!Conf_SSLOptions.KeyFile) {
  364. Log(LOG_ERR, "No SSL server key configured!");
  365. return false;
  366. }
  367. SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
  368. SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
  369. if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
  370. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  371. LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
  372. return false;
  373. }
  374. cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
  375. if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
  376. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  377. LogOpenSSLError("Failed to load certificate chain", cert_key);
  378. return false;
  379. }
  380. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  381. if (!SSL_CTX_check_private_key(ctx)) {
  382. LogOpenSSLError("Server private key does not match certificate", NULL);
  383. return false;
  384. }
  385. if (Load_DH_params()) {
  386. if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
  387. LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
  388. /* don't return false here: the non-DH modes will still work */
  389. DH_free(dh_params);
  390. dh_params = NULL;
  391. }
  392. return true;
  393. }
  394. #endif
  395. static bool
  396. ConnSSL_Init_SSL(CONNECTION *c)
  397. {
  398. int ret;
  399. LogDebug("Initializing SSL ...");
  400. assert(c != NULL);
  401. #ifdef HAVE_LIBSSL
  402. if (!ssl_ctx) {
  403. Log(LOG_ERR,
  404. "Can't initialize SSL context, OpenSSL initialization failed at startup!");
  405. return false;
  406. }
  407. assert(c->ssl_state.ssl == NULL);
  408. assert(c->ssl_state.fingerprint == NULL);
  409. c->ssl_state.ssl = SSL_new(ssl_ctx);
  410. if (!c->ssl_state.ssl) {
  411. LogOpenSSLError("Failed to create SSL structure", NULL);
  412. return false;
  413. }
  414. Conn_OPTION_ADD(c, CONN_SSL);
  415. ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
  416. if (ret != 1) {
  417. LogOpenSSLError("Failed to set SSL file descriptor", NULL);
  418. ConnSSL_Free(c);
  419. return false;
  420. }
  421. #endif
  422. #ifdef HAVE_LIBGNUTLS
  423. Conn_OPTION_ADD(c, CONN_SSL);
  424. ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
  425. if (ret != GNUTLS_E_SUCCESS) {
  426. Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
  427. gnutls_strerror(ret));
  428. ConnSSL_Free(c);
  429. return false;
  430. }
  431. /*
  432. * The intermediate (long) cast is here to avoid a warning like:
  433. * "cast to pointer from integer of different size" on 64-bit platforms.
  434. * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
  435. * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
  436. */
  437. gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
  438. (gnutls_transport_ptr_t) (long) c->sock);
  439. gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
  440. GNUTLS_CERT_REQUEST);
  441. ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
  442. GNUTLS_CRD_CERTIFICATE, x509_cred);
  443. if (ret != 0) {
  444. Log(LOG_ERR, "Failed to set SSL credentials: %s",
  445. gnutls_strerror(ret));
  446. ConnSSL_Free(c);
  447. return false;
  448. }
  449. gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
  450. #endif
  451. return true;
  452. }
  453. bool
  454. ConnSSL_PrepareConnect(CONNECTION *c, UNUSED CONF_SERVER *s)
  455. {
  456. bool ret;
  457. #ifdef HAVE_LIBGNUTLS
  458. int err;
  459. err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
  460. if (err) {
  461. Log(LOG_ERR, "Failed to initialize new SSL session: %s",
  462. gnutls_strerror(err));
  463. return false;
  464. }
  465. #endif
  466. ret = ConnSSL_Init_SSL(c);
  467. if (!ret)
  468. return false;
  469. Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
  470. #ifdef HAVE_LIBSSL
  471. assert(c->ssl_state.ssl);
  472. SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
  473. #endif
  474. return true;
  475. }
  476. /**
  477. * Check and handle error return codes after failed calls to SSL functions.
  478. *
  479. * OpenSSL:
  480. * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
  481. * SSL_write() on ssl.
  482. *
  483. * GnuTLS:
  484. * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
  485. *
  486. * @param c The connection handle.
  487. * @prarm code The return code.
  488. * @param fname The name of the function in which the error occurred.
  489. * @return -1 on fatal errors, 0 if we can try again later.
  490. */
  491. static int
  492. ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
  493. {
  494. #ifdef HAVE_LIBSSL
  495. int ret = SSL_ERROR_SYSCALL;
  496. unsigned long sslerr;
  497. int real_errno = errno;
  498. ret = SSL_get_error(c->ssl_state.ssl, code);
  499. switch (ret) {
  500. case SSL_ERROR_WANT_READ:
  501. io_event_del(c->sock, IO_WANTWRITE);
  502. Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
  503. return 0; /* try again later */
  504. case SSL_ERROR_WANT_WRITE:
  505. io_event_del(c->sock, IO_WANTREAD);
  506. Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
  507. case SSL_ERROR_NONE:
  508. return 0; /* try again later */
  509. case SSL_ERROR_ZERO_RETURN:
  510. LogDebug("SSL connection shut down normally.");
  511. break;
  512. case SSL_ERROR_SYSCALL:
  513. /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
  514. * and SSL_ERROR_WANT_X509_LOOKUP */
  515. sslerr = ERR_get_error();
  516. if (sslerr) {
  517. Log(LOG_ERR, "SSL error: %s [in %s()]!",
  518. ERR_error_string(sslerr, NULL), fname);
  519. } else {
  520. switch (code) { /* EOF that violated protocol */
  521. case 0:
  522. Log(LOG_ERR,
  523. "SSL error, client disconnected [in %s()]!",
  524. fname);
  525. break;
  526. case -1: /* low level socket I/O error, check errno */
  527. Log(LOG_ERR, "SSL error: %s [in %s()]!",
  528. strerror(real_errno), fname);
  529. }
  530. }
  531. break;
  532. case SSL_ERROR_SSL:
  533. LogOpenSSLError("SSL protocol error", fname);
  534. break;
  535. default:
  536. Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
  537. }
  538. ConnSSL_Free(c);
  539. return -1;
  540. #endif
  541. #ifdef HAVE_LIBGNUTLS
  542. switch (code) {
  543. case GNUTLS_E_AGAIN:
  544. case GNUTLS_E_INTERRUPTED:
  545. if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
  546. Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
  547. io_event_del(c->sock, IO_WANTREAD);
  548. } else {
  549. Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
  550. io_event_del(c->sock, IO_WANTWRITE);
  551. }
  552. break;
  553. default:
  554. assert(code < 0);
  555. if (gnutls_error_is_fatal(code)) {
  556. Log(LOG_ERR, "SSL error: %s [%s].",
  557. gnutls_strerror(code), fname);
  558. ConnSSL_Free(c);
  559. return -1;
  560. }
  561. }
  562. return 0;
  563. #endif
  564. }
  565. static void
  566. ConnSSL_LogCertInfo( CONNECTION *c )
  567. {
  568. #ifdef HAVE_LIBSSL
  569. SSL *ssl = c->ssl_state.ssl;
  570. assert(ssl);
  571. Log(LOG_INFO, "Connection %d: initialized %s using cipher %s.",
  572. c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl));
  573. #endif
  574. #ifdef HAVE_LIBGNUTLS
  575. gnutls_session_t sess = c->ssl_state.gnutls_session;
  576. gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
  577. Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
  578. c->sock,
  579. gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
  580. gnutls_cipher_get_name(cipher),
  581. gnutls_mac_get_name(gnutls_mac_get(sess)));
  582. #endif
  583. }
  584. /*
  585. Accept incoming SSL connection.
  586. Return Values:
  587. 1: SSL Connection established
  588. 0: try again
  589. -1: SSL Connection not established due to fatal error.
  590. */
  591. int
  592. ConnSSL_Accept( CONNECTION *c )
  593. {
  594. assert(c != NULL);
  595. if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
  596. #ifdef HAVE_LIBGNUTLS
  597. int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
  598. if (err) {
  599. Log(LOG_ERR, "Failed to initialize new SSL session: %s",
  600. gnutls_strerror(err));
  601. return false;
  602. }
  603. #endif
  604. if (!ConnSSL_Init_SSL(c))
  605. return -1;
  606. }
  607. return ConnectAccept(c, false );
  608. }
  609. int
  610. ConnSSL_Connect( CONNECTION *c )
  611. {
  612. assert(c != NULL);
  613. #ifdef HAVE_LIBSSL
  614. assert(c->ssl_state.ssl);
  615. #endif
  616. assert(Conn_OPTION_ISSET(c, CONN_SSL));
  617. return ConnectAccept(c, true);
  618. }
  619. static int
  620. ConnSSL_InitCertFp( CONNECTION *c )
  621. {
  622. const char hex[] = "0123456789abcdef";
  623. int i;
  624. #ifdef HAVE_LIBSSL
  625. unsigned char digest[EVP_MAX_MD_SIZE];
  626. unsigned int digest_size;
  627. X509 *cert;
  628. cert = SSL_get_peer_certificate(c->ssl_state.ssl);
  629. if (!cert)
  630. return 0;
  631. if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
  632. X509_free(cert);
  633. return 0;
  634. }
  635. X509_free(cert);
  636. #endif /* HAVE_LIBSSL */
  637. #ifdef HAVE_LIBGNUTLS
  638. gnutls_x509_crt_t cert;
  639. unsigned int cert_list_size;
  640. const gnutls_datum_t *cert_list;
  641. unsigned char digest[MAX_HASH_SIZE];
  642. size_t digest_size;
  643. if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
  644. GNUTLS_CRT_X509)
  645. return 0;
  646. if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
  647. return 0;
  648. cert_list_size = 0;
  649. cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
  650. &cert_list_size);
  651. if (!cert_list) {
  652. gnutls_x509_crt_deinit(cert);
  653. return 0;
  654. }
  655. if (gnutls_x509_crt_import(cert, &cert_list[0],
  656. GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
  657. gnutls_x509_crt_deinit(cert);
  658. return 0;
  659. }
  660. digest_size = sizeof(digest);
  661. if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
  662. &digest_size)) {
  663. gnutls_x509_crt_deinit(cert);
  664. return 0;
  665. }
  666. gnutls_x509_crt_deinit(cert);
  667. #endif /* HAVE_LIBGNUTLS */
  668. assert(c->ssl_state.fingerprint == NULL);
  669. c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
  670. if (!c->ssl_state.fingerprint)
  671. return 0;
  672. for (i = 0; i < (int)digest_size; i++) {
  673. c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
  674. c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
  675. }
  676. c->ssl_state.fingerprint[i * 2] = '\0';
  677. return 1;
  678. }
  679. /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
  680. static int
  681. ConnectAccept( CONNECTION *c, bool connect)
  682. {
  683. int ret;
  684. #ifdef HAVE_LIBSSL
  685. SSL *ssl = c->ssl_state.ssl;
  686. assert(ssl != NULL);
  687. ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
  688. if (1 != ret)
  689. return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
  690. #endif
  691. #ifdef HAVE_LIBGNUTLS
  692. (void) connect;
  693. ret = gnutls_handshake(c->ssl_state.gnutls_session);
  694. if (ret)
  695. return ConnSSL_HandleError(c, ret, "gnutls_handshake");
  696. #endif /* _GNUTLS */
  697. (void)ConnSSL_InitCertFp(c);
  698. Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
  699. ConnSSL_LogCertInfo(c);
  700. Conn_StartLogin(CONNECTION2ID(c));
  701. return 1;
  702. }
  703. ssize_t
  704. ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
  705. {
  706. ssize_t bw;
  707. Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
  708. assert(count > 0);
  709. #ifdef HAVE_LIBSSL
  710. bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
  711. #endif
  712. #ifdef HAVE_LIBGNUTLS
  713. bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
  714. #endif
  715. if (bw > 0)
  716. return bw;
  717. if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
  718. errno = EAGAIN; /* try again */
  719. return -1;
  720. }
  721. ssize_t
  722. ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
  723. {
  724. ssize_t br;
  725. Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
  726. #ifdef HAVE_LIBSSL
  727. br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
  728. if (br > 0) /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
  729. return br;
  730. #endif
  731. #ifdef HAVE_LIBGNUTLS
  732. br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
  733. if (br >= 0) /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
  734. return br;
  735. #endif
  736. /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
  737. if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
  738. errno = EAGAIN;
  739. return -1;
  740. }
  741. return 0;
  742. }
  743. bool
  744. ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
  745. {
  746. #ifdef HAVE_LIBSSL
  747. char *nl;
  748. SSL *ssl = c->ssl_state.ssl;
  749. if (!ssl)
  750. return false;
  751. *buf = 0;
  752. SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
  753. nl = strchr(buf, '\n');
  754. if (nl)
  755. *nl = 0;
  756. return true;
  757. #endif
  758. #ifdef HAVE_LIBGNUTLS
  759. if (Conn_OPTION_ISSET(c, CONN_SSL)) {
  760. const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
  761. unsigned keysize;
  762. gnutls_session_t sess = c->ssl_state.gnutls_session;
  763. gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
  764. name_cipher = gnutls_cipher_get_name(cipher);
  765. name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
  766. keysize = gnutls_cipher_get_key_size(cipher) * 8;
  767. name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
  768. name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
  769. return snprintf(buf, len, "%s-%s%15s Kx=%s Enc=%s(%u) Mac=%s",
  770. name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
  771. }
  772. return false;
  773. #endif
  774. }
  775. char *
  776. ConnSSL_GetCertFp(CONNECTION *c)
  777. {
  778. return c->ssl_state.fingerprint;
  779. }
  780. bool
  781. ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
  782. {
  783. assert (c != NULL);
  784. c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
  785. return c->ssl_state.fingerprint != NULL;
  786. }
  787. #else
  788. bool
  789. ConnSSL_InitLibrary(void)
  790. {
  791. return true;
  792. }
  793. #endif /* SSL_SUPPORT */
  794. /* -eof- */