> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/code-injection.md).

# Code Injection

Code Injection is a vulnerability that occurs when user-controlled input is passed to functions that interpret and execute code at runtime. When the input is not properly sanitized, an attacker can inject and execute arbitrary code within the context of the vulnerable application.

***

### How to Identify

* Input is used by backend functions like `eval()`, `exec()`, `system()`, `popen()`, or interpreted in scripting languages. [list](https://www.php.net/manual/en/book.exec.php)
* Inject expressions or function calls and observe for unexpected behaviour or responses
* Look for error messages showing interpreted code results
* Check for time delays using functions like `sleep()` to identify blind injection
* Review server responses for code output or side effects

***

#### Vulnerable Code (PHP)

```php
<?php
$code = $_GET['code'];
eval($code);
?>
```

This code is vulnerable because it executes user input directly using `eval()` Without any validation.

***

#### Exploitation Steps

* Inject a function to read a sensitive file

  ```bash
  http://example.com/page.php?code=echo file_get_contents('/etc/passwd');
  ```
* Inject system command execution

  ```bash
  http://example.com/page.php?code=echo shell_exec('id');
  ```
* Use backtick syntax for shell execution (if supported)

  ```bash
  http://example.com/page.php?code=echo `whoami`;
  ```
* Inject sleep function for blind detection

  ```bash
  http://example.com/page.php?code=sleep(5);
  ```

***

### Impact

* **Arbitrary code execution:** Execute attacker-controlled code within the application.
* **Remote code execution:** Gain control of the underlying server if code executes on the host.
* **Sensitive data disclosure:** Access application data, configuration files, and secrets.
* **Privilege escalation:** Execute code with the privileges of the vulnerable application.

### Prevention

* **Avoid dynamic code execution:** Do not use functions such as `eval()`, `exec()`, or similar on untrusted input.
* **Validate and sanitize input:** Accept only expected input using strict allowlists.
* **Isolate execution environments:** Use sandboxes, containers, or virtual machines where appropriate.
* **Apply least privilege:** Run the application with the minimum required permissions.
