# Code Review Examples

| Vulnerability            | Language | Vulnerable Code                                                                                                     | Reason for Vulnerability                | Fixed Code                                                                                                                                                                                                                                                                                                                                           | Reason for Fix                                               |
| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| RCE                      | PHP      | `eval($_GET['cmd']);`                                                                                               | Directly executing user input           | `$allowedCmds = ['ls', 'pwd']; if (in_array($_GET['cmd'], $allowedCmds)) { system($_GET['cmd']); }`                                                                                                                                                                                                                                                  | Whitelist of allowed commands                                |
| SQLi                     | PHP      | `$query = "SELECT * FROM users WHERE id = '$id'";`                                                                  | Direct inclusion of user input in SQL   | `$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$id]);`                                                                                                                                                                                                                                                                  | Parameterized query                                          |
| SQLi                     | Java     | `String query = "SELECT * FROM users WHERE id = '" + id + "'";`                                                     | String concatenation in SQL             | `PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?"); stmt.setString(1, id);`                                                                                                                                                                                                                                         | Use of PreparedStatement                                     |
| SQLi                     | Python   | `cursor.execute(f"SELECT * FROM users WHERE id = '{id}'")`                                                          | String formatting in SQL                | `cursor.execute("SELECT * FROM users WHERE id = %s", (id,))`                                                                                                                                                                                                                                                                                         | Parameterized query                                          |
| XSS                      | PHP      | `echo $_GET['user'];`                                                                                               | Direct output of user input             | `echo htmlspecialchars($_GET['user'], ENT_QUOTES, 'UTF-8');`                                                                                                                                                                                                                                                                                         | Encoding special characters                                  |
| XSS                      | Java     | `out.println("<input value='" + request.getParameter("name") + "'>");`                                              | Unescaped data in HTML                  | `out.println("<input value='" + Encode.forHtmlAttribute(request.getParameter("name")) + "'>");`                                                                                                                                                                                                                                                      | Using encoding library                                       |
| XSS                      | Python   | `return f"<p>{user_input}</p>"`                                                                                     | Unescaped data in HTML                  | `return f"<p>{escape(user_input)}</p>"`                                                                                                                                                                                                                                                                                                              | Using escape function                                        |
| CSRF                     | PHP      | `if ($_POST['action'] == 'delete') { delete_item($id); }`                                                           | No CSRF token check                     | `if ($_POST['csrf_token'] === $_SESSION['csrf_token']) { delete_item($id); }`                                                                                                                                                                                                                                                                        | Validating CSRF token                                        |
| CSRF                     | Java     | `@PostMapping("/transfer")`                                                                                         | No CSRF protection                      | `@PostMapping("/transfer") @CsrfProtect`                                                                                                                                                                                                                                                                                                             | Using CSRF protection annotation                             |
| CSRF                     | Python   | `@app.route('/change-email', methods=['POST'])`                                                                     | No CSRF protection                      | `@app.route('/change-email', methods=['POST']) @csrf.protect()`                                                                                                                                                                                                                                                                                      | Using CSRF protection decorator                              |
| Insecure Deserialization | PHP      | `$data = unserialize($_GET['data']);`                                                                               | Deserializing user input                | `$data = json_decode($_GET['data'], true);`                                                                                                                                                                                                                                                                                                          | Using JSON instead of serialized data                        |
| Insecure Deserialization | Java     | `ObjectInputStream ois = new ObjectInputStream(input); Object obj = ois.readObject();`                              | Deserializing without checks            | `ObjectInputStream ois = new ObjectInputStream(input) { @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!allowedClasses.contains(desc.getName())) throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName()); return super.resolveClass(desc); } };` | Implementing a custom ObjectInputStream with class whitelist |
| Insecure Deserialization | Python   | `pickle.loads(data)`                                                                                                | Using pickle for deserialization        | `json.loads(data)`                                                                                                                                                                                                                                                                                                                                   | Using JSON instead of pickle                                 |
| XXE                      | PHP      | `$dom = new DOMDocument(); $dom->loadXML($xml);`                                                                    | No entity restriction                   | \`$dom = new DOMDocument(); $dom->loadXML($xml, LIBXML\_NOENT                                                                                                                                                                                                                                                                                        | LIBXML\_DTDLOAD);\`                                          |
| XXE                      | Java     | `DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder();` | Default DocumentBuilderFactory settings | `DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);`                                                                                                                                                                                                                   | Enabling secure processing feature                           |
| XXE                      | Python   | `ET.fromstring(xml_data)`                                                                                           | Default XML parsing                     | `ET.fromstring(xml_data, ET.XMLParser(resolve_entities=False))`                                                                                                                                                                                                                                                                                      | Disabling entity resolution                                  |
| SSRF                     | PHP      | `$content = file_get_contents($_GET['url']);`                                                                       | No URL validation                       | `$allowedHosts = ['example.com']; $url = parse_url($_GET['url']); if (in_array($url['host'], $allowedHosts)) { $content = file_get_contents($_GET['url']); }`                                                                                                                                                                                        | Whitelist of allowed hosts                                   |
| SSRF                     | Java     | `URL url = new URL(request.getParameter("url")); url.openConnection();`                                             | No URL validation                       | `URL url = new URL(request.getParameter("url")); if (!isAllowedHost(url.getHost())) { throw new SecurityException("Host not allowed"); }`                                                                                                                                                                                                            | Validating host against whitelist                            |
| SSRF                     | Python   | `requests.get(url)`                                                                                                 | No URL validation                       | `if not is_valid_url(url): raise ValueError("Invalid URL")`                                                                                                                                                                                                                                                                                          | Custom URL validation function                               |
| Path Traversal           | PHP      | `include($_GET['file'] . ".php");`                                                                                  | No path validation                      | `$file = basename($_GET['file']); include("/var/www/files/$file.php");`                                                                                                                                                                                                                                                                              | Using basename to remove directory traversal                 |
| Path Traversal           | Java     | `File file = new File(baseDir + fileName);`                                                                         | No path normalization                   | `File file = new File(baseDir, fileName).getCanonicalFile(); if (!file.getPath().startsWith(baseDir)) { throw new SecurityException("Invalid file path"); }`                                                                                                                                                                                         | Path normalization and validation                            |
| Path Traversal           | Python   | `open(os.path.join(base_dir, user_file))`                                                                           | No path validation                      | `file_path = os.path.normpath(os.path.join(base_dir, user_file)); if not file_path.startswith(base_dir): raise ValueError("Invalid file path")`                                                                                                                                                                                                      | Path normalization and validation                            |
| Command Injection        | PHP      | `system("ping " . $_GET['ip']);`                                                                                    | Unsanitized input in system command     | `$ip = escapeshellarg($_GET['ip']); system("ping $ip");`                                                                                                                                                                                                                                                                                             | Escaping shell arguments                                     |
| Command Injection        | Java     | `Runtime.getRuntime().exec("ping " + ip);`                                                                          | Unsanitized input in command            | `ProcessBuilder pb = new ProcessBuilder("ping", ip); pb.start();`                                                                                                                                                                                                                                                                                    | Using ProcessBuilder with arguments                          |
| Command Injection        | Python   | `os.system("ping " + ip)`                                                                                           | Unsanitized input in system command     | `subprocess.run(["ping", ip], check=True)`                                                                                                                                                                                                                                                                                                           | Using subprocess with arguments                              |
| IDOR                     | PHP      | `$data = $db->query("SELECT * FROM users WHERE id = " . $_GET['id']);`                                              | No access control check                 | `if ($user->canAccess($_GET['id'])) { $data = $db->query("SELECT * FROM users WHERE id = ?", [$_GET['id']]); }`                                                                                                                                                                                                                                      | Implementing access control                                  |
| IDOR                     | Java     | `return userRepository.findById(id);`                                                                               | No access control check                 | `if (currentUser.canAccess(id)) { return userRepository.findById(id); } else { throw new AccessDeniedException(); }`                                                                                                                                                                                                                                 | Implementing access control                                  |
| IDOR                     | Python   | `return User.objects.get(id=user_id)`                                                                               | No access control check                 | `if request.user.can_access(user_id): return User.objects.get(id=user_id)`                                                                                                                                                                                                                                                                           | Implementing access control                                  |
| NoSQL Injection          | PHP      | `$users = $collection->find(array("username" => $_GET['username']));`                                               | Direct use of user input in query       | `$users = $collection->find(array("username" => new MongoDB\BSON\Regex('^' . preg_quote($_GET['username']) . '$', 'i')));`                                                                                                                                                                                                                           | Using regex for exact match                                  |
| NoSQL Injection          | Java     | `collection.find(eq("username", username))`                                                                         | Direct use of user input in query       | `collection.find(regex("username", "^" + Pattern.quote(username) + "$"))`                                                                                                                                                                                                                                                                            | Using regex for exact match                                  |
| NoSQL Injection          | Python   | `collection.find({"username": username})`                                                                           | Direct use of user input in query       | `collection.find({"username": {"$regex": "^" + re.escape(username) + "$"}})`                                                                                                                                                                                                                                                                         | Using regex for exact match                                  |
| Buffer Overflow          | C        | `char buffer[5]; strcpy(buffer, argv[1]);`                                                                          | No bounds checking                      | `char buffer[5]; strncpy(buffer, argv[1], sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = '\0';`                                                                                                                                                                                                                                                   | Using bounded string copy                                    |

| Programming Language | Function                                         | Possible Vulnerability          | Vulnerable Scenarios                                               | Remediation                                                                           |
| -------------------- | ------------------------------------------------ | ------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| PHP                  | `eval()`                                         | Code Injection                  | When user-controlled input is directly passed to `eval()`          | Avoid using `eval()`. Prefer alternative approaches or secure code design             |
|                      | `assert()`                                       | Code Injection                  | When user-controlled input is directly passed to `assert()`        | Avoid using `assert()`. Prefer alternative approaches or secure code design           |
|                      | `system(), shell_exec(), passthru(), popen(), )` | Command Injection               | When user-controlled input is directly passed to these functions   | Use proper input validation and parameterization. Sanitize user input                 |
|                      | `include(), require()`                           | File Inclusion                  | When user-controlled input is used without proper validation       | Validate and sanitize user input for the included/required file path                  |
|                      | `unserialize()`                                  | Deserialization Vulnerabilities | When untrusted data is deserialized without proper validation      | Implement proper input validation and utilize safe unserialization methods            |
| Python               | `yaml.load()`                                    | Deserialization Vulnerabilities | When untrusted YAML data is deserialized without proper validation | Implement proper input validation and utilize safe deserialization methods            |
| JavaScript           | `document.location.href()`                       | Cross-Site Scripting (XSS)      | When user-controlled input is used without proper sanitization     | Properly sanitize and validate user input before using it in `document.location.href` |
| Ruby                 | `%x(), backticks(code)`                          | Command Injection               | When user-controlled input is directly passed to these functions   | Use proper input validation and parameterization. Sanitize user input                 |
|                      | `Marshal.load()`                                 | Deserialization Vulnerabilities | When untrusted data is deserialized without proper validation      | Implement proper input validation and utilize safe deserialization methods            |
|                      | `yaml.load()`                                    | Deserialization Vulnerabilities | When untrusted YAML data is deserialized without proper validation | Implement proper input validation and utilize safe deserialization methods            |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
