Python Security
Python
Python applications have unique vulnerabilities including pickle deserialization, SSTI in Jinja2, and dangerous use of eval/exec.
Dangerous Functions
python
# VULNERABLE - eval/exec with user input
user_input = request.args.get('calc')
result = eval(user_input) # RCE: __import__('os').system('id')
# VULNERABLE - pickle with untrusted data
import pickle
data = pickle.loads(user_data) # RCE via __reduce__
# Pickle RCE payload
import pickle
import os
class Exploit:
def __reduce__(self):
return (os.system, ('id',))
payload = pickle.dumps(Exploit())
# VULNERABLE - yaml.load (before PyYAML 5.1)
import yaml
data = yaml.load(user_input) # RCE possible
# SECURE - yaml.safe_load
data = yaml.safe_load(user_input)
# VULNERABLE - subprocess with shell=True
import subprocess
subprocess.call("ls " + user_input, shell=True) # Command injection
# SECURE - Use list arguments
subprocess.call(["ls", user_input], shell=False)Jinja2 SSTI
python
# VULNERABLE - User input in template string
from flask import render_template_string
@app.route('/greet')
def greet():
name = request.args.get('name')
template = f"Hello {name}!" # SSTI vulnerability
return render_template_string(template)
# Exploit: ?name={{config}}
# Exploit: ?name={{''.__class__.__mro__[1].__subclasses__()}}
# SECURE - Use template variables
@app.route('/greet')
def greet():
name = request.args.get('name')
return render_template_string("Hello {{ name }}!", name=name)