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-06-29. Synthesized from 241 of 241 curated resources. Browse all 241 Python resources →

Problem Framing

Python's pervasive use in application development, scripting, and security tooling presents a dual-edged sword. Its accessibility and extensive ecosystem simplify development but also create vectors for sophisticated attacks. Application security professionals must contend with vulnerabilities stemming from the language's dynamic nature, its package management system, and the inherent risks of executing untrusted code. The threat landscape is evolving, with attackers increasingly targeting supply chains, exploiting deserialization flaws, and leveraging AI-driven code generation for malicious purposes. Understanding these attack vectors and the underlying mechanics is crucial for effective defense.

Core Mechanics

Python's execution model and runtime environment are central to many security vulnerabilities. The interpreter's flexibility, while powerful, can be a liability.

Dynamic Execution and Code Injection

Python's ability to execute code dynamically, particularly through functions like eval() and exec(), is a prime target for injection attacks [1]. When untrusted input is passed to these functions without proper sanitization, attackers can achieve arbitrary code execution. This extends to the use of subprocess or os.system with unsanitized user input, leading to command injection [2].

Deserialization Vulnerabilities

Python's serialization mechanisms, particularly the pickle module, are notoriously insecure. pickle.load() can execute arbitrary code if it encounters malicious serialized objects, often exploiting the __reduce__ method [3]. This vulnerability has been observed in various libraries, including Azure Core [4], LangChain Core [5], and even in security tools designed to scan for such issues, like Picklescan, which had bypasses exploiting pip.main() within pickle payloads [6][7][8]. Other serialization formats like YAML, when parsed insecurely with libraries such as PyYAML, can also lead to code execution [9].

The Python Packaging Ecosystem

PyPI (Python Package Index) is the primary distribution point for Python packages. Its open nature, however, makes it susceptible to supply chain attacks. Attackers employ techniques like typosquatting, name confusion, and account takeovers to distribute malicious packages [10][9]. These packages can embed malware, credential stealers, or persistence mechanisms. The compromise of legitimate packages, such as LiteLLM [11] and DurableTask [9], demonstrates the severity of these threats. Furthermore, compromised CI/CD pipelines, like GitHub Actions, can be exploited to inject malicious code into packages before they are published [12].

Implicit Code Execution via .pth Files

Python's mechanism for adding directories to sys.path at startup via .pth files can be abused. Attackers can place malicious .pth files in locations where Python automatically loads them, causing their code to execute implicitly during interpreter initialization [10]. This technique has been used for persistence and credential exfiltration.

Concurrency and Asynchronous Operations

While beneficial for performance, Python's concurrency and asynchronous programming models can introduce subtle vulnerabilities. For example, an out-of-bounds write vulnerability was identified in Python's Windows asyncio implementation [13]. Securely managing threads and processes is paramount to avoid race conditions and other concurrency-related bugs.

Notable Techniques

Several specific attack techniques leverage Python's features and ecosystem to achieve malicious objectives.

Supply Chain Attacks via PyPI and CI/CD

Attackers target the Python supply chain through multiple avenues. Malicious code can be injected directly into packages published on PyPI, often disguised as legitimate libraries or through typosquatting [10][9]. Compromised GitHub accounts and CI/CD workflows provide an entry point to inject malware into the build and deployment process, leading to compromised packages being distributed [12]. The TeamPCP campaign is a prominent example, compromising packages like LiteLLM and DurableTask [10][9].

Exploiting .pth Files for Persistence and Exfiltration

The .pth file mechanism, used by Python to automatically add directories to sys.path on startup, has been exploited for stealthy persistence and credential exfiltration [10]. By placing a malicious .pth file in an accessible location, attackers ensure their code runs every time the Python interpreter starts, enabling continuous data theft or control.

Malicious Model Loading (GGUF Parser Flaws)

In the context of AI/ML, vulnerabilities in parsers for model formats like GGUF have been discovered. These flaws can allow for arbitrary code execution or unauthorized data reads by crafting malicious model files [14]. This highlights the need for secure parsing and validation of AI model artifacts.

Code Injection via eval(), exec(), and Dynamic Construction

Beyond direct injection into these functions, attackers can exploit scenarios where code is dynamically constructed or evaluated based on user-provided data. This includes injection via Jinja2 Server-Side Template Injection (SSTI) [15] or by leveraging LLM-generated code in validation phases where it's executed without proper sandboxing [16].

Exploiting Undocumented Features and Library Internals

Attackers often probe libraries for undocumented features or internal mechanisms that can be abused. A notable example is the RCE vulnerability in PLY, exploiting an undocumented picklefile parameter in the yacc() function [17][16]. Similarly, bypassing security scanners by calling legitimate functions like pip.main() within pickle payloads is a sophisticated evasion technique [6].

