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-09-01. Synthesized from 216 of 216 curated resources. Browse all 216 Python resources →

Problem Framing

Python's widespread adoption across diverse domains, from web development and data science to AI and cloud infrastructure, makes it a prime target for attackers. Its dynamic nature, rich ecosystem of third-party packages, and the inherent complexity of modern software supply chains introduce a broad attack surface. Understanding these vulnerabilities and attack vectors is crucial for application security practitioners. Malicious actors actively exploit Python's features and its ecosystem to achieve objectives ranging from unauthorized code execution and data exfiltration to persistent system compromise and large-scale supply chain attacks [1][2][3].

Core Mechanics

The core mechanics enabling Python-based attacks often leverage language features, the package management system, and the broader execution environment.

Package Management Vulnerabilities and Supply Chain Attacks

The Python Package Index (PyPI) is the primary repository for Python packages. Malicious actors exploit this system through various means:

Insecure Deserialization

Python's built-in pickle module, along with other serialization libraries like dill, jsonpickle, and marshal, can be exploited if used to deserialize untrusted data. The __reduce__ method, in particular, allows for arbitrary code execution during the deserialization process. Libraries and frameworks that automatically deserialize user-supplied data without proper validation are prime targets [7][8][9][10][11]. This vulnerability extends to AI/ML libraries that might deserialize model data, potentially leading to RCE [12][13].

Code Injection and Dynamic Execution

Python's dynamic nature allows for code execution via functions like eval() and exec(), as well as through templating engines like Jinja2, which can suffer from Server-Side Template Injection (SSTI). Exploiting these requires an attacker to inject code that gets dynamically executed by the Python interpreter or the templating engine. The subprocess module and os.system() are also common vectors for OS command injection if not used with strictly validated inputs [14][15].

Persistence Mechanisms

Once an attacker gains initial access, persistence is critical. Python-based payloads can establish persistence through various methods:

Secret Extraction and Exfiltration

Attackers prioritize obtaining sensitive information. This includes:

Input Validation Flaws

Similar to other languages, Python applications are susceptible to input validation bypasses. This can manifest as:

Linux Kernel Vulnerabilities

While not strictly Python-specific, Python scripts can be used to exploit system-level vulnerabilities. The "Copy Fail" vulnerability (CVE-2026-31431) in the Linux kernel allowed for privilege escalation by enabling unprivileged users to perform 4-byte writes to the page cache, which could be leveraged by a Python script to gain root access [20].

Notable Techniques

Beyond the core mechanics, several specific techniques are frequently employed by attackers targeting Python environments.

Typosquatting and Name Confusion

This is a prevalent technique for distributing malicious packages. Attackers register package names that are one or two characters different from popular libraries (e.g., requesst instead of requests, or coloramaa instead of colorama) [4]. They also utilize name confusion by publishing packages with slightly altered names or by exploiting common naming conventions in project structures.

Leveraging .pth Files for Stealthy Persistence

Python's .pth files, located in site-packages directories, are automatically processed by the interpreter at startup. Malicious code can be placed within these files to execute automatically, providing a discreet method for persistence and payload delivery, as seen in attacks involving LiteLLM and elementary-data [16][17].

Insecure Deserialization Gadgets

Specific libraries and frameworks can introduce deserialization vulnerabilities. For instance, Flask Ninja has been found to leak internal headers through deserialization, and LangChain Core has a serialization injection flaw allowing secret leakage [21][22]. Exploits often involve crafting specific payloads that trigger vulnerable methods during deserialization.

Command Injection via Templating Engines (Jinja2 SSTI)

Jinja2, a popular templating engine, can be vulnerable to Server-Side Template Injection (SSTI) if user input is rendered directly without proper sanitization. This allows attackers to execute arbitrary code on the server. The xmlattr filter has been specifically identified as a vector for arbitrary HTML attribute injection in Jinja2 [23].

Exploiting Input Validation Flaws

Beyond basic path traversal, attackers exploit specific checks. For example, a single character in a Host header could bypass path controls in Starlette, leading to RCE in AI agent deployments [24]. Similarly, the startswith check has been a target for directory traversal vulnerabilities [19].

SQL Injection via Internal Django Query Parameters

Django's query parameter handling has shown vulnerabilities, such as SQL injection exploits using internal parameters like _connector and _negated in QuerySet methods [25].

