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_free(ssl_ctx);
406 Log(LOG_INFO, "%s initialized.", OpenSSL_version(OPENSSL_VERSION));
409 SSL_CTX_free(newctx);
410 array_free(&Conf_SSLOptions.ListenPorts);
413 #ifdef HAVE_LIBGNUTLS
415 static bool initialized;
418 err = gnutls_global_init();
420 Log(LOG_ERR, "Failed to initialize GnuTLS: %s",
421 gnutls_strerror(err));
426 if (!ConnSSL_LoadServerKey_gnutls())
429 if (priorities_cache != NULL) {
430 gnutls_priority_deinit(priorities_cache);
432 if (gnutls_priority_init(&priorities_cache, Conf_SSLOptions.CipherList,
433 NULL) != GNUTLS_E_SUCCESS) {
435 "Failed to apply GnuTLS cipher list \"%s\"!",
436 Conf_SSLOptions.CipherList);
440 if (!ConnSSL_SetVerifyProperties_gnutls())
443 Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
447 array_free(&Conf_SSLOptions.ListenPorts);
453 #ifdef HAVE_LIBGNUTLS
455 ConnSSL_SetVerifyProperties_gnutls(void)
459 if (!Conf_SSLOptions.CAFile)
462 err = gnutls_certificate_set_x509_trust_file(x509_cred,
463 Conf_SSLOptions.CAFile,
464 GNUTLS_X509_FMT_PEM);
466 Log(LOG_ERR, "Failed to load x509 trust file %s: %s",
467 Conf_SSLOptions.CAFile, gnutls_strerror(err));
470 if (Conf_SSLOptions.CRLFile) {
472 gnutls_certificate_set_x509_crl_file(x509_cred,
473 Conf_SSLOptions.CRLFile,
474 GNUTLS_X509_FMT_PEM);
476 Log(LOG_ERR, "Failed to load x509 crl file %s: %s",
477 Conf_SSLOptions.CRLFile, gnutls_strerror(err));
486 ConnSSL_LoadServerKey_gnutls(void)
489 const char *cert_file;
491 x509_cred_slot *slot = NULL;
492 gnutls_certificate_credentials_t x509_cred;
494 err = gnutls_certificate_allocate_credentials(&x509_cred);
496 Log(LOG_ERR, "Failed to allocate certificate credentials: %s",
497 gnutls_strerror(err));
501 if (array_bytes(&Conf_SSLOptions.KeyFilePassword))
503 "Ignoring SSL \"KeyFilePassword\": Not supported by GnuTLS.");
505 if (!Load_DH_params())
508 gnutls_certificate_set_dh_params(x509_cred, dh_params);
510 cert_file = Conf_SSLOptions.CertFile ?
511 Conf_SSLOptions.CertFile : Conf_SSLOptions.KeyFile;
512 if (Conf_SSLOptions.KeyFile) {
513 err = gnutls_certificate_set_x509_key_file(x509_cred, cert_file,
514 Conf_SSLOptions.KeyFile,
515 GNUTLS_X509_FMT_PEM);
518 "Failed to set certificate key file (cert %s, key %s): %s",
520 Conf_SSLOptions.KeyFile ? Conf_SSLOptions.KeyFile : "(NULL)",
521 gnutls_strerror(err));
526 /* Free currently active x509 context (if any) unless it is still in use */
527 slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
528 if ((slot != NULL) && (slot->refcnt <= 0) && (slot->x509_cred != NULL)) {
529 LogDebug("Discarding X509 certificate credentials from slot %zd.",
531 gnutls_certificate_free_keys(slot->x509_cred);
532 gnutls_certificate_free_credentials(slot->x509_cred);
533 slot->x509_cred = NULL;
534 gnutls_dh_params_deinit(slot->dh_params);
535 slot->dh_params = NULL;
540 x509_cred_idx = (size_t) -1;
542 for (slot = array_start(&x509_creds), i = 0;
543 i < array_length(&x509_creds, sizeof(x509_cred_slot));
545 if (slot->refcnt <= 0) {
550 /* ... allocate new slot otherwise. */
551 if (x509_cred_idx == (size_t) -1) {
552 x509_cred_idx = array_length(&x509_creds, sizeof(x509_cred_slot));
553 slot = array_alloc(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
555 Log(LOG_ERR, "Failed to allocate new slot for certificate credentials");
559 Log(LOG_INFO, "Storing new X509 certificate credentials in slot %zd.", x509_cred_idx);
560 slot->x509_cred = x509_cred;
570 ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
575 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
576 SSL_CTX_set_default_passwd_cb_userdata(ctx, &Conf_SSLOptions.KeyFilePassword);
578 if (!Conf_SSLOptions.KeyFile)
581 if (SSL_CTX_use_PrivateKey_file(ctx, Conf_SSLOptions.KeyFile, SSL_FILETYPE_PEM) != 1) {
582 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
583 LogOpenSSLError("Failed to add private key", Conf_SSLOptions.KeyFile);
587 cert_key = Conf_SSLOptions.CertFile ? Conf_SSLOptions.CertFile:Conf_SSLOptions.KeyFile;
588 if (SSL_CTX_use_certificate_chain_file(ctx, cert_key) != 1) {
589 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
590 LogOpenSSLError("Failed to load certificate chain", cert_key);
594 array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
596 if (!SSL_CTX_check_private_key(ctx)) {
597 LogOpenSSLError("Server private key does not match certificate", NULL);
600 if (Load_DH_params()) {
601 if (SSL_CTX_set_tmp_dh(ctx, dh_params) != 1)
602 LogOpenSSLError("Error setting DH parameters", Conf_SSLOptions.DHFile);
603 /* don't return false here: the non-DH modes will still work */
612 ConnSSL_SetVerifyProperties_openssl(SSL_CTX * ctx)
614 X509_STORE *store = NULL;
618 if (!Conf_SSLOptions.CAFile)
621 if (SSL_CTX_load_verify_locations(ctx, Conf_SSLOptions.CAFile, NULL) !=
623 LogOpenSSLError("SSL_CTX_load_verify_locations", NULL);
627 if (Conf_SSLOptions.CRLFile) {
628 X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
629 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
630 SSL_CTX_set1_param(ctx, param);
632 store = SSL_CTX_get_cert_store(ctx);
634 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
636 LogOpenSSLError("X509_STORE_add_lookup",
637 Conf_SSLOptions.CRLFile);
641 if (X509_load_crl_file
642 (lookup, Conf_SSLOptions.CRLFile, X509_FILETYPE_PEM) != 1) {
643 LogOpenSSLError("X509_load_crl_file",
644 Conf_SSLOptions.CRLFile);
649 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
651 SSL_CTX_set_verify_depth(ctx, MAX_CERT_CHAIN_LENGTH);
654 if (Conf_SSLOptions.CRLFile)
655 free(Conf_SSLOptions.CRLFile);
656 Conf_SSLOptions.CRLFile = NULL;
663 ConnSSL_Init_SSL(CONNECTION *c)
667 LogDebug("Initializing SSL ...");
673 "Can't initialize SSL context, OpenSSL initialization failed at startup!");
676 assert(c->ssl_state.ssl == NULL);
677 assert(c->ssl_state.fingerprint == NULL);
679 c->ssl_state.ssl = SSL_new(ssl_ctx);
680 if (!c->ssl_state.ssl) {
681 LogOpenSSLError("Failed to create SSL structure", NULL);
684 Conn_OPTION_ADD(c, CONN_SSL);
686 ret = SSL_set_fd(c->ssl_state.ssl, c->sock);
688 LogOpenSSLError("Failed to set SSL file descriptor", NULL);
693 #ifdef HAVE_LIBGNUTLS
694 Conn_OPTION_ADD(c, CONN_SSL);
695 ret = gnutls_priority_set(c->ssl_state.gnutls_session, priorities_cache);
696 if (ret != GNUTLS_E_SUCCESS) {
697 Log(LOG_ERR, "Failed to set GnuTLS session priorities: %s",
698 gnutls_strerror(ret));
703 * The intermediate (long) cast is here to avoid a warning like:
704 * "cast to pointer from integer of different size" on 64-bit platforms.
705 * There doesn't seem to be an alternate GNUTLS API we could use instead, see e.g.
706 * http://www.mail-archive.com/help-gnutls@gnu.org/msg00286.html
708 gnutls_transport_set_ptr(c->ssl_state.gnutls_session,
709 (gnutls_transport_ptr_t) (long) c->sock);
710 gnutls_certificate_server_set_request(c->ssl_state.gnutls_session,
711 GNUTLS_CERT_REQUEST);
713 LogDebug("Using X509 credentials from slot %zd.", x509_cred_idx);
714 c->ssl_state.x509_cred_idx = x509_cred_idx;
715 x509_cred_slot *slot = array_get(&x509_creds, sizeof(x509_cred_slot), x509_cred_idx);
717 ret = gnutls_credentials_set(c->ssl_state.gnutls_session,
718 GNUTLS_CRD_CERTIFICATE, slot->x509_cred);
720 Log(LOG_ERR, "Failed to set SSL credentials: %s",
721 gnutls_strerror(ret));
725 gnutls_dh_set_prime_bits(c->ssl_state.gnutls_session, DH_BITS_MIN);
732 ConnSSL_PrepareConnect(CONNECTION * c, CONF_SERVER * s)
735 #ifdef HAVE_LIBGNUTLS
738 err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_CLIENT);
740 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
741 gnutls_strerror(err));
745 ret = ConnSSL_Init_SSL(c);
748 Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
751 assert(c->ssl_state.ssl);
753 X509_VERIFY_PARAM *param = SSL_get0_param(c->ssl_state.ssl);
754 X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
755 int err = X509_VERIFY_PARAM_set1_host(param, s->host, 0);
758 "Cannot set up hostname verification for '%s': %u",
764 SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_PEER,
767 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);
942 /* Outgoing connection. Verify the remote server! */
943 int err = SSL_get_verify_result(ssl);
944 if (err == X509_V_OK) {
945 const char *peername = SSL_get0_peername(ssl);
946 if (peername != NULL)
948 LogDebug("X509_V_OK, peername = '%s'", peername);
950 Log(LOG_WARNING, "Certificate validation failed: %s!",
951 X509_verify_cert_error_string(err));
953 snprintf(msg, sizeof(msg), "Got %svalid server certificate",
954 cert_ok ? "" : "in");
955 LogOpenSSL_CertInfo(LOG_INFO, peer_cert, msg);
957 /* Incoming connection.
958 * Accept all certificates, don't depend on their
959 * validity: for example, we don't know the hostname
960 * to check, because we not yet even know if this is a
961 * server connection at all and if so, which one, so we
962 * don't know a host name to look for. On the other
963 * hand we want client certificates, for example for
964 * "CertFP" authentication with services ... */
965 LogOpenSSL_CertInfo(LOG_INFO, peer_cert,
966 "Got unchecked client certificate");
969 X509_free(peer_cert);
972 #ifdef HAVE_LIBGNUTLS
974 gnutls_credentials_type_t cred;
975 gnutls_session_t sess = c->ssl_state.gnutls_session;
976 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
978 Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
980 gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
981 gnutls_cipher_get_name(cipher),
982 gnutls_mac_get_name(gnutls_mac_get(sess)));
983 cred = gnutls_auth_get_type(c->ssl_state.gnutls_session);
984 if (cred == GNUTLS_CRD_CERTIFICATE && connect) {
987 gnutls_certificate_verify_peers2(c->
988 ssl_state.gnutls_session,
992 "gnutls_certificate_verify_peers2 failed: %s",
993 gnutls_strerror(verify));
994 goto done_cn_validation;
998 if (gnutls_certificate_verification_status_print
999 (status, gnutls_certificate_type_get(sess), &out,
1000 0) == GNUTLS_E_SUCCESS) {
1002 "Certificate validation failed: %s",
1004 gnutls_free(out.data);
1008 gnutls_x509_crt_t cert;
1009 unsigned cert_list_size;
1010 const gnutls_datum_t *cert_list =
1011 gnutls_certificate_get_peers(sess, &cert_list_size);
1012 if (!cert_list || cert_list_size == 0) {
1013 Log(LOG_ERR, "No certificates found");
1014 goto done_cn_validation;
1016 int err = gnutls_x509_crt_init(&cert);
1019 "Failed to initialize x509 certificate: %s",
1020 gnutls_strerror(err));
1021 goto done_cn_validation;
1023 err = gnutls_x509_crt_import(cert, cert_list,
1024 GNUTLS_X509_FMT_DER);
1026 Log(LOG_ERR, "Failed to parse the certificate: %s",
1027 gnutls_strerror(err));
1028 goto done_cn_validation;
1030 err = gnutls_x509_crt_check_hostname(cert, c->host);
1033 "Failed to verify the hostname, expected \"%s\"",
1036 cert_ok = verify == 0 && status == 0;
1038 snprintf(msg, sizeof(msg), "%svalid peer certificate",
1039 cert_ok ? "" : "in");
1040 LogGnuTLS_CertInfo(cert_ok ? LOG_DEBUG : LOG_ERR, cert, msg);
1042 gnutls_x509_crt_deinit(cert);
1048 * can be used later to check if connection was authenticated, e.g.
1049 * if inbound connection tries to register itself as server.
1050 * Could also restrict /OPER to authenticated connections, etc.
1053 Conn_OPTION_ADD(c, CONN_SSL_PEERCERT_OK);
1055 Log(LOG_INFO, "Peer did not present a certificate.");
1060 Accept incoming SSL connection.
1062 1: SSL Connection established
1064 -1: SSL Connection not established due to fatal error.
1067 ConnSSL_Accept( CONNECTION *c )
1070 if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
1071 #ifdef HAVE_LIBGNUTLS
1072 int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
1074 Log(LOG_ERR, "Failed to initialize new SSL session: %s",
1075 gnutls_strerror(err));
1079 if (!ConnSSL_Init_SSL(c))
1082 return ConnectAccept(c, false );
1087 ConnSSL_Connect( CONNECTION *c )
1091 assert(c->ssl_state.ssl);
1093 assert(Conn_OPTION_ISSET(c, CONN_SSL));
1094 return ConnectAccept(c, true);
1098 ConnSSL_InitCertFp( CONNECTION *c )
1100 const char hex[] = "0123456789abcdef";
1104 unsigned char digest[EVP_MAX_MD_SIZE];
1105 unsigned int digest_size;
1108 cert = SSL_get_peer_certificate(c->ssl_state.ssl);
1112 if (!X509_digest(cert, EVP_sha256(), digest, &digest_size)) {
1118 #endif /* HAVE_LIBSSL */
1119 #ifdef HAVE_LIBGNUTLS
1120 gnutls_x509_crt_t cert;
1121 unsigned int cert_list_size;
1122 const gnutls_datum_t *cert_list;
1123 unsigned char digest[MAX_HASH_SIZE];
1126 if (gnutls_certificate_type_get(c->ssl_state.gnutls_session) !=
1130 if (gnutls_x509_crt_init(&cert) != GNUTLS_E_SUCCESS)
1134 cert_list = gnutls_certificate_get_peers(c->ssl_state.gnutls_session,
1137 gnutls_x509_crt_deinit(cert);
1141 if (gnutls_x509_crt_import(cert, &cert_list[0],
1142 GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
1143 gnutls_x509_crt_deinit(cert);
1147 digest_size = sizeof(digest);
1148 if (gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, digest,
1150 gnutls_x509_crt_deinit(cert);
1154 gnutls_x509_crt_deinit(cert);
1155 #endif /* HAVE_LIBGNUTLS */
1157 assert(c->ssl_state.fingerprint == NULL);
1159 c->ssl_state.fingerprint = malloc(SHA256_STRING_LEN);
1160 if (!c->ssl_state.fingerprint)
1163 for (i = 0; i < (int)digest_size; i++) {
1164 c->ssl_state.fingerprint[i * 2] = hex[digest[i] / 16];
1165 c->ssl_state.fingerprint[i * 2 + 1] = hex[digest[i] % 16];
1167 c->ssl_state.fingerprint[i * 2] = '\0';
1172 /* accept/connect wrapper. if connect is true, connect to peer, otherwise wait for incoming connection */
1174 ConnectAccept( CONNECTION *c, bool connect)
1178 SSL *ssl = c->ssl_state.ssl;
1179 assert(ssl != NULL);
1181 ret = connect ? SSL_connect(ssl) : SSL_accept(ssl);
1183 return ConnSSL_HandleError(c, ret, connect ? "SSL_connect": "SSL_accept");
1185 #ifdef HAVE_LIBGNUTLS
1187 ret = gnutls_handshake(c->ssl_state.gnutls_session);
1189 return ConnSSL_HandleError(c, ret, "gnutls_handshake");
1190 #endif /* _GNUTLS */
1191 (void)ConnSSL_InitCertFp(c);
1193 Conn_OPTION_DEL(c, (CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_CONNECT));
1194 ConnSSL_LogCertInfo(c, connect);
1196 Conn_StartLogin(CONNECTION2ID(c));
1202 ConnSSL_Write(CONNECTION *c, const void *buf, size_t count)
1206 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1210 bw = (ssize_t) SSL_write(c->ssl_state.ssl, buf, count);
1212 #ifdef HAVE_LIBGNUTLS
1213 bw = gnutls_write(c->ssl_state.gnutls_session, buf, count);
1217 if (ConnSSL_HandleError( c, bw, "ConnSSL_Write") == 0)
1218 errno = EAGAIN; /* try again */
1224 ConnSSL_Read(CONNECTION *c, void * buf, size_t count)
1228 Conn_OPTION_DEL(c, CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ);
1230 br = (ssize_t) SSL_read(c->ssl_state.ssl, buf, count);
1231 if (br > 0) /* on EOF we have to call ConnSSL_HandleError(), see SSL_read(3) */
1234 #ifdef HAVE_LIBGNUTLS
1235 br = gnutls_read(c->ssl_state.gnutls_session, buf, count);
1236 if (br >= 0) /* on EOF we must _not_ call ConnSSL_HandleError, see gnutls_record_recv(3) */
1239 /* error on read: switch ConnSSL_HandleError() return values -> 0 is "try again", so return -1 and set EAGAIN */
1240 if (ConnSSL_HandleError(c, br, "ConnSSL_Read") == 0) {
1249 ConnSSL_GetCipherInfo(CONNECTION *c, char *buf, size_t len)
1253 SSL *ssl = c->ssl_state.ssl;
1258 SSL_CIPHER_description(SSL_get_current_cipher(ssl), buf, len);
1259 nl = strchr(buf, '\n');
1264 #ifdef HAVE_LIBGNUTLS
1265 if (Conn_OPTION_ISSET(c, CONN_SSL)) {
1266 const char *name_cipher, *name_mac, *name_proto, *name_keyexchange;
1269 gnutls_session_t sess = c->ssl_state.gnutls_session;
1270 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
1271 name_cipher = gnutls_cipher_get_name(cipher);
1272 name_mac = gnutls_mac_get_name(gnutls_mac_get(sess));
1273 keysize = gnutls_cipher_get_key_size(cipher) * 8;
1274 name_proto = gnutls_protocol_get_name(gnutls_protocol_get_version(sess));
1275 name_keyexchange = gnutls_kx_get_name(gnutls_kx_get(sess));
1277 return snprintf(buf, len, "%s-%s%15s Kx=%s Enc=%s(%u) Mac=%s",
1278 name_cipher, name_mac, name_proto, name_keyexchange, name_cipher, keysize, name_mac) > 0;
1285 ConnSSL_GetCertFp(CONNECTION *c)
1287 return c->ssl_state.fingerprint;
1291 ConnSSL_SetCertFp(CONNECTION *c, const char *fingerprint)
1294 c->ssl_state.fingerprint = strndup(fingerprint, SHA256_STRING_LEN - 1);
1295 return c->ssl_state.fingerprint != NULL;
1300 ConnSSL_InitLibrary(void)
1305 #endif /* SSL_SUPPORT */