Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-scc-remediation@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin google-cloud-scc-remediation v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install google-cloud-scc-remediation

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/google-cloud-scc-remediation/

Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-scc-remediation for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 12.1 KB
---
name: google-cloud-scc-remediation
metadata:
  category: Security
  version: "1.0.1"
description: >-
  Remediates Google Cloud Security Command Center findings, including IAM
  permission fixes, cloud resource misconfigurations, vulnerabilities, and Toxic
  Combinations. Use when asked to fix, remediate, or mitigate a Security Command Center
  finding or address attack paths. Don't use for general IAM policy querying without a
  Security Command Center finding. For runtime threat detections, this skill provides
  containment and investigation guidance rather than automated configuration fixes.
---

# Google Cloud Security Command Center Remediation

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).

## Overview

A unified remediation skill for Google Cloud Security Command Center findings.
It handles both single-domain findings and multi-domain Toxic Combinations.

## 1. Safety & Consent Gate

Security Command Center remediations modify infrastructure, access policies, or
workload deployments.

*   **Mandatory Consent Gate**: NEVER execute mutating `gcloud`, `terraform`, or
    API commands without first presenting a structured remediation plan and the
    exact command/config diff to the user. STOP after presenting the plan and
    ALWAYS ask: "Do you approve executing this remediation plan?" before
    execution. Automatic mutation of security policies or resource
    configurations can cause unintended outages, lockouts, or compliance
    violations.
*   **Confirm the Target Project**: Before executing, confirm that the active
    `gcloud` account and project match the project of the finding's resource.
    Every mutating command MUST specify the target explicitly, with `--project`
    or a full resource path, rather than relying on the default `gcloud`
    project.
*   **Verification & Rollback Required**: Every proposed remediation plan MUST
    explicitly include, for each mutating step:
    *   the mutating remediation command(s),
    *   the verification check command(s) (`gcloud ... describe` or `list`), and
    *   the rollback command(s) that undo the change, or an explicit statement
        that the step cannot be undone (for example, service account key
        deletion).

    Use the commands from the loaded playbook where they exist. If the playbook
    lacks a verification or rollback command for a step, derive the command and
    label it as not sourced from a playbook.
*   **Dependency & Impact Checks**: Every remediation plan MUST state what could
    break as a result of each change and ask the user to confirm nothing depends
    on it. For example:
    *   IAM role changes or revocations: you MUST explicitly advise the user to
        verify cross-project dependencies and CI/CD pipeline workflows that rely
        on the existing permissions before revoking a project-level role
        binding.
    *   Firewall rule changes: other traffic the same rule allows (such as web
        traffic on ports 80 or 443).
    *   External IP removal: inbound access and outbound internet access for the
        VM.
    *   Public Access Prevention on a bucket: sites or users that legitimately
        read it publicly.
*   **CRITICAL WORKFLOW RULE**: Do NOT execute any mutating commands in the same
    turn that you present the remediation plan. You MUST end your turn
    immediately after asking for approval and wait for the user's next message.
    *   If there is no interactive user (for example, a scheduled or pipeline
        run), stop at the plan and never execute.
    *   If the user approves only part of the plan, or the plan changes after
        approval, present the updated plan and ask for approval again before
        executing.
*   **Narrowly Scoped Changes**: Always propose the narrowest possible fix that
    resolves the finding. When more than one fix would work, prefer reversible
    changes over irreversible ones (for example, disable a key before deleting
    it), resource-level changes over project, folder, or organization-level
    changes, and changes that affect only the finding's resource over changes
    that affect other resources. Do not bundle fixes for unrelated issues
    noticed along the way; mention them to the user separately.

## 2. Intent Router & Progressive Disclosure

Do not load all reference playbooks into memory at once. Analyze the Security
Command Center finding's `category`, `findingClass`, or attack path, then read
ONLY the relevant reference document(s).

Match on the finding's `category` **first**, and fall back to `findingClass`
only when no category matches. Routing on `findingClass` alone misroutes IAM
findings: Security Health Analytics IAM findings are `MISCONFIGURATION` class,
and IAM recommender findings are `Vulnerability` class, so neither would ever
reach the IAM playbook.

| Match On                | Values                                    | Target Reference Playbook                                                    |
| :---------------------- | :---------------------------------------- | :--------------------------------------------------------------------------- |
| `category`              | `PRIMITIVE_ROLES_USED`,                   | [`references/remediation_iam.md`](references/remediation_iam.md)             |
: (Security Health        : `OVER_PRIVILEGED_SERVICE_ACCOUNT_USER`,   :                                                                              :
: Analytics)              : `ADMIN_SERVICE_ACCOUNT`,                  :                                                                              :
:                         : `SERVICE_ACCOUNT_ROLE_SEPARATION`,        :                                                                              :
:                         : `KMS_ROLE_SEPARATION`,                    :                                                                              :
:                         : `USER_MANAGED_SERVICE_ACCOUNT_KEY`,       :                                                                              :
:                         : `SERVICE_ACCOUNT_KEY_NOT_ROTATED`         :                                                                              :
| `category`              | `IAM_ROLE_HAS_EXCESSIVE_PERMISSIONS`,     | [`references/remediation_iam.md`](references/remediation_iam.md)             |
: (IAM recommender)       : `UNUSED_IAM_ROLE`,                        :                                                                              :
:                         : `SERVICE_AGENT_GRANTED_BASIC_ROLE`,       :                                                                              :
:                         : `SERVICE_AGENT_ROLE_REPLACED_WITH_BASIC_ROLE` :                                                                          :
| `category`              | `PUBLIC_BUCKET_ACL`, `PUBLIC_IP_ADDRESS`, | [`references/remediation_misconfig.md`](references/remediation_misconfig.md) |
: (Security Health        : `OPEN_FIREWALL`, `OPEN_SSH_PORT`,         :                                                                              :
: Analytics)              : `OPEN_RDP_PORT`, `KMS_KEY_NOT_ROTATED`   :                                                                              :
| `category`              | `OS_VULNERABILITY`, `SOFTWARE_VULNERABILITY`, | [`references/remediation_vuln.md`](references/remediation_vuln.md)           |
:                         : `GKE_RUNTIME_OS_VULNERABILITY` (CVEs, OS  :                                                                              :
:                         : patch, container base image upgrade,      :                                                                              :
:                         : vulnerable package, GKE node pool upgrade). :                                                                            :
:                         : Note: Web Security Scanner (WSS) findings :                                                                              :
:                         : fall through to *no match* below.         :                                                                              :
| `findingClass`          | `TOXIC_COMBINATION` — attack path         | **Sequential Load**: Identify each exposed facet in the attack path and load |
:                         : exposure, multi-domain attack vector      : the matching reference playbooks sequentially.                               :
| *no match*              | Any other category or finding class       | See **Findings Without Dedicated Playbooks** below. Do not force a finding   |
:                         :                                           : into a playbook that does not cover it.                                      :

### Findings Without Dedicated Playbooks & Runtime Threat Detections

When presented with Security Command Center findings that do not have automated
configuration remediation playbooks—such as runtime threat detections (e.g.,
Cloud Run Threat Detection, Agent Platform Threat Detection, Event Threat
Detection, Container Threat Detection):

1.  **Do NOT execute automated mutation commands**: Runtime threat detections
    represent active alerts or behavioral anomalies rather than static resource
    misconfigurations.
2.  **Provide Documentation & Containment Guidance**:
    *   Refer the user to the relevant Security Command Center documentation
        (e.g.,
        [Cloud Run Threat Detection](https://docs.cloud.google.com/security-command-center/docs/cloud-run-threat-detection-overview.md.txt#detectors),
        [Agent Platform Threat Detection](https://docs.cloud.google.com/security-command-center/docs/agent-platform-threat-detection-overview.md.txt#detectors)).
    *   Recommend manual investigation steps: analyzing audit logs in Cloud
        Logging, identifying compromised service accounts or API keys, and
        isolating affected workloads.
    *   Advise the user on containment options (e.g., revoking active
        credentials, blocking malicious IPs at Cloud Armor/firewall).

## 3. Standard Remediation Workflow

1.  **Inspect Finding Details & Intentionality**:
    *   If the finding's details are not already in the conversation, retrieve
        them using the `google-cloud-scc-query` skill. Verify the finding name,
        affected resource (`resourceName`), category, and attack exposure score.
    *   Before planning a fix, ask the user whether the flagged configuration is
        intentional (for example, a bucket serving a public website, or a VM that
        must accept public traffic). If it is, do not propose a remediation.
        Suggest muting the finding with a documented justification instead;
        muting changes the finding's state, so it also requires the user's
        approval.
2.  **Route & Load Reference**: Read the matching reference playbook(s) from the
    routing table above.
3.  **Formulate Least-Privilege Remediation**: Before drafting, check whether the
    resource is managed by infrastructure as code (ask the user, and check for
    signals such as the `goog-terraform-provisioned` label). If it is, draft the
    change to the Terraform configuration rather than a `gcloud` command.
    Otherwise, draft the exact CLI (`gcloud`) or IAM binding change needed to
    close the exposure without disrupting business workloads.
4.  **Present Plan & Seek Consent**: Show the user the plan required by the
    Safety & Consent Gate: for each step, the remediation command, the
    verification command, the rollback command, and what could break. STOP
    execution here and ALWAYS ask the explicit question: "Do you approve
    executing this remediation plan?"
5.  **Execute on Approval**: ONLY after receiving explicit user confirmation,
    execute the remediation commands and run the verification commands to confirm
    the resource is fixed. If a command fails, stop and report the error; do not
    try a different command without presenting it and getting approval again.
    Tell the user that the finding's state in Security Command Center updates on
    the detector's next scan, which may take some time, and do not manually mark
    the finding as resolved.
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-scc-remediation)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include
    `agent-skills/1.0 (skill:google-cloud-scc-remediation)`
    in the `User-Agent` header. If a `User-Agent` header is already specified,
    append this string to the end of it rather than overwriting existing
    `User-Agent` data — the collection pipeline parses the
    `agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
    attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-scc-remediation)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
remediation_iam.md 6.8 KB
# IAM Remediation Playbook (`remediation_iam.md`)

Use this playbook when remediating Security Command Center findings related to
over-privileged service accounts, basic role bindings, or unrotated service
account keys. This covers the Security Health Analytics categories
`PRIMITIVE_ROLES_USED`, `OVER_PRIVILEGED_SERVICE_ACCOUNT_USER`,
`ADMIN_SERVICE_ACCOUNT`, `SERVICE_ACCOUNT_ROLE_SEPARATION`,
`KMS_ROLE_SEPARATION`, `USER_MANAGED_SERVICE_ACCOUNT_KEY`, and
`SERVICE_ACCOUNT_KEY_NOT_ROTATED`, plus the IAM recommender categories
`IAM_ROLE_HAS_EXCESSIVE_PERMISSIONS`, `UNUSED_IAM_ROLE`,
`SERVICE_AGENT_GRANTED_BASIC_ROLE`, and
`SERVICE_AGENT_ROLE_REPLACED_WITH_BASIC_ROLE`.

**Usage and consent**: This playbook is a reference for the
`google-cloud-scc-remediation` skill and inherits that skill's consent gate,
even if you reached this file directly. Every mutating command below MUST be
presented to the user as part of a remediation plan, together with its
verification command, and MUST NOT be executed until the user answers "Do you
approve executing this remediation plan?". Never execute a mutating command in
the same turn you propose it.

## Table of Contents

*   [1. Core Principles](#1-core-principles)
*   [2. Inspecting Current IAM Bindings](#2-inspecting-current-iam-bindings)
*   [3. Standard Remediation Patterns](#3-standard-remediation-patterns)
    *   [A. Revoking Overly Broad Basic Roles](#a-revoking-overly-broad-basic-roles)
    *   [B. Remediating Default Service Account Overuse](#b-remediating-default-service-account-overuse)
    *   [C. User-Managed Service Account Key Management & Rotation](#c-user-managed-service-account-key-management--rotation)
    *   [D. Separation of Duties & Sensitive IAM Roles](#d-separation-of-duties--sensitive-iam-roles)
    *   [E. Scoping Service Account Impersonation](#e-scoping-service-account-impersonation)
*   [4. Verification Check](#4-verification-check)

## 1. Core Principles

*   **Principle of Least Privilege**: Replace basic roles — `roles/admin`,
    `roles/writer`, `roles/reader`, and the legacy `roles/owner`,
    `roles/editor`, `roles/viewer` — or other overly broad roles with predefined
    or custom roles scoped strictly to required API actions.
*   **Check Cross-Project Dependencies**: You shouldn't try to determine this
    yourself. Before revoking a binding from a service account, ask the user to
    confirm whether other services or CI/CD pipelines rely on those permissions,
    and tell them which breakages to look for. Never assert that a revocation is
    safe.

## 2. Inspecting Current IAM Bindings

Before drafting a fix, inspect the current IAM policy bindings for the affected
resource:

```bash
# Check project-level IAM policy for a specific member
gcloud projects get-iam-policy {PROJECT_ID} \
    --flatten="bindings[].members" \
    --format="table(bindings.role)" \
    --filter="bindings.members:{MEMBER_EMAIL}"
```

## 3. Standard Remediation Patterns

### A. Revoking Overly Broad Basic Roles

When a principal holds a basic role (`roles/admin`, `roles/writer`, or the
legacy `roles/owner`, `roles/editor`), revoke the basic role after identifying
the specific replacement role required:

```bash
# 1. Grant the least-privilege replacement role first (to prevent outage)
gcloud projects add-iam-policy-binding {PROJECT_ID} \
    --member="serviceAccount:{SERVICE_ACCOUNT_EMAIL}" \
    --role="{LEAST_PRIVILEGE_ROLE}"

# 2. Remove the troublesome basic role
gcloud projects remove-iam-policy-binding {PROJECT_ID} \
    --member="serviceAccount:{SERVICE_ACCOUNT_EMAIL}" \
    --role="{BASIC_ROLE}"
```

### B. Remediating Default Service Account Overuse

If a workload is using the default Compute Engine or App Engine service account
with editor permissions:

1.  Recommend creating a dedicated user-managed service account.
2.  Grant only the minimal required IAM roles to the new service account.
3.  Update the workload to run as the new service account.

### C. User-Managed Service Account Key Management & Rotation

When a finding reports unrotated or expired user-managed service account keys
(`USER_MANAGED_SERVICE_ACCOUNT_KEY`, `SERVICE_ACCOUNT_KEY_NOT_ROTATED`):

1.  **Prefer Workload Identity / Short-Lived Credentials**: Recommend migrating
    workloads to Workload Identity Federation or attached service accounts to
    eliminate exported keys.
2.  **Disable the Stale Key** (reversible):

    ```bash
    # List user-managed keys. The default table includes a DISABLED column, so
    # this doubles as the verification command for the disable step below.
    gcloud iam service-accounts keys list \
        --iam-account="{SERVICE_ACCOUNT_EMAIL}" \
        --managed-by=user

    # Disable the unrotated or expired key
    gcloud iam service-accounts keys disable {KEY_ID} \
        --iam-account="{SERVICE_ACCOUNT_EMAIL}"
    ```

3.  **Verify**: re-run the `keys list` command above and confirm the key shows
    `True` in the `DISABLED` column.
4.  **Roll Back if Needed**: disabling is reversible while the key still exists.
    If workloads break, restore access immediately with:

    ```bash
    gcloud iam service-accounts keys enable {KEY_ID} \
        --iam-account="{SERVICE_ACCOUNT_EMAIL}"
    ```

5.  **Delete Only After Confirming Health** (NOT reversible): once workloads
    have been confirmed healthy with the key disabled, delete it:

    ```bash
    gcloud iam service-accounts keys delete {KEY_ID} \
        --iam-account="{SERVICE_ACCOUNT_EMAIL}"
    ```

### D. Separation of Duties & Sensitive IAM Roles

When a finding flags conflicting administrative and operational roles assigned
to the same principal (e.g. `KMS_ROLE_SEPARATION`):

1.  Identify the operational role (e.g.,
    `roles/cloudkms.cryptoKeyEncrypterDecrypter`) vs the administrative role
    (`roles/cloudkms.admin`).
2.  Revoke the administrative role from the workload principal, ensuring
    management and data plane operations are segregated across separate
    identities.

### E. Scoping Service Account Impersonation

When a finding reports overly broad `roles/iam.serviceAccountTokenCreator` or
`roles/iam.serviceAccountUser` granted at the project level:

1.  Remove the project-level role binding.
2.  Grant the role only on the specific service account resource that the
    principal needs to impersonate.

## 4. Verification Check

After applying the IAM policy change, verify that the troublesome binding has
been removed:

```bash
gcloud projects get-iam-policy {PROJECT_ID} \
    --flatten="bindings[].members" \
    --format="table(bindings.role)" \
    --filter="bindings.members:{MEMBER_EMAIL} AND bindings.role:{TROUBLESOME_ROLE}"
```

If the command returns no rows, the remediation is successful. The `--flatten`
flag is required: without it, the filter matches whenever *any* binding has the
member and *any* binding has the role, yielding a false positive on an
already-remediated policy.
remediation_misconfig.md 8.8 KB
# Infrastructure Misconfiguration Remediation Playbook (`remediation_misconfig.md`)

Use this playbook when remediating Security Command Center findings for publicly
accessible Cloud Storage buckets, compute instances exposed to the public
internet, or KMS keys without a rotation schedule. This covers the Security
Health Analytics categories `PUBLIC_BUCKET_ACL`, `PUBLIC_IP_ADDRESS`,
`OPEN_FIREWALL`, `OPEN_SSH_PORT`, `OPEN_RDP_PORT`, and `KMS_KEY_NOT_ROTATED`.

`MISCONFIGURATION` is a broad finding class spanning many more detectors than
these four. If a misconfiguration finding is not one of the categories above,
this playbook does not cover it: fall back to the skill's **Findings Without
Dedicated Playbooks** guidance rather than forcing the finding into one of the
patterns below.

**Usage and consent**: This playbook is a reference for the
`google-cloud-scc-remediation` skill and inherits that skill's consent gate,
even if you reached this file directly. Every mutating command below MUST be
presented to the user as part of a remediation plan, together with its
verification command, and MUST NOT be executed until the user answers "Do you
approve executing this remediation plan?". Never execute a mutating command in
the same turn you propose it.

## Table of Contents

*   [1. Public Cloud Storage Buckets (`PUBLIC_BUCKET_ACL`)](#1-public-cloud-storage-buckets-public_bucket_acl)
*   [2. Public Compute Instances & Firewall Exposures (`PUBLIC_IP_ADDRESS`, `OPEN_FIREWALL`, `OPEN_SSH_PORT`, `OPEN_RDP_PORT`)](#2-public-compute-instances--firewall-exposures-public_ip_address-open_firewall-open_ssh_port-open_rdp_port)
*   [3. KMS Key Rotation Misconfigurations (`KMS_KEY_NOT_ROTATED`)](#3-kms-key-rotation-misconfigurations-kms_key_not_rotated)
*   [4. Verification Check](#4-verification-check)

## 1. Public Cloud Storage Buckets (`PUBLIC_BUCKET_ACL`)

When a Security Command Center finding reports that a Cloud Storage bucket is
publicly accessible via `allUsers` or `allAuthenticatedUsers`:

### A. Check Public Access Prevention Status

```bash
gcloud storage buckets describe gs://{BUCKET_NAME} \
    --format="get(public_access_prevention)"
```

This returns `enforced` or `inherited`. Note that `gcloud storage` reports this
as a top-level snake_case field; the JSON API spelling
(`iamConfiguration.publicAccessPrevention`) does not exist in this surface and
silently returns an empty string instead of failing.

### B. Identify the Actual Public Role Bindings

Do not assume the role. A bucket can be made public through any role, and there
may be more than one binding:

```bash
gcloud storage buckets get-iam-policy gs://{BUCKET_NAME} \
    --flatten="bindings[].members" \
    --format="table(bindings.role, bindings.members)"
```

This command does not support `--filter`, so scan the output for rows whose
member is `allUsers` or `allAuthenticatedUsers`. Every such row is a binding you
must remove in the next step.

### C. Remediation: Enforce Public Access Prevention & Revoke Public Bindings

```bash
# 1. Enable Public Access Prevention. When enforced, this blocks public access
#    granted through either IAM bindings or legacy ACLs. Note this is a boolean
#    flag: use --public-access-prevention, not --public-access-prevention=enforced.
gcloud storage buckets update gs://{BUCKET_NAME} \
    --public-access-prevention

# 2. Remove every binding reported in step B. Repeat for each role returned,
#    substituting {PUBLIC_ROLE}.
gcloud storage buckets remove-iam-policy-binding gs://{BUCKET_NAME} \
    --member="allUsers" \
    --role="{PUBLIC_ROLE}"

gcloud storage buckets remove-iam-policy-binding gs://{BUCKET_NAME} \
    --member="allAuthenticatedUsers" \
    --role="{PUBLIC_ROLE}"
```

If the bucket has uniform bucket-level access disabled, individual objects may
also be public through legacy per-object ACLs, which `get-iam-policy` does not
report. Enforcing Public Access Prevention blocks those as well; if an
organization policy exception prevents enforcing it, enable uniform bucket-level
access instead so ACLs can no longer grant access:

```bash
gcloud storage buckets update gs://{BUCKET_NAME} \
    --uniform-bucket-level-access
```

## 2. Public Compute Instances & Firewall Exposures (`PUBLIC_IP_ADDRESS`, `OPEN_FIREWALL`, `OPEN_SSH_PORT`, `OPEN_RDP_PORT`)

When a VM instance is exposed to the internet via an external IP or overly
permissive firewall rules (e.g., `0.0.0.0/0` on port 22 or 3389):

### A. Remediation: Restrict Firewall Ingress to IAP / Trusted Ranges

`35.235.240.0/20` is a fixed, Google-published range used by IAP TCP forwarding.
It is the same for every project, so it is safe to use as a literal whenever
administrative SSH/RDP access should be brokered through IAP.

It is **not** a universal answer. If the workload legitimately needs ingress
from somewhere else — a corporate egress range, a peered VPC, a load balancer or
health-check range — ask the user which ranges are required. Never invent a
range, and never leave `0.0.0.0/0` in place because the correct value is
unknown.

```bash
# 1. Inspect the permissive firewall rule. Record the existing --source-ranges
#    from this output: they are the rollback value for step 2.
gcloud compute firewall-rules describe {FIREWALL_RULE_NAME} \
    --project={PROJECT_ID}

# 2. Restrict source ranges to IAP TCP forwarding
gcloud compute firewall-rules update {FIREWALL_RULE_NAME} \
    --project={PROJECT_ID} \
    --source-ranges="35.235.240.0/20"
```

To roll back, re-apply the original ranges recorded in step 1:

```bash
gcloud compute firewall-rules update {FIREWALL_RULE_NAME} \
    --project={PROJECT_ID} \
    --source-ranges="{ORIGINAL_SOURCE_RANGES}"
```

### B. Remediation: Remove External IP from VM Instance

If the VM does not require direct public internet ingress/egress:

```bash
# 1. Discover the access config name (Cloud Console defaults to "External NAT";
#    gcloud CLI and Terraform default to "external-nat")
gcloud compute instances describe {INSTANCE_NAME} \
    --project={PROJECT_ID} \
    --zone={ZONE} \
    --format="get(networkInterfaces[0].accessConfigs[0].name)"

# 2. Remove external access config from network interface using the discovered name
gcloud compute instances delete-access-config {INSTANCE_NAME} \
    --project={PROJECT_ID} \
    --zone={ZONE} \
    --access-config-name="{ACCESS_CONFIG_NAME}"
```

Removing the access config releases an ephemeral external IP permanently; the
VM cannot be given the same address back. A static (reserved) address can be
re-attached. To roll back:

```bash
gcloud compute instances add-access-config {INSTANCE_NAME} \
    --project={PROJECT_ID} \
    --zone={ZONE} \
    --access-config-name="{ACCESS_CONFIG_NAME}"
```

## 3. KMS Key Rotation Misconfigurations (`KMS_KEY_NOT_ROTATED`)

When a Cloud KMS customer-managed encryption key (CMEK) lacks an automated
rotation schedule:

```bash
# Configure automatic 90-day rotation schedule for the key
gcloud kms keys update {KEY_NAME} \
    --project={PROJECT_ID} \
    --keyring={KEY_RING} \
    --location={LOCATION} \
    --rotation-period="7776000s" \
    --next-rotation-time="{NEXT_ROTATION_ISO_TIMESTAMP}"
```

To roll back, remove the rotation schedule:

```bash
gcloud kms keys update {KEY_NAME} \
    --project={PROJECT_ID} \
    --keyring={KEY_RING} \
    --location={LOCATION} \
    --remove-rotation-schedule
```

## 4. Verification Check

After applying infrastructure remediation commands, verify that the target
resources are properly secured:

### A. Public Cloud Storage Buckets (`PUBLIC_BUCKET_ACL`)

Verify that `public_access_prevention` is `enforced` and that public principals
(`allUsers` and `allAuthenticatedUsers`) are absent from the bucket IAM policy:

```bash
# Verify public access prevention is enforced
gcloud storage buckets describe gs://{BUCKET_NAME} \
    --format="get(public_access_prevention)"

# Verify allUsers and allAuthenticatedUsers are removed
gcloud storage buckets get-iam-policy gs://{BUCKET_NAME}
```

### B. Public Compute Instances & Firewall Exposures (`PUBLIC_IP_ADDRESS`, `OPEN_FIREWALL`)

Verify that the firewall rule source ranges are restricted and that the VM
instance external access configuration is removed:

```bash
# Verify restricted source ranges on the firewall rule
gcloud compute firewall-rules describe {FIREWALL_RULE_NAME} \
    --project={PROJECT_ID}

# Verify external access configuration is removed from the VM instance
gcloud compute instances describe {INSTANCE_NAME} \
    --project={PROJECT_ID} \
    --zone={ZONE}
```

### C. KMS Key Rotation Misconfigurations (`KMS_KEY_NOT_ROTATED`)

Verify the rotation period and next scheduled rotation time for the KMS key:

```bash
gcloud kms keys describe {KEY_NAME} \
    --project={PROJECT_ID} \
    --keyring={KEY_RING} \
    --location={LOCATION}
```

If the returned resource descriptions confirm enforced access prevention,
restricted firewall rules, removed external IP configurations, and automated key
rotation schedules, the remediation is successful.
remediation_vuln.md 4.5 KB
# Software Vulnerability Remediation Playbook (`remediation_vuln.md`)

Use this playbook when remediating Security Command Center findings related to
`VULNERABILITY`, such as unpatched OS packages, vulnerable container base
images, or outdated GKE node pools.

**Usage and consent**: This playbook is a reference for the
`google-cloud-scc-remediation` skill and inherits that skill's consent gate,
even if you reached this file directly. Every mutating command below MUST be
presented to the user as part of a remediation plan, together with its
verification command, and MUST NOT be executed until the user answers "Do you
approve executing this remediation plan?". Never execute a mutating command in
the same turn you propose it.

## Table of Contents

*   [1. GKE Node Pool Vulnerabilities](#1-gke-node-pool-vulnerabilities)
*   [2. Compute Engine VM OS Package Vulnerabilities](#2-compute-engine-vm-os-package-vulnerabilities)
*   [3. Container Image & Artifact Registry Vulnerabilities](#3-container-image--artifact-registry-vulnerabilities)

## 1. GKE Node Pool Vulnerabilities

When a Security Command Center vulnerability finding affects a GKE node pool
running an outdated or vulnerable Kubernetes version / OS image:

### A. Check Current Node Pool Version

```bash
gcloud container node-pools describe {NODE_POOL_NAME} \
    --project={PROJECT_ID} \
    --cluster={CLUSTER_NAME} \
    --region={REGION} \
    --format="get(version,config.imageType)"
```

### B. Remediation: Upgrade GKE Node Pool

*Note: GKE node pools cannot be upgraded to a Kubernetes version higher than the
cluster control plane. If the target patch version requires a newer minor
version, upgrade the control plane (`--master`) first.*

```bash
# Upgrade the node pool to the latest supported patch version
gcloud container clusters upgrade {CLUSTER_NAME} \
    --project={PROJECT_ID} \
    --node-pool={NODE_POOL_NAME} \
    --region={REGION}
```

A node pool upgrade cannot be rolled back: GKE does not support downgrading a
node pool to an earlier version. Treat this step as irreversible and confirm the
target version with the user before executing.

### C. Verification

Verify that the node pool has successfully upgraded to the patched version:

```bash
gcloud container node-pools describe {NODE_POOL_NAME} \
    --project={PROJECT_ID} \
    --cluster={CLUSTER_NAME} \
    --region={REGION} \
    --format="get(version)"
```

## 2. Compute Engine VM OS Package Vulnerabilities

When a Security Command Center finding identifies CVEs in OS packages (e.g.,
`openssl`, `kernel`, `glibc`) on Compute Engine VMs:

### A. Remediation using OS Config Patch Management (Preferred for Production)

```bash
# Execute an on-demand OS patch job for the target instance.
# --instance-filter-names requires the URI form; a bare instance name matches
# zero instances and the patch job silently succeeds without patching anything.
gcloud compute os-config patch-jobs execute \
    --project={PROJECT_ID} \
    --instance-filter-names="zones/{ZONE}/instances/{INSTANCE_NAME}" \
    --display-name="patch-{CVE_ID}"
```

Applying OS package updates cannot be undone by a rollback command. If a patch
must be reverted, the user has to restore the VM from a disk snapshot taken
before the patch job, so confirm a snapshot exists before executing.

### B. Verification

Verify patch completion status:

```bash
gcloud compute os-config patch-jobs list \
    --project={PROJECT_ID} \
    --filter="displayName:patch-{CVE_ID}" \
    --limit=1
```

## 3. Container Image & Artifact Registry Vulnerabilities

When a vulnerability is detected in a container image stored in Artifact
Registry:

### A. Remediation: Rebuild and Redeploy Container Image

1.  Identify the affected base image layer or third-party dependency from the
    finding's CVE details.
2.  Recommend bumping the base image tag in the workload's `Dockerfile` (e.g.,
    from `debian:11-slim` to `debian:12-slim` or the latest security patch
    release).
3.  Rebuild and publish the container image, then trigger a rolling restart of
    the deployment.

### B. Verification

After rebuilding and publishing the updated container image, verify the newly
published image tag in Artifact Registry:

```bash
# List recent container images in the repository to verify the updated tag/digest
gcloud artifacts docker images list {LOCATION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} \
    --limit=5
```

If the updated container image tag is published and deployed without the
reported CVE, the remediation is successful.

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE