
إطار عمل بايثوني لنمذجة التهديدات
غالبًا ما تأتي نمذجة التهديدات التقليدية متأخرة جدًا إلى الحفلة، أو أحيانًا لا تأتي أبدًا. بالإضافة إلى ذلك، يمكن أن يستغرق إنشاء تدفقات البيانات والتقارير اليدوية وقتًا طويلاً للغاية. الهدف من 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/) مثبتًا (متاح افتراضيًا على توزيعات لينكس ولكن ليس على 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.
- تثبيت Devbox على Linux/MacOS: `curl -fsSL https://get.jetify.com/devbox | bash`
- تثبيت Devbox على [Windows/WSL](https://www.jetify.com/docs/devbox/installing-devbox/index#installing-wsl2)
- التحديث إلى أحدث إصدار من devbox: `devbox version update`
- قم بتعيين رمز الوصول الخاص بـ GitHub في ملف `~/.config/nix/nix.conf`: `access-tokens = github.com=YOUR_TOKEN_HERE`
- إنشاء بيئة شل جديدة ومعزولة تتضمن جميع الأدوات والحزم المحددة في ملف `devbox.json` للمشروع: `devbox shell`
- عرض المسار الكامل للملف التنفيذي لـ Python الذي سيتم استخدامه عند كتابة `python` في الطرفية باستخدام أمر which python. يجب أن يكون الإخراج المسار التالي: `.devbox/nix/profile/default/bin/python`
- اختبر بتشغيل الأمر التالي، والذي يجب أن ينشئ DFD كملف PNG باسم `sample.png`: `./tm.py --dfd | dot -Tpng -o sample.png`
- الخروج من بيئة شل Devbox: `exit`
## الاستخدام
جميع الوسائط المتاحة:```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
وسيطة stale_days تحاول تحديد المسافة بالأيام بين البرنامج النصي للنموذج (الذي تكتبه) والكود الذي ينفذ النظام الجاري نمذجته. من الناحية المثالية، يجب أن يكونا متقاربين جدًا في معظم حالات النظام الذي يتم تطويره بنشاط. يمكنك تشغيل هذا بشكل دوري لقياس نبض مشروعك و"حداثة" نموذج التهديد الخاص بك.
العناصر المتاحة حاليًا هي: TM, Element, Server, ExternalEntity, Datastore, Actor, Process, SetOfProcesses, Dataflow, Boundary, Lambda, LLM و Agent.
يمكن سرد الخصائص المتاحة للعنصر باستخدام --describe متبوعًا باسم العنصر:```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
وسيطة *colormap*، المستخدمة مع *dfd*، تنتج مخطط تدفق البيانات (DFD) مرمز بالألوان حيث يتم طلاء العناصر باللون الأحمر أو الأصفر أو الأخضر اعتمادًا على مستوى المخاطرة (كما تم تحديده من خلال تشغيل القواعد).
## الاستخدام - متغير Devbox
- `devbox shell`
- `pytm` usage as usual
- `exit`
## إنشاء نموذج تهديد
فيما يلي ملف `tm.py` نموذجي يصف تطبيقًا بسيطًا حيث يقوم المستخدم بتسجيل الدخول إلى التطبيق ونشر التعليقات على التطبيق. يقوم خادم التطبيق بتخزين تلك التعليقات في قاعدة البيانات. هناك AWS Lambda تقوم بتنظيف قاعدة البيانات بشكل دوري.```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
)
my_lambda = Lambda("cleanDBevery6hours")
my_lambda.hasAccessControl = True
my_lambda.inBoundary = Web_DB
llm_api = LLM("AI Writing Assistant")
llm_api.isThirdParty = True
llm_api.processesPersonalData = True
llm_api.hasContentFiltering = False
llm_api.hasSystemPrompt = True
llm_api.processesUntrustedInput = True
my_lambda_to_db = Dataflow(my_lambda, db, "(λ)Periodically cleans DB")
my_lambda_to_db.protocol = "SQL"
my_lambda_to_db.dstPort = 3306
user_to_web = Dataflow(user, web, "User enters comments (*)")
user_to_web.protocol = "HTTP"
user_to_web.dstPort = 80
user_to_web.data = comments
web_to_user = Dataflow(web, user, "Comments saved (*)")
web_to_user.protocol = "HTTP"
web_to_db = Dataflow(web, db, "Insert query with comments")
web_to_db.protocol = "MySQL"
web_to_db.dstPort = 3306
db_to_web = Dataflow(db, web, "Comments contents")
db_to_web.protocol = "MySQL"
db_to_web.data = results
web_to_llm = Dataflow(web, llm_api, "Chat completion request")
web_to_llm.protocol = "HTTPS"
web_to_llm.dstPort = 443
tm.process()
لديك أيضًا خيار استخدام pytmGPT لإنشاء نماذجك من النصوص!
يتم إخراج المخططات بصيغة Dot و PlantUML.
عند تمرير الوسيط --dfd إلى ملف tm.py المذكور أعلاه، فإنه يولد مخرجات إلى stdout، والتي تغذى إلى أداة dot من Graphviz لتوليد مخطط تدفق البيانات:```bash
tm.py --dfd | dot -Tpng -o sample.png
يُنتج هذا الرسم البياني:
dfd.png
إضافة السمات ".levels = [1,2]" إلى عنصر سيؤدي إلى ظهوره (وDataflows المرتبطة به إذا كانت نهايتا التدفق في نفس مستوى DFD) أو عدم ظهوره اعتمادًا على وسيطة الأمر "--levels 1 2".
يُنتج الأمر التالي مخطط تسلسل.```bash
tm.py --seq | java -Djava.awt.headless=true -jar plantuml.jar -tpng -pipe > seq.png
يُنتج هذا الرسم البياني:
seq.png
يمكن تضمين الرسوم البيانية والنتائج في القالب لإنشاء تقرير نهائي:```bash
tm.py --report docs/basic_template.md | pandoc -f markdown -t html > report.html
تنسيق القوالب المستخدم في قالب التقرير بسيط جدًا:```text
# Threat Model Sample
***
## System Description
{tm.description}
## Dataflow Diagram

## Dataflows
Name|From|To |Data|Protocol|Port
----|----|---|----|--------|----
{dataflows:repeat:{{item.name}}|{{item.source.name}}|{{item.sink.name}}|{{item.data}}|{{item.protocol}}|{{item.dstPort}}
}
## Findings
{findings:repeat:* {{item.description}} on element "{{item.target}}"
}
لتجميع النتائج حسب العناصر، استخدم حلقة متداخلة أكثر تقدمًا:```text
{elements🔁{{item.findings:if:
{{item.findings🔁 Threat: {{{{item.id}}}} - {{{{item.description}}}}
Severity: {{{{item.severity}}}}
Mitigations: {{{{item.mitigations}}}}
References: {{{{item.references}}}}
}}}}}
يجب إفلات جميع العناصر داخل الحلقة، مع مضاعفة الأقواس، لذلك يصبح `{item.name}` `{{item.name}}`.
المثال أعلاه يستخدم حلقتين متداخلتين، لذلك يجب إفلات العناصر في الحلقة الداخلية مرتين، ولهذا يستخدمون أربعة أقواس.
### التجاوزات
يمكنك تجاوز سمات النتائج (التهديدات المطابقة لأصول النموذج و/أو تدفقات البيانات)، على سبيل المثال لتعيين درجة CVSS مخصصة و/أو نص استجابة:```python
user_to_web = Dataflow(user, web, "User enters comments (*)", protocol="HTTP", dstPort="80")
user_to_web.overrides = [
Finding(
# Overflow Buffers
threat_id="INP02",
cvss="9.3",
response="""**To Mitigate**: run a memory sanitizer to validate the binary""",
severity="Very High",
)
]
إذا كنت تضيف اكتشافًا (Finding)، فتأكد من إضافة مستوى خطورة: "Very High", "High", "Medium", "Low", "Very Low".
بالنسبة لممارس الأمن، يمكنك توفير ملف التهديدات الخاص بك عن طريق تعيين TM.threatsFile. يجب أن يحتوي على إدخالات مثل:```json
{
"SID":"INP01",
"target": ["Lambda","Process"],
"description": "Buffer Overflow via Environment Variables",
"details": "This attack pattern involves causing a buffer overflow through manipulation of environment variables. Once the attacker finds that they can modify an environment variable, they may try to overflow associated buffers. This attack leverages implicit trust often placed in environment variables.",
"Likelihood Of Attack": "High",
"severity": "High",
"condition": "target.usesEnvironmentVariables is True and target.controls.sanitizesInput is False and target.controls.checksInputBounds is False",
"prerequisites": "The application uses environment variables.An environment variable exposed to the user is vulnerable to a buffer overflow.The vulnerable environment variable uses untrusted data.Tainted data used in the environment variables is not properly validated. For instance boundary checking is not done before copying the input data to a buffer.",
"mitigations": "Do not expose environment variable to the user.Do not use untrusted data in your environment variables. Use a language or compiler that performs automatic bounds checking. There are tools such as Sharefuzz [R.10.3] which is an environment variable fuzzer for Unix that support loading a shared library. You can use Sharefuzz to determine if you are exposing an environment variable vulnerable to buffer overflow.",
"example": "Attack Example: Buffer Overflow in $HOME A buffer overflow in sccw allows local users to gain root access via the $HOME environmental variable. Attack Example: Buffer Overflow in TERM A buffer overflow in the rlogin program involves its consumption of the TERM environmental variable.",
"references": "https://capec.mitre.org/data/definitions/10.html, CVE-1999-0906, CVE-1999-0046, http://cwe.mitre.org/data/definitions/120.html, http://cwe.mitre.org/data/definitions/119.html, http://cwe.mitre.org/data/definitions/680.html"
}
حقل `target` يسرد فئات عناصر النموذج لمطابقة هذا التهديد ضدها.
يمكن أن تكون هذه أصولاً، مثل: Actor، Datastore، Server، Process، SetOfProcesses، ExternalEntity،
Lambda، LLM، Agent أو Element، وهي الفئة الأساسية وتطابق أي شيء. ويمكن أن تكون أيضاً Dataflow التي تربط أصلين.
جميع الحقول الأخرى (باستثناء `condition`) متاحة للعرض ويمكن استخدامها في القالب
لسرد النتائج في [التقرير](#report) النهائي.
> **تحذير**
>
> يحتوي ملف `threats.json` على سلاسل نصية يتم تشغيلها عبر `eval()`. تأكد من أن الملف لديه الأذونات الصحيحة
> وإلا فأنت تخاطر بأن يقوم مهاجم بتغيير السلاسل ويجعلك تشغل كوداً نيابة عنه.
المنطق موجود في `condition`، حيث يمكن تقييم أعضاء `target` منطقياً.
إرجاع قيمة true يعني أن القاعدة تولد نتيجة، وإلا فلا توجد نتيجة.
قد تقارن `condition` سمات `target` و/أو سمات التحكم الخاصة بـ `target.control` وتستدعي أيضاً إحدى هذه الطرق:
* `target.oneOf(class, ...)` حيث `class` هي واحدة أو أكثر من: Actor, Datastore, Server, Process, SetOfProcesses, ExternalEntity, Lambda, LLM, Agent أو Dataflow،
* `target.crosses(Boundary)`،
* `target.enters(Boundary)`،
* `target.exits(Boundary)`،
* `target.inside(Boundary)`.
إذا كان `target` هو Dataflow، تذكر أنه يمكنك الوصول إلى `target.source` و/أو `target.sink` بالإضافة إلى سمات أخرى.
يمكن للشروط على الأصول تحليل جميع Dataflows الواردة والصادرة عن طريق فحص
سمات `target.input` و `target.output`. على سبيل المثال، لمطابقة تهديد فقط ضد
الخوادم التي لديها حركة مرور واردة، استخدم `any(target.inputs)`. مثال أكثر تقدماً،
لمطابقة العناصر التي تتصل بمخازن بيانات SQL، سيكون `any(f.sink.oneOf(Datastore) and f.sink.isSQL for f in target.outputs)`.
## الاستيراد من JSON
باستخدام القليل من كود Python، من الممكن استيراد نموذج تهديد من JSON (لاحظ التنسيق الخاص في المثال الموجود في `tests/input.json`). المثال التالي يستورد مثال `input.json` الموجود في الاختبارات. احفظ الكود التالي باسم `tm2.py`.```python
#!/usr/bin/env python3
# Example tm2.py contents
# Run: python tm2.py --dfd | dot -Tpng -o sample_json.png
from pytm import (
TM,
Actor,
Boundary,
Classification,
Data,
Dataflow,
Datastore,
Lambda,
Server,
DatastoreType,
Assumption,
load,
)
json_file_string = './tests/input.json'
with open(json_file_string) as input_json:
TM.reset()
tm = load(input_json)
tm.process()
يمكننا استدعاء tm2.py بنفس الطريقة التي فعلناها من قبل، هنا مع --dfd ثم إعادة توجيه المخرجات إلى Graphviz (dot):```bash
python tm2.py --dfd | dot -Tpng -o sample_json.png
## صنع الشرائح!
بمجرد أن يصبح نموذج التهديد جاهزًا ومكتملاً، تأتي مرحلة العرض التقديمي المخيفة - والآن يمكن لـ pytm مساعدتك أيضًا، من خلال قالب يعبر عن نموذج التهديد الخاص بك في شرائح، باستخدام قوة (RevealMD)[https://github.com/webpro/reveal-md]! فقط استخدم القالب docs/revealjs.md وستحصل على شرائح جميلة، قابلة للتخصيص بالكامل، يمكنك تقديمها ومشاركتها من متصفحك.
https://github.com/izar/pytm/assets/368769/30218241-c7cc-4085-91e9-bbec2843f838
## التهديدات المدعومة حالياً```text
INP01 - Buffer Overflow via Environment Variables
INP02 - Overflow Buffers
INP03 - Server Side Include (SSI) Injection
CR01 - Session Sidejacking
INP04 - HTTP Request Splitting
CR02 - Cross Site Tracing
INP05 - Command Line Execution through SQL Injection
INP06 - SQL Injection through SOAP Parameter Tampering
SC01 - JSON Hijacking (aka JavaScript Hijacking)
LB01 - API Manipulation
AA01 - Authentication Abuse/ByPass
DS01 - Excavation
DE01 - Interception
DE02 - Double Encoding
API01 - Exploit Test APIs
AC01 - Privilege Abuse
INP07 - Buffer Manipulation
AC02 - Shared Data Manipulation
DO01 - Flooding
HA01 - Path Traversal
AC03 - Subverting Environment Variable Values
DO02 - Excessive Allocation
DS02 - Try All Common Switches
INP08 - Format String Injection
INP09 - LDAP Injection
INP10 - Parameter Injection
INP11 - Relative Path Traversal
INP12 - Client-side Injection-induced Buffer Overflow
AC04 - XML Schema Poisoning
DO03 - XML Ping of the Death
AC05 - Content Spoofing
INP13 - Command Delimiters
INP14 - Input Data Manipulation
DE03 - Sniffing Attacks
CR03 - Dictionary-based Password Attack
API02 - Exploit Script-Based APIs
HA02 - White Box Reverse Engineering
DS03 - Footprinting
AC06 - Using Malicious Files
HA03 - Web Application Fingerprinting
SC02 - XSS Targeting Non-Script Elements
AC07 - Exploiting Incorrectly Configured Access Control Security Levels
INP15 - IMAP/SMTP Command Injection
HA04 - Reverse Engineering
SC03 - Embedding Scripts within Scripts
INP16 - PHP Remote File Inclusion
AA02 - Principal Spoof
CR04 - Session Credential Falsification through Forging
DO04 - XML Entity Expansion
DS04 - XSS Targeting Error Pages
SC04 - XSS Using Alternate Syntax
CR05 - Encryption Brute Forcing
AC08 - Manipulate Registry Information
DS05 - Lifting Sensitive Data Embedded in Cache
SC05 - Removing Important Client Functionality
INP17 - XSS Using MIME Type Mismatch
AA03 - Exploitation of Trusted Credentials
AC09 - Functionality Misuse
INP18 - Fuzzing and observing application log data/errors for application mapping
CR06 - Communication Channel Manipulation
AC10 - Exploiting Incorrectly Configured SSL
CR07 - XML Routing Detour Attacks
AA04 - Exploiting Trust in Client
CR08 - Client-Server Protocol Manipulation
INP19 - XML External Entities Blowup
INP20 - iFrame Overlay
AC11 - Session Credential Falsification through Manipulation
INP21 - DTD Injection
INP22 - XML Attribute Blowup
INP23 - File Content Injection
DO05 - XML Nested Payloads
AC12 - Privilege Escalation
AC13 - Hijacking a privileged process
AC14 - Catching exception throw/signal from privileged block
INP24 - Filter Failure through Buffer Overflow
INP25 - Resource Injection
INP26 - Code Injection
INP27 - XSS Targeting HTML Attributes
INP28 - XSS Targeting URI Placeholders
INP29 - XSS Using Doubled Characters
INP30 - XSS Using Invalid Characters
INP31 - Command Injection
INP32 - XML Injection
INP33 - Remote Code Inclusion
INP34 - SOAP Array Overflow
INP35 - Leverage Alternate Encoding
DE04 - Audit Log Manipulation
AC15 - Schema Poisoning
INP36 - HTTP Response Smuggling
INP37 - HTTP Request Smuggling
INP38 - DOM-Based XSS
AC16 - Session Credential Falsification through Prediction
INP39 - Reflected XSS
INP40 - Stored XSS
AC17 - Session Hijacking - ServerSide
AC18 - Session Hijacking - ClientSide
INP41 - Argument Injection
AC19 - Reusing Session IDs (aka Session Replay) - ServerSide
AC20 - Reusing Session IDs (aka Session Replay) - ClientSide
AC21 - Cross Site Request Forgery
DS06 - Data Leak
DR01 - Unprotected Sensitive Data
AC22 - Credentials Aging (deprecated)
AC23 - Credentials Disclosure
AC24 - Use of hardcoded credentials
LLM01 - Direct Prompt Injection
LLM02 - Indirect Prompt Injection via Retrieved Content
LLM03 - Sensitive Data Leakage to Third-Party Provider
LLM04 - Training Data Poisoning
LLM05 - Excessive Agency via Unauthorized Tool Use
LLM06 - Arbitrary Code Execution via LLM Agent
LLM07 - Jailbreaking and Safety Bypass
LLM08 - Sensitive Information Disclosure Through Output
LLM09 - Untrusted Tool Launch Configuration