PREP WITH PROOF
Menu
SECURITY & NETWORKING / PRACTICAL GUIDE

Troubleshoot mTLS: Client Certificates, Trust and curl Errors

Separate server trust from client authentication in mTLS. Diagnose missing certificates, wrong issuers, key mismatches and authorization with a tested local TLS lab.

THE QUICK ANSWER

A working server certificate proves only one direction of trust. In mutual TLS, the client must also present an acceptable certificate and prove possession of its private key. Diagnose which peer rejected which evidence before changing a trust store. This guide separates client-side server verification, server-side client authentication, and the application authorization decision, then demonstrates those boundaries with an isolated loopback lab.

Draw the two trust decisions before changing files

A service can have a publicly trusted server certificate while accepting client certificates from a private organization CA. Those are separate policies. On the client, the server CA bundle helps verify the service it contacted. On the server, the client CA configuration determines which client certificate paths it will accept. Copying one bundle into the other location can create an unintended trust boundary.

Think of four distinct artifacts: the server certificate and key, the client trust anchors for servers, the client certificate and key, and the server trust anchors for clients. A PEM filename does not reveal which role it serves. Label each file by purpose and owner before replacing it. Intermediate certificates help construct paths; they do not become trusted merely because a peer sends them.

After certificate authentication, an application still needs to decide which operations that identity may perform. A valid client certificate issued by an accepted CA is not automatically permission to read every tenant or invoke every API. Record the expected identity mapping and authorization policy alongside the TLS configuration.

Source: Python ssl: contexts, certificate requirements and verification ↗

Capture the failing layer and the actual TLS terminator

Record the URL hostname, port, time, client version, TLS backend, and exact error from an authorized diagnostic request. Use curl --version to identify its TLS backend. A Linux OpenSSL-backed curl and a Windows Schannel build can load identities and trust differently. The PEM examples below target the former; consult the documentation for your actual build.

Identify where TLS terminates: the application, ingress, load balancer, API gateway, or sidecar. If a gateway authenticates the caller and opens a second connection upstream, those are two TLS sessions with independent credentials and policies. Inspect the logs at the component that rejected the first session. Application logs may be empty when the handshake never reached HTTP.

Use the smallest read-only request that reproduces the issue. Verbose output can expose hostnames, headers, and identity details, so redact it before sharing. Do not publish private keys or passphrase material in diagnostic logs. Changing both certificate bundles and the endpoint simultaneously destroys the comparison you need.

Source: curl command-line options: certificate, key, CA and resolve ↗

Use curl options for their separate roles

In this command, --cacert verifies the server, while --cert and --key supply the client identity. The server decides whether to request and accept that identity. Merely supplying a client certificate does not prove that the server required one. Successful authentication also requires proof of possession of the corresponding private key during the handshake.

The hostname in the URL remains the service identity being verified. If you need to direct an approved diagnostic request to a particular IP, --resolve can preserve the intended hostname while selecting that address. It does not make an arbitrary address trustworthy. Keep certificate verification enabled and confirm that the certificate SAN covers the requested name.

The --insecure option weakens server verification; it does not repair the client certificate, its issuing chain, or the server client-CA policy. Likewise, trusting the client issuing CA locally does not make the remote server trust it. Fix the failing direction and repeat the same request before investigating a later layer.

curl --version
curl --cacert server-trust.pem \
  --cert client.pem --key client.key \
  --connect-timeout 5 --max-time 15 \
  https://api.example.com/health

Source: curl command-line options: certificate, key, CA and resolve ↗

Translate symptoms into a specific next check

Error wording and curl exit codes vary by TLS version, backend, and which peer sends the alert. A generic handshake error is not a reliable diagnosis by itself. Compare the client output with the TLS terminator log at the same time, then test one hypothesis. The table identifies investigation paths rather than promising a universal mapping from text to cause.

ObservationInspect nextDecision boundary
Server certificate validation failsRequested hostname, server chain, client server-CA storeClient verifies server
Server says certificate requiredWhether client identity was loaded and offeredServer requires client
Unknown CA / issuer rejectionClient chain and server accepted client CAsServer verifies client
Unsuitable certificate purposeLeaf extended key usage and server validation policyCertificate suitability
Local key/certificate loading failureFile format, access, passphrase and public-key matchClient setup
HTTP 403 after TLSIdentity mapping, route and authorization logsApplication or gateway policy

Source: curl: server certificate verification and CA stores ↗

Check the client identity without exporting its private key

Inspect the leaf subject, issuer, dates, and extensions. Extended Key Usage, when present, constrains certificate use; an identity restricted to server authentication can be unsuitable for client authentication. Also check intermediate constraints, signature policy, and the intended trust anchor. A client certificate can be correctly signed yet inappropriate for this service.

The local verification command below checks one proposed path for the sslclient purpose. Supply the server-approved client trust anchors and required untrusted intermediates, rather than whatever bundle happens to exist on your laptop. This is supporting evidence: the server may enforce additional policies, revocation checks, identity rules, or a different chain-building configuration.

Compare public keys from the leaf certificate and private key if loading fails. Use a suitable tool for the key type; do not rely on an RSA-only modulus recipe when the identity uses EC keys. Verify file readability in the actual service account or container. Reissuing a certificate will not fix a process that cannot read the mounted identity.

Keep a distinction between the certificate path you can assemble offline and the certificate list the client actually sends. A successful local verify invocation with manually supplied intermediates does not establish that a gateway received those intermediates. Check the client format requirements and the terminator diagnostic evidence. In deployments with intermediate issuing CAs, reproduce both complete-chain and missing-intermediate cases in staging. Do not solve a missing-intermediate problem by trusting every leaf or disabling validation. Conversely, avoid assuming that the peer must send the root: the receiving side needs its own explicitly approved trust anchor. The simple direct-root lab below intentionally leaves this chain-delivery question outside its test coverage.

openssl x509 -in client.pem -noout -subject -issuer -dates -text
openssl verify -purpose sslclient \
  -CAfile accepted-client-roots.pem \
  -untrusted client-intermediates.pem client.pem

Source: OpenSSL verify: purpose and certificate-chain validation ↗

Distinguish requesting a certificate from enforcing validation

Test utilities can deliberately relax behavior to aid debugging. For OpenSSL s_server, lowercase -verify requests a client certificate without requiring one; uppercase -Verify requires the client to supply a certificate. Use -verify_return_error to stop on certificate verification errors, because the diagnostic default can otherwise continue after displaying them. A server that prints a validation failure and then responds is not evidence of enforced client trust.

For an application server, inspect its equivalent settings separately: request client certificates, require one, and reject invalid chains. Python server contexts can use CERT_REQUIRED together with explicitly loaded client CA certificates. Product-specific settings differ, so do not transfer an OpenSSL command-line switch into an ingress configuration by analogy.

Source: OpenSSL s_server: required certificates and verification errors ↗

Run an isolated lab with separate server and client CAs

Save the following as mtls_lab.py and run python3 mtls_lab.py with Python 3, OpenSSL 3.x and an OpenSSL-backed curl available on PATH. It creates one-day disposable CA and leaf keys in a temporary directory, binds only to 127.0.0.1 on an operating-system-selected port, bypasses proxies for these loopback requests, and removes its files on exit. It does not install a CA, use real identities, or contact a public endpoint.

The fixture deliberately uses different server and client CA roots. It runs seven cases under each of TLS 1.2 and TLS 1.3: a valid exchange, no client identity, an untrusted client issuer, a client leaf with server-only purpose, a wrong server hostname, an incorrect server trust bundle, and a mismatched client key. Only the valid case may return the exact HTTP body with a successful curl exit.

The code was executed with Python 3.12.14, OpenSSL 3.0.13 and curl 8.5.0 using the OpenSSL backend: all 14 cases passed. These are local fixture observations, not a claim about every platform or production gateway. The server catches expected handshake failures, while each client case must independently satisfy its success or rejection assertion.

import os
import socket
import ssl
import subprocess
import tempfile
import threading
from pathlib import Path

