Skip to content
Misconfiguration Disclosed report Intermediate

Fail-Open in set_tlsext_servername_callback on pyopenssl via unhandled exceptions leads to security bypass

The pyopenssl library's SNI callback wrapper catches exceptions from user code but returns success to OpenSSL, so a TLS handshake continues even when the security check crashes. An attacker could bypass SNI-based access controls if they can trigger an exception in the callback.

uv3doble Follow

Originally disclosed on HackerOne

  • Triaged in under an hour
  • Fixed in 38 hours
  • Disclosed after 32 days

Fail-Open Vulnerability in set_tlsext_servername_callback allows Security Bypass via Unhandled Exceptions

Summary

The pyopenssl library exhibits a Fail-Open vulnerability in its handling of the Server Name Indication (SNI) callback (set_tlsext_servername_callback). The internal wrapper for this callback catches all Python exceptions raised by user code but returns 0 (Success/SSL_TLSEXT_ERR_OK) to the underlying OpenSSL engine.

This behavior allows a TLS connection to be successfully established even when the security validation logic inside the callback crashes or raises an exception, potentially bypassing critical access controls or authentication mechanisms implemented at the SNI layer.

Vulnerability Description

In src/OpenSSL/SSL.py, the set_tlsext_servername_callback method wraps the user-provided function with a decorator that does not explicitly handle exceptions to signal failure:

Python
# OpenSSL/SSL.py
@wraps(callback)
def wrapper(ssl, alert, arg):
    callback(Connection._reverse_mapping[ssl])
    return 0  # Always returns Success (0)

When callback(...) raises an exception, the CFFI layer catches it, prints the traceback to stderr, and returns the default value for the declared return type (int), which is 0.

In the context of the OpenSSL SSL_CTX_set_tlsext_servername_callback, a return value of 0 corresponds to SSL_TLSEXT_ERR_OK. Consequently, OpenSSL proceeds with the handshake as if the validation succeeded.

Correct Secure Behavior (Fail-Closed): If the callback raises an unhandled exception, the wrapper should catch it and return SSL_TLSEXT_ERR_ALERT_FATAL (or similar) to abort the handshake, ensuring a secure failure state.

Steps to Reproduce

  1. Install pyopenssl.
  2. Run the following Python script (poc.py).
  3. Observe that the client successfully connects and receives data ("VULNERABILITY CONFIRMED") despite the server's validation callback raising a ValueError.

Proof of Concept (PoC)

Python
import socket
import threading
import time
from OpenSSL import SSL, crypto
import os

def generate_cert():
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)
    cert = crypto.X509()
    cert.get_subject().CN = 'VulnerableServer'
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')
    return cert, k

cert, key = generate_cert()

def crashing_callback(connection):
    # Simulates a security check that crashes (e.g., DB error, logic bug)
    print("\n[SERVER] Callback executing... Raising Exception!")
    raise ValueError("Critical Security Check Failed!")
    # The code never reaches a point to explicitly reject the connection.

def start_server():
    context = SSL.Context(SSL.TLS_SERVER_METHOD)
    context.use_privatekey(key)
    context.use_certificate(cert)
    context.set_tlsext_servername_callback(crashing_callback)
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Using port 4433 to avoid conflicts
    try:
        server.bind(('localhost', 4433))
    except Exception as e:
        print(f"[SERVER] Bind failed (port busy?): {e}")
        return
        
    server.listen(1)
    
    try:
        conn, addr = server.accept()
        ssl_conn = SSL.Connection(context, conn)
        ssl_conn.set_accept_state()
        try:
            ssl_conn.do_handshake()
            # If we reach here, the vulnerability is triggered
            ssl_conn.sendall(b"VULNERABILITY CONFIRMED: Connection Accepted")
            ssl_conn.shutdown()
        except Exception as e:
            print(f"[SERVER] Handshake Failed (Safe): {e}")
        finally:
            ssl_conn.close()
            conn.close()
    finally:
        server.close()

