Monthly Archives: December 2015

Mounting Remote Directory Using SSHFS

Ever heard network file system (NFS)? Yeah, that’s good.

But in this article we won’t discuss NFS, just something similar in term of access remote directory locally. SSHFS is file system over SSH. It is a mean to mount directory / partition on remote server on our local box. The cool thing is it use SSH, a Secure Shell connection, as media to transfer data. The SSH itself is secure protocol, all data transmitted / received is through encrypted channel thus the secrecy is guaranteed.

In this article, I use following to demonstrate:

Generally speaking, the Arch Linux would be installed as guest using VirtualBox. We will make sure ArchLinux has SSH server and we can login to it. Then we install SSHFS on our local / host box. All the steps then be used to mount our local box to remote box.

Our goal in this article is we can install and mount linux partition on our box.

I assume Arc linux is up and running. You can also use other Linux, as long as it can be installed SSH server.

Installation

Local

We need to install SSHFS on local. As I use ParrotSec which is Debian derivative, I invoke following command:

apt-get install sshfs

If you are using other Linux, you would achieve the same by invoking:

# ArchLinux
pacman -S sshfs fuse

# CentOS
### SSHFS is on EPEL repository so we should add EPEL first
http://ftp-stud.hs-esslingen.de/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rp
yum update
### installing SSHFS
yum install fuse-sshfs

Remote

All we need is SSH server. SSH server is used to receive ssh connection. We use OpenSSH-server here.

# Arch Linux
pacman -S openssh
systemctl start sshd

# Debian
apt-get install openssh-server
service sshd start

# CentOS
yum -y install openssh-server
chkconfig sshd on
service sshd start

Or you can install Dropbear, alternative SSH server

# Arch Linux
pacman -S dropbear
systemctl start dropbear

# Debian
apt-get install dropbear
service dropbear start

# CentOS
### dropbear is on EPEL repository so we should add EPEL first
http://ftp-stud.hs-esslingen.de/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rp
yum update
### installing dropbear
yum install dropbear
service dropbear start

Testing

Preparation

Make sure both end can ping each other. For the sake of simplicity, I will use following network situation:

local: 
IP 192.168.56.1/24
GW 192.168.56.1

remote:
IP 192.168.56.101/24
GW 192.168.56.1

Create user remote on remote server try to login from our local machine:

ssh remote@192.168.56.101

Create a directory (or using existing partition) and create two files on it.

mkdir /home/remote/mydir
echo "Please read this file for me" > /home/remote/mydir/file1
touch /home/remote/mydir/file2

Next we create a directory in our local machine as a mount point.

mkdir -p /mnt/sshfs/1

Mount

Next we try to mount freshly created directory

sshfs remote@192.168.56.101:/home/remote/mydir /mnt/sshfs/1 -o workaround=all,allow_other

Create/Read/Write File

As we mount it with allow_other, any user on our local box can access the file and directory mounted. Any I/O operation to them will be redirected to remote server and performed as the referred user (remote).

To prove it, read the /mnt/sshfs/1/file1 on our local box. And then write something to /mnt/sshfs/1/file2 and read /home/remote/mydir/file2 on remote server.

# Local
cat /mnt/sshfs/1/file1
echo "Xathrya has came" > /mnt/sshfs/1/file2

# Remote
cat /home/remote/mydir/file2
ls -la

See the result for yourself.

The post Mounting Remote Directory Using SSHFS appeared first on Xathrya.ID.

Before Wt: Installing Prerequisite for Wt

In this article we will discuss about installation of various packages and software as requirement for Wt. The goal of this article is for everyone to successfully install prerequisites for building Wt.

For this purpose, I use Slackware64 14.0 as development machine. However, you can also use other machine.

This article can be broken down to two sections:

  • System requirements
  • Optional packages

System Requirements

Applications on this sections is the primary requirements for building Wt. At least there are two packages:

  • CMake: cross platform make configure utility.
  • Boost C++ Library: A general purpose library for C++. Latest version is recommended.

Another requirements are the connector support which depend on what would you like.

For FastCGI (Unix only)

  • Apache2 or other web server which supports the FastCGI protocol. You can go to this page for more information about Web Server (Apache, Lighttpd, Nginx, etc). When using Apache use mod_fastcgi-2.4.x or mod_fcgid-2.3.5 alternatively.
  • FastCGI development kit

For built in http daemon

For ISAPI (Windows only)

  • ISAPI, which only works for deploying Wt applications within Microsoft IIS server.

Optional Packages

The following packages are optional, but highly recommended for Wt. They enables additional features in Wt. The packages are:

  • OpenSSL: Enabling HTTPS protocol support for Client (Http::Client) and Server (Http::Server)
  • libharu: Enabling rendering support for PDF documents.
  • GraphicsMagick: Enabling rendering support for raster images like PNG or GIF
  • pango: Text rendering for TrueType font selection
  • PostgreSQL, MySQL/MariaDB, and Firebird: Enabling connectors database for ORM library (alongside the Sqlite3 connector). You can choose any (all whole).

CMake

Cross platform, open-source build system consists of tools designed to build, test, and packaging software. It used to control the software compilation process using simple platform and compiler independent configuration files.

For information on how to install CMake, follow this article.

Boost C++ Library

Portable C++ source libraries and work well with the C++ Standard Library. It is intended to be widely useful and usable across a broad spectrum of applications.

For information on how to install Boost Library, follow this article.

OpenSSL

libharu

Free, cross platform, open source library for generating PDF files.

For information on how to install libHaru, follow this article.

GraphicsMagick

The swiss army knife of image processing. It provides a robust and efficient collection of tools and libraries which support reading, writing, and manipulating an image in over 88 major formats including DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

For information on how to install GraphicsMagick, follow this article.

pango

PostgreSQL

MySQL

MariaDB

Firebird

A relational database offering many ANSI SQL standard features that runs on various operating system. It offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers.

For information on how to install FirebirdSQL, follow this article.

FastCGI Development Kit

whttpd

The post Before Wt: Installing Prerequisite for Wt appeared first on Xathrya.ID.

Five Ways to Communicate with Embedded Device in Linux

Embedded system / device running operating system such as Linux / BSD is not so uncommon today. Most of them fall in category as routers, servers, NAS devices and mostly have communication interface (serial port with RS-232, or even fancy USB). We can communicate with these kind of devices, by redirect our I/O to this port. That’s the hardware part, how can we feed information to it? What tools should we use?

This article will mention five ways to communicate with embedded device. Our operating system of choice is Linux.

Of course we need to specify, our embedded system is the one which is designed to send/receive data / command using communication line.

Preparation

The physical port might be one and only, but how it is referred by our system? Thus we should check. The port commonly referred as ttyS*, ttyACM*, ttyUSB*. It is analogous to COM* on Windows. Let’s check by dmesg command. Connect our box with our device and invoke following command:

dmesg | egrep --color 'serial|ttyS|ttyACM|ttyUSB'

This one will be our example:

[    1.245258] serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
[    1.265727] serial8250: ttyS1 at I/O 0x2f8 (irq = 3) is a 16550A
[    1.286713] 00:07: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
[    1.307321] 00:08: ttyS1 at I/O 0x2f8 (irq = 3) is a 16550A

Let’s get initial report regarding the port. We need the configuration information associated with serial port (in this context):

setserial -g /dev/ttyS[0123]

Sample outputs:

/dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 4
/dev/ttyS1, UART: 16550A, Port: 0x02f8, IRQ: 3
/dev/ttyS2, UART: unknown, Port: 0x03e8, IRQ: 4
/dev/ttyS3, UART: unknown, Port: 0x02e8, IRQ: 3

After confirmed, we can use following method to communicate.

CU Command

You might also want to read my old article: using CU to communicate with modem.

CU, abbreviated from call up, is an old unix command used to call up another system and act as dial in terminal. In some unix it is preinstalled. If not, you can always install it, most modern distro available.

Next, we use following command to communicate:

cu -l /dev/device -s baud-rate-speed

In our case, /dev/device would be /dev/ttyS0. Our baud rate is anything predefined value you want such as 19200 or 115200. Make sure the baudrate in both end is the same value.

 
cu -l /dev/device -s baud-rate-speed

In this example, I’m using /dev/ttyS0 with 115200 baud-rate:

 
cu -l /dev/ttyS0 -s 115200

To exit enter tilde dot (~.).

Screen Command

Most case, screen is used as a trick to run a process in server when we are remotely connect to it. We can also use screen to communicate with device.

screen /dev/device baud-rate

Minicom Command

Minicom is another approach. It is a tool designed for the job. Before we use, we need to setup it.

minicom -s

You will see some menu there. The most crucial part here is Serial port setup. Make sure the port and baud rate are set correctly.

Invoke minicom to do the job. We don’t need to specify command to minicom everytime we invoke it if we have saved the configuration before.

minicom

PuTTY Command

PuTTY, yes it is available also on Linux. It is a free and open source gui X based terminal emulator client for the SSH, Telnet, rlogin, and raw TCP computing protocols and as a serial console client. To use it, invoke PuTTY and wait for its GUI.

putty

On Session, select Serial. Again, specify the port as Serial line and the baud rate as Speed.

Tip command

Last but not least, is using tip command. To use tip, we invoke following:

tip -baud device

For example:

tip -115200 ttyS0

The post Five Ways to Communicate with Embedded Device in Linux appeared first on Xathrya.ID.

Ringzer0team CTF Writeup – ELF Crackme 1 – Time to Learning x86 ASM & gdb

Register yourself if you have not yet.

Access the challenge at http://ringzer0team.com/challenges/11

Download the subject,  the checksum:

  • f6816b590d2021a16ba8005aa235e6a3 (md5)
  • b8c18db3e4678e09683e3b20e9004d1183c2420b (sha1)

The challenge clearly instruct as to utilize GDB. In this case, I have customize my GDB using init script which can be downloaded from my github.

After downloading the binary, ran ‘file’ then ‘readelf’ to get some initial information about the file.

# file 88eb31060c4abd0931878bf7d2dd8c1a
88eb31060c4abd0931878bf7d2dd8c1a: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=a5f44b829c4727ed369f823f19d575087673f34e, not stripped

# readelf -h 88eb31060c4abd0931878bf7d2dd8c1a
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x8048380
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4508 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30
  Section header string table index: 27

We know the entrypoint which is 0x8048380 and certain that the file is ELF32.

Load the binary to GDB, we use Intel syntax instead of AT&T syntax and break to entrypoint. We then run the binary so we can reach our breakpoint.

# gdb 88eb31060c4abd0931878bf7d2dd8c1a
gdb$ set disassembly-flavor intel
gdb$ break *0x8048380
gdb$ run

If you are using my .gdbinit script you can see the all the registers. If not, see the disassembly of $eip and let’s analyze the code.

gdb$ disassemble $eip

See the code and learn that there are interesting parts.

...
   0x080484ae <+66>:	mov    DWORD PTR [eax],0x47414c46
   0x080484b4 <+72>:	mov    DWORD PTR [eax+0x4],0x3930342d
   0x080484bb <+79>:	mov    WORD PTR [eax+0x8],0x32
...
   0x080484e9 <+125>:	mov    DWORD PTR [eax],0x75393438
   0x080484ef <+131>:	mov    DWORD PTR [eax+0x4],0x6a326f69
   0x080484f6 <+138>:	mov    WORD PTR [eax+0x8],0x66
...
   0x08048530 <+196>:	mov    DWORD PTR [eax],0x6a736c6b
   0x08048536 <+202>:	mov    DWORD PTR [eax+0x4],0x6c6b34

All of them are pushing the code into some region of memory pointed by eax. It’s ASCII, if you know. Let’s search it in our ASCII table.

0x47414c46   ==> GALF
0x3930342d   ==> 904-
0x32         ==> 2
...
0x75393438   ==> u948
0x6a326f69   ==> j2oi
0x66         ==> f
...
0x6a736c6b   ==> jslk
0x6c6b34     ==> lk4

Well, it doesn’t make sense, unless you remember they are pushed in reverse order for each word. So, the flag would be

FLAG-4092849uio2jfklsj4kl

Submit the flag!

The post Ringzer0team CTF Writeup – ELF Crackme 1 – Time to Learning x86 ASM & gdb appeared first on Xathrya.ID.

My Student’s Final Project, 20 January 2015

Here is my presentation of student’s final project as requirement for graduation from Institut Teknologi Bandung (ITB).

The slides would be in Indonesian Language.

The title would be “Analisis Keamanan dalam Pengembangan Sistem Transaksi ATM Menggunakan Otentikasi Pembuluh Darah” or in English it would be “Security Analysis on ATM System Development using Vein Authentication”

Hai, ini presentasi tugas akhir saya sebagai persyaratan untuk lulus dari Institut Teknologi Bandung (ITB).

Slide presentasi akan menggunakan Bahasa Indonesia.

Judul yang diberikan adalah “Analisis Keamanan dalam Pengembangan Sistem Transaksi ATM Menggunakan Otentikasi Pembuluh Darah”.

 


The post My Student’s Final Project, 20 January 2015 appeared first on Xathrya.ID.

Running Debian MIPS Linux in QEMU

Have you ever want to try system other than your PC? MIPS for example.

As a reverse engineer, I sometimes want to run a MIPS Linux system so that I can observe, develop, and testing somethings. However, I don’t have much room for another device, so virtualization might be a solution.

In this article we will try to run MIPS Linux on QEMU. In specific, Debian MIPS Linux, with following materials used:

  1. Slackware64 14.1
  2. QEMU 2.1.50

The article written here should be as generic as possible so I hope it can be used for different setup you use.

Obtain the Materials

Refer to this article to build a QEMU, if you don’t have one: Installing QEMU from Source

Next, we need to download the kernel images and a disk image which has Debian installed there. Go to this site to download. The ‘mips’ directory is for Big Endian MIPS and ‘mipsel’ is for Little Endian one. Choose what you want but in this case I will download both of them. In specific, we will test kernel version 3.2.0 (denoted as vmlinux-3.2.0-4-5kc-malta) with Debian Wheezy (denoted as debian_wheezy_mipsel_standard.qcow2)

At this point, we have (at least):

  1. QEMU installed
  2. Debian kernel
  3. Disk Image with qcow2 format.

Setup Bridged Networking

In order to make QEMU environment connected to the network, we need to do some additional setup.

Now create the two new files, /etc/qemu-ifup and /etc/qemu-ifdown. Make sure you give them executable permission. Also make sure you have right configuration, like GATEWAY and BROADCAST address. Also pay attention to the USER. It is a username you should specify when you want to run qemu.

#!/bin/bash
ETH0IPADDR=192.168.1.100
GATEWAY=192.168.1.1
BROADCAST=192.168.1.255
USER=xathrya
 
# First take eth0 down, then bring it up with IP address 0.0.0.0
/sbin/ifconfig eth0 down
/sbin/ifconfig eth0 0.0.0.0 promisc up
 
# Bring up the tap device (name specified as first argument, by QEMU)
/usr/sbin/openvpn --mktun --dev $1 --user $USER
/sbin/ifconfig $1 0.0.0.0 promisc up
 
