目次
Amazon CodeGuru Security 完全ガイド v2.0(2026年最新対応)
SAST/DAST統合セキュリティスキャン・多言語対応・IDE統合
目次
- ドキュメントメタデータ
- 概要と課題
- アーキテクチャと設計原則
- 検出カテゴリ・脆弱性
- コアコンポーネント
- 主要ユースケース
- 設定・操作の具体例
- 類似サービス比較表
- ベストプラクティス
- トラブルシューティング表
- 2025-2026最新動向
- 学習リソース・参考文献
- 実装例・チェックリスト
- まとめ
ドキュメントメタデータ
- 最終更新: 2026-04-26
- バージョン: v2.0
- 対象者: Security Engineer、Application Developer、DevSecOps、CISO
- 難易度: 中級~上級
- ⚠️ 重要: End-of-Life 2025-04-30(CodeGuru Reviewer セキュリティ機能統合)
- 関連サービス: CodeGuru Reviewer、Amazon Q Developer、Inspector、GuardDuty、AWS WAF
概要と課題
本質
Amazon CodeGuru Security は 「機械学習と静的解析(SAST)を組み合わせた多言語対応コードセキュリティスキャンサービス」 である。OWASP Top 10・CWE(共通脆弱性タイプ一覧)基準でセキュリティ脆弱性を検出し、Java・Python・JavaScript・TypeScript・C#・Go・Ruby・Rust の 8 言語に対応する。IDE プラグイン(VS Code・JetBrains)・CodePipeline・GitHub Actions に統合でき、コーディング中のリアルタイムセキュリティフィードバック(Shift Left)を実現する。
2025-04-30 に CodeGuru Reviewer のセキュリティ機能を統合し、CodeGuru Security がセキュリティ検出の唯一の統合窓口になる。
このサービスを選ぶ理由
なぜ Amazon CodeGuru Security なのか?
-
AWS ネイティブの SAST
- Snyk・Checkmarx 等の外部 SAST ツールと異なり、CodeGuru Security は AWS SDK の使用パターン・IAM ポリシー・認証情報の誤った扱いなどの AWS 固有のセキュリティ問題を検出可能
- Lambda タイムアウト設定漏れ・DynamoDB スキャン過剰・SQS 権限昇格などを自動検出
-
多言語対応(8 言語)
- 従来の CodeGuru Reviewer(Java/Python のみ)と異なり、TypeScript・Go・C# など多言語対応
- マルチ言語マイクロサービス環境で統一 SAST ツール実現
-
IDE でのリアルタイム検出(Shift Left)
- VS Code・JetBrains プラグインをインストール
- コーディング中に脆弱性を警告・修正提案を実時間表示
- コミット前に修正でき、CI/CD での後付けレビューより効率的
-
CI/CD パイプラインへのネイティブ統合
- CodePipeline アクション・GitHub Actions ワークフロー・GitLab CI から直接呼び出し
- セキュリティ脆弱性を含むコードの本番マージをパイプラインレベルでブロック
- 脆弱性レベル(Critical / High)に応じた自動判定
-
見つかった脆弱性への修正提案
- 単なる問題検出ではなく、具体的なコード修正提案を提供
- セキュリティ専門知識がない開発者でも問題修正可能
-
CodeGuru Reviewer との統合
- CodeGuru Reviewer のセキュリティ機能(Secrets Detection など)を CodeGuru Security に統合 -単一のセキュリティ検出エンジン・料金体系で一元化
このサービスを選ばない理由
- DAST(動的解析)が必須 → AWS WAF・GuardDuty などと併用
- SCA(ソフトウェア構成分析)が必須 → Inspector と併用
- Runtime 脅威検出が必須 → GuardDuty と併用
アーキテクチャと設計原則
全体構成図(Mermaid 1)
graph TB
subgraph Developer["開発環境"]
IDE["IDE: VS Code / JetBrains<br/>CodeGuru Security Plugin"]
GIT["Git Push / PR"]
end
subgraph Scanner["CodeGuru Security Engine"]
SAST["SAST Analysis<br/>(Static Code Analysis)"]
ML["ML Detection<br/>(Pattern Recognition)"]
SECRET["Secrets Detection<br/>(Credentials)"]
end
subgraph Integration["統合ポイント"]
GITHUB_PR["GitHub Actions<br/>Workflow"]
PIPELINE["CodePipeline<br/>Stage"]
CONSOLE["AWS Console<br/>Dashboard"]
end
subgraph Result["検出・修正"]
FINDING["Finding<br/>(Critical/High/...)"]
FIX["Suggested Fix<br/>Code Snippet"]
end
IDE -->|Scan on Save| SAST
GIT -->|Push| GITHUB_PR
GITHUB_PR -->|Trigger| SAST
SAST -->|並行実行| ML
ML -->|Pattern Match| FINDING
SAST -->|Credential Detection| SECRET
SECRET -->|Hardcoded Creds| FINDING
FINDING -->|Line-by-Line| FIX
FIX -->|IDE Plugin| IDE
FINDING -->|Workflow Report| GITHUB_PR
FINDING -->|Gate Result| PIPELINE
FINDING -->|Dashboard| CONSOLE
style SAST fill:#e8f4f8
style ML fill:#fff3cd
style SECRET fill:#d4edda
style FINDING fill:#f8d7da
style FIX fill:#d1ecf1
スキャン実行パターン
┌─ IDE リアルタイムスキャン(最速フィードバック)
│ ├─ File Save 時に自動トリガー
│ ├─ Finding を行番号付きで表示
│ └─ FIX Suggestion をポップアップ表示
│
├─ PR トリガースキャン(GitHub / GitLab)
│ ├─ PR 作成 / Push で自動トリガー
│ ├─ Diff のみ解析(高速)
│ └─ PR Comments で Finding 投稿
│
├─ CodePipeline 統合スキャン(CI/CD Gate)
│ ├─ Build ステージ後に自動実行
│ ├─ Critical / High で Pipeline 失敗
│ └─ CloudWatch / SNS で通知
│
└─ オンデマンドスキャン(定期・全リポジトリ)
├─ AWS Console / API で手動実行
├─ S3 コードアップロード解析
└─ Full Repository Scan(git history 不要)
検出カテゴリ・脆弱性
1. OWASP Top 10 ベース検出
A01: Broken Access Control
パス・トラバーサル脆弱性:
const file = fs.readFileSync(`/data/${userInput}`);
// ← ../ で任意ファイルアクセス可能
推奨: パス検証 & パスの正規化
const normalized = path.normalize(`/data/${userInput}`);
if (!normalized.startsWith('/data/')) throw new Error('Invalid path');
権限昇格: ユーザー ID 検証漏れ
@PostMapping('/admin/users/{id}')
public void updateUser(@PathVariable int id) {
// ← 認可チェックなし → 他ユーザーの権限昇格可能
}
A02: Cryptographic Failures
弱い暗号化:
MessageDigest.getInstance("MD5") // ❌ 128bit・衝突脆弱性あり
推奨: MessageDigest.getInstance("SHA-256")
ハードコード暗号鍵:
private static final String KEY = "my-secret-key-12345";
推奨: AWS Secrets Manager / Parameter Store から取得
ECB モード(ブロック暗号・最弱):
Cipher.getInstance("AES/ECB/PKCS5Padding")
推奨: Cipher.getInstance("AES/GCM/NoPadding")
平文でのパスワード保存:
String hashedPassword = password; // ❌ 平文保存
推奨: BCrypt / Argon2 でハッシュ化
A03: Injection
SQL インジェクション:
String sql = "SELECT * FROM users WHERE id = " + userId;
stmt = connection.createStatement();
rs = stmt.executeQuery(sql); // ← SQL インジェクション
推奨: Prepared Statement
String sql = "SELECT * FROM users WHERE id = ?";
stmt = connection.prepareStatement(sql);
stmt.setInt(1, userId);
コマンドインジェクション:
Runtime.getRuntime().exec("rm -rf " + userPath);
推奨: ProcessBuilder + Whitelist
XSS(クロスサイトスクリプティング):
response.write("<h1>" + userInput + "</h1>");
推奨: HTML エスケープ or Content Security Policy
LDAP インジェクション:
String filter = "(uid=" + username + ")";
// ← LDAP フィルターインジェクション
A05: Security Misconfiguration
CORS 過剰許可:
@CrossOrigin(origins = "*")
// ❌ すべてのオリジンからのリクエスト許可
推奨: @CrossOrigin(origins = "https://trusted-domain.com")
デバッグモード本番有効化:
logger.setLevel(Level.DEBUG);
推奨: 本番環境では INFO level
デフォルトクレデンシャル:
database.connect("sa", ""); // デフォルト SQL Server ユーザー
A06: Vulnerable Components
既知脆弱性を持つライブラリ(CVE 検出):
log4j-core 2.14.0(Log4Shell)← RCE 脆弱性あり
推奨: log4j-core 2.17.1+ にアップグレード
古いフレームワークバージョン:
spring-core 5.0.0(2018年リリース) → セキュリティ更新なし
A09: Security Logging Failures
スタックトレース漏洩:
} catch (Exception e) {
e.printStackTrace(); // ← stdout に内部情報漏洩
}
推奨: logger.error("Error", e);
機密情報のログ出力:
logger.info("Password: " + password);
推奨: logger.info("User authentication attempt");
2. AWS 固有検出
IAM ポリシー過剰許可:
"Action": "*",
"Resource": "*"
推奨: 最小権限原則
認証情報ハードコーディング:
AWS_ACCESS_KEY = "AKIA..."
推奨: IAM Role / Assume Role / Credentials Provider
Lambda タイムアウト設定漏れ:
serverless.yml で timeout: 3(デフォルト)
推奨: timeout: 30 以上(コールドスタート考慮)
DynamoDB キャパシティ設定:
BillingMode: PROVISIONED で小さい値 → スロットリング
推奨: on-demand 選択 or 適切に provisioning
CloudTrail ログ暗号化なし:
EnableLogFileValidation: false
推奨: EnableLogFileValidation: true + KMS 暗号化
コアコンポーネント
1. Scan(スキャン実行)
定義 CodeGuru Security の単一の解析実行を表すリソース
属性
- ScanName: 識別名(unique)
- ScanArn: arn:aws:codeguru-security:region:account:scan/...
- State: Queued / InProgress / Succeeded / Failed / Canceled
- CreatedAt: ISO 8601
- AnalysisType: Repository / SourceCode / Package(将来拡張)
- ResourceId: リソースの ARN(CodeCommit / GitHub など)
ライフサイクル
Created(IDE Save / PR / API 呼び出し)
↓
Queued(キュー待機)
↓
InProgress(SAST + ML 実行)
↓
Succeeded / Failed
↓
Completed(Finding 取得可能)
2. Finding(検出結果)
定義 検出された個々のセキュリティ問題
属性
- FindingId: 一意識別子
- Severity: CRITICAL / HIGH / MEDIUM / LOW / INFO
- Rule: {RuleId, RuleName, Tags}
例: "java/sql-injection", "py/weak-cryptography"
- Location: {FilePath, StartLine, EndLine, CodeSnippet}
- Message: 問題説明
- Recommendation: 修正提案コード
- RelatedFindings: 関連する Finding(多重脆弱性検出)
重要度ガイドライン
CRITICAL:
- RCE(Remote Code Execution)
- 認証情報漏洩
- SQL インジェクション
→ 即時修正必須
HIGH:
- 権限昇格
- XSS
- CSRF 保護なし
→ リリース前修正
MEDIUM:
- セキュリティ設定ミス
- 弱い暗号化
→ 次スプリント修正推奨
LOW / INFO:
- ベストプラクティス提案
→ バックログに追加
3. Suppression(抑制・無視)
定義 誤検知・例外として Finding を無視する仕組み
形式
# 1. コメントベース抑制
# codeguru-security-suppress: hardcoded-credentials
# Reason: This is a test API key, not production
TEST_API_KEY = "sk-test-1234567890"
# 2. File-level suppression(.suppression ファイル)
# rules:
# - rule: hardcoded-credentials
# paths: [tests/**]
# reason: Test credentials in non-prod code
4. IDE Plugin(VS Code / JetBrains)
機能
- Real-time Scanning(File Save 時)
- Inline Finding Display(行番号付き警告)
- Quick Fix(ワンクリック修正提案)
- Severity Badge(CRITICAL / HIGH 目立つ表示)
インストール
# VS Code
# 1. Extensions → "CodeGuru Security" 検索
# 2. Install
# 3. AWS Credentials 設定(IAM ユーザー / assume role)
# JetBrains (IntelliJ / WebStorm など)
# 1. Settings → Plugins → Marketplace → "CodeGuru"
# 2. Install
# 3. Restart IDE
主要ユースケース
1. IDE リアルタイムセキュリティフィードバック(Shift Left)
シナリオ 開発者がコードを書きながら、VS Code で秒単位にセキュリティ脆弱性を検出・修正提案を表示
# test.py
import hashlib # ← CodeGuru Plugin が警告
def hash_password(password):
# ❌ Severity: HIGH
# CodeGuru: Weak cryptography detected
# Line 5: hashlib.md5 is insecure
# Suggestion: Use hashlib.sha256 instead
return hashlib.md5(password.encode()).hexdigest()
# 開発者が修正提案をクリック → 自動修正
def hash_password(password):
import bcrypt # ← IDE が自動 import
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
2. GitHub Actions で PR Security Gate
シナリオ PR 作成時に GitHub Actions で CodeGuru Security を実行→CRITICAL・HIGH で merge ブロック
name: CodeGuru Security Scan
on:
pull_request:
branches: [main, develop]
push:
branches: [main]
jobs:
security-scan:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
security-events: write
steps:
- uses: actions/checkout@v4
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/codeguru-github-oidc
aws-region: ap-northeast-1
- name: CodeGuru Security Scan
uses: aws-actions/codeguru-security@v1
with:
source_path: .
aws_region: ap-northeast-1
fail_on_severity: High # High 以上で失敗
s3_bucket: my-codeguru-scan-bucket
- name: Upload SARIF to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: codeguru-results.sarif.json
3. CodePipeline Security Quality Gate
シナリオ CodePipeline の Build → Test → Security Gate ステージで CodeGuru を実行
{
"stages": [
{
"name": "Source",
"actions": [...]
},
{
"name": "Build",
"actions": [...]
},
{
"name": "SecurityScan",
"actions": [{
"name": "CodeGuruSecurityGate",
"actionTypeId": {
"category": "Invoke",
"owner": "AWS",
"provider": "Lambda",
"version": "1"
},
"configuration": {
"FunctionName": "codeguru-security-gate-lambda"
}
}]
}
]
}
import boto3
def lambda_handler(event, context):
codeguru_security = boto3.client('codeguru-security')
codepipeline = boto3.client('codepipeline')
job_id = event['CodePipeline.job']['id']
# CodeGuru Security Scan
scan_response = codeguru_security.create_scan(
scanName=f"pipeline-scan-{job_id}",
resourceId={'codeArtifacts': {...}}
)
# Findings を取得
findings = codeguru_security.get_findings(
scanName=scan_response['scanName'],
status='Open'
)['findings']
# Critical / High をカウント
blockers = [f for f in findings if f['severity'] in ['CRITICAL', 'HIGH']]
if not blockers:
codepipeline.put_job_success_result(jobId=job_id)
else:
codepipeline.put_job_failure_result(
jobId=job_id,
failureDetails={
'message': f'{len(blockers)} security findings',
'type': 'JobFailed'
}
)
4-12. (その他 9 ユースケース省略)
設定・操作の具体例
CLI / API 操作(5 パターン)
1. Scan 作成・Status 監視
# S3 にコードをアップロード
aws s3 cp myapp.zip s3://codeguru-scans/myapp.zip
# Upload URL 取得
UPLOAD_URL=$(aws codeguru-security create-upload-url \
--scan-name myapp-scan-$(date +%Y%m%d) \
--region ap-northeast-1 \
--query 'uploadUrl' \
--output text)
# コードをアップロード
curl -X PUT "$UPLOAD_URL" \
-H "Content-Type: application/zip" \
--data-binary @myapp.zip
# Scan 開始
SCAN_ARN=$(aws codeguru-security create-scan \
--scan-name myapp-scan \
--resource-id codeArtifacts='[{
"s3BucketName": "codeguru-scans",
"codeArtifactsS3ObjectKey": "myapp.zip"
}]' \
--region ap-northeast-1 \
--query 'scanArn' \
--output text)
# Status 監視
while true; do
STATE=$(aws codeguru-security get-scan \
--scan-arn $SCAN_ARN \
--region ap-northeast-1 \
--query 'scan.state' \
--output text)
echo "State: $STATE"
if [ "$STATE" = "Succeeded" ] || [ "$STATE" = "Failed" ]; then
break
fi
sleep 10
done
2. Findings 取得・フィルタリング
# 全 Findings
aws codeguru-security get-findings \
--scan-arn $SCAN_ARN \
--status Open \
--region ap-northeast-1
# CRITICAL のみ
aws codeguru-security get-findings \
--scan-arn $SCAN_ARN \
--status Open \
--query 'findings[?severity==`CRITICAL`].[ruleName,filePath,lineNumber,message]' \
--output table
# JSON で詳細取得
aws codeguru-security get-findings \
--scan-arn $SCAN_ARN \
--status Open \
--output json > findings.json
3. Finding Status 更新(Suppression)
# Finding を Suppressed(無視)にする
aws codeguru-security update-finding-status \
--scan-arn $SCAN_ARN \
--finding-id finding-123 \
--status Suppressed \
--reason "Test credential, not production" \
--region ap-northeast-1
4. CodeCommit リポジトリのスキャン(CLI)
# CodeCommit リポジトリをスキャン
SCAN_ARN=$(aws codeguru-security create-scan \
--scan-name codecommit-scan \
--resource-id codeRepository='{
"repositoryName": "my-repo",
"branchName": "main"
}' \
--region ap-northeast-1 \
--query 'scanArn' \
--output text)
echo "Scan started: $SCAN_ARN"
5. SARIF フォーマットでエクスポート(GitHub Security)
# SARIF フォーマットで Findings を取得
aws codeguru-security get-findings \
--scan-arn $SCAN_ARN \
--output json | \
jq -r '.findings | map({
ruleId: .ruleName,
message: {text: .message},
locations: [{
physicalLocation: {
artifactLocation: {uri: .filePath},
region: {startLine: .lineNumber}
}
}]
}) | {version: "2.1.0", runs: [{tool: {driver: {name: "CodeGuru-Security", rules: .}}, results: .}]}' \
> codeguru-results.sarif.json
# GitHub にアップロード(GitHub Actions で)
curl -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Content-Type: application/json" \
https://api.github.com/repos/$GITHUB_REPO/code-scanning/sarifs \
-d @codeguru-results.sarif.json
SDK / Infrastructure as Code(5 パターン)
1. CloudFormation での IAM Role 設定
AWSTemplateFormatVersion: '2010-09-09'
Resources:
CodeGuruSecurityRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: codeguru-security.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonCodeGuruSecurityFullAccess
Policies:
- PolicyName: S3Access
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::codeguru-scans/*
CodeGuruSecurityBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub 'codeguru-scans-${AWS::AccountId}'
VersioningConfiguration:
Status: Enabled
2. Terraform での自動スキャン設定
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_s3_bucket" "codeguru_scans" {
bucket = "codeguru-scans-${data.aws_caller_identity.current.account_id}"
}
resource "aws_iam_role" "codeguru_security" {
name = "codeguru-security-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
Service = "codeguru-security.amazonaws.com"
}
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role_policy" "codeguru_security_s3" {
name = "codeguru-security-s3"
role = aws_iam_role.codeguru_security.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject"
]
Resource = "${aws_s3_bucket.codeguru_scans.arn}/*"
}]
})
}
data "aws_caller_identity" "current" {}
3. CDK(TypeScript)での GitHub Actions 統合
import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class CodeGuruSecurityStack extends cdk.Stack {
constructor(scope: cdk.App, id: string) {
super(scope, id);
// S3 Bucket for scans
const scanBucket = new s3.Bucket(this, 'ScanBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
// IAM Role for GitHub Actions OIDC
const githubRole = new iam.Role(this, 'GitHubOIDCRole', {
assumedBy: new iam.WebIdentityPrincipal(
'arn:aws:iam::' + this.account + ':oidc-provider/token.actions.githubusercontent.com',
{
StringEquals: {
'token.actions.githubusercontent.com:aud': 'sts.amazonaws.com',
},
StringLike: {
'token.actions.githubusercontent.com:sub': 'repo:myorg/myrepo:ref:refs/heads/main',
},
}
),
});
githubRole.addToPolicy(
new iam.PolicyStatement({
actions: [
'codeguru-security:CreateScan',
'codeguru-security:GetScan',
'codeguru-security:GetFindings',
],
resources: ['*'],
})
);
scanBucket.grantReadWrite(githubRole);
}
}
4. Python SDK(Boto3)での自動スキャン・レポート生成
import boto3
import json
from datetime import datetime
def scan_and_report(scan_name: str, s3_bucket: str, code_key: str):
"""CodeGuru Security を実行してレポート生成"""
codeguru = boto3.client('codeguru-security')
s3 = boto3.client('s3')
# 1. Scan 作成
print(f"Creating scan: {scan_name}")
response = codeguru.create_scan(
scanName=scan_name,
resourceId={
'codeArtifacts': [
{
's3BucketName': s3_bucket,
'codeArtifactsS3ObjectKey': code_key
}
]
}
)
scan_arn = response['scanArn']
print(f"Scan ARN: {scan_arn}")
# 2. Scan 完了まで待機
waiter = codeguru.get_waiter('scan_succeeded')
try:
waiter.wait(scanArn=scan_arn)
except Exception as e:
print(f"Scan failed: {e}")
return None
# 3. Findings 取得
findings_response = codeguru.get_findings(
scanArn=scan_arn,
status='Open'
)
findings = findings_response.get('findings', [])
# 4. レポート生成
report = {
'timestamp': datetime.now().isoformat(),
'scanArn': scan_arn,
'totalFindings': len(findings),
'bySeverity': {},
'byRule': {},
'criticalHighFindings': []
}
for finding in findings:
severity = finding['severity']
rule = finding['ruleName']
# Severity ごとの集計
if severity not in report['bySeverity']:
report['bySeverity'][severity] = 0
report['bySeverity'][severity] += 1
# Rule ごとの集計
if rule not in report['byRule']:
report['byRule'][rule] = 0
report['byRule'][rule] += 1
# Critical / High 詳細
if severity in ['CRITICAL', 'HIGH']:
report['criticalHighFindings'].append({
'ruleName': rule,
'filePath': finding['filePath'],
'lineNumber': finding['lineNumber'],
'message': finding['message']
})
# 5. レポートを S3 に保存
report_key = f"reports/{scan_name}-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
s3.put_object(
Bucket=s3_bucket,
Key=report_key,
Body=json.dumps(report, indent=2),
ContentType='application/json'
)
print(f"Report saved to: s3://{s3_bucket}/{report_key}")
print(json.dumps(report, indent=2))
return report
if __name__ == '__main__':
scan_and_report(
scan_name='myapp-security-scan',
s3_bucket='codeguru-scans-123456789012',
code_key='myapp.zip'
)
5. Lambda で定期スキャン(EventBridge)
import boto3
import os
from datetime import datetime
codeguru = boto3.client('codeguru-security')
s3 = boto3.client('s3')
def lambda_handler(event, context):
"""
EventBridge Scheduled Event(毎週月曜 09:00 UTC)で実行
複数リポジトリを自動スキャン
"""
repositories = [
{'name': 'myapp-api', 'key': 'repos/myapp-api.zip'},
{'name': 'myapp-web', 'key': 'repos/myapp-web.zip'},
{'name': 'myapp-worker', 'key': 'repos/myapp-worker.zip'},
]
bucket = os.environ['CODEGURU_BUCKET']
scan_results = []
for repo in repositories:
print(f"Scanning: {repo['name']}")
try:
# Scan 作成
response = codeguru.create_scan(
scanName=f"weekly-{repo['name']}-{datetime.now().strftime('%Y%m%d')}",
resourceId={
'codeArtifacts': [
{
's3BucketName': bucket,
'codeArtifactsS3ObjectKey': repo['key']
}
]
}
)
scan_results.append({
'repository': repo['name'],
'scanArn': response['scanArn'],
'status': 'started'
})
except Exception as e:
print(f"Error scanning {repo['name']}: {str(e)}")
scan_results.append({
'repository': repo['name'],
'status': 'failed',
'error': str(e)
})
return {
'statusCode': 200,
'scans': scan_results
}
類似サービス比較表
| 観点 | CodeGuru Security | Snyk Code | SonarQube | Semgrep | GitHub Advanced Security |
|---|---|---|---|---|---|
| 対応言語 | 8言語 | 20+ | 30+ | 30+ | 多言語 |
| 検出基準 | OWASP / CWE | OWASP / CWE | カスタム | カスタム | OWASP |
| IDE プラグイン | VS Code / JetBrains | ✅ | ✅ | ❌ | ❌ |
| PR コメント | ❌ | ✅ | △ | ✅ | ✅ |
| AWS SDK 検出 | ✅ | △ | ❌ | ❌ | ❌ |
| SCA(脆弱性ライブラリ) | ❌ | ✅ | ✅(プラグイン) | ❌ | ✅ |
| DAST(動的解析) | ❌ | △ | ✅ | ❌ | ❌ |
| リアルタイムIDE | ✅ | ✅ | ✅ | ❌ | ❌ |
| CloudFormation検出 | ❌ | ❌ | ❌ | ❌ | ❌ |
| 料金 | $0.01/100行 | $250+/月 | 無料/商用 | 無料/商用 | GitHub Enterprise |
| 推奨用途 | AWS + 多言語 | 多言語DevSecOps | エンタープライズ | セキュアな開発 | GitHub統合 |
ベストプラクティス(✅/❌)
| # | プラクティス | 理由 |
|---|---|---|
| ✅ 1 | IDE プラグイン導入で Shift Left | コミット前に修正・効率最大化 |
| ✅ 2 | CI/CD パイプラインで Quality Gate | 脆弱性コードの本番マージ防止 |
| ✅ 3 | Severity 別の SLA 設定 | CRITICAL: 24h / HIGH: 1 週間 / MEDIUM: 2 週間 |
| ✅ 4 | Suppression で誤検知管理 | Suppression コメント + Reason 記載 |
| ✅ 5 | CloudWatch で Finding トレンド監視 | メトリクス・アラーム設定 |
| ✅ 6 | Secrets を除外スキャン対象に | .suppression で test 資格情報をホワイトリスト |
| ✅ 7 | 定期的な全リポジトリスキャン | 月1回の complete scan で陳腐化検出 |
| ✅ 8 | SARIF エクスポートで GitHub Security 連携 | GitHub のセキュリティダッシュボード統合 |
| ❌ 1 | スキャン結果を放置 → 積み残し増加 | |
| ❌ 2 | 全 Finding をブロッカーに → 開発速度低下 | |
| ❌ 3 | セキュリティチームへの通知なし → コンプライアンスリスク |
トラブルシューティング表
| エラー / 症状 | 原因 | 対策 |
|---|---|---|
| Scan が Queued のまま | キュー待機中・スキャン容量枯渇 | 数分待機 / 別の時間帯にリトライ |
| “Insufficient permissions” | IAM ロール権限不足 | AmazonCodeGuruSecurityFullAccess ポリシー追加 |
| “Invalid S3 URI” | S3 バケット / キーが存在しない | aws s3 ls s3://bucket/key で確認 |
| IDE Plugin が Finding を表示しない | AWS Credentials 未設定 | IDE Settings → AWS → Credentials 設定 |
| Finding のコード片が表示されない | ソースコード読み込み失敗 | S3 / リポジトリアクセス権限確認 |
| SARIF エクスポートで GitHub に upload できない | GitHub Token 権限不足 | security-events:write 権限確認 |
| CloudFormation / Terraform で関数が見つからない | AWS Provider バージョン古い | aws provider upgrade / terraform init -upgrade |
2025-2026 最新動向
1. Container Image Scanning(2026 上半期 GA 予定)
# ECR イメージ自動スキャン
aws codeguru-security scan-image \
--image-reference 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/myapp:latest
2. Infrastructure as Code(IaC)Scanning
CloudFormation / Terraform の セキュリティ検出
- 過度な IAM 権限(Resource: “*”)
- 暗号化なし EBS ボリューム
- Public RDS Database
3. CodeGuru Security + Q Developer 統合
Amazon Q が Finding に対して自動修正提案・コード生成
4. Runtime Threat Detection との連携
GuardDuty Runtime Threat Detection + CodeGuru Security の完全統合
- 開発時:CodeGuru Security(SAST)
- Runtime:GuardDuty Malware Protection
学習リソース・参考文献
AWS 公式ドキュメント
-
Amazon CodeGuru Security User Guide
-
CodeGuru Security API Reference
-
CodeGuru Detector Library
オープンソース・ベンダー
-
OWASP Top 10
-
CWE (Common Weakness Enumeration)
-
SonarQube
-
Semgrep
実装例・チェックリスト
実装例:GitHub → CodeGuru Security → GitHub Security 統合
(省略:設定スクリプト・workflow ファイル)
採用チェックリスト
- [ ] 複数言語(Java / Python / TypeScript / Go など)を使用
- [ ] GitHub / GitLab / CodeCommit を使用
- [ ] IDE リアルタイムセキュリティフィードバックが必要
- [ ] CodePipeline / GitHub Actions でセキュリティゲートが必要
- [ ] OWASP Top 10 対応が必須(規制要件)
- [ ] AWS SDK 固有の脆弱性検出が必要
- [ ] Secrets Detection(認証情報ハードコーディング検出)が必要
- [ ] $0.01/100 行の従量課金が予算内か
まとめ
Amazon CodeGuru Security は 「機械学習と静的解析を組み合わせた多言語対応コードセキュリティスキャンサービス」。OWASP Top 10・CWE 基準で 8 言語の脆弱性を検出し、IDE プラグインで開発中にリアルタイムフィードバックを提供する(Shift Left)。CodePipeline・GitHub Actions のゲートとして高重要度の脆弱性をリリース前にブロックし、Secrets Detection で認証情報ハードコーディングを防ぐ。AWS SDK 固有のセキュリティパターン検出に優れ、2025-04-30 の CodeGuru Reviewer End-of-Life に伴い、コードセキュリティ検出の統一されたエンジンになる。従量課金($0.01/100 行)で低コスト・高精度のセキュリティスキャンを実現。
最終更新:2026-04-26 バージョン:v2.0