> For the complete documentation index, see [llms.txt](https://docs.hackjiji.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hackjiji.org/web-pentesting/code-review.md).

# Code Review

### Purpose

These code snippets demonstrate common security vulnerabilities for educational purposes. Each example shows insecure code that students should learn to identify during security reviews.

### 1. SQL Injection

#### Vulnerable Code (Python)

```python
def get_user_data(username):
    query = "SELECT * FROM users WHERE username = '" + username + "'"
    cursor.execute(query)
    return cursor.fetchone()
```

**What to look for:**

* String concatenation in SQL queries
* User input directly embedded in queries
* Missing parameterized queries/prepared statements

**Attack example:** `username = "admin' OR '1'='1"`

***

### 2. Cross-Site Scripting (XSS)

#### Vulnerable Code (JavaScript/Node.js)

```javascript
app.get('/search', (req, res) => {
    const searchTerm = req.query.q;
    res.send('<h1>Search results for: ' + searchTerm + '</h1>');
});
```

**What to look for:**

* User input rendered directly in HTML
* Missing output encoding/escaping
* Use of innerHTML or similar unsafe DOM manipulation

**Attack example:** `q=<script>alert(document.cookie)</script>`

***

### 3. Command Injection

#### Vulnerable Code (Python)

```python
import os

def ping_host(hostname):
    command = "ping -c 4 " + hostname
    os.system(command)
```

**What to look for:**

* User input in system commands
* Use of os.system(), exec(), eval()
* Shell=True in subprocess calls
* Missing input validation

**Attack example:** `hostname = "google.com; rm -rf /"`

***

### 4. Path Traversal

#### Vulnerable Code (Java)

```java
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String filename) {
    Path path = Paths.get("uploads/" + filename);
    Resource resource = new FileSystemResource(path.toFile());
    return ResponseEntity.ok().body(resource);
}
```

**What to look for:**

* User-controlled file paths
* Missing path validation/sanitization
* Direct file system access with user input

**Attack example:** `filename=../../../etc/passwd`

***

### 5. Insecure Authentication

#### Vulnerable Code (PHP)

```php
<?php
session_start();

if ($_POST['username'] == 'admin' && $_POST['password'] == 'password123') {
    $_SESSION['authenticated'] = true;
    $_SESSION['username'] = $_POST['username'];
}
?>
```

**What to look for:**

* Hardcoded credentials
* Plain text password comparison
* Missing password hashing
* Weak session management

***

### 6. Insecure Cryptography

#### Vulnerable Code (Python)

```python
from Crypto.Cipher import DES

def encrypt_data(data, key):
    cipher = DES.new(key, DES.MODE_ECB)
    return cipher.encrypt(data)
```

**What to look for:**

* Use of weak algorithms (DES, MD5, SHA1 for passwords)
* ECB mode usage
* Hardcoded encryption keys
* Missing salt for password hashing

***

### 7. Insecure Deserialization

#### Vulnerable Code (Java)

```java
public Object deserializeData(String base64Data) {
    byte[] bytes = Base64.getDecoder().decode(base64Data);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
    return ois.readObject();
}
```

**What to look for:**

* Deserialization of untrusted data
* Use of readObject() on user input
* Missing type validation before deserialization

***

### 8. XML External Entity (XXE)

#### Vulnerable Code (Java)

```java
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlInput)));
```

**What to look for:**

* XML parsing without disabling external entities
* Missing setFeature() calls for XXE prevention
* Processing untrusted XML

***

### 9. Insecure Random Number Generation

#### Vulnerable Code (Java)

```java
Random random = new Random();
String token = String.valueOf(random.nextInt(999999));
```

**What to look for:**

* Use of Random instead of SecureRandom
* Predictable tokens/session IDs
* Weak random generation for security purposes

***

### 10. Hardcoded Secrets

#### Vulnerable Code (Python)

```python
AWS_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE"
AWS_SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

s3_client = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY
)
```

**What to look for:**

* API keys, passwords in source code
* Connection strings with credentials
* Private keys in repositories

***

### 11. Missing Access Control

#### Vulnerable Code (Node.js/Express)

```javascript
app.get('/admin/users/:userId', (req, res) => {
    const userId = req.params.userId;
    const user = database.getUser(userId);
    res.json(user);
});
```

**What to look for:**

* Missing authentication checks
* Missing authorization validation
* Direct object reference without ownership check
* No role-based access control

***

### 12. Race Condition (TOCTOU)

#### Vulnerable Code (Python)

```python
def withdraw_money(account_id, amount):
    balance = get_balance(account_id)
    if balance >= amount:
        # Vulnerable window here!
        time.sleep(0.1)  # Simulating processing time
        new_balance = balance - amount
        update_balance(account_id, new_balance)
        return True
    return False
```

**What to look for:**

* Check-then-use patterns
* Time gap between validation and action
* Missing locks/transactions
* File system TOCTOU issues

***

### 13. Buffer Overflow (C)

#### Vulnerable Code (C)

```c
void process_input(char *input) {
    char buffer[10];
    strcpy(buffer, input);  // No bounds checking
    printf("Processed: %s\n", buffer);
}
```

**What to look for:**

* Use of strcpy, strcat, gets, sprintf
* Fixed-size buffers with unchecked input
* Missing bounds validation

***

### 14. Missing Input Validation

#### Vulnerable Code (JavaScript)

```javascript
function transferMoney(amount, toAccount) {
    // No validation on amount
    const fromBalance = getCurrentBalance();
    const newBalance = fromBalance - amount;
    updateBalance(newBalance);
    creditAccount(toAccount, amount);
}
```

**What to look for:**

* Missing validation on numeric inputs
* No checks for negative numbers
* Missing range validation
* Type confusion vulnerabilities

***

### 15. Insecure Direct Object Reference (IDOR)

#### Vulnerable Code (Python/Flask)

```python
@app.route('/api/document/<doc_id>')
def get_document(doc_id):
    doc = Document.query.filter_by(id=doc_id).first()
    return jsonify(doc.to_dict())
```

**What to look for:**

* Direct use of user-provided IDs
* Missing ownership checks
* No authorization validation
* Predictable identifiers

***

### 16. Cross-Site Request Forgery (CSRF)

#### Vulnerable Code (PHP)

```php
if ($_POST['action'] == 'delete_account') {
    $user_id = $_SESSION['user_id'];
    delete_user_account($user_id);
    echo "Account deleted";
}
```

**What to look for:**

* State-changing operations without CSRF tokens
* Missing SameSite cookie attributes
* No verification of request origin

***

### 17. Insecure File Upload

#### Vulnerable Code (PHP)

```php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
```

**What to look for:**

* Missing file type validation
* No file size limits
* Executable files in web-accessible directories
* Missing virus scanning

***

### 18. Information Disclosure

#### Vulnerable Code (Python/Django)

```python
try:
    result = process_payment(card_number, cvv)
except Exception as e:
    return JsonResponse({
        'error': str(e),
        'trace': traceback.format_exc(),
        'locals': locals()
    })
```

**What to look for:**

* Detailed error messages to users
* Stack traces in responses
* Debug mode in production
* Exposed internal paths/versions

***

### 19. Server-Side Request Forgery (SSRF)

#### Vulnerable Code (Python)

```python
import requests

@app.route('/fetch')
def fetch_url():
    url = request.args.get('url')
    response = requests.get(url)
    return response.content
```

**What to look for:**

* User-controlled URLs in HTTP requests
* Missing URL validation/whitelisting
* Access to internal networks
* Cloud metadata endpoint access

***

### 20. Weak Password Policy

#### Vulnerable Code (JavaScript)

```javascript
function validatePassword(password) {
    if (password.length >= 6) {
        return true;
    }
    return false;
}
```

**What to look for:**

* Short minimum password length
* No complexity requirements
* Missing checks for common passwords
* No password strength meter

***

### Review Checklist

When conducting security code reviews, always check for:

1. **Input Validation**: All user inputs validated and sanitized
2. **Output Encoding**: Proper encoding for context (HTML, SQL, OS)
3. **Authentication**: Strong authentication mechanisms
4. **Authorization**: Proper access controls on all resources
5. **Cryptography**: Strong algorithms, proper key management
6. **Error Handling**: No sensitive data in error messages
7. **Session Management**: Secure session handling
8. **Data Protection**: Sensitive data encrypted at rest and in transit
9. **Logging**: Security events logged without sensitive data
10. **Dependencies**: No known vulnerable libraries

### Additional Resources

* OWASP Top 10
* CWE Top 25
* SANS Top 25
* Security code review tools (SonarQube, Semgrep, etc.)

**Tips**:

Always look to the framework documentation to understand the function&#x20;

Claude to generate vulnerable code&#x20;

**Tools**:

* Visual Studio
* Opengrep (Sast tool)
* Challenge yourself and exercice with the owasp vulnerable apps with access to the source code: <https://owasp.org/www-project-vulnerable-web-applications-directory/>
*