def start_client():
    time.sleep(1)
    context = SSL.Context(SSL.TLS_CLIENT_METHOD)
    context.set_verify(SSL.VERIFY_NONE, lambda *args: True)
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', 4433))
        ssl_conn = SSL.Connection(context, sock)
        ssl_conn.set_connect_state()
        ssl_conn.set_tlsext_host_name(b"test.local")
        
        try:
            ssl_conn.do_handshake()
            data = ssl_conn.recv(1024)
            print(f"\n[CLIENT] Received: {data.decode()}")
        except Exception as e:
            print(f"\n[CLIENT] Handshake Failed: {e}")
    finally:
        sock.close()

if __name__ == '__main__':
    t = threading.Thread(target=start_server)
    t.start()
    start_client()
    t.join()

Impact

This issue allows attackers to bypass security controls implemented via SNI callbacks.

If a developer relies on set_tlsext_servername_callback to enforce access policies (e.g., "Allow connection only if SNI matches X"), an attacker who can trigger an exception in that logic (e.g., via malformed input or resource exhaustion) will successfully establish a TLS connection, bypassing the intended restriction. This violates the "Fail-Secure" design principle required for security-critical libraries.

The original report as published on HackerOne, by uv3doble. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 7 min read.

Context

pyopenssl is a Python wrapper around OpenSSL, published by the Python Cryptographic Authority and hosted at https://github.com/pyca/pyopenssl. Among the features it exposes is the Server Name Indication (SNI) callback, registered through set_tlsext_servername_callback. SNI lets a TLS client announce the hostname it wants to reach during the handshake, and the callback is the hook where a server can inspect that name and decide whether the connection should continue. Developers commonly use it to select a certificate or to enforce access policy, for example allowing a connection only when the SNI matches an expected value.

The report describes a fail-open behaviour in that callback path: when the user-supplied callback raises an unhandled Python exception, the library still tells the underlying OpenSSL engine that the callback succeeded, so the handshake proceeds.

Setup

The reproduction needs only a working Python environment with pyopenssl installed. The proof of concept generates its own self-signed certificate at runtime, so no external certificate files, accounts or roles are required. The server binds to localhost on port 4433, chosen in the script to avoid conflicts, and the client connects to the same address. The client disables certificate verification with SSL.VERIFY_NONE, which keeps the demonstration focused on the SNI callback rather than on certificate validation.

Finding it

The researcher looked at how set_tlsext_servername_callback in src/OpenSSL/SSL.py wraps the function supplied by the developer. The wrapper is decorated with @wraps(callback) and does not handle exceptions in any way that signals failure:

Python
# OpenSSL/SSL.py
@wraps(callback)
def wrapper(ssl, alert, arg):
    callback(Connection._reverse_mapping[ssl])
    return 0  # Always returns Success (0)

Two things stand out. First, the wrapper returns 0 unconditionally after invoking the callback. Second, when callback(...) raises, the exception is not caught by the wrapper at all: it propagates into the CFFI layer, which catches it, prints the traceback to stderr, and returns the default value for the declared return type (int), which is 0.

In the OpenSSL API, the return value of a callback registered through SSL_CTX_set_tlsext_servername_callback is interpreted as a status code, and 0 corresponds to SSL_TLSEXT_ERR_OK. So in both the normal path and the crashing path, OpenSSL is told that the SNI processing succeeded and the handshake continues. The report states that a crash inside security validation logic should instead abort the handshake, which is the fail-closed behaviour the library should provide.

Exploitation

Step 1: Install the library

Install pyopenssl in the environment where the proof of concept will run.

Step 2: Run the proof of concept

The script below generates a certificate, starts a TLS server whose SNI callback always raises ValueError, and connects a client that sends the SNI name [redacted].

Python
import socket
import threading
import time
from OpenSSL import SSL, crypto
import os

def generate_cert():
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)
    cert = crypto.X509()
    cert.get_subject().CN = 'VulnerableServer'
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')
    return cert, k

cert, key = generate_cert()

