Configuring mTLS on Nginx: Block API Leaks Using Client Certificates

Security tutorial - IT technology blog
Security tutorial - IT technology blog

A 2 AM Wake-Up Call and the Lesson of an Internal API Leak

At 2 AM, the on-call phone rang incessantly. An urgent alert had triggered. Looking at Grafana, the request graph spiked vertically like a cliff: over 45,000 requests per minute slamming into /api/v1/internal/sync-data—the balance reconciliation endpoint between the Payment and Ledger services. Every single IP originated from unfamiliar public ranges across Eastern Europe.

The culprit? The X-Internal-Token header was exposed when a junior engineer inadvertently committed a .env.local file to a public GitHub repository barely 15 minutes earlier.

That night, the entire team learned an expensive lesson: HTTPS combined with Bearer Tokens alone is not enough. Once a token leaks, Nginx still processes incoming requests as usual. Standard TLS only provides one-way encryption and server authentication. If you want to drop unauthorized callers right at the TLS handshake before requests ever reach your application server, you need mTLS (Mutual TLS).

How Does mTLS Differ from Traditional One-Way TLS?

The standard TLS model only requires the client to verify the server. The client checks whether the server certificate is valid and matches the requested domain. Conversely, the server remains completely blind to the client’s identity at the transport layer. All authentication responsibilities are offloaded to the application layer via JWTs, API keys, or session cookies.

With mTLS (Mutual TLS), the rules of engagement change:

  • The server sends its certificate so the client can verify its identity.
  • The client is strictly required to present its own Client Certificate back to the server.
  • Nginx verifies directly whether the client certificate was signed by the trusted internal Root CA. If the certificate is missing or invalid, Nginx terminates the connection immediately with an HTTP 400 Bad Request (No required SSL certificate was sent) status.

The biggest architectural advantage: malicious traffic is severed at the network layer. Upstream backends written in Node.js, Go, or Python do not waste a single CPU cycle parsing JSON or querying databases to validate tokens.

Hands-On: Generating Certificates and Configuring Nginx Step by Step

Step 1: Initialize an Internal Certificate Authority (CA)

First, you must establish an internal Certificate Authority (CA). Every microservice across your cluster will trust this authority. Create a dedicated directory on your management server:

mkdir -p /etc/nginx/certs && cd /etc/nginx/certs

# 1. Generate the private key for the CA (AES-256 encrypted)
openssl genrsa -aes256 -out ca.key 4096

# 2. Generate a self-signed Root CA certificate (valid for 5 years = 1825 days)
openssl req -new -x509 -days 1825 -key ca.key -sha256 -out ca.crt \
  -subj "/C=VN/ST=Hanoi/L=Hanoi/O=FintechCore/OU=Infra/CN=Internal-Root-CA"

Safeguard the ca.key file rigorously and never deploy it to a public server. Only the ca.crt file should be placed on Nginx to verify client signatures.

Step 2: Issue a Server Certificate for Nginx

The Nginx server requires its own key pair and certificate for client identification:

# 1. Generate the private key for the Server
openssl genrsa -out server.key 2048

# 2. Create a Certificate Signing Request (CSR)
openssl req -new -key server.key -out server.csr \
  -subj "/C=VN/ST=Hanoi/L=Hanoi/O=FintechCore/OU=Backend/CN=api-internal.local"

# 3. Sign the Server certificate using the Root CA (valid for 365 days)
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out server.crt -sha256

Step 3: Issue a Client Certificate for the Consuming Microservice

Suppose you have a microservice named payment-worker-01 that needs to query the backend:

# 1. Generate the private key for the Client
openssl genrsa -out client.key 2048

# 2. Create a CSR for the Client
openssl req -new -key client.key -out client.csr \
  -subj "/C=VN/ST=Hanoi/L=Hanoi/O=FintechCore/OU=PaymentWorker/CN=payment-worker-01"

# 3. Sign the Client certificate using the internal CA
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out client.crt -sha256

# (Optional) Export to PKCS#12 (.p12) if administrators need to import into Chrome or Postman
openssl pkcs12 -export -out client.p12 -inkey client.key -in client.crt -certfile ca.crt

Step 4: Configure the Nginx Virtual Host to Enable mTLS

Open /etc/nginx/conf.d/internal-api.conf and add the mTLS configuration block:

server {
    listen 443 ssl http2;
    server_name api-internal.local;

    # Nginx Server's own certificates
    ssl_certificate /etc/nginx/certs/server.crt;
    ssl_certificate_key /etc/nginx/certs/server.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # Enable mutual TLS (mTLS) verification
    ssl_client_certificate /etc/nginx/certs/ca.crt;
    ssl_verify_client on; # Require clients to present a valid certificate
    ssl_verify_depth 2;   # Maximum allowed CA certificate verification depth

    location / {
        # Forward client certificate details upstream to backend via headers
        proxy_set_header X-Client-DN $ssl_client_s_dn;
        proxy_set_header X-Client-Verify $ssl_client_verify;
        
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Validate the syntax and reload Nginx configuration:

nginx -t && systemctl reload nginx

Step 5: Practical Testing with cURL

First, simulate an attacker issuing API calls with a leaked token but without providing a client certificate:

curl -k -I https://api-internal.local/api/v1/internal/sync-data

Nginx rejects the connection outright:

HTTP/1.1 400 Bad Request
Server: nginx
<html>
<head><title>400 No required SSL certificate was sent</title></head>
...

The request never reaches the backend application. Compromised tokens or malicious scripts are rendered entirely powerless.

Now, submit a legitimate request providing the client certificate and private key:

curl --cacert /etc/nginx/certs/ca.crt \
     --cert /etc/nginx/certs/client.crt \
     --key /etc/nginx/certs/client.key \
     https://api-internal.local/api/v1/internal/sync-data

The connection succeeds! Nginx verifies the client certificate signature and securely proxies the request downstream to your service.

Conclusion

mTLS transforms service-to-service communication into a true Zero Trust stronghold. Even if secret tokens or internal API URLs leak into public logs, attackers lacking the corresponding private key and client certificate remain completely locked out at the Nginx gateway.

Share: