SQL Security (Injection Prevention) π‘οΈΒΆ
Prerequisites: SELECT Statement, INSERT Statement
Mentor's Note: The most dangerous weapon against a database is a simple text box. If you aren't careful, a hacker can type SQL code into your "Login" box and delete your whole database. This is called SQL Injection. β οΈ
π The Scenario: The Fake Ticket π«ΒΆ
Imagine a bus conductor who only reads the text on a ticket. - Normal Passenger: "Ticket for Rustompura." (Conductor takes him there). β - Malicious Passenger: "Ticket for Rustompura... AND then DRIVE THE BUS TO MY HOUSE!" - The Result: If the conductor just follows instructions blindly, the bus is hijacked! ππ¨
π» 1. What is SQL Injection?ΒΆ
It happens when user input is combined directly with a query.
-- β DANGEROUS CODE (Vulnerable)
-- User types: ' OR 1=1 --
query = "SELECT * FROM users WHERE username = '" + user_input + "'";
-- Becomes:
SELECT * FROM users WHERE username = '' OR 1=1 --';
-- Result: Logged in as EVERYONE! π
π‘οΈ 2. The Solution: Prepared StatementsΒΆ
Instead of combining strings, we use Placeholders (?). The database treats the input as "Data Only," never as "Code."
-- β
SECURE CODE (Parameterized)
query = "SELECT * FROM users WHERE username = ?";
-- User input is safely swapped into the ? marker.
π¨ Visual Logic: The Safety ShieldΒΆ
graph TD
A[User Input β¨οΈ] --> B{Safety Check}
B -- "Direct String" --> C[SQL Injection Risk π£]
B -- "Parameterized" --> D[Secure Query Execution π‘οΈ]
D --> E[(Database ποΈ)]
π 3. Top Security Best PracticesΒΆ
- Least Privilege: Give the application "Read-Only" access if it doesn't need to "Delete." π
- Input Validation: If you expect a "Phone Number," don't accept letters! π’
- Encrypted Passwords: NEVER store passwords in plain text. Use Hashing. π
- Hide Errors: Don't show technical SQL errors to the end-user. Show a friendly "Something went wrong" message. π€«
π‘ Interview Tip πΒΆ
"If an interviewer asks 'How do you stop SQL Injection?', the first word out of your mouth should be: Prepared Statements (or Parameterized Queries)!"