Python provides several built-in modules and third-party libraries that can help you secure your code against common vulnerabilities. Here are some techniques you can use:
Use parameterized queries instead of building SQL statements with user input. The sqlite3 module provides a way to do this, and third-party libraries like SQLAlchemy can also help.
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
username = input("Enter username: ")
password = input("Enter password: ")
# Using parameterized queries to prevent SQL injection
c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
Validate and sanitize user input before using it. Use libraries like html to escape HTML tags and json to validate JSON input.
import json
# Validating JSON input
try:
data = json.loads(request.data)
except ValueError:
return "Invalid JSON input", 400
# Sanitizing user input to prevent XSS attacks
from html import escape
user_input = '<script>alert("Hello")</script>'
sanitized_input = escape(user_input)
Use secure hash algorithms, like SHA-256 or SHA-512, to store passwords. The hashlib module can help you generate and verify secure password hashes.
import hashlib
password = 'password123'
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
hashed_password = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
hashed_password = binascii.hexlify(hashed_password)
Use HTTPS instead of HTTP to encrypt data in transit. Use libraries like requests to make HTTPS requests and ssl to configure SSL/TLS connections.
import requests
response = requests.get('https://example.com')
Avoid using eval() and exec() functions, as they can execute arbitrary code and introduce security vulnerabilities. If you need to evaluate user input, use safer alternatives like ast.literal_eval().
import ast
user_input = '[1, 2, 3]'
try:
data = ast.literal_eval(user_input)
except ValueError:
return "Invalid input", 400