LCOV - code coverage report
Current view: top level - src/tds - tls.c (source / functions) Hit Total Coverage
Test: FreeTDS coverage Lines: 330 431 76.6 %
Date: 2026-11-25 04:57:11 Functions: 22 26 84.6 %

          Line data    Source code
       1             : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
       2             :  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003  Brian Bruns
       3             :  * Copyright (C) 2004-2015  Ziglio Frediano
       4             :  *
       5             :  * This library is free software; you can redistribute it and/or
       6             :  * modify it under the terms of the GNU Library General Public
       7             :  * License as published by the Free Software Foundation; either
       8             :  * version 2 of the License, or (at your option) any later version.
       9             :  *
      10             :  * This library is distributed in the hope that it will be useful,
      11             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      13             :  * Library General Public License for more details.
      14             :  *
      15             :  * You should have received a copy of the GNU Library General Public
      16             :  * License along with this library; if not, write to the
      17             :  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
      18             :  * Boston, MA 02111-1307, USA.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : 
      23             : /* enabled some additional definitions for inet_pton */
      24             : #define _WIN32_WINNT 0x600
      25             : 
      26             : #include <stdio.h>
      27             : 
      28             : #if HAVE_ERRNO_H
      29             : #include <errno.h>
      30             : #endif /* HAVE_ERRNO_H */
      31             : 
      32             : #if HAVE_UNISTD_H
      33             : #include <unistd.h>
      34             : #endif /* HAVE_UNISTD_H */
      35             : 
      36             : #if HAVE_STDLIB_H
      37             : #include <stdlib.h>
      38             : #endif /* HAVE_STDLIB_H */
      39             : 
      40             : #if HAVE_STRING_H
      41             : #include <string.h>
      42             : #endif /* HAVE_STRING_H */
      43             : 
      44             : #if HAVE_DIRENT_H
      45             : #include <dirent.h>
      46             : #endif /* HAVE_DIRENT_H */
      47             : 
      48             : #if HAVE_SYS_STAT_H
      49             : #include <sys/stat.h>
      50             : #endif /* HAVE_SYS_STAT_H */
      51             : 
      52             : #ifdef HAVE_SYS_SOCKET_H
      53             : #include <sys/socket.h>
      54             : #endif
      55             : 
      56             : #include <freetds/tds.h>
      57             : #include <freetds/utils/string.h>
      58             : #include <freetds/utils.h>
      59             : #include <freetds/tds/tls.h>
      60             : #include <freetds/alloca.h>
      61             : #include <freetds/replacements.h>
      62             : 
      63             : #include <assert.h>
      64             : 
      65             : /**
      66             :  * \addtogroup network
      67             :  * @{ 
      68             :  */
      69             : 
      70             : #if defined(HAVE_GNUTLS) || defined(HAVE_OPENSSL)
      71             : 
      72             : #ifdef HAVE_GNUTLS
      73             : #define SSL_RET ssize_t
      74             : #define SSL_PULL_ARGS gnutls_transport_ptr_t ptr, void *data, size_t len
      75             : #define SSL_PUSH_ARGS gnutls_transport_ptr_t ptr, const void *data, size_t len
      76             : #define SSL_PTR ptr
      77             : #else
      78             : 
      79             : /* some compatibility layer */
      80             : #if !HAVE_BIO_GET_DATA
      81             : static inline void
      82             : BIO_set_init(BIO *b, int init)
      83             : {
      84             :         b->init = init;
      85             : }
      86             : 
      87             : static inline void
      88             : BIO_set_data(BIO *b, void *ptr)
      89             : {
      90             :         b->ptr = ptr;
      91             : }
      92             : 
      93             : static inline void *
      94             : BIO_get_data(const BIO *b)
      95             : {
      96             :         return b->ptr;
      97             : }
      98             : #define TLS_client_method SSLv23_client_method
      99             : #define TLS_ST_OK SSL_ST_OK
     100             : #endif
     101             : 
     102             : #define SSL_RET int
     103             : #define SSL_PULL_ARGS BIO *bio, char *data, int len
     104             : #define SSL_PUSH_ARGS BIO *bio, const char *data, int len
     105             : #define SSL_PTR BIO_get_data(bio)
     106             : #endif
     107             : 
     108             : #if !HAVE_ASN1_STRING_GET0_DATA
     109             : #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
     110             : #endif
     111             : 
     112             : #if ENABLE_ODBC_MARS
     113             : #define CONN2TDS(conn) (conn->in_net_tds)
     114             : #else
     115             : #define CONN2TDS(conn) ((TDSSOCKET *) conn)
     116             : #endif
     117             : 
     118             : /* tds/8.0 */
     119             : #define TDS8_ALPN_ARRAY 't', 'd', 's', '/', '8', '.', '0'
     120             : #define TDS8_ALPN_ARRAY_LEN 7
     121             : 
     122             : /* channel binding types, see RFC 5929 */
     123             : #define TDS_CB_TLS_UNIQUE "tls-unique:"
     124             : #define TDS_CB_TLS_SERVER_END_POINT "tls-server-end-point:"
     125             : 
     126             : /**
     127             :  * Fill channel binding application data with given prefix and data.
     128             :  * @param cb      output buffer
     129             :  * @param cblen   output buffer size
     130             :  * @param prefix  channel binding type prefix, including the final colon
     131             :  * @param data    channel binding data
     132             :  * @param data_len channel binding data length
     133             :  * @return length of application data or 0 on error
     134             :  */
     135             : static size_t
     136         778 : tds_ssl_fill_cb(void *cb, size_t cblen, const char *prefix, const void *data, size_t data_len)
     137             : {
     138         778 :         size_t prefix_len = strlen(prefix);
     139             : 
     140         778 :         if (data_len == 0 || prefix_len + data_len > cblen) {
     141           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: no space for %s channel binding\n", prefix);
     142             :                 return 0;
     143             :         }
     144         778 :         memcpy(cb, prefix, prefix_len);
     145         778 :         memcpy((char *) cb + prefix_len, data, data_len);
     146         778 :         return prefix_len + data_len;
     147             : }
     148             : 
     149             : static SSL_RET
     150       20424 : tds_pull_func_login(SSL_PULL_ARGS)
     151             : {
     152       20424 :         TDSSOCKET *tds = (TDSSOCKET *) SSL_PTR;
     153             :         int have;
     154             : 
     155       20424 :         tdsdump_log(TDS_DBG_FUNC, "in tds_pull_func_login\n");
     156             :         
     157             :         /* here we are initializing (crypted inside TDS packets) */
     158             : 
     159             :         /* if we have some data send it */
     160             :         /* here MARS is not already initialized so test is correct */
     161             :         /* TODO test even after initializing ?? */
     162       20424 :         if (tds->out_pos > 8)
     163        4712 :                 tds_flush_packet(tds);
     164             : 
     165             :         for(;;) {
     166       25136 :                 have = tds->in_len - tds->in_pos;
     167       25136 :                 assert(have >= 0);
     168       25136 :                 if (have > 0)
     169             :                         break;
     170        4712 :                 if (tds_read_packet(tds) < 0)
     171             :                         return -1;
     172             :         }
     173       20424 :         if (len > have)
     174           0 :                 len = have;
     175       20424 :         memcpy(data, tds->in_buf + tds->in_pos, len);
     176       20424 :         tds->in_pos += len;
     177       20424 :         return len;
     178             : }
     179             : 
     180             : static SSL_RET
     181        7068 : tds_push_func_login(SSL_PUSH_ARGS)
     182             : {
     183        7068 :         TDSSOCKET *tds = (TDSSOCKET *) SSL_PTR;
     184             : 
     185        7068 :         tdsdump_log(TDS_DBG_FUNC, "in tds_push_func_login\n");
     186             : 
     187             :         /* initializing SSL, write crypted data inside normal TDS packets */
     188        7068 :         tds_put_n(tds, data, len);
     189        7068 :         return len;
     190             : }
     191             : 
     192             : static SSL_RET
     193       94427 : tds_pull_func(SSL_PULL_ARGS)
     194             : {
     195       94427 :         TDSCONNECTION *conn = (TDSCONNECTION *) SSL_PTR;
     196             :         TDSSOCKET *tds;
     197             : 
     198       94427 :         tdsdump_log(TDS_DBG_FUNC, "in tds_pull_func\n");
     199             : 
     200       94427 :         tds = CONN2TDS(conn);
     201       94427 :         assert(tds);
     202             : 
     203             :         /* already initialized (crypted TDS packets) */
     204             : 
     205             :         /* read directly from socket */
     206             :         /* TODO we block write on other sessions */
     207             :         /* also we should already have tested for data on socket */
     208       94427 :         return tds_goodread(tds, (unsigned char*) data, len);
     209             : }
     210             : 
     211             : static SSL_RET
     212       39899 : tds_push_func(SSL_PUSH_ARGS)
     213             : {
     214       39899 :         TDSCONNECTION *conn = (TDSCONNECTION *) SSL_PTR;
     215             :         TDSSOCKET *tds;
     216             : 
     217       39899 :         tdsdump_log(TDS_DBG_FUNC, "in tds_push_func\n");
     218             : 
     219             :         /* write to socket directly */
     220       39899 :         tds = CONN2TDS(conn);
     221       39899 :         return tds_goodwrite(tds, (const unsigned char*) data, len);
     222             : }
     223             : 
     224             : static int tls_initialized = 0;
     225             : static tds_mutex tls_mutex = TDS_MUTEX_INITIALIZER;
     226             : 
     227             : #if ENABLE_ODBC_MARS
     228             : static void
     229             : set_current_tds(TDSCONNECTION *conn, TDSSOCKET *tds)
     230             : {
     231        1178 :         tds_mutex_lock(&conn->list_mtx);
     232        1178 :         conn->in_net_tds = tds;
     233        1178 :         tds_mutex_unlock(&conn->list_mtx);
     234             : }
     235             : #else
     236             : static inline void
     237             : set_current_tds(TDSCONNECTION *conn TDS_UNUSED, TDSSOCKET *tds TDS_UNUSED)
     238             : {
     239             : }
     240             : #endif
     241             : 
     242             : static const char *
     243             : wanted_certificate_hostname(TDSLOGIN *login)
     244             : {
     245        2356 :         if (!tds_dstr_isempty(&login->certificate_host_name))
     246           0 :                 return tds_dstr_cstr(&login->certificate_host_name);
     247             : 
     248        1178 :         return tds_dstr_cstr(&login->server_host_name);
     249             : }
     250             : 
     251             : #ifdef HAVE_GNUTLS
     252             : 
     253             : /**
     254             :  * Error for GnuTLS when pull functions fail.
     255             :  * Our pull functions block, so a failure is never a temporary one;
     256             :  * returning a fixed error avoids GnuTLS reporting GNUTLS_E_AGAIN or
     257             :  * GNUTLS_E_INTERRUPTED due to a stale errno.
     258             :  */
     259             : static int
     260          12 : tds_pull_errno(gnutls_transport_ptr_t ptr TDS_UNUSED)
     261             : {
     262          12 :         return EIO;
     263             : }
     264             : 
     265             : static void
     266         366 : tds_tls_log(int level, const char *s)
     267             : {
     268         366 :         tdsdump_log(TDS_DBG_INFO1, "GNUTLS: level %d:\n  %s", level, s);
     269         366 : }
     270             : 
     271             : #ifdef TDS_ATTRIBUTE_DESTRUCTOR
     272             : static void __attribute__((destructor))
     273        1302 : tds_tls_deinit(void)
     274             : {
     275        1302 :         if (tls_initialized)
     276         667 :                 gnutls_global_deinit();
     277        1302 : }
     278             : #endif
     279             : 
     280             : #if defined(_THREAD_SAFE) && defined(TDS_HAVE_PTHREAD_MUTEX) && !defined(GNUTLS_USE_NETTLE)
     281             : GCRY_THREAD_OPTION_PTHREAD_IMPL;
     282             : #define tds_gcry_init() gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
     283             : #else
     284             : #define tds_gcry_init() do {} while(0)
     285             : #endif
     286             : 
     287             : /* This piece of code is copied from GnuTLS new sources to handle IP in the certificate */
     288             : #if GNUTLS_VERSION_NUMBER < 0x030306
     289             : static int
     290             : check_ip(gnutls_x509_crt_t cert, const void *ip, unsigned ip_size)
     291             : {
     292             :         char temp[16];
     293             :         size_t temp_size;
     294             :         unsigned i;
     295             :         int ret = 0;
     296             : 
     297             :         /* try matching against:
     298             :          *  1) a IPaddress alternative name (subjectAltName) extension
     299             :          *     in the certificate
     300             :          */
     301             : 
     302             :         /* Check through all included subjectAltName extensions, comparing
     303             :          * against all those of type IPAddress.
     304             :          */
     305             :         for (i = 0; ret >= 0; ++i) {
     306             :                 temp_size = sizeof(temp);
     307             :                 ret = gnutls_x509_crt_get_subject_alt_name(cert, i,
     308             :                                                            temp,
     309             :                                                            &temp_size,
     310             :                                                            NULL);
     311             : 
     312             :                 if (ret == GNUTLS_SAN_IPADDRESS) {
     313             :                         if (temp_size == ip_size && memcmp(temp, ip, ip_size) == 0)
     314             :                                 return 1;
     315             :                 } else if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
     316             :                         ret = 0;
     317             :                 }
     318             :         }
     319             : 
     320             :         /* not found a matching IP */
     321             :         return 0;
     322             : }
     323             : 
     324             : static int
     325             : tds_check_ip(gnutls_x509_crt_t cert, const char *hostname)
     326             : {
     327             :         int ret;
     328             :         union {
     329             :                 struct in_addr v4;
     330             :                 struct in6_addr v6;
     331             :         } ip;
     332             :         unsigned ip_size;
     333             : 
     334             :         /* check whether @hostname is an ip address */
     335             :         if (strchr(hostname, ':') != NULL) {
     336             :                 ip_size = 16;
     337             :                 ret = inet_pton(AF_INET6, hostname, &ip.v6);
     338             :         } else {
     339             :                 ip_size = 4;
     340             :                 ret = inet_pton(AF_INET, hostname, &ip.v4);
     341             :         }
     342             : 
     343             :         if (ret != 0)
     344             :                 ret = check_ip(cert, &ip, ip_size);
     345             : 
     346             :         /* There are several misconfigured servers, that place their IP
     347             :          * in the DNS field of subjectAlternativeName. Don't break these
     348             :          * configurations and verify the IP as it would have been a DNS name. */
     349             : 
     350             :         return ret;
     351             : }
     352             : 
     353             : /* function for replacing old GnuTLS version */
     354             : static int
     355             : tds_x509_crt_check_hostname(gnutls_x509_crt_t cert, const char *hostname)
     356             : {
     357             :         int ret;
     358             : 
     359             :         ret = tds_check_ip(cert, hostname);
     360             :         if (ret)
     361             :                 return ret;
     362             : 
     363             :         return gnutls_x509_crt_check_hostname(cert, hostname);
     364             : }
     365             : #define gnutls_x509_crt_check_hostname tds_x509_crt_check_hostname
     366             : 
     367             : #endif
     368             : 
     369             : #if GNUTLS_VERSION_MAJOR < 3
     370             : static int
     371             : tds_certificate_set_x509_system_trust(gnutls_certificate_credentials_t cred)
     372             : {
     373             :         static const char ca_directory[] = "/etc/ssl/certs";
     374             :         DIR *dir;
     375             :         struct dirent *dent;
     376             : #ifdef HAVE_READDIR_R
     377             :         struct dirent ent;
     378             : #endif
     379             :         int rc;
     380             :         int ncerts;
     381             :         size_t ca_file_length;
     382             :         char *ca_file;
     383             : 
     384             : 
     385             :         dir = opendir(ca_directory);
     386             :         if (!dir)
     387             :                 return 0;
     388             : 
     389             :         ca_file_length = strlen(ca_directory) + sizeof(dent->d_name) + 2;
     390             :         ca_file = alloca(ca_file_length);
     391             : 
     392             :         ncerts = 0;
     393             :         for (;;) {
     394             :                 struct stat st;
     395             : 
     396             : #ifdef HAVE_READDIR_R
     397             :                 if (readdir_r(dir, &ent, &dent))
     398             :                         dent = NULL;
     399             : #else
     400             :                 dent = readdir(dir);
     401             : #endif
     402             :                 if (!dent)
     403             :                         break;
     404             : 
     405             :                 snprintf(ca_file, ca_file_length, "%s/%s", ca_directory, dent->d_name);
     406             :                 if (stat(ca_file, &st) != 0)
     407             :                         continue;
     408             : 
     409             :                 if (!S_ISREG(st.st_mode))
     410             :                         continue;
     411             : 
     412             :                 rc = gnutls_certificate_set_x509_trust_file(cred, ca_file, GNUTLS_X509_FMT_PEM);
     413             :                 if (rc >= 0)
     414             :                         ncerts += rc;
     415             :         }
     416             : 
     417             :         closedir(dir);
     418             :         return ncerts;
     419             : }
     420             : #define gnutls_certificate_set_x509_system_trust tds_certificate_set_x509_system_trust
     421             : 
     422             : #endif
     423             : 
     424             : static int
     425           0 : tds_verify_certificate(gnutls_session_t session, TDSSOCKET *tds)
     426             : {
     427             :         unsigned int status;
     428             :         int ret;
     429             : 
     430             : #ifdef ENABLE_DEVELOPING
     431             :         unsigned int list_size;
     432             :         const gnutls_datum_t *cert_list;
     433             : #endif
     434             : 
     435           0 :         if (!tds->login) {
     436           0 :                 tdsdump_log(TDS_DBG_ERROR, "No login while checking certificate\n");
     437             :                 return GNUTLS_E_CERTIFICATE_ERROR;
     438             :         }
     439             : 
     440           0 :         ret = gnutls_certificate_verify_peers2(session, &status);
     441           0 :         if (ret < 0) {
     442           0 :                 tdsdump_log(TDS_DBG_ERROR, "Error verifying certificate: %s\n", gnutls_strerror(ret));
     443             :                 return GNUTLS_E_CERTIFICATE_ERROR;
     444             :         }
     445             : 
     446             : #ifdef ENABLE_DEVELOPING
     447             :         cert_list = gnutls_certificate_get_peers(session, &list_size);
     448             :         if (cert_list) {
     449             :                 gnutls_x509_crt_t cert;
     450             :                 gnutls_datum_t cinfo;
     451             :                 char buf[8192];
     452             :                 size_t size;
     453             : 
     454             :                 gnutls_x509_crt_init(&cert);
     455             : 
     456             :                 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
     457             : 
     458             :                 /* This is the preferred way of printing short information about
     459             :                  * a certificate. */
     460             :                 size = sizeof(buf);
     461             :                 ret = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_PEM, buf, &size);
     462             :                 if (ret == 0) {
     463             :                         FILE *f = fopen("cert.dat", "wb");
     464             :                         if (f) {
     465             :                                 fwrite(buf, size, 1, f);
     466             :                                 fclose(f);
     467             :                         }
     468             :                 }
     469             : 
     470             :                 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
     471             :                 if (ret == 0) {
     472             :                         tdsdump_log(TDS_DBG_INFO1, "Certificate info: %s\n", cinfo.data);
     473             :                         gnutls_free(cinfo.data);
     474             :                 }
     475             : 
     476             :                 gnutls_x509_crt_deinit(cert);
     477             :         }
     478             : #endif
     479             : 
     480             :         /* Certificate is not trusted */
     481           0 :         if (status != 0) {
     482           0 :                 tdsdump_log(TDS_DBG_ERROR, "Certificate status: %u\n", status);
     483             :                 return GNUTLS_E_CERTIFICATE_ERROR;
     484             :         }
     485             : 
     486             :         /* check hostname */
     487           0 :         if (tds->login->check_ssl_hostname) {
     488             :                 const gnutls_datum_t *cert_list;
     489             :                 unsigned int list_size;
     490             :                 gnutls_x509_crt_t cert;
     491             : 
     492           0 :                 cert_list = gnutls_certificate_get_peers(session, &list_size);
     493           0 :                 if (!cert_list) {
     494           0 :                         tdsdump_log(TDS_DBG_ERROR, "Error getting TLS session peers\n");
     495           0 :                         return GNUTLS_E_CERTIFICATE_ERROR;
     496             :                 }
     497           0 :                 gnutls_x509_crt_init(&cert);
     498           0 :                 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
     499           0 :                 ret = gnutls_x509_crt_check_hostname(cert, wanted_certificate_hostname(tds->login));
     500           0 :                 gnutls_x509_crt_deinit(cert);
     501           0 :                 if (!ret) {
     502           0 :                         tdsdump_log(TDS_DBG_ERROR, "Certificate hostname does not match\n");
     503             :                         return GNUTLS_E_CERTIFICATE_ERROR;
     504             :                 }
     505             :         }
     506             : 
     507             :         /* notify gnutls to continue handshake normally */
     508             :         return 0;
     509             : }
     510             : 
     511             : static int
     512           0 : tds_verify_certificate_tds(gnutls_session_t session)
     513             : {
     514           0 :         TDSSOCKET *tds = (TDSSOCKET *) gnutls_transport_get_ptr(session);
     515             : 
     516           0 :         return tds_verify_certificate(session, tds);
     517             : }
     518             : 
     519             : static int
     520           0 : tds_verify_certificate_conn(gnutls_session_t session)
     521             : {
     522           0 :         TDSCONNECTION *conn = (TDSCONNECTION*) gnutls_transport_get_ptr(session);
     523             : 
     524           0 :         return tds_verify_certificate(session, CONN2TDS(conn));
     525             : }
     526             : 
     527             : TDSRET
     528        1178 : tds_ssl_init(TDSSOCKET *tds, bool full)
     529             : {
     530             :         gnutls_session_t session;
     531             :         gnutls_certificate_credentials_t xcred;
     532             :         int ret;
     533             :         const char *tls_msg;
     534             :         int (*verify_func)(gnutls_session_t session);
     535             : 
     536        1178 :         xcred = NULL;
     537        1178 :         session = NULL; 
     538        1178 :         tls_msg = "initializing tls";
     539             : 
     540        1178 :         if (!tls_initialized) {
     541         667 :                 ret = 0;
     542         667 :                 tds_mutex_lock(&tls_mutex);
     543         667 :                 if (!tls_initialized) {
     544             :                         tds_gcry_init();
     545         667 :                         ret = gnutls_global_init();
     546         667 :                         if (ret == 0)
     547         667 :                                 tls_initialized = 1;
     548             :                 }
     549         667 :                 tds_mutex_unlock(&tls_mutex);
     550         667 :                 if (ret != 0)
     551             :                         goto cleanup;
     552             :         }
     553             : 
     554        1178 :         if (tds_write_dump && tls_initialized < 2) {
     555           2 :                 gnutls_global_set_log_level(11);
     556           2 :                 gnutls_global_set_log_function(tds_tls_log);
     557           2 :                 tls_initialized = 2;
     558             :         }
     559             : 
     560        1178 :         tls_msg = "allocating credentials";
     561        1178 :         ret = gnutls_certificate_allocate_credentials(&xcred);
     562        1178 :         if (ret != 0)
     563             :                 goto cleanup;
     564             : 
     565             :         /* Initialize TLS session */
     566        1178 :         tls_msg = "initializing session";
     567        1178 :         ret = gnutls_init(&session, GNUTLS_CLIENT);
     568        1178 :         if (ret != 0)
     569             :                 goto cleanup;
     570        1178 :         gnutls_transport_set_errno_function(session, tds_pull_errno);
     571             : 
     572        1178 :         if (!full) {
     573        1178 :                 gnutls_transport_set_ptr(session, tds);
     574        1178 :                 gnutls_transport_set_pull_function(session, tds_pull_func_login);
     575        1178 :                 gnutls_transport_set_push_function(session, tds_push_func_login);
     576        1178 :                 verify_func = tds_verify_certificate_tds;
     577             :         } else {
     578           0 :                 gnutls_transport_set_ptr(session, tds->conn);
     579           0 :                 gnutls_transport_set_pull_function(session, tds_pull_func);
     580           0 :                 gnutls_transport_set_push_function(session, tds_push_func);
     581           0 :                 verify_func = tds_verify_certificate_conn;
     582             :         }
     583             : 
     584        2356 :         if (!tds_dstr_isempty(&tds->login->cafile)) {
     585           0 :                 tls_msg = "loading CA file";
     586           0 :                 if (strcasecmp(tds_dstr_cstr(&tds->login->cafile), "system") == 0)
     587           0 :                         ret = gnutls_certificate_set_x509_system_trust(xcred);
     588             :                 else
     589           0 :                         ret = gnutls_certificate_set_x509_trust_file(xcred, tds_dstr_cstr(&tds->login->cafile), GNUTLS_X509_FMT_PEM);
     590           0 :                 if (ret <= 0)
     591             :                         goto cleanup;
     592           0 :                 if (!tds_dstr_isempty(&tds->login->crlfile)) {
     593           0 :                         tls_msg = "loading CRL file";
     594           0 :                         ret = gnutls_certificate_set_x509_crl_file(xcred, tds_dstr_cstr(&tds->login->crlfile), GNUTLS_X509_FMT_PEM);
     595           0 :                         if (ret <= 0)
     596             :                                 goto cleanup;
     597             :                 }
     598             : #ifdef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
     599           0 :                 gnutls_certificate_set_verify_function(xcred, verify_func);
     600             : #endif
     601             :         }
     602             : 
     603             :         /* use default priorities unless overridden by gnutls ciphers setting in freetds.conf file... */
     604        2356 :         if (!tds_dstr_isempty(&tds->login->gnutls_ciphers)) {
     605           0 :                 tdsdump_log(TDS_DBG_INFO1, "setting custom gnutls ciphers to:%s\n", tds_dstr_cstr(&tds->login->gnutls_ciphers));
     606           0 :                 gnutls_priority_set_direct(session, tds_dstr_cstr(&tds->login->gnutls_ciphers), NULL);
     607             :         } else {
     608             :                 /* NOTE: these functions return int however they cannot fail */
     609             : 
     610             :                 /* use default priorities... */
     611        1178 :                 gnutls_set_default_priority(session);
     612             : 
     613             : #ifdef HAVE_GNUTLS_SET_DEFAULT_PRIORITY_APPEND
     614             :                 gnutls_session_enable_compatibility_mode(session);
     615             : #define set_ciphers(session, ciphers) \
     616             :         gnutls_set_default_priority_append(session, "" ciphers, NULL, 0)
     617             : #else
     618             : #define set_ciphers(session, ciphers) \
     619             :         gnutls_priority_set_direct(session, "NORMAL:%COMPAT:" ciphers, NULL)
     620             : #endif
     621             : 
     622             :                 /* ... but overwrite some */
     623        1178 :                 if (tds->login && tds->login->enable_tls_v1)
     624         785 :                         ret = set_ciphers(session, "-VERS-SSL3.0:+VERS-TLS1.0:+VERS-TLS1.1");
     625         393 :                 else if (tds->login && tds->login->enable_tls_v1_1)
     626           0 :                         ret = set_ciphers(session, "-VERS-SSL3.0:-VERS-TLS1.0:+VERS-TLS1.1");
     627             :                 else
     628         393 :                         ret = set_ciphers(session, "-VERS-SSL3.0:-VERS-TLS1.0:-VERS-TLS1.1");
     629        1178 :                 if (ret != 0)
     630             :                         goto cleanup;
     631             :         }
     632             : 
     633             :         /* mssql does not like padding too much */
     634             : #ifdef HAVE_GNUTLS_RECORD_DISABLE_PADDING
     635        1178 :         gnutls_record_disable_padding(session);
     636             : #endif
     637             : 
     638             :         /* put the anonymous credentials to the current session */
     639        1178 :         tls_msg = "setting credential";
     640        1178 :         ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
     641        1178 :         if (ret != 0)
     642             :                 goto cleanup;
     643             : 
     644             : #ifdef HAVE_GNUTLS_ALPN_SET_PROTOCOLS
     645        1178 :         if (IS_TDS80_PLUS(tds->conn)) {
     646             :                 static const unsigned char alpn[] = { TDS8_ALPN_ARRAY };
     647             :                 static const gnutls_datum_t tds8_alpn = { (void*) alpn, sizeof(alpn) };
     648           0 :                 gnutls_alpn_set_protocols(session, &tds8_alpn, 1, 0);
     649             :         }
     650             : #endif
     651             : 
     652        1178 :         if (full)
     653           0 :                 set_current_tds(tds->conn, tds);
     654             : 
     655             :         /* Perform the TLS handshake */
     656        1178 :         tls_msg = "handshake";
     657        1178 :         ret = gnutls_handshake (session);
     658        1178 :         if (ret != 0)
     659             :                 goto cleanup;
     660             : 
     661             : #ifndef HAVE_GNUTLS_CERTIFICATE_SET_VERIFY_FUNCTION
     662             :         if (!tds_dstr_isempty(&tds->login->cafile)) {
     663             :                 ret = tds_verify_certificate(session, tds);
     664             :                 if (ret != 0)
     665             :                         goto cleanup;
     666             :         }
     667             : #endif
     668             : 
     669        1178 :         tdsdump_log(TDS_DBG_INFO1, "handshake succeeded!!\n");
     670             : 
     671        1178 :         if (!full) {
     672             :                 /* some TLS implementations send some sort of paddind at the end, remove it */
     673        1178 :                 tds->in_pos = tds->in_len;
     674             : 
     675        1178 :                 gnutls_transport_set_ptr(session, tds->conn);
     676        1178 :                 gnutls_transport_set_pull_function(session, tds_pull_func);
     677        1178 :                 gnutls_transport_set_push_function(session, tds_push_func);
     678             :         }
     679             : 
     680        2356 :         set_current_tds(tds->conn, NULL);
     681             : 
     682        1178 :         tds->conn->tls_session = session;
     683        1178 :         tds->conn->tls_credentials = xcred;
     684             : 
     685        1178 :         return TDS_SUCCESS;
     686             : 
     687           0 : cleanup:
     688           0 :         if (session)
     689           0 :                 gnutls_deinit(session);
     690           0 :         set_current_tds(tds->conn, NULL);
     691           0 :         if (xcred)
     692           0 :                 gnutls_certificate_free_credentials(xcred);
     693           0 :         tdsdump_log(TDS_DBG_ERROR, "%s failed: %s\n", tls_msg, gnutls_strerror (ret));
     694             :         return TDS_FAIL;
     695             : }
     696             : 
     697             : void
     698        5306 : tds_ssl_deinit(TDSCONNECTION *conn)
     699             : {
     700        5306 :         if (conn->tls_session) {
     701        1178 :                 gnutls_deinit((gnutls_session_t) conn->tls_session);
     702        1178 :                 conn->tls_session = NULL;
     703             :         }
     704        5306 :         if (conn->tls_credentials) {
     705        1178 :                 gnutls_certificate_free_credentials((gnutls_certificate_credentials_t) conn->tls_credentials);
     706        1178 :                 conn->tls_credentials = NULL;
     707             :         }
     708        5306 :         conn->encrypt_single_packet = 0;
     709        5306 : }
     710             : 
     711             : #if GNUTLS_VERSION_NUMBER >= 0x030603
     712             : /**
     713             :  * Compute the "tls-server-end-point" hash of a certificate (RFC 5929, section 4.1).
     714             :  * The hash function is the one used by the certificate signature, MD5 and SHA-1 are replaced by SHA-256.
     715             :  * @param der      certificate in DER format
     716             :  * @param hash     output buffer
     717             :  * @param hash_len output buffer size
     718             :  * @return hash length or 0 on error
     719             :  */
     720             : static size_t
     721             : tds_ssl_end_point_hash(const gnutls_datum_t *der, unsigned char *hash, size_t hash_len)
     722             : {
     723             :         gnutls_x509_crt_t cert;
     724             :         gnutls_digest_algorithm_t dig;
     725             :         int sign_algo;
     726             :         size_t len;
     727             : 
     728             :         if (gnutls_x509_crt_init(&cert) < 0)
     729             :                 return 0;
     730             :         if (gnutls_x509_crt_import(cert, der, GNUTLS_X509_FMT_DER) < 0) {
     731             :                 gnutls_x509_crt_deinit(cert);
     732             :                 return 0;
     733             :         }
     734             :         sign_algo = gnutls_x509_crt_get_signature_algorithm(cert);
     735             :         gnutls_x509_crt_deinit(cert);
     736             :         if (sign_algo < 0)
     737             :                 return 0;
     738             : 
     739             :         dig = gnutls_sign_get_hash_algorithm((gnutls_sign_algorithm_t) sign_algo);
     740             :         if (dig == GNUTLS_DIG_MD5 || dig == GNUTLS_DIG_SHA1)
     741             :                 dig = GNUTLS_DIG_SHA256;
     742             :         if (dig == GNUTLS_DIG_UNKNOWN)
     743             :                 return 0;
     744             :         len = gnutls_hash_get_len(dig);
     745             :         if (len == 0 || len > hash_len)
     746             :                 return 0;
     747             :         if (gnutls_hash_fast(dig, der->data, der->size, hash) < 0)
     748             :                 return 0;
     749             :         return len;
     750             : }
     751             : 
     752             : static size_t
     753             : tds_ssl_get_cb_end_point(gnutls_session_t session, void *cb, size_t cblen)
     754             : {
     755             :         const gnutls_datum_t *cert_list;
     756             :         unsigned int list_size = 0;
     757             :         unsigned char hash[64];
     758             :         size_t hash_len;
     759             : 
     760             :         cert_list = gnutls_certificate_get_peers(session, &list_size);
     761             :         if (!cert_list || list_size == 0) {
     762             :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: no server certificate for tls-server-end-point\n");
     763             :                 return 0;
     764             :         }
     765             :         hash_len = tds_ssl_end_point_hash(&cert_list[0], hash, sizeof(hash));
     766             :         if (hash_len == 0) {
     767             :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: failed to compute tls-server-end-point hash\n");
     768             :                 return 0;
     769             :         }
     770             :         return tds_ssl_fill_cb(cb, cblen, TDS_CB_TLS_SERVER_END_POINT, hash, hash_len);
     771             : }
     772             : #endif
     773             : 
     774             : size_t
     775         389 : tds_ssl_get_cb(TDSCONNECTION *conn, void *cb, size_t cblen)
     776             : {
     777             :         int rc;
     778             :         gnutls_datum_t unique;
     779         389 :         gnutls_session_t session = (gnutls_session_t) conn->tls_session;
     780             :         size_t len;
     781             : 
     782             :         /* No CBT, skip channel binding */
     783         389 :         if (!session)
     784             :                 return 0;
     785             : 
     786             : #if GNUTLS_VERSION_NUMBER >= 0x030603
     787             :         /* tls-unique is not defined for TLS 1.3 */
     788             :         if (gnutls_protocol_get_version(session) == GNUTLS_TLS1_3)
     789             :                 return tds_ssl_get_cb_end_point(session, cb, cblen);
     790             : #endif
     791             : 
     792         389 :         rc = gnutls_session_channel_binding(session, GNUTLS_CB_TLS_UNIQUE, &unique);
     793         389 :         if (rc) {
     794           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: failed to get tls-unique: %s\n", gnutls_strerror(rc));
     795             :                 return 0;
     796             :         }
     797         389 :         len = tds_ssl_fill_cb(cb, cblen, TDS_CB_TLS_UNIQUE, unique.data, unique.size);
     798         389 :         gnutls_free(unique.data);
     799         389 :         return len;
     800             : }
     801             : 
     802             : #else /* !HAVE_GNUTLS */
     803             : static long
     804        5890 : tds_ssl_ctrl_login(BIO *b TDS_UNUSED, int cmd, long num TDS_UNUSED, void *ptr TDS_UNUSED)
     805             : {
     806        5890 :         switch (cmd) {
     807             :         case BIO_CTRL_FLUSH:
     808             :                 return 1;
     809             :         }
     810        3534 :         return 0;
     811             : }
     812             : 
     813             : static int
     814        2356 : tds_ssl_free(BIO *a TDS_UNUSED)
     815             : {
     816             :         /* nothing to do but required */
     817        2356 :         return 1;
     818             : }
     819             : 
     820             : #if OPENSSL_VERSION_NUMBER < 0x1010000FL || defined(LIBRESSL_VERSION_NUMBER)
     821             : static BIO_METHOD tds_method_login[1] = {
     822             : {
     823             :         BIO_TYPE_MEM,
     824             :         "tds",
     825             :         tds_push_func_login,
     826             :         tds_pull_func_login,
     827             :         NULL,
     828             :         NULL,
     829             :         tds_ssl_ctrl_login,
     830             :         NULL,
     831             :         tds_ssl_free,
     832             :         NULL,
     833             : }};
     834             : 
     835             : static BIO_METHOD tds_method[1] = {
     836             : {
     837             :         BIO_TYPE_MEM,
     838             :         "tds",
     839             :         tds_push_func,
     840             :         tds_pull_func,
     841             :         NULL,
     842             :         NULL,
     843             :         NULL,
     844             :         NULL,
     845             :         tds_ssl_free,
     846             :         NULL,
     847             : }};
     848             : 
     849             : static inline void
     850             : tds_init_ssl_methods(void)
     851             : {
     852             : }
     853             : #else
     854             : static BIO_METHOD *tds_method_login;
     855             : static BIO_METHOD *tds_method;
     856             : 
     857             : static void
     858         667 : tds_init_ssl_methods(void)
     859             : {
     860             :         BIO_METHOD *meth;
     861             : 
     862         667 :         tds_method_login = meth = BIO_meth_new(BIO_TYPE_MEM, "tds");
     863         667 :         BIO_meth_set_write(meth, tds_push_func_login);
     864         667 :         BIO_meth_set_read(meth, tds_pull_func_login);
     865         667 :         BIO_meth_set_ctrl(meth, tds_ssl_ctrl_login);
     866         667 :         BIO_meth_set_destroy(meth, tds_ssl_free);
     867             : 
     868         667 :         tds_method = meth = BIO_meth_new(BIO_TYPE_MEM, "tds");
     869         667 :         BIO_meth_set_write(meth, tds_push_func);
     870         667 :         BIO_meth_set_read(meth, tds_pull_func);
     871         667 :         BIO_meth_set_ctrl(meth, tds_ssl_ctrl_login);
     872         667 :         BIO_meth_set_destroy(meth, tds_ssl_free);
     873         667 : }
     874             : 
     875             : #  ifdef TDS_ATTRIBUTE_DESTRUCTOR
     876             : static void __attribute__((destructor))
     877        1302 : tds_deinit_openssl_methods(void)
     878             : {
     879        1302 :         BIO_meth_free(tds_method_login);
     880        1302 :         BIO_meth_free(tds_method);
     881        1302 : }
     882             : #  endif
     883             : #endif
     884             : 
     885             : #if OPENSSL_VERSION_NUMBER < 0x1010000FL || defined(LIBRESSL_VERSION_NUMBER)
     886             : static tds_mutex *openssl_locks;
     887             : 
     888             : static void
     889             : openssl_locking_callback(int mode, int type, const char *file TDS_UNUSED, int line TDS_UNUSED)
     890             : {
     891             :         if (mode & CRYPTO_LOCK)
     892             :                 tds_mutex_lock(&openssl_locks[type]);
     893             :         else
     894             :                 tds_mutex_unlock(&openssl_locks[type]);
     895             : }
     896             : 
     897             : static void
     898             : tds_init_openssl_thread(void)
     899             : {
     900             :         int i, n = CRYPTO_num_locks();
     901             : 
     902             :         /* if already set do not overwrite,
     903             :          * application or another library took care of */
     904             :         if (CRYPTO_get_locking_callback())
     905             :                 return;
     906             : 
     907             :         openssl_locks = tds_new(tds_mutex, n);
     908             :         for (i=0; i < n; ++i)
     909             :                 tds_mutex_init(&openssl_locks[i]);
     910             : 
     911             :         /* read back in the attempt to avoid race conditions
     912             :          * this is not safe but there are no race free ways */
     913             :         if (CRYPTO_get_locking_callback() == NULL)
     914             :                 CRYPTO_set_locking_callback(openssl_locking_callback);
     915             :         if (CRYPTO_get_locking_callback() == openssl_locking_callback)
     916             :                 return;
     917             : 
     918             :         for (i=0; i < n; ++i)
     919             :                 tds_mutex_free(&openssl_locks[i]);
     920             :         free(openssl_locks);
     921             :         openssl_locks = NULL;
     922             : }
     923             : 
     924             : #ifdef TDS_ATTRIBUTE_DESTRUCTOR
     925             : static void __attribute__((destructor))
     926             : tds_deinit_openssl(void)
     927             : {
     928             :         int i, n;
     929             : 
     930             :         if (!tls_initialized
     931             :             || CRYPTO_get_locking_callback() != openssl_locking_callback)
     932             :                 return;
     933             : 
     934             :         CRYPTO_set_locking_callback(NULL);
     935             :         n = CRYPTO_num_locks();
     936             :         for (i=0; i < n; ++i)
     937             :                 tds_mutex_free(&openssl_locks[i]);
     938             :         free(openssl_locks);
     939             :         openssl_locks = NULL;
     940             : }
     941             : #endif
     942             : 
     943             : #else
     944             : static inline void
     945             : tds_init_openssl_thread(void)
     946             : {
     947             : }
     948             : #endif
     949             : 
     950             : #if OPENSSL_VERSION_NUMBER < 0x40100000L || defined(LIBRESSL_VERSION_NUMBER)
     951             : static inline size_t
     952             : ASN1_STRING_get_length(const ASN1_STRING *s)
     953             : {
     954         150 :         return (size_t) ASN1_STRING_length((ASN1_STRING *) s);
     955             : }
     956             : #endif
     957             : 
     958             : static SSL_CTX *
     959        1178 : tds_init_openssl(void)
     960             : {
     961             :         const SSL_METHOD *meth;
     962             : 
     963        1178 :         if (!tls_initialized) {
     964         667 :                 tds_mutex_lock(&tls_mutex);
     965         667 :                 if (!tls_initialized) {
     966         667 :                         SSL_library_init();
     967             :                         tds_init_openssl_thread();
     968         667 :                         tds_init_ssl_methods();
     969         667 :                         tls_initialized = 1;
     970             :                 }
     971         667 :                 tds_mutex_unlock(&tls_mutex);
     972             :         }
     973        1178 :         meth = TLS_client_method();
     974        1178 :         if (meth == NULL)
     975             :                 return NULL;
     976        1178 :         return SSL_CTX_new (meth);
     977             : }
     978             : 
     979             : static int
     980       23600 : check_wildcard(const char *host, const char *match)
     981             : {
     982             :         const char *p, *w;
     983             :         size_t n, lh, lm;
     984             : 
     985             :         /* U-label (binary) */
     986      247800 :         for (p = match; *p; ++p)
     987      225378 :                 if ((unsigned char) *p >= 0x80)
     988        1178 :                         return strcmp(host, match) == 0;
     989             : 
     990             :         for (;;) {
     991             :                 /* A-label (starts with xn--) */
     992       22422 :                 if (strncasecmp(match, "xn--", 4) == 0)
     993             :                         break;
     994             : 
     995             :                 /* match must not be in domain and domain should contains 2 parts */
     996       18888 :                 w = strchr(match, '*');
     997       18888 :                 p = strchr(match, '.');
     998       18888 :                 if (!w || !p            /* no wildcard or domain */
     999       14136 :                     || p[1] == '.'      /* empty domain */
    1000       14136 :                     || w > p || strchr(p, '*') != NULL)      /* wildcard in domain */
    1001             :                         break;
    1002       10602 :                 p = strchr(p+1, '.');
    1003       10602 :                 if (!p || p[1] == 0)    /* not another domain */
    1004             :                         break;
    1005             : 
    1006             :                 /* check start */
    1007        9424 :                 n = w - match;  /* prefix len */
    1008        9424 :                 if (n > 0 && strncasecmp(host, match, n) != 0)
    1009             :                         return 0;
    1010             : 
    1011             :                 /* check end */
    1012        8246 :                 lh = strlen(host);
    1013        8246 :                 lm = strlen(match);
    1014        8246 :                 n = lm - n - 1; /* suffix len */
    1015        8246 :                 if (lm - 1 > lh || strcasecmp(host+lh-n, match+lm-n) != 0 || host[0] == '.')
    1016             :                         return 0;
    1017             : 
    1018        5890 :                 return 1;
    1019             :         }
    1020       12998 :         return strcasecmp(host, match) == 0;
    1021             : }
    1022             : 
    1023             : #if ENABLE_EXTRA_CHECKS
    1024             : static void
    1025        1178 : tds_check_wildcard_test(void)
    1026             : {
    1027        1178 :         assert(check_wildcard("foo", "foo") == 1);
    1028        1178 :         assert(check_wildcard("FOO", "foo") == 1);
    1029        1178 :         assert(check_wildcard("foo", "FOO") == 1);
    1030        1178 :         assert(check_wildcard("\x90oo", "\x90OO") == 0);
    1031        1178 :         assert(check_wildcard("xn--foo", "xn--foo") == 1);
    1032        1178 :         assert(check_wildcard("xn--FOO", "XN--foo") == 1);
    1033        1178 :         assert(check_wildcard("xn--a.example.org", "xn--*.example.org") == 0);
    1034        1178 :         assert(check_wildcard("a.*", "a.*") == 1);
    1035        1178 :         assert(check_wildcard("a.b", "a.*") == 0);
    1036        1178 :         assert(check_wildcard("ab", "a*") == 0);
    1037        1178 :         assert(check_wildcard("a.example.", "*.example.") == 0);
    1038        1178 :         assert(check_wildcard("a.example.com", "*.example.com") == 1);
    1039        1178 :         assert(check_wildcard("a.b.example.com", "a.*.example.com") == 0);
    1040        1178 :         assert(check_wildcard("foo.example.com", "foo*.example.com") == 1);
    1041        1178 :         assert(check_wildcard("fou.example.com", "foo*.example.com") == 0);
    1042        1178 :         assert(check_wildcard("baz.example.com", "*baz.example.com") == 1);
    1043        1178 :         assert(check_wildcard("buzz.example.com", "b*z.example.com") == 1);
    1044        1178 :         assert(check_wildcard("bz.example.com", "b*z.example.com") == 1);
    1045        1178 :         assert(check_wildcard(".example.com", "*.example.com") == 0);
    1046        1178 :         assert(check_wildcard("example.com", "*.example.com") == 0);
    1047        1178 : }
    1048             : #else
    1049             : #define tds_check_wildcard_test() do { } while(0)
    1050             : #endif
    1051             : 
    1052             : static int
    1053          40 : check_name_match(const ASN1_STRING *name, const char *hostname)
    1054             : {
    1055          40 :         char *name_utf8 = NULL, *tmp_name;
    1056             :         int ret, name_len;
    1057             : 
    1058          40 :         name_len = ASN1_STRING_to_UTF8((unsigned char **) &name_utf8, name);
    1059          40 :         if (name_len < 0)
    1060             :                 return 0;
    1061             : 
    1062          40 :         tmp_name = tds_strndup(name_utf8, name_len);
    1063          40 :         OPENSSL_free(name_utf8);
    1064          40 :         if (!tmp_name)
    1065             :                 return 0;
    1066             : 
    1067          40 :         name_utf8 = tmp_name;
    1068             : 
    1069          40 :         tdsdump_log(TDS_DBG_INFO1, "Got name %s\n", name_utf8);
    1070          40 :         ret = 0;
    1071          40 :         if (strlen(name_utf8) == name_len && check_wildcard(hostname, name_utf8))
    1072          10 :                 ret = 1;
    1073          40 :         free(name_utf8);
    1074          40 :         return ret;
    1075             : }
    1076             : 
    1077             : static int
    1078          45 : check_alt_names(X509 *cert, const char *hostname)
    1079             : {
    1080             :         STACK_OF(GENERAL_NAME) *alt_names;
    1081             :         int i, num;
    1082          45 :         int ret = 1;
    1083             :         union {
    1084             :                 struct in_addr v4;
    1085             :                 struct in6_addr v6;
    1086             :         } ip;
    1087          45 :         unsigned ip_size = 0;
    1088             : 
    1089             :         /* check whether @hostname is an ip address */
    1090          45 :         if (strchr(hostname, ':') != NULL) {
    1091          15 :                 ip_size = 16;
    1092          15 :                 ret = inet_pton(AF_INET6, hostname, &ip.v6);
    1093             :         } else {
    1094          30 :                 ip_size = 4;
    1095          30 :                 ret = inet_pton(AF_INET, hostname, &ip.v4);
    1096             :         }
    1097          45 :         if (ret == 0)
    1098          15 :                 ip_size = 0;
    1099             : 
    1100          45 :         alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
    1101          45 :         if (!alt_names)
    1102             :                 return -1;
    1103             : 
    1104          45 :         num = sk_GENERAL_NAME_num(alt_names);
    1105          45 :         tdsdump_log(TDS_DBG_INFO1, "Alt names number %d\n", num);
    1106         130 :         for (i = 0; i < num; ++i) {
    1107             :                 const char *altptr;
    1108             :                 size_t altlen;
    1109             : 
    1110         150 :                 const GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
    1111         150 :                 if (!name)
    1112           0 :                         continue;
    1113             : 
    1114         150 :                 altptr = (const char *) ASN1_STRING_get0_data(name->d.ia5);
    1115         300 :                 altlen = ASN1_STRING_get_length(name->d.ia5);
    1116             : 
    1117         150 :                 if (name->type == GEN_DNS && ip_size == 0) {
    1118          15 :                         if (!check_name_match(name->d.dNSName, hostname))
    1119          10 :                                 continue;
    1120         135 :                 } else if (name->type == GEN_IPADD && ip_size != 0) {
    1121          75 :                         if (altlen != ip_size || memcmp(altptr, &ip, altlen) != 0)
    1122          60 :                                 continue;
    1123             :                 } else {
    1124          60 :                         continue;
    1125             :                 }
    1126             : 
    1127          20 :                 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
    1128          20 :                 return 1;
    1129             :         }
    1130          25 :         sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
    1131          25 :         return -1;
    1132             : }
    1133             : 
    1134             : static int
    1135          45 : check_hostname(X509 *cert, const char *hostname)
    1136             : {
    1137             :         int ret, i, j;
    1138             :         const X509_NAME *subject;
    1139             :         const ASN1_STRING *name;
    1140             : 
    1141             :         /* check by subject */
    1142          45 :         ret = check_alt_names(cert, hostname);
    1143          45 :         if (ret >= 0)
    1144             :                 return ret;
    1145             : 
    1146             :         /* check by common name (old method) */
    1147          25 :         subject = X509_get_subject_name(cert);
    1148          25 :         if (!subject)
    1149             :                 return 0;
    1150             : 
    1151             :         i = -1;
    1152          50 :         while ((j = X509_NAME_get_index_by_NID((X509_NAME *) subject, NID_commonName, i)) >= 0)
    1153             :                 i = j;
    1154          25 :         if (i < 0)
    1155             :                 return 0;
    1156             : 
    1157          25 :         name = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
    1158          25 :         if (!name)
    1159             :                 return 0;
    1160             : 
    1161          25 :         return check_name_match(name, hostname);
    1162             : }
    1163             : 
    1164             : int
    1165        1178 : tds_ssl_init(TDSSOCKET *tds, bool full)
    1166             : {
    1167             : #define DEFAULT_OPENSSL_CTX_OPTIONS \
    1168             :         (SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1)
    1169             : #define DEFAULT_OPENSSL_CIPHERS "HIGH:!SSLv2:!aNULL:-DH"
    1170             : 
    1171             :         SSL *con;
    1172             :         SSL_CTX *ctx;
    1173             :         BIO *b, *b2;
    1174             : 
    1175             :         int ret, connect_ret;
    1176             :         const char *tls_msg;
    1177             : 
    1178        1178 :         unsigned long ctx_options = DEFAULT_OPENSSL_CTX_OPTIONS;
    1179             : 
    1180        1178 :         con = NULL;
    1181        1178 :         b = NULL;
    1182        1178 :         b2 = NULL;
    1183        1178 :         ret = 1;
    1184             : 
    1185        1178 :         tds_check_wildcard_test();
    1186             : 
    1187        1178 :         tds_ssl_deinit(tds->conn);
    1188             : 
    1189        1178 :         tls_msg = "initializing tls";
    1190        1178 :         ctx = tds_init_openssl();
    1191        1178 :         if (!ctx)
    1192             :                 goto cleanup;
    1193             : 
    1194        1178 :         if (tds->login && tds->login->enable_tls_v1)
    1195         785 :                 ctx_options &= ~SSL_OP_NO_TLSv1;
    1196        1178 :         if (tds->login && tds->login->enable_tls_v1_1)
    1197           0 :                 ctx_options &= ~SSL_OP_NO_TLSv1_1;
    1198        1178 :         SSL_CTX_set_options(ctx, ctx_options);
    1199             : 
    1200        2356 :         if (!tds_dstr_isempty(&tds->login->cafile)) {
    1201           0 :                 tls_msg = "loading CA file";
    1202           0 :                 if (strcasecmp(tds_dstr_cstr(&tds->login->cafile), "system") == 0)
    1203           0 :                         ret = SSL_CTX_set_default_verify_paths(ctx);
    1204             :                 else
    1205           0 :                         ret = SSL_CTX_load_verify_locations(ctx, tds_dstr_cstr(&tds->login->cafile), NULL);
    1206           0 :                 if (ret != 1)
    1207             :                         goto cleanup;
    1208           0 :                 if (!tds_dstr_isempty(&tds->login->crlfile)) {
    1209           0 :                         X509_STORE *store = SSL_CTX_get_cert_store(ctx);
    1210             :                         X509_LOOKUP *lookup;
    1211             : 
    1212           0 :                         tls_msg = "loading CRL file";
    1213           0 :                         if (!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()))
    1214           0 :                             || (!X509_load_crl_file(lookup, tds_dstr_cstr(&tds->login->crlfile), X509_FILETYPE_PEM)))
    1215             :                                 goto cleanup;
    1216             : 
    1217           0 :                         X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
    1218             :                 }
    1219           0 :                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    1220             :         }
    1221             : 
    1222             :         /* Initialize TLS session */
    1223        1178 :         tls_msg = "initializing session";
    1224        1178 :         con = SSL_new(ctx);
    1225        1178 :         if (!con)
    1226             :                 goto cleanup;
    1227             : 
    1228        1178 :         tls_msg = "creating bio";
    1229        1178 :         b = BIO_new(full ? tds_method : tds_method_login);
    1230        1178 :         if (!b)
    1231             :                 goto cleanup;
    1232             : 
    1233        1178 :         if (!full) {
    1234        1178 :                 b2 = BIO_new(tds_method);
    1235        1178 :                 if (!b2)
    1236             :                         goto cleanup;
    1237             :         }
    1238             : 
    1239        1178 :         BIO_set_init(b, 1);
    1240        1178 :         BIO_set_data(b, full ? (void *) tds->conn : (void *) tds);
    1241        2356 :         BIO_set_conn_hostname(b, wanted_certificate_hostname(tds->login));
    1242        1178 :         SSL_set_bio(con, b, b);
    1243        1178 :         b = NULL;
    1244             : 
    1245             :         /* use default priorities unless overridden by openssl ciphers setting in freetds.conf file... */
    1246        2356 :         if (!tds_dstr_isempty(&tds->login->openssl_ciphers)) {
    1247           0 :                 tdsdump_log(TDS_DBG_INFO1, "setting custom openssl cipher to:%s\n", tds_dstr_cstr(&tds->login->openssl_ciphers));
    1248           0 :                 SSL_set_cipher_list(con, tds_dstr_cstr(&tds->login->openssl_ciphers) );
    1249             :         } else {
    1250        1178 :                 tdsdump_log(TDS_DBG_INFO1, "setting default openssl cipher to:%s\n", DEFAULT_OPENSSL_CIPHERS );
    1251        1178 :                 SSL_set_cipher_list(con, DEFAULT_OPENSSL_CIPHERS);
    1252             :         }
    1253             : 
    1254             : #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
    1255             :         /* this disable a security improvement but allow connection... */
    1256        1178 :         SSL_set_options(con, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
    1257             : #endif
    1258             : 
    1259             : #ifdef HAVE_SSL_SET_ALPN_PROTOS
    1260        1178 :         if (IS_TDS80_PLUS(tds->conn)) {
    1261             :                 static const unsigned char tds8_alpn[] = {
    1262             :                         TDS8_ALPN_ARRAY_LEN, TDS8_ALPN_ARRAY
    1263             :                 };
    1264           0 :                 SSL_set_alpn_protos(con, tds8_alpn, sizeof(tds8_alpn));
    1265             :         }
    1266             : #endif
    1267             : 
    1268             :         if (full)
    1269             :                 set_current_tds(tds->conn, tds);
    1270             : 
    1271             :         /* Perform the TLS handshake */
    1272        1178 :         tls_msg = "handshake";
    1273        1178 :         ERR_clear_error();
    1274        1178 :         SSL_set_connect_state(con);
    1275        1178 :         connect_ret = SSL_connect(con);
    1276        2356 :         ret = connect_ret != 1 || SSL_get_state(con) != TLS_ST_OK;
    1277             :         if (ret != 0) {
    1278           0 :                 tdsdump_log(TDS_DBG_ERROR, "handshake failed with %d %d %d\n",
    1279             :                             connect_ret, SSL_get_state(con), SSL_get_error(con, connect_ret));
    1280             :                 goto cleanup;
    1281             :         }
    1282             : 
    1283             :         /* flush pending data */
    1284        2356 :         if (!full && tds->out_pos > 8)
    1285           0 :                 tds_flush_packet(tds);
    1286             : 
    1287             :         /* check certificate hostname */
    1288        2356 :         if (!tds_dstr_isempty(&tds->login->cafile) && tds->login->check_ssl_hostname) {
    1289             :                 X509 *cert;
    1290             : 
    1291           0 :                 cert =  SSL_get_peer_certificate(con);
    1292           0 :                 tls_msg = "checking hostname";
    1293           0 :                 if (!cert || !check_hostname(cert, wanted_certificate_hostname(tds->login)))
    1294             :                         goto cleanup;
    1295           0 :                 X509_free(cert);
    1296             :         }
    1297             : 
    1298        1178 :         tdsdump_log(TDS_DBG_INFO1, "handshake succeeded!!\n");
    1299             : 
    1300        1178 :         if (!full) {
    1301             :                 /* some TLS implementations send some sort of paddind at the end, remove it */
    1302        1178 :                 tds->in_pos = tds->in_len;
    1303             : 
    1304        1178 :                 BIO_set_init(b2, 1);
    1305        1178 :                 BIO_set_data(b2, tds->conn);
    1306        1178 :                 SSL_set_bio(con, b2, b2);
    1307             :         }
    1308             : 
    1309        1178 :         set_current_tds(tds->conn, NULL);
    1310             : 
    1311        1178 :         tds->conn->tls_session = con;
    1312        1178 :         tds->conn->tls_ctx = ctx;
    1313             : 
    1314        1178 :         return TDS_SUCCESS;
    1315             : 
    1316           0 : cleanup:
    1317           0 :         if (b2)
    1318           0 :                 BIO_free(b2);
    1319           0 :         if (b)
    1320           0 :                 BIO_free(b);
    1321           0 :         if (con) {
    1322           0 :                 SSL_shutdown(con);
    1323           0 :                 SSL_free(con);
    1324             :         }
    1325           0 :         set_current_tds(tds->conn, NULL);
    1326           0 :         SSL_CTX_free(ctx);
    1327           0 :         tdsdump_log(TDS_DBG_ERROR, "%s failed\n", tls_msg);
    1328             :         return TDS_FAIL;
    1329             : }
    1330             : 
    1331             : void
    1332        6439 : tds_ssl_deinit(TDSCONNECTION *conn)
    1333             : {
    1334        6439 :         if (conn->tls_session) {
    1335             :                 /* NOTE do not call SSL_shutdown here */
    1336        1178 :                 SSL_free((SSL *) conn->tls_session);
    1337        1178 :                 conn->tls_session = NULL;
    1338             :         }
    1339        6439 :         if (conn->tls_ctx) {
    1340        1178 :                 SSL_CTX_free((SSL_CTX *) conn->tls_ctx);
    1341        1178 :                 conn->tls_ctx = NULL;
    1342             :         }
    1343        6439 :         conn->encrypt_single_packet = 0;
    1344        6439 : }
    1345             : 
    1346             : #ifdef TLS1_3_VERSION
    1347             : /**
    1348             :  * Compute the "tls-server-end-point" hash of a certificate (RFC 5929, section 4.1).
    1349             :  * The hash function is the one used by the certificate signature, MD5 and SHA-1 are replaced by SHA-256.
    1350             :  * @param cert     certificate
    1351             :  * @param hash     output buffer
    1352             :  * @param hash_len output buffer size
    1353             :  * @return hash length or 0 on error
    1354             :  */
    1355             : static size_t
    1356          20 : tds_ssl_end_point_hash(X509 *cert, unsigned char *hash, size_t hash_len)
    1357             : {
    1358             :         const EVP_MD *md;
    1359          20 :         int md_nid = NID_undef;
    1360          20 :         unsigned int len = 0;
    1361             : 
    1362             : #ifndef LIBRESSL_VERSION_NUMBER
    1363             :         /* this handles also RSA-PSS signatures */
    1364          20 :         if (!X509_get_signature_info(cert, &md_nid, NULL, NULL, NULL))
    1365             :                 return 0;
    1366             : #else
    1367             :         if (!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &md_nid, NULL))
    1368             :                 return 0;
    1369             : #endif
    1370          20 :         if (md_nid == NID_md5 || md_nid == NID_sha1)
    1371           5 :                 md_nid = NID_sha256;
    1372          20 :         md = EVP_get_digestbynid(md_nid);
    1373          20 :         if (!md || EVP_MD_size(md) <= 0 || (size_t) EVP_MD_size(md) > hash_len)
    1374             :                 return 0;
    1375          20 :         if (!X509_digest(cert, md, hash, &len))
    1376             :                 return 0;
    1377          20 :         return len;
    1378             : }
    1379             : 
    1380             : static size_t
    1381           0 : tds_ssl_get_cb_end_point(SSL *ssl, void *cb, size_t cblen)
    1382             : {
    1383             :         X509 *cert;
    1384             :         unsigned char hash[EVP_MAX_MD_SIZE];
    1385             :         size_t hash_len;
    1386             : 
    1387           0 :         cert = SSL_get_peer_certificate(ssl);
    1388           0 :         if (!cert) {
    1389           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: no server certificate for tls-server-end-point\n");
    1390             :                 return 0;
    1391             :         }
    1392           0 :         hash_len = tds_ssl_end_point_hash(cert, hash, sizeof(hash));
    1393           0 :         X509_free(cert);
    1394           0 :         if (hash_len == 0) {
    1395           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: failed to compute tls-server-end-point hash\n");
    1396             :                 return 0;
    1397             :         }
    1398           0 :         return tds_ssl_fill_cb(cb, cblen, TDS_CB_TLS_SERVER_END_POINT, hash, hash_len);
    1399             : }
    1400             : #endif
    1401             : 
    1402             : size_t
    1403         389 : tds_ssl_get_cb(TDSCONNECTION *conn, void *cb, size_t cblen)
    1404             : {
    1405             :         SSL *ssl;
    1406             :         unsigned char tls_unique[EVP_MAX_MD_SIZE];
    1407             :         size_t tls_unique_len;
    1408             : 
    1409             :         /* No CBT, skip channel binding */
    1410         389 :         if (!conn->tls_session)
    1411             :                 return 0;
    1412             : 
    1413         389 :         ssl = (SSL *) conn->tls_session;
    1414             : 
    1415             : #ifdef TLS1_3_VERSION
    1416             :         /* tls-unique is not defined for TLS 1.3 */
    1417         389 :         if (SSL_version(ssl) >= TLS1_3_VERSION)
    1418           0 :                 return tds_ssl_get_cb_end_point(ssl, cb, cblen);
    1419             : #endif
    1420             : 
    1421             :         /* Get tls-unique from OpenSSL */
    1422         389 :         tls_unique_len = SSL_get_finished(ssl, tls_unique, sizeof(tls_unique));
    1423         389 :         if (tls_unique_len == 0) {
    1424             :                 /* Try peer finished as fallback */
    1425           0 :                 tls_unique_len = SSL_get_peer_finished(ssl, tls_unique, sizeof(tls_unique));
    1426             :         }
    1427         389 :         if (tls_unique_len == 0 || tls_unique_len > sizeof(tls_unique)) {
    1428           0 :                 tdsdump_log(TDS_DBG_ERROR, "tds_ssl_get_cb: failed to get tls-unique from OpenSSL\n");
    1429             :                 /* No tls-unique available, skip channel binding */
    1430             :                 return 0;
    1431             :         }
    1432         389 :         return tds_ssl_fill_cb(cb, cblen, TDS_CB_TLS_UNIQUE, tls_unique, tls_unique_len);
    1433             : }
    1434             : #endif
    1435             : 
    1436             : #endif
    1437             : /** @} */
    1438             : 

Generated by: LCOV version 1.13