Skip to content

[UPDATE QUERY] Python: cover XPath, str.format and LLM prompt injection gaps; argparse injection already covered (CWE-643, CWE-1336, CWE-1427, CWE-78) - #370

Draft
felickz with Copilot wants to merge 5 commits into
mainfrom
copilot/fix-332622516-1410885174-c67cd115-817c-40bb-8200-88064b3552c8
Draft

felickz with Copilot wants to merge 5 commits into
mainfrom
copilot/fix-332622516-1410885174-c67cd115-817c-40bb-8200-88064b3552c8

Conversation

Copilot AI commented Oct 31, 2026 •

Copy link
Copy Markdown

📝 Query Update

  • Query File: languages/python/custom/src/XpathInjectionExtended/XpathInjectionExtended.ql, languages/python/custom/src/StrFormatTemplateInjection/StrFormatTemplateInjection.ql, languages/python/custom/src/PromptInjectionExtended/PromptInjectionExtended.ql, languages/python/custom/src/Shared/CapturedUnpackedVariableFlow.qll
  • Language: python
  • Update Type: enhanced detection, framework support

🎯 Changes

What Changed

  • Shared/CapturedUnpackedVariableFlow.qll: adds a flow step from a variable defined by iterable unpacking (a, b = f(), loop targets) to reads of that variable in nested scopes (generator expressions, comprehensions, lambdas, inner functions).
  • py/xpath-injection-extended (CWE-643): the upstream XpathInjection sources, sinks and sanitizers, plus the step above.
  • py/str-format-template-injection (CWE-1336, new):
    • Sink: a user-controlled format string in str.format, str.format_map, string.Formatter.format or string.Formatter.vformat.
    • Fires only when at least one formatted argument is not a literal, so cases like format() or format_map({}) are not reported.
    • Barrier: ConstCompareBarrier.
    • Uses the shared capture step.
  • py/prompt-injection-extended (CWE-1427, new):
    • Sink: the prompt argument of complete, acomplete, stream_complete or astream_complete on an LLM created from a llama_index.llms.*.* or llama_index.core.llms.* class.
    • LLM instances are found with a separate taint-tracking pass.
    • Added steps:
      • substitute and safe_substitute arguments flow to the call result.
      • self.x, self.y = rhs flows to self.x reads in other methods of the same class.
  • CWE-78 (DVSA): no query change. py/command-line-injection already reports argparse values reaching os.system when the local threat model is enabled. This PR adds a regression test that enables local through an .ext.yml.
  • The test pack now depends on codeql/python-queries so the regression test can reference the upstream query.

Why This Change

The issue guessed that DSVW's query string is not a recognised source. That guess is wrong: self.path on BaseHTTPRequestHandler is already a remote source. The real cause is a gap in python-all's variable-capture flow. It only starts from definitions that have a single assigned value, and a target of iterable unpacking has none. So query loses its taint inside the generator expression:

path, query = self.path.split("?", 1) if "?" in self.path else (self.path, "")
params = dict((m.group("p"), unquote(",".join(re.findall("%s=..." % ..., query))))  # query untainted here
              for m in re.finditer(r"...", query))
doc.xpath(".//user[name/text()='%s']" % params["name"])

Because of this gap, the upstream queries report nothing on dsvw.py, including the obvious SQL and command injections.

unguard's flow breaks in two places:

  • string.Template.substitute is not modelled.
  • Values are not tracked into attribute targets of an unpacking assignment: self._llm_model, self._embeddings_model = init_ollama_models(...).

The experimental upstream py/prompt-injection covers only OpenAI and the Agents SDK, not LlamaIndex.

Impact

New alerts appear only for the patterns above. py/xpath-injection-extended reports a superset of py/xpath-injection. If both queries run, the shared results appear twice.

🔍 Before vs. After

Previous Behavior

Finding Baseline
DSVW XPath (dsvw.py:35) not reported
DSVW str.format (dsvw.py:55) not reported (no query)
DVSA argparse into os.system not reported under the default threat model; reported under local
unguard self._llm_model.complete(prompt) not reported (experimental py/prompt-injection also finds nothing)

New Behavior

Finding Result
DSVW XPath py/xpath-injection-extended reports dsvw.py:35
DSVW str.format py/str-format-template-injection reports dsvw.py:55
DVSA unchanged; use --threat-model local
unguard py/prompt-injection-extended reports rag.py:104

🧪 Testing

  • New/updated test cases added
  • All tests pass
  • Regression tests validated
  • No unintended side effects

Each test has positive and negative cases. Known gaps were confirmed first: upstream py/xpath-injection misses the generator and inner-function cases, and experimental py/prompt-injection finds nothing. Each new prompt-injection step was also confirmed necessary: removing it drops the alerts that depend on it.

📊 Impact Analysis

  • Compatibility: backward compatible. All queries are new custom queries, and no upstream query is modified.
  • Performance: neutral. The capture step is a small, scope-restricted jump step. The prompt query runs one extra taint-tracking pass to find LLM instances.
  • Accuracy: better recall. Known false-positive risks, which is why the new queries are @precision medium:
    • substitute and safe_substitute are matched by method name only.
    • The self.<attr> unpacking step ignores the tuple index.
    • Any .format method on a user-controlled receiver is treated as a sink.

📋 Checklist

  • Query compiles without errors
  • Documentation updated
  • Tests updated with new expectations
  • Metadata updated if needed

Each query has a .md help file. The change note is languages/python/custom/src/change-notes/2026-10-31-python-misc-injection.md.

🔗 References

…with captured unpacked variable flow step

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
out.append(tmpl.format_map({"env": os.environ})) # $ Alert
out.append(string.Formatter().format(tmpl, Config())) # $ Alert
out.append(string.Formatter().vformat(tmpl, (Config(),), {})) # $ Alert
return "".join(out)
# Safe: compared against a constant.
if tmpl == "{0.name}":
out.append(tmpl.format(Config()))
return "".join(out)
path, query = self.path.split("?", 1) if "?" in self.path else (self.path, "")
params = dict(
(m.group("name"), urllib.parse.unquote(",".join(re.findall(r"%s=([^&]+)" % re.escape(m.group("name")), query))))
for m in re.finditer(r"(?P<name>\w+)=[^&]+", query)
path, query = self.path.split("?", 1) if "?" in self.path else (self.path, "")
params = dict(
(m.group("name"), urllib.parse.unquote(",".join(re.findall(r"%s=([^&]+)" % re.escape(m.group("name")), query))))
for m in re.finditer(r"(?P<name>\w+)=[^&]+", query)
# Already reported by `py/xpath-injection`: no nested scope involved.
_, value = self.path.split("=", 1)
doc = lxml.etree.parse(io.BytesIO(USERS_XML.encode()))
return doc.xpath("//user[name='%s']" % value) # $ Alert
Copilot AI and others added 2 commits October 31, 2026 07:02
… regression test, docs and change note

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
…npacked literals as non-traversable

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Copilot Request [UPDATE QUERY] Python: cover XPath, str.format and LLM prompt injection gaps; argparse injection already covered (CWE-643, CWE-1336, CWE-1427, CWE-78) Oct 31, 2026
Copilot AI requested a review from felickz October 31, 2026 07:08
@felickz
felickz requested a balanced review from Copilot November 2, 2026 18:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The shared flow helper creates false positives by propagating taint from overwritten values, while the format-injection query misses templates passed through vformat’s format_string keyword.

2 open issues
What changed in this PR

This PR expands the custom Python CodeQL pack to address injection detection gaps identified in #361. It adds XPath capture-flow support, format-string injection detection, and LlamaIndex prompt-injection detection, while confirming existing argparse coverage under the local threat model.

Changes:

  • Adds three queries and shared flow handling for unpacked variables captured by nested scopes.
  • Adds positive and negative regression fixtures, including an upstream command-injection test with the local threat model enabled.
  • Documents query behavior and adds the upstream Python query pack as a test dependency.
File Description
languages/​python/​custom/​test/​XpathInjectionExtended/​XpathInjectionExtended.qlref Connects XPath tests to the custom query.
languages/​python/​custom/​test/​XpathInjectionExtended/​XpathInjectionExtended.expected Records expected XPath alerts and paths.
languages/​python/​custom/​test/​XpathInjectionExtended/​server.py Exercises captured variables and safe XPath usage.
languages/​python/​custom/​test/​StrFormatTemplateInjection/​StrFormatTemplateInjection.qlref Connects format-string tests to the query.
languages/​python/​custom/​test/​StrFormatTemplateInjection/​StrFormatTemplateInjection.expected Records expected format-string alerts and paths.
languages/​python/​custom/​test/​StrFormatTemplateInjection/​server.py Tests formatting through captured request parameters.
languages/​python/​custom/​test/​StrFormatTemplateInjection/​flask_app.py Tests formatting APIs and negative cases.
languages/​python/​custom/​test/​qlpack.yml Adds the upstream Python query dependency.
languages/​python/​custom/​test/​PromptInjectionExtended/​rag.py Exercises completion prompts and negative cases.
languages/​python/​custom/​test/​PromptInjectionExtended/​PromptInjectionExtended.qlref Connects prompt-injection tests to the query.
languages/​python/​custom/​test/​PromptInjectionExtended/​PromptInjectionExtended.expected Records expected prompt-injection alerts and paths.
languages/​python/​custom/​test/​PromptInjectionExtended/​prepare_prompt.py Exercises both template substitution methods.
languages/​python/​custom/​test/​PromptInjectionExtended/​init_models.py Provides LlamaIndex model-construction fixtures.
languages/​python/​custom/​test/​PromptInjectionExtended/​config.py Defines the prompt template fixture.
languages/​python/​custom/​test/​PromptInjectionExtended/​classification.py Supplies request inputs through FastAPI routes.
languages/​python/​custom/​test/​CommandInjectionLocalThreatModel/​package_template.py Tests argparse-to-shell flows and safe alternatives.
languages/​python/​custom/​test/​CommandInjectionLocalThreatModel/​CommandInjection.qlref References the upstream command-injection query.
languages/​python/​custom/​test/​CommandInjectionLocalThreatModel/​CommandInjection.ext.yml Enables the local threat model.
languages/​python/​custom/​test/​CommandInjectionLocalThreatModel/​CommandInjection.expected Records expected command-injection alerts and paths.
languages/​python/​custom/​src/​XpathInjectionExtended/​XpathInjectionExtended.ql Extends XPath detection with captured-variable flow.
languages/​python/​custom/​src/​XpathInjectionExtended/​XpathInjectionExtended.md Documents XPath coverage and remediation.
languages/​python/​custom/​src/​StrFormatTemplateInjection/​StrFormatTemplateInjection.ql Detects untrusted format strings with non-literal arguments.
languages/​python/​custom/​src/​StrFormatTemplateInjection/​StrFormatTemplateInjection.md Documents format-string risks and alternatives.
languages/​python/​custom/​src/​Shared/​CapturedUnpackedVariableFlow.qll Adds shared flow handling for captured unpacked variables.
languages/​python/​custom/​src/​PromptInjectionExtended/​PromptInjectionExtended.ql Models LlamaIndex completion sinks and supporting flows.
languages/​python/​custom/​src/​PromptInjectionExtended/​PromptInjectionExtended.md Documents prompt-injection coverage and mitigations.
languages/​python/​custom/​src/​change-notes/​2026-10-31-python-misc-injection.md Summarizes the three new queries.

Review effort: Balanced

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants