# Implementing GCP Vpc Firewall Rules

> 实施和审计 GCP VPC 防火墙规则，强制执行网络分段，限制入站和出站流量，在整个组织范围内应用分层防火墙策略，并使用 VPC 流日志监控防火墙规则有效性。

- Skill: `killvxk/implementing-gcp-vpc-firewall-rules` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add killvxk/implementing-gcp-vpc-firewall-rules`
- Raw SKILL.md: https://api.skillmd.com/api/skills/killvxk/implementing-gcp-vpc-firewall-rules/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- License: Apache-2.0
- Author: killvxk (https://skillmd.com/u/killvxk)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/killvxk/implementing-gcp-vpc-firewall-rules

---


# 实施 GCP VPC 防火墙规则

## 适用场景

- 部署需要网络级访问控制的新 GCP 工作负载时
- 审计现有防火墙配置中过于宽松的规则时
- 在 GCP VPC 网络中实施零信任网络分段时
- 响应 Security Command Center 关于开放防火墙规则的发现时
- 在 GCP 组织范围内构建分层防火墙策略时

**不适用于**：应用层过滤（使用 Cloud Armor WAF）、基于 DNS 的过滤（使用 Cloud DNS 响应策略），或在不了解 VPC 防火墙规则仅适用于 VPC 内部流量的情况下过滤 VPN/互联流量。

## 前置条件

- 已启用 Compute Engine API 的 GCP 项目
- IAM 角色：防火墙管理使用 `roles/compute.securityAdmin`，审计使用 `roles/compute.networkViewer`
- 分层防火墙策略需要 Organization Admin 角色
- 使用适当权限完成身份验证的 gcloud CLI
- 目标子网已启用 VPC 流日志用于监控

## 工作流程

### 步骤 1：审计现有防火墙规则的安全漏洞

枚举所有防火墙规则并识别过于宽松的配置。

```bash
# 列出项目中的所有防火墙规则
gcloud compute firewall-rules list \
  --format="table(name, network, direction, priority, allowed[].map().firewall_rule().list():label=ALLOWED, sourceRanges, targetTags)"

# 查找允许来自 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

# 查找允许所有协议和端口的规则
gcloud compute firewall-rules list \
  --filter="direction=INGRESS AND allowed[].IPProtocol=all" \
  --format="table(name, network, sourceRanges, targetTags)"

# 查找向互联网开放 SSH（22）或 RDP（3389）的规则
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)"

# 检查已禁用的规则
gcloud compute firewall-rules list \
  --filter="disabled=true" \
  --format="table(name, network, direction)"
```

### 步骤 2：创建限制性入站防火墙规则

使用网络标签和服务账号作为目标，实施最小权限入站规则。

```bash
# 创建仅允许来自互联网到 Web 服务器的 HTTPS 规则
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"

# 创建仅允许从堡垒机子网进行 SSH 的规则
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"

# 创建允许应用层级间内部通信的规则
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"

# 创建基于服务账号的规则（比标签更安全）
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=1000
```

### 步骤 3：实施出站限制

配置出站防火墙规则以控制外发流量并防止数据泄露。

```bash
# 默认拒绝所有出站（低优先级）
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"

# 允许通过受限 VIP 访问 Google API
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"

# 允许 DNS 解析
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"

# 允许访问特定外部服务
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=1000
```

### 步骤 4：部署分层防火墙策略

创建组织和文件夹级防火墙策略，应用于所有项目。

```bash
# 创建组织级防火墙策略
gcloud compute firewall-policies create \
  --organization=ORG_ID \
  --short-name=org-security-policy \
  --description="Organization-wide security firewall policy"

# 在组织级添加规则以阻断已知恶意 IP 段
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"

# 在组织级添加规则强制仅允许 HTTPS 入站
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"

# 将策略关联到组织
gcloud compute firewall-policies associations create \
  --firewall-policy=org-security-policy \
  --organization=ORG_ID
```

### 步骤 5：启用 VPC 流日志进行监控

配置 VPC 流日志以监控流量模式并验证防火墙规则有效性。

```bash
# 在子网上启用流日志
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

# 在 Cloud Logging 中查询被拒绝流量的流日志
gcloud logging read '
  resource.type="gce_subnetwork"
  AND jsonPayload.disposition="DENIED"
  AND timestamp>="2026-02-22T00:00:00Z"
' --limit=50 --format=json

# 查找命中过于宽松规则的流量
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)"

# 将流日志导出到 BigQuery 进行分析
gcloud logging sinks create vpc-flow-bq \
  bigquery.googleapis.com/projects/PROJECT/datasets/vpc_flow_logs \
  --log-filter='resource.type="gce_subnetwork"'
```

## 核心概念

| 术语 | 定义 |
|------|------|
| VPC 防火墙规则（VPC Firewall Rule） | 基于 IP 段、协议、端口和标签对 VM 实例流量进行允许或拒绝的有状态网络级访问控制 |
| 分层防火墙策略（Hierarchical Firewall Policy） | 在 VPC 级规则之前评估的组织或文件夹级防火墙策略，应用于所有子项目 |
| 网络标签（Network Tag） | 应用于 VM 实例的标签，用于确定哪些防火墙规则适用，可作为入站和出站规则的目标 |
| 服务账号防火墙规则（Service Account Firewall Rule） | 基于实例附加服务账号的防火墙规则，比可变的网络标签提供更安全的目标定位 |
| VPC 流日志（VPC Flow Logs） | 在子网级捕获的网络遥测数据，记录流量元数据，用于监控、取证和防火墙规则验证 |
| 隐含规则（Implied Rules） | GCP 默认防火墙规则，允许所有目标的出站流量并拒绝所有来源的入站流量，优先级最低（65535） |

## 工具与系统

- **gcloud compute firewall-rules**：用于在 GCP 中创建、列出和管理 VPC 防火墙规则的 CLI 命令
- **分层防火墙策略（Hierarchical Firewall Policies）**：在所有项目中强制执行安全控制的组织和文件夹级策略
- **VPC 流日志（VPC Flow Logs）**：用于监控、故障排除和验证防火墙有效性的子网级流量日志
- **Cloud Logging**：用于分析 VPC 流日志和防火墙规则命中次数的查询引擎
- **Security Command Center**：具有过于宽松防火墙配置发现功能的 GCP 原生安全平台

## 常见场景

### 场景：发现过于宽松规则后锁定生产 VPC

**场景背景**：安全审计发现生产 VPC 存在允许来自 `0.0.0.0/0` 的 SSH 流量和不受限出站流量的默认允许规则。Security Command Center 报告了 14 个防火墙发现。

**方法**：
1. 使用 `gcloud compute firewall-rules list` 枚举所有现有规则并按风险分类
2. 在所有子网上启用 VPC 流日志，捕获 7 天的基线流量模式
3. 分析流日志以识别需要显式允许规则的合法流量
4. 为每个应用层创建目标入站规则（Web：443，应用：8080，数据库：5432）
5. 将 SSH-from-anywhere 规则替换为仅允许从堡垒机子网 SSH
6. 实施默认拒绝出站规则，并为所需的出站目标添加显式允许规则
7. 在验证应用程序正常运行后，删除过于宽松的默认允许规则

**常见陷阱**：在不了解流量模式的情况下删除防火墙规则会导致服务中断。删除规则前务必启用流日志并分析流量。网络标签可由任何拥有 compute.instances.setTags 权限的人添加，对于关键规则，基于服务账号的目标定位比网络标签更安全。

## 输出格式

```
GCP VPC 防火墙审计报告
================================
项目: production-project
VPC 网络: production-vpc
审计日期: 2026-02-23

规则清单:
  防火墙规则总数: 34
  入站规则数: 22
  出站规则数: 12
  已禁用规则数: 3

关键发现:
[FW-001] SSH 向互联网开放
  规则: default-allow-ssh
  来源: 0.0.0.0/0 -> tcp:22
  目标: 所有实例（无标签）
  优先级: 65534
  修复建议: 限制为堡垒机子网 CIDR

[FW-002] 无出站限制
  问题: 仅存在隐含的允许所有出站规则
  风险: 对出站数据泄露无控制措施
  修复建议: 添加默认拒绝出站规则和显式允许规则

已完成的修复操作:
  已删除规则: 3 条（过于宽松的默认规则）
  已创建规则: 8 条（目标允许规则）
  出站拒绝规则: 已在优先级 65534 创建
  已启用流日志: 6 个子网
```

