Cloud Armor: WAF Rules, DDoS Protection, and Rate Limiting
A production-focused guide to Cloud Armor: WAF Rules, DDoS Protection, and Rate Limiting on Google Cloud Platform..
20+ years shipping production infrastructure and CI/CD at scale. Drawn from code that ran under real load.
- ✓Google Cloud account with billing enabled, gcloud CLI installed and configured (version 400.0.0+), basic understanding of HTTP/HTTPS protocols, familiarity with Google Cloud Load Balancers and Cloud CDN, Terraform (optional, for infrastructure as code), jq (for JSON parsing in scripts)
Cloud Armor is Google Cloud's edge WAF and DDoS protection service. Use preconfigured OWASP rules for instant SQLi/XSS protection, custom CEL expressions for fine-grained IP/geo/header filtering, and rate limiting with multiple enforcement keys (IP + User-Agent + cookie) to defeat botnets. Always test new rules in preview mode before enforcing.
Cloud Armor is like a bouncer at a club who checks every person at the door. Some people are on the banned list (known attackers), some look suspicious (SQL injection attempts), and some try to push in too fast (DDoS). The bouncer can block, slow down, or kick them out—all before they reach the dance floor (your servers).
In 2023, a major e-commerce platform lost $2M in 30 minutes because their rate limiting was based on IP alone — attackers rotated through a botnet of 10,000 residential proxies. Cloud Armor could have stopped that with adaptive rate limiting and fingerprinting. Most teams treat WAF as a checkbox: enable OWASP rules, set a few IP blocks, and call it done. That's like locking your front door but leaving the windows open. Cloud Armor is not just a firewall; it's a programmable edge security layer that can inspect requests, enforce complex logic, and scale to absorb multi-terabit DDoS attacks. This article walks through building production-grade WAF rules, configuring DDoS protection, and implementing rate limiting that actually works — with real code, real failure modes, and no fluff.
Understanding Cloud Armor's Architecture
Cloud Armor operates at the edge of Google's network, before traffic reaches your backend. It integrates with External HTTP(S) Load Balancers and Cloud CDN. Policies are evaluated in order: first, preconfigured WAF rules (e.g., OWASP), then custom rules, then rate limiting. Each rule has a priority (lower number = higher priority). If a rule matches, the action (allow, deny, redirect, rate limit) is taken. If no rule matches, the default is to allow. This is critical: if you misconfigure priorities, you might accidentally allow malicious traffic. For example, a deny rule with priority 1000 might be overridden by an allow rule with priority 999. Always plan your rule numbering with gaps (e.g., 1000, 2000, 3000) to insert new rules later. Cloud Armor also supports edge security policies for Cloud CDN, which can block traffic before it even reaches the load balancer.
Preconfigured WAF Rules: OWASP Top 10 Protection
Cloud Armor offers preconfigured rule sets for common attack vectors: SQL injection (sqli-stable), cross-site scripting (xss-stable), local file inclusion (lfi-stable), remote file inclusion (rfi-stable), and more. These are maintained by Google and updated regularly. To use them, you write a rule with evaluatePreconfiguredExpr('rule-set-name'). You can also use versioned rules (e.g., sqli-v0.9-ea) for early access. Important: these rules are evaluated against the request body, headers, and query parameters. However, they can produce false positives. For example, a blog post about SQL might trigger the SQLi rule if it contains the word 'SELECT'. To mitigate, you can use the 'request.headers' or 'request.path' in your expression to narrow scope. Also, you can set the action to 'throttle' instead of 'deny' to slow down suspicious traffic instead of blocking it outright. Always test preconfigured rules in a staging environment with real traffic before enabling in production.
Custom WAF Rules with CEL Expressions
Cloud Armor uses Common Expression Language (CEL) for custom rules. CEL is a simple, fast expression language that can inspect request attributes like IP, headers, path, query parameters, and even geolocation. For example, you can block requests from a specific country, require a custom header, or match a regex pattern. CEL expressions are evaluated in a sandboxed environment with limited functions. You can use boolean operators (&&, ||, !), string functions (startsWith, contains, matches), and IP functions (inIpRange). One powerful pattern is to block requests that don't have a specific User-Agent header, which can stop many automated scanners. However, be careful: blocking based on User-Agent can also block legitimate clients like curl. A better approach is to allow known good User-Agents and deny everything else. Also, you can use the 'request.headers' map to access any header. For example, to block requests without a valid API key: !has(request.headers['x-api-key']) || request.headers['x-api-key'] != 'expected-value'.
Rate Limiting: Beyond Simple IP Throttling
Cloud Armor's rate limiting can be based on IP, IP range, or even custom keys like a session cookie or API key. You define a rate limit rule with a threshold (e.g., 100 requests per minute) and an action (deny or throttle). Throttling slows down requests instead of blocking them, which is useful for APIs. However, IP-based rate limiting is easily bypassed by botnets. A better approach is to use a combination of IP and a fingerprint like User-Agent or a custom header. For example, you can rate limit based on the 'x-session-id' header. But beware: if an attacker can spoof that header, they can bypass the limit. For production, consider using Cloud Armor's 'enforceOnKey' feature with a key like 'http-request-cookie' or 'http-request-header'. Also, you can set a 'rateLimitThreshold' per minute and a 'conformAction' for requests that exceed the limit. Always set a 'banDurationSec' to temporarily block offenders. A common pattern is to allow 100 requests per minute, then throttle for 10 minutes, then ban for 1 hour.
DDoS Protection: Google's Edge Defense
Cloud Armor includes Google's global DDoS infrastructure, which can absorb attacks up to multiple Tbps. This is always-on and requires no configuration. However, you can fine-tune protection with 'threat intelligence' rules that block known malicious IPs from Google's threat database. You can also enable 'Adaptive Protection' which uses machine learning to detect anomalous traffic patterns and automatically generate rules. Adaptive Protection is especially useful for application-layer DDoS attacks that mimic legitimate traffic. It learns your normal traffic profile over 24 hours and then flags deviations. When enabled, it can create a suggested rule that you can review and apply. For volumetric attacks, Cloud Armor automatically drops traffic at the edge. But for application-layer attacks, you need to configure rules. A common mistake is to rely solely on Cloud Armor's DDoS protection without setting up rate limiting or WAF rules. DDoS protection is a layered approach: network-layer is automatic, application-layer needs your rules.
Logging and Monitoring: Visibility is Key
Cloud Armor logs all requests that match a rule (allow or deny) to Cloud Logging. You can also enable 'enforceOnKey' logging for rate limiting. To get meaningful insights, export logs to BigQuery and create dashboards in Looker Studio. Key metrics: deny rate, top blocked IPs, top blocked paths, and rate limit triggers. Set up alerts for sudden spikes in deny rate, which could indicate an attack. Also, monitor false positives: if a legitimate endpoint is being blocked, you need to adjust rules. Cloud Armor also integrates with Cloud Monitoring for metrics like 'blocked_requests' and 'throttled_requests'. Use these to create alerting policies. A common mistake is not logging enough: by default, only denied requests are logged. Enable logging for allowed requests as well to understand your traffic baseline. But beware of costs: logging all requests can be expensive. Use sampling or filter to log only specific rules.
Testing and Deploying WAF Rules Safely
Before deploying a new rule to production, test it in a staging environment with mirrored traffic. Cloud Armor supports 'preview' mode: you can create a rule with action 'preview' that logs what would have happened without actually blocking. This is invaluable for testing. Also, use the Cloud Armor policy simulator to test individual requests. For rate limiting, you can set a low threshold temporarily to see if it triggers on legitimate traffic. Another technique: deploy rules with a 'throttle' action first, then switch to 'deny' after confirming no false positives. Always have a rollback plan: keep a copy of the previous policy and be ready to apply it. Use infrastructure as code (e.g., Terraform) to manage policies, so you can version control and rollback easily. Never edit a policy directly in the console in production — it's too easy to make a typo.
Advanced: Geolocation and IP Reputation Rules
Cloud Armor can use geolocation (origin.region_code) and IP reputation (evaluateThreatIntelligence) to block traffic from high-risk regions or known malicious IPs. For example, you might block all traffic from countries where you don't do business. However, be careful: attackers can use VPNs to appear from allowed regions. IP reputation rules use Google's threat intelligence to block IPs known for scanning, phishing, or malware. These are updated in real-time. You can also use custom IP lists (e.g., from your own threat feeds) by creating a 'security policy with a list of IPs'. For geolocation, you can allow only specific countries or block specific ones. A common pattern: allow all traffic, but apply stricter rate limiting to high-risk countries. For example, allow 100 req/min from US, but only 10 req/min from other countries. This can be done with multiple rules and priorities.
Integrating with Cloud CDN and Load Balancers
Cloud Armor policies are attached to backend services or target proxies of External HTTP(S) Load Balancers. You can also attach them to Cloud CDN's edge security policies. When attached to CDN, rules are evaluated at the edge before the CDN cache, which can block attacks before they hit your origin. However, CDN edge policies have fewer features (e.g., no rate limiting). For full protection, attach the policy to the load balancer's backend service. You can also use multiple policies: one at the CDN edge for basic filtering, and one at the load balancer for deeper inspection. A common architecture: use Cloud CDN with an edge security policy that blocks known bad IPs and geos, and then a more comprehensive WAF policy on the backend service. This reduces load on the WAF and improves performance.
Cost Optimization: Balancing Security and Budget
Cloud Armor pricing is based on the number of policies, rules, and requests evaluated. Each policy has a monthly cost, and each rule adds a small cost. Additionally, you pay per million requests evaluated. To optimize costs: consolidate rules into fewer policies, use preconfigured rules instead of custom ones when possible, and enable logging selectively. Also, consider using 'throttle' instead of 'deny' for some rules — throttled requests still incur evaluation costs but may reduce backend costs. Another tip: use Cloud Armor's 'preview' mode sparingly in production, as it logs all requests and can increase logging costs. For high-traffic sites, costs can add up. Monitor your Cloud Armor usage in the billing console and set budgets. A common mistake is to create many fine-grained rules that each cost money. Instead, combine conditions using OR (||) in a single rule.
Incident Response: Handling a WAF Bypass
No WAF is perfect. Attackers constantly find ways to bypass rules. When a bypass is detected, the first step is to analyze the logs to understand how the attack evaded detection. Common bypass techniques: encoding, case variation, parameter pollution, and using different HTTP methods. Update your rules to cover the bypass. For example, if an attacker used URL encoding, add a rule to normalize the request before evaluation (Cloud Armor does some normalization automatically, but not all). Also, consider using 'evaluatePreconfiguredExpr' with a stricter version. If the bypass is due to a missing rule, create a custom CEL rule. After fixing, test the rule in preview mode. Finally, communicate with your team about the incident and update your runbook. A good practice is to have a 'WAF bypass' playbook that includes steps to quickly create a temporary rule while you develop a permanent fix.
| File | Command / Code | Purpose |
|---|---|---|
| create-security-policy.sh | gcloud compute security-policies create prod-waf-policy \ | Understanding Cloud Armor's Architecture |
| enable-owasp-rules.sh | gcloud compute security-policies rules create 3000 \ | Preconfigured WAF Rules |
| custom-cel-rule.sh | gcloud compute security-policies rules create 5000 \ | Custom WAF Rules with CEL Expressions |
| rate-limit-rule.sh | gcloud compute security-policies rules create 7000 \ | Rate Limiting |
| enable-adaptive-protection.sh | gcloud compute security-policies update prod-waf-policy \ | DDoS Protection |
| enable-logging.sh | gcloud compute security-policies update prod-waf-policy \ | Logging and Monitoring |
| main.tf | resource "google_compute_security_policy" "waf" { | Testing and Deploying WAF Rules Safely |
| geo-ip-rep-rules.sh | gcloud compute security-policies rules create 9000 \ | Advanced |
| attach-policy.sh | gcloud compute backend-services update my-backend-service \ | Integrating with Cloud CDN and Load Balancers |
| cost-optimized-policy.sh | gcloud compute security-policies rules create 11000 \ | Cost Optimization |
| bypass-response.sh | gcloud compute security-policies rules create 12000 \ | Incident Response |
Key takeaways
Common mistakes to avoid
3 patternsIgnoring gcp cloud armor best practices
Over-provisioning without rightsizing analysis
Skipping IAM least-privilege principles
Interview Questions on This Topic
What is the difference between Cloud Armor's throttle and rate-based ban actions?
ban_duration_sec) after exceeding the threshold. Throttle can be promoted to rate-based ban but not vice versa.Frequently Asked Questions
20+ years shipping production infrastructure and CI/CD at scale. Drawn from code that ran under real load.
That's Google Cloud. Mark it forged?
6 min read · try the examples if you haven't