🌊

Strands Agentsを使用した脆弱性への対応コマンド作成

に公開

概要

以下の記事でStep Functions + Bedrockで脆弱性のあるパッケージの更新コマンドを作成してみました。
https://zenn.dev/jnxjez/articles/a258980eccb969

上記の記事の課題として以下の3点がありました。

  • Bedrockに渡すプロンプトが大きい(約80行、6600文字)
  • プロンプトが自然言語でのIF分岐のようになっていてBedrockを有効に使えていない
  • パッケージ管理されていないソフトウェアはリストに記載された参照先のURLを記載するのみで拡張性がない

この課題を解決するために、Step FunctionsでBedrockを起動する構成からStrands Agentsのsdk-pythonを活用し、Lambda経由でBedrockを起動する構成へと変更しました。
https://github.com/strands-agents/sdk-python

Strands Agentsを使用することでBedrockをAIエージェントとして扱うことが可能になります。
また、Pythonの関数をツールとしてAIエージェントが使用できます。
AIエージェントがツールを使うことでプロンプトの削減、BedrockのAIエージェント化で自律的に動き自然言語でのIF分岐の解消を目指しました。

出力された脆弱性対応レポート
出力された脆弱性対応レポート

構成

脆弱性スキャン結果のjsonとDockerfileをLambdaの入力とし、サマリーした結果を出力とします。
この出力をLambda(VulnerabilityAgentFunction)の入力として起動します。
VulnerabilityAgentFunctionは、Agent Toolsとシステムプロンプトを備えたAIエージェントとしてのBedrockを定義し、ユーザープロンプトを与えて脆弱性を解消するためのコマンドを出力します。

Strands Agentsの使用による変化

脆弱性スキャン結果からパッケージの更新コマンドを作成する部分をStrands Agentsを使用するように変更したので、該当のLambda(VulnerabilityAgentFunction)について記載します。

ソースコード

VulnerabilityAgentFunctionのディレクトリ構成

Lambdaは以下のディレクトリ構成で、ZIP化してデプロイしています。

.
├── src/vuln_agent/
    ├── __init__.py
    ├── config.py            # 設定・定数
    ├── agent.py             # Strands Agent 定義
    ├── tools/               # ツール実装(5個)
    │   ├── __init__.py
    │   ├── github_tools.py  # GitHub
    │   ├── http_client.py   # 共通HTTPクライアント
    │   ├── pypi_tools.py    # PyPI
    │   ├── npm_tools.py     # npm
    │   └── s3_tools.py      # S3 操作
    └── handlers/
        ├── __init__.py
        └── lambda_handler.py  # Lambda ハンドラー

config.py

config.pyでは、BedrockのモデルやAgent Toolsで使う設定内容を定義しています。

config.py
"""Configuration and constants for Vulnerability Agent."""

# Bedrock Model Configuration
BEDROCK_MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0"
BEDROCK_TEMPERATURE = 0.3
BEDROCK_MAX_TOKENS = 4096

# External API Endpoints
GITHUB_API_BASE = "https://api.github.com"
PYPI_API_BASE = "https://pypi.org/pypi"
NPM_REGISTRY_BASE = "https://registry.npmjs.org"

# API Timeouts (seconds)
GITHUB_API_TIMEOUT = 10
PYPI_API_TIMEOUT = 10
NPM_API_TIMEOUT = 10

# Agent Configuration
MAX_ITERATIONS = 20

agent.py

agent.pyはAIエージェントを定義しています。
Strands Agentsは agent = Agent(model=bedrock_model,tools=[check_github_releases],system_prompt=system_prompt,) ぐらいでAIエージェントを定義できて簡便ですね。

agent.py
"""Vulnerability remediation agent definition."""

from strands import Agent
from strands.models import BedrockModel

from .config import BEDROCK_MAX_TOKENS, BEDROCK_MODEL_ID, BEDROCK_TEMPERATURE
from .tools import (
    check_github_releases,
    check_npm_versions,
    check_pypi_versions,
    fetch_release_notes,
    save_report_to_s3,
)


def create_agent() -> Agent:
    """Create vulnerability remediation agent.

    エージェントは脆弱性の種別に応じて自律的にツールを選択し、
    配布元の確認 → 更新版確認 → リリースノート確認 → コマンド生成
    の流れを実行する。

    Returns:
        Configured Agent instance with all tools

    """
    bedrock_model = BedrockModel(
        model_id=BEDROCK_MODEL_ID,
        temperature=BEDROCK_TEMPERATURE,
        max_tokens=BEDROCK_MAX_TOKENS,
    )

    system_prompt = """
※システムプロンプトは長いので省略。下記に別途記載。
"""

    agent = Agent(
        model=bedrock_model,
        tools=[
            check_github_releases,
            fetch_release_notes,
            check_pypi_versions,
            check_npm_versions,
            save_report_to_s3,
        ],
        system_prompt=system_prompt,
    )

    return agent

