<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Apkudo &#187; HelloWorld</title>
	<atom:link href="http://mspotten.com/wordpress/tag/helloworld/feed/" rel="self" type="application/rss+xml" />
	<link>http://mspotten.com/wordpress</link>
	<description></description>
	<lastBuildDate>Mon, 05 Jan 2015 21:04:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.42</generator>
	<item>
		<title>Reverse Engineering Android: Disassembling Hello World</title>
		<link>http://mspotten.com/wordpress/reverse-engineering-android-disassembling-hello-world/</link>
		<comments>http://mspotten.com/wordpress/reverse-engineering-android-disassembling-hello-world/#comments</comments>
		<pubDate>Tue, 16 Oct 2012 23:16:10 +0000</pubDate>
		<dc:creator><![CDATA[mspotten]]></dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[baksmali]]></category>
		<category><![CDATA[HelloWorld]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[reverse engineering]]></category>
		<category><![CDATA[smali]]></category>

		<guid isPermaLink="false">http://blog.apkudo.com/?p=775</guid>
		<description><![CDATA[When it comes to learning Android, it&#8217;s amazing how easy it is to find tutorials, code samples, and documentation to immerse yourself into. Interestingly, I&#8217;ve found the inverse to be true for the, dare I say, way cooler world of hacking Android. Reverse engineering Android applications can be really fun and give you a decent knowledge for the inner workings of the Dalvik Virtual Machine. This post will be an all-out, start-to-finish, beginners* tutorial on the tools and practices of reverse engineering Android through the disassembly and code injection of the Android Hello World application. *Beginner means that you know...]]></description>
				<content:encoded><![CDATA[<p>When it comes to learning Android, it&#8217;s amazing how easy it is to find tutorials, code samples, and documentation to immerse yourself into. Interestingly, I&#8217;ve found the inverse to be true for the, dare I say, way cooler world of <strong><em>hacking</em></strong> Android. Reverse engineering Android applications can be really fun and give you a decent knowledge for the inner workings of the <a href="http://en.wikipedia.org/wiki/Dalvik_(software)" target="_blank">Dalvik Virtual Machine</a>. This post will be an all-out, start-to-finish, beginners* tutorial on the tools and practices of reverse engineering Android through the disassembly and code injection of the <a href="http://developer.android.com/training/basics/firstapp/index.html" target="_blank">Android Hello World application</a>.</p>
<p><em>*Beginner means that you know a bit about Android and Java in general, if not, <a href="http://developer.android.com/training/index.html" target="_blank">learn</a> a bit first and come back. Experience in the terminal environment on your machine is also probably necessary.</em></p>
<h4>The Apk</h4>
<p>In order to start reverse engineering, you must first understand what you&#8217;re working with. So what exactly is an apk? (hint: not <a href="http://www.americanparkour.com/" target="_blank">American Parkour</a>.) An <a href="http://en.wikipedia.org/wiki/APK_(file_format)" target="_blank">Android package</a>, or apk, is the container for an Android app&#8217;s resources and executables. It&#8217;s a zipped file that contains simply:</p>
<ul>
<li>AndroidManifest.xml (serialized, non human readable)</li>
<li>classes.dex</li>
<li>res/</li>
<li>lib/ (sometimes)</li>
<li>META-INF/</li>
</ul>
<p>The meat of the application is the classes.dex file, or the Dalvik executable (get it, dex) that runs on the device. The application&#8217;s resources (i.e. images, sound files) reside in the res directory, and the AndroidManifest.xml is more or less the link between the two, providing some additional information about the application to the OS. The lib directory contains native libraries that the application may use via <a href="http://developer.android.com/tools/sdk/ndk/index.html" target="_blank">NDK</a>, and the META-INF directory contains information regarding the <a href="http://developer.android.com/tools/publishing/app-signing.html" target="_blank">application&#8217;s signature</a>.</p>
<p>You can grab the HelloWorld apk we will be hacking <a href="http://www.davtbaum.com/bin/HelloWorld.apk">here</a>. The source to this apk is available from the <a href="http://developer.android.com/training/basics/firstapp/index.html" target="_blank">developer docs tutorial</a>, and when compiled looks something like this:</p>
<div id="attachment_150" style="width: 178px" class="wp-caption aligncenter"><a href="http://apkudo.files.wordpress.com/2012/10/helloworld.png" target="_blank"><img class="size-medium wp-image-150 " title="HelloWorld" alt="" src="http://apkudo.files.wordpress.com/2012/10/helloworld.png" height="300" width="168" /></a><p class="wp-caption-text">Flashy, huh</p></div>
<h4>The Tools</h4>
<p>In order to complete this tutorial, you&#8217;ll need to download and install the following tools:</p>
<ul>
<li><a href="http://code.google.com/p/android-apktool/downloads/list" target="_blank">apktool</a></li>
<li><a href="http://docs.oracle.com/javase/1.3/docs/tooldocs/win32/jarsigner.html" target="_blank">jarsigner</a></li>
<li><a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html" target="_blank">keytool</a></li>
</ul>
<div>Apktool does all of the disassembling/reassembling and wraps functionality from a lot of tools in the reverse engineering realm (smali/baksmali assembler, XML deserializers, etc). I&#8217;m not a _huge_ fan of the tool, but it&#8217;s a great way to get started. Jarsigner and keytool allow you to re-sign the application after it&#8217;s been disassembled. We&#8217;ll get into what the signing process does later on.</div>
<div></div>
<h4>Disassembling the Apk</h4>
<p>Once you&#8217;ve installed apktool, go ahead and open up your terminal and change directory into where you&#8217;ve placed the downloaded apk.</p>
<pre>$ cd ~/Desktop/HelloWorld</pre>
<p>Execution of the apktool binary without arguments will give you its usage, but we will only use the &#8216;d&#8217; (dump) and &#8216;b&#8217; (build) commandline options for this tutorial. Dump the apk using the apktool &#8216;d&#8217; option:</p>
<pre>$ apktool d HelloWorld.apk</pre>
<p>This will tell the tool to decode the assets and disassemble the .dex file in the apk. When finished, you will see the ./HelloWorld directory, containing:</p>
<ul>
<li>AndroidManifest.xml (decoded, human readable)</li>
<li>res/ (decoded)</li>
<li>smali/</li>
<li>apktool.yml</li>
</ul>
<p>The AndroidManifest.xml is now readable, the resources have been decoded, and a smali directory has been created (ignore the apktool.yml as it&#8217;s just a configuration for the tool itself). The smali directory is probably the most important of the three, as it contains a set of smali files, or bytecode representation of the application&#8217;s dex file. You can think of it as an intermediate file between the .java and the executable.</p>
<p>So let&#8217;s take a look at what&#8217;s in the smali directory , &#8216;ls&#8217; yields:</p>
<pre> $ ls HelloWorld/smali/com/test/helloworld/
HelloWorldActivity.smali
R$attr.smali
R$drawable.smali
R$layout.smali
R$string.smali
R.smali</pre>
<p>Immediately we notice that the smali directory contains subdirectories defining the application&#8217;s namespace (com.test.helloworld). Additionally, we can see an individual smali file for each java class. There&#8217;s one catch &#8211; any &#8216;$&#8217; in the smali file&#8217;s name means it&#8217;s an<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html" target="_blank"> inner class </a>in Java. Here we see the bytecode representation of the following classes:</p>
<ul>
<li>HelloWorldActivity.java</li>
<li>R.java</li>
</ul>
<p>Where R.java contains inner classes attr, string, and so on. It&#8217;s evident that HelloWorldActivity is the activity that&#8217;s displayed when the app launches, so what exactly is R?</p>
<p>R.java is an automatically generated file at application build time that maps resources to an associated id. When a developer wants to use anything in the res folder, he/she must use the R class to appropriately reference that resource. Because of this, we&#8217;ll omit the R.java from our investigation, as it really only contains a bunch of constants that no one cares about.</p>
<h4>Reading the Smali</h4>
<p>Now that we&#8217;ve disassembled our apk, let&#8217;s take a look at the java and smali representations of our impressive HelloWorldActivity.</p>
<pre>package com.test.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloWorldActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView text = new TextView(this);
        text.setText("Hello World, Android");
        setContentView(text);
    }
}
.class public Lcom/test/helloworld/HelloWorldActivity;
.super Landroid/app/Activity;
.source "HelloWorldActivity.java"

# direct methods
.method public constructor ()V
    .locals 0

    .prologue
    .line 7
    invoke-direct {p0}, Landroid/app/Activity;-&gt;()V

    return-void
.end method

# virtual methods
.method public onCreate(Landroid/os/Bundle;)V
    .locals 2
    .parameter "savedInstanceState"

    .prologue
    .line 11
    invoke-super {p0, p1}, Landroid/app/Activity;-&gt;onCreate(Landroid/os/Bundle;)V

    .line 13
    new-instance v0, Landroid/widget/TextView;

    invoke-direct {v0, p0}, Landroid/widget/TextView;-&gt;(Landroid/content/Context;)V

    .line 14
    .local v0, text:Landroid/widget/TextView;
    const-string v1, "Hello World, Android"

    invoke-virtual {v0, v1}, Landroid/widget/TextView;-&gt;setText(Ljava/lang/CharSequence;)V

    .line 15
    invoke-virtual {p0, v0}, Lcom/test/helloworld/HelloWorldActivity;-&gt;setContentView(Landroid/view/View;)V

    .line 17
    return-void
.end method</pre>
<p>It should be pretty evident which one of these files is written in java, nonetheless, the smali representation shouldn&#8217;t be too intimidating.</p>
<p>Let&#8217;s break down whats going on here in java first.  In <strong>line 07</strong>, we define our HelloWorldActivity class that extends android.app.Activity, and within that class, override the onCreate() method. Inside the method, we create an instance of the TextView class and call the TextView.setText() method with our message. Finally, in <strong>line 15 </strong>we set the view by calling setContentView(), passing in the TextView instance.</p>
<p>In smali, we can see that we have a bit more going on. Let&#8217;s break it up into sections, we have:</p>
<ol>
<li>class declarations from <strong>lines 01-03</strong></li>
<li>a constructor method from <strong>lines 07-15</strong></li>
<li>a bigger onCreate() method from <strong>lines 19-43</strong></li>
</ol>
<div>
<h4>Declarations and Constructor</h4>
<p>The class declarations in smali are essentially the same in java, just in a different syntax. They give the virtual machine their class and superclass name via the .class and .super tags. Additionally, the compiler throws in the source file name for&#8230;shits and gigs? Nope, stack traces.</p>
<p>The constructor has seemingly appeared out of no where, but really was inserted by the compiler because we extended another class. You can see that in <strong>line 12</strong> the virtual machine is to make a direct invokation of the super classes constructor &#8211; this follows the nature of subclasses, they must call their superclasses constructor.</p>
<h4>Data Types</h4>
<p>In the onCreate() method beginning on <strong>line 19</strong>, we can see that the smali method definition isn&#8217;t that far off from its java counterpart. The method&#8217;s parameter types are defined within the parenthesis (semicolon separated) with the return type discreetly placed on the end of the .method line. Object return types are easy to recognize, given they begin with an L and are in full namespace. Java primitives, however, are represented as capital chars and follow the format:</p>
<pre>V	 void
Z	 boolean
B	 byte
S	 short
C	 char
I	 int
J	 long (64 bits)
F	 float
D	 double (64 bits)</pre>
<p>So for our onCreate() definition in smali, we can expect a void return value.</p>
<h4>Registers</h4>
<p>Moving one line down, on <strong>line 20</strong> we see the &#8216;.locals&#8217; directive. This determines how many registers the Dalvik vm will use for this method <strong>_without_</strong> including registers allocated to the parameters of the method. Additionally, the number of parameters for any virtual method <strong>will always be the number of input parameters + 1</strong>. This is due to an implicit reference to the current object that resides in parameter register 0 or p0 (<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html" target="_blank">in java this is called the &#8220;this&#8221; reference</a>). The registers are essentially references, and can point to both primitive data types and java objects. Given 2 local registers, 1 parameter register, and 1 &#8220;this&#8221; reference, the onCreate() method uses an effective 4 registers.</p>
<p>For convenience, smali uses a &#8216;v&#8217; and &#8216;p&#8217; naming convention for local vs. parameter registers. Essentially, parameter (p) registers can be represented by local (v) registers and will always reside in the highest available registers. For this example, onCreate() has 2 local registers and 2 parameter registers, so the naming scheme will look something like this:</p>
<pre>v0 - local 0
v1 - local 1
v2/p0 - local 2 or parameter 0 (this)
v3/p1 - local 3 or parameter 1 (android/os/Bundle)</pre>
<p><strong><em>Note: You may see the .registers directive as oppose to the .locals directive. The only difference is that the .registers directive includes parameter registers (including &#8220;this&#8221;) into the count. Given the onCreate() example, .locals 2 == .registers 4</em></strong></p>
</div>
<h4>Opcodes</h4>
<p>Dalvik opcodes are relatively straightforward, but there are a <a href="http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html" target="_blank">lot of them</a>. For the sake of this post&#8217;s length, we&#8217;ll only go over the basic (yet important) opcodes found in our example HelloWorldActivity.smali. In the onCreate method in HelloWorldActivity the following opcodes are used:</p>
<ol>
<li><strong>invoke-super vx, vy, &#8230;</strong> invokes the parent classes method in object vx, passing in parameter(s) vy, &#8230;</li>
<li><strong>new-instance vx </strong>creates a new object instance and places its reference in vx</li>
<li><strong>invoke-direct vx, vy, &#8230;</strong> invokes a method in object vx with parameters vy, &#8230; without the virtual method resolution</li>
<li><strong>const-string vx</strong> creates string constant and passes reference into vx</li>
<li><strong>invoke-virtual vx, vy, &#8230;</strong> invokes the virtual method in object vx, passing in parameters vy, &#8230;</li>
<li><strong>return-void</strong> returns void</li>
</ol>
<h4>Hacking the App</h4>
<p>Now that we know what we&#8217;re looking at, lets inject some code and rebuild the app. The code we will inject is only one line in java and presents the user with the toast message &#8220;hacked!&#8221;.</p>
<pre>Toast.makeText(getApplicationContext(), "Hacked!", Toast.LENGTH_SHORT).show();</pre>
<p>How do we do this in smali? Easy, let&#8217;s just compile this into another application and disassemble. The end result is something like this:</p>
<pre>    .line 18
    invoke-virtual {p0}, Lcom/test/helloworld/HelloWorldActivity;-&gt;getApplicationContext()Landroid/content/Context;

    move-result-object v1

    const-string v2, "Hacked!"

    const/4 v3, 0x0

    invoke-static {v1, v2, v3}, Landroid/widget/Toast;-&gt;makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;

    move-result-object v1

    invoke-virtual {v1}, Landroid/widget/Toast;-&gt;show()V</pre>
<p>Now, let&#8217;s ensure we have the right amount of registers in our original onCreate() to support these method calls. We can see that the highest register in the code we want to patch is v3, which we have but will require us to overwrite both of our parameter registers. Given we won&#8217;t be using either of those registers after setContentView(), this number is appropriate. Our final patched HelloWorldActivity.smali should look like:</p>
<pre>.class public Lcom/test/helloworld/HelloWorldActivity;
.super Landroid/app/Activity;
.source "HelloWorldActivity.java"

# direct methods
.method public constructor ()V
    .locals 0

    .prologue
    .line 8
    invoke-direct {p0}, Landroid/app/Activity;-&gt;()V

    return-void
.end method

# virtual methods
.method public onCreate(Landroid/os/Bundle;)V
    .locals 2
    .parameter "savedInstanceState"

    .prologue
    .line 12
    invoke-super {p0, p1}, Landroid/app/Activity;-&gt;onCreate(Landroid/os/Bundle;)V

    .line 14
    new-instance v0, Landroid/widget/TextView;

    invoke-direct {v0, p0}, Landroid/widget/TextView;-&gt;(Landroid/content/Context;)V

    .line 15
    .local v0, text:Landroid/widget/TextView;
    const-string v1, "Hello World, Android"

    invoke-virtual {v0, v1}, Landroid/widget/TextView;-&gt;setText(Ljava/lang/CharSequence;)V

    .line 16
    invoke-virtual {p0, v0}, Lcom/test/helloworld/HelloWorldActivity;-&gt;setContentView(Landroid/view/View;)V

    # Patches Start

    invoke-virtual {p0}, Lcom/test/helloworld/HelloWorldActivity;-&gt;getApplicationContext()Landroid/content/Context;

    move-result-object v1

    const-string v2, "Hacked!"

    const/4 v3, 0x0

    invoke-static {v1, v2, v3}, Landroid/widget/Toast;-&gt;makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;

    move-result-object v1

    invoke-virtual {v1}, Landroid/widget/Toast;-&gt;show()V

    # Patches End

    return-void
.end method</pre>
<p><strong>Lines 40+</strong> contain the injected code.</p>
<h4>Rebuilding the Apk</h4>
<p>Now all that&#8217;s left is to rebuild the app!</p>
<pre>$ apktool b ./HelloWorld</pre>
<p>This will instruct apktool to rebuild the app, however, this rebuilt app will <strong>not</strong> be signed. We will need to sign the app before it can be successfully installed on any device or emulator.</p>
<h4>Signing the Apk</h4>
<p>In order to sign the apk, you&#8217;ll need jarsigner and keytool (or a platform specific alternative, like <a href="http://www.londatiga.net/it/how-to-sign-apk-zip-files/" target="_blank">signapk for windows</a>). With jarsigner and keytool, however, the steps are pretty easy. First create the key:</p>
<pre>$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -validity 10000</pre>
<p>Then use jarsigner to sign your apk, referencing that key:</p>
<pre>$ jarsigner -verbose -keystore my-release-key.keystore ./HelloWorld/dist/HelloWorld.apk alias_name</pre>
<p>Then you&#8217;re done! Install the app onto your device or emulator and impress the shit out of yourself!</p>
<div id="attachment_318" style="width: 178px" class="wp-caption aligncenter"><a href="http://apkudo.files.wordpress.com/2012/10/mm.png" target="_blank"><img class="size-medium wp-image-318 " title="Hello World Hacked" alt="" src="http://apkudo.files.wordpress.com/2012/10/mm.png" height="300" width="168" /></a><p class="wp-caption-text">damn&#8230;impressive</p></div>
<p>That&#8217;s it for this tutorial, but stay tuned. There will definitely be more in the future. Feel free to leave any questions in the comment section, or <a href="mailto:david@apkudo.com" target="_blank">contact </a>me with any questions.</p>
<p>Happy hacking,</p>
<p>David Teitelbaum</p>
]]></content:encoded>
			<wfw:commentRss>http://mspotten.com/wordpress/reverse-engineering-android-disassembling-hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
