conn-ssl.c 22 KB

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