]> arthur.barton.de Git - ngircd-alex.git/commitdiff
Optionally validate certificates on TLS server links bug120-ValidateServerCertificates
authorChristoph Biedl <ngircd.anoy@manchmal.in-ulm.de>
Wed, 5 Nov 2014 22:11:03 +0000 (23:11 +0100)
committerAlexander Barton <alex@barton.de>
Tue, 20 Jan 2015 22:36:59 +0000 (23:36 +0100)
Bugzilla #120 is a *really* long-standing issue, and it's a very important
one: The peer's certificate is *not* validated on a server link, rendering
the security on such links useless since a man-in-the-middle attacker can
easily capture all the traffic and re-encode it without even being noticed.

More than five years ago, Florian Westphal wrote a patch to mitigate the
issue but it was never completed nor made it to master. So I took the
liberty to rebase the patch onto rel-22, update the configuration
variables to reflect the rel-19-ish configuration changes, and to fix a
common error in certificate validation: The certificate's CN must match
the host name the client connects to.

This is anything but ready for prime time. Please test in every
conceivable way, there are many. Especially CRL is completely untested. If
you have an SSL/TLS guru at hand, please seek his advice. There are many,
many pitfalls in this area and certainly some are still present. Host name
validation should not solely done against the CN, this is rather a last
resort [citation needed]. Also, an outgoing connection probably does not
work against SNI but certainly should.

Also to do: Minor code style cleanup, some more error checking.

Cheers,
    Christoph, beware of easter eggs

Based on
    From: Florian Westphal <fw@strlen.de>
    Date: Mon, 18 May 2009 00:29:02 +0200
    Subject: [PATCH] SSL/TLS: add initial certificate support to openssl backend

doc/sample-ngircd.conf.tmpl
man/ngircd.conf.5.tmpl
src/ngircd/conf.c
src/ngircd/conf.h
src/ngircd/conn-ssl.c
src/ngircd/conn.c
src/ngircd/conn.h
src/ngircd/irc-server.c

index b5db1d9e1edffa5af2070dfc27bf9fa990590ce6..a4d58b945024f1ff050fe817a58333b56351066a 100644 (file)
        # is only available when ngIRCd is compiled with support for SSL!
        # So don't forget to remove the ";" above if this is the case ...
 
+       # SSL Trusted CA Certificates File (for verifying peer certificates)
+       ;CAFile = /etc/ssl/CA/cacert.pem
+
+       # Certificate Revocation File (for marking otherwise valid
+       # certficates as invalid)
+       ;CRLFile = /etc/ssl/CA/crl.pem
+
        # SSL Server Key Certificate
        ;CertFile = :ETCDIR:/ssl/server-cert.pem
 
        # Additional Listen Ports that expect SSL/TLS encrypted connections
        ;Ports = 6697, 9999
 
+       # Enforce Client Certificates? (Default: false)
+       ;RequireClientCert = false
+
 [Operator]
        # [Operator] sections are used to define IRC Operators. There may be
        # more than one [Operator] block, one for each local operator.
index 0d57f902d46c4b5a0fb5f8cc3651a4030694554b..f3830456a5dff5b82b254c6650073ce82debfee3 100644 (file)
@@ -370,6 +370,13 @@ All SSL-related configuration variables are located in the
 section. Please note that this whole section is only recognized by ngIRCd
 when it is compiled with support for SSL using OpenSSL or GnuTLS!
 .TP
+\fBCAFile (string)\fR
+Filename pointing to the Trusted CA Certificates. This is required for
+verifying peer certificates and must be set if <RequireClientCert> is set.
+.TP
+\fBCRLFile (string)\fR
+Filename of Certificate Revocation List.
+.TP
 \fBCertFile\fR (string)
 SSL Certificate file of the private server key.
 .TP
@@ -398,6 +405,10 @@ OpenSSL only: Password to decrypt the private key file.
 Same as \fBPorts\fR , except that ngIRCd will expect incoming connections
 to be SSL/TLS encrypted. Common port numbers for SSL-encrypted IRC are 6669
 and 6697. Default: none.
+.TP
+\fBRequireClientCert (boolean)\fR
+Do not accept SSL connections from clients that do not have a valid certificate. Defaults to false.
+Also see \fBSSLVerify\fR below.
 .SH [OPERATOR]
 .I [Operator]
 sections are used to define IRC Operators. There may be more than one
