/*
* util/net_help.c - implementation of the network helper code
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* Implementation of net_help.h.
*/
/** max length of an IP address (the address portion) that we allow */
#define MAX_ADDR_STRLEN 128 /* characters */
/** max length of a hostname (with port and tls name) that we allow */
#define MAX_HOST_STRLEN (LDNS_MAX_DOMAINLEN * 3) /* characters */
/** default value for EDNS ADVERTISED size */
uint16_t EDNS_ADVERTISED_SIZE = 4096;
/** minimal responses when positive answer: default is no */
int MINIMAL_RESPONSES = 0;
/** rrset order roundrobin: default is yes */
int RRSET_ROUNDROBIN = 1;
/** log tag queries with name instead of 'info' for filtering */
int LOG_TAG_QUERYREPLY = 0;
#ifdef HAVE_SSL
/**
* callback TLS session ticket encrypt and decrypt
* For use with SSL_CTX_set_tlsext_ticket_key_cb or
* SSL_CTX_set_tlsext_ticket_key_evp_cb
* @param s: the SSL_CTX to use (from connect_sslctx_create())
* @param key_name: secret name, 16 bytes
* @param iv: up to EVP_MAX_IV_LENGTH.
* @param evp_ctx: the evp cipher context, function sets this.
* @param hmac_ctx: the hmac context, function sets this.
* with ..key_cb it is of type HMAC_CTX*
* with ..key_evp_cb it is of type EVP_MAC_CTX*
* @param enc: 1 is encrypt, 0 is decrypt
* @return 0 on no ticket, 1 for okay, and 2 for okay but renew the ticket
* (the ticket is decrypt only). and <0 for failures.
*/
int tls_session_ticket_key_cb(SSL *s, unsigned char* key_name,
unsigned char* iv, EVP_CIPHER_CTX *evp_ctx,
#ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
EVP_MAC_CTX *hmac_ctx,
#else
HMAC_CTX* hmac_ctx,
#endif
int enc);
#endif /* HAVE_SSL */
/* returns true is string addr is an ip6 specced address */
int
str_is_ip6(const char* str)
{
if(strchr(str, ':'))
return 1;
else return 0;
}
int
fd_set_nonblock(int s)
{
#ifdef HAVE_FCNTL
int flag;
if((flag = fcntl(s, F_GETFL)) == -1) {
log_err("can't fcntl F_GETFL: %s", strerror(errno));
flag = 0;
}
flag |= O_NONBLOCK;
if(fcntl(s, F_SETFL, flag) == -1) {
log_err("can't fcntl F_SETFL: %s", strerror(errno));
return 0;
}
#elif defined(HAVE_IOCTLSOCKET)
unsigned long on = 1;
if(ioctlsocket(s, FIONBIO, &on) != 0) {
log_err("can't ioctlsocket FIONBIO on: %s",
wsa_strerror(WSAGetLastError()));
}
#endif
return 1;
}
/* RPZ format address dname to network byte order address */
static int ipdnametoaddr(uint8_t* dname, size_t dnamelen,
struct sockaddr_storage* addr, socklen_t* addrlen, int* af)
{
uint8_t* ia;
int dnamelabs = dname_count_labels(dname);
uint8_t lablen;
char* e = NULL;
int z = 0;
size_t len = 0;
int i;
*af = AF_INET;
/* need 1 byte for label length */
if(dnamelen < 1)
return 0;
if(dnamelabs > 6 ||
dname_has_label(dname, dnamelen, (uint8_t*)"\002zz")) {
*af = AF_INET6;
}
len = *dname;
lablen = *dname++;
i = (*af == AF_INET) ? 3 : 15;
if(*af == AF_INET6) {
struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
*addrlen = (socklen_t)sizeof(struct sockaddr_in6);
memset(sa, 0, *addrlen);
sa->sin6_family = AF_INET6;
ia = (uint8_t*)&sa->sin6_addr;
} else { /* ip4 */
struct sockaddr_in* sa = (struct sockaddr_in*)addr;
*addrlen = (socklen_t)sizeof(struct sockaddr_in);
memset(sa, 0, *addrlen);
sa->sin_family = AF_INET;
ia = (uint8_t*)&sa->sin_addr;
}
while(lablen && i >= 0 && len <= dnamelen) {
char buff[LDNS_MAX_LABELLEN+1];
uint16_t chunk; /* big enough to not overflow on IPv6 hextet */
if((*af == AF_INET && (lablen > 3 || dnamelabs > 6)) ||
(*af == AF_INET6 && (lablen > 4 || dnamelabs > 10))) {
return 0;
}
if(memcmp(dname, "zz", 2) == 0 && *af == AF_INET6) {
/* Add one or more 0 labels. Address is initialised at
* 0, so just skip the zero part. */
int zl = 11 - dnamelabs;
if(z || zl < 0)
return 0;
z = 1;
i -= (zl*2);
} else {
memcpy(buff, dname, lablen);
buff[lablen] = '\0';
chunk = strtol(buff, &e, (*af == AF_INET) ? 10 : 16);
if(!e || *e != '\0' || (*af == AF_INET && chunk > 255))
return 0;
if(*af == AF_INET) {
log_assert(i < 4 && i >= 0);
ia[i] = (uint8_t)chunk;
i--;
} else {
log_assert(i < 16 && i >= 1);
/* ia in network byte order */
ia[i-1] = (uint8_t)(chunk >> 8);
ia[i] = (uint8_t)(chunk & 0x00FF);
i -= 2;
}
}
dname += lablen;
lablen = *dname++;
len += lablen;
}
if(i != -1)
/* input too short */
return 0;
return 1;
}
/* This needs to be checked by the caller */
log_assert(addr->ss_family == AF_INET);
/* Current usage is only from config values; prefix lengths enforced
* during config validation */
log_assert(prefixnet_is_nat64(nat64_prefixnet));
#if defined(HAVE_SSL) && defined(HAVE_SSL_CTX_SET_ALPN_SELECT_CB)
static int
dot_alpn_select_cb(SSL* ATTR_UNUSED(ssl), const unsigned char** out,
unsigned char* outlen, const unsigned char* in, unsigned int inlen,
void* ATTR_UNUSED(arg))
{
static const unsigned char alpns[] = { 3, 'd', 'o', 't' };
unsigned char* tmp_out;
int ret;
ret = SSL_select_next_proto(&tmp_out, outlen, alpns, sizeof(alpns), in, inlen);
if(ret == OPENSSL_NPN_NO_OVERLAP) {
/* Client sent ALPN but no overlap. Should have been error,
* but for privacy we continue without ALPN (e.g., if certain
* ALPNs are blocked) */
return SSL_TLSEXT_ERR_NOACK;
}
*out = tmp_out;
return SSL_TLSEXT_ERR_OK;
}
#endif
#if defined(HAVE_SSL) && defined(HAVE_NGHTTP2) && defined(HAVE_SSL_CTX_SET_ALPN_SELECT_CB)
static int doh_alpn_select_cb(SSL* ATTR_UNUSED(ssl), const unsigned char** out,
unsigned char* outlen, const unsigned char* in, unsigned int inlen,
void* ATTR_UNUSED(arg))
{
int rv = nghttp2_select_next_protocol((unsigned char **)out, outlen, in,
inlen);
if(rv == -1) {
return SSL_TLSEXT_ERR_NOACK;
}
/* either http/1.1 or h2 selected */
return SSL_TLSEXT_ERR_OK;
}
#endif
int
listen_sslctx_setup(void* ctxt)
{
#ifdef HAVE_SSL
SSL_CTX* ctx = (SSL_CTX*)ctxt;
/* no SSLv2, SSLv3 because has defects */
#if SSL_OP_NO_SSLv2 != 0
if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
!= SSL_OP_NO_SSLv2){
log_crypto_err("could not set SSL_OP_NO_SSLv2");
return 0;
}
#endif
if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
!= SSL_OP_NO_SSLv3){
log_crypto_err("could not set SSL_OP_NO_SSLv3");
return 0;
}
#if defined(SSL_OP_NO_TLSv1) && defined(SSL_OP_NO_TLSv1_1)
/* if we have tls 1.1 disable 1.0 */
if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1) & SSL_OP_NO_TLSv1)
!= SSL_OP_NO_TLSv1){
log_crypto_err("could not set SSL_OP_NO_TLSv1");
return 0;
}
#endif
#if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
/* if we have tls 1.2 disable 1.1 */
if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1) & SSL_OP_NO_TLSv1_1)
!= SSL_OP_NO_TLSv1_1){
log_crypto_err("could not set SSL_OP_NO_TLSv1_1");
return 0;
}
#endif
#if defined(SSL_OP_NO_RENEGOTIATION)
/* disable client renegotiation */
if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION) {
log_crypto_err("could not set SSL_OP_NO_RENEGOTIATION");
return 0;
}
#endif
#if defined(SHA256_DIGEST_LENGTH) && defined(USE_ECDSA)
/* if we detect system-wide crypto policies, use those */
if (access( "/etc/crypto-policies/config", F_OK ) != 0 ) {
/* if we have sha256, set the cipher list to have no known vulns */
if(!SSL_CTX_set_cipher_list(ctx, "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256"))
log_crypto_err("could not set cipher list with SSL_CTX_set_cipher_list");
}
#endif
#if defined(SSL_OP_IGNORE_UNEXPECTED_EOF)
/* ignore errors when peers do not send the mandatory close_notify
* alert on shutdown.
* Relevant for openssl >= 3 */
if((SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF) &
SSL_OP_IGNORE_UNEXPECTED_EOF) != SSL_OP_IGNORE_UNEXPECTED_EOF) {
log_crypto_err("could not set SSL_OP_IGNORE_UNEXPECTED_EOF");
return 0;
}
#endif
if((SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE) &
SSL_OP_CIPHER_SERVER_PREFERENCE) !=
SSL_OP_CIPHER_SERVER_PREFERENCE) {
log_crypto_err("could not set SSL_OP_CIPHER_SERVER_PREFERENCE");
return 0;
}
#ifdef USE_WINSOCK
/* For windows, the CA trust store is not read by openssl.
Add code to open the trust store using wincrypt API and add
the root certs into openssl trust store */
static int
add_WIN_cacerts_to_openssl_store(SSL_CTX* tls_ctx)
{
HCERTSTORE hSystemStore;
PCCERT_CONTEXT pTargetCert = NULL;
X509_STORE* store;
verbose(VERB_ALGO, "Adding Windows certificates from system root store to CA store");
/* load just once per context lifetime for this version
TODO: dynamically update CA trust changes as they are available */
if (!tls_ctx)
return 0;
/* Call wincrypt's CertOpenStore to open the CA root store. */
if ((hSystemStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
0,
0,
/* NOTE: mingw does not have this const: replace with 1 << 16 from code
CERT_SYSTEM_STORE_CURRENT_USER, */
1 << 16,
L"root")) == 0)
{
return 0;
}
store = SSL_CTX_get_cert_store(tls_ctx);
if (!store)
return 0;
/* failure if the CA store is empty or the call fails */
if ((pTargetCert = CertEnumCertificatesInStore(
hSystemStore, pTargetCert)) == 0) {
verbose(VERB_ALGO, "CA certificate store for Windows is empty.");
return 0;
}
/* iterate over the windows cert store and add to openssl store */
do
{
X509 *cert1 = d2i_X509(NULL,
(const unsigned char **)&pTargetCert->pbCertEncoded,
pTargetCert->cbCertEncoded);
if (!cert1) {
unsigned long error = ERR_get_error();
/* return error if a cert fails */
verbose(VERB_ALGO, "%s %d:%s",
"Unable to parse certificate in memory",
(int)error, ERR_error_string(error, NULL));
return 0;
}
else {
/* return error if a cert add to store fails */
if (X509_STORE_add_cert(store, cert1) == 0) {
unsigned long error = ERR_peek_last_error();
/* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
* certificate is already in the store. */
if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
error = ERR_get_error();
verbose(VERB_ALGO, "%s %d:%s\n",
"Error adding certificate", (int)error,
ERR_error_string(error, NULL));
X509_free(cert1);
return 0;
}
}
X509_free(cert1);
}
} while ((pTargetCert = CertEnumCertificatesInStore(
hSystemStore, pTargetCert)) != 0);
/* Clean up memory and quit. */
if (pTargetCert)
CertFreeCertificateContext(pTargetCert);
if (hSystemStore)
{
if (!CertCloseStore(
hSystemStore, 0))
return 0;
}
verbose(VERB_ALGO, "Completed adding Windows certificates to CA store successfully");
return 1;
}
#endif /* USE_WINSOCK */
void* connect_sslctx_create(char* key, char* pem, char* verifypem, int wincert)
{
#ifdef HAVE_SSL
SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
if(!ctx) {
log_crypto_err("could not allocate SSL_CTX pointer");
return NULL;
}
#if SSL_OP_NO_SSLv2 != 0
if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
!= SSL_OP_NO_SSLv2) {
log_crypto_err("could not set SSL_OP_NO_SSLv2");
SSL_CTX_free(ctx);
return NULL;
}
#endif
if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
!= SSL_OP_NO_SSLv3) {
log_crypto_err("could not set SSL_OP_NO_SSLv3");
SSL_CTX_free(ctx);
return NULL;
}
#if defined(SSL_OP_NO_RENEGOTIATION)
/* disable client renegotiation */
if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION) {
log_crypto_err("could not set SSL_OP_NO_RENEGOTIATION");
SSL_CTX_free(ctx);
return 0;
}
#endif
#if defined(SSL_OP_IGNORE_UNEXPECTED_EOF)
/* ignore errors when peers do not send the mandatory close_notify
* alert on shutdown.
* Relevant for openssl >= 3 */
if((SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF) &
SSL_OP_IGNORE_UNEXPECTED_EOF) != SSL_OP_IGNORE_UNEXPECTED_EOF) {
log_crypto_err("could not set SSL_OP_IGNORE_UNEXPECTED_EOF");
SSL_CTX_free(ctx);
return 0;
}
#endif
if(key && key[0]) {
if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
log_err("error in client certificate %s", pem);
log_crypto_err("error in certificate file");
SSL_CTX_free(ctx);
return NULL;
}
if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
log_err("error in client private key %s", key);
log_crypto_err("error in key file");
SSL_CTX_free(ctx);
return NULL;
}
if(!SSL_CTX_check_private_key(ctx)) {
log_err("error in client key %s", key);
log_crypto_err("error in SSL_CTX_check_private_key");
SSL_CTX_free(ctx);
return NULL;
}
}
if((verifypem && verifypem[0]) || wincert) {
if(verifypem && verifypem[0]) {
if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
log_crypto_err("error in SSL_CTX verify");
SSL_CTX_free(ctx);
return NULL;
}
}
#ifdef USE_WINSOCK
if(wincert) {
if(!add_WIN_cacerts_to_openssl_store(ctx)) {
log_crypto_err("error in add_WIN_cacerts_to_openssl_store");
SSL_CTX_free(ctx);
return NULL;
}
}
#else
if(wincert) {
if(!SSL_CTX_set_default_verify_paths(ctx)) {
log_crypto_err("error in default_verify_paths");
SSL_CTX_free(ctx);
return NULL;
}
}
#endif
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
}
return ctx;
#else
(void)key; (void)pem; (void)verifypem; (void)wincert;
return NULL;
#endif
}
int check_auth_name_for_ssl(char* auth_name)
{
if(!auth_name) return 1;
#if defined(HAVE_SSL) && !defined(HAVE_SSL_SET1_HOST) && !defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
log_err("the query has an auth_name %s, but libssl has no call to "
"perform TLS authentication. Remove that name from config "
"or upgrade the ssl crypto library.", auth_name);
return 0;
#else
return 1;
#endif
}
/** set the authname on an SSL structure, SSL* ssl */
int set_auth_name_on_ssl(void* ssl, char* auth_name, int use_sni)
{
if(!auth_name) return 1;
#ifdef HAVE_SSL
if(use_sni) {
(void)SSL_set_tlsext_host_name(ssl, auth_name);
}
#else
(void)ssl;
(void)use_sni;
#endif
#ifdef HAVE_SSL_SET1_HOST
SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
/* setting the hostname makes openssl verify the
* host name in the x509 certificate in the
* SSL connection*/
if(!SSL_set1_host(ssl, auth_name)) {
log_err("SSL_set1_host failed");
return 0;
}
#elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
/* openssl 1.0.2 has this function that can be used for
* set1_host like verification */
if(auth_name) {
X509_VERIFY_PARAM* param = SSL_get0_param(ssl);
# ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
# endif
if(!X509_VERIFY_PARAM_set1_host(param, auth_name, strlen(auth_name))) {
log_err("X509_VERIFY_PARAM_set1_host failed");
return 0;
}
SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
}
#else
verbose(VERB_ALGO, "the query has an auth_name, but libssl has no call to perform TLS authentication");
#endif /* HAVE_SSL_SET1_HOST */
return 1;
}
#if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
/** global lock list for openssl locks */
static lock_basic_type *ub_openssl_locks = NULL;
/** callback that gets thread id for openssl */
#ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
static void
ub_crypto_id_cb(CRYPTO_THREADID *id)
{
CRYPTO_THREADID_set_numeric(id, (unsigned long)log_thread_get());
}
#else
static unsigned long
ub_crypto_id_cb(void)
{
return (unsigned long)log_thread_get();
}
#endif