def crashing_callback(connection):
    # Simulates a security check that crashes (e.g., DB error, logic bug)
    print("\n[SERVER] Callback executing... Raising Exception!")
    raise ValueError("Critical Security Check Failed!")
    # The code never reaches a point to explicitly reject the connection.

def start_server():
    context = SSL.Context(SSL.TLS_SERVER_METHOD)
    context.use_privatekey(key)
    context.use_certificate(cert)
    context.set_tlsext_servername_callback(crashing_callback)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Using port 4433 to avoid conflicts
    try:
        server.bind(('localhost', 4433))
    except Exception as e:
        print(f"[SERVER] Bind failed (port busy?): {e}")
        return

    server.listen(1)

    try:
        conn, addr = server.accept()
        ssl_conn = SSL.Connection(context, conn)
        ssl_conn.set_accept_state()
        try:
            ssl_conn.do_handshake()
            # If we reach here, the vulnerability is triggered
            ssl_conn.sendall(b"VULNERABILITY CONFIRMED: Connection Accepted")
            ssl_conn.shutdown()
        except Exception as e:
            print(f"[SERVER] Handshake Failed (Safe): {e}")
        finally:
            ssl_conn.close()
            conn.close()
    finally:
        server.close()

def start_client():
    time.sleep(1)
    context = SSL.Context(SSL.TLS_CLIENT_METHOD)
    context.set_verify(SSL.VERIFY_NONE, lambda *args: True)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', 4433))
        ssl_conn = SSL.Connection(context, sock)
        ssl_conn.set_connect_state()
        ssl_conn.set_tlsext_host_name(b"[redacted]")

        try:
            ssl_conn.do_handshake()
            data = ssl_conn.recv(1024)
            print(f"\n[CLIENT] Received: {data.decode()}")
        except Exception as e:
            print(f"\n[CLIENT] Handshake Failed: {e}")
    finally:
        sock.close()

if __name__ == '__main__':
    t = threading.Thread(target=start_server)
    t.start()
    start_client()
    t.join()

The important parts:

  • generate_cert() builds a 2048-bit RSA key and a self-signed certificate with common name VulnerableServer, serial number 1000, valid from now for ten years, signed with sha256. This is only there so the server has something to present.
  • crashing_callback(connection) is the SNI callback. It prints a line and then raises ValueError("Critical Security Check Failed!"). The comment in the script notes that the code never reaches a point where it could explicitly reject the connection, which models a security check that crashes before it can make a decision.
  • start_server() creates a TLS_SERVER_METHOD context, loads the key and certificate, and registers crashing_callback with set_tlsext_servername_callback. It binds to localhost:4433, listens for one connection, wraps the accepted socket in an SSL.Connection, sets the accept state and calls do_handshake(). If the handshake returns, the server sends VULNERABILITY CONFIRMED: Connection Accepted. If the handshake raises, it prints [SERVER] Handshake Failed (Safe): ... instead.
  • start_client() waits one second, creates a TLS_CLIENT_METHOD context with SSL.VERIFY_NONE, connects to localhost:4433, sets the connect state, sets the SNI name to [redacted] with set_tlsext_host_name(b"[redacted]"), performs the handshake and reads up to 1024 bytes.

Step 3: Observe the result

The client connects successfully and receives the data VULNERABILITY CONFIRMED, even though the server's validation callback raised ValueError. In other words, the handshake completed on both sides despite the crash in the SNI logic. The server-side branch that would have printed Handshake Failed (Safe) is not taken.

Root cause

The wrapper installed by set_tlsext_servername_callback has no exception handling that maps a failure to a failure status. When the callback returns normally, the wrapper returns 0. When the callback raises, the exception escapes the wrapper, CFFI catches it, prints the traceback to stderr and returns the default value for the declared int return type, which is again 0. In both cases OpenSSL receives SSL_TLSEXT_ERR_OK and continues the handshake.

The design intent of the OpenSSL callback contract is that the return value carries the decision: SSL_TLSEXT_ERR_OK means proceed, while an alert value such as SSL_TLSEXT_ERR_ALERT_FATAL aborts the handshake. Because the wrapper never produces a non-zero value on the exception path, the decision that the developer's code failed to make is silently replaced by "proceed". The report frames this as a violation of the fail-secure principle expected of security-critical libraries: the safe default when validation cannot complete should be to reject, not to accept.

Impact

Any application that relies on set_tlsext_servername_callback to enforce access policy is affected in the situation where the callback raises. The report's example is a policy of the form "allow the connection only if the SNI matches X". If an attacker can cause the callback logic to throw, for instance through malformed input or resource exhaustion, the TLS connection is established anyway and the intended restriction is bypassed. The same applies to authentication or access-control decisions implemented at the SNI layer: a crash in that logic becomes an allow rather than a deny.

The severity recorded for the report is low. Exploitation depends on the attacker being able to trigger an exception in the specific callback logic of the target application; the library bug turns that crash into a bypass, but it does not by itself provide a way to cause the crash.

Fix

The report states the correct secure behaviour rather than a specific patch: if the callback raises an unhandled exception, the wrapper should catch it and return SSL_TLSEXT_ERR_ALERT_FATAL (or a similar alert value) so that the handshake is aborted and the failure is secure.

Variants to test

  1. Other pyopenssl callbacks with the same wrapper pattern. Look for callbacks whose return value is a status code and whose wrapper returns a constant. A positive result is a callback that raises and yet the handshake or operation continues.
  2. SNI callbacks that return None implicitly. A callback that falls off the end without returning anything may be treated the same way as a crash. A positive result is a handshake that completes when the callback made no explicit decision.
  3. Applications that enforce policy in the SNI callback. Review server code that uses set_tlsext_servername_callback for allow-listing or certificate selection. A positive result is a connection that succeeds after the callback raises, for example when a lookup fails or input is malformed.
  4. Exception paths triggered by attacker-controlled input. Where the callback parses the SNI name or looks it up in a data store, try inputs that cause parsing errors or lookup failures. A positive result is a completed handshake with the policy not applied.
  5. Resource exhaustion inside the callback. If the callback performs I/O or allocation, drive it into failure. A positive result is again a successful handshake despite the failed check.
  6. Comparable wrappers in other language bindings. Check bindings that expose the same OpenSSL SNI callback and see whether an exception in user code maps to a fatal alert or to success. A positive result is a handshake that proceeds after the user callback throws.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

A library called pyopenssl lets Python programs talk to the OpenSSL engine, which is the software that handles encrypted connections (the padlock in your browser). One of the things you can do with it is register a small function of your own that gets called during the very first moments of an encrypted connection, when the client says which website name it is trying to reach. That moment is called the SNI callback.

Developers use that callback as a checkpoint: "only let this connection continue if the name looks right". The report shows that if the developer's checkpoint function crashes (throws an error), pyopenssl still tells OpenSSL "all good, carry on". The connection is then accepted even though the security check never finished. In security language, a system that lets you through when its check breaks is called fail-open. The opposite, letting nothing through when the check breaks, is fail-closed or fail-secure, and that is what a security library should do.

The report was filed against the Python Cryptographic Authority's pyopenssl project on GitHub, and its severity was recorded as low.

Some background before we start