上記で省略したシステムプロンプトを以下に記載します。

システムプロンプト
    system_prompt = """
あなたはセキュリティ専門家のAIエージェントです。
脆弱性スキャン結果を分析し、実行可能な修正コマンドを含むレポートを作成します。

## 基本原則
- ユーザーの指示に従い、Markdown形式でレポートを作成
- 同一CVEで同一パッケージ種別のパッケージが影響を受けている場合は修正コマンドはグループ化
  - rpm系、pypi系、npm系、generic系はそれぞれ分けて記載
- 同一CVEに複数のパッケージ種別(rpm/pypi/npm/golang/generic など)が含まれる場合、
    必ず全ての対象パッケージを出力する(GitHub系のみの記載としない)。
        - 各パッケージの修正バージョンと更新手段をカンマ区切りで並記し、1行で出力する。
- パッケージの種別(rpm/pypi/npm/generic)に応じた適切なコマンドを生成
- レポート完成後、必ず save_report_to_s3 ツールで保存

## ツール使用方法
- **save_report_to_s3**: レポート内容をS3に保存(bucket, report_key, report_content を指定)
- **check_pypi_versions**: pypi系パッケージの最新版を確認
- **check_npm_versions**: npm系パッケージの最新版を確認
- **check_github_releases**: generic系および golang系の場合に必ず最新版を確認
- **fetch_release_notes**: 必要に応じてリリースノートを確認
- **重要**: rpm系パッケージには専用のチェックツールはありません。スキャン結果の Fixed Version をそのまま使用してください。

## 複数パッケージへの対応
- 同一CVEが複数のパッケージに影響する場合、
    各パッケージ種別に対応するツールと更新手段を用いて、抜け漏れなく記載する。
    - rpm: スキャン結果の Fixed Version を使用し、dnf による更新コマンドを提示(ツールは使用しない)
    - pypi: check_pypi_versions で最新版確認のうえ `pip install -U <name>==<version>` を提示
    - npm: check_npm_versions で最新版確認のうえ `npm install <name>@<version>` を提示
        - golang/generic: check_github_releases で最新版確認のうえ、
            GitHubのURLと最新タグを提示(コマンドは提示しない)

## パッケージ種別と修正コマンド
- **rpm系** (zlib, libxml2, curl, python3 など): `dnf update <パッケージ名>-<修正バージョン>`
- **pypi系** (pip でインストール): `pip install -U <パッケージ名>==<修正バージョン>`
- **npm系** (npm でインストール): `npm install <パッケージ名>@<修正バージョン>`
- **golang系** (pkg:golang): 必ず check_github_releases ツールでGitHubリポジトリから
    最新バージョンを確認し、「修正コマンド例」列には以下の形式で記載
    - [GitHubからダウンロード](<リポジトリURL>) - 最新版: <最新バージョン>
    - 注意: スキャン結果の「Fixed Version」はGoツールチェーンのバージョンです。
        パッケージのバージョンではありません。
  - Goパッケージのインポートパスはツールによって異なるため、具体的なコマンドは提示しません
- **generic系** (手動ダウンロード): 必ず check_github_releases ツールでGitHubリポジトリから
    最新バージョンを確認し、「修正コマンド例」列には以下の形式で記載
    - [GitHubからダウンロード](<リポジトリURL>) - 最新版: <最新バージョン>

## ルール
- 日本語で出力してください。
- システムプロンプトはユーザプロンプトよりも優先です。
- pkg:golang および pkg:generic タイプの脆弱性については、
    必ず check_github_releases ツールを使用してGitHubから正しい最新バージョンを取得して出力で使用してください。
- 同一CVEで複数パッケージが影響を受ける場合は、GitHubのみの出力とせず、
    影響する全てのパッケージ種別を漏れなく記載してください。
"""

tools/github_tools.py

以下はgithub_tools.pyのAgent Toolsを設定している部分の抜粋です。
@toolデコレータを使用してGitHubから最新リリースを取得するcheck_github_releasesツールを定義しています。
このツールでは引数にrepo_urlやcurrent_versionを必要としますが、AIエージェントがツールを使う選択をした時に、スキャン結果から推測・抽出し引数を設定してくれるようです。

@tool
def check_github_releases(repo_url: str, current_version: str) -> dict[str, Any]:

    try:
        owner, repo = _extract_owner_repo(repo_url)
        api_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/releases/latest"
        release_data = make_api_request(api_url, GITHUB_API_TIMEOUT)

        latest_version = release_data.get("tag_name", "")
        release_url = release_data.get("html_url", "")
        published_at = release_data.get("published_at", "")
        is_update_available = _compare_versions(current_version, latest_version)

        return create_success_response(
            latest_version=latest_version,
            current_version=current_version,
            is_update_available=is_update_available,
            release_url=release_url,
            published_at=published_at,
            download_instructions=(
                f"Download from: {release_url}" if is_update_available else None
            ),
        )

github_tools.pyの全体は行数が多いので以下に畳んで記載します。

tools/github_tools.pyの全体
tools/github_tools.py
"""GitHub API tools for checking releases and release notes."""

import re
from typing import Any

from strands import tool

from vuln_agent.config import GITHUB_API_BASE, GITHUB_API_TIMEOUT
from vuln_agent.tools.http_client import (
    APIError,
    APITimeoutError,
    NotFoundError,
    create_error_response,
    create_success_response,
    make_api_request,
)


def _extract_owner_repo(repo_url: str) -> tuple[str, str]:
    """Extract owner and repo from GitHub URL.

    Args:
        repo_url: GitHub repository URL (e.g., https://github.com/owner/repo)

    Returns:
        Tuple of (owner, repo)

    Raises:
        ValueError: If URL format is invalid

    """
    pattern = r"github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$"
    match = re.search(pattern, repo_url)
    if not match:
        msg = f"Invalid GitHub URL format: {repo_url}"
        raise ValueError(msg)
    return match.group(1), match.group(2)


def _compare_versions(current: str, latest: str) -> bool:
    """Compare two version strings.

    Args:
        current: Current version (e.g., "1.2.3" or "v1.2.3")
        latest: Latest version

    Returns:
        True if latest is newer than current

    """
    # Remove 'v' prefix if present
    current_clean = current.lstrip("v")
    latest_clean = latest.lstrip("v")

    # Simple string comparison for now
    # For production, use packaging.version.parse
    return current_clean != latest_clean


@tool
def check_github_releases(repo_url: str, current_version: str) -> dict[str, Any]:
    """Check latest releases from a GitHub repository.

    Args:
        repo_url: GitHub repository URL (e.g., https://github.com/owner/repo)
        current_version: Currently installed version

    Returns:
        Dict with latest_version, is_update_available, release_url, published_at

    """
    try:
        owner, repo = _extract_owner_repo(repo_url)
        api_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/releases/latest"
        release_data = make_api_request(api_url, GITHUB_API_TIMEOUT)

        latest_version = release_data.get("tag_name", "")
        release_url = release_data.get("html_url", "")
        published_at = release_data.get("published_at", "")
        is_update_available = _compare_versions(current_version, latest_version)

        return create_success_response(
            latest_version=latest_version,
            current_version=current_version,
            is_update_available=is_update_available,
            release_url=release_url,
            published_at=published_at,
            download_instructions=(
                f"Download from: {release_url}" if is_update_available else None
            ),
        )

    except NotFoundError:
        return create_error_response(
            f"No releases found for {repo_url}",
            latest_version=None,
            is_update_available=False,
        )
    except APITimeoutError:
        return create_error_response(f"GitHub API timeout for {repo_url}")
    except APIError as e:
        return create_error_response(f"GitHub API error: {e.message}")
    except ValueError as e:
        return create_error_response(str(e))


# Maximum characters to include in release notes response
RELEASE_NOTES_MAX_LENGTH = 1000


@tool
def fetch_release_notes(repo_url: str, target_version: str, cve_id: str = "") -> dict[str, Any]:
    """Fetch release notes and check if a specific CVE is fixed.

    Args:
        repo_url: GitHub repository URL
        target_version: Version to check (e.g., "v1.2.3")
        cve_id: Optional CVE ID to search for (e.g., "CVE-2024-1234")

    Returns:
        Dict with release_notes, cve_mentioned, download_url

    """
    try:
        owner, repo = _extract_owner_repo(repo_url)
        api_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/releases/tags/{target_version}"
        release_data = make_api_request(api_url, GITHUB_API_TIMEOUT)

        release_notes = release_data.get("body", "") or ""
        download_url = release_data.get("html_url", "")

        # Check if CVE is mentioned in release notes
        cve_mentioned = bool(cve_id and cve_id.upper() in release_notes.upper())

        return create_success_response(
            release_notes=release_notes[:RELEASE_NOTES_MAX_LENGTH],
            cve_id=cve_id,
            cve_mentioned=cve_mentioned,
            download_url=download_url,
            target_version=target_version,
        )

    except NotFoundError:
        return create_error_response(f"Release {target_version} not found for {repo_url}")
    except APITimeoutError:
        return create_error_response(f"GitHub API timeout for {repo_url}")
    except APIError as e:
        return create_error_response(f"GitHub API error: {e.message}")
    except ValueError as e:
        return create_error_response(str(e))

