appsec.fyi

Python — A Practical Guide

A curated AppSec resource library covering XSS, SQLi, SSRF, IDOR, RCE, XXE, OSINT, and more.

Python: A Practical Guide

Curated and synthesized by . Last updated 2026-08-01. Synthesized from 247 of 247 curated resources. Browse all 247 Python resources →

Problem Framing

Python's widespread adoption across various domains, from web development and data science to AI/ML and system administration, makes it a prime target for attackers. Its interpreted nature, dynamic typing, and rich ecosystem of third-party packages introduce a broad attack surface. Understanding the common vulnerabilities and exploitation vectors within the Python landscape is crucial for application security professionals. This guide aims to provide a practitioner-focused overview of Python's security posture, highlighting key risks and mitigation strategies relevant to experienced security professionals.

Core Mechanics

Python's execution model, while offering flexibility, also presents inherent security challenges. The ability to dynamically execute code, load modules from arbitrary locations, and interact with the underlying operating system are powerful features that, if misused or improperly secured, can lead to severe vulnerabilities.

One fundamental mechanism is the use of built-in functions like eval() and exec(). These functions can execute arbitrary Python code passed as strings. While useful for legitimate purposes like dynamic configuration or scripting, they are a direct conduit for code injection if the input is not rigorously validated and sanitized. For instance, an attacker could supply malicious code to eval() that deletes files or executes shell commands. A safer alternative for evaluating simple literals is ast.literal_eval(), which restricts evaluation to Python literals like strings, numbers, tuples, lists, dicts, booleans, and None [1].

Another critical area is deserialization, particularly with the pickle module. pickle is designed to serialize and deserialize arbitrary Python object structures. This process can be exploited because the __reduce__ method of pickled objects can be manipulated to execute arbitrary code during deserialization [2][3]. An attacker can craft a malicious pickle payload that, when deserialized, triggers RCE. Tools like pickletools can be used to disassemble pickle byte streams, aiding in the analysis of suspicious data [S-internal-tooling]. Beyond pickle, other serialization formats like PyYAML, JSON (via libraries like jsonpickle), and marshal also present deserialization risks if used with untrusted data without proper safeguards [4].

Python's package management system, primarily pip, and its ecosystem are frequent targets for supply chain attacks. Malicious packages can be introduced to PyPI through various means, including typosquatting, compromised maintainer accounts, or CI/CD pipeline manipulation [5][6]. These poisoned packages might execute malicious code upon installation, either directly or by leveraging Python's startup hooks, such as .pth files, to achieve persistence or steal credentials [5][6]. The uv and pipx tools are modern alternatives for package management that can improve dependency management and isolation [S-internal-tooling]. Pinning dependencies with cryptographic hashes using uv lock or uv pip compile --generate-hashes is a vital defense mechanism [S-internal-tooling].

Python's standard library also contains modules that, when used incorrectly, can lead to vulnerabilities. For example, the os.system() function and the subprocess module can be used to execute shell commands. If user-supplied input is passed directly to these functions without proper sanitization, command injection becomes a significant risk [S-internal-tooling]. Similarly, network-related modules can be vulnerable if input is not validated, leading to issues like HTTP Response Splitting via CRLF injection in libraries like aiohttp [S-internal-tooling].

Notable Techniques

Several specific techniques are commonly employed by attackers targeting Python applications. Understanding these provides actionable intelligence for defense.

Insecure Deserialization: This remains a pervasive threat. Exploiting pickle is a classic example, where an attacker crafts a pickle payload that executes arbitrary code upon deserialization [2][3]. Libraries like PyYAML can be vulnerable if yaml.load() is used instead of yaml.safe_load() [4]. jsonpickle also presents similar risks [4]. Even specialized libraries like LangChain and Azure Core have seen vulnerabilities related to insecure deserialization, leading to secret extraction or RCE [7][S-aggregate-summaries]. The shelve module, which uses pickle internally, is also susceptible [4].

Code Injection: Beyond eval() and exec(), code injection can occur through various channels. This includes server-side template injection (SSTI), particularly in templating engines like Jinja2, where malformed inputs can lead to arbitrary code execution [8]. AI-generated code in LLM frameworks like Langflow and CrewAI has also been identified as a vector for code injection due to insufficient validation [S-aggregate-summaries].

Supply Chain Attacks: This category is broad and constantly evolving.

Credential Theft: Attackers are adept at harvesting credentials from various sources. This includes API keys stored insecurely in code or environment variables, cloud provider credentials, and even secrets embedded in malware or exfiltrated through custom backdoors. The LiteLLM compromise included credential theft mechanisms [5][6].

Directory Traversal: Vulnerabilities like directory traversal can occur in web applications when user-supplied input is used in file path operations without proper sanitization. The startswith() method's limitations were exploited in Flask-Admin to achieve this [9].

Denial of Service (DoS): Excessive resource consumption can lead to DoS. The python-Pillow library has had vulnerabilities causing DoS via memory exhaustion [S-aggregate-summaries]. The Starlette framework has also seen DoS vulnerabilities related to multipart form data handling and ReDoS [S-aggregate-summaries].

Vulnerability Exploitation via Malformed HTTP Headers: The "BadHost" vulnerability in Starlette (affecting frameworks like FastAPI, vLLM, and LiteLLM) allows access control bypass by manipulating the Host header [10]. This impacts AI agents by potentially rerouting requests or altering their intended targets.

Remote Code Execution (RCE): This is a common outcome of many of the above techniques. Insecure deserialization, code injection via SSTI, and exploiting vulnerable dependencies can all lead to RCE. Notable examples include CVE-2026-45829 in ChromaDB via embedded model execution [11], CVE-2026-5760 in SGLang via GGUF files and Jinja2 SSTI [8], and CVE-2026-39987 in Marimo via unauthenticated WebSocket endpoints [S-aggregate-summaries].

Privilege Escalation: In specific environments, vulnerabilities in Python or the underlying OS can lead to privilege escalation. CVE-2026-31431 (Copy Fail) in the Linux Kernel allows privilege escalation with a small Python script [12].

AI/ML Model Security: The growing use of AI/ML models in Python applications introduces new attack vectors. Malicious GGUF files can exploit vulnerabilities in model loaders, leading to RCE [13][8]. Insecure deserialization can also impact ML frameworks [11].

Detection & Prevention

A multi-layered approach is necessary to detect and prevent Python-related vulnerabilities.

Static Analysis (SAST): SAST tools are invaluable for identifying potential vulnerabilities in source code without executing it.

Dynamic Analysis (DAST): DAST tools test running applications for vulnerabilities. While less Python-specific, they are crucial for web applications. Tools like Wapiti can be used for web vulnerability scanning [S-internal-tooling].

Dependency Scanning: Identifying known vulnerabilities in third-party packages is critical.

Secure Coding Practices:

Runtime Security:

Supply Chain Security:

Tooling

A robust set of tools is available for securing Python applications.

Static Analysis:

Dependency Management & Scanning:

Security Testing & Analysis:

Runtime & System Tools:

Network Analysis:

Secure Development Frameworks:

Recent Developments

The Python security landscape is dynamic, with new vulnerabilities and attack vectors emerging regularly.

AI/LLM Security: The rapid integration of Large Language Models (LLMs) into Python applications has introduced new attack surfaces. Vulnerabilities in libraries handling AI models, such as ChromaDB's RCE via embedded models [11] and SGLang's RCE via malicious GGUF files [8], highlight the risks. Code injection via AI-generated code in frameworks like Langflow and CrewAI is also a growing concern [S-aggregate-summaries].

Sophisticated Supply Chain Attacks: Attackers are becoming more sophisticated in their supply chain attacks. The compromise of the LiteLLM package via a poisoned security scanner's CI/CD pipeline is a stark reminder of how attackers can pivot through development workflows to achieve their goals [5][6]. The TeamPCP campaign, involving multiple compromised Python packages like DurableTask and LiteLLM, demonstrates sustained and targeted efforts [27][28]. The Shai-Hulud worm campaign's reach across package repositories underscores the interconnectedness of the software ecosystem [S-aggregate-summaries].

PickleScan Bypasses: Despite the existence of tools like Picklescan for detecting malicious pickle files, attackers have found multiple ways to bypass it. This includes using specific file extensions, manipulating ZIP archive flags, and subclassing dangerous imports [15]. This emphasizes that Picklescan should not be the sole defense against deserialization attacks.

Exploiting Undocumented Parameters: The discovery of RCE in PLY (Python Lex-Yacc) via an undocumented picklefile parameter illustrates how attackers can leverage obscure or internal features of libraries for exploitation [29].