A few ideas come up again and again, so here they are from zero.

  • Library: a bundle of ready-made code that other programs use, so the programmer does not have to write everything themselves. Think of it as a box of pre-built Lego pieces.
  • OpenSSL: the most widely used library for encrypted connections. When your browser shows a padlock, OpenSSL (or something like it) is doing the encryption work underneath.
  • pyopenssl: a thin Python layer that lets Python code use OpenSSL. It is a wrapper: it takes your Python instructions and passes them down to OpenSSL.
  • TLS handshake: the short conversation at the start of an encrypted connection where the two sides agree on keys and check who they are. If the handshake succeeds, data can flow. If it fails, the connection is dropped.
  • SNI (Server Name Indication): during the handshake, the client tells the server which hostname it wants, for example shop.example.com. This lets one server host many websites. The name travels in the clear, before encryption is set up.
  • Callback: a function you hand to a library, which the library promises to call for you at the right moment. Like leaving your phone number with a receptionist: they call you when your visitor arrives.
  • Exception: Python's word for an error being raised. When code hits a problem it cannot handle, it "raises" an exception, and unless something catches it, the program stops that piece of work.
  • CFFI: a Python tool that lets Python call C code (OpenSSL is written in C). It sits between the Python wrapper and OpenSSL and translates values back and forth.
  • Return value / status code: when a function finishes, it hands back a value. In callback contracts, that value is often a status code: a number that means "ok", "stop", "send an alert", and so on.
  • Fail-open vs fail-closed: fail-open means a broken check lets traffic through. Fail-closed means a broken check blocks traffic. For security checks, fail-closed is the safe choice.

Context

pyopenssl is a Python wrapper around OpenSSL, published by the Python Cryptographic Authority and hosted at https://github.com/pyca/pyopenssl. Among the features it exposes is the Server Name Indication (SNI) callback, registered through set_tlsext_servername_callback. SNI lets a TLS client announce the hostname it wants to reach during the handshake, and the callback is the hook where a server can inspect that name and decide whether the connection should continue. Developers commonly use it to select a certificate or to enforce access policy, for example allowing a connection only when the SNI matches an expected value.

The report describes a fail-open behaviour in that callback path: when the user-supplied callback raises an unhandled Python exception, the library still tells the underlying OpenSSL engine that the callback succeeded, so the handshake proceeds.

In everyday terms: you hire a doorman (the callback) to check IDs at the door. If the doorman faints, the building's rulebook should say "nobody enters". Here, the rulebook says "if the doorman faints, assume the ID was fine".

Setup

The reproduction needs only a working Python environment with pyopenssl installed. The proof of concept generates its own self-signed certificate at runtime, so no external certificate files, accounts or roles are required. The server binds to localhost on port 4433, chosen in the script to avoid conflicts, and the client connects to the same address. The client disables certificate verification with SSL.VERIFY_NONE, which keeps the demonstration focused on the SNI callback rather than on certificate validation.

A few words on those pieces:

  • Self-signed certificate: a certificate the program makes for itself instead of buying one from an authority. Fine for a local test, because nobody else needs to trust it.
  • localhost: your own computer, seen from inside. A server on localhost is only reachable from the same machine.
  • Port: a numbered door on a computer. Web traffic normally uses 443; the script uses 4433 to avoid clashing with anything already running.
  • SSL.VERIFY_NONE: tells the client not to check the server's certificate. In real life you would never do this; here it removes a distraction so the test only shows the SNI callback behaviour.

Finding it

The researcher looked at how set_tlsext_servername_callback in src/OpenSSL/SSL.py wraps the function supplied by the developer. The wrapper is decorated with @wraps(callback) and does not handle exceptions in any way that signals failure:

Python
# OpenSSL/SSL.py
@wraps(callback)
def wrapper(ssl, alert, arg):
    callback(Connection._reverse_mapping[ssl])
    return 0  # Always returns Success (0)

Line by line:

  1. # OpenSSL/SSL.py is just a comment saying which file this code lives in.
  2. @wraps(callback) is a Python decoration that makes the wrapper look like the original function (same name, same documentation). It changes nothing about behaviour.
  3. def wrapper(ssl, alert, arg): defines the function that OpenSSL will actually call. It receives three things from OpenSSL: the connection, an alert value, and an extra argument.
  4. callback(Connection._reverse_mapping[ssl]) calls the developer's own function, translating the raw OpenSSL connection into the Python object the developer expects.
  5. return 0 # Always returns Success (0) hands back the number 0 to OpenSSL, no matter what happened inside the developer's function.

Two things stand out. First, the wrapper returns 0 unconditionally after invoking the callback. Second, when callback(...) raises, the exception is not caught by the wrapper at all: it propagates into the CFFI layer, which catches it, prints the traceback to stderr, and returns the default value for the declared return type (int), which is 0.

In the OpenSSL API, the return value of a callback registered through SSL_CTX_set_tlsext_servername_callback is interpreted as a status code, and 0 corresponds to SSL_TLSEXT_ERR_OK. So in both the normal path and the crashing path, OpenSSL is told that the SNI processing succeeded and the handshake continues. The report states that a crash inside security validation logic should instead abort the handshake, which is the fail-closed behaviour the library should provide.

Why does CFFI return 0? When the callback raises, CFFI catches it, prints the traceback to stderr, and returns the default value for the declared return type (int), which is 0. And zero, in this particular contract, happens to mean "success". That is the unlucky coincidence at the heart of the bug.

Exploitation

Step 1: Install the library

Install pyopenssl in the environment where the proof of concept will run.

This step is just preparation: the test script needs the library present before it can import it.

Step 2: Run the proof of concept

The script below generates a certificate, starts a TLS server whose SNI callback always raises ValueError, and connects a client that sends the SNI name [redacted].

Python
import socket
import threading
import time
from OpenSSL import SSL, crypto
import os

def generate_cert():
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)
    cert = crypto.X509()
    cert.get_subject().CN = 'VulnerableServer'
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')
    return cert, k

cert, key = generate_cert()

def crashing_callback(connection):
    # Simulates a security check that crashes (e.g., DB error, logic bug)
    print("\n[SERVER] Callback executing... Raising Exception!")
    raise ValueError("Critical Security Check Failed!")
    # The code never reaches a point to explicitly reject the connection.

def start_server():
    context = SSL.Context(SSL.TLS_SERVER_METHOD)
    context.use_privatekey(key)
    context.use_certificate(cert)
    context.set_tlsext_servername_callback(crashing_callback)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Using port 4433 to avoid conflicts
    try:
        server.bind(('localhost', 4433))
    except Exception as e:
        print(f"[SERVER] Bind failed (port busy?): {e}")
        return

    server.listen(1)

    try:
        conn, addr = server.accept()
        ssl_conn = SSL.Connection(context, conn)
        ssl_conn.set_accept_state()
        try:
            ssl_conn.do_handshake()
            # If we reach here, the vulnerability is triggered
            ssl_conn.sendall(b"VULNERABILITY CONFIRMED: Connection Accepted")
            ssl_conn.shutdown()
        except Exception as e:
            print(f"[SERVER] Handshake Failed (Safe): {e}")
        finally:
            ssl_conn.close()
            conn.close()
    finally:
        server.close()

def start_client():
    time.sleep(1)
    context = SSL.Context(SSL.TLS_CLIENT_METHOD)
    context.set_verify(SSL.VERIFY_NONE, lambda *args: True)

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', 4433))
        ssl_conn = SSL.Connection(context, sock)
        ssl_conn.set_connect_state()
        ssl_conn.set_tlsext_host_name(b"[redacted]")

        try:
            ssl_conn.do_handshake()
            data = ssl_conn.recv(1024)
            print(f"\n[CLIENT] Received: {data.decode()}")
        except Exception as e:
            print(f"\n[CLIENT] Handshake Failed: {e}")
    finally:
        sock.close()

if __name__ == '__main__':
    t = threading.Thread(target=start_server)
    t.start()
    start_client()
    t.join()

The important parts:

  • generate_cert() builds a 2048-bit RSA key and a self-signed certificate with common name VulnerableServer, serial number 1000, valid from now for ten years, signed with sha256. This is only there so the server has something to present.
  • crashing_callback(connection) is the SNI callback. It prints a line and then raises ValueError("Critical Security Check Failed!"). The comment in the script notes that the code never reaches a point where it could explicitly reject the connection, which models a security check that crashes before it can make a decision.
  • start_server() creates a TLS_SERVER_METHOD context, loads the key and certificate, and registers crashing_callback with set_tlsext_servername_callback. It binds to localhost:4433, listens for one connection, wraps the accepted socket in an SSL.Connection, sets the accept state and calls do_handshake(). If the handshake returns, the server sends VULNERABILITY CONFIRMED: Connection Accepted. If the handshake raises, it prints [SERVER] Handshake Failed (Safe): ... instead.
  • start_client() waits one second, creates a TLS_CLIENT_METHOD context with SSL.VERIFY_NONE, connects to localhost:4433, sets the connect state, sets the SNI name to [redacted] with set_tlsext_host_name(b"[redacted]"), performs the handshake and reads up to 1024 bytes.

