npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- When deploying new GCP workloads that require network-level access controls
- When auditing existing firewall configurations for overly permissive rules
- When implementing zero trust network segmentation within GCP VPC networks
- When responding to Security Command Center findings about open firewall rules
- When building hierarchical firewall policies across a GCP organization
Do not use for application-layer filtering (use Cloud Armor WAF), for DNS-based filtering (use Cloud DNS response policies), or for VPN/interconnect traffic filtering without understanding that VPC firewall rules apply to traffic within the VPC.
Prerequisites
- GCP project with Compute Engine API enabled
- IAM roles:
roles/compute.securityAdminfor firewall management,roles/compute.networkViewerfor auditing - Organization Admin role for hierarchical firewall policies
- gcloud CLI authenticated with appropriate permissions
- VPC Flow Logs enabled on target subnets for monitoring
Workflow
Step 1: Audit Existing Firewall Rules for Security Gaps
Enumerate all firewall rules and identify overly permissive configurations.
# List all firewall rules in the project
gcloud compute firewall-rules list \
--format="table(name, network, direction, priority, allowed[].map().firewall_rule().list():label=ALLOWED, sourceRanges, targetTags)"
# Find rules allowing all traffic from 0.0.0.0/0
gcloud compute firewall-rules list \
--filter="direction=INGRESS AND sourceRanges=0.0.0.0/0" \
--format="table(name, network, allowed, priority, targetTags)" \
--sort-by=priority
# Find rules allowing all protocols and ports
gcloud compute firewall-rules list \
--filter="direction=INGRESS AND allowed[].IPProtocol=all" \
--format="table(name, network, sourceRanges, targetTags)"
# Find rules with SSH (22) or RDP (3389) open to the internet
gcloud compute firewall-rules list \
--filter="direction=INGRESS AND sourceRanges=0.0.0.0/0 AND (allowed[].ports=22 OR allowed[].ports=3389)" \
--format="table(name, network, allowed, sourceRanges)"
# Check for disabled rules
gcloud compute firewall-rules list \
--filter="disabled=true" \
--format="table(name, network, direction)"Step 2: Create Restrictive Ingress Firewall Rules
Implement least-privilege ingress rules using network tags and service accounts for targeting.
# Create rule allowing HTTPS from the internet to web servers only
gcloud compute firewall-rules create allow-https-web \
--network=production-vpc \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:443 \
--source-ranges=0.0.0.0/0 \
--target-tags=web-server \
--priority=1000 \
--description="Allow HTTPS to web servers from internet"
# Create rule allowing SSH only from bastion host subnet
gcloud compute firewall-rules create allow-ssh-bastion \
--network=production-vpc \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:22 \
--source-ranges=10.0.1.0/24 \
--target-tags=ssh-allowed \
--priority=1000 \
--description="Allow SSH only from bastion subnet"
# Create rule allowing internal communication between app tiers
gcloud compute firewall-rules create allow-app-to-db \
--network=production-vpc \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:5432 \
--source-tags=app-server \
--target-tags=db-server \
--priority=1000 \
--description="Allow PostgreSQL from app tier to database tier"
# Create service-account-based rule (more secure than tags)
gcloud compute firewall-rules create allow-api-internal \
--network=production-vpc \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:8080 \
--source-service-accounts=api-client@project.iam.gserviceaccount.com \
--target-service-accounts=api-server@project.iam.gserviceaccount.com \
--priority=1000Step 3: Implement Egress Restrictions
Configure egress firewall rules to control outbound traffic and prevent data exfiltration.
# Deny all egress by default (low priority)
gcloud compute firewall-rules create deny-all-egress \
--network=production-vpc \
--direction=EGRESS \
--action=DENY \
--rules=all \
--destination-ranges=0.0.0.0/0 \
--priority=65534 \
--description="Default deny all egress traffic"
# Allow egress to Google APIs via restricted VIP
gcloud compute firewall-rules create allow-google-apis \
--network=production-vpc \
--direction=EGRESS \
--action=ALLOW \
--rules=tcp:443 \
--destination-ranges=199.36.153.4/30 \
--priority=1000 \
--description="Allow HTTPS to Google APIs restricted VIP"
# Allow DNS resolution
gcloud compute firewall-rules create allow-dns-egress \
--network=production-vpc \
--direction=EGRESS \
--action=ALLOW \
--rules=udp:53,tcp:53 \
--destination-ranges=169.254.169.254/32,8.8.8.8/32,8.8.4.4/32 \
--priority=1000 \
--description="Allow DNS resolution to metadata and Google DNS"
# Allow egress to specific external services
gcloud compute firewall-rules create allow-external-apis \
--network=production-vpc \
--direction=EGRESS \
--action=ALLOW \
--rules=tcp:443 \
--destination-ranges=PARTNER_CIDR/32 \
--target-tags=api-client \
--priority=1000Step 4: Deploy Hierarchical Firewall Policies
Create organization and folder-level firewall policies that apply across all projects.
# Create an organization-level firewall policy
gcloud compute firewall-policies create \
--organization=ORG_ID \
--short-name=org-security-policy \
--description="Organization-wide security firewall policy"
# Add rule to block known malicious IP ranges at org level
gcloud compute firewall-policies rules create 100 \
--firewall-policy=org-security-policy \
--organization=ORG_ID \
--direction=INGRESS \
--action=deny \
--src-ip-ranges=THREAT_INTEL_CIDR_1,THREAT_INTEL_CIDR_2 \
--layer4-configs=all \
--description="Block known malicious IPs organization-wide"
# Add rule to enforce HTTPS-only ingress at org level
gcloud compute firewall-policies rules create 200 \
--firewall-policy=org-security-policy \
--organization=ORG_ID \
--direction=INGRESS \
--action=allow \
--src-ip-ranges=0.0.0.0/0 \
--layer4-configs=tcp:443 \
--description="Allow only HTTPS from external sources"
# Associate policy with the organization
gcloud compute firewall-policies associations create \
--firewall-policy=org-security-policy \
--organization=ORG_IDStep 5: Enable VPC Flow Logs for Monitoring
Configure VPC Flow Logs to monitor traffic patterns and validate firewall rule effectiveness.
# Enable flow logs on a subnet
gcloud compute networks subnets update production-subnet \
--region=us-central1 \
--enable-flow-logs \
--logging-aggregation-interval=interval-5-sec \
--logging-flow-sampling=1.0 \
--logging-metadata=include-all
# Query flow logs in Cloud Logging for denied traffic
gcloud logging read '
resource.type="gce_subnetwork"
AND jsonPayload.disposition="DENIED"
AND timestamp>="2026-02-22T00:00:00Z"
' --limit=50 --format=json
# Find traffic hitting overly permissive rules
gcloud logging read '
resource.type="gce_subnetwork"
AND jsonPayload.rule_details.reference:"/firewall-rules/default-allow-"
' --limit=100 --format="table(jsonPayload.connection.src_ip,jsonPayload.connection.dest_ip,jsonPayload.connection.dest_port)"
# Export flow logs to BigQuery for analysis
gcloud logging sinks create vpc-flow-bq \
bigquery.googleapis.com/projects/PROJECT/datasets/vpc_flow_logs \
--log-filter='resource.type="gce_subnetwork"'Key Concepts
| Term | Definition |
|---|---|
| VPC Firewall Rule | Stateful network-level access control that allows or denies traffic to and from VM instances based on IP ranges, protocols, ports, and tags |
| Hierarchical Firewall Policy | Organization or folder-level firewall policy that is evaluated before VPC-level rules and applies across all child projects |
| Network Tag | Label applied to VM instances that determines which firewall rules apply, used for targeting ingress and egress rules |
| Service Account Firewall Rule | Firewall rule that targets instances based on their attached service account, providing more secure targeting than mutable network tags |
| VPC Flow Logs | Network telemetry captured at the subnet level that records traffic metadata for monitoring, forensics, and firewall rule validation |
| Implied Rules | Default GCP firewall rules that allow egress to all destinations and deny ingress from all sources, with lowest priority (65535) |
Tools & Systems
- gcloud compute firewall-rules: CLI commands for creating, listing, and managing VPC firewall rules in GCP
- Hierarchical Firewall Policies: Organization and folder-level policies enforcing security controls across all projects
- VPC Flow Logs: Subnet-level traffic logging for monitoring, troubleshooting, and validating firewall effectiveness
- Cloud Logging: Query engine for analyzing VPC Flow Logs and firewall rule hit counts
- Security Command Center: GCP-native security platform with findings for overly permissive firewall configurations
Common Scenarios
Scenario: Locking Down a Production VPC After Discovery of Overly Permissive Rules
Context: A security audit reveals that the production VPC has default-allow rules permitting SSH from 0.0.0.0/0 and unrestricted egress. SCC reports 14 firewall findings.
Approach:
- Enumerate all existing rules with
gcloud compute firewall-rules listand categorize by risk - Enable VPC Flow Logs on all subnets to capture baseline traffic patterns for 7 days
- Analyze flow logs to identify legitimate traffic that needs explicit allow rules
- Create targeted ingress rules for each application tier (web: 443, app: 8080, db: 5432)
- Replace the SSH-from-anywhere rule with SSH-from-bastion-subnet-only
- Implement default-deny egress and add explicit allow rules for required outbound destinations
- Delete the overly permissive default-allow rules after verifying applications function correctly
Pitfalls: Deleting firewall rules without understanding traffic patterns causes outages. Always enable flow logs and analyze traffic before removing rules. Network tags can be added by anyone with compute.instances.setTags permission, making them less secure than service-account-based targeting for critical rules.
Output Format
GCP VPC Firewall Audit Report
================================
Project: production-project
VPC Network: production-vpc
Audit Date: 2026-02-23
RULE INVENTORY:
Total firewall rules: 34
Ingress rules: 22
Egress rules: 12
Disabled rules: 3
CRITICAL FINDINGS:
[FW-001] SSH Open to Internet
Rule: default-allow-ssh
Source: 0.0.0.0/0 -> tcp:22
Target: All instances (no tags)
Priority: 65534
Remediation: Restrict to bastion subnet CIDR
[FW-002] No Egress Restrictions
Issue: Only implied allow-all-egress rule exists
Risk: No controls on outbound data exfiltration
Remediation: Add default-deny egress and explicit allow rules
REMEDIATION ACTIONS COMPLETED:
Rules deleted: 3 (overly permissive defaults)
Rules created: 8 (targeted allow rules)
Egress deny rule: Created at priority 65534
Flow logs enabled: 6 subnetsReferences and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.3 KB
API Reference: Implementing GCP VPC Firewall Rules
Libraries
google-cloud-compute
- Install:
pip install google-cloud-compute - Docs: https://cloud.google.com/python/docs/reference/compute/latest
Key Classes and Methods
| Class | Method | Description |
|---|---|---|
FirewallsClient |
list(project) |
List all firewall rules |
FirewallsClient |
get(project, firewall) |
Get rule details |
FirewallsClient |
insert(project, firewall_resource) |
Create rule |
FirewallsClient |
patch(project, firewall, firewall_resource) |
Update rule |
FirewallsClient |
delete(project, firewall) |
Delete rule |
NetworksClient |
list(project) |
List VPC networks |
Firewall Rule Object Fields
name-- Rule name (unique per project)network-- VPC network pathdirection--INGRESSorEGRESSpriority-- 0 (highest) to 65535 (lowest)allowed[]-- Protocol and port combinations to allowdenied[]-- Protocol and port combinations to denysource_ranges[]-- Source CIDR ranges for ingressdestination_ranges[]-- Destination CIDRs for egresstarget_tags[]-- Network tags to apply rule tosource_tags[]-- Source instance tagsdisabled-- Boolean to disable without deletinglog_config.enable-- Enable firewall rule logging
Priority Ranges (Best Practice)
- 0-999: Emergency/override rules
- 1000-9999: Organization policies
- 10000-49999: Application-specific rules
- 50000-64999: Default deny rules
- 65534: Implied allow egress (GCP default)
- 65535: Implied deny ingress (GCP default)
gcloud CLI Equivalents
gcloud compute firewall-rules listgcloud compute firewall-rules create NAME --allow tcp:22 --source-ranges 10.0.0.0/8gcloud compute firewall-rules delete NAMEgcloud compute firewall-rules update NAME --disabled
Hierarchical Firewall Policies
- Organization-level:
compute.firewallPolicies - Folder-level: Applied via
compute.firewallPolicies.addAssociation - Evaluation order: Organization > Folder > VPC rules
External References
- VPC Firewall Rules: https://cloud.google.com/vpc/docs/firewalls
- Firewall Policies: https://cloud.google.com/vpc/docs/firewall-policies
- VPC Flow Logs: https://cloud.google.com/vpc/docs/using-flow-logs
- Cloud Armor WAF: https://cloud.google.com/armor/docs
Scripts 1
agent.py7.4 KB
#!/usr/bin/env python3
"""GCP VPC firewall rules audit and management agent."""
import json
import sys
import argparse
from datetime import datetime
try:
from google.cloud import compute_v1
from google.api_core.exceptions import GoogleAPIError
except ImportError:
print("Install: pip install google-cloud-compute")
sys.exit(1)
def get_firewall_client():
"""Create GCP Compute Engine firewall client."""
return compute_v1.FirewallsClient()
def list_firewall_rules(project_id):
"""List all VPC firewall rules in a project."""
client = get_firewall_client()
rules = []
for rule in client.list(project=project_id):
rules.append({
"name": rule.name,
"network": rule.network.split("/")[-1] if rule.network else "",
"direction": rule.direction,
"priority": rule.priority,
"action": "ALLOW" if rule.allowed else "DENY",
"source_ranges": list(rule.source_ranges) if rule.source_ranges else [],
"destination_ranges": list(rule.destination_ranges) if rule.destination_ranges else [],
"target_tags": list(rule.target_tags) if rule.target_tags else [],
"allowed": [{"protocol": a.I_p_protocol,
"ports": list(a.ports) if a.ports else ["all"]}
for a in rule.allowed] if rule.allowed else [],
"denied": [{"protocol": d.I_p_protocol,
"ports": list(d.ports) if d.ports else ["all"]}
for d in rule.denied] if rule.denied else [],
"disabled": rule.disabled,
"log_config_enabled": rule.log_config.enable if rule.log_config else False,
})
return sorted(rules, key=lambda r: r["priority"])
def find_overly_permissive_rules(project_id):
"""Identify firewall rules that are overly permissive (0.0.0.0/0)."""
rules = list_firewall_rules(project_id)
findings = []
for rule in rules:
if rule["disabled"]:
continue
if "0.0.0.0/0" in rule.get("source_ranges", []):
for allowed in rule.get("allowed", []):
ports = allowed.get("ports", ["all"])
severity = "CRITICAL" if "all" in ports or "22" in ports or "3389" in ports \
else "HIGH" if "80" in ports or "443" in ports else "MEDIUM"
findings.append({
"rule_name": rule["name"],
"network": rule["network"],
"severity": severity,
"protocol": allowed["protocol"],
"ports": ports,
"issue": "Source range 0.0.0.0/0 allows traffic from any IP",
"recommendation": "Restrict source ranges to specific CIDR blocks",
})
return findings
def audit_default_rules(project_id):
"""Audit default network firewall rules for security issues."""
rules = list_firewall_rules(project_id)
default_issues = []
for rule in rules:
if "default" in rule["name"].lower():
if "0.0.0.0/0" in rule.get("source_ranges", []) and not rule["disabled"]:
default_issues.append({
"rule": rule["name"],
"issue": "Default rule allows traffic from all sources",
"action": "Disable or restrict default permissive rules",
})
return default_issues
def create_firewall_rule(project_id, name, network, direction, priority,
allowed_protocols, source_ranges, target_tags=None):
"""Create a new VPC firewall rule."""
client = get_firewall_client()
allowed = []
for proto, ports in allowed_protocols.items():
entry = compute_v1.Allowed()
entry.I_p_protocol = proto
if ports:
entry.ports = ports
allowed.append(entry)
rule = compute_v1.Firewall()
rule.name = name
rule.network = f"projects/{project_id}/global/networks/{network}"
rule.direction = direction
rule.priority = priority
rule.allowed = allowed
rule.source_ranges = source_ranges
if target_tags:
rule.target_tags = target_tags
rule.log_config = compute_v1.FirewallLogConfig(enable=True)
try:
operation = client.insert(project=project_id, firewall_resource=rule)
return {"name": name, "status": "creating", "operation": operation.name}
except GoogleAPIError as e:
return {"name": name, "status": "error", "message": str(e)}
def delete_firewall_rule(project_id, rule_name):
"""Delete a firewall rule by name."""
client = get_firewall_client()
try:
operation = client.delete(project=project_id, firewall=rule_name)
return {"name": rule_name, "status": "deleting", "operation": operation.name}
except GoogleAPIError as e:
return {"name": rule_name, "status": "error", "message": str(e)}
def check_logging_status(project_id):
"""Check which firewall rules have logging enabled."""
rules = list_firewall_rules(project_id)
unlogged = [r for r in rules if not r["log_config_enabled"] and not r["disabled"]]
logged = [r for r in rules if r["log_config_enabled"]]
return {"logged": len(logged), "unlogged": len(unlogged),
"unlogged_rules": [r["name"] for r in unlogged]}
def run_firewall_audit(project_id):
"""Run a comprehensive firewall audit."""
print(f"\n{'='*60}")
print(f" GCP VPC FIREWALL AUDIT")
print(f" Project: {project_id}")
print(f" Generated: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC")
print(f"{'='*60}\n")
rules = list_firewall_rules(project_id)
print(f"--- ALL RULES ({len(rules)}) ---")
for r in rules:
status = "DISABLED" if r["disabled"] else "ACTIVE"
print(f" [{r['priority']:5d}] {r['name']} ({status}) -> {r['network']}")
findings = find_overly_permissive_rules(project_id)
print(f"\n--- OVERLY PERMISSIVE RULES ({len(findings)}) ---")
for f in findings:
print(f" [{f['severity']}] {f['rule_name']}: {f['protocol']} ports {f['ports']}")
print(f" {f['recommendation']}")
default_issues = audit_default_rules(project_id)
print(f"\n--- DEFAULT RULE ISSUES ({len(default_issues)}) ---")
for d in default_issues:
print(f" {d['rule']}: {d['issue']}")
logging = check_logging_status(project_id)
print(f"\n--- LOGGING STATUS ---")
print(f" Rules with logging: {logging['logged']}")
print(f" Rules without logging: {logging['unlogged']}")
print(f"\n{'='*60}\n")
return {"total_rules": len(rules), "permissive_findings": len(findings),
"logging": logging}
def main():
parser = argparse.ArgumentParser(description="GCP VPC Firewall Rules Agent")
parser.add_argument("--project", required=True, help="GCP project ID")
parser.add_argument("--audit", action="store_true", help="Run firewall audit")
parser.add_argument("--list", action="store_true", help="List all rules")
parser.add_argument("--output", help="Save report to JSON")
args = parser.parse_args()
if args.audit:
report = run_firewall_audit(args.project)
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
elif args.list:
rules = list_firewall_rules(args.project)
print(json.dumps(rules, indent=2))
else:
parser.print_help()
if __name__ == "__main__":
main()