Defensive Programming
Contents
1. Protecting Your Program from Invalid Inputs
2. Assertions
3. Error-Handling Techniques
4. Exceptions
5. Barricade Your Program to Contain the
Damage Caused by Errors
6. Debugging Aids
Defensive Programing
Defensive programming means coding
carefully to prevent bugs before they happen
and handling problems gracefully instead of
letting the program crash.
Garbage in, garbage out
Protecting Your Program from Invalid
Inputs
There are three general ways to handle garbage in
1.Check the values of all data from external
sources(INPUT VALIDATION)
2. Check the values of all routine input parameters
3. Decide how to handle bad inputs
INPUT VALIDATION
• SQL INJECTION
• EMAIL VALIDATION
• PASSWORD VALIDATION
SQL INJECTION
Test this SQL Injection In testing website link given
below
Altoro Mutual
Never build SQL by concatenating user
input into the SQL string.
"SELECT * FROM users WHERE username = '" + username + "' AND
password = '" + password + “’”
1) What the code does
It joins (concatenates) whatever the user types for username and
password directly into the SQL text.
That means the user can supply not only data but also characters that
look like SQL (quotes, --, OR, ;, etc.).
2) How an attacker abuses it (two common tricks)
A — Comment trick (--)
If attacker sets:
username = admin' --
password = anything
SELECT * FROM users WHERE username =
'admin' --' AND password = 'anything'
CASE2
SELECT * FROM users WHERE username = '' OR '1'='1' AND
password = '' OR '1'='1’
Because '1'='1' is always true, the WHERE can evaluate true and
return rows → data leakage.
User input changes SQL structure, not just values
Preventions
Primary fix: Never concatenate user input into SQL. Use parameterized queries /
placeholders so SQL text is fixed and inputs are sent separately as data
.
(Example form:
SELECT * FROM users WHERE username = ? AND password = ?
with parameters provided separately.)
Extra layer: input validation/whitelisting for fields that have a strict format
(usernames, IDs). Validation helps but does not replace parameterization.
Email validation
Password validation