mcpField
M
model-supply-chain-security

model-supply-chain-security

github.com/bagelholeセキュリティ1.2k307 回インストール23 週間前に更新
リポジトリ

model-supply-chain-security について

model-supply-chain-security は、ML モデルや推論コンポーネントを改ざんや依存関係の侵害から守るスキルです。ML プラットフォームやセキュリティ担当者向けに、成果物の検証、ビルド来歴の追跡、イメージスキャン、昇格ポリシーの適用を扱います。

主な機能

  1. 01モデル成果物の署名と検証
  2. 02SLSA 来歴情報の生成
  3. 03イメージスキャンと SBOM 生成
  4. 04成果物昇格ポリシーの適用
  5. 05推論ランタイムの強化

活用シーン

  1. 01公開レジストリの事前学習モデルの検証
  2. 02モデルサービング用コンテナのリリース保護
  3. 03侵害された ML 依存関係の調査

インストール

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

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill model-supply-chain-security

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

詳細

モデルサプライチェーンセキュリティ

モデルや推論コンポーネントを、改ざん、依存関係の侵害、信頼できないアーティファクトの昇格から保護します。

このスキルを使用するタイミング

次の場合にこのスキルを使用します。

  • 公開レジストリ(Hugging Face、TensorFlow Hub)から事前学習済みモデルを取得するとき
  • 本番環境にデプロイするモデルサービングコンテナを構築するとき
  • 環境間でMLアーティファクトを昇格する際の信頼ポリシーを確立するとき
  • ML依存関係に影響するサプライチェーンインシデントに対応するとき
  • AIシステムに関するSLSAまたはSOC2のコンプライアンス要件を満たすとき

前提条件

  • 署名と検証のためにcosign v2+がインストールされていること
  • モデルサービングイメージのSBOM生成に使用するsyft
  • OCIイメージ検査用のcraneまたはskopeo
  • 署名に対応したコンテナレジストリ(GHCR、ECR、ACR、Artifact Registry)
  • プロベナンス生成機能を備えたCI/CDパイプライン

脅威

  • 汚染された事前学習済みの重みやアダプター
  • 悪意のあるモデル変換ツールやローダー
  • 侵害されたビルドパイプラインやレジストリ
  • 重大なCVEを含む安全でないランタイムイメージ
  • モデルレジストリでのタイポスクワッティング
  • pickleやカスタムローダーを介したデシリアライズ攻撃

管理目標

  • アーティファクトの完全性をエンドツーエンドで検証する
  • 昇格するすべてのモデルについてプロベナンスを証明する
  • デプロイ前に脆弱な依存関係を検出する
  • 信頼できる署名済みアーティファクトのみ実行できるよう制限する

Cosignによるモデル署名

モデルアーティファクトに署名する
# Generate a keypair (store private key securely)
cosign generate-key-pair

# Sign an OCI-packaged model image
cosign sign --key cosign.key ghcr.io/acme/ml-models/sentiment:v2.1.0

# Keyless signing with Sigstore (uses OIDC identity)
cosign sign ghcr.io/acme/ml-models/sentiment:v2.1.0

# Verify the signature
cosign verify --key cosign.pub ghcr.io/acme/ml-models/sentiment:v2.1.0

# Keyless verification (requires certificate identity)
cosign verify \
  [email protected] \
  --certificate-oidc-issuer=https://accounts.google.com \
  ghcr.io/acme/ml-models/sentiment:v2.1.0
モデルの重みファイルに直接署名する
# For model files stored as blobs (not OCI images)
# Compute digest and sign
sha256sum model-weights.safetensors > model-weights.sha256
cosign sign-blob --key cosign.key model-weights.safetensors \
  --output-signature model-weights.sig \
  --output-certificate model-weights.crt

# Verify blob signature
cosign verify-blob --key cosign.pub \
  --signature model-weights.sig \
  model-weights.safetensors

MLパイプライン向けSLSA

モデルビルドに関するSLSAレベル要件
# slsa-requirements.yaml
slsa_levels:
  level_1:
    - Build process is scripted (not manual)
    - Provenance document generated automatically
  level_2:
    - Build runs on hosted CI service
    - Provenance is authenticated (signed)
    - Source is version controlled
  level_3:
    - Build environment is ephemeral and isolated
    - Provenance is non-falsifiable (hardened builder)
    - Source integrity verified (two-person review)
モデルトレーニングのSLSAプロベナンスを生成する
# .github/workflows/model-build-slsa.yml
name: Model Build with SLSA Provenance
on:
  push:
    tags: ['model-v*']

jobs:
  train-and-package:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4

      - name: Train model
        run: python train.py --config configs/production.yaml

      - name: Package model as OCI artifact
        run: |
          oras push ghcr.io/acme/ml-models/sentiment:${{ github.ref_name }} \
            model-weights.safetensors:application/vnd.acme.model.safetensors \
            model-config.json:application/json

      - name: Generate SBOM for training environment
        run: |
          syft dir:. -o cyclonedx-json > training-sbom.json

      - name: Sign and attest
        run: |
          cosign sign ghcr.io/acme/ml-models/sentiment:${{ github.ref_name }}
          cosign attest --predicate training-sbom.json \
            --type cyclonedx \
            ghcr.io/acme/ml-models/sentiment:${{ github.ref_name }}

      - name: Generate provenance
        uses: slsa-framework/slsa-github-generator/.github/workflows/[email protected]
        with:
          image: ghcr.io/acme/ml-models/sentiment
          digest: ${{ steps.push.outputs.digest }}

プロベナンス用モデルカード

# model-card.yaml
model_details:
  name: "sentiment-classifier-v2.1.0"
  version: "2.1.0"
  type: "text-classification"
  framework: "pytorch"
  license: "Apache-2.0"

provenance:
  training_data:
    source: "s3://acme-datasets/sentiment-v3/"
    hash: "sha256:abc123..."
    data_card_ref: "https://internal.acme.com/data-cards/sentiment-v3"
  training_config:
    source: "git://github.com/acme/ml-models@abc123"
    hyperparameters:
      learning_rate: 0.00005
      epochs: 10
      batch_size: 32
  build_environment:
    builder: "github-actions"
    runner: "ubuntu-22.04"
    python: "3.11.7"
    torch: "2.1.2"
    cuda: "12.1"
  build_id: "gh-actions-12345"
  commit_sha: "abc123def456"
  build_timestamp: "2025-01-15T10:30:00Z"
  signed_by: "[email protected]"

performance:
  accuracy: 0.94
  f1_score: 0.93
  evaluation_dataset: "s3://acme-datasets/sentiment-eval-v3/"
  evaluation_hash: "sha256:def456..."

security:
  vulnerability_scan: "clean"
  sbom_ref: "ghcr.io/acme/ml-models/sentiment:v2.1.0.sbom"
  last_security_review: "2025-01-10"
  known_limitations:
    - "May produce biased outputs for underrepresented languages"
    - "Not evaluated for adversarial robustness"

レジストリのスキャン

# Scan model-serving image for CVEs
trivy image ghcr.io/acme/ml-models/sentiment-serving:v2.1.0

# Generate SBOM for the serving container
syft ghcr.io/acme/ml-models/sentiment-serving:v2.1.0 -o spdx-json > serving-sbom.json

# Scan SBOM for vulnerabilities
grype sbom:serving-sbom.json --fail-on critical

# Check for known-malicious model files (pickle scanning)
pip install fickling
fickling --check model.pkl
レジストリスキャンの自動化パイプライン
# .github/workflows/registry-scan.yml
name: Nightly Registry Scan
on:
  schedule:
    - cron: '0 2 * * *'

jobs:
  scan:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        image:
          - ghcr.io/acme/ml-models/sentiment-serving:latest
          - ghcr.io/acme/ml-models/embedding-serving:latest
          - ghcr.io/acme/ml-models/rag-api:latest
    steps:
      - name: Scan image
        run: |
          trivy image --severity CRITICAL,HIGH \
            --exit-code 1 \
            --format json \
            --output scan-$(echo ${{ matrix.image }} | tr '/:' '-').json \
            ${{ matrix.image }}

      - name: Verify signatures are still valid
        run: |
          cosign verify \
            [email protected] \
            --certificate-oidc-issuer=https://accounts.google.com \
            ${{ matrix.image }}

昇格ポリシーの適用

#!/usr/bin/env python3
"""model_promotion_gate.py - Verify model meets all promotion criteria."""

import subprocess
import json
import sys

def check_signature(image: str) -> bool:
    result = subprocess.run(
        ["cosign", "verify", "[email protected]",
         "--certificate-oidc-issuer=https://accounts.google.com", image],
        capture_output=True, text=True,
    )
    return result.returncode == 0

def check_vulnerabilities(image: str) -> bool:
    result = subprocess.run(
        ["trivy", "image", "--severity", "CRITICAL", "--exit-code", "1",
         "--quiet", image],
        capture_output=True, text=True,
    )
    return result.returncode == 0

def check_sbom_exists(image: str) -> bool:
    result = subprocess.run(
        ["cosign", "verify-attestation", "--type", "cyclonedx",
         "[email protected]",
         "--certificate-oidc-issuer=https://accounts.google.com", image],
        capture_output=True, text=True,
    )
    return result.returncode == 0

def check_model_card(image: str) -> bool:
    result = subprocess.run(
        ["cosign", "verify-attestation", "--type", "custom",
         "[email protected]",
         "--certificate-oidc-issuer=https://accounts.google.com", image],
        capture_output=True, text=True,
    )
    return result.returncode == 0

def main():
    image = sys.argv[1]
    checks = {
        "signature_valid": check_signature(image),
        "no_critical_cves": check_vulnerabilities(image),
        "sbom_attached": check_sbom_exists(image),
        "model_card_present": check_model_card(image),
    }
    all_passed = all(checks.values())
    for name, passed in checks.items():
        status = "PASS" if passed else "FAIL"
        print(f"  [{status}] {name}")
    if not all_passed:
        print("Promotion BLOCKED: not all checks passed.")
        sys.exit(1)
    print("Promotion APPROVED: all checks passed.")

if __name__ == "__main__":
    main()

ランタイムの強化

  • 推論コンテナを非rootユーザーとして実行します。
  • 不正なダウンロードを防ぐため、送信トラフィックを制限します。
  • 可能な場合は、モデルボリュームを読み取り専用でマウントします。
  • 未署名アーティファクトのプル試行をアラートで通知します。
  • デシリアライズ攻撃を防ぐため、pickleの代わりにsafetensors形式を使用します。
# kubernetes deployment hardening
apiVersion: apps/v1
kind: Deployment
metadata:
  name: model-serving
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 1000
      containers:
        - name: inference
          image: ghcr.io/acme/ml-models/sentiment-serving:v2.1.0
          securityContext:
            readOnlyRootFilesystem: true
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: model-weights
              mountPath: /models
              readOnly: true
          resources:
            limits:
              memory: "4Gi"
              nvidia.com/gpu: "1"
      volumes:
        - name: model-weights
          persistentVolumeClaim:
            claimName: model-weights-pvc
            readOnly: true

Admission Control用Kyvernoポリシー

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-signed-model-images
spec:
  validationFailureAction: Enforce
  rules:
    - name: verify-model-image-signature
      match:
        any:
          - resources:
              kinds: ["Pod"]
              namespaces: ["ml-serving"]
      verifyImages:
        - imageReferences: ["ghcr.io/acme/ml-models/*"]
          attestors:
            - entries:
                - keyless:
                    subject: "[email protected]"
                    issuer: "https://accounts.google.com"

トラブルシューティング

問題原因解決策
cosign verifyが「no matching signatures」で失敗するイメージが署名なしでプッシュされた署名手順を再実行します。CIパイプラインのログを確認します
プロベナンスのアテステーションが見つからないSLSAジェネレーターが設定されていないビルドワークフローにslsa-github-generatorを追加します
TrivyがベースイメージのCVEを報告するベースイメージが古いDockerfileのFROMイメージを更新し、再ビルドして再署名します
pickleのデシリアライズ警告が出るモデルが安全でない形式で保存されているsafetensorsに変換します:model.save_pretrained(".", safe_serialization=True)
キーレス検証が失敗するOIDC発行者またはIDが正しくない--certificate-identityフラグと--certificate-oidc-issuerフラグを確認します
アーティファクトのモデルカードが見つからないアテステーションがダイジェストに紐付けられていないcosign attest --predicate model-card.yaml --type custom IMAGEで紐付けます

関連スキル

コメント