> 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/python-library-hijacking/python-library-hijacking-hashlib-linux-privilege-escalation.md).

# Угон библиотек Python (hashlib) — повышение привилегий в Linux

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

Захват библиотек Python злоупотребляет механизмом разрешения импортов Python, когда привилегированный скрипт импортирует модули из места, доступного для записи. Поместив вредоносный модуль раньше в пути импорта, злоумышленник может выполнить код от имени привилегированного пользователя. На этой конкретной странице рассматривается **Захват библиотеки Python (hashlib)** и делает процесс эксплуатации практичным: определить условие, безопасно его проверить, а затем запустить минимальный полезный код, необходимый для подтверждения воздействия.

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

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

```bash
python3 -c "import sys; print('/n'.join(sys.path))"
find / -name '*.py' -writable 2>/dev/null
```

## Примеры

По мере того как **пользователь jordan**, мы видим, каковы привилегии sudoers, мы пытаемся запустить **скрипт Python** от имени jordanmacia, и это работает корректно:

<figure><img src="/files/756deb143b53bed74927a26024c22856e1b1dabf" alt=""><figcaption></figcaption></figure>

В данном случае у нас есть **разрешения на чтение, но не на запись**. Мы замечаем, что он импортирует **переменную hashlib**. Если мы сделаем **locate** с именем переменной, мы увидим, где она **хранится**. Наконец, мы замечаем, что в **PATH Python**, первая пустая, и это уязвимость:

<figure><img src="/files/f41d8906749db371a23830ae37062c07754d9d91" alt=""><figcaption></figcaption></figure>

В той же директории /tmp мы создаём **файл hashlib.py** со следующим содержимым. Этот скрипт, когда мы запускаем скрипт **example.py** в общем случае Python начинает искать эти библиотеки в текущем рабочем каталоге, а затем в путях, определённых в **переменной sys.path**.

```python
import os 
os.system("bash)
```

Наконец, выполнив **example.py**, даст нам доступ к Bash как пользователю jordanmacia (у нас будет **перемещены к пользователю** с, вероятно, более высокими привилегиями):

<figure><img src="/files/db9d3af8313cf09f6dd7796aad280c3cedf41803" 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/python-library-hijacking/python-library-hijacking-hashlib-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.
