Policies
Every Cloud Workload Security resource this lab deploys - the deployment, its policy sets, the policies and the Rego behind them. Deployed by Terraform, and open in the dashboard at Cloud Workload Security ↗.
The deployment
| Setting | Value | Meaning |
|---|---|---|
| Name | cws-lab | ID - |
| Default mode | ALLOW | Requests no policy matches are allowed: these are guardrails, not an allow-list. |
| On error action | BLOCK | If a policy fails at runtime, the request is refused rather than waved through. |
| Policy sets | Data perimeter, AWS guardrails, Cloudflare API guardrails | |
| Domain ACL | cws-lab-cloud-apis | Default BLOCK; allows .amazonaws.com and api.cloudflare.com. Workloads behind this proxy talk to cloud APIs and nothing else. Anything else is refused at CONNECT, before a single byte of the request is sent. |
| Basic Auth | ci-pipeline, workstation | Clients identify themselves to the proxy; policies and workloads can match on it. |
Policy sets
| Policy set | Applies to | Policies |
|---|---|---|
| Data perimeter Stop data leaving the company's own AWS resources. | AWS APIs | aws-data-perimeter |
| AWS guardrails Configuration guardrails for anything that changes AWS. | AWS APIs | aws-s3-no-public-buckets aws-sqs-encryption-required aws-iam-no-admin |
| Cloudflare API guardrails The same idea, for changes to Cloudflare itself. | Cloudflare API | cf-r2-no-public-access cf-dns-proxied-only |
Workloads
| Workload | Filter | |
|---|---|---|
| AWS APIs | http.request.host contains "amazonaws.com" | Every request to an AWS API endpoint. |
| Cloudflare API | http.request.host == "api.cloudflare.com" | Every request to the Cloudflare API. |
| CI/CD pipelines | auth.basic_auth.username == "ci-pipeline" | Requests from GitLab CI jobs. Not attached to a policy set: the identity-aware chapter attaches it live. |
| Developer workstations | auth.basic_auth.username == "workstation" | Requests from people rather than pipelines. Not attached: see the identity-aware chapter. |
The policies
aws-data-perimeter
Data may only be written to company-owned resources, listed in the data-perimeter metadata.
- Filter
http.request.host contains "amazonaws.com"- Blocks
- s3:PutObject, sqs:SendMessage, sns:Publish, kinesis:PutRecord, dynamodb:PutItem and their batch forms, to any resource not on the approved list.
- Policy set
- Data perimeter · Enforce on
- Demo
- Stop data exfiltration through cloud APIs
Regoaws_data_perimeter.rego
# Data perimeter: data may only be written to resources the company owns.
#
# This is the control the exfiltration test exercises. An insider with valid
# AWS credentials can call s3:PutObject, sqs:SendMessage, sns:Publish,
# kinesis:PutRecord and dynamodb:PutItem against anyone's resources - IAM in
# the attacker's own account is happy to accept the data. The only place to
# stop it is on the way out, by checking the destination of every write
# against the list of approved resources in the data_perimeter metadata.
package policy.aws_data_perimeter
import data.lib.cws_lab
import data.metadata.data_perimeter
write_operations := {
"PutObject", "CopyObject", "CreateMultipartUpload",
"SendMessage", "SendMessageBatch",
"Publish", "PublishBatch",
"PutRecord", "PutRecords",
"PutItem", "BatchWriteItem", "UpdateItem", "TransactWriteItems",
}
default valid := false
valid if not violation
violation if {
cws_lab.op_in(write_operations)
not approved_destination
}
approved_destination if {
count(cws_lab.resource_names) > 0
every name in cws_lab.resource_names {
name in data_perimeter.approved_resources
}
}aws-s3-no-public-buckets
S3 buckets stay private.
- Filter
http.request.host contains "amazonaws.com"- Blocks
- Deleting or weakening the public access block, public ACLs, and bucket policies whose principal is everyone.
- Policy set
- AWS guardrails · Enforce on
- Demo
- A pipeline tries to make a bucket public
Regoaws_s3_no_public_buckets.rego
# S3 buckets stay private.
#
# Blocks the four ways a pipeline makes a bucket public: removing the public
# access block, weakening it, granting a public ACL, and attaching a bucket
# policy whose principal is everyone.
package policy.aws_s3_no_public_buckets
import data.lib.cws_lab
public_acls := {"public-read", "public-read-write", "authenticated-read"}
default valid := false
valid if not violation
violation if cws_lab.op_is("DeletePublicAccessBlock")
violation if {
cws_lab.op_is("PutPublicAccessBlock")
regex.match(
`(blockpublicacls|ignorepublicacls|blockpublicpolicy|restrictpublicbuckets)("?:|>)"?false`,
cws_lab.text,
)
}
violation if {
cws_lab.op_in({"PutBucketAcl", "PutObjectAcl", "CreateBucket", "PutObject"})
lower(cws_lab.header("x-amz-acl")) in public_acls
}
violation if {
cws_lab.op_in({"PutBucketAcl", "PutObjectAcl"})
cws_lab.mentions("acs.amazonaws.com/groups/global/AllUsers")
}
violation if {
cws_lab.op_is("PutBucketPolicy")
some principal in [`"principal":"*"`, `"principal":{"aws":"*"}`, `"principal":{"aws":["*"]}`]
cws_lab.mentions(principal)
}aws-sqs-encryption-required
SQS queues are encrypted at rest.
- Filter
http.request.host contains "sqs."- Blocks
- CreateQueue without SQS-managed SSE or a KMS key, and SetQueueAttributes turning SSE off.
- Policy set
- AWS guardrails · Enforce on
- Demo
- Rules IAM cannot write
Regoaws_sqs_encryption_required.rego
# SQS queues are encrypted at rest - with SQS-managed keys or a KMS key.
#
# The classic Kivera example: IAM can say who may create a queue, but not
# that the queue they create must be encrypted. CWS reads the request body
# and checks the attribute before the queue exists.
package policy.aws_sqs_encryption_required
import data.lib.cws_lab
default valid := false
valid if not violation
violation if {
cws_lab.op_is("CreateQueue")
not encrypted
}
violation if {
cws_lab.op_is("SetQueueAttributes")
lower(sprintf("%v", [attributes.SqsManagedSseEnabled])) == "false"
not kms_key
}
default attributes := {}
attributes := object.get(cws_lab.parsed_body, "Attributes", {})
kms_key if {
key := attributes.KmsMasterKeyId
is_string(key)
key != ""
}
encrypted if kms_key
encrypted if lower(sprintf("%v", [attributes.SqsManagedSseEnabled])) == "true"aws-iam-no-admin
Pipelines do not hand out administrator access.
- Filter
http.request.host contains "iam.amazonaws.com"- Blocks
- Attaching AdministratorAccess, and inline policies allowing every action on every resource.
- Policy set
- AWS guardrails · Enforce on
- Demo
- Rules IAM cannot write
Regoaws_iam_no_admin.rego
# Pipelines do not hand out administrator access.
#
# Blocks attaching the AdministratorAccess managed policy to anything, and
# inline policies that allow every action on every resource.
package policy.aws_iam_no_admin
import data.lib.cws_lab
default valid := false
valid if not violation
violation if {
cws_lab.op_in({"AttachRolePolicy", "AttachUserPolicy", "AttachGroupPolicy"})
cws_lab.mentions("arn:aws:iam::aws:policy/AdministratorAccess")
}
violation if {
cws_lab.op_in({"PutRolePolicy", "PutUserPolicy", "PutGroupPolicy", "CreatePolicy", "CreatePolicyVersion"})
cws_lab.mentions(`"action":"*"`)
cws_lab.mentions(`"resource":"*"`)
}cf-r2-no-public-access
R2 buckets stay private - the guardrail from the CWS get-started guide.
- Filter
application.name == "Cloudflare" and application.service == "r2" and application.operation == "r2-put-bucket-public-policy"- Blocks
- Turning on public r2.dev access for any bucket.
- Policy set
- Cloudflare API guardrails · Enforce on
- Demo
- Guardrails for the Cloudflare API
Regocf_r2_no_public_access.rego
# R2 buckets stay private - the guardrail from the CWS get-started guide.
#
# Its filter selects exactly one Cloudflare API operation, so the Rego has
# nothing to work out about the request: it only reads the body.
package policy.cf_r2_no_public_access
default valid := false
valid if {
input.http.request.body.enabled == false
}cf-dns-proxied-only
Web DNS records are proxied, so no origin address is published.
- Filter
http.request.host == "api.cloudflare.com" and http.request.method in {"POST" "PUT" "PATCH"}- Blocks
- Creating or updating an A, AAAA or CNAME record with proxied set to false.
- Policy set
- Cloudflare API guardrails · Enforce on
- Demo
- Guardrails for the Cloudflare API
Regocf_dns_proxied_only.rego
# Cloudflare DNS: web records are proxied.
#
# An unproxied A, AAAA or CNAME record publishes the origin's real address and
# routes around the WAF, DDoS protection and everything else in front of it.
# This one is written against the HTTP request rather than an Action Mapper
# operation, to show that both styles work.
package policy.cf_dns_proxied_only
import data.lib.cws_lab
web_record_types := {"A", "AAAA", "CNAME"}
default valid := false
valid if not violation
violation if {
cws_lab.method in {"POST", "PUT", "PATCH"}
regex.match(`^/client/v4/zones/[^/]+/dns_records(/[^/]+)?$`, cws_lab.path)
upper(cws_lab.body.type) in web_record_types
cws_lab.body.proxied == false
}Shared Rego
cws-lab-helpers
What a request is (op_is), where it writes (resource_names) and what it says (mentions) - for every AWS protocol.
Rego modulelib/cws_lab.rego
# Shared helpers for the lab's Cloud Workload Security policies.
#
# Uploaded as a CWS Rego module. Policies import it with
#
# import data.lib.cws_lab
#
# Every helper prefers the proxy's own classification (input.application.*,
# filled in by the Action Mapper) and falls back to reading the AWS wire
# protocol from input.http.request. The fallback is there because the exact
# spelling the Action Mapper uses for AWS operations is not documented, and a
# guardrail that silently stops matching is worse than one that does a little
# more work: it fails open, and nobody notices until the demo.
package lib.cws_lab
request := object.get(input, ["http", "request"], {})
host := lower(object.get(request, "host", ""))
method := upper(object.get(request, "method", ""))
path := split(object.get(request, "path", ""), "?")[0]
path_segments := [s | some s in split(path, "/"); s != ""]
query := object.get(request, "query", "")
raw_body := object.get(request, "body", null)
# --- Headers -----------------------------------------------------------------
header(name) := value if {
some key, raw in object.get(request, "headers", {})
lower(key) == lower(name)
value := scalar(raw)
}
scalar(x) := x if is_string(x)
scalar(x) := x[0] if {
is_array(x)
count(x) > 0
}
# --- Query string ------------------------------------------------------------
has_query_param(name) if {
is_string(query)
regex.match(sprintf(`(^|[?&])%s(=|&|$)`, [name]), query)
}
has_query_param(name) if {
is_object(query)
name in object.keys(query)
}
# --- Body --------------------------------------------------------------------
#
# AWS sends three shapes: JSON (SQS, DynamoDB, Kinesis), form-encoded query
# protocol (SNS, IAM) and XML (S3). The proxy may hand any of them over parsed
# or as a string, so `body` is the parsed form when there is one.
body := raw_body if is_object(raw_body)
body := json.unmarshal(raw_body) if {
is_string(raw_body)
startswith(trim_space(raw_body), "{")
}
body := urlquery.decode_object(raw_body) if {
is_string(raw_body)
contains(raw_body, "=")
not startswith(trim_space(raw_body), "{")
not startswith(trim_space(raw_body), "<")
}
body_field(name) := scalar(body[name])
# Everything a request says, lower-cased, with whitespace and JSON escaping
# removed, for checks that only need to know whether a value is present
# anywhere - "does this request mention AdministratorAccess".
default parsed_body := {}
parsed_body := body
as_text(x) := x if is_string(x)
as_text(x) := json.marshal(x) if not is_string(x)
# Strings are taken as they are - json.marshal would turn S3's XML into
# \u003c...\u003e - and structured values are serialised, then the escaped
# quotes of any JSON nested inside a string field (an IAM policy document,
# say) are unescaped so it reads like JSON too.
text := lower(regex.replace(
strings.replace_n(
{`\"`: `"`, `\u003c`: "<", `\u003e`: ">", `\u0026`: "&"},
concat(" ", [as_text(path), as_text(query), as_text(raw_body), as_text(parsed_body)]),
),
`\s+`,
"",
))
mentions(needle) if contains(text, lower(needle))
# --- Service and operation ---------------------------------------------------
service_is(name) if lower(object.get(input, ["application", "service"], "")) == lower(name)
service_is(name) if startswith(host, sprintf("%s.", [lower(name)]))
mapped_operation := op if {
op := input.application.operation
is_string(op)
}
# JSON protocols name the operation in X-Amz-Target ("AmazonSQS.SendMessage"),
# query protocols in the Action parameter, and S3 not at all - it is implied by
# the method, the path and the sub-resource in the query string.
wire_operation := op if {
target := header("x-amz-target")
parts := split(target, ".")
op := parts[count(parts) - 1]
} else := op if {
op := body_field("Action")
} else := op if {
is_object(query)
op := scalar(query.Action)
} else := op if {
service_is("s3")
op := s3_operation
}
s3_operation := "PutBucketPolicy" if {
method == "PUT"
has_query_param("policy")
} else := "DeleteBucketPolicy" if {
method == "DELETE"
has_query_param("policy")
} else := "PutPublicAccessBlock" if {
method == "PUT"
has_query_param("publicAccessBlock")
} else := "DeletePublicAccessBlock" if {
method == "DELETE"
has_query_param("publicAccessBlock")
} else := "PutBucketAcl" if {
method == "PUT"
has_query_param("acl")
count(path_segments) == 1
} else := "PutObjectAcl" if {
method == "PUT"
has_query_param("acl")
} else := "CreateBucket" if {
method == "PUT"
count(path_segments) == 1
} else := "PutObject" if {
method == "PUT"
count(path_segments) > 1
}
normalise(s) := lower(regex.replace(s, `[^A-Za-z0-9]`, ""))
# Matches "PutObject", "s3:PutObject" and "s3-put-object" alike.
op_is(name) if endswith(normalise(mapped_operation), normalise(name))
op_is(name) if normalise(wire_operation) == normalise(name)
op_in(names) if {
some name in names
op_is(name)
}
# --- Resources ---------------------------------------------------------------
#
# The names of the resources a request writes to. A set, because a batch write
# can name several, and because a request that names none should be treated as
# "unknown destination" by the caller rather than as "no destination".
s3_bucket := path_segments[0] if service_is("s3")
resource_names contains name if {
name := s3_bucket
}
resource_names contains name if {
url := body_field("QueueUrl")
parts := split(url, "/")
name := parts[count(parts) - 1]
}
resource_names contains name if {
arn := body_field("TopicArn")
parts := split(arn, ":")
name := parts[count(parts) - 1]
}
resource_names contains name if {
name := body_field("StreamName")
}
resource_names contains name if {
arn := body_field("StreamARN")
parts := split(arn, "/")
name := parts[count(parts) - 1]
}
resource_names contains name if {
name := body_field("TableName")
}
resource_names contains name if {
some name, _ in object.get(parsed_body, "RequestItems", {})
}
# The Basic Auth identity the client presented to the proxy, if any.
identity := object.get(input, ["auth", "basic_auth", "username"], "")data-perimeter
The company-owned resources data may be written to. Everything else is outside the perimeter.
Read by policies as data.metadata.data_perimeter.
{
"approved_resources": [
"acme-corp-data",
"acme-website-assets",
"acme-orders",
"acme-alerts",
"acme-clickstream",
"acme-customers"
]
}As code
All of the above is created by the Cloudflare Terraform provider's cloudflare_zero_trust_cws_*
resources, generated from one manifest in the lab bundle. A policy, for example:
resource "cloudflare_zero_trust_cws_policy" "lab" {
for_each = local.cws.policies
account_id = var.account_tag
name = each.value.name
description = each.value.description
filter = each.value.filter
rego_source = local.cws_rego[each.value.file]
entrypoint = "valid"
}
resource "cloudflare_zero_trust_cws_policy_set" "lab" {
for_each = local.cws.policy_sets
account_id = var.account_tag
name = each.value.name
include_workload_ids = [for w in each.value.include : cloudflare_zero_trust_cws_workload.lab[w].id]
policies = [for p in each.value.policies : {
policy_id = cloudflare_zero_trust_cws_policy.lab[p].id
enforce = var.cws_enforce
}]
}
Tested
31 unit tests run every policy against requests that should pass and requests that should fail - each written twice where it matters, as the proxy classifies the request and as raw HTTP, so a policy cannot quietly depend on one or the other.
$ opa test vm/policies
PASS: 31/31