cobraphp 0.1.0.dev3__tar.gz → 0.1.0.dev4__tar.gz

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 (43) hide show
  1. {cobraphp-0.1.0.dev3/src/cobraphp.egg-info → cobraphp-0.1.0.dev4}/PKG-INFO +13 -2
  2. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/README.md +12 -1
  3. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/pyproject.toml +1 -1
  4. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/__init__.py +6 -1
  5. cobraphp-0.1.0.dev4/src/cobraphp/analysis/_database_writes.py +708 -0
  6. cobraphp-0.1.0.dev4/src/cobraphp/analysis/database_writes.toml +120 -0
  7. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4/src/cobraphp.egg-info}/PKG-INFO +13 -2
  8. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp.egg-info/SOURCES.txt +2 -0
  9. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/LICENSE +0 -0
  10. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/setup.cfg +0 -0
  11. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/__init__.py +0 -0
  12. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/_backend.py +0 -0
  13. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/_placeholder.py +0 -0
  14. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_ast_types.py +0 -0
  15. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_call_builder.py +0 -0
  16. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_call_graph.py +0 -0
  17. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_call_graph_nodes.py +0 -0
  18. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_callee_index.py +0 -0
  19. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_defuse_builder.py +0 -0
  20. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_errors.py +0 -0
  21. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_file_filter.py +0 -0
  22. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_project_root.py +0 -0
  23. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_records.py +0 -0
  24. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_semgrep_runner.py +0 -0
  25. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_source_kinds.py +0 -0
  26. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_taint_graph.py +0 -0
  27. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_taint_propagator.py +0 -0
  28. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/_taint_rules.py +0 -0
  29. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/frameworks.toml +0 -0
  30. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/php_ast_types.toml +0 -0
  31. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/rules/database_taint.yaml +0 -0
  32. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/analysis/rules/user_input_taint.yaml +0 -0
  33. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/config.py +0 -0
  34. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/entries.py +0 -0
  35. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/errors.py +0 -0
  36. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/graphs.py +0 -0
  37. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/project.py +0 -0
  38. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/py.typed +0 -0
  39. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp/results.py +0 -0
  40. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp.egg-info/dependency_links.txt +0 -0
  41. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp.egg-info/requires.txt +0 -0
  42. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/src/cobraphp.egg-info/top_level.txt +0 -0
  43. {cobraphp-0.1.0.dev3 → cobraphp-0.1.0.dev4}/tests/test_interface.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cobraphp
3
- Version: 0.1.0.dev3
3
+ Version: 0.1.0.dev4
4
4
  Summary: Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects.
5
5
  License-Expression: GPL-2.0-only
6
6
  Requires-Python: >=3.11
@@ -20,7 +20,7 @@ Python interface of [CobraPHP](https://github.com/jhu-seclab-cobra/CobraPHP), th
20
20
 
21
21
  **Placeholder.** The Python binding is not fully implemented. Interfaces and results may change between versions.
22
22
 
23
- The subpackage `cobraphp.analysis` builds a call graph and a data flow from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
23
+ The subpackage `cobraphp.analysis` builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
24
24
 
25
25
  ## Install
26
26
 
@@ -75,6 +75,17 @@ for node_id in flow.tainted[USER_INPUT]:
75
75
  print(node_id, backward_slice(flow, node_id, max_depth=3))
76
76
  ```
77
77
 
78
+ Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored:
79
+
80
+ ```python
81
+ from cobraphp.analysis import find_database_writes, reached_database_writes
82
+
83
+ writes = find_database_writes(ast)
84
+ for node_id in flow.tainted[USER_INPUT]:
85
+ for write in reached_database_writes(ast, flow, writes, node_id):
86
+ print(node_id, write.file, write.line, write.kind, write.table)
87
+ ```
88
+
78
89
  Apply the same file exclusions outside `parse_project`:
79
90
 
80
91
  ```python
@@ -6,7 +6,7 @@ Python interface of [CobraPHP](https://github.com/jhu-seclab-cobra/CobraPHP), th
6
6
 
7
7
  **Placeholder.** The Python binding is not fully implemented. Interfaces and results may change between versions.
8
8
 
9
- The subpackage `cobraphp.analysis` builds a call graph and a data flow from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
9
+ The subpackage `cobraphp.analysis` builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
10
10
 
11
11
  ## Install
12
12
 
@@ -61,6 +61,17 @@ for node_id in flow.tainted[USER_INPUT]:
61
61
  print(node_id, backward_slice(flow, node_id, max_depth=3))
62
62
  ```
63
63
 
64
+ Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored:
65
+
66
+ ```python
67
+ from cobraphp.analysis import find_database_writes, reached_database_writes
68
+
69
+ writes = find_database_writes(ast)
70
+ for node_id in flow.tainted[USER_INPUT]:
71
+ for write in reached_database_writes(ast, flow, writes, node_id):
72
+ print(node_id, write.file, write.line, write.kind, write.table)
73
+ ```
74
+
64
75
  Apply the same file exclusions outside `parse_project`:
65
76
 
66
77
  ```python
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cobraphp"
8
- version = "0.1.0.dev3"
8
+ version = "0.1.0.dev4"
9
9
  description = "Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects."
10
10
  readme = "README.md"
11
11
  license = "GPL-2.0-only"
@@ -1,4 +1,5 @@
1
- """Static analysis of a php-parser-py AST in Python: call graph, data-flow graph, backward slice.
1
+ """Static analysis of a php-parser-py AST in Python: call graph, data-flow graph, backward slice, and the
2
+ database writes a data-flow node reaches.
2
3
 
3
4
  The call graph comes back as CCG records of `cobraphp.GraphExport`; Semgrep runs as the `semgrep` program
4
5
  to find the expressions each Source kind's rule matches. See docs/design-analysis-subpackage.md.
@@ -9,6 +10,7 @@ from __future__ import annotations
9
10
  from php_parser_py import AST
10
11
 
11
12
  from ._call_builder import CallBuilder
13
+ from ._database_writes import DatabaseWrite, find_database_writes, reached_database_writes
12
14
  from ._errors import AnalysisTimeoutError, StaticAnalysisError
13
15
  from ._file_filter import app_file_filter, framework_excluded_dirs, make_app_file_filter
14
16
  from ._records import DataFlowGraph, backward_slice, call_graph_export, data_flow_graph
@@ -52,11 +54,14 @@ __all__ = [
52
54
  "USER_INPUT",
53
55
  "AnalysisTimeoutError",
54
56
  "DataFlowGraph",
57
+ "DatabaseWrite",
55
58
  "StaticAnalysisError",
56
59
  "app_file_filter",
57
60
  "backward_slice",
58
61
  "build_call_graph",
59
62
  "build_data_flow",
63
+ "find_database_writes",
60
64
  "framework_excluded_dirs",
61
65
  "make_app_file_filter",
66
+ "reached_database_writes",
62
67
  ]
@@ -0,0 +1,708 @@
1
+ """Database writes of a php-parser-py AST, recognised by the table of database_writes.toml.
2
+
3
+ A write is a call: a SQL-text call whose SQL text starts with a write statement, or a write method of a model
4
+ or query builder. Its operands are the AST nodes whose values it stores, so that a data-flow node inside an
5
+ operand reaches the write. Every name and SQL text is read inside the write's own scope (function, method,
6
+ closure or top-level file code), in source order.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import re
13
+ import tomllib
14
+ from collections import deque
15
+ from collections.abc import Iterator
16
+ from dataclasses import dataclass, field
17
+ from importlib import resources
18
+ from typing import cast
19
+
20
+ from php_parser_py import AST, Node
21
+
22
+ from ._ast_types import load_php_ast_types
23
+ from ._callee_index import FUNCTION_CALL_TYPE, NAMESPACE_SEPARATOR, _enclosing_class_name
24
+ from ._records import DataFlowGraph, _relative_file
25
+
26
+ _METHOD_CALL_TYPE = "Expr_MethodCall"
27
+ _STATIC_CALL_TYPE = "Expr_StaticCall"
28
+ _VARIABLE_TYPE = "Expr_Variable"
29
+ _PROPERTY_FETCH_TYPE = "Expr_PropertyFetch"
30
+ _ARRAY_DIM_FETCH_TYPE = "Expr_ArrayDimFetch"
31
+ _ASSIGN_TYPE = "Expr_Assign"
32
+ _NEW_TYPE = "Expr_New"
33
+ _NAME_TYPES = frozenset({"Name", "Name_FullyQualified", "Name_Relative"})
34
+ _STRING_TYPE = "Scalar_String"
35
+ _INTERPOLATED_TYPE = "Scalar_InterpolatedString"
36
+ _INTERPOLATED_PART_TYPE = "InterpolatedStringPart"
37
+ _CONCAT_TYPE = "Expr_BinaryOp_Concat"
38
+ _COMPOUND_ASSIGN_TYPES = load_php_ast_types()[2] - {_ASSIGN_TYPE}
39
+ _NAMESPACE_TYPE = "Stmt_Namespace"
40
+ _USE_TYPE = "Stmt_Use"
41
+ _GROUP_USE_TYPE = "Stmt_GroupUse"
42
+ _USE_ITEM_TYPE = "UseItem"
43
+ # `type` of a `use` statement or item that imports a class (php-parser `Use_::TYPE_NORMAL`); 0 on an item
44
+ # means the statement's type.
45
+ _USE_CLASS_KIND = 1
46
+ # Callables with their own variable scope; an arrow function reads the enclosing one, as in _defuse_builder.
47
+ _SCOPE_TYPES = frozenset({"Stmt_Function", "Stmt_ClassMethod", "Expr_Closure"})
48
+ _ENCLOSING_CLASS_KEYWORDS = frozenset({"self", "static"})
49
+ # Name of the table a SQL write statement names, when the SQL text spells it out in full.
50
+ _SQL_TABLE = re.compile(
51
+ r"(?:INSERT|REPLACE)\s+(?:(?:LOW_PRIORITY|DELAYED|HIGH_PRIORITY|IGNORE)\s+)*(?:INTO\s+)?(?!INTO\b)"
52
+ r"[`\"\[]?([\w$.]+)[`\"\]]?(?=[\s(])"
53
+ r"|UPDATE\s+(?:(?:LOW_PRIORITY|IGNORE)\s+)*[`\"\[]?([\w$.]+)[`\"\]]?(?=\s)",
54
+ re.IGNORECASE,
55
+ )
56
+
57
+
58
+ @dataclass(frozen=True, slots=True, kw_only=True)
59
+ class DatabaseWrite:
60
+ """One recognised database write: a call that stores values in a database.
61
+
62
+ `node_id` is the AST node id of the call; `file` its project-relative POSIX path and `line` its line.
63
+ `kind` is the SQL statement keyword (`INSERT`, `UPDATE`, `REPLACE`) for SQL text, else the write method's
64
+ name as `database_writes.toml` spells it. `call` is the function or method called, spelled as that table
65
+ spells it. `table` is the table or model class name when the code spells it out, else `None`.
66
+ `operand_ids` are the AST node ids of the expressions whose values the write stores, in AST order.
67
+ """
68
+
69
+ node_id: str
70
+ file: str
71
+ line: int
72
+ kind: str
73
+ call: str
74
+ table: str | None
75
+ operand_ids: tuple[str, ...]
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class _SqlCall:
80
+ name: str
81
+ sql_argument: int
82
+ bind_methods: frozenset[str]
83
+ bind_functions: frozenset[str]
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class _Table:
88
+ statements: tuple[str, ...]
89
+ sql_functions: dict[str, _SqlCall]
90
+ sql_methods: dict[str, _SqlCall]
91
+ write_methods: dict[str, tuple[str, int | None]]
92
+ value_methods: frozenset[str]
93
+ table_methods: frozenset[str]
94
+ table_functions: frozenset[str]
95
+ builder_classes: frozenset[str]
96
+ bind_functions: frozenset[str]
97
+ not_write_classes: frozenset[str]
98
+
99
+
100
+ @functools.cache
101
+ def _load_table() -> _Table:
102
+ raw = tomllib.loads((resources.files("cobraphp.analysis") / "database_writes.toml").read_text(encoding="utf-8"))
103
+ sql_functions: dict[str, _SqlCall] = {}
104
+ sql_methods: dict[str, _SqlCall] = {}
105
+ for entry in raw["sql"]["call"]:
106
+ is_method = "method" in entry
107
+ name = str(entry["method"] if is_method else entry["function"])
108
+ call = _SqlCall(
109
+ name=name,
110
+ sql_argument=int(entry["sql_argument"]),
111
+ bind_methods=frozenset(str(n).lower() for n in entry.get("bind_methods", [])),
112
+ bind_functions=frozenset(str(n).lower() for n in entry.get("bind_functions", [])),
113
+ )
114
+ (sql_methods if is_method else sql_functions)[name.lower()] = call
115
+ method = raw["method"]
116
+ write_methods: dict[str, tuple[str, int | None]] = {}
117
+ for entry in method["write"]:
118
+ table_argument = entry.get("table_argument")
119
+ write_methods[str(entry["name"]).lower()] = (
120
+ str(entry["name"]),
121
+ None if table_argument is None else int(table_argument),
122
+ )
123
+ return _Table(
124
+ statements=tuple(str(s).upper() for s in raw["sql"]["statements"]),
125
+ sql_functions=sql_functions,
126
+ sql_methods=sql_methods,
127
+ write_methods=write_methods,
128
+ value_methods=frozenset(str(n).lower() for n in method["values"]),
129
+ table_methods=frozenset(str(n).lower() for n in method["table_methods"]),
130
+ table_functions=frozenset(str(n).lower() for n in method["table_functions"]),
131
+ builder_classes=frozenset(str(n).lower() for n in method["builder_classes"]),
132
+ bind_functions=frozenset(n for call in sql_functions.values() for n in call.bind_functions),
133
+ not_write_classes=frozenset(str(n).lower() for n in method["not_write_classes"]),
134
+ )
135
+
136
+
137
+ @dataclass(slots=True)
138
+ class _Scope:
139
+ """Assignments and receiver calls of one scope in source order.
140
+
141
+ An assignment carries the file position where it ends, so that a variable inside its own RHS lies before
142
+ that position; a call carries the position where it starts.
143
+ """
144
+
145
+ # variable name -> (end position, RHS node, plain `=`)
146
+ assignments: dict[str, list[tuple[int, Node, bool]]] = field(default_factory=dict)
147
+ # receiver key (`$o`, `$this->db`) -> (end position, RHS node) of `key->p = RHS` and `key[...] = RHS`
148
+ member_assignments: dict[str, list[tuple[int, Node]]] = field(default_factory=dict)
149
+ # receiver key -> (position, call node, lower-case method name)
150
+ receiver_calls: dict[str, list[tuple[int, Node, str]]] = field(default_factory=dict)
151
+ # first-argument variable name -> (position, call node, lower-case function name)
152
+ first_argument_calls: dict[str, list[tuple[int, Node, str]]] = field(default_factory=dict)
153
+
154
+
155
+ def find_database_writes(project_ast: AST) -> tuple[DatabaseWrite, ...]:
156
+ """The database writes `database_writes.toml` recognises in `project_ast`, ordered by file and position.
157
+
158
+ Raises `StaticAnalysisError` when a write's node has no file path.
159
+ """
160
+ return tuple(_Recognizer(project_ast).writes())
161
+
162
+
163
+ def reached_database_writes(
164
+ project_ast: AST,
165
+ graph: DataFlowGraph,
166
+ writes: tuple[DatabaseWrite, ...],
167
+ node_id: str,
168
+ *,
169
+ max_depth: int = 10,
170
+ ) -> tuple[DatabaseWrite, ...]:
171
+ """The `writes` that the value of `node_id` reaches within `max_depth` steps.
172
+
173
+ The reached nodes are `node_id` itself and the nodes a breadth-first walk reaches within `max_depth` steps.
174
+ A step is a data-flow edge (a successor, the reverse of `graph.predecessors`), a step from an expression to
175
+ the expression of `project_ast` that contains its value (`_containing_expression`), or a step from a
176
+ closure's `use` variable to the uses of that variable in the closure. A negative `max_depth` counts as 0;
177
+ a node outside the graph and the AST reaches only itself. A write is reached when one of its `operand_ids`
178
+ is a reached node. The result keeps the order of `writes`. An empty result means that no path within
179
+ `max_depth` steps leads to a recognised write, not that the value is never stored: the graph and the
180
+ recognition table both miss flows (docs/design-analysis-subpackage.md).
181
+ """
182
+ reached = _reached_nodes(project_ast, graph, node_id, max_depth)
183
+ return tuple(write for write in writes if not reached.isdisjoint(write.operand_ids))
184
+
185
+
186
+ def _reached_nodes(ast: AST, graph: DataFlowGraph, node_id: str, max_depth: int) -> frozenset[str]:
187
+ successors = _successors(graph)
188
+ closure_uses: dict[str, dict[str, list[str]]] = {}
189
+ visited = {node_id}
190
+ queue: deque[tuple[str, int]] = deque([(node_id, 0)])
191
+ while queue:
192
+ current, depth = queue.popleft()
193
+ if depth >= max_depth:
194
+ continue
195
+ steps = list(successors.get(current, ()))
196
+ node = ast.node(current)
197
+ if node is not None:
198
+ steps.extend(_containing_steps(ast, node, closure_uses))
199
+ for step in steps:
200
+ if step not in visited:
201
+ visited.add(step)
202
+ queue.append((step, depth + 1))
203
+ return frozenset(visited)
204
+
205
+
206
+ # The successor lists of the most recent graph object a reach used. A graph is a frozen record, so its lists
207
+ # stay valid; one entry keeps a caller's repeated calls on one graph at one inversion of its edges. The entry
208
+ # holds the graph until a reach with another graph replaces it.
209
+ _successor_cache: list[tuple[DataFlowGraph, dict[str, tuple[str, ...]]]] = []
210
+
211
+
212
+ def _successors(graph: DataFlowGraph) -> dict[str, tuple[str, ...]]:
213
+ if _successor_cache and _successor_cache[0][0] is graph:
214
+ return _successor_cache[0][1]
215
+ lists: dict[str, list[str]] = {}
216
+ for node_id, predecessors in graph.predecessors.items():
217
+ for predecessor in predecessors:
218
+ lists.setdefault(predecessor, []).append(node_id)
219
+ successors = {node_id: tuple(ids) for node_id, ids in lists.items()}
220
+ _successor_cache[:] = [(graph, successors)]
221
+ return successors
222
+
223
+
224
+ # ── Containing expressions ──────────────────────────────────────────
225
+
226
+ # Expressions whose value is computed from the value of each child: casts, unary and binary operators
227
+ # (concatenation and null coalescing among them), interpolated strings and array literals (through their
228
+ # items). A ternary's result is its second and third child; its condition is not part of the result, except
229
+ # in the short form `a ?: b`, whose first child is also the result.
230
+ _CAST_PREFIX = "Expr_Cast_"
231
+ _BINARY_PREFIX = "Expr_BinaryOp_"
232
+ _UNARY_TYPES = frozenset({"Expr_UnaryMinus", "Expr_UnaryPlus", "Expr_BitwiseNot", "Expr_BooleanNot"})
233
+ _ARRAY_TYPE = "Expr_Array"
234
+ _ARRAY_ITEM_TYPE = "ArrayItem"
235
+ _TERNARY_TYPE = "Expr_Ternary"
236
+ _CLOSURE_USE_TYPE = "ClosureUse"
237
+ _CLOSURE_TYPE = "Expr_Closure"
238
+
239
+
240
+ def _containing_steps(ast: AST, node: Node, closure_uses: dict[str, dict[str, list[str]]]) -> list[str]:
241
+ parent = _parent(ast, node)
242
+ if parent is None:
243
+ return []
244
+ if parent.node_type == _CLOSURE_USE_TYPE and node.node_type == _VARIABLE_TYPE:
245
+ closure = _parent(ast, parent)
246
+ if closure is None or closure.node_type != _CLOSURE_TYPE:
247
+ return []
248
+ if closure.id not in closure_uses:
249
+ closure_uses[closure.id] = _scope_variables(ast, closure)
250
+ return closure_uses[closure.id].get(_name(node), [])
251
+ container = _containing_expression(ast, node, parent)
252
+ return [] if container is None else [container.id]
253
+
254
+
255
+ # The expression whose value contains the value of `node`, one level up, or None.
256
+ def _containing_expression(ast: AST, node: Node, parent: Node) -> Node | None:
257
+ parent_type = parent.node_type
258
+ if parent_type == _ARRAY_ITEM_TYPE:
259
+ array = _parent(ast, parent)
260
+ return array if array is not None and array.node_type == _ARRAY_TYPE else None
261
+ if parent_type == _TERNARY_TYPE:
262
+ children = list(ast.succ(parent))
263
+ return None if len(children) == 3 and children[0].id == node.id else parent
264
+ if (
265
+ parent_type.startswith((_CAST_PREFIX, _BINARY_PREFIX))
266
+ or parent_type in _UNARY_TYPES
267
+ or parent_type == _INTERPOLATED_TYPE
268
+ ):
269
+ return parent
270
+ return None
271
+
272
+
273
+ # Variable nodes of a closure's own scope by name: its body and its nested arrow functions, and the `use`
274
+ # variables of closures nested in it, which read this scope.
275
+ def _scope_variables(ast: AST, closure: Node) -> dict[str, list[str]]:
276
+ variables: dict[str, list[str]] = {}
277
+ pending = [child for child in ast.succ(closure) if child.node_type != _CLOSURE_USE_TYPE]
278
+ while pending:
279
+ node = pending.pop()
280
+ if node.node_type in _SCOPE_TYPES:
281
+ pending.extend(child for child in ast.succ(node) if child.node_type == _CLOSURE_USE_TYPE)
282
+ continue
283
+ if node.node_type == _VARIABLE_TYPE and _name(node):
284
+ variables.setdefault(_name(node), []).append(node.id)
285
+ pending.extend(ast.succ(node))
286
+ return variables
287
+
288
+
289
+ class _Recognizer:
290
+ def __init__(self, ast: AST) -> None:
291
+ self._ast = ast
292
+ self._table = _load_table()
293
+ self._scopes: dict[str, _Scope] = {}
294
+ self._scope_of: dict[str, str] = {}
295
+ self._calls: list[Node] = []
296
+ self._namespaces: dict[str, tuple[str, dict[str, str]]] = {}
297
+
298
+ def writes(self) -> Iterator[DatabaseWrite]:
299
+ for file_node in sorted(self._ast.file_nodes(), key=lambda n: str(n.relative_path or "")):
300
+ self._calls.clear()
301
+ self._index_file(file_node)
302
+ for call in self._calls:
303
+ write = self._write(call)
304
+ if write is not None:
305
+ yield write
306
+
307
+ # ── Scope index ─────────────────────────────────────────────────
308
+
309
+ def _index_file(self, file_node: Node) -> None:
310
+ # Pre-order walk with an explicit stack, so a deeply nested expression fits; source order is kept.
311
+ pending: list[tuple[Node, str]] = [(file_node, file_node.id)]
312
+ self._scopes[file_node.id] = _Scope()
313
+ while pending:
314
+ node, scope_id = pending.pop()
315
+ if node.node_type in _SCOPE_TYPES:
316
+ scope_id = node.id
317
+ self._scopes[scope_id] = _Scope()
318
+ self._scope_of[node.id] = scope_id
319
+ self._index_node(node, self._scopes[scope_id])
320
+ pending.extend((child, scope_id) for child in reversed(list(self._ast.succ(node))))
321
+
322
+ def _index_node(self, node: Node, scope: _Scope) -> None:
323
+ node_type = node.node_type
324
+ if node_type == _ASSIGN_TYPE or node_type in _COMPOUND_ASSIGN_TYPES:
325
+ children = list(self._ast.succ(node))
326
+ if len(children) < 2:
327
+ return
328
+ lhs, rhs = children[0], children[1]
329
+ position = node.end_file_pos
330
+ if lhs.node_type == _VARIABLE_TYPE:
331
+ name = _name(lhs)
332
+ if name:
333
+ scope.assignments.setdefault(name, []).append((position, rhs, node_type == _ASSIGN_TYPE))
334
+ elif lhs.node_type in (_PROPERTY_FETCH_TYPE, _ARRAY_DIM_FETCH_TYPE):
335
+ key = self._receiver_key(_first_child(self._ast, lhs))
336
+ if key is not None:
337
+ scope.member_assignments.setdefault(key, []).append((position, rhs))
338
+ return
339
+ if node_type not in (FUNCTION_CALL_TYPE, _METHOD_CALL_TYPE, _STATIC_CALL_TYPE):
340
+ return
341
+ self._calls.append(node)
342
+ call_name = self._call_name(node)
343
+ if call_name is None:
344
+ return
345
+ if node_type == _METHOD_CALL_TYPE:
346
+ key = self._receiver_key(_first_child(self._ast, node))
347
+ if key is not None:
348
+ scope.receiver_calls.setdefault(key, []).append((node.start_file_pos, node, call_name))
349
+ elif node_type == FUNCTION_CALL_TYPE and call_name in self._table.bind_functions:
350
+ arguments = self._arguments(node)
351
+ if arguments and arguments[0].node_type == _VARIABLE_TYPE and _name(arguments[0]):
352
+ scope.first_argument_calls.setdefault(_name(arguments[0]), []).append(
353
+ (node.start_file_pos, node, call_name)
354
+ )
355
+
356
+ # `$o`, `$this->db`: a variable, or a property chain over a variable; else None.
357
+ def _receiver_key(self, node: Node | None) -> str | None:
358
+ parts: list[str] = []
359
+ while node is not None and node.node_type == _PROPERTY_FETCH_TYPE:
360
+ children = list(self._ast.succ(node))
361
+ if len(children) < 2 or children[1].node_type != "Identifier" or not _name(children[1]):
362
+ return None
363
+ parts.append(_name(children[1]))
364
+ node = children[0]
365
+ if node is None or node.node_type != _VARIABLE_TYPE or not _name(node):
366
+ return None
367
+ return "$" + "->".join([_name(node), *reversed(parts)])
368
+
369
+ # ── Writes ──────────────────────────────────────────────────────
370
+
371
+ def _write(self, call: Node) -> DatabaseWrite | None:
372
+ name = self._call_name(call)
373
+ if name is None:
374
+ return None
375
+ scope = self._scopes[self._scope_of[call.id]]
376
+ if call.node_type == FUNCTION_CALL_TYPE:
377
+ sql_call = self._table.sql_functions.get(name)
378
+ return None if sql_call is None else self._sql_write(call, sql_call, scope)
379
+ sql_call = self._table.sql_methods.get(name)
380
+ if sql_call is not None:
381
+ return self._sql_write(call, sql_call, scope)
382
+ method = self._table.write_methods.get(name)
383
+ return None if method is None else self._method_write(call, method, scope)
384
+
385
+ def _sql_write(self, call: Node, sql_call: _SqlCall, scope: _Scope) -> DatabaseWrite | None:
386
+ arguments = self._arguments(call)
387
+ if sql_call.sql_argument >= len(arguments):
388
+ return None
389
+ sql = arguments[sql_call.sql_argument]
390
+ text = self._leading_text(sql, scope, call.start_file_pos)
391
+ statement = self._statement(text)
392
+ if statement is None or text is None:
393
+ return None
394
+ operands = [sql]
395
+ if sql_call.bind_methods or sql_call.bind_functions:
396
+ operands.extend(self._bound_values(call, sql_call, scope))
397
+ return self._record(call, statement, sql_call.name, _sql_table(text), operands)
398
+
399
+ def _method_write(self, call: Node, method: tuple[str, int | None], scope: _Scope) -> DatabaseWrite | None:
400
+ canonical, table_argument = method
401
+ receiver = _first_child(self._ast, call)
402
+ receiver_class = self._receiver_class(receiver, scope, call.start_file_pos)
403
+ if receiver_class is not None and self._resolved_class(receiver_class) in self._table.not_write_classes:
404
+ return None
405
+ arguments = self._arguments(call)
406
+ operands: list[Node] = list(arguments)
407
+ chain = self._receiver_chain(call)
408
+ for link in chain:
409
+ if link.node_type == _METHOD_CALL_TYPE and self._call_name(link) in self._table.value_methods:
410
+ operands.extend(self._arguments(link))
411
+ innermost = chain[-1] if chain else _first_child(self._ast, call)
412
+ key = self._receiver_key(innermost)
413
+ if key is not None and call.node_type == _METHOD_CALL_TYPE:
414
+ operands.extend(self._receiver_values(key, scope, call.start_file_pos))
415
+ table = self._table_name(arguments, table_argument, chain, receiver_class, call)
416
+ return self._record(call, canonical, canonical, table, operands)
417
+
418
+ def _record(self, call: Node, kind: str, name: str, table: str | None, operands: list[Node]) -> DatabaseWrite:
419
+ return DatabaseWrite(
420
+ node_id=call.id,
421
+ file=_relative_file(call),
422
+ line=call.start_line,
423
+ kind=kind,
424
+ call=name,
425
+ table=table,
426
+ operand_ids=self._stored_value_ids(operands, self._scope_of[call.id]),
427
+ )
428
+
429
+ # ── Values a write stores ───────────────────────────────────────
430
+
431
+ # Ids of the `roots` subtrees and, for each variable of the write's scope in them, of the values assigned
432
+ # to it before that use (`_variable_values`), followed again through their variables. The data-flow graph
433
+ # has no edge from an operand to the expression that holds it, so a value inside an array or a
434
+ # concatenation assigned to an argument variable is linked here. Each node is visited once, and each visited
435
+ # variable scans only the assignments to its own name in the scope.
436
+ def _stored_value_ids(self, roots: list[Node], scope_id: str) -> tuple[str, ...]:
437
+ scope = self._scopes[scope_id]
438
+ seen: set[str] = set()
439
+ ordered: list[str] = []
440
+ pending = list(reversed(roots))
441
+ while pending:
442
+ node = pending.pop()
443
+ if node.id in seen:
444
+ continue
445
+ seen.add(node.id)
446
+ ordered.append(node.id)
447
+ pending.extend(reversed(list(self._ast.succ(node))))
448
+ if node.node_type == _VARIABLE_TYPE and self._scope_of.get(node.id) == scope_id:
449
+ pending.extend(reversed(self._variable_values(node, scope)))
450
+ return tuple(ordered)
451
+
452
+ # Values a variable use holds: the RHS of the latest plain assignment that ends before the use, and of each
453
+ # later compound assignment and element or property assignment to the variable before the use.
454
+ def _variable_values(self, variable: Node, scope: _Scope) -> list[Node]:
455
+ name, position = _name(variable), variable.start_file_pos
456
+ if not name:
457
+ return []
458
+ assignments = [a for a in scope.assignments.get(name, []) if a[0] < position]
459
+ start = max((a[0] for a in assignments if a[2]), default=-1)
460
+ values = [rhs for end, rhs, _ in assignments if end >= start]
461
+ values.extend(rhs for end, rhs in scope.member_assignments.get("$" + name, []) if start <= end < position)
462
+ return values
463
+
464
+ # Values set on a write's receiver before the write: `key->p = RHS`, `key[...] = RHS` and the arguments of
465
+ # value methods called on `key`, after the latest plain assignment to the receiver variable. Scans only the
466
+ # assignments and calls of `key` in the scope, once per write.
467
+ def _receiver_values(self, key: str, scope: _Scope, position: int) -> list[Node]:
468
+ variable = key[1:].split("->", 1)[0]
469
+ start = max((a[0] for a in scope.assignments.get(variable, []) if a[2] and a[0] < position), default=-1)
470
+ values = [rhs for pos, rhs in scope.member_assignments.get(key, []) if start <= pos < position]
471
+ for pos, call, name in scope.receiver_calls.get(key, []):
472
+ if start <= pos < position and name in self._table.value_methods:
473
+ values.extend(self._arguments(call))
474
+ return values
475
+
476
+ # Values bound to a prepared statement: bind calls chained on the prepare call, and bind calls on the
477
+ # variable the prepare call is assigned to, after it.
478
+ def _bound_values(self, call: Node, sql_call: _SqlCall, scope: _Scope) -> list[Node]:
479
+ values: list[Node] = []
480
+ current = call
481
+ while True:
482
+ parent = next(iter(self._ast.prev(current)), None)
483
+ receiver = None if parent is None else _first_child(self._ast, parent)
484
+ if parent is None or parent.node_type != _METHOD_CALL_TYPE or receiver is None or receiver.id != current.id:
485
+ break
486
+ if self._call_name(parent) in sql_call.bind_methods:
487
+ values.extend(self._arguments(parent))
488
+ current = parent
489
+ parent = next(iter(self._ast.prev(call)), None)
490
+ if parent is None or parent.node_type != _ASSIGN_TYPE:
491
+ return values
492
+ target = _first_child(self._ast, parent)
493
+ if target is None or target.node_type != _VARIABLE_TYPE or not _name(target):
494
+ return values
495
+ name, position = _name(target), call.start_file_pos
496
+ for pos, bind_call, method in scope.receiver_calls.get("$" + name, []):
497
+ if pos > position and method in sql_call.bind_methods:
498
+ values.extend(self._arguments(bind_call))
499
+ for pos, bind_call, function in scope.first_argument_calls.get(name, []):
500
+ if pos > position and function in sql_call.bind_functions:
501
+ values.extend(self._arguments(bind_call)[1:])
502
+ return values
503
+
504
+ # ── Names ───────────────────────────────────────────────────────
505
+
506
+ def _table_name(
507
+ self,
508
+ arguments: list[Node],
509
+ table_argument: int | None,
510
+ chain: list[Node],
511
+ receiver_class: Node | None,
512
+ call: Node,
513
+ ) -> str | None:
514
+ if table_argument is not None and table_argument < len(arguments):
515
+ argument = arguments[table_argument]
516
+ if argument.node_type == _STRING_TYPE:
517
+ text = str(argument.get("value", ""))
518
+ return _sql_table(text) if self._statement(text) else (text or None)
519
+ for link in chain:
520
+ name = self._call_name(link)
521
+ if name is None:
522
+ continue
523
+ is_table_call = (link.node_type == FUNCTION_CALL_TYPE and name in self._table.table_functions) or (
524
+ link.node_type != FUNCTION_CALL_TYPE and name in self._table.table_methods
525
+ )
526
+ link_arguments = self._arguments(link) if is_table_call else []
527
+ if link_arguments and link_arguments[0].node_type == _STRING_TYPE:
528
+ return str(link_arguments[0].get("value", "")) or None
529
+ if receiver_class is None:
530
+ return None
531
+ if receiver_class.node_type == _VARIABLE_TYPE:
532
+ return _enclosing_class_name(self._ast, receiver_class)
533
+ name = _name(receiver_class)
534
+ if name.lower() in _ENCLOSING_CLASS_KEYWORDS:
535
+ return _enclosing_class_name(self._ast, receiver_class)
536
+ short = name.rsplit(NAMESPACE_SEPARATOR, 1)[-1]
537
+ return None if not short or short.lower() in self._table.builder_classes or short == "parent" else short
538
+
539
+ # The class a write's receiver denotes, as the name node of a static call's class or of `new X` (through
540
+ # a call chain and through the latest `new`, static or method call assigned to a receiver variable), or
541
+ # the `$this` variable when the receiver is `$this` itself. None when the code does not spell the class
542
+ # out, and when the chain starts at a property or method of `$this`: such a receiver is another object.
543
+ def _receiver_class(self, node: Node | None, scope: _Scope, position: int) -> Node | None:
544
+ if node is None:
545
+ return None
546
+ if node.node_type in _NAME_TYPES:
547
+ return node
548
+ if node.node_type in (_NEW_TYPE, _STATIC_CALL_TYPE):
549
+ return self._receiver_class(_first_child(self._ast, node), scope, position)
550
+ if node.node_type in (_METHOD_CALL_TYPE, _PROPERTY_FETCH_TYPE):
551
+ chain = self._receiver_chain(node)
552
+ found = self._receiver_class(chain[-1] if chain else None, scope, position)
553
+ return None if found is not None and found.node_type == _VARIABLE_TYPE else found
554
+ if node.node_type != _VARIABLE_TYPE or not _name(node):
555
+ return None
556
+ if _name(node) == "this":
557
+ return node
558
+ assignments = [a for a in scope.assignments.get(_name(node), []) if a[2] and a[0] < position]
559
+ if not assignments:
560
+ return None
561
+ end, rhs, _ = max(assignments, key=lambda a: a[0])
562
+ if rhs.node_type not in (_NEW_TYPE, _STATIC_CALL_TYPE, _METHOD_CALL_TYPE):
563
+ return None
564
+ return self._receiver_class(rhs, scope, end)
565
+
566
+ # Lower-case fully qualified name a class name node denotes under PHP name resolution: a fully
567
+ # qualified name as written; else the `use` import of its first segment; else the name inside the
568
+ # enclosing namespace. `self`, `static`, `parent` and the `$this` variable give None.
569
+ def _resolved_class(self, node: Node) -> str | None:
570
+ if node.node_type == _VARIABLE_TYPE:
571
+ return None
572
+ name = _name(node)
573
+ if not name or name.lower() in (*_ENCLOSING_CLASS_KEYWORDS, "parent"):
574
+ return None
575
+ if node.node_type == "Name_FullyQualified":
576
+ return name.lower()
577
+ namespace, imports = self._imports(node)
578
+ if node.node_type == "Name_Relative":
579
+ return NAMESPACE_SEPARATOR.join(filter(None, (namespace, name))).lower()
580
+ first, _, rest = name.partition(NAMESPACE_SEPARATOR)
581
+ imported = imports.get(first.lower())
582
+ if imported is not None:
583
+ return NAMESPACE_SEPARATOR.join(filter(None, (imported, rest))).lower()
584
+ return NAMESPACE_SEPARATOR.join(filter(None, (namespace, name))).lower()
585
+
586
+ # Namespace name and class imports (lower-case alias -> name) of the namespace that holds `node`, or of
587
+ # its file when the file declares no namespace block.
588
+ def _imports(self, node: Node) -> tuple[str, dict[str, str]]:
589
+ container = next(
590
+ (a for a in self._ast.ancestors(node) if a.node_type in (_NAMESPACE_TYPE, "File")), None
591
+ )
592
+ if container is None:
593
+ return "", {}
594
+ cached = self._namespaces.get(container.id)
595
+ if cached is not None:
596
+ return cached
597
+ namespace = ""
598
+ imports: dict[str, str] = {}
599
+ for child in self._ast.succ(container):
600
+ if child.node_type == "Name" and container.node_type == _NAMESPACE_TYPE:
601
+ namespace = _name(child)
602
+ elif child.node_type in (_USE_TYPE, _GROUP_USE_TYPE):
603
+ self._add_imports(child, imports)
604
+ self._namespaces[container.id] = (namespace, imports)
605
+ return namespace, imports
606
+
607
+ def _add_imports(self, statement: Node, imports: dict[str, str]) -> None:
608
+ children = list(self._ast.succ(statement))
609
+ prefix = ""
610
+ if statement.node_type == _GROUP_USE_TYPE and children and children[0].node_type == "Name":
611
+ prefix = _name(children[0])
612
+ for item in children:
613
+ if item.node_type != _USE_ITEM_TYPE:
614
+ continue
615
+ kind = item.get("type") or statement.get("type")
616
+ parts = list(self._ast.succ(item))
617
+ if kind != _USE_CLASS_KIND or not parts or parts[0].node_type != "Name":
618
+ continue
619
+ name = NAMESPACE_SEPARATOR.join(filter(None, (prefix, _name(parts[0]))))
620
+ alias = next((_name(p) for p in parts[1:] if p.node_type == "Identifier"), "")
621
+ imports[(alias or name.rsplit(NAMESPACE_SEPARATOR, 1)[-1]).lower()] = name
622
+
623
+ # Lower-case name of a call's function or method, or None when the name is an expression.
624
+ def _call_name(self, call: Node) -> str | None:
625
+ wanted = _NAME_TYPES if call.node_type == FUNCTION_CALL_TYPE else frozenset({"Identifier"})
626
+ child = next((c for c in self._ast.succ(call) if c.node_type in wanted), None)
627
+ if child is None or not _name(child):
628
+ return None
629
+ return _name(child).rsplit(NAMESPACE_SEPARATOR, 1)[-1].lower()
630
+
631
+ # ── SQL text ────────────────────────────────────────────────────
632
+
633
+ # Literal text a SQL expression starts with: a string, an interpolated string's first part, a
634
+ # concatenation's left operand, or a variable's latest assignment in the scope before `position`.
635
+ def _leading_text(self, expression: Node, scope: _Scope, position: int) -> str | None:
636
+ node: Node | None = expression
637
+ while node is not None:
638
+ if node.node_type == _STRING_TYPE:
639
+ return str(node.get("value", ""))
640
+ if node.node_type == _INTERPOLATED_TYPE:
641
+ first = _first_child(self._ast, node)
642
+ if first is None or first.node_type != _INTERPOLATED_PART_TYPE:
643
+ return None
644
+ return str(first.get("value", ""))
645
+ if node.node_type == _CONCAT_TYPE:
646
+ node = _first_child(self._ast, node)
647
+ continue
648
+ if node.node_type != _VARIABLE_TYPE or not _name(node):
649
+ return None
650
+ assignments = [a for a in scope.assignments.get(_name(node), []) if a[2] and a[0] < position]
651
+ if not assignments:
652
+ return None
653
+ # Each step moves to an assignment that ends before the current position, so the walk ends.
654
+ position, node, _ = max(assignments, key=lambda a: a[0])
655
+ return None
656
+
657
+ def _statement(self, text: str | None) -> str | None:
658
+ if text is None:
659
+ return None
660
+ words = text.lstrip(" \t\r\n(").split(None, 1)
661
+ if not words:
662
+ return None
663
+ keyword = re.match(r"[A-Za-z]+", words[0])
664
+ if keyword is None or keyword.group(0).upper() not in self._table.statements:
665
+ return None
666
+ return keyword.group(0).upper()
667
+
668
+ # ── AST helpers ─────────────────────────────────────────────────
669
+
670
+ def _arguments(self, call: Node) -> list[Node]:
671
+ arguments: list[Node] = []
672
+ for child in self._ast.succ(call):
673
+ if child.node_type == "Arg":
674
+ expression = _first_child(self._ast, child)
675
+ if expression is not None:
676
+ arguments.append(expression)
677
+ return arguments
678
+
679
+ # Method calls, static calls and property fetches under a call's receiver, outermost first, ending with
680
+ # the innermost receiver that is none of them (or with the innermost static call).
681
+ def _receiver_chain(self, call: Node) -> list[Node]:
682
+ chain: list[Node] = []
683
+ node = _first_child(self._ast, call)
684
+ while node is not None:
685
+ chain.append(node)
686
+ if node.node_type not in (_METHOD_CALL_TYPE, _PROPERTY_FETCH_TYPE):
687
+ break
688
+ node = _first_child(self._ast, node)
689
+ return chain
690
+
691
+
692
+ def _sql_table(text: str) -> str | None:
693
+ match = _SQL_TABLE.match(text.lstrip(" \t\r\n("))
694
+ if match is None:
695
+ return None
696
+ return match.group(1) or match.group(2)
697
+
698
+
699
+ def _first_child(ast: AST, node: Node) -> Node | None:
700
+ return next(iter(ast.succ(node)), None)
701
+
702
+
703
+ def _parent(ast: AST, node: Node) -> Node | None:
704
+ return next(iter(ast.prev(node)), None)
705
+
706
+
707
+ def _name(node: Node) -> str:
708
+ return cast(str, node.get("name") or "")
@@ -0,0 +1,120 @@
1
+ # Database writes `find_database_writes` recognises in a php-parser-py AST: SQL text a call runs, and the
2
+ # write methods of the Laravel, Yii, ThinkPHP and CodeIgniter models and query builders.
3
+ #
4
+ # Names compare case-insensitively, as PHP compares function, method and class names. A method name matches
5
+ # on any receiver except one whose class `method.not_write_classes` lists.
6
+
7
+ [sql]
8
+ # Leading keyword of a SQL text that writes rows.
9
+ statements = ["INSERT", "UPDATE", "REPLACE"]
10
+
11
+ # A call that runs the SQL text at `sql_argument` (0-based) of its arguments. `function` names a free
12
+ # function, `method` a method of any receiver. For a prepared statement, the arguments of `bind_methods`
13
+ # called on the statement, and of `bind_functions` called with the statement as first argument, are the
14
+ # values the statement writes.
15
+ [[sql.call]]
16
+ function = "mysqli_query"
17
+ sql_argument = 1
18
+
19
+ [[sql.call]]
20
+ function = "mysql_query"
21
+ sql_argument = 0
22
+
23
+ [[sql.call]]
24
+ method = "query"
25
+ sql_argument = 0
26
+
27
+ [[sql.call]]
28
+ method = "exec"
29
+ sql_argument = 0
30
+
31
+ [[sql.call]]
32
+ method = "prepare"
33
+ sql_argument = 0
34
+ bind_methods = ["execute", "bind_param", "bindParam", "bindValue"]
35
+
36
+ [[sql.call]]
37
+ function = "mysqli_prepare"
38
+ sql_argument = 1
39
+ bind_functions = ["mysqli_stmt_bind_param", "mysqli_stmt_execute"]
40
+
41
+ # Yii: `createCommand($sql)->bindValue(...)->execute()`.
42
+ [[sql.call]]
43
+ method = "createCommand"
44
+ sql_argument = 0
45
+ bind_methods = ["bindValue", "bindValues", "bindParam", "execute"]
46
+
47
+ [method]
48
+ # Methods whose arguments set the values a later write on the same receiver stores: in the receiver chain
49
+ # of the write (`$m->data($row)->save()`) or called on the same receiver before it (`$m->fill($row);
50
+ # $m->save();`).
51
+ values = ["fill", "data", "set", "setAttributes", "load"]
52
+ # Chain methods and functions whose string-literal first argument names the table.
53
+ table_methods = ["table", "name"]
54
+ table_functions = ["M", "D", "db", "model"]
55
+ # Classes whose static calls start a query builder; their name is not a model name.
56
+ builder_classes = ["DB", "Db"]
57
+ # Classes whose write-named methods store no value in a database. A write method on a receiver whose class
58
+ # the code spells out (a static call, `new`, or the latest such call assigned to the receiver variable) and
59
+ # whose fully qualified name, resolved through the file's namespace and `use` imports, is listed here is not
60
+ # a write. A receiver whose class the code does not spell out stays a write.
61
+ not_write_classes = [
62
+ # Laravel schema builder: `Schema::create($table, $callback)` creates a table.
63
+ "Illuminate\\Support\\Facades\\Schema", "Schema",
64
+ # Laravel session store: `save`, `increment`, `decrement` act on session data.
65
+ "Illuminate\\Support\\Facades\\Session", "Session",
66
+ # Laravel cache: `increment`, `decrement` act on cache items.
67
+ "Illuminate\\Support\\Facades\\Cache", "Cache",
68
+ # Faker: `Factory::create($locale)` makes a fake-data generator.
69
+ "Faker\\Factory",
70
+ # Image libraries: `save($path)` writes an image file.
71
+ "Spatie\\Image\\Image",
72
+ "Intervention\\Image\\Facades\\Image", "Intervention\\Image\\ImageManagerStatic",
73
+ "Intervention\\Image\\ImageManager",
74
+ # Carbon: `Carbon::create(...)` makes a date.
75
+ "Carbon\\Carbon",
76
+ ]
77
+
78
+ # A method call that writes a model or the rows its receiver chain selects. `table_argument` is the argument
79
+ # that names the table when it is a string literal (CodeIgniter `$this->db->insert('t', $row)`, Yii
80
+ # `createCommand()->insert('t', $row)`); a literal SQL text there names its table as SQL does.
81
+ [[method.write]]
82
+ name = "save"
83
+
84
+ [[method.write]]
85
+ name = "create"
86
+
87
+ [[method.write]]
88
+ name = "insert"
89
+ table_argument = 0
90
+
91
+ [[method.write]]
92
+ name = "insertGetId"
93
+
94
+ [[method.write]]
95
+ name = "insertAll"
96
+
97
+ [[method.write]]
98
+ name = "update"
99
+ table_argument = 0
100
+
101
+ [[method.write]]
102
+ name = "updateOrCreate"
103
+
104
+ [[method.write]]
105
+ name = "firstOrCreate"
106
+
107
+ [[method.write]]
108
+ name = "updateAll"
109
+
110
+ [[method.write]]
111
+ name = "increment"
112
+
113
+ [[method.write]]
114
+ name = "decrement"
115
+
116
+ [[method.write]]
117
+ name = "setInc"
118
+
119
+ [[method.write]]
120
+ name = "setDec"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cobraphp
3
- Version: 0.1.0.dev3
3
+ Version: 0.1.0.dev4
4
4
  Summary: Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects.
5
5
  License-Expression: GPL-2.0-only
6
6
  Requires-Python: >=3.11
@@ -20,7 +20,7 @@ Python interface of [CobraPHP](https://github.com/jhu-seclab-cobra/CobraPHP), th
20
20
 
21
21
  **Placeholder.** The Python binding is not fully implemented. Interfaces and results may change between versions.
22
22
 
23
- The subpackage `cobraphp.analysis` builds a call graph and a data flow from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
23
+ The subpackage `cobraphp.analysis` builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
24
24
 
25
25
  ## Install
26
26
 
@@ -75,6 +75,17 @@ for node_id in flow.tainted[USER_INPUT]:
75
75
  print(node_id, backward_slice(flow, node_id, max_depth=3))
76
76
  ```
77
77
 
78
+ Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored:
79
+
80
+ ```python
81
+ from cobraphp.analysis import find_database_writes, reached_database_writes
82
+
83
+ writes = find_database_writes(ast)
84
+ for node_id in flow.tainted[USER_INPUT]:
85
+ for write in reached_database_writes(ast, flow, writes, node_id):
86
+ print(node_id, write.file, write.line, write.kind, write.table)
87
+ ```
88
+
78
89
  Apply the same file exclusions outside `parse_project`:
79
90
 
80
91
  ```python
@@ -22,6 +22,7 @@ src/cobraphp/analysis/_call_builder.py
22
22
  src/cobraphp/analysis/_call_graph.py
23
23
  src/cobraphp/analysis/_call_graph_nodes.py
24
24
  src/cobraphp/analysis/_callee_index.py
25
+ src/cobraphp/analysis/_database_writes.py
25
26
  src/cobraphp/analysis/_defuse_builder.py
26
27
  src/cobraphp/analysis/_errors.py
27
28
  src/cobraphp/analysis/_file_filter.py
@@ -32,6 +33,7 @@ src/cobraphp/analysis/_source_kinds.py
32
33
  src/cobraphp/analysis/_taint_graph.py
33
34
  src/cobraphp/analysis/_taint_propagator.py
34
35
  src/cobraphp/analysis/_taint_rules.py
36
+ src/cobraphp/analysis/database_writes.toml
35
37
  src/cobraphp/analysis/frameworks.toml
36
38
  src/cobraphp/analysis/php_ast_types.toml
37
39
  src/cobraphp/analysis/rules/database_taint.yaml
File without changes
File without changes