Where Cloud Armor sits
Builds on33. Proxies and load balancers
Cloud Armor is not a box in the network. It is a set of rules that Google's front end runs on each request, before the request reaches your backend. That is only possible on a proxy load balancer, because only a proxy has read the request (chapter 11 section 05).
A rule set is called a security policy. You attach it to a backend service (link 4 of the chain in chapter 12.1), not to the load balancer as a whole.
- Run by Google
- Allowed traffic and replies
- Firewall and access rules
Wide by design - scroll it sideways.
| # | Policy type | Runs | Can do | Attaches to |
|---|---|---|---|---|
| 1 | Backend security policy | After the cache lookup, before the backend | Everything in this chapter: IP, expressions, WAF rules, rate limits | Backend services. Kadé's kade-edge-policy |
| 2 | Edge security policy | First, before the cache | Allow or deny by IP and country only | Backend services and backend buckets |
| 3 | Network edge security policy | At layer 3 and 4 | Filter packets by address, port and protocol | Passthrough load balancers and VMs with external IPs. Enterprise only |
A policy only judges what passes through it. There are three ways a request never does:
- Run by Google
- Your VPC
- Firewall and access rules
Check every backend service for a policy (command 3), close the side doors (chapter 10 section 05), and use an edge policy when someone must be blocked from cached content too.
Wide by design - scroll it sideways.
Anatomy of a rule
A policy is a list of rules. Every rule has the same four parts:
- One rule in kade-edge-policy
Wide by design - scroll it sideways.
| # | Action | What the client gets | Used for |
|---|---|---|---|
| 1 | allow | The request goes on to the backend | Exceptions, and the default rule |
| 2 | deny-403, deny-404, deny-502 | That status code, from Google. The backend is never called | Blocking. 404 hides that anything is there |
| 3 | throttle | 429 for requests over a rate | Slowing down a busy client (section 06) |
| 4 | rate-based-ban | 429 for everything, for a set time, after going over a rate | Stopping a client that is clearly abusing (section 06) |
| 5 | redirect | A redirect to another URL, or to a reCAPTCHA check | Bot checks. Needs reCAPTCHA set up |
Every policy ends with a default rule at priority 2147483647, which matches everything. You cannot delete it; you only choose whether it allows or denies.
- Run by Google
- Allowed traffic and replies
- Firewall and access rules
A public shop is a block list, so Kadé's default is allow for now. An admin tool, or an origin locked to Cloudflare (chapter 13), is an allow list.
Wide by design - scroll it sideways.
How a policy decides
Rules are checked in priority order, lowest number first, and the first rule that matches decides. Nothing after it is looked at. This is the same idea as firewall rules (chapter 5.1), with one extra twist: a rule in preview never decides.
Send each request down Kadé's finished policy and watch where it stops:
Reached kade-api: allowed by rule 2147483647.
No rule above the default matches, so the default rule decides. Kadé's default is allow.
Show the log entry
httpRequest.requestUrl: /api/products httpRequest.status: 200 jsonPayload.enforcedSecurityPolicy: name: "kade-edge-policy" priority: 2147483647 configuredAction: "ALLOW" outcome: "ACCEPT"
| # | Consequence | What to do |
|---|---|---|
| 1 | An allow rule placed early skips every rule below it, including the WAF rules | Keep early allow rules as narrow as possible. Prefer "deny unless" over "allow if" |
| 2 | Order is the design | Cheap and certain checks first (IP, path), expensive ones after (WAF rules) |
| 3 | You will need to insert rules later | Leave gaps: 100, 200, 300 for your own rules, 1000 and up for WAF rules |
Writing a match
There are two ways to say which requests a rule applies to:
| # | Basic match | Advanced match | |
|---|---|---|---|
| 1 | Written as | A list of IP ranges (--src-ip-ranges) | An expression (--expression) |
| 2 | Can look at | The source address only | Address, country, path, query, method, headers |
| 3 | Use it for | A plain block list or allow list | Everything else |
An expression is built from what Cloud Armor knows about the request:
- The name to use in an expression
Wide by design - scroll it sideways.
Join them with && (and), || (or) and ! (not). Text can be tested with contains, startsWith, endsWith and matches (a regular expression). Four expressions worth keeping:
Admin pages, unless from the office
request.path.startsWith('/admin') && !inIpRange(origin.ip, '198.51.100.20/32')
One path and one method
request.path.matches('/api/login') && request.method == 'POST'
A scanner that names itself
request.headers['user-agent'].lower().contains('sqlmap')
Everything except two countries
!(origin.region_code == 'LK' || origin.region_code == 'IN')
Preconfigured WAF rules
Writing your own rule for every kind of attack is impossible. Google maintains ready-made rule sets, based on the open OWASP Core Rule Set, and you switch each one on with a single expression:
evaluatePreconfiguredWaf('sqli-v33-stable', {'sensitivity': 1})
| # | Rule set | Catches | Kadé |
|---|---|---|---|
| 1 | sqli-v33-stable | SQL injection: database commands hidden in input | On |
| 2 | xss-v33-stable | Cross-site scripting: script tags and handlers in input | On |
| 3 | rce-v33-stable | Remote code execution: shell commands in input | Preview, then on |
| 4 | lfi-v33-stable, rfi-v33-stable | File inclusion: paths like ../../etc/passwd, or remote URLs | Next |
| 5 | scannerdetection-v33-stable | Known scanning tools | Next |
| 6 | protocolattack-v33-stable, methodenforcement-v33-stable | Malformed HTTP, request smuggling, unexpected methods | Later |
| 7 | php-, java-, nodejs-v33-stable | Attacks on one language's runtime | Only the one you run |
-canary version with the newest signatures. Use -stable in production. gcloud compute security-policies list-preconfigured-expression-sets prints the current list.Sensitivity: how much to switch on
Each rule set is many small signatures, and each signature has a level from 1 to 4. The sensitivity you choose switches on every signature at that level and below:
- Signatures switched on
Wide by design - scroll it sideways.
A false positive is a real shopper's request that a signature mistakes for an attack. A signature looks for a pattern, and patterns do not know intent:
- A SQL injection signature
Wide by design - scroll it sideways.
The higher the sensitivity, the more often this happens.
Tuning out a false positive
When the logs show a real request being caught, narrow the rule instead of removing it. From the smallest change to the largest:
- How much of the rule set you switch off
Wide by design - scroll it sideways.
One signature off
evaluatePreconfiguredWaf('sqli-v33-stable',
{'sensitivity': 2, 'opt_out_rule_ids': ['owasp-crs-v030301-id942260-sqli']})
Everywhere except the search box
evaluatePreconfiguredWaf('sqli-v33-stable', {'sensitivity': 2})
&& !request.path.startsWith('/api/search')
The signature ID to opt out of is printed in the log entry of the request it caught (section 08).
What the rules can read
- Read by the WAF rules
Wide by design - scroll it sideways.
| # | Limit | Consequence |
|---|---|---|
| 1 | Only the start of a body is inspected: the first 8 KB by default | The WAF is a filter, not a guarantee. The app must still validate its input |
| 2 | JSON bodies are read as plain text unless JSON parsing is on | For a JSON API like Kadé's, turn it on (command 9). It cuts false positives and catches more |
| 3 | File uploads and other body types are not parsed | Scan uploads in the app or in storage, not here |
Rate limiting
A rate limit rule counts requests per client and acts when a client goes over. There are two actions, and they behave very differently. Try both:
Over six minutes: 360 allowed, 180 refused with 429.
Throttle keeps letting 60 a minute through and refuses the rest. The client is slowed down, never locked out. Good for a busy but honest client, such as search.
Green is let through, red is refused. Real counting is approximate: Cloud Armor counts per Google region, so treat a threshold as a rough line, not an exact one.
Every rate limit rule answers three questions:
| # | Question | Setting | Kadé's login rule |
|---|---|---|---|
| 1 | Which requests are counted? | The rule's match | request.path.matches('/api/login') |
| 2 | Counted per what? | --enforce-on-key | IP |
| 3 | How many, in how long? | --rate-limit-threshold-count and -interval-sec | 60 in 60 seconds, then banned for 600 |
The key decides how requests are grouped into counters. The same six requests, counted three ways:
- One counter
Wide by design - scroll it sideways.
| # | Key | One counter per | Use when |
|---|---|---|---|
| 1 | IP | Source address | The default. Clients reach Google directly |
| 2 | HTTP-HEADER | Value of a header you name | Another proxy is in front and passes the visitor's address in a header (section 09), or clients send an API key |
| 3 | HTTP-COOKIE | Value of a cookie you name | Limiting per logged-in session |
| 4 | XFF-IP | First address in X-Forwarded-For | Rarely: a client can write that header itself |
| 5 | ALL | One counter for everyone | Protecting a fragile backend from total load |
Rolling out a rule safely
A WAF rule that blocks a real shopper at checkout costs more than most attacks. So no blocking rule goes straight to production. It goes through preview:
- The only step that can block a shopper
Wide by design - scroll it sideways.
| # | Step | How | Done when |
|---|---|---|---|
| 1 | Add in preview | --preview on the rule (command 7) | The rule is in the list and marked preview |
| 2 | Read the logs | Look for previewSecurityPolicy entries (command 5) | You have seen a full week, including the busiest day |
| 3 | Tune | Section 05: exclude, opt out, lower, scope | Every remaining match is a real attack |
| 4 | Enforce | --no-preview (command 8), at a quiet time | The same requests now show under enforcedSecurityPolicy |
| 5 | Keep watching | An alert on a sudden rise in denies (chapter 16.2) | Always. New app features bring new false positives |
Reading the logs
Cloud Armor does not have its own log. Its decision is written into the load balancer's request log, so logging must be on for the backend service (chapter 12.1). Kadé's is at 100%.
- What the line tells you
Wide by design - scroll it sideways.
Turn on verbose logging for the policy while tuning (command 9). The entry then also names the field and the piece of text that matched, which is usually enough to see at once whether it was an attack.
The real client IP
origin.ip is the address the connection to Google came from. With nothing in front, that is the shopper. With another proxy in front, it is the proxy:
- Allowed traffic and replies
- Firewall and access rules
Wide by design - scroll it sideways.
| # | What breaks | Fix |
|---|---|---|
| 1 | Per-IP rate limits count all shoppers as a few proxy addresses, and ban everyone at once | Key the limit on the header: --enforce-on-key=HTTP-HEADER with --enforce-on-key-name=CF-Connecting-IP |
| 2 | Rules on origin.ip or origin.region_code judge the proxy, not the visitor | Match on the header instead, or move that rule to the proxy |
| 3 | Anyone who reaches Google directly can write the header themselves | Lock the origin first, so only the proxy can reach it |
Standard or Enterprise
| # | Standard | Enterprise adds | |
|---|---|---|---|
| 1 | Everything so far | Yes: rules, expressions, WAF rule sets, rate limits, preview | - |
| 2 | Large network floods (layer 3 and 4) | Absorbed by the load balancer itself, always on | Extra protection for passthrough load balancers and VMs |
| 3 | Adaptive Protection | Basic alerts | Learns your normal traffic, flags an HTTP flood and proposes the rule to stop it |
| 4 | Threat intelligence | - | Google-kept lists to match on: Tor exit nodes, known bad addresses, search engine crawlers |
| 5 | Named IP lists | - | Provider ranges kept up to date for you, such as Cloudflare's |
| 6 | Billing | Per policy, per rule, per million requests | A subscription, or pay as you go |
Limits and traps
| # | Trap | What happens | Avoid it by |
|---|---|---|---|
| 1 | Enforcing a WAF rule without preview | Real shoppers get 403 at checkout | Section 07, every time |
| 2 | A broad allow rule at a low priority | It skips every WAF rule below it | Narrow allows; put the condition in a deny instead |
| 3 | Changing the default to deny first | The site goes down until allow rules exist | Add the allow rules, check the logs, then flip the default |
| 4 | Logging off on the backend service | Rules work, but you cannot see what they do | Logging on before the first rule |
| 5 | A new backend service with no policy | That part of the site is unprotected | Command 3, and an organisation policy later (chapter 17) |
| 6 | Trusting the WAF alone | Attacks past the 8 KB, or shaped to avoid signatures, get through | The app still validates input and uses parameterised queries |
| 7 | Per-IP limits behind a proxy | Everyone is banned together | Section 09 |
Back to Kadé
| # | Priority | Match | Action | State |
|---|---|---|---|---|
| 1 | 100 | /api/login, over 60 a minute per IP | ban for 10 min, 429 | Enforced |
| 2 | 200 | /admin, not from 198.51.100.20 | deny 404 | Enforced |
| 3 | 300 | /api/search, over 120 a minute per IP | throttle, 429 | Enforced |
| 4 | 500 | (kept free for the origin lock, chapter 13) | - | - |
| 5 | 1000 | sqli-v33-stable, sensitivity 1 | deny 403 | Enforced |
| 6 | 1001 | xss-v33-stable, sensitivity 1 | deny 403 | Enforced |
| 7 | 1002 | rce-v33-stable, sensitivity 1 | deny 403 | Preview |
| 8 | 2147483647 | everything else | allow | Default |
The whole policy as Terraform
The same policy as one file, for when it lives in version control instead of being typed rule by rule:
resource "google_compute_security_policy" "kade_edge" {
name = "kade-edge-policy"
advanced_options_config {
json_parsing = "STANDARD"
log_level = "VERBOSE"
}
rule {
priority = 100
action = "rate_based_ban"
match {
expr { expression = "request.path.matches('/api/login')" }
}
rate_limit_options {
conform_action = "allow"
exceed_action = "deny(429)"
enforce_on_key = "IP"
ban_duration_sec = 600
rate_limit_threshold {
count = 60
interval_sec = 60
}
}
}
rule {
priority = 200
action = "deny(404)"
match {
expr { expression = "request.path.startsWith('/admin') && !inIpRange(origin.ip, '198.51.100.20/32')" }
}
}
rule {
priority = 300
action = "throttle"
match {
expr { expression = "request.path.startsWith('/api/search')" }
}
rate_limit_options {
conform_action = "allow"
exceed_action = "deny(429)"
enforce_on_key = "IP"
rate_limit_threshold {
count = 120
interval_sec = 60
}
}
}
rule {
priority = 1000
action = "deny(403)"
match {
expr { expression = "evaluatePreconfiguredWaf('sqli-v33-stable', {'sensitivity': 1})" }
}
}
rule {
priority = 1001
action = "deny(403)"
match {
expr { expression = "evaluatePreconfiguredWaf('xss-v33-stable', {'sensitivity': 1})" }
}
}
rule {
priority = 1002
action = "deny(403)"
preview = true
match {
expr { expression = "evaluatePreconfiguredWaf('rce-v33-stable', {'sensitivity': 1})" }
}
}
rule {
priority = 2147483647
action = "allow"
match {
versioned_expr = "SRC_IPS_V1"
config { src_ip_ranges = ["*"] }
}
}
}
Commands in this chapter
Commands 1 to 5 are read-only. Commands 6 to 10 change the project. Command 11 only sends test requests.
See a policy and all its rules
- What it shows: Every rule in kade-edge-policy: priority, match, action and whether it is in preview.
- What to look for: The order, the default rule's action at the bottom, and
preview: trueon rules still being tested.
gcloud compute security-policies describe kade-edge-policyList the ready-made WAF rule sets
- What it shows: The preconfigured rule sets and the signature IDs inside each.
- What to look for: The
-stablenames used in section 05, and the IDs you see in log entries.
gcloud compute security-policies list-preconfigured-expression-setsFind backend services without a policy
- What it shows: Each backend service and the policy attached to it.
- What to look for: An empty policy column on anything public (the first trap in section 01).
gcloud compute backend-services list \ --format="table(name,securityPolicy.basename(),edgeSecurityPolicy.basename())"See what was blocked in the last hour
- What it shows: Requests Cloud Armor refused, with the rule that refused each.
- What to look for: The priority column. A real shopper in this list is a false positive to tune (section 05).
gcloud logging read 'resource.type="http_load_balancer" AND jsonPayload.enforcedSecurityPolicy.outcome="DENY"' --freshness=1h --limit=20 \ --format="table(timestamp,httpRequest.remoteIp,httpRequest.requestUrl,jsonPayload.enforcedSecurityPolicy.priority)"See what a preview rule would have blocked
- What it shows: Requests that matched a rule in preview and were let through.
- What to look for: Read these for a week before enforcing. The signature IDs are what you opt out of.
gcloud logging read 'resource.type="http_load_balancer" AND jsonPayload.previewSecurityPolicy.outcome="DENY"' --freshness=7d --limit=50 \ --format="table(timestamp,httpRequest.remoteIp,httpRequest.requestUrl,jsonPayload.previewSecurityPolicy.priority,jsonPayload.previewSecurityPolicy.preconfiguredExprIds)"Add the admin rule and the search throttle (changes the project)
- What it shows: A deny rule with an expression, and a throttle rule.
- What to look for: Both rules in command 1. From outside the office,
/adminnow returns 404.
gcloud compute security-policies rules create 200 --security-policy=kade-edge-policy \ --expression="request.path.startsWith('/admin') && !inIpRange(origin.ip, '198.51.100.20/32')" \ --action=deny-404 --description="admin: office only"gcloud compute security-policies rules create 300 --security-policy=kade-edge-policy \ --expression="request.path.startsWith('/api/search')" \ --action=throttle --rate-limit-threshold-count=120 --rate-limit-threshold-interval-sec=60 \ --conform-action=allow --exceed-action=deny-429 --enforce-on-key=IPAdd a WAF rule set in preview (changes the project)
- What it shows: Step 1 of section 07: the remote code execution rules, logging only.
- What to look for:
preview: truein command 1, then matches in command 5.
gcloud compute security-policies rules create 1002 --security-policy=kade-edge-policy \ --expression="evaluatePreconfiguredWaf('rce-v33-stable', {'sensitivity': 1})" \ --action=deny-403 --previewEnforce a rule that has been in preview (changes the project)
- What it shows: Step 4 of section 07.
- What to look for: The same requests move from command 5 to command 4. Do it at a quiet time, and wait a few minutes before testing.
gcloud compute security-policies rules update 1002 --security-policy=kade-edge-policy --no-previewTurn on JSON parsing and verbose logs (changes the project)
- What it shows: Two settings of the policy itself, not of a rule.
- What to look for:
jsonParsing: STANDARDandlogLevel: VERBOSEin command 1. Set the log level back toNORMALwhen tuning is done.
gcloud compute security-policies update kade-edge-policy \ --json-parsing=STANDARD --log-level=VERBOSETighten the login rule into a ban (changes the project)
- What it shows: The login rule as a rate-based ban: 60 a minute per IP, then refused for 10 minutes.
- What to look for:
rateLimitOptionswithbanDurationSec: 600in command 1.
gcloud compute security-policies rules update 100 --security-policy=kade-edge-policy \ --expression="request.path.matches('/api/login')" \ --action=rate-based-ban --rate-limit-threshold-count=60 --rate-limit-threshold-interval-sec=60 \ --ban-duration-sec=600 --conform-action=allow --exceed-action=deny-429 --enforce-on-key=IPTest each rule with curl
- What it shows: The status code each kind of request gets back.
- What to look for: 403 for the first, 403 for the second, 404 for the third (from outside the office), and 429 appearing partway through the loop. Only run these against your own service.
curl -s -o /dev/null -w "%{http_code}\n" "https://api.kade.lk/api/search?q=%27%20OR%20%271%27=%271"curl -s -o /dev/null -w "%{http_code}\n" "https://api.kade.lk/api/search?q=%3Cscript%3Ealert(1)%3C/script%3E"curl -s -o /dev/null -w "%{http_code}\n" "https://api.kade.lk/admin/orders"for i in $(seq 1 70); do curl -s -o /dev/null -w "%{http_code} " -X POST "https://api.kade.lk/api/login" -d "user=test&pass=wrong"done