conn-ssl.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 (!ssl_ctx) {
  247. SSL_library_init();
  248. SSL_load_error_strings();
  249. }
  250. if (!RAND_status()) {
  251. Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
  252. /*
  253. * it is probably best to fail and let the user install EGD or
  254. * a similar program if no kernel random device is available.
  255. * According to OpenSSL RAND_egd(3): "The automatic query of
  256. * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
  257. * so it makes little sense to deal with PRNGD seeding ourselves.
  258. */
  259. array_free(&Conf_SSLOptions.ListenPorts);
  260. return false;
  261. }
  262. newctx = SSL_CTX_new(SSLv23_method());
  263. if (!newctx) {
  264. LogOpenSSLError("Failed to create SSL context", NULL);
  265. array_free(&Conf_SSLOptions.ListenPorts);
  266. return false;
  267. }
  268. if (!ConnSSL_LoadServerKey_openssl(newctx))
  269. goto out;
  270. if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
  271. Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
  272. Conf_SSLOptions.CipherList);
  273. goto out;
  274. }
  275. SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
  276. SSL_CTX_set_options(newctx, SSL_OP_SINGLE_DH_USE|SSL_OP_NO_SSLv2);
  277. SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
  278. SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
  279. Verify_openssl);
  280. SSL_CTX_free(ssl_ctx);
  281. ssl_ctx = newctx;
  282. Log(LOG_INFO, "%s initialized.", SSLeay_version(SSLEAY_VERSION));
  283. return true;
  284. out:
  285. SSL_CTX_free(newctx);
  286. array_free(&Conf_SSLOptions.ListenPorts);
  287. return false;
  288. #endif
  289. #ifdef HAVE_LIBGNUTLS
  290. int err;
  291. static bool initialized;
  292. if (initialized) {
  293. /* TODO: cannot reload gnutls keys: can't simply free x509
  294. * context -- it may still be in use */
  295. return false;
  296. }
  297. err = gnutls_global_init();
  298. if (err) {
  299. Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
  300. gnutls_strerror(err));
  301. goto out;
  302. }
  303. if (!ConnSSL_LoadServerKey_gnutls())
  304. goto out;
  305. if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
  306. NULL) != GNUTLS_E_SUCCESS) {
  307. Log(LOG_ERR,
  308. "Failed to apply GnuTLS cipher list \"%s\"!",
  309. Conf_SSLOptions.CipherList);
  310. goto out;
  311. }
  312. Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
  313. initialized = true;
  314. return true;
  315. out:
  316. array_free(&Conf_SSLOptions.ListenPorts);
  317. return false;
  318. #endif
  319. }
  320. #ifdef HAVE_LIBGNUTLS
  321. static bool
  322. ConnSSL_LoadServerKey_gnutls(void)
  323. {
  324. int err;
  325. const char *cert_file;
  326. err = gnutls_certificate_allocate_credentials(&x509_cred);
  327. if (err < 0) {
  328. Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
  329. gnutls_strerror(err));
  330. return false;
  331. }
  332. cert_file = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
  333. if (!cert_file) {
  334. Log(LOG_ERR, "No SSL server key configured!");
  335. return false;
  336. }
  337. if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
  338. Log(LOG_WARNING,
  339. "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
  340. if (!Load_DH_params())
  341. return false;
  342. gnutls_certificate_set_dh_params(x509_cred, dh_params);
  343. err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file, Conf_SSLOptions.KeyFile, GNUTLS_X509_FMT_PEM);
  344. if (err < 0) {
  345. Log(LOG_ERR,
  346. "Failed to set certificate key file (cert %s, key %s): %s",
  347. cert_file,
  348. Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
  349. gnutls_strerror(err));
  350. return false;
  351. }
  352. return true;
  353. }
  354. #endif
  355. #ifdef HAVE_LIBSSL
  356. static bool
  357. ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
  358. {
  359. char *cert_key;
  360. assert(ctx);
  361. if (!Conf_SSLOptions.KeyFile) {
  362. Log(LOG_ERR, "No SSL server key configured!");
  363. return false;
  364. }
  365. SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
  366. SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
  367. if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
  368. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  369. LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
  370. return false;
  371. }
  372. cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
  373. if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
  374. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  375. LogOpenSSLError("Failed to load certificate chain", cert_key);
  376. return false;
  377. }
  378. array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
  379. if (!SSL_CTX_check_private_key(ctx)) {
  380. LogOpenSSLError("Server private key does not match certificate", NULL);
  381. return false;
  382. }
  383. if (Load_DH_params()) {
  384. if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
  385. LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
  386. /* don't return false here: the non-DH modes will still work */
  387. DH_free(dh_params);
  388. dh_params = NULL;
  389. }
  390. return true;
  391. }
  392. #endif
  393. static bool
  394. ConnSSL_Init_SSL(CONNECTION *c)
  395. {
  396. int ret;
  397. LogDebug("Initializing SSL ...");
  398. assert(c != NULL);
  399. #ifdef HAVE_LIBSSL
  400. if (!ssl_ctx) {
  401. Log(LOG_ERR,
  402. "Can't initialize SSL context, OpenSSL initialization failed at startup!");
  403. return false;
  404. }
  405. assert(c->ssl_state.ssl == NULL);
  406. assert(c->ssl_state.fingerprint == NULL);
  407. c->ssl_state.ssl = SSL_new(ssl_ctx);
  408. if (!c->ssl_state.ssl) {
  409. LogOpenSSLError("Failed to create SSL structure", NULL);
  410. return false;
  411. }
  412. Conn_OPTION_ADD(c, CONN_SSL);
  413. ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
  414. if (ret != 1) {
  415. LogOpenSSLError("Failed to set SSL file descriptor", NULL);
  416. ConnSSL_Free(c);
  417. return false;
  418. }
  419. #endif
  420. #ifdef HAVE_LIBGNUTLS
  421. Conn_OPTION_ADD(c, CONN_SSL);
  422. ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
  423. if (ret != GNUTLS_E_SUCCESS) {
  424. Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
  425. gnutls_strerror(ret));
  426. ConnSSL_Free(c);
  427. return false;
  428. }
  429. /*
  430. * The intermediate (long) cast is here to avoid a warning like:
  431. * "cast to pointer from integer of different size" on 64-bit platforms.
  432. * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
  433. * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
  434. */
  435. gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
  436. (gnutls_transport_ptr_t) (long) c->sock);
  437. gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
  438. GNUTLS_CERT_REQUEST);
  439. ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
  440. GNUTLS_CRD_CERTIFICATE, x509_cred);
  441. if (ret != 0) {
  442. Log(LOG_ERR, "Failed to set SSL credentials: %s",
  443. gnutls_strerror(ret));
  444. ConnSSL_Free(c);
  445. return false;
  446. }
  447. gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
  448. #endif
  449. return true;
  450. }
  451. bool
  452. ConnSSL_PrepareConnect(CONNECTION *c, UNUSED CONF_SERVER *s)
  453. {
  454. bool ret;
  455. #ifdef HAVE_LIBGNUTLS
  456. int err;
  457. err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
  458. if (err) {
  459. Log(LOG_ERR, "Failed to initialize new SSL session: %s",
  460. gnutls_strerror(err));
  461. return false;
  462. }
  463. #endif
  464. ret = ConnSSL_Init_SSL(c);
  465. if (!ret)
  466. return false;
  467. Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
  468. #ifdef HAVE_LIBSSL
  469. assert(c->ssl_state.ssl);
  470. SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
  471. #endif
  472. return true;
  473. }
  474. /**
  475. * Check and handle error return codes after failed calls to SSL functions.
  476. *
  477. * OpenSSL:
  478. * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
  479. * SSL_write() on ssl.
  480. *
  481. * GnuTLS:
  482. * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
  483. *
  484. * @param c The connection handle.
  485. * @prarm code The return code.
  486. * @param fname The name of the function in which the error occurred.
  487. * @return -1 on fatal errors, 0 if we can try again later.
  488. */
  489. static int
  490. ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
  491. {
  492. #ifdef HAVE_LIBSSL
  493. int ret = SSL_ERROR_SYSCALL;
  494. unsigned long sslerr;
  495. int real_errno = errno;
  496. ret = SSL_get_error(c->ssl_state.ssl, code);
  497. switch (ret) {
  498. case SSL_ERROR_WANT_READ:
  499. io_event_del(c->sock, IO_WANTWRITE);
  500. Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
  501. return 0; /* try again later */
  502. case SSL_ERROR_WANT_WRITE:
  503. io_event_del(c->sock, IO_WANTREAD);
  504. Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
  505. case SSL_ERROR_NONE:
  506. return 0; /* try again later */
  507. case SSL_ERROR_ZERO_RETURN:
  508. LogDebug("SSL connection shut down normally.");
  509. break;
  510. case SSL_ERROR_SYSCALL:
  511. /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
  512. * and SSL_ERROR_WANT_X509_LOOKUP */
  513. sslerr = ERR_get_error();
  514. if (sslerr) {
  515. Log(LOG_ERR, "SSL error: %s [in %s()]!",
  516. ERR_error_string(sslerr, NULL), fname);
  517. } else {
  518. switch (code) { /* EOF that violated protocol */
  519. case 0:
  520. Log(LOG_ERR,
  521. "SSL error, client disconnected [in %s()]!",
  522. fname);
  523. break;
  524. case -1: /* low level socket I/O error, check errno */
  525. Log(LOG_ERR, "SSL error: %s [in %s()]!",
  526. strerror(real_errno), fname);
  527. }
  528. }
  529. break;
  530. case SSL_ERROR_SSL:
  531. LogOpenSSLError("SSL protocol error", fname);
  532. break;
  533. default:
  534. Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
  535. }
  536. ConnSSL_Free(c);
  537. return -1;
  538. #endif
  539. #ifdef HAVE_LIBGNUTLS
  540. switch (code) {
  541. case GNUTLS_E_AGAIN:
  542. case GNUTLS_E_INTERRUPTED:
  543. if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
  544. Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
  545. io_event_del(c->sock, IO_WANTREAD);
  546. } else {
  547. Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
  548. io_event_del(c->sock, IO_WANTWRITE);
  549. }
  550. break;
  551. default:
  552. assert(code < 0);
  553. if (gnutls_error_is_fatal(code)) {
  554. Log(LOG_ERR, "SSL error: %s [%s].",
  555. gnutls_strerror(code), fname);
  556. ConnSSL_Free(c);
  557. return -1;
  558. }
  559. }
  560. return 0;
  561. #endif
  562. }
  563. static void
  564. ConnSSL_LogCertInfo( CONNECTION *c )
  565. {
  566. #ifdef HAVE_LIBSSL
  567. SSL *ssl = c->ssl_state.ssl;
  568. assert(ssl);
  569. Log(LOG_INFO, "Connection %d: initialized %s using cipher %s.",
  570. c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl));
  571. #endif
  572. #ifdef HAVE_LIBGNUTLS
  573. gnutls_session_t sess = c->ssl_state.gnutls_session;
  574. gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
  575. Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
  576. c->sock,
  577. gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
  578. gnutls_cipher_get_name(cipher),
  579. gnutls_mac_get_name(gnutls_mac_get(sess)));
  580. #endif
  581. }
  582. /*
  583. Accept incoming SSL connection.
  584. Return Values:
  585. 1: SSL Connection established
  586. 0: try again
  587. -1: SSL Connection not established due to fatal error.
  588. */
  589. int
  590. ConnSSL_Accept( CONNECTION *c )
  591. {
  592. assert(c != NULL);
  593. if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
  594. #ifdef HAVE_LIBGNUTLS
  595. int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
  596. if (err) {
  597. Log(LOG_ERR, "Failed to initialize new SSL session: %s",
  598. gnutls_strerror(err));
  599. return false;
  600. }
  601. #endif
  602. if (!ConnSSL_Init_SSL(c))
  603. return -1;
  604. }
  605. return ConnectAccept(c, false );
  606. }
  607. int
  608. ConnSSL_Connect( CONNECTION *c )
  609. {
  610. assert(c != NULL);
  611. #ifdef HAVE_LIBSSL
  612. assert(c->ssl_state.ssl);
  613. #endif
  614. assert(Conn_OPTION_ISSET(c, CONN_SSL));
  615. return ConnectAccept(c, true);
  616. }
  617. static int
  618. ConnSSL_InitCertFp( CONNECTION *c )
  619. {
  620. const char hex[] = "0123456789abcdef";
  621. int i;
  622. #ifdef HAVE_LIBSSL
  623. unsigned char digest[EVP_MAX_MD_SIZE];
  624. unsigned int digest_size;
  625. X509 *cert;
  626. cert = SSL_get_peer_certificate(c->ssl_state.ssl);
  627. if (!cert)
  628. return 0;
  629. if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
  630. X509_free(cert);
  631. return 0;
  632. }
  633. X509_free(cert);
  634. #endif /* HAVE_LIBSSL */
  635. #ifdef HAVE_LIBGNUTLS
  636. gnutls_x509_crt_t cert;
  637. unsigned int cert_list_size;
  638. const gnutls_datum_t *cert_list;
  639. unsigned char digest[MAX_HASH_SIZE];
  640. size_t digest_size;
  641. if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
  642. GNUTLS_CRT_X509)
  643. return 0;
  644. if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
  645. return 0;
  646. cert_list_size = 0;
  647. cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
  648. &cert_list_size);
  649. if (!cert_list) {
  650. gnutls_x509_crt_deinit(cert);
  651. return 0;
  652. }
  653. if (gnutls_x509_crt_import(cert, &cert_list[0],
  654. GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
  655. gnutls_x509_crt_deinit(cert);
  656. return 0;
  657. }
  658. digest_size = sizeof(digest);
  659. if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
  660. &digest_size)) {
  661. gnutls_x509_crt_deinit(cert);
  662. return 0;
  663. }
  664. gnutls_x509_crt_deinit(cert);
  665. #endif /* HAVE_LIBGNUTLS */
  666. assert(c->ssl_state.fingerprint == NULL);
  667. c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
  668. if (!c->ssl_state.fingerprint)
  669. return 0;
  670. for (i = 0; i < (int)digest_size; i++) {
  671. c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
  672. c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
  673. }
  674. c->ssl_state.fingerprint[i * 2] = '\0';
  675. return 1;
  676. }
  677. /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
  678. static int
  679. ConnectAccept( CONNECTION *c, bool connect)
  680. {
  681. int ret;
  682. #ifdef HAVE_LIBSSL
  683. SSL *ssl = c->ssl_state.ssl;
  684. assert(ssl != NULL);
  685. ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
  686. if (1 != ret)
  687. return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
  688. #endif
  689. #ifdef HAVE_LIBGNUTLS
  690. (void) connect;
  691. ret = gnutls_handshake(c->ssl_state.gnutls_session);
  692. if (ret)
  693. return ConnSSL_HandleError(c, ret, "gnutls_handshake");
  694. #endif /* _GNUTLS */
  695. (void)ConnSSL_InitCertFp(c);
  696. Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
  697. ConnSSL_LogCertInfo(c);
  698. Conn_StartLogin(CONNECTION2ID(c));
  699. return 1;
  700. }
  701. ssize_t
  702. ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
  703. {
  704. ssize_t bw;
  705. Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
  706. assert(count > 0);
  707. #ifdef HAVE_LIBSSL
  708. bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
  709. #endif
  710. #ifdef HAVE_LIBGNUTLS
  711. bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
  712. #endif
  713. if (bw > 0)
  714. return bw;
  715. if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
  716. errno = EAGAIN; /* try again */
  717. return -1;
  718. }
  719. ssize_t
  720. ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
  721. {
  722. ssize_t br;
  723. Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
  724. #ifdef HAVE_LIBSSL
  725. br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
  726. if (br > 0) /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
  727. return br;
  728. #endif
  729. #ifdef HAVE_LIBGNUTLS
  730. br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
  731. if (br >= 0) /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
  732. return br;
  733. #endif
  734. /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
  735. if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
  736. errno = EAGAIN;
  737. return -1;
  738. }
  739. return 0;
  740. }
  741. bool
  742. ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
  743. {
  744. #ifdef HAVE_LIBSSL
  745. char *nl;
  746. SSL *ssl = c->ssl_state.ssl;
  747. if (!ssl)
  748. return false;
  749. *buf = 0;
  750. SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
  751. nl = strchr(buf, '\n');
  752. if (nl)
  753. *nl = 0;
  754. return true;
  755. #endif
  756. #ifdef HAVE_LIBGNUTLS
  757. if (Conn_OPTION_ISSET(c, CONN_SSL)) {
  758. const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
  759. unsigned keysize;
  760. gnutls_session_t sess = c->ssl_state.gnutls_session;
  761. gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
  762. name_cipher = gnutls_cipher_get_name(cipher);
  763. name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
  764. keysize = gnutls_cipher_get_key_size(cipher) * 8;
  765. name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
  766. name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
  767. return snprintf(buf, len, "%s-%s%15s Kx=%s Enc=%s(%u) Mac=%s",
  768. name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
  769. }
  770. return false;
  771. #endif
  772. }
  773. char *
  774. ConnSSL_GetCertFp(CONNECTION *c)
  775. {
  776. return c->ssl_state.fingerprint;
  777. }
  778. bool
  779. ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
  780. {
  781. assert (c != NULL);
  782. c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
  783. return c->ssl_state.fingerprint != NULL;
  784. }
  785. #else
  786. bool
  787. ConnSSL_InitLibrary(void)
  788. {
  789. return true;
  790. }
  791. #endif /* SSL_SUPPORT */
  792. /* -eof- */