Chapters

Cloud Armor: the web application firewall

Chapter 12.1 attached a Cloud Armor policy to Kadé's backend service and moved on. This chapter opens the policy up: how a rule is built, how a request travels down the list, how the ready-made WAF rules and rate limits work, and how to add a blocking rule to a live shop without blocking the shoppers.

The front door · chapter 17 of 26 · 22 min read

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.

Shopper203.0.113.99Google's front end1 edge policyIP, country2 Cloud CDNcache3 backend policyall rule typeskade-apiCloud Runrefused403 · 404 · 429cache hit: answered here, and the backend policy never runs
  • Run by Google
  • Allowed traffic and replies
  • Firewall and access rules

Wide by design - scroll it sideways.

#Policy typeRunsCan doAttaches to
1Backend security policyAfter the cache lookup, before the backendEverything in this chapter: IP, expressions, WAF rules, rate limitsBackend services. Kadé's kade-edge-policy
2Edge security policyFirst, before the cacheAllow or deny by IP and country onlyBackend services and backend buckets
3Network edge security policyAt layer 3 and 4Filter packets by address, port and protocolPassthrough 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:

1 · a backend service without a policyAttacker2 · a way around the load balancerAttacker3 · a cache hitAttackerload balancerno policy attachedkade-mediapolicy: never askeda run.app address, or a VM's external IPkade-apiCloud CDNanswers from cachebackend policybackend
  • 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:

1000prioritylowest firstevaluatePreconfiguredWaf('sqli-v33-stable')matchwhich requestsdeny-403actionwhat happenspreview: offpreviewon = log only
  • One rule in kade-edge-policy

Wide by design - scroll it sideways.

#ActionWhat the client getsUsed for
1allowThe request goes on to the backendExceptions, and the default rule
2deny-403, deny-404, deny-502That status code, from Google. The backend is never calledBlocking. 404 hides that anything is there
3throttle429 for requests over a rateSlowing down a busy client (section 06)
4rate-based-ban429 for everything, for a set time, after going over a rateStopping a client that is clearly abusing (section 06)
5redirectA redirect to another URL, or to a reCAPTCHA checkBot 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.

default allow: a block listrequestsall of themdeny ruleskade-apigets the rest✕what a rule namesdefault deny: an allow listrequestsall of themallow ruleskade-apigets only those✕everything else
  • 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:

Rule 1002 is
GET /api/productsfrom 203.0.113.99100rate limit /api/login60 a minute per IP, then banned 10 min429no match ↓200/admin from outside the officepath starts with /admin, not 198.51.100.20deny 404no match ↓300throttle /api/search120 a minute per IP429no match ↓1000WAF · sqli-v33-stableSQL injection, sensitivity 1deny 403no match ↓1001WAF · xss-v33-stablecross-site scripting, sensitivity 1deny 403no match ↓1002WAF · rce-v33-stableremote code execution, sensitivity 1deny 403 · previewno match ↓2147483647default ruleeverything elseallowALLOWS

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"
#ConsequenceWhat to do
1An allow rule placed early skips every rule below it, including the WAF rulesKeep early allow rules as narrow as possible. Prefer "deny unless" over "allow if"
2Order is the designCheap and certain checks first (IP, path), expensive ones after (WAF rules)
3You will need to insert rules laterLeave 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 matchAdvanced match
1Written asA list of IP ranges (--src-ip-ranges)An expression (--expression)
2Can look atThe source address onlyAddress, country, path, query, method, headers
3Use it forA plain block list or allow listEverything else

An expression is built from what Cloud Armor knows about the request:

one requestwhat an expression calls itfrom 203.0.113.99origin.ipcountry: LKorigin.region_codePOSTrequest.method/api/searchrequest.path?q=rice&page=2request.queryUser-Agent: Mozilla/5.0 …request.headers['user-agent']header names arewritten in lower case
  • 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 setCatchesKadé