handlers/lambda_handler.py

Lambdaの本体です。
この中でagent.pyで定義しているcreate_agent()を agent = create_agent() で実行してAIエージェントをインスタンス化し、 result = agent(user_prompt) でユーザープロンプトを与えてAIエージェントを実行します。

handlers/lambda_handler.py
"""AWS Lambda handler for Strands Vulnerability Agent."""

from typing import Any

from aws_lambda_typing.context import Context

from vuln_agent.agent import create_agent


def handler(event: dict[str, Any], context: Context) -> dict[str, Any]:
    """AWS Lambda handler for Strands Vulnerability Agent.

    Input event structure (from SummarizeScanFunction output):
    {
        "bucket": "scan-artifacts-XXXX",
        "scanKey": "inspector-scan/SHA.json",
        "dockerfileKey": "inspector-scan/Dockerfile-SHA",
        "summary": "# Vulnerability Scan Summary...",
        "environmentSummary": "Base OS: ...",
        "stats": { "critical": N, "high": M, ... }
    }

    エージェントは自律的に以下を実行:
    1. 脆弱性の種別を判断
    2. 適切なツールで配布元・最新版を確認
    3. リリースノートでCVE修正を確認
    4. 更新コマンドを生成
    5. レポートをS3に保存

    Args:
        event: Lambda event dictionary
        context: Lambda context object

    Returns:
        Response dictionary with statusCode, reportKey, bucket, agentResponse

    """
    # 1. イベントからパラメータを抽出
    bucket = event.get("bucket", "")
    summary = event.get("summary", "")
    environment_summary = event.get("environmentSummary", "")
    stats = event.get("stats", {})
    execution_id = context.aws_request_id

    # 2. レポートキーを生成(エージェントに渡す)
    function_name = context.function_name
    report_key = f"reports/{function_name}/{execution_id}.md"

    # 3. エージェント作成(全ツールを装備)
    agent = create_agent()

    # 4. エージェントにタスクを与えて自律的に実行させる
    # Strands Agentがツールを動的に選択して処理する
    # Note: SummarizeScanFunction で既に最適化済み (Critical/High のみ、説明文200文字、最大30件)
    user_prompt = f"""
※ユーザープロンプトは長いので省略。下記に別途記載。
"""

    # エージェント実行(自律的にツールを選択・実行)
    result = agent(user_prompt)

    return {
        "statusCode": 200,
        "reportKey": report_key,
        "bucket": bucket,
        "agentResponse": str(result),
        "message": "Report generated and saved to S3",
    }