A slower walk through the same script, in the order it runs:

  1. The imports at the top bring in socket (raw network connections), threading (so the server and client can run at the same time in one program), time (for the one-second pause), and SSL and crypto from OpenSSL.
  2. generate_cert() makes a key pair and a certificate. A key pair is a matched pair of numbers: one public (shared with the world) and one private (kept secret). The certificate is the public half plus a name, wrapped up so the other side can use it.
  3. cert, key = generate_cert() runs that function once and keeps the results.
  4. crashing_callback is the doorman that faints. It is deliberately broken: it raises an error instead of saying yes or no. This models a real check that hits a database error or a bug.
  5. start_server() builds a context, which is the settings bundle for a TLS server: which key, which certificate, which callback. Then it opens a socket, binds it to localhost on port 4433, and waits for one connection.
  6. When a client arrives, the server wraps the raw connection in SSL.Connection, tells it to act as the accepting side, and starts the handshake. The handshake is where the SNI callback fires.
  7. If do_handshake() returns without error, the server sends the confirmation text. If it raises, the server prints the "Safe" message. Which branch runs is the whole test.
  8. start_client() waits a second so the server is ready, builds a client context, turns off certificate checking, connects, sets the SNI name to [redacted], and starts its own handshake. Then it reads up to 1024 bytes and prints them.
  9. The if __name__ == '__main__': block starts the server in a background thread, runs the client in the main thread, and waits for the server thread to finish.

Step 3: Observe the result

The client connects successfully and receives the data VULNERABILITY CONFIRMED, even though the server's validation callback raised ValueError. In other words, the handshake completed on both sides despite the crash in the SNI logic. The server-side branch that would have printed Handshake Failed (Safe) is not taken.

That single line of output is the proof. The doorman fainted, and the door opened anyway.

Root cause

The wrapper installed by set_tlsext_servername_callback has no exception handling that maps a failure to a failure status. When the callback returns normally, the wrapper returns 0. When the callback raises, the exception escapes the wrapper, CFFI catches it, prints the traceback to stderr and returns the default value for the declared int return type, which is again 0. In both cases OpenSSL receives SSL_TLSEXT_ERR_OK and continues the handshake.

The design intent of the OpenSSL callback contract is that the return value carries the decision: SSL_TLSEXT_ERR_OK means proceed, while an alert value such as SSL_TLSEXT_ERR_ALERT_FATAL aborts the handshake. Because the wrapper never produces a non-zero value on the exception path, the decision that the developer's code failed to make is silently replaced by "proceed". The report frames this as a violation of the fail-secure principle expected of security-critical libraries: the safe default when validation cannot complete should be to reject, not to accept.

Think of a traffic light with a broken controller. The safe behaviour is to flash red or switch to a default that stops cars. Here, the broken controller defaults to green.

Impact

Any application that relies on set_tlsext_servername_callback to enforce access policy is affected in the situation where the callback raises. The report's example is a policy of the form "allow the connection only if the SNI matches X". If an attacker can cause the callback logic to throw, for instance through malformed input or resource exhaustion, the TLS connection is established anyway and the intended restriction is bypassed. The same applies to authentication or access-control decisions implemented at the SNI layer: a crash in that logic becomes an allow rather than a deny.

The severity recorded for the report is low. Exploitation depends on the attacker being able to trigger an exception in the specific callback logic of the target application; the library bug turns that crash into a bypass, but it does not by itself provide a way to cause the crash.

In plain words: the bug is a multiplier, not a standalone attack. The attacker still needs a way to make the application's own check fall over. Once that happens, this library bug turns the stumble into an open door.

