Skip to content

sergioaz/FastAPI-mTLS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI with Mutual TLS (mTLS) Implementation

A complete implementation of Mutual TLS (mTLS) authentication in FastAPI, providing bidirectional certificate-based authentication between client and server.

πŸ” What is Mutual TLS?

Mutual TLS (mTLS) extends the standard TLS protocol by requiring both the client and server to authenticate each other using X.509 certificates. Unlike standard TLS where only the server presents a certificate, mTLS ensures both parties verify each other's identity.

Benefits of mTLS

  • Enhanced Security: Bidirectional authentication prevents unauthorized access
  • Zero Trust Architecture: Implements "never trust, always verify" principles
  • API Security: Ensures only authorized clients can access your APIs
  • Compliance: Meets regulatory requirements for secure communications

πŸ“‹ Project Structure

fastapi-mtls/
β”œβ”€β”€ generate_certs.sh     # Certificate generation script
β”œβ”€β”€ main.py              # FastAPI application with mTLS
β”œβ”€β”€ server.py            # Alternative server configuration
β”œβ”€β”€ client.py            # Client examples for testing
β”œβ”€β”€ requirements.txt     # Python dependencies
β”œβ”€β”€ Dockerfile          # Docker container configuration
β”œβ”€β”€ docker-compose.yml  # Docker Compose setup
β”œβ”€β”€ docker-entrypoint.sh # Container entrypoint script
└── certs/              # Certificate directory (generated)
    β”œβ”€β”€ ca/             # Certificate Authority
    β”œβ”€β”€ server/         # Server certificates
    └── client/         # Client certificates

πŸš€ Quick Start

1. Generate Certificates

First, generate the required certificates for mTLS:

# Make the script executable
chmod +x generate_certs.sh

# Generate all certificates
./generate_certs.sh

This creates:

  • CA Certificate: Root certificate authority
  • Server Certificate: For the FastAPI server
  • Client Certificate: For client authentication

2. Install Dependencies

pip install -r requirements.txt

3. Run the Server

Option A: Direct Python execution

python main.py

Option B: Using the server script (recommended)

python server.py

Option C: Using Docker

# Build and run with Docker Compose
docker-compose up --build

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

4. Test the Connection

Option A: Using the Python client

python client.py

Option B: Using curl

# Test the health endpoint
curl -k --cert ./certs/client/client-cert.pem --key ./certs/client/client-key.pem https://localhost:8443/health

# Test the secure endpoint
curl -k --cert ./certs/client/client-cert.pem --key ./certs/client/client-key.pem https://localhost:8443/secure

πŸ“Š API Endpoints

Endpoint Description Authentication Required
/ Root endpoint with basic info No
/health Health check endpoint No*
/secure Secure endpoint requiring mTLS Yes
/cert-info Display client certificate info Yes

*Note: In production, even health checks should require authentication.

πŸ”§ Configuration

Environment Variables

Variable Description Default
SSL_CERT_DIR Directory containing certificates ./certs
SERVER_HOST Server bind address 0.0.0.0
SERVER_PORT Server port 8443
LOG_LEVEL Logging level INFO

SSL/TLS Settings

The implementation uses these security settings:

  • Minimum TLS Version: 1.2
  • Client Certificates: Required (CERT_REQUIRED)
  • Certificate Verification: Full chain validation
  • Cipher Suites: High-security ciphers only

πŸ›‘οΈ Security Best Practices

Certificate Management

  1. Use Strong Key Sizes: Minimum 2048-bit RSA or 256-bit ECDSA
  2. Regular Rotation: Rotate certificates before expiration
  3. Secure Storage: Store private keys with restricted permissions (600)
  4. Certificate Revocation: Implement CRL or OCSP checking
  5. CA Security: Keep CA private key offline and secure

Production Deployment

  1. Reverse Proxy: Use nginx/HAProxy for SSL termination
  2. Certificate Validation: Validate certificate chains and expiration
  3. Monitoring: Monitor certificate expiry and SSL handshake failures
  4. Network Security: Use VPCs and security groups
  5. Secrets Management: Use HashiCorp Vault or AWS Secrets Manager

Code Security

# βœ… Good: Validate certificates at multiple layers
def validate_certificate(cert_data: bytes) -> bool:
    # Check certificate chain
    # Check expiration
    # Check revocation status
    # Check certificate policies
    pass

# ❌ Bad: Skip certificate validation
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

🐳 Docker Deployment

Building the Image

docker build -t fastapi-mtls .

Running with Docker Compose

# Start the service
docker-compose up -d

# View logs
docker-compose logs -f fastapi-mtls

# Health check
docker-compose exec fastapi-mtls python -c "
import requests
response = requests.get('https://localhost:8443/health', 
                       cert=('./certs/client/client-cert.pem', './certs/client/client-key.pem'),
                       verify='./certs/ca/ca-cert.pem')
print(f'Status: {response.status_code}')
print(f'Response: {response.json()}')
"

Production Docker Setup

# Use specific tag for production
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# With nginx reverse proxy
docker-compose --profile with-nginx up -d

πŸ” Troubleshooting

Common Issues

1. Certificate Not Found

Error: Certificate file not found Solution:

# Ensure certificates are generated
./generate_certs.sh

# Check file permissions
ls -la certs/*/

2. SSL Handshake Failure

Error: SSL: CERTIFICATE_VERIFY_FAILED Possible Causes:

  • Certificate expired
  • Certificate not signed by trusted CA
  • Hostname mismatch
  • Client certificate not provided

Debug Steps:

# Check certificate validity
openssl x509 -in certs/server/server-cert.pem -text -noout

# Test SSL connection
openssl s_client -connect localhost:8443 -cert certs/client/client-cert.pem -key certs/client/client-key.pem -CAfile certs/ca/ca-cert.pem

3. Permission Denied

Error: Permission denied: 'certs/server/server-key.pem' Solution:

# Fix certificate permissions
chmod 600 certs/*/\*-key.pem
chmod 644 certs/*/\*-cert.pem

4. Docker Container Issues

Error: Container fails to start Debug Steps:

# Check container logs
docker-compose logs fastapi-mtls

# Run container interactively
docker-compose run --rm fastapi-mtls bash

# Verify certificate mounting
docker-compose exec fastapi-mtls ls -la /app/certs/

Debug Mode

Enable debug logging:

# In main.py or server.py
logging.basicConfig(level=logging.DEBUG)

SSL Debug

# Enable SSL debug in OpenSSL
export SSLKEYLOGFILE=ssl-keys.log
export OPENSSL_CONF=/dev/null

# Run with verbose SSL logging
python -c "
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# Your mTLS code here
"

πŸ“ˆ Performance Considerations

Connection Pooling

# Use connection pooling for better performance
import urllib3

http = urllib3.PoolManager(
    cert_file='./certs/client/client-cert.pem',
    key_file='./certs/client/client-key.pem',
    ca_certs='./certs/ca/ca-cert.pem'
)

Certificate Caching

# Cache certificate validation results
from functools import lru_cache

@lru_cache(maxsize=1000)
def validate_certificate_cached(cert_fingerprint: str) -> bool:
    # Validation logic here
    pass

Load Testing

# Install Apache Bench with SSL support
apt-get install apache2-utils

# Load test mTLS endpoint
ab -n 1000 -c 10 -f TLS1.2 \
   -Z ./certs/client/client-cert.pem \
   -Z ./certs/client/client-key.pem \
   https://localhost:8443/health

πŸ“š Additional Resources

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

⚠️ Security Notice: This implementation is for educational and development purposes. For production use, conduct a thorough security review and implement additional security measures as required by your environment.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published