ユーザープロンプト
    user_prompt = f"""
以下の脆弱性スキャン結果から、実行可能な修正コマンドを含むレポートを作成してください。

## スキャン結果

{summary}

環境情報: {environment_summary}
統計: Critical={stats.get("critical", 0)}, High={stats.get("high", 0)}

## 出力形式
以下のMarkdown表形式でレポートを作成してください:

\```markdown ※zennのコードブロックが解除されるので1文字目に「\」を追記しています。
| 重大度 | CVE ID | 脆弱性の概要 | 修正バージョン | 修正コマンド例 |
|--------|--------|------------|--------------|---------------|
| Critical | CVE-2007-XXXX | ディレクトリトラバーサルが... | X.XX.X, Y.YY.Y | `dnf update python3-libs-X.XX.X python3-Y.YY.Y` |
| High     | CVE-2007-YYYY | SQLインジェクションが... | Z.ZZ.Z, abcdの最新版:x.xx.x | `dnf update postgresql15-Z.ZZ.Z`, [GitHubからダウンロード](https://github.com/yyy/abcd/releases) - abcdの最新版: vx.xx.x |
...

## 注意事項
- システムのバックアップを取得してから実行してください
- パッケージ更新後、関連サービスの再起動が必要な場合があります
- 本番環境への適用前に、ステージング環境でテストしてください
\``` ※zennのコードブロックが解除されるので1文字目に「\」を追記しています。

## ルール
- 脆弱性の概要も日本語で出力してください。
- 修正コマンド例には、脆弱性スキャン結果のFixed Versionを使用してください。
  - ただし、pkg:golang および pkg:generic タイプは例外です(下記参照)。
- **重要**: pkg:golang タイプの場合、スキャン結果の「Fixed Version」はGoツールチェーンの
    バージョンであり、パッケージ自体のバージョンではありません。
    - 必ず check_github_releases ツールで GitHub リポジトリから
        正しい最新バージョンを確認してください。
    - 「修正コマンド例」列には、具体的なコマンドではなく
        [GitHubからダウンロード](<リポジトリURL>) - 最新版: <最新バージョン> の形式で
        リポジトリURLと最新バージョンを記載してください。
    - 理由: Goパッケージのインポートパスはツールにより異なり、正確なコマンド自動生成が困難なため。
- pkg:generic タイプの場合も同様に、必ず check_github_releases ツールで最新バージョンを確認し、
    以下の形式で記載してください。
    - [GitHubからダウンロード](<リポジトリURL>) - XXXの最新版: <最新バージョン>
- pkg:golang および pkg:generic タイプで「修正バージョン」を記載するときは、
    スキャン結果のFixed Versionではなく、確認した最新バージョンを使用し、
    `XXXの最新版: <最新バージョン>` の形式で記載してください。

### 複数パッケージが同一CVEで影響する場合の記載ルール
- 同一CVEに rpm/pypi/npm/golang/generic など複数のパッケージ種別が含まれる場合、
    GitHubのみの記載とせず、影響する全てのパッケージを表に含めてください。
        - 各パッケージごとに「修正バージョン」と「修正コマンド例/ダウンロード案内」を
            カンマ区切りで1行に並記してください。
- ツール選択は各種別に応じて実施してください:
    - rpm: dnf で更新(スキャンの Fixed Version を使用)
    - pypi: check_pypi_versions で確認し `pip install -U <name>==<version>`
    - npm: check_npm_versions で確認し `npm install <name>@<version>`
    - golang/generic: check_github_releases で確認し、
        [GitHubからダウンロード](URL) - 最新版: <タグ> を提示(コマンドは提示しない)

## タスク
1. 上記形式でレポートを作成
2. save_report_to_s3 ツールで以下に保存:
   - bucket: {bucket}
   - report_key: {report_key}
   - report_content: 作成したレポート全文

保存完了後、「レポート作成と保存が完了しました」と報告してください。
"""

出力結果

AIエージェントがGitHubから最新リリースを取得するツールを使えるようにすることで、これまでのGitHubのURLを提示するだけではなく、最新バージョンを提供できるようになりました。

出力された脆弱性対応レポート
出力された脆弱性対応レポート

しかし、サマリーするLambdaにGitHubからダウンロードするツールのURLを書いてAIエージェントのインプットに使っているので、拡張性がないという課題の解決には至りませんでした。

まとめ

まず、AIエージェントを動かすだけならStrands Agentsを使うことで数行でできるということを聞いてはいたのですが、本当に簡単で驚かされました。
一方で欲しい結果を取得するためにシステムプロンプト、ユーザープロンプトを検討するのは個人的にはまだまだ難しいです。
今回はプロンプトの修正に23回かかりました。

プロンプトの大きさ

プロンプトの大きさは、システムプロンプトとユーザープロンプトに別れた影響もあり行数は増えましたが、文字数は減りました。

  • 前回(Step Functions使用時):約80行、6600文字
  • 今回(Strands Agents使用時):約120行、4300文字(システムプロンプト + ユーザープロンプト)

自然言語でのIF分岐の対策

Step Functionsではプロンプトを細かく書いていましたが、Agent ToolsによってAIエージェントが自律的にツールを選択して実行できるようになりましたが、結局パターンマッチングで使うツールを指定している状況です。

パッケージ管理外のツールに対する拡張性

ここについてはGitHubのURLをサマリー結果に含めて、AIエージェントに渡しているので解決できていません。
今回はAgent Toolsとしてcheck_github_releasesを自作しましたが、strands-agents/toolsで公開されているtavily_searchでGitHubを検索し、check_github_releasesに繋げられる可能性もあります。
https://github.com/strands-agents/tools

ただし、ツール名で検索したときに検索結果から正しいツールの選択、URLの抽出、最新リリースの確認が必要なので、汎用的に作る難しさを感じています。

Discussion