cloud security

Performing GCP Security Assessment with Forseti

Performing comprehensive security assessments of Google Cloud Platform environments using Forseti Security, Security Command Center, and gcloud CLI to audit IAM policies, firewall rules, storage permissions, and compliance against CIS GCP Foundations Benchmark.

cis-benchmarkcloud-securityforsetigcpiam-auditsecurity-command-center
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When conducting periodic security assessments of GCP organizations and projects
  • When onboarding new GCP projects and establishing security baselines
  • When compliance mandates CIS GCP Foundations Benchmark evaluation
  • When auditing IAM bindings, firewall rules, and storage ACLs across multiple GCP projects
  • When building continuous security monitoring for GCP infrastructure

Do not use as a replacement for GCP Security Command Center Premium for real-time threat detection, for application-level vulnerability scanning (use Web Security Scanner), or for GKE-specific security (use GKE Security Posture).

Prerequisites

  • GCP Organization with Organization Admin or Security Admin IAM role
  • gcloud CLI authenticated with sufficient permissions (roles/securitycenter.admin, roles/iam.securityReviewer)
  • Security Command Center (SCC) enabled at the organization level
  • ScoutSuite installed for multi-cloud comparison (pip install scoutsuite)
  • Python 3.8+ for custom audit scripts using google-cloud-asset and google-cloud-securitycenter libraries

Workflow

Step 1: Enable Security Command Center and Asset Inventory

Enable SCC and set up Cloud Asset Inventory for comprehensive resource visibility.

# Enable Security Command Center API
gcloud services enable securitycenter.googleapis.com \
  --project=PROJECT_ID
 
# Enable Cloud Asset API
gcloud services enable cloudasset.googleapis.com \
  --project=PROJECT_ID
 
# List all assets in the organization
gcloud asset search-all-resources \
  --scope=organizations/ORG_ID \
  --asset-types="compute.googleapis.com/Instance,storage.googleapis.com/Bucket,iam.googleapis.com/ServiceAccount" \
  --format="table(name, assetType, location, project)"
 
# Export asset inventory to BigQuery for analysis
gcloud asset export \
  --organization=ORG_ID \
  --output-bigquery-force \
  --output-bigquery-dataset=projects/PROJECT_ID/datasets/asset_inventory \
  --output-bigquery-table=resources \
  --content-type=resource

Step 2: Audit IAM Policies and Bindings

Review IAM policies across the organization for overly permissive bindings, primitive roles, and service account misuse.

# List all IAM policy bindings at org level
gcloud organizations get-iam-policy ORG_ID \
  --format=json > org-iam-policy.json
 
# Find all users with Owner or Editor roles across projects
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:roles/owner OR policy:roles/editor" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"
 
# Identify service accounts with admin roles
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy.bindings.members:serviceAccount AND policy:roles/owner" \
  --format=json
 
# Check for allUsers or allAuthenticatedUsers bindings (public access)
gcloud asset search-all-iam-policies \
  --scope=organizations/ORG_ID \
  --query="policy:allUsers OR policy:allAuthenticatedUsers" \
  --format="table(resource, policy.bindings.role, policy.bindings.members)"
 
# List service account keys older than 90 days
gcloud iam service-accounts keys list \
  --iam-account=SA_EMAIL \
  --managed-by=user \
  --format="table(name,validAfterTime,validBeforeTime)"

Step 3: Assess Firewall Rules and Network Configuration

Audit VPC firewall rules for overly permissive ingress rules, missing logging, and network exposure.

# List all firewall rules allowing ingress 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, sourceRanges, targetTags)"
 
# Find firewall rules allowing all protocols/ports
gcloud compute firewall-rules list \
  --filter="direction=INGRESS AND allowed[].IPProtocol=all" \
  --format="table(name, network, sourceRanges, targetTags)"
 
# Check for SSH (22) and RDP (3389) open to 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)"
 
# Audit VPC flow log configuration
gcloud compute networks subnets list \
  --format="table(name, region, enableFlowLogs, logConfig.aggregationInterval)"

Step 4: Audit Cloud Storage Bucket Permissions

Check for publicly accessible storage buckets and missing encryption configurations.

# List all buckets in a project
gsutil ls -p PROJECT_ID
 
# Check bucket IAM for public access
for bucket in $(gsutil ls -p PROJECT_ID); do
  echo "=== $bucket ==="
  gsutil iam get "$bucket" | grep -E "allUsers|allAuthenticatedUsers" && \
    echo "  WARNING: PUBLIC ACCESS DETECTED" || \
    echo "  OK: No public access"
done
 
# Check bucket encryption configuration
for bucket in $(gsutil ls -p PROJECT_ID); do
  echo "=== $bucket ==="
  gsutil kms encryption "$bucket" 2>/dev/null || echo "  Using Google-managed encryption"
done
 
# Check uniform bucket-level access enforcement
for bucket in $(gsutil ls -p PROJECT_ID); do
  gsutil uniformbucketlevelaccess get "$bucket"
done

Step 5: Run ScoutSuite for Comprehensive Assessment

Execute ScoutSuite for an automated multi-check security assessment of the GCP environment.

# Run ScoutSuite against GCP
python3 -m ScoutSuite gcp \
  --user-account \
  --all-projects \
  --report-dir ./scoutsuite-gcp-report
 
# Run with service account credentials
python3 -m ScoutSuite gcp \
  --service-account /path/to/service-account-key.json \
  --all-projects \
  --report-dir ./scoutsuite-gcp-report
 
# Open the HTML report
open ./scoutsuite-gcp-report/gcp-report.html

Step 6: Query Security Command Center Findings

Retrieve and analyze SCC findings for vulnerabilities, misconfigurations, and threats.

# List active SCC findings
gcloud scc findings list ORG_ID \
  --filter="state=\"ACTIVE\" AND severity=\"CRITICAL\"" \
  --format="table(finding.category, finding.severity, finding.resourceName, finding.eventTime)"
 
# List findings by category
gcloud scc findings list ORG_ID \
  --filter="state=\"ACTIVE\" AND category=\"PUBLIC_BUCKET_ACL\"" \
  --format=json
 
# Get finding statistics grouped by category
gcloud scc findings group ORG_ID \
  --group-by="category" \
  --filter="state=\"ACTIVE\""
 
# List compliance violations from SCC
gcloud scc findings list ORG_ID \
  --filter="state=\"ACTIVE\" AND sourceProperties.compliance_standard=\"CIS\"" \
  --format="table(finding.category, finding.severity, finding.resourceName)"

Key Concepts

Term Definition
Security Command Center GCP-native security and risk management platform that provides asset inventory, vulnerability detection, and threat monitoring
Forseti Security Open-source GCP security toolkit (now deprecated in favor of SCC) that provided inventory, scanning, enforcement, and notification capabilities
Cloud Asset Inventory GCP service that provides a complete inventory of cloud resources with metadata, IAM policies, and org policy configurations
CIS GCP Foundations Benchmark Security best practice guidelines from Center for Internet Security specific to Google Cloud Platform configuration
Uniform Bucket-Level Access GCP storage setting that disables legacy ACLs and enforces access exclusively through IAM policies for consistent access control
Organization Policy GCP constraint-based governance mechanism that restricts resource configurations across the organization hierarchy

Tools & Systems

  • Security Command Center: GCP-native CSPM providing asset inventory, vulnerability findings, and compliance scoring
  • ScoutSuite: Multi-cloud security auditing tool with comprehensive GCP checks for IAM, compute, storage, and networking
  • gcloud CLI: Primary command-line interface for querying GCP resource configurations and security settings
  • Cloud Asset Inventory: API for searching and exporting resource metadata and IAM policies across GCP projects
  • Forseti Security: Legacy open-source GCP security toolkit, superseded by SCC but still referenced in compliance frameworks

Common Scenarios

Scenario: Assessing a Newly Acquired GCP Organization

Context: After a company acquisition, the security team needs to assess the security posture of the acquired company's GCP organization with 30+ projects.

Approach:

  1. Enable Cloud Asset API and export full resource inventory to BigQuery for analysis
  2. Run gcloud asset search-all-iam-policies to find all Owner/Editor bindings and public access grants
  3. Audit firewall rules across all projects for overly permissive ingress from 0.0.0.0/0
  4. Check all storage buckets for public access using gsutil iam get
  5. Run ScoutSuite for a comprehensive automated assessment with HTML report
  6. Enable SCC and review all CRITICAL and HIGH findings
  7. Generate a risk-prioritized remediation roadmap for the integration team

Pitfalls: GCP IAM bindings are inherited from organization to folder to project. A permissive binding at the organization level affects all downstream projects. Always audit IAM at every level of the hierarchy, not just at the project level.

Output Format

GCP Security Assessment Report
=================================
Organization: acme-acquired-org (ORG_ID: 123456789)
Projects Assessed: 34
Assessment Date: 2026-02-23
Standards: CIS GCP Foundations 2.0
 
IAM FINDINGS:
  Users with Owner role at org level:       3
  Service accounts with Editor role:        12
  Resources with allUsers binding:           5
  Service account keys > 90 days:           18
 
NETWORK FINDINGS:
  Firewall rules allowing 0.0.0.0/0:       14
  SSH open to internet:                      7
  RDP open to internet:                      2
  Subnets without VPC flow logs:            22
 
STORAGE FINDINGS:
  Publicly accessible buckets:               5
  Buckets without CMEK encryption:          28
  Buckets without uniform access:           15
 
CRITICAL FINDINGS: 12
HIGH FINDINGS: 34
MEDIUM FINDINGS: 78
LOW FINDINGS: 145
 
TOP REMEDIATION PRIORITIES:
  1. Remove allUsers bindings from 5 storage buckets (CRITICAL)
  2. Restrict 0.0.0.0/0 firewall rules to specific CIDRs (HIGH)
  3. Rotate 18 service account keys older than 90 days (HIGH)
  4. Enable VPC flow logs on 22 subnets (MEDIUM)
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md1.9 KB

API Reference: GCP Security Assessment with Forseti

Google Cloud Security Command Center API

Method Description
SecurityCenterClient.list_findings(parent, filter) List active findings by severity and state
SecurityCenterClient.list_sources(parent) List security sources in an organization
SecurityCenterClient.group_findings(parent, group_by) Group findings by category or severity

Cloud Asset Inventory API

Method Description
AssetServiceClient.search_all_iam_policies(scope, query) Search IAM policies across org
AssetServiceClient.search_all_resources(scope, asset_types) Search resources by type
AssetServiceClient.export_assets(parent, output_config) Export asset inventory to BigQuery

Compute Engine API (Firewall)

Method Description
FirewallsClient.list(project) List all VPC firewall rules
FirewallsClient.get(project, firewall) Get specific firewall rule details

Cloud Storage API

Method Description
Client.list_buckets() List all buckets in a project
Bucket.get_iam_policy() Get IAM policy for a bucket

Python Libraries

Library Version Purpose
google-cloud-securitycenter >=1.23 Security Command Center API access
google-cloud-asset >=3.19 Cloud Asset Inventory searches
google-cloud-storage >=2.10 Storage bucket auditing
google-cloud-compute >=1.14 Firewall rule enumeration

References

Scripts 1

agent.py7.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for performing GCP security assessment.

Audits IAM policies, firewall rules, storage permissions, and
Security Command Center findings using Google Cloud client libraries.
"""

import json
import sys
from collections import defaultdict

from google.cloud import securitycenter_v1
from google.cloud import asset_v1
from google.cloud import storage
from google.cloud import compute_v1


class GCPSecurityAssessmentAgent:
    """Performs security assessments on GCP organizations and projects."""

    def __init__(self, organization_id, project_id=None):
        self.org_id = organization_id
        self.project_id = project_id
        self.scc_client = securitycenter_v1.SecurityCenterClient()
        self.asset_client = asset_v1.AssetServiceClient()

    def list_scc_findings(self, severity="CRITICAL"):
        """List active Security Command Center findings by severity."""
        parent = f"organizations/{self.org_id}/sources/-"
        findings = []
        request = securitycenter_v1.ListFindingsRequest(
            parent=parent,
            filter=f'state="ACTIVE" AND severity="{severity}"',
        )
        for finding_result in self.scc_client.list_findings(request=request):
            f = finding_result.finding
            findings.append({
                "category": f.category,
                "severity": securitycenter_v1.Finding.Severity(f.severity).name,
                "resource": f.resource_name,
                "event_time": f.event_time.isoformat() if f.event_time else None,
                "description": f.description[:200] if f.description else "",
            })
        return findings

    def audit_iam_policies(self):
        """Search for overly permissive IAM bindings across the organization."""
        scope = f"organizations/{self.org_id}"
        findings = {"owner_bindings": [], "public_access": [], "sa_admin": []}

        for query, category in [
            ("policy:roles/owner OR policy:roles/editor", "owner_bindings"),
            ("policy:allUsers OR policy:allAuthenticatedUsers", "public_access"),
        ]:
            request = asset_v1.SearchAllIamPoliciesRequest(scope=scope, query=query)
            for result in self.asset_client.search_all_iam_policies(request=request):
                for binding in result.policy.bindings:
                    findings[category].append({
                        "resource": result.resource,
                        "role": binding.role,
                        "members": list(binding.members),
                    })
        return findings

    def audit_firewall_rules(self):
        """Audit VPC firewall rules for overly permissive ingress."""
        if not self.project_id:
            return {"error": "project_id required for firewall audit"}

        client = compute_v1.FirewallsClient()
        risky_rules = []

        for rule in client.list(project=self.project_id):
            if rule.direction != "INGRESS":
                continue
            source_ranges = list(rule.source_ranges) if rule.source_ranges else []
            if "0.0.0.0/0" not in source_ranges:
                continue
            allowed_ports = []
            for allowed in rule.allowed:
                ports = list(allowed.ports) if allowed.ports else ["all"]
                allowed_ports.append({
                    "protocol": allowed.I_p_protocol,
                    "ports": ports,
                })
            risky_rules.append({
                "name": rule.name,
                "network": rule.network,
                "source_ranges": source_ranges,
                "allowed": allowed_ports,
                "priority": rule.priority,
                "disabled": rule.disabled,
            })
        return risky_rules

    def audit_storage_buckets(self):
        """Check storage buckets for public access and encryption settings."""
        if not self.project_id:
            return {"error": "project_id required for storage audit"}

        client = storage.Client(project=self.project_id)
        bucket_findings = []

        for bucket in client.list_buckets():
            policy = bucket.get_iam_policy()
            is_public = False
            public_roles = []
            for binding in policy.bindings:
                members = set(binding.get("members", []))
                if "allUsers" in members or "allAuthenticatedUsers" in members:
                    is_public = True
                    public_roles.append(binding["role"])

            bucket_findings.append({
                "name": bucket.name,
                "location": bucket.location,
                "storage_class": bucket.storage_class,
                "is_public": is_public,
                "public_roles": public_roles,
                "uniform_access": bucket.iam_configuration.get(
                    "uniformBucketLevelAccess", {}
                ).get("enabled", False),
                "versioning": bucket.versioning_enabled,
            })
        return bucket_findings

    def get_finding_summary(self):
        """Get summary counts of SCC findings grouped by severity."""
        parent = f"organizations/{self.org_id}/sources/-"
        summary = defaultdict(int)

        for severity in ["CRITICAL", "HIGH", "MEDIUM", "LOW"]:
            request = securitycenter_v1.ListFindingsRequest(
                parent=parent,
                filter=f'state="ACTIVE" AND severity="{severity}"',
            )
            count = 0
            for _ in self.scc_client.list_findings(request=request):
                count += 1
            summary[severity] = count
        return dict(summary)

    def generate_assessment_report(self):
        """Generate a comprehensive GCP security assessment report."""
        report = {
            "organization_id": self.org_id,
            "project_id": self.project_id,
        }

        report["scc_findings_summary"] = self.get_finding_summary()
        report["critical_findings"] = self.list_scc_findings("CRITICAL")
        report["iam_audit"] = self.audit_iam_policies()

        if self.project_id:
            report["firewall_audit"] = self.audit_firewall_rules()
            report["storage_audit"] = self.audit_storage_buckets()

        print(json.dumps(report, indent=2, default=str))
        return report


def main():
    if len(sys.argv) < 2:
        print("Usage: agent.py <org_id> [project_id] [action]")
        print("Actions: report, findings, iam, firewall, storage")
        sys.exit(1)

    org_id = sys.argv[1]
    project_id = sys.argv[2] if len(sys.argv) > 2 else None
    action = sys.argv[3] if len(sys.argv) > 3 else "report"

    agent = GCPSecurityAssessmentAgent(org_id, project_id)

    if action == "report":
        agent.generate_assessment_report()
    elif action == "findings":
        findings = agent.list_scc_findings()
        print(json.dumps(findings, indent=2, default=str))
    elif action == "iam":
        iam = agent.audit_iam_policies()
        print(json.dumps(iam, indent=2))
    elif action == "firewall":
        fw = agent.audit_firewall_rules()
        print(json.dumps(fw, indent=2))
    elif action == "storage":
        buckets = agent.audit_storage_buckets()
        print(json.dumps(buckets, indent=2))


if __name__ == "__main__":
    main()
Keep exploring