Getting Started with Cloudflare mTLS: A Comprehensive Guide
Mutual TLS (mTLS) adds a crucial layer of security to your applications by verifying the identity of both the client and the server. Unlike traditional TLS, which only verifies the server’s certificate, mTLS requires the client to also present a valid certificate. This makes it significantly harder for unauthorized clients to access your resources, providing robust protection against various attacks, including man-in-the-middle, credential stuffing, and API abuse.
Cloudflare simplifies the implementation of mTLS, allowing you to easily enforce client certificate verification for your applications. This article provides a step-by-step guide to getting started with Cloudflare’s mTLS service.
1. Prerequisites:
- A Cloudflare account (Free, Pro, Business, or Enterprise)
- A domain added to Cloudflare and proxied (orange-clouded in the DNS settings)
- A trusted Certificate Authority (CA). You can use:
- A publicly trusted CA (like Let’s Encrypt, though it’s less common for mTLS clients).
- A private CA (like OpenSSL, HashiCorp Vault, or a dedicated corporate CA). This is the recommended and more common approach for internal services and IoT devices.
- Cloudflare’s built-in mTLS CA (available with specific plans, discussed later). This is a very convenient option.
- Client certificates issued by your chosen CA. These certificates should identify your clients and be signed by the CA’s private key.
- OpenSSL (or equivalent) installed on your system for certificate generation and management (if not using Cloudflare’s CA).
2. Creating a Client Certificate (if not using Cloudflare’s CA):
This section outlines creating a self-signed CA and client certificate for testing purposes. For production environments, use a trusted CA.
a. Generate a CA Private Key and Certificate (Self-Signed):
“`bash
Generate a private key for the CA
openssl genrsa -out ca.key 2048
Generate a self-signed CA certificate
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -subj “/C=US/ST=California/L=San Francisco/O=My Org/OU=Engineering/CN=My mTLS CA”
``
ca.key
*: The CA's private key. **Keep this extremely secure.**
ca.crt
*: The CA's public certificate. This is what you'll upload to Cloudflare.
-subj
*: Sets the subject (identifying information) of the CA. Adjust these fields as needed.
/CN=My mTLS CA` is the most crucial part, as it’s the Common Name.
b. Generate a Client Private Key and Certificate Signing Request (CSR):
“`bash
Generate a private key for the client
openssl genrsa -out client.key 2048
Generate a CSR
openssl req -new -key client.key -out client.csr -subj “/C=US/ST=California/L=San Francisco/O=My Org/OU=Engineering/CN=client1.example.com”
``
client.key
*: The client's private key. This is used by the client application to authenticate itself.
client.csr
*: The Certificate Signing Request. This contains the client's public key and identifying information, which the CA will sign.
-subj
*: Sets the subject of the client certificate.
/CN=client1.example.com` is crucial; it should uniquely identify the client.
c. Sign the Client CSR with the CA:
bash
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
* client.crt
: The signed client certificate. This is what the client will present to Cloudflare.
* -CAcreateserial
: Creates a serial number file for the CA to track issued certificates.
d. (Optional) Convert to PKCS#12 format (PFX):
Some applications require the client certificate and key to be bundled together in a PKCS#12 (PFX) file.
bash
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.crt -certfile ca.crt
* client.pfx
: The PKCS#12 file containing the client certificate, private key, and optionally the CA certificate. You’ll be prompted for a password to protect this file.
3. Uploading the CA Certificate to Cloudflare:
- Log in to your Cloudflare dashboard.
- Select the domain you want to configure mTLS for.
- Navigate to SSL/TLS -> Client Certificates.
- Click Add a client certificate configuration.
- Certificate Pack or CA: Choose CA Certificate.
- Certificate Authority (CA) Certificate: Paste the contents of your
ca.crt
file (or the certificate of your trusted CA) into the text box. - Associated Hostnames (Optional): Here, you can specify which hostnames this CA certificate applies to. If left blank, it applies to all hostnames within the zone. This is useful for using different CAs for different parts of your site.
- JWT Validation (Optional): If your client certificates contain JSON Web Tokens (JWTs), you can configure validation rules here. This is an advanced feature that allows you to enforce claims within the JWT. We’ll skip this for basic setup.
- Click Add certificate.
4. Configuring mTLS Rules (Access or Firewall Rules):
You have two primary ways to enforce mTLS: using Cloudflare Access or Firewall Rules.
a. Cloudflare Access (Recommended for Applications):
Cloudflare Access is a zero-trust network access solution that’s ideal for securing internal applications.
- Navigate to Access -> Applications.
- Click Add an application.
- Choose the appropriate application type (Self-hosted, SaaS, etc.).
- Configure your application details (hostname, path, etc.).
- Under Policies, click Add a policy.
- Action: Choose
Allow
. - Include: Add a rule:
- Selector:
Valid Certificate
. - Value: Leave blank. This requires a valid client certificate signed by any of the CAs you’ve uploaded.
- (Optional, more specific): You can use the
Certificate SAN
orCertificate Serial
selectors to require a certificate with a specific SAN or serial number. This provides much finer-grained control.
- Selector:
- (Optional) Add additional rules to further restrict access (e.g., by IP address, country, etc.).
- Click Add policy.
- Save the application configuration.
b. Cloudflare Firewall Rules (More Flexible, but Requires More Configuration):
Firewall Rules provide more granular control but require you to define the matching criteria yourself.
- Navigate to Security -> WAF -> Firewall Rules.
- Click Create a firewall rule.
- Rule name: Give your rule a descriptive name (e.g., “Require mTLS”).
- When incoming requests match… Build your rule expression. The key field is
ssl.client_certificate_verified
.- Field:
ssl.client_certificate_verified
- Operator:
equals
- Value:
true
(This requires a valid client certificate.) - You can add additional conditions (e.g., based on the URL path, HTTP method, etc.) to apply mTLS only to specific requests. Example:
(ssl.client_certificate_verified eq true) and (http.request.uri.path contains "/api")
This requires a valid client certificate only for requests to paths containing “/api”.
- Field:
- Then… Choose the action.
- Action:
Block
(This is the typical action for failed mTLS). You can also choose other actions likeChallenge
(e.g., to present a CAPTCHA) orLog
.
- Action:
- Click Deploy.
5. Testing your mTLS Configuration:
- Without a client certificate: Try accessing your protected resource (e.g., a webpage or API endpoint) from a browser or using a tool like
curl
without providing a client certificate. You should receive an error (typically a 403 Forbidden or a Cloudflare-specific error). -
With a valid client certificate: Use
curl
(or a similar tool) to test with the client certificate:bash
curl --cert client.crt --key client.key https://yourdomain.com/protected-resource
*--cert client.crt
: Specifies the path to your client certificate file.
*--key client.key
: Specifies the path to your client private key file.
* Replacehttps://yourdomain.com/protected-resource
with the actual URL you’re testing.If everything is configured correctly, the request should succeed.
-
Using a browser (with PFX): If you created a
client.pfx
file, you can import it into your browser’s certificate store. The exact process varies depending on your browser (search for “import pfx certificate [your browser name]”). After importing, try accessing the protected resource.
6. Cloudflare’s Built-in mTLS CA (Simplified Approach):
Cloudflare offers a built-in mTLS CA, which simplifies certificate management. This is available on certain paid plans (check Cloudflare’s pricing page for details).
- Go to SSL/TLS > Client Certificates.
- Enable the Cloudflare mTLS CA feature. This usually involves a one-time setup process.
- You can then generate client certificates directly from the Cloudflare dashboard. These certificates will be automatically trusted by your mTLS rules.
- Download the generated client certificate and key. The downloaded
.pem
file will contain both. You’ll need to separate them intoclient.crt
andclient.key
if your application needs separate files. You can split using a text editor, looking for the-----BEGIN CERTIFICATE-----
and-----BEGIN PRIVATE KEY-----
markers. - The steps for configuring mTLS rules (using Access or Firewall Rules) remain the same as described above.
Important Considerations:
- Certificate Revocation: Implement a certificate revocation mechanism (e.g., using OCSP or CRLs) to handle compromised or expired client certificates. Cloudflare supports both. See Cloudflare’s documentation on “Configure a revocation check” for details.
- Certificate Rotation: Regularly rotate your client certificates and CA certificates (especially the CA root) for improved security.
- Security Best Practices: Store your CA private key securely, preferably in a hardware security module (HSM) or a highly secure key management system.
- Error Handling: Your application should handle mTLS errors gracefully, providing informative messages to users if their client certificate is invalid or missing.
- Choosing Access vs. Firewall Rules: Cloudflare Access is generally preferred for securing applications due to its ease of use and zero-trust features. Firewall Rules offer more flexibility for complex scenarios but require more manual configuration.
- Performance: While mTLS adds a small overhead, Cloudflare’s optimized infrastructure minimizes the impact on performance.
By following these steps, you can successfully implement mTLS with Cloudflare to enhance the security of your applications and protect against unauthorized access. Remember to thoroughly test your configuration and follow security best practices to maintain a robust security posture.