Skip to content

Report the OpenSSL reason when SSL_read/SSL_write fail - #1402

Open
uglide wants to merge 1 commit into
masterfrom
im/async-tls-error-reason
Open

uglide wants to merge 1 commit into
masterfrom
im/async-tls-error-reason

Conversation

@uglide

@uglide uglide commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

redisSSLRead() and redisSSLWrite() report every failure through __redisSetError(c, REDIS_ERR_IO, NULL), which builds the message from errno. For SSL_ERROR_SSL no system call failed, so errno is typically 0 and the error text is Success.

This is most visible on non-blocking contexts. There the TLS handshake is completed by the first reads/writes rather than by SSL_connect(), so a rejected server certificate (untrusted CA, verify_name mismatch, expired certificate, ...) reaches the async disconnect callback as:

Error: Success

The blocking path is not affected: redisSSLConnect() already reads the reason from the OpenSSL error queue.

Fix

Add a small helper, redisSSLSetIOError(), that takes the reason from the OpenSSL error queue when the failure is SSL_ERROR_SSL and keeps the errno based message for everything else. The non-blocking branch of redisSSLRead() and the error branch of redisSSLWrite() use it. The same failure now reads:

Error: SSL error: certificate verify failed

Test

A new polling-adapter test fails an async handshake with a verify_name mismatch and checks that the callback receives REDIS_ERR_IO with an SSL error: message. It needs no libevent and runs with the existing TLS tests. It fails without the ssl.c change.

Verification

Ubuntu 24.04, OpenSSL 3.0.13:

  • Makefile build (USE_SSL=1) and CMake build (-Werror, SSL, SSL tests, async tests, examples): no warnings.
  • TEST_SSL=1 ./test.sh: all tests pass with both builds.

Not tested locally: macOS, Windows, BoringSSL.

Note

#1390 touches the same two functions (it clears the error queue before the I/O call). The changes are complementary and edit different lines of ssl.c, but both add a test call at the same place in test.c, so whichever lands second needs a trivial conflict resolution.

🤖 Generated with Claude Code


Note

Low Risk
Small, localized change to SSL error reporting in the non-blocking read/write paths, with a targeted regression test; no API or handshake logic changes.

Overview
Fixes misleading "Success" I/O errors when async TLS handshakes fail during the first SSL_read/SSL_write (e.g. certificate or verify_name rejection), because SSL_ERROR_SSL puts the reason on OpenSSL’s error queue rather than in errno.

Adds redisSSLSetIOError(), which formats SSL error: <reason> from ERR_peek_last_error() for SSL_ERROR_SSL and otherwise keeps the existing errno-based path. redisSSLRead() and redisSSLWrite() now call it instead of __redisSetError(..., NULL).

Adds test_ssl_async_handshake_failure_reason, which forces a verify_name mismatch on a polling async SSL connection and asserts the disconnect/connect callback sees REDIS_ERR_IO with an SSL error: prefix. It runs with the existing SSL verify-name tests.

Reviewed by Cursor Bugbot for commit d9540ef. Bugbot is set up for automated code reviews on this repo. Configure here.

redisSSLRead() and redisSSLWrite() reported every failure through
__redisSetError(c, REDIS_ERR_IO, NULL), which builds the message from
errno. For SSL_ERROR_SSL no system call failed, so errno is typically 0
and the error text was "Success".

This is most visible on non-blocking contexts: the TLS handshake is
completed by the first reads/writes rather than by SSL_connect(), so a
rejected server certificate (untrusted CA, verify_name mismatch, ...)
reached the async disconnect callback as "Success" with no usable
reason.

Take the reason from the OpenSSL error queue for SSL_ERROR_SSL, as
redisSSLConnect() already does, and keep the errno based message for
everything else.

Add a polling-adapter test that fails an async handshake with a
verify_name mismatch and checks the reported error.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T14:21:29.830793Z d9540ef PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown

ABI compatibility check

✅ libhiredis — compatible

No ABI changes detected.

✅ libhiredis_ssl — compatible

No ABI changes detected.

Baseline e90c24e2239395ea4eb4972cb14eb7a77a778d7b vs head d9540ef7555eb344a4fe0718d0adfd9f1631cc76. Apply the ignore-abi-check label to skip this check for an intentional, SONAME-bumped ABI break.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit d9540ef. Configure here.

Comment thread ssl.c
}
}
__redisSetError(c, REDIS_ERR_IO, NULL);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SSL error fallback still uses errno

Low Severity

When the failure is SSL_ERROR_SSL but ERR_reason_error_string returns NULL, redisSSLSetIOError still calls __redisSetError with a NULL message, so errstr is filled from errno. No syscall failed in this case, so that text is often Success, which is the misleading message this helper exists to avoid. redisSSLConnect already substitutes unknown error when the OpenSSL reason is missing.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d9540ef. Configure here.

@bobymicroby

Copy link
Copy Markdown
Member

Hey @uglide , looks good to me. I ran the tests on darwin/openssl 3.5.9, all pass, and the new test fails without the ssl.c change, so all looks good there.

I played a bit with the blocking path since the description says its not affected. For the cert check thats true, but i found two cases where the read still looses the openssl reason. Both are old, they are on master too, not from this pr - so up to you if you want them here or in a follow up.

  1. blocking read, tls error after the handshake

In redisSSLRead() the REDIS_BLOCK branch only looks at errno and never at err, so it does not go through your new helper. I made a small server that finishes the handshake and then sends a broken tls record :

hiredis c->errstr : "Success"
OpenSSL's reason  : "decryption failed or bad record mac"

(thats on ubuntu 24.04 with openssl 3.0.13, on mac i get "Undefined error: 0" and "record layer failure")

redisSSLWrite() is fine because it has one error branch for both modes. So after this PR blocking write gives the real reason and blocking read doesn't.

  1. SSL_read() returns 0 on a tls alert

redis with tls-auth-clients yes, client sends no cert, TLS 1.3. Handshake is ok on the client side and the rejection comes on the first read:

hiredis c->errstr : "Server closed the connection"
OpenSSL's reason  : "tlsv13 alert certificate required"

the nread == 0 branch reports EOF and doesnt ask openssl anything. I think this one is more common in real life, forgetting the client cert is an easy mistake. I only tested it with a blocking connection, but the check is before the blocking / non-blocking split so i guess async has the same problem.

One nit on the helper - i don't know if its worth the effort to be super defensive here, but in rare cases like openssl builds without error strings, ERR_reason_error_string() can return NULL and then we are back to the errno message. redisSSLConnect() uses "unknown error" for that so we could do the same :

         const char *reason = ERR_reason_error_string(ERR_peek_last_error());
-        if (reason) {
-            char msg[256];
-            snprintf(msg, sizeof(msg), "SSL error: %s", reason);
-            __redisSetError(c, REDIS_ERR_IO, msg);
-            return;
-        }
+        char msg[256];
+        snprintf(msg, sizeof(msg), "SSL error: %s",
+                 reason ? reason : "unknown error");
+        __redisSetError(c, REDIS_ERR_IO, msg);
+        return;
     }
     __redisSetError(c, REDIS_ERR_IO, NULL);

Repro is below if you want to play with it, its one file and needs only docker:

docker run --rm -i ubuntu:24.04 bash < pr-1402-repro.sh

it builds hiredis from this PR inside the container and runs both cases. You can pass -e HIREDIS_REF=master (or any branch / pull/<n>/head) to build something else, e.g to check a fix.

pr-1402-repro.sh
#!/bin/bash
# Repro for two cases where a hiredis TLS read loses the OpenSSL reason.
#
# Run it in a clean Ubuntu container (nothing is installed on the host):
#
#   docker run --rm -i ubuntu:24.04 bash < pr-1402-repro.sh
#
# By default it builds hiredis from PR #1402. To test another ref:
#
#   docker run --rm -i -e HIREDIS_REF=master ubuntu:24.04 bash < pr-1402-repro.sh
#
set -eu
HIREDIS_REF=${HIREDIS_REF:-pull/1402/head}
export DEBIAN_FRONTEND=noninteractive

echo "== installing build tools, redis and openssl (takes a minute)"
apt-get update -qq < /dev/null > /dev/null
apt-get install -y -qq git ca-certificates build-essential libssl-dev \
    redis-server python3 openssl < /dev/null > /dev/null 2>&1

echo "== building hiredis from $HIREDIS_REF"
git clone -q https://github.com/redis/hiredis /hiredis < /dev/null
cd /hiredis
git fetch -q origin "$HIREDIS_REF" < /dev/null
git checkout -q FETCH_HEAD
make USE_SSL=1 libhiredis.a libhiredis_ssl.a > /dev/null 2>&1
echo "hiredis commit: $(git log -1 --format='%h %s')"
echo "$(openssl version), $(redis-server --version | cut -d' ' -f1-3)"

mkdir /work
cd /work

# Blocking client: connects, starts TLS, sends PING, then prints what hiredis
# reports and what OpenSSL has on its error queue at that moment.
cat > repro.c <<'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <openssl/err.h>
#include "hiredis.h"
#include "hiredis_ssl.h"

