Problem Framing
Python's dynamic nature, extensive ecosystem, and ease of use make it a popular choice for a wide range of applications, from web services and data science to scripting and automation. However, these same characteristics can introduce significant security vulnerabilities if not managed carefully. Application security practitioners must understand Python's inherent risks, particularly in areas like deserialization, supply chain integrity, code execution, and secrets management, to effectively secure Python-based systems.
Core Mechanics
Python's security landscape is shaped by several core mechanics:
- Dynamic Typing and Interpretation: Python's interpreted nature and dynamic typing allow for flexible code execution but can also make certain types of vulnerabilities, such as type confusion or unintended code execution, harder to detect at static analysis time.
- Serialization and Deserialization: Python's built-in serialization modules like
pickleare powerful but extremely dangerous when used with untrusted data. Thepicklemodule, in particular, can execute arbitrary code during deserialization via the__reduce__method [1][2][3][4][5]. Other serialization formats can also be vulnerable if not handled with care. - Package Management: The Python Package Index (PyPI) is a vast repository for third-party libraries. However, it is also a prime target for supply chain attacks, where malicious packages are published to trick developers into installing them, often through typosquatting or by compromising legitimate package maintainers [6][7][8][9][10][11][12][13].
- Dynamic Execution and Evaluation: Functions like
eval(),exec(), and thesubprocessmodule, when used with unsanitized user input or dynamically constructed commands, open the door to code injection and command execution vulnerabilities [14][15][16]. - Import System: Python's import mechanism can be abused. For example, the presence of
.pthfiles in directories Python searches for modules can lead to code execution during startup, offering a persistence mechanism for attackers [7][8][10]. - Sandboxing Limitations: While Python offers mechanisms for restricting code execution, achieving true sandboxing for untrusted Python code can be challenging. Exploits have been found that escape sandboxes by leveraging features like structural pattern matching or insecure use of introspection [17][18].
- Web Frameworks and Templating: Popular web frameworks often have their own security considerations. Server-Side Template Injection (SSTI) is a common vulnerability in templating engines like Jinja2, which can lead to Remote Code Execution (RCE) if user input is used unsafely within templates [19][20][21].
Notable Techniques
Several techniques are frequently leveraged by attackers targeting Python applications:
- Deserialization of Untrusted Data (CWE-502): This is a pervasive vulnerability. For example, the Ultralytics library's
load_dataset_cache_filefunction was found to be vulnerable to RCE via insecure pickle deserialization [22]. Similarly, Xoscar allowed unauthenticated RCE through actor message deserialization [23], and Serena suffered from RCE via insecure pickle deserialization of LSP symbol caches [24]. Flask-Ninja's HttpBearer component could leak internal headers through deserialization gadgets [25]. Azure Core Python library also had a critical RCE due to insecure deserialization [26]. LangChain Core had a vulnerability (CVE-2025-68664) that allowed secret leakage or object instantiation via the 'lc' key, exploiting its serialization mechanism [27]. Fickling's handling ofcProfile.run()in pickle analysis led to RCE (CVE-2026-22607) [28]. PLY had an undocumentedpicklefileparameter leading to RCE (CVE-2025-56005) [29]. Exploitingshelve, which relies onpickle, is another vector [4]. - Server-Side Template Injection (SSTI): This allows attackers to inject malicious template code that gets executed on the server. For instance, Jinja2 has been a target, with filter bypasses enabling RCE [20]. SGLang had an RCE via malicious GGUF model files exploiting Jinja2 SSTI [30].
- Command Injection: This occurs when unsanitized user input is used to construct system commands. This can be achieved through functions like
os.system()or thesubprocessmodule. Thesubprocessmodule itself is not inherently unsafe, but its misuse with untrusted input is a common cause of vulnerabilities [14][15][16]. Langflow experienced a code injection vulnerability viaexec()(CVE-2026-33017) [31]. CrewAI had multiple RCE vulnerabilities, including through Docker fallback (CVE-2026-2287) and via its Code Interpreter tool falling back to SandboxPython [32]. Langflow's Agentic Assistant had an RCE via LLM-generated code execution (CVE-2026-33873) [33]. - Directory Traversal: Improper validation of file paths allows attackers to access files outside the intended directory. Flask-Admin was affected by such a vulnerability due to its use of
startswith()for path validation [34]. CrewAI also suffered from arbitrary local file read via a JSON loader (CVE-2026-2285) [32]. - Privilege Escalation: Vulnerabilities in input validation or kernel logic can lead to privilege escalation. Python 3.11.0a3 to 3.15.0b2 had insecure input validation on Windows, potentially leading to privilege escalation [35]. The Linux Kernel 'Copy Fail' vulnerability (CVE-2026-31431) can be leveraged for root access [36][37][38].
- Authentication Bypass: Vulnerabilities like Host header manipulation can bypass authentication. Starlette's BadHost vulnerability (CVE-2026-48710) allowed authentication bypass by manipulating the Host header [39]. Marimo had a pre-authenticated RCE via its WebSocket endpoint lacking authentication (CVE-2026-39987), which was rapidly exploited for credential theft [40].
- Supply Chain Attacks: This is a significant threat vector.
- Malicious Packages on PyPI: Attackers use typosquatting or compromise legitimate packages. Examples include 'sisaws' and 'secmeasure' packages delivering the SilentSync RAT [41], and the 'colorama' copycat package with advanced backdoors [42].
- Compromised CI/CD Pipelines: The LiteLLM package was trojanized by TeamPCP, reportedly via a compromise of the CI/CD pipeline (Trivy, Checkmarx KICS) [8][42]. This involved versions 1.82.7 and 1.82.8. TeamPCP also compromised Durable Task's Microsoft Python client [9][10].
- Exploitation of Startup Hooks: Malicious
.pthfiles in Python's module search path can execute code at interpreter startup, providing persistence. This was seen in the LiteLLM attack [7][8][10]. - Typo-squatting and Domain Takeovers: Attackers can register similar domain names or exploit legacy bootstrap scripts to compromise package management systems like PyPI [12].
- Malicious Model Files: In AI/ML contexts, malicious model files (e.g., GGUF) can contain exploits like Jinja2 SSTI [30]. NeMo and Uni2TS libraries were vulnerable to RCE via malicious model metadata due to Hydra instantiation [30].
- Credential Harvesting and Exfiltration: Attackers actively seek to steal credentials from environment variables, SSH keys, cloud tokens, and other sensitive sources. The LiteLLM compromise, for instance, delivered a credential stealer [42].
- Exploiting Structural Pattern Matching: AWS MCP's Python sandbox escape was achieved by exploiting structural pattern matching and
__match_args__[17]. - Container Breakout: Vulnerabilities like shared page cache issues can enable attackers to break out of containers [37].
- Use of Obfuscated Code: Attackers often use obfuscation to evade detection, making analysis more difficult [8][11].
- Cross-Site Scripting (XSS) in Templating Engines: Jinja2 has had XSS vulnerabilities, such as CVE-2024-22195 [21]. AIOHTTP also had an XSS vulnerability due to HTTP Response Splitting (CVE-2026-34519) [43].
- Insecure Use of
eval()and Related Functions: Directly usingeval()orexec()with untrusted input is a direct path to RCE [14][15]. - Exploiting Undocumented Features: The PLY library's undocumented
picklefileparameter was used for RCE [29]. - Arbitrary File Read: CrewAI had a vulnerability allowing arbitrary local file read via a JSON loader (CVE-2026-2285) [32].
- Sandbox Escapes: Redash had an unpatched Python sandbox escape vulnerability that granted attackers full server access [18].
- Bypassing Static Analysis Tools: Techniques exist to bypass tools like Picklescan. For example, using
pip.main()can allow RCE by enabling the installation of malicious packages [44]. PickleScan itself had multiple bypass vulnerabilities related to file extensions, ZIP archive handling, import blacklists, and hidden file detection [45][46]. - File Extension Bypass and Archive Manipulation: Attackers use techniques like file extension bypasses and ZIP archive manipulation to evade malware detection [45].
- Monkey-Patching: Modifying classes or modules at runtime can be used for malicious purposes [47].
- SSRF via Unvalidated URLs: CrewAI's RAG search tools were vulnerable to SSRF [32].
- JWT Security Testing: Techniques like bruteforcing, algorithm confusion, and KID injection are used to compromise JWT-based authentication [14].
- Reverse Shells: Implementing reverse shells is a common post-exploitation technique [48].
- Leveraging Low-Level APIs: Using
ctypesto interact with low-level APIs or dynamically loading Python libraries from C are advanced techniques that can be misused [14]. - Obfuscation: Attackers use obfuscation techniques to hide malicious code [8][11].
Detection & Prevention
Effective security for Python applications requires a multi-layered approach:
- Secure Coding Practices:
- Input Validation: Strictly validate all user-supplied input to prevent injection attacks (SQLi, command injection, SSTI). Sanitize and validate data before using it in database queries, system commands, or template rendering.
- Avoid Insecure Deserialization: Never deserialize data from untrusted sources using
pickle. Use safer alternatives like JSON or YAML with safe loaders, or consider schema-based serialization. Ifpicklemust be used, ensure the data source is absolutely trusted and consider integrity checks. - Secure File Handling: Implement robust path validation to prevent directory traversal.
- Secrets Management: Never hardcode secrets (API keys, passwords, tokens) directly in code. Use environment variables, secret management systems (like HashiCorp Vault, AWS Secrets Manager), or secure credential storage libraries like
keyring[49]. For GitHub Actions, use the built-in secrets system [49]. - Least Privilege: Run Python applications with the minimum necessary privileges. In containerized environments, leverage security contexts and capabilities to restrict access.
- Sandboxing: For untrusted code execution, implement strict sandboxing using mechanisms like process isolation, system call filtering (
seccomp), and resource limits (setrlimit) [50]. - Secure Web Development: Follow OWASP Top 10 guidelines for web applications. Be mindful of vulnerabilities specific to templating engines and frameworks.
- Dependency Management & Supply Chain Security:
- Pin Dependencies: Use lock files (e.g., generated by
uv lockorpipenv) to ensure reproducible builds and prevent unexpected updates to vulnerable versions [51]. - Vulnerability Scanning: Regularly scan dependencies for known CVEs using tools like
pip-auditor commercial solutions like Snyk [52][53][21][54][51][8][13]. - Verify Package Sources: Exercise extreme caution when installing packages from PyPI. Be aware of typosquatting and verify the authenticity of packages, especially those from less-known maintainers. Consider using trusted package repositories and signing mechanisms.
- Secure Publishing: For organizations publishing their own packages, leverage secure publishing workflows like Trusted Publishing with OIDC [55][54].
- Pin Dependencies: Use lock files (e.g., generated by
- Static Analysis (SAST):
- Linters and SAST Tools: Employ static analysis tools like Bandit, Semgrep, or Ruff to identify potential security flaws in Python code during development [56]. These tools can detect common issues like insecure function usage (e.g.,
eval(),os.system()), hardcoded secrets, and improper input handling. - Specialized Scanners: Tools like Picklescan can analyze pickle files for potential security risks, although they can be bypassed [28][44][45][46].
- Linters and SAST Tools: Employ static analysis tools like Bandit, Semgrep, or Ruff to identify potential security flaws in Python code during development [56]. These tools can detect common issues like insecure function usage (e.g.,
- Dynamic Analysis (DAST) and Fuzzing:
- Runtime Security:
- Intrusion Detection Systems (IDS): Monitor network traffic and system logs for anomalous behavior.
- Runtime Application Self-Protection (RASP): Integrate RASP solutions that can detect and block attacks in real-time.
- Interactive Debugging for Operations: Tools like
manholeallow attaching an interactive Python prompt to a running process for debugging, but must be used with extreme caution in production due to security implications [58][59].
- Secure Configuration: Ensure that web servers, databases, and other infrastructure components are securely configured.
- Logging and Monitoring: Implement comprehensive logging of security-relevant events and monitor logs for suspicious activity.
Tooling
A variety of tools can aid in securing Python applications:
- Static Analysis (SAST):
Bandit: A widely used tool for finding common security issues in Python code [56].Semgrep: Supports Python and allows for defining custom security rules through pattern matching.Ruff: A fast Python linter that includes security-focused rules.PickleScan: For scanning Python pickle files and PyTorch models for vulnerabilities, though it has bypasses [45][46].
- Dependency Scanning:
pip-audit: Checks installed Python packages against known vulnerabilities.Snyk: A commercial platform offering vulnerability detection, license compliance, and AI-assisted remediation across dependencies [52][53][21][54][51][8][13].uv: A fast Python package manager and resolver that can also help with dependency pinning [51].CycloneDX: For generating Software Bill of Materials (SBOMs).
- Dynamic Analysis (DAST) & Fuzzing:
- Secrets Management:
keyring: A library that provides a uniform interface to OS-native secure credential storage [49].- Cloud-specific secret managers (e.g., AWS Secrets Manager, GCP Secret Manager, Azure Key Vault).
- Dedicated secret management solutions (e.g., HashiCorp Vault).
- Runtime Debugging:
- Web Scraping & Automation:
- Cryptography:
- Network Security:
- Web Vulnerability Testing:
- AI/ML Specific:
Safetensors: A safer format for AI/ML model serialization.
Recent Developments
The Python security landscape is constantly evolving:
- Sophistication of Supply Chain Attacks: Attacks are becoming more sophisticated, targeting CI/CD pipelines and using multi-stage payloads. The TeamPCP activity demonstrates advanced persistence and credential exfiltration techniques [7][8][71][31].
- Vulnerabilities in AI/ML Libraries: The rapid growth of AI/ML libraries has introduced new attack surfaces. Vulnerabilities in libraries like LangChain, SGLang, NeMo, Uni2TS, and CrewAI highlight risks associated with serialization, code execution via LLM output, and insecure model handling [27][30][32][33].
- Exploitation of Modern Language Features: Features like structural pattern matching have been exploited to bypass sandboxes [17].
- Bypassing Static Analysis: Attackers are developing increasingly effective methods to bypass static analysis tools, as seen with the vulnerabilities discovered in Picklescan [45][46].
- Cloud-Native Attack Vectors: Container breakout techniques and exploiting vulnerabilities within cloud environments remain active areas of research and exploitation [37].
- AI for Security: Conversely, AI is also being explored for vulnerability discovery and exploit generation [72][37].
- Post-Quantum Cryptography: There's ongoing effort to integrate post-quantum cryptography solutions into Python libraries to prepare for future threats [73].
- Security in Modern Web Frameworks: Vulnerabilities continue to be found in popular web frameworks and their components, requiring continuous vigilance and patching [34][39][74][43].
- Container Security in Python: Techniques for container breakout via shared page cache or exploiting misconfigurations in containerized Python applications are a growing concern [37].
Where to Go Deeper
To further deepen your understanding and capabilities in securing Python applications:
- OWASP Python Security Project: Explore resources and guidelines specific to Python security from the Open Web Application Security Project.
- PyCon and Security Track Talks: Review presentations from security-focused tracks at PyCon and other Python conferences. Many talks provide detailed technical analyses of vulnerabilities and mitigation strategies.
- Security Blogs and Research Papers: Follow blogs from security research firms (e.g., Snyk, Wiz, SentinelOne, Sonatype) and independent researchers who frequently publish detailed analyses of Python vulnerabilities.
- Source Code Review: Regularly review the source code of critical Python libraries you depend on. Understanding how they work internally can reveal potential security weaknesses.
- Hands-on Labs: Practice identifying and exploiting common Python vulnerabilities in controlled lab environments. Resources like OWASP Pygoat offer a starting point [75].
- Tooling Documentation: Deeply understand the capabilities and limitations of security tooling like Bandit, Semgrep, pip-audit, and dependency scanners.
- Python Internals: Gain a better understanding of Python's interpreter, import system, and core modules. This knowledge is invaluable for identifying complex vulnerabilities and crafting effective defenses.
- Responsible Disclosure Programs: Participate in or follow bug bounty programs related to Python applications and libraries.
- Specific Vulnerability Classes: Dedicate time to studying specific vulnerability classes relevant to Python, such as deserialization, SSTI, and supply chain attacks, with deep dives into their exploitability and defense mechanisms [1][2][3][4][19][20][6][7][8].