Fix

The report states the correct secure behaviour rather than a specific patch: if the callback raises an unhandled exception, the wrapper should catch it and return SSL_TLSEXT_ERR_ALERT_FATAL (or a similar alert value) so that the handshake is aborted and the failure is secure.

A fatal alert is a TLS message that says "stop, this connection is over". Sending it is the equivalent of the doorman, on fainting, having a colleague lock the door.

Variants to test

  1. Other pyopenssl callbacks with the same wrapper pattern. Look for callbacks whose return value is a status code and whose wrapper returns a constant. A positive result is a callback that raises and yet the handshake or operation continues.
  2. SNI callbacks that return None implicitly. A callback that falls off the end without returning anything may be treated the same way as a crash. A positive result is a handshake that completes when the callback made no explicit decision.
  3. Applications that enforce policy in the SNI callback. Review server code that uses set_tlsext_servername_callback for allow-listing or certificate selection. A positive result is a connection that succeeds after the callback raises, for example when a lookup fails or input is malformed.
  4. Exception paths triggered by attacker-controlled input. Where the callback parses the SNI name or looks it up in a data store, try inputs that cause parsing errors or lookup failures. A positive result is a completed handshake with the policy not applied.
  5. Resource exhaustion inside the callback. If the callback performs I/O or allocation, drive it into failure. A positive result is again a successful handshake despite the failed check.
  6. Comparable wrappers in other language bindings. Check bindings that expose the same OpenSSL SNI callback and see whether an exception in user code maps to a fatal alert or to success. A positive result is a handshake that proceeds after the user callback throws.

These variants are all the same question asked in different places: when the check breaks, does the system say no, or does it say yes?

Glossary

  • API: a defined set of functions one piece of software offers to another, like a menu of things you are allowed to ask for.
  • Callback: a function you give to a library so it can call it later at the right moment.
  • Certificate: a digital document that binds a name to a public key, used to prove identity in an encrypted connection.
  • CFFI: a Python tool that lets Python code call C code and translates values between the two.
  • Context (SSL.Context): a bundle of settings (keys, certificates, callbacks) used to create encrypted connections.
  • Exception: Python's mechanism for signalling that something went wrong; if uncaught, it interrupts the current work.
  • Fail-closed / fail-secure: when a check breaks, the safe outcome is to deny.
  • Fail-open: when a check breaks, the unsafe outcome is to allow.
  • Fatal alert: a TLS message that aborts the connection immediately.
  • Handshake: the opening conversation of a TLS connection where the two sides agree on keys and verify each other.
  • Key pair: a matched public and private key; the public one is shared, the private one stays secret.
  • Library: reusable code that other programs build on.
  • localhost: the name a computer uses to refer to itself.
  • OpenSSL: the widely used C library that implements TLS encryption.
  • Port: a numbered channel on a computer that network connections use.
  • pyopenssl: a Python wrapper that exposes OpenSSL to Python programs.
  • Return value / status code: the value a function hands back, often a number that encodes a decision.
  • Self-signed certificate: a certificate signed by its own key rather than by an external authority.
  • SNI (Server Name Indication): the hostname a client announces at the start of a TLS handshake.
  • Socket: the programmatic handle for a network connection.
  • SSL_TLSEXT_ERR_OK: the OpenSSL status meaning "SNI processing succeeded, continue".
  • SSL_TLSEXT_ERR_ALERT_FATAL: the OpenSSL status meaning "abort the handshake with a fatal alert".
  • Thread: a way for one program to do two things at once, used here to run server and client together.
  • TLS: the protocol that encrypts traffic between a client and a server (the S in HTTPS).
  • Traceback: the printed list of function calls that led to an error.
  • Wrapper: code that sits around another piece of code and passes calls through, sometimes adding behaviour.

More from Python Cryptographic Authority

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Security misconfiguration

The lesson behind this report.

Settings left unsafe: exposed panels, open storage buckets, debug modes, default credentials.