
Un framework Pythonic per la modellazione delle minacce
La modellazione delle minacce tradizionale arriva troppo spesso in ritardo, o a volte non arriva affatto. Inoltre, creare manualmente flussi di dati e report può richiedere molto tempo. L'obiettivo di pytm è spostare la modellazione delle minacce a sinistra, rendendola più automatizzata e incentrata sullo sviluppatore.
Basandosi sul tuo input e sulla definizione del progetto architetturale, pytm può generare automaticamente i seguenti elementi:
tm.py è un modello di esempio. Puoi eseguirlo per generare il report e i file immagine del diagramma a cui fa riferimento:```
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
C'è anche un esempio di `Makefile` che racchiude tutto questo in target che possono essere facilmente condivisi per più modelli. Se hai [GNU make](https://www.gnu.org/software/make/) installato (disponibile per impostazione predefinita sulle distribuzioni Linux ma non su OSX), esegui semplicemente:```
make MODEL=the_name_of_your_model_minus_.py
Dovresti avere plantuml.jar nella stessa directory del tuo modello, oppure impostare PLANTUML_PATH.
Per evitare di installare tutte le dipendenze, come pandoc o Java, lo script può essere eseguito all'interno di un container:```
export USE_DOCKER=true make image
make
### Getting Started - Devbox Variant
Per semplificare l'utilizzo di `pytm`, le dipendenze dell'host possono essere completamente isolate utilizzando [`Devbox`](https://github.com/jetify-com/devbox). Questa è solitamente un'alternativa a minor carico di lavoro e più comoda rispetto all'approccio del contenitore OCI.
- Installa Devbox su Linux/MacOS: `curl -fsSL https://get.jetify.com/devbox | bash`
- Installa Devbox su [Windows/WSL](https://www.jetify.com/docs/devbox/installing-devbox/index#installing-wsl2)
- Aggiorna all'ultima versione di devbox: `devbox version update`
- Imposta il tuo token di accesso GitHub nel file `~/.config/nix/nix.conf`: `access-tokens = github.com=YOUR_TOKEN_HERE`
- Crea un nuovo ambiente shell isolato che include tutti gli strumenti e i pacchetti specificati nel file `devbox.json` del progetto: `devbox shell`
- Mostra il percorso completo dell'eseguibile Python che verrà utilizzato quando digiti semplicemente `python` nel terminale usando il comando which python. L'output dovrebbe essere il seguente percorso: `.devbox/nix/profile/default/bin/python`
- Testa eseguendo il seguente comando, che dovrebbe generare un DFD come file PNG chiamato `sample.png`: `./tm.py --dfd | dot -Tpng -o sample.png`
- Esci dall'ambiente shell Devbox: `exit`
## Usage
Tutti gli argomenti disponibili:```text
usage: tm.py [-h] [--debug] [--dfd] [--report REPORT]
[--exclude EXCLUDE] [--seq] [--list] [--describe DESCRIBE]
[--list-elements] [--json JSON] [--levels LEVELS [LEVELS ...]]
[--stale_days STALE_DAYS]
optional arguments:
-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
L'argomento stale_days tenta di determinare quanto distanti in giorni siano lo script del modello (che stai scrivendo) dal codice che implementa il sistema modellizzato. Idealmente, dovrebbero essere abbastanza vicini nella maggior parte dei casi di un sistema attivamente sviluppato. Puoi eseguirlo periodicamente per misurare il polso del tuo progetto e la 'freschezza' del tuo modello di minaccia.
Gli elementi attualmente disponibili sono: TM, Element, Server, ExternalEntity, Datastore, Actor, Process, SetOfProcesses, Dataflow, Boundary, Lambda, LLM e Agent.
Le proprietà disponibili di un elemento possono essere elencate utilizzando --describe seguito dal nome di un elemento:```text
(pytm) ➜ pytm git:(master) ✗ ./tm.py --describe Element Element class attributes: OS definesConnectionTimeout default: False description handlesResources default: False implementsAuthenticationScheme default: False implementsNonce default: False inBoundary inScope Is the element in scope of the threat model, default: True isAdmin default: False isHardened default: False name required onAWS default: False
L'argomento *colormap*, usato insieme a *dfd*, produce un DFD codificato a colori in cui gli elementi sono dipinti in rosso, giallo o verde a seconda del loro livello di rischio (come identificato dall'esecuzione delle regole).
## Utilizzo - Variante Devbox
- `devbox shell`
- `pytm` utilizzo come di consueto
- `exit`
## Creazione di un Modello di Minaccia
Quello che segue è un esempio di file `tm.py` che descrive una semplice applicazione in cui un Utente accede all'applicazione e pubblica commenti sull'app. Il server dell'applicazione memorizza tali commenti nel database. C'è una AWS Lambda che pulisce periodicamente il Database.```python
#!/usr/bin/env python3
from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor, Lambda, LLM, Data, Classification
tm = TM("my test tm")
tm.description = "another test tm"
tm.isOrdered = True
User_Web = Boundary("User/Web")
Web_DB = Boundary("Web/DB")
user = Actor("User")
user.inBoundary = User_Web
web = Server("Web Server")
web.OS = "CloudOS"
web.isHardened = True
web.sourceCode = "server/web.cc"
db = Datastore("SQL Database (*)")
db.OS = "CentOS"
db.isHardened = False
db.inBoundary = Web_DB
db.isSql = True
db.inScope = False
db.sourceCode = "model/schema.sql"
comments = Data(
name="Comments",
description="Comments in HTML or Markdown",
classification=Classification.PUBLIC,
isPII=False,
isCredentials=False,
# credentialsLife=Lifetime.LONG,
isStored=True,
isSourceEncryptedAtRest=False,
isDestEncryptedAtRest=True
)
results = Data(
name="results",
description="Results of insert op",
classification=Classification.SENSITIVE,
isPII=False,
isCredentials=False,
# credentialsLife=Lifetime.LONG,
isStored=True,
isSourceEncryptedAtRest=False,
isDestEncryptedAtRest=True
)