
위협 모델링을 위한 파이썬스러운 프레임워크
전통적인 위협 모델링은 너무 늦게 도입되거나 전혀 도입되지 않는 경우가 많습니다. 또한 수동 데이터 흐름 및 보고서 작성은 매우 시간이 많이 소요될 수 있습니다. pytm의 목표는 위협 모델링을 왼쪽으로 이동시켜 더 자동화되고 개발자 중심으로 만드는 것입니다.
입력 및 아키텍처 설계 정의를 기반으로 pytm은 다음 항목을 자동으로 생성할 수 있습니다:
tm.py는 예제 모델입니다. 이를 실행하여 참조하는 보고서와 다이어그램 이미지 파일을 생성할 수 있습니다:```
mkdir -p tm
./tm.py --report docs/basic_template.md | pandoc -f markdown -t html > tm/report.html
./tm.py --dfd | dot -Tpng -o tm/dfd.png
./tm.py --seq | java -Djava.awt.headless=true -jar $PLANTUML_PATH -tpng -pipe > tm/seq.png
또한 예시 `Makefile`이 있어서 이 모든 것을 여러 모델에 쉽게 공유할 수 있는 타겟으로 묶어줍니다. [GNU make](https://www.gnu.org/software/make/)가 설치되어 있다면 (Linux 배포판에는 기본적으로 포함되어 있지만 OSX에는 없음), 다음을 실행하세요:```
make MODEL=the_name_of_your_model_minus_.py
모델과 동일한 디렉토리에 plantuml.jar를 두거나 PLANTUML_PATH를 설정해야 합니다.
pandoc이나 Java와 같은 모든 의존성을 설치하지 않으려면, 스크립트를 컨테이너 내에서 실행할 수 있습니다:```
export USE_DOCKER=true make image
make
### Devbox 변형 - 시작하기
`pytm` 호스트 종속성의 사용을 단순화하기 위해 [`Devbox`](https://github.com/jetify-com/devbox)를 사용하여 완전히 격리할 수 있습니다. 이는 일반적으로 OCI 컨테이너 접근 방식에 비해 오버헤드가 낮고 더 편리한 대안입니다.
- Linux/MacOS에 Devbox 설치: `curl -fsSL https://get.jetify.com/devbox | bash`
- [Windows/WSL](https://www.jetify.com/docs/devbox/installing-devbox/index#installing-wsl2)에 Devbox 설치
- 최신 버전의 devbox로 업데이트: `devbox version update`
- `~/.config/nix/nix.conf` 파일에 GitHub 액세스 토큰 설정: `access-tokens = github.com=YOUR_TOKEN_HERE`
- 프로젝트의 `devbox.json` 파일에 지정된 모든 도구와 패키지를 포함하는 새로운 격리된 셸 환경 생성: `devbox shell`
- 터미널에 `python`을 입력할 때 사용될 Python 실행 파일의 전체 경로를 `which python` 명령어를 사용하여 표시합니다. 출력은 다음 경로여야 합니다: `.devbox/nix/profile/default/bin/python`
- 다음 명령을 실행하여 테스트합니다. 이 명령은 `sample.png`라는 PNG 파일로 DFD를 생성해야 합니다: `./tm.py --dfd | dot -Tpng -o sample.png`
- Devbox 셸 환경 종료: `exit`
## 사용법
사용 가능한 모든 인수:```text
usage: tm.py [-h] [--debug] [--dfd] [--report REPORT] [--exclude EXCLUDE]
[--seq] [--list] [--colormap] [--describe DESCRIBE]
[--list-elements] [--json JSON] [--levels LEVELS [LEVELS ...]]
[--stale_days STALE_DAYS]
options:
-h, --help show this help message and exit
--debug print debug messages
--dfd output DFD
--report REPORT output report using the named template file (sample
template file is under docs/template.md)
--exclude EXCLUDE specify threat IDs to be ignored
--seq output sequential diagram
--list list all available threats
--colormap color the risk in the diagram
--describe DESCRIBE describe the properties available for a given element
--list-elements list all elements which can be part of a threat model
--json JSON output a JSON file
--levels LEVELS [LEVELS ...]
Select levels to be drawn in the threat model (int
separated by comma).
--stale_days STALE_DAYS
checks if the delta between the TM script and the code
described by it is bigger than the specified value in
days
stale_days 인자는 작성 중인 모델 스크립트가 모델링 대상 시스템을 구현하는 코드와 며칠이나 차이가 나는지 확인하려고 시도합니다. 이상적으로는, 적극적으로 개발 중인 시스템의 경우 대부분의 상황에서 이 차이가 가까워야 합니다. 이를 주기적으로 실행하여 프로젝트의 맥박과 위협 모델의 '신선도'를 측정할 수 있습니다.
현재 사용 가능한 요소는 다음과 같습니다: TM, Element, Server, ExternalEntity, Datastore, Actor, Process, SetOfProcesses, Dataflow, Boundary, Lambda, LLM 및 Agent.
요소의 사용 가능한 속성은 --describe 뒤에 요소 이름을 붙여서 확인할 수 있습니다:```text
$ ./tm.py --describe Server
Server class attributes:
OS Operating system
default: ''
assumptions Assumptions about the element. These optionally allow to exclude threats with the given SIDs
default factory: list
controls Security controls for this element
default factory: Controls
data pytm.Data object(s) in incoming data flows
default factory: DataSet
description Description of the element
default: ''
findings Threats that apply to this element
default factory: list
handlesResources Does this asset handle resources?
default: False
inBoundary Trust boundary this element exists in
default: None
inScope Is the element in scope of the threat model
default: True
inputs incoming Dataflows
default factory: list
is_drawn default: False
levels List of levels (0, 1, 2, ...) to be drawn in the model
default factory:
maxClassification Maximum data classification this element can handle
default: <Classification.UNKNOWN: 0>
minTLSVersion Minimum TLS version required
default: <TLSVersion.NONE: 0>
name Name of the element
required
onAWS Is this asset on AWS?
default: False
outputs outgoing Dataflows
default factory: list
overrides Overrides to findings, allowing to set a custom response, CVSS score or override other attributes
default factory: list
port Default TCP port for incoming data flows
default: -1
protocol Default network protocol for incoming data flows
default: ''
severity Severity level of threats affecting this element
default: 0
sourceFiles Location of the source code that describes this element relative to the directory of the model script
default factory: list
usesCache Does this server use cache?
default: False
usesEnvironmentVariables Does this asset use environment variables?
default: False
usesSessionTokens Does this server use session tokens?
default: False
usesVPN Does this server use VPN?
default: False
usesXMLParser Does this server use XML parser?
default: False
uuid default factory:
The *colormap* argument, used together with *dfd*, outputs a color-coded DFD where the elements are painted red, yellow or green depending on their risk level (as identified by running the rules).
## 사용법 - Devbox 변형
- `devbox shell`
- `pytm` 평소처럼 사용
- `exit`
## 위협 모델 생성
다음은 사용자가 애플리케이션에 로그인하여 댓글을 게시하는 간단한 애플리케이션을 설명하는 샘플 `tm.py` 파일입니다. 앱 서버는 해당 댓글을 데이터베이스에 저장합니다. 주기적으로 데이터베이스를 정리하는 AWS Lambda가 있습니다.```python
#!/usr/bin/env python3
from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor, Lambda, LLM, Data, Classification, DatastoreType
tm = TM("my test tm")
tm.description = "another test tm"
tm.isOrdered = True
User_Web = Boundary("User/Web")
Web_DB = Boundary("Web/DB")