Advertisement
Cyberguru

DEFCON CTF [catwestern]

May 18th, 2015
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. import commands
  2. import socket  
  3. import re
  4. import struct
  5. import os
  6.  
  7. def gen_opcode(s):
  8.     a,b = s.split('=')
  9.     d = {}
  10.     d['rax'] = '\x48\xB8'
  11.     d['rbx'] = '\x48\xBB'
  12.     d['rcx'] = '\x48\xB9'
  13.     d['rdx'] = '\x48\xBA'
  14.     d['rsi'] = '\x48\xBE'
  15.     d['rdi'] = '\x48\xBF'
  16.     d['r8'] = '\x49\xB8'
  17.     d['r9'] = '\x49\xB9'
  18.     d['r10'] = '\x49\xBA'
  19.     d['r11'] = '\x49\xBB'
  20.     d['r12'] = '\x49\xBC'
  21.     d['r13'] = '\x49\xBD'
  22.     d['r14'] = '\x49\xBE'
  23.     d['r15'] = '\x49\xBF'
  24.     return d[a] + struct.pack('<Q', int(b, 16))
  25.  
  26. def fullhex(s):
  27.     ret = ''
  28.     for c in s:
  29.         b = hex(ord(c))[2:]
  30.         b = b.rjust(2, '0')
  31.         ret += '\\x' + b
  32.     return ret
  33.  
  34. def conv(r):
  35.     return 'asm("mov %%%%%s,%%0" : "=r"(%s));' % (r, r)
  36.  
  37. def conv2(s):
  38.     return 'printf("%s=0x%%llx\\n", %s);' % (s,s)
  39.  
  40. conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  41. conn.connect(('catwestern_631d7907670909fc4df2defc13f2057c.quals.shallweplayaga.me', 9999))
  42. d = conn.recv(1024)
  43. d = d.split('\n')
  44. d.pop(0)
  45. d = filter(lambda x : x, d)
  46. opcode = ''.join(map(gen_opcode, d))
  47.  
  48. shellcode = conn.recv(1024)
  49. l = re.search('About to send (\d+) bytes', shellcode, re.DOTALL).group(1)
  50. l = int(l)
  51. shellcode = shellcode[-l:]
  52. shellcode = opcode + shellcode
  53. open('/tmp/shellcode', 'wb').write(shellcode)
  54. shellcode = fullhex(shellcode)
  55.  
  56. regs = ['rax','rbx','rcx','rdx','rsi','rdi','r8','r9','r10','r11','r12','r13','r14','r15']
  57. asm = map(conv, regs)
  58. asm = '\r\n'.join(asm)
  59.  
  60. c = map(conv2, regs)
  61. c = '\r\n'.join(c)
  62.  
  63. s = '''#include <stdio.h>
  64. char shellcode[] = "%s";
  65. int main()
  66. {  
  67. long int rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
  68. (*(void (*)()) shellcode)();
  69. %s
  70. %s
  71. }''' % (shellcode, asm, c)
  72.  
  73. open('/tmp/out.c', 'wb').write(s)
  74. os.system('gcc /tmp/out.c -fno-stack-protector -z execstack -o /tmp/out')
  75. ans =  commands.getoutput('/tmp/out') + '\n'
  76. conn.send(ans)
  77. print conn.recv(1024)
  78. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement