Security is a crucial aspect of software development. In this guide, we will discuss common vulnerabilities in Python code and how to mitigate them.
1. Avoiding Code Injection
Code injection occurs when an attacker injects malicious code into a vulnerable program. One of the most common ways this happens in Python is through eval().
# Insecure
user_input = input("Enter command: ")
eval(user_input) # Dangerous: Allows arbitrary code execution
Instead, use safer alternatives like dictionaries for controlled command execution.
2. Using Secure Password Hashing
Never store plain-text passwords. Use a strong hashing algorithm like bcrypt.
from bcrypt import hashpw, gensalt
password = b"securepassword"
hashed = hashpw(password, gensalt())
3. Preventing SQL Injection
Always use parameterized queries instead of string concatenation.
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
4. Handling Untrusted Data
Sanitize and validate all user input to prevent XSS and injection attacks.
5. Restricting File Access
Avoid allowing arbitrary file access through user input. Use whitelisting for file paths.
ALLOWED_FILES = {"config": "config.yaml", "data": "data.csv"}
file_name = ALLOWED_FILES.get(user_input, None)
if file_name:
with open(file_name, "r") as f:
data = f.read()
6. Secure API Communication
Always use HTTPS and validate certificates to prevent MITM attacks.
7. Keep Dependencies Updated
Regularly update third-party libraries to patch vulnerabilities.
pip list --outdated
Conclusion
By following secure coding practices, you can reduce the risk of exploits and make your Python applications more resilient to attacks.