index 221e7a96e8621c37b6f2db3d26d4c0accdf9075a..c382cb1a8beff3bba94a2d0861a586ecb08d0dac 100644 (file)
@@ -112,8 +112,16 @@ ConfSSL_Init(void)
        free(Conf_SSLOptions.CertFile);
        Conf_SSLOptions.CertFile = NULL;
 
+       free(Conf_SSLOptions.CAFile);
+       Conf_SSLOptions.CAFile = NULL;
+
+       free(Conf_SSLOptions.CRLFile);
+       Conf_SSLOptions.CRLFile = NULL;
+
        free(Conf_SSLOptions.DHFile);
        Conf_SSLOptions.DHFile = NULL;
+
+       Conf_SSLOptions.RequireClientCert = false;
        array_free_wipe(&Conf_SSLOptions.KeyFilePassword);
 
        array_free(&Conf_SSLOptions.ListenPorts);
@@ -462,7 +470,8 @@ Conf_Test( void )
                printf( "  Host = %s\n", Conf_Server[i].host );
                printf( "  Port = %u\n", (unsigned int)Conf_Server[i].port );
 #ifdef SSL_SUPPORT
-               printf( "  SSLConnect = %s\n", Conf_Server[i].SSLConnect?"yes":"no");
+               printf( "  SSLConnect = %s\n", yesno_to_str(Conf_Server[i].SSLConnect));
+               printf( "  SSLVerify = %s\n", yesno_to_str(Conf_Server[i].SSLVerify));
 #endif
                printf( "  MyPassword = %s\n", Conf_Server[i].pwd_in );
                printf( "  PeerPassword = %s\n", Conf_Server[i].pwd_out );
@@ -1038,6 +1047,11 @@ Read_Config(bool TestOnly, bool IsStarting)
        CheckFileReadable("CertFile", Conf_SSLOptions.CertFile);
        CheckFileReadable("DHFile", Conf_SSLOptions.DHFile);
        CheckFileReadable("KeyFile", Conf_SSLOptions.KeyFile);
+        if (Conf_SSLOptions.RequireClientCert) {
+               CheckFileReadable("CAFile", Conf_SSLOptions.CAFile);
+                if (Conf_SSLOptions.CRLFile)
+                       CheckFileReadable("CRLFile", Conf_SSLOptions.CRLFile);
+        }
 
        /* Set the default ciphers if none were configured */
        if (!Conf_SSLOptions.CipherList)
@@ -1913,6 +1927,20 @@ Handle_SSL(const char *File, int Line, char *Var, char *Arg)
                Conf_SSLOptions.CipherList = strdup_warn(Arg);
                return;
        }
+       if (strcasecmp(Var, "CAFile") == 0) {
+               assert(Conf_SSLOptions.CAFile == NULL);
+               Conf_SSLOptions.CAFile = strdup_warn( Arg );
+                return;
+       }
+       if (strcasecmp(Var, "CRLFile") == 0) {
+               assert(Conf_SSLOptions.CRLFile == NULL);
+               Conf_SSLOptions.CRLFile = strdup_warn( Arg );
+                return;
+        }
+       if (strcasecmp(Var, "RequireClientCert") == 0) {
+               Conf_SSLOptions.RequireClientCert = Check_ArgIsTrue( Arg );
+                return;
+       }
 
        Config_Error_Section(File, Line, Var, "SSL");
 }
@@ -2044,6 +2072,10 @@ Handle_SERVER(const char *File, int Line, char *Var, char *Arg )
                New_Server.SSLConnect = Check_ArgIsTrue(Arg);
                return;
         }
+       if( strcasecmp( Var, "SSLVerify" ) == 0 ) {
+               New_Server.SSLVerify = Check_ArgIsTrue(Arg);
+               return;
+        }
 #endif
        if( strcasecmp( Var, "Group" ) == 0 ) {
                /* Server group */
@@ -2278,6 +2310,10 @@ Validate_Config(bool Configtest, bool Rehash)
            array_length(&Conf_Channels, sizeof(struct Conf_Channel)));
 #endif
 
+#ifdef SSL_SUPPORT
+       if (Conf_SSLOptions.RequireClientCert && array_bytes(&Conf_ListenPorts))
+               Log(LOG_WARNING, "SSL certificate validation enabled, (RequireClientCert=yes), but non-SSL listening ports are set");
+#endif
        return config_valid;
 }
 
@@ -2408,6 +2444,9 @@ Init_Server_Struct( CONF_SERVER *Server )
        Proc_InitStruct(&Server->res_stat);
        Server->conn_id = NONE;
        memset(&Server->bind_addr, 0, sizeof(Server->bind_addr));
+#ifdef SSL_SUPPORT
+       Server->SSLVerify = false;
+#endif
 }
 
 /* -eof- */
index aa80b8dd94942536c29ff4fce85c18e316e591ce..12ad6f547aa9280a6101717c7a86dd898e2a0f1a 100644 (file)
@@ -61,6 +61,7 @@ typedef struct _Conf_Server
        ng_ipaddr_t dst_addr[2];        /**< List of addresses to connect to */
 #ifdef SSL_SUPPORT
        bool SSLConnect;                /**< Establish connection using SSL? */
+       bool SSLVerify;                 /**< Verify server certificate using CA? */
 #endif
        char svs_mask[CLIENT_ID_LEN];   /**< Mask of nicknames that should be
                                             treated and counted as services */
@@ -76,6 +77,9 @@ struct SSLOptions {
        array ListenPorts;              /**< Array of listening SSL ports */
        array KeyFilePassword;          /**< Key file password */
        char *CipherList;               /**< Set SSL cipher list to use */
+       char *CAFile;                   /**< Trusted CA certificates file */
+       char *CRLFile;                  /**< Certificate revocation file */
+       bool RequireClientCert;         /**< Enforce client certifiactes? */
 };
 #endif
 
index c9bbdd2497ee3f7f9742415ab5888fad4b1c7186..3e21ad268f1d4abf34cd3ee9d14a788875a012ee 100644 (file)
@@ -47,8 +47,11 @@ static SSL_CTX * ssl_ctx;
 static DH *dh_params;
 
 static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
+static bool ConnSSL_SetVerifyProperties_openssl PARAMS(( SSL_CTX *c ));
 #endif
 
+#define MAX_CERT_CHAIN_LENGTH  10 /* XXX: do not hardcode */
+
 #ifdef HAVE_LIBGNUTLS
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -61,10 +64,16 @@ static bool ConnSSL_LoadServerKey_openssl PARAMS(( SSL_CTX *c ));
 
 #define MAX_HASH_SIZE  64      /* from gnutls-int.h */
 
+gnutls_x509_crl_t *crl_list;
+gnutls_x509_crt_t *ca_list;
+size_t crl_list_size;
+size_t ca_list_size;
+
 static gnutls_certificate_credentials_t x509_cred;
 static gnutls_dh_params_t dh_params;
 static gnutls_priority_t priorities_cache;
 static bool ConnSSL_LoadServerKey_gnutls PARAMS(( void ));
+static bool ConnSSL_SetVerifyProperties_gnutls PARAMS(( void ));
 #endif
 
 #define SHA256_STRING_LEN      (32 * 2 + 1)
@@ -125,6 +134,34 @@ out:
  * @param msg The error message.
  * @param info Additional information text or NULL.
  */
+static void
+LogOpenSSL_CertInfo(X509 *cert, const char *msg)
+{
+       BIO *mem;
+       char *memptr;
+       long len;
+
+       assert(cert);
+       assert(msg);
+
+       if (!cert) return;
+
+       mem = BIO_new(BIO_s_mem());
+       if (!mem) return;
+
+       X509_NAME_print_ex(mem, X509_get_subject_name (cert), 4, XN_FLAG_ONELINE);
+       X509_NAME_print_ex(mem, X509_get_issuer_name (cert), 4, XN_FLAG_ONELINE);
+       if (BIO_write(mem, "", 1) == 1) {
+               len = BIO_get_mem_data(mem, &memptr);
+               assert(memptr);
+               assert(len>0);
+               Log(LOG_INFO, "%s: \"%s\"", msg, memptr);
+       }
+
+       (void)BIO_set_close(mem, BIO_CLOSE);
+       BIO_free(mem);
+}
+
 static void
 LogOpenSSLError(const char *error, const char *info)
 {
@@ -167,9 +204,33 @@ pem_passwd_cb(char *buf, int size, int rwflag, void *password)
 
 
 static int
-Verify_openssl(UNUSED int preverify_ok, UNUSED X509_STORE_CTX *x509_ctx)
+Verify_openssl(int preverify_ok, X509_STORE_CTX *ctx)
 {
-       return 1;
+       X509 *err_cert;
+       int err, depth;
+
+       err_cert = X509_STORE_CTX_get_current_cert(ctx);
+       err = X509_STORE_CTX_get_error(ctx);
+       depth = X509_STORE_CTX_get_error_depth(ctx);
+
+       LogDebug("preverify_ok %d error:num=%d:%s:depth=%d",
+                       preverify_ok, err, X509_verify_cert_error_string(err), depth);
+
+       if (preverify_ok != 1) {
+               /*
+                * if certificates are not being enforced, ignore any errors.
+                * its possible to check if a connection has a valid certificate
+                * by testing the CONN_SSL_PEERCERT_OK flag.
+                * This can be used to enforce certificates for incoming servers,
+                * but not irc clients.
+                */
+               if (!Conf_SSLOptions.RequireClientCert)
+                       preverify_ok = 1;
+               else
+                       Log(LOG_ERR, "verify error:num=%d:%s:depth=%d", err,
+                               X509_verify_cert_error_string(err), depth);
+       }
+       return preverify_ok;
 }
 #endif
 
@@ -317,6 +378,9 @@ ConnSSL_InitLibrary( void )
                goto out;
        }
 
+       if (!ConnSSL_SetVerifyProperties_openssl(newctx))
+                goto out;
+
        SSL_CTX_set_options(newctx, SSL_OP_SINGLE_DH_USE|SSL_OP_NO_SSLv2);
        SSL_CTX_set_mode(newctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
        SSL_CTX_set_verify(newctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
@@ -358,6 +422,9 @@ out:
                goto out;
        }
 
+       if (!ConnSSL_SetVerifyProperties_gnutls())
+               goto out;
+
        Log(LOG_INFO, "GnuTLS %s initialized.", gnutls_check_version(NULL));
        initialized = true;
        return true;
@@ -369,6 +436,30 @@ out:
 
 
 #ifdef HAVE_LIBGNUTLS
+static bool
+ConnSSL_SetVerifyProperties_gnutls(void)
+{
+       int err;
+
+       if (Conf_SSLOptions.CAFile) {
+               err = gnutls_certificate_set_x509_trust_file(x509_cred, Conf_SSLOptions.CAFile, GNUTLS_X509_FMT_PEM);
+               if (err < 0) {
+                       Log(LOG_ERR, "Failed to load x509 trust file %s: %s", Conf_SSLOptions.CAFile, gnutls_strerror(err));
+                       return false;
+               }
+       }
+       if (Conf_SSLOptions.CRLFile) {
+               err = gnutls_certificate_set_x509_crl_file(x509_cred, Conf_SSLOptions.CRLFile, GNUTLS_X509_FMT_PEM);
+               if (err < 0) {
+                       Log(LOG_ERR, "Failed to load x509 crl file %s: %s", Conf_SSLOptions.CRLFile, gnutls_strerror(err));
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+
 static bool
 ConnSSL_LoadServerKey_gnutls(void)
 {
@@ -455,6 +546,48 @@ ConnSSL_LoadServerKey_openssl(SSL_CTX *ctx)
 }
 
 
+static bool
+ConnSSL_SetVerifyProperties_openssl(SSL_CTX * ctx)
+{
+       X509_STORE *store = NULL;
+       X509_LOOKUP *lookup;
+       int verify_flags = SSL_VERIFY_PEER;
+       bool ret = false;
+
+       if (!Conf_SSLOptions.CAFile)
+               return true;
+
+       if (SSL_CTX_load_verify_locations(ctx, Conf_SSLOptions.CAFile, NULL) != 1) {
+               LogOpenSSLError("SSL_CTX_load_verify_locations", NULL);
+               goto out;
+       }
+
+       store = SSL_CTX_get_cert_store(ctx);
+       assert(store);
+       lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
+       if (!lookup) {
+               LogOpenSSLError("X509_STORE_add_lookup", Conf_SSLOptions.CRLFile);
+               goto out;
+       }
+
+       if (1 != X509_load_crl_file(lookup, Conf_SSLOptions.CRLFile, X509_FILETYPE_PEM)) {
+               LogOpenSSLError("X509_load_crl_file", Conf_SSLOptions.CRLFile);
+               goto out;
+       }
+
+       if (Conf_SSLOptions.RequireClientCert)
+               verify_flags |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
+
+       SSL_CTX_set_verify(ctx, verify_flags, Verify_openssl);
+       SSL_CTX_set_verify_depth(ctx, MAX_CERT_CHAIN_LENGTH);
+       ret = true;
+ out:
+       free(Conf_SSLOptions.CRLFile);
+       Conf_SSLOptions.CRLFile = NULL;
+       return ret;
+}
+
+
 #endif
 static bool
 ConnSSL_Init_SSL(CONNECTION *c)
@@ -540,7 +673,11 @@ ConnSSL_PrepareConnect(CONNECTION *c, UNUSED CONF_SERVER *s)
        Conn_OPTION_ADD(c, CONN_SSL_CONNECT);
 #ifdef HAVE_LIBSSL
        assert(c->ssl_state.ssl);
-       SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
+
+       if (s->SSLVerify)
+               SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_PEER, Verify_openssl);
+       else
+               SSL_set_verify(c->ssl_state.ssl, SSL_VERIFY_NONE, NULL);
 #endif
        return true;
 }
@@ -639,27 +776,191 @@ ConnSSL_HandleError(CONNECTION * c, const int code, const char *fname)
 }
 
 
+#ifdef HAVE_LIBGNUTLS
+static bool check_verification(unsigned output)
+{
+       char errmsg[256] = "";
+
+       if (output & GNUTLS_CERT_SIGNER_NOT_FOUND)
+               strlcpy(errmsg, "No Issuer found", sizeof errmsg);
+       if (output & GNUTLS_CERT_SIGNER_NOT_CA) {
+               if (errmsg[0])
+                       strlcat(errmsg, " ,", sizeof errmsg);
+               strlcat(errmsg, "Issuer is not a CA", sizeof errmsg);
+       }
+       if (output & GNUTLS_CERT_INSECURE_ALGORITHM) {
+               if (errmsg[0])
+                       strlcat(errmsg, " ,", sizeof errmsg);
+               strlcat(errmsg, "Insecure Algorithm", sizeof errmsg);
+       }
+       if (output & GNUTLS_CERT_REVOKED) {
+               if (errmsg[0])
+                       strlcat(errmsg, " ,", sizeof errmsg);
+               strlcat(errmsg, "Certificate Revoked", sizeof errmsg);
+       }
+#ifdef DEBUG
+       if (output & GNUTLS_CERT_INVALID)
+               assert(errmsg[0]); /* check for unhandled error */
+#endif
+       if (!(output & GNUTLS_CERT_INVALID) && !errmsg[0]) {
+               LogDebug("Certificate verified.");
+               return true;
+       }
+       Log(LOG_ERR, "Certificate Validation failed: %s", errmsg);
+       return false;
+}
+
+static void *LogMalloc(size_t s)
+{
+       void *mem = malloc(s);
+       if (!mem)
+               Log(LOG_ERR, "Out of memory: Could not allocate %lu byte", (unsigned long) s);
+       return mem;
+}
+
+static void
+LogGnuTLS_CertInfo(gnutls_x509_crt_t cert, const char *msg)
+{
+       char *dn, *issuer_dn;
+       size_t size = 0;
+       int err = gnutls_x509_crt_get_dn(cert, NULL, &size);
+       if (size == 0 || (err && err != GNUTLS_E_SHORT_MEMORY_BUFFER))
+               goto err_crt_get;
+       dn = LogMalloc(size);
+       if (!dn)
+               return;
+       err = gnutls_x509_crt_get_dn(cert, dn, &size);
+       if (err) {
+ err_crt_get:
+               Log(LOG_ERR, "gnutls_x509_crt_get_dn: %s", err ? gnutls_strerror(err) : "size == 0");
+               return;
+       }
+       gnutls_x509_crt_get_issuer_dn(cert, NULL, &size);
+       assert(size);
+       issuer_dn = LogMalloc(size);
+       if (!issuer_dn) {
+               Log(LOG_INFO, "%s: Distinguished Name: %s", msg, dn);
+               free(dn);
+               return;
+       }
+       gnutls_x509_crt_get_issuer_dn(cert, issuer_dn, &size);
+       Log(LOG_INFO, "%s: Distinguished Name: \"%s\", Issuer \"%s\"", msg, dn, issuer_dn);
+       free(dn);
+       free(issuer_dn);
+}
+#endif
+
 static void
 ConnSSL_LogCertInfo( CONNECTION *c )
 {
+       const char *comp_alg = "no compression";
+       bool cert_seen = false, cert_ok = false, cn_match = false;
+       char msg[128];
 #ifdef HAVE_LIBSSL
+       const void *comp;
+       X509 *client_cert = NULL;
        SSL *ssl = c->ssl_state.ssl;
 
        assert(ssl);
-
-       Log(LOG_INFO, "Connection %d: initialized %s using cipher %s.",
-               c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl));
+       comp=SSL_get_current_compression(ssl);
+       if (comp) {
+               Conn_OPTION_ADD(c, CONN_SSL_COMPRESSION);
+               comp_alg = SSL_COMP_get_name(comp);
+       }
+       Log(LOG_INFO, "Connection %d: initialized %s using cipher %s, %s.",
+               c->sock, SSL_get_version(ssl), SSL_get_cipher(ssl), comp_alg);
+       client_cert = SSL_get_peer_certificate(ssl);
+       if (client_cert) {
+               int err = SSL_get_verify_result(ssl);
+               if (err == X509_V_OK)
+                       cert_ok = true;
+               else
+                       Log(LOG_ERR, "Certificate Validation failed: %s", X509_verify_cert_error_string(err));
+               X509_NAME *subjectName;
+               char cn[256];
+               subjectName = X509_get_subject_name(client_cert);
+               X509_NAME_get_text_by_NID(
+                           subjectName, NID_commonName, cn, sizeof(cn));
+               if (strcmp (cn, c->host) == 0)
+                       cn_match = true;
+               else
+                       Log(LOG_ERR, "CN mismatch! Got \"%s\", expected \"%s\"", cn, c->host);
+
+               snprintf(msg, sizeof(msg), "%svalid peer certificate", cert_ok ? "":"in");
+               LogOpenSSL_CertInfo(client_cert, msg);
+               X509_free(client_cert);
+               cert_seen = true;
+       }
 #endif
 #ifdef HAVE_LIBGNUTLS
+       unsigned int status;
+       int ret;
+       gnutls_credentials_type_t cred;
        gnutls_session_t sess = c->ssl_state.gnutls_session;
        gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(sess);
+       gnutls_compression_method_t comp = gnutls_compression_get(sess);
 
-       Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s.",
+       if (comp != GNUTLS_COMP_NULL)
+               comp_alg = gnutls_compression_get_name(comp);
+       Log(LOG_INFO, "Connection %d: initialized %s using cipher %s-%s, %s.",
            c->sock,
            gnutls_protocol_get_name(gnutls_protocol_get_version(sess)),
            gnutls_cipher_get_name(cipher),
-           gnutls_mac_get_name(gnutls_mac_get(sess)));
+           gnutls_mac_get_name(gnutls_mac_get(sess)),
+            comp_alg);
+       ret = gnutls_certificate_verify_peers2(c->ssl_state.gnutls_session, &status);
+       if (ret < 0)
+               Log(LOG_ERR, "gnutls_certificate_verify_peers2 failed: %s", gnutls_strerror(ret));
+       if (ret == 0 && check_verification(status))
+               cert_ok = true;
+
+       cred = gnutls_auth_get_type (c->ssl_state.gnutls_session);
+       if (cred == GNUTLS_CRD_CERTIFICATE) {
+               gnutls_x509_crt_t cert;
+               unsigned cert_list_size;
+               const gnutls_datum_t *cert_list = gnutls_certificate_get_peers(sess, &cert_list_size);
+               if (!cert_list) {
+                       Log(LOG_ERR, "gnutls_certificate_get_peers() failed");
+                       return;
+               }
+               assert(cert_list_size > 0);
+               gnutls_x509_crt_init(&cert);
+               gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER);
+
+               char *cn;
+               size_t size = 0;
+               int err = gnutls_x509_crt_get_dn_by_oid(cert,
+                       GNUTLS_OID_X520_COMMON_NAME,
+                       0, 0, NULL, &size);
+               if (size == 0 || (err && err != GNUTLS_E_SHORT_MEMORY_BUFFER))
+                       goto done_cn_validation;
+               cn = LogMalloc(size);
+               if (!cn)
+                       goto done_cn_validation;
+               gnutls_x509_crt_get_dn_by_oid (cert,
+                       GNUTLS_OID_X520_COMMON_NAME,
+                       0, 0, cn, &size);
+               if (strcmp (cn, c->host) == 0)
+                       cn_match = true;
+               else
+                       Log(LOG_ERR, "CN mismatch! Got \"%s\", expected \"%s\"", cn, c->host);
+               free (cn);
+done_cn_validation:
+
+               snprintf(msg, sizeof(msg), "%svalid peer certificate", cert_ok ? "":"in");
+               LogGnuTLS_CertInfo(cert, msg);
+               gnutls_x509_crt_deinit(cert);
+               cert_seen = true;
+       }
 #endif
