-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpython-injection.mdc
More file actions
178 lines (151 loc) · 8.83 KB
/
python-injection.mdc
File metadata and controls
178 lines (151 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
---
description: Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03
globs: *.py, *.ini, *.cfg, *.yml, *.yaml, *.json, *.toml
alwaysApply: false
---
# Python Injection Security Standards (OWASP A03:2021)
This rule enforces security best practices to prevent injection vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A03.
<rule>
name: python_injection
description: Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03
filters:
- type: file_extension
pattern: "\\.(py)$"
- type: file_path
pattern: ".*"
actions:
- type: enforce
conditions:
# Pattern 1: SQL Injection - String concatenation in SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*\\s*[\\+%]|cursor\\.(execute|executemany)\\([^,]+\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*"
message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string concatenation."
# Pattern 2: SQL Injection - String formatting in SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*%[^\"']*[\"']\\s*%\\s*|cursor\\.(execute|executemany)\\([\"'][^\"']*{[^\"']*}[\"']\\.format"
message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string formatting."
# Pattern 3: Command Injection - Shell command execution with user input
- pattern: "(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*format\\(|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*f['\"]"
message: "Potential command injection vulnerability. Never use string concatenation or formatting with shell commands. Use subprocess with shell=False and pass arguments as a list."
# Pattern 4: Command Injection - Shell=True in subprocess
- pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*shell\\s*=\\s*True"
message: "Using shell=True with subprocess functions is dangerous and can lead to command injection. Use shell=False (default) and pass arguments as a list."
# Pattern 5: XSS - Unescaped template variables
- pattern: "\\{\\{\\s*[^|]*\\s*\\}\\}|\\{\\%\\s*autoescape\\s+off\\s*\\%\\}"
message: "Potential XSS vulnerability. Ensure all template variables are properly escaped. Avoid using 'autoescape off' in templates."
# Pattern 6: XSS - Unsafe HTML rendering in Flask/Django
- pattern: "render_template\\([^)]*\\)|render\\([^)]*\\)|mark_safe\\([^)]*\\)|safe\\s*\\|"
message: "Potential XSS vulnerability. Ensure all user-supplied data is properly escaped before rendering in templates."
# Pattern 7: Path Traversal - Unsafe file operations
- pattern: "open\\([^)]*\\+|open\\([^)]*format\\(|open\\([^)]*f['\"]"
message: "Potential path traversal vulnerability. Validate and sanitize file paths before opening files. Consider using os.path.abspath and os.path.normpath."
# Pattern 8: LDAP Injection - Unsafe LDAP queries
- pattern: "ldap\\.search\\([^)]*\\+|ldap\\.search\\([^)]*format\\(|ldap\\.search\\([^)]*f['\"]"
message: "Potential LDAP injection vulnerability. Use proper LDAP escaping for user-supplied input in LDAP queries."
# Pattern 9: NoSQL Injection - Unsafe MongoDB queries
- pattern: "find\\(\\{[^}]*\\+|find\\(\\{[^}]*format\\(|find\\(\\{[^}]*f['\"]"
message: "Potential NoSQL injection vulnerability. Use parameterized queries or proper escaping for MongoDB queries."
# Pattern 10: Template Injection - Unsafe template rendering
- pattern: "Template\\([^)]*\\)\\.(render|substitute)\\(|eval\\([^)]*\\)|exec\\([^)]*\\)"
message: "Potential template injection or code injection vulnerability. Avoid using eval() or exec() with user input, and ensure template variables are properly validated."
- type: suggest
message: |
**Python Injection Prevention Best Practices:**
1. **SQL Injection Prevention:**
- Use parameterized queries (prepared statements) with placeholders:
```python
# Safe SQL query with parameters
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
# Django ORM (safe by default)
User.objects.filter(username=username, password=password)
# SQLAlchemy (safe by default)
session.query(User).filter(User.username == username, User.password == password)
```
- Use ORM frameworks when possible (Django ORM, SQLAlchemy)
- Apply proper input validation and sanitization
2. **Command Injection Prevention:**
- Never use shell=True with subprocess functions
- Pass command arguments as a list, not a string:
```python
# Safe command execution
subprocess.run(["ls", "-l", user_dir], shell=False)
```
- Use shlex.quote() if you must include user input in shell commands
- Consider using safer alternatives like Python libraries instead of shell commands
3. **XSS Prevention:**
- Use template auto-escaping (enabled by default in modern frameworks)
- Explicitly escape user input before rendering:
```python
# Django
from django.utils.html import escape
safe_data = escape(user_input)
# Flask/Jinja2
from markupsafe import escape
safe_data = escape(user_input)
```
- Use Content-Security-Policy headers
- Validate input against allowlists
4. **Path Traversal Prevention:**
- Validate and sanitize file paths:
```python
import os
safe_path = os.path.normpath(os.path.join(safe_base_dir, user_filename))
if not safe_path.startswith(safe_base_dir):
raise ValueError("Invalid path")
```
- Use os.path.abspath() and os.path.normpath()
- Implement proper access controls
- Consider using libraries like Werkzeug's secure_filename()
5. **NoSQL Injection Prevention:**
- Use parameterized queries or query builders
- Validate input against schemas
- Apply proper type checking
```python
# Safe MongoDB query
collection.find({"username": username, "status": "active"})
```
6. **Template Injection Prevention:**
- Avoid using eval() or exec() with user input
- Use sandboxed template engines
- Limit template functionality to what's necessary
- Apply proper input validation
- type: validate
conditions:
# Check 1: Safe SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\(|cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\[|Model\\.objects\\.filter\\(|session\\.query\\("
message: "Using parameterized queries or ORM for database access."
# Check 2: Safe command execution
- pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\(\\[[^\\]]*\\]"
message: "Using subprocess with arguments as a list (safe pattern)."
# Check 3: Proper input validation
- pattern: "validate|sanitize|clean|escape|is_valid\\(|validators\\."
message: "Implementing input validation or sanitization."
# Check 4: Safe file operations
- pattern: "os\\.path\\.join|os\\.path\\.abspath|os\\.path\\.normpath|secure_filename"
message: "Using safe file path handling techniques."
metadata:
priority: high
version: 1.0
tags:
- security
- python
- injection
- sql-injection
- xss
- command-injection
- owasp
- language:python
- framework:django
- framework:flask
- framework:fastapi
- category:security
- subcategory:injection
- standard:owasp-top10
- risk:a03-injection
references:
- "https://owasp.org/Top10/A03_2021-Injection/"
- "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"
- "https://docs.python.org/3/library/subprocess.html"
- "https://docs.djangoproject.com/en/stable/topics/security/"
- "https://flask.palletsprojects.com/en/latest/security/"
</rule>