Introduction#
This guide provides non-exhaustive recommendations and general best practices to achieve a comprehensive Layer 7 (L7) / Application Security approach with Cloudflare.
This may be relevant for those seeking similar frameworks, such as CIS Benchmarks.
Some features mentioned are available only through advanced Cloudflare bundles, such as WAF Advanced, Advanced Rate Limiting, or Enterprise features like Enterprise Bot Management.
This guide assumes that your domain is already onboarded to Cloudflare as a Zone and configured using Full Setup, meaning Cloudflare is acting as your authoritative DNS provider. Additionally, it’s recommended to have DNSSEC enabled.
Troubleshooting#
- Review the Cloudflare Status page.
- Consult the Troubleshooting section.
- Gather necessary information and contact Cloudflare Support.
- Use Trace to understand the impact of your Cloudflare configurations on specific requests.
Recommendations#
In general, in most cases you can create rules with the action set to “Log” for testing purposes. This allows you to review what it matches in the Security Events and fine-tune it as needed before applying a more impactful action, such as “Block”, “Managed Challenge”, or even “SKIP”.
For more information, review the older article Protecting OSI layers.
WAF Managed Rules#
Deploy WAF Managed Ruleset#
It’s widely recommended to briefly review and then deploy the Managed Ruleset across the entire Zone. Create specific exceptions, if required.
Note that it is not recommended to have both Account-level WAF Managed Rules, as well as Zone-level WAF Managed Rules deployed and enabled at the same time as this could lead to confusion when reviewing the Security Events. Preferably and if possible, only enable the Account-level WAF Managed Rules.
Reference: Cloudflare Managed Ruleset.
Stricter Security Requirements with WAF Managed Ruleset#
For additional and stricter security requirements, deploy some of the following rules:
- XSS, HTML Injection with Rule ID 882b37d6bd5f4bf2a3cdb374d503ded0.
- Anomaly:URL:Path - Multiple Slashes, Relative Paths, CR, LF or NULL with Rule ID 6e759e70dc814d90a003f10424644cfb.
- Anomaly:Body - Large with Rule ID 7b822fd1f5814e17888ded658480ea8f, in order to mitigate body payloads which are higher than the processing limit.
- It is generally recommended to add WAF exceptions for this, especially for upload endpoints.
- Anomaly:Port - Non Standard Port (not 80 or 443) with Rule ID 8e361ee4328f4a3caf6caf3e664ed6fe.
- Anomaly:Method - Unusual HTTP Method with Rule ID ab53f93c9b03472ab34a5405d9bdc7d5.
- Anomaly:Method - Unknown HTTP Method with Rule ID 6e2240ffcb87477bbd4881b6fd13142f.
- Including all the Vulnerability scanner activity-related Rules.
- Any other relevant Rules you might need.
Log the payload of matched rules, if required, to help diagnosing the behavior of the rules. The encrypted payloads can be found in the Metadata field in Firewall events logs.
It is also generally recommended to disable Browser Integrity Check (BIC), especially to prevent potential false positives with API / automated traffic.
Reference: Security Events and Changelog.
Deploy OWASP Core Ruleset#
If required, review and then deploy the OWASP Core Ruleset.
Note: Those types of rules are prone for false positives.
For customers also using Zaraz, it is recommended configuring an exception for the configured Zaraz endpoint.
Reference: Handle false positives.
WAF Custom Rules#
Allow Verified Bots#
It’s ordinarily recommended to have as one of the first top Custom Rules a SKIP Custom Rule, allowing Verified Bots, such as i.e. Search Engine Crawler (like GoogleBot).
Reference: Verified Bots
Allow APIs#
It’s generally recommended to have as one of the first top Custom Rules a SKIP Custom Rule, allowing your and/or partner APIs (i.e. payment callbacks, PreRender IO, etc.), being as specific and using as many fields as possible. The ultimate goal is to pursue a positive security model by implementing API Shield.
Reference: API Shield.
Redirect to Custom HTML#
Using a Custom HTML response type, one can create a redirect to another site for specific requests. In this example, any non-verified bot requests coming from the US are redirected.
Block Fallthrough API Requests#
In order to truly enforce a Positive Security Model, for any fallthrough action of requests not matching any of the API Shield-managed endpoints, create a WAF Custom Rule similar to the one below, preferably with more specific fields to your API.
Reference: Schema Validation.
Visibility into Non-expected Request Methods#
In some cases, you want to be specific about what type of HTTP Request Methods are allowed on certain endpoints or coming from specific requests, or even just logging relevant methods for visibility.
Reference: HTTP Method Field.
Mitigate likely Malicious Payloads#
Every HTTP request with a payload receives a WAF Attack Score, indicating the likelihood of containing something malicious related to SQLi, XSS, or RCE attacks.
Reference: WAF attack score.
Mitigate known Open Proxies, Anonymizers, VPNs, Malware, and Botnets#
By using the Cloudflare-Managed IP Lists, including your own Custom Lists, you can decide what to do with those IP categories. Generally, one wants to block Botnets and Malware.
Reference: Managed IP Lists.
If you wish to manually block VPNs, here’s a list of ASNs commonly associated with popular VPN providers: AS62041, AS202420, AS20473, AS23966, AS36352, AS14061, AS209854, AS20001, AS20115, AS32934, AS16276
.
Mitigate Tor Traffic#
In case that Tor traffic – an overlay network for enabling anonymous communication – is unwanted, one can simply mitigate it. Make sure to also disable Onion Routing in this case.
Reference: Onion Routing and Tor support.
Mitigate unwanted ASNs#
Any unwanted traffic coming from Cloud ASNs (such as AWS, Azure, GCP, etc.) or other ASNs from which you don’t expect traffic, you might want to mitigate. Use Lists with ASNs to easily manage these.
Reference: Custom Lists.
Block High Risk Countries#
Block high risk countries like the ones that appear in The Office of Foreign Assets Control (OFAC) List.
References: Sanctions List Search and OpenSanctions.
Block known Bot User-Agents#
Block unwanted requests of user-agents known to be used by bots, such as cURL, go-http-client, or even empty user-agents.
Reference: Challenge bad bots.
Restrict WP Admin Dashboard Access#
If you are using WordPress, restrict access to the /wp-admin
to only specific static source IPs of employees or admins, or alternatively opt for a Zero Trust approach with Cloudflare Access.
Reference: Allow traffic from IP addresses in allowlist only.
Restrict Access to Employees Only#
If you have employee portals or extranets, restrict access to countries in which you have employees located, or preferably opt for a Zero Trust approach. Try to be as specific as possible.
Another alternative is to take advantage of mTLS, only allowing access to employees with valid client certificates.
Reference: Allow traffic from specific countries only.
Mutual TLS Authentication#
Block all requests that do not have a valid client certificate for Mutual TLS (mTLS) authentication on a specific hostname.
Additionally, another consideration is to also check if the Client Certificates, generated with the default Cloudflare Managed CA, have been revoked and block those.
References: Cloudflare Public Key Infrastructure (PKI), CFSSL, API Shield mTLS and Workers mTLS. Check out this Learning Path on mTLS at Cloudflare.
Another interesting use case is to associate specific mTLS hostnames with Client Certificate Serial Numbers (cf.tls_client_auth.cert_serial
). This allows for more granular control.
User-Specific JWT Claim Mitigation#
To enhance the security of your API endpoints that rely on JSON Web Tokens (JWT), you can create rules targeting specific JWT claims, such as the user claim.
In this example, requests from admin
users based on the user
claim are subjected to additional scrutiny by challenging requests flagged as potentially malicious based on their WAF Attack Score.
Reference: Issue challenge for admin user in JWT claim based on attack score and API Shield.
Visibility into Automated Bot Traffic#
In general, one wants to have visibility into automated traffic. This can be commonly achieved with a LOG action, logging anything with a Bot Score likely automated.
Reference: Bot Management variables.
Mitigating Pretend-Browsers with JavaScript Detections#
In scenarios where the BotScore alone may not reliably differentiate between likely human and bots, you can enhance detection by optionally enabling JavaScript Detections (JSD).
Note: JSD can only be applied to HTML responses and it cannot be at the root/first HTML request.
When enforced via cf.bot_management.js_detection.passed
rules and a Managed Challenge, JSD ensures active verification checks.
Note: Test with a logging action before enforcing rules to avoid impacting legitimate traffic. Additionally, the Rule should only apply on critical paths and not on initial landing pages, where JS might have not been injected yet.
Reference: Enforcing execution of JavaScript detections.
Visibility into IPv6 IPs#
Most web applications want to be available via IPv6 IP addresses. However, in case that IPv6 is undesired, customers can mitigate IPv6 IPs through the WAF and also disable IPv6 compatibility, if needed.
Reference: IPv6 compatibility.
Account Takeover (ATO) Detections#
To detect and mitigate predictable bot behavior, such as login failures, one can use Detection IDs. This is also available for Rate Limiting Rules.
Reference: Account takeover detections and Turnstile.
Mitigate Disposable Emails on SignUps#
To prevent users from signing up with known disposable emails, Cloudflare’s Disposable Email Check can easily check this behavior and the customer can decide what to do with this: block, challenge, log, rate limit, or even add a request header for the origin server.
Reference: Cloudflare Fraud Detection.
Mitigate Authentication Requests#
Prevent or trigger a different behavior when a user tries to log in (authentication event) with leaked credentials, as per Have I been Pwned (HIBP). Or use different related fields.
Note: Authentication events (
cf.waf.auth_detected
) refers to authentication credentials detected in a request with a status code 2XX.
Reference: Leaked credentials detection.
Time-based Rules#
Time-based rules can leverage the http.request.timestamp.sec field to apply logic based on specific time periods.
For example, you could block all POST or PUT requests to a particular endpoint during a defined time frame.
Or simply Log or Skip (allow) specific requests for a specific time.
Note: The timestamp is represented in UNIX time and consists of a 10-digit value.
Reference: Configure a rule with the Skip action.
Mitigate Unauthorized Cloudflare Workers#
The CF-Worker
request header identifies the originating host of a subrequest made by a Cloudflare Workers Subrequest, such as when using the Fetch API.
Do not use CF-Worker
in WAF Custom Rules, as it is added after rule evaluation. Instead, use cf.worker.upstream_zone
, which holds the same value.
Block a specific Worker:
cf.worker.upstream_zone eq "example.com"
Block all Worker subrequests except from your own Worker:
not (cf.worker.upstream_zone in {"" "your-zone.com"})
Reference: CF-Connecting-IP in Worker subrequests.
More Common Use Cases for Custom Rules#
Review the get started guide and the common use cases for custom rules for more examples. Additionally, for some use cases or if you are managing many Zones, the Account-level WAF can be a good feature to have.
Moreover, monitor and replace insecure JS libraries used in your applications.
Review all the fields reference.
Rate Limiting Rules#
IP-based Rate Limiting for Logins#
To protect login endpoints from multiple login attempts from the same IP address, rate limit based on the required characteristics.
Reference: Rate limiting parameters.
Rate Limiting Uploads#
To prevent too many uploads / HTTP requests using POST / PUT / PATCH methods.
Reference: Standard fields.
Rate Limit Credential Stuffing#
To protect against credential stuffing attacks, it’s generally recommended using a layered-security approach. This rate limiting rule is but one example of several approaches.
Reference: Protecting against credential stuffing and Find an appropriate rate limit.
Rate Limit Suspicious Logins#
Implement rate limiting for suspicious login attempts (authentication events) using leaked credentials, specifically leaked passwords, as per Have I been Pwned (HIBP).
Reference: Leaked credentials detection.
Geography-based Rate Limiting#
If there are markets from which one does not expect a lot of traffic coming from in general, one could rate limit requests coming from those countries based on IPs or other characteristics.
Reference: Enforcing granular access control.
IPv6-based Rate Limiting#
To protect against entire IPv6 Prefixes, rate limit with the custom characteristics using the cidr6 function and specifying the prefix length.
Reference: Rules language.
Client Certificate-based Rate Limiting#
Rate limit based on the same Client Certificate being used multiple times over a specific period of time, in order to prevent abuse of potentially compromised certificates or devices. This is part of mTLS protection.
Reference: SHA-256 fingerprint of the certificate.
JavaScript Detection-based Rate Limiting#
Use JavaScript Detections (JSD) to identify human-like clients by solving a challenge in subsequent HTML requests, flagged as cf.bot_management.js_detection.passed
. Since JSD cannot run on the first HTML request, track failed JSD attempts on subsequent HTML responses (Content-Type: text/html
) and block or challenge clients after 5 consecutive failures.
Reference: Do the Challenge actions support content types other than HTML (for example, AJAX or XHR requests)?.
Cookie-based Rate Limiting#
In order to limit the amount of times a cookie can be used, one can rate limit by its characteristics. For example, rate limit session cookies or limit the amount of times a single cf_clearance cookie can be used.
Reference: Cloudflare Cookies.
More Common Use Cases for Rate Limiting Rules#
Review the rate limiting best practices for more examples.
Review all the fields reference.
Turnstile#
Cloudflare’s Turnstile allows challenges anywhere on your site. It runs in standard browsers, including mobile – even native mobile apps – when using WebView. Implicit rendering auto-loads on static pages, while explicit rendering offers control over when and where it appears, ideal for dynamic content or Single-Page Applications (SPAs). Learn more about the differences here.
Enterprise customers can also take advantage of Ephemeral IDs, which can help track bots over longer time periods and rate limit based on these IDs instead of IPs or other characteristics.
Note: While Turnstile can be run in invisible mode, it is recommended to use managed mode for login and signup forms to provide users with a clear indication that an action is taking place. Additionally, the Turnstile Siteverify API should be triggered when the user clicks the button, initiating the POST request.
When integrating on mobile, address common issues to ensure smooth functionality.
It is also suggested to integrate Turnstile with WAF and Bot Management.
Page Shield#
Monitor your application’s JavaScript dependencies and get notified of any changes with Cloudflare Page Shield.
In general, you would want to periodically monitor resources and cookies running on your application. This is relevant for PCI DSS compliance.
Create Policies to enforce a positive security model, allowing only specific resources.
SSL/TLS Certificates#
It is typically recommended to use the Advanced Certificate Manager (ACM).
Soon you’ll be benefiting from the Automatic SSL/TLS.
For customers with stricter requirements, additionally, disable the Universal SSL certificate.
Those seeking PCI compliance and granular customization over cipher suites should review the developer documentations, as well as the features TLS 1.3, Minimum TLS Version (TLS 1.2 is the recommended option here), Automatic HTTPS Rewrites, Always Use HTTPS (or preferably disable HTTP plaintext altogether).
Note: Review the Post-Quantum Cryptography (PQC) documentation.
Additionally, it is recommended to configure the origin server to match on origin.
Verify that there’s always a valid and active Edge Certificate for your Zones.
Moreover, enabling HTTP/2, HTTP/3 (QUIC), and HTTP/2 to Origin are performance-related features, but also good for improved security.
Branding#
In case that branding is important to you and your business, you are able to configure Custom Pages (Error and Challenge) and (preferably) Custom Errors.
Additionally, for the Cloudflare WAF, you are able to configure a custom response for blocked requests or custom error responses for the Cloudflare Rules.
Analytics & Log Management#
You can review all matched Rules in the Security Events section. A broader overview of all requests can be found in the Security Analytics section.
For an account-level overview, review the Account Analytics.
Note: All Cloudflare Dashboard analytics are sampled.
Note: Exclude the
/cdn-cgi/
endpoint from your Security Rules, specifically relevant for challenges.
It is strongly recommended to use Logpush, pushing your logs to storage services (such as R2, S3, or others), SIEMs, or log management providers.
It is highly recommended to set up Notifications to keep up to date with everything, and periodically review the Cloudflare Status page.
Scans and Penetration Testing Policy#
Cloudflare customers may conduct scans and penetration tests (with certain restrictions) on application and network-layer aspects of their own assets.
You can review all details in the developer documentation.
Automation & User Management#
Automate deployments and configuration changes or even rollbacks with:
- Cloudflare API
- SDKs
- Terraform
- For external scripts / uncovered resources, use external.
- If you’re planning to change from Dashboard UI to Terraform, use cf-terraforming.
- Pulumi
For effective Cloudflare Account User Management, it’s important to follow general best practices that ensure both security and operational efficiency. Start by adhering to the principle of least privilege: assign each user or department only the permissions they need by utilizing the Dashboard’s role management capabilities (Roles). Permissions for Cloudflare API endpoints differ from those in the Dashboard. Ensure API access is configured appropriately to align with your security and access control policies.
For more advanced requirements, consider developing custom integrations using Cloudflare’s SDKs or leveraging Account-Owned Tokens. These options allow you to automate processes and fine-tune access controls based on your organization’s specific needs.
Additionally, integrating Single Sign-On (SSO) simplifies user authentication and reinforces security policies. Complement these measures by enforcing Multi-Factor Authentication (MFA), regularly reviewing user roles, and monitoring Audit Logs to promptly detect and address any suspicious activities.
Origin Server Protection#
Generally, it’s recommended to properly secure and manage your origin servers.
When migrating to Cloudflare, it’s highly recommended to rotate Origin Server IPs and proxy all DNS records.
There’s a variety of different ways and options explained on the Developer Documentation to protect your origin server, as well as prepare for surges or spikes in web traffic for seasonal events, such as during holidays.
Note: Review the Post-Quantum Cryptography (PQC) documentation.
Additionally, review and enable the available Managed Transforms options to add some bot protection headers, remove “X-Powered-By” headers, or even create your own Content Security Policy (CSP) with the Transform Rules.
Reference: Encryption modes.
HTTP/S Use Cases#
Fighting Automated Requests (Bots)#
A general goal is protecting against automated requests and bots – though there are different types of bot attacks and often it’s about fraud detection or solving one of these use cases:
- Credential / Credit Card Stuffing
- Content Scraping
- Inventory Hoarding
- Account Takeover (ATO)
- Fake Account Creation
- Content Spam
The best approach to combating bots depends on the Cloudflare features available and configured, as well as the specific types of bot attacks being observed. DDoS attacks are usually also launched by bots. Every website is unique, and often so are the attack patterns it faces. In general, fighting bots is a cat-and-mouse game, requiring continuous adaptation to evolving threats. Cloudflare continuously enhances its capabilities based on customer feedback and its Threat Intelligence to try to stay ahead.
To effectively mitigate bot traffic, consider the following (non-exhaustive) layered-security approach:
- Allow (skip) Verified Bots or Verified Bot Categories.
- Block or mitigate unwanted bots (i.e. AI bots) by leveraging Bot Management fields in combination with other security controls, solutions (i.e. Snippets) and fields.
- Example honeypot for bots.
- Enable JavaScript Detections (JSD) and enforce them if possible.
- If enforcement isn’t feasible (i.e. for native mobile apps), consider implementing Turnstile (in WebView for mobile) alongside the WAF or Cloudflare’s new mobile SDK (Enterprise feature), which can be combined with API Shield JWT Validation or Snippets.
- Analyze heuristics using Security Analytics and available fields to build WAF Custom Rules.
- Deploy the WAF Managed Rules regularly updated security rules.
- For important endpoints, we also recommend WAF Attack Score enforcement.
- Identify ASN patterns and block unwanted traffic from certain networks or cloud providers (i.e. AWS or GCP).
- Use Managed IP Lists for dynamic mitigations.
- Use (Body) Payload Inspection to perform more detailed mitigations.
- Apply Rate Limiting based on IP or other characteristics to prevent abuse and credential stuffing attacks.
- This is often combined with Leaked Credentials Detection.
- For APIs, implement a positive security model with API Shield, including Schema Validation and Sequence Mitigation.
- Alternatively, one can use Sequence Rules (or also called Cookie-based Sequences) to track and enforce the order of requests a user has made and the time between requests.
- Caching anything possible can also help reduce the load and resources of the origin servers.
- Cloudflare is gradually rolling out Fraud Detection features, such as disposable email checks.
- Additional bot-related configurations can be adjusted by Cloudflare’s Bot Team on a case-by-case basis.
Some interesting methods include:
- Delay action
- Send suspect bots to a honeypot
- price scraping
- Turnstile with Workers
- Data loss prevention
- Forward specific HTTP Request Headers with Managed Transforms Rules for the origin to act on.
Non-HTTP/S Use Cases#
There are scenarios where users might want to leverage Cloudflare’s global network and robust L3/L4 DDoS protection without handling TLS termination or processing HTTP/S traffic and payloads. For these specialized use cases, Cloudflare offers several options tailored to non-HTTP/S requirements.
Available Options:
Grey-Clouded DNS Records
This involves setting a DNS record to “DNS Only” mode. However, this approach is not recommended, as it exposes the origin server’s IP address, compromising security.Spectrum
A powerful TCP/UDP proxy solution that supports various non-HTTP/S protocols.- It is typically recommended to enable Proxy Protocol.
- To avoid unintended handling of TLS, ensure the Edge TLS Termination option is disabled.
Privacy Gateway
Privacy Gateway uses the Oblivious HTTP (OHTTP) standard to hide client IPs during backend interactions. Acting as a trusted relay, it forwards encrypted messages between clients and servers without accessing their content, ensuring enhanced privacy and anonymity.Magic Transit
Operating at the network layer, Magic Transit offers advanced DDoS protection and traffic management without TLS termination.- For a deeper dive, check out the Magic Transit Reference Architecture.
Additional Resources#
For more guidance on avoiding Cloudflare TLS termination and decryption, visit the Cloudflare Data Localization FAQ.
Disclaimer#
Educational purposes only.
This blog post is independently created and is not affiliated with, endorsed by, or necessarily representative of the views or opinions of any organizations or services mentioned herein.
The images used in this article primarily consist of screenshots from the Cloudflare Dashboard or other publicly available materials, such as Cloudflare webinar slides.
The guidelines provided in this post are intended for general educational purposes. They should be customized to fit your specific use cases and traffic patterns. You are responsible for configuring settings according to your unique requirements, and it is important to understand their potential impact. Familiarity with Cloudflare concepts such as WAF Phases, Proxy Status, and other relevant features is recommended.
The author of this post is not responsible for any misconfigurations, errors, or unintended consequences that may arise from implementing the guidelines or recommendations discussed herein. You assume full responsibility for any actions taken based on this content and for ensuring that configurations are appropriate for your specific environment.
For additional learning resources, explore the following:
- Learning Paths
- Enterprise Customer Portal (for Enterprise customers)
- Security Center
For tailored support, and in general, if you have any questions or need assistance, please contact Cloudflare support, or (also for non-customers) call the Under Attack (UA) Hotline in emergency situations.