Skip to content

Python: Reduce log injection false positives#22231

Open
Ali-Razmjoo wants to merge 1 commit into
github:mainfrom
Ali-Razmjoo:python-log-injection
Open

Python: Reduce log injection false positives#22231
Ali-Razmjoo wants to merge 1 commit into
github:mainfrom
Ali-Razmjoo:python-log-injection

Conversation

@Ali-Razmjoo

Copy link
Copy Markdown

Add SimpleTypeSanitizer in a new semmle.python.security.Sanitizers, the Python counterpart of the class the Java and C# queries already use. A routed parameter annotated with a simple type such as int or uuid.UUID is validated by the web framework before the request handler runs, so it cannot contain a line break and cannot be used to forge a log entry. The annotation is only trusted on routed parameters, since Python does not enforce annotations at run time. Annotated[T, ...], Optional[T] and T | None are unwrapped.

Recognize more ways of neutralizing a log message: str.translate, str.encode("unicode_escape"), a re.sub or re.compile(...).sub whose pattern matches control characters, and escaping conversions such as repr and json.dumps.

Recognize a logging.Formatter subclass that strips control characters from the records it renders. Such a formatter sanitizes when the record is written rather than where it is created, so no sanitizing call appears between the source and the logging call. Callees are resolved through module-level definitions, which local flow does not reach from a nested scope.

@Ali-Razmjoo
Ali-Razmjoo requested a review from a team as a code owner July 23, 2026 22:07
Add `SimpleTypeSanitizer` in a new `semmle.python.security.Sanitizers`, the
Python counterpart of the class the Java and C# queries already use. A routed
parameter annotated with a simple type such as `int` or `uuid.UUID` is validated
by the web framework before the request handler runs, so it cannot contain a
line break and cannot be used to forge a log entry. The annotation is only
trusted on routed parameters, since Python does not enforce annotations at run
time. `Annotated[T, ...]`, `Optional[T]` and `T | None` are unwrapped.

Recognize more ways of neutralizing a log message: `str.translate`,
`str.encode("unicode_escape")`, a `re.sub` or `re.compile(...).sub` whose
pattern matches control characters, and escaping conversions such as `repr` and
`json.dumps`.

Recognize a `logging.Formatter` subclass that strips control characters from the
records it renders. Such a formatter sanitizes when the record is written rather
than where it is created, so no sanitizing call appears between the source and
the logging call. Callees are resolved through module-level definitions, which
local flow does not reach from a nested scope.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant