AWS セキュリティエージェント(クラウドセキュリティの監視・検査を行う自動化ツール)を現在のワークスペースに設定します。エージェント用のスペース、IAM サービスロール(アクセス権限)、S3 バケット(データ保存場所)を新規作成または既存のものを再利用します。 次のような場合に使用: - ユーザーが「セキュリティエージェントをセットアップしてほしい」と依頼したとき - 「セキュリティスキャナを設定してほしい」と依頼されたとき - 「セキュリティエージェントは設定済みですか」と質問されたとき - 初めてセキュリティスキャンやペネトレーションテスト(脆弱性診断)を実行する前に必要な初期設定として
Configure AWS Security Agent for the current workspace — provision or reuse an agent space, IAM service role, and S3 bucket. Use when the user asks to "set up security agent", "configure security scanner", "is security agent configured", or on first-time use before any scan or pentest.
このスキルの役目は、ワークスペースに動作するエージェント スペース、IAM サービスロール、および S3 バケットが適切に連携していることを確認することです。スキャンとペネトレーション テスト(セキュリティ侵入試験)は別のスキルで実行され、このセットアップが済んでいることを前提としています。
すべての Security Agent スキルは、.security-agent/ 下にワークスペースローカルな状態を共有します:
config.json — { "agent_space_id": "as-...", "region": "us-east-1", "code_reviews": { "<abs_path>": "cr-..." } } の形式。アカウント ID、ロール ARN、バケット名は規約によって導出されます。code_reviews マップにより、スキャン機能は同じワークスペース内で同じ CodeReview を再利用できます。scans.json — { scan_id, code_review_id, job_id, agent_space_id, scan_type, title, started_at, status, path } の形式の配列(最新 50 件を保持)pentests.json — ペネトレーション テスト ジョブ用で同じ構造.gitignore — * の内容で、このディレクトリが Git で追跡されないようにしますfindings-{scan_id}.md — 各スキャン完了後、スキャン スキルが書き込むファイルこのスキルの役目は、config.json を生成し、.gitignore を作成することです。
他のスキルは config.json から読み込むのではなく、実行時に毎回以下の値を計算します:
| 値 | 規約 |
|---|---|
ACCOUNT |
aws sts get-caller-identity --query Account --output text |
REGION |
config.region(デフォルト us-east-1) |
service_role_arn |
arn:aws:iam::${ACCOUNT}:role/SecurityAgentScanRole |
s3_bucket |
security-agent-scans-${ACCOUNT}-${REGION} |
最小限の設定にする理由: ロール名とバケット名は決定的に生成されるため、それらを保存すると設定ずれが生じるリスク(ユーザーが手動でロールを再作成した場合、古いパスを無言で使用する可能性)があります。agent_space_id だけを保存するのは、ユーザーが複数のエージェント スペースを持つ可能性があり、セッションのたびに尋ねたくないからです。
既存の状態を確認: .security-agent/config.json があれば読み込みます。
呼び出し元のアイデンティティとリージョン:
export ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
export REGION="${AWS_REGION:-us-east-1}"
エージェント スペース:
config.agent_space_id が設定されている場合、以下で検証します:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>
レスポンスに存在しないことが示されている場合は、不在として扱います。
不在の場合、既存のものを一覧表示します:
aws securityagent list-agent-spaces
既存のものがある場合 → ユーザーに表示(名前と ID を示す)し、「これらのうちの 1 つを再利用しますか、それとも新しいものを作成しますか?」と尋ねます。ユーザーの答えを待ちます。自動選択しないでください。
ユーザーが 1 つを選択した場合は、その agentSpaceId を使用します。
ユーザーが新規作成を希望するか、存在しない場合:
aws securityagent create-agent-space --name security-scans
返された agentSpaceId を記録します。
サービスロール (SecurityAgentScanRole、ARN は arn:aws:iam::$ACCOUNT:role/SecurityAgentScanRole):
プローブ:
aws iam get-role --role-name SecurityAgentScanRole
NoSuchEntity が返される場合、ロールを作成します。べき等性の注意: create-role は、ロールが既に存在する場合 EntityAlreadyExists で失敗します。その場合は update-assume-role-policy に進んで、信頼ポリシーが正しいことを確認します。
# 信頼ポリシー — aws:SourceAccount の混同代理人ガード(不正利用防止)を含みます
cat > /tmp/sa-trust.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"securityagent.amazonaws.com"},"Action":"sts:AssumeRole","Condition":{"StringEquals":{"aws:SourceAccount":"${ACCOUNT}"}}}]}
EOF
# 権限ポリシー(S3 + CloudWatch Logs)
cat > /tmp/sa-perms.json <<EOF
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","s3:GetObjectVersion","s3:ListBucket"],"Resource":["arn:aws:s3:::security-agent-scans-${ACCOUNT}-${REGION}","arn:aws:s3:::security-agent-scans-${ACCOUNT}-${REGION}/*"]},
{"Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"arn:aws:logs:*:${ACCOUNT}:log-group:/aws/securityagent/*"}
]}
EOF
aws iam create-role --role-name SecurityAgentScanRole --assume-role-policy-document file:///tmp/sa-trust.json
# EntityAlreadyExists の場合:
aws iam update-assume-role-policy --role-name SecurityAgentScanRole --policy-document file:///tmp/sa-trust.json
# 常に権限を適用(または再適用):
aws iam put-role-policy --role-name SecurityAgentScanRole --policy-name SecurityAgentCodeReviewAccess --policy-document file:///tmp/sa-perms.json
S3 バケット (security-agent-scans-$ACCOUNT-$REGION):
バケット所有権の強制(必須)。 バケット名はカラーの AWS アカウント ID とリージョンから導出されます。これらは秘密ではなく、ARN / ECR URI から公に導出可能です。そのため、第三者は予測可能な名前を自分のアカウントで事前登録(横取り)できます。すべての S3 呼び出しは
--expected-bucket-owner "$ACCOUNT"を渡す必要があります。これにより、バケットが他のアカウントに所有されている場合、操作は失敗します。存在するが他のアカウント所有のバケットへの403 Forbiddenは致命的 — セットアップを中止し、決してアップロードしないでください。
プローブ(所有権を主張):
BUCKET="security-agent-scans-${ACCOUNT}-${REGION}"
NEED_CREATE=0
if aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT" 2>/tmp/sa-head.err; then
: # バケットが存在し、このアカウントが所有 — 再利用できます
elif grep -q '404' /tmp/sa-head.err; then
NEED_CREATE=1
elif grep -Eq '403|Forbidden' /tmp/sa-head.err; then
echo "FATAL: bucket $BUCKET exists but is owned by another account (403). Possible bucket-squatting — aborting. Nothing was uploaded." >&2
exit 1
else
cat /tmp/sa-head.err >&2; exit 1
fi
見つからない場合は作成します。BucketAlreadyExists エラーは他のアカウントが既に世界規模の名前を保有していることを意味します — 致命的として扱い、BucketAlreadyOwnedByYou(安全なノーオペレーション)と区別します。作成後、さらに使用する前に所有権を再度主張します:
if [ "$NEED_CREATE" = "1" ]; then
if [ "$REGION" = "us-east-1" ]; then
# us-east-1: LocationConstraint なし
aws s3api create-bucket --bucket "$BUCKET" 2>/tmp/sa-create.err || true
else
# 他のリージョン:
aws s3api create-bucket --bucket "$BUCKET" \
--create-bucket-configuration LocationConstraint="$REGION" 2>/tmp/sa-create.err || true
fi
if grep -q 'BucketAlreadyExists' /tmp/sa-create.err; then
echo "FATAL: bucket name $BUCKET is already owned by another account (BucketAlreadyExists). Possible bucket-squatting — aborting." >&2
exit 1
elif [ -s /tmp/sa-create.err ] && ! grep -q 'BucketAlreadyOwnedByYou' /tmp/sa-create.err; then
cat /tmp/sa-create.err >&2; exit 1
fi
# 新しく作成したバケットの所有権を使用前に確認します。
aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT"
fi
常にパブリック アクセス ブロックと 30 日のライフサイクルを適用(または再適用):
aws s3api put-public-access-block --bucket "$BUCKET" \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
cat > /tmp/sa-lifecycle.json <<'EOF'
{"Rules":[{"ID":"AutoDeleteUploads","Status":"Enabled","Filter":{"Prefix":""},"Expiration":{"Days":30}}]}
EOF
aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" --lifecycle-configuration file:///tmp/sa-lifecycle.json
エージェント スペースにロールとバケットを登録(べき等):
既存のリソースを読み込みます:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>
agentSpaces[0].awsResources.iamRoles と awsResources.s3Buckets を確認します。
ロール ARN またはバケット名がそれらのリストにない場合、マージして更新します:
aws securityagent update-agent-space --agent-space-id <id> --name <existing-name> \
--aws-resources iamRoles=[<arn1>,<arn2>...],s3Buckets=[<bucket1>,<bucket2>...]
.security-agent/config.json に永続化(最小限 — アカウント/ロール/バケットは導出):
{
"agent_space_id": "as-xxxxx",
"region": "us-east-1"
}
gitignore がない場合は作成:
mkdir -p .security-agent
echo '*' > .security-agent/.gitignore
ユーザーに確認:「セットアップが完了しました。セキュリティ スキャンまたはペネトレーション テストを実行できるようになりました。」
--expected-bucket-owner "$ACCOUNT" を渡す必要があります。バケット名は秘密でないアカウント ID から導出されるため、第三者が事前登録できます。外部所有バケットへの 403/BucketAlreadyExists は致命的 — 中止して決してアップロードしないでください。securityagent.amazonaws.com(本番サービス プリンシパル)を許可し、aws:SourceAccount 混同代理人ガードを含める必要がありますSecurityAgentScanRole / security-agent-scans-${ACCOUNT}-${REGION})を使用しています。これらのデフォルトを受け入れるか、スキルを拡張してください — 他のスキルは設定から読み込むのではなく、これらの名前を導出します。config.json が不在の場合このスキルをインラインで呼び出すことができます — 初回利用者がセットアップを別途実行する必要はありません。iam:CreateRole 呼び出しで AccessDenied → ユーザーは IAM 権限がありません。ユーザー自身のロール ARN でセットアップを実行するか、iam:CreateRole + iam:PutRolePolicy を付与するよう依頼してください。This skill handles ONE thing: making sure the workspace has a working agent space, IAM service role, and S3 bucket linked together. Scans and pentests live in separate skills and assume this is done.
All Security Agent skills share workspace-local state at .security-agent/:
config.json — { "agent_space_id": "as-...", "region": "us-east-1", "code_reviews": { "<abs_path>": "cr-..." } }. Account ID, role ARN, and bucket name are derived by convention. The code_reviews map lets scans reuse the same CodeReview for a workspace.scans.json — array of { scan_id, code_review_id, job_id, agent_space_id, scan_type, title, started_at, status, path } (keep last 50)pentests.json — same shape, for pentest jobs.gitignore — contents * so this directory stays untrackedfindings-{scan_id}.md — written by the scan skill after each scan completesThis skill's job is to populate config.json and create .gitignore.
Other skills compute these on each invocation rather than reading them from config.json:
| Value | Convention |
|---|---|
ACCOUNT |
aws sts get-caller-identity --query Account --output text |
REGION |
config.region (default us-east-1) |
service_role_arn |
arn:aws:iam::${ACCOUNT}:role/SecurityAgentScanRole |
s3_bucket |
security-agent-scans-${ACCOUNT}-${REGION} |
Why minimal config: the role name and bucket name are deterministic, so storing them adds drift risk (a user re-creating a role manually would silently use a stale path). Only agent_space_id is stored because users may have multiple agent spaces and we don't want to ask which one every session.
Check existing state: read .security-agent/config.json if it exists.
Caller identity + region:
export ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
export REGION="${AWS_REGION:-us-east-1}"
Agent space:
If config.agent_space_id is set, verify with:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>
If the response shows it doesn't exist, treat as missing.
If missing, list existing:
aws securityagent list-agent-spaces
If any exist → show them to the user with name + id and ask: "Would you like to reuse one of these, or should I create a new one?" Wait for the answer. Do not auto-select.
If user picks one, use that agentSpaceId.
If user wants new, or none exist:
aws securityagent create-agent-space --name security-scans
Capture returned agentSpaceId.
Service role (SecurityAgentScanRole, ARN arn:aws:iam::$ACCOUNT:role/SecurityAgentScanRole):
Probe:
aws iam get-role --role-name SecurityAgentScanRole
If NoSuchEntity is returned, create the role. Idempotency note: create-role will fail with EntityAlreadyExists if the role already exists. If that happens, fall through to update-assume-role-policy to ensure the trust policy is correct.
# Trust policy — includes aws:SourceAccount confused-deputy guard
cat > /tmp/sa-trust.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"securityagent.amazonaws.com"},"Action":"sts:AssumeRole","Condition":{"StringEquals":{"aws:SourceAccount":"${ACCOUNT}"}}}]}
EOF
# Permissions policy (S3 + CloudWatch Logs)
cat > /tmp/sa-perms.json <<EOF
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","s3:GetObjectVersion","s3:ListBucket"],"Resource":["arn:aws:s3:::security-agent-scans-${ACCOUNT}-${REGION}","arn:aws:s3:::security-agent-scans-${ACCOUNT}-${REGION}/*"]},
{"Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":"arn:aws:logs:*:${ACCOUNT}:log-group:/aws/securityagent/*"}
]}
EOF
aws iam create-role --role-name SecurityAgentScanRole --assume-role-policy-document file:///tmp/sa-trust.json
# if EntityAlreadyExists:
aws iam update-assume-role-policy --role-name SecurityAgentScanRole --policy-document file:///tmp/sa-trust.json
# always (re)apply permissions:
aws iam put-role-policy --role-name SecurityAgentScanRole --policy-name SecurityAgentCodeReviewAccess --policy-document file:///tmp/sa-perms.json
S3 bucket (security-agent-scans-$ACCOUNT-$REGION):
Bucket-ownership enforcement (required). The bucket name is derived from the caller's AWS account ID and region — both non-secret and publicly derivable from ARNs / ECR URIs — so any third party can pre-register ("squat") the predictable name in their own account. Every S3 call MUST pass
--expected-bucket-owner "$ACCOUNT"so the operation fails closed if the bucket is owned by someone else. A403 Forbiddenon a bucket that exists but is foreign-owned is fatal — abort setup and never upload.
Probe (asserts ownership):
BUCKET="security-agent-scans-${ACCOUNT}-${REGION}"
NEED_CREATE=0
if aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT" 2>/tmp/sa-head.err; then
: # bucket exists and is owned by this account — safe to reuse
elif grep -q '404' /tmp/sa-head.err; then
NEED_CREATE=1
elif grep -Eq '403|Forbidden' /tmp/sa-head.err; then
echo "FATAL: bucket $BUCKET exists but is owned by another account (403). Possible bucket-squatting — aborting. Nothing was uploaded." >&2
exit 1
else
cat /tmp/sa-head.err >&2; exit 1
fi
If not found, create it. A BucketAlreadyExists error means another account
already holds the global name — treat it as fatal and distinct from
BucketAlreadyOwnedByYou (which is a safe no-op). Re-assert ownership after
creation before any further use:
if [ "$NEED_CREATE" = "1" ]; then
if [ "$REGION" = "us-east-1" ]; then
# us-east-1: no LocationConstraint
aws s3api create-bucket --bucket "$BUCKET" 2>/tmp/sa-create.err || true
else
# other regions:
aws s3api create-bucket --bucket "$BUCKET" \
--create-bucket-configuration LocationConstraint="$REGION" 2>/tmp/sa-create.err || true
fi
if grep -q 'BucketAlreadyExists' /tmp/sa-create.err; then
echo "FATAL: bucket name $BUCKET is already owned by another account (BucketAlreadyExists). Possible bucket-squatting — aborting." >&2
exit 1
elif [ -s /tmp/sa-create.err ] && ! grep -q 'BucketAlreadyOwnedByYou' /tmp/sa-create.err; then
cat /tmp/sa-create.err >&2; exit 1
fi
# Confirm ownership of the freshly created bucket before using it.
aws s3api head-bucket --bucket "$BUCKET" --expected-bucket-owner "$ACCOUNT"
fi
Always (re)apply public access block + 30-day lifecycle:
aws s3api put-public-access-block --bucket "$BUCKET" \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
cat > /tmp/sa-lifecycle.json <<'EOF'
{"Rules":[{"ID":"AutoDeleteUploads","Status":"Enabled","Filter":{"Prefix":""},"Expiration":{"Days":30}}]}
EOF
aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" --lifecycle-configuration file:///tmp/sa-lifecycle.json
Register role + bucket on the agent space (idempotent):
Read existing resources:
aws securityagent batch-get-agent-spaces --agent-space-ids <id>
Look at agentSpaces[0].awsResources.iamRoles and awsResources.s3Buckets.
If the role ARN or the bucket name is missing from those lists, merge and update:
aws securityagent update-agent-space --agent-space-id <id> --name <existing-name> \
--aws-resources iamRoles=[<arn1>,<arn2>...],s3Buckets=[<bucket1>,<bucket2>...]
Persist to .security-agent/config.json (minimal — account/role/bucket are derived):
{
"agent_space_id": "as-xxxxx",
"region": "us-east-1"
}
Create gitignore if missing:
mkdir -p .security-agent
echo '*' > .security-agent/.gitignore
Confirm to user: "Setup complete. You can run security scans or pentests now."
--expected-bucket-owner "$ACCOUNT". The bucket name is derived from a non-secret account ID, so a third party can pre-register it; a 403/BucketAlreadyExists on a foreign-owned bucket is fatal — abort and never upload.securityagent.amazonaws.com (production service principal) and include the aws:SourceAccount confused-deputy guardSecurityAgentScanRole / security-agent-scans-${ACCOUNT}-${REGION}). Either accept those defaults or extend the skill — the other skills derive these names rather than reading them from config.config.json is missing — first-time users don't need to run setup separately.AccessDenied calling iam:CreateRole → user lacks IAM permissions. Ask them to run setup with their own role ARN, or to grant iam:CreateRole + iam:PutRolePolicy.AccessDenied on s3api create-bucket → either the bucket name is taken globally, or the user lacks s3:CreateBucket. Suggest using an existing bucket they own and pass it explicitly.403 Forbidden / BucketAlreadyExists on the derived bucket → the predictable name is owned by a different account (bucket-squatting). This is fatal by design — do not upload. Have the user pick a bucket name they own (or run from the expected account/region) and re-run setup.update-assume-role-policy (step 4 fallback). If they don't want that role updated, ask them for a different role ARN.原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。