Infrastructure-as-Code (IaC) and CI/CD Security: As organizations increasingly rely on IaC and automated CI/CD pipelines, these systems become prime targets. Compromises like the one affecting the Trivy CI/CD pipeline, which then led to the LiteLLM backdoor, demonstrate the cascading impact of a single compromised infrastructure component [6].

Emerging Deserialization Vulnerabilities: New deserialization vulnerabilities continue to be found in various libraries, including LangChain Core [7] and Azure Core [S-aggregate-summaries].

Where to Go Deeper

For practitioners seeking to deepen their understanding of Python security, several avenues are available:

Sources cited in this guide

  1. Code injection in Python: examples and prevention — snyk.io
  2. Exploiting Python Pickles - David Hamann — davidhamann.de
  3. How Python Pickle Deserialization Security Exploit Works — securecodingpractices.com
  4. Insecure Deserialization in Python: Attack Techniques and Secure Coding — redfoxsec.com
  5. How a Poisoned Security Scanner Became the Key to Backdooring LiteLLM — snyk.io
  6. How a Poisoned Security Scanner Backdoored LiteLLM — snyk.io
  7. CVE-2025-68664: Critical LangChain Flaw Enables Secret Extraction — socradar.io
  8. SGLang CVE-2026-5760 (CVSS 9.8) Enables RCE via Malicious GGUF Model Files — thehackernews.com
  9. How I Found a High-Severity Directory Traversal in Flask-Admin — infosecwriteups.com
  10. BadHost - One character and your AI agent switches sides — korben.info
  11. Max-severity flaw in ChromaDB for AI apps allows server hijacking — bleepingcomputer.com
  12. Linux Kernel Elevation of Privilege Vulnerability — hkcert.org
  13. llama.cpp GGUF Parser Flaws: Critical Integer Overflow Enables Arbitrary Reads in Every Local AI Stack — techtimes.com
  14. How to Set Up Semgrep for AI Code: 13 Steps 60 Min [2026] — tech-insider.org
  15. Exposing 4 Critical Vulnerabilities in Python PickleScan | Sonatype — sonatype.com
  16. How To Keep A Secret in Python Apps — talkpython.fm
  17. Running Untrusted Python Code — healeycodes.com
  18. GitHub - cle-b/httpdbg: A tool for Python developers to easily debug the HTTP(S) client requests in a Python program. — github.com
  19. pwviptbl/ProxyHunter: Aplicação Python com interface gráfica que permite configurar regras de interceptação para modificar parâmetros de requisições HTTP. Quando o navegador envia uma requisição para uma rota configurada, o proxy intercepta, modifica apenas os parâmetros especificados e encaminha a requisição mantendo todos os outros parâmetros originais. — github.com
  20. dr34mhacks/jwtauditor: JWT Auditor – Analyze, break, and understand your tokens like a pro. — github.com
  21. yo-yo-yo-jbo/python_for_researchers: Python for offensive security research — github.com
  22. Cryptography — The Hitchhiker's Guide to Python — docs.python-guide.org
  23. A Python prompt into a running process: debugging with Manhole — pythonspeed.com
  24. Usage Scapy 2.4.5. documentation — scapy.readthedocs.io
  25. fortra/impacket — github.com
  26. Show HN: Drawbridge – Drop-In SSRF Protection for Python | Hacker News — news.ycombinator.com
  27. Microsoft DurableTask Python Client Targeted in TeamPCP Cyberattack — gbhackers.com
  28. Microsoft's durabletask package on PyPi Compromised. Mini Shai Hulud attacks again... again! — aikido.dev
  29. CVE-2025-56005: PLY RCE Vulnerability — sentinelone.com
  30. Tryhackme New Room — FLIP — infosecwriteups.com
  31. Leaking internal headers in Flask Ninja with deserialization — eval.blog
  32. OWASP Pygoat — owasp.org
  33. https://www.codelivly.com/building-a-vulnerability-scanner-using-python/ — codelivly.com
  34. https://www.thepythoncode.com/article/create-reverse-shell-python — thepythoncode.com
  35. dis Disassembler for Python bytecode Python 3.9.6 documentation — docs.python.org
  36. Understanding Python Bytecode — medium.com
📚 This guide is synthesized from the full text of resources curated in the Python library, and refreshed as new material is added.