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 #define MAX_CERT_CHAIN_LENGTH 10 /* XXX: do not hardcode */
50 static SSL_CTX * ssl_ctx;
53 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
54 static bool ConnSSL_SetVerifyProperties_openssl PARAMS((SSL_CTX * c));
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), 0,
160 X509_NAME_print_ex(mem, X509_get_issuer_name(cert), 2, 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)
216 int err = X509_STORE_CTX_get_error(ctx);
217 LogDebug("Certificate validation failed: %s",
218 X509_verify_cert_error_string(err));
225 /* Always(!) return success as we have to deal with invalid
226 * (self-signed, expired, ...) client certificates and with invalid
227 * server certificates when "SSLVerify" is disabled, which we don't
228 * know at this stage. Therefore we postpone this check, it will be
229 * (and has to be!) handled in cb_connserver_login_ssl(). */
242 if (!Conf_SSLOptions.DHFile) {
243 Log(LOG_NOTICE, "Configuration option \"DHFile\" not set!");
246 fp = fopen(Conf_SSLOptions.DHFile, "r");
248 Log(LOG_ERR, "%s: %s", Conf_SSLOptions.DHFile, strerror(errno));
251 dh_params = PEM_read_DHparams(fp, NULL, NULL, NULL);
253 Log(LOG_ERR, "%s: Failed to read SSL DH parameters!",
254 Conf_SSLOptions.DHFile);
260 #ifdef HAVE_LIBGNUTLS
261 bool need_dhgenerate = true;
263 gnutls_dh_params_t tmp_dh_params;
265 err = gnutls_dh_params_init(&tmp_dh_params);
267 Log(LOG_ERR, "Failed to initialize SSL DH parameters: %s",
268 gnutls_strerror(err));
271 if (Conf_SSLOptions.DHFile) {
272 gnutls_datum_t dhparms;
274 dhparms.data = (unsigned char *) openreadclose(Conf_SSLOptions.DHFile, &size);
277 err = gnutls_dh_params_import_pkcs3(tmp_dh_params, &dhparms, GNUTLS_X509_FMT_PEM);
279 need_dhgenerate = false;
282 "Failed to initialize SSL DH parameters: %s",
283 gnutls_strerror(err));
285 memset(dhparms.data, 0, size);
289 if (need_dhgenerate) {
291 "DHFile not set, generating %u bit DH parameters. This may take a while ...",
293 err = gnutls_dh_params_generate2(tmp_dh_params, DH_BITS);
295 Log(LOG_ERR, "Failed to generate SSL DH parameters: %s",
296 gnutls_strerror(err));
300 dh_params = tmp_dh_params;
306 void ConnSSL_Free(CONNECTION *c)
309 SSL *ssl = c->ssl_state.ssl;
313 c->ssl_state.ssl = NULL;
314 if (c->ssl_state.fingerprint) {
315 free(c->ssl_state.fingerprint);
316 c->ssl_state.fingerprint = NULL;
320 #ifdef HAVE_LIBGNUTLS
321 gnutls_session_t sess = c->ssl_state.gnutls_session;
322 if (Conn_OPTION_ISSET(c, CONN_SSL)) {
323 gnutls_bye(sess, GNUTLS_SHUT_RDWR);
326 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), c->ssl_state.x509_cred_idx);
327 assert(slot != NULL);
328 assert(slot->refcnt > 0);
329 assert(slot->x509_cred != NULL);
331 if ((c->ssl_state.x509_cred_idx != x509_cred_idx) && (slot->refcnt <= 0)) {
332 LogDebug("Discarding X509 certificate credentials from slot %zd.",
333 c->ssl_state.x509_cred_idx);
334 gnutls_certificate_free_keys(slot->x509_cred);
335 gnutls_certificate_free_credentials(slot->x509_cred);
336 slot->x509_cred = NULL;
337 gnutls_dh_params_deinit(slot->dh_params);
338 slot->dh_params = NULL;
342 assert(Conn_OPTION_ISSET(c, CONN_SSL));
343 /* can't just set bitmask to 0 -- there are other, non-ssl related flags, e.g. CONN_ZIP. */
344 Conn_OPTION_DEL(c, CONN_SSL_FLAGS_ALL);
349 ConnSSL_InitLibrary( void )
351 if (!Conf_SSLInUse()) {
352 LogDebug("SSL not in use, skipping initialization.");
359 #if OPENSSL_API_COMPAT < 0x10100000L
362 SSL_load_error_strings();
366 if (!RAND_status()) {
367 Log(LOG_ERR, "OpenSSL PRNG not seeded: /dev/urandom missing?");
369 * it is probably best to fail and let the user install EGD or
370 * a similar program if no kernel random device is available.
371 * According to OpenSSL RAND_egd(3): "The automatic query of
372 * /var/run/egd-pool et al was added in OpenSSL 0.9.7";
373 * so it makes little sense to deal with PRNGD seeding ourselves.
375 array_free(&Conf_SSLOptions.ListenPorts);
379 newctx = SSL_CTX_new(SSLv23_method());
381 LogOpenSSLError("Failed to create SSL context", NULL);
382 array_free(&Conf_SSLOptions.ListenPorts);
386 if (!ConnSSL_LoadServerKey_openssl(newctx)) {
387 /* Failed to read new key but an old ssl context
388 * already exists -> reuse old context */
390 SSL_CTX_free(newctx);
392 "Re-Initializing of SSL failed, using old keys!");
395 /* No preexisting old context -> error. */
399 if (SSL_CTX_set_cipher_list(newctx, Conf_SSLOptions.CipherList) == 0) {
400 Log(LOG_ERR, "Failed to apply OpenSSL cipher list \"%s\"!",
401 Conf_SSLOptions.CipherList);
405 SSL_CTX_set_session_id_context(newctx, (unsigned char *)"ngircd", 6);
406 if (!ConnSSL_SetVerifyProperties_openssl(newctx))
408 SSL_CTX_set_options(newctx,
409 SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2 |
410 SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
411 SSL_OP_NO_COMPRESSION);
412 SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
413 SSL_CTX_free(ssl_ctx);
415 Log(LOG_INFO, "%s initialized.", OpenSSL_version(OPENSSL_VERSION));
418 SSL_CTX_free(newctx);
419 array_free(&Conf_SSLOptions.ListenPorts);
422 #ifdef HAVE_LIBGNUTLS
424 static bool initialized;
427 err = gnutls_global_init();
429 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
430 gnutls_strerror(err));
435 if (!ConnSSL_LoadServerKey_gnutls())
438 if (priorities_cache != NULL) {
439 gnutls_priority_deinit(priorities_cache);
441 if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
442 NULL) != GNUTLS_E_SUCCESS) {
444 "Failed to apply GnuTLS cipher list \"%s\"!",
445 Conf_SSLOptions.CipherList);
449 if (!ConnSSL_SetVerifyProperties_gnutls())
452 Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
456 array_free(&Conf_SSLOptions.ListenPorts);
462 #ifdef HAVE_LIBGNUTLS
464 ConnSSL_SetVerifyProperties_gnutls(void)
468 if (!Conf_SSLOptions.CAFile)
471 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
472 gnutls_certificate_credentials_t x509_cred = slot->x509_cred;
474 err = gnutls_certificate_set_x509_trust_file(x509_cred,
475 Conf_SSLOptions.CAFile,
476 GNUTLS_X509_FMT_PEM);
478 Log(LOG_ERR, "Failed to load x509 trust file %s: %s",
479 Conf_SSLOptions.CAFile, gnutls_strerror(err));
482 if (Conf_SSLOptions.CRLFile) {
484 gnutls_certificate_set_x509_crl_file(x509_cred,
485 Conf_SSLOptions.CRLFile,
486 GNUTLS_X509_FMT_PEM);
488 Log(LOG_ERR, "Failed to load x509 crl file %s: %s",
489 Conf_SSLOptions.CRLFile, gnutls_strerror(err));
498 ConnSSL_LoadServerKey_gnutls(void)
501 const char *cert_file;
503 x509_cred_slot *slot = NULL;
504 gnutls_certificate_credentials_t x509_cred;
506 err = gnutls_certificate_allocate_credentials(&x509_cred);
508 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
509 gnutls_strerror(err));
513 if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
515 "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
517 if (!Load_DH_params())
520 gnutls_certificate_set_dh_params(x509_cred, dh_params);
522 cert_file = Conf_SSLOptions.CertFile ?
523 Conf_SSLOptions.CertFile : Conf_SSLOptions.KeyFile;
524 if (Conf_SSLOptions.KeyFile) {
525 err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file,
526 Conf_SSLOptions.KeyFile,
527 GNUTLS_X509_FMT_PEM);
530 "Failed to set certificate key file (cert %s, key %s): %s",
532 Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
533 gnutls_strerror(err));
538 /* Free currently active x509 context (if any) unless it is still in use */
539 slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
540 if ((slot != NULL) && (slot->refcnt <= 0) && (slot->x509_cred != NULL)) {
541 LogDebug("Discarding X509 certificate credentials from slot %zd.",
543 gnutls_certificate_free_keys(slot->x509_cred);
544 gnutls_certificate_free_credentials(slot->x509_cred);
545 slot->x509_cred = NULL;
546 gnutls_dh_params_deinit(slot->dh_params);
547 slot->dh_params = NULL;
552 x509_cred_idx = (size_t) -1;
554 for (slot = array_start(&x509_creds), i = 0;
555 i < array_length(&x509_creds, sizeof(x509_cred_slot));
557 if (slot->refcnt <= 0) {
562 /* ... allocate new slot otherwise. */
563 if (x509_cred_idx == (size_t) -1) {
564 x509_cred_idx = array_length(&x509_creds, sizeof(x509_cred_slot));
565 slot = array_alloc(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
567 Log(LOG_ERR, "Failed to allocate new slot for certificate credentials");
571 Log(LOG_INFO, "Storing new X509 certificate credentials in slot %zd.", x509_cred_idx);
572 slot->x509_cred = x509_cred;
582 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
587 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
588 SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
590 if (!Conf_SSLOptions.KeyFile)
593 if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
594 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
595 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
599 cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
600 if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
601 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
602 LogOpenSSLError("Failed to load certificate chain", cert_key);
606 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
608 if (!SSL_CTX_check_private_key(ctx)) {
609 LogOpenSSLError("Server private key does not match certificate", NULL);
612 if (Load_DH_params()) {
613 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
614 LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
615 /* don't return false here: the non-DH modes will still work */
624 ConnSSL_SetVerifyProperties_openssl(SSL_CTX * ctx)
626 X509_STORE *store = NULL;
630 if (!Conf_SSLOptions.CAFile)
633 if (SSL_CTX_load_verify_locations(ctx, Conf_SSLOptions.CAFile, NULL) !=
635 LogOpenSSLError("SSL_CTX_load_verify_locations", NULL);
639 if (Conf_SSLOptions.CRLFile) {
640 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
641 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
642 SSL_CTX_set1_param(ctx, param);
644 store = SSL_CTX_get_cert_store(ctx);
646 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
648 LogOpenSSLError("X509_STORE_add_lookup",
649 Conf_SSLOptions.CRLFile);
653 if (X509_load_crl_file
654 (lookup, Conf_SSLOptions.CRLFile, X509_FILETYPE_PEM) != 1) {
655 LogOpenSSLError("X509_load_crl_file",
656 Conf_SSLOptions.CRLFile);
661 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
663 SSL_CTX_set_verify_depth(ctx, MAX_CERT_CHAIN_LENGTH);
666 if (Conf_SSLOptions.CRLFile)
667 free(Conf_SSLOptions.CRLFile);
668 Conf_SSLOptions.CRLFile = NULL;
675 ConnSSL_Init_SSL(CONNECTION *c)
679 LogDebug("Initializing SSL ...");
685 "Can't initialize SSL context, OpenSSL initialization failed at startup!");
688 assert(c->ssl_state.ssl == NULL);
689 assert(c->ssl_state.fingerprint == NULL);
691 c->ssl_state.ssl = SSL_new(ssl_ctx);
692 if (!c->ssl_state.ssl) {
693 LogOpenSSLError("Failed to create SSL structure", NULL);
696 Conn_OPTION_ADD(c, CONN_SSL);
698 ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
700 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
705 #ifdef HAVE_LIBGNUTLS
706 Conn_OPTION_ADD(c, CONN_SSL);
707 ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
708 if (ret != GNUTLS_E_SUCCESS) {
709 Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
710 gnutls_strerror(ret));
715 * The intermediate (long) cast is here to avoid a warning like:
716 * "cast to pointer from integer of different size" on 64-bit platforms.
717 * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
718 * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
720 gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
721 (gnutls_transport_ptr_t) (long) c->sock);
722 gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
723 GNUTLS_CERT_REQUEST);
725 LogDebug("Using X509 credentials from slot %zd.", x509_cred_idx);
726 c->ssl_state.x509_cred_idx = x509_cred_idx;
727 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
729 ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
730 GNUTLS_CRD_CERTIFICATE, slot->x509_cred);
732 Log(LOG_ERR, "Failed to set SSL credentials: %s",
733 gnutls_strerror(ret));
737 gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
744 ConnSSL_PrepareConnect(CONNECTION * c, CONF_SERVER * s)
747 #ifdef HAVE_LIBGNUTLS
751 err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
753 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
754 gnutls_strerror(err));
758 ret = ConnSSL_Init_SSL(c);
761 Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
764 assert(c->ssl_state.ssl);
766 X509_VERIFY_PARAM *param = SSL_get0_param(c->ssl_state.ssl);
767 X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
768 int err = X509_VERIFY_PARAM_set1_host(param, s->host, 0);
771 "Cannot set up hostname verification for '%s': %u",
777 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_PEER,
780 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
788 * Check and handle error return codes after failed calls to SSL functions.
791 * SSL_connect(), SSL_accept(), SSL_do_handshake(), SSL_read(), SSL_peek(), or
792 * SSL_write() on ssl.
795 * gnutlsssl_read(), gnutls_write() or gnutls_handshake().
797 * @param c The connection handle.
798 * @prarm code The return code.
799 * @param fname The name of the function in which the error occurred.
800 * @return -1 on fatal errors, 0 if we can try again later.
803 ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
806 int ret = SSL_ERROR_SYSCALL;
807 unsigned long sslerr;
808 int real_errno = errno;
810 ret = SSL_get_error(c->ssl_state.ssl, code);
813 case SSL_ERROR_WANT_READ:
814 io_event_del(c->sock, IO_WANTWRITE);
815 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
816 return 0; /* try again later */
817 case SSL_ERROR_WANT_WRITE:
818 io_event_del(c->sock, IO_WANTREAD);
819 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE); /* fall through */
821 return 0; /* try again later */
822 case SSL_ERROR_ZERO_RETURN:
823 LogDebug("SSL connection shut down normally.");
825 case SSL_ERROR_SYSCALL:
826 /* SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
827 * and SSL_ERROR_WANT_X509_LOOKUP */
828 sslerr = ERR_get_error();
830 Log(LOG_ERR, "SSL error: %s [in %s()]!",
831 ERR_error_string(sslerr, NULL), fname);
833 switch (code) { /* EOF that violated protocol */
836 "SSL error, client disconnected [in %s()]!",
840 /* Low level socket I/O error, check errno. But
841 * we don't need to log this here, the generic
842 * connection layer will take care of it. */
843 LogDebug("SSL error: %s [in %s()]!",
844 strerror(real_errno), fname);
849 LogOpenSSLError("SSL protocol error", fname);
852 Log(LOG_ERR, "Unknown SSL error %d [in %s()]!", ret, fname);
857 #ifdef HAVE_LIBGNUTLS
860 case GNUTLS_E_INTERRUPTED:
861 if (gnutls_record_get_direction(c->ssl_state.gnutls_session)) {
862 Conn_OPTION_ADD(c, CONN_SSL_WANT_WRITE);
863 io_event_del(c->sock, IO_WANTREAD);
865 Conn_OPTION_ADD(c, CONN_SSL_WANT_READ);
866 io_event_del(c->sock, IO_WANTWRITE);
871 if (gnutls_error_is_fatal(code)) {
872 Log(LOG_ERR, "SSL error: %s [%s].",
873 gnutls_strerror(code), fname);
883 #ifdef HAVE_LIBGNUTLS
887 void *mem = malloc(s);
889 Log(LOG_ERR, "Out of memory: Could not allocate %lu byte",
896 LogGnuTLS_CertInfo(int level, gnutls_x509_crt_t cert, const char *msg)
898 char *dn, *issuer_dn;
900 int err = gnutls_x509_crt_get_dn(cert, NULL, &size);
902 Log(LOG_ERR, "gnutls_x509_crt_get_dn: size == 0");
905 if (err && err != GNUTLS_E_SHORT_MEMORY_BUFFER)
907 dn = LogMalloc(size);
910 err = gnutls_x509_crt_get_dn(cert, dn, &size);
913 gnutls_x509_crt_get_issuer_dn(cert, NULL, &size);
915 issuer_dn = LogMalloc(size);
917 Log(level, "%s: Distinguished Name: %s", msg, dn);
921 gnutls_x509_crt_get_issuer_dn(cert, issuer_dn, &size);
922 Log(level, "%s: Distinguished Name: \"%s\", Issuer \"%s\"", msg, dn,
929 Log(LOG_ERR, "gnutls_x509_crt_get_dn: %s", gnutls_strerror(err));
936 ConnSSL_LogCertInfo( CONNECTION * c, bool connect)
938 bool cert_seen = false, cert_ok = false;
941 const char *comp_alg = "no compression";
943 X509 *peer_cert = NULL;
944 SSL *ssl = c->ssl_state.ssl;
948 comp = SSL_get_current_compression(ssl);
950 comp_alg = SSL_COMP_get_name(comp);
951 Log(LOG_INFO, "Connection %d: initialized %s using cipher %s, %s.",
952 c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl), comp_alg);
953 peer_cert = SSL_get_peer_certificate(ssl);
958 /* Outgoing connection. Verify the remote server! */
959 int err = SSL_get_verify_result(ssl);
960 if (err == X509_V_OK) {
961 const char *peername = SSL_get0_peername(ssl);
962 if (peername != NULL)
964 LogDebug("X509_V_OK, peername = '%s'", peername);
966 Log(LOG_WARNING, "Certificate validation failed: %s!",
967 X509_verify_cert_error_string(err));
969 snprintf(msg, sizeof(msg), "Got %svalid server certificate",
970 cert_ok ? "" : "in");
971 LogOpenSSL_CertInfo(LOG_INFO, peer_cert, msg);
973 /* Incoming connection.
974 * Accept all certificates, don't depend on their
975 * validity: for example, we don't know the hostname
976 * to check, because we not yet even know if this is a
977 * server connection at all and if so, which one, so we
978 * don't know a host name to look for. On the other
979 * hand we want client certificates, for example for
980 * "CertFP" authentication with services ... */
981 LogOpenSSL_CertInfo(LOG_INFO, peer_cert,
982 "Got unchecked client certificate");
985 X509_free(peer_cert);
988 #ifdef HAVE_LIBGNUTLS
990 gnutls_credentials_type_t cred;
991 gnutls_session_t sess = c->ssl_state.gnutls_session;
992 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
994 Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
996 gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
997 gnutls_cipher_get_name(cipher),
998 gnutls_mac_get_name(gnutls_mac_get(sess)));
999 cred = gnutls_auth_get_type(c->ssl_state.gnutls_session);
1000 if (cred == GNUTLS_CRD_CERTIFICATE) {
1003 gnutls_x509_crt_t cert;
1004 unsigned cert_list_size;
1005 const gnutls_datum_t *cert_list =
1006 gnutls_certificate_get_peers(sess, &cert_list_size);
1007 if (!cert_list || cert_list_size == 0) {
1008 Log(LOG_ERR, "No certificates found");
1009 goto done_cn_validation;
1011 int err = gnutls_x509_crt_init(&cert);
1014 "Failed to initialize x509 certificate: %s",
1015 gnutls_strerror(err));
1016 goto done_cn_validation;
1018 err = gnutls_x509_crt_import(cert, cert_list,
1019 GNUTLS_X509_FMT_DER);
1021 Log(LOG_ERR, "Failed to parse the certificate: %s",
1022 gnutls_strerror(err));
1023 goto done_cn_validation;
1028 gnutls_certificate_verify_peers2(c->
1029 ssl_state.gnutls_session,
1033 "gnutls_certificate_verify_peers2 failed: %s",
1034 gnutls_strerror(verify));
1035 goto done_cn_validation;
1036 } else if (status) {
1039 if (gnutls_certificate_verification_status_print
1040 (status, gnutls_certificate_type_get(sess), &out,
1041 0) == GNUTLS_E_SUCCESS) {
1043 "Certificate validation failed: %s",
1045 gnutls_free(out.data);
1049 err = gnutls_x509_crt_check_hostname(cert, c->host);
1052 "Failed to verify the hostname, expected \"%s\"",
1055 cert_ok = verify == 0 && status == 0;
1057 snprintf(msg, sizeof(msg), "Got %svalid server certificate",
1058 cert_ok ? "" : "in");
1059 LogGnuTLS_CertInfo(LOG_INFO, cert, msg);
1061 /* Incoming connection. Please see comments for OpenSSL! */
1062 LogGnuTLS_CertInfo(LOG_INFO, cert,
1063 "Got unchecked peer certificate");
1066 gnutls_x509_crt_deinit(cert);
1072 * can be used later to check if connection was authenticated, e.g.
1073 * if inbound connection tries to register itself as server.
1074 * Could also restrict /OPER to authenticated connections, etc.
1077 Conn_OPTION_ADD(c, CONN_SSL_PEERCERT_OK);
1079 Log(LOG_INFO, "Peer did not present a certificate.");
1084 Accept incoming SSL connection.
1086 1: SSL Connection established
1088 -1: SSL Connection not established due to fatal error.
1091 ConnSSL_Accept( CONNECTION *c )
1094 if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
1095 #ifdef HAVE_LIBGNUTLS
1096 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
1098 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
1099 gnutls_strerror(err));
1103 if (!ConnSSL_Init_SSL(c))
1106 return ConnectAccept(c, false );
1111 ConnSSL_Connect( CONNECTION *c )
1115 assert(c->ssl_state.ssl);
1117 assert(Conn_OPTION_ISSET(c, CONN_SSL));
1118 return ConnectAccept(c, true);
1122 ConnSSL_InitCertFp( CONNECTION *c )
1124 const char hex[] = "0123456789abcdef";
1128 unsigned char digest[EVP_MAX_MD_SIZE];
1129 unsigned int digest_size;
1132 cert = SSL_get_peer_certificate(c->ssl_state.ssl);
1136 if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
1142 #endif /* HAVE_LIBSSL */
1143 #ifdef HAVE_LIBGNUTLS
1144 gnutls_x509_crt_t cert;
1145 unsigned int cert_list_size;
1146 const gnutls_datum_t *cert_list;
1147 unsigned char digest[MAX_HASH_SIZE];
1150 if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
1154 if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
1158 cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
1161 gnutls_x509_crt_deinit(cert);
1165 if (gnutls_x509_crt_import(cert, &cert_list[0],
1166 GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
1167 gnutls_x509_crt_deinit(cert);
1171 digest_size = sizeof(digest);
1172 if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
1174 gnutls_x509_crt_deinit(cert);
1178 gnutls_x509_crt_deinit(cert);
1179 #endif /* HAVE_LIBGNUTLS */
1181 assert(c->ssl_state.fingerprint == NULL);
1183 c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
1184 if (!c->ssl_state.fingerprint)
1187 for (i = 0; i < (int)digest_size; i++) {
1188 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
1189 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
1191 c->ssl_state.fingerprint[i * 2] = '\0';
1196 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
1198 ConnectAccept( CONNECTION *c, bool connect)
1202 SSL *ssl = c->ssl_state.ssl;
1203 assert(ssl != NULL);
1205 ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
1207 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
1209 #ifdef HAVE_LIBGNUTLS
1211 ret = gnutls_handshake(c->ssl_state.gnutls_session);
1213 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
1214 #endif /* _GNUTLS */
1215 (void)ConnSSL_InitCertFp(c);
1217 Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
1218 ConnSSL_LogCertInfo(c, connect);
1220 Conn_StartLogin(CONNECTION2ID(c));
1226 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
1230 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1234 bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
1236 #ifdef HAVE_LIBGNUTLS
1237 bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
1241 if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
1242 errno = EAGAIN; /* try again */
1248 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
1252 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1254 br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
1255 if (br > 0) /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
1258 #ifdef HAVE_LIBGNUTLS
1259 br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
1260 if (br >= 0) /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
1263 /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
1264 if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
1273 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
1277 SSL *ssl = c->ssl_state.ssl;
1282 SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
1283 nl = strchr(buf, '\n');
1288 #ifdef HAVE_LIBGNUTLS
1289 if (Conn_OPTION_ISSET(c, CONN_SSL)) {
1290 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
1293 gnutls_session_t sess = c->ssl_state.gnutls_session;
1294 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
1295 name_cipher = gnutls_cipher_get_name(cipher);
1296 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
1297 keysize = gnutls_cipher_get_key_size(cipher) * 8;
1298 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
1299 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
1301 return snprintf(buf, len, "%s-%s%15s Kx=%s Enc=%s(%u) Mac=%s",
1302 name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
1309 ConnSSL_GetCertFp(CONNECTION *c)
1311 return c->ssl_state.fingerprint;
1315 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
1318 c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
1319 return c->ssl_state.fingerprint != NULL;
1324 ConnSSL_InitLibrary(void)
1329 #endif /* SSL_SUPPORT */