Open to everyone Reading, lesson 58 of 100, 2 min read
Reviewing code for security
Reading code with a security eye
You do not need to be an expert programmer to spot many security problems. Code review is about asking the same questions again and again.
Questions to ask of any feature
- Where does input come from? Forms, URLs, cookies, headers, uploaded files, other systems.
- Is it checked on the server? Type, length, format, allowed values.
- Where does it go? Into a database query (injection), into a page (XSS), into a file path, into a shell command, into an email header.
- Is it made safe for where it goes? Parameterised queries, output encoding, safe file names.
- Who may do this? Is there an authorisation check for this user and this item?
- What happens on error? Does it fail safely, without revealing internal details?
- Are secrets handled properly? No passwords or keys in the code, logs or error messages.
- Is it logged? Important actions (sign-ins, permission changes, payments) should leave a record.
Common red flags
| Pattern | Why it is risky |
|---|---|
| Building SQL with string joins and user input | SQL injection |
| Printing user input into HTML without encoding | XSS |
if user.isAdmin checked only in JavaScript | Broken access control |
| Using a file name from the user to open files | Path traversal: ../../etc/passwd |
| Comparing passwords as plain text | Passwords stored unhashed |
catch (e) { show(e) } on public pages | Information disclosure |
| A hard-coded password or API key | Anyone with the code has the secret |
| Turning off certificate checks "to make it work" | Man-in-the-middle |
Be kind and specific
Good review comments explain the risk and suggest a fix: "This builds the query from $_GET['id']; an attacker can change the query. Use a prepared statement with ? instead." Reviews are about the code, not the person.
Note
This module's assignment gives you a short, made-up piece of code with several problems to find and explain.