mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-08-06 19:00:17 +03:00
Initial commit - 611 cybersecurity skills across all subdomains
This commit is contained in:
@@ -0,0 +1,371 @@
|
||||
---
|
||||
name: configuring-identity-aware-proxy-with-google-iap
|
||||
description: >
|
||||
Configuring Google Cloud Identity-Aware Proxy (IAP) to enforce per-request identity
|
||||
verification for Compute Engine, App Engine, Cloud Run, and GKE services using
|
||||
access levels, context-aware policies, and programmatic access with service accounts.
|
||||
domain: cybersecurity
|
||||
subdomain: zero-trust-architecture
|
||||
tags: [google-iap, identity-aware-proxy, gcp, zero-trust, access-context-manager, cloud-run, app-engine]
|
||||
version: "1.0"
|
||||
author: mahipal
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Configuring Identity-Aware Proxy with Google IAP
|
||||
|
||||
## When to Use
|
||||
|
||||
- When protecting Google Cloud applications (App Engine, Cloud Run, GKE, Compute Engine) with identity-based access
|
||||
- When implementing context-aware access requiring device posture and location verification
|
||||
- When providing secure access to internal tools without VPN or public IP exposure
|
||||
- When needing per-request authentication and authorization for web applications and TCP services
|
||||
- When configuring programmatic access to IAP-protected resources using service accounts
|
||||
|
||||
**Do not use** for non-HTTP applications that cannot be placed behind an HTTPS load balancer, for public-facing applications that need unauthenticated access, or when applications handle their own authentication and IAP would conflict with existing auth flows.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Google Cloud project with billing enabled
|
||||
- IAP API enabled (`gcloud services enable iap.googleapis.com`)
|
||||
- Application deployed behind HTTPS Load Balancer, App Engine, or Cloud Run
|
||||
- Cloud Identity or Google Workspace for user management
|
||||
- Access Context Manager API enabled for access levels
|
||||
- OAuth consent screen configured for the project
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Enable IAP on Backend Services
|
||||
|
||||
Configure IAP for different GCP compute platforms.
|
||||
|
||||
```bash
|
||||
# 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" \
|
||||
--support_email=security@company.com
|
||||
|
||||
# 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:service-PROJECT_NUM@gcp-sa-iap.iam.gserviceaccount.com" \
|
||||
--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:developers@company.com" \
|
||||
--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
|
||||
```
|
||||
|
||||
### Step 2: Configure IAM Bindings for Access Control
|
||||
|
||||
Grant access to specific users and groups with optional access level conditions.
|
||||
|
||||
```bash
|
||||
# Grant basic access to a group
|
||||
gcloud iap web add-iam-policy-binding \
|
||||
--resource-type=backend-services \
|
||||
--service=my-backend-service \
|
||||
--member="group:engineering@company.com" \
|
||||
--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:finance@company.com" \
|
||||
--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:admins@company.com" \
|
||||
--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:api-consumers@company.com" \
|
||||
--role="roles/iap.httpsResourceAccessor" \
|
||||
--condition='expression=request.path.startsWith("/api/v2/"),title=APIv2Access'
|
||||
```
|
||||
|
||||
### Step 3: Create Access Levels with Access Context Manager
|
||||
|
||||
Define context-based access requirements using device attributes and network conditions.
|
||||
|
||||
```bash
|
||||
# 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
|
||||
```
|
||||
|
||||
### Step 4: Configure Session Settings and Re-authentication
|
||||
|
||||
Set session duration and re-authentication policies per application.
|
||||
|
||||
```bash
|
||||
# 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
|
||||
```
|
||||
|
||||
### Step 5: Configure Programmatic Access for Service Accounts
|
||||
|
||||
Enable service-to-service communication through IAP-protected endpoints.
|
||||
|
||||
```python
|
||||
#!/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()
|
||||
```
|
||||
|
||||
### Step 6: Set Up Audit Logging and Monitoring
|
||||
|
||||
Configure logging for all IAP access decisions.
|
||||
|
||||
```bash
|
||||
# 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
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| Identity-Aware Proxy | GCP service that intercepts web requests and TCP connections, authenticating users and evaluating access policies before proxying to backend services |
|
||||
| Backend Service | GCP load balancer component that IAP protects; can serve Compute Engine instances, GKE pods, Cloud Run services, or App Engine |
|
||||
| IAP Tunnel | Secure TCP tunnel through IAP allowing SSH, RDP, and other TCP access to VMs without public IPs or VPN |
|
||||
| OAuth Consent Screen | GCP configuration specifying the application name and support email shown to users during IAP authentication |
|
||||
| Access Level | Named condition in Access Context Manager evaluated during IAP authorization (device posture, IP, geography) |
|
||||
| Re-authentication | IAP feature requiring users to prove their identity again after a configurable session duration |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **Google Cloud IAP**: Identity-aware reverse proxy for GCP applications and TCP services
|
||||
- **Access Context Manager**: Defines access levels based on device, network, and geographic attributes
|
||||
- **gcloud CLI**: Command-line tool for configuring IAP, access levels, and IAM bindings
|
||||
- **IAP TCP Forwarding**: Tunnel-based access to VMs for SSH/RDP without public IPs
|
||||
- **Cloud Audit Logs**: Immutable records of all IAP access decisions for compliance
|
||||
- **Endpoint Verification**: Chrome extension collecting device attributes for access level evaluation
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: Securing 15 Internal GCP Services with IAP
|
||||
|
||||
**Context**: An e-commerce company runs 15 internal services on GKE and Cloud Run (admin dashboards, internal APIs, monitoring tools). Currently, these services are protected only by VPN and firewall rules, creating excessive network-level access.
|
||||
|
||||
**Approach**:
|
||||
1. Deploy all services behind an HTTPS Load Balancer with managed SSL certificates
|
||||
2. Enable IAP on each backend service with per-service OAuth clients
|
||||
3. Create IAM bindings mapping Google Groups to specific services (admin group -> admin dashboard, engineering -> monitoring)
|
||||
4. Define access levels: managed-device (encryption + screen lock), corp-network (office IP ranges)
|
||||
5. Apply managed-device access level to admin dashboard and financial tools
|
||||
6. Configure IAP TCP tunneling for SSH access to GKE nodes (replacing SSH bastion host)
|
||||
7. Set re-authentication to 4 hours for admin tools, 8 hours for monitoring
|
||||
8. Configure Cloud Audit Logs and create alerting for repeated denials
|
||||
|
||||
**Pitfalls**: IAP adds 10-50ms latency per request; test application performance. WebSocket connections through IAP require specific backend service configuration. Service-to-service calls within GKE should bypass IAP using internal service mesh, not external IAP endpoints. Break-glass access should use a separate IAM binding without access level conditions.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
# Google Cloud IAP - Configuration Checklist
|
||||
|
||||
## Project Information
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| GCP Project | ecommerce-internal-prod |
|
||||
| Organization | E-Commerce Corp |
|
||||
| IAP OAuth Brand | Corporate Applications |
|
||||
| Lead | Security Engineering |
|
||||
|
||||
## IAP Backend Service Configuration
|
||||
|
||||
| Service | Platform | IAP Enabled | Access Level | Re-auth | Groups |
|
||||
|---------|----------|-------------|-------------|---------|--------|
|
||||
| admin-dashboard | GKE | Yes | managed-device | 1h / SECURE_KEY | admins@ |
|
||||
| internal-api | Cloud Run | Yes | corp-network | 8h / LOGIN | engineering@ |
|
||||
| monitoring | GKE | Yes | None | 8h / LOGIN | sre@, engineering@ |
|
||||
| hr-portal | Compute Engine | Yes | high-trust | 4h / LOGIN | hr@ |
|
||||
| finance-app | Compute Engine | Yes | high-trust | 1h / SECURE_KEY | finance@ |
|
||||
| wiki | App Engine | Yes | None | 8h / LOGIN | all-staff@ |
|
||||
|
||||
## Access Levels
|
||||
|
||||
| Level Name | Type | Device Policy | Encryption | IP Restriction | Region |
|
||||
|-----------|------|--------------|------------|---------------|--------|
|
||||
| managed-device | Basic | Admin-approved, Screen lock | ENCRYPTED | None | US, GB |
|
||||
| corp-network | Basic | None | None | 203.0.113.0/24 | US |
|
||||
| high-trust | Custom (CEL) | Admin-approved, Encrypted | ENCRYPTED | Corp network OR ChromeOS | US |
|
||||
|
||||
## IAP TCP Tunnel Access
|
||||
|
||||
| VM | Zone | IAP Tunnel | Groups | External IP Removed |
|
||||
|----|------|-----------|--------|-------------------|
|
||||
| bastion-1 | us-central1-a | SSH | sre@ | Yes |
|
||||
| db-admin | us-central1-b | SSH | dba@ | Yes |
|
||||
| windows-admin | us-east1-b | RDP | admins@ | Yes |
|
||||
|
||||
## Validation Checklist
|
||||
- [x] IAP enabled on all internal backend services
|
||||
- [x] Direct access blocked (no public IPs, firewall rules restrict to LB + IAP)
|
||||
- [x] Access levels applied to sensitive services
|
||||
- [x] Re-authentication configured per sensitivity tier
|
||||
- [x] Break-glass IAM binding created without access level conditions
|
||||
- [ ] Service account programmatic access tested
|
||||
- [x] Audit logs enabled and flowing to BigQuery
|
||||
- [x] Alert policies created for access denials
|
||||
|
||||
## Sign-Off
|
||||
| Role | Name | Date | Approved |
|
||||
|------|------|------|----------|
|
||||
| Security Architect | _________________ | __________ | [ ] |
|
||||
| Cloud Platform Lead | _________________ | __________ | [ ] |
|
||||
@@ -0,0 +1,31 @@
|
||||
# Google Cloud IAP - Standards & References
|
||||
|
||||
## NIST SP 800-207: Zero Trust Architecture
|
||||
- **Section 3.1**: Policy Engine - IAP evaluates identity and context per request
|
||||
- **Section 3.2**: Trust Algorithm - Access Levels compute trust score
|
||||
- **Section 4.2**: SDP Gateway Model - IAP acts as application-layer gateway
|
||||
- **URL**: https://csrc.nist.gov/publications/detail/sp/800-207/final
|
||||
|
||||
## CISA Zero Trust Maturity Model v2.0
|
||||
- **Identity Pillar**: Per-request identity verification via IAP
|
||||
- **Application Pillar**: Application-level access controls
|
||||
- **URL**: https://www.cisa.gov/zero-trust-maturity-model
|
||||
|
||||
## Google Cloud Documentation
|
||||
- **IAP Overview**: https://cloud.google.com/iap/docs/concepts-overview
|
||||
- **Enabling IAP for Compute Engine**: https://cloud.google.com/iap/docs/enabling-compute-howto
|
||||
- **Enabling IAP for App Engine**: https://cloud.google.com/iap/docs/app-engine-quickstart
|
||||
- **Enabling IAP for Cloud Run**: https://cloud.google.com/iap/docs/enabling-cloud-run
|
||||
- **IAP TCP Forwarding**: https://cloud.google.com/iap/docs/using-tcp-forwarding
|
||||
- **Context-Aware Access**: https://cloud.google.com/iap/docs/cloud-iap-context-aware-access-howto
|
||||
- **Managing Access**: https://cloud.google.com/iap/docs/managing-access
|
||||
- **Access Context Manager**: https://cloud.google.com/access-context-manager/docs
|
||||
- **Programmatic Authentication**: https://cloud.google.com/iap/docs/authentication-howto
|
||||
|
||||
## Google BeyondCorp Papers
|
||||
- **BeyondCorp: A New Approach to Enterprise Security** (2014): https://research.google/pubs/pub43231/
|
||||
- **BeyondCorp: The Access Proxy** (2017): https://research.google/pubs/pub45728/
|
||||
|
||||
## FedRAMP
|
||||
- Google Cloud IAP operates within FedRAMP High boundary
|
||||
- **URL**: https://cloud.google.com/security/compliance/fedramp
|
||||
@@ -0,0 +1,60 @@
|
||||
# Google IAP Configuration Workflow
|
||||
|
||||
## Phase 1: Prerequisites (Day 1)
|
||||
1. Enable IAP API: `gcloud services enable iap.googleapis.com`
|
||||
2. Enable Access Context Manager API
|
||||
3. Configure OAuth consent screen with organization branding
|
||||
4. Create OAuth client credentials for IAP
|
||||
5. Verify applications are behind HTTPS Load Balancer or Cloud Run/App Engine
|
||||
|
||||
## Phase 2: IAP Enablement (Day 2-3)
|
||||
|
||||
### Compute Engine / GKE Backend Services
|
||||
1. Enable IAP on each backend service with OAuth credentials
|
||||
2. Configure health checks to work through IAP
|
||||
3. Verify backend service firewall rules allow only load balancer and IAP ranges
|
||||
4. Block direct access to backend instances (remove external IPs, restrict firewall)
|
||||
|
||||
### App Engine
|
||||
1. Enable IAP on App Engine with OAuth credentials
|
||||
2. Verify no App Engine firewall rules bypass IAP
|
||||
3. Test authentication flow with pilot users
|
||||
|
||||
### Cloud Run
|
||||
1. Grant IAP service account Cloud Run Invoker role
|
||||
2. Configure Cloud Run service with `--no-allow-unauthenticated`
|
||||
3. Enable IAP on the backend service fronting Cloud Run
|
||||
4. Test end-to-end request flow
|
||||
|
||||
### TCP Forwarding (SSH/RDP)
|
||||
1. Grant IAP Tunnel Resource Accessor role to user groups
|
||||
2. Remove public IP addresses from VMs
|
||||
3. Configure firewall rules to allow only IAP tunnel IP ranges (35.235.240.0/20)
|
||||
4. Test SSH/RDP access through IAP tunnel
|
||||
|
||||
## Phase 3: Access Control (Day 4-5)
|
||||
1. Create IAM bindings mapping Google Groups to backend services
|
||||
2. Add access level conditions for sensitive applications
|
||||
3. Configure time-based conditions for admin access
|
||||
4. Set up path-based conditions for API access
|
||||
5. Test each binding with authorized and unauthorized users
|
||||
|
||||
## Phase 4: Access Levels (Day 6-7)
|
||||
1. Create basic access levels for device posture (encryption, OS, screen lock)
|
||||
2. Create IP-based access levels for corporate network
|
||||
3. Create custom access levels with CEL for complex conditions
|
||||
4. Apply access levels as conditions on IAM bindings
|
||||
5. Validate with compliant and non-compliant devices
|
||||
|
||||
## Phase 5: Session and Re-auth (Day 8)
|
||||
1. Configure session duration per application tier
|
||||
2. Set re-authentication method (LOGIN or SECURE_KEY)
|
||||
3. Test session expiry and re-authentication flow
|
||||
4. Document expected user experience
|
||||
|
||||
## Phase 6: Audit and Monitoring (Day 9-10)
|
||||
1. Enable data access audit logs for IAP
|
||||
2. Create log-based metrics for access denials
|
||||
3. Set up alerting for anomalous patterns
|
||||
4. Build dashboard for IAP access analytics
|
||||
5. Test break-glass access procedures
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Google Cloud IAP - Configuration Audit Tool
|
||||
|
||||
Audits IAP-enabled backend services, IAM bindings, access levels,
|
||||
session settings, and access logs for compliance validation.
|
||||
|
||||
Requirements:
|
||||
pip install google-cloud-compute google-auth requests
|
||||
"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
def run_gcloud(args: list[str]) -> Any:
|
||||
"""Execute gcloud command and return JSON output."""
|
||||
cmd = ["gcloud"] + args + ["--format=json"]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
try:
|
||||
return json.loads(result.stdout) if result.stdout.strip() else []
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
|
||||
def audit_iap_backends(project_id: str) -> list[dict]:
|
||||
"""Audit all backend services for IAP configuration."""
|
||||
print("\n[1/5] Auditing IAP-enabled backend services...")
|
||||
backends = run_gcloud(["compute", "backend-services", "list", "--project", project_id])
|
||||
if not isinstance(backends, list):
|
||||
return []
|
||||
|
||||
results = []
|
||||
for backend in backends:
|
||||
name = backend.get("name", "unknown")
|
||||
iap = backend.get("iap", {})
|
||||
enabled = iap.get("enabled", False)
|
||||
|
||||
info = {"name": name, "iap_enabled": enabled, "bindings": [], "has_conditions": False}
|
||||
|
||||
if enabled:
|
||||
policy = run_gcloud([
|
||||
"iap", "web", "get-iam-policy",
|
||||
"--resource-type=backend-services",
|
||||
"--service", name, "--project", project_id
|
||||
])
|
||||
bindings = policy.get("bindings", []) if isinstance(policy, dict) else []
|
||||
info["bindings"] = bindings
|
||||
info["bindings_count"] = len(bindings)
|
||||
info["has_conditions"] = any(b.get("condition") for b in bindings)
|
||||
print(f" [IAP ON] {name}: {len(bindings)} bindings, conditions: {info['has_conditions']}")
|
||||
else:
|
||||
print(f" [IAP OFF] {name}")
|
||||
|
||||
results.append(info)
|
||||
return results
|
||||
|
||||
|
||||
def audit_access_levels(policy_id: str) -> list[dict]:
|
||||
"""Audit Access Context Manager levels."""
|
||||
print("\n[2/5] Auditing access levels...")
|
||||
if not policy_id:
|
||||
print(" Skipped - no policy ID provided")
|
||||
return []
|
||||
|
||||
levels = run_gcloud(["access-context-manager", "levels", "list", "--policy", policy_id])
|
||||
if not isinstance(levels, list):
|
||||
return []
|
||||
|
||||
results = []
|
||||
for level in levels:
|
||||
name = level.get("name", "").split("/")[-1]
|
||||
title = level.get("title", "")
|
||||
basic = level.get("basic", {})
|
||||
has_device = any(
|
||||
c.get("devicePolicy") for c in basic.get("conditions", [])
|
||||
)
|
||||
has_ip = any(
|
||||
c.get("ipSubnetworks") for c in basic.get("conditions", [])
|
||||
)
|
||||
results.append({"name": name, "title": title, "has_device": has_device, "has_ip": has_ip})
|
||||
print(f" {title}: device_policy={has_device}, ip_restriction={has_ip}")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def audit_iap_tunnel_access(project_id: str) -> dict:
|
||||
"""Audit IAP TCP tunnel permissions."""
|
||||
print("\n[3/5] Auditing IAP tunnel access...")
|
||||
instances = run_gcloud(["compute", "instances", "list", "--project", project_id])
|
||||
if not isinstance(instances, list):
|
||||
return {"total_vms": 0}
|
||||
|
||||
stats = {"total_vms": len(instances), "with_external_ip": 0, "tunnel_accessible": 0}
|
||||
for vm in instances:
|
||||
name = vm.get("name", "unknown")
|
||||
interfaces = vm.get("networkInterfaces", [])
|
||||
has_ext_ip = any(
|
||||
iface.get("accessConfigs") for iface in interfaces
|
||||
)
|
||||
if has_ext_ip:
|
||||
stats["with_external_ip"] += 1
|
||||
|
||||
print(f" Total VMs: {stats['total_vms']}, With external IP: {stats['with_external_ip']}")
|
||||
if stats["with_external_ip"] > 0:
|
||||
print(f" [WARN] {stats['with_external_ip']} VMs have external IPs - consider removing for IAP-only access")
|
||||
return stats
|
||||
|
||||
|
||||
def audit_iap_logs(project_id: str) -> dict:
|
||||
"""Analyze recent IAP access logs."""
|
||||
print("\n[4/5] Analyzing IAP access logs (24h)...")
|
||||
start = (datetime.now(timezone.utc) - timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
logs = run_gcloud([
|
||||
"logging", "read",
|
||||
f'resource.type="gce_backend_service" AND protoPayload.serviceName="iap.googleapis.com" AND timestamp>="{start}"',
|
||||
"--project", project_id, "--limit=500"
|
||||
])
|
||||
if not isinstance(logs, list):
|
||||
return {"total": 0, "allowed": 0, "denied": 0}
|
||||
|
||||
stats = {"total": len(logs), "allowed": 0, "denied": 0, "users": set()}
|
||||
for entry in logs:
|
||||
payload = entry.get("protoPayload", {})
|
||||
status = payload.get("status", {}).get("code", 0)
|
||||
user = payload.get("authenticationInfo", {}).get("principalEmail", "")
|
||||
if status == 0:
|
||||
stats["allowed"] += 1
|
||||
else:
|
||||
stats["denied"] += 1
|
||||
if user:
|
||||
stats["users"].add(user)
|
||||
|
||||
stats["unique_users"] = len(stats["users"])
|
||||
del stats["users"]
|
||||
print(f" Requests: {stats['total']}, Allowed: {stats['allowed']}, Denied: {stats['denied']}")
|
||||
return stats
|
||||
|
||||
|
||||
def generate_report(project_id: str, backends: list, levels: list,
|
||||
tunnels: dict, logs: dict) -> str:
|
||||
"""Generate IAP audit report."""
|
||||
print("\n[5/5] Generating report...")
|
||||
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
|
||||
iap_on = [b for b in backends if b["iap_enabled"]]
|
||||
iap_off = [b for b in backends if not b["iap_enabled"]]
|
||||
with_conditions = [b for b in iap_on if b.get("has_conditions")]
|
||||
|
||||
report = f"""
|
||||
Google Cloud IAP Audit Report
|
||||
{'=' * 55}
|
||||
Project: {project_id}
|
||||
Generated: {now}
|
||||
|
||||
1. BACKEND SERVICES
|
||||
Total backend services: {len(backends)}
|
||||
IAP enabled: {len(iap_on)}
|
||||
IAP disabled: {len(iap_off)}
|
||||
With access level conditions: {len(with_conditions)} / {len(iap_on)}
|
||||
|
||||
2. ACCESS LEVELS
|
||||
Total defined: {len(levels)}
|
||||
With device policy: {sum(1 for l in levels if l['has_device'])}
|
||||
With IP restrictions: {sum(1 for l in levels if l['has_ip'])}
|
||||
|
||||
3. VM ACCESS
|
||||
Total VMs: {tunnels['total_vms']}
|
||||
With external IP: {tunnels['with_external_ip']}
|
||||
|
||||
4. ACCESS LOGS (24h)
|
||||
Total requests: {logs['total']}
|
||||
Allowed: {logs['allowed']}
|
||||
Denied: {logs['denied']}
|
||||
Unique users: {logs.get('unique_users', 0)}
|
||||
|
||||
5. RECOMMENDATIONS
|
||||
"""
|
||||
recs = []
|
||||
if iap_off:
|
||||
recs.append(f" - Enable IAP on {len(iap_off)} unprotected backend service(s)")
|
||||
if len(with_conditions) < len(iap_on):
|
||||
recs.append(f" - Add access level conditions to {len(iap_on) - len(with_conditions)} IAP service(s)")
|
||||
if tunnels["with_external_ip"] > 0:
|
||||
recs.append(f" - Remove external IPs from {tunnels['with_external_ip']} VM(s) for IAP-only access")
|
||||
if not recs:
|
||||
recs.append(" - Configuration meets best practices")
|
||||
report += "\n".join(recs)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python process.py <project-id> [access-policy-id]")
|
||||
sys.exit(1)
|
||||
|
||||
project_id = sys.argv[1]
|
||||
policy_id = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
backends = audit_iap_backends(project_id)
|
||||
levels = audit_access_levels(policy_id)
|
||||
tunnels = audit_iap_tunnel_access(project_id)
|
||||
logs = audit_iap_logs(project_id)
|
||||
report = generate_report(project_id, backends, levels, tunnels, logs)
|
||||
print(report)
|
||||
|
||||
filename = f"iap_audit_{project_id}_{datetime.now().strftime('%Y%m%d')}.txt"
|
||||
with open(filename, "w") as f:
|
||||
f.write(report)
|
||||
print(f"\nReport saved to: {filename}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user