Malicious Payload Embedding and Obfuscation

Payloads are often obfuscated using techniques like base64 encoding or more complex code transformations to evade static analysis and signature-based detection. Some attacks have even embedded executable code within seemingly benign files, such as audio files [2].

Multi-Stage Malware Delivery

Attackers frequently employ multi-stage attack chains. An initial dropper package might download and execute subsequent stages of malware, which could include credential stealers, info-stealers, worms, or ransomware. This layered approach allows for more sophisticated and evasive attacks [2][3].

Exploiting AI/ML Library Vulnerabilities

The increasing use of AI and ML libraries in Python applications introduces new attack vectors. Vulnerabilities have been found in libraries like Ultralytics, LiteLLM, and LangChain, often related to insecure deserialization of model metadata or CI/CD compromises [1][16][22][12]. Exploiting the instantiate() function in libraries like Hydra has also been observed for RCE [5].

Detection & Prevention

A multi-layered approach is essential for detecting and preventing Python-related security risks.

Static Application Security Testing (SAST)

SAST tools analyze source code without executing it, identifying potential vulnerabilities.

Dependency Scanning and Software Bill of Materials (SBOMs)

Given the prevalence of supply chain attacks, scrutinizing dependencies is paramount.

Runtime Security and Monitoring

Runtime analysis and continuous monitoring complement static analysis.

Secure Coding Practices

Embedding security into the development lifecycle is critical.

Sandboxing and Resource Limiting

For running untrusted code, sandboxing and resource limiting are essential.

Tooling

A range of tools aid practitioners in securing Python applications.

Static Analysis

Dependency Management and Scanning

Deserialization Analysis

Secrets Management

Web Security and Network Analysis

Runtime Security and Debugging

Cryptography

Containerization

Recent Developments

The Python security landscape is continuously evolving, with new threats and defense mechanisms emerging regularly.

AI-Powered Vulnerability Detection and Remediation

Tools are leveraging AI, including Large Language Models (LLMs), to enhance vulnerability detection and even suggest or apply fixes. Snyk Agent Fix, for instance, uses LLMs to remediate vulnerabilities with consideration for code security and functionality [42]. LLM-based tools are also emerging for specific vulnerability detection in Python code [S]. This trend promises to accelerate the security patching process, although the effectiveness of AI fixes can vary, and human oversight remains critical.

Sophisticated Supply Chain Attacks

The sophistication of supply chain attacks continues to grow. Recent incidents have shown attackers leveraging compromised CI/CD systems not just for initial injection but for multi-stage payloads, data exfiltration, and establishing persistent backdoors [2][5][43]. The .pth file mechanism has been notably exploited for stealthy persistence post-compromise [16].

Bypasses for Security Tools

Attackers are actively developing methods to bypass existing security tooling. Critical vulnerabilities have been discovered in Picklescan, a tool designed to detect malicious pickle files, demonstrating that even specialized security tools can have exploitable weaknesses [11][29][13]. These bypasses often involve subtle manipulation of file formats (e.g., ZIP archives) or leveraging less-obvious language features.

Framework and Library Vulnerabilities

Vulnerabilities continue to be found within popular Python frameworks and libraries. Recent examples include RCE in Azure Core Python Library [12], command injection in SGLang via crafted model files [23], and critical SQL injection in Django [25]. These findings underscore the importance of staying current with security advisories for all components of the software stack.

LLM Security Specifics

With the rise of LLMs, specific vulnerabilities related to their integration are appearing. LangChain Core has seen serialization injection flaws allowing secret extraction [22]. Exploiting AI/ML libraries through malicious model metadata or insecure deserialization is an ongoing concern [5].

Where to Go Deeper

For practitioners seeking to deepen their expertise in Python security, several resources and avenues are recommended.

Official Python Documentation and Security Advisories

The Python Software Foundation (PSF) provides official documentation, and security advisories are crucial for understanding the latest language-level security concerns. Monitoring release notes for security-related changes is a proactive measure.

Security Blogs and Research Publications

Tooling Documentation and Tutorials

Hands-on Learning Platforms

Books and Courses

Dedicated books and courses on Python security, secure coding practices, and application security principles are invaluable for structured learning.

Community Engagement

Participating in security communities, forums, and mailing lists can provide real-time insights into emerging threats and defense strategies. Following security researchers on social media platforms also offers a stream of timely information.

Sources cited in this guide

  1. Ultralytics AI Library Hacked via GitHub for Cryptomining — wiz.io
  2. How a Poisoned Security Scanner Became the Key to Backdooring LiteLLM — snyk.io
  3. Microsoft's durabletask package on PyPi Compromised. Mini Shai Hulud attacks again... again! — aikido.dev
  4. Malicious PyPI Packages Deliver SilentSync RAT — zscaler.com
  5. Compromised LiteLLM PyPI Package Delivers Credential Stealer — sonatype.com
  6. Hunting Leaked PyPI Tokens: 62 Live, 125 Packages Exposed — blog.gitguardian.com
  7. Escalating Deserialization Attacks in Python — frichetten.com
  8. Exploiting Python Pickles - David Hamann — davidhamann.de
  9. How Python Pickle Deserialization Security Exploit Works — securecodingpractices.com
  10. Insecure Deserialization in Python: Attack Techniques and Secure Coding — redfoxsec.com
  11. Picklescan Allows RCE via Malicious Pickle File — github.com
  12. CVE-2026-21226: Azure Core Python Library RCE Vulnerability — sentinelone.com
  13. PyTorch Users at Risk: 3 Zero-Day PickleScan Vulnerabilities | JFrog — jfrog.com
  14. Code injection in Python: examples and prevention — snyk.io
  15. Python Security Vulnerabilities | Top Issues | Aikido — aikido.dev
  16. Three’s a Crowd: TeamPCP trojanizes LiteLLM in Continuation of Campaign — wiz.io
  17. Script Injection and Data Theft: Python Data Analysis Tool Compromised — heise.de
  18. How To Keep A Secret in Python Apps — talkpython.fm
  19. How I Found a High-Severity Directory Traversal in Flask-Admin — infosecwriteups.com
  20. Python Software Foundation - Python 3.11.0a3 to 3.15.0b2 — bishopfox.com
  21. Leaking internal headers in Flask Ninja with deserialization — eval.blog
  22. CVE-2025-68664: Critical LangChain Flaw Enables Secret Extraction — socradar.io
  23. SGLang CVE-2026-5760 (CVSS 9.8) Enables RCE via Malicious GGUF Model Files — thehackernews.com
  24. BadHost - One character and your AI agent switches sides — korben.info
  25. Critical SQL Injection Vulnerability in Django (CVE-2025-64459) — endorlabs.com
  26. Bandit: Python Static Application Security Testing Guide — dev.to
  27. Python SAST Tools: Free & Paid Solutions for Secure Code Analysis — bito.ai
  28. A Python prompt into a running process: debugging with Manhole — pythonspeed.com
  29. Exposing 4 Critical Vulnerabilities in Python PickleScan | Sonatype — sonatype.com
  30. Running Untrusted Python Code — healeycodes.com
  31. Reversing Pickles with r2pickledec — blog.doyensec.com
  32. GitHub - wapiti-scanner/wapiti: Web vulnerability scanner written in Python3 — github.com
  33. GitHub - xnl-h4ck3r/knoxnl: This is a python wrapper around the amazing KNOXSS API by Brute Logic — github.com
  34. GitHub - danialhalo/SqliSniper: Advanced Time-based Blind SQL Injection fuzzer for HTTP Headers — github.com
  35. Download and Installation Scapy 2.4.5. documentation — scapy.readthedocs.io
  36. Usage Scapy 2.4.5. documentation — scapy.readthedocs.io
  37. A Beginners Guide to Python for Cybersecurity — coursereport.com
  38. python/scapy DNS sniffer and parser - Stack Overflow — stackoverflow.com
  39. How to Brute-Force SSH Servers in Python — thepythoncode.com
  40. How to scrape websites with Python and BeautifulSoup — link.medium.com
  41. 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
  42. Benchmarking Secure-and-Functional Remediation and How Snyk Agent Fix Lifts Frontier-Model Fix Rates by over 14% — snyk.io
  43. LiteLLM PyPI Package Compromised in TeamPCP Supply Chain Attack — bleepingcomputer.com
  44. Insecure Deserialization in Python | Semgrep — semgrep.dev
  45. Quickstart Web3.py 5.23.1 documentation — web3py.readthedocs.io
📚 This guide is synthesized from the full text of resources curated in the Python library, and refreshed as new material is added.