# Create the bridge between eth0 and the tap device
/usr/sbin/brctl addbr br0
/usr/sbin/brctl addif br0 eth0
/usr/sbin/brctl addif br0 $1
 
# Only a single bridge so loops are not possible, turn off spanning tree protocol
/usr/sbin/brctl stp br0 off
 
# Bring up the bridge with ETH0IPADDR and add the default route
 
/sbin/ifconfig br0 $ETH0IPADDR netmask 255.255.255.0 broadcast $BROADCAST
/sbin/route add default gw $GATEWAY

and

#!/bin/bash
 
# Bring down eth0 and br0
/sbin/ifconfig eth0 down
/sbin/ifconfig br0 down
 
# Delete the bridge
/usr/sbin/brctl delbr br0
 
# Bring up eth0 in "normal" mode
/sbin/ifconfig eth0 -promisc
/sbin/ifconfig eth0 up
 
# Delete the tap debice
/usr/sbin/openvpn --rmtun --dev $1

To starting network bridge, just invoke

/etc/qemu-ifup tap0

and then invoke

/etc/qemu-ifdown tap0

to stop it.

Running the Debian MIPS

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

Go to the directory where we store kernel and disk image, for example $HOME/debian-mipsel, and then invoke following command:

qemu-system-mips64el -net nic -net tap,ifname=tap0,script=no,downscript=no 
-M malta -kernel vmlinux-3.2.0-4-5kc-malta -hda debian_wheezy_mipsel_standard.qcow2 
-append "root=/dev/sda1 console=tty0"

We can also create a script to simplify it.

#!/bin/bash

qemu=qemu-system-mips64el
path="$HOME/debian-mipsel/"
hda="$path/debian_wheezy_mipsel_standard.qcow2"
kernel="$path/vmlinux-3.2.0-4-5kc-malta"
iface=tap0

echo "Stopping eth0, starting tap0"

/etc/qemu-ifup tap0 || quit 1 "Failed to start tap0"

echo "Starting Debian MIPS"

$qemu -net nic -net tap,ifname=$iface,script=no,downscript=no 
-nographic -M malta -kernel $kernel -hda $hda -append "root=/dev/sda1 console=tty0"

If everything goes well, you should see Debian is booting and then greeted with sweet login prompt.

Further Configuration

It’s nice to work with QEMU window. But you should admit taht QEMU console is very limiting, so you need SSH connection to do most of your work. You can, by installing OpenSSH inside Debian system using apt:

apt-get update
apt-get install openssh-server

The post Running Debian MIPS Linux in QEMU appeared first on Xathrya.ID.

Installing QEMU from Source

You might notice that I had written an article before about building QEMU from source. That one is QEMU KVM (Kernel Virtual Machine).  As per version version 1.3 QEMU-KVM is merged to upstream QEMU project therefore the QEMU-KVM is no longer maintained. It’s been done long time ago, actually.

QEMU is a generic and open source machine emulator and virtualizer.

When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine. By using dynamic translation, it achieves very good performance.

In this article we will discuss about installing QEMU and use following requirement:

  1. Slackware64 14.0, although any version is OK
  2. latest qemu source code

There are two options for us: building the stable release or building the development code

Obtain the Source Code

Between the stable release source code and development code, which one is suitable for us?If you want to download the latest stable release, you can obtain it from qemu official site here.

At the time of writing this article, the latest stable version is 2.2.0 (per January 8th 2015). You can download it by direct link here. http://wiki.qemu-project.org/download/qemu-2.2.0.tar.bz2

Once you have done downloading, uncompress it with:

tar -jxvf qemu-2.2.0.tar.bz2

If you want to download the development code. You can clone the git repository by:

git clone git://git.qemu-project.org/qemu.git

For any option we choose, we should have qemu source code now.

Installation

Next thing to do is doing configuration and make the binary code. The default installation path would be on /usr/local and we won’t change this thus we will do default procedures. Now invoke following command:

./configure
make
make install

It may take a while. Once you have compile it, you will have qemu installed on standard location on /usr/local. Verify whether qemu has already installed:

qemu-arm -version

You should see some text like this:

qemu-arm version 2.2.0, Copyright (c) 2003-2008 Fabrice Bellard

Congratulation! You have installed qemu.

The post Installing QEMU from Source appeared first on Xathrya.ID.

Building GCC MinGW Toolchain Cross Compiler

Windows, up until today, is still popular Operating System and have large market. This Microsoft’s product is designed for end-user and reducing complexity of Operating System. Even when some other OS such as Linux and Mac OS starts invading, this Operating System is still major and fanatically used by some people in the world.

In this article we will about how to build GCC Win32 and Win64 Toolchain for Win32 and Win64 architecture, which is a cross compiler to build Win32 and Win64 program.

Requirement set for this article:

    1. GCC (Native platform)
    2. Binutils (Native platform)
    3. Bison
    4. Flex
    5. gperf

CoreutilsMake (>= 3.8.1)

  1. SVN & CVS client

Also the test is done on Slackware64 current, though it is optional. You can use other Linux distribution which suit you.

While the previous list is requirement on your host system (your system which will build the cross compiler), we have another list. Some of the component mentioned below will be taken out from their respective repository.

  1. MinGW-w64 (SVN repository)
  2. GCC 4.9.2
  3. Binutils 2.24
  4. GDB 7.8.1
  5. GMP 6.0.0
  6. MPFR 3.1.2
  7. MPC 1.0.2

The Target

There are two architecture: Win32 and Win64. You are free to choose what MinGW system you will build. However, in this article, we will build MinGW Cross Compiler for Windows 64-bit. If you read other cross compiler article, we need a target alias (or simply target) which is the target of the toolchain.

Preparation

We will need some disk space (~2GB should be enough). We also need root access to install it on “system-wide”.

We will create a working directory. We will refer it as $MINGWGCC, so $MINGWGCC/src should really be something like ~/MINGWGCC/src (the ~ means your home directory). So go ahead and create following directory structure:

# set aliases
export MINGWGCC=~/
export PREFIX=/usr/local
export BUILD=$(gcc -dumpmachine)
export TARGET=x86_64-w64-mingw32

export BINUTILS_BUILD=${MINGWGCC}/build/binutils-build
export GCC_BUILD=${MINGWGCC}/build/gcc-build
export GDB_BUILD=${MINGWGCC}/build/gdb-build
export MINGW_BUILD=${MINGWGCC}/build/mingw-build
export MINGW_H_BUILD=${MINGWGCC}/build/mingw-h-build

export BINUTILS_SRC=${MINGWGCC}/src/binutils-2.24
export GCC_SRC=${MINGWGCC}/src/gcc-4.9.2
export GDB_SRC=${MINGWGCC}/src/gdb-7.8.1
export MINGW_SRC=${MINGWGCC}/src/mingw/
export MINGW_HEADERS=${MINGW_SRC}/mingw-w64-headers

# make base dir, original archives dir (orig), source code dir (src), 
# and working / building dir (build) 
mkdir ${MINGWGCC}{,/{orig,src,build}}

# Make build directory for each component
mkdir ${MINGWGCC}/build/{binutils,gcc,gdb,mingw{,-h}}-build

Acquiring the Materials

A cross compiler for Win32 and Win64 are provided by MinGW-w64 project. Download latest packages of GCC, GDB, binutils, and MinGW-w64 source code. You can download it using wget or alternatively download via browser and move it to $MINGWGCC/orig.

cd ${MINGWGCC}/orig

wget ftp://ftp.gnu.org/pub/gnu/gcc/gcc-4.9.2/gcc-4.9.2.tar.bz2
wget ftp://ftp.gnu.org/pub/gnu/gdb/gdb-7.8.1.tar.xz
wget ftp://ftp.gnu.org/gnu/binutils/binutils-2.24.tar.bz2

wget ftp://ftp.gnu.org/pub/gnu/gmp/gmp-6.0.0a.tar.xz
wget ftp://ftp.gnu.org/pub/gnu/mpc/mpc-1.0.2.tar.gz
wget ftp://ftp.gnu.org/pub/gnu/mpfr/mpfr-3.1.2.tar.gz

Then, extract them to src directory.

cd ${MINGWGCC}/src

tar -jxf ${MINGWGCC}/orig/gcc-4.9.2.tar.bz2
tar -Jxf ${MINGWGCC}/orig/gdb-7.8.1.tar.xz
tar -jxf ${MINGWGCC}/orig/binutils-2.24.tar.bz2

Next, the MinGW and GCC codes.

cd ${MINGWGCC}/src
svn co 'https://svn.code.sf.net/p/mingw-w64/code/trunk' mingw

Next we need to download some prerequisites, especially GMP (GNU Multiple Precision), MPC (Multiple-Precision Complex), and MPFR (Multiple-Precision Floating Point Reliably) which is used for computation. The prerequisites can be downloaded by invoking following command:

The MPFR, GMP, and MPC is not the latest version, but at least we can build GCC. Suppose your working directory at /home/xathrya/ARMGCC, to obtain MPDR, GMP, and MPC invoke following command:

cd ${GCC_SRC}
./contrib/download_prerequisites

However, the version of GMP, MPC, and MPFR is not the latest version. We can switch to the latest version by download the latest version and create symbolic link to it.

cd ${GCC_SRC}

rm {gmp,mpc,mpfr}

tar -Jxf ${MINGWGCC}/orig/gmp-6.0.0a.tar.xz
tar -zxf ${MINGWGCC}/orig/mpc-1.0.2.tar.gz
tar -zxf ${MINGWGCC}/orig/mpfr-3.1.2.tar.gz

ln -s gmp-6.0.0 gmp
ln -s mpc-1.0.2 mpc
ln -s mpfr-3.1.2 mpfr

Building the Toolchains

Building stage is pretty simple. Honestly speaking, the tricky part is about how GCC and built concept and ordering them in correct order.

Binutils

First, built binutils. This will provide lots of useful tools in building MinGW libraries and binaries (like objdump, ld, ranlib, etc). Invoke following commands:

cd ${BINUTILS_BUILD}
${BINUTILS_SRC}/configure 
   --target=${TARGET} 
   --enable-targets=x86_64-w64-mingw32,i686-w64-mingw32 
   --prefix=${PREFIX} 
   --disable-nls
make -j4 all
make install
make clean

MinGW Headers

MinGW headers is set of headers used to build MinGW application. It is different beast with Linux GCC headers, although we use the same vendor compiler.

cd ${MINGW_H_BUILD}
${MINGW_HEADERS}/configure 
    --build=${BUILD} 
    --host=${TARGET} 
    --prefix=${PREFIX}/${TARGET}
make install

For v3 and later trunk, we have to append ${TARGET} to our prefix. If not, your native GCC will be contaminated. Please note it.

This will install MinGW headers into ${PREFIX}/${TARGET}/include/ or in our case it would be /usr/local/x86_64-w64-mingw32/include/.

MinGW Directories and Symlinks

We should end up with a ${PREFIX}/${TARGET}/ directory. Manually create lib/ directory and create symbolic link as lib64/

GCC also requires the ${TARGET} directory to be mirrored as a directory ‘mingw’ in the same root (it’s ${PREFIX} directory). Therefore, we need to make a soft link there.

n -s ${PREFIX}/${TARGET} ${PREFIX}/mingw
mkdir -p ${PREFIX}/${TARGET}/lib{,32}
ln -s ${PREFIX}/${TARGET}/lib ${PREFIX}/${TARGET}/lib64

GCC Core

Next we will build the GCC. But please note that we are only intereset on C and C++ so we will ignore other language. To built GCC, do this:

cd ${GCC_BUILD}
${GCC_SRC}/configure 
   --build=${BUILD} 
   --target=${TARGET} 
   --enable-targets=all 
   --prefix=${PREFIX} 
   --enable-interwork 
   --enable-multilib 
   --enable-languages="c,c++" 
   --enable-shared 
   --enable-fully-dynamic-string 
   --with-system-zlib 
   --disable-nls
make -j4 all-gcc install-gcc
make clean

C RunTime (CRT) Library

 Next we will build the C runtime library or the MinGW itself. In the short: building libs required. The static and dynamic lib built with GCC core we have built.

cd ${MINGW_BUILD}
${MINGW_SRC}/configure 
    --host=${TARGET} 
    --prefix=${PREFIX}/${TARGET} 
    --enable-multilib 
    --enable-shared 
    --enable-lib32
make -j4 all
make install

For v3 and later trunk, we have to append ${TARGET} to our prefix. If not, your native GCC will be contaminated. Please note it.

Make sure you have following directories in the ${PREFIX}:

# ${PREFIX} => /usr/local
# ${TARGET} => x86_64-w64-mingw32

${PREFIX}/${TARGET}
${PREFIX}/${TARGET}/include
${PREFIX}/${TARGET}/lib
${PREFIX}/${TARGET}/lib32
${PREFIX}/${TARGET}/lib64 [link to lib]
${PREFIX}/mingw [link to ${TARGET}]
${PREFIX}/mingw/include
${PREFIX}/mingw/lib
${PREFIX}/mingw/lib32
${PREFIX}/mingw/lib64 [link to lib]

GCC (again)

Now that we have our runtime libraries, go back and ginish the GCC build:

cd ${GCC_BUILD}
make -j4
make install

GDB

Optionally you can build GDB. To do so, invoke following:

cd ${GDB_BUILD}
${GDB_SRC}/configure 
   --target=${TARGET} 
   --prefix=${PREFIX} 
   --enable-interwork 
   --enable-multilib
make -j4 all 
make install

And that’s it. You should have them now.

Testing

The toolchain can be tested with the minimal code here, save as demo.c:

int main()
{
   return 0;
}

void exit(int code)
{
   while(1);
}

Invoke following command to compile:

x86_64-w64-mingw32-gcc demo.c -o demo.exe

The post Building GCC MinGW Toolchain Cross Compiler appeared first on Xathrya.ID.

Base Conversion and Rax2 (Radare2 Framework)

As a reverse engineer, we are often face various number in various base and then the need to do conversion rise. We need a handy and simple calculator and converter tool to convert numbers from different bases, change the endianness, etc. Our shell and linux might ship this capability but not as flexible as we want.

Fortunately ‘rax2’ utility comes with Radare2 Framework for a good use. Rax aims to be a minimalistic expression evaluator for the shell and can be used for making base conversions easily between floating point values, hexadecimal representations, hexpair strings to ascii, octal to integer, etc.

In this article we will discuss about some of Rax2 capability.

Invocation

rax2 is a single utility program. We can invoke it directly in our terminal. If no arguments given, rax2 can run on interactive mode.

Let’s see the help.

rax2 -h

And what we see in out screen:

