Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Python mTLS Server Example

A simple HTTPS server with mutual TLS authentication using Python's built-in modules.

Features

  • ✅ Mutual TLS authentication
  • ✅ Client certificate verification
  • ✅ RESTful API endpoints
  • ✅ No external dependencies (uses stdlib only)
  • ✅ Graceful shutdown

Prerequisites

  • Python 3.7+ (built-in ssl and http.server modules)
  • Certificates generated by the mtls CLI tool

Setup

# No dependencies needed for basic functionality
# Optional: Install development tools
pip install -r requirements.txt

Running the Server

# Make executable (optional)
chmod +x server.py

# Run directly
python3 server.py

# Or
./server.py

The server will start on https://localhost:8443.

Endpoints

  • GET / - Main endpoint with client certificate info
  • GET /health - Health check endpoint
  • GET /api/data - Sample data endpoint
  • POST /api/echo - Echo back the request body

Testing

You can test the server using:

  1. The Python client in ../python-client
  2. curl with certificates:
curl --cert ../../certs/servers/localhost/server-cert.pem \
     --key ../../certs/servers/localhost/server-key.pem \
     --cacert ../../certs/ca/ca-cert.pem \
     https://localhost:8443/

Certificate Loading

The server creates an SSL context with mTLS:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2

# Load server certificate
context.load_cert_chain(
    certfile='server-cert.pem',
    keyfile='server-key.pem'
)

# Load CA for client verification
context.load_verify_locations(cafile='ca-cert.pem')

# Require client certificate
context.verify_mode = ssl.CERT_REQUIRED

Client Certificate Info

The server extracts client certificate information:

cert = connection.getpeercert()
subject = dict(x[0] for x in cert.get('subject', []))
cn = subject.get('commonName')

Error Handling

The server will reject connections from:

  • Clients without a certificate
  • Clients with invalid certificates
  • Clients with certificates not signed by the trusted CA

Graceful Shutdown

Press Ctrl+C to gracefully shutdown the server.

Port Configuration

To change the port, modify the port variable in server.py:

port = 8443  # Change to your desired port

Troubleshooting

SSL certificate error:

  • Ensure certificate paths are correct
  • Check certificate permissions
  • Verify certificates are not expired

Permission denied on port 443:

  • Use port 8443 or higher
  • Or run with sudo (not recommended)

Client verification fails:

  • Check CA certificate is loaded correctly
  • Ensure client certificate is signed by the same CA