mcpField
C
configuring-identity-aware-proxy-with-google-iap

configuring-identity-aware-proxy-with-google-iap

github.com/mukul975安全35.2k76 次安装8 周前更新
代码仓库

关于 configuring-identity-aware-proxy-with-google-iap

这项实用技能介绍如何配置 Google Cloud Identity-Aware Proxy,为 Web 应用和 TCP 服务实施访问控制,涵盖 IAM 策略、基于上下文的访问、会话、服务账号与审计日志。

主要功能

  1. 01为 GCP 服务配置 IAP
  2. 02设置 IAM 访问绑定
  3. 03定义设备和网络访问级别
  4. 04设置会话与重新认证规则
  5. 05启用服务账号访问
  6. 06配置审计日志

适用场景

  1. 01按用户或群组限制内部应用访问
  2. 02要求访问敏感服务时使用受管设备
  3. 03无需公共 IP 提供 SSH 或 RDP 访问
  4. 04通过 IAP 配置服务间访问

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill configuring-identity-aware-proxy-with-google-iap

安装后在 Claude Code 中输入/configuring-identity-aware-proxy-with-google-iap确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
assets/
template.md
references/
api-reference.md
standards.md
workflows.md
scripts/
agent.py
process.py

详细介绍

使用 Google IAP 配置 Identity-Aware Proxy

适用场景

  • 需要通过基于身份的访问保护 Google Cloud 应用(App Engine、Cloud Run、GKE、Compute Engine)时
  • 需要实现上下文感知访问,并验证设备状态和位置信息时
  • 需要在不使用 VPN 或暴露公网 IP 的情况下,安全访问内部工具时
  • 需要为 Web 应用和 TCP 服务配置逐请求身份验证和授权时
  • 需要使用服务账号配置对受 IAP 保护资源的程序化访问时

不要用于无法置于 HTTPS 负载均衡器之后的非 HTTP 应用、需要允许未经身份验证访问的面向公众的应用,或自行处理身份验证且 IAP 会与现有身份验证流程冲突的应用。

先决条件

  • 已启用结算功能的 Google Cloud 项目
  • 已启用 IAP API(gcloud services enable iap.googleapis.com)
  • 已将应用部署在 HTTPS 负载均衡器、App Engine 或 Cloud Run 后面
  • 用于用户管理的 Cloud Identity 或 Google Workspace
  • 已启用用于访问级别的 Access Context Manager API
  • 已为项目配置 OAuth 同意屏幕

工作流

步骤 1:在后端服务上启用 IAP

为不同的 GCP 计算平台配置 IAP。

# Enable required APIs
gcloud services enable iap.googleapis.com
gcloud services enable accesscontextmanager.googleapis.com

# Create OAuth consent screen
gcloud iap oauth-brands create \
  --application_title="Internal Applications" \
  [email protected]

# Create OAuth client
gcloud iap oauth-clients create \
  projects/PROJECT_ID/brands/BRAND_ID \
  --display_name="IAP Web Client"

# === Enable IAP on Compute Engine Backend Service ===
gcloud compute backend-services update my-backend-service \
  --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRET \
  --global

# === Enable IAP on App Engine ===
gcloud iap web enable \
  --resource-type=app-engine \
  --oauth2-client-id=CLIENT_ID \
  --oauth2-client-secret=CLIENT_SECRET

# === Enable IAP on Cloud Run ===
# First grant IAP service account the Cloud Run Invoker role
gcloud run services add-iam-policy-binding my-service \
  --member="serviceAccount:[email protected]" \
  --role="roles/run.invoker" \
  --region=us-central1

# Enable IAP on the Cloud Run backend service
gcloud compute backend-services update my-cloud-run-backend \
  --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRET \
  --global

# === Enable IAP TCP Forwarding for SSH/RDP ===
# No load balancer needed - uses IAP tunnel
gcloud compute instances add-iam-policy-binding my-vm \
  --member="group:[email protected]" \
  --role="roles/iap.tunnelResourceAccessor" \
  --zone=us-central1-a

# SSH through IAP tunnel
gcloud compute ssh my-vm --zone=us-central1-a --tunnel-through-iap

# RDP through IAP tunnel
gcloud compute start-iap-tunnel my-windows-vm 3389 \
  --local-host-port=localhost:3390 \
  --zone=us-central1-a
步骤 2:配置用于访问控制的 IAM 绑定

向特定用户和群组授予访问权限,并可选择添加访问级别条件。

# Grant basic access to a group
gcloud iap web add-iam-policy-binding \
  --resource-type=backend-services \
  --service=my-backend-service \
  --member="group:[email protected]" \
  --role="roles/iap.httpsResourceAccessor"

# Grant access with access level condition
gcloud iap web add-iam-policy-binding \
  --resource-type=backend-services \
  --service=finance-app \
  --member="group:[email protected]" \
  --role="roles/iap.httpsResourceAccessor" \
  --condition='expression=request.auth.access_levels.exists(x, x == "accessPolicies/POLICY_ID/accessLevels/corporate-device"),title=RequireCorporateDevice,description=Requires managed corporate device'

# Grant access only during business hours
gcloud iap web add-iam-policy-binding \
  --resource-type=backend-services \
  --service=admin-console \
  --member="group:[email protected]" \
  --role="roles/iap.httpsResourceAccessor" \
  --condition='expression=request.time.getHours("America/New_York") >= 8 && request.time.getHours("America/New_York") <= 18 && request.time.getDayOfWeek("America/New_York") >= 1 && request.time.getDayOfWeek("America/New_York") <= 5,title=BusinessHoursOnly'

# Grant access to a specific URL path
gcloud iap web add-iam-policy-binding \
  --resource-type=backend-services \
  --service=internal-api \
  --member="group:[email protected]" \
  --role="roles/iap.httpsResourceAccessor" \
  --condition='expression=request.path.startsWith("/api/v2/"),title=APIv2Access'
步骤 3:使用 Access Context Manager 创建访问级别

使用设备属性和网络条件定义基于上下文的访问要求。

# Create access level requiring encrypted corporate device
cat > managed-device.yaml << 'EOF'
- devicePolicy:
    allowedEncryptionStatuses:
      - ENCRYPTED
    osConstraints:
      - osType: DESKTOP_WINDOWS
        minimumVersion: "10.0.19045"
      - osType: DESKTOP_MAC
        minimumVersion: "14.0"
      - osType: DESKTOP_CHROME_OS
    requireScreenlock: true
    requireAdminApproval: true
    allowedDeviceManagementLevels:
      - ADVANCED
EOF

gcloud access-context-manager levels create managed-device \
  --policy=POLICY_ID \
  --title="Managed Device" \
  --basic-level-spec=managed-device.yaml

# Create access level for corporate network
cat > corp-network.yaml << 'EOF'
- ipSubnetworks:
    - "203.0.113.0/24"
    - "198.51.100.0/24"
  regions:
    - US
    - GB
EOF

gcloud access-context-manager levels create corp-network \
  --policy=POLICY_ID \
  --title="Corporate Network" \
  --basic-level-spec=corp-network.yaml

# Create custom access level using CEL for complex logic
cat > high-trust.yaml << 'EOF'
expression: >
  device.encryption_status == DeviceEncryptionStatus.ENCRYPTED &&
  device.is_admin_approved_device == true &&
  (
    origin.ip in ["203.0.113.0/24"] ||
    device.os_type == OsType.DESKTOP_CHROME_OS
  ) &&
  request.auth.claims.hd == "company.com"
EOF

gcloud access-context-manager levels create high-trust \
  --policy=POLICY_ID \
  --title="High Trust" \
  --custom-level-spec=high-trust.yaml
步骤 4:配置会话设置和重新身份验证

为每个应用设置会话时长和重新身份验证策略。

# Configure re-authentication for a backend service
# Requires login every 4 hours for sensitive apps
gcloud iap settings set \
  --project=PROJECT_ID \
  --resource-type=compute \
  --service=finance-app \
  reauthSettings.method=LOGIN \
  reauthSettings.maxAge=14400s \
  reauthSettings.policyType=MINIMUM

# Configure session settings for App Engine
gcloud iap settings set \
  --project=PROJECT_ID \
  --resource-type=app-engine \
  reauthSettings.method=SECURE_KEY \
  reauthSettings.maxAge=3600s \
  reauthSettings.policyType=MINIMUM

# View current IAP settings
gcloud iap settings get \
  --project=PROJECT_ID \
  --resource-type=compute \
  --service=finance-app
步骤 5:为服务账号配置程序化访问

通过受 IAP 保护的端点启用服务间通信。

#!/usr/bin/env python3
"""Access IAP-protected resource using service account credentials."""

import google.auth
import google.auth.transport.requests
from google.auth import impersonated_credentials
import requests as req

IAP_CLIENT_ID = "YOUR_IAP_OAUTH_CLIENT_ID.apps.googleusercontent.com"
IAP_URL = "https://my-app.company.com/api/data"

def access_iap_resource():
    # Get default credentials (works with service account key or workload identity)
    credentials, project = google.auth.default()

    # Create IAP-authenticated request
    authed_session = google.auth.transport.requests.AuthorizedSession(
        credentials,
        target_audience=IAP_CLIENT_ID
    )

    # Make request to IAP-protected resource
    response = authed_session.get(IAP_URL)
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text[:500]}")

    return response

if __name__ == "__main__":
    access_iap_resource()
步骤 6:设置审核日志记录和监控

为所有 IAP 访问决策配置日志记录。

# Enable data access audit logs for IAP
gcloud projects get-iam-policy PROJECT_ID --format=json > policy.json

# Add IAP audit config to policy.json:
# {
#   "service": "iap.googleapis.com",
#   "auditLogConfigs": [
#     {"logType": "ADMIN_READ"},
#     {"logType": "DATA_READ"},
#     {"logType": "DATA_WRITE"}
#   ]
# }

gcloud projects set-iam-policy PROJECT_ID policy.json

# Create log-based metric for denied access
gcloud logging metrics create iap-denied-access \
  --description="Count of IAP access denials" \
  --log-filter='resource.type="gce_backend_service" AND protoPayload.status.code=16'

# Create alerting policy for high denial rates
gcloud alpha monitoring policies create \
  --display-name="IAP High Denial Rate" \
  --condition-display-name="Denied access > 50 in 5 min" \
  --condition-filter='metric.type="logging.googleapis.com/user/iap-denied-access"' \
  --condition-threshold-value=50 \
  --condition-threshold-duration=300s \
  --notification-channels=projects/PROJECT_ID/notificationChannels/CHANNEL_ID

# Query IAP access logs
gcloud logging read '
  resource.type="gce_backend_service"
  protoPayload.serviceName="iap.googleapis.com"
  timestamp >= "2026-02-22T00:00:00Z"
' --project=PROJECT_ID --format='table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.status.code,resource.labels.backend_service_name)' --limit=50

核心概念

术语定义
Identity-Aware ProxyGCP 服务,可拦截 Web 请求和 TCP 连接,在将请求代理到后端服务之前验证用户身份并评估访问策略
后端服务受 IAP 保护的 GCP 负载均衡器组件;可为 Compute Engine 实例、GKE Pod、Cloud Run 服务或 App Engine 提供服务
IAP 隧道通过 IAP 建立的安全 TCP 隧道,无需公网 IP 或 VPN 即可通过 SSH、RDP 等方式访问 VM
OAuth 同意屏幕GCP 配置,用于指定用户在 IAP 身份验证期间看到的应用名称和支持邮箱
访问级别Access Context Manager 中的命名条件,在 IAP 授权期间进行评估(设备状态、IP、地理位置)
重新身份验证IAP 功能,要求用户在可配置的会话时长后再次证明其身份

工具和系统

  • Google Cloud IAP:面向 GCP 应用和 TCP 服务的身份感知反向代理
  • Access Context Manager:根据设备、网络和地理位置属性定义访问级别
  • gcloud CLI:用于配置 IAP、访问级别和 IAM 绑定的命令行工具
  • IAP TCP Forwarding:基于隧道的 VM 访问方式,无需公网 IP 即可通过 SSH/RDP 连接
  • Cloud Audit Logs:记录所有 IAP 访问决策的不可变日志,用于合规审查
  • Endpoint Verification:可收集设备属性以供评估访问级别的 Chrome 扩展程序

常见场景

场景:使用 IAP 保护 15 个内部 GCP 服务

背景:一家电商公司在 GKE 和 Cloud Run 上运行着 15 个内部服务(管理控制面板、内部 API、监控工具)。目前,这些服务仅受 VPN 和防火墙规则保护,导致网络级访问权限过大。

方案:

  1. 将所有服务部署在 HTTPS 负载均衡器后方,并使用托管 SSL 证书
  2. 在每个后端服务上启用 IAP,并为每个服务配置独立的 OAuth 客户端
  3. 创建 IAM 绑定,将 Google 群组映射到特定服务(管理员群组 -> 管理控制面板,工程团队 -> 监控工具)
  4. 定义访问级别:托管设备(加密 + 屏幕锁定)、公司网络(办公室 IP 范围)
  5. 将托管设备访问级别应用于管理控制面板和财务工具
  6. 为 SSH 访问 GKE 节点配置 IAP TCP 隧道(取代 SSH 堡垒主机)
  7. 将管理工具的重新身份验证间隔设为 4 小时,监控工具设为 8 小时
  8. 配置 Cloud Audit Logs,并针对重复拒绝创建告警

注意事项:IAP 会为每个请求增加 10-50 毫秒的延迟;请测试应用性能。通过 IAP 建立 WebSocket 连接需要进行特定的后端服务配置。GKE 内部的服务间调用应通过内部服务网格绕过 IAP,而不是使用外部 IAP 端点。紧急访问应使用不带访问级别条件的单独 IAM 绑定。

输出格式

Google Cloud IAP Configuration Report
==================================================
Project: ecommerce-internal
Report Date: 2026-02-23

IAP-PROTECTED SERVICES:
  Backend Services:     12
  App Engine:            1
  Cloud Run:             2
  IAP TCP Tunnels:       4 (SSH access)
  Total:                19

ACCESS CONTROL:
  IAM Bindings:         34
  With Access Levels:   18 (52.9%)
  Access Levels:         3 (managed-device, corp-network, high-trust)

SESSION POLICIES:
  Admin tools:          4h re-auth (SECURE_KEY)
  Sensitive apps:       4h re-auth (LOGIN)
  General tools:        8h re-auth (LOGIN)

ACCESS LOGS (last 24h):
  Total requests:       23,456
  Authenticated:        23,289 (99.3%)
  Denied by IAM:           112
  Denied by access level:   55
  Unique users:            134

评论

支持 Markdown