Secure Python: Injection Defense, Framework Security, and Dependency Auditing
Part of the Cybersecurity Skills Guide — This article is one deep-dive in our complete guide series.
By HADESS Team | February 28, 2026 | Updated: February 28, 2026 | 5 min read
Python’s readability makes it popular for web applications, automation, and data pipelines. That same readability can mask security problems — dangerous functions look harmless, and the standard library includes several footguns that developers use without thinking twice.
Injection Prevention
Command injection through os.system() and subprocess.shell=True is the most common Python vulnerability in security assessments. Never pass user input to a shell:
“python
Vulnerable
os.system(f"ping {user_input}")
Safe
subprocess.run(["ping", "-c", "1", user_input], shell=False)
`
With shell=False and a list of arguments, the input is passed as a single argument to the program, not interpreted by the shell.
SQL injection follows the same pattern as other languages. Use parameterized queries:
`python
Vulnerable
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
Safe
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
`
SQLAlchemy ORM queries are parameterized by default, but text() with string formatting is not.
Template injection in Jinja2 allows code execution when user input is rendered as a template. Never use Template(user_input).render(). Use render_template() with variables passed separately.
Pickle Exploits
pickle.loads() executes arbitrary Python code during deserialization. Never unpickle data from untrusted sources. This includes data from caches, message queues, and APIs where you do not control the sender.
`python
Never do this with untrusted data
import pickle
data = pickle.loads(untrusted_bytes) # Arbitrary code execution
`
Use JSON, MessagePack, or Protocol Buffers for serialization instead. If you must use pickle, implement __reduce__ restrictions and use hmac to verify data integrity before deserialization — though this is still inferior to avoiding pickle entirely.
Django Security
Django ships with strong defaults, but misconfigurations undo them:
- Set DEBUG = False
in production. Debug mode leaks settings, database queries, and full tracebacks. - Configure ALLOWED_HOSTS
explicitly. An empty list withDEBUG = Falserejects all requests, but a wildcard[‘*’]enables host header attacks. - Use Django's ORM. raw()
andextra()with string formatting reintroduce SQL injection. - Enable CSRF middleware and use {% csrf_token %}
in all forms. - Set SECURE_HSTS_SECONDS
,SECURE_SSL_REDIRECT,SESSION_COOKIE_SECURE, andCSRF_COOKIE_SECUREfor production.
Flask Security
Flask has no security defaults. Everything is manual:
`python
from flask_talisman import Talisman
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__) Talisman(app) # Forces HTTPS, sets security headers CSRFProtect(app) # Enables CSRF protection app.config['SESSION_COOKIE_SECURE'] = True app.config['SESSION_COOKIE_HTTPONLY'] = True `
Flask's secret_key must be cryptographically random and stored in environment variables. A weak or hardcoded secret key allows session forgery.
Dependency Auditing
Python dependencies are a supply chain risk. Use pip-audit to check for known vulnerabilities:
`bash`
pip-audit --requirement requirements.txt
Pin all dependency versions in requirements.txt or use poetry.lock/pipenv.lock. Review updates before applying them. Use safety as a second scanner — different tools use different vulnerability databases.
Check for typosquatting: requests vs request, python-dateutil vs dateutil`. Verify package names before installing.
Related Career Paths
Secure Python development maps to Application Security Expert and DevSecOps roles. Python appears in web apps, automation pipelines, and infrastructure code — all of which need security review.
Next Steps
- Benchmark your Python security skills with the skills assessment
- Explore related topics in the skills library
- Build a targeted study plan with the coaching tool
Related Guides in This Series
- Secure Coding in .NET: Input Validation, Auth, and CSRF Defense — HADESS | 2026
- Secure Java/Spring Development: From Config to Defense — HADESS | 2026
- Secure JavaScript: XSS, CSP, and Dependency Safety — HADESS | 2026
Take the Next Step
Browse 80+ skills on HADESS. Go to the browse 80+ skills on hadess on HADESS.
See your certification roadmap. Check out the see your certification roadmap.
Get started free — Create your HADESS account and access all career tools.
Frequently Asked Questions
How long does it take to learn this skill?
Most practitioners build working proficiency in 4-8 weeks of dedicated study with hands-on practice. Mastery takes longer and comes primarily through on-the-job experience.
Do I need certifications for this skill?
Certifications validate your knowledge to employers but are not strictly required. Hands-on experience and portfolio projects often carry more weight in technical interviews. Check the certification roadmap for relevant options.
What career paths use this skill?
Explore the career path explorer to see which roles require this skill and how it fits into different cybersecurity specializations.
—
HADESS Team consists of cybersecurity practitioners, hiring managers, and career strategists who have collectively spent 50+ years in the field.
