Detecting Python Injection Vulnerabilities with AST Analysis

This article explains how Python injection flaws—such as OS command, code, SQL, and arbitrary file download attacks—can be identified by analyzing abstract syntax trees, tracking controllable parameters, and implementing static checks to flag dangerous function calls.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Detecting Python Injection Vulnerabilities with AST Analysis

0x01 Introduction

Python’s simplicity and rich libraries have driven its widespread adoption, but unsafe coding practices can lead to serious security issues. This article examines Python injection problems by analyzing source code, constructing abstract syntax trees (AST), and tracing data flows to locate injection points.

0x02 Injection Scenarios

Common injection cases in web applications include:

OS command injection : using dangerous functions such as os.system, os.popen, commands.getoutput, commands.getstatusoutput, subprocess. Example:

def myserve(request, fullname): os.system('sudo rm -f %s' % fullname)

Code injection : execution of arbitrary code via eval. Example: def eval_test(request, login): login = eval(login) SQL injection : unsafe string formatting in SQL statements. Example:

def getUsers(user_id): sql = 'select * from auth_user where id =%s' % user_id; cur.execute(sql)

Arbitrary file download : uncontrolled file paths in response generation. Example:

def export_task(request, filename): return HttpResponse(filename)

0x03 Detection Principle

All scenarios share the use of dangerous functions with controllable arguments. By validating these arguments—ensuring they are numeric, sanitized paths, or free of special symbols—before invoking the functions, injection risks can be mitigated. The challenge is to track whether a parameter remains controllable throughout its propagation.

0x04 Python AST

Regular expressions are insufficient for tracking parameter flow; instead, Python’s built‑in ast module (or the optimized PySonar wrapper) can represent source code as a tree of dictionaries.

File representation : a module node contains a body list of function, class, and other statements, e.g. {"body":[{},{}],"filename":"test.py","type":"module"}.

Function representation : a FunctionDef node includes fields such as name, args, body, and decorator_list. Example fields: type=FunctionDef, name=is_this_subdomain, args=args, kwarg, lineno, etc.

Class representation : a ClassDef node contains name, bases, body, and other metadata.

Example snippet : the code if type not in ["RSAS", "BVS"]: return HttpResponse("2") yields an AST where the Compare node represents the condition, with left as type, ops as not in, and comparators as the list.

0x05 Implementation of Injection Detection

The detection process consists of two steps: (1) maintain a list of dangerous functions; when an AST node calls a function in this list, flag the line. (2) Trace the arguments of the dangerous call back to the outer function’s parameters, considering five propagation patterns:

Attribute access (e.g., request.GET).

String concatenation using + or %.

Slicing operations.

List comprehensions based on a controllable variable.

Simple wrapper functions that return unfiltered strings.

If an assignment follows any of these patterns, the resulting value is added to a controllable‑parameter list, and the analysis continues recursively. Certain early‑exit cases—such as checks with os.path.isdir followed by return None or range‑limited checks returning a response—are excluded from further tracing.

0x06 Conclusion

Automating the detection of Python injection vulnerabilities through AST analysis reduces reliance on manual code review and helps uncover hidden security flaws. While the current approach has limitations—especially in handling class methods and imported functions—it demonstrates a practical static‑analysis technique for improving code security.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonASTSecurityinjection
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.