Insecure Deserialization with pickle and Other Modules

The pickle module's propensity for executing arbitrary code is a persistent threat [3]. Exploitation often involves crafting malicious serialized objects. Beyond pickle, other serialization methods like shelve and marshal can also be vulnerable if mishandled [9].

Command Injection via subprocess and System Commands

When Python scripts interact with the operating system by executing shell commands, unsanitized input can lead to command injection [2]. Libraries like subprocess and functions like os.system are common vectors if not used with extreme caution and robust input validation.

Leveraging LLM-Generated Code for Exploitation

The rise of LLMs in code generation introduces new attack vectors. Prompt injection can influence LLMs to generate code that, when executed in an application's validation or processing phase, leads to vulnerabilities like RCE [16]. This underscores the need for rigorous review and sandboxing of any LLM-generated code.

Obfuscated Python Code for Malware Delivery

Malware authors frequently obfuscate their Python code to evade detection by signature-based antivirus software and manual analysis. Techniques range from simple string obfuscation to complex packing methods, requiring deobfuscation tools and techniques for analysis [18].

Detection & Prevention

Mitigating Python-specific security risks requires a multi-layered approach encompassing secure coding practices, dependency management, runtime security, and continuous monitoring.

Secure Coding Practices

Dependency Scanning and Supply Chain Security

Runtime Security and Monitoring

Web Application Security Specifics

Binary and Low-Level Analysis

For analyzing compiled Python artifacts or understanding low-level interactions, tools like Ghidra and IDA Pro are invaluable. Python itself can be used as a scripting language within these environments or for direct interaction with system calls.

Tooling

A rich ecosystem of tools aids application security professionals in analyzing, defending, and attacking Python applications.

Static Analysis Security Testing (SAST)

Dynamic Analysis Security Testing (DAST) and Web Scanners

Dependency Scanning and Software Composition Analysis (SCA)

Runtime Security and Debugging

Reverse Engineering and Malware Analysis

Network Security Tools

Cryptography and Secrets Management

Web Scraping and Automation

Recent Developments

The security landscape for Python applications is dynamic, with new vulnerabilities and attack techniques emerging regularly.

AI/ML Model Security and Supply Chain Risks

The increasing adoption of AI/ML has introduced new attack surfaces. Vulnerabilities in AI model parsers (e.g., GGUF) and the serialization of models pose risks of arbitrary code execution [14]. The compromise of AI libraries via CI/CD pipelines, such as Ultralytics, highlights the intersection of AI development and supply chain security [12].

Escalation of Supply Chain Attacks

Attackers are refining their methods for compromising the Python supply chain. Beyond simple package poisoning, techniques include leveraging compromised GitHub accounts and tokens to inject malware into build pipelines. The speed at which vulnerabilities are discovered and exploited necessitates rapid patching and continuous monitoring.

Advanced Deserialization Exploitation

While pickle vulnerabilities are well-known, attackers continue to find novel ways to exploit them, including bypassing security scanners like Picklescan by leveraging legitimate functions or undocumented library features [6][7][8].

LLM-Generated Code Vulnerabilities

The use of Large Language Models (LLMs) in code generation introduces new avenues for attack. Prompt injection can lead to LLMs generating malicious code that is then executed within applications, bypassing traditional security controls [16].

Exploitation of Cloud-Native Python Applications

As Python applications are increasingly deployed in cloud environments, vulnerabilities in libraries used for cloud interactions, like Azure Core, become critical [4]. Attacks targeting cloud tokens and credentials exfiltrated from these applications are a growing concern.

Zero-Day Exploitation in Widely Used Libraries

Critical vulnerabilities continue to be found in widely used libraries and frameworks. Examples include the BadHost vulnerability in Starlette/FastAPI affecting path-based access controls [14], and numerous issues in AI/ML libraries and frameworks. The rapid patching and disclosure cycles mean security teams must remain vigilant.

Where to Go Deeper

For application security practitioners seeking to deepen their understanding of Python security, several resources and areas of focus are recommended.

OWASP Resources

The Open Web Application Security Project (OWASP) provides invaluable guidance. The OWASP Top 10 list is a fundamental reference for web application security. Specific OWASP projects like OWASP Pygoat offer hands-on learning through intentionally vulnerable applications [40].

Security Community Blogs and Advisories

Follow blogs from security research firms and individual researchers who frequently publish detailed analyses of Python vulnerabilities. Sites like Snyk, SentinelOne, BleepingComputer, and various security news outlets are excellent sources for timely information [23][4][11].

Python Enhancement Proposals (PEPs)

Understanding the rationale behind Python's design and evolution, as documented in PEPs, can provide context for certain security behaviors and features.

Deep Dives into Specific Vulnerability Classes

Hands-on Labs and CTFs

Participating in Capture The Flag (CTF) competitions that include Python challenges, or setting up local labs with intentionally vulnerable applications like OWASP Pygoat, provides practical experience in identifying and exploiting vulnerabilities.

Python Security Tooling Mastery

Become proficient with the SAST, DAST, SCA, and reverse engineering tools mentioned earlier. Understanding their capabilities and limitations is crucial for effective security assessments. For example, mastering Scapy for network traffic analysis or Bandit for static code review can significantly enhance an investigator's toolkit [35][19].

Community Engagement

Engage with the Python and cybersecurity communities through forums, mailing lists, and conferences. Sharing knowledge and learning from others' experiences is a continuous process.

Framework-Specific Security Guidance

For applications built with specific frameworks like Django or Flask, consult their respective security documentation and best practices. Frameworks often provide built-in tools and patterns to mitigate common vulnerabilities [26].

Sources cited in this guide

  1. Code injection in Python: examples and prevention — snyk.io
  2. Command injection in Python: examples and prevention — snyk.io
  3. Insecure Deserialization in Python | Semgrep — semgrep.dev
  4. CVE-2026-21226: Azure Core Python Library RCE Vulnerability — sentinelone.com
  5. CVE-2025-68664: Critical LangChain Flaw Enables Secret Extraction — socradar.io
  6. CVE-2025-1716 Sonatype Security Advisory — sonatype.com
  7. Exposing 4 Critical Vulnerabilities in Python PickleScan | Sonatype — sonatype.com
  8. PyTorch Users at Risk: 3 Zero-Day PickleScan Vulnerabilities | JFrog — jfrog.com
  9. Microsoft DurableTask Python Client Compromised by TeamPCP — cyberpress.org
  10. How a Poisoned Security Scanner Became the Key to Backdooring LiteLLM — snyk.io
  11. LiteLLM PyPI Package Compromised in TeamPCP Supply Chain Attack — bleepingcomputer.com
  12. Ultralytics AI Library Hacked via GitHub for Cryptomining — wiz.io
  13. Python Vulnerability Allows Out-of-Bounds Write on Windows Systems — cybersecuritynews.com
  14. BadHost - One character and your AI agent switches sides — korben.info
  15. SGLang CVE-2026-5760 (CVSS 9.8) Enables RCE via Malicious GGUF Model Files — thehackernews.com
  16. Critical Python PLY Library Vulnerability Enables RCE — cyberpress.org
  17. CVE-2025-56005: PLY RCE Vulnerability — sentinelone.com
  18. Programming Languages for Cyber Security: What the Tools Use — latesthackingnews.com
  19. Langflow RCE Flaw Lets Attackers Execute Arbitrary Python Code Without Authentication — gbhackers.com
  20. How to store your users' API keys securely in Django ? — photondesigner.com
  21. How To Keep A Secret in Python Apps — talkpython.fm
  22. Millions of AI agents imperiled by critical vulnerability in open source package — arstechnica.com
  23. Understanding and mitigating the Jinja2 XSS vulnerability (CVE-2024-22195) — snyk.io
  24. Running Untrusted Python Code — healeycodes.com
  25. GitHub - apify/crawlee-python: Crawlee—A web scraping and browser automation library for Python to build reliable crawlers. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with BeautifulSoup, Playwright, and raw HTTP. Both headful and headless mode. With proxy rotation. — github.com
  26. Pygoat - Learn Django security the hard way - Speaker Deck — speakerdeck.com
  27. Critical SQL Injection Vulnerability in Django (CVE-2025-64459) — endorlabs.com
  28. GitHub - mkalioby/django-mfa2: A Django app that handles MFA, it supports TOTP, U2F, FIDO2 U2F (Webauthn), Email Token and Trusted Devices — github.com
  29. GitHub - wapiti-scanner/wapiti: Web vulnerability scanner written in Python3 — github.com
  30. A Python prompt into a running process: debugging with Manhole — pythonspeed.com
  31. A Python prompt into a running process: debugging with Manhole — pythonspeed.com
  32. Let’s create a Python Debugger together: Part 1 | Mostly nerdless — mostlynerdless.de
  33. The easy way to concurrency and parallelism with Python stdlib — bitecode.dev
  34. Reversing Pickles with r2pickledec — blog.doyensec.com
  35. Usage Scapy 2.4.5. documentation — scapy.readthedocs.io
  36. Malware extraction in Python with Scapy — link.medium.com
  37. python/scapy DNS sniffer and parser - Stack Overflow — stackoverflow.com
  38. fortra/impacket — github.com
  39. How to Brute-Force SSH Servers in Python — thepythoncode.com
  40. OWASP Pygoat — owasp.org
📚 This guide is synthesized from the full text of resources curated in the Python library, and refreshed as new material is added.