codewatch-scan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. codewatch/__init__.py +0 -0
  2. codewatch/__main__.py +14 -0
  3. codewatch/asgi.py +16 -0
  4. codewatch/settings.py +175 -0
  5. codewatch/urls.py +40 -0
  6. codewatch/wsgi.py +16 -0
  7. codewatch_scan-0.1.0.dist-info/METADATA +81 -0
  8. codewatch_scan-0.1.0.dist-info/RECORD +136 -0
  9. codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
  10. codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
  11. codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
  12. codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +0 -0
  14. core/analyzers/__init__.py +19 -0
  15. core/analyzers/accessibility.py +199 -0
  16. core/analyzers/base.py +192 -0
  17. core/analyzers/body_models.py +154 -0
  18. core/analyzers/codewatch_checks.py +394 -0
  19. core/analyzers/constant_branches.py +251 -0
  20. core/analyzers/containers.py +316 -0
  21. core/analyzers/coverage.py +131 -0
  22. core/analyzers/dependencies.py +347 -0
  23. core/analyzers/drf_serializers.py +65 -0
  24. core/analyzers/else_branches.py +106 -0
  25. core/analyzers/extra.py +400 -0
  26. core/analyzers/flask_resources.py +65 -0
  27. core/analyzers/inline_scripts.py +50 -0
  28. core/analyzers/jinja_sandboxes.py +63 -0
  29. core/analyzers/match_statements.py +148 -0
  30. core/analyzers/multi_tools.py +888 -0
  31. core/analyzers/php_template_sinks.py +444 -0
  32. core/analyzers/project_checks.py +150 -0
  33. core/analyzers/python_tools.py +333 -0
  34. core/analyzers/route_converters.py +237 -0
  35. core/analyzers/slices.py +94 -0
  36. core/analyzers/starred_targets.py +42 -0
  37. core/analyzers/stored_fields.py +386 -0
  38. core/analyzers/summaries.py +1387 -0
  39. core/analyzers/template_sinks.py +162 -0
  40. core/api.py +360 -0
  41. core/apps.py +6 -0
  42. core/benchmark.py +955 -0
  43. core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
  44. core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
  45. core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
  46. core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
  47. core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
  48. core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
  49. core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
  50. core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
  51. core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
  52. core/bundled/catalog/custom/mappings.json +360 -0
  53. core/bundled/catalog/custom/overrides.json +4 -0
  54. core/bundled/catalog/custom/rules/django-settings.yml +19 -0
  55. core/bundled/catalog/imported/changes.json +5 -0
  56. core/bundled/catalog/imported/docs.json +1143 -0
  57. core/bundled/catalog/imported/meta.json +54 -0
  58. core/bundled/catalog/imported/rules.json +85421 -0
  59. core/bundled/catalog/imported/standards.json +11191 -0
  60. core/bundled/tools/analyzers.lock +786 -0
  61. core/bundled/tools/axe-scan.mjs +45 -0
  62. core/bundled/tools/checkov.lock +2463 -0
  63. core/bundled/tools/codewatch-checks.mjs +99 -0
  64. core/bundled/tools/eslint-a11y.config.js +16 -0
  65. core/bundled/tools/eslint-quality.config.js +63 -0
  66. core/bundled/tools/eslint-typed.config.js +18 -0
  67. core/bundled/tools/package-lock.json +6102 -0
  68. core/bundled/tools/package.json +32 -0
  69. core/bundled/tools/rule-metadata.mjs +56 -0
  70. core/bundled/tools/semgrep.lock +1232 -0
  71. core/bundled/tools/stylelint.config.json +11 -0
  72. core/catalog/__init__.py +190 -0
  73. core/catalog/build.py +84 -0
  74. core/catalog/merge.py +122 -0
  75. core/catalog/sources.py +418 -0
  76. core/catalog/standards.py +119 -0
  77. core/catalog/update.py +99 -0
  78. core/catalog_views.py +115 -0
  79. core/client.py +645 -0
  80. core/collect.py +518 -0
  81. core/duplicates.py +60 -0
  82. core/fingerprint.py +25 -0
  83. core/folders.py +73 -0
  84. core/gate.py +77 -0
  85. core/git.py +149 -0
  86. core/jobs.py +86 -0
  87. core/management/__init__.py +0 -0
  88. core/management/commands/__init__.py +0 -0
  89. core/management/commands/addproject.py +40 -0
  90. core/management/commands/buildcatalog.py +15 -0
  91. core/management/commands/scan.py +74 -0
  92. core/management/commands/updatecatalog.py +14 -0
  93. core/mcp_server.py +140 -0
  94. core/middleware.py +17 -0
  95. core/migrations/0001_initial.py +115 -0
  96. core/migrations/0002_auth_tokens_a11y.py +60 -0
  97. core/migrations/0003_default_admin.py +43 -0
  98. core/migrations/0004_project_members.py +28 -0
  99. core/migrations/0005_uploads_and_sources.py +55 -0
  100. core/migrations/0006_thresholds.py +28 -0
  101. core/migrations/0007_also_reported_by.py +18 -0
  102. core/migrations/0008_new_code_period.py +18 -0
  103. core/migrations/0009_resolution_safe.py +18 -0
  104. core/migrations/0010_analysis_progress.py +18 -0
  105. core/migrations/0011_overall_gate_conditions.py +20 -0
  106. core/migrations/__init__.py +0 -0
  107. core/models.py +323 -0
  108. core/network.py +41 -0
  109. core/paths.py +29 -0
  110. core/ratings.py +67 -0
  111. core/runner.py +168 -0
  112. core/templates/core/account.html +30 -0
  113. core/templates/core/analysis.html +49 -0
  114. core/templates/core/base.html +121 -0
  115. core/templates/core/form_table.html +12 -0
  116. core/templates/core/gate_badge.html +1 -0
  117. core/templates/core/index.html +26 -0
  118. core/templates/core/issues.html +38 -0
  119. core/templates/core/login.html +13 -0
  120. core/templates/core/new_project.html +27 -0
  121. core/templates/core/password_change.html +10 -0
  122. core/templates/core/project.html +40 -0
  123. core/templates/core/rating.html +1 -0
  124. core/templates/core/ratings.html +32 -0
  125. core/templates/core/rule.html +33 -0
  126. core/templates/core/rules.html +42 -0
  127. core/templates/core/scan_progress.html +2 -0
  128. core/templates/core/settings.html +36 -0
  129. core/templates/core/source.html +15 -0
  130. core/templates/core/standards.html +30 -0
  131. core/templates/core/user_edit.html +15 -0
  132. core/templates/core/users.html +18 -0
  133. core/templatetags/__init__.py +0 -0
  134. core/templatetags/codewatch.py +42 -0
  135. core/tool_setup.py +68 -0
  136. core/views.py +564 -0
