conn-ssl.c 22 KB

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