int main(int argc, char **argv) {
    if (argc < 3) return 2;
    redisSSLContextError e = REDIS_SSL_CTX_NONE;
    /* Trust the test CA, but send NO client certificate. */
    redisSSLOptions opt = { .cacert_filename = argv[2], .verify_mode = REDIS_SSL_VERIFY_PEER };
    redisSSLContext *ctx = redisCreateSSLContextWithOptions(&opt, &e);
    if (!ctx) { printf("ctx error: %s\n", redisSSLContextGetError(e)); return 2; }

    redisContext *c = redisConnect("127.0.0.1", atoi(argv[1]));   /* blocking */
    if (!c || c->err) { printf("tcp connect failed: %s\n", c ? c->errstr : "oom"); return 2; }
    printf("blocking flag set : %s\n", (c->flags & REDIS_BLOCK) ? "yes" : "no");

    int rc = redisInitiateSSLWithContext(c, ctx);
    printf("TLS handshake     : %s%s\n", rc == REDIS_OK ? "OK" : "FAILED: ", rc == REDIS_OK ? "" : c->errstr);
    if (rc != REDIS_OK) return 2;

    errno = 0;
    redisReply *r = redisCommand(c, "PING");
    printf("PING reply        : %s\n", r ? r->str : "(none, command failed)");
    printf("hiredis c->err    : %d (REDIS_ERR_IO is %d, REDIS_ERR_EOF is %d)\n", c->err, REDIS_ERR_IO, REDIS_ERR_EOF);
    printf("hiredis c->errstr : \"%s\"\n", c->errstr);
    const char *reason = ERR_reason_error_string(ERR_peek_last_error());
    printf("OpenSSL's reason  : \"%s\"\n", reason ? reason : "(none)");
    if (r) freeReplyObject(r);
    redisFree(c);
    redisFreeSSLContext(ctx);
    return 0;
}
EOF

# TLS server that finishes the handshake, then sends one broken TLS record.
cat > garbage_server.py <<'EOF'
import socket, ssl, sys, os
port, cert, key = int(sys.argv[1]), sys.argv[2], sys.argv[3]
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(cert, key)
ls = socket.socket(); ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ls.bind(("127.0.0.1", port)); ls.listen(1)
s, _ = ls.accept()
inb, outb = ssl.MemoryBIO(), ssl.MemoryBIO()
obj = ctx.wrap_bio(inb, outb, server_side=True)
while True:
    try:
        obj.do_handshake(); break
    except ssl.SSLWantReadError:
        if outb.pending: s.sendall(outb.read())
        inb.write(s.recv(65536))
if outb.pending: s.sendall(outb.read())
# A record header that says "application data, 32 bytes", followed by junk.
s.sendall(b"\x17\x03\x03\x00\x20" + os.urandom(32))
try: s.recv(65536)
except OSError: pass
s.close()
EOF

# Test CA and a server certificate for 127.0.0.1.
printf 'subjectAltName = IP:127.0.0.1\n' > ext.cnf
openssl genrsa -out ca.key 2048 2> /dev/null
openssl req -x509 -new -nodes -sha256 -key ca.key -days 2 -subj '/CN=Repro CA' -out ca.crt 2> /dev/null
openssl genrsa -out srv.key 2048 2> /dev/null
openssl req -new -sha256 -key srv.key -subj '/CN=Repro Server' 2> /dev/null | \
    openssl x509 -req -sha256 -CA ca.crt -CAkey ca.key -CAcreateserial -days 2 \
        -extfile ext.cnf -out srv.crt 2> /dev/null

cc -I/hiredis repro.c /hiredis/libhiredis_ssl.a /hiredis/libhiredis.a -lssl -lcrypto -o repro

echo
echo "== case 1: blocking read, server sends a broken TLS record after the handshake"
python3 garbage_server.py 56556 srv.crt srv.key < /dev/null > server1.log 2>&1 &
PID=$!
sleep 2
./repro 56556 ca.crt < /dev/null || echo "repro exit=$?"
kill $PID 2> /dev/null || true

echo
echo "== case 2: redis requires a client certificate, client sends none (TLS 1.3)"
redis-server --port 0 --tls-port 56555 --bind 127.0.0.1 \
    --tls-cert-file srv.crt --tls-key-file srv.key --tls-ca-cert-file ca.crt \
    --tls-auth-clients yes --save "" --dir /work --daemonize no < /dev/null > server2.log 2>&1 &
PID=$!
sleep 2
./repro 56555 ca.crt < /dev/null || echo "repro exit=$?"
kill $PID 2> /dev/null || true

echo
echo "In both cases 'hiredis c->errstr' should carry OpenSSL's reason, and it does not."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants