-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Python: Prompt injection in OpenAI clients #21141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mbaluda
wants to merge
39
commits into
github:main
Choose a base branch
from
mbaluda:prompt-injection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+519
−1
Open
Changes from 27 commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
005db5b
Add first version prompt injection query python openai agents sdk
knewbury01 7a9e03d
Add support for `openai.OpenAI` client library
mbaluda b30444b
Merge branch 'knewbury01/add-prompt-injection-query-python' into prom…
mbaluda 6c5c87e
Fix projcet build errors
mbaluda 616698c
Fix newline at end of PromptInjection.qlref
mbaluda 942834d
Update python/ql/lib/semmle/python/frameworks/OpenAI.qll
mbaluda df979da
Update python/ql/src/Security/CWE-1427/PromptInjection.ql
mbaluda bacecb7
Add example to qlhelp
mbaluda a9d0a16
Fix missing predicate
mbaluda 04193f4
Une inline expectations
mbaluda 2c83dc3
Use models as data
mbaluda 0c7996e
Update python/ql/src/Security/CWE-1427/examples/example.py
mbaluda 21a2146
Update python/ql/lib/semmle/python/Concepts.qll
mbaluda 7d450c5
Update python/ql/src/Security/CWE-1427/PromptInjection.qhelp
mbaluda c352ffd
Update python/ql/lib/change-notes/2026-01-02-prompt-injection.md
mbaluda 9ea0a12
Fix capitalization typo
mbaluda fd8e170
QLdoc
mbaluda b4275e8
Merge branch 'main' into knewbury01/add-prompt-injection-query-python
knewbury01 4117252
Merge pull request #4 from github/main
mbaluda c7d99a1
Merge branch 'knewbury01/add-prompt-injection-query-python' into prom…
mbaluda 1a0feb4
precise models for experimental query
mbaluda 01b9fa2
removed spurious file
mbaluda 29aad2e
remove test
mbaluda 0a36be1
Refactor openai model
mbaluda dccaa84
Improve agents sdk modelling (#5)
knewbury01 1ec82d9
Update OpenAI.qll
mbaluda 3c14266
Merge branch 'github:main' into prompt-injection
mbaluda 16370d6
Update python/ql/test/experimental/query-tests/Security/CWE-1427-Prom…
mbaluda 4542681
Update python/ql/lib/semmle/python/frameworks/OpenAI.qll
mbaluda afb8702
Merge branch 'main' into prompt-injection
mbaluda 4c88fc5
Fix formatting
mbaluda 82c6a23
Merge branch 'github:main' into prompt-injection
mbaluda aac5287
Merge branch 'github:main' into prompt-injection
mbaluda cd18ab9
Fix expected file
mbaluda 5214643
Update integration tests expected output.
mbaluda abfb205
Merge branch 'main' into prompt-injection
mbaluda 0ec1da8
Merge branch 'github:main' into prompt-injection
mbaluda 6f4abe2
Python: Support for prompt-injeciton sink models.
mbaluda 2ed0814
python: move files into experimental directory
yoff File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| category: minorAnalysis | ||
| --- | ||
| * Added experimental query `py/prompt-injection` to detect potential prompt injection vulnerabilities in code using LLMs. | ||
| * Added taint flow model and type model for `agents` and `openai` modules. |
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| /** | ||
| * Provides classes modeling security-relevant aspects of the `openAI` Agents SDK package. | ||
| * See https://github.com/openai/openai-agents-python. | ||
| * As well as the regular openai python interface. | ||
| * See https://github.com/openai/openai-python. | ||
| */ | ||
|
|
||
| private import python | ||
| private import semmle.python.ApiGraphs | ||
|
|
||
| /** | ||
| * Provides models for agents SDK (instances of the `agents.Runner` class etc). | ||
| * | ||
| * See https://github.com/openai/openai-agents-python. | ||
| */ | ||
| module AgentSDK { | ||
| /** Gets a reference to the `agents.Agent` class. */ | ||
| API::Node classRef() { result = API::moduleImport("agents").getMember("Runner") } | ||
|
|
||
| /** Gets a reference to the `run` members. */ | ||
| API::Node runMembers() { result = classRef().getMember(["run", "run_sync", "run_streamed"]) } | ||
|
|
||
| /** Gets a reference to a potential property of `agents.Runner` called input which can refer to a system prompt depending on the role specified. */ | ||
| API::Node getContentNode() { | ||
| result = runMembers().getKeywordParameter("input").getASubscript().getSubscript("content") | ||
| or | ||
| result = runMembers().getParameter(_).getASubscript().getSubscript("content") | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Provides models for Agent (instances of the `openai.OpenAI` class). | ||
| * | ||
| * See https://github.com/openai/openai-python. | ||
| */ | ||
| module OpenAI { | ||
| /** Gets a reference to the `openai.OpenAI` class. */ | ||
| API::Node classRef() { | ||
| result = | ||
| API::moduleImport("openai").getMember(["OpenAI", "AsyncOpenAI", "AzureOpenAI"]).getReturn() | ||
| } | ||
|
|
||
| /** Gets a reference to a potential property of `openai.OpenAI` called instructions which refers to the system prompt. */ | ||
| API::Node getContentNode() { | ||
| exists(API::Node content | | ||
| content = | ||
| classRef() | ||
| .getMember("responses") | ||
| .getMember("create") | ||
| .getKeywordParameter(["input", "instructions"]) or | ||
mbaluda marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| content = | ||
| classRef() | ||
| .getMember("responses") | ||
| .getMember("create") | ||
| .getKeywordParameter(["input", "instructions"]) | ||
| .getASubscript() | ||
| .getSubscript("content") or | ||
| content = | ||
| classRef() | ||
| .getMember("realtime") | ||
| .getMember("connect") | ||
| .getReturn() | ||
| .getMember("conversation") | ||
| .getMember("item") | ||
| .getMember("create") | ||
| .getKeywordParameter("item") | ||
| .getSubscript("content") or | ||
| content = | ||
| classRef() | ||
| .getMember("chat") | ||
| .getMember("completions") | ||
| .getMember("create") | ||
| .getKeywordParameter("messages") | ||
| .getASubscript() | ||
| .getSubscript("content") | ||
| | | ||
| // content | ||
| if not exists(content.getASubscript()) | ||
| then result = content | ||
| else | ||
| // content.text | ||
| result = content.getASubscript().getSubscript("text") | ||
| ) | ||
| } | ||
| } | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| extensions: | ||
| - addsTo: | ||
| pack: codeql/python-all | ||
| extensible: sinkModel | ||
| data: | ||
| - ['agents', 'Member[Agent].Argument[instructions:]', 'prompt-injection'] |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| extensions: | ||
| - addsTo: | ||
| pack: codeql/python-all | ||
| extensible: sinkModel | ||
| data: | ||
| - ['OpenAI', 'Member[beta].Member[assistants].Member[create].Argument[instructions:]', 'prompt-injection'] | ||
|
|
||
| - addsTo: | ||
| pack: codeql/python-all | ||
| extensible: typeModel | ||
| data: | ||
| - ['OpenAI', 'openai', 'Member[OpenAI,AsyncOpenAI,AzureOpenAI].ReturnValue'] |
64 changes: 64 additions & 0 deletions
64
python/ql/lib/semmle/python/security/dataflow/PromptInjectionCustomizations.qll
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /** | ||
| * Provides default sources, sinks and sanitizers for detecting | ||
| * "prompt injection" | ||
| * vulnerabilities, as well as extension points for adding your own. | ||
| */ | ||
|
|
||
| import python | ||
| private import semmle.python.dataflow.new.DataFlow | ||
| private import semmle.python.Concepts | ||
| private import semmle.python.dataflow.new.RemoteFlowSources | ||
| private import semmle.python.dataflow.new.BarrierGuards | ||
| private import semmle.python.frameworks.data.ModelsAsData | ||
| private import semmle.python.frameworks.OpenAI | ||
|
|
||
| /** | ||
| * Provides default sources, sinks and sanitizers for detecting | ||
| * "prompt injection" | ||
| * vulnerabilities, as well as extension points for adding your own. | ||
| */ | ||
| module PromptInjection { | ||
| /** | ||
| * A data flow source for "prompt injection" vulnerabilities. | ||
| */ | ||
| abstract class Source extends DataFlow::Node { } | ||
|
|
||
| /** | ||
| * A data flow sink for "prompt injection" vulnerabilities. | ||
| */ | ||
| abstract class Sink extends DataFlow::Node { } | ||
|
|
||
| /** | ||
| * A sanitizer for "prompt injection" vulnerabilities. | ||
| */ | ||
| abstract class Sanitizer extends DataFlow::Node { } | ||
|
|
||
| /** | ||
| * An active threat-model source, considered as a flow source. | ||
| */ | ||
| private class ActiveThreatModelSourceAsSource extends Source, ActiveThreatModelSource { } | ||
|
|
||
| /** | ||
| * A prompt to an AI model, considered as a flow sink. | ||
| */ | ||
| class AIPromptAsSink extends Sink { | ||
| AIPromptAsSink() { this = any(AIPrompt p).getAPrompt() } | ||
| } | ||
|
|
||
| private class SinkFromModel extends Sink { | ||
| SinkFromModel() { this = ModelOutput::getASinkNode("prompt-injection").asSink() } | ||
| } | ||
|
|
||
| private class PromptContentSink extends Sink { | ||
| PromptContentSink() { | ||
| this = OpenAI::getContentNode().asSink() | ||
| or | ||
| this = AgentSDK::getContentNode().asSink() | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * A comparison with a constant, considered as a sanitizer-guard. | ||
| */ | ||
| class ConstCompareAsSanitizerGuard extends Sanitizer, ConstCompareBarrier { } | ||
| } |
25 changes: 25 additions & 0 deletions
25
python/ql/lib/semmle/python/security/dataflow/PromptInjectionQuery.qll
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| /** | ||
| * Provides a taint-tracking configuration for detecting "prompt injection" vulnerabilities. | ||
| * | ||
| * Note, for performance reasons: only import this file if | ||
| * `PromptInjection::Configuration` is needed, otherwise | ||
| * `PromptInjectionCustomizations` should be imported instead. | ||
| */ | ||
|
|
||
| private import python | ||
| import semmle.python.dataflow.new.DataFlow | ||
| import semmle.python.dataflow.new.TaintTracking | ||
| import PromptInjectionCustomizations::PromptInjection | ||
|
|
||
| private module PromptInjectionConfig implements DataFlow::ConfigSig { | ||
| predicate isSource(DataFlow::Node node) { node instanceof Source } | ||
|
|
||
| predicate isSink(DataFlow::Node node) { node instanceof Sink } | ||
|
|
||
| predicate isBarrier(DataFlow::Node node) { node instanceof Sanitizer } | ||
|
|
||
| predicate observeDiffInformedIncrementalMode() { any() } | ||
| } | ||
|
|
||
| /** Global taint-tracking for detecting "prompt injection" vulnerabilities. */ | ||
| module PromptInjectionFlow = TaintTracking::Global<PromptInjectionConfig>; |
24 changes: 24 additions & 0 deletions
24
python/ql/src/experimental/Security/CWE-1427/PromptInjection.qhelp
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <!DOCTYPE qhelp PUBLIC | ||
| "-//Semmle//qhelp//EN" | ||
| "qhelp.dtd"> | ||
| <qhelp> | ||
|
|
||
| <overview> | ||
| <p>Prompts can be constructed to bypass the original purposes of an agent and lead to sensitive data leak or | ||
mbaluda marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| operations that were not intended.</p> | ||
| </overview> | ||
|
|
||
| <recommendation> | ||
| <p>Sanitize user input and also avoid using user input in developer or system level prompts.</p> | ||
| </recommendation> | ||
|
|
||
| <example> | ||
| <p>In the following examples, the cases marked GOOD show secure prompt construction; whereas in the case marked BAD they may be susceptible to prompt injection.</p> | ||
| <sample src="examples/example.py" /> | ||
| </example> | ||
|
|
||
| <references> | ||
| <li>OpenAI: <a href="https://openai.github.io/openai-guardrails-python">Guardrails</a>.</li> | ||
| </references> | ||
|
|
||
| </qhelp> | ||
20 changes: 20 additions & 0 deletions
20
python/ql/src/experimental/Security/CWE-1427/PromptInjection.ql
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| /** | ||
| * @name Prompt injection | ||
| * @kind path-problem | ||
| * @problem.severity error | ||
| * @security-severity 5.0 | ||
| * @precision high | ||
| * @id py/prompt-injection | ||
| * @tags security | ||
| * experimental | ||
| * external/cwe/cwe-1427 | ||
| */ | ||
|
|
||
| import python | ||
| import semmle.python.security.dataflow.PromptInjectionQuery | ||
| import PromptInjectionFlow::PathGraph | ||
|
|
||
| from PromptInjectionFlow::PathNode source, PromptInjectionFlow::PathNode sink | ||
| where PromptInjectionFlow::flowPath(source, sink) | ||
| select sink.getNode(), source, sink, "This prompt construction depends on a $@.", source.getNode(), | ||
| "user-provided value" |
17 changes: 17 additions & 0 deletions
17
python/ql/src/experimental/Security/CWE-1427/examples/example.py
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| from flask import Flask, request | ||
| from agents import Agent | ||
| from guardrails import GuardrailAgent | ||
|
|
||
mbaluda marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| @app.route("/parameter-route") | ||
| def get_input(): | ||
| input = request.args.get("input") | ||
|
|
||
| goodAgent = GuardrailAgent( # GOOD: Agent created with guardrails automatically configured. | ||
mbaluda marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| config=Path("guardrails_config.json"), | ||
mbaluda marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| name="Assistant", | ||
| instructions="This prompt is customized for " + input) | ||
|
|
||
| badAgent = Agent( | ||
| name="Assistant", | ||
| instructions="This prompt is customized for " + input # BAD: user input in agent instruction. | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.