Repository navigation
Conversation
1 task done
…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 |
… 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
There was a problem hiding this comment.
🟡 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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

📝 Query Update
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🎯 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 upstreamXpathInjectionsources, sinks and sanitizers, plus the step above.py/str-format-template-injection(CWE-1336, new):str.format,str.format_map,string.Formatter.formatorstring.Formatter.vformat.format()orformat_map({})are not reported.ConstCompareBarrier.py/prompt-injection-extended(CWE-1427, new):complete,acomplete,stream_completeorastream_completeon an LLM created from allama_index.llms.*.*orllama_index.core.llms.*class.substituteandsafe_substitutearguments flow to the call result.self.x, self.y = rhsflows toself.xreads in other methods of the same class.py/command-line-injectionalready reportsargparsevalues reachingos.systemwhen thelocalthreat model is enabled. This PR adds a regression test that enableslocalthrough an.ext.yml.codeql/python-queriesso 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.pathonBaseHTTPRequestHandleris 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. Soqueryloses its taint inside the generator expression: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.substituteis not modelled.self._llm_model, self._embeddings_model = init_ollama_models(...).The experimental upstream
py/prompt-injectioncovers only OpenAI and the Agents SDK, not LlamaIndex.Impact
New alerts appear only for the patterns above.
py/xpath-injection-extendedreports a superset ofpy/xpath-injection. If both queries run, the shared results appear twice.🔍 Before vs. After
Previous Behavior
dsvw.py:35)str.format(dsvw.py:55)os.systemlocalself._llm_model.complete(prompt)py/prompt-injectionalso finds nothing)New Behavior
py/xpath-injection-extendedreportsdsvw.py:35str.formatpy/str-format-template-injectionreportsdsvw.py:55--threat-model localpy/prompt-injection-extendedreportsrag.py:104🧪 Testing
Each test has positive and negative cases. Known gaps were confirmed first: upstream
py/xpath-injectionmisses the generator and inner-function cases, and experimentalpy/prompt-injectionfinds nothing. Each new prompt-injection step was also confirmed necessary: removing it drops the alerts that depend on it.📊 Impact Analysis
@precision medium:substituteandsafe_substituteare matched by method name only.self.<attr>unpacking step ignores the tuple index..formatmethod on a user-controlled receiver is treated as a sink.📋 Checklist
Each query has a
.mdhelp file. The change note islanguages/python/custom/src/change-notes/2026-10-31-python-misc-injection.md.🔗 References