Django is known for its strong security features, but no framework is immune to misconfiguration or developer error. In this blog post, we'll explore how to automate testing of common web vulnerabilities in Django using Python and the requests
library.
This guide is intended for educational and penetration testing purposes on your own applications or testing environments only.
We will cover tests for the following:
Cross-Site Scripting (XSS)
Cross-Site Request Forgery (CSRF)
SQL Injection
Clickjacking
Host Header Injection
Session Hijacking
Unsafe File Uploads
You can use the following Python script to run all tests at once. Each test function is modular and simulates a typical attack scenario.
import requests
# 1. XSS
def test_xss_attack(url):
print("[*] Testing XSS...")
payload = "<script>alert('XSS')</script>"
data = {"input": payload}
try:
res = requests.post(url, data=data)
if payload in res.text:
print("[!] XSS vulnerability detected!")
else:
print("[+] XSS test passed.")
except Exception as e:
print(f"[X] XSS test failed: {e}")
# 2. CSRF
def test_csrf_attack(url):
print("[*] Testing CSRF...")
data = {"username": "admin", "password": "123"}
try:
res = requests.post(url, data=data)
if res.status_code == 403:
print("[+] CSRF protection is working.")
else:
print("[!] Potential CSRF vulnerability!")
except Exception as e:
print(f"[X] CSRF test failed: {e}")
# 3. SQL Injection
def test_sql_injection(url):
print("[*] Testing SQL Injection...")
payload = "' OR '1'='1"
data = {"username": payload, "password": "irrelevant"}
try:
res = requests.post(url, data=data)
if "Welcome" in res.text or res.status_code == 200:
print("[!] SQL Injection vulnerability detected!")
else:
print("[+] SQL Injection test passed.")
except Exception as e:
print(f"[X] SQL Injection test failed: {e}")
# 4. Clickjacking
def test_clickjacking(url):
print("[*] Testing Clickjacking...")
try:
res = requests.get(url)
if "X-Frame-Options" not in res.headers:
print("[!] X-Frame-Options header missing - possible clickjacking!")
else:
print(f"[+] X-Frame-Options: {res.headers['X-Frame-Options']}")
except Exception as e:
print(f"[X] Clickjacking test failed: {e}")
# 5. Host Header Injection
def test_host_header_injection(url):
print("[*] Testing Host Header Injection...")
headers = {"Host": "evil.com"}
try:
res = requests.get(url, headers=headers)
if "evil.com" in res.text:
print("[!] Host header injection vulnerability!")
else:
print("[+] Host header validated.")
except Exception as e:
print(f"[X] Host header test failed: {e}")
# 6. Session Hijacking
def test_session_hijacking(url, fake_sessionid):
print("[*] Testing Session Hijacking...")
cookies = {"sessionid": fake_sessionid}
try:
res = requests.get(url, cookies=cookies)
if "Welcome" in res.text or res.status_code == 200:
print("[!] Session hijack may be possible!")
else:
print("[+] Session protection OK.")
except Exception as e:
print(f"[X] Session hijack test failed: {e}")
# 7. File Upload
def test_file_upload(url):
print("[*] Testing File Upload...")
files = {"file": ("test.php", "<?php echo 'Hacked'; ?>", "application/x-php")}
try:
res = requests.post(url, files=files)
if res.status_code == 200:
print("[!] Dangerous file uploaded! Check if it can be executed!")
else:
print("[+] File upload restrictions are working.")
except Exception as e:
print(f"[X] File upload test failed: {e}")
# Run all tests
def run_all_tests():
base_url = "https://lightproweb.com"
run_config = {
"xss": f"{base_url}/search",
"csrf": f"{base_url}/login",
"sql": f"{base_url}/login",
"clickjacking": f"{base_url}/",
"host_header": f"{base_url}/",
"session_hijack": f"{base_url}/dashboard",
"upload": f"{base_url}/upload"
}
test_xss_attack(run_config["xss"])
test_csrf_attack(run_config["csrf"])
test_sql_injection(run_config["sql"])
test_clickjacking(run_config["clickjacking"])
test_host_header_injection(run_config["host_header"])
test_session_hijacking(run_config["session_hijack"], "fake-sessionid-123")
test_file_upload(run_config["upload"])
if __name__ == "__main__":
run_all_tests()
Save the script above as security_tester.py
.
Replace the base_url
with your Django test server or localhost.
Run it:
While Django offers built-in protection against many common web attacks, developers should still:
Validate and sanitize user input
Use Django’s CSRF and XSS middleware properly
Avoid raw SQL queries
Configure file upload and session settings carefully
Regularly test endpoints for regressions
These test scripts provide a basic starting point. For professional-grade testing, consider integrating tools like OWASP ZAP, Burp Suite, or static analysis tools like Bandit.
๐ก๏ธ Security is not a one-time task. Test often. Fix fast. Stay safe.
Learn how to automatically scan your local network using Nmap with Python, detect active devices and operating systems, and export scan results to JSON format.
5 min readLearn how to fingerprint LAN devices using Python, Scapy, and Impacket. Collect OS info, open ports, HTTP server data, and SMB banners with a single script.
5 min readLearn how to write a Python script to scan local networks using TCP SYN packets, detect live hosts, and discover connected devices with IPs and hostnames.
5 min readLearn how to use Python and Scapy to scan your local network, detect connected devices by IP and hostname, and quickly discover active hosts in your LAN.
5 min readScan your website for security headers, SSL issues, open ports, and vulnerabilities like SQL Injection or XSS using a Python script and generate a HTML.
5 min read