Security Questions

Securing Python applications.

1. SQL Injection

Question: How do you prevent SQL injection in Python?

Always use parameterized queries or an ORM. Never construct SQL queries by string concatenation with user input.

# Bad
cursor.execute("SELECT * FROM users WHERE name = '" + name + "'")

# Good
cursor.execute("SELECT * FROM users WHERE name = %s", (name,))

2. XSS (Cross-Site Scripting)

Question: How do you prevent XSS in a Python web app?

Ensure that all user-generated content is escaped before rendering it in the browser. Modern templates like Jinja2 (used in Flask) and Django templates do this automatically.

3. CSRF (Cross-Site Request Forgery)

Question: What is CSRF and how do you prevent it?

CSRF attacks trick a user into executing unwanted actions on a web application where they are currently authenticated.

Prevention: Use CSRF tokens. Frameworks like Django and Flask-WTF include this protection by default. The server generates a unique token for the user's session and validates it with every state-changing request (POST, PUT, DELETE).

4. Password Hashing

Question: How should you store passwords in a database?

Never store passwords in plain text. Use a strong hashing algorithm like bcrypt or Argon2.

Salting: Always add a unique "salt" to each password before hashing to prevent rainbow table attacks. Libraries like `bcrypt` handle salting automatically.

5. Input Validation

Question: Why is input validation important?

To ensure that the data received by the application is in the expected format. This prevents malformed data from causing errors or security vulnerabilities.

Tools: Use libraries like Pydantic (for data validation) or framework-specific validators (Django Forms, WTForms).