Tag Archives: Linux

CTF OverTheWire: Natas9

Continuing with the CTF Natas series, now is the turn for natas9

Natas Level 8 → Level 9
Username: natas9
URL:      http://natas9.natas.labs.overthewire.org

Using the flag obtained in the previous challenge, we go to the URL showed in the description and we will see the following screen.

It’s just a simple web page with a basic input form, if we type nonsense nothing happens, we proceed to click the View sourcecode and we are redirected to index-source.html

This is supposed to be the backend code of the html form.

<?
$key = "";

if(array_key_exists("needle", $_REQUEST)) {
    $key = $_REQUEST["needle"];
}

if($key != "") {
    passthru("grep -i $key dictionary.txt");
}
?>

The vulnerability in this code happens when calling the passthru function, we are reading user input directly from the needle request parameter, then saving it into the $key variable and using it without any kind of sanitization when calling the function, that’s essentially command injection. We are going to try to execute commands in the web server by exploiting this vulnerability.

Sending ;ls -la;

Results in all files on the current directory to be listed

I was a little bit lost at this point but then I remember the CTF instructions.

Each level has access to the password of the next level. Your job is to somehow obtain that next password and level up. All passwords are also stored in /etc/natas_webpass/. E.g. the password for natas5 is stored in the file /etc/natas_webpass/natas5 and only readable by natas4 and natas5.

So we do ;cat /etc/natas_webpass/natas10;

The flag for the next level, natas10, is: nOpp1igQAkUzaI1GUUjzn1bFVj7xCNzu

As mentioned before, this challenge we exploit a command injection vulnerability that essentially allow us to execute arbitrary commands on the server, depending on the privileges of the user running the web server we might read, write or delete files.

Happy hacking 🙂

Commands and Code Snippets I usually forget

Some commands and code snippets I use rarely during CTFs or my daily work, but still I need them from time to time and I’m very lazy to remember them. This note may grow over time.

Javascript

Playing with dec, hexa and bin (not really) in JS
String.fromCharCode(0x41) // 'A'

parseInt('0xf', 16) // 15

var n = 15

n.toString(16) // 'f'
n.toString(2) // '1111'
n.toString() // '15'

var n = 'A'
n.charCodeAt() // 65
// dec to hex
n.charCodeAt().toString(16) // '41'
// dec to bin
n.charCodeAt().toString(2) // '1000001'
// dec to hex
parseInt(255).toString(16) // 'ff'
// dec to bin
parseInt(5).toString(2) // '101'
Simple HTTP GET request using nodejs
const https = require('https');

https.get('https://www.alevsk.com', (resp) => {
  let data = '';
  resp.on('data', (chunk) => {
    data += chunk;
  });
  resp.on('end', () => {
    //DO something with data
  });
}).on("error", (err) => {
  console.log("Error: " + err.message);
});
Simple HTTP POST request using nodejs
const https = require('https')

const data = JSON.stringify({
  todo: 'Buy the milk'
})

const options = {
  hostname: 'whatever.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, res => {
  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.write(data)

req.end()
Extract content between regular expression patterns using JS
const message =  data.match(/<p>([^<]+)<\/p>/)[1];
const lat =  data.match(/name="lat" value="([^<]+)" min=/)[1];
const long =  data.match(/name="lon" value="([^<]+)" min=/)[1];
const token =  data.match(/name="token" value="([^<]+)"/)[1];

Linux

Mount NTFS on Linux
mount -t ntfs [FILE] [PATH]
mount -t type device directory
Extract extended attributes from NTFS disk
getfattr --only-values [FILE] -n [ATTR-NAME] > file
Parsing file with awk and run xargs
cat [FILE] | awk '{print $1 .. $n}' | xargs

Python

Start Simple HTTP server with Python
python -m SimpleHTTPServer
Inline Python commands
python -c 'print "\x41" * 20'

PHP

Run PHP interactive mode
php -a

CTF OverTheWire: Natas8

After a break we continue with the CTF Natas series, now is the turn for natas8

Natas Level 7 → Level 8
Username: natas8
URL:      http://natas8.natas.labs.overthewire.org

Using the flag obtained in the previous challenge, we go to the URL showed in the description and we will see the following screen.

It’s just a simple web page with a basic input form, if we type nonsense we get an error message displaying Wrong secret, we proceed to click the the View sourcecode

<html>
<head>
<!-- This stuff in the header has nothing to do with the level -->
<link rel="stylesheet" type="text/css" href="http://natas.labs.overthewire.org/css/level.css">
<link rel="stylesheet" href="http://natas.labs.overthewire.org/css/jquery-ui.css" />
<link rel="stylesheet" href="http://natas.labs.overthewire.org/css/wechall.css" />
<script src="http://natas.labs.overthewire.org/js/jquery-1.9.1.js"></script>
<script src="http://natas.labs.overthewire.org/js/jquery-ui.js"></script>
<script src=http://natas.labs.overthewire.org/js/wechall-data.js></script><script src="http://natas.labs.overthewire.org/js/wechall.js"></script>
<script>var wechallinfo = { "level": "natas8", "pass": "<censored>" };</script></head>
<body>
<h1>natas8</h1>
<div id="content">

<?

$encodedSecret = "3d3d516343746d4d6d6c315669563362";

function encodeSecret($secret) {
    return bin2hex(strrev(base64_encode($secret)));
}

if(array_key_exists("submit", $_POST)) {
    if(encodeSecret($_POST['secret']) == $encodedSecret) {
    print "Access granted. The password for natas9 is <censored>";
    } else {
    print "Wrong secret";
    }
}
?>

<form method=post>
Input secret: <input name=secret><br>
<input type=submit name=submit>
</form>

<div id="viewsource"><a href="index-source.html">View sourcecode</a></div>
</div>
</body>
</html>

This is supposed to be the backend code of the HTML page we just saw, the important part of this challenge is in the PHP code functions, taking a quick look the data flow looks like this:

  • Check if submit key exists on $_POST
  • Pass $_POST[‘secret’] to encodeSecret function
  • encodeSecret function will apply some transformation to the secret and return it
  • The transformed secret must be equal to 3d3d516343746d4d6d6c315669563362, otherwise we are getting the Wrong secret error we saw already

As I say before, the important part is happening inside the encodeSecret function, the code is basically doing this:

secret -> base64_encode -> strrev -> bin2hex -> 3d3d516343746d4d6d6c315669563362

So we need to perform exactly the same operations but in reverse order to obtain the original secret, ie: the old bin2hex should be hex2bin, I don’t know if we should call this reverse engineering, anyway ¯\_(ツ)_/¯

3d3d516343746d4d6d6c315669563362 -> hex2bin -> strrev -> base64_encode -> secret

We can use PHP from the command line and do this:

$ php -r "echo base64_decode(strrev(hex2bin('3d3d516343746d4d6d6c315669563362')));"
oubWYf2kBq
$

We get the secret: oubWYf2kBq, we try it on the input form.

The flag for the next level, natas9, is: W0mMhUcRRnG8dcghE4qvk3JA9lGt8nDl

In this challenge we take advantage of a security vulnerability called Source code disclosure and then we did basic reverse engineering on the PHP code.

Happy hacking 🙂

CTF OverTheWire: Natas7

Continuamos con la serie de tutoriales del CTF Natas, ahora toca el turno de natas7.

Natas Level 6 → Level 7
Username: natas7
URL:      http://natas7.natas.labs.overthewire.org

Utilizamos la bandera obtenida en el reto anterior y accedemos a la URL indicada en las instrucciones del reto, veremos una pantalla como la siguiente.

Inspeccionamos el código fuente de la pagina y observamos un par de cosas interesantes:

Vemos dos hypervinculos (index.php?page=home y index.php?page=about) y un comentario que dice:

<!-- hint: password for webuser natas8 is in /etc/natas_webpass/natas8 -->

Dependiendo el valor del parámetro page el contenido de la pagina cambia, todo apunta a que estamos ante una vulnerabilidad de tipo Local File Inclusion, escribimos texto aleatorio solo para verificar la vulnerabilidad.

Efectivamente podemos ver la ruta del archivo php en el servidor (path disclosure), debido a esta vulnerabilidad podemos leer cualquier archivo al que el usuario que ejecuta el servidor web tenga acceso, por ahora solo nos centraremos en obtener la bandera del reto con http://natas7.natas.labs.overthewire.org/index.php?page=/etc/natas_webpass/natas8

La bandera para acceder a natas8 es DBfUBfqQG69KvJvJ1iAbMoIpwSNQ9bWe

En este reto aprovechamos un fallo de seguridad llamado Local File Inclusion, con el que es posible leer otros archivos que no son accesibles directamente en el servidor.

Happy hacking 🙂

CTF OverTheWire: Natas6

Continuamos con la serie de tutoriales del CTF Natas, ahora toca el turno de natas6.

Natas Level 5 → Level 6
Username: natas6
URL:      http://natas6.natas.labs.overthewire.org

Utilizamos la bandera obtenida en el reto anterior y accedemos a la URL indicada en las instrucciones del reto, veremos una pantalla como la siguiente.

Es solo un formulario donde nos piden ingresar una contraseña o secreto, al introducir cualquier cosa obtenemos un mensaje de error.

En la misma pagina hay un enlace que dice view sourcecode (ver código fuente), damos clic y veremos lo siguiente.

La parte importa es:

<?

include "includes/secret.inc";

    if(array_key_exists("submit", $_POST)) {
        if($secret == $_POST['secret']) {
        print "Access granted. The password for natas7 is <censored>";
    } else {
        print "Wrong secret";
    }
    }
?>

Es un código php muy sencillo, podemos ver que obtiene un parámetro via POST (el que enviamos mediante el formulario) y lo compara con la variable $secret, ademas hace include de un archivo interesante includes/secret.inc

Accedemos a ese archivo usando el navegador.

Y utilizamos el secret que acabamos de descubrir en el formulario inicial.

La bandera para acceder a natas7 es 7z3hEENjQtflzgnT29q7wAvMNfZdh0i9

En este reto aprovechamos un fallo de seguridad llamado Source code disclosure, en donde tenemos acceso a código que solo debería ser consumido del lado del servidor.

Happy hacking 🙂