ersinkoc/security-check/sc-lang-python

Claude Code and agent skill by ersinkoc/security-check

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Python-specific security deep scan

Install

npx vskill@latest install ersinkoc/security-check/sc-lang-python

SKILL.md

The same SKILL.md was published earlier as ersinkoc/security-check/sc-lang-python.

SC: Python Security Deep Scan

Purpose

Detects Python-specific security anti-patterns and language-idiomatic attack vectors across the entire Python ecosystem, including standard library misuse, web framework pitfalls, serialization dangers, cryptographic weaknesses, and supply-chain risks. This skill goes beyond generic vulnerability scanning to identify issues that are unique to Python's dynamic nature, duck typing, and common idioms.

Activation

Activates when Python source files (.py, .pyw, .pyi) are detected in the scan target, or when Python-related configuration files (pyproject.toml, setup.py, setup.cfg, Pipfile, requirements.txt, poetry.lock, tox.ini, pytest.ini, .flake8) are present.

Checklist Reference

References references/python-security-checklist.md for the full enumeration of checks. Each category below maps to one or more checklist items.

Severity Levels

  • CRITICAL: Remote code execution, authentication bypass, data exfiltration
  • HIGH: SQL injection, SSRF, path traversal, insecure deserialization
  • MEDIUM: Weak cryptography, information disclosure, insecure defaults
  • LOW: Best-practice violations, minor information leaks, code quality

Python-Specific Vulnerability Patterns

1. Pickle Deserialization RCE

Description: Python's pickle module can deserialize arbitrary objects, including those with __reduce__ methods that execute arbitrary code. An attacker who controls pickled input can achieve full remote code execution.

Dangerous Functions:

  • pickle.loads(), pickle.load()
  • pickle.Unpickler().load()
  • cPickle.loads(), cPickle.load()
  • joblib.load() (uses pickle internally)
  • torch.load() (uses pickle internally)
  • numpy.load(allow_pickle=True)

Safe Alternative: Use json, msgpack, or protocol buffers for data interchange. If pickle is absolutely required, use hmac to sign pickled data and verify before loading, or use fickling to audit pickle files.

Vulnerable Code:

python
import pickle
def process_request(data):
obj = pickle.loads(data) # RCE if data is attacker-controlled
return obj

Safe Code:

python
import json
import hmac
import hashlib
def process_request(data):
obj = json.loads(data) # JSON cannot execute code
return obj
# If pickle is unavoidable, sign and verify
def safe_pickle_load(data, secret_key):
signature = data[:64]
payload = data[64:]
expected = hmac.new(secret_key, payload, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
raise ValueError("Tampered pickle data")
return pickle.loads(payload)

Severity: CRITICAL


2. YAML Unsafe Loading

Description: yaml.load() without a safe Loader can instantiate arbitrary Python objects via YAML tags like !!python/object/apply:os.system. This is equivalent to pickle deserialization in risk.

Dangerous Functions:

  • yaml.load(data) (no Loader argument)
  • yaml.load(data, Loader=yaml.FullLoader) (partially restricted but still dangerous)
  • yaml.load(data, Loader=yaml.UnsafeLoader)

Safe Alternative: Always use yaml.safe_load() or yaml.load(data, Loader=yaml.SafeLoader).

Vulnerable Code:

python
import yaml
def parse_config(raw):
config = yaml.load(raw) # Arbitrary code execution via YAML tags
return config

Safe Code:

python
import yaml
def parse_config(raw):
config = yaml.safe_load(raw) # Only basic Python types
return config

Severity: CRITICAL


3. eval(), exec(), compile() Code Injection

Description: These built-in functions execute arbitrary Python code from strings. When user input reaches them, attackers can execute any code with the privileges of the running process.

Dangerous Functions:

  • eval()
  • exec()
  • compile() followed by exec()
  • execfile() (Python 2)
  • input() in Python 2 (calls eval internally)

Safe Alternative: Use ast.literal_eval() for parsing literal expressions. For math, use a dedicated parser. For configuration, use JSON or TOML.

Vulnerable Code:

python
def calculate(expression):
return eval(expression) # User sends "__import__('os').system('rm -rf /')"
def apply_filter(user_code):
exec(user_code) # Full code execution

Safe Code:

python
import ast
import operator
SAFE_OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv}
def safe_calculate(expression):
tree = ast.parse(expression, mode='eval')
return _eval_node(tree.body)
def _eval_node(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in SAFE_OPS:
return SAFE_OPS[type(node.op)](_eval_node(node.left), _eval_node(node.right))
raise ValueError(f"Unsupported expression: {ast.dump(node)}")

Severity: CRITICAL


4. Subprocess Shell Injection

Description: Using shell=True with subprocess or calling os.system() / os.popen() passes commands through the system shell, enabling shell metacharacter injection. Attackers can chain commands with ;, |, &&, backticks, or $().

Dangerous Functions:

  • subprocess.call(cmd, shell=True)
  • subprocess.Popen(cmd, shell=True)
  • subprocess.run(cmd, shell=True)
  • os.system(cmd)
  • os.popen(cmd)
  • commands.getoutput(cmd) (Python 2)

Safe Alternative: Pass commands as a list without shell=True. Use shlex.quote() if shell is absolutely required.

Vulnerable Code:

python
import subprocess
def ping_host(hostname):
subprocess.run(f"ping -c 3 {hostname}", shell=True)
# hostname = "8.8.8.8; cat /etc/passwd" -> RCE

Safe Code:

python
import subprocess
import re
def ping_host(hostname):
if not re.match(r'^[a-zA-Z0-9.\-]+$', hostname):
raise ValueError("Invalid hostname")
subprocess.run(["ping", "-c", "3", hostname]) # No shell, list of args

Severity: CRITICAL


5. Django ORM raw() and extra() SQL Injection

Description: Django's ORM provides raw() and extra() methods that accept raw SQL strings. String formatting or concatenation in these methods bypasses Django's built-in SQL injection protections.

Dangerous Functions:

  • Model.objects.raw(f"SELECT * FROM t WHERE id = {user_input}")
  • Model.objects.extra(where=[f"id = {user_input}"])
  • cursor.execute(f"SELECT ... {user_input}")
  • RawSQL() with unparameterized input

Safe Alternative: Use Django ORM's parameterized queries or pass parameters as the second argument to raw().

Vulnerable Code:

python
def get_user(request):
user_id = request.GET['id']
users = User.objects.raw(f"SELECT * FROM auth_user WHERE id = {user_id}")
# user_id = "1 UNION SELECT password FROM auth_user--"
return users

Safe Code:

python
def get_user(request):
user_id = request.GET['id']
users = User.objects.raw("SELECT * FROM auth_user WHERE id = %s", [user_id])
# Or simply:
user = User.objects.get(id=user_id)
return user

Severity: HIGH


6. Django Security Misconfigurations

Description: Django has many security-related settings that, when misconfigured, open the application to CSRF bypass, XSS, clickjacking, and information disclosure.

Dangerous Patterns:

  • DEBUG = True in production
  • SECRET_KEY hardcoded or in version control
  • ALLOWED_HOSTS = ['*']
  • CSRF_COOKIE_SECURE = False / SESSION_COOKIE_SECURE = False
  • SECURE_SSL_REDIRECT = False in production
  • X_FRAME_OPTIONS not set to 'DENY'
  • SECURE_HSTS_SECONDS = 0
  • Missing django.middleware.csrf.CsrfViewMiddleware in MIDDLEWARE
  • Template injection via mark_safe() or |safe filter on user data
  • @csrf_exempt on sensitive views

Safe Configuration:

python
# settings/production.py
DEBUG = False
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
ALLOWED_HOSTS = ['example.com', 'www.example.com']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'

Severity: HIGH (DEBUG/SECRET_KEY), MEDIUM (cookie settings)


7. Flask / Jinja2 Server-Side Template Injection (SSTI)

Description: Rendering user-controlled strings as Jinja2 templates allows attackers to access Python internals via the MRO chain (__class__.__mro__), read files, or execute commands.

Dangerous Functions:

  • Template(user_input).render()
  • render_template_string(user_input)
  • Environment().from_string(user_input).render()

Safe Alternative: Never pass user input as the template itself. Pass it as a variable to a predefined template.

Vulnerable Code:

python
from flask import request, render_template_string
@app.route('/greet')
def greet():
name = request.args.get('name')
return render_template_string(f"<h1>Hello {name}!</h1>")
# name = "{{config.items()}}" -> leaks Flask config

Safe Code:

python
from flask import request, render_template_string
@app.route('/greet')
def greet():
name = request.args.get('name')
return render_template_string("<h1>Hello {{ name }}!</h1>", name=name)

Severity: CRITICAL


8. Flask Debug Mode and Secret Key Exposure

Description: Running Flask with debug=True in production exposes the Werkzeug debugger, which provides an interactive Python console. A weak or default secret_key allows session cookie forgery.

Dangerous Patterns:

  • app.run(debug=True) in production
  • app.secret_key = 'dev' or any hardcoded/guessable key
  • FLASK_DEBUG=1 in environment without restriction
  • Werkzeug debugger PIN exposed or brute-forceable

Safe Alternative: Use environment variables for configuration and never enable debug mode in production.

Vulnerable Code:

python
app = Flask(__name__)
app.secret_key = 'super-secret' # Hardcoded, guessable
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0') # Debugger open to the world

Safe Code:

python
import os
app = Flask(__name__)
app.secret_key = os.environ['FLASK_SECRET_KEY']
if __name__ == '__main__':
app.run(
debug=os.environ.get('FLASK_DEBUG', 'false').lower() == 'true',
host='127.0.0.1'
)

Severity: CRITICAL (debug mode), HIGH (weak secret key)


9. Requests Library SSL Bypass and SSRF

Description: Disabling SSL verification with verify=False enables man-in-the-middle attacks. Passing user-controlled URLs to requests.get() without validation enables Server-Side Request Forgery (SSRF) to reach internal services, cloud metadata endpoints, or internal network resources.

Dangerous Patterns:

  • requests.get(url, verify=False)
  • requests.get(user_supplied_url) without URL validation
  • urllib.request.urlopen(user_input)
  • Accessing http://169.254.169.254/ (cloud metadata)
  • Accessing http://localhost:... or http://127.0.0.1:... internal services

Safe Alternative: Always verify SSL. Validate and restrict URLs with an allowlist of domains/schemes.

Vulnerable Code:

python
import requests
def fetch_url(url):
resp = requests.get(url, verify=False) # MitM + SSRF
return resp.text

Safe Code:

python
import requests
from urllib.parse import urlparse
import ipaddress
ALLOWED_HOSTS = {'api.example.com', 'cdn.example.com'}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
46
Repository forks
5
7-day trend score
19

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ersinkoc/security-check/sc-lang-python/badge)](https://verified-skill.com/skills/ersinkoc/security-check/sc-lang-python)

Something wrong with this skill or its page? Tell us.