1sqli-v33-stableSQL injection: database commands hidden in inputOn
2xss-v33-stableCross-site scripting: script tags and handlers in inputOn
3rce-v33-stableRemote code execution: shell commands in inputPreview, then on
4lfi-v33-stable, rfi-v33-stableFile inclusion: paths like ../../etc/passwd, or remote URLsNext
5scannerdetection-v33-stableKnown scanning toolsNext
6protocolattack-v33-stable, methodenforcement-v33-stableMalformed HTTP, request smuggling, unexpected methodsLater
7php-, java-, nodejs-v33-stableAttacks on one language's runtimeOnly the one you run
Each set also has a -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 onfalse positivessensitivity 1rare← start heresensitivity 2somesensitivity 3commonsensitivity 4many: needs careful tuning
  • 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:

an attackq=' OR '1'='1a signature matches403correct: this is SQL injectiona shopperq=rice 'n' curry -- 5kga signature matches403false positive: this is a search for rice
  • 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:

protection given up1 · Exclude a fieldone header, cookie or parameter is not readwhen one field always holds odd text2 · Opt out of a signatureone signature off, by its IDwhen one signature misfires in many fields3 · Scope the rulethe rule skips one pathwhen only one endpoint has the problem4 · Lower the sensitivitya whole level of signatures offwhen many signatures misfire
  • 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

POST body · 64 KBfirst 8 KBthe rest: not inspectedinspectedan attack placed here passes the WAF rules
  • Read by the WAF rules

Wide by design - scroll it sideways.

#LimitConsequence
1Only the start of a body is inspected: the first 8 KB by defaultThe WAF is a filter, not a guarantee. The app must still validate its input
2JSON bodies are read as plain text unless JSON parsing is onFor a JSON API like Kadé's, turn it on (command 9). It cuts false positives and catches more
3File uploads and other body types are not parsedScan 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:

One client sends
The rule is
limit: 60 a minute per IP · each bar is 10 seconds01 min2 min3 min4 min5 min6 min

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:

#QuestionSettingKadé's login rule
1Which requests are counted?The rule's matchrequest.path.matches('/api/login')
2Counted per what?--enforce-on-keyIP
3How many, in how long?--rate-limit-threshold-count and -interval-sec60 in 60 seconds, then banned for 600

The key decides how requests are grouped into counters. The same six requests, counted three ways:

key: IPclients reach Google directly203.0.113.99198.51.100.7192.0.2.44key: IP, behind a proxyeveryone arrives as the proxy173.245.48.10one counter: all banned togetherkey: HTTP-HEADERcounted by CF-Connecting-IP203.0.113.99198.51.100.7192.0.2.44
  • One counter

Wide by design - scroll it sideways.

#KeyOne counter perUse when
1IPSource addressThe default. Clients reach Google directly
2HTTP-HEADERValue of a header you nameAnother proxy is in front and passes the visitor's address in a header (section 09), or clients send an API key
3HTTP-COOKIEValue of a cookie you nameLimiting per logged-in session
4XFF-IPFirst address in X-Forwarded-ForRarely: a client can write that header itself
5ALLOne counter for everyoneProtecting 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:

1 · Add in preview--preview2 · Read the logsa week of traffic3 · Tuneopt out, exclude4 · Enforce--no-preview5 · Keep watchingalert on deniesrepeat until no real shopper is caught
  • The only step that can block a shopper

Wide by design - scroll it sideways.

#StepHowDone when
1Add in preview--preview on the rule (command 7)The rule is in the list and marked preview
2Read the logsLook for previewSecurityPolicy entries (command 5)You have seen a full week, including the busiest day
3TuneSection 05: exclude, opt out, lower, scopeEvery remaining match is a real attack
4Enforce--no-preview (command 8), at a quiet timeThe same requests now show under enforcedSecurityPolicy
5Keep watchingAn 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%.

statusDetails: "denied_by_security_policy"Cloud Armor refused it, not the appenforcedSecurityPolicy: name: "kade-edge-policy" priority: 1000which rule decided configuredAction: "DENY"what the rule is set to do outcome: "DENY"what happened to the request preconfiguredExprIds: ["…id942130-sqli"]the signature: the ID to opt out ofpreviewSecurityPolicy: …the same, for a rule still in preview
  • 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:

Shopper203.0.113.99Cloudflare173.245.48.10Cloud Armor seesorigin.ip = 173.245.48.10CF-Connecting-IP: 203.0.113.99every shopper has the same origin.ip:count and block by the header instead
  • Allowed traffic and replies
  • Firewall and access rules

Wide by design - scroll it sideways.

#What breaksFix
1Per-IP rate limits count all shoppers as a few proxy addresses, and ban everyone at onceKey the limit on the header: --enforce-on-key=HTTP-HEADER with --enforce-on-key-name=CF-Connecting-IP
2Rules on origin.ip or origin.region_code judge the proxy, not the visitorMatch on the header instead, or move that rule to the proxy
3Anyone who reaches Google directly can write the header themselvesLock the origin first, so only the proxy can reach it
Kadé meets all three in chapter 13, where Cloudflare goes in front and the origin lock is added at priority 500.

Standard or Enterprise

#StandardEnterprise adds
1Everything so farYes: rules, expressions, WAF rule sets, rate limits, preview-
2Large network floods (layer 3 and 4)Absorbed by the load balancer itself, always onExtra protection for passthrough load balancers and VMs
3Adaptive ProtectionBasic alertsLearns your normal traffic, flags an HTTP flood and proposes the rule to stop it
4Threat intelligence-Google-kept lists to match on: Tor exit nodes, known bad addresses, search engine crawlers
5Named IP lists-Provider ranges kept up to date for you, such as Cloudflare's
6BillingPer policy, per rule, per million requestsA subscription, or pay as you go

Limits and traps

#TrapWhat happensAvoid it by
1Enforcing a WAF rule without previewReal shoppers get 403 at checkoutSection 07, every time
2A broad allow rule at a low priorityIt skips every WAF rule below itNarrow allows; put the condition in a deny instead
3Changing the default to deny firstThe site goes down until allow rules existAdd the allow rules, check the logs, then flip the default
4Logging off on the backend serviceRules work, but you cannot see what they doLogging on before the first rule
5A new backend service with no policyThat part of the site is unprotectedCommand 3, and an organisation policy later (chapter 17)
6Trusting the WAF aloneAttacks past the 8 KB, or shaped to avoid signatures, get throughThe app still validates input and uses parameterised queries
7Per-IP limits behind a proxyEveryone is banned togetherSection 09

Back to Kadé

#PriorityMatchActionState
1100/api/login, over 60 a minute per IPban for 10 min, 429Enforced
2200/admin, not from 198.51.100.20deny 404Enforced
3300/api/search, over 120 a minute per IPthrottle, 429Enforced
4500(kept free for the origin lock, chapter 13)--
51000sqli-v33-stable, sensitivity 1deny 403Enforced
61001xss-v33-stable, sensitivity 1deny 403Enforced
71002rce-v33-stable, sensitivity 1deny 403Preview
82147483647everything elseallowDefault

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: true on rules still being tested.
gcloud compute security-policies describe kade-edge-policy

List the ready-made WAF rule sets

  • What it shows: The preconfigured rule sets and the signature IDs inside each.
  • What to look for: The -stable names used in section 05, and the IDs you see in log entries.
gcloud compute security-policies list-preconfigured-expression-sets

Find 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, /admin now 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=IP

Add 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: true in 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 --preview

Enforce 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-preview

Turn 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: STANDARD and logLevel: VERBOSE in command 1. Set the log level back to NORMAL when tuning is done.
gcloud compute security-policies update kade-edge-policy \  --json-parsing=STANDARD --log-level=VERBOSE

Tighten 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: rateLimitOptions with banDurationSec: 600 in 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=IP

Test 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

Spotted a mistake, or something unclear? Suggest an edit on GitHub