@@ -0,0 +1,3382 @@
1
+ # codewatch built-in rules for Python web code (Flask, Django, FastAPI, Starlette).
2
+ # Taint rules report a vulnerability only when data from the HTTP request reaches a dangerous call, so plain use
3
+ # of an API is left to the hotspot rules. Shared pieces are YAML anchors.
4
+ rules:
5
+ - id: codewatch.python.web.command-injection
6
+ mode: taint
7
+ languages: [python]
8
+ severity: ERROR
9
+ message: >-
10
+ Data from the HTTP request reaches a shell or process command, so a user can run their own commands.
11
+ Pass arguments as a list without a shell, validate them against an allowlist, or quote with shlex.quote().
12
+ metadata: &meta-command
13
+ category: security
14
+ subcategory: [vuln]
15
+ type: vulnerability
16
+ title: Request data used in an OS command
17
+ cwe: ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"]
18
+ owasp: ["A05:2025 - Injection"]
19
+ references:
20
+ - https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html
21
+ - https://docs.python.org/3/library/subprocess.html#security-considerations
22
+ pattern-sources: &web-sources
23
+ - pattern: flask.request
24
+ # A view's request, not a local such as `request = urllib.request.Request(url)`.
25
+ - patterns:
26
+ - pattern: request
27
+ - pattern-not-inside: |
28
+ request = $MAKE(...)
29
+ ...
30
+ # Nor in a module with a function of its own by that name, which hides the framework's: codewatch's
31
+ # CLI client, `def request(url, token, data=None)`, then `status, body = request(f"{url}/api/...")`.
32
+ - pattern-not-inside: |
33
+ def request(...):
34
+ ...
35
+ ...
36
+ - pattern: starlette.requests.Request
37
+ # The request passed on to a helper under a short name: pgAdmin's file manager, add(self, req) reading
38
+ # req.form.get('currentpath') (GHSA-cr8c-972v-rmp3). Only the parts a Flask/Werkzeug request has and an
39
+ # HTTP client's response doesn't (`req = requests.get(url); req.json()` is the server's reply).
40
+ - patterns:
41
+ - pattern-either:
42
+ - pattern: req.form
43
+ - pattern: req.args
44
+ - pattern: req.values
45
+ - pattern: req.files
46
+ - pattern: req.get_json(...)
47
+ - pattern-not-inside: |
48
+ req = $MAKE(...)
49
+ ...
50
+ # Class-based views (Django, DRF, Tornado) keep the request on self, and Django's the URL captures in
51
+ # self.kwargs/self.args.
52
+ - patterns:
53
+ - pattern: self.request
54
+ - pattern-not-inside: |
55
+ self.request = $MAKE(...)
56
+ ...
57
+ - patterns:
58
+ - pattern-inside: |
59
+ class $VIEW(..., $BASE, ...):
60
+ ...
61
+ - metavariable-regex: {metavariable: $BASE, regex: '(View|ViewSet)$'}
62
+ - pattern-either:
63
+ - pattern: self.kwargs
64
+ - pattern: self.args
65
+ # A route function's parameters come from the URL path or, in FastAPI, the query string, form or headers:
66
+ # @app.route("/user/<name>") def user(name). Typed ones count only as text (str, Optional[str], list[str]);
67
+ # numbers, UUIDs, models and Depends() don't. Flask converters (<int:id>) are written on the scanned copy
68
+ # as annotations (route_converters.py). The parameter itself is the source (focus-metavariable), not each use of
69
+ # its name, so `name = secure_filename(name)` replaces it (changedetection.io GHSA-9jj8-v89v-xjvw).
70
+ - patterns:
71
+ - pattern-either:
72
+ - pattern-inside: |
73
+ @$APP.$ROUTE($PATH, ...)
74
+ def $VIEW(..., $PARAM: $TYPE, ...):
75
+ ...
76
+ - pattern-inside: |
77
+ @$APP.$ROUTE($PATH, ...)
78
+ async def $VIEW(..., $PARAM: $TYPE, ...):
79
+ ...
80
+ - metavariable-regex:
81
+ metavariable: $TYPE
82
+ regex: '^((typing\.)?(Optional|List|Annotated)\[str\b.*|(list|set)\[str\]|str( \| None)?|Any)$'
83
+ - metavariable-regex: {metavariable: $ROUTE, regex: '^(route|get|post|put|patch|delete|api_route)$'}
84
+ - metavariable-regex: {metavariable: $PATH, regex: '^[rbuf]*[''"]/'}
85
+ - focus-metavariable: $PARAM
86
+ # Frappe (ERPNext, HRMS): the request's form as frappe.form_dict, and the arguments of a @frappe.whitelist()
87
+ # method, which the client calls by name at /api/method/... with any arguments it likes. Not numeric or
88
+ # boolean ones, which Frappe converts by their annotation. Frappe CVE-2026-55823 and CVE-2026-55796 (gap notes,
89
+ # PLAN.md step 128).
90
+ - pattern: frappe.form_dict
91
+ - pattern: frappe.local.form_dict
92
+ # A script report's filters, which the report page sends (frappe.desk.query_report.run calls the module's
93
+ # execute(filters)): HRMS CVE-2026-55796. Only in a module that imports frappe.
94
+ - patterns:
95
+ - pattern-either:
96
+ - pattern-inside: |
97
+ import frappe
98
+ ...
99
+ def execute($FILTERS=None):
100
+ ...
101
+ - pattern-inside: |
102
+ import frappe
103
+ ...
104
+ def execute($FILTERS):
105
+ ...
106
+ - metavariable-regex: {metavariable: $FILTERS, regex: '^filters$'}
107
+ - focus-metavariable: $FILTERS
108
+ - patterns:
109
+ - pattern-either:
110
+ - pattern-inside: |
111
+ @frappe.whitelist(...)
112
+ def $METHOD(..., $PARAM, ...):
113
+ ...
114
+ - pattern-inside: |
115
+ @frappe.whitelist
116
+ def $METHOD(..., $PARAM, ...):
117
+ ...
118
+ - pattern-not-inside: |
119
+ def $METHOD(..., $PARAM: int, ...):
120
+ ...
121
+ - pattern-not-inside: |
122
+ def $METHOD(..., $PARAM: int = $DEFAULT, ...):
123
+ ...
124
+ - pattern-not-inside: |
125
+ def $METHOD(..., $PARAM: float, ...):
126
+ ...
127
+ - pattern-not-inside: |
128
+ def $METHOD(..., $PARAM: float = $DEFAULT, ...):
129
+ ...
130
+ - pattern-not-inside: |
131
+ def $METHOD(..., $PARAM: bool, ...):
132
+ ...
133
+ - pattern-not-inside: |
134
+ def $METHOD(..., $PARAM: bool = $DEFAULT, ...):
135
+ ...
136
+ - focus-metavariable: $PARAM
137
+ # An MCP server's tool arguments (FastMCP, mcp.server.fastmcp: @mcp.tool / @mcp.tool()): the model chooses
138
+ # them, and whatever text it reads can steer it, so they're as untrusted as a request's. Text-typed only, as
139
+ # for routes. Vibe-Trading GHSA-mjrq-xg2m-qg94 (a run id joined into a path).
140
+ - patterns:
141
+ - pattern-either:
142
+ - pattern-inside: |
143
+ @$MCP.tool
144
+ def $TOOL(..., $PARAM: $TYPE, ...):
145
+ ...
146
+ - pattern-inside: |
147
+ @$MCP.tool
148
+ async def $TOOL(..., $PARAM: $TYPE, ...):
149
+ ...
150
+ - pattern-inside: |
151
+ @$MCP.tool(...)
152
+ def $TOOL(..., $PARAM: $TYPE, ...):
153
+ ...
154
+ - pattern-inside: |
155
+ @$MCP.tool(...)
156
+ async def $TOOL(..., $PARAM: $TYPE, ...):
157
+ ...
158
+ - pattern-inside: |
159
+ @$MCP.tool
160
+ def $TOOL(..., $PARAM: $TYPE = $DEFAULT, ...):
161
+ ...
162
+ - pattern-inside: |
163
+ @$MCP.tool
164
+ async def $TOOL(..., $PARAM: $TYPE = $DEFAULT, ...):
165
+ ...
166
+ - pattern-inside: |
167
+ @$MCP.tool(...)
168
+ def $TOOL(..., $PARAM: $TYPE = $DEFAULT, ...):
169
+ ...
170
+ - pattern-inside: |
171
+ @$MCP.tool(...)
172
+ async def $TOOL(..., $PARAM: $TYPE = $DEFAULT, ...):
173
+ ...
174
+ - metavariable-regex:
175
+ metavariable: $TYPE
176
+ regex: '^((typing\.)?(Optional|List|Annotated)\[str\b.*|(list|set)\[str\]|str( \| None)?|Any)$'
177
+ - focus-metavariable: $PARAM
178
+ # An agent tool class's arguments, which the model fills in from a JSON schema, as for MCP tools above: the
179
+ # method an agent framework calls (LangChain/CrewAI `_run`, smolagents `forward`, a project's own
180
+ # `execute(self, **kwargs)`) in a class based on a *Tool class that describes itself to the model
181
+ # (`description`, `args_schema` or a `parameters` schema). Vibe-Trading GHSA-3j25 (RememberTool.execute's
182
+ # memory_type joined into a file path). Not numeric-typed parameters.
183
+ - patterns:
184
+ - pattern-inside: |
185
+ class $CLS(..., $BASE, ...):
186
+ ...
187
+ - pattern-either:
188
+ - pattern-inside: |
189
+ class $CLS(...):
190
+ ...
191
+ $DESC = ...
192
+ ...
193
+ - pattern-inside: |
194
+ class $CLS(...):
195
+ ...
196
+ $DESC: $DTYPE = ...
197
+ ...
198
+ - metavariable-regex: {metavariable: $BASE, regex: '^(\w+\.)*\w*Tool$'}
199
+ - metavariable-regex: {metavariable: $DESC, regex: '^(description|args_schema|parameters)$'}
200
+ - pattern-either:
201
+ - patterns:
202
+ - pattern-inside: |
203
+ def $RUN(self, ..., **$KW):
204
+ ...
205
+ - pattern: $KW
206
+ - patterns:
207
+ - pattern-either:
208
+ - pattern-inside: |
209
+ def $RUN(self, ..., $PARAM, ...):
210
+ ...
211
+ - pattern-inside: |
212
+ async def $RUN(self, ..., $PARAM, ...):
213
+ ...
214
+ - pattern-not-inside: |
215
+ def $RUN(..., $PARAM: int, ...):
216
+ ...
217
+ - pattern-not-inside: |
218
+ def $RUN(..., $PARAM: int = $DEFAULT, ...):
219
+ ...
220
+ - pattern-not-inside: |
221
+ def $RUN(..., $PARAM: float, ...):
222
+ ...
223
+ - pattern-not-inside: |
224
+ def $RUN(..., $PARAM: float = $DEFAULT, ...):
225
+ ...
226
+ - pattern-not-inside: |
227
+ def $RUN(..., $PARAM: bool, ...):
228
+ ...
229
+ - pattern-not-inside: |
230
+ def $RUN(..., $PARAM: bool = $DEFAULT, ...):
231
+ ...
232
+ - focus-metavariable: $PARAM
233
+ - metavariable-regex: {metavariable: $RUN, regex: '^(execute|run|_run|_arun|arun|forward|invoke|ainvoke|__call__)$'}
234
+ # Django REST framework serializers: the request body after DRF's field checks, as `validated_data` in
235
+ # create()/update(), `attrs` in validate(), a field's value in validate_<field>(), and .validated_data or
236
+ # .initial_data on a serializer (firefighter GHSA-fqvv: create(self, validated_data) passes
237
+ # validated_data["attachments"] to the Jira client, which fetches each URL). A field with its own
238
+ # validate_<field> method is cleared by the project's serializer checks (drf_serializers.py).
239
+ - patterns:
240
+ - pattern-inside: |
241
+ class $SER(..., $SBASE, ...):
242
+ ...
243
+ - metavariable-regex: {metavariable: $SBASE, regex: '^(\w+\.)*\w*Serializer(\[.*\])?$'}
244
+ - pattern-either:
245
+ - pattern-inside: |
246
+ def create(self, $PARAM, ...):
247
+ ...
248
+ - pattern-inside: |
249
+ def update(self, $INSTANCE, $PARAM, ...):
250
+ ...
251
+ - pattern-inside: |
252
+ def validate(self, $PARAM, ...):
253
+ ...
254
+ - patterns:
255
+ - pattern-inside: |
256
+ def $FIELD_CHECK(self, $PARAM, ...):
257
+ ...
258
+ - metavariable-regex: {metavariable: $FIELD_CHECK, regex: '^validate_\w+$'}
259
+ - focus-metavariable: $PARAM
260
+ - pattern: $SERIALIZER.validated_data
261
+ - pattern: $SERIALIZER.initial_data
262
+ # A FastAPI route's uploaded files: the name the client sent (file: UploadFile, files: List[UploadFile]),
263
+ # not the file object, whose contents aren't a path or markup. libre-chat GHSA-3864-rp2m-2qfj, LightRAG
264
+ # GHSA-v9w6-9hq9-33ch (both: open(os.path.join(folder, file.filename), "wb")).
265
+ - patterns:
266
+ - pattern-either:
267
+ - pattern-inside: |
268
+ @$APP.$ROUTE($PATH, ...)
269
+ def $VIEW(..., $PARAM: $TYPE, ...):
270
+ ...
271
+ - pattern-inside: |
272
+ @$APP.$ROUTE($PATH, ...)
273
+ async def $VIEW(..., $PARAM: $TYPE, ...):
274
+ ...
275
+ - pattern-inside: |
276
+ @$APP.$ROUTE($PATH, ...)
277
+ def $VIEW(..., $PARAM: $TYPE = $DEFAULT, ...):
278
+ ...
279
+ - pattern-inside: |
280
+ @$APP.$ROUTE($PATH, ...)
281
+ async def $VIEW(..., $PARAM: $TYPE = $DEFAULT, ...):
282
+ ...
283
+ - metavariable-regex:
284
+ metavariable: $TYPE
285
+ regex: '^((typing\.)?(Optional|List)\[|(list|set)\[)?(fastapi\.)?UploadFile\]?( \| None)?$'
286
+ - metavariable-regex: {metavariable: $ROUTE, regex: '^(route|get|post|put|patch|delete|api_route)$'}
287
+ - metavariable-regex: {metavariable: $PATH, regex: '^[rbuf]*[''"]/'}
288
+ - pattern-either:
289
+ - pattern: $PARAM.filename
290
+ - patterns:
291
+ - pattern-inside: |
292
+ for $F in $PARAM:
293
+ ...
294
+ - pattern: $F.filename
295
+ - patterns:
296
+ - pattern-either:
297
+ - pattern-inside: |
298
+ @$APP.$ROUTE($PATH, ...)
299
+ def $VIEW(..., $PARAM, ...):
300
+ ...
301
+ - pattern-inside: |
302
+ @$APP.$ROUTE($PATH, ...)
303
+ async def $VIEW(..., $PARAM, ...):
304
+ ...
305
+ - pattern-not-inside: |
306
+ def $VIEW(..., $PARAM: $TYPE, ...):
307
+ ...
308
+ - pattern-not-inside: |
309
+ async def $VIEW(..., $PARAM: $TYPE, ...):
310
+ ...
311
+ - pattern-not-inside: |
312
+ def $VIEW(..., $PARAM=Depends(...), ...):
313
+ ...
314
+ - pattern-not-inside: |
315
+ def $VIEW(..., $PARAM=fastapi.Depends(...), ...):
316
+ ...
317
+ - pattern-not-inside: |
318
+ def $VIEW(..., $PARAM=Security(...), ...):
319
+ ...
320
+ - pattern-not-inside: |
321
+ async def $VIEW(..., $PARAM=Depends(...), ...):
322
+ ...
323
+ - pattern-not-inside: |
324
+ async def $VIEW(..., $PARAM=fastapi.Depends(...), ...):
325
+ ...
326
+ - pattern-not-inside: |
327
+ async def $VIEW(..., $PARAM=Security(...), ...):
328
+ ...
329
+ - metavariable-regex: {metavariable: $PARAM, regex: '^(?!(self|cls)$)\w+$'}
330
+ - metavariable-regex: {metavariable: $ROUTE, regex: '^(route|get|post|put|patch|delete|api_route)$'}
331
+ - metavariable-regex: {metavariable: $PATH, regex: '^[rbuf]*[''"]/'}
332
+ - focus-metavariable: $PARAM
333
+ # Flask-AppBuilder and Flask-Admin views (Airflow 1.x, Superset): @expose("/variables/<form>") on a view
334
+ # class's method routes like @app.route, and its arguments come from the URL path. Converters other than
335
+ # string and path are typed on the scanned copy (route_converters.py) and skipped like any typed argument.
336
+ # Airflow GHSA-rv25-9wgj-xg75.
337
+ - patterns:
338
+ - pattern-either:
339
+ - pattern-inside: |
340
+ @expose($PATH, ...)
341
+ def $VIEW(self, ..., $PARAM, ...):
342
+ ...
343
+ - pattern-inside: |
344
+ @$MODULE.expose($PATH, ...)
345
+ def $VIEW(self, ..., $PARAM, ...):
346
+ ...
347
+ - pattern-not-inside: |
348
+ def $VIEW(..., $PARAM: $TYPE, ...):
349
+ ...
350
+ - metavariable-regex: {metavariable: $PARAM, regex: '^(?!(self|cls)$)\w+$'}
351
+ - metavariable-regex: {metavariable: $PATH, regex: '^[rbuf]*[''"]/'}
352
+ - focus-metavariable: $PARAM
353
+ # A Django function view's arguments from its urls.py route, where the converter or regex group passes free
354
+ # text (path("files/<path:name>", serve)); marked on the scanned copy by route_converters.py. CodeRed CMS
355
+ # GHSA-h454-rq3m-89rc.
356
+ - patterns:
357
+ - pattern-either:
358
+ - pattern-inside: |
359
+ def $VIEW($REQUEST, ..., $PARAM: codewatch_url_text, ...):
360
+ ...
361
+ - pattern-inside: |
362
+ async def $VIEW($REQUEST, ..., $PARAM: codewatch_url_text, ...):
363
+ ...
364
+ - focus-metavariable: $PARAM
365
+ pattern-propagators: &propagators
366
+ - {pattern: '$TO.append($FROM)', from: $FROM, to: $TO}
367
+ - {pattern: '$TO.extend($FROM)', from: $FROM, to: $TO}
368
+ - {pattern: '$TO.insert($I, $FROM)', from: $FROM, to: $TO}
369
+ - {pattern: '$TO.add($FROM)', from: $FROM, to: $TO}
370
+ - {pattern: '$TO.update($FROM)', from: $FROM, to: $TO}
371
+ - {pattern: '$TO.set($SECTION, $KEY, $FROM)', from: $FROM, to: $TO}
372
+ - {pattern: '$TO.put($FROM)', from: $FROM, to: $TO}
373
+ - {pattern: '$TO.write($FROM)', from: $FROM, to: $TO}
374
+ # Shared: data counts as validated after an `if` that checks its content and returns or raises.
375
+ pattern-sanitizers:
376
+ - &validated-guard
377
+ pattern-either:
378
+ # A validator that raises, called on its own before the value is used: check_lfi_path(image_url)
379
+ # (LLaMA Factory), validate_path_is_safe(path) (MLflow). Named for what it checks, so an authorization
380
+ # call (check_permission(user, name)) doesn't clear the name.
381
+ - patterns:
382
+ - pattern-inside: |
383
+ $CHECK(..., $X, ...)
384
+ ...
385
+ - pattern-not-inside: $CHECK(..., $X, ...)
386
+ - metavariable-regex:
387
+ metavariable: $CHECK
388
+ regex: '(?i)^(.*\.)?_?(check|validate|verify|ensure|assert)_?\w{0,30}(path|url|uri|file|filename|safe|ssrf|lfi|traversal|redirect|host)\w{0,30}$'
389
+ - pattern: $X
390
+ # A named check that said no ends the request: `if not is_safe_url(nxt): return redirect("/")`, or
391
+ # `if not url_has_allowed_host_and_scheme(nxt, ...): abort(400)`. The yes-branch form is checked-inside.
392
+ - patterns:
393
+ - pattern-either:
394
+ - pattern-inside: |
395
+ if not $CHECK(..., $X, ...):
396
+ ...
397
+ return ...
398
+ ...
399
+ - pattern-inside: |
400
+ if not $CHECK(..., $X, ...):
401
+ ...
402
+ raise ...
403
+ ...
404
+ - pattern-inside: |
405
+ if not $CHECK(..., $X, ...):
406
+ ...
407
+ flask.abort(...)
408
+ ...
409
+ - pattern-inside: |
410
+ if not $CHECK(..., $X, ...):
411
+ ...
412
+ abort(...)
413
+ ...
414
+ - pattern-inside: |
415
+ if not $CHECK(..., url=$X, ...):
416
+ ...
417
+ return ...
418
+ ...
419
+ - pattern-inside: |
420
+ if not $CHECK(..., url=$X, ...):
421
+ ...
422
+ raise ...
423
+ ...
424
+ - pattern-inside: |
425
+ if not $CHECK(..., url=$X, ...):
426
+ ...
427
+ flask.abort(...)
428
+ ...
429
+ - pattern-inside: |
430
+ if not $CHECK(..., url=$X, ...):
431
+ ...
432
+ abort(...)
433
+ ...
434
+ # Not in the branch where the check said no: `if not is_safe_url(nxt): return redirect(nxt)`.
435
+ - pattern-not-inside: |
436
+ if not $CHECK(..., $X, ...):
437
+ ...
438
+ - pattern-not-inside: |
439
+ if not $CHECK(..., url=$X, ...):
440
+ ...
441
+ - metavariable-regex:
442
+ metavariable: $CHECK
443
+ regex: '(?i)^(.*\.)?(is_?|check_?)?(safe|valid|allowed|permitted|trusted|whitelisted|allowlisted)\w{0,40}$|^(.*\.)?url_has_allowed_host_and_scheme$'
444
+ - pattern: $X
445
+ - patterns:
446
+ - pattern-either:
447
+ - pattern-inside: |
448
+ if <... $X.endswith(...) ...>:
449
+ ...
450
+ return ...
451
+ ...
452
+ - pattern-inside: |
453
+ if <... $X.endswith(...) ...>:
454
+ ...
455
+ raise ...
456
+ ...
457
+ - pattern-inside: |
458
+ if <... $X.isalnum() ...>:
459
+ ...
460
+ return ...
461
+ ...
462
+ - pattern-inside: |
463
+ if <... $X.isalnum() ...>:
464
+ ...
465
+ raise ...
466
+ ...
467
+ - pattern-inside: |
468
+ if <... $X.isdigit() ...>:
469
+ ...
470
+ return ...
471
+ ...
472
+ - pattern-inside: |
473
+ if <... $X.isdigit() ...>:
474
+ ...
475
+ raise ...
476
+ ...
477
+ - pattern-inside: |
478
+ if <... $X.isidentifier() ...>:
479
+ ...
480
+ return ...
481
+ ...
482
+ - pattern-inside: |
483
+ if <... $X.isidentifier() ...>:
484
+ ...
485
+ raise ...
486
+ ...
487
+ - pattern-inside: |
488
+ if <... re.match(..., $X, ...) ...>:
489
+ ...
490
+ return ...
491
+ ...
492
+ - pattern-inside: |
493
+ if <... re.match(..., $X, ...) ...>:
494
+ ...
495
+ raise ...
496
+ ...
497
+ - pattern-inside: |
498
+ if <... re.fullmatch(..., $X, ...) ...>:
499
+ ...
500
+ return ...
501
+ ...
502
+ - pattern-inside: |
503
+ if <... re.fullmatch(..., $X, ...) ...>:
504
+ ...
505
+ raise ...
506
+ ...
507
+ # Only a failed membership check ends the request: `if not x in ALLOWED: return`. After
508
+ # `if x in ALLOWED: return render(x)` the code below runs for the values that aren't allowed.
509
+ - pattern-inside: |
510
+ if <... not $X in $ALLOWED ...>:
511
+ ...
512
+ return ...
513
+ ...
514
+ - pattern-inside: |
515
+ if <... not $X in $ALLOWED ...>:
516
+ ...
517
+ raise ...
518
+ ...
519
+ - pattern-inside: |
520
+ if <... $X not in $ALLOWED ...>:
521
+ ...
522
+ return ...
523
+ ...
524
+ - pattern-inside: |
525
+ if <... $X not in $ALLOWED ...>:
526
+ ...
527
+ raise ...
528
+ ...
529
+ - pattern-inside: |
530
+ if <... url_has_allowed_host_and_scheme($X, ...) ...>:
531
+ ...
532
+ return ...
533
+ ...
534
+ - pattern-inside: |
535
+ if <... url_has_allowed_host_and_scheme(..., url=$X, ...) ...>:
536
+ ...
537
+ return ...
538
+ ...
539
+ - pattern-inside: |
540
+ if <... url_has_allowed_host_and_scheme($X, ...) ...>:
541
+ ...
542
+ raise ...
543
+ ...
544
+ - pattern-inside: |
545
+ if <... url_has_allowed_host_and_scheme(..., url=$X, ...) ...>:
546
+ ...
547
+ raise ...
548
+ ...
549
+ - pattern-inside: |
550
+ $URL = urllib.parse.urlparse($X)
551
+ ...
552
+ if <... $URL.$PART ...>:
553
+ ...
554
+ return ...
555
+ ...
556
+ - pattern-inside: |
557
+ $URL = urllib.parse.urlparse($X)
558
+ ...
559
+ if <... $URL.$PART ...>:
560
+ ...
561
+ raise ...
562
+ ...
563
+ - pattern-inside: |
564
+ try:
565
+ ...
566
+ $URL = urllib.parse.urlparse($X)
567
+ ...
568
+ if <... $URL.$PART ...>:
569
+ ...
570
+ return ...
571
+ ...
572
+ except $EXC:
573
+ ...
574
+ ...
575
+ - pattern-inside: |
576
+ try:
577
+ ...
578
+ $URL = urllib.parse.urlparse($X)
579
+ ...
580
+ if <... $URL.$PART ...>:
581
+ ...
582
+ return ...
583
+ ...
584
+ except:
585
+ ...
586
+ ...
587
+ # A compiled pattern, as re.match above: `subdomain_regex = re.compile("^[a-zA-Z-]+$")` then
588
+ # `if not subdomain_regex.match(subdomain): return Response(...)` (PostHog GHSA-jrwm at its fix).
589
+ # Only receivers named as a pattern, so a router's or a model's own .match() isn't one.
590
+ - patterns:
591
+ - pattern-either:
592
+ - pattern-inside: |
593
+ if <... $RE.$MATCH($X, ...) ...>:
594
+ ...
595
+ return ...
596
+ ...
597
+ - pattern-inside: |
598
+ if <... $RE.$MATCH($X, ...) ...>:
599
+ ...
600
+ raise ...
601
+ ...
602
+ - metavariable-regex: {metavariable: $MATCH, regex: ^(match|fullmatch)$}
603
+ - metavariable-regex: {metavariable: $RE, regex: '(?i)^(.*[._])?(re|rx|regex|regexp|pattern)$'}
604
+ # A normalised path checked against its base and a separator (pyLoad GHSA-48rp at its fix):
605
+ # if not os.path.abspath(p).startswith(os.path.abspath(base) + os.sep): return. Not without the
606
+ # separator: /srv/files_evil starts with /srv/files (xiaomusic's advisory).
607
+ - pattern-inside: |
608
+ if <... os.path.abspath($X).startswith($BASE + os.sep) ...>:
609
+ ...
610
+ return ...
611
+ ...
612
+ - pattern-inside: |
613
+ if <... os.path.abspath($X).startswith($BASE + os.sep) ...>:
614
+ ...
615
+ raise ...
616
+ ...
617
+ - pattern-inside: |
618
+ if <... os.path.abspath($X).startswith($BASE + "/") ...>:
619
+ ...
620
+ return ...
621
+ ...
622
+ - pattern-inside: |
623
+ if <... os.path.abspath($X).startswith($BASE + "/") ...>:
624
+ ...
625
+ raise ...
626
+ ...
627
+ - pattern-inside: |
628
+ if <... os.path.realpath($X).startswith($BASE + os.sep) ...>:
629
+ ...
630
+ return ...
631
+ ...
632
+ - pattern-inside: |
633
+ if <... os.path.realpath($X).startswith($BASE + os.sep) ...>:
634
+ ...
635
+ raise ...
636
+ ...
637
+ - pattern-inside: |
638
+ if <... os.path.realpath($X).startswith($BASE + "/") ...>:
639
+ ...
640
+ return ...
641
+ ...
642
+ - pattern-inside: |
643
+ if <... os.path.realpath($X).startswith($BASE + "/") ...>:
644
+ ...
645
+ raise ...
646
+ ...
647
+ - pattern-inside: |
648
+ if <... os.path.normpath($X).startswith($BASE + os.sep) ...>:
649
+ ...
650
+ return ...
651
+ ...
652
+ - pattern-inside: |
653
+ if <... os.path.normpath($X).startswith($BASE + os.sep) ...>:
654
+ ...
655
+ raise ...
656
+ ...
657
+ - pattern-inside: |
658
+ if <... os.path.normpath($X).startswith($BASE + "/") ...>:
659
+ ...
660
+ return ...
661
+ ...
662
+ - pattern-inside: |
663
+ if <... os.path.normpath($X).startswith($BASE + "/") ...>:
664
+ ...
665
+ raise ...
666
+ ...
667
+ # A resolved path checked against its base directory: if not str(p).startswith(str(base)): return
668
+ - pattern-inside: |
669
+ if <... str($X).startswith(...) ...>:
670
+ ...
671
+ return ...
672
+ ...
673
+ - pattern-inside: |
674
+ if <... str($X).startswith(...) ...>:
675
+ ...
676
+ raise ...
677
+ ...
678
+ - pattern-inside: |
679
+ if <... $X.is_relative_to(...) ...>:
680
+ ...
681
+ return ...
682
+ ...
683
+ - pattern-inside: |
684
+ if <... $X.is_relative_to(...) ...>:
685
+ ...
686
+ raise ...
687
+ ...
688
+ # A normalised path compared with its base by commonpath: `if os.path.commonpath([p, base]) != base:
689
+ # raise` (SQLBot GHSA-fghj-qqgj-7rxf's fix).
690
+ - pattern-inside: |
691
+ if <... os.path.commonpath(<... $X ...>) ...>:
692
+ ...
693
+ raise ...
694
+ ...
695
+ - pattern-inside: |
696
+ if <... os.path.commonpath(<... $X ...>) ...>:
697
+ ...
698
+ return ...
699
+ ...
700
+ # The same check as a relative_to() that raises, on a normalised path: pgAdmin GHSA-cr8c-972v-rmp3's
701
+ # fix, `try: Path(os.path.abspath(os.path.join(base, name))).relative_to(base) except ValueError:
702
+ # return`. Not the lexical one it replaced (Path(name).relative_to(base) lets "a/../../x" through).
703
+ - pattern-inside: |
704
+ try:
705
+ ...
706
+ pathlib.Path(<... os.path.abspath(<... $X ...>) ...>).relative_to(...)
707
+ ...
708
+ except ValueError:
709
+ ...
710
+ return ...
711
+ ...
712
+ - pattern-inside: |
713
+ try:
714
+ ...
715
+ pathlib.Path(<... os.path.realpath(<... $X ...>) ...>).relative_to(...)
716
+ ...
717
+ except ValueError:
718
+ ...
719
+ return ...
720
+ ...
721
+ - pattern-inside: |
722
+ try:
723
+ ...
724
+ pathlib.Path(..., <... $X ...>, ...).resolve().relative_to(...)
725
+ ...
726
+ except ValueError:
727
+ ...
728
+ return ...
729
+ ...
730
+ # A failed check that replaces the value: if urlsplit(next).netloc != "": next = url_for("index")
731
+ - pattern-inside: |
732
+ if <... urllib.parse.urlsplit($X).$PART ...>:
733
+ ...
734
+ $X = $SAFE
735
+ ...
736
+ - pattern-inside: |
737
+ if <... urllib.parse.urlparse($X).$PART ...>:
738
+ ...
739
+ $X = $SAFE
740
+ ...
741
+ # ...or Django's old same-origin test said no and replaced it: `if redirect_to and not
742
+ # same_origin(request.build_absolute_uri(redirect_to), request.build_absolute_uri()): redirect_to =
743
+ # None` (Horizon GHSA-j72v-mpwp-rg79's fix, PLAN.md step 128). An `and` that skips it only skips
744
+ # an empty value.
745
+ - pattern-inside: |
746
+ if <... not django.utils.http.same_origin(<... $X ...>, ...) ...>:
747
+ ...
748
+ $X = $SAFE
749
+ ...
750
+ # ...or a named check that said no replaces it: `if nxt is None or not _is_safe_redirect_url(nxt):
751
+ # nxt = url_for("index")` (pgAdmin GHSA-7r93-vp6c-cw5m's fix). Not when an `and` can skip the check.
752
+ - patterns:
753
+ - pattern-inside: |
754
+ if <... not $CHECK(..., $X, ...) ...>:
755
+ ...
756
+ $X = $SAFE
757
+ ...
758
+ - pattern-not-inside: |
759
+ if $A and <... not $CHECK(..., $X, ...) ...>:
760
+ ...
761
+ ...
762
+ - pattern-not-inside: |
763
+ if <... not $CHECK(..., $X, ...) ...> and $B:
764
+ ...
765
+ ...
766
+ - pattern-not-inside: |
767
+ if <... not $CHECK(..., $X, ...) ...>:
768
+ ...
769
+ - metavariable-regex:
770
+ metavariable: $CHECK
771
+ regex: '(?i)^(.*\.)?_?(is_?|check_?)?(safe|valid|allowed|permitted|trusted|whitelisted|allowlisted)\w{0,40}$'
772
+ # ...or used only inside the branch where an allowlist check passed.
773
+ - pattern-inside: |
774
+ if <... url_has_allowed_host_and_scheme($X, ...) ...>:
775
+ ...
776
+ - pattern-inside: |
777
+ if <... url_has_allowed_host_and_scheme(..., url=$X, ...) ...>:
778
+ ...
779
+ # A forbidden-character check that bails out: if "'" in name: return ... Only for a few punctuation
780
+ # characters or a control escape: `if 'http' in q: return redirect(q)` routes the value, it doesn't
781
+ # check it (Whoogle GHSA-mxvc: the else branch put q in an error page printed |safe).
782
+ - patterns:
783
+ - pattern-either:
784
+ - pattern-inside: |
785
+ if <... $CHAR in $X ...>:
786
+ ...
787
+ return ...
788
+ ...
789
+ - pattern-inside: |
790
+ if <... $CHAR in $X ...>:
791
+ ...
792
+ raise ...
793
+ ...
794
+ - metavariable-regex:
795
+ metavariable: $CHAR
796
+ regex: '^[rbu]*(''|")([^A-Za-z0-9\s]{1,3}|\\[nrt0]|\\x00)\1$'
797
+ - pattern-inside: |
798
+ if <... $X in $ALLOWED ...>:
799
+ ...
800
+ - pattern: $X
801
+ # Not in the branch where a membership check said no, which `$X in $ALLOWED` above also matches:
802
+ # `if preset_id not in PRESETS: return HTMLResponse(f"Unknown preset: {preset_id}")`
803
+ # (nextcloud-mcp-server's gap note, PLAN.md step 128).
804
+ - pattern-not-inside: |
805
+ if <... $X not in $ALLOWED ...>:
806
+ ...
807
+ - pattern-not-inside: |
808
+ if <... not $X in $ALLOWED ...>:
809
+ ...
810
+ # Nor under an `or`, which lets a value that isn't in the list through on the other test: `if path in
811
+ # pwa_assets or path.startswith('workbox-'): return send_file(...)` (Bazarr, PLAN.md step 156).
812
+ - pattern-not-inside: |
813
+ if $X in $ALLOWED or $OTHER:
814
+ ...
815
+ - pattern-not-inside: |
816
+ if $OTHER or $X in $ALLOWED:
817
+ ...
818
+ # Never the request's own mappings: `if not ("hitId" in request.args): raise` checks that a key is
819
+ # there and says nothing about the values (psiturk GHSA-9mq4-9556-6qxq lost every finding below it).
820
+ - metavariable-regex:
821
+ metavariable: $X
822
+ regex: '^(?!((flask\.)?request|self\.request|req)\.(args|form|values|GET|POST|files|FILES|cookies|COOKIES|headers|META|data|query_params|json)$)'
823
+ - patterns:
824
+ - pattern-either:
825
+ # A value that must equal a known one, or the request ends: if path != s.mac + ".png": abort(404)
826
+ # (CTFd share.py). Only a plain comparison: `if x != y and z: return` lets x through when z is false.
827
+ - pattern-inside: |
828
+ if $X != $EXPECTED:
829
+ ...
830
+ return ...
831
+ ...
832
+ - pattern-inside: |
833
+ if $X != $EXPECTED:
834
+ ...
835
+ raise ...
836
+ ...
837
+ - pattern-inside: |
838
+ if $X != $EXPECTED:
839
+ ...
840
+ abort(...)
841
+ ...
842
+ - pattern-inside: |
843
+ if $X != $EXPECTED:
844
+ ...
845
+ flask.abort(...)
846
+ ...
847
+ - pattern: $X
848
+ # Not in the branch where it didn't match: `if name != "index.html": return f"No page {name}"`.
849
+ - pattern-not-inside: |
850
+ if $X != $EXPECTED:
851
+ ...
852
+ # Known to the server: not a bare variable or anything from the request (vulpy:
853
+ # `if password != password_again: return` compares two request values).
854
+ - metavariable-regex:
855
+ metavariable: $EXPECTED
856
+ regex: '^(?![a-z_][a-z0-9_]*$)(?!.*\b(request|req|form|args|params|data|query|body|json|POST|GET)\b)'
857
+ # A prefix test that ends the request: `if not page.startswith("/"): return`. Every rule but path traversal,
858
+ # which takes it only on a resolved path: `path.startswith('workbox-')` doesn't stop `workbox-../../x`
859
+ # (Bazarr CVE-2026-137585, PLAN.md step 156).
860
+ - &prefix-guard
861
+ patterns:
862
+ - pattern-either:
863
+ - pattern-inside: |
864
+ if <... $X.startswith(...) ...>:
865
+ ...
866
+ return ...
867
+ ...
868
+ - pattern-inside: |
869
+ if <... $X.startswith(...) ...>:
870
+ ...
871
+ raise ...
872
+ ...
873
+ - pattern: $X
874
+ # Used only where a check said yes: `if is_safe_url(x): return redirect(x)` (GHSA-6rmf-cv6p-4h27).
875
+ - &checked-inside
876
+ patterns:
877
+ - pattern-either:
878
+ - pattern-inside: |
879
+ if $CHECK(..., $X, ...):
880
+ ...
881
+ - pattern-inside: |
882
+ if $CHECK(..., $X, ...) and $MORE:
883
+ ...
884
+ - pattern-inside: |
885
+ if $FIRST and $CHECK(..., $X, ...):
886
+ ...
887
+ - metavariable-regex:
888
+ metavariable: $CHECK
889
+ regex: '(?i)^(.*\.)?(is_?|check_?)?(safe|valid|allowed|permitted|trusted|whitelisted|allowlisted)\w{0,40}$|^(.*\.)?url_has_allowed_host_and_scheme$'
890
+ - pattern: $X
891
+ # Replaced where a check said no: `if not url_has_allowed_host_and_scheme(next, ...): next = reverse(...)`
892
+ # (wger), so afterwards it is either checked or the replacement.
893
+ - &checked-or-replaced
894
+ patterns:
895
+ - pattern-either:
896
+ - pattern-inside: |
897
+ if <... not $CHECK(..., $X, ...) ...>:
898
+ ...
899
+ $X = $OTHER
900
+ ...
901
+ - pattern-inside: |
902
+ if <... not $CHECK(..., url=$X, ...) ...>:
903
+ ...
904
+ $X = $OTHER
905
+ ...
906
+ - metavariable-regex:
907
+ metavariable: $CHECK
908
+ regex: '(?i)^(.*\.)?(is_?|check_?)?(safe|valid|allowed|permitted|trusted|whitelisted|allowlisted)\w{0,40}$|^(.*\.)?url_has_allowed_host_and_scheme$'
909
+ - pattern: $X
910
+ # Shared: functions named as validators (safe_next, validate_url, sanitize_path, clean_*) return checked
911
+ # data, taken at face value since the analysis doesn't look inside them; and request.path in a route with
912
+ # no variable parts, whose value routing has already fixed.
913
+ - &known-safe
914
+ pattern-either:
915
+ - patterns:
916
+ - pattern: $CHECK(...)
917
+ - metavariable-regex: {metavariable: $CHECK, regex: '(?i)(.*\.)?((get_|make_|to_)?safe|valid|saniti[sz]|clean|is_allowed)\w{0,40}$'}
918
+ # Numbers can't carry markup, paths or quotes; url_for() only builds links to this app's own routes.
919
+ - pattern: int(...)
920
+ - pattern: float(...)
921
+ - pattern: bool(...)
922
+ - pattern: len(...)
923
+ - pattern: flask.url_for(...)
924
+ - pattern: url_for(...)
925
+ # Flask-Login's link to the app's own login view, the request's URL only in its `next` parameter
926
+ # (pgAdmin: redirect(login_url("mfa.validate", next_url=next_url))).
927
+ - pattern: flask_login.login_url(...)
928
+ - pattern: flask_login.utils.login_url(...)
929
+ # Django's equivalents: a URL for one of this app's routes, or a model's own page (wger).
930
+ - pattern: django.urls.reverse(...)
931
+ - pattern: reverse(...)
932
+ - pattern: $OBJ.get_absolute_url()
933
+ # An extension or type from Python's own table (".jpg", "image/png"), whatever it was asked about
934
+ # (recipes: mimetypes.guess_extension(content_type) in an uploaded image's file name).
935
+ - pattern: mimetypes.guess_extension(...)
936
+ - pattern: mimetypes.guess_type(...)
937
+ # The signed-in account and a model's metadata are the server's data, not what the client sent (taiga:
938
+ # request.user.id and qs.model._meta.db_table formatted into SQL).
939
+ - pattern: request.user
940
+ - pattern: self.request.user
941
+ - pattern: $MODEL._meta
942
+ - patterns:
943
+ - pattern: request.$PART.get(..., type=$NUMERIC, ...)
944
+ - metavariable-regex: {metavariable: $NUMERIC, regex: ^(int|float|bool)$}
945
+ - patterns:
946
+ - pattern-either:
947
+ - pattern: flask.request.path
948
+ - pattern: request.path
949
+ - pattern-inside: |
950
+ @$APP.route("$ROUTE", ...)
951
+ def $VIEW(...):
952
+ ...
953
+ - metavariable-regex: {metavariable: $ROUTE, regex: '^[^<]*$'}
954
+ # A helper that looks something up by the request value returns that thing, not the value: get_clip(clip_id),
955
+ # fetch_order(order_no). Only bare calls (project helpers, not request.get_json()), and not names that say
956
+ # they return request data (get_param, get_json). A helper that does return it is found by the returner pass.
957
+ - &lookup-result
958
+ pattern-either:
959
+ - patterns:
960
+ # The variable it's assigned to, not the call: a sink among the call's arguments still counts.
961
+ - pattern-either:
962
+ - pattern-inside: |
963
+ $RESULT = $LOOKUP(...)
964
+ ...
965
+ - pattern-inside: |
966
+ $RESULT, $CREATED = $LOOKUP(...)
967
+ ...
968
+ - pattern-inside: |
969
+ try:
970
+ ...
971
+ $RESULT = $LOOKUP(...)
972
+ ...
973
+ except $ERR:
974
+ ...
975
+ ...
976
+ - pattern-inside: |
977
+ try:
978
+ ...
979
+ $RESULT = $LOOKUP(...)
980
+ ...
981
+ except $ERR as $E:
982
+ ...
983
+ ...
984
+ - pattern: $RESULT
985
+ - metavariable-regex:
986
+ metavariable: $LOOKUP
987
+ # A method on self counts too (paperless: self._get_effective_file_doc(...)), but not one that
988
+ # hands back the request's own data (get_serializer, get_form, get_success_url, get_next_url).
989
+ # So does one on a store or a call that returns one (MLflow GHSA-wc6j-5g83-xfm6 at its fix:
990
+ # _get_tracking_store().get_run(run_id)), but not on the request.
991
+ # An ORM query run to its row (Model.objects.filter(...).first(), Users.query.filter_by(...).first(),
992
+ # manager.only(...).filter(id=x).first()) is the stored row too.
993
+ # Nor helpers that build a query from the value: get_conditions(filters), get_where_clause(...)
994
+ # (HRMS CVE-2026-55796, an ERPNext report idiom; PLAN.md step 128).
995
+ regex: '(?s)^((self\.|(?!((flask\.)?request|self\.request|req)\b)[\w.]+(\(\))?\.)?_?(cached_)?(get|fetch|load|find|lookup)_(?!(json|data|params?|args?|query|queries|headers?|cookies?|body|form|forms|fields?|values?|inputs?|text|str|string|url|uri|path|file|filename|name|key|id|var|env|config|setting|content|request|req|payload|serializer|success|redirect|next|return|kwargs|conditions?|filters?|where|clauses?|sql)(_|$))\w+|(?!((flask\.)?request|self\.request|req)\.)\w+(\.\w+)*\.(objects\.|query\.|(only|filter|filter_by|exclude|where|select_related|prefetch_related|order_by)\(.*\)\.(first|last|get|one|one_or_none|scalar_one_or_none|first_or_404|get_or_404|get_or_create|update_or_create)$).*)$'
996
+ # Rows a Django query returns, wherever they're used (recipes: `for rule in
997
+ # Automation.objects.filter(space=request.space)...`). The query's own arguments can't be a
998
+ # project function's sink; raw() and extra() take SQL and stay out.
999
+ - patterns:
1000
+ - pattern: $MODEL.objects.$QUERY(...)
1001
+ - metavariable-regex: {metavariable: $QUERY, regex: '^(?!(raw|extra)$)\w+$'}
1002
+ # What an outbound HTTP call returns is the remote server's data, not the request's (taiga's importers:
1003
+ # a project id sent to GitHub or Jira, then avatar URLs and attachment names from the reply).
1004
+ - patterns:
1005
+ - pattern-either:
1006
+ - pattern-inside: |
1007
+ $RESULT = requests.$HTTP_METHOD(...)
1008
+ ...
1009
+ - pattern-inside: |
1010
+ $RESULT = httpx.$HTTP_METHOD(...)
1011
+ ...
1012
+ - pattern-inside: |
1013
+ $RESULT = requests.$HTTP_METHOD(...).$READ(...)
1014
+ ...
1015
+ - pattern-inside: |
1016
+ $RESULT = httpx.$HTTP_METHOD(...).$READ(...)
1017
+ ...
1018
+ - pattern: $RESULT
1019
+ # A django-filter FilterSet's rows (netbox: self.filterset(request.GET, self.queryset).qs).
1020
+ - pattern: $FILTERSET(...).qs
1021
+ - pattern: shlex.quote(...)
1022
+ # secure_filename() leaves only letters, digits, "_", "." and "-": nothing a shell treats specially.
1023
+ - pattern: secure_filename(...)
1024
+ - pattern: werkzeug.utils.secure_filename(...)
1025
+ # A URL with a literal scheme and host, as one argv element (mpv "https://youtube.com/watch?v={id}"): it can't
1026
+ # become the program or an option, and a shell command line doesn't start with "https://".
1027
+ - patterns:
1028
+ - pattern: $URL
1029
+ - pattern: f"..."
1030
+ - metavariable-regex: {metavariable: $URL, regex: '^[fF][rR]?["'']https?://[\w.-]+/'}
1031
+ - patterns:
1032
+ - pattern: '"$PREFIX" + $X'
1033
+ - metavariable-regex: {metavariable: $PREFIX, regex: '^https?://[\w.-]+/'}
1034
+ pattern-sinks:
1035
+ - patterns:
1036
+ - pattern-either:
1037
+ - pattern: subprocess.$FUNC($CMD, ...)
1038
+ - pattern: os.system($CMD)
1039
+ - pattern: os.popen($CMD, ...)
1040
+ - patterns:
1041
+ - pattern: os.$EXEC($CMD, ...)
1042
+ - metavariable-regex: {metavariable: $EXEC, regex: '^(exec[lv]p?e?|spawn[lv]p?e?)$'}
1043
+ - focus-metavariable: $CMD
1044
+
1045
+ - id: codewatch.python.web.code-injection
1046
+ mode: taint
1047
+ languages: [python]
1048
+ severity: ERROR
1049
+ message: >-
1050
+ Data from the HTTP request is evaluated as Python code. Never pass user input to eval/exec/compile;
1051
+ use ast.literal_eval for literals or an explicit mapping of allowed operations.
1052
+ metadata:
1053
+ category: security
1054
+ subcategory: [vuln]
1055
+ type: vulnerability
1056
+ title: Request data evaluated as code
1057
+ cwe: ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"]
1058
+ owasp: ["A05:2025 - Injection"]
1059
+ references:
1060
+ - https://docs.python.org/3/library/functions.html#eval
1061
+ - https://owasp.org/www-community/attacks/Code_Injection
1062
+ pattern-sources: *web-sources
1063
+ pattern-propagators: *propagators
1064
+ pattern-sanitizers:
1065
+ - *validated-guard
1066
+ - *prefix-guard
1067
+ - *checked-inside
1068
+ - *known-safe
1069
+ - *lookup-result
1070
+ pattern-sinks:
1071
+ # Not compile(): it only builds a code object and runs nothing, and compiling to check syntax is the usual
1072
+ # fix (Langflow GHSA-v798: validate_code() exec'd each function, the fix only compiles it). What compile()
1073
+ # returns stays tainted, so exec(compile(...)) and eval(compile(...)) are still found.
1074
+ - patterns:
1075
+ - pattern-either:
1076
+ - pattern: eval($CODE, ...)
1077
+ - pattern: exec($CODE, ...)
1078
+ - focus-metavariable: $CODE
1079
+
1080
+ - id: codewatch.python.web.sql-injection
1081
+ mode: taint
1082
+ languages: [python]
1083
+ severity: ERROR
1084
+ message: >-
1085
+ Data from the HTTP request is built into an SQL statement. Use query parameters
1086
+ (cursor.execute(sql, params), the ORM, or sqlalchemy.text() with bound parameters) instead of string formatting.
1087
+ metadata:
1088
+ category: security
1089
+ subcategory: [vuln]
1090
+ type: vulnerability
1091
+ title: Request data built into SQL
1092
+ cwe: ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"]
1093
+ owasp: ["A05:2025 - Injection"]
1094
+ references:
1095
+ - https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html
1096
+ - https://docs.djangoproject.com/en/stable/topics/db/sql/#passing-parameters-into-raw
1097
+ - https://peps.python.org/pep-0249/
1098
+ pattern-sources: *web-sources
1099
+ pattern-propagators: *propagators
1100
+ pattern-sanitizers:
1101
+ - *validated-guard
1102
+ - *prefix-guard
1103
+ - *checked-inside
1104
+ - *known-safe
1105
+ - *lookup-result
1106
+ # A SQLAlchemy statement built by select()/insert()/update()/delete() or a session's ORM query() binds the
1107
+ # values in it as parameters (flaskbb: sa.select(Topic).filter(Topic.id.in_(ids)) run by session.execute;
1108
+ # dispatch: db_session.query(...).filter(Entity.value == value)). sqlalchemy.text() stays a sink.
1109
+ - pattern-either:
1110
+ - patterns:
1111
+ - pattern: sqlalchemy.$BUILD(...)
1112
+ - metavariable-regex: {metavariable: $BUILD, regex: '^(select|insert|update|delete)$'}
1113
+ - patterns:
1114
+ - pattern: $SESSION.query(...)
1115
+ - metavariable-regex: {metavariable: $SESSION, regex: '(?i)^(.*\.)?(db_?)?session$'}
1116
+ # A model's table builds the same statements (CTFd: Pages.__table__.select().where(Pages.route == route)).
1117
+ - patterns:
1118
+ - pattern: $MODEL.__table__.$BUILD(...)
1119
+ - metavariable-regex: {metavariable: $BUILD, regex: '^(select|insert|update|delete)$'}
1120
+ - patterns:
1121
+ - pattern: $CHAIN.$METHOD(...)
1122
+ - metavariable-pattern:
1123
+ metavariable: $CHAIN
1124
+ pattern-either:
1125
+ - patterns:
1126
+ - pattern: <... sqlalchemy.$BUILD(...) ...>
1127
+ - metavariable-regex: {metavariable: $BUILD, regex: '^(select|insert|update|delete)$'}
1128
+ - patterns:
1129
+ - pattern: <... $SESSION.query(...) ...>
1130
+ - metavariable-regex: {metavariable: $SESSION, regex: '(?i)^(.*\.)?(db_?)?session$'}
1131
+ - patterns:
1132
+ - pattern: <... $MODEL.__table__.$BUILD(...) ...>
1133
+ - metavariable-regex: {metavariable: $BUILD, regex: '^(select|insert|update|delete)$'}
1134
+ # Django's compiled WHERE/query: SQL with %s placeholders, the values returned separately (taiga:
1135
+ # queryset.query.where.as_sql(compiler, connection)). str(queryset.query) inlines them and stays tainted.
1136
+ - pattern: $NODE.as_sql(...)
1137
+ # The same shape from a project's own builder: `sql, params = build(...)` hands back the SQL text and the
1138
+ # values to bind, and unpacking taints both names alike (label-studio's _build_flat_increment_sql puts every
1139
+ # key in params and only %s in the text). The params half stays tainted for whatever else uses it.
1140
+ - patterns:
1141
+ - pattern-inside: |
1142
+ $SQL, $PARAMS = $BUILD(...)
1143
+ ...
1144
+ - pattern: $SQL
1145
+ - metavariable-regex: {metavariable: $PARAMS, regex: '(?i)^\w*(params|args|values|bindings|binds)$'}
1146
+ - metavariable-regex: {metavariable: $SQL, regex: '(?i)^\w*(sql|query|expr|clause|where)$'}
1147
+ pattern-sinks:
1148
+ - patterns:
1149
+ - pattern-either:
1150
+ - pattern: $CUR.execute($SQL, ...)
1151
+ - pattern: $CUR.executemany($SQL, ...)
1152
+ - pattern: $CUR.executescript($SQL)
1153
+ - pattern: $MODEL.objects.raw($SQL, ...)
1154
+ - pattern: $QS.extra(where=$SQL, ...)
1155
+ - pattern: sqlalchemy.text($SQL)
1156
+ - pattern: $CONN.exec_driver_sql($SQL, ...)
1157
+ # Frappe runs the string as given; values= binds values (CVE-2026-55823, CVE-2026-55796).
1158
+ - pattern: frappe.db.sql($SQL, ...)
1159
+ - pattern: frappe.db.sql(query=$SQL, ...)
1160
+ # pandas runs the string as given; params= binds values.
1161
+ - pattern: pandas.read_sql($SQL, ...)
1162
+ - pattern: pandas.read_sql_query($SQL, ...)
1163
+ - pattern: pandas.read_sql(sql=$SQL, ...)
1164
+ - pattern: pandas.read_sql_query(sql=$SQL, ...)
1165
+ # Prisma Client Python: query_raw(sql, *params).
1166
+ - pattern: $DB.query_raw($SQL, ...)
1167
+ - pattern: $DB.query_raw(query=$SQL, ...)
1168
+ - pattern: $DB.query_first($SQL, ...)
1169
+ - pattern: $DB.query_first(query=$SQL, ...)
1170
+ - pattern: $DB.execute_raw($SQL, ...)
1171
+ - pattern: $DB.execute_raw(query=$SQL, ...)
1172
+ # pgAdmin's driver runs the string it's given: conn.execute_scalar(sql), execute_dict, execute_2darray,
1173
+ # execute_void (GHSA-v395-x24j-4r3g: a restore point's name formatted into the SQL).
1174
+ - patterns:
1175
+ - pattern: $CONN.$EXEC($SQL, ...)
1176
+ - metavariable-regex: {metavariable: $EXEC, regex: '^execute_(scalar|dict|2darray|void|async)$'}
1177
+ - focus-metavariable: $SQL
1178
+
1179
+ - id: codewatch.python.web.path-traversal
1180
+ mode: taint
1181
+ languages: [python]
1182
+ severity: ERROR
1183
+ message: >-
1184
+ Data from the HTTP request is used in a file path, so "../" can reach files outside the intended directory.
1185
+ Use werkzeug.utils.secure_filename / os.path.basename, or resolve the path and check it stays inside the base.
1186
+ metadata:
1187
+ category: security
1188
+ subcategory: [vuln]
1189
+ type: vulnerability
1190
+ title: Request data used in a file path
1191
+ cwe: ["CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"]
1192
+ owasp: ["A01:2025 - Broken Access Control"]
1193
+ references:
1194
+ - https://owasp.org/www-community/attacks/Path_Traversal
1195
+ - https://werkzeug.palletsprojects.com/en/stable/utils/#werkzeug.utils.secure_filename
1196
+ pattern-sources: *web-sources
1197
+ pattern-propagators: *propagators
1198
+ pattern-sanitizers:
1199
+ - *validated-guard
1200
+ # A prefix test counts only on a resolved or normalised path (Bazarr CVE-2026-137585 at its fix:
1201
+ # `fullpath = os.path.realpath(os.path.join(base, path))`, then `if not fullpath.startswith(...)`), never
1202
+ # on the raw value: `path.startswith('workbox-')` lets `workbox-../../etc/passwd` through.
1203
+ - patterns:
1204
+ - pattern-either:
1205
+ - pattern-inside: |
1206
+ if <... $X.startswith(...) ...>:
1207
+ ...
1208
+ return ...
1209
+ ...
1210
+ - pattern-inside: |
1211
+ if <... $X.startswith(...) ...>:
1212
+ ...
1213
+ raise ...
1214
+ ...
1215
+ - pattern-either:
1216
+ - pattern-inside: |
1217
+ $X = os.path.realpath(...)
1218
+ ...
1219
+ - pattern-inside: |
1220
+ $X = os.path.abspath(...)
1221
+ ...
1222
+ - pattern-inside: |
1223
+ $X = os.path.normpath(...)
1224
+ ...
1225
+ - pattern-inside: |
1226
+ $X = $P.resolve(...)
1227
+ ...
1228
+ - pattern-inside: |
1229
+ $X = str($P.resolve(...))
1230
+ ...
1231
+ - pattern: $X
1232
+ # The same, inside a branch whose else ends the request, used after it (tiny-scientist GHSA-rrgf at its fix:
1233
+ # `if pdf_path.startswith("/api/files/"):` resolves and checks the path, `else: return ...`, then
1234
+ # os.path.exists(path)).
1235
+ - patterns:
1236
+ - pattern-either:
1237
+ - pattern-inside: |
1238
+ if $COND:
1239
+ ...
1240
+ $X = os.path.$NORM(...)
1241
+ ...
1242
+ if <... $X.startswith(...) ...>:
1243
+ ...
1244
+ return ...
1245
+ ...
1246
+ else:
1247
+ ...
1248
+ return ...
1249
+ ...
1250
+ - pattern-inside: |
1251
+ if $COND:
1252
+ ...
1253
+ $X = os.path.$NORM(...)
1254
+ ...
1255
+ if <... $X.startswith(...) ...>:
1256
+ ...
1257
+ raise ...
1258
+ ...
1259
+ else:
1260
+ ...
1261
+ raise ...
1262
+ ...
1263
+ - metavariable-regex: {metavariable: $NORM, regex: ^(realpath|abspath|normpath)$}
1264
+ - pattern: $X
1265
+ - *checked-inside
1266
+ - *known-safe
1267
+ - *lookup-result
1268
+ - pattern: os.path.basename(...)
1269
+ - pattern: pathlib.Path(...).name
1270
+ - pattern: pathlib.Path(...).stem
1271
+ - pattern: pathlib.PurePath(...).name
1272
+ - pattern: pathlib.PurePath(...).stem
1273
+ # The same through a variable: candidate = Path(run_id) ... base / candidate.name (Vibe-Trading GHSA-mjrq at its
1274
+ # fix).
1275
+ - patterns:
1276
+ - pattern-either:
1277
+ - pattern-inside: |
1278
+ $CANDIDATE = pathlib.Path(...)
1279
+ ...
1280
+ - pattern-inside: |
1281
+ $CANDIDATE = pathlib.PurePath(...)
1282
+ ...
1283
+ - pattern-either:
1284
+ - pattern: $CANDIDATE.name
1285
+ - pattern: $CANDIDATE.stem
1286
+ - pattern: werkzeug.utils.secure_filename(...)
1287
+ - pattern: secure_filename(...)
1288
+ # Replacing every character outside a class of letters, digits, "_", "-" and spaces leaves one name that can't
1289
+ # climb (changedetection.io GHSA-9jj8-v89v-xjvw at its fix: re.sub(r'[^a-z0-9_]+', '', group)). [^\w.-] keeps
1290
+ # "..", so it doesn't.
1291
+ - patterns:
1292
+ - pattern: re.sub($PATTERN, $WITH, ...)
1293
+ - metavariable-regex:
1294
+ metavariable: $PATTERN
1295
+ regex: '^r?[''"]\[\^([a-zA-Z0-9_ -]|\\[wd])+\][+*]?[''"]$'
1296
+ - metavariable-regex: {metavariable: $WITH, regex: '^[rbu]*[''"][-_]?[''"]$'}
1297
+ # A path a containment helper said stays inside its base: `if not is_path_within_root_dirs(str(p)): return`
1298
+ # (swingmusic GHSA-pj88 at its fix), `if is_relative_to(new_path, root_dir): new_path.mkdir()` or
1299
+ # `if not is_relative_to(target, root) or target == root: return False` (archivy 2565a9ab11d1). The path is
1300
+ # the helper's first argument; named for containment, not for permission (check_access_permission isn't one).
1301
+ # Not where an `and` can skip the check, nor in the branch where it said no.
1302
+ - patterns:
1303
+ - pattern-either:
1304
+ - pattern-inside: |
1305
+ if <... not $CHECK(<... $X ...>, ...) ...>:
1306
+ ...
1307
+ return ...
1308
+ ...
1309
+ - pattern-inside: |
1310
+ if <... not $CHECK(<... $X ...>, ...) ...>:
1311
+ ...
1312
+ raise ...
1313
+ ...
1314
+ - pattern-inside: |
1315
+ if <... not $CHECK(<... $X ...>, ...) ...>:
1316
+ ...
1317
+ abort(...)
1318
+ ...
1319
+ - pattern-inside: |
1320
+ if <... not $CHECK(<... $X ...>, ...) ...>:
1321
+ ...
1322
+ flask.abort(...)
1323
+ ...
1324
+ - pattern-inside: |
1325
+ if $CHECK(<... $X ...>, ...):
1326
+ ...
1327
+ - pattern-not-inside: |
1328
+ if $A and <... not $CHECK(<... $X ...>, ...) ...>:
1329
+ ...
1330
+ ...
1331
+ - pattern-not-inside: |
1332
+ if <... not $CHECK(<... $X ...>, ...) ...> and $B:
1333
+ ...
1334
+ ...
1335
+ - pattern-not-inside: |
1336
+ if <... not $CHECK(<... $X ...>, ...) ...>:
1337
+ ...
1338
+ - metavariable-regex:
1339
+ metavariable: $CHECK
1340
+ regex: '(?i)^(.*\.)?_?(is_?|check_?)?\w{0,30}(within|inside|contained|relative_to)\w{0,30}$'
1341
+ - pattern: $X
1342
+ # The same check written out: a resolved path whose base is among its parents, else return or raise
1343
+ # (`if BASE.resolve() not in target.parents: raise`), or used only where it is.
1344
+ - patterns:
1345
+ - pattern-either:
1346
+ - pattern-inside: |
1347
+ if <... $BASE not in $X.parents ...>:
1348
+ ...
1349
+ return ...
1350
+ ...
1351
+ - pattern-inside: |
1352
+ if <... $BASE not in $X.parents ...>:
1353
+ ...
1354
+ raise ...
1355
+ ...
1356
+ - pattern-inside: |
1357
+ if <... $BASE in $X.parents ...>:
1358
+ ...
1359
+ - pattern-not-inside: |
1360
+ if <... $BASE not in $X.parents ...>:
1361
+ ...
1362
+ - pattern: $X
1363
+ # A resolved path whose relative_to() its base must not raise, else return or raise (Agent Zero GHSA-8j45 at
1364
+ # its fix: `resolved = candidate.resolve(strict=False)`, then `try: resolved.relative_to(base_dir) except
1365
+ # ValueError as exc: raise ValueError(...) from exc`). Only a resolved one: Path(name).relative_to(base) lets "a/../../x" through.
1366
+ - patterns:
1367
+ - pattern-either:
1368
+ - pattern-inside: |
1369
+ $X = $P.resolve(...)
1370
+ ...
1371
+ try:
1372
+ ...
1373
+ $X.relative_to(...)
1374
+ ...
1375
+ except ValueError:
1376
+ ...
1377
+ raise ...
1378
+ ...
1379
+ - pattern-inside: |
1380
+ $X = $P.resolve(...)
1381
+ ...
1382
+ try:
1383
+ ...
1384
+ $X.relative_to(...)
1385
+ ...
1386
+ except ValueError as $E:
1387
+ ...
1388
+ raise ...
1389
+ ...
1390
+ - pattern-inside: |
1391
+ $X = $P.resolve(...)
1392
+ ...
1393
+ try:
1394
+ ...
1395
+ $X.relative_to(...)
1396
+ ...
1397
+ except ValueError as $E:
1398
+ ...
1399
+ raise $EXC from $E
1400
+ ...
1401
+ - pattern-inside: |
1402
+ $X = $P.resolve(...)
1403
+ ...
1404
+ try:
1405
+ ...
1406
+ $X.relative_to(...)
1407
+ ...
1408
+ except ValueError:
1409
+ ...
1410
+ return ...
1411
+ ...
1412
+ - pattern-inside: |
1413
+ $X = $P.resolve(...)
1414
+ ...
1415
+ try:
1416
+ ...
1417
+ $X.relative_to(...)
1418
+ ...
1419
+ except ValueError as $E:
1420
+ ...
1421
+ return ...
1422
+ ...
1423
+ - pattern: $X
1424
+ pattern-sinks:
1425
+ - patterns:
1426
+ - pattern-either:
1427
+ - pattern: open($PATH, ...)
1428
+ - pattern: io.open($PATH, ...)
1429
+ - pattern: codecs.open($PATH, ...)
1430
+ - pattern: os.open($PATH, ...)
1431
+ - pattern: pathlib.Path($PATH, ...)
1432
+ - pattern: os.remove($PATH)
1433
+ - pattern: os.unlink($PATH)
1434
+ - pattern: os.rename($PATH, ...)
1435
+ - pattern: os.listdir($PATH)
1436
+ - pattern: os.path.exists($PATH)
1437
+ - pattern: os.path.isfile($PATH)
1438
+ - pattern: os.path.isdir($PATH)
1439
+ - pattern: os.stat($PATH)
1440
+ # A pathlib.Path built from request data, used once it's built: (base / name).read_text()
1441
+ - patterns:
1442
+ - pattern: $PATH.$USE(...)
1443
+ - metavariable-regex:
1444
+ metavariable: $USE
1445
+ regex: ^(exists|is_file|is_dir|stat|open|read_text|read_bytes|write_text|write_bytes|unlink|rmdir|mkdir|touch|rename|replace|iterdir|glob|rglob|chmod)$
1446
+ - metavariable-pattern:
1447
+ metavariable: $PATH
1448
+ pattern-either: &pathlib-value
1449
+ - pattern: pathlib.Path(...)
1450
+ - pattern: pathlib.PurePath(...)
1451
+ - pattern: pathlib.Path(...) / $NAME
1452
+ - pattern: (pathlib.Path(...) / $NAME).resolve(...)
1453
+ - pattern: pathlib.Path(...).joinpath(...)
1454
+ - pattern: $BASE / $NAME
1455
+ - pattern: ($BASE / $NAME).resolve(...)
1456
+ - pattern: $BASE.joinpath(...)
1457
+ - patterns:
1458
+ - pattern: $PATH.$USE(...)
1459
+ - metavariable-regex:
1460
+ metavariable: $USE
1461
+ regex: ^(exists|is_file|is_dir|stat|open|read_text|read_bytes|write_text|write_bytes|unlink|rmdir|mkdir|touch|rename|replace|iterdir|glob|rglob|chmod)$
1462
+ - pattern-inside: |
1463
+ $PATH = $INIT
1464
+ ...
1465
+ - metavariable-pattern:
1466
+ metavariable: $INIT
1467
+ pattern-either: *pathlib-value
1468
+ # A path a project helper built and returned, then used: self._file_path().open() (Checkmk
1469
+ # 31dfe9231eee, where _file_path() joins a request's file_id to the upload directory), or
1470
+ # `path = file_path(name); path.write_text(...)`. Only helpers named for a path, so an Odoo record's
1471
+ # unlink() isn't one, and no replace()/rename(), which a returned str has too.
1472
+ # The whole receiver is the helper's call (a regex, since metavariable-pattern also matches inside it:
1473
+ # label-studio's Storage.objects.filter(path=normalize_storage_path(p)).exists() is a query).
1474
+ # Lower-case names only: pathlib.Path(x) is the pathlib sinks' above.
1475
+ - patterns:
1476
+ - pattern-either:
1477
+ - patterns:
1478
+ - pattern: $PATH.$USE(...)
1479
+ - metavariable-regex:
1480
+ metavariable: $PATH
1481
+ regex: &path-helper-call (?s)^(\w+\.)?_*([a-z0-9]+_)*(path|dir|directory|folder|filepath)\(.*\)$
1482
+ - patterns:
1483
+ - pattern: $PATH.$USE(...)
1484
+ - pattern-inside: |
1485
+ $PATH = $CALL
1486
+ ...
1487
+ - metavariable-regex:
1488
+ metavariable: $CALL
1489
+ regex: *path-helper-call
1490
+ - metavariable-regex:
1491
+ metavariable: $USE
1492
+ regex: ^(exists|is_file|is_dir|stat|open|read_text|read_bytes|write_text|write_bytes|unlink|rmdir|mkdir|touch|iterdir|glob|rglob|chmod)$
1493
+ - pattern: shutil.$OP($PATH, ...)
1494
+ # werkzeug's FileStorage.save(path) for an upload, or an image saved under a request-made name.
1495
+ # Django storages reject "..", so their save() isn't a sink.
1496
+ - patterns:
1497
+ - pattern: $FILE.save($PATH, ...)
1498
+ - metavariable-regex: {metavariable: $FILE, regex: '(?i)^(?!.*storage)'}
1499
+ - pattern: flask.send_file($PATH, ...)
1500
+ - pattern: send_file($PATH, ...)
1501
+ - pattern: django.http.FileResponse(open($PATH, ...), ...)
1502
+ # Starlette and FastAPI open the path they're given (Fides GHSA-r25m-cr6v-p9hq).
1503
+ - pattern: starlette.responses.FileResponse($PATH, ...)
1504
+ - pattern: fastapi.responses.FileResponse($PATH, ...)
1505
+ # A path's name or extension is a string, not a file opened (paperless-ngx: Path(str(doc.filename)).suffix).
1506
+ - pattern-not-inside: pathlib.Path(...).suffix
1507
+ - pattern-not-inside: pathlib.Path(...).suffixes
1508
+ - pattern-not-inside: pathlib.Path(...).stem
1509
+ - pattern-not-inside: pathlib.Path(...).name
1510
+ - pattern-not-inside: pathlib.Path(...).parts
1511
+ # A containment check opens nothing (pgAdmin GHSA-cr8c-972v-rmp3: Path(new_name).relative_to(the_dir) in a
1512
+ # try, before the open() that is the sink).
1513
+ - pattern-not-inside: pathlib.Path(...).relative_to(...)
1514
+ - pattern-not-inside: pathlib.Path(...).is_relative_to(...)
1515
+ # A Path assigned to a variable opens nothing yet; each use of the variable is a sink of its own
1516
+ # (Vibe-Trading GHSA-mjrq at its fix: candidate = Path(run_id), checked, then only candidate.name used).
1517
+ - pattern-not-inside: $CANDIDATE = pathlib.Path($PATH, ...)
1518
+ - pattern-not-inside: $CANDIDATE = pathlib.PurePath($PATH, ...)
1519
+ # Nor resolved first, to be checked: `resolved_path = Path(query.path).resolve()` then a containment check
1520
+ # (swingmusic GHSA-pj88 at its fix). Its uses (resolved_path.exists()) are still the sinks above.
1521
+ - pattern-not-inside: $CANDIDATE = pathlib.Path($PATH, ...).resolve(...)
1522
+ - pattern-not-inside: $CANDIDATE = pathlib.Path($PATH, ...).absolute()
1523
+ - focus-metavariable: $PATH
1524
+
1525
+ - id: codewatch.python.web.xss
1526
+ mode: taint
1527
+ languages: [python]
1528
+ severity: ERROR
1529
+ message: >-
1530
+ Data from the HTTP request is written into an HTML response without escaping. Render it through an
1531
+ auto-escaping template, or escape it with html.escape()/markupsafe.escape() first.
1532
+ metadata:
1533
+ category: security
1534
+ subcategory: [vuln]
1535
+ type: vulnerability
1536
+ title: Request data in an HTML response without escaping
1537
+ cwe: ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"]
1538
+ owasp: ["A05:2025 - Injection"]
1539
+ references:
1540
+ - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
1541
+ - https://flask.palletsprojects.com/en/stable/web-security/#cross-site-scripting-xss
1542
+ pattern-sources: *web-sources
1543
+ pattern-propagators: *propagators
1544
+ pattern-sanitizers:
1545
+ - *validated-guard
1546
+ - *prefix-guard
1547
+ - *checked-inside
1548
+ - *known-safe
1549
+ - *lookup-result
1550
+ - pattern: html.escape(...)
1551
+ - pattern: markupsafe.escape(...)
1552
+ - pattern: flask.escape(...)
1553
+ - pattern: django.utils.html.escape(...)
1554
+ - pattern: bleach.clean(...)
1555
+ - pattern: flask.jsonify(...)
1556
+ - pattern: jsonify(...)
1557
+ - pattern: json.dumps(...)
1558
+ # Percent-encoding with the default safe characters ('/' for quote, none for quote_plus) turns < > " ' and : into
1559
+ # %XX: the value can't close an attribute, open a tag or start a javascript: URL (vulnerability-lookup's fix,
1560
+ # Markup(f"<a href='/sightings?query={quote_plus(id)}'>")). A safe= argument may let them through: one argument only.
1561
+ - pattern: urllib.parse.quote($X)
1562
+ - pattern: urllib.parse.quote_plus($X)
1563
+ # A file response's body is the file; the name only goes into a quoted Content-Disposition header.
1564
+ - pattern: flask.send_file(...)
1565
+ - pattern: send_file(...)
1566
+ - pattern: flask.send_from_directory(...)
1567
+ - pattern: send_from_directory(...)
1568
+ # What a file holds isn't what the request sent, even when the request named the file; reading from a path it
1569
+ # chose is path traversal, reported by its own rule (CodeRed: HttpResponse(open(fullpath, 'rb').read())).
1570
+ - pattern: open(...)
1571
+ - pattern: $PATH.read_text(...)
1572
+ - pattern: $PATH.read_bytes(...)
1573
+ # Jinja templates escape what they're given; redirect() escapes the URL in its body.
1574
+ - pattern: flask.render_template(...)
1575
+ - pattern: render_template(...)
1576
+ # Flask-AppBuilder/Flask-Admin views render their templates (autoescaped) and JSON replies through self.
1577
+ - patterns:
1578
+ - pattern: self.$RENDER(...)
1579
+ - metavariable-regex: {metavariable: $RENDER, regex: '^(render|render_template|response(_\d{3})?)$'}
1580
+ - pattern: django.shortcuts.render(...)
1581
+ - pattern: django.template.loader.render_to_string(...)
1582
+ # A model or helper that renders its own template, given the request for context (djangoproject.com:
1583
+ # instance.render_to_string(request=request)).
1584
+ - pattern: $OBJ.render_to_string(...)
1585
+ # A Django template loaded by name renders autoescaped too (netbox's handler_500:
1586
+ # template = loader.get_template(name), then HttpResponseServerError(template.render({...}))). Not Jinja's
1587
+ # Template, which doesn't escape unless its environment says so.
1588
+ - pattern: django.template.loader.get_template(...).render(...)
1589
+ - pattern: django.template.loader.select_template(...).render(...)
1590
+ - patterns:
1591
+ - pattern: $T.render(...)
1592
+ - pattern-either:
1593
+ - pattern-inside: |
1594
+ $T = django.template.loader.get_template(...)
1595
+ ...
1596
+ - pattern-inside: |
1597
+ $T = django.template.loader.select_template(...)
1598
+ ...
1599
+ - pattern-inside: |
1600
+ try:
1601
+ ...
1602
+ $T = django.template.loader.get_template(...)
1603
+ ...
1604
+ except ...:
1605
+ ...
1606
+ ...
1607
+ - pattern-inside: |
1608
+ try:
1609
+ ...
1610
+ $T = django.template.loader.select_template(...)
1611
+ ...
1612
+ except ...:
1613
+ ...
1614
+ ...
1615
+ - pattern: django.template.response.TemplateResponse(...)
1616
+ - pattern: flask.redirect(...)
1617
+ - pattern: redirect(...)
1618
+ - pattern: url_for(...)
1619
+ - pattern: flask.url_for(...)
1620
+ # Project helpers named like escape_html / html_escape are treated as escaping functions.
1621
+ - patterns:
1622
+ - pattern: $ESCAPE(...)
1623
+ - metavariable-regex: {metavariable: $ESCAPE, regex: '(?i).*escape\w{0,30}$'}
1624
+ pattern-sinks:
1625
+ # The request choosing a response's type: text/html makes whatever the body holds run as a page, a stored
1626
+ # upload included (SecurityEval CWE-113 sonar_1/sonar_2; n8n GHSA-c8hm is the JavaScript form). Werkzeug and
1627
+ # Django refuse newlines in header values, so the danger is the type, not a split response. send_file() is a
1628
+ # sanitizer of this rule (a file's bytes aren't request data), so its mimetype= isn't covered.
1629
+ - patterns:
1630
+ - pattern: $RESP(..., $KW=$CT, ...)
1631
+ # An attachment is downloaded, not rendered, whatever its type (label-studio's export FileResponse).
1632
+ - pattern-not: $RESP(..., as_attachment=True, ...)
1633
+ - metavariable-regex: {metavariable: $RESP, regex: '^(\w+\.)*(Response|HttpResponse|StreamingHttpResponse|FileResponse|make_response)$'}
1634
+ - metavariable-regex: {metavariable: $KW, regex: '^(mimetype|content_type)$'}
1635
+ # A type looked up in the app's own table (TYPES.get(fmt, 'text/plain')) is one of its values.
1636
+ - metavariable-regex: {metavariable: $CT, regex: '^(?![A-Z][A-Z0-9_]*(\.get\(|\[))'}
1637
+ - focus-metavariable: $CT
1638
+ - patterns:
1639
+ - pattern-either:
1640
+ - pattern: $R.mimetype = $CT
1641
+ - pattern: $R.content_type = $CT
1642
+ - pattern-inside: |
1643
+ $R = $RESP(...)
1644
+ ...
1645
+ - metavariable-regex: {metavariable: $RESP, regex: '^(\w+\.)*(Response|HttpResponse|StreamingHttpResponse|FileResponse|make_response)$'}
1646
+ # A type looked up in the app's own table (TYPES.get(fmt, 'text/plain')) is one of its values.
1647
+ - metavariable-regex: {metavariable: $CT, regex: '^(?![A-Z][A-Z0-9_]*(\.get\(|\[))'}
1648
+ - focus-metavariable: $CT
1649
+ - patterns:
1650
+ - pattern-either:
1651
+ - patterns:
1652
+ - pattern-either:
1653
+ - pattern: $R.headers[$K] = $CT
1654
+ - pattern: $R[$K] = $CT
1655
+ - pattern-inside: |
1656
+ $R = $RESP(...)
1657
+ ...
1658
+ - metavariable-regex: {metavariable: $RESP, regex: '^(\w+\.)*(Response|HttpResponse|StreamingHttpResponse|FileResponse|make_response)$'}
1659
+ - patterns:
1660
+ - pattern-either:
1661
+ - pattern: $H.add($K, $CT)
1662
+ - pattern: $H.set($K, $CT)
1663
+ - pattern: $H[$K] = $CT
1664
+ - pattern-inside: |
1665
+ $H = $HEADERS(...)
1666
+ ...
1667
+ - metavariable-regex: {metavariable: $HEADERS, regex: '^(\w+\.)*Headers$'}
1668
+ - metavariable-regex: {metavariable: $K, regex: '(?i)^[''"]content-type[''"]$'}
1669
+ # A type looked up in the app's own table (TYPES.get(fmt, 'text/plain')) is one of its values.
1670
+ - metavariable-regex: {metavariable: $CT, regex: '^(?![A-Z][A-Z0-9_]*(\.get\(|\[))'}
1671
+ - focus-metavariable: $CT
1672
+ # A (body, status, headers) tuple: only the body is rendered; header values can't inject markup.
1673
+ - patterns:
1674
+ # Flask routes, and Flask-AppBuilder/Flask-Admin @expose methods (Airflow GHSA-rv25-9wgj-xg75).
1675
+ - pattern-either:
1676
+ - pattern-inside: |
1677
+ @$APP.route(...)
1678
+ def $VIEW(...):
1679
+ ...
1680
+ - pattern-inside: |
1681
+ @expose(...)
1682
+ def $VIEW(self, ...):
1683
+ ...
1684
+ - pattern-inside: |
1685
+ @$MODULE.expose(...)
1686
+ def $VIEW(self, ...):
1687
+ ...
1688
+ # A function defined inside the view returns to its caller, not to the client.
1689
+ - pattern-not-inside: |
1690
+ def $VIEW(...):
1691
+ ...
1692
+ def $INNER(...):
1693
+ ...
1694
+ - pattern-either:
1695
+ - patterns:
1696
+ - pattern: return $BODY
1697
+ - pattern-not: return ($FIRST, $SECOND, ...)
1698
+ - pattern: return ($BODY, $SECOND, ...)
1699
+ # Flask serves a returned dict or list as JSON.
1700
+ - pattern-not: return {...}
1701
+ - pattern-not: return [...]
1702
+ - pattern-not: return ({...}, ...)
1703
+ - pattern-not: return ([...], ...)
1704
+ # Returning a response object built earlier: its body was checked where it was built (sinks below).
1705
+ - pattern-not-inside: |
1706
+ $BODY = make_response(...)
1707
+ ...
1708
+ - pattern-not-inside: |
1709
+ $BODY = flask.make_response(...)
1710
+ ...
1711
+ - pattern-not-inside: |
1712
+ $BODY = flask.Response(...)
1713
+ ...
1714
+ - pattern-not: return flask.Response(...)
1715
+ - pattern-not: return flask.make_response(...)
1716
+ - pattern-not: return make_response(...)
1717
+ - focus-metavariable: $BODY
1718
+ # A dict or list body is turned into JSON by Flask (MLflow: make_response({"user": user.to_json()})).
1719
+ - patterns:
1720
+ - pattern-either:
1721
+ - pattern: flask.make_response(($BODY, $SECOND, ...), ...)
1722
+ - pattern: make_response(($BODY, $SECOND, ...), ...)
1723
+ - pattern-not: $MAKE(({...}, ...), ...)
1724
+ - pattern-not: $MAKE(([...], ...), ...)
1725
+ - focus-metavariable: $BODY
1726
+ - patterns:
1727
+ - pattern-either:
1728
+ - patterns:
1729
+ - pattern-either:
1730
+ - pattern: flask.make_response($BODY, ...)
1731
+ - pattern: make_response($BODY, ...)
1732
+ - pattern-not: flask.make_response(($FIRST, $SECOND, ...), ...)
1733
+ - pattern-not: make_response(($FIRST, $SECOND, ...), ...)
1734
+ - pattern-not: $MAKE({...}, ...)
1735
+ - pattern-not: $MAKE([...], ...)
1736
+ - patterns:
1737
+ - pattern-either:
1738
+ - pattern: flask.Response($BODY, ...)
1739
+ - pattern: django.http.HttpResponse($BODY, ...)
1740
+ # Its error subclasses render their body as text/html too (CVAT CVE-2024-47064:
1741
+ # HttpResponseNotFound(f"There is no request with specified id: {pk}")).
1742
+ # HttpResponseNotAllowed's first argument is the allowed methods, not a body.
1743
+ - pattern: django.http.HttpResponseNotFound($BODY, ...)
1744
+ - pattern: django.http.HttpResponseBadRequest($BODY, ...)
1745
+ - pattern: django.http.HttpResponseForbidden($BODY, ...)
1746
+ - pattern: django.http.HttpResponseGone($BODY, ...)
1747
+ - pattern: django.http.HttpResponseServerError($BODY, ...)
1748
+ # Starlette's (and so FastAPI's) HTMLResponse sends its content as text/html, by position
1749
+ # or as content= (nextcloud-mcp-server, PLAN.md step 119).
1750
+ - pattern: starlette.responses.HTMLResponse($BODY, ...)
1751
+ - pattern: starlette.responses.HTMLResponse(..., content=$BODY, ...)
1752
+ - pattern: fastapi.responses.HTMLResponse($BODY, ...)
1753
+ - pattern: fastapi.responses.HTMLResponse(..., content=$BODY, ...)
1754
+ # Media, JSON, plain text and downloads aren't rendered as HTML (recipes:
1755
+ # HttpResponse(export_file, content_type='application/force-download')).
1756
+ - pattern-not: $RESP($B, ..., mimetype="=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/", ...)
1757
+ - pattern-not: $RESP($B, ..., content_type="=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/", ...)
1758
+ - pattern: flask.render_template_string($BODY, ...)
1759
+ - pattern: render_template_string($BODY, ...)
1760
+ - pattern: markupsafe.Markup($BODY)
1761
+ - pattern: django.utils.safestring.mark_safe($BODY)
1762
+ - pattern: mark_safe($BODY)
1763
+ # format_html escapes its arguments, not its format string: format_html(f"<b>{name}</b>") doesn't.
1764
+ - pattern: django.utils.html.format_html($BODY, ...)
1765
+ - pattern: format_html($BODY, ...)
1766
+ # A response given a non-HTML type on the next lines: r = make_response(text); r.mimetype = "text/plain"
1767
+ # (CTFd views.py).
1768
+ - pattern-not-inside: |
1769
+ $R = $MAKE(...)
1770
+ ...
1771
+ $R.mimetype = "=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/"
1772
+ - pattern-not-inside: |
1773
+ $R = $MAKE(...)
1774
+ ...
1775
+ $R.content_type = "=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/"
1776
+ - pattern-not-inside: |
1777
+ $R = $MAKE(...)
1778
+ ...
1779
+ $R[$HEADER] = "=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/"
1780
+ - pattern-not-inside: |
1781
+ $R = $MAKE(...)
1782
+ ...
1783
+ $R.headers[$HEADER] = "=~/^(image|video|audio|font)\/|^application\/(json|octet-stream|pdf|zip|force-download|x-download|(x-)?yaml)|^text\/(plain|csv|(x-)?yaml)/"
1784
+ - focus-metavariable: $BODY
1785
+
1786
+ - id: codewatch.python.web.xpath-injection
1787
+ mode: taint
1788
+ languages: [python]
1789
+ severity: ERROR
1790
+ message: >-
1791
+ Data from the HTTP request is built into an XPath query. Pass it as an XPath variable
1792
+ (e.g. tree.xpath("//user[@name=$name]", name=value)) instead of formatting it into the query.
1793
+ metadata:
1794
+ category: security
1795
+ subcategory: [vuln]
1796
+ type: vulnerability
1797
+ title: Request data built into XPath
1798
+ cwe: ["CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath Injection')"]
1799
+ owasp: ["A05:2025 - Injection"]
1800
+ references:
1801
+ - https://owasp.org/www-community/attacks/XPATH_Injection
1802
+ - https://lxml.de/xpathxslt.html#the-xpath-method
1803
+ pattern-sources: *web-sources
1804
+ pattern-propagators: *propagators
1805
+ pattern-sanitizers:
1806
+ - *validated-guard
1807
+ - *prefix-guard
1808
+ - *checked-inside
1809
+ - *known-safe
1810
+ - *lookup-result
1811
+ # Replacing the quote that delimits the value (' -> &apos;) stops it from closing the XPath string.
1812
+ - patterns:
1813
+ - pattern: $X.replace($QUOTE, ...)
1814
+ - metavariable-regex: {metavariable: $QUOTE, regex: '^["'']\\?["'']["'']$'}
1815
+ pattern-sinks:
1816
+ - patterns:
1817
+ - pattern-either:
1818
+ - pattern: lxml.etree.XPath($QUERY, ...)
1819
+ - pattern: lxml.etree.ETXPath($QUERY, ...)
1820
+ - pattern: $TREE.xpath($QUERY, ...)
1821
+ - pattern: elementpath.select($ROOT, $QUERY, ...)
1822
+ - focus-metavariable: $QUERY
1823
+ # ElementTree's find/findall, not a regular expression's: re.findall(pattern, text) or a compiled
1824
+ # `_TOKEN_RE.findall(text)` (Vibe-Trading's memory search, reached once agent tool arguments were sources).
1825
+ - patterns:
1826
+ - pattern-either:
1827
+ - pattern: $TREE.findall($QUERY, ...)
1828
+ - pattern: $TREE.find($QUERY, ...)
1829
+ - metavariable-regex:
1830
+ metavariable: $TREE
1831
+ regex: '^(?!(re|regex)$)(?!(?i:.*([._]|^)(re|rx|regex|regexp|pattern)$)).*$'
1832
+ # Nor a MongoDB collection's find({...}) (mongo.db.users, items_collection; nosql-injection's) or
1833
+ # BeautifulSoup's find(tag name), which take no path. Nor a compiled JSONPath's find(document), whose
1834
+ # argument is the data searched (dispatch's `jpath.find(signal_instance.raw)`).
1835
+ - metavariable-regex:
1836
+ metavariable: $TREE
1837
+ regex: '^(?!(?i:((.*\.)?(db|mongo|database)(\.\w+|\[[^\]]+\])|(.*\.)?\w*(collection|coll|_col)s?)$))(?!(?i:.*soup))(?!(?i:(.*[._])?(jpath|jsonpath|json_path)$)).*$'
1838
+ - pattern-not: $TREE.find({...}, ...)
1839
+ - pattern-not: $TREE.findall({...}, ...)
1840
+ # Nor a module's own find function (codewatch's `catalog.find(rule_id)`, a rule lookup): no XML library
1841
+ # has one at module level, so a receiver the file imports as a module isn't a tree.
1842
+ - pattern-not-inside: |
1843
+ import $TREE
1844
+ ...
1845
+ - pattern-not-inside: |
1846
+ import $MOD as $TREE
1847
+ ...
1848
+ - pattern-not-inside: |
1849
+ from $MOD import $TREE
1850
+ ...
1851
+ - pattern-not-inside: |
1852
+ from $MOD import $OTHER, $TREE
1853
+ ...
1854
+ - focus-metavariable: $QUERY
1855
+
1856
+ - id: codewatch.python.web.ldap-injection
1857
+ mode: taint
1858
+ languages: [python]
1859
+ severity: ERROR
1860
+ message: >-
1861
+ Data from the HTTP request is built into an LDAP search filter. Escape it with
1862
+ ldap3.utils.conv.escape_filter_chars() (or ldap.filter.escape_filter_chars) first.
1863
+ metadata:
1864
+ category: security
1865
+ subcategory: [vuln]
1866
+ type: vulnerability
1867
+ title: Request data built into an LDAP filter
1868
+ cwe: ["CWE-90: Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')"]
1869
+ owasp: ["A05:2025 - Injection"]
1870
+ references:
1871
+ - https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html
1872
+ - https://ldap3.readthedocs.io/en/latest/searches.html
1873
+ pattern-sources: *web-sources
1874
+ pattern-propagators: *propagators
1875
+ pattern-sanitizers:
1876
+ - *validated-guard
1877
+ - *prefix-guard
1878
+ - *checked-inside
1879
+ - *known-safe
1880
+ - *lookup-result
1881
+ - patterns:
1882
+ - pattern: $ESCAPE(...)
1883
+ - metavariable-regex: {metavariable: $ESCAPE, regex: '(?i).*escape'}
1884
+ pattern-sinks:
1885
+ - patterns:
1886
+ - pattern-either:
1887
+ - pattern: $CONN.search($BASE, $FILTER, ...)
1888
+ - pattern: $CONN.search(..., search_filter=$FILTER, ...)
1889
+ - pattern: $CONN.search_s($BASE, $SCOPE, $FILTER, ...)
1890
+ - pattern: $CONN.search_st($BASE, $SCOPE, $FILTER, ...)
1891
+ - pattern: $CONN.search_ext_s($BASE, $SCOPE, $FILTER, ...)
1892
+ # ldap3's paged search, which directory connectors use for large result sets.
1893
+ - pattern: $CONN.extend.standard.paged_search($BASE, $FILTER, ...)
1894
+ - pattern: $CONN.extend.standard.paged_search(..., search_filter=$FILTER, ...)
1895
+ # A bind DN built from the user name: `uid=x,ou=people,...` with a `,` or `+` in x names another
1896
+ # entry. ldap3.utils.dn.escape_rdn() escapes it.
1897
+ - pattern: ldap3.Connection($SERVER, $FILTER, ...)
1898
+ - pattern: ldap3.Connection(..., user=$FILTER, ...)
1899
+ - pattern: $CONN.rebind(user=$FILTER, ...)
1900
+ - pattern: $CONN.simple_bind_s($FILTER, ...)
1901
+ - pattern: $CONN.bind_s($FILTER, ...)
1902
+ # Only where an LDAP library is in use: Post.search(q, page) is an ORM method, not a directory query.
1903
+ - pattern-either:
1904
+ - pattern-inside: |
1905
+ import ldap3
1906
+ ...
1907
+ - pattern-inside: |
1908
+ import ldap
1909
+ ...
1910
+ - pattern-inside: |
1911
+ from ldap3 import $NAME
1912
+ ...
1913
+ - pattern-inside: |
1914
+ from ldap import $NAME
1915
+ ...
1916
+ - focus-metavariable: $FILTER
1917
+
1918
+ - id: codewatch.python.web.nosql-injection
1919
+ mode: taint
1920
+ languages: [python]
1921
+ severity: ERROR
1922
+ message: >-
1923
+ Data from the HTTP request becomes part of a NoSQL query's syntax. In a MongoDB filter a JSON value can be an
1924
+ object such as {"$ne": null} instead of a string and change what the query matches; in $where it runs as
1925
+ JavaScript on the database server; in a DynamoDB expression string it can name other attributes and
1926
+ conditions. Convert JSON values to the type expected (str(), int(), ObjectId()) or validate the body with a
1927
+ schema, keep request data out of $where, and give DynamoDB values through ExpressionAttributeValues or
1928
+ boto3.dynamodb.conditions Key()/Attr().
1929
+ metadata:
1930
+ category: security
1931
+ subcategory: [vuln]
1932
+ type: vulnerability
1933
+ title: Request data in NoSQL query syntax
1934
+ cwe: ["CWE-943: Improper Neutralization of Special Elements in Data Query Logic"]
1935
+ owasp: ["A05:2025 - Injection"]
1936
+ references:
1937
+ - https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html
1938
+ - https://www.mongodb.com/docs/manual/reference/operator/query/where/
1939
+ - https://boto3.amazonaws.com/v1/documentation/api/latest/guide/dynamodb.html#querying-and-scanning
1940
+ pattern-sources:
1941
+ - pattern-either: *web-sources
1942
+ # A parsed JSON body is the only request data that can be an object or a list: query strings, form fields
1943
+ # and headers are always text, so {"name": request.args["name"]} can't carry an operator.
1944
+ - label: JSON
1945
+ pattern-either:
1946
+ - pattern: flask.request.get_json(...)
1947
+ - pattern: flask.request.json
1948
+ - pattern: request.get_json(...)
1949
+ - pattern: request.json
1950
+ - pattern: req.get_json(...)
1951
+ - pattern: request.json()
1952
+ - pattern: json.loads(<... request ...>)
1953
+ - pattern: json.loads(<... self.request ...>)
1954
+ # Django REST framework's parsed body.
1955
+ - patterns:
1956
+ - pattern-either:
1957
+ - pattern: request.data
1958
+ - pattern: self.request.data
1959
+ - pattern-either:
1960
+ - pattern-inside: |
1961
+ class $VIEW(..., $BASE, ...):
1962
+ ...
1963
+ - pattern-inside: |
1964
+ @api_view(...)
1965
+ def $FUNC(...):
1966
+ ...
1967
+ - pattern-inside: |
1968
+ @rest_framework.decorators.api_view(...)
1969
+ def $FUNC(...):
1970
+ ...
1971
+ - metavariable-regex: {metavariable: $BASE, regex: '(APIView|ViewSet|ViewSetMixin)$'}
1972
+ pattern-propagators: *propagators
1973
+ pattern-sanitizers:
1974
+ - *validated-guard
1975
+ - *prefix-guard
1976
+ - *checked-inside
1977
+ - *known-safe
1978
+ - *lookup-result
1979
+ - patterns:
1980
+ - pattern-either:
1981
+ - pattern: str(...)
1982
+ - pattern: int(...)
1983
+ - pattern: float(...)
1984
+ - pattern: bool(...)
1985
+ - pattern: ObjectId(...)
1986
+ - pattern: bson.ObjectId(...)
1987
+ - pattern: bson.objectid.ObjectId(...)
1988
+ - pattern: uuid.UUID(...)
1989
+ # A schema or model that checks the body's types: marshmallow's load(), pydantic's model_validate().
1990
+ - pattern: $SCHEMA.load(...)
1991
+ - pattern: $MODEL.model_validate(...)
1992
+ - pattern: $MODEL.parse_obj(...)
1993
+ # boto3's condition builders send the value as an expression attribute value, never as syntax:
1994
+ # Attr("owner").eq(name) & Key("pk").begins_with(prefix).
1995
+ - patterns:
1996
+ - pattern-either:
1997
+ - pattern: $COND(...).$OP(...)
1998
+ - pattern: $COND(...)
1999
+ - metavariable-regex: {metavariable: $COND, regex: '^(boto3\.dynamodb\.conditions\.)?(Key|Attr)$'}
2000
+ - patterns:
2001
+ - pattern: $X
2002
+ - pattern-inside: |
2003
+ if isinstance($X, str):
2004
+ ...
2005
+ pattern-sinks:
2006
+ # Operators come only from a JSON body: a filter (or pipeline) given to a MongoDB collection method.
2007
+ - requires: JSON
2008
+ patterns:
2009
+ - pattern-either:
2010
+ - pattern: $COLL.$METHOD($QUERY, ...)
2011
+ - pattern: $COLL.$METHOD(..., filter=$QUERY, ...)
2012
+ - metavariable-regex:
2013
+ metavariable: $COLL
2014
+ # mongo.db.users, db["users"], self.collection, users_collection: named for a database or a
2015
+ # collection, so BeautifulSoup's soup.find() and str.find() don't match.
2016
+ regex: '(?i)^((.*\.)?(db|mongo|database)(\.\w+|\[[^\]]+\])|(.*\.)?\w*(collection|coll|_col)s?)$'
2017
+ - metavariable-regex:
2018
+ metavariable: $METHOD
2019
+ regex: '^(find|find_one|find_one_and_update|find_one_and_delete|find_one_and_replace|update_one|update_many|replace_one|delete_one|delete_many|count_documents|aggregate)$'
2020
+ - pattern-not: '$COLL.$METHOD({..., "$where": $W, ...}, ...)'
2021
+ - focus-metavariable: $QUERY
2022
+ # $where runs as JavaScript on the database server, so request text in it is code whatever its type.
2023
+ - patterns:
2024
+ - pattern: '{..., "$where": $CODE, ...}'
2025
+ - focus-metavariable: $CODE
2026
+ # DynamoDB expressions and PartiQL statements are syntax; values belong in ExpressionAttributeValues or
2027
+ # Parameters (SecurityEval CWE-943 sonar_1: FilterExpression=username + " = :u AND password = :p").
2028
+ - patterns:
2029
+ - pattern: $CLIENT.$METHOD(..., $KW=$EXPR, ...)
2030
+ - metavariable-regex:
2031
+ metavariable: $KW
2032
+ regex: '^(FilterExpression|KeyConditionExpression|ConditionExpression|UpdateExpression|ProjectionExpression|Statement)$'
2033
+ - focus-metavariable: $EXPR
2034
+
2035
+ - id: codewatch.python.web.open-redirect
2036
+ mode: taint
2037
+ languages: [python]
2038
+ severity: WARNING
2039
+ message: >-
2040
+ Data from the HTTP request decides where the user is redirected, so a link to this site can forward
2041
+ users to any other site. Redirect only to relative paths or an allowlist of hosts
2042
+ (Django: url_has_allowed_host_and_scheme).
2043
+ metadata:
2044
+ category: security
2045
+ subcategory: [vuln]
2046
+ type: vulnerability
2047
+ title: Request data used as a redirect target
2048
+ cwe: ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"]
2049
+ owasp: ["A01:2025 - Broken Access Control"]
2050
+ references:
2051
+ - https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html
2052
+ - https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.http.url_has_allowed_host_and_scheme
2053
+ pattern-sources: *web-sources
2054
+ pattern-propagators: *propagators
2055
+ pattern-sanitizers:
2056
+ - *validated-guard
2057
+ - *prefix-guard
2058
+ - *checked-inside
2059
+ - *checked-or-replaced
2060
+ - *known-safe
2061
+ - *lookup-result
2062
+ # Back to the page the user came from: only the site that linked here chose it, so it can't send anyone
2063
+ # anywhere they weren't already.
2064
+ - pattern-either:
2065
+ - pattern: $REQ.referrer
2066
+ - pattern: $REQ.headers.get("Referer", ...)
2067
+ - pattern: $REQ.META.get("HTTP_REFERER", ...)
2068
+ # The app's own root (scheme and Host): a link can't change the Host header (GHSA-g3cm-qg2v-2hj5, pyload,
2069
+ # urljoin(request.url_root, url_for(...))).
2070
+ - patterns:
2071
+ - pattern-either:
2072
+ - pattern: $REQ.url_root
2073
+ - pattern: $REQ.host_url
2074
+ - pattern: $REQ.build_absolute_uri("/")
2075
+ - metavariable-regex: {metavariable: $REQ, regex: '^((flask\.)?request|self\.request)$'}
2076
+ # The request's own path stays on this site unless it starts with "//"; open-redirect-path covers that.
2077
+ - &request-path
2078
+ pattern-either:
2079
+ - pattern: request.path
2080
+ - pattern: request.path_info
2081
+ - pattern: request.full_path
2082
+ - pattern: request.get_full_path(...)
2083
+ - pattern: request.get_full_path_info(...)
2084
+ - pattern: flask.request.path
2085
+ - pattern: flask.request.full_path
2086
+ # Added after "?", "#" or "&", a value can change the query or fragment but not where the link goes.
2087
+ - pattern-either:
2088
+ - pattern: '"=~/^[?#\x26]/" % $X'
2089
+ - pattern: '"=~/^[?#\x26]/" + $X'
2090
+ - pattern: '"=~/^[?#\x26]/".format(...)'
2091
+ - pattern: urllib.parse.urlencode(...)
2092
+ # A route's own URL with more text after it stays on this site when that text starts with something other
2093
+ # than "/" (reverse("index") is "/", and "/" + "/evil.example" would leave): recipes'
2094
+ # build_absolute_uri(request, reverse("index")) + f"recipe/{pk}" and reverse("login") + "?next=" + path.
2095
+ - patterns:
2096
+ - pattern-either:
2097
+ - pattern: $BASE + $REST
2098
+ - pattern: $BASE + $REST + $MORE
2099
+ - metavariable-pattern:
2100
+ metavariable: $BASE
2101
+ pattern-either:
2102
+ - pattern: reverse(...)
2103
+ - pattern: django.urls.reverse(...)
2104
+ - pattern: url_for(...)
2105
+ - pattern: flask.url_for(...)
2106
+ - patterns:
2107
+ - pattern-either:
2108
+ - pattern: $BUILD(..., reverse(...), ...)
2109
+ - pattern: $BUILD(..., django.urls.reverse(...), ...)
2110
+ - metavariable-regex: {metavariable: $BUILD, regex: '^(.*\.)?build_absolute_uri$'}
2111
+ - metavariable-regex: {metavariable: $REST, regex: '^f?[''"][^/\\''"{]'}
2112
+ # The mount point the server was configured with (SCRIPT_NAME), not something a link can set.
2113
+ - pattern: request.script_root
2114
+ - pattern: flask.request.script_root
2115
+ # A model looked up by the value: redirect() sends the user to the stored object's own URL.
2116
+ - pattern: $MODEL.objects.$QUERY(...)
2117
+ # A project helper that returns only a URL it found safe (flaskbb: get_first_safe_redirect_url(next, ...,
2118
+ # allowed_hosts=...) returns the candidate when its host is allowed, else the fallback).
2119
+ # A leading underscore only makes it private: _safe_next_url(next) (MISP website GHSA-jwxw at its fix),
2120
+ # _safe_redirect(past) (araa-search bda4154bfac3).
2121
+ - patterns:
2122
+ - pattern: $SAFE(...)
2123
+ - metavariable-regex: {metavariable: $SAFE, regex: '(?i)^(.*\.)?_*(\w+_)?safe_(\w+_)?(url|redirect|next|target)$'}
2124
+ # python3-saml's login()/logout() return the identity provider's URL from the SAML settings; return_to only
2125
+ # goes into its RelayState, which the assertion consumer redirects to later (MobSF GHSA-8m9j at its fix:
2126
+ # redirect(auth.login(return_to=redirect_url)), auth from init_saml_auth(req) built of the request).
2127
+ - patterns:
2128
+ - pattern-either:
2129
+ - pattern: $AUTH.login(...)
2130
+ - pattern: $AUTH.logout(...)
2131
+ - pattern-either:
2132
+ - pattern-inside: |
2133
+ $AUTH = onelogin.saml2.auth.OneLogin_Saml2_Auth(...)
2134
+ ...
2135
+ - patterns:
2136
+ - pattern-inside: |
2137
+ $AUTH = $INIT(...)
2138
+ ...
2139
+ - metavariable-regex: {metavariable: $INIT, regex: '(?i)^(\w+\.)?_*(init|get|make|build|create)_saml2?_auth$'}
2140
+ pattern-sinks: &redirect-sinks
2141
+ - patterns:
2142
+ - pattern-either:
2143
+ - pattern: flask.redirect($URL, ...)
2144
+ - pattern: redirect($URL, ...)
2145
+ # Called through its module: `from django import shortcuts` then shortcuts.redirect(next)
2146
+ # (Horizon GHSA-j72v-mpwp-rg79, PLAN.md step 128).
2147
+ - pattern: django.shortcuts.redirect($URL, ...)
2148
+ - pattern: django.http.HttpResponseRedirect($URL, ...)
2149
+ - pattern: django.http.HttpResponsePermanentRedirect($URL, ...)
2150
+ - pattern: starlette.responses.RedirectResponse($URL, ...)
2151
+ - focus-metavariable: $URL
2152
+ - patterns:
2153
+ - pattern-either:
2154
+ - pattern: $RESP.headers[$NAME] = $URL
2155
+ - pattern: $RESP[$NAME] = $URL
2156
+ - pattern: $HEADERS.add($NAME, $URL, ...)
2157
+ - pattern: $HEADERS.set($NAME, $URL, ...)
2158
+ - pattern: $HEADERS.setdefault($NAME, $URL)
2159
+ - metavariable-regex: {metavariable: $NAME, regex: '(?i)^[''"]location[''"]$'}
2160
+ - focus-metavariable: $URL
2161
+ - patterns:
2162
+ - pattern-either:
2163
+ - pattern: '$RESPONSE(..., headers={..., $NAME: $URL, ...}, ...)'
2164
+ - metavariable-regex: {metavariable: $NAME, regex: '(?i)^[''"]location[''"]$'}
2165
+ - focus-metavariable: $URL
2166
+
2167
+ - id: codewatch.python.web.trust-boundary
2168
+ mode: taint
2169
+ languages: [python]
2170
+ severity: WARNING
2171
+ message: >-
2172
+ Unvalidated data from the HTTP request is stored in the server-side session, where later code will trust it.
2173
+ Validate it (type, range, allowlist) before storing it.
2174
+ metadata:
2175
+ category: security
2176
+ subcategory: [vuln]
2177
+ type: vulnerability
2178
+ title: Request data stored in the session unvalidated
2179
+ cwe: ["CWE-501: Trust Boundary Violation"]
2180
+ owasp: ["A06:2025 - Insecure Design"]
2181
+ references:
2182
+ - https://cwe.mitre.org/data/definitions/501.html
2183
+ - https://flask.palletsprojects.com/en/stable/api/#sessions
2184
+ pattern-sources: *web-sources
2185
+ pattern-propagators: *propagators
2186
+ pattern-sanitizers:
2187
+ - *validated-guard
2188
+ - *prefix-guard
2189
+ - *checked-inside
2190
+ - *known-safe
2191
+ - *lookup-result
2192
+ # What a login or verification call returns is the checked identity, not the raw request value.
2193
+ - patterns:
2194
+ - pattern: $AUTH(...)
2195
+ - metavariable-regex: {metavariable: $AUTH, regex: '(?i)(.*\.)?(login|authenticate|verify_\w{1,30}|check_password)$'}
2196
+ # A record's id and a hash or signature are the server's values, whatever the request said: CTFd's
2197
+ # login_user(user) stores user.id and hmac(user.password) for a user just created from the sign-up form.
2198
+ - patterns:
2199
+ - pattern-either:
2200
+ - pattern: $OBJ.id
2201
+ - pattern: $OBJ.pk
2202
+ - metavariable-regex: {metavariable: $OBJ, regex: '^(?!((flask\.)?request|self\.request)(\.|$))[\w.]+$'}
2203
+ - patterns:
2204
+ - pattern: $HASH(...)
2205
+ - metavariable-regex:
2206
+ metavariable: $HASH
2207
+ regex: '(?i)^(.*\.)?(hmac|hash\w*|\w+_hash|\w*digest|sha\d+|md5|blake2\w|sign|sign_\w+)$'
2208
+ # A row looked up by a request value is the database's record, not the request's (GHSA-9x43-5qcq-h79q,
2209
+ # Grappelli: the switched-from user's id and name).
2210
+ - pattern: get_object_or_404(...)
2211
+ - patterns:
2212
+ - pattern-either:
2213
+ - pattern: $MODEL.objects.$QUERY(...)
2214
+ - pattern: $MODEL.query.$QUERY(...)
2215
+ - metavariable-regex: {metavariable: $QUERY, regex: '^(get|filter|first|get_or_404|first_or_404|one|one_or_none|filter_by)$'}
2216
+ pattern-sinks:
2217
+ - patterns:
2218
+ - pattern-either: &session-store
2219
+ - pattern: flask.session[$KEY] = $VALUE
2220
+ - pattern: session[$KEY] = $VALUE
2221
+ - pattern: $REQ.session[$KEY] = $VALUE
2222
+ # A key with a fixed prefix (f"player_{code}") can't name another entry, such as the logged-in user's.
2223
+ - metavariable-regex: {metavariable: $KEY, regex: '^(?![rbuf]*[''"][^''"{]+)'}
2224
+ - focus-metavariable: $KEY
2225
+ - patterns:
2226
+ - pattern-either: *session-store
2227
+ - focus-metavariable: $VALUE
2228
+
2229
+ - id: codewatch.python.web.unsafe-deserialization
2230
+ mode: taint
2231
+ languages: [python]
2232
+ severity: ERROR
2233
+ message: >-
2234
+ Data from the HTTP request is deserialized with a loader that can run code (pickle, marshal, yaml.load
2235
+ without SafeLoader). Use JSON or yaml.safe_load for untrusted data.
2236
+ metadata:
2237
+ category: security
2238
+ subcategory: [vuln]
2239
+ type: vulnerability
2240
+ title: Request data deserialized unsafely
2241
+ cwe: ["CWE-502: Deserialization of Untrusted Data"]
2242
+ owasp: ["A08:2025 - Software or Data Integrity Failures"]
2243
+ references:
2244
+ - https://docs.python.org/3/library/pickle.html
2245
+ - https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html
2246
+ pattern-sources: *web-sources
2247
+ pattern-propagators: *propagators
2248
+ pattern-sanitizers:
2249
+ - *validated-guard
2250
+ - *prefix-guard
2251
+ - *checked-inside
2252
+ - *known-safe
2253
+ - *lookup-result
2254
+ pattern-sinks:
2255
+ - patterns:
2256
+ - pattern-either:
2257
+ - pattern: pickle.loads($DATA, ...)
2258
+ - pattern: pickle.load($DATA, ...)
2259
+ - pattern: _pickle.loads($DATA, ...)
2260
+ - pattern: marshal.loads($DATA, ...)
2261
+ - pattern: shelve.open($DATA, ...)
2262
+ - pattern: jsonpickle.decode($DATA, ...)
2263
+ - pattern: dill.loads($DATA, ...)
2264
+ # cloudpickle's loads is pickle's (fugue's RPC server, GHSA-xv5p-fjw5-vrj6).
2265
+ - pattern: cloudpickle.loads($DATA, ...)
2266
+ - pattern: cloudpickle.load($DATA, ...)
2267
+ - patterns:
2268
+ - pattern: yaml.load($DATA, ...)
2269
+ - pattern-not: yaml.load($DATA, Loader=yaml.SafeLoader, ...)
2270
+ - pattern-not: yaml.load($DATA, Loader=yaml.CSafeLoader, ...)
2271
+ - pattern: yaml.unsafe_load($DATA, ...)
2272
+ - focus-metavariable: $DATA
2273
+
2274
+ - id: codewatch.python.web.weak-random-token
2275
+ mode: taint
2276
+ languages: [python]
2277
+ severity: WARNING
2278
+ message: >-
2279
+ A value from the non-cryptographic `random` module is used as a session or cookie value, so it can be
2280
+ predicted. Use the `secrets` module (secrets.token_urlsafe(), secrets.randbelow()).
2281
+ metadata:
2282
+ category: security
2283
+ subcategory: [vuln]
2284
+ type: vulnerability
2285
+ title: Predictable random value used as a token
2286
+ cwe: ["CWE-330: Use of Insufficiently Random Values"]
2287
+ owasp: ["A04:2025 - Cryptographic Failures"]
2288
+ references:
2289
+ - https://docs.python.org/3/library/random.html
2290
+ - https://docs.python.org/3/library/secrets.html
2291
+ pattern-sources:
2292
+ - patterns:
2293
+ - pattern: random.$FUNC(...)
2294
+ - metavariable-regex: {metavariable: $FUNC, regex: '^(?!SystemRandom$)\w{1,40}$'}
2295
+ pattern-propagators: *propagators
2296
+ pattern-sanitizers:
2297
+ - *validated-guard
2298
+ - *prefix-guard
2299
+ - *checked-inside
2300
+ - *known-safe
2301
+ - *lookup-result
2302
+ pattern-sinks:
2303
+ - patterns:
2304
+ - pattern-either:
2305
+ - pattern: $RESP.set_cookie($NAME, $VALUE, ...)
2306
+ - pattern: flask.session[$KEY] = $VALUE
2307
+ - pattern: session[$KEY] = $VALUE
2308
+ # request.session, self.session; not any dict (game['questions'] = ...).
2309
+ - patterns:
2310
+ - pattern: $SESSION[$KEY] = $VALUE
2311
+ - metavariable-regex: {metavariable: $SESSION, regex: '(?i)^(.*\.)?\w*session$'}
2312
+ - focus-metavariable: $VALUE
2313
+
2314
+ - id: codewatch.python.weak-hash
2315
+ languages: [python]
2316
+ severity: WARNING
2317
+ message: >-
2318
+ MD4, MD5 and SHA-1 are broken for security use. Use SHA-256 or better, or a password hash
2319
+ (hashlib.scrypt, argon2, Django's password hashers) for passwords. If this hash isn't used for security,
2320
+ pass usedforsecurity=False.
2321
+ metadata:
2322
+ category: security
2323
+ subcategory: [vuln]
2324
+ type: vulnerability
2325
+ title: Weak hash algorithm
2326
+ security-purpose: required
2327
+ cwe: ["CWE-328: Use of Weak Hash"]
2328
+ owasp: ["A04:2025 - Cryptographic Failures"]
2329
+ references:
2330
+ - https://docs.python.org/3/library/hashlib.html
2331
+ - https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
2332
+ patterns:
2333
+ - pattern-either:
2334
+ - pattern: hashlib.md5(...)
2335
+ - pattern: hashlib.sha1(...)
2336
+ # Matches the value, so hashlib.new(ALGORITHM) with ALGORITHM = "sha1" counts too.
2337
+ - pattern: hashlib.new("=~/(?i)^(md4|md5|sha1|sha-1|md5-sha1|ripemd160)$/", ...)
2338
+ - pattern-not: hashlib.$F(..., usedforsecurity=False, ...)
2339
+
2340
+ - id: codewatch.python.insecure-cookie
2341
+ languages: [python]
2342
+ severity: WARNING
2343
+ message: >-
2344
+ This cookie can be sent over plain HTTP, where it can be intercepted. Set secure=True
2345
+ (and httponly=True unless JavaScript needs it).
2346
+ metadata:
2347
+ category: security
2348
+ subcategory: [vuln]
2349
+ type: vulnerability
2350
+ title: Cookie without the Secure flag
2351
+ cwe: ["CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute"]
2352
+ owasp: ["A02:2025 - Security Misconfiguration"]
2353
+ references:
2354
+ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies
2355
+ - https://flask.palletsprojects.com/en/stable/api/#flask.Response.set_cookie
2356
+ patterns:
2357
+ # No secure= at all, or a literal False. A variable (secure=settings.SESSION_COOKIE_SECURE) is the
2358
+ # deployment's choice, not something the code got wrong (CTFd's session interface).
2359
+ - pattern-either:
2360
+ - patterns:
2361
+ - pattern: $RESP.set_cookie(...)
2362
+ - pattern-not: $RESP.set_cookie(..., secure=$SECURE, ...)
2363
+ - pattern: $RESP.set_cookie(..., secure=False, ...)
2364
+ - pattern-not: $RESP.delete_cookie(...)
2365
+ # Clearing a cookie (empty value, already expired) sends nothing worth intercepting.
2366
+ - pattern-not: $RESP.set_cookie($NAME, "", ...)
2367
+ - pattern-not: $RESP.set_cookie(..., expires=0, ...)
2368
+ - pattern-not: $RESP.set_cookie(..., max_age=0, ...)
2369
+
2370
+ - id: codewatch.python.xml-external-entities
2371
+ languages: [python]
2372
+ severity: ERROR
2373
+ message: >-
2374
+ External entity resolution is switched on for this XML parser, so if it ever parses a document someone else
2375
+ wrote, that document can read local files or make network requests (XXE). Leave it off, or parse untrusted
2376
+ XML with defusedxml.
2377
+ metadata:
2378
+ category: security
2379
+ subcategory: [audit]
2380
+ type: security_hotspot
2381
+ title: XML external entities enabled
2382
+ cwe: ["CWE-611: Improper Restriction of XML External Entity Reference"]
2383
+ owasp: ["A02:2025 - Security Misconfiguration"]
2384
+ references:
2385
+ - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
2386
+ - https://docs.python.org/3/library/xml.html#xml-vulnerabilities
2387
+ pattern-either:
2388
+ - pattern: $P.setFeature(xml.sax.handler.feature_external_ges, True)
2389
+ - pattern: $P.setFeature(xml.sax.handler.feature_external_pes, True)
2390
+ - pattern: lxml.etree.XMLParser(..., resolve_entities=True, ...)
2391
+ - pattern: lxml.etree.XMLParser(..., no_network=False, ...)
2392
+
2393
+ - id: codewatch.python.web.xxe
2394
+ mode: taint
2395
+ languages: [python]
2396
+ severity: ERROR
2397
+ message: >-
2398
+ Request data is parsed as XML by a parser that resolves external entities (switched on, or lxml's default
2399
+ before 5.0), so a crafted document can read local files or make network requests (XXE). Turn entity
2400
+ resolution off (XMLParser(resolve_entities=False)), or parse with defusedxml.
2401
+ metadata:
2402
+ category: security
2403
+ subcategory: [vuln]
2404
+ type: vulnerability
2405
+ title: Request data parsed with XML external entities enabled
2406
+ cwe: ["CWE-611: Improper Restriction of XML External Entity Reference"]
2407
+ owasp: ["A02:2025 - Security Misconfiguration"]
2408
+ references:
2409
+ - https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
2410
+ - https://docs.python.org/3/library/xml.html#xml-vulnerabilities
2411
+ pattern-sources: *web-sources
2412
+ pattern-propagators: *propagators
2413
+ pattern-sanitizers:
2414
+ - *validated-guard
2415
+ - *prefix-guard
2416
+ - *checked-inside
2417
+ - *known-safe
2418
+ - *lookup-result
2419
+ pattern-sinks:
2420
+ - patterns:
2421
+ - pattern-either:
2422
+ - pattern-inside: |
2423
+ $P.setFeature(xml.sax.handler.feature_external_ges, True)
2424
+ ...
2425
+ - pattern-inside: |
2426
+ $P.setFeature(xml.sax.handler.feature_external_pes, True)
2427
+ ...
2428
+ - pattern-inside: |
2429
+ $P = lxml.etree.XMLParser(..., resolve_entities=True, ...)
2430
+ ...
2431
+ - pattern-inside: |
2432
+ $P = lxml.etree.XMLParser(..., no_network=False, ...)
2433
+ ...
2434
+ - pattern-either:
2435
+ - pattern: xml.dom.minidom.parseString($DATA, $P, ...)
2436
+ - pattern: xml.dom.minidom.parse($DATA, $P, ...)
2437
+ - pattern: xml.dom.pulldom.parseString($DATA, $P, ...)
2438
+ - pattern: xml.sax.parseString($DATA, ...)
2439
+ - pattern: $P.parse($DATA, ...)
2440
+ - pattern: $P.feed($DATA)
2441
+ - pattern: lxml.etree.fromstring($DATA, $P, ...)
2442
+ - pattern: lxml.etree.fromstring($DATA, parser=$P, ...)
2443
+ - pattern: lxml.etree.XML($DATA, $P, ...)
2444
+ - pattern: lxml.etree.XML($DATA, parser=$P, ...)
2445
+ - pattern: lxml.etree.parse($DATA, $P, ...)
2446
+ - pattern: lxml.etree.parse($DATA, parser=$P, ...)
2447
+ - focus-metavariable: $DATA
2448
+ # lxml's default parser resolved external entities until 5.0, and which lxml is installed isn't visible here.
2449
+ - patterns:
2450
+ - pattern-either:
2451
+ - pattern: lxml.etree.fromstring($DATA)
2452
+ - pattern: lxml.etree.XML($DATA)
2453
+ - pattern: lxml.etree.parse($DATA)
2454
+ - focus-metavariable: $DATA
2455
+
2456
+ - id: codewatch.python.template-autoescape-disabled
2457
+ languages: [python]
2458
+ severity: ERROR
2459
+ message: >-
2460
+ HTML escaping is switched off for every template this environment renders, so any request data a template
2461
+ prints becomes markup and script (XSS). Use autoescape=True or jinja2.select_autoescape(), and mark the few
2462
+ trusted fragments safe one by one.
2463
+ metadata:
2464
+ category: security
2465
+ subcategory: [vuln]
2466
+ type: vulnerability
2467
+ title: Template auto-escaping disabled
2468
+ cwe: ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"]
2469
+ owasp: ["A05:2025 - Injection"]
2470
+ references:
2471
+ - https://jinja.palletsprojects.com/en/stable/api/#autoescaping
2472
+ - https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
2473
+ # Only an explicit autoescape=False for HTML: a bare jinja2.Environment() is also used for SQL, config and code
2474
+ # generation, where escaping would be wrong (bandit B701 still lists those for review).
2475
+ pattern-either:
2476
+ - pattern: aiohttp_jinja2.setup(..., autoescape=False, ...)
2477
+ - pattern: $APP.jinja_env.autoescape = False
2478
+ - pattern: '$APP.jinja_options = {..., "autoescape": False, ...}'
2479
+ - patterns:
2480
+ - pattern: jinja2.Environment(..., autoescape=False, ...)
2481
+ - pattern-either:
2482
+ - pattern: jinja2.Environment(..., loader=$LOADER, ...)
2483
+ - metavariable-pattern:
2484
+ metavariable: $LOADER
2485
+ pattern-either:
2486
+ - pattern: jinja2.PackageLoader(...)
2487
+ - pattern: jinja2.FileSystemLoader(...)
2488
+ # Templates kept in a folder named for prompts, SQL or plain text aren't HTML (paperless-ngx: LLM prompts
2489
+ # from PackageLoader("paperless_ai", "prompts")).
2490
+ - metavariable-regex:
2491
+ metavariable: $LOADER
2492
+ regex: '^(?![^)]*(?i:prompt|sql|quer(y|ies)|txt|plain|markdown|yaml|codegen))'
2493
+
2494
+ - id: codewatch.python.web.ssrf
2495
+ mode: taint
2496
+ languages: [python]
2497
+ severity: ERROR
2498
+ message: >-
2499
+ Data from the HTTP request decides which URL the server fetches, so a user can make it call internal
2500
+ services or cloud metadata endpoints (SSRF). Build the URL from a fixed scheme and host, or check the host
2501
+ against an allowlist.
2502
+ metadata:
2503
+ category: security
2504
+ subcategory: [vuln]
2505
+ type: vulnerability
2506
+ title: Request data used as a URL the server fetches
2507
+ cwe: ["CWE-918: Server-Side Request Forgery (SSRF)"]
2508
+ owasp: ["A01:2025 - Broken Access Control"]
2509
+ references:
2510
+ - https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
2511
+ pattern-sources: *web-sources
2512
+ pattern-propagators: *propagators
2513
+ pattern-sanitizers:
2514
+ - *validated-guard
2515
+ - *prefix-guard
2516
+ - *checked-inside
2517
+ - *checked-or-replaced
2518
+ - *known-safe
2519
+ - *lookup-result
2520
+ # Only the path or query is user data when the scheme and host are fixed in front of it.
2521
+ - patterns:
2522
+ - pattern-either:
2523
+ - pattern: '"$PREFIX" + $X'
2524
+ - pattern: '"$PREFIX" % $X'
2525
+ - pattern: '"$PREFIX".format(...)'
2526
+ - metavariable-regex: {metavariable: $PREFIX, regex: '^[''"]?https?://[^/''"{%]+/'}
2527
+ - patterns:
2528
+ - pattern: $URL
2529
+ - metavariable-pattern:
2530
+ metavariable: $URL
2531
+ patterns:
2532
+ - pattern: f"..."
2533
+ - pattern-regex: '^f[''"]https?://[^/{''"]+/'
2534
+ # The same, with the fixed start kept in a field by __init__: `self.api_url = "https://api.github.com/{}"`,
2535
+ # then `self.api_url.format(uri_path)` (taiga's GithubClient.get, reached once receivers of a project class
2536
+ # were connected).
2537
+ - patterns:
2538
+ - pattern-inside: |
2539
+ class $HOLDER(...):
2540
+ ...
2541
+ def __init__(...):
2542
+ ...
2543
+ self.$BASE = "$PREFIX"
2544
+ ...
2545
+ ...
2546
+ - pattern-either:
2547
+ - pattern: self.$BASE.format(...)
2548
+ - pattern: self.$BASE + $REST
2549
+ - pattern: self.$BASE % $REST
2550
+ - metavariable-regex: {metavariable: $PREFIX, regex: '^https?://[^/{%]+/'}
2551
+ # A urllib Request is checked where it's built (its URL is a sink below), so what it carries on to urlopen()
2552
+ # is only its body and headers: codewatch's MCP server posts a tool's arguments as JSON to a configured host.
2553
+ # The variable, not the call, so a request URL among the call's arguments still reaches that sink.
2554
+ - patterns:
2555
+ - pattern-inside: |
2556
+ $REQ = urllib.request.Request(...)
2557
+ ...
2558
+ - pattern: $REQ
2559
+ pattern-sinks:
2560
+ - patterns:
2561
+ - pattern-either:
2562
+ - pattern: requests.$METHOD($URL, ...)
2563
+ - pattern: httpx.$METHOD($URL, ...)
2564
+ - metavariable-regex: {metavariable: $METHOD, regex: ^(get|post|put|patch|delete|head|options|stream)$}
2565
+ - focus-metavariable: $URL
2566
+ # The URL by keyword (Scout GHSA-g53g-q539-93cv: requests.request(method=request.method, url=remote_url)).
2567
+ - patterns:
2568
+ - pattern-either:
2569
+ - pattern: requests.$METHOD(..., url=$URL, ...)
2570
+ - pattern: httpx.$METHOD(..., url=$URL, ...)
2571
+ - metavariable-regex: {metavariable: $METHOD, regex: ^(get|post|put|patch|delete|head|options|stream|request)$}
2572
+ - focus-metavariable: $URL
2573
+ - patterns:
2574
+ - pattern-either:
2575
+ - pattern: requests.request($M, $URL, ...)
2576
+ - pattern: httpx.request($M, $URL, ...)
2577
+ - pattern: urllib.request.urlopen($URL, ...)
2578
+ - pattern: urllib.request.Request($URL, ...)
2579
+ - pattern: urllib.request.urlretrieve($URL, ...)
2580
+ - focus-metavariable: $URL
2581
+ # The same calls on a client or session object: `requests.Session()`, `httpx.Client()` /
2582
+ # `httpx.AsyncClient()`, made in the function (`with httpx.Client() as client:`) or kept in a field by
2583
+ # __init__, including `getattr(self._client, method)(url)` (firefighter GHSA-fqvv's HttpClient.call).
2584
+ - patterns:
2585
+ - pattern-either:
2586
+ - patterns:
2587
+ - pattern-either:
2588
+ - pattern-inside: |
2589
+ $CLIENT = $SESSION(...)
2590
+ ...
2591
+ - pattern-inside: |
2592
+ with $SESSION(...) as $CLIENT:
2593
+ ...
2594
+ - pattern-inside: |
2595
+ async with $SESSION(...) as $CLIENT:
2596
+ ...
2597
+ - pattern-either:
2598
+ - patterns:
2599
+ - pattern-either:
2600
+ - pattern: $CLIENT.$METHOD($URL, ...)
2601
+ - pattern: $CLIENT.$METHOD(..., url=$URL, ...)
2602
+ - metavariable-regex: {metavariable: $METHOD, regex: ^(get|post|put|patch|delete|head|options|stream)$}
2603
+ - pattern: $CLIENT.request($VERB, $URL, ...)
2604
+ - pattern: $CLIENT.request(..., url=$URL, ...)
2605
+ - pattern: getattr($CLIENT, $NAME)($URL, ...)
2606
+ - patterns:
2607
+ - pattern-inside: |
2608
+ class $HOLDER(...):
2609
+ ...
2610
+ def __init__(...):
2611
+ ...
2612
+ self.$FIELD = $SESSION(...)
2613
+ ...
2614
+ ...
2615
+ - pattern-either:
2616
+ - patterns:
2617
+ - pattern-either:
2618
+ - pattern: self.$FIELD.$METHOD($URL, ...)
2619
+ - pattern: self.$FIELD.$METHOD(..., url=$URL, ...)
2620
+ - metavariable-regex: {metavariable: $METHOD, regex: ^(get|post|put|patch|delete|head|options|stream)$}
2621
+ - pattern: self.$FIELD.request($VERB, $URL, ...)
2622
+ - pattern: self.$FIELD.request(..., url=$URL, ...)
2623
+ - pattern: getattr(self.$FIELD, $NAME)($URL, ...)
2624
+ - metavariable-regex: {metavariable: $SESSION, regex: '^(requests\.(Session|session)|httpx\.(Client|AsyncClient))$'}
2625
+ - focus-metavariable: $URL
2626
+
2627
+ - id: codewatch.python.web.regex-injection
2628
+ mode: taint
2629
+ languages: [python]
2630
+ severity: WARNING
2631
+ message: >-
2632
+ Data from the HTTP request is used as a regular expression, so a user can send a pattern that takes
2633
+ exponential time to match (ReDoS) or matches more than intended. Escape it with re.escape(), or match
2634
+ literally with `in`.
2635
+ metadata:
2636
+ category: security
2637
+ subcategory: [vuln]
2638
+ type: vulnerability
2639
+ title: Request data used as a regular expression
2640
+ cwe: ["CWE-730: OWASP Top Ten 2004 Category A9 - Denial of Service", "CWE-1333: Inefficient Regular Expression Complexity"]
2641
+ owasp: ["A05:2025 - Injection"]
2642
+ references:
2643
+ - https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
2644
+ pattern-sources: *web-sources
2645
+ pattern-propagators: *propagators
2646
+ pattern-sanitizers:
2647
+ - *validated-guard
2648
+ - *prefix-guard
2649
+ - *checked-inside
2650
+ - *known-safe
2651
+ - *lookup-result
2652
+ - pattern: re.escape(...)
2653
+ pattern-sinks:
2654
+ - patterns:
2655
+ - pattern-either:
2656
+ - pattern: re.$FUNC($PATTERN, ...)
2657
+ - patterns:
2658
+ - pattern: regex.$FUNC($PATTERN, ...)
2659
+ # The regex module's timeout bounds a slow pattern: a user's own pattern taken on purpose
2660
+ # (recipes' automations, regex.sub(rule[1], ..., timeout=REGEX_TIMEOUT)).
2661
+ - pattern-not: regex.$FUNC(..., timeout=$TIMEOUT, ...)
2662
+ # A compiled pattern in a variable named regex isn't the regex module: its findall(text) takes
2663
+ # the text to search, not a pattern (codewatch's own summaries.assigned_calls: `for regex in
2664
+ # regexes: regex.findall(text)`, PLAN.md step 152). Only regex.$FUNC: `regex =
2665
+ # re.compile(request_value)` is still a sink (PLAN.md step 154).
2666
+ - pattern-not-inside: |
2667
+ for regex in $ITEMS:
2668
+ ...
2669
+ - pattern-not-inside: |
2670
+ regex = $VALUE
2671
+ ...
2672
+ - pattern-not-inside: '[$X for regex in $ITEMS]'
2673
+ - pattern-not-inside: '{$X for regex in $ITEMS}'
2674
+ - pattern-not-inside: '($X for regex in $ITEMS)'
2675
+ - pattern-not-inside: '{$N for $A in $B for regex in $ITEMS for $N in $C}'
2676
+ # A compile that only checks the pattern, alone in a try: compiling doesn't backtrack, and its result is
2677
+ # dropped (paperless-ngx's validate_regex_pattern, before matching with a timeout elsewhere).
2678
+ - pattern-not-inside: |
2679
+ try:
2680
+ $LIB.compile($PATTERN, ...)
2681
+ except $ERROR:
2682
+ ...
2683
+ - pattern-not-inside: |
2684
+ try:
2685
+ $LIB.compile($PATTERN, ...)
2686
+ except $ERROR as $E:
2687
+ ...
2688
+ - metavariable-regex: {metavariable: $FUNC, regex: ^(compile|search|match|fullmatch|findall|finditer|sub|subn|split)$}
2689
+ - focus-metavariable: $PATTERN
2690
+
2691
+ - id: codewatch.python.web.log-injection
2692
+ mode: taint
2693
+ languages: [python]
2694
+ severity: INFO
2695
+ message: >-
2696
+ Data from the HTTP request is written to the log as it is, so a value with line breaks can forge log
2697
+ entries in a plain-text log. Strip or escape CR and LF first (or log repr(value)).
2698
+ # For review: whether a forged line matters depends on the log format (JSON logs escape it) and who reads it.
2699
+ metadata:
2700
+ category: security
2701
+ subcategory: [audit]
2702
+ type: security_hotspot
2703
+ title: Request data written to the log unescaped
2704
+ cwe: ["CWE-117: Improper Output Neutralization for Logs"]
2705
+ owasp: ["A09:2025 - Security Logging and Alerting Failures"]
2706
+ references:
2707
+ - https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
2708
+ pattern-sources: *web-sources
2709
+ pattern-propagators: *propagators
2710
+ pattern-sanitizers:
2711
+ - *validated-guard
2712
+ - *prefix-guard
2713
+ - *checked-inside
2714
+ - *known-safe
2715
+ - *lookup-result
2716
+ - pattern: repr(...)
2717
+ - pattern: json.dumps(...)
2718
+ - patterns:
2719
+ - pattern: $S.replace($NL, ...)
2720
+ - metavariable-regex: {metavariable: $NL, regex: '\\[rn]'}
2721
+ # The message itself, or a later argument that a %s in a literal format string inserts as it is (%r and %d
2722
+ # don't let a line break through).
2723
+ pattern-sinks:
2724
+ - patterns:
2725
+ - pattern-either:
2726
+ - pattern: logging.$LEVEL($MSG, ...)
2727
+ - patterns:
2728
+ - pattern: $LOGGER.$LEVEL($MSG, ...)
2729
+ - metavariable-regex: &logger-name {metavariable: $LOGGER, regex: '(?i)^(.*\.)?_?(log|logger|logging|\w+_log(ger)?)$'}
2730
+ - metavariable-regex: &log-level {metavariable: $LEVEL, regex: ^(debug|info|warning|warn|error|critical|exception|fatal)$}
2731
+ - focus-metavariable: $MSG
2732
+ - patterns:
2733
+ - pattern-either:
2734
+ - pattern: logging.$LEVEL("$FMT", ..., $ARG, ...)
2735
+ - patterns:
2736
+ - pattern: $LOGGER.$LEVEL("$FMT", ..., $ARG, ...)
2737
+ - metavariable-regex: *logger-name
2738
+ - metavariable-regex: *log-level
2739
+ - metavariable-regex: {metavariable: $FMT, regex: '%-?\d*s'}
2740
+ - focus-metavariable: $ARG
2741
+
2742
+ - id: codewatch.python.web.open-redirect-path
2743
+ mode: taint
2744
+ languages: [python]
2745
+ severity: INFO
2746
+ message: >-
2747
+ The redirect target is built from the request's own path. That stays on this site unless the path can
2748
+ start with "//" (a request for "//evil.example/..." becomes a redirect to another host): check that the
2749
+ URL patterns can't match such a path, or collapse repeated slashes first.
2750
+ # For review: whether "//host" can reach this view depends on the URL configuration.
2751
+ metadata:
2752
+ category: security
2753
+ subcategory: [audit]
2754
+ type: security_hotspot
2755
+ title: Redirect built from the request path
2756
+ interprocedural: false
2757
+ cwe: ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"]
2758
+ owasp: ["A01:2025 - Broken Access Control"]
2759
+ references:
2760
+ - https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html
2761
+ pattern-sources:
2762
+ - *request-path
2763
+ pattern-sanitizers:
2764
+ - *validated-guard
2765
+ - *prefix-guard
2766
+ - *checked-inside
2767
+ - *checked-or-replaced
2768
+ - *known-safe
2769
+ - *lookup-result
2770
+ - patterns:
2771
+ - pattern: re.sub($PATTERN, "/", ...)
2772
+ - metavariable-regex: {metavariable: $PATTERN, regex: '^r?[''"]/(\{2,\}|/\+|\+)[''"]$'}
2773
+ pattern-sinks: *redirect-sinks
2774
+
2775
+ - id: codewatch.python.web.unrestricted-upload
2776
+ mode: taint
2777
+ languages: [python]
2778
+ severity: WARNING
2779
+ message: >-
2780
+ An uploaded file is stored under the name the client sent, extension included, and nothing checks the
2781
+ type. An .html, .svg or script file served back from this site runs as part of it. Check the extension
2782
+ against an allowlist, or store the file under a generated name with an extension you choose.
2783
+ # For review: harmless if the folder is never served or executed; secure_filename() stops "../" only.
2784
+ metadata:
2785
+ category: security
2786
+ subcategory: [audit]
2787
+ type: security_hotspot
2788
+ title: Upload stored under the client's file name
2789
+ interprocedural: false
2790
+ cwe: ["CWE-434: Unrestricted Upload of File with Dangerous Type"]
2791
+ owasp: ["A06:2025 - Insecure Design"]
2792
+ references:
2793
+ - https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html
2794
+ - https://flask.palletsprojects.com/en/stable/patterns/fileuploads/
2795
+ pattern-sources:
2796
+ - pattern-either:
2797
+ - pattern: request.files[$KEY].filename
2798
+ - pattern: request.files.get(...).filename
2799
+ - pattern: flask.request.files[$KEY].filename
2800
+ - pattern: flask.request.files.get(...).filename
2801
+ - pattern: request.FILES[$KEY].name
2802
+ - pattern: request.FILES.get(...).name
2803
+ - patterns:
2804
+ - pattern-either:
2805
+ - pattern-inside: |
2806
+ $F = request.files[$KEY]
2807
+ ...
2808
+ - pattern-inside: |
2809
+ $F = request.files.get(...)
2810
+ ...
2811
+ - pattern-inside: |
2812
+ for $F in request.files.getlist(...):
2813
+ ...
2814
+ - pattern-inside: |
2815
+ for $F in request.files.values():
2816
+ ...
2817
+ - pattern: $F.filename
2818
+ - patterns:
2819
+ - pattern-either:
2820
+ - pattern-inside: |
2821
+ $F = request.FILES[$KEY]
2822
+ ...
2823
+ - pattern-inside: |
2824
+ $F = request.FILES.get(...)
2825
+ ...
2826
+ - pattern-inside: |
2827
+ for $F in request.FILES.getlist(...):
2828
+ ...
2829
+ - pattern: $F.name
2830
+ # FastAPI / Starlette: def upload(file: UploadFile = File(...))
2831
+ - patterns:
2832
+ - pattern-either:
2833
+ - pattern-inside: |
2834
+ def $H(..., $F: UploadFile, ...):
2835
+ ...
2836
+ - pattern-inside: |
2837
+ async def $H(..., $F: UploadFile, ...):
2838
+ ...
2839
+ - pattern-inside: |
2840
+ def $H(..., $F: UploadFile = $DEFAULT, ...):
2841
+ ...
2842
+ - pattern-inside: |
2843
+ async def $H(..., $F: UploadFile = $DEFAULT, ...):
2844
+ ...
2845
+ - pattern: $F.filename
2846
+ pattern-sanitizers:
2847
+ - *known-safe
2848
+ - *lookup-result
2849
+ # Inside, or after, a check that looks at the name's extension or type: if allowed_file(f.filename): ...
2850
+ - patterns:
2851
+ - pattern-either:
2852
+ - pattern-inside: |
2853
+ if $COND:
2854
+ ...
2855
+ - pattern-inside: |
2856
+ if $COND:
2857
+ ...
2858
+ return ...
2859
+ ...
2860
+ - pattern-inside: |
2861
+ if $COND:
2862
+ ...
2863
+ raise ...
2864
+ ...
2865
+ - pattern-inside: |
2866
+ if $COND:
2867
+ ...
2868
+ abort(...)
2869
+ ...
2870
+ - metavariable-regex:
2871
+ metavariable: $COND
2872
+ regex: '(?i).*(allow|permit|valid|ext|suffix|mime|content_type|image)'
2873
+ # Only the stem kept, so the stored file gets an extension the code chose.
2874
+ - pattern: os.path.splitext(...)[0]
2875
+ - pattern: pathlib.Path(...).stem
2876
+ pattern-sinks:
2877
+ - patterns:
2878
+ - pattern-either:
2879
+ - pattern: $FILE.save($PATH, ...)
2880
+ - pattern: $STORAGE.save($PATH, ...)
2881
+ - pattern: open($PATH, "=~/[wax]/", ...)
2882
+ - pattern: open($PATH, mode="=~/[wax]/", ...)
2883
+ - pattern: aiofiles.open($PATH, "=~/[wax]/", ...)
2884
+ - pattern: shutil.copyfileobj($SRC, open($PATH, ...), ...)
2885
+ - pattern: shutil.move($SRC, $PATH)
2886
+ - pattern: shutil.copy($SRC, $PATH)
2887
+ - pattern: pathlib.Path($PATH).write_bytes(...)
2888
+ - focus-metavariable: $PATH
2889
+
2890
+ - id: codewatch.python.web.stack-trace-exposure
2891
+ mode: taint
2892
+ languages: [python]
2893
+ severity: WARNING
2894
+ message: >-
2895
+ A stack trace is sent back in the response. It shows file paths, code and sometimes data to whoever made
2896
+ the request. Log it on the server and return a generic error message instead.
2897
+ metadata:
2898
+ category: security
2899
+ subcategory: [vuln]
2900
+ type: vulnerability
2901
+ title: Stack trace sent in the response
2902
+ interprocedural: false
2903
+ cwe: ["CWE-209: Generation of Error Message Containing Sensitive Information"]
2904
+ owasp: ["A10:2025 - Mishandling of Exceptional Conditions"]
2905
+ references:
2906
+ - https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html
2907
+ pattern-sources:
2908
+ - patterns:
2909
+ - pattern-either:
2910
+ - pattern: traceback.format_exc(...)
2911
+ - pattern: traceback.format_exception(...)
2912
+ - pattern: traceback.format_tb(...)
2913
+ - pattern: traceback.format_stack(...)
2914
+ - pattern: traceback.extract_tb(...)
2915
+ - pattern-not-inside: |
2916
+ if <... $X.debug ...>:
2917
+ ...
2918
+ - pattern-not-inside: |
2919
+ if <... $X.DEBUG ...>:
2920
+ ...
2921
+ - pattern-not-inside: |
2922
+ if <... DEBUG ...>:
2923
+ ...
2924
+ pattern-sinks: &error-response-sinks
2925
+ - patterns:
2926
+ - pattern-either:
2927
+ - pattern-inside: |
2928
+ @$APP.$ROUTE(...)
2929
+ def $VIEW(...):
2930
+ ...
2931
+ - pattern-inside: |
2932
+ @$APP.$ROUTE(...)
2933
+ async def $VIEW(...):
2934
+ ...
2935
+ - metavariable-regex: {metavariable: $ROUTE, regex: ^(route|get|post|put|patch|delete|api_route|errorhandler)$}
2936
+ - pattern: return $BODY
2937
+ - focus-metavariable: $BODY
2938
+ - pattern-either:
2939
+ - pattern: flask.jsonify(...)
2940
+ - pattern: jsonify(...)
2941
+ - pattern: flask.make_response(...)
2942
+ - pattern: make_response(...)
2943
+ - pattern: flask.Response(...)
2944
+ - pattern: flask.abort(...)
2945
+ - pattern: abort(...)
2946
+ - pattern: django.http.HttpResponse(...)
2947
+ - pattern: django.http.JsonResponse(...)
2948
+ - pattern: django.http.HttpResponseServerError(...)
2949
+ - pattern: django.http.HttpResponseBadRequest(...)
2950
+ - pattern: starlette.responses.$RESPONSE(...)
2951
+ - pattern: fastapi.responses.$RESPONSE(...)
2952
+ - pattern: fastapi.HTTPException(...)
2953
+ - pattern: starlette.exceptions.HTTPException(...)
2954
+ - pattern: rest_framework.response.Response(...)
2955
+
2956
+ - id: codewatch.python.web.exception-message-in-response
2957
+ mode: taint
2958
+ languages: [python]
2959
+ severity: INFO
2960
+ message: >-
2961
+ The text of an unexpected exception is sent back in the response. Messages from databases, file and
2962
+ network errors can show queries, paths, hosts or data. Log the exception and return a generic message.
2963
+ # For review: catching Exception means the message comes from anywhere; a specific exception's message is
2964
+ # usually written for the user and isn't reported.
2965
+ metadata:
2966
+ category: security
2967
+ subcategory: [audit]
2968
+ type: security_hotspot
2969
+ title: Exception message sent in the response
2970
+ interprocedural: false
2971
+ cwe: ["CWE-209: Generation of Error Message Containing Sensitive Information"]
2972
+ owasp: ["A10:2025 - Mishandling of Exceptional Conditions"]
2973
+ references:
2974
+ - https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html
2975
+ pattern-sources:
2976
+ - patterns:
2977
+ - pattern-either:
2978
+ - pattern-inside: |
2979
+ try:
2980
+ ...
2981
+ except Exception as $E:
2982
+ ...
2983
+ - pattern-inside: |
2984
+ try:
2985
+ ...
2986
+ except BaseException as $E:
2987
+ ...
2988
+ - pattern: $E
2989
+ - pattern-not-inside: |
2990
+ if <... $X.debug ...>:
2991
+ ...
2992
+ - pattern-not-inside: |
2993
+ if <... $X.DEBUG ...>:
2994
+ ...
2995
+ - pattern-not-inside: |
2996
+ if <... DEBUG ...>:
2997
+ ...
2998
+ pattern-sanitizers:
2999
+ # The exception's class name says what failed without saying anything about the data.
3000
+ - pattern: type(...)
3001
+ - pattern: $E.__class__
3002
+ pattern-sinks: *error-response-sinks
3003
+
3004
+ - id: codewatch.python.web.mass-assignment
3005
+ languages: [python]
3006
+ severity: WARNING
3007
+ message: >-
3008
+ Every field of the request body is passed to a model, so a client can also set fields the form never
3009
+ offers (is_admin, owner, price). Pass only the fields this view should change, or load the body through a
3010
+ serializer/schema that lists them.
3011
+ # For review: fine if the model has no field a client mustn't set.
3012
+ metadata:
3013
+ category: security
3014
+ subcategory: [audit]
3015
+ type: security_hotspot
3016
+ title: Whole request body assigned to a model
3017
+ cwe: ["CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes"]
3018
+ owasp: ["A08:2025 - Software or Data Integrity Failures"]
3019
+ references:
3020
+ - https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html
3021
+ patterns:
3022
+ # The body itself, or a variable holding it: not a dict built from chosen fields of it.
3023
+ - pattern-either:
3024
+ - patterns:
3025
+ - pattern-either: &py-model-writes
3026
+ - patterns:
3027
+ - pattern-either:
3028
+ - pattern: $MODEL(..., **$DATA, ...)
3029
+ - pattern: $MODEL.objects.$CREATE(..., **$DATA, ...)
3030
+ - pattern: $MODEL.objects.$QUERY(...).update(..., **$DATA, ...)
3031
+ - metavariable-regex: {metavariable: $MODEL, regex: '^[A-Z]\w*$'}
3032
+ - pattern: $MODEL.query.$FILTER(...).update($DATA, ...)
3033
+ - pattern: |
3034
+ for $K, $V in $DATA.items():
3035
+ ...
3036
+ setattr($OBJ, $K, $V)
3037
+ - metavariable-regex: &whole-body
3038
+ metavariable: $DATA
3039
+ regex: '^(request\.(json|form|values|POST|data)|request\.(get_json|form\.to_dict|POST\.dict)\(.*\)|json\.loads\(request\.(body|data)\))$'
3040
+ - patterns:
3041
+ - pattern-either: *py-model-writes
3042
+ - pattern-inside: |
3043
+ $DATA = $BODY
3044
+ ...
3045
+ - metavariable-regex:
3046
+ <<: *whole-body
3047
+ metavariable: $BODY
3048
+ - focus-metavariable: $DATA
3049
+
3050
+ - id: codewatch.python.web.template-injection
3051
+ mode: taint
3052
+ languages: [python]
3053
+ severity: ERROR
3054
+ message: >-
3055
+ Data from the HTTP request is compiled as a template, so a user can write template code
3056
+ ({{ ''.__class__.__mro__ }}...) that runs on the server. Pass request data as a template variable,
3057
+ never as the template text; if users must write templates, use jinja2's SandboxedEnvironment.
3058
+ metadata:
3059
+ category: security
3060
+ subcategory: [vuln]
3061
+ type: vulnerability
3062
+ title: Request data compiled as a server-side template
3063
+ cwe: ["CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine"]
3064
+ owasp: ["A05:2025 - Injection"]
3065
+ references:
3066
+ - https://portswigger.net/web-security/server-side-template-injection
3067
+ - https://jinja.palletsprojects.com/en/stable/sandbox/
3068
+ pattern-sources: *web-sources
3069
+ pattern-propagators: *propagators
3070
+ pattern-sanitizers:
3071
+ - *validated-guard
3072
+ - *prefix-guard
3073
+ - *checked-inside
3074
+ - *known-safe
3075
+ - *lookup-result
3076
+ pattern-sinks:
3077
+ - patterns:
3078
+ - pattern-either:
3079
+ - pattern: jinja2.Template($TEMPLATE, ...)
3080
+ - pattern: jinja2.Environment(...).from_string($TEMPLATE, ...)
3081
+ - pattern: flask.render_template_string($TEMPLATE, ...)
3082
+ - pattern: render_template_string($TEMPLATE, ...)
3083
+ - pattern: mako.template.Template($TEMPLATE, ...)
3084
+ - pattern: django.template.Template($TEMPLATE, ...)
3085
+ - pattern: django.template.Engine(...).from_string($TEMPLATE)
3086
+ - pattern: django.template.engines[$NAME].from_string($TEMPLATE)
3087
+ - pattern: tornado.template.Template($TEMPLATE, ...)
3088
+ - patterns:
3089
+ - pattern: $ENV.from_string($TEMPLATE, ...)
3090
+ - pattern-not-inside: |
3091
+ $ENV = jinja2.sandbox.SandboxedEnvironment(...)
3092
+ ...
3093
+ - focus-metavariable: $TEMPLATE
3094
+
3095
+ - id: codewatch.python.web.cors-any-origin-with-credentials
3096
+ languages: [python]
3097
+ severity: ERROR
3098
+ message: >-
3099
+ CORS is set up to accept any origin and to allow credentials, so the library echoes back whatever
3100
+ Origin the browser sends: any website can make logged-in requests to this API and read the answers.
3101
+ List the origins that may call it.
3102
+ metadata:
3103
+ category: security
3104
+ subcategory: [vuln]
3105
+ type: vulnerability
3106
+ title: Any origin allowed together with credentials
3107
+ cwe: ["CWE-942: Permissive Cross-domain Security Policy with Untrusted Domains"]
3108
+ owasp: ["A02:2025 - Security Misconfiguration"]
3109
+ references:
3110
+ - https://portswigger.net/web-security/cors
3111
+ - https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#cross-origin-resource-sharing
3112
+ pattern-either:
3113
+ # flask-cors: origins default to "*", which it reflects when credentials are on.
3114
+ - patterns:
3115
+ - pattern-either:
3116
+ - pattern: flask_cors.CORS(..., supports_credentials=True, ...)
3117
+ - pattern: flask_cors.cross_origin(..., supports_credentials=True, ...)
3118
+ - pattern-not: flask_cors.CORS(..., origins=$ORIGINS, ...)
3119
+ - pattern-not: flask_cors.CORS(..., resources=$RESOURCES, ...)
3120
+ - pattern-not: flask_cors.cross_origin(..., origins=$ORIGINS, ...)
3121
+ - pattern: flask_cors.CORS(..., supports_credentials=True, ..., origins="*", ...)
3122
+ - pattern: flask_cors.CORS(..., origins="*", ..., supports_credentials=True, ...)
3123
+ - pattern: flask_cors.cross_origin(..., supports_credentials=True, ..., origins="*", ...)
3124
+ - pattern: flask_cors.cross_origin(..., origins="*", ..., supports_credentials=True, ...)
3125
+ # Starlette / FastAPI: allow_origins=["*"] with credentials echoes the request's Origin.
3126
+ - patterns:
3127
+ - pattern: $APP.add_middleware($MIDDLEWARE, ..., allow_credentials=True, ...)
3128
+ - pattern-either:
3129
+ - pattern: $APP.add_middleware($MIDDLEWARE, ..., allow_origins=["*"], ...)
3130
+ - pattern: $APP.add_middleware($MIDDLEWARE, ..., allow_origin_regex="=~/^\.[*+]$/", ...)
3131
+ # django-cors-headers settings.
3132
+ - patterns:
3133
+ - pattern-either:
3134
+ - pattern-inside: |
3135
+ CORS_ALLOW_CREDENTIALS = True
3136
+ ...
3137
+ - pattern-inside: |
3138
+ $ALL = True
3139
+ ...
3140
+ CORS_ALLOW_CREDENTIALS = True
3141
+ - pattern-either:
3142
+ - pattern: CORS_ALLOW_ALL_ORIGINS = True
3143
+ - pattern: CORS_ORIGIN_ALLOW_ALL = True
3144
+ # By hand: the request's Origin echoed on a response that also allows credentials.
3145
+ - patterns:
3146
+ - pattern-either:
3147
+ - pattern: |
3148
+ $RESP.headers[$ACAO] = <... $REQ.headers.get($ORIGIN, ...) ...>
3149
+ ...
3150
+ $RESP.headers[$ACAC] = $TRUE
3151
+ - pattern: |
3152
+ $RESP.headers[$ACAC] = $TRUE
3153
+ ...
3154
+ $RESP.headers[$ACAO] = <... $REQ.headers.get($ORIGIN, ...) ...>
3155
+ - pattern: |
3156
+ $RESP[$ACAO] = <... $REQ.headers.get($ORIGIN, ...) ...>
3157
+ ...
3158
+ $RESP[$ACAC] = $TRUE
3159
+ - pattern: |
3160
+ $RESP[$ACAC] = $TRUE
3161
+ ...
3162
+ $RESP[$ACAO] = <... $REQ.headers.get($ORIGIN, ...) ...>
3163
+ - metavariable-regex: {metavariable: $ACAO, regex: '(?i)^[''"]access-control-allow-origin[''"]$'}
3164
+ - metavariable-regex: {metavariable: $ACAC, regex: '(?i)^[''"]access-control-allow-credentials[''"]$'}
3165
+ - metavariable-regex: {metavariable: $ORIGIN, regex: '(?i)^[''"](http_)?origin[''"]$'}
3166
+ - metavariable-regex: {metavariable: $TRUE, regex: '(?i)^([''"]true[''"]|True)$'}
3167
+
3168
+ - id: codewatch.python.timing-unsafe-signature-check
3169
+ languages: [python]
3170
+ severity: WARNING
3171
+ message: >-
3172
+ An HMAC or signature is compared with == or !=, which stops at the first differing character: by timing
3173
+ responses an attacker can guess a valid signature byte by byte. Compare with hmac.compare_digest().
3174
+ metadata:
3175
+ category: security
3176
+ subcategory: [vuln]
3177
+ type: vulnerability
3178
+ title: Signature compared in variable time
3179
+ cwe: ["CWE-208: Observable Timing Discrepancy"]
3180
+ owasp: ["A04:2025 - Cryptographic Failures"]
3181
+ references:
3182
+ - https://docs.python.org/3/library/hmac.html#hmac.compare_digest
3183
+ patterns:
3184
+ - pattern-either:
3185
+ - pattern: $A == $B
3186
+ - pattern: $A != $B
3187
+ - pattern-either:
3188
+ - pattern: <... hmac.new(...) ...> == $B
3189
+ - pattern: $A == <... hmac.new(...) ...>
3190
+ - pattern: <... hmac.new(...) ...> != $B
3191
+ - pattern: $A != <... hmac.new(...) ...>
3192
+ - patterns:
3193
+ - pattern-inside: |
3194
+ $MAC = <... hmac.new(...) ...>
3195
+ ...
3196
+ - pattern-either:
3197
+ - pattern: $MAC == $B
3198
+ - pattern: $A == $MAC
3199
+ - pattern: $MAC != $B
3200
+ - pattern: $A != $MAC
3201
+ # Comparing lengths or against a constant (an empty value) leaks nothing about the secret.
3202
+ - pattern-not: len(...) == $B
3203
+ - pattern-not: $A == len(...)
3204
+ - pattern-not: $A == "..."
3205
+ - pattern-not: $A == None
3206
+
3207
+ - id: codewatch.python.web.route-without-login
3208
+ languages: [python]
3209
+ severity: WARNING
3210
+ message: >-
3211
+ This view accepts {POST/PUT/PATCH/DELETE} but has no login decorator, while other views in the same module
3212
+ do. Check that anonymous users may really call it; if not, add the same decorator here.
3213
+ # For review: some views are meant to be public; one missing decorator in a protected module often isn't.
3214
+ metadata:
3215
+ category: security
3216
+ subcategory: [audit]
3217
+ type: security_hotspot
3218
+ title: Changing view without the login check other views use
3219
+ cwe: ["CWE-306: Missing Authentication for Critical Function"]
3220
+ owasp: ["A07:2025 - Authentication Failures"]
3221
+ references:
3222
+ - https://flask-login.readthedocs.io/en/latest/#flask_login.login_required
3223
+ patterns:
3224
+ - pattern: |
3225
+ @$APP.$ROUTE($PATH, ..., methods=$METHODS, ...)
3226
+ def $F(...):
3227
+ ...
3228
+ - metavariable-regex: {metavariable: $ROUTE, regex: '^route$'}
3229
+ - metavariable-regex: {metavariable: $METHODS, regex: '(?i).*(post|put|patch|delete)'}
3230
+ # Sign-up as POST to the users collection is public by nature.
3231
+ - metavariable-regex: {metavariable: $PATH, regex: '^(?![''"]/(api/)?(v\d+/)?(users?|accounts?|members?)/?[''"]$)'}
3232
+ - metavariable-regex: {metavariable: $PATH, regex: '^(?!(?i:.*(login|logout|register|signup|sign_up|signin|forgot|reset|verify|confirm|activate|token|refresh|oauth|callback|webhook|public|health|status|contact|subscribe)))'}
3233
+ - pattern-not: |
3234
+ @login_required
3235
+ def $F(...):
3236
+ ...
3237
+ - pattern-not: |
3238
+ @$M.login_required
3239
+ def $F(...):
3240
+ ...
3241
+ - pattern-not: |
3242
+ @jwt_required(...)
3243
+ def $F(...):
3244
+ ...
3245
+ - pattern-not: |
3246
+ @$M.jwt_required(...)
3247
+ def $F(...):
3248
+ ...
3249
+ - pattern-not: |
3250
+ @fresh_jwt_required
3251
+ def $F(...):
3252
+ ...
3253
+ - pattern-not: |
3254
+ @roles_required(...)
3255
+ def $F(...):
3256
+ ...
3257
+ - pattern-not: |
3258
+ @roles_accepted(...)
3259
+ def $F(...):
3260
+ ...
3261
+ - pattern-not: |
3262
+ @$M.roles_required(...)
3263
+ def $F(...):
3264
+ ...
3265
+ - pattern-not: |
3266
+ @permission_required(...)
3267
+ def $F(...):
3268
+ ...
3269
+ - pattern-not: |
3270
+ @$M.permission_required(...)
3271
+ def $F(...):
3272
+ ...
3273
+ - pattern-not: |
3274
+ @admin_required
3275
+ def $F(...):
3276
+ ...
3277
+ - pattern-not: |
3278
+ @token_required
3279
+ def $F(...):
3280
+ ...
3281
+ - pattern-not: |
3282
+ @requires_auth
3283
+ def $F(...):
3284
+ ...
3285
+ - pattern-not: |
3286
+ @auth_required
3287
+ def $F(...):
3288
+ ...
3289
+ - pattern-not: |
3290
+ @$M.auth_required
3291
+ def $F(...):
3292
+ ...
3293
+ - pattern-not: |
3294
+ @auth_required(...)
3295
+ def $F(...):
3296
+ ...
3297
+ - pattern-not: |
3298
+ @$M.auth_required(...)
3299
+ def $F(...):
3300
+ ...
3301
+ - pattern-not: |
3302
+ @login_required(...)
3303
+ def $F(...):
3304
+ ...
3305
+ - pattern-not: |
3306
+ @$M.login_required(...)
3307
+ def $F(...):
3308
+ ...
3309
+ - pattern-not: |
3310
+ @$M.verify_token
3311
+ def $F(...):
3312
+ ...
3313
+ - pattern-not: |
3314
+ @$M.verify_password
3315
+ def $F(...):
3316
+ ...
3317
+ - pattern-not: |
3318
+ @$M.require(...)
3319
+ def $F(...):
3320
+ ...
3321
+ # Another view in this module has a login decorator.
3322
+ - pattern-either:
3323
+ - pattern-inside: |
3324
+ @$AUTH
3325
+ def $G(...):
3326
+ ...
3327
+ ...
3328
+ - pattern-inside: |
3329
+ @$AUTH(...)
3330
+ def $G(...):
3331
+ ...
3332
+ ...
3333
+ - pattern-inside: |
3334
+ @$APP.$ROUTE($PATH, ..., methods=$METHODS, ...)
3335
+ def $F(...):
3336
+ ...
3337
+ ...
3338
+ @$AUTH
3339
+ def $G(...):
3340
+ ...
3341
+ - pattern-inside: |
3342
+ @$APP.$ROUTE($PATH, ..., methods=$METHODS, ...)
3343
+ def $F(...):
3344
+ ...
3345
+ ...
3346
+ @$AUTH(...)
3347
+ def $G(...):
3348
+ ...
3349
+ - metavariable-regex: {metavariable: $AUTH, regex: '(?i)(.*\.)?(login_required|jwt_required|fresh_jwt_required|roles_required|roles_accepted|permission_required|admin_required|token_required|requires_auth|auth_required)$'}
3350
+ - focus-metavariable: $F
3351
+
3352
+ - id: codewatch.python.cookie-protection-off
3353
+ languages: [python]
3354
+ severity: INFO
3355
+ message: >-
3356
+ Cookie protection is switched off here: without HttpOnly any injected script can read the cookie, without
3357
+ Secure it travels over plain HTTP, and SameSite=None sends it on cross-site requests. Keep the defaults
3358
+ (HttpOnly, Secure in production, SameSite=Lax) for session and CSRF cookies.
3359
+ # For review: Secure off is common in development settings; SameSite=None is needed for some embeds.
3360
+ metadata:
3361
+ category: security
3362
+ subcategory: [audit]
3363
+ type: security_hotspot
3364
+ title: Cookie protection switched off
3365
+ cwe: ["CWE-1004: Sensitive Cookie Without 'HttpOnly' Flag", "CWE-1275: Sensitive Cookie with Improper SameSite Attribute"]
3366
+ owasp: ["A02:2025 - Security Misconfiguration"]
3367
+ references:
3368
+ - https://docs.djangoproject.com/en/stable/ref/settings/#session-cookie-httponly
3369
+ - https://flask.palletsprojects.com/en/stable/config/#SESSION_COOKIE_HTTPONLY
3370
+ pattern-either:
3371
+ - pattern: $RESP.set_cookie(..., httponly=False, ...)
3372
+ - pattern: $RESP.set_cookie(..., samesite="None", ...)
3373
+ - pattern: $RESP.set_cookie(..., samesite=None, ...)
3374
+ - patterns:
3375
+ - pattern: $SETTING = False
3376
+ - metavariable-regex: {metavariable: $SETTING, regex: '^SESSION_COOKIE_HTTPONLY$'}
3377
+ - patterns:
3378
+ - pattern: $SETTING = "None"
3379
+ - metavariable-regex: {metavariable: $SETTING, regex: '^(SESSION_COOKIE_SAMESITE|CSRF_COOKIE_SAMESITE)$'}
3380
+ - patterns:
3381
+ - pattern: $CONFIG[$SETTING] = False
3382
+ - metavariable-regex: {metavariable: $SETTING, regex: '^[''"]SESSION_COOKIE_HTTPONLY[''"]$'}