"Fossies" - the Fresh Open Source Software Archive

Member "redis-6.2.5/src/tls.c" (21 Jul 2021, 32996 Bytes) of package /linux/misc/redis-6.2.5.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "tls.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 6.2.4_vs_6.2.5.

    1 /*
    2  * Copyright (c) 2019, Redis Labs
    3  * All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions are met:
    7  *
    8  *   * Redistributions of source code must retain the above copyright notice,
    9  *     this list of conditions and the following disclaimer.
   10  *   * Redistributions in binary form must reproduce the above copyright
   11  *     notice, this list of conditions and the following disclaimer in the
   12  *     documentation and/or other materials provided with the distribution.
   13  *   * Neither the name of Redis nor the names of its contributors may be used
   14  *     to endorse or promote products derived from this software without
   15  *     specific prior written permission.
   16  *
   17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   27  * POSSIBILITY OF SUCH DAMAGE.
   28  */
   29 
   30 
   31 #include "server.h"
   32 #include "connhelpers.h"
   33 #include "adlist.h"
   34 
   35 #ifdef USE_OPENSSL
   36 
   37 #include <openssl/conf.h>
   38 #include <openssl/ssl.h>
   39 #include <openssl/err.h>
   40 #include <openssl/rand.h>
   41 #include <openssl/pem.h>
   42 
   43 #define REDIS_TLS_PROTO_TLSv1       (1<<0)
   44 #define REDIS_TLS_PROTO_TLSv1_1     (1<<1)
   45 #define REDIS_TLS_PROTO_TLSv1_2     (1<<2)
   46 #define REDIS_TLS_PROTO_TLSv1_3     (1<<3)
   47 
   48 /* Use safe defaults */
   49 #ifdef TLS1_3_VERSION
   50 #define REDIS_TLS_PROTO_DEFAULT     (REDIS_TLS_PROTO_TLSv1_2|REDIS_TLS_PROTO_TLSv1_3)
   51 #else
   52 #define REDIS_TLS_PROTO_DEFAULT     (REDIS_TLS_PROTO_TLSv1_2)
   53 #endif
   54 
   55 extern ConnectionType CT_Socket;
   56 
   57 SSL_CTX *redis_tls_ctx = NULL;
   58 SSL_CTX *redis_tls_client_ctx = NULL;
   59 
   60 static int parseProtocolsConfig(const char *str) {
   61     int i, count = 0;
   62     int protocols = 0;
   63 
   64     if (!str) return REDIS_TLS_PROTO_DEFAULT;
   65     sds *tokens = sdssplitlen(str, strlen(str), " ", 1, &count);
   66 
   67     if (!tokens) { 
   68         serverLog(LL_WARNING, "Invalid tls-protocols configuration string");
   69         return -1;
   70     }
   71     for (i = 0; i < count; i++) {
   72         if (!strcasecmp(tokens[i], "tlsv1")) protocols |= REDIS_TLS_PROTO_TLSv1;
   73         else if (!strcasecmp(tokens[i], "tlsv1.1")) protocols |= REDIS_TLS_PROTO_TLSv1_1;
   74         else if (!strcasecmp(tokens[i], "tlsv1.2")) protocols |= REDIS_TLS_PROTO_TLSv1_2;
   75         else if (!strcasecmp(tokens[i], "tlsv1.3")) {
   76 #ifdef TLS1_3_VERSION
   77             protocols |= REDIS_TLS_PROTO_TLSv1_3;
   78 #else
   79             serverLog(LL_WARNING, "TLSv1.3 is specified in tls-protocols but not supported by OpenSSL.");
   80             protocols = -1;
   81             break;
   82 #endif
   83         } else {
   84             serverLog(LL_WARNING, "Invalid tls-protocols specified. "
   85                     "Use a combination of 'TLSv1', 'TLSv1.1', 'TLSv1.2' and 'TLSv1.3'.");
   86             protocols = -1;
   87             break;
   88         }
   89     }
   90     sdsfreesplitres(tokens, count);
   91 
   92     return protocols;
   93 }
   94 
   95 /* list of connections with pending data already read from the socket, but not
   96  * served to the reader yet. */
   97 static list *pending_list = NULL;
   98 
   99 /**
  100  * OpenSSL global initialization and locking handling callbacks.
  101  * Note that this is only required for OpenSSL < 1.1.0.
  102  */
  103 
  104 #if OPENSSL_VERSION_NUMBER < 0x10100000L
  105 #define USE_CRYPTO_LOCKS
  106 #endif
  107 
  108 #ifdef USE_CRYPTO_LOCKS
  109 
  110 static pthread_mutex_t *openssl_locks;
  111 
  112 static void sslLockingCallback(int mode, int lock_id, const char *f, int line) {
  113     pthread_mutex_t *mt = openssl_locks + lock_id;
  114 
  115     if (mode & CRYPTO_LOCK) {
  116         pthread_mutex_lock(mt);
  117     } else {
  118         pthread_mutex_unlock(mt);
  119     }
  120 
  121     (void)f;
  122     (void)line;
  123 }
  124 
  125 static void initCryptoLocks(void) {
  126     unsigned i, nlocks;
  127     if (CRYPTO_get_locking_callback() != NULL) {
  128         /* Someone already set the callback before us. Don't destroy it! */
  129         return;
  130     }
  131     nlocks = CRYPTO_num_locks();
  132     openssl_locks = zmalloc(sizeof(*openssl_locks) * nlocks);
  133     for (i = 0; i < nlocks; i++) {
  134         pthread_mutex_init(openssl_locks + i, NULL);
  135     }
  136     CRYPTO_set_locking_callback(sslLockingCallback);
  137 }
  138 #endif /* USE_CRYPTO_LOCKS */
  139 
  140 void tlsInit(void) {
  141     /* Enable configuring OpenSSL using the standard openssl.cnf
  142      * OPENSSL_config()/OPENSSL_init_crypto() should be the first 
  143      * call to the OpenSSL* library.
  144      *  - OPENSSL_config() should be used for OpenSSL versions < 1.1.0
  145      *  - OPENSSL_init_crypto() should be used for OpenSSL versions >= 1.1.0
  146      */
  147     #if OPENSSL_VERSION_NUMBER < 0x10100000L
  148     OPENSSL_config(NULL);
  149     #elif OPENSSL_VERSION_NUMBER < 0x10101000L
  150     OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
  151     #else
  152     OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG|OPENSSL_INIT_ATFORK, NULL);
  153     #endif
  154     ERR_load_crypto_strings();
  155     SSL_load_error_strings();
  156     SSL_library_init();
  157 
  158 #ifdef USE_CRYPTO_LOCKS
  159     initCryptoLocks();
  160 #endif
  161 
  162     if (!RAND_poll()) {
  163         serverLog(LL_WARNING, "OpenSSL: Failed to seed random number generator.");
  164     }
  165 
  166     pending_list = listCreate();
  167 }
  168 
  169 void tlsCleanup(void) {
  170     if (redis_tls_ctx) {
  171         SSL_CTX_free(redis_tls_ctx);
  172         redis_tls_ctx = NULL;
  173     }
  174     if (redis_tls_client_ctx) {
  175         SSL_CTX_free(redis_tls_client_ctx);
  176         redis_tls_client_ctx = NULL;
  177     }
  178 
  179     #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  180     OPENSSL_cleanup();
  181     #endif
  182 }
  183 
  184 /* Callback for passing a keyfile password stored as an sds to OpenSSL */
  185 static int tlsPasswordCallback(char *buf, int size, int rwflag, void *u) {
  186     UNUSED(rwflag);
  187 
  188     const char *pass = u;
  189     size_t pass_len;
  190 
  191     if (!pass) return -1;
  192     pass_len = strlen(pass);
  193     if (pass_len > (size_t) size) return -1;
  194     memcpy(buf, pass, pass_len);
  195 
  196     return (int) pass_len;
  197 }
  198 
  199 /* Create a *base* SSL_CTX using the SSL configuration provided. The base context
  200  * includes everything that's common for both client-side and server-side connections.
  201  */
  202 static SSL_CTX *createSSLContext(redisTLSContextConfig *ctx_config, int protocols, int client) {
  203     const char *cert_file = client ? ctx_config->client_cert_file : ctx_config->cert_file;
  204     const char *key_file = client ? ctx_config->client_key_file : ctx_config->key_file;
  205     const char *key_file_pass = client ? ctx_config->client_key_file_pass : ctx_config->key_file_pass;
  206     char errbuf[256];
  207     SSL_CTX *ctx = NULL;
  208 
  209     ctx = SSL_CTX_new(SSLv23_method());
  210 
  211     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
  212 
  213 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  214     SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
  215 #endif
  216 
  217     if (!(protocols & REDIS_TLS_PROTO_TLSv1))
  218         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1);
  219     if (!(protocols & REDIS_TLS_PROTO_TLSv1_1))
  220         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1);
  221 #ifdef SSL_OP_NO_TLSv1_2
  222     if (!(protocols & REDIS_TLS_PROTO_TLSv1_2))
  223         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_2);
  224 #endif
  225 #ifdef SSL_OP_NO_TLSv1_3
  226     if (!(protocols & REDIS_TLS_PROTO_TLSv1_3))
  227         SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_3);
  228 #endif
  229 
  230 #ifdef SSL_OP_NO_COMPRESSION
  231     SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
  232 #endif
  233 
  234     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  235     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  236 
  237     SSL_CTX_set_default_passwd_cb(ctx, tlsPasswordCallback);
  238     SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) key_file_pass);
  239 
  240     if (SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0) {
  241         ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
  242         serverLog(LL_WARNING, "Failed to load certificate: %s: %s", cert_file, errbuf);
  243         goto error;
  244     }
  245 
  246     if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
  247         ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
  248         serverLog(LL_WARNING, "Failed to load private key: %s: %s", key_file, errbuf);
  249         goto error;
  250     }
  251 
  252     if ((ctx_config->ca_cert_file || ctx_config->ca_cert_dir) &&
  253         SSL_CTX_load_verify_locations(ctx, ctx_config->ca_cert_file, ctx_config->ca_cert_dir) <= 0) {
  254         ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
  255         serverLog(LL_WARNING, "Failed to configure CA certificate(s) file/directory: %s", errbuf);
  256         goto error;
  257     }
  258 
  259     if (ctx_config->ciphers && !SSL_CTX_set_cipher_list(ctx, ctx_config->ciphers)) {
  260         serverLog(LL_WARNING, "Failed to configure ciphers: %s", ctx_config->ciphers);
  261         goto error;
  262     }
  263 
  264 #ifdef TLS1_3_VERSION
  265     if (ctx_config->ciphersuites && !SSL_CTX_set_ciphersuites(ctx, ctx_config->ciphersuites)) {
  266         serverLog(LL_WARNING, "Failed to configure ciphersuites: %s", ctx_config->ciphersuites);
  267         goto error;
  268     }
  269 #endif
  270 
  271     return ctx;
  272 
  273 error:
  274     if (ctx) SSL_CTX_free(ctx);
  275     return NULL;
  276 }
  277 
  278 /* Attempt to configure/reconfigure TLS. This operation is atomic and will
  279  * leave the SSL_CTX unchanged if fails.
  280  */
  281 int tlsConfigure(redisTLSContextConfig *ctx_config) {
  282     char errbuf[256];
  283     SSL_CTX *ctx = NULL;
  284     SSL_CTX *client_ctx = NULL;
  285 
  286     if (!ctx_config->cert_file) {
  287         serverLog(LL_WARNING, "No tls-cert-file configured!");
  288         goto error;
  289     }
  290 
  291     if (!ctx_config->key_file) {
  292         serverLog(LL_WARNING, "No tls-key-file configured!");
  293         goto error;
  294     }
  295 
  296     if (((server.tls_auth_clients != TLS_CLIENT_AUTH_NO) || server.tls_cluster || server.tls_replication) &&
  297             !ctx_config->ca_cert_file && !ctx_config->ca_cert_dir) {
  298         serverLog(LL_WARNING, "Either tls-ca-cert-file or tls-ca-cert-dir must be specified when tls-cluster, tls-replication or tls-auth-clients are enabled!");
  299         goto error;
  300     }
  301 
  302     int protocols = parseProtocolsConfig(ctx_config->protocols);
  303     if (protocols == -1) goto error;
  304 
  305     /* Create server side/generla context */
  306     ctx = createSSLContext(ctx_config, protocols, 0);
  307     if (!ctx) goto error;
  308 
  309     if (ctx_config->session_caching) {
  310         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
  311         SSL_CTX_sess_set_cache_size(ctx, ctx_config->session_cache_size);
  312         SSL_CTX_set_timeout(ctx, ctx_config->session_cache_timeout);
  313         SSL_CTX_set_session_id_context(ctx, (void *) "redis", 5);
  314     } else {
  315         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
  316     }
  317 
  318 #ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
  319     SSL_CTX_set_options(ctx, SSL_OP_NO_CLIENT_RENEGOTIATION);
  320 #endif
  321 
  322     if (ctx_config->prefer_server_ciphers)
  323         SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  324 
  325 #if defined(SSL_CTX_set_ecdh_auto)
  326     SSL_CTX_set_ecdh_auto(ctx, 1);
  327 #endif
  328     SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
  329 
  330     if (ctx_config->dh_params_file) {
  331         FILE *dhfile = fopen(ctx_config->dh_params_file, "r");
  332         DH *dh = NULL;
  333         if (!dhfile) {
  334             serverLog(LL_WARNING, "Failed to load %s: %s", ctx_config->dh_params_file, strerror(errno));
  335             goto error;
  336         }
  337 
  338         dh = PEM_read_DHparams(dhfile, NULL, NULL, NULL);
  339         fclose(dhfile);
  340         if (!dh) {
  341             serverLog(LL_WARNING, "%s: failed to read DH params.", ctx_config->dh_params_file);
  342             goto error;
  343         }
  344 
  345         if (SSL_CTX_set_tmp_dh(ctx, dh) <= 0) {
  346             ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf));
  347             serverLog(LL_WARNING, "Failed to load DH params file: %s: %s", ctx_config->dh_params_file, errbuf);
  348             DH_free(dh);
  349             goto error;
  350         }
  351 
  352         DH_free(dh);
  353     }
  354 
  355     /* If a client-side certificate is configured, create an explicit client context */
  356     if (ctx_config->client_cert_file && ctx_config->client_key_file) {
  357         client_ctx = createSSLContext(ctx_config, protocols, 1);
  358         if (!client_ctx) goto error;
  359     }
  360 
  361     SSL_CTX_free(redis_tls_ctx);
  362     SSL_CTX_free(redis_tls_client_ctx);
  363     redis_tls_ctx = ctx;
  364     redis_tls_client_ctx = client_ctx;
  365 
  366     return C_OK;
  367 
  368 error:
  369     if (ctx) SSL_CTX_free(ctx);
  370     if (client_ctx) SSL_CTX_free(client_ctx);
  371     return C_ERR;
  372 }
  373 
  374 #ifdef TLS_DEBUGGING
  375 #define TLSCONN_DEBUG(fmt, ...) \
  376     serverLog(LL_DEBUG, "TLSCONN: " fmt, __VA_ARGS__)
  377 #else
  378 #define TLSCONN_DEBUG(fmt, ...)
  379 #endif
  380 
  381 ConnectionType CT_TLS;
  382 
  383 /* Normal socket connections have a simple events/handler correlation.
  384  *
  385  * With TLS connections we need to handle cases where during a logical read
  386  * or write operation, the SSL library asks to block for the opposite
  387  * socket operation.
  388  *
  389  * When this happens, we need to do two things:
  390  * 1. Make sure we register for the event.
  391  * 2. Make sure we know which handler needs to execute when the
  392  *    event fires.  That is, if we notify the caller of a write operation
  393  *    that it blocks, and SSL asks for a read, we need to trigger the
  394  *    write handler again on the next read event.
  395  *
  396  */
  397 
  398 typedef enum {
  399     WANT_READ = 1,
  400     WANT_WRITE
  401 } WantIOType;
  402 
  403 #define TLS_CONN_FLAG_READ_WANT_WRITE   (1<<0)
  404 #define TLS_CONN_FLAG_WRITE_WANT_READ   (1<<1)
  405 #define TLS_CONN_FLAG_FD_SET            (1<<2)
  406 
  407 typedef struct tls_connection {
  408     connection c;
  409     int flags;
  410     SSL *ssl;
  411     char *ssl_error;
  412     listNode *pending_list_node;
  413 } tls_connection;
  414 
  415 static connection *createTLSConnection(int client_side) {
  416     SSL_CTX *ctx = redis_tls_ctx;
  417     if (client_side && redis_tls_client_ctx)
  418         ctx = redis_tls_client_ctx;
  419     tls_connection *conn = zcalloc(sizeof(tls_connection));
  420     conn->c.type = &CT_TLS;
  421     conn->c.fd = -1;
  422     conn->ssl = SSL_new(ctx);
  423     return (connection *) conn;
  424 }
  425 
  426 connection *connCreateTLS(void) {
  427     return createTLSConnection(1);
  428 }
  429 
  430 /* Fetch the latest OpenSSL error and store it in the connection */
  431 static void updateTLSError(tls_connection *conn) {
  432     conn->c.last_errno = 0;
  433     if (conn->ssl_error) zfree(conn->ssl_error);
  434     conn->ssl_error = zmalloc(512);
  435     ERR_error_string_n(ERR_get_error(), conn->ssl_error, 512);
  436 }
  437 
  438 /* Create a new TLS connection that is already associated with
  439  * an accepted underlying file descriptor.
  440  *
  441  * The socket is not ready for I/O until connAccept() was called and
  442  * invoked the connection-level accept handler.
  443  *
  444  * Callers should use connGetState() and verify the created connection
  445  * is not in an error state.
  446  */
  447 connection *connCreateAcceptedTLS(int fd, int require_auth) {
  448     tls_connection *conn = (tls_connection *) createTLSConnection(0);
  449     conn->c.fd = fd;
  450     conn->c.state = CONN_STATE_ACCEPTING;
  451 
  452     if (!conn->ssl) {
  453         updateTLSError(conn);
  454         conn->c.state = CONN_STATE_ERROR;
  455         return (connection *) conn;
  456     }
  457 
  458     switch (require_auth) {
  459         case TLS_CLIENT_AUTH_NO:
  460             SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
  461             break;
  462         case TLS_CLIENT_AUTH_OPTIONAL:
  463             SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, NULL);
  464             break;
  465         default: /* TLS_CLIENT_AUTH_YES, also fall-secure */
  466             SSL_set_verify(conn->ssl, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  467             break;
  468     }
  469 
  470     SSL_set_fd(conn->ssl, conn->c.fd);
  471     SSL_set_accept_state(conn->ssl);
  472 
  473     return (connection *) conn;
  474 }
  475 
  476 static void tlsEventHandler(struct aeEventLoop *el, int fd, void *clientData, int mask);
  477 
  478 /* Process the return code received from OpenSSL>
  479  * Update the want parameter with expected I/O.
  480  * Update the connection's error state if a real error has occured.
  481  * Returns an SSL error code, or 0 if no further handling is required.
  482  */
  483 static int handleSSLReturnCode(tls_connection *conn, int ret_value, WantIOType *want) {
  484     if (ret_value <= 0) {
  485         int ssl_err = SSL_get_error(conn->ssl, ret_value);
  486         switch (ssl_err) {
  487             case SSL_ERROR_WANT_WRITE:
  488                 *want = WANT_WRITE;
  489                 return 0;
  490             case SSL_ERROR_WANT_READ:
  491                 *want = WANT_READ;
  492                 return 0;
  493             case SSL_ERROR_SYSCALL:
  494                 conn->c.last_errno = errno;
  495                 if (conn->ssl_error) zfree(conn->ssl_error);
  496                 conn->ssl_error = errno ? zstrdup(strerror(errno)) : NULL;
  497                 break;
  498             default:
  499                 /* Error! */
  500                 updateTLSError(conn);
  501                 break;
  502         }
  503 
  504         return ssl_err;
  505     }
  506 
  507     return 0;
  508 }
  509 
  510 void registerSSLEvent(tls_connection *conn, WantIOType want) {
  511     int mask = aeGetFileEvents(server.el, conn->c.fd);
  512 
  513     switch (want) {
  514         case WANT_READ:
  515             if (mask & AE_WRITABLE) aeDeleteFileEvent(server.el, conn->c.fd, AE_WRITABLE);
  516             if (!(mask & AE_READABLE)) aeCreateFileEvent(server.el, conn->c.fd, AE_READABLE,
  517                         tlsEventHandler, conn);
  518             break;
  519         case WANT_WRITE:
  520             if (mask & AE_READABLE) aeDeleteFileEvent(server.el, conn->c.fd, AE_READABLE);
  521             if (!(mask & AE_WRITABLE)) aeCreateFileEvent(server.el, conn->c.fd, AE_WRITABLE,
  522                         tlsEventHandler, conn);
  523             break;
  524         default:
  525             serverAssert(0);
  526             break;
  527     }
  528 }
  529 
  530 void updateSSLEvent(tls_connection *conn) {
  531     int mask = aeGetFileEvents(server.el, conn->c.fd);
  532     int need_read = conn->c.read_handler || (conn->flags & TLS_CONN_FLAG_WRITE_WANT_READ);
  533     int need_write = conn->c.write_handler || (conn->flags & TLS_CONN_FLAG_READ_WANT_WRITE);
  534 
  535     if (need_read && !(mask & AE_READABLE))
  536         aeCreateFileEvent(server.el, conn->c.fd, AE_READABLE, tlsEventHandler, conn);
  537     if (!need_read && (mask & AE_READABLE))
  538         aeDeleteFileEvent(server.el, conn->c.fd, AE_READABLE);
  539 
  540     if (need_write && !(mask & AE_WRITABLE))
  541         aeCreateFileEvent(server.el, conn->c.fd, AE_WRITABLE, tlsEventHandler, conn);
  542     if (!need_write && (mask & AE_WRITABLE))
  543         aeDeleteFileEvent(server.el, conn->c.fd, AE_WRITABLE);
  544 }
  545 
  546 static void tlsHandleEvent(tls_connection *conn, int mask) {
  547     int ret, conn_error;
  548 
  549     TLSCONN_DEBUG("tlsEventHandler(): fd=%d, state=%d, mask=%d, r=%d, w=%d, flags=%d",
  550             fd, conn->c.state, mask, conn->c.read_handler != NULL, conn->c.write_handler != NULL,
  551             conn->flags);
  552 
  553     ERR_clear_error();
  554 
  555     switch (conn->c.state) {
  556         case CONN_STATE_CONNECTING:
  557             conn_error = connGetSocketError((connection *) conn);
  558             if (conn_error) {
  559                 conn->c.last_errno = conn_error;
  560                 conn->c.state = CONN_STATE_ERROR;
  561             } else {
  562                 if (!(conn->flags & TLS_CONN_FLAG_FD_SET)) {
  563                     SSL_set_fd(conn->ssl, conn->c.fd);
  564                     conn->flags |= TLS_CONN_FLAG_FD_SET;
  565                 }
  566                 ret = SSL_connect(conn->ssl);
  567                 if (ret <= 0) {
  568                     WantIOType want = 0;
  569                     if (!handleSSLReturnCode(conn, ret, &want)) {
  570                         registerSSLEvent(conn, want);
  571 
  572                         /* Avoid hitting UpdateSSLEvent, which knows nothing
  573                          * of what SSL_connect() wants and instead looks at our
  574                          * R/W handlers.
  575                          */
  576                         return;
  577                     }
  578 
  579                     /* If not handled, it's an error */
  580                     conn->c.state = CONN_STATE_ERROR;
  581                 } else {
  582                     conn->c.state = CONN_STATE_CONNECTED;
  583                 }
  584             }
  585 
  586             if (!callHandler((connection *) conn, conn->c.conn_handler)) return;
  587             conn->c.conn_handler = NULL;
  588             break;
  589         case CONN_STATE_ACCEPTING:
  590             ret = SSL_accept(conn->ssl);
  591             if (ret <= 0) {
  592                 WantIOType want = 0;
  593                 if (!handleSSLReturnCode(conn, ret, &want)) {
  594                     /* Avoid hitting UpdateSSLEvent, which knows nothing
  595                      * of what SSL_connect() wants and instead looks at our
  596                      * R/W handlers.
  597                      */
  598                     registerSSLEvent(conn, want);
  599                     return;
  600                 }
  601 
  602                 /* If not handled, it's an error */
  603                 conn->c.state = CONN_STATE_ERROR;
  604             } else {
  605                 conn->c.state = CONN_STATE_CONNECTED;
  606             }
  607 
  608             if (!callHandler((connection *) conn, conn->c.conn_handler)) return;
  609             conn->c.conn_handler = NULL;
  610             break;
  611         case CONN_STATE_CONNECTED:
  612         {
  613             int call_read = ((mask & AE_READABLE) && conn->c.read_handler) ||
  614                 ((mask & AE_WRITABLE) && (conn->flags & TLS_CONN_FLAG_READ_WANT_WRITE));
  615             int call_write = ((mask & AE_WRITABLE) && conn->c.write_handler) ||
  616                 ((mask & AE_READABLE) && (conn->flags & TLS_CONN_FLAG_WRITE_WANT_READ));
  617 
  618             /* Normally we execute the readable event first, and the writable
  619              * event laster. This is useful as sometimes we may be able
  620              * to serve the reply of a query immediately after processing the
  621              * query.
  622              *
  623              * However if WRITE_BARRIER is set in the mask, our application is
  624              * asking us to do the reverse: never fire the writable event
  625              * after the readable. In such a case, we invert the calls.
  626              * This is useful when, for instance, we want to do things
  627              * in the beforeSleep() hook, like fsynching a file to disk,
  628              * before replying to a client. */
  629             int invert = conn->c.flags & CONN_FLAG_WRITE_BARRIER;
  630 
  631             if (!invert && call_read) {
  632                 conn->flags &= ~TLS_CONN_FLAG_READ_WANT_WRITE;
  633                 if (!callHandler((connection *) conn, conn->c.read_handler)) return;
  634             }
  635 
  636             /* Fire the writable event. */
  637             if (call_write) {
  638                 conn->flags &= ~TLS_CONN_FLAG_WRITE_WANT_READ;
  639                 if (!callHandler((connection *) conn, conn->c.write_handler)) return;
  640             }
  641 
  642             /* If we have to invert the call, fire the readable event now
  643              * after the writable one. */
  644             if (invert && call_read) {
  645                 conn->flags &= ~TLS_CONN_FLAG_READ_WANT_WRITE;
  646                 if (!callHandler((connection *) conn, conn->c.read_handler)) return;
  647             }
  648 
  649             /* If SSL has pending that, already read from the socket, we're at
  650              * risk of not calling the read handler again, make sure to add it
  651              * to a list of pending connection that should be handled anyway. */
  652             if ((mask & AE_READABLE)) {
  653                 if (SSL_pending(conn->ssl) > 0) {
  654                     if (!conn->pending_list_node) {
  655                         listAddNodeTail(pending_list, conn);
  656                         conn->pending_list_node = listLast(pending_list);
  657                     }
  658                 } else if (conn->pending_list_node) {
  659                     listDelNode(pending_list, conn->pending_list_node);
  660                     conn->pending_list_node = NULL;
  661                 }
  662             }
  663 
  664             break;
  665         }
  666         default:
  667             break;
  668     }
  669 
  670     updateSSLEvent(conn);
  671 }
  672 
  673 static void tlsEventHandler(struct aeEventLoop *el, int fd, void *clientData, int mask) {
  674     UNUSED(el);
  675     UNUSED(fd);
  676     tls_connection *conn = clientData;
  677     tlsHandleEvent(conn, mask);
  678 }
  679 
  680 static void connTLSClose(connection *conn_) {
  681     tls_connection *conn = (tls_connection *) conn_;
  682 
  683     if (conn->ssl) {
  684         SSL_free(conn->ssl);
  685         conn->ssl = NULL;
  686     }
  687 
  688     if (conn->ssl_error) {
  689         zfree(conn->ssl_error);
  690         conn->ssl_error = NULL;
  691     }
  692 
  693     if (conn->pending_list_node) {
  694         listDelNode(pending_list, conn->pending_list_node);
  695         conn->pending_list_node = NULL;
  696     }
  697 
  698     CT_Socket.close(conn_);
  699 }
  700 
  701 static int connTLSAccept(connection *_conn, ConnectionCallbackFunc accept_handler) {
  702     tls_connection *conn = (tls_connection *) _conn;
  703     int ret;
  704 
  705     if (conn->c.state != CONN_STATE_ACCEPTING) return C_ERR;
  706     ERR_clear_error();
  707 
  708     /* Try to accept */
  709     conn->c.conn_handler = accept_handler;
  710     ret = SSL_accept(conn->ssl);
  711 
  712     if (ret <= 0) {
  713         WantIOType want = 0;
  714         if (!handleSSLReturnCode(conn, ret, &want)) {
  715             registerSSLEvent(conn, want);   /* We'll fire back */
  716             return C_OK;
  717         } else {
  718             conn->c.state = CONN_STATE_ERROR;
  719             return C_ERR;
  720         }
  721     }
  722 
  723     conn->c.state = CONN_STATE_CONNECTED;
  724     if (!callHandler((connection *) conn, conn->c.conn_handler)) return C_OK;
  725     conn->c.conn_handler = NULL;
  726 
  727     return C_OK;
  728 }
  729 
  730 static int connTLSConnect(connection *conn_, const char *addr, int port, const char *src_addr, ConnectionCallbackFunc connect_handler) {
  731     tls_connection *conn = (tls_connection *) conn_;
  732 
  733     if (conn->c.state != CONN_STATE_NONE) return C_ERR;
  734     ERR_clear_error();
  735 
  736     /* Initiate Socket connection first */
  737     if (CT_Socket.connect(conn_, addr, port, src_addr, connect_handler) == C_ERR) return C_ERR;
  738 
  739     /* Return now, once the socket is connected we'll initiate
  740      * TLS connection from the event handler.
  741      */
  742     return C_OK;
  743 }
  744 
  745 static int connTLSWrite(connection *conn_, const void *data, size_t data_len) {
  746     tls_connection *conn = (tls_connection *) conn_;
  747     int ret, ssl_err;
  748 
  749     if (conn->c.state != CONN_STATE_CONNECTED) return -1;
  750     ERR_clear_error();
  751     ret = SSL_write(conn->ssl, data, data_len);
  752 
  753     if (ret <= 0) {
  754         WantIOType want = 0;
  755         if (!(ssl_err = handleSSLReturnCode(conn, ret, &want))) {
  756             if (want == WANT_READ) conn->flags |= TLS_CONN_FLAG_WRITE_WANT_READ;
  757             updateSSLEvent(conn);
  758             errno = EAGAIN;
  759             return -1;
  760         } else {
  761             if (ssl_err == SSL_ERROR_ZERO_RETURN ||
  762                     ((ssl_err == SSL_ERROR_SYSCALL && !errno))) {
  763                 conn->c.state = CONN_STATE_CLOSED;
  764                 return 0;
  765             } else {
  766                 conn->c.state = CONN_STATE_ERROR;
  767                 return -1;
  768             }
  769         }
  770     }
  771 
  772     return ret;
  773 }
  774 
  775 static int connTLSRead(connection *conn_, void *buf, size_t buf_len) {
  776     tls_connection *conn = (tls_connection *) conn_;
  777     int ret;
  778     int ssl_err;
  779 
  780     if (conn->c.state != CONN_STATE_CONNECTED) return -1;
  781     ERR_clear_error();
  782     ret = SSL_read(conn->ssl, buf, buf_len);
  783     if (ret <= 0) {
  784         WantIOType want = 0;
  785         if (!(ssl_err = handleSSLReturnCode(conn, ret, &want))) {
  786             if (want == WANT_WRITE) conn->flags |= TLS_CONN_FLAG_READ_WANT_WRITE;
  787             updateSSLEvent(conn);
  788 
  789             errno = EAGAIN;
  790             return -1;
  791         } else {
  792             if (ssl_err == SSL_ERROR_ZERO_RETURN ||
  793                     ((ssl_err == SSL_ERROR_SYSCALL) && !errno)) {
  794                 conn->c.state = CONN_STATE_CLOSED;
  795                 return 0;
  796             } else {
  797                 conn->c.state = CONN_STATE_ERROR;
  798                 return -1;
  799             }
  800         }
  801     }
  802 
  803     return ret;
  804 }
  805 
  806 static const char *connTLSGetLastError(connection *conn_) {
  807     tls_connection *conn = (tls_connection *) conn_;
  808 
  809     if (conn->ssl_error) return conn->ssl_error;
  810     return NULL;
  811 }
  812 
  813 int connTLSSetWriteHandler(connection *conn, ConnectionCallbackFunc func, int barrier) {
  814     conn->write_handler = func;
  815     if (barrier)
  816         conn->flags |= CONN_FLAG_WRITE_BARRIER;
  817     else
  818         conn->flags &= ~CONN_FLAG_WRITE_BARRIER;
  819     updateSSLEvent((tls_connection *) conn);
  820     return C_OK;
  821 }
  822 
  823 int connTLSSetReadHandler(connection *conn, ConnectionCallbackFunc func) {
  824     conn->read_handler = func;
  825     updateSSLEvent((tls_connection *) conn);
  826     return C_OK;
  827 }
  828 
  829 static void setBlockingTimeout(tls_connection *conn, long long timeout) {
  830     anetBlock(NULL, conn->c.fd);
  831     anetSendTimeout(NULL, conn->c.fd, timeout);
  832     anetRecvTimeout(NULL, conn->c.fd, timeout);
  833 }
  834 
  835 static void unsetBlockingTimeout(tls_connection *conn) {
  836     anetNonBlock(NULL, conn->c.fd);
  837     anetSendTimeout(NULL, conn->c.fd, 0);
  838     anetRecvTimeout(NULL, conn->c.fd, 0);
  839 }
  840 
  841 static int connTLSBlockingConnect(connection *conn_, const char *addr, int port, long long timeout) {
  842     tls_connection *conn = (tls_connection *) conn_;
  843     int ret;
  844 
  845     if (conn->c.state != CONN_STATE_NONE) return C_ERR;
  846 
  847     /* Initiate socket blocking connect first */
  848     if (CT_Socket.blocking_connect(conn_, addr, port, timeout) == C_ERR) return C_ERR;
  849 
  850     /* Initiate TLS connection now.  We set up a send/recv timeout on the socket,
  851      * which means the specified timeout will not be enforced accurately. */
  852     SSL_set_fd(conn->ssl, conn->c.fd);
  853     setBlockingTimeout(conn, timeout);
  854 
  855     if ((ret = SSL_connect(conn->ssl)) <= 0) {
  856         conn->c.state = CONN_STATE_ERROR;
  857         return C_ERR;
  858     }
  859     unsetBlockingTimeout(conn);
  860 
  861     conn->c.state = CONN_STATE_CONNECTED;
  862     return C_OK;
  863 }
  864 
  865 static ssize_t connTLSSyncWrite(connection *conn_, char *ptr, ssize_t size, long long timeout) {
  866     tls_connection *conn = (tls_connection *) conn_;
  867 
  868     setBlockingTimeout(conn, timeout);
  869     SSL_clear_mode(conn->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
  870     int ret = SSL_write(conn->ssl, ptr, size);
  871     SSL_set_mode(conn->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
  872     unsetBlockingTimeout(conn);
  873 
  874     return ret;
  875 }
  876 
  877 static ssize_t connTLSSyncRead(connection *conn_, char *ptr, ssize_t size, long long timeout) {
  878     tls_connection *conn = (tls_connection *) conn_;
  879 
  880     setBlockingTimeout(conn, timeout);
  881     int ret = SSL_read(conn->ssl, ptr, size);
  882     unsetBlockingTimeout(conn);
  883 
  884     return ret;
  885 }
  886 
  887 static ssize_t connTLSSyncReadLine(connection *conn_, char *ptr, ssize_t size, long long timeout) {
  888     tls_connection *conn = (tls_connection *) conn_;
  889     ssize_t nread = 0;
  890 
  891     setBlockingTimeout(conn, timeout);
  892 
  893     size--;
  894     while(size) {
  895         char c;
  896 
  897         if (SSL_read(conn->ssl,&c,1) <= 0) {
  898             nread = -1;
  899             goto exit;
  900         }
  901         if (c == '\n') {
  902             *ptr = '\0';
  903             if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
  904             goto exit;
  905         } else {
  906             *ptr++ = c;
  907             *ptr = '\0';
  908             nread++;
  909         }
  910         size--;
  911     }
  912 exit:
  913     unsetBlockingTimeout(conn);
  914     return nread;
  915 }
  916 
  917 static int connTLSGetType(connection *conn_) {
  918     (void) conn_;
  919 
  920     return CONN_TYPE_TLS;
  921 }
  922 
  923 ConnectionType CT_TLS = {
  924     .ae_handler = tlsEventHandler,
  925     .accept = connTLSAccept,
  926     .connect = connTLSConnect,
  927     .blocking_connect = connTLSBlockingConnect,
  928     .read = connTLSRead,
  929     .write = connTLSWrite,
  930     .close = connTLSClose,
  931     .set_write_handler = connTLSSetWriteHandler,
  932     .set_read_handler = connTLSSetReadHandler,
  933     .get_last_error = connTLSGetLastError,
  934     .sync_write = connTLSSyncWrite,
  935     .sync_read = connTLSSyncRead,
  936     .sync_readline = connTLSSyncReadLine,
  937     .get_type = connTLSGetType
  938 };
  939 
  940 int tlsHasPendingData() {
  941     if (!pending_list)
  942         return 0;
  943     return listLength(pending_list) > 0;
  944 }
  945 
  946 int tlsProcessPendingData() {
  947     listIter li;
  948     listNode *ln;
  949 
  950     int processed = listLength(pending_list);
  951     listRewind(pending_list,&li);
  952     while((ln = listNext(&li))) {
  953         tls_connection *conn = listNodeValue(ln);
  954         tlsHandleEvent(conn, AE_READABLE);
  955     }
  956     return processed;
  957 }
  958 
  959 /* Fetch the peer certificate used for authentication on the specified
  960  * connection and return it as a PEM-encoded sds.
  961  */
  962 sds connTLSGetPeerCert(connection *conn_) {
  963     tls_connection *conn = (tls_connection *) conn_;
  964     if (conn_->type->get_type(conn_) != CONN_TYPE_TLS || !conn->ssl) return NULL;
  965 
  966     X509 *cert = SSL_get_peer_certificate(conn->ssl);
  967     if (!cert) return NULL;
  968 
  969     BIO *bio = BIO_new(BIO_s_mem());
  970     if (bio == NULL || !PEM_write_bio_X509(bio, cert)) {
  971         if (bio != NULL) BIO_free(bio);
  972         return NULL;
  973     }
  974 
  975     const char *bio_ptr;
  976     long long bio_len = BIO_get_mem_data(bio, &bio_ptr);
  977     sds cert_pem = sdsnewlen(bio_ptr, bio_len);
  978     BIO_free(bio);
  979 
  980     return cert_pem;
  981 }
  982 
  983 #else   /* USE_OPENSSL */
  984 
  985 void tlsInit(void) {
  986 }
  987 
  988 void tlsCleanup(void) {
  989 }
  990 
  991 int tlsConfigure(redisTLSContextConfig *ctx_config) {
  992     UNUSED(ctx_config);
  993     return C_OK;
  994 }
  995 
  996 connection *connCreateTLS(void) { 
  997     return NULL;
  998 }
  999 
 1000 connection *connCreateAcceptedTLS(int fd, int require_auth) {
 1001     UNUSED(fd);
 1002     UNUSED(require_auth);
 1003 
 1004     return NULL;
 1005 }
 1006 
 1007 int tlsHasPendingData() {
 1008     return 0;
 1009 }
 1010 
 1011 int tlsProcessPendingData() {
 1012     return 0;
 1013 }
 1014 
 1015 sds connTLSGetPeerCert(connection *conn_) {
 1016     (void) conn_;
 1017     return NULL;
 1018 }
 1019 
 1020 #endif