These are the notes for Cybersecurity Fundamentals (defensive), episode 65. Episode 64 showed that in every cloud model your data and who can access it are your job. This episode gives you the three big tools for that job: identity and access management, the private network your servers live in, and encryption and backups that protect the data itself. Every term is defined the first time it appears; the Glossary collects them.
Scope. Defensive and educational only. Every program is a toy simulation; account numbers and keys are made up and no real cloud account is touched. Samples were run on 13 Nov 2026 in the SyntaxPilot compiler (Python 3.13; the envelope demo uses the cryptography library).
Examples use AWS names; Azure and Google Cloud offer the same ideas under their own names.
Step 1: IAM policies
Real-life example: an office building. A person holds an ID card (who), wants to open a door (does what) on floor 3 (to what), and security checks an access list (the rules). No entry unless listed.
- IAM (identity and access management): the cloud service that decides who can do what.
- Principal: anything that can make a request: a user, an application, a role, a cloud service.
- Action: an operation, written
service:Operation, e.g.s3:GetObject(read a file from S3). - Resource: the thing acted on, e.g. a bucket or an object in it.
- IAM policy: a document (usually JSON) of statements, each with an
Effect(AlloworDeny), actions and resources. - Default deny (episode 24): if no statement allows a request, it is denied.
- Explicit deny: a
Denystatement. AWS: "An explicit deny in either of these policies overrides the allow." - Wildcard:
*, matching anything. Convenient, and the usual way policies grant far more than intended. - Identity-based policy: attached to a user or role (what they can do). Resource-based policy: attached to a resource (who can use it), e.g. a bucket policy. In the same account, AWS combines them as a union: allowed if either allows (and nothing denies).
Demo 1: a toy policy evaluator
# A toy cloud IAM policy evaluator: default deny, explicit Deny wins.
from fnmatch import fnmatch
POLICIES = {
"role/web-app": [
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "shop-images/*"},
{"Effect": "Allow", "Action": "s3:*", "Resource": "shop-*"},
{"Effect": "Deny", "Action": "s3:Delete*", "Resource": "*"},
]}
def decide(principal, action, resource):
verdict = "DENY (no statement allows it)" # default deny
for st in POLICIES.get(principal, []):
if fnmatch(action, st["Action"]) and fnmatch(resource, st["Resource"]):
if st["Effect"] == "Deny":
return "DENY (explicit Deny wins)"
verdict = "ALLOW"
return verdict
for action, resource in [("s3:GetObject", "shop-images/logo.png"),
("s3:GetObject", "hr-salaries/2026.csv"),
("s3:GetObject", "shop-backups/db.sql"),
("s3:DeleteObject", "shop-images/logo.png")]:
print(f"{action:16} {resource:24} -> {decide('role/web-app', action, resource)}")
Real output:
s3:GetObject shop-images/logo.png -> ALLOW
s3:GetObject hr-salaries/2026.csv -> DENY (no statement allows it)
s3:GetObject shop-backups/db.sql -> ALLOW
s3:DeleteObject shop-images/logo.png -> DENY (explicit Deny wins)
The third line is the lesson: the lazy s3:* on shop-* lets the web app read the database backup. Name exact actions on exact resources (least privilege, episode 3).
A real AWS policy statement looks like this:
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::shop-images/*"}
]
}
(ARN, Amazon Resource Name: AWS's unique name for a resource.)
Step 2: roles, trust policies and temporary credentials
Real-life example: a copied office key works forever for whoever holds it; a visitor pass is issued by reception after checking a list, and expires at 6 pm on its own.
- Access key: a long-lived credential (key ID + secret) for programmatic access. Pasted into a config file, it leaks with the file.
- Role: a set of permissions that no one owns permanently; principals assume it to use it for a while.
- Assume role: temporarily become the role and get its permissions. On AWS this is the STS (Security Token Service)
AssumeRolecall. - Trust policy: the role's list of who may assume it. AWS: a role has "a role trust policy that specifies who can assume the role, and a permissions policy that specifies what can be done with the role." A trust policy can require MFA (
aws:MultiFactorAuthPresent). - Temporary credentials: what assuming a role returns: an access key ID, a secret access key, a session token and an expiration. AWS default duration is 3600 seconds, from 900 seconds (15 min) up to the role's maximum session (1 to 12 hours).
- Cross-account access: a role in account A whose trust policy trusts account B; B's principals assume it, with no shared passwords. AWS: "your Amazon Web Services account must be trusted by the role."
Demo 2: assume role, live
# Roles and temporary credentials: who may assume, and for how long (toy STS).
ROLE = {"name": "deploy-role",
"trust": ["account/111111111111:user/asha", "service/ec2"], # trust policy
"max_seconds": 3600}
NOW = 0 # a toy clock, in seconds
def assume_role(caller, seconds):
if caller not in ROLE["trust"]:
return "AccessDenied: not trusted to assume " + ROLE["name"]
return {"key": "ASIA-TOY-7F3A", # made-up key
"expires": NOW + min(seconds, ROLE["max_seconds"])}
def use(creds):
return "OK" if NOW < creds["expires"] else "ExpiredToken"
print("stranger :", assume_role("account/999999999999:user/eve", 900))
creds = assume_role("account/111111111111:user/asha", 900)
print("asha :", creds)
NOW = 60
print("at t=60 :", use(creds))
NOW = 1000 # 1000 seconds later
print("at t=1000:", use(creds), "<- a stolen copy is useless now")
Real output:
stranger : AccessDenied: not trusted to assume deploy-role
asha : {'key': 'ASIA-TOY-7F3A', 'expires': 900}
at t=60 : OK
at t=1000: ExpiredToken <- a stolen copy is useless now
service/ec2 in the trust list is how a virtual machine gets credentials without any stored key: the VM's role is assumed for it automatically.
Step 3: permission boundaries and SCPs
The problem: you let developers create roles for their apps. One creates a role with full admin rights and uses it. That is privilege escalation (episode 9) through IAM.
- Permissions boundary: a ceiling an admin sets on a user or role. AWS: "the resulting permissions are the intersection of the two" (identity policies and the boundary); it can reduce what the user can do, never add.
- Service control policy (SCP): a ceiling set by the AWS organisation (episode 64) for every principal in an account (or group of accounts). For a member account, AWS: "an action must be allowed by all three policy types" (the user's policies, SCPs and resource control policies, RCPs).
- Guardrail: an SCP is the classic preventive guardrail ("no one in this account may disable audit logging").
- Boundaries and SCPs never grant; they only limit. An explicit deny anywhere still wins.
Demo 3: effective permissions
# Effective permissions = what EVERY layer allows (an intersection).
identity_policy = {"s3:*", "ec2:*", "iam:CreateRole", "iam:AttachRolePolicy"}
permissions_boundary = {"s3:*", "ec2:*", "iam:CreateRole"} # set by admins
scp = {"s3:*", "ec2:*", "iam:CreateRole", "iam:AttachRolePolicy",
"cloudtrail:LookupEvents"} # org-wide guardrail
scp_denies = {"ec2:*"} # e.g. no new servers in this account
effective = (identity_policy & permissions_boundary & scp) - scp_denies
print("policy :", sorted(identity_policy))
print("boundary :", sorted(identity_policy & permissions_boundary))
print("after SCP:", sorted(effective))
print("can attach an admin policy?", "iam:AttachRolePolicy" in effective)
Real output:
policy : ['ec2:*', 'iam:AttachRolePolicy', 'iam:CreateRole', 's3:*']
boundary : ['ec2:*', 'iam:CreateRole', 's3:*']
after SCP: ['iam:CreateRole', 's3:*']
can attach an admin policy? False
(The toy uses Python sets; real policies match actions and resources with patterns and conditions, but the intersection logic is the same.)
Case study: Capital One (2019)
- Capital One announced the breach on 19 July 2019; over 100 million US and Canadian customer records were accessed.
- The path: a misconfigured web application firewall (WAF) was abused with server-side request forgery (SSRF, episode 43: tricking a server into making requests for the attacker). The WAF's role had access to S3 buckets holding sensitive data (over 700 buckets).
- Lessons: least privilege for every role (a firewall role has no reason to read customer data), continuous compliance monitoring, and alerts on unusual access (a WAF role listing hundreds of buckets).
Step 4: networking — VPCs, subnets, security groups, NACLs, private endpoints
Real-life example: a gated housing society with its own walls and roads, shops near the gate and homes deep inside, a guard at each flat and a guard at each block.
- VPC (virtual private cloud): your own isolated private network in the cloud, with your own address range (CIDR, episode 18).
- Subnet: a smaller address range inside a VPC, in one availability zone.
- Public subnet: has a route to an internet gateway (the VPC's door to the internet); for web servers and load balancers.
- Private subnet: no direct route in from the internet; for databases and internal services.
- Security group (SG): a virtual firewall around each instance.
- Network ACL (NACL): a firewall for a whole subnet.
- Stateful: remembers connections, so replies are allowed automatically. Stateless: checks every packet on its own.
- Ephemeral ports: the temporary high-numbered ports (e.g. 1024-65535) a client uses for each connection; replies go back to them.
| Security group | Network ACL | |
|---|---|---|
| Works at | instance level | subnet level |
| Rules | allow rules only | allow and deny rules |
| Evaluation | all rules evaluated before deciding | rules in ascending number order until a match |
| Return traffic | automatically allowed (stateful) | must be explicitly allowed (stateless) |
(Source: AWS VPC documentation.)
Demo 4: the stateless NACL drops the reply
# Security group (stateful) vs network ACL (stateless): does the reply get back?
# A browser on port 51515 asks our web server on port 443.
request = {"dir": "in", "port": 443}
reply = {"dir": "out", "port": 51515} # replies go to the client's port
def security_group(pkt, seen):
if pkt["dir"] == "in":
if pkt["port"] == 443: seen.add("conn"); return "allow"
return "drop"
return "allow" if "conn" in seen else "drop" # remembers the connection
def nacl(pkt, out_rules):
if pkt["dir"] == "in":
return "allow" if pkt["port"] == 443 else "drop"
return "allow" if any(lo <= pkt["port"] <= hi for lo, hi in out_rules) else "drop"
seen = set()
print("security group :", security_group(request, seen), "/", security_group(reply, seen))
print("NACL, out 443 :", nacl(request, [(443, 443)]), "/", nacl(reply, [(443, 443)]))
print("NACL, ephemeral:", nacl(request, [(1024, 65535)]), "/", nacl(reply, [(1024, 65535)]))
Real output:
security group : allow / allow
NACL, out 443 : allow / drop
NACL, ephemeral: allow / allow
Private endpoints
- Problem: a database in a private subnet must write backups to object storage (a public service) without opening an internet path.
- Private endpoint: a doorway to a cloud service that appears inside your VPC with a private IP address. AWS's PrivateLink interface VPC endpoints connect your subnets to the service through network interfaces, "without the use of an internet gateway"; DNS resolves the service name to the endpoint's private IPs.
- A bucket policy can then require that requests come only through that endpoint.
Step 5: data protection — bucket policies, object encryption, KMS, backup
Real-life example: a bank locker room with a list on the door, each locker locked inside, and the master keys in a vault only the manager can open.
- Bucket policy: a resource-based policy on a bucket (who may do what with it). It can require encrypted connections (HTTPS) or a specific private endpoint.
- Encryption at rest: data is encrypted while stored. Object encryption: each stored object is encrypted.
- SSE-S3: server-side encryption with keys S3 manages. Since 5 January 2023, S3 automatically applies SSE-S3 to all new objects, and the default encryption setting can no longer be removed from any bucket.
- KMS (key management service): a cloud service that creates, stores and uses encryption keys inside HSMs (hardware security modules, tamper-resistant key hardware). AWS: "Your plaintext KMS keys never leave the HSMs."
- Customer-managed key (CMK): a KMS key you create and control: you define its access and usage policy, and can rotate it automatically or on demand. AWS managed key: created in your account for a service; usage is logged but you have no direct control.
- Key rotation: replacing key material on a schedule.
- Envelope encryption: a fresh data key encrypts the data; the KMS key encrypts ("wraps") the data key; the wrapped key is stored next to the data.
Demo 5: envelope encryption
# Envelope encryption: a data key encrypts the file, a master key wraps the data key.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
master_key = AESGCM.generate_key(256) # lives inside the KMS, never leaves
def kms_encrypt(plain): # toy KMS: only it holds master_key
n = os.urandom(12); return n + AESGCM(master_key).encrypt(n, plain, None)
def kms_decrypt(blob):
return AESGCM(master_key).decrypt(blob[:12], blob[12:], None)
data_key = AESGCM.generate_key(256) # 1. a fresh key for this file
n = os.urandom(12)
stored = {"file": n + AESGCM(data_key).encrypt(n, b"customers.csv: Priya, Neha", None),
"wrapped_key": kms_encrypt(data_key)} # 2. store the key ENCRYPTED
del data_key # 3. forget the plain data key
print("stored file :", stored["file"][:16].hex(), "...")
print("stored key :", stored["wrapped_key"][:16].hex(), "... (useless alone)")
key = kms_decrypt(stored["wrapped_key"]) # 4. later: ask KMS to unwrap
print("decrypted :", AESGCM(key).decrypt(stored["file"][:12], stored["file"][12:], None).decode())
Real output (the hex is random on every run):
stored file : 9d9a25f0da9c5b0f4fd4863fd8d56bbe ...
stored key : d7a18d4b00f48dced6cb1003927bd220 ... (useless alone)
decrypted : customers.csv: Priya, Neha
AES-GCM is the authenticated encryption from episode 12; the nonce is the 12 random bytes. In a real cloud, step 4 is a KMS API call that is checked against the key policy and written to the audit log — and disabling the key makes every file under it unreadable at once.
Cloud backup
- Backup: a copy you can restore after loss, corruption or attack.
- Ransomware (episode 5) operators with a stolen admin role delete backups first, then encrypt the data.
- Keep backups in a separate account (different credentials and blast radius), ideally another region, and immutable: they can't be changed or deleted until a set date.
- Restore test: actually restoring from a backup on a schedule; a backup never restored is only a hope.
- The classic 3-2-1 rule: 3 copies, on 2 different media, 1 off-site.
The whole chain
- Who can do what? → IAM policies, default deny, explicit deny.
- Permanent keys leak → roles, trust policies, temporary credentials.
- Developers make themselves admin → permission boundaries, SCPs.
- Servers exposed → VPC, subnets, security groups, network ACLs.
- Storage over the internet → private endpoints.
- Data stolen or deleted → bucket policies, encryption, KMS keys, backups.
Common mistakes (and the fix)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
"Action": "s3:*", "Resource": "*" |
s3:GetObject shop-backups/db.sql -> ALLOW |
wildcards grant everything | exact actions on exact resources |
access key pasted in app.config |
a leaked repository gives permanent access | long-lived credential | a role with temporary credentials |
| letting devs create roles with no boundary | a dev creates and uses an admin role | privilege escalation | permissions boundary + SCP |
| NACL allows only port 443 out | NACL, out 443 : allow / drop |
NACLs are stateless | allow the ephemeral port range |
| database in a public subnet | the database answers on the internet | no network isolation | private subnet, SG allowing only the app |
| backups in the production account | ransomware deletes data and backups | same blast radius | separate account, immutable, restore tests |
KMS key policy grants kms:* to everyone |
anyone can decrypt everything | key policy too broad | least privilege on keys; log and alert on key use |
Mini project: a mini IAM simulator
Combine Demos 1 and 3 into one simulator. (1) Store identity policies, a permissions boundary and an SCP for three principals. (2) Support Allow/Deny, wildcards and an explicit deny in any layer. (3) For each request print the final decision and which layer decided it. (4) Add a resource-based bucket policy that allows a principal from another account (cross-account). (5) Write five test cases with assert.
Practice
1. Fix Demo 1 so the web app can read only shop-images/*, while keeping the delete protection.
Solution
Remove the s3:* on shop-* statement:
POLICIES = {"role/web-app": [
{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "shop-images/*"},
{"Effect": "Deny", "Action": "s3:Delete*", "Resource": "*"}]}
Now shop-backups/db.sql -> DENY (no statement allows it).
2. Add an MFA requirement to the toy assume_role.
Solution
def assume_role(caller, seconds, mfa=False):
if caller not in ROLE["trust"]:
return "AccessDenied: not trusted to assume " + ROLE["name"]
if not mfa:
return "AccessDenied: MFA required"
return {"key": "ASIA-TOY-7F3A", "expires": NOW + min(seconds, ROLE["max_seconds"])}
3. Make the toy NACL check numbered rules in ascending order (first match wins), with a final deny.
Solution
RULES = [(100, "allow", 443, 443), (200, "deny", 1, 1023), (300, "allow", 1024, 65535)]
def nacl_out(port):
for num, action, lo, hi in sorted(RULES):
if lo <= port <= hi:
return f"{action} (rule {num})"
return "deny (default *)"
print(nacl_out(51515)) # allow (rule 300)
print(nacl_out(25)) # deny (rule 200)
4. Why can't an SCP that allows iam:AttachRolePolicy let the user in Demo 3 attach policies?
Solution
Effective permissions are the intersection of all layers. The boundary doesn't include the action, so it is excluded whatever the SCP says. SCPs and boundaries limit; they never grant.
5. Write a backup plan for a small online shop.
Solution
Daily database snapshots and object-storage copies, replicated to a separate backup account in a second region; immutable for 35 days; backup account access only via a break-glass role with MFA; monthly restore test into a test account; alerts on backup failure or deletion attempts.
Quick quiz
A: yes, the identity policy allows it
B: no, the boundary is a ceiling
C: yes, if an SCP also allows it
D: only on Mondays
A user's policy allows iam:AttachRolePolicy. Their permissions boundary doesn't. Can they attach it?
Answer
B. Effective permissions are the intersection of every layer. A permissions boundary never grants, it only limits.
Interview questions
- How does cloud IAM decide a request? Default deny; allow only if a policy allows it; any explicit deny wins; boundaries and SCPs cap the result (intersection).
- Why roles instead of access keys? Roles hand out short-lived temporary credentials; nothing permanent is stored to leak.
- What is a trust policy? The part of a role that says who may assume it (users, accounts, services), optionally with conditions like MFA.
- How do you give another account access safely? A role in your account whose trust policy trusts the other account, with least-privilege permissions; no shared credentials.
- Permissions boundary vs SCP? A boundary caps one user or role; an SCP caps every principal in an account or OU; neither grants.
- Security group vs network ACL? SG: instance level, allow only, stateful. NACL: subnet level, allow and deny, ordered, stateless.
- Why put databases in private subnets? No direct route from the internet; only the app's security group can reach them.
- What is a private endpoint? A private-IP doorway to a cloud service inside your VPC, so traffic needs no internet gateway.
- What is envelope encryption? Data encrypted with a data key; the data key encrypted by a KMS key and stored with the data.
- Customer-managed vs provider-managed keys? With a CMK you control the key policy and rotation and can disable it; provider-managed keys are controlled by the provider.
- What made the Capital One breach so large? An SSRF through a misconfigured WAF, and a role with access to far more buckets than it needed.
Glossary
| Term | Meaning |
|---|---|
| IAM | identity and access management: who can do what |
| principal | anything that makes a request: user, role, app, service |
| action | an operation such as s3:GetObject |
| resource | the thing acted on, e.g. a bucket |
| IAM policy | JSON statements that Allow or Deny actions on resources |
| statement | one Allow/Deny rule inside a policy |
| default deny | denied unless something allows it |
| explicit deny | a Deny statement; always overrides Allow |
| wildcard | * that matches anything |
| identity-based policy | attached to a user or role |
| resource-based policy | attached to a resource, e.g. a bucket policy |
| ARN | Amazon Resource Name |
| access key | a long-lived programmatic credential |
| role | permissions that principals assume temporarily |
| assume role | temporarily take on a role's permissions |
| STS | AWS Security Token Service, issues temporary credentials |
| trust policy | the role's list of who may assume it |
| temporary credentials | key ID, secret, session token and expiry from assuming a role |
| cross-account access | a role trusted by another account |
| privilege escalation | gaining more permissions than you were given |
| permissions boundary | a ceiling on a user's or role's permissions |
| SCP | service control policy: an organisation-wide ceiling for an account |
| guardrail | a central rule that cannot be broken |
| SSRF | server-side request forgery: tricking a server into making requests |
| WAF | web application firewall |
| VPC | virtual private cloud: your isolated cloud network |
| subnet | an address range inside a VPC |
| internet gateway | the VPC's door to the internet |
| public / private subnet | with / without a direct internet route |
| security group | stateful instance-level firewall, allow rules only |
| network ACL | stateless subnet-level firewall, ordered allow/deny rules |
| stateful / stateless | remembers connections / checks each packet alone |
| ephemeral ports | temporary high ports clients use |
| private endpoint | a private-IP doorway to a cloud service inside your VPC |
| PrivateLink | AWS's private endpoint technology |
| bucket policy | a resource-based policy on a bucket |
| encryption at rest | data encrypted while stored |
| SSE-S3 | S3 server-side encryption with S3-managed keys |
| KMS | key management service |
| HSM | hardware security module |
| customer-managed key | a KMS key whose policy and rotation you control |
| AWS managed key | a KMS key managed by AWS for a service |
| key rotation | replacing key material on a schedule |
| envelope encryption | data key encrypts data; KMS key wraps the data key |
| data key | the key that encrypts the actual data |
| backup | a restorable copy |
| immutable backup | can't be changed or deleted until a set date |
| restore test | regularly restoring to prove backups work |
| 3-2-1 rule | 3 copies, 2 media, 1 off-site |
Summary
- IAM policies: principal, action, resource; default deny; explicit deny wins; avoid wildcards.
- Roles and temporary credentials replace permanent keys; trust policies say who may assume them.
- Permission boundaries and SCPs are ceilings; effective permissions are the intersection.
- VPCs and subnets isolate; security groups are stateful, NACLs stateless; private endpoints avoid the internet.
- Bucket policies, default object encryption, and KMS customer-managed keys protect stored data.
- Backups belong in a separate account, immutable, and tested.
- Next episode: infrastructure as code and cloud-native security platforms.
Sources (fetched 13 Nov 2026)
- AWS IAM, policy evaluation logic: https://docs.aws.amazon.com/IAM/latest/UserGuide/AccessPolicyLanguage_EvaluationLogic.html
- AWS CLI reference, sts assume-role: https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html
- AWS VPC, infrastructure security (security groups vs network ACLs): https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html
- AWS PrivateLink, access AWS services: https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-aws-services.html
- AWS What's New, S3 encrypts new objects by default (Jan 2023): https://aws.amazon.com/about-aws/whats-new/2023/01/amazon-s3-automatically-encrypts-new-objects
- AWS KMS FAQs: https://aws.amazon.com/kms/faqs/
- Rackspace, Capital One data breach: https://docs.rackspace.com/blog/capital-one-data-breach-two-security-controls-you-should-review/