Skip to content
Tech Interview Prep
Technical interview guide

Cloud-Native Network Security

Security groups, network ACLs, and private networking that control traffic flow within a cloud environment.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: AWS VPC, Azure networking/Private Link, Google Cloud NGFW, and NIST SP 800-207 guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Explain and combine AWS security groups and network ACLs.

Answer

What a strong candidate says first

They are two filters at two different layers, and only one of them is stateful.

Security groups attach to an elastic network interface: an EC2 instance, an RDS instance, a Lambda ENI, a load balancer node. They are allow-only: there is no deny rule, and all rules are evaluated together as a union, so order is irrelevant. They are stateful: once a flow is permitted inbound, the response is permitted outbound automatically, and vice versa. A newly created security group denies all inbound and all outbound until you add rules. The VPC's default security group is the exception: it allows all inbound from members of itself and all outbound, and it cannot be deleted.

Network ACLs attach to a subnet, so one rule set covers every resource in it. They have both allow and deny rules, numbered 1–32766, evaluated lowest-number-first with first match winning. They are stateless: the request and the reply are evaluated independently, and the reply's destination port is an ephemeral port, not the service port. A new custom NACL denies everything until you add rules; the default NACL allows all inbound and outbound on rule 100.

Where each one earns its place

Use security groups as the primary control, scoped to the workload role, and reference other security groups as sources rather than CIDRs: a rule allowing TCP 5432 from sg-rds-clients survives an IP renumbering. Add NACLs for the two things security groups cannot do: a coarse subnet-level guardrail, and an explicit deny. Blocking a specific CIDR after a compromise is a NACL job; a security group can only fail to allow it.

Security groupNetwork ACL
Attaches toENISubnet
RulesAllow only, unordered unionAllow and deny, numbered, first match wins
StateStatefulStateless
Default when newDeny all in and outDeny all in and out
VPC defaultAllow all in from self, all outAllow all in and out, rule 100
Default quota60 in + 60 out rules; 5 SGs per ENI20 rules per NACL
Same-subnet trafficEvaluatedNot evaluated

That last row matters: two instances in the same subnet talk to each other without the NACL seeing the packets, so a NACL deny you added for a subnet does not isolate those two from each other.

Failure modes

Missing ephemeral return rule. NACL outbound allows TCP 443 to the server, the server subnet's NACL inbound allows TCP 443 from the client, and the connection still hangs. The SYN-ACK comes back from server port 443 to the client's ephemeral port, and the server subnet's NACL outbound has no rule for it. Client-side tcpdump shows repeated SYN with no SYN-ACK; Reachability Analyzer reports the blocking component. The ranges to allow: 1024–65535 for traffic from a NAT gateway or an ELB, 32768–60999 for a Linux client's default ip_local_port_range, 49152–65535 for Windows.

Rule order. A deny at rule 100 for 0.0.0.0/0 beats an allow at rule 200 for 10.0.2.0/24. Adding the allow at 32766 changes nothing.

Asymmetric NACLs across AZs. Subnet A's NACL allows outbound to subnet B, but subnet B's NACL has no matching inbound rule. Works one way, fails the other; the symptom is a one-directional timeout that looks like an application bug.

Default security group drift. An instance launched without an explicit security group lands in the default one, which allows all inbound from every other member of the default security group. That is lateral movement inside the VPC.

Rule quota. At 60 inbound rules per security group you start merging CIDRs; a /24 that should have been a prefix list is the usual cause.

Diagnosing

VPC Flow Logs give per-ENI ACCEPT/REJECT records with srcaddr, dstaddr, srcport, dstport: enough to see which direction stopped. Reachability Analyzer tests a path between two ENIs and names the blocking component. Neither replaces reading the NACL rule numbers in order.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Explain why private networking is not zero trust.

Answer

Zero trust is a decision model, not a topology. NIST SP 800-207 (final, August 2020) assumes no implicit trust in an asset or account because of its physical or network location, and its tenets state that all communication is secured regardless of network location. A VPC, an RFC 1918 range, a VNet peering or an AWS PrivateLink endpoint answers one question: can this host reach that service? It does not say who is calling or whether that caller may do the thing. A control that reads "the packet came from 10.0.0.0/16" is a perimeter, not zero trust.

Private routing earns its place: it removes unsolicited internet exposure and keeps traffic on a path you control. The mistake is letting reachability substitute for authorization. Four places that happens:

  • East-west is allow-all by default. Kubernetes NetworkPolicy (networking.k8s.io/v1, stable since 1.7) only restricts a pod once a policy selects it, and only if the CNI enforces policy: Calico and Cilium do, a plain flannel install does not. So a pod in a private /16 can open a connection to any of 65,536 addresses when the only thing it needs is one service on one port.
  • A mesh is not automatically mTLS. Istio's mesh-wide default PeerAuthentication is PERMISSIVE: a sidecarred service still accepts plaintext from anything that can route to it, and only STRICT rejects it. "We run a service mesh" and "this request carried a verified workload identity" are different claims.
  • Humans on the private path collapse into one network identity. Split-tunnel VPN clients, contractor laptops and a shared bastion all originate trusted-range packets, so a stolen VPN session looks like a legitimate engineer.
  • Static secrets on a private path never earn rotation. A database reachable only through a private endpoint, with a password sitting in a ConfigMap, grants ambient authority to whoever reads the file.
QuestionPrivate network answersZero trust answers
Who sent this?source IP in 10.0.0.0/16mTLS cert subject, or a SPIFFE ID such as spiffe://prod.example/ns/payments/sa/ledger
May they do this?port and CIDR ACL, staticpolicy on identity, method, resource
Re-decided when?at connection setupevery request, on current device and context
Revoked how?edit the ACLexpire or rotate the SVID

Failure modes and detection. Trusting source IP inside the application: detect with VPC Flow Logs or Cilium Hubble flagging a workload-to-destination pair never seen before, and alert on new pairs rather than on volume; the operational cost is that containment is coarse, because you cannot revoke one compromised pod's identity, so you cut the subnet and break healthy callers with it. PERMISSIVE mesh drift: istio_requests_total with connection_security_policy="none" staying non-zero after the migration you thought finished, which becomes an outage the day you flip to STRICT. Long-lived shared secrets: a credential used from a workload or SPIFFE ID that never used it before. SPIRE issues X.509 SVIDs with a 1-hour default TTL, so a hypothetical mesh of 10,000 workloads rotates roughly 240,000 SVIDs a day, which is why a stolen SVID is worth little and a ConfigMap password is worth a lot.

Alternatives and deciding criteria. Private routing is cheap, needs no application change and satisfies data-residency rules; workload identity via SPIFFE/SPIRE or Istio STRICT, plus cloud IAM such as IAM roles for service accounts or SigV4 for API authorization, costs a trust bundle, a rotation pipeline and per-service policy work. The criterion that settles it: does the control distinguish one caller from another, and can it be re-evaluated per request? If it only says "same network," it is exposure reduction, not authorization. Private-only is defensible for a low-value service on a single-tenant network with no untrusted peers and no shared secrets, and even then it is a recorded risk acceptance rather than zero trust.

Prove independence from a real boundary: a valid internal address with no valid identity must fail, and a valid identity from a disallowed device or context must fail. Either one succeeding means private networking is standing in for zero trust.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Move a managed database from public access to a private endpoint.

Answer

Assume Azure SQL Database with public network access enabled, clients in three VNets (two in East US, one in West Europe) and an on-prem network via ExpressRoute. The server has a firewall rule allowing 0.0.0.0/0.

The short answer: create a private endpoint in each VNet that needs access, approve the private endpoint connection on the SQL server, link a private DNS zone privatelink.database.windows.net to those VNets, then disable public network access. The private endpoint is a network interface with a private IP in your subnet. DNS override makes the server's hostname resolve to that IP. Clients never traverse the internet. The key mechanism is that Private Link is one-way: the client initiates a connection to the private endpoint's private IP, and the private endpoint forwards it to the SQL server over the Azure backbone. The SQL server never initiates connections back to the client.

Here's how I'd do it. First, inventory consumers. Use Azure Monitor logs, SQL audit logs, or NSG flow logs to find source IPs. Check the DNS TTL on the server's CNAME. It's typically short, but clients may cache longer. That matters because when you flip DNS, old clients may keep using the public IP until their cache expires.

Second, create the private endpoint. In the Azure portal, go to the SQL server's Networking blade, select Private endpoint connections, and create a new private endpoint. Choose the VNet and subnet. The private endpoint gets a private IP, say 10.0.1.5. Ensure the subnet has enough free IPs; a /24 subnet gives 251 usable. Approve the connection on the SQL server. Repeat for each VNet. If you have a VNet in another region, you need a private endpoint in that region or VNet peering. Azure SQL supports up to 1000 private endpoints per server, so check limits if you have many VNets.

Third, DNS. Create a private DNS zone named privatelink.database.windows.net. Link it to each VNet. The private endpoint automatically creates an A record for yourserver pointing to 10.0.1.5. For on-prem, configure conditional forwarders on your DNS servers to forward database.windows.net to Azure DNS (168.63.129.16) or use Azure DNS Private Resolver. Without this, on-prem clients resolve to the public IP and fail.

Fourth, validate. From a VM in each VNet, run nslookup yourserver.database.windows.net. It should return 10.0.1.5. Test a connection with sqlcmd or your app. From outside, confirm it fails.

Fifth, cutover. Migrate clients in waves: non-production first, then production. Monitor connection failures. Once all clients use the private endpoint, disable public network access in the SQL server's Networking blade. Remove the 0.0.0.0/0 firewall rule.

Tradeoffs. Private endpoint vs service endpoint: Service endpoints allow access from a subnet to the SQL server's public IP, but the server still has a public IP and public access must be enabled. Private endpoint gives a private IP and lets you disable public access. Private endpoint vs firewall allowlist: You could keep public access but restrict to on-prem IPs. That's simpler but leaves the database publicly reachable. Staged cutover vs big-bang: Staged reduces risk but requires dual access (public and private) during transition. Big-bang is faster but riskier.

Failure modes. DNS caching: clients that resolved the public IP before the change keep using it until TTL expires. Detection: connection errors after disabling public access. Mitigation: lower TTL before cutover, or restart clients. On-prem DNS: missing conditional forwarders cause on-prem clients to resolve to public IP and fail. Detection: on-prem clients cannot connect. Mitigation: configure forwarders. Cross-region: private endpoints are regional. A VNet in another region without a private endpoint or peering will fail. Detection: connection timeout from that region. Mitigation: create a private endpoint there or peer VNets.

Here's a DNS resolution trace. Before: client queries yourserver.database.windows.net. Public DNS returns the public IP. After: public DNS returns CNAME yourserver.privatelink.database.windows.net. If the client's VNet is linked to the private DNS zone, the resolver finds A record 10.0.1.5. If not, the CNAME resolution fails with NXDOMAIN.

OptionPublic exposureDNS changeComplexity
Private endpointNonePrivate DNS zoneMedium
Service endpointPublic IP remainsNoneLow
Firewall allowlistPublic IP remainsNoneLow

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Secure a managed database network boundary.

Answer

Assumptions: one managed Postgres/SQL Server instance, app in the same VPC/VNet, no public access required.

What a strong candidate says first. The boundary is three layers that fail independently: reachability, identity, transit. Kill the public path first: RDS publicly_accessible = false, Azure SQL public network access Disabled, Cloud SQL delete the public IP. Then attach private connectivity: RDS is VPC-native, so the endpoint resolves to a private IP inside the VPC; Azure SQL and Cloud SQL need Private Link / Private Service Connect. Bind the endpoint to that one service, not a shared one. Link the private DNS zone, or clients keep resolving the public name and either fail or bypass the endpoint. On the DB side, allow only the app security group on the DB port: never a CIDR. Split admin (bastion + MFA) from app and replication paths. Enforce TLS with server validation, and use database-level auth (IAM / Entra ID) so a network allow is not authorization.

Control map

LayerAWS RDSAzure SQLCloud SQL
Public pathpublicly_accessible = falsePublic network access = DisabledDelete public IP
Private pathVPC-native private IPPrivate Endpoint (Private Link)Private Service Connect or private IP
Private DNSnot neededlink privatelink.database.windows.net to the VNetPSC endpoint DNS; private IP needs none
Network allowSG ingress from app SG on 5432NSG on the PE subnetVPC firewall, authorized networks removed
TLSrds.force_ssl=1 (PG), require_secure_transport=ON (MySQL)minimum TLS 1.2 (always encrypted)sslMode=ENCRYPTED_ONLY
DB authIAM database authenticationEntra ID authIAM database authentication

Terraform, AWS RDS

HCL
resource "aws_db_instance" "app" {
  identifier             = "app-db"
  engine                 = "postgres"
  engine_version         = "16.3"
  publicly_accessible    = false
  db_subnet_group_name   = aws_db_subnet_group.db.name
  vpc_security_group_ids = [aws_security_group.db.id]
  parameter_group_name   = aws_db_parameter_group.pg.name
}

resource "aws_db_parameter_group" "pg" {
  name   = "app-db-pg"
  family = "postgres16"
  parameter {
    name  = "rds.force_ssl"
    value = "1"
  }
}

resource "aws_security_group_rule" "app_to_db" {
  type                     = "ingress"
  from_port                = 5432
  to_port                  = 5432
  protocol                 = "tcp"
  security_group_id        = aws_security_group.db.id
  source_security_group_id = aws_security_group.app.id
}

The DB security group's default egress is allow-all; replace it with KMS, the S3 gateway endpoint, and monitoring only.

Worked trace (representative run, psql 16.3 against RDS Postgres 16.3)

$ dig +short app-db.abc123.us-east-1.rds.amazonaws.com
10.0.2.14                      # private IP in the DB subnet, no public address

$ psql "host=app-db.abc123.us-east-1.rds.amazonaws.com dbname=app user=app \
        sslmode=verify-full sslrootcert=global-bundle.pem"
psql (16.3, server 16.3)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
app=>

Two ways it breaks. Drop the SG rule and the packet is dropped, not refused:

$ psql "host=app-db... sslmode=verify-full"
psql: error: connection to server at "app-db..." (10.0.2.14), port 5432 failed: timeout expired

Connect without TLS while rds.force_ssl=1:

$ psql "host=app-db... sslmode=disable"
psql: error: ... FATAL:  no pg_hba.conf entry for host "10.0.1.7", user "app", database "app", no encryption

Failure modes. Private endpoint created but the private DNS zone is not linked → the client resolves the public IP and either times out or goes public; check with dig from the client subnet. SG ingress 0.0.0.0/0 on 5432 → public exposure; catch with AWS Config or Azure Policy. Admin and app sharing one SG → lateral movement; VPC flow logs show the admin port from the app subnet. Unrestricted DB egress → exfiltration path; flow logs to unexpected destinations.

Trade-offs. Private endpoints cost roughly $0.01/hr per endpoint plus $0.01/GB processed (list prices, AWS/Azure/GCP) and add DNS and multi-region complexity. RDS private IP is free but unreachable from outside the VPC without a bastion or VPN. If a partner must connect, put a proxy in front with an IP allowlist, TLS, and strong auth: never open the DB port to 0.0.0.0/0. If the DB is already VPC-native and only the app talks to it, a private endpoint is redundant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Secure an internet-facing application load balancer and its backends.

Answer

Assumptions: AWS ALB in a public subnet, EC2/ECS targets in private subnets, one VPC, clients on IPv4 and IPv6. The same shape applies to a GCP HTTPS LB or an nginx edge, with different names.

The 90-second answer. An internet-facing ALB is two boundaries, not one. The frontend is the listener the internet reaches; the backend is the target group the ALB reaches. Secure them independently, because a rule on one does not govern the other.

Frontend: exactly two listeners. Port 443 open to 0.0.0.0/0 and ::/0, TLS 1.2 minimum (1.3 where the security policy supports it), an ACM-managed certificate, HSTS. Port 80 open only to issue a 301 to https: no application content. Attach AWS WAF with the managed core rule set plus a rate-based rule (for example 2000 requests per 5 minutes per IP) and leave Shield Standard on; it is automatic.

Backend: the target security group allows the application port only from the ALB's security group ID, never 0.0.0.0/0. Security-group referencing is resolved at the ENI, so it survives IP changes and covers ALB health checks, which originate from the ALB nodes themselves.

Why the details matter. Health-check source depends on the LB type. An ALB health-checks from its own nodes, so the ALB SG reference covers it. An NLB with client-IP preservation health-checks from the NLB subnet CIDR, so you must allow that CIDR explicitly: a rule that only allows the ALB SG silently fails health checks and drains targets.

X-Forwarded-For is spoofable because the client sets it. ALB appends the real client IP, so a request arriving with X-Forwarded-For: 1.2.3.4 from client 203.0.113.7 leaves as 1.2.3.4, 203.0.113.7. An app that reads the leftmost value trusts the attacker; read the rightmost hop your proxy added, or configure a trusted proxy count. Same for X-Forwarded-Proto: trust it only from the proxy.

Trade-offs. SG referencing is the cheapest backend control and works inside one VPC. When backends live in another VPC or account, use PrivateLink (interface endpoint) so the backend has no public path at all. When you must authenticate the client at the edge, terminate mTLS on the ALB with a trust store: heavier to operate, but it moves auth to the boundary instead of every app.

Failure modes to test. Direct-to-backend: if a target has a public IP or a permissive SG, the ALB is bypassable. Curl the target IP directly. Alternate port: scan for the app port open on the target. Spoofed header: send a forged X-Forwarded-For and confirm the app logs the real client. IPv6: an IPv4-only SG rule leaves ::/0 open on dual-stack.

BoundaryPortSource
ALB SG in4430.0.0.0/0, ::/0
ALB SG in800.0.0.0/0, ::/0 (301 only)
Backend SG inapp (8080)ALB SG id
Backend SG inhealth checkALB SG id (ALB) / NLB subnet CIDR (NLB)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Protect workloads from cloud metadata credential theft.

Answer

What I'd say first

The metadata service is an unauthenticated HTTP endpoint on a link-local address (169.254.169.254 on AWS, GCE and Azure) that hands the instance's IAM credentials to any process that can make an HTTP request from that host. An SSRF in your app is therefore a credential-theft primitive, not a nuisance. I'd assume AWS EC2/EKS as the primary case and flag where GCE and Azure differ.

Three layers, ordered by how much they survive a real SSRF:

  1. Take the credential off the endpoint. Move pods to IRSA / EKS Pod Identity / GKE Workload Identity / Azure Workload Identity, so they get short-lived, scoped tokens via OIDC and IMDS has nothing worth stealing. This is the only layer that holds against an SSRF that can send arbitrary methods and headers.
  2. Make the endpoint require something a naive SSRF can't supply. Enforce IMDSv2 (HttpTokens=required). IMDSv2 is session-oriented: a PUT /latest/api/token with X-aws-ec2-metadata-token-ttl-seconds (max 21600) mints a token, and every subsequent GET needs X-aws-ec2-metadata-token. The common SSRF (fetch a URL, read the body) gets a 401.
  3. Restrict who can reach it. HttpPutResponseHopLimit=1 (the AWS default) drops the token response if it has to cross a network hop, so a container on a bridge network can't mint one. That's the control that keeps a compromised pod from reading the node's instance role.
# IMDSv1 — what a GET-only SSRF does
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
# -> 200 with AccessKeyId / SecretAccessKey / Token

# IMDSv2 — same GET, no token
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
# -> 401 Unauthorized

# IMDSv2 token mint, then the same GET
TOKEN=$(curl -X PUT http://169.254.169.254/latest/api/token \
  -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name
# -> 200
ProviderEndpointRequired header/tokenWithout it
AWS169.254.169.254, fd00:ec2::254 (IPv6)IMDSv2 PUT token401
GCEmetadata.google.internalMetadata-Flavor: Google403
Azure169.254.169.254Metadata: true400

Trade-offs. Full disable (HttpEndpoint=disabled) is the strongest single control, but it breaks everything on the default credential chain (SDKs, node agents, kubelet) so you migrate to IRSA first and disable second. Token enforcement is cheap and reversible but only stops header-naive SSRF; a full SSRF that can issue PUT still mints a token. A metadata proxy sidecar that allowlists paths gives per-path control at the cost of another component to run and patch.

Failure modes. Hop limit 1 silently breaks pods that legitimately need IMDS: you see credential-chain 401s in application logs, not a clear platform error, so roll it out per-namespace. And you cannot block IMDS with a security group: link-local traffic is handled by the hypervisor and never hits SG/NACL evaluation, so the block has to be host iptables or the container network namespace. Detect theft with GuardDuty InstanceCredentialExfiltration findings and CloudTrail showing the instance role used from an unexpected IP; VPC flow logs won't show link-local traffic at all. Test the SSRF, proxy, container and IPv6 paths, and confirm you can revoke the role's sessions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Secure DNS across private cloud networks.

Answer

Core answer. Assume multi-VPC AWS, Direct Connect to on-prem, Route 53 Resolver, internal names under internal.example.com. Two rules make the whole thing safe: every internal name lives in a private hosted zone that is authoritative for it and associated with exactly the VPCs that need it, and every resolver path is either inside a trusted network or encrypted. A private endpoint resolving publicly is almost always a missing VPC association on the private zone: the query falls through to the public resolver and returns the public record.

Find the leak. Inventory every private zone, its VPC associations, and its records. Defaults: 100 VPC associations per private hosted zone (soft limit, raisable by request), 500 private hosted zones per account, 10,000 records per zone. Then check for split-horizon: the same name in a public and a private zone. Turn on Resolver query logging (CloudWatch Logs, S3, or Firehose) and look for queries for internal names answered by a public resolver; 30-day retention is enough for incident work and keeps ingestion cost bounded.

Hybrid. Inbound endpoints let on-prem resolve cloud names; outbound endpoints let cloud resolve on-prem names. Each endpoint takes up to 10 IP addresses, so spread them across AZs and point on-prem conditional forwarders at all of them. Inbound endpoints accept DoH on port 443 (added in 2021), so on-prem clients can encrypt that hop directly: no VPN needed for DNS. DoT is not supported on Resolver endpoints. Outbound endpoints forward on port 53, so encrypting that hop means IPsec VPN or MACsec on the Direct Connect, or a self-managed resolver (BIND or Unbound) that speaks DoT/DoH.

Rebinding and exfiltration. Rebinding: an attacker's public zone answers with a private address and a short TTL, and the client connects inward. The structural fix is that private zones are authoritative for every internal name, so nothing internal ever resolves from public data; DNS Firewall blocks the malicious domains, and egress rules should allow UDP/TCP 53 only to your resolver IPs. Exfiltration: data encoded in subdomains of an attacker-controlled domain. DNS Firewall blocks known-bad domains; query logging surfaces the tell: long labels, high NXDOMAIN rates, one client talking to one domain.

Wildcards. *.internal.example.com in a private zone is fine if it points at internal addresses. The same wildcard in a public zone answers for names you never defined, which is how a private endpoint ends up with a public IP.

Route 53 Resolver endpointsSelf-managed BIND/Unbound on EC2
Cost$0.125/hr per endpoint IP + per-queryEC2 (t3.medium ≈ $0.0416/hr in us-east-1) + your ops time
OpsAWS patches and scalesYou own HA, patching, upgrades
FeaturesDNS Firewall, query logging, VPC-native, DoH on inboundRPZ, custom views, arbitrary DoT/DoH
Pick whenSmall team, AWS-native, compliance wants managedYou need RPZ or custom views, or already run DNS

A typical HA pair (one inbound and one outbound endpoint, 2 IPs each in two AZs) is 4 IP-hours × $0.125 = $0.50/hr, about $360/month before query charges.

Failure modes. Inbound endpoint ENIs in one AZ: an AZ event takes on-prem resolution down; detection is timeouts in on-prem resolver logs, mitigation is IPs in at least two AZs plus health monitoring. Bad record pushed to a private zone: roll back via Terraform, and stage zone changes in a non-production VPC first. Query logging is not real-time enough to be the only detection: pair it with an alarm on NXDOMAIN rate.

Trace. On-prem client resolves app.internal.example.com. Its resolver has a conditional forwarder for internal.example.com to inbound endpoint IPs 10.0.1.5 and 10.0.2.5. The query hits 10.0.1.5 over DoH on 443. The Resolver finds the private zone internal.example.com, which is associated with the app VPC, and returns A 10.0.2.10, TTL 60. The client connects to 10.0.2.10:443 and the cert SAN matches.

Leak variant: a new VPC is not associated with the private zone. A client there queries the same name. The Resolver has no private zone for it, forwards to the public resolver, and gets the public A record 203.0.113.5 (documentation range). The client connects to 203.0.113.5:443. TLS either fails on name mismatch or succeeds against the public-facing endpoint: either way internal traffic is now crossing the public path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Secure network access for a serverless function calling private services.

Answer

What I'd say first

Two questions decide this: which private services does the function actually call, and does it need any public egress at all? I'll assume AWS Lambda calling a private RDS instance and an internal HTTP service, with no public internet needed. Then the answer is: attach the function to private subnets, reach AWS services through VPC endpoints, reach the database through RDS Proxy, and only add a NAT gateway if something genuinely needs the public internet.

Why attachment changes everything

A Lambda outside a VPC runs in an AWS-managed network with internet access and can reach public AWS endpoints directly. Attaching it to your VPC moves its ENI into your subnets, so routing becomes your route tables' problem. Private subnets with no NAT route have no internet: that's the point, not a bug. The cold-start cost is smaller than it used to be: Lambda creates Hyperplane ENIs shared per (subnet, security group) pair, so the first invocation in a new combination pays roughly 10–90 seconds, and later functions reusing that pair don't.

The connection problem

The classic failure is connection exhaustion, and it has two layers.

NAT gateway: it supports 55,000 simultaneous connections per unique destination (IP:port:protocol). A Lambda fleet at 1,000 concurrency each opening a connection to the same DB host:port can hit that ceiling. Symptom: intermittent connect timeouts under load, and the ErrorPortAllocation CloudWatch metric climbing.

Database: 1,000 Lambdas each holding a DB connection will exhaust max_connections on a small RDS instance long before the NAT limit. RDS Proxy pools and multiplexes: it holds a small pool and lets many function invocations share it. It adds a few milliseconds and costs about $0.015 per vCPU-hour of the underlying instance, cheap next to a connection storm.

Choosing the path

PathCostWhen
No VPC$0Function only calls public AWS APIs
VPC + gateway endpoint (S3, DynamoDB)FreeThose two services only
VPC + interface endpoint (PrivateLink)~$7.30/mo per AZ + $0.01/GBPrivate access to AWS services, no internet
VPC + NAT gateway~$32/mo + $0.045/GBGenuine public egress needed
VPC + RDS Proxy~$0.015/vCPU-hrAny Lambda→RDS at scale

Locking it down

Give the function its own execution role and its own security group. The security group should allow outbound only to the specific endpoint SG or DB SG on the specific port, not 0.0.0.0/0. Don't let unrelated functions share a privileged connector role or SG; that turns one compromised function into lateral movement. If EC2 or ECS shares the subnet, enforce IMDSv2 with hop limit 1 so an SSRF in the function can't read instance credentials from 169.254.169.254. Lambda's own credentials come from the execution role via environment variables, so scope that role to the exact actions and resources.

Failure modes and how you'd see them

  • Subnet IP exhaustion: Hyperplane ENIs need free IPs. Symptom: function fails to initialize, ENILimitReached in logs. Watch subnet IP utilization.
  • DNS: VPC-attached Lambda uses the Route 53 Resolver at VPC CIDR+2. If you point it at a custom resolver without forwarding private zones, private hostnames fail with UnknownHostException.
  • NAT exhaustion: ErrorPortAllocation metric, connect timeouts at peak concurrency.
  • Cross-environment access: a function in prod reaching a staging DB because the SG is shared. Detect with VPC Flow Logs and CloudTrail, correlating function identity → connector → flow → application log.

Test before you ship

Deny public fallback and confirm the function fails closed, not open. Confirm cross-environment access is refused. Load-test to the concurrency you expect and watch NAT and DB connection counts, not just error rates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Diagnose an intermittent private-endpoint connectivity failure.

Answer

What a strong candidate says first (60–120 s)

"First I'd split two cases: one client that fails sometimes, versus some clients that always fail. Different causes. I'll assume Azure Private Link: a private endpoint in VNet A, clients in a peered VNet B, DNS served by a Private DNS zone privatelink.blob.core.windows.net, endpoint connection state Approved.

Intermittent failures here come from three mechanisms: DNS handing back a mix of private and public answers, a stateful hop dropping an idle flow, or SNAT port exhaustion on the client. I'd capture the failing client's resolved IP and the 5-tuple at the moment of failure: that one observation usually picks the branch. Then I fix the smallest authoritative layer: if the answer is wrong, fix DNS, not the firewall."

Mechanism 1: DNS returns a mixed answer. A client that resolved the public IP before the private endpoint existed keeps using it until its TTL expires. The private DNS zone record points at the endpoint's NIC address; the public record still resolves to the service's public IP. If public access is disabled on the service, the cached client fails while a freshly-resolved client succeeds, which looks intermittent but is a cache.

Worked trace (illustrative figures):

  1. T−30 min: client resolves contoso.blob.core.windows.net → public 20.1.2.3, TTL 3600 s, cached locally.
  2. T0: private endpoint created; zone record contoso.privatelink.blob.core.windows.net → 10.0.1.4, TTL 10 s, zone linked to VNet A and B.
  3. T0 → T+60 min: the client still uses 20.1.2.3 and fails; clients that re-resolved get 10.0.1.4 and succeed.
  4. Detection: nslookup contoso.blob.core.windows.net on the failing host returns 20.1.2.3, on a working host 10.0.1.4. Fix: flush the resolver cache (ipconfig /flushdns, resolvectl flush-caches) and confirm the zone is linked to both VNets.

Mechanism 2: a stateful hop drops an idle flow. Azure Load Balancer's default TCP idle timeout is 240 s; an NSG or firewall in the path tracks the flow and silently drops the next packet after idle. Detection: flow logs show a SYN with no SYN-ACK, or a RST, roughly 240 s after the last packet. Fix: raise the idle timeout or enable TCP keepalive on the client.

Mechanism 3: SNAT port exhaustion. Default SNAT allocation is 1024 ports per backend instance. A client opening 200 connections/min, each held 240 s, holds 200 × 4 = 800 ports in steady state; add a second workload and you cross 1024, so new SYNs are dropped intermittently. Detection: the Used SNAT Ports metric approaching 1024, or flow logs showing unanswered SYNs.

SymptomMechanismDetection
Fails on some hosts, alwaysDNS cache holding public IPnslookup differs between hosts
Fails after ~4 min idleNSG/LB idle timeoutflow log: RST/no ACK after 240 s
Fails under load, recoversSNAT exhaustionUsed SNAT Ports → 1024
Fails from one subnet onlyUDR sends return path publiceffective routes + traceroute

Trade-offs. The fix belongs at whichever layer produced the wrong answer. Linking the DNS zone is narrow and correct; adding a broad firewall allow rule to "make it work" hides a DNS bug and widens exposure; changing a UDR is right only when the return path is genuinely asymmetric. Deciding criterion: does the failing client's resolved IP match the endpoint's private address? If not, it's DNS.

Failure modes and detection. Asymmetric routing: return traffic leaves via the public path and a stateful firewall drops it; detect with traceroute from both ends plus the effective route table. Policy propagation: NSG and route changes take minutes to apply, so don't chase a fix that hasn't landed. Endpoint approval: a Pending or Rejected connection state fails every client; check az network private-endpoint show. Verify the fix by re-running the probe from the same identity and subnet, and confirm public fallback is denied.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Maintain equivalent IPv4 and IPv6 exposure controls.

Answer

Assumption to state up front: IPv6 is not a translation of IPv4. It is a second, independently routable path to the same service, with its own addresses, its own route-table entries and its own firewall rule family. "Equivalent controls" therefore means one policy source that emits both families, plus a detection loop that catches anything that got only one.

Why v6 drifts (the mechanism). Four things make it diverge from v4 without anyone deciding to:

  • SLAAC. A host with accept_ra=1 (the Linux default when forwarding is off) forms its own address from the router advertisement. No DHCP lease, no inventory entry, no ticket. RA Guard (RFC 6105) on the access switch is what stops a rogue or misconfigured RA from handing out a prefix.
  • /64 subnets. AWS hands a VPC a /56 and each subnet a /64: 2^64 addresses. You cannot scan that. Exposure is found through DNS AAAA records, flow logs and route tables, not through a port scan.
  • No NAT. A host that was hidden behind NAT44 is now globally addressed. The v4 rule that said "only the load balancer is reachable" has no v6 equivalent unless you write it.
  • Separate rule families. In AWS a security-group rule for 0.0.0.0/0 does nothing for IPv6; you need a second rule for ::/0. Same for NACLs, same for GCP firewall rules, same for nftables.

The decision. Two credible approaches:

  • Policy-as-code, single source. One Terraform module or policy file that takes a service and emits both families, with a CI check that fails when a rule set has a v4 entry with no v6 twin. I'd pick this above a handful of services, because the failure mode is omission and omission is exactly what a generator prevents.
  • Per-family review. Two independent reviews, one per family, on the theory that a shared generator can emit a wrong rule twice. Defensible for a small static estate; it scales badly and re-introduces the human omission you were trying to remove.

Where native v6 beats translation: NAT64/DNS64 lets you keep v4-only firewall semantics and buys time, but it hides source addresses in logs, breaks anything that embeds addresses end-to-end, and does nothing for inbound. Use it as a migration bridge, not as the control.

Failure modes, concretely.

  • A security group allowing 22/tcp from 0.0.0.0/0 and, because a copy-paste tool emitted both families, also from ::/0. Detection: a CI diff flagging any ::/0 ingress on a management port, plus VPC Flow Logs filtered on action=ACCEPT with a v6 source.
  • An AAAA record added for a staging host whose firewall only has v4 rules. The host is now reachable over v6 with no policy at all. Detection: reconcile the DNS zone against the rule set. Every AAAA must have a matching v6 rule.
  • ICMPv6 blocked wholesale because someone mirrored the v4 ICMP policy. IPv6 needs ICMPv6 for Neighbor Discovery and Path MTU Discovery; blocking it breaks connectivity in ways that look like random packet loss. Detection: allow ICMPv6 types 1-4 and 128-137 at minimum.

Worked check. One service, api.example.com, dual-stack.

layerv4v6equivalent?
DNSA → 203.0.113.10AAAA → 2001:db8:1::10yes
LB listener0.0.0.0/0:443::/0:443yes
SG ingress443 from 0.0.0.0/0443 from ::/0yes
SG ingress mgmt22 from 10.0.0.0/8missingno
Route0.0.0.0/0 → IGW::/0 → IGWyes

The missing row is the whole point: the v4 management path is scoped to the private range, and the v6 twin was never written, so the host is either unreachable over v6 (benign) or reachable via a default ::/0 rule someone added later (not benign). The check is mechanical: every row has both columns filled or an explicit "not exposed on this family" note.

First minute, spoken: assume v6 is a second path, generate both families from one source, and reconcile DNS against firewall rules, because AAAA records are where exposure appears before anyone writes a rule.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Introduce default-deny egress for cloud workloads.

Answer

Assume AWS, private subnets, workloads on EC2 or EKS. Security groups are stateful and start with an outbound 0.0.0.0/0 allow; NACLs are stateless. Default-deny egress means deleting that rule and adding only what each workload needs. The same pattern maps to Azure NSG + Azure Firewall + Private Endpoints, and GCP VPC firewall rules + Cloud NAT + Private Service Connect.

In the first minute: inventory, classify, route, block metadata, test, roll out. The mechanism matters. For AWS services, use VPC endpoints so traffic stays on the AWS network. For internet APIs, use a firewall or forward proxy that can allowlist by domain. Use NAT only for IP-based allowlists. Block 169.254.169.254 by default and enforce IMDSv2 with hop limit 1; SSRF can otherwise steal instance credentials.

Inventory from architecture and owners, VPC Flow Logs, and Route 53 Resolver query logs. Flow logs show IP:port, bytes, accept/reject; DNS logs show queried names. Flow logs miss DNS names; DNS logs miss direct IP connections and encrypted SNI. Together they cover most. Classify: stable provider endpoints (S3, DynamoDB, ECR, STS, KMS, Secrets Manager), package repos (yum/apt, npm, PyPI), telemetry (CloudWatch, Datadog), payment APIs, NTP, backup/DR.

OptionUse forCost (us-east-1, 2024 list)Limitation
VPC gateway endpoint (S3, DynamoDB)AWS servicesFreeOnly S3/DynamoDB
VPC interface endpointAWS services (ECR, STS, KMS, Secrets Manager, SQS, SNS, CloudWatch Logs)$0.01/hr per AZ + $0.01/GBPer-service, per-AZ
AWS Network FirewallDomain allowlist, IDS/IPS$0.395/hr per endpoint + $0.065/GBComplex, cost
Forward proxy (Squid/Envoy)HTTP/HTTPS domain allowlistEC2 cost + opsTLS inspection needs CA trust
NAT GatewayIP allowlist only$0.045/hr + $0.045/GBNo domain control

Trace a pod reaching S3. Before: security group egress 0.0.0.0/0. Pod resolves s3.amazonaws.com to public IPs, sends SYN to 52.216.x.x:443, NAT gateway forwards. After default-deny: remove 0.0.0.0/0. Add gateway endpoint for S3; route table sends the S3 prefix list (pl-63a5400a in us-east-1) to vpce-xxx. Security group allows egress to that prefix list on 443. Pod resolves S3 to public IPs, but the route table matches the prefix list, so the packet goes to the endpoint ENI, not NAT. If no endpoint, the packet hits NAT but the security group drops it. Denied flow log shows REJECT.

Failure modes and detection:

  • Startup: can't reach ECR or package repo. Detect: pod CrashLoopBackOff, ImagePullBackOff, denied flow logs. Cost: deployment blocked.
  • Credential rotation: can't reach STS or Secrets Manager. Detect: 403 from AWS API, CloudTrail AccessDenied, app auth errors.
  • DNS: blocking UDP 53 to VPC resolver (10.0.0.2) breaks all resolution. Detect: DNS timeouts, SERVFAIL.
  • Metadata: blocking 169.254.169.254 breaks instance profile credentials. Detect: credential retrieval errors. Fix: use IRSA on EKS.
  • Failover: standby region can't reach primary's dependencies. Detect: health check failures, cross-region latency.
  • Incident tooling: can't reach monitoring or break-glass. Detect: missing metrics, no logs, on-call can't SSH.

Start in learning mode: allow all egress but log. Build denied-flow dashboard with CloudWatch Logs Insights: fields @timestamp, srcAddr, dstAddr, dstPort, action | filter action="REJECT" | stats count() by dstAddr, dstPort. Add expiring exceptions (30 days) for unknown destinations. Reconcile observed egress to declared dependencies weekly. Then flip to default-deny per workload, starting with non-production.

Default-deny reduces exfiltration and C2, but increases operational burden and can break dynamic cloud services. When not to use: if you lack inventory, or if the workload is a proxy itself. Alternatives: allowlist by domain via proxy vs IP via security group. Domain allowlist is more precise but requires TLS SNI or MITM; IP allowlist is simpler but breaks when provider IPs change. For AWS services, VPC endpoints beat NAT on cost and security: 1 TB/month through NAT Gateway costs about $32.85 (hourly) + $46.08 (data) = $78.93; through a 3-AZ interface endpoint costs about $21.90 + $10.24 = $32.14. List price, us-east-1, 2024.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Prevent data exfiltration through cloud network paths.

Answer

Core answer (first 90 seconds)

Assume a multi-account AWS estate, workloads in private subnets, and no business need to reach arbitrary internet hosts. Exfiltration isn't one path: it's five, and each has a different enforcement point. So I enumerate the paths, deny each one, then re-open only what the workload needs with an identity and a resource condition.

The five: internet egress via NAT/IGW; VPC endpoints to AWS services (gateway and interface); DNS resolution; managed-service cross-account access (bucket policies, resource policies, presigned URLs); and the instance metadata service. A control on one does nothing for the others: that's the usual mistake.

Then: default-deny egress, allow per path, monitor the residue.

Mechanism: what each control actually enforces

  • Gateway endpoints (S3, DynamoDB) are a route-table entry plus an endpoint policy. The endpoint policy is an IAM policy evaluated in addition to the identity policy: both must allow. The default endpoint policy is full access, so an unset policy enforces nothing. And the endpoint only applies if the subnet route table carries the service prefix list; without it the request goes to NAT and the policy is never evaluated.
  • Interface endpoints (PrivateLink) support security groups and endpoint policies. In us-east-1 list pricing they cost $0.01 per AZ-hour plus $0.01/GB, against NAT gateway at $0.045/GB processed. 500 GB/month through NAT is ~$22.50 in processing; through a 3-AZ interface endpoint it's ~$21.90 hourly plus $5.00 data: comparable, so cost alone doesn't decide it.
  • DNS: Route 53 Resolver DNS Firewall evaluates domain lists per VPC with ALLOW/DENY/ALERT; query logging gives you the record. Tunneling shows as high-entropy subdomains and query-volume spikes.
  • Managed services: VPC Service Controls (GCP) perimeters with restrictedServices and egress policies; S3 Block Public Access at account level; resource policies scoped by aws:PrincipalOrgID.
  • Metadata: IMDSv2 with HttpTokens: required and hop limit 1 removes the SSRF-to-credentials path.

Trace: one S3 request, two outcomes

An instance in a private subnet calls s3.us-east-1.amazonaws.com. The resolver returns public IPs. Route lookup: if the subnet route table has the S3 prefix list (e.g. pl-63a5400a in us-east-1) → gateway endpoint → endpoint policy evaluated → 403 if the bucket isn't in the allow list. If that route is missing → 0.0.0.0/0 → NAT → public S3 endpoint → endpoint policy never evaluated, data leaves. Same code, same IAM role, opposite outcome. Detection: VPC flow logs show the destination ENI as the NAT gateway rather than the endpoint.

When tight egress isn't worth it

High-churn dev accounts and SaaS with rotating IPs generate more breakage than risk reduction. Give those an internal package mirror (CodeArtifact, Artifactory) and a documented break-glass path, or you get shadow IT: a second NAT in a forgotten account.

Failure modes and detection

  • Endpoint policy left at default → CloudTrail data events show writes to a bucket outside the org.
  • DNS tunneling through an allowed domain → Resolver query logs, entropy anomaly.
  • Compromised proxy credentials → proxy logs show an authenticated principal reaching a novel destination.
  • IMDSv1 still enabled → GuardDuty InstanceCredentialExfiltration.

Prices are us-east-1 list and change; verify before quoting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How do you enforce pod-to-pod network segmentation and runtime egress policies using Kubernetes NetworkPolicies or CNI plugins?

Answer

What I'd say first

NetworkPolicy is a spec, not an implementation: it does nothing unless the CNI enforces it. Calico, Cilium and Antrea do; a bare Flannel install does not. So the first thing I'd establish is the dataplane, because that decides what I can express. networking.k8s.io/v1 NetworkPolicy is L3/L4 allow-list only: no deny, no FQDN, no HTTP. FQDN-scoped egress, explicit deny and L7 matching are CNI extensions.

The shape: default-deny per namespace in both directions, additive allow rules for the exact flows, then a CNI layer for egress leaving the cluster.

Default deny, then allow

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: production}
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]

That isolates every pod in production in both directions, and only in that namespace. Policies are additive, so the next one only adds:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: payment-api, namespace: production}
spec:
  podSelector: {matchLabels: {app: payment-api}}
  policyTypes: [Ingress, Egress]
  ingress:
    - from: [{podSelector: {matchLabels: {app: frontend}}}]
      ports: [{protocol: TCP, port: 8443}]
  egress:
    - to:
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}
          podSelector: {matchLabels: {k8s-app: kube-dns}}
      ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}]

The DNS rule is not optional. Egress default-deny without it breaks every lookup in the namespace, and Could not resolve host reads like an app bug. kubernetes.io/metadata.name is applied to namespaces automatically since 1.21.

Egress to the outside

CIDR allow-lists are the wrong tool for SaaS endpoints: Stripe's ranges change, and a pinned /32 is a silent outage. Cilium's toFQDNs scopes egress to a name, with the DNS proxy feeding resolved IPs into the ipcache:

YAML
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata: {name: payment-api-egress, namespace: production}
spec:
  endpointSelector: {matchLabels: {app: payment-api}}
  egress:
    - toEndpoints:
        - matchLabels: {io.kubernetes.pod.namespace: kube-system, k8s-app: kube-dns}
      toPorts:
        - ports: [{port: "53", protocol: ANY}]
          rules: {dns: [{matchPattern: "*"}]}
    - toFQDNs: [{matchName: "api.stripe.com"}]
      toPorts:
        - ports: [{port: "443", protocol: TCP}]
  egressDeny:
    - toCIDRSet: [{cidr: "169.254.169.254/32"}]

egressDeny is what standard NetworkPolicy cannot express: deny beats allow, so IMDS stays blocked even if a later rule allows a broad CIDR. Method/path rules in Cilium examples only work on plaintext HTTP; on 443 you get FQDN and port granularity unless TLS is terminated at the proxy.

Proving it

$ kubectl -n production exec deploy/frontend -- curl -s -o /dev/null -w '%{http_code}\n' --max-time 3 https://payment-api:8443/charge
200
$ kubectl -n production exec deploy/reporting -- curl -sS --max-time 3 https://payment-api:8443/charge
curl: (28) Connection timed out after 3001 milliseconds

The timeout is the policy, not a broken service: hubble observe --verdict DROPPED shows the SYN with reason Policy denied. A connection refused instead of a timeout means the packet got through and nothing was listening.

Failure modes

  • FQDN bypass. DoH/DoT or a hardcoded IP never reaches the DNS proxy: fail-closed drop, or fail-open if a broad CIDR allow exists. The ipcache is keyed by IP, so two names sharing one IP are indistinguishable.
  • hostNetwork. Those pods have no veth and no Cilium endpoint; policy doesn't apply. kubectl get pods -A -o json | jq -r '.items[] | select(.spec.hostNetwork) | .metadata.name'.
  • Additive merging. ingress: [{}] or egress: [{}] in any policy selecting the pod opens that direction to everything. A policy with policyTypes: [Ingress] doesn't isolate egress at all.
  • kubelet probes. Default-deny ingress can break liveness/readiness probes depending on the CNI; watch probe failures right after rollout.
  • Enforcement is in the pod netns. A privileged container with NET_ADMIN can strip the tc/BPF hooks on its own interface. Policy bounds blast radius; it isn't a boundary against a root container.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Build useful flow-log observability.

Answer

Clarify first. "Useful" for whom: detection engineering, incident response, or cost governance? I'll assume detection and IR on a cloud network, and that I can pick the platform. I'll answer for AWS VPC Flow Logs, note where GCP and Azure differ, and flag the numbers I'd re-check against current pricing.

Assumptions: multi-account AWS, VPC Flow Logs available, CloudWatch Logs or S3 as destination, ~50k concurrent flows on the busiest host.

Core answer (60–120s). Turn on flow logs at every boundary you can't otherwise see: internet gateway, NAT gateway, transit gateway, VPC peering, and the ENIs themselves: at 60-second aggregation, not the 600-second default. Use the custom format: srcaddr, dstaddr, srcport, dstport, protocol, action, bytes, packets, start, end, interface-id, log-status. Ship to S3 for cheap retention and to a query layer for hot search. Then enrich: join srcaddr to ENI to instance tags (owner, app), dstport to security-group rules, dstaddr to DNS and threat intel. Alert on new public paths, denied spikes, and egress to never-before-seen destinations. Validate with a controlled connection whose expected record you already know.

Why 60s, not 600s. A 600-second aggregation merges a 30-second connection into a 10-minute bucket, so you lose ordering and can't separate a scan from a session. 60s costs roughly 10x the records but preserves timing.

Why sampling is the trap. GCP VPC Flow Logs sample 50% of packets by default (sampling rate 0.5). A single-packet probe (a SYN to a closed port, a one-shot DNS beacon) is logged with probability 0.5. Over N packets detection is 1 − 0.5^N, so a 10-packet C2 session is caught ~99.9% of the time, but a lone scan probe is a coin flip. If you need single-packet fidelity, set sampling to 1.0 and pay for it.

Cost arithmetic. 50k flows × 60 records/hour × 150 bytes ≈ 450 MB/hour ≈ 10.8 GB/day per host. At CloudWatch Logs ingestion ($0.50/GB in us-east-1) that's ~$5.40/day, ~$160/month for one host, so S3 delivery plus query-on-demand is the default, CloudWatch only for accounts you're actively hunting in.

ChoiceDetection you gainCost
60s aggregation, all ENIsordering; scan vs session~10x records vs 600s
600s aggregationvolume trendsloses sub-10-min events
GCP sampling 0.5half the packetsmisses single-packet events
GCP sampling 1.0every packetfull ingestion cost

Enrichment is what makes it triageable. Raw 10.0.3.14 → 203.0.113.9:443 ACCEPT is a row. Joined to tags and DNS it becomes "payments-api → unknown-external, first seen today": the difference between a 30-minute and a 3-minute triage.

Failure modes and how you catch them.

  • Excluded traffic: AWS doesn't log 169.254.169.254, the Amazon DNS resolver, DHCP, or Windows activation. Detect by comparing flow-log bytes to the interface's NetworkIn/NetworkOut CloudWatch metrics; a persistent gap is the excluded set.
  • Sampling blind spot: read the sampling-rate field, or send a known single-packet connection and confirm it appears.
  • Clock skew: start/end are host epoch seconds; if NTP drifts, correlation with app logs breaks. Compare against metric timestamps.
  • Destination as attack surface: an attacker with credentials can delete the flow log or the bucket. Watch CloudTrail for DeleteFlowLogs and lock the bucket with Object Lock.

When not to. Dev accounts, or high-volume data-plane traffic where you only need metadata: sample or aggregate there and spend the budget on the boundaries that matter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Test cloud firewall rules before production.

Answer

The 90-second answer

"Test before production" is ambiguous, so I'd pin it down first: you're proving two things. Every path that should work does, and every path that shouldn't is actually blocked. I'd assume AWS with Security Groups plus NACLs, all managed in Terraform, and a non-prod account whose VPC mirrors prod's subnet and route layout.

Then three passes, cheapest first, stopping when a pass stops finding things.

Pass 1: static. Run conftest/OPA or Checkov over the Terraform in CI. This catches 0.0.0.0/0 on 22/3389, rules with no description, and shadowed rules. Seconds to run, no infrastructure.

Pass 2: config-level reachability. AWS Reachability Analyzer takes a source ENI, destination ENI and port and reports whether the configuration permits the path (SG, NACL, route table, IGW) without sending a packet. It's the fastest way to find a missing NACL rule or a route gap.

Pass 3: active probes. Only this proves the data plane. You need a host in each subnet class you care about, and you send real SYNs, not ping (ICMP is often blocked independently of the rule you're testing).

Why the passes differ: the mechanism

Security Groups are stateful: allow inbound 443 and the return traffic is tracked automatically. NACLs are stateless and numbered, evaluated lowest-number-first, first match wins. So a NACL that allows inbound 443 on the server subnet still drops the SYN-ACK unless its outbound rules permit the client's ephemeral port. Linux's default ip_local_port_range is 32768–60999, so an outbound rule scoped to 1024–32767 silently fails for most connections. This is the single most common "it works in the console, not in prod" bug, and only a real probe finds it.

Trade-offs

Passive (flow logs, config analysis) is cheap and safe but can't prove a path is open: absence of traffic isn't absence of a rule. Active probing proves it, but costs a host per vantage point, NAT Gateway data processing at $0.045/GB, and can trip IDS or rate limits. A full shadow VPC is the most faithful and the most expensive: a second NAT Gateway is ~$32/month before traffic, and it drifts from prod the moment someone hotfixes prod. My rule: shadow only for the paths you can't reach from a probe host. Internet ingress, cross-account peering, on-prem VPN.

Failure modes and how you'd see them

  • Shadowing: a broad allow at NACL rule 100 makes rule 200 dead. Detect by computing effective rules, not reading the file.
  • Asymmetric path: traffic leaves via NAT but returns via a different AZ's IGW. Symptom is one-way connections; detect with VPC Flow Logs showing NODATA on the return direction.
  • Propagation lag: SG changes take effect in seconds, but org-level firewall policies can take minutes. Test rollback explicitly.

Worked trace

Client 10.0.1.5:49876 → server 10.0.2.10:443.

HopRuleResult
Client NACL outallow 443 → 10.0.2.0/24pass
Server NACL inallow 443pass
Server NACL outallow 443 onlydrop SYN-ACK
Fixallow 1024–65535 → 10.0.1.0/24pass

A curl from the client hangs; tcpdump on the server shows the SYN arriving and no SYN-ACK leaving. That's the signature.

Finally, wire the probes into a scheduled job so drift is caught continuously, not once.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Define observability and metrics for cloud network security.

Answer

What I'd say in the first two minutes

Observability is the ability to answer a question you didn't plan for using telemetry you already collect, without shipping new code. Monitoring answers the questions you wrote down: "is the firewall up?" Observability answers "which of my 400 accounts can reach the prod database on 5432 right now, and what changed at 03:14?" For cloud network security that means four telemetry planes: control plane (CloudTrail, AWS Config, Terraform state), data plane (VPC Flow Logs, NSG flow logs, Route 53 resolver query logs), identity (IAM policies, SCPs), and endpoint (host agents, eBPF). Metrics are the questions you ask of those planes on a schedule.

The mechanism that makes it work

Flow logs record at the ENI, one record per flow per aggregation interval (60 s default, 600 s max on AWS) with ACCEPT/REJECT and NODATA/SKIPDATA status. So the reachability you can prove is the set of observed ACCEPT flows; the reachability you must infer is route table ∩ NACL ∩ security group. Config alone over-approximates: NACLs are stateless, SGs are stateful, and AWS-managed prefix lists change under you. Flow logs alone under-approximate: they show only what happened, and they skip DHCP, DNS to the .2 resolver, and 169.254.169.254 metadata traffic. The gap between inferred and observed reachability is itself the most useful metric you have: a new ACCEPT pair that no config path explains means someone bypassed your IaC.

Metrics I'd actually run

MetricSourceTarget / alert
Internet-exposed resources (0.0.0.0/0 on 22/3389)Config + SG rules0; alert on any delta
New src→dst ACCEPT pair vs 30-day baselineFlow logsalert < 5 min
Control-plane drift vs IaC stateCloudTrail vs Terraformalert < 5 min
REJECT rateFlow logsalert on >3σ over 7-day baseline
Flow-log record lossSKIPDATA countalert > 0.1% of records
Time to detect exposureCloudTrail event → alertp95 < 5 min
Time to containalert → SG revert verified by re-query< 15 min

Trade-offs

Three sources, chosen by question. Flow logs are cheap, universal, L3/L4 only, no payload, no process attribution. Host agents (eBPF, Cilium) give L7 and process attribution but cost CPU and go blind on managed services like RDS or Lambda. Active probes give ground truth for "can this actually connect" but are point-in-time and trip IDS. Most teams run flow logs everywhere and agents only where the workload justifies it.

Failure modes and how you catch them

  • SKIPDATA means records were dropped under load: your reachability view has holes exactly when traffic spikes. Detect by ratio, not by eyeballing.
  • 60 s is the floor on AWS aggregation, so a 3-second port scan collapses into one record. Catch that with Network Firewall or GuardDuty, not flow logs.
  • A misconfigured NACL floods REJECT and buries the real signal. Baseline and alert on deviation, never on absolute count.
  • GCP samples flows by default, so a single short-lived exfil connection can vanish; AWS doesn't sample but skips metadata traffic. Know which one you're on before you trust a negative.

Cost, because it decides the design

10 GB/day of flow logs into CloudWatch Logs at $0.50/GB ingest is ~$150/month in us-east-1; the same volume in S3 at $0.023/GB-month is ~$7. Route raw records to S3 and query with Athena; keep only derived metrics in CloudWatch.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Detect and remediate cloud network-policy drift.

Answer

The first minute

Assume a multi-account AWS org, network resources defined in Terraform, AWS Config recording on, and a Transit Gateway hub. Drift is any gap between what the code declares and what the APIs return, but the gap that decides an incident is reachable paths, not rule text. So I detect on two layers: a state diff that says what changed and who changed it, and a path analysis that says whether reachability changed. I remediate in three tiers by blast radius, and I never auto-delete a route or revoke a rule I do not own.

Layer 1: declared state vs recorded state

Two records, each blind in a different place.

  • Terraform: terraform plan -refresh-only per account from CI. With -detailed-exitcode, 2 means differences, 0 means none, 1 means an error. It sees only what it owns, so out-of-band resources stay invisible until they collide with a managed one.
  • AWS Config: a configuration recorder writes a configuration item for each supported resource on every change (security groups, route tables, NACLs, Transit Gateway route tables, VPC attributes) and stores the relationships between them. Managed rules worth enabling: vpc-sg-open-only-to-authorized-ports, restricted-common-ports, internet-gateway-authorized-vpc-only, vpc-default-security-group-closed. It is billed per item recorded and per rule evaluation, so scope the recorder deliberately.

Raw diffs are noisy because equivalent policy is rarely identical text. Normalize both sides to a set of (protocol, port range, source CIDR or prefix-list ID, principal) tuples and compare sets.

ChangeHow it appearsWrong moveRight move
Gateway VPC endpoint route (S3, DynamoDB)prefix-list destination, vpce- target, in a table Terraform manages with in-line route {} blocks, which make the resource authoritative for the whole tableapply the plan, delete the route, blackhole S3 from that subnettreat the route as data, or ignore_changes it; let the endpoint own its association
Same policy, two encodings: 10.0.0.0/8 vs two /9s, or a prefix list vs the CIDRs it containsstring differencerevoke and re-add, closing the port for a momentcompare normalized sets
Service-created groups and ENIs: Lambda VPC configs, EKS and ELB groups, the default group's self-referencing inbound rulerules you did not writerevoke, breaking the serviceexclude from remediation by tag or name pattern, not from detection
New spoke attachmentpropagated routes in the hub Transit Gateway table; the spoke plan shows nothingread the empty plan as no driftowner-scoped alert in the hub account; deleting those routes breaks spoke-to-spoke traffic

Layer 2: paths, because equivalence is semantic

CreateNetworkInsightsPath then StartNetworkInsightsAnalysis for a named pair returns the path as ordered components, each with the route table entry, security group rule or subnet NACL rule that allowed or blocked it. It is static configuration analysis and sends no packets, so it cannot see a host firewall or a process that is not listening. CreateNetworkInsightsAccessScope with StartNetworkInsightsAccessScopeAnalysis turns it around: enumerate paths from a scope such as all internet gateway sources to your resources, instead of guessing the pairs.

Why paths beat rule text: 0.0.0.0/0 on port 22 attached to an instance in a private subnet with no internet gateway route and no public IP is unreachable, while a narrow-looking rule is reachable when the listener, target group and chained groups line up behind an internet-facing ALB. Rank reachable internet and cross-boundary paths first, then data sensitivity.

Remediation, three tiers

  1. Prevent the class. Azure Policy with a deny effect on Microsoft.Network/networkSecurityGroups, or an SCP denying ec2:AuthorizeSecurityGroupIngress and ec2:CreateRoute to every principal except the pipeline role. The price is break-glass access, so you need a documented, audited exception path.
  2. Auto-revert tested invariants only. AWS Firewall Manager security group policies across an org are exactly this shape: audit, then remediate the rules the policy says must never exist. Public admin ports, public object storage, disabled logging.
  3. Quarantine or page a human for everything else. Attach a restrictive group to the ENI with ModifyNetworkInterfaceAttribute --groups, or notify the owner tag with a deadline (an hour for internet-facing admin, a day for internal) and escalate. Never auto-delete routes or revoke rules you do not own; a service-created rule reverted at 03:00 is how you cause the outage you were preventing.

Hypothetical timing: 02:14 CloudTrail shows AuthorizeSecurityGroupIngress on sg-0a1b from the assumed role lambda-sg-sync, and Config records the new item. 02:15 vpc-sg-open-only-to-authorized-ports flips NON_COMPLIANT because the rule allows 0.0.0.0/0 on 3389. 02:16 the analysis shows a new path from the internet gateway to a production instance. 02:18 revoke, re-run the analysis, path gone. Then fix lambda-sg-sync, which held a stale group ID in an environment variable.

Each drift carries three pieces of evidence: the CloudTrail event naming principal and call, the Config item before and after with its capture time, the analysis before and after. Close with an active probe rather than a dashboard, because from outside the VPC the connect must time out and a connection refused means you reached the host. You are done when the plan is empty, every internet-reachable path has a named owner, and the principal that caused the drift can no longer make that call.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Roll out an organization-level firewall guardrail.

Answer

Assumptions: GCP, one org with folders, Terraform-managed, instances addressed by secure tags. Checked against Google Cloud hierarchical firewall policy docs, 2025.

The 90-second answer

Use a hierarchical firewall policy attached at the org node. It is the only firewall construct a project owner cannot override: a deny there beats every folder policy and VPC firewall rule below it. Pick one invariant worth the blast radius ("no ingress to PCI-tagged VMs from outside the VPC"), write it as a deny at a reserved priority, and put a goto_next rule underneath so everything else still falls through to the folder and VPC rules teams already have. Roll out with logging on and no enforcement, diff the logged flows against what you expect, then flip the action to deny. Rollback is detaching the association: one API call.

Mechanism: why priority and goto_next decide the blast radius

Rules evaluate lowest priority number first, first match wins, and the levels evaluate org → folder → VPC. Priority range is 0–2147483646; the implied rules (implied-allow-egress, implied-deny-ingress) sit at 65535. A rule whose action is goto_next is not terminal: evaluation continues at the next level down. That is the whole design lever: a deny is terminal and shadows everything below it, goto_next delegates.

Reserve the priority space so the guardrail can't be crowded out:

PriorityPurpose
0–999break-glass denies, added during an incident
1000–1999org guardrails (the invariant)
2000goto_next, target all instances

Trace

Org policy org-guardrail: rule 1000 = deny ingress, target secure tag pci, source 0.0.0.0/0; rule 2000 = goto_next, all instances. Folder policy: allow ingress tcp:443 from 10.0.0.0/8. VPC rule: allow tcp:22 from 35.235.240.0/20 (IAP).

  • SYN to a PCI-tagged VM, port 443, from 10.1.2.3: rule 1000 matches (tag pci, ingress) → denied. Folder and VPC rules are never evaluated.
  • SYN to a non-PCI VM, port 443, from 10.1.2.3: rule 1000 does not match; rule 2000 matches and delegates → folder allow matches → allowed. The VPC rule is not reached.
  • SSH to a non-PCI VM from 35.235.240.0/20: org delegates, folder has no match, VPC rule matches → allowed.

Trade-offs

  • Hierarchical policy at the org: inherited, not overridable by project owners. Use when the requirement is "no project owner can open this, ever."
  • A Terraform module of VPC firewall rules per project: simpler, visible to the team that owns the VPC, but any project owner can edit or delete it. Use when the goal is a default template, not a hard boundary.
  • IAM/org-policy restriction on who may edit firewall rules: controls the API, not the packets; it does not stop a rule that already exists. Use alongside, not instead.

Deciding criterion: does the invariant have to survive a project owner who disagrees? If yes, org-level policy; if no, the module is cheaper to operate.

Failure modes

  • goto_next above a deny. A delegation rule at priority 1500 shadows your deny at 2000. Detect: firewall rule logs show allowed flows that should be denied.
  • Policy unassociated. Rules silently stop applying. Detect: alert on association state via gcloud compute firewall-policies describe or Cloud Asset Inventory.
  • Secure-tag drift. A VM loses its tag, falls through goto_next, and is allowed by a lower rule. Detect: alert on tag membership changes for tagged instances.
  • Eventual consistency. Propagation is not instantaneous; a deny may not be live everywhere the moment the API returns. Verify by querying firewall logs from several zones before declaring the rollout done.

Store owner, rationale, exceptions and expiry in the same Terraform as the policy, and alert if the policy becomes unassociated or a target attribute changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design a multi-account hub-and-spoke network securely.

Answer

Assumptions I'd state before drawing anything: AWS, accounts under AWS Organizations with SCPs, one primary region (us-east-1), spokes are workload VPCs that need shared services and internet egress but not each other, and the network account owns the transit layer. If spokes must talk directly at high volume, or you need multi-region active-active, the design changes and I'd say so up front.

The answer. One Transit Gateway in the network account, shared to the org with AWS RAM. Three route tables on it:

Route tableAssociated withPropagationsEffect
spoke-rtevery spoke VPC attachmentinspection attachment onlya spoke sees the firewall, never another spoke
inspection-rtinspection VPC attachmentall spoke attachmentsfirewall can route back to any spoke
shared-rtshared-services VPCspokes that need itendpoints reachable

Spokes associate with spoke-rt and propagate into inspection-rt. A TGW route table contains only routes propagated into it, so spoke A has no route to spoke B's CIDR at all: the isolation is a property of the route table, not a firewall rule you have to keep correct. That is the mechanism, and it is why you don't need per-spoke ACLs to prevent lateral movement.

The inspection VPC runs AWS Network Firewall endpoints, one per AZ, and its TGW attachment has appliance mode enabled. Appliance mode pins a flow to a single AZ for its lifetime, so the request and the return packet hit the same firewall endpoint. Without it, TGW can hash the two directions to different AZs; the firewall sees a SYN in AZ-a and a SYN-ACK in AZ-b, has no matching flow, and drops the return. Symptom: connections establish, then hang, and firewall logs show the return packet dropped as not matching an established flow. That is the asymmetric-routing failure, and appliance mode is the fix.

CIDR: allocate from 10.0.0.0/8, one /16 per VPC, /20 per subnet, no overlaps. TGW does not resolve duplicate prefixes deterministically: a repeated /16 makes routing depend on propagation order. Reserve a block for future regions now.

Guardrails: an SCP denying ec2:CreateInternetGateway, ec2:CreateVpcPeeringConnection and ec2:CreateTransitGatewayVpcAttachment outside the network account stops a team from building a bypass path. Shared services (S3, ECR, KMS) go over gateway/interface VPC endpoints or PrivateLink rather than being routed through the hub.

Trade-off: centralize inspection or not. Centralized gives one policy and one log stream, but every spoke-to-spoke and spoke-to-internet byte crosses the TGW twice and the firewall once. Rough us-east-1 list arithmetic for 10 TB/month of spoke egress (verify current pricing): TGW data processing $0.02/GB × 2 legs = $0.04/GB → ~$410; Network Firewall $0.065/GB processed → ~$666, plus ~$0.395/endpoint-hour × 3 AZs × 730 h ≈ $865. Call it ~$1,900/month before NAT. Per-spoke egress with its own NAT gateway skips the TGW and firewall legs but gives up central logging and multiplies NAT hourly charges across accounts. Don't centralize when a spoke's traffic is dominated by one high-volume destination: put a gateway endpoint or PrivateLink in front of it and keep it off the hub.

Failure modes and tests. Spoke compromise: confirm it cannot reach another spoke. A traceroute should show the firewall hop, not a direct path. Firewall endpoint failure: does traffic fail closed? Route change: propagate a new spoke and confirm it lands only in inspection-rt. Then AZ loss and rollback. Correlate TGW flow logs, Network Firewall logs and VPC flow logs on a single flow to prove the path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design secure hybrid connectivity from on-premises to cloud.

Answer

First two minutes

Clarify before designing: which direction carries the bulk (on-prem→cloud replication, or users→apps), the RTO/RPO, whether regulated data may cross the public internet at all, and whether we own the on-prem edge or a carrier does.

Assumptions I'd state: AWS, one region, two on-prem data centres, ~4 Gbps steady replication plus interactive traffic, no regulatory ban on internet transit.

Recommendation: a private circuit as primary and IPsec VPN over the internet as backup, both terminated on redundant customer gateways in two AZs, BGP between them, non-overlapping address plans, and resource-level authentication so the network path is never the trust boundary.

Choosing the path

IPsec VPN over internetDedicated private circuit
Throughput1.25 Gbps per AWS tunnel, ECMP across tunnelsDX port 1/10/100 Gbps; ExpressRoute 50 Mbps–10 Gbps
Latencyvariable, internet-dependentpredictable, carrier SLA
MTU1400 recommended1500
Provisioningminutesweeks to months
Failure domaininternet + both edgescarrier + cross-connect + edge

VPN alone is wrong for sustained multi-Gbps replication: you saturate the tunnels, and ECMP hashing pins a single flow to one tunnel. A private circuit alone is wrong without a backup: one cross-connect or carrier maintenance window takes you down for hours.

Routing and addressing

Non-overlapping RFC 1918 plans. If overlap is unavoidable, NAT at the edge, but that breaks DNS answers and identity-based policy, so treat it as a last resort. BGP: customer ASN (e.g. 65000) peering with the AWS virtual private gateway ASN 64512; ExpressRoute peers with Microsoft AS 12076. Advertise only the prefixes you need: a leaked default route hairpins cloud internet traffic through on-prem. AWS defaults to 100 routes per BGP session on VPN and private VIFs; alert before you hit it.

Why symmetry matters

Stateful firewalls keep per-device session tables. If the primary path fails mid-flow and the return packet arrives on the backup firewall, that device has no entry and drops it; the flow stalls until the client retries. Fix it by terminating both paths on the same HA pair with session synchronisation, or by keeping the firewall stateless and enforcing at security groups.

Failover trace

The Direct Connect BGP session drops. Without BFD, the hold timer (180 s by default, three times the 60 s keepalive) must expire before routes are withdrawn: up to three minutes of blackhole. With BFD, detection drops to sub-second. The VPN routes, already present but less preferred via AS-path prepending, are then installed. If the backup is 2×1.25 Gbps ECMP and the primary was 4 Gbps, you fail into a degraded state: decide in advance which replication jobs to shed.

Failure modes and detection

  • Asymmetric path after partial failure: firewall drop counters and TCP retransmit rate.
  • Route leak from on-prem: diff the advertised and received prefix lists, alert on count changes.
  • DNS: private zones must resolve to private addresses from both sides (Route 53 Resolver inbound/outbound endpoints, or Azure Private DNS resolver). Split-horizon mistakes send cloud traffic to public IPs: catch them in resolver query logs.
  • Compromised on-prem segment: source IP proves nothing. Require IAM/SigV4 or mTLS per resource; the tunnel is transport, not authorisation.
  • Logging: VPC flow logs, VPN/DX connection logs, and CloudTrail on route-table and gateway changes, with a named owner on each side.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design secure administrator access to private cloud resources.

Answer

Start with a managed session, not a bastion, when the target can run an agent. On AWS that is Systems Manager Session Manager; on GCP, IAP TCP forwarding; on Azure, Bastion if you cannot install an agent. The goal is to delete inbound 22/3389 from the VPC and make every admin action an authenticated, logged, short-lived session. Assume Linux and Windows VMs in private subnets, no public IPs, admins federated to an IdP with MFA and device compliance, and a requirement to audit commands.

OptionInbound ports on targetPrereqAuditWhen it wins
SSM Session ManagernoneSSM agent, outbound 443 to ssm/ssmmessages/ec2messages, IAMCloudTrail + S3 session logsLinux/Windows EC2, agent allowed
GCP IAP TCP forwarding22/3389 from 35.235.240.0/20 onlyIAP API, firewall rule, no external IPCloud Audit LogsGCP VMs, no agent
Azure Bastionnone (RDP/SSH over 443 to Bastion)AzureBastionSubnet /26 or larger, Bastion SKUAzure activity log, session diagnosticsAzure VMs, no agent, portal access
JIT VM accessopens NSG for a windowDefender for CloudActivity logStanding admin roles, not a session path

Mechanism: the SSM agent polls outbound 443 to ssm.<region>.amazonaws.com, ssmmessages.<region>.amazonaws.com, ec2messages.<region>.amazonaws.com. No security group inbound rule is needed. Scope the IAM policy to the instance ID via a tag. Session Manager idle timeout defaults to 20 minutes. For RDP, port forwarding runs over the same channel. GCP IAP needs a firewall rule allowing ingress from 35.235.240.0/20 to 22/3389 and no external IP. Azure Bastion deploys into AzureBastionSubnet (/26 or larger) and proxies RDP/SSH over 443 from the portal. JIT is not a session path; it opens an NSG for a window, so pair it with one of the above.

Trade-offs: SSM wins when you can install the agent and egress 443 is allowed or you can create VPC endpoints. It fails on appliances or OS images that cannot run the agent. Bastion wins for those appliances and for browser RDP without agent install; it costs a subnet and a public IP on the Bastion, and SKU limits concurrent sessions. IAP wins on GCP because it needs only a firewall rule, but it still requires the IAP API and the 35.235.240.0/20 range. JIT beats standing admin roles because it removes permanent NSG allow rules, but it does not replace session logging; use it with SSM/IAP/Bastion.

Failure modes: stolen creds. Require MFA and device compliance at the IdP; issue STS AssumeRole default 1h, max 12h; detect anomalous AssumeRole in CloudTrail and risky sign-in in Entra. Unmanaged device: conditional access blocks; if you only check password, an unmanaged laptop can reach the bastion. Alternate ports: SSH on 2222 bypasses an NSG rule for 22; block all inbound from 0.0.0.0/0 except load balancers, and alert on VPC flow logs and GuardDuty. Peer/hybrid bypass: a VPC peering or VPN from on-prem can reach 22; centralize ingress in a shared VPC, use security group references, and put AWS Network Firewall or equivalent on the TGW. Provider control-plane outage: SSM/IAP/Bastion down; keep a break-glass path with a hardware key, a VPN to a jump host, and sealed credentials, tested quarterly. Patch the bastion and session service with SSM Patch Manager or Azure Update Manager.

Trace: admin -> IdP (MFA + compliant device) -> STS AssumeRole (1h) -> SSM StartSession -> target shell. CloudTrail records StartSession; S3 records commands; idle 20 min terminates. No inbound 22.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Respond to an accidentally public database firewall rule.

Answer

What I'd say in the first two minutes

Before I touch anything: is the database actually reachable from the internet, or is the rule inert? On RDS, a 0.0.0.0/0 ingress rule on 5432 does nothing if publicly_accessible is false: the instance has no public IP, so there's no route for the packet to arrive on. My first move is to confirm reachability, not to assume breach.

Assuming it is reachable, I contain first and investigate second, because the evidence I need is captured out-of-band. I revoke the offending ingress rule, then reconstruct the exposure window from CloudTrail, VPC flow logs and database audit logs. Revoking does not destroy evidence: CloudTrail already recorded the AuthorizeSecurityGroupIngress call, flow logs recorded the traffic, and DB audit recorded the sessions. There is no reason to leave the hole open "for forensics."

Containment

Revoke via a trusted path: SSM Session Manager or a bastion, never through the public rule itself. If the DB should never be public, revoke outright. If a legitimate client needs public access, narrow to their /32 and require TLS; the deciding criterion is whether any real client depends on that path.

Reconstruct the window

SourceProvesCan't prove
CloudTrailwho added the rule, exact CIDR and port, whenwhether anyone connected
VPC flow logsACCEPT/REJECT, srcaddr, bytes, packetsauth success; default aggregation is 10 min
DB audit (pgaudit, MySQL audit plugin, RDS Database Activity Streams where supported)logins, queries, failed authtraffic before audit was enabled

Decide impact

If flow logs show ACCEPT from a public srcaddr and DB audit shows a successful login from that address, treat credentials as compromised: rotate, then look for exfiltration. Large SELECTs, COPY, mysqldump. If flow logs were disabled or rolled out of retention, you cannot prove a negative; assume exposure.

Failure modes

  • Reading "no successful auth" as clean when flow logs were off or the 10-minute aggregation window rolled over.
  • Rotating the DB password but not the copy in the app config or secrets manager: that's an outage, not a fix.
  • Checking only IPv4. A 0.0.0.0/0 rule does not cover ::/0; check both families.

Close

Validate externally: scan from a host outside the VPC, over IPv4 and IPv6, and confirm the port is filtered. Then prevent recurrence with policy-as-code: an AWS Config rule or SCP denying 0.0.0.0/0 on database ports, and a guardrail requiring publicly_accessible=false.

Worked timeline (hypothetical)

  • 14:02. CloudTrail: AuthorizeSecurityGroupIngress, 0.0.0.0/0 → 5432, principal = deploy role.
  • 14:02–16:40. Flow logs: 3 ACCEPT records from 203.0.113.7, 41 KB total.
  • 16:41. pgaudit: connection authorized: user=app from 203.0.113.7, then a SELECT on customers.
  • 16:45. Rule revoked; app password rotated.
  • 17:10. External scan shows 5432 filtered on both families.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Manage an exception for broad network access.

Answer

First 90 seconds

Default is deny. An exception is a documented allow with an owner, an expiry and compensating controls, not a permanent widening. Clarify what "broad" means before granting: a CIDR wider than the client set, a port range wider than the service listens on, or a direction nobody needs. Assume AWS (the pattern maps to Azure NSGs and GCP firewall rules), policy-as-code in the provisioning path, flow logs in the detection path.

Then try to delete the range rather than scope it. SSM Session Manager removes inbound 22 entirely. A PrivateLink endpoint removes public exposure for a service. An mTLS proxy moves the decision from "which IP" to "which identity". When none fit, allow corporate egress 203.0.113.0/24, require mTLS with 24h client certs, and add a WAF rate-based rule of 2000 requests per 5 minutes per IP.

Scope by something the requester can't rewrite

Key the exception on a tag like env=prod and anyone holding ec2:CreateTags can add their resource to it: privilege escalation through a tag write. Scope by account ID, VPC ID or resource ARN, or by a tag only the platform role can write:

JSON
{
  "Effect": "Deny",
  "Action": "ec2:CreateTags",
  "Resource": "*",
  "Condition": {
    "StringEquals": { "aws:RequestTag/env": "prod" },
    "StringNotEquals": { "aws:PrincipalArn": "arn:aws:iam::111122223333:role/platform" }
  }
}

Detection and expiry

VPC Flow Logs to CloudWatch Logs. A metric filter counts ACCEPT lines on the port, but metric filters can't do CIDR math: a subscription Lambda compares srcaddr against the registry allowlist and alarms on a miss. Expiry is a registry field (expires: 2025-06-01) plus an owner. An AWS Config custom rule flags expired entries; its remediation action runs an SSM Automation document that revokes the ingress rule and notifies the owner. No response in 7 days pages security on-call.

Worked example

The exception lives in a registry file, not on the rule: EC2 security group rules aren't taggable. Conftest runs with the plan and the registry as inputs.

YAML
# exceptions.yaml
- id: EXC-1042
  cidr: 203.0.113.0/24
  port: 5432
  owner: data-platform
  expires: 2025-06-01
HCL
resource "aws_security_group_rule" "db_exception" {
  type              = "ingress"
  from_port         = 5432
  to_port           = 5432
  protocol          = "tcp"
  cidr_blocks       = [var.exception_cidr]
  security_group_id = aws_security_group.db.id
}
REGO
deny[msg] {
  rule := input.resource.aws_security_group_rule[name]
  rule.type == "ingress"
  rule.cidr_blocks[_] == "0.0.0.0/0"
  msg := sprintf("%s: 0.0.0.0/0 ingress is never allowed", [name])
}

deny[msg] {
  rule := input.resource.aws_security_group_rule[name]
  rule.type == "ingress"
  cidr := rule.cidr_blocks[_]
  cidr != "0.0.0.0/0"
  not exception_for(cidr, rule.from_port)
  msg := sprintf("%s: ingress %s:%v has no registry entry", [name, cidr, rule.from_port])
}

exception_for(cidr, port) {
  ex := input.exceptions[_]
  ex.cidr == cidr
  ex.port == port
}

Trace: data science asks for 0.0.0.0/0 to 5432; Conftest denies it outright. They narrow to 203.0.113.0/24:5432 and add EXC-1042 with owner and expiry; policy passes, rule applied. Flow logs show ACCEPT from 203.0.113.7: inside the allowlist, no alarm. Two weeks later someone edits the group in the console to 0.0.0.0/0, bypassing the pipeline. Flow logs now show ACCEPT from 198.51.100.7, outside the registry allowlist, so the alarm fires and the Config rule VPC_SG_OPEN_ONLY_TO_AUTHORIZED_PORTS flags the same drift. On 2025-06-02 the expiry job revokes the rule and posts to #sec-exceptions.

Boundary test

After applying 203.0.113.0/24:443, from inside the range 203.0.113.1:443 and 203.0.113.200:443 must connect; from outside, 203.0.112.255:443, 203.0.114.0:443, 198.51.100.1:443 and 203.0.113.1:22 must be refused. The inside pair catches a CIDR narrowed to /25, the outside pair catches one widened to /23 or /0, the port check catches a from_port/to_port typo.

ControlConcrete settingStops
Source restrictionSG ingress from 203.0.113.0/24 onlyScanning from arbitrary internet
AuthmTLS, client cert from internal CA, 24h TTLCredential replay
Rate limitWAF rate-based rule, 2000 requests / 5 min / IPBrute force
MonitoringFlow Logs → CloudWatch; subscription Lambda compares srcaddr to the registry allowlistUndetected drift
ExpiryRegistry expires + Config custom rule + SSM Automation revokePermanent drift

Failure modes: the exception becomes permanent because the revocation job isn't monitored. Alarm on its error metric and on any exception past expiry. Scope expands because tag write is too broad: a CloudTrail metric filter on CreateTags by a non-platform principal catches it. The compensating control is bypassed because the proxy allows direct access: the flow-log alarm and a Config check that the group's only source is the proxy's security group catch it.

Alternatives: private endpoint, mTLS proxy, SSM session, narrower identity target. When not to use: a third-party client you don't control, then WAF, rate limiting and mTLS, and accept the CIDR.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Retire a cloud network path safely.

Answer

Assumptions first. This is AWS, and the path being retired is a VPC peering connection between an app VPC and a shared-services VPC, replaced by a Transit Gateway attachment. Two invariants before I touch anything: no packet may be dropped that a client cannot retry, and the old path must be restorable with one API call for a defined window.

The plan, four phases with a gate between each.

  1. Map what actually uses it. VPC Flow Logs at the 60-second aggregation interval (the default is 600) give you the ENIs and ports; Route 53 Resolver query logs give you the names; the peering connection's route tables give you the CIDRs. Flow logs have real gaps: they do not record traffic to the instance metadata service at 169.254.169.254, DHCP, or the VPC DNS resolver, so a path used only for those looks dead. Cross-check against the peer's own logs.

  2. Drain. Move clients to the replacement and watch the old path's byte count fall to zero across a full business cycle. A weekly batch job means seven days, not one quiet afternoon.

  3. Disable reversibly. Remove the route entries, not the peering connection. Routes referencing a deleted peering go to blackhole; deleting the route entry alone is a one-line revert. Leave the peering connection and its security-group references intact.

  4. Delete. Only after the negative test passes: from a client, a connection to a peer address must fail, and the replacement must succeed, over IPv4 and IPv6.

Why draining matters mechanically. Removing a route does not send a TCP RST. The next packet is dropped and the client sits in retransmission until Linux's tcp_retries2 default of 15 gives up (about 924 seconds, roughly 15 minutes) before the application sees an error. A client mid-transaction at cutover hangs for 15 minutes and then fails, which is worse than a clean refusal. Draining first means the only flows left on the old path are ones you have already decided can fail.

Trade-offs.

approachwhen it winscost
Big-bang cutoverunder ~10 clients, stateless, off-peakone bad client = 15-minute hang, no rollback signal
Phased drain by client groupmany clients, mixed statefulnessdays of dual-path cost and dual monitoring
Soft teardown (disable, keep N days)regulated peers, hard-to-reach on-premthe path stays a live attack surface

The deciding criterion is how long a client can tolerate a failed call. If the answer is "zero", you drain. If it is "retry in 30 seconds", big-bang is fine.

Failure modes and how to detect them.

  • Stale on-prem firewall rule. The cloud side is clean but the datacenter firewall still permits the old CIDR, so return traffic is blackholed. Detect: asymmetric flow logs. Bytes out, zero bytes in.
  • DNS still resolving to the old endpoint. Clients move but the name does not. Detect: Resolver query logs showing the old private hosted zone still answering; check the record TTL before cutover.
  • Automation recreates the path. Terraform still declares the peering. Detect: terraform plan after deletion must be empty; if it proposes the peering, the next apply undoes your work.
  • Orphaned exposure. A security group rule or NACL entry referencing the peer CIDR survives the path. NACLs are stateless, so a leftover inbound allow is a real hole. Detect: query security groups and NACLs for the retired CIDR.

Close. Retain flow logs and Resolver logs for the audit window, remove the peering connection, its routes, and any endpoint or public IP, then update the runbook and diagram. The gate that matters: terraform plan clean, negative test failing, and 24 hours of zero bytes on the old path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design network security for a three-tier cloud application.

Answer

Assumptions I'd state before designing: one AWS account, the three tiers are ALB → app (EC2/ECS) → RDS Postgres, subnets are dual-stack IPv4/IPv6, and there is no service mesh. Change any of those and the answer shifts.

Core answer. Default-deny, then add exactly one allow rule per real hop, and make each rule reference an identity, a security group or a role, rather than a CIDR. Enforce at three layers: security groups at the ENI, NACLs at the subnet, and a policy layer (WAF at the edge, Network Firewall or endpoint policies for egress). The design is four hops.

HopAllowed byPortNotes
Internet → ALBALB SG: 0.0.0.0/0, ::/0443WAF + Shield; TLS 1.2+
ALB → appapp SG inbound references ALB SG id8080no CIDR anywhere
app → RDSdb SG inbound references app SG id5432RDS private, publicly_accessible = false
app → AWS APIsapp SG → interface endpoint ENIs443PrivateLink, no NAT
app → internetapp SG → NAT GW / egress-only IGW443domain allowlist at the firewall

Why the SG reference is the whole trick. A rule that says "8080 from sg-alb" is evaluated against the source ENI's group membership, so a compromised app instance cannot reach another app instance on 8080: it isn't in sg-alb. A rule that says "8080 from 10.0.1.0/24" lets any host in that subnet in, including one an attacker just launched. Same for the DB: sg-db accepts 5432 only from sg-app.

NACLs are stateless, so the return path needs its own rule: allow outbound 1024–65535 on the app subnet's NACL or the TCP handshake to RDS stalls after SYN. This is the single most common reason a correct-looking SG design still fails.

Trade-offs. SG-only (distributed) is cheap, adds no hop, and is enough for a single account with under ~10 services. Centralized inspection, Transit Gateway into a firewall VPC running AWS Network Firewall, buys L7 egress domain filtering and one place to read logs, at list price around $0.40 per endpoint-hour plus per-GB processing, and it puts an extra hop in every flow. Identity-based control (mTLS via a service mesh) gives per-call identity that survives network moves, but adds a sidecar to every pod and 1–3 ms p50 per hop. I'd pick SG-only plus private endpoints here, and only build the inspection VPC when egress filtering or multi-account central logging is a stated requirement.

Failure modes, with detection.

  • SSRF to IMDSv1. An app that fetches a user-supplied URL can read 169.254.169.254 and steal the instance role. Detect via GuardDuty UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS and CloudTrail calls from non-AWS IPs. Fix: HttpTokens: required, HttpPutResponseHopLimit: 1. Cost: agents and SDKs that only speak IMDSv1 break on rollout.
  • DB reachable from the internet. Detect with AWS Config rds-instance-public-access-check and restricted-common-ports. The fix is a subnet with no route to an IGW, not a tighter SG.
  • IPv6 gap. Rules written only for IPv4 leave ::/0 open on a dual-stack subnet. Detect by grepping VPC Flow Logs for records whose srcaddr is IPv6.
  • Open egress. Exfil to an attacker bucket. Detect via flow logs to unknown destinations and GuardDuty Exfiltration:S3/ObjectRead.Unusual.

Don't log everything. Flow logs bill per GB ingested. At 10 Gbps sustained that is ~1.25 GB/s, ~108 TB/day, so scope logging to the app and DB subnets and sample the rest.

What I'd do differently: if the app is a single service in one account, skip the inspection VPC and the mesh; SG references, private endpoints, IMDSv2 and Config rules cover it. Add centralized egress inspection only when a compliance or multi-account requirement names it.

Curated: · Written: · Reviewed:

Difficulty: Hard