Senin, 29 Januari 2018

Write up In CTF - Giant XOR

writeup

inctf - GiantXOR

Deskripsi Soal

Diberikan source code encrypt.py dan ciphertext.txt dalam hexadecimal encode. Berikut isi dari kedua file tersebut.
encrypt.py
from os import urandom
import string

key = ""

def get_key(keylength):
    global key
    c = urandom(1)
    if len(key)!=keylength:
        if c in string.printable and c not in string.whitespace:
            key += c
            get_key(keylength)
        else:
            get_key(keylength)

def multiplyKey(pt, k):
    while len(k) < len(pt):
        k += k
    k = k[:len(pt)]
    return k

def encrypt(plaintext, k):
    ciphertext = ""
    plaintext = plaintext.encode("base64")
    k = multiplyKey(plaintext, k)
    assert len(k) == len(plaintext)
    for i in range(len(plaintext)):
        ciphertext += chr(ord(plaintext[i]) ^ ord(k[i]))
    return ciphertext.encode("hex")

secret_flag = open("plaintext.txt",'r').read().strip()
keylength = int(open("keylength.txt",'r').read().strip())

get_key(keylength)

print "key: ", key
print "keylength: ", keylength

ciphertext = encrypt(secret_flag, key)

object1 = open("ciphertext.txt",'w').write(ciphertext)
ciphertext
6e19223f204b31183e333f005c122d37264a350e3e3c2808672436250b3f3d1b2e2c151c671d553e182b4713262c3f045c1d553e0b3f391c1449385d7309223c20153d022d3c011a673322394822242e0118003a5a1333123b222b361b22353d5110231230222b1f102c28566e03281a2e21240c041e3e2d491337022e313b26181a3a5a532919122a31343e071f2e2d4928531a2e31342607713702673a3963140b1737001c0f5c742d3a172e133a331b4b3d167f090418210b3a31390d0f025933390810023a334e0e2427733c021818081119141c0928552629170c172a230f08373808246a0a113d142645421b357e0853327132013d2439243565000c190514093d3f171b0b6503070a2f001b2e0d140a0e6a7f0a340522442d1a3d17356913500870290b2e31435d0d7a32061e70101f7e2f495d5f6730263a1a4b39042d49055f6d79506d48

Solusi

Jika kita lihat dari encrypt.py, program mengenkrip plaintext dengan alur berikut.
  1. Plaintext dijadikan base64 terlebih dahulu
  2. Hasil dari base64 plain, dilakukan multiple xor dengan key printable string dari urandom dengan panjang key yang tidak diketahui.
Kesulitan dari soal ini adalah plaintext diubah menjadi base64 sehingga kita tidak dapat menggunakan xortool secara langsung untuk mendecrypt ciphertext dan mencari key. Karena itu kita akan mencoba memecahkannya secara manual.
Untuk mendekript ini, kita harus mencari panjang key nya terlebih dahulu. Panjang key dapat diketahui dengan menggunakan hamming distance. Berikut script hamming distance yang digunakan untuk mencari length key.
#! /usr/bin/env python

from binascii import b2a_hex

def hamming_distance(A, B):
  X = int(b2a_hex(A),16) ^ int(b2a_hex(B),16)
  return count_binary_ones(X)

def count_binary_ones(X):
  ret = 0
  while X != 0:
    ret = ret + 1
    X &= X-1  
  return ret

def normalized_hamming_distance (A, length): # Takes adjacent groups of 'length' length and finds avg hamming dist and normalizes it
  ham_sum = 0
  for i in range(len(A)/length - 1):
    ham_sum += hamming_distance(A[(i+0)*length:(i+1)*length], A[(i+1)*length:(i+2)*length])
  ham_avg = (1.0 * ham_sum) / (len(A)/length - 1)
  norm_ham = ham_avg / length
  return norm_ham

def test():
  if hamming_distance("this is a test","wokka wokka!!!") == 37:
    print "Hamming Distance tests pass"
  if normalized_hamming_distance("this is a testwokka wokka!!!",14) == 37.0/14:
    print "Normalized Hamming Distance tests pass"


data = ""
filename = 'ciphertext.txt'
filename = open(filename).read()
data = filename.decode('hex')
test()
best_hamming_dist = float('inf')
for KEYSIZE in range(2,80):
  ham = normalized_hamming_distance(data,KEYSIZE)
  if ham < best_hamming_dist:
    best_hamming_dist = ham
    best_keysize = KEYSIZE

KEYSIZE = best_keysize

print "[#] Inferred KEYSIZE = " + str(KEYSIZE)
Hasil
a@a-l ~/CTF/inctf/giantxor $ python hd.py 
Hamming Distance tests pass
Normalized Hamming Distance tests pass
[#] Inferred KEYSIZE = 12
Dari script didapat panjang key adalah 12 karakter. Ide selanjut nya kita harus menebak key dari ciphertext yang sudah ada. Kita tidak dapat menggunakan frequency english letter pada plaintext, karena string di encode menggunakan base64. Kita coba cara lain, yaitu dengan melakukan bruteforce, perhuruf pada key. Berikut alur bruteforce tersebut.
misal 
key = "sesuatu" 
cipher = cipher

brute key ke 0. xor key ke 0 dengan semua cipher[0 + j*12]
kalo semua hasil nya masuk ke base64 tambah key

brute key ke i. xor key ke i dengan semua cipher[i + j*12]
kalo semua hasil nya masuk ke base64 tambah key.

lakukan sampai semua key memenuhi syarat tersebut
Menggunakan rekursif sederhana key dapat diketahui. Jika kita sudah mendapatkan key. Lakukan multiple xor dengan cipher text. dan didapatkan plaintext.
Berikut script untuk mencari kunci sekaligus mendecrypt ciphertext
import string 
from base64 import *
base64str = string.ascii_letters + string.digits + "=+/" + "\n"
prstring = string.printable

def multiplexor(cipher, key):
 hasil = ""
 for i in range(len(cipher)):
  hasil += chr( ord(cipher[i]) ^ ord(key[i % 12]))
 return hasil

def valid(key_index, ch): 
 # Cek semua hasil xor jika ada yang bukan merupakan string base64 return 0
 for index in range(key_index, len(data), 12):
  if( chr(ord(data[index]) ^ ord(ch)) not in base64str ):
   return 0
 return 1 

def findkey_rec(data, block, level, part):
 if (level == part):

  for ch in prstring:
   if valid(block + level, ch) :
    key.append(ch)
    part_key = ''.join(key)
    global password
    password += part_key
    return part_key
    # Password ketemu
 for ch in prstring:
  if valid(block + level, ch) :
   key.append(ch)
   findkey_rec(data, block, level + 1, part)
   key.pop()


data = open("ciphertext.txt").read()
data = data.decode('hex')

key = []
password = ""
part = 6

# Part dilakukan untuk mendapatkan key perblock.

for block in range(0, 12, part+1):
 key = []
 findkey_rec(data, block, 0, part) 

hasil = multiplexor(data, password)
print "Base64 plain :\n\n%s" % hasil

print "Plain : %s" % b64decode(hasil)
Berikut hasil dekripsi ciphertext
Base64 plain :

SSBob3BlIHRoaXMgd2FzIGEgZnVuIGNoYWxsZW5nZS4gQWRkaW5nIGJhc2U2NCBlbmNvZGluZyBi
ZWZvcmUgYSByZXBlYXRlZCBrZXkgWE9SIHJlYWxseSBtYWRlIHRoaW5ncyBhIGJpdCBtb3JlIGRp
ZmZpY3VsdCwgb3IgZGlkIGl0PyBCdHcsIENvbmdyYXRzIG9uIHNvbHZpbmcgdGhlIGNoYWxsZW5n
ZSEgR29vZCB3b3JrISBIZXJlIGlzIHlvdXIgZmxhZzogaW5jdGZ7YmFzZTY0X2QxZF80bGxfN2hl
X200ZzFjX3JpZ2h0P30=

Plain : I hope this was a fun challenge. Adding base64 encoding before a repeated key XOR really made things a bit more difficult, or did it? Btw, Congrats on solving the challenge! Good work! Here is your flag: inctf{base64_d1d_4ll_7he_m4g1c_right?}
FLAG : inctf{base64_d1d_4ll_7he_m4g1c_right?}

Selasa, 16 Januari 2018

Write up TUCTF - Crypto Clock

readme

TUCTF - Crypto Clock (300 pts)

Deskripsi soal

These damn hackers have hit our NTP server with something called crypto clock...

Our sysadmin found these suspicious packets just before our systems went down.

Can you get back in???

nc cryptoclock.tuctf.com 1230

MD5 (network_dump) = bdfcfee713b6ad53f4923f96863e385c

UPDATE: The server side code is running Python 2

Solusi

Diberikan koneksi socat dan sebuah file pcap. Ketika file pcap diekstrak didapatkan string base64 encode yang sepertinya merupakan source dari program socat tersebut.

Berikut adalah source code dari program tersebut

#!/usr/bin/env python
import sys
import random
import arrow

big_1=44125640252420890531874960299151489144331823129767199713521591380666658119888039423611193245874268914543544757701212460841500066756559202618153643704131510144412854121922874915334989288095965983299150884589072558175944926880089918837606946144787884895502736057098445881755704071137014578861355153558L
big_2=66696868460135246134548422790675846019514082280010222055190431834695902320690870624800896599876321653748703472303898494328735060007496463688173184134683195070014971393479052888965363156438222430598115999221042866547813179681064777805881205219874282594291769479529691352248899548787766385840180279125343043041L


flag = "THEFLAG"
keys = {
    "n":142592923782837889588057810280074407737423643916040668869726059762141765501708356840348112967723017380491537652089235085114921790608646587431612689308433796755742900776477504777927984318043841155548537514797656674327871309567995961808817111092091178333559727506289043092271411929507972666960139142195351097141,
    "e": 3
}

#now to get some randomness in here!
with open('/dev/urandom', 'rb') as f:
    rand = f.read(8)

rand_int = int(rand.encode('hex'),16)

#now lets use something easier.
random.seed(rand_int)

offset = random.randint(big_1,big_2)

while True:
    sys.stdout.write( '''Welcome to the ntp server
What would you like to do?
    1) get current time
    2) enter admin area
    3) exit
:''')
    sys.stdout.flush()
    response = raw_input('')
    if response == '1':
        time = arrow.utcnow().timestamp + offset
        enc_time = pow(time,keys['e'],keys['n'])
        sys.stdout.write('HAHAHAHAHAHA, this NTP server has been taken over by hackers!!!\n')
        sys.stdout.write('here is the time encrypted with sweet RSA!\n')
        sys.stdout.write(str(enc_time))
        sys.stdout.write('\n')
        sys.stdout.flush()
    elif response == '2':
        # lets get even more random!
        time = arrow.utcnow().timestamp + offset
        random.seed(time)
        guessing_int = random.randint(0,999999999999)
        sys.stdout.write('''ACCESS IS ONLY FOR TRUE HACKERS!
to prove you are a true hacker, predict the future:''')
        sys.stdout.flush()
        response = raw_input('')
        if response == str(guessing_int):
            sys.stdout.write('''Wow, guess you are a hacker.\n''')
            sys.stdout.write(flag)
            sys.stdout.write('\n')
            break
        else:
            sys.stdout.write('''I knew you weren't a hacker''')
            sys.stdout.write('\n')
            break
    else:
        print 'Good by.'
        break

Kita coba jalankan program tersebut di lokal.

Welcome to the ntp server
What would you like to do?
    1) get current time
    2) enter admin area
    3) exit
:1
HAHAHAHAHAHA, this NTP server has been taken over by hackers!!!
here is the time encrypted with sweet RSA!
65591483448351902802226912239888261427877913051459257537112647909433135321660465779739007818787246507102769966318792178070355998594386277071706789962602338898599051561589547815383532059656459033598538670267245423729643879149408096186929277608549861896324902862127612063620348480277444341149873394682980975464
Welcome to the ntp server
What would you like to do?
    1) get current time
    2) enter admin area
    3) exit
:2
ACCESS IS ONLY FOR TRUE HACKERS!
to prove you are a true hacker, predict the future:1337
I knew you weren't a hacker

Sebelum program tersebut dijalankan, program akan menggenerate variabel random antara byte1 dan byte2 dengan 8 byte seed dari urandom.

with open('/dev/urandom', 'rb') as f:
    rand = f.read(8)

rand_int = int(rand.encode('hex'),16)

#now lets use something easier.
random.seed(rand_int)

offset = random.randint(big_1,big_2)

Terdapat 3 pilihan. Jika kita memilih 1, program akan mengoutput nilai enc_time yang merupakan hasil RSA encyript dengan plain = utcnow + offset, dengan e = 3, dan n = 142592923782837889588057810280074407737423643916040668869726059762141765501708356840348112967723017380491537652089235085114921790608646587431612689308433796755742900776477504777927984318043841155548537514797656674327871309567995961808817111092091178333559727506289043092271411929507972666960139142195351097141;

Karena bilangan n yang besar, n tidak dapat difaktorkan dengan menggunakan faktor db.

if response == '1':
        time = arrow.utcnow().timestamp + offset
        enc_time = pow(time,keys['e'],keys['n'])
        sys.stdout.write(str(enc_time))

Pada pilihan kedua nilai enctime saat ini, dijadikan randomseed. Lalu program menggenerate nilai random yang harus kita tebak. Jika kita berhasil menebak angka random tersebut kita akan mendapatkan flag.

elif response == '2':
        # lets get even more random!
        time = arrow.utcnow().timestamp + offset
        random.seed(time)
        guessing_int = random.randint(0,999999999999)
        response = raw_input('')
        if response == str(guessing_int):
            sys.stdout.write(flag)

Inti dari challange ini adalah kita harus menebak berapa offset random yang di generate oleh program. Kita coba analisis dari sistem enkripsi RSA pada pilihan 1.

Jika kita lihat time yang diencrypt

time = arrow.utcnow().timestamp + offset

time akan bertambah satu setiap detik.

Kita misalkan time stamp saat ini adalah ts

time0 = ts + offset
time1 = ts + offset + 1
time2 = ts + offset + 2
time3 = ts + offset + 3
.
.
.

Kita coba ringkas lagi. ts + offset menjadi tso

time0 = tso
time1 = tso + 1
time2 = tso + 2
time3 = tso + 3
.
.

Dapat diliat pola dari plaintext linier. Sehingga kita dapat mendapatkan nilai tso tanpa mencari private key, yaitu dengan menggunakan Franklin Reiter Attack

Kita coba buat enkripsi RSA menjadi sebuah persamaan polinomial dengan derajat 3 karena e = 3.

enctime0 = RSA(time0, 3, n) = (tso)**3 % n
enctime1 = RSA(time1, 3, n) = (tso + 1)**3 % n =( tso**3 + 3 * tso**2 + 3  * tso + 1 ) % n
enctime2 = RSA(time2, 3, n) = (tso + 2)**3 % n =( tso**3 + 6 * tso**2 + 12 * tso + 4 ) % n
enctime3 = RSA(time3, 3, n) = (tso + 3)**3 % n =( tso**3 + 9 * tso**2 + 27 * tso + 9 ) % n

Jika kita manipulasi keempat persamaan tersebut secara manual. Dapat diperoleh persamaan dengan derajat 1. Contohnya seperti berikut.

enctime3 + enctime0 - enctime1 - enctime2 = (12 * tso + 18 ) % n

Karena persamaan sudah terlihat linier, maka kita dapat mencari nilai tso dengan mudah. Bisa dengan gmpy atau kita coba manual.

Jika kita mengetahui nilai tso, kita dapat menggenerate nilai offset dan menggenerate nilai random yang sama dengan yang dibuat oleh program.

Berikut script untuk mendapatkan flag

import random
import arrow
import time
from pwn import *
from sys import *

keys = {
    "n":142592923782837889588057810280074407737423643916040668869726059762141765501708356840348112967723017380491537652089235085114921790608646587431612689308433796755742900776477504777927984318043841155548537514797656674327871309567995961808817111092091178333559727506289043092271411929507972666960139142195351097141,
    "e": 3
}


def getcur():
 p.sendline('1')
 p.recvuntil('RSA!\n')
 return eval(p.recvline().strip())

def getdata():
 for i in range(4):
  if i == 0:
   firsttime.append(arrow.utcnow().timestamp)
   # ambil time awal
  enctime.append(getcur())
  # print enctime[i]
  # print
  sleep(1)

def compute():
 # enctime3 + enctime0 - enctime1 - enctime2 = (12 * tso + 18 ) % n

 totalenc = enctime[3] + enctime[0] - enctime[1] - enctime[2] - 18
 totalenc = totalenc % keys['n']
 while totalenc % 12 != 0:
  totalenc += keys['n']
 # bruteforce manual mencari kelipatan 12
 tso = (totalenc/12) % keys['n']
 
 offset = tso - firsttime[0]

 assert enctime[0] == pow(firsttime[0]+offset, 3, keys['n'])
 # print enctime[0], pow(firsttime+offset, 3, keys['n'])
 # cek manual enc time dengan enc sistem
 return offset

def attack(offset):
 time = arrow.utcnow().timestamp + offset
 print offset
 p.sendline('2')
 random.seed(time)
 guessing_int = random.randint(0,999999999999)
 p.sendline(str(guessing_int))
 p.interactive()
 # print anything


enctime = []

p = process('./soal.py')
firsttime = []
getdata()
offset = compute()
attack(offset)

Mati kita coba jalankan dengan semangat

a@a-l ~/CTF/tuctf/crypto/cryptoclock $ python solve.py 
[+] Starting local process './soal.py': pid 8101
55969035464709264574317945966340530441212223514033774913384027420606040108552999045539910802429093186897367580038431282346833841212343691474112849644573699358976007547301899048552330679832668433949084639764634834550486404163431865278602312818657312396033813763706085140312567944945436838398692227407066593980
[*] Switching to interactive mode
Welcome to the ntp server
What would you like to do?
    1) get current time
    2) enter admin area
    3) exit
:ACCESS IS ONLY FOR TRUE HACKERS!
to prove you are a true hacker, predict the future:Wow, guess you are a hacker.
THEFLAG
[*] Got EOF while reading in interactive
$ 
[*] Process './soal.py' stopped with exit code 0 (pid 8101)

Bahan referensi : RSA Paper