Usage: rax2 [options] [expr ...]
  =[base]                 ;  rax2 =10 0x46 -> output in base 10
  int   ->  hex           ;  rax2 10
  hex   ->  int           ;  rax2 0xa
  -int  ->  hex           ;  rax2 -77
  -hex  ->  int           ;  rax2 0xffffffb3
  int   ->  bin           ;  rax2 b30
  int   ->  ternary       ;  rax2 t42
  bin   ->  int           ;  rax2 1010d
  float ->  hex           ;  rax2 3.33f
  hex   ->  float         ;  rax2 Fx40551ed8
  oct   ->  hex           ;  rax2 35o
  hex   ->  oct           ;  rax2 Ox12 (O is a letter)
  bin   ->  hex           ;  rax2 1100011b
  hex   ->  bin           ;  rax2 Bx63
  hex   ->  ternary       ;  rax2 Tx23
  raw   ->  hex           ;  rax2 -S < /binfile
  hex   ->  raw           ;  rax2 -s 414141
  -b    binstr -> bin     ;  rax2 -b 01000101 01110110
  -B    keep base         ;  rax2 -B 33+3 -> 36
  -d    force integer     ;  rax2 -d 3 -> 3 instead of 0x3
  -e    swap endianness   ;  rax2 -e 0x33
  -f    floating point    ;  rax2 -f 6.3+2.1
  -F    stdin slurp C hex ;  rax2 -F < shellcode.c
  -h    help              ;  rax2 -h
  -k    randomart         ;  rax2 -k 0x34 1020304050
  -n    binary number     ;  rax2 -n 0x1234 # 34120000
  -N    binary number     ;  rax2 -N 0x1234 # x34x12x00x00
  -s    hexstr -> raw     ;  rax2 -s 43 4a 50
  -S    raw -> hexstr     ;  rax2 -S < /bin/ls > ls.hex
  -t    tstamp -> str     ;  rax2 -t 1234567890
  -x    hash string       ;  rax2 -x linux osx
  -u    units             ;  rax2 -u 389289238 # 317.0M
  -v    version           ;  rax2 -V

Compact yet informative.

Number Representations

Mathematical constants are simply fixed values we write, such as: 1, 135, 182, 666, etc. It can be represented in various format / base. Some common representations (in computer science) are: binary, octal, decimal, hexadecimal.

Let’s see some example.

$ rax2 0x345
837
$ rax2 837
0x345
$ rax2 44.44f
Fx8fc23142 
$ rax2 0xfffffffd
-3
$ rax2 -3
0xfffffffd 
$ rax2 -s "41 42 43 44"
ABCD

Decimal number are written as is. The hexadecimal number has 0x prefix on them. We also see 44.44f which is a decimal floating point number (suffix f) and then converted to the hexadecimal representation Fx8fc23142 (with prefix Fx). As you can see, prefix and suffix give important meaning to the conversion. List of all prefix and suffix can be seen on rax2 usage.

Endianness

Endianness (Big Endian and Little Endian) define interpretation of the bytes making up a data word when those bytes stored in computer memory.

Suppose we have value 0x12345678. This is 8 byte value (32-bit) and if we split it into byte, we have 4 bytes. Thus we have 4 bytes: 12, 34, 56, 78 where each byte requires 2 hex digits. The number will be stored differently in Big Endian system and Little Endian system.

Data are written in memory location, using the smallest unit available: byte. Computer are a big array of chunks, addressable by memory address. Memory address is like another number and range from low address to high address.

In Big Endian, you store the most significant byte in the smallest address. In our case, 0x12345678 will be seen as this:

hex1

In Little Endian, things will be different. You store the least significant byte in the smallest address. Here’s how the same value represented:

hex2

Notice that Little Endian is in the reverse order compared to Big Endian.

The good news is, in addition to convert base rax2 can also convert value from one endianness to another endianness. It’s as easy as invoking rax2 with -e argument. For example:

$ rax2 0x12345678
305419896

$ rax2 -e 0x12345678
2018915346

The post Base Conversion and Rax2 (Radare2 Framework) appeared first on Xathrya.ID.

Reverse Engineering Hostile Codes

Computer criminals are always ready to compromise weakness in the system with their hostile codes. Computer Viruses, Worms, Trojans, Malwares, you name it. Often these programs are custom compiled and not widely distributed. Because of this, anti-virus software won’t detect their presences.

In this article we will try to outlines the process of reverse engineering hostile codes. Hostile codes mean any process running on a system that is not authorized by the system administrators. However, our scope will be limited. This article is not intended to be an in-depth tutorial, rather a description of the tools and steps involved.

Tools

There are many tools which can be used for reverse engineering. Reverse engineering can be done in both Unix and Windows platform. However, Unix is still the ideal platform in my opinion. If you are installing Cygwin on Windows, you can emulate Unix environment and do what you can do in Unix.

Going to Windows route will cost lot of money to us where as most of solutions are all free and open source.