+       /*
+        * can be used later to check if connection was authenticated, e.g. if inbound connection
+        * tries to register itself as server. could also restrict /OPER to authenticated connections, etc.
+        */
+       if (cert_ok && cn_match)
+               Conn_OPTION_ADD(c, CONN_SSL_PEERCERT_OK);
+       if (!cert_seen)
+               Log(LOG_INFO, "Peer did not present a certificate");
 }
 
 
@@ -676,12 +977,15 @@ ConnSSL_Accept( CONNECTION *c )
        assert(c != NULL);
        if (!Conn_OPTION_ISSET(c, CONN_SSL)) {
 #ifdef HAVE_LIBGNUTLS
+               gnutls_certificate_request_t req;
                int err = gnutls_init(&c->ssl_state.gnutls_session, GNUTLS_SERVER);
                if (err) {
                        Log(LOG_ERR, "Failed to initialize new SSL session: %s",
                            gnutls_strerror(err));
                        return false;
                }
+               req = Conf_SSLOptions.RequireClientCert ? GNUTLS_CERT_REQUIRE : GNUTLS_CERT_REQUEST;
+               gnutls_certificate_server_set_request(c->ssl_state.gnutls_session, req);
 #endif
                if (!ConnSSL_Init_SSL(c))
                        return -1;
@@ -744,7 +1048,7 @@ ConnSSL_InitCertFp( CONNECTION *c )
                gnutls_x509_crt_deinit(cert);
                return 0;
        }
-       
+
        if (gnutls_x509_crt_import(cert, &cert_list[0],
                                   GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) {
                gnutls_x509_crt_deinit(cert);
index 62561544866413f5abb1534da27caac1e2aa2218..418728e3c39b1ab202dcf8266052fededa105abc 100644 (file)
@@ -269,6 +269,7 @@ server_login(CONN_ID idx)
                      Conf_ServerName, Conf_ServerInfo);
 }
 
+
 /**
  * IO callback for established non-SSL client and server connections.
  *
@@ -335,6 +336,48 @@ Conn_Init( void )
                Init_Conn_Struct(i);
 } /* Conn_Init */
 
+
+/*
+ * create protocol and server identification.
+ * The syntax used by ngIRCd in PASS commands and the extended flags
+ * are described in doc/Protocol.txt
+ *
+ * @param i connection index, may be < 0 to get compile-time constants
+ * @return pointer to static buffer with the connection flags matching i.
+ */
+GLOBAL const char*
+Conn_BuildProtoID(CONN_ID i)
+{
+       static char proto[256];
+#ifdef IRCPLUS
+       snprintf(proto, sizeof(proto), "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS);
+#ifdef ZLIB
+       /* don't bother with link compression if ssl already does it */
+#ifdef SSL_SUPPORT
+       if (i < 0 || !Conn_OPTION_ISSET(&My_Connections[i], CONN_SSL_COMPRESSION))
+#else
+       if (i < 0)
+#endif
+               strlcat(proto, "Z", sizeof(proto));
+#endif
+       if (Conf_OperCanMode)
+               strlcat(proto, "o", sizeof(proto));
+#else
+       snprintf(proto, sizeof(proto), "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION);
+#endif
+       strlcat(proto, " P", sizeof(proto));
+#ifdef ZLIB
+#ifdef SSL_SUPPORT
+       if (i < 0 || !Conn_OPTION_ISSET(&My_Connections[i], CONN_SSL_COMPRESSION))
+#else
+       if (i < 0)
+#endif
+               strlcat(proto, "Z", sizeof(proto));
+#endif
+       return proto;
+}
+
+
 /**
  * Clean up connection module.
  */
@@ -2523,6 +2566,7 @@ static void
 cb_connserver_login_ssl(int sock, short unused)
 {
        CONN_ID idx = Socket2Index(sock);
+       int serveridx;
 
        assert(idx >= 0);
        if (idx < 0) {
@@ -2540,10 +2584,25 @@ cb_connserver_login_ssl(int sock, short unused)
                        return;
        }
 
+       serveridx = Conf_GetServer(idx);
+       assert(serveridx >= 0);
+       if (serveridx < 0)
+               goto err;
+
        Log( LOG_INFO, "SSL connection %d with \"%s:%d\" established.", idx,
            My_Connections[idx].host, Conf_Server[Conf_GetServer( idx )].port );
 
+       if (Conf_Server[serveridx].SSLVerify &&
+                       !Conn_OPTION_ISSET(&My_Connections[idx], CONN_SSL_PEERCERT_OK))
+       {
+               Log(LOG_ERR, "SSLVerify enabled for %d, but peer certificate check failed", idx);
+               goto err;
+       }
        server_login(idx);
+       return;
+ err:
+       Log(LOG_ERR, "SSL connection on socket %d failed!", sock);
+       Conn_Close(idx, "Can't connect!", NULL, false);
 }
 
 
index c642541f07ce486b712f5a3b0e719a438d9ea8da..258dcb592456b97e8fda640a3055e8df69db85cd 100644 (file)
@@ -40,7 +40,9 @@
 #define CONN_SSL               32      /* this connection is SSL encrypted */
 #define CONN_SSL_WANT_WRITE    64      /* SSL/TLS library needs to write protocol data */
 #define CONN_SSL_WANT_READ     128     /* SSL/TLS library needs to read protocol data */
-#define CONN_SSL_FLAGS_ALL     (CONN_SSL_CONNECT|CONN_SSL|CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ)
+#define CONN_SSL_PEERCERT_OK   256     /* peer presented a valid certificate (used to check inbound server auth */
+#define CONN_SSL_COMPRESSION   512     /* SSL/TLS link is compressed */
+#define CONN_SSL_FLAGS_ALL     (CONN_SSL_CONNECT|CONN_SSL|CONN_SSL_WANT_WRITE|CONN_SSL_WANT_READ|CONN_SSL_PEERCERT_OK|CONN_SSL_COMPRESSION)
 #endif
 typedef int CONN_ID;
 
@@ -143,6 +145,7 @@ GLOBAL char *Conn_GetCertFp PARAMS((CONN_ID Idx));
 GLOBAL bool Conn_SetCertFp PARAMS((CONN_ID Idx, const char *fingerprint));
 GLOBAL bool Conn_UsesSSL PARAMS((CONN_ID Idx));
 
+GLOBAL const char* Conn_BuildProtoID PARAMS((CONN_ID i));
 #ifdef SSL_SUPPORT
 GLOBAL bool Conn_GetCipherInfo PARAMS((CONN_ID Idx, char *buf, size_t len));
 #endif
index 92186aff7fcdbae8d8a7e5c02f7c177e1d231281..6f64c3b2983d05c77d4b97e6034df0a70537d7e6 100644 (file)
@@ -97,6 +97,21 @@ IRC_SERVER( CLIENT *Client, REQUEST *Req )
                        return DISCONNECTED;
                }
 
+#ifdef SSL_SUPPORT
+               /*
+                * This check is only done if RequireClientCert is disabled, and this Servers [SERVER] section has
+                * "SSLVerify" enabled.
+                * (if RequireClientCert is set, certificate validation is done during SSL/TLS handshake)
+                */
+               CONN_ID con = Client_Conn (Client);
+               if (Conf_Server[i].SSLVerify && !(Conn_Options(con) & CONN_SSL_PEERCERT_OK)) {
+                       Log(LOG_ERR, "Connection %d: SSLVerify is set, and server \"%s\" did not present a valid certificate",
+                                                                               Client_Conn(Client), Req->argv[0]);
+                       Conn_Close(Client_Conn(Client), NULL, "No valid SSL certificate", true);
+                       return DISCONNECTED;
+               }
+#endif
+
                /* Is there a registered server with this ID? */
                if (!Client_CheckID(Client, Req->argv[0]))
                        return DISCONNECTED;