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.
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.
17 * SSL wrapper functions
34 #include "conn-func.h"
40 extern struct SSLOptions Conf_SSLOptions;
43 #include <openssl/err.h>
44 #include <openssl/rand.h>
45 #include <openssl/dh.h>
46 #include <openssl/x509v3.h>
48 static SSL_CTX * ssl_ctx;
51 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
52 static bool ConnSSL_SetVerifyProperties_openssl PARAMS((SSL_CTX * c));
55 #define MAX_CERT_CHAIN_LENGTH 10 /* XXX: do not hardcode */
58 #include <sys/types.h>
62 #include <gnutls/x509.h>
65 #define DH_BITS_MIN 1024
67 #define MAX_HASH_SIZE 64 /* from gnutls-int.h */
71 gnutls_certificate_credentials_t x509_cred;
72 gnutls_dh_params_t dh_params;
75 static array x509_creds = INIT_ARRAY;
76 static size_t x509_cred_idx;
78 static gnutls_dh_params_t dh_params;
79 static gnutls_priority_t priorities_cache = NULL;
80 static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
81 static bool ConnSSL_SetVerifyProperties_gnutls PARAMS((void));
84 #define SHA256_STRING_LEN (32 * 2 + 1)
86 static bool ConnSSL_Init_SSL PARAMS(( CONNECTION *c ));
87 static int ConnectAccept PARAMS(( CONNECTION *c, bool connect ));
88 static int ConnSSL_HandleError PARAMS(( CONNECTION *c, const int code, const char *fname ));
91 static char * openreadclose(const char *name, size_t *len)
96 int fd = open(name, O_RDONLY);
98 Log(LOG_ERR, "Could not open %s: %s", name, strerror(errno));
102 Log(LOG_ERR, "Could not fstat %s: %s", name, strerror(errno));
105 if (!S_ISREG(s.st_mode)) {
106 Log(LOG_ERR, "%s: Not a regular file", name);
109 if (s.st_size <= 0) {
110 Log(LOG_ERR, "%s: invalid file length (size %ld <= 0)", name, (long) s.st_size);
113 buf = malloc(s.st_size);
115 Log(LOG_ERR, "Could not malloc %lu bytes for file %s: %s", s.st_size, name, strerror(errno));
118 br = read(fd, buf, s.st_size);
119 if (br != (ssize_t)s.st_size) {
120 Log(LOG_ERR, "Could not read file %s: read returned %ld, expected %ld: %s",
121 name, (long) br, (long) s.st_size, br == -1 ? strerror(errno):"short read?!");
122 memset(buf, 0, s.st_size);
137 * Log OpenSSL error message.
139 * @param level The log level
140 * @param msg The error message.
141 * @param info Additional information text or NULL.
144 LogOpenSSL_CertInfo(int level, X509 * cert, const char *msg)
155 mem = BIO_new(BIO_s_mem());
158 X509_NAME_print_ex(mem, X509_get_subject_name(cert), 4,
160 X509_NAME_print_ex(mem, X509_get_issuer_name(cert), 4, XN_FLAG_ONELINE);
161 if (BIO_write(mem, "", 1) == 1) {
162 len = BIO_get_mem_data(mem, &memptr);
163 if (memptr && len > 0)
164 Log(level, "%s: \"%s\"", msg, memptr);
166 (void)BIO_set_close(mem, BIO_CLOSE);
171 LogOpenSSLError(const char *error, const char *info)
173 unsigned long err = ERR_get_error();
175 ? ERR_error_string(err, NULL)
176 : "Unable to determine error";
178 assert(error != NULL);
181 Log(LOG_ERR, "%s: %s (%s)", error, info, errmsg);
183 Log(LOG_ERR, "%s: %s", error, errmsg);
188 pem_passwd_cb(char *buf, int size, int rwflag, void *password)
190 array *pass = password;
193 (void)rwflag; /* rwflag is unused if DEBUG is not set. */
194 assert(rwflag == 0); /* 0 -> callback used for decryption.
195 * See SSL_CTX_set_default_passwd_cb(3) */
197 passlen = (int) array_bytes(pass);
199 LogDebug("pem_passwd_cb buf size %d, array size %d", size, passlen);
200 assert(passlen >= 0);
202 Log(LOG_ERR, "PEM password required but not set [in pem_passwd_cb()]!");
205 size = passlen > size ? size : passlen;
206 memcpy(buf, (char *)(array_start(pass)), size);
212 Verify_openssl(int preverify_ok, X509_STORE_CTX * ctx)
217 err = X509_STORE_CTX_get_error(ctx);
218 Log(LOG_ERR, "Certificate validation failed: %s",
219 X509_verify_cert_error_string(err));
233 if (!Conf_SSLOptions.DHFile) {
234 Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
237 fp = fopen(Conf_SSLOptions.DHFile, "r");
239 Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
242 dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
244 Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
245 Conf_SSLOptions.DHFile);
251 #ifdef HAVE_LIBGNUTLS
252 bool need_dhgenerate = true;
254 gnutls_dh_params_t tmp_dh_params;
256 err = gnutls_dh_params_init(&tmp_dh_params);
258 Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
259 gnutls_strerror(err));
262 if (Conf_SSLOptions.DHFile) {
263 gnutls_datum_t dhparms;
265 dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
268 err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
270 need_dhgenerate = false;
273 "Failed to initialize SSL DH parameters: %s",
274 gnutls_strerror(err));
276 memset(dhparms.data, 0, size);
280 if (need_dhgenerate) {
282 "DHFile not set, generating %u bit DH parameters. This may take a while ...",
284 err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
286 Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
287 gnutls_strerror(err));
291 dh_params = tmp_dh_params;
297 void ConnSSL_Free(CONNECTION *c)
300 SSL *ssl = c->ssl_state.ssl;
304 c->ssl_state.ssl = NULL;
305 if (c->ssl_state.fingerprint) {
306 free(c->ssl_state.fingerprint);
307 c->ssl_state.fingerprint = NULL;
311 #ifdef HAVE_LIBGNUTLS
312 gnutls_session_t sess = c->ssl_state.gnutls_session;
313 if (Conn_OPTION_ISSET(c, CONN_SSL)) {
314 gnutls_bye(sess, GNUTLS_SHUT_RDWR);
317 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), c->ssl_state.x509_cred_idx);
318 assert(slot != NULL);
319 assert(slot->refcnt > 0);
320 assert(slot->x509_cred != NULL);
322 if ((c->ssl_state.x509_cred_idx != x509_cred_idx) && (slot->refcnt <= 0)) {
323 LogDebug("Discarding X509 certificate credentials from slot %zd.",
324 c->ssl_state.x509_cred_idx);
325 gnutls_certificate_free_keys(slot->x509_cred);
326 gnutls_certificate_free_credentials(slot->x509_cred);
327 slot->x509_cred = NULL;
328 gnutls_dh_params_deinit(slot->dh_params);
329 slot->dh_params = NULL;
333 assert(Conn_OPTION_ISSET(c, CONN_SSL));
334 /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
335 Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
340 ConnSSL_InitLibrary( void )
342 if (!Conf_SSLInUse()) {
343 LogDebug("SSL not in use, skipping initialization.");
350 #if OPENSSL_API_COMPAT < 0x10100000L
353 SSL_load_error_strings();
357 if (!RAND_status()) {
358 Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
360 * it is probably best to fail and let the user install EGD or
361 * a similar program if no kernel random device is available.
362 * According to OpenSSL RAND_egd(3): "The automatic query of
363 * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
364 * so it makes little sense to deal with PRNGD seeding ourselves.
366 array_free(&Conf_SSLOptions.ListenPorts);
370 newctx = SSL_CTX_new(SSLv23_method());
372 LogOpenSSLError("Failed to create SSL context", NULL);
373 array_free(&Conf_SSLOptions.ListenPorts);
377 if (!ConnSSL_LoadServerKey_openssl(newctx)) {
378 /* Failed to read new key but an old ssl context
379 * already exists -> reuse old context */
381 SSL_CTX_free(newctx);
383 "Re-Initializing of SSL failed, using old keys!");
386 /* No preexisting old context -> error. */
390 if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
391 Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
392 Conf_SSLOptions.CipherList);
396 SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
397 if (!ConnSSL_SetVerifyProperties_openssl(newctx))
399 SSL_CTX_set_options(newctx,
400 SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2 |
401 SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
402 SSL_OP_NO_COMPRESSION);
403 SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
404 SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
406 SSL_CTX_free(ssl_ctx);
408 Log(LOG_INFO, "%s initialized.", OpenSSL_version(OPENSSL_VERSION));
411 SSL_CTX_free(newctx);
412 array_free(&Conf_SSLOptions.ListenPorts);
415 #ifdef HAVE_LIBGNUTLS
417 static bool initialized;
420 err = gnutls_global_init();
422 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
423 gnutls_strerror(err));
428 if (!ConnSSL_LoadServerKey_gnutls())
431 if (priorities_cache != NULL) {
432 gnutls_priority_deinit(priorities_cache);
434 if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
435 NULL) != GNUTLS_E_SUCCESS) {
437 "Failed to apply GnuTLS cipher list \"%s\"!",
438 Conf_SSLOptions.CipherList);
442 if (!ConnSSL_SetVerifyProperties_gnutls())
445 Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
449 array_free(&Conf_SSLOptions.ListenPorts);
455 #ifdef HAVE_LIBGNUTLS
457 ConnSSL_SetVerifyProperties_gnutls(void)
461 if (!Conf_SSLOptions.CAFile)
464 err = gnutls_certificate_set_x509_trust_file(x509_cred,
465 Conf_SSLOptions.CAFile,
466 GNUTLS_X509_FMT_PEM);
468 Log(LOG_ERR, "Failed to load x509 trust file %s: %s",
469 Conf_SSLOptions.CAFile, gnutls_strerror(err));
472 if (Conf_SSLOptions.CRLFile) {
474 gnutls_certificate_set_x509_crl_file(x509_cred,
475 Conf_SSLOptions.CRLFile,
476 GNUTLS_X509_FMT_PEM);
478 Log(LOG_ERR, "Failed to load x509 crl file %s: %s",
479 Conf_SSLOptions.CRLFile, gnutls_strerror(err));
488 ConnSSL_LoadServerKey_gnutls(void)
491 const char *cert_file;
493 x509_cred_slot *slot = NULL;
494 gnutls_certificate_credentials_t x509_cred;
496 err = gnutls_certificate_allocate_credentials(&x509_cred);
498 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
499 gnutls_strerror(err));
503 if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
505 "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
507 if (!Load_DH_params())
510 gnutls_certificate_set_dh_params(x509_cred, dh_params);
512 cert_file = Conf_SSLOptions.CertFile ?
513 Conf_SSLOptions.CertFile : Conf_SSLOptions.KeyFile;
514 if (Conf_SSLOptions.KeyFile) {
515 err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file,
516 Conf_SSLOptions.KeyFile,
517 GNUTLS_X509_FMT_PEM);
520 "Failed to set certificate key file (cert %s, key %s): %s",
522 Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
523 gnutls_strerror(err));
528 /* Free currently active x509 context (if any) unless it is still in use */
529 slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
530 if ((slot != NULL) && (slot->refcnt <= 0) && (slot->x509_cred != NULL)) {
531 LogDebug("Discarding X509 certificate credentials from slot %zd.",
533 gnutls_certificate_free_keys(slot->x509_cred);
534 gnutls_certificate_free_credentials(slot->x509_cred);
535 slot->x509_cred = NULL;
536 gnutls_dh_params_deinit(slot->dh_params);
537 slot->dh_params = NULL;
542 x509_cred_idx = (size_t) -1;
544 for (slot = array_start(&x509_creds), i = 0;
545 i < array_length(&x509_creds, sizeof(x509_cred_slot));
547 if (slot->refcnt <= 0) {
552 /* ... allocate new slot otherwise. */
553 if (x509_cred_idx == (size_t) -1) {
554 x509_cred_idx = array_length(&x509_creds, sizeof(x509_cred_slot));
555 slot = array_alloc(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
557 Log(LOG_ERR, "Failed to allocate new slot for certificate credentials");
561 Log(LOG_INFO, "Storing new X509 certificate credentials in slot %zd.", x509_cred_idx);
562 slot->x509_cred = x509_cred;
572 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
577 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
578 SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
580 if (!Conf_SSLOptions.KeyFile)
583 if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
584 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
585 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
589 cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
590 if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
591 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
592 LogOpenSSLError("Failed to load certificate chain", cert_key);
596 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
598 if (!SSL_CTX_check_private_key(ctx)) {
599 LogOpenSSLError("Server private key does not match certificate", NULL);
602 if (Load_DH_params()) {
603 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
604 LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
605 /* don't return false here: the non-DH modes will still work */
614 ConnSSL_SetVerifyProperties_openssl(SSL_CTX * ctx)
616 X509_STORE *store = NULL;
618 int verify_flags = SSL_VERIFY_PEER;
621 if (!Conf_SSLOptions.CAFile)
624 if (SSL_CTX_load_verify_locations(ctx, Conf_SSLOptions.CAFile, NULL) !=
626 LogOpenSSLError("SSL_CTX_load_verify_locations", NULL);
630 if (Conf_SSLOptions.CRLFile) {
631 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
632 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
633 SSL_CTX_set1_param(ctx, param);
635 store = SSL_CTX_get_cert_store(ctx);
637 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
639 LogOpenSSLError("X509_STORE_add_lookup",
640 Conf_SSLOptions.CRLFile);
644 if (X509_load_crl_file
645 (lookup, Conf_SSLOptions.CRLFile, X509_FILETYPE_PEM) != 1) {
646 LogOpenSSLError("X509_load_crl_file",
647 Conf_SSLOptions.CRLFile);
652 SSL_CTX_set_verify(ctx, verify_flags, Verify_openssl);
653 SSL_CTX_set_verify_depth(ctx, MAX_CERT_CHAIN_LENGTH);
656 if (Conf_SSLOptions.CRLFile)
657 free(Conf_SSLOptions.CRLFile);
658 Conf_SSLOptions.CRLFile = NULL;
665 ConnSSL_Init_SSL(CONNECTION *c)
669 LogDebug("Initializing SSL ...");
675 "Can't initialize SSL context, OpenSSL initialization failed at startup!");
678 assert(c->ssl_state.ssl == NULL);
679 assert(c->ssl_state.fingerprint == NULL);
681 c->ssl_state.ssl = SSL_new(ssl_ctx);
682 if (!c->ssl_state.ssl) {
683 LogOpenSSLError("Failed to create SSL structure", NULL);
686 Conn_OPTION_ADD(c, CONN_SSL);
688 ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
690 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
695 #ifdef HAVE_LIBGNUTLS
696 Conn_OPTION_ADD(c, CONN_SSL);
697 ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
698 if (ret != GNUTLS_E_SUCCESS) {
699 Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
700 gnutls_strerror(ret));
705 * The intermediate (long) cast is here to avoid a warning like:
706 * "cast to pointer from integer of different size" on 64-bit platforms.
707 * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
708 * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
710 gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
711 (gnutls_transport_ptr_t) (long) c->sock);
712 gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
713 GNUTLS_CERT_REQUEST);
715 LogDebug("Using X509 credentials from slot %zd.", x509_cred_idx);
716 c->ssl_state.x509_cred_idx = x509_cred_idx;
717 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
719 ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
720 GNUTLS_CRD_CERTIFICATE, slot->x509_cred);
722 Log(LOG_ERR, "Failed to set SSL credentials: %s",
723 gnutls_strerror(ret));
727 gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
734 ConnSSL_PrepareConnect(CONNECTION * c, CONF_SERVER * s)
737 #ifdef HAVE_LIBGNUTLS
740 err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
742 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
743 gnutls_strerror(err));
747 ret = ConnSSL_Init_SSL(c);
750 Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
752 assert(c->ssl_state.ssl);
754 X509_VERIFY_PARAM *param = NULL;
755 param = SSL_get0_param(c->ssl_state.ssl);
756 X509_VERIFY_PARAM_set_hostflags(param,
757 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
758 int err = X509_VERIFY_PARAM_set1_host(param, s->host, 0);
761 "Cannot set up hostname verification for '%s': %u",
765 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_PEER,
768 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
775 * Check and handle error return codes after failed calls to SSL functions.
778 * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
779 * SSL_write() on ssl.
782 * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
784 * @param c The connection handle.
785 * @prarm code The return code.
786 * @param fname The name of the function in which the error occurred.
787 * @return -1 on fatal errors, 0 if we can try again later.
790 ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
793 int ret = SSL_ERROR_SYSCALL;
794 unsigned long sslerr;
795 int real_errno = errno;
797 ret = SSL_get_error(c->ssl_state.ssl, code);
800 case SSL_ERROR_WANT_READ:
801 io_event_del(c->sock, IO_WANTWRITE);
802 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
803 return 0; /* try again later */
804 case SSL_ERROR_WANT_WRITE:
805 io_event_del(c->sock, IO_WANTREAD);
806 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
808 return 0; /* try again later */
809 case SSL_ERROR_ZERO_RETURN:
810 LogDebug("SSL connection shut down normally.");
812 case SSL_ERROR_SYSCALL:
813 /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
814 * and SSL_ERROR_WANT_X509_LOOKUP */
815 sslerr = ERR_get_error();
817 Log(LOG_ERR, "SSL error: %s [in %s()]!",
818 ERR_error_string(sslerr, NULL), fname);
820 switch (code) { /* EOF that violated protocol */
823 "SSL error, client disconnected [in %s()]!",
826 case -1: /* low level socket I/O error, check errno */
827 Log(LOG_ERR, "SSL error: %s [in %s()]!",
828 strerror(real_errno), fname);
833 LogOpenSSLError("SSL protocol error", fname);
836 Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
841 #ifdef HAVE_LIBGNUTLS
844 case GNUTLS_E_INTERRUPTED:
845 if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
846 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
847 io_event_del(c->sock, IO_WANTREAD);
849 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
850 io_event_del(c->sock, IO_WANTWRITE);
855 if (gnutls_error_is_fatal(code)) {
856 Log(LOG_ERR, "SSL error: %s [%s].",
857 gnutls_strerror(code), fname);
867 #ifdef HAVE_LIBGNUTLS
871 void *mem = malloc(s);
873 Log(LOG_ERR, "Out of memory: Could not allocate %lu byte",
880 LogGnuTLS_CertInfo(int level, gnutls_x509_crt_t cert, const char *msg)
882 char *dn, *issuer_dn;
884 int err = gnutls_x509_crt_get_dn(cert, NULL, &size);
886 Log(LOG_ERR, "gnutls_x509_crt_get_dn: size == 0");
889 if (err && err != GNUTLS_E_SHORT_MEMORY_BUFFER)
891 dn = LogMalloc(size);
894 err = gnutls_x509_crt_get_dn(cert, dn, &size);
897 gnutls_x509_crt_get_issuer_dn(cert, NULL, &size);
899 issuer_dn = LogMalloc(size);
901 Log(level, "%s: Distinguished Name: %s", msg, dn);
905 gnutls_x509_crt_get_issuer_dn(cert, issuer_dn, &size);
906 Log(level, "%s: Distinguished Name: \"%s\", Issuer \"%s\"", msg, dn,
913 Log(LOG_ERR, "gnutls_x509_crt_get_dn: %s", gnutls_strerror(err));
920 ConnSSL_LogCertInfo( CONNECTION * c, bool connect)
922 bool cert_seen = false, cert_ok = false;
925 const char *comp_alg = "no compression";
927 X509 *peer_cert = NULL;
928 SSL *ssl = c->ssl_state.ssl;
932 comp = SSL_get_current_compression(ssl);
934 comp_alg = SSL_COMP_get_name(comp);
935 Log(LOG_INFO, "Connection %d: initialized %s using cipher %s, %s.",
936 c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl), comp_alg);
937 peer_cert = SSL_get_peer_certificate(ssl);
938 if (peer_cert && connect) {
940 /* Client: Check server certificate */
941 int err = SSL_get_verify_result(ssl);
942 if (err == X509_V_OK) {
943 const char *peername = SSL_get0_peername(ssl);
944 if (peername != NULL)
946 LogDebug("X509_V_OK, peername = '%s'", peername);
948 Log(LOG_ERR, "Certificate validation failed: %s",
949 X509_verify_cert_error_string(err));
950 snprintf(msg, sizeof(msg), "%svalid peer certificate",
951 cert_ok ? "" : "in");
952 LogOpenSSL_CertInfo(cert_ok ? LOG_DEBUG : LOG_ERR, peer_cert,
955 X509_free(peer_cert);
958 #ifdef HAVE_LIBGNUTLS
960 gnutls_credentials_type_t cred;
961 gnutls_session_t sess = c->ssl_state.gnutls_session;
962 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
964 Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
966 gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
967 gnutls_cipher_get_name(cipher),
968 gnutls_mac_get_name(gnutls_mac_get(sess)));
969 cred = gnutls_auth_get_type(c->ssl_state.gnutls_session);
970 if (cred == GNUTLS_CRD_CERTIFICATE && connect) {
973 gnutls_certificate_verify_peers2(c->
974 ssl_state.gnutls_session,
978 "gnutls_certificate_verify_peers2 failed: %s",
979 gnutls_strerror(verify));
980 goto done_cn_validation;
984 if (gnutls_certificate_verification_status_print
985 (status, gnutls_certificate_type_get(sess), &out,
986 0) == GNUTLS_E_SUCCESS) {
988 "Certificate validation failed: %s",
990 gnutls_free(out.data);
994 gnutls_x509_crt_t cert;
995 unsigned cert_list_size;
996 const gnutls_datum_t *cert_list =
997 gnutls_certificate_get_peers(sess, &cert_list_size);
998 if (!cert_list || cert_list_size == 0) {
999 Log(LOG_ERR, "No certificates found");
1000 goto done_cn_validation;
1002 int err = gnutls_x509_crt_init(&cert);
1005 "Failed to initialize x509 certificate: %s",
1006 gnutls_strerror(err));
1007 goto done_cn_validation;
1009 err = gnutls_x509_crt_import(cert, cert_list,
1010 GNUTLS_X509_FMT_DER);
1012 Log(LOG_ERR, "Failed to parse the certificate: %s",
1013 gnutls_strerror(err));
1014 goto done_cn_validation;
1016 err = gnutls_x509_crt_check_hostname(cert, c->host);
1019 "Failed to verify the hostname, expected \"%s\"",
1022 cert_ok = verify == 0 && status == 0;
1024 snprintf(msg, sizeof(msg), "%svalid peer certificate",
1025 cert_ok ? "" : "in");
1026 LogGnuTLS_CertInfo(cert_ok ? LOG_DEBUG : LOG_ERR, cert, msg);
1028 gnutls_x509_crt_deinit(cert);
1034 * can be used later to check if connection was authenticated, e.g.
1035 * if inbound connection tries to register itself as server.
1036 * Could also restrict /OPER to authenticated connections, etc.
1039 Conn_OPTION_ADD(c, CONN_SSL_PEERCERT_OK);
1041 Log(LOG_INFO, "Peer did not present a certificate");
1046 Accept incoming SSL connection.
1048 1: SSL Connection established
1050 -1: SSL Connection not established due to fatal error.
1053 ConnSSL_Accept( CONNECTION *c )
1056 if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
1057 #ifdef HAVE_LIBGNUTLS
1058 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
1060 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
1061 gnutls_strerror(err));
1065 if (!ConnSSL_Init_SSL(c))
1068 return ConnectAccept(c, false );
1073 ConnSSL_Connect( CONNECTION *c )
1077 assert(c->ssl_state.ssl);
1079 assert(Conn_OPTION_ISSET(c, CONN_SSL));
1080 return ConnectAccept(c, true);
1084 ConnSSL_InitCertFp( CONNECTION *c )
1086 const char hex[] = "0123456789abcdef";
1090 unsigned char digest[EVP_MAX_MD_SIZE];
1091 unsigned int digest_size;
1094 cert = SSL_get_peer_certificate(c->ssl_state.ssl);
1098 if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
1104 #endif /* HAVE_LIBSSL */
1105 #ifdef HAVE_LIBGNUTLS
1106 gnutls_x509_crt_t cert;
1107 unsigned int cert_list_size;
1108 const gnutls_datum_t *cert_list;
1109 unsigned char digest[MAX_HASH_SIZE];
1112 if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
1116 if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
1120 cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
1123 gnutls_x509_crt_deinit(cert);
1127 if (gnutls_x509_crt_import(cert, &cert_list[0],
1128 GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
1129 gnutls_x509_crt_deinit(cert);
1133 digest_size = sizeof(digest);
1134 if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
1136 gnutls_x509_crt_deinit(cert);
1140 gnutls_x509_crt_deinit(cert);
1141 #endif /* HAVE_LIBGNUTLS */
1143 assert(c->ssl_state.fingerprint == NULL);
1145 c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
1146 if (!c->ssl_state.fingerprint)
1149 for (i = 0; i < (int)digest_size; i++) {
1150 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
1151 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
1153 c->ssl_state.fingerprint[i * 2] = '\0';
1158 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
1160 ConnectAccept( CONNECTION *c, bool connect)
1164 SSL *ssl = c->ssl_state.ssl;
1165 assert(ssl != NULL);
1167 ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
1169 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
1171 #ifdef HAVE_LIBGNUTLS
1173 ret = gnutls_handshake(c->ssl_state.gnutls_session);
1175 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
1176 #endif /* _GNUTLS */
1177 (void)ConnSSL_InitCertFp(c);
1179 Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
1180 ConnSSL_LogCertInfo(c, connect);
1182 Conn_StartLogin(CONNECTION2ID(c));
1188 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
1192 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1196 bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
1198 #ifdef HAVE_LIBGNUTLS
1199 bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
1203 if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
1204 errno = EAGAIN; /* try again */
1210 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
1214 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1216 br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
1217 if (br > 0) /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
1220 #ifdef HAVE_LIBGNUTLS
1221 br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
1222 if (br >= 0) /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
1225 /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
1226 if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
1235 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
1239 SSL *ssl = c->ssl_state.ssl;
1244 SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
1245 nl = strchr(buf, '\n');
1250 #ifdef HAVE_LIBGNUTLS
1251 if (Conn_OPTION_ISSET(c, CONN_SSL)) {
1252 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
1255 gnutls_session_t sess = c->ssl_state.gnutls_session;
1256 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
1257 name_cipher = gnutls_cipher_get_name(cipher);
1258 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
1259 keysize = gnutls_cipher_get_key_size(cipher) * 8;
1260 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
1261 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
1263 return snprintf(buf, len, "%s-%s%15s Kx=%s Enc=%s(%u) Mac=%s",
1264 name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
1271 ConnSSL_GetCertFp(CONNECTION *c)
1273 return c->ssl_state.fingerprint;
1277 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
1280 c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
1281 return c->ssl_state.fingerprint != NULL;
1286 ConnSSL_InitLibrary(void)
1291 #endif /* SSL_SUPPORT */