Some useful commands based on their categories:

  1. Disk Image Tool – To create disk image, convert and copy a file byte-to-byte. Useful to perform analysis on a compromised system’s disk without affecting the integrity of evidence of the intrusion. Solution in this category: dd.
  2. File Type Identifier – Identifies the type of a file. Identification should rely on magic number used in some part of the file, rather than rely on file extension. Solution in this category: file.
  3. String Identifier – Outputs readable strings from file. Strings might reside in data section or event code section. Solution in this category: strings
  4. Hex Editor – Read and edit binary files. Solution in this category: okteta, HexRay.
  5. Checksum – Creates a unique checksum for comparison purpose. Solution in this category: md5sum, sha1sum, sha256sum.
  6. Diff Tools – Show differences between files. Solution in this category: diff.
  7. Files Monitors – Show all open files and sockets by process. Solution in this category: lsof
  8. Packet Sniffer – Sniffing network packet and traffic to/from machine. Solution in this category: tcpdump, wireshark.
  9. String Search – Search for strings within a file. Solution in this category: grep.
  10. Packer/Unpacker – see Packer section.
  11. Decompiler – see Decomilation.
  12. Disassembler – see Disassembler.

Packer

Malwares are often compressed with an executable packer. This not only makes the code more compact, but also prevets much of the internal string data from being viewed. The most commonly used packer is UPX, which can compress Linux of Windows binaries. Other solutions are available, but they are typically Windows only packer. Good thing is, UPX provide manual decompression to restore the original image. This saves lot of times.

In an ordinary executable, running the “strings” command or examining the malwares with hexeditor should show many readable and complete strings in the file. If we see random characters or mostly truncated and scattered pieces of text, most likely the executables has been packed. Find string “UPX” somewhere in the file to confirm UPX packer involved here. You may want to deal with one of the many other executable packers.

Decompilation

Some malwares might be written in an interpreted or semi-interpreted language such as .NET, Java, etc. You can consider yourself being lucky. There are tools available to decompile these languages to varying degrees.

  • .NET – Microsoft flagship platform for programming. Some decompiler exists around such as ILSpy, dotPeek, etc.
  • Visual Basic – More precisely, Visual Basic before the era of .NET. Visual Basic application is assembled into so called PCode. One of Visual Basic PCode decompiler is P32Dasm.
  • Java – Next infamous cross platform. There is an excellent decompiler jad. Several other known decompilers exist such as: JD, Mocha, JEB Decompiler (for android APK).
  • Delphi – The Pascal in different way. Delphi is once become de facto Rapid Application Development standard. Several decompiler exists, such as DeDe, DE Decompiler, Interactive Delphi Reconstructor.

Some popular interpreted language can be compiled to native codes. And also, there are some tools for decompiling them. While malware engineered using these language are rarely seen, it’s good choice to keep the tools on our arsenal.

If malwares are written in native codes using compiled language, there is chance we can decompile it. Hex-Rays decompiler is one of tool serves this purpose. The Hex Rays decompiler is a plug-ing for IDA Pro, so we should have IDA Pro first. Another option available is Boomerang Decompiler.

However please keep in mind that there is no guarantee that decompilation will return the code as is.

Disassembling

Native code decompiler might exists, however as said before decompilation won’t give guarantee the code returned as is. Our next option is disassembler. These tools work by disassembly the executables into assembly code. For Unix we can use objdump and some of its wrapper like dasm. For windows we can use W32dasm. Some multi platform tool exists, such as IDA Pro and Radare2. These programs will disassemble our code then match up strings in the data segment to where they are used in the program, as well show us separation between subroutines.

Debuggers

Deadlisting can be quite valuable, but we still want to debug the code, especially if the malware is communication via network sockets. Debuggers give us access to the memory and temporary variables stored in the program, as well as all data it is sending and receiving from socket communication.

On Unix land, there is gdb debugger. Under Windows, the choices are far more varied, but most tutorials on reverse engineering under Win32 land use OllyDbg and SoftICE.

Environment Preparation

Running hostile codes must be done with more precautions, even under debugger. Never debug malwares on production machine or network. Ideally, a lab network specially created for this is recommended. Here is the minimal network configuration recommended:

reverseengineeringtrojans1

The debug system should have a clean install of whatever Operating System the malware is intended for. The Firewall is used to protect the network from unwanted incident from outside. Ensure that you firewall all outbound connections, allowing only the Trojan’s control connection through. If you don’t want the master controller to know your lab network is running the Trojan, you can set up services to mimic the resources the Trojan needs, such as an IRC or FTP/TFTP server. The third machine on the network is sniffer which emulate the service and also acts to capture the network traffic generated by the malwares.

Debugging Process

Key-Function Search

First, we skim the code and search for particular interesting function used. We look for key function such as Winsock and file I/O calls. Then we search the occurrence or where are our key-functions invoked. Let the debugger breakpoints on them. There we can interrupt the flow of the program and examine memory and CPU registers at that point.

Running the Code

One of the case we want to inspect is how the malwares communicates with other. Or maybe how the malware communicates with its controller. Often, sniffing the network traffic will be sufficient. However, many newer Trojans are incorporating encryption into their network traffic, making network sniffing useless. However, with some cleverness we can grab the messages from memory before they are encrypted. By setting a breakpoint on the “send” socket library call, we can interrupt the code just prior to the packet being sent. Then, by getting a stack trace, we can see where we are in the program.

Another thing we should consider is the payload or what the malwares do. Poking through file system and access interesting system calls might interest us.

The post Reverse Engineering Hostile Codes appeared first on Xathrya.ID.