with tempfile.TemporaryDirectory(prefix='pwp-mtls-') as directory:
    root = Path(directory)

    def openssl(*args):
        subprocess.run(['openssl', *args], cwd=root, check=True,
                       capture_output=True, timeout=30)
        for key in root.glob('*.key'):
            key.chmod(0o600)

    for name in ['server-ca', 'client-ca', 'other-ca']:
        openssl('req', '-x509', '-newkey', 'rsa:2048', '-nodes',
                '-keyout', name + '.key', '-out', name + '.pem',
                '-days', '1', '-subj', '/CN=' + name,
                '-addext', 'basicConstraints=critical,CA:TRUE',
                '-addext', 'keyUsage=critical,keyCertSign,cRLSign')

    def leaf(name, ca, purpose, serial, san=''):
        openssl('req', '-new', '-newkey', 'rsa:2048', '-nodes',
                '-keyout', name + '.key', '-out', name + '.csr',
                '-subj', '/CN=' + name)
        extension = ('basicConstraints=critical,CA:FALSE\n'
                     'keyUsage=critical,digitalSignature,keyEncipherment\n'
                     'extendedKeyUsage=' + purpose + '\n')
        if san:
            extension += 'subjectAltName=' + san + '\n'
        (root / (name + '.ext')).write_text(extension)
        openssl('x509', '-req', '-in', name + '.csr',
                '-CA', ca + '.pem', '-CAkey', ca + '.key',
                '-set_serial', str(serial), '-days', '1',
                '-extfile', name + '.ext', '-out', name + '.pem')

    leaf('server', 'server-ca', 'serverAuth', 10, 'DNS:localhost')
    leaf('client', 'client-ca', 'clientAuth', 11)
    leaf('untrusted', 'other-ca', 'clientAuth', 12)
    leaf('wrong-purpose', 'client-ca', 'serverAuth', 13)

    checks = 0
    for version, curl_flag in [(ssl.TLSVersion.TLSv1_2, '--tlsv1.2'),
                               (ssl.TLSVersion.TLSv1_3, '--tlsv1.3')]:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.minimum_version = context.maximum_version = version
        context.load_cert_chain(root / 'server.pem', root / 'server.key')
        context.load_verify_locations(root / 'client-ca.pem')
        context.verify_mode = ssl.CERT_REQUIRED
        listener = socket.socket()
        listener.bind(('127.0.0.1', 0))
        listener.listen()
        listener.settimeout(0.2)
        port = listener.getsockname()[1]
        stopped = threading.Event()
        unexpected = []

        def serve():
            while not stopped.is_set():
                try:
                    raw, _ = listener.accept()
                except socket.timeout:
                    continue
                try:
                    raw.settimeout(3)
                    with context.wrap_socket(raw, server_side=True) as conn:
                        request = b''
                        while b'\r\n\r\n' not in request and len(request) < 8192:
                            block = conn.recv(1024)
                            if not block:
                                break
                            request += block
                        if b'\r\n\r\n' in request:
                            conn.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 3\r\n'
                                         b'Connection: close\r\n\r\nOK\n')
                except (ssl.SSLError, ConnectionError, TimeoutError):
                    pass  # Expected negative-handshake cases.
                except Exception as error:
                    unexpected.append(repr(error))
                finally:
                    raw.close()

        thread = threading.Thread(target=serve)
        thread.start()
        try:
            identity = ['--cert', 'client.pem', '--key', 'client.key']
            cases = [
                ('valid', identity, 'localhost', 'server-ca.pem', True),
                ('missing client', [], 'localhost', 'server-ca.pem', False),
                ('wrong issuer', ['--cert', 'untrusted.pem', '--key', 'untrusted.key'],
                 'localhost', 'server-ca.pem', False),
                ('wrong purpose', ['--cert', 'wrong-purpose.pem', '--key', 'wrong-purpose.key'],
                 'localhost', 'server-ca.pem', False),
                ('wrong hostname', identity, 'wrong.test', 'server-ca.pem', False),
                ('wrong server trust', identity, 'localhost', 'other-ca.pem', False),
                ('mismatched key', ['--cert', 'client.pem', '--key', 'untrusted.key'],
                 'localhost', 'server-ca.pem', False),
            ]
            for name, credentials, host, trust, expected in cases:
                result = subprocess.run(
                    ['curl', '-q', '--silent', '--show-error', '--noproxy', '*',
                     '--max-time', '5', '--http1.1', curl_flag,
                     '--resolve', f'{host}:{port}:127.0.0.1', '--cacert', trust,
                     *credentials, f'https://{host}:{port}/'],
                    cwd=root, capture_output=True, timeout=8)
                success = result.returncode == 0 and result.stdout == b'OK\n'
                assert success == expected, (version.name, name, result.stderr)
                if not expected:
                    assert result.returncode != 0, (name, result.stdout)
                checks += 1
                print(version.name, name, 'PASS')
        finally:
            stopped.set()
            thread.join(timeout=4)
            listener.close()
        assert not thread.is_alive() and not unexpected, unexpected
    print(f'{checks} TLS cases passed; temporary certificates removed on exit.')

Source: Python ssl: contexts, certificate requirements and verification ↗

Separate certificate identity from HTTP authorization

If you receive an HTTP response, some TLS session carried that response. It does not necessarily prove end-to-end mTLS to the application. A gateway can return an error page, accept optional client certificates, or terminate TLS before forwarding. Confirm the authenticated identity and route in its logs before declaring the original client-certificate problem solved.

Define identity matching explicitly, for example an approved SAN value mapped to a service account. Do not treat a display name or arbitrary forwarded header as sufficient proof. When an upstream relies on gateway-provided identity, restrict direct access to the upstream and have the trusted gateway overwrite or remove caller-supplied identity headers. The exact mechanism needs the gateway and application documentation.

For certificate rotation, verify overlap intentionally: deploy the intended new trust path, test the new client identity, observe real authorization, and remove old trust only when migration is complete. Record ownership and expiry monitoring. This is an operational sequence to adapt to your system, not a guarantee that every trust-store reload is immediate or disruption-free.

What this lab establishes, and what it leaves open

The lab demonstrates separate trust directions and several concrete rejection paths on one OpenSSL-based environment. Its leaves are signed directly by disposable roots. It does not exercise intermediate-chain delivery, revocation, encrypted private keys, hardware tokens, session resumption, a service mesh, Windows certificate stores, or production certificate rotation. Test those features in an authorized staging environment that matches your deployment.

Use a rejection test as part of configuration verification, not only a happy-path request. Confirm that an absent or unauthorized client identity cannot obtain the protected response, then confirm that a valid identity receives only its intended permissions. Keep the endpoint, client implementation and trust files fixed while changing one variable. That produces evidence you can act on without broadening trust to make an error disappear.

KEEP THESE THREE THINGS

Your next steps

  1. Verify the server and authenticate the client as separate trust decisions.
  2. A supplied certificate, a successful handshake and application authorization are different observations.
  3. Use negative cases to confirm enforcement; preserve server verification throughout diagnosis.

Sources & official resources

Linked resources checked on 2026-10-28. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →