Experiments and implementations · Intermediate

Test certificate hostname validation

Use a disposable local CA and TLS server to distinguish a trusted chain from a certificate matching the intended hostname.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Encryption and intended-peer validation are separate questions
  2. Create a disposable CA and a SAN-bearing certificate
  3. Run three cases without disabling verification
  4. Interpret one success and two rejections
  5. State what the fixture does not verify
  6. Do not count unrelated connection failures as validation success
  7. Exercise: explain name and destination separately
  8. Ask Logeia about this articleCheck your understanding

Encryption and intended-peer validation are separate questions

If TLS encrypts a connection, has the client necessarily reached its intended peer? Connect to a self-owned local server under three conditions: the correct name, a different name, and an untrusted CA. No real site's certificate or browser configuration is modified. Certificate verification remains enabled, and the experiment requires one success and two distinct rejections. Read the public-key, PKI, and TLS overview first.

The network address is 127.0.0.1, but the intended service name is app.test. Reaching an address and matching the intended name against the certificate are different checks. Python's server_hostname argument supplies that name in this fixture. Merely observing that a socket connected does not demonstrate that the expected service identity was checked. The experiment deliberately makes these inputs visible and independently variable.

Create a disposable CA and a SAN-bearing certificate

Provide Python 3.12 and the OpenSSL command-line tool. The program creates a CA key and certificate in a temporary directory, then uses that CA to sign a server certificate. The server certificate contains subjectAltName DNS:app.test. CA signing and server-authentication purposes are specified, and certificates last one day for this experiment. Private-key files are not distributed outside the temporary workspace.

Client trust is configured through cafile on an SSLContext. The program does not add a CA to the operating system or an existing browser. The server binds only to a free loopback port. No DNS registration for app.test is required because the socket explicitly connects to 127.0.0.1. Distinguish name resolution, network connection, and the identity being validated rather than assuming they must always be the same input string.

Run three cases without disabling verification

Save the code as certificate_boundary.py and run python3.12 certificate_boundary.py. It uses create_default_context and asserts that check_hostname is true and verify_mode is CERT_REQUIRED. The positive case trusts the test CA and uses app.test. The name-mismatch case retains that CA and changes only the requested name to other.test.

The untrusted-CA case restores app.test but uses default trust without loading the experimental CA. Changing one condition at a time keeps the rejection reason interpretable. The server catches TLS errors from negative cases because those clients deliberately reject the handshake. Other server exceptions are retained and checked at the end. Connection and join timeouts prevent an unnoticed failed test from waiting indefinitely. Preserve those checks when adapting the fixture rather than weakening validation to make completion easier.

python
import json
import socket
import ssl
import subprocess
import tempfile
import threading
from pathlib import Path

def openssl(*args):
    subprocess.run(['openssl', *args], check=True, capture_output=True)

with tempfile.TemporaryDirectory(prefix='lavacs-tls-') as directory:
    root = Path(directory)
    def p(name): return str(root / name)
    openssl('req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-sha256', '-days', '1', '-subj', '/CN=LavaCS disposable test CA', '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign', '-keyout', p('ca.key'), '-out', p('ca.pem'))
    openssl('req', '-new', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=app.test', '-keyout', p('server.key'), '-out', p('server.csr'))
    (root / 'extensions.cnf').write_text('subjectAltName=DNS:app.test\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n')
    openssl('x509', '-req', '-in', p('server.csr'), '-CA', p('ca.pem'), '-CAkey', p('ca.key'), '-CAcreateserial', '-days', '1', '-sha256', '-extfile', p('extensions.cnf'), '-out', p('server.pem'))
    server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    server_context.load_cert_chain(p('server.pem'), p('server.key'))
    listener = socket.socket()
    listener.bind(('127.0.0.1', 0))
    listener.listen(3)
    listener.settimeout(10)
    port = listener.getsockname()[1]
    server_errors = []
    def serve():
        try:
            for _ in range(3):
                conn, _ = listener.accept()
                with conn:
                    try:
                        with server_context.wrap_socket(conn, server_side=True) as tls:
                            tls.sendall(b'ok')
                    except ssl.SSLError:
                        pass  # Negative client tests intentionally reject this handshake.
        except Exception as error:
            server_errors.append(repr(error))
    thread = threading.Thread(target=serve, daemon=True)
    thread.start()
    observations = []
    try:
        for case, name, trust_ca in [('correct', 'app.test', True), ('wrong-name', 'other.test', True), ('untrusted-ca', 'app.test', False)]:
            context = ssl.create_default_context(cafile=p('ca.pem')) if trust_ca else ssl.create_default_context()
            assert context.check_hostname and context.verify_mode == ssl.CERT_REQUIRED
            try:
                with socket.create_connection(('127.0.0.1', port), timeout=5) as raw:
                    with context.wrap_socket(raw, server_hostname=name) as tls:
                        assert tls.recv(2) == b'ok'
                assert case == 'correct'
                observations.append({'case': case, 'accepted': True})
            except ssl.SSLCertVerificationError as error:
                assert case != 'correct'
                observations.append({'case': case, 'accepted': False, 'verifyCode': error.verify_code, 'reason': error.verify_message})
    finally:
        thread.join(timeout=12)
        listener.close()
    assert not thread.is_alive() and not server_errors, server_errors
    assert [x['accepted'] for x in observations] == [True, False, False]
    print(json.dumps({'openssl': ssl.OPENSSL_VERSION, 'observations': observations}))

Interpret one success and two rejections

The recorded Python 3.12.14 runtime linked OpenSSL 3.5.8. The correct case succeeded; wrong-name and untrusted-ca raised SSLCertVerificationError. Verification codes were 62 for name mismatch and 20 for the untrusted CA. These are recorded environment observations, not a promise that every release uses identical wording. Preserve the condition, exception category, and reason. The OpenSSL executable used for certificate creation can also have a different version from the library linked into Python.

The valid success distinguishes verification rejection from a server that simply never started. The two negative cases answer different questions. A trusted CA signature does not make a different hostname the intended peer, while a matching name without a trust basis is insufficient. Possessing some certificate establishes neither condition by itself.

State what the fixture does not verify

This fixture tests explicit CA trust and intended-hostname validation. It does not fully test revocation-information retrieval, public trust-store operations, key rotation, mutual TLS, or load-balancer configuration. Ordinary certificate validation also considers validity periods, but the fixture does not implement an expiry scenario. One successful handshake cannot certify an entire production TLS deployment.

Nor does successful TLS peer validation authorize application operations. After connecting to the correct service, permission to read a particular document remains an authentication and authorization question. Changing to check_hostname=False or CERT_NONE after a failure would remove the boundaries just tested. Investigate the intended CA, expected name, certificate purpose, clock, and network path to identify the failed condition. Correct its cause rather than treating absent validation as a successful repair.

Do not count unrelated connection failures as validation success

The wrong-name case does not accept just any connection failure as a passing negative test. It catches SSLCertVerificationError; connection refusal or timeout remains an ordinary test failure. A stopped server cannot provide evidence that hostname validation worked. Combine the successful positive connection, the two certificate-validation failures, and the absence of unexpected server errors. Together they support the claim that rejection occurred at the intended boundary. This is also why the program retains explicit thread completion checks instead of silently abandoning a server that never processed the expected handshakes.

Exercise: explain name and destination separately

Explain what happens when only server_hostname changes to other.test while the network destination stays fixed. The socket can reach loopback, but the certificate lacks that SAN identity, so validation rejects it. Next explain why removing CA trust fails even after restoring app.test. The expected name matches, but the chain no longer has the intended trust basis. State the changed condition instead of reporting only “TLS failed.”

Finally assess the claim that a verification error makes encryption pointless. It does not: the peer-validation check has rejected an unsatisfied condition that needs investigation. Record Python and linked OpenSSL versions, the certificate-generation tool version, all three name/trust combinations, acceptance or rejection, and reasons. Exclude private-key contents and reusable credentials from the record.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 21

Choose a learning path