# Code Review

## Overview

The first and most crucial step - reviewing source code to understand design and functionality.

### Requirements

* Programming language knowledge
* Ability to read multiple languages
* Knowledge of potential flaws
* Understanding of advanced web vulnerabilities

***

## Code Review Phases

```
Planning & Data Gathering
         ↓
    Scope Selection
         ↓
Prioritization & Scope Reduction
         ↓
   Reverse Engineering
         ↓
   Prioritize Targets
```

***

## Phase 1: Planning & Data Gathering

### Meetings Required

* Development team
* Other stakeholders

### Assets to Collect

* Source code
* Test server access
* Design documentation
* User credentials (various roles)

### Key Points

* All tests on **test environment first**
* May need to set up own test server
* Learn to replicate production environment

***

## Phase 2: Scope Selection

### With Documentation

* Study application design documents
* Understand each function's role
* Identify critical areas

### Without Documentation

* Reverse engineer codebase
* Read comments (if any)
* Map function relationships

### Cost Impact

| Documentation Quality | Impact                       |
| --------------------- | ---------------------------- |
| Well documented       | Lower cost, faster testing   |
| Poor documentation    | Higher cost, longer exercise |
| No comments           | Most expensive, most time    |

***

## Phase 3: Prioritization & Scope Reduction

### Technique 1: Application Design Based

Select functions based on understanding of application design **before looking at code**.

**Example**: Files under `/purchases/` deal with payment → high priority

### Technique 2: Search-Based

Search for sensitive functions through codebase.

**PHP Examples**:

```bash
# Command execution
grep -rn "exec\|system\|passthru\|shell_exec" .

# File operations
grep -rn "file_get_contents\|fopen\|include\|require" .

# SQL
grep -rn "mysql_query\|mysqli_query\|->query" .
```

**Pros**: Fast\
**Cons**: May miss opportunities

### Technique 3: Dynamic Usage

Mix of dynamic + static analysis.

**Process**:

1. Use the application
2. Examine pages and requests
3. Prioritize based on behavior

**Example**: Page throws many errors → focus on it

### Priority Functions by Category

| Category       | Examples               | Why Priority           |
| -------------- | ---------------------- | ---------------------- |
| Authentication | login, password reset  | Auth bypass            |
| OS Interaction | exec, system, file ops | Command injection, LFI |
| Database       | queries, ORM calls     | SQL injection          |
| User Input     | forms, uploads         | XSS, file upload       |
| Crypto         | encryption, hashing    | Weak crypto            |
| Session        | session handling       | Session hijacking      |

***

## Phase 4: Reverse Engineering

### Process

1. **Read function line by line**
2. **Add comments** for what each line does
3. **Trace variables** to sources in other files
4. **Review external functions** called

### Why It Matters

**Example Scenario**:

* Dangerous function interacts with OS
* Direct input is well filtered ✅
* BUT: Under some conditions, input not filtered
* OR: Additional input source (e.g., from DB) not filtered

**Without reverse engineering** → Overlooked\
**With thorough reverse engineering** → Caught

### Documentation Pattern

```python
# Original code
result = process_input(user_data)

# Documented
# Line 45: process_input() - from utils/processor.py
# Takes raw user data, applies filters (see line 12-30 in processor.py)
# Returns sanitized string
# NOTE: filters bypass if data comes from DB (see line 67)
result = process_input(user_data)
```

***

## Phase 5: Prioritize Targets

### Impact × Probability Matrix

|               | Low Impact | Medium Impact | High Impact     |
| ------------- | ---------- | ------------- | --------------- |
| **High Prob** | Medium (3) | High (4)      | **Highest (5)** |
| **Med Prob**  | Low (2)    | Medium (3)    | High (4)        |
| **Low Prob**  | Lowest (1) | Low (2)       | Medium (3)      |

### Prioritization Examples

| Finding                     | Probability | Impact | Priority    |
| --------------------------- | ----------- | ------ | ----------- |
| Auth bypass in login        | High        | High   | **Highest** |
| XSS in admin-only page      | High        | Low    | Medium      |
| SQLi in rarely-used feature | Low         | High   | Medium      |
| Info disclosure             | Medium      | Low    | Low         |

***

## Code Review Checklist

### Preparation

* [ ] Meet with dev team
* [ ] Collect all assets
* [ ] Understand application purpose
* [ ] Set up test environment

### Scope

* [ ] Review design docs (if available)
* [ ] Identify sensitive areas
* [ ] Search for dangerous functions
* [ ] Use application dynamically

### Analysis

* [ ] Read prioritized functions
* [ ] Document understanding
* [ ] Trace input/output flows
* [ ] Identify potential issues

### Output

* [ ] Shortlist of functions to test
* [ ] Priority ranking
* [ ] Notes on potential vulnerabilities
* [ ] Dependencies mapped

***

## Dangerous Functions by Language

### PHP

```php
exec(), system(), passthru(), shell_exec()  // Command execution
include(), require(), file_get_contents()   // File operations
eval(), preg_replace('/e')                  // Code execution
unserialize()                               // Deserialization
```

### Python

```python
eval(), exec()                              # Code execution
subprocess.*, os.system()                   # Command execution
pickle.loads()                              # Deserialization
open(), os.path.*                           # File operations
```

### JavaScript (Node.js)

```javascript
eval(), Function()                          // Code execution
child_process.*                             // Command execution
require() with user input                   // Module injection
fs.*                                        // File operations
```

### Java

```java
Runtime.exec()                              // Command execution
ObjectInputStream.readObject()              // Deserialization
ProcessBuilder                              // Command execution
Class.forName() with user input             // Reflection attacks
```

***

## Tips

1. **Start broad, then narrow** - Understand overall design first
2. **Follow the data** - Trace user input through the application
3. **Question assumptions** - "Is this always true?"
4. **Check edge cases** - What happens with unexpected input?
5. **Review dependencies** - Third-party code can be vulnerable too
