
threatcl v0.6.5
HCLを使った脅威モデルの文書化
threatcl
HCLを使った脅威モデリング
hcltmはどうなったの?
hcltmはthreatclに改名されました。ようこそ!
概要
[!TIP] 新しいドキュメントを読みたいですか?threatcl.dev にアクセスしてください。
脅威モデルの文書化にはさまざまな方法があります。シンプルなテキストファイルから、より詳細なワード文書、集中型ソリューションでの完全に計装された脅威モデルまで様々です。脅威モデルの最も価値のある属性の2つは、脅威を明確に文書化できることと、価値ある変化を促進できることです。
threatclは、以下の目標に焦点を当てることで、システム脅威モデルを文書化するためのDevOpsファーストのアプローチを提供することを目指しています:
- シンプルなテキストファイル形式
- シンプルなCLI駆動のユーザーエクスペリエンス
- バージョン管理システム(VCS)への統合
このリポジトリはthreatcl CLIソフトウェアの本拠地です。threatclの仕様は、HCL2(HashiCorpの設定言語)に基づいており、「人間にとって読み書きしやすく、機械が生成・解析しやすいJSONベースのバリエーション」を目指しています。threatclの仕様はgithub.com/threatcl/specにあります。threatcl CLIソフトウェアとthreatcl仕様を組み合わせることで、実践者はHCLでシステム脅威モデルを定義できます。例えば:```hcl
threatmodel "Tower of London" {
description = "A historic castle"
author = "@xntrik"
attributes { new_initiative = "true" internet_facing = "true" initiative_size = "Small" }
information_asset "crown jewels" { description = "including the imperial state crown" information_classification = "Confidential" }
usecase { description = "The Queen can fetch the crown" }
third_party_dependency "community watch" { description = "The community watch helps guard the premise" uptime_dependency = "degraded" }
threat "Crown theft" { description = "Someone who isn't the Queen steals the crown" impacts = ["Confidentiality"]
control "Guards" {
description = "Trained guards patrol tower"
risk_reduction = 75
}
}
data_flow_diagram_v2 "dfd name" { // ... see below for more information }
}
データフローダイアグラムを自動的にPNGに変換する方法の詳細については、[Data Flow Diagram](#data-flow-diagram) を参照してください。
[OWASP Proactive Controls](https://owasp.org/www-project-proactive-controls/) および [AWS Security Checklist](https://d1.awsstatic.com/whitepapers/Security/AWS_Security_Checklist.pdf) の事前定義されたコントロールライブラリを参照する方法の例については、[examples/tm3.hcl](https://github.com/threatcl/threatcl/blob/HEAD/examples/tm3.hcl) を参照してください。また、[MITRE ATT&CK Controls](https://attack.mitre.org/mitigations/enterprise/) は[here](https://github.com/threatcl/threatcl/blob/HEAD/examples/MITRE_ATTACK_controls.hcl)にも用意しています。
外部の脅威モデルを自身のモデルに組み込むことで、そのすべての情報を参照して使用することもできます。例としては、[examples/including-example/corp-app.hcl](https://github.com/threatcl/threatcl/blob/HEAD/examples/including-example/corp-app.hcl) を参照してください。
仕様の完全な説明については、[here](https://github.com/threatcl/threatcl/blob/HEAD/spec.hcl) を参照するか、以下を実行してください:```bash
threatcl generate boilerplate
threatcl は JSON ファイルも処理できますが、唯一の注意点として、インポートモジュールと変数は機能しません。例として examples/tm1.json を参照してください。
HCL の理由
HCL は、HashiCorp の製品、特にオープンソースの Infrastructure-as-Code ソフトウェアである Terraform で使用される主要な設定言語です。私は HashiCorp でしばらく働いていましたが、この言語はとても気に入りました。さらに、DevOps やソフトウェアエンジニアがこの言語を使用しているなら、脅威モデルの文書化を簡素化することは threatcl の目標と一致します。
threatcl を JSON で使用することもできますが、一部の機能は失われます。詳細については、examples/ フォルダを参照してください。
なぜ MD で文書化しないのか?
プログラム的に操作できる形式を使うというアイデアが気に入りました。
謝辞と参考資料
threatcl の機能の 1 つは、HCL ファイルから データフロー図 を自動生成することです。これは、Marqeta と Blake Hitchcock による go-dfd パッケージを活用しています。DevOps の速度での脅威モデル に関する彼らのブログ記事もぜひご覧ください。
また、HashiCorp の Jamie Finnigan と Talha Tariq には、HashiCorp を退職した後もこのオープンソースツールの開発を続けることを許可してくれたことに感謝します。
さらに、OpenThreatModel 仕様 を提供してくれた IriusRisk チームにも感謝します。
threatcl CLI
インストール
最新バージョンを リリースページ からダウンロードし、threatcl バイナリを PATH に移動してください。
Homebrew でインストール
Homebrew を使用して threatcl をインストールします — フォーミュラは homebrew-core にあります。```bash
brew install threatcl
## Docker で実行```bash
docker run --rm -it ghcr.io/threatcl/threatcl:latest
リリースの検証(ビルドの来歴)
すべてのタグ付きリリースにはSLSAビルド来歴が含まれています —
Sigstoreで署名され、キーレスな証明書であり、GitHub Actionsのリリースパイプラインによって生成されます(GitHub OIDC → Fulcio、署名鍵は不要)。GitHub CLI(gh attestation verify — 追加のツールや信頼された鍵の管理は不要)を使用して、バイナリまたはコンテナイメージがこのリポジトリのリリースワークフローから真正にビルドされたことを検証できます。
ダウンロードしたアーカイブ(またはSHA256SUMSファイル)を検証します:```bash
gh attestation verify threatcl_.tar.gz --repo threatcl/threatcl
コンテナイメージを検証してください(タグは自動的にダイジェストに解決されます):```bash
gh attestation verify oci://ghcr.io/threatcl/threatcl:<version> --repo threatcl/threatcl
実行するイメージを正確にピン留めするには、ダイジェストを自分で解決し、ダイジェストで検証(およびプル)を行ってください:```bash digest=$(docker buildx imagetools inspect ghcr.io/threatcl/threatcl: --format '{{ .Manifest.Digest }}') gh attestation verify oci://ghcr.io/threatcl/threatcl@${digest} --repo threatcl/threatcl
完全なサプライチェーンの姿勢については、[docs/SLSA.md](https://github.com/threatcl/threatcl/blob/HEAD/docs/SLSA.md) を参照してください。
## GitHub Actions で実行する
`threatcl` は、https://github.com/threatcl/threatcl-action を使用して GitHub リポジトリに直接統合できます。これは脅威モデルを管理する理想的な方法の一つであり、バージョン管理システムへの統合という目標を達成するのに役立ちます。
## ソースからのビルド
1. このリポジトリをクローンします。
2. `threatcl` ディレクトリに移動します。
3. `make bootstrap`
4. `make build`
`threatcl` への貢献に関する詳細なヘルプについては、[CHANGELOG.md](https://github.com/threatcl/threatcl/blob/HEAD/CHANGELOG.md) を参照してください。
## 使用方法
任意のサブコマンドのヘルプを表示するには、`-h` フラグを使用します。```bash
$ threatcl
Usage: threatcl [--version] [--help] <command> [<args>]
Available commands are:
cloud Interact with ThreatCL Cloud services
dashboard Generate markdown files from existing HCL threatmodel file(s)
dfd Generate Data Flow Diagram PNG or DOT files from existing HCL threatmodel file(s)
export Export threat models into other formats
generate Generate an HCL Threat Model
list List Threatmodels found in HCL file(s)
mcp Model Context Protocol (MCP) server for threatcl
mermaid Output raw mermaid source from 'mermaid' blocks in existing HCL threatmodel file(s)
query Execute GraphQL queries against threat model data
server Start a GraphQL API server for threat models
terraform Parse output from 'terraform show -json'
validate Validate existing HCL Threatmodel file(s)
view View existing HCL Threatmodel file(s)
(オプション) 設定ファイル
threatcl コマンドのほとんどには -config フラグがあり、config.hcl ファイルを指定できます。このファイル内の HCL を使用して、threatcl のデフォルト属性の一部を上書きできます。以下にその一覧を示します。
- Initiative Sizes - デフォルトは "Undefined", "Small", "Medium", "Large"
- Default Initiative Size - デフォルトは "Undefined"
- Information Classifications - デフォルトは "Restricted", "Confidential", "Public"
- Default Information Classification - デフォルトは "Confidential"
- Impact Types - デフォルトは "Confidentiality", "Integrity", "Availability"
- STRIDE Elements - デフォルトは "Spoofing", "Tampering", "Info Disclosure", "Denial Of Service", "Elevation Of Privilege"
- Uptime Dependency Classifications - デフォルトは "none", "degraded", "hard", "operational"
- Default Uptime Depency Classification - デフォルトは "none"
例:```hcl initiative_sizes = ["S", "M", "L"] default_initiative_size = "M" info_classifications = ["1", "2"] default_info_classification = "1" impact_types = ["big", "small"] strides = ["S", "T"] uptime_dep_classifications = ["N", "D"] default_uptime_dep_classification = "N"
これらの属性を変更する場合は、他の操作のために設定ファイルを提供する必要があることを覚えておいてください。これは検証やダッシュボードの作成に影響を与える可能性があります。
## クラウドコマンド
`cloud` サブコマンドの詳細については、https://threatcl.dev/cloud/overview/ をご覧ください。
## リストと表示
`threatcl list` および `threatcl view` コマンドを使用して、`threatcl` 仕様の HCL ファイルからデータを一覧表示および表示できます。```bash
$ threatcl list examples/*
# File Threatmodel Author
1 examples/tm1.hcl Tower of London @xntrik
2 examples/tm1.hcl Fort Knox @xntrik
3 examples/tm2.hcl Modelly model @xntrik
Validate
threatcl validate コマンドは、threatcl スペック HCL ファイルを検証するために使用されます。```bash
$ threatcl validate examples/*
Validated 3 threatmodels in 3 files
### 不変条件
`threatcl validate`は、組織全体の不変条件 — 機械的にチェック可能なルール(例:「公開エンドポイントは認証なしであってはならない」や「すべてのインターネット向け機能は監査ログを文書化しなければならない」)— を、検証済みのすべての脅威モデルに対して適用することもできます:```bash
$ threatcl validate -invariants=invariants.hcl ./models/
Validated 4 threatmodels in 3 files
Invariant violation [error] 'threats_have_implemented_controls': threat 'Credential theft' in threatmodel 'Payments' (models/payments.hcl): Every threat must have at least one implemented control
Checked 3 invariants against 4 threatmodels: 1 errors, 0 warnings, 1 exemptions
不変条件(Invariants)は独自のHCLファイルに存在し、特定のコレクション(脅威、コントロール、DFDプロセス、フローなど)をターゲットとし、その条件をネイティブのHCL式として表現します。error/warningの重大度と、モデルごとの正当化を伴う免除をサポートしています。詳細はdocs/invariants.mdを参照してください。
エクスポート
threatcl exportコマンドは、threatcl脅威モデル(または複数のモデル)を、デフォルトではネイティブJSON表現に、またはOTM json表現に、さらにはhclに戻す(動的脅威モデルから新しいHCLを出力するのに便利です)ために使用されます。-outputフラグを使用してファイルに直接保存することもできます。```bash
$ threatcl export -format=otm examples/tm1.hcl
[{"assets":[{"description":"including the imperial state crown","id":"crown-jewels","name":"crown jewels","risk":{"availability":0,"confidentiality":0,"integrity":0}}],"mitigations":[{"attributes":{"implementation_notes":"They are trained to be guards as well","implemented":true},"description":"Lots of guards patrol the area","id":"lots-of-guards","name":"Lots of Guards","riskReduction":80}],"otmVersion":"0.2.0","project":{"attributes":{"initiative_size":"Small","internet_facing":true,"network_segment":"dmz","new_initiative":true},"description":"A historic castle","id":"tower-of-london","name":"Tower of London","owner":"@xntrik"},"threats":[{"categories":["Confidentiality"],"description":"Someone who isn't the Queen steals the crown","id":"threat-1","name":"Threat 1","risk":{"impact":0,"likelihood":null}}]},{"assets":[{"description":"Lots of gold","id":"gold","name":"Gold","risk":{"availability":0,"confidentiality":0,"integrity":0}}],"mitigations":[{"attributes":{"implemented":true},"description":"A large wall surrounds the fort","id":"big-wall","name":"Big Wall","riskReduction":80}],"otmVersion":"0.2.0","project":{"attributes":{"initiative_size":"Small","internet_facing":true,"new_initiative":false},"description":"A .. fort?","id":"fort-knox","name":"Fort Knox","owner":"@xntrik"},"threats":[{"categories":["Confidentiality"],"description":"Someone steals the gold","id":"threat-1","name":"Threat 1","risk":{"impact":0,"likelihood":null}}]}]
## 生成
`threatcl generate`コマンドは、汎用の`boilerplate` `threatcl`仕様HCLファイルを出力するか、対話的にユーザーに質問して`threatcl`仕様HCLファイルを出力するために使用されます。
### 対話的な生成
次の例を参照してください:```bash
threatcl generate interactive
対話型エディタを生成する
$EDITOR 内で直接作業することを好む場合は、次のコマンドを実行します:```bash
threatcl generate interactive editor
これにより、最小限のHCL脅威モデルがエディタで開かれます。作成後にモデルを検証したい場合は、`-validate`フラグを使用してください。
## MCP
`threatcl mcp`コマンドは、ローカルの[MCP](https://modelcontextprotocol.io/introduction)サーバーを公開します。これにより、MCPホストを介してthreatcl hclファイルと対話できます。例えば、[Claude Desktop](https://claude.ai/download)、[Cursor](https://www.cursor.com/)、またはMCPをサポートするその他のAI/LLMアプリケーションなどです。
このコマンドは、オプションの引数`-dir=<path>`を1つ受け取ります。これにより、追加のMCPツールがそのパス内のファイルと対話できるようになります。この設定がない場合、MCPツールは文字列と対話できますが、基盤となるファイルシステムとの対話はMCPホスト内の他のメカニズムに依存します。
現時点では、この機能はかなりベータ版であると言えます。
## LSP(言語サーバー)
`threatcl lsp`コマンドは、[Language Server Protocol](https://microsoft.github.io/language-server-protocol/)サーバーをstdio上で実行し、LSP対応エディタにthreatcl HCL脅威モデルのライブ診断、補完、ホバー、ドキュメントシンボル、および書式設定を提供します。
これは手動で実行するのではなく、エディタのLSPクライアントによって起動されます。threatclファイルはTerraformやその他のHCL方言と`.hcl`拡張子を共有するため、`*.tm.hcl`でのマッチング(またはクライアントを脅威モデルワークスペースにスコープする)により、Terraform言語サーバーとの競合を回避できます。
エディタの設定(Neovim、Helix、VS Code、Zed)と現在の制限事項については、[docs/lsp.md](https://github.com/threatcl/threatcl/blob/HEAD/docs/lsp.md)を参照してください。
## Server(GraphQL API)
`threatcl server`コマンドは、GraphQL APIサーバーを起動し、脅威モデルをHTTP経由で公開して、プログラムによるクエリと統合を可能にします。
### 基本的な使い方```bash
# Start the server
$ threatcl server -dir ./examples
# With file watching for auto-reload
$ threatcl server -dir ./examples -watch
# Custom port
$ threatcl server -dir ./examples -port 3000
http://localhost:8080 に移動して、インタラクティブなGraphQL Playgroundにアクセスしてください。
クエリ例```graphql
query { stats { totalThreatModels totalThreats implementedControls }
threatModels(filter: { internetFacing: true }) { name threats { description controls { name implemented } } } }
### ドキュメント
完全なAPIドキュメント、スキーマリファレンス、高度なクエリ、および統合例については、以下を参照してください:
- **完全なAPIドキュメント**: [docs/graphql-api.md](https://github.com/threatcl/threatcl/blob/HEAD/docs/graphql-api.md)
- **クエリ例**: [examples/graphql-queries.md](https://github.com/threatcl/threatcl/blob/HEAD/examples/graphql-queries.md)
## クエリ(GraphQL CLI)
`threatcl query` コマンドは、サーバーを起動せずにコマンドラインから直接GraphQLクエリを実行します。これは自動化、CI/CDパイプライン、およびシェルスクリプトに最適です。
### 基本的な使い方```bash
# Get statistics
$ threatcl query -dir ./examples -query '{ stats { totalThreats } }'
# Query from file
$ threatcl query -dir ./examples -file queries/get-stats.graphql
# Use in scripts
$ THREATS=$(threatcl query -dir ./examples \
-query '{ stats { totalThreats } }' \
-output compact | jq -r '.data.stats.totalThreats')
$ echo "Found $THREATS threats"
出力形式
pretty(デフォルト): インデント付きの整形されたJSONjson: prettyと同じcompact: スクリプト用の一行JSON
変数を使ったクエリ```bash
$ threatcl query -dir ./examples
-query 'query($author: String) { threatModels(filter: {author: $author}) { name } }'
-vars '{"author": "John Doe"}'
### CI/CD の例```bash
#!/bin/bash
# Check if all controls are implemented before deployment
UNIMPLEMENTED=$(threatcl query -dir ./threatmodels \
-query '{ stats { totalControls implementedControls } }' \
-output compact | jq -r '.data.stats.totalControls - .data.stats.implementedControls')
if [ "$UNIMPLEMENTED" -gt 0 ]; then
echo "ERROR: $UNIMPLEMENTED controls are not yet implemented"
exit 1
fi
echo "All controls implemented, proceeding with deployment"
利用可能なクエリとGraphQLスキーマについては、docs/graphql-api.mdを参照してください。
Dashboard
threatcl dashboardコマンドは、threatcl仕様のHCLファイルを受け取り、多数のmarkdownおよびpngファイルを生成し、選択したフォルダに出力します。```bash
$ threatcl dashboard -overwrite -outdir=dashboard-example examples/*
Created the 'dashboard-example' directory
Writing dashboard markdown files to 'dashboard-example' and overwriting existing files
Successfully wrote to 'dashboard-example/tm1-toweroflondon.md'
Successfully wrote to 'dashboard-example/tm1-fortknox.md'
Successfully wrote to 'dashboard-example/tm2-modellymodel.png'
Successfully wrote to 'dashboard-example/tm2-modellymodel.md'
Successfully wrote to 'dashboard-example/dashboard.md'
### Custom Markdown Templates
`threatcl dashboard` コマンドは、カスタムテンプレートを指定するためのオプションフラグも受け取ることができます(Go言語の [text/template](https://pkg.go.dev/text/template) に準拠)。
ダッシュボードテンプレートファイルを指定するには、`-dashboard-template` フラグを使用します。例については、[dashboard-template.tpl](https://github.com/threatcl/threatcl/blob/HEAD/examples/dashboard-template.tpl) を参照してください。
スレットモデルテンプレートファイルを指定するには、`-threatmodel-template` フラグを使用します。例については、[threatmodel-template.tpl](https://github.com/threatcl/threatcl/blob/HEAD/examples/threatmodel-template.tpl) を参照してください。
### Custom Filename for the Dashboard Index file
`threatcl dashboard` コマンドは、生成されるダッシュボードファイルの「インデックス」ファイル名を指定するためのオプションフラグも受け取ることができます。デフォルトではこのファイルは `dashboard.md` です。拡張子なしで `-dashboard-filename` フラグを使用して、このファイル名を変更します。
## Data Flow Diagram
[spec](https://github.com/threatcl/threatcl/blob/HEAD/spec.hcl) に従って、`threatmodel` は `data_flow_diagram_v2` ブロックを含むことができます。簡単なDFDの例は [こちら](https://github.com/threatcl/threatcl/blob/HEAD/examples/tm2.hcl) にあります。古い単一使用ブロックの `data_flow_diagram` はいつか非推奨になる予定なので、名前付きブロックの `data_flow_diagram_v2` を使用することをお勧めします。これにより、複数の関連するDFDを持つことができます。
`threatcl dfd` コマンドは、`threatcl` 仕様のHCLファイルを受け取り、複数のPNGファイルを生成して、選択したフォルダに配置します。
HCLファイルに `data_flow_diagram` または `data_flow_diagram_v2` ブロックを含む `threatmodel` ブロックがない場合、何も出力されません。
コマンド自体は Dashboard コマンドと非常に似ています。```bash
$ threatcl dfd -overwrite -outdir testout examples/*
Successfully created 'testout/tm2-modellymodel.png'
threatmodelにdiagram_linkが含まれていないが、data_flow_diagramが含まれている場合、threatcl dashboardを実行するときにもこれがレンダリングされます。
Mermaid
仕様specに従って、threatmodelには自由形式のmermaidブロックを含めることもできます。data_flow_diagram_v2(threatclが自動的にレンダリング)とは異なり、mermaidブロックは生のmermaidソースをそのまま埋め込みます。mermaidはコンテンツの最初の行から図のタイプ(シーケンス、状態、フローチャートなど)を推測します。
threatcl mermaidコマンドはその生のソースを抽出し、他のレンダリングツールにパイプできるようにします。それ自体は画像をレンダリングしません。
デフォルトでは、ソースはSTDOUTに出力されます:```bash $ threatcl mermaid examples/tm2.hcl sequenceDiagram User->>App: credentials App->>Auth: verify Auth-->>App: token
これにより、[mermaid-cli](https://github.com/mermaid-js/mermaid-cli) のようなレンダラーにパイプで渡すことが簡単になります:```bash
$ threatcl mermaid model.hcl | mmdc -o diagram.svg -i -
複数の mermaid ブロックがある場合、-index=n で一つを選択するか、-outdir でそれらすべてをディレクトリに書き込みます(ブロックごとに一つの .mmd ファイル)。また、-out で単一のブロックをファイルに書き込むこともできます。```bash
$ threatcl mermaid -outdir testout model.hcl
Successfully created 'testout/model-mymodelloginsequence.mmd'
## Terraform
`threatcl terraform` コマンドは、`terraform show -json`([ドキュメントはこちら](https://www.terraform.io/docs/cli/commands/show.html))の出力(プランファイルまたはアクティブなステートファイル)からデータリソースを抽出し、それらをドラフトの `information_asset` ブロックに変換して、`threatcl` ファイルに含めることができます。
既存のステートがあるフォルダにいる場合は、次のコマンドを実行できます。```bash
terraform show -json | threatcl terraform -stdin
出力は次のようになります:```bash information_asset "aws_rds_cluster default" { description = "cluster_identifier: aurora-cluster-demo, database_name: mydb" information_classification = "" source = "terraform state" } information_asset "aws_s3_bucket example" { description = "bucket: terraform-20211107232017071500000001" information_classification = "" source = "terraform state" }
また、まだTerraformで適用されていない計画ファイルからの同様の出力を確認するには、次のコマンドを実行します。```bash
terraform show -json <plan-file> | threatcl terraform -stdin
既存の threatcl 脅威モデルファイル("threatmodel.hcl")を更新したい場合は、次のようにします:```bash
terraform show -json | threatcl terraform -stdin -add-to-existing=threatmodel.hcl > new-threatmodel.hcl
`-add-to-existing` フラグを使用すると、ソースファイル内に複数の脅威モデルがある場合に、特定の脅威モデルを指定するために `-tm-name=<string>` を指定することもできます。また、`-default-classification=Confidential` フラグを使用して、デフォルトの分類を適用することもできます。
これらのコマンドはファイルを入力として受け取ることもできます。その場合は、`-stdin` フラグを省略してください。
`threatcl` が認識している terraform リソースは、[pkg/terraform/terraform.go](https://github.com/threatcl/threatcl/blob/HEAD/pkg/terraform/terraform.go) にハードコードされています。`threatcl terraform` コマンドでそこに含まれていない他の `information_asset` リソースを出力したい場合は、`-tf-collection=<json file>` フラグを使用して、この json の独自バージョンを提供できます。