Saturday, August 22, 2015

Checklists In Rails 4

This will briefly cover how to create a many-to-many form checklist using the Rails 4 method collection_check_boxes.

In this scenario we'll have a User model (with a first_name and last_name) and a Subject model (with a name). A User should be able to select multiple Subjects. The User/Subject associations are both many-to-many.

If you don't already have it, add the associations to your models and create a linking table.

app/models/subject.rb
has_and_belongs_to_many :users
app/models/user.rb
has_and_belongs_to_many :subjects
db/migrate/[DATETIME]_create_join_table_user_subject.rb
class CreateJoinTableUserSubject < ActiveRecord::Migration
  def change
    create_join_table :users, :subjects do |t|
      t.index [:user_id, :subject_id]
      t.index [:subject_id, :user_id]
    end
  end
end
Next, allow your UserController to accept an array of Subject IDs in its parameters.

app/controllers/users_controller.rb
private
  def user_params
    params.require(:user).permit(:first_name,
                                                   :last_name,
                                                   :subject_ids => [])
  end
To generate the checklist collection_check_boxes will, by default, render all of your checkboxes with labels next to each other. I want them stacked so I've added a block to the end. Inside of the block, you can define the HTML generated for each item using the check_box and label helper methods.

app/views/users/edit.html.erb
<%= form_for(@user) do |f| %>
  <p>Subjects</p>
  <%= f.collection_check_boxes(:subject_ids, Subject.all, :id, :name) do |s| %>
    <%= s.check_box %> <%= s.label %> <br />
  <% end %>
  <%= f.submit "Update Your Subjects" %>
<% end %>
Assuming you have an update route already functioning in your UserController, your @user.update(user_params) should be good to go. If you'd like to display a User's selected Subjects, you can use @user.subjects.map{|s| s.name}.join(', ').

Relevant Links

Friday, August 21, 2015

Android Reversing Bootcamp

[This article was originally written in April 2013 and published in the Spring 2014 issue of 2600: The Hacker Quarterly. Feel free to replace references to BackTrack with Kali or Santoku. If you're into this kind of stuff and want to learn more, pick up a copy of the excellent Android Hacker's Handbook.]

Android Reversing Bootcamp
by Andy G (@vxhex)

So, you've built your first Android application. Now what?
This is a brief introduction to Android application reversing. It assumes a basic knowledge of Java (packages, classes, etc.) and the Android SDK (activities, intents, and the manifest). If you're new to Android development, it'd be helpful to read through some of Vogella's excellent tutorials.[1]
Most of the tools we'll be using are available in the "Reverse Engineering" section on the latest BackTrack (currently version 5rc3).[2]
Reversing engineering can violate some EULAs. It can be used for malicious or legitimate purposes. Be careful what you hack (or who you talk to about it).

First Thing's First
Android apps are packaged into an APK (application package) file for distribution. APKs are based on Java's JAR format: they're zipped archives containing the app's manifest, resources, and code. Like JARs, you can unpackage them with any zip archive manager.
To get our hands on some APKs, we'll be using ASTRO File Manager, available in the Google Play store. Astro allows you to "back up" your apps by saving them to your device's memory as an APK. In Astro, navigate to the Application Manager, select an installed app, and click "backup." The APK will be saved to backups/apps/. From there, you can upload it to your dropbox, email it to yourself, or USB it from your device.
Other methods exist for acquiring APKs (like scripts for the Play store and ADB pulls). If you're interested in trying these out, flex your Google-fu and let me know what worked best for you.

XML Xcitement
Now that we have some APKs, let's unpack them using apktool. Apktool is a program for unpacking and repacking APKs. You can unpack an APK with:
apktool d application.apk
This will create a folder containing the unpacked APK's components.
AndroidManifest.xml is a good place to start.[3] Here we can check permissions, services, and the app's main activity.
An app's starting activity will have an intent-filter listing an action of android.intent.action.MAIN. An app is permitted to have multiple entry points, but it is common to see just one. Make a note of the app's starting activity, as that will be the starting point for our code analysis.
The res folder contains the app's resources, like icons, menus, and strings. Android encourages storing strings and values in XML files instead of hardcoding them into your application, and these can be found in res/values/. Menus, also defined in XML, are found in res/layout/.
An assets folder may also be present, containing miscellaneous files used by the app.

Reading Some Code
It's fairly easy to reconstruct decent Java from an APK. The Java typically won't be perfect, but it's readable and lets you examine the app's logic.
First we'll convert our APK to a JAR using dex2jar.
d2j-dex2jar.sh application.apk
This will produce a JAR file, named application-dex2jar.jar, that can be reversed like any other Java application.
We'll use JD-GUI to look at what we've got.[4] Although it doesn't come standard on BackTrack, JD-GUI will run out-of-the-box. Just extract the tarball and click the "jd-gui" icon to run. From here, head to File->Open, and select the newly-created jar. This will load the app into the decompiler and you should see the packages laid out in a nice tree to the left. You can start from the main activity's onCreate() method and work your way through the application's flow.
If you don't want to install any new software, you can use a Java decompiler called jad. We can unzip the jar file, explore the package structure, and run jad on the .class files we're interested in. This will produce .jad files that contain the class's Java code. From here, you're free to grep away.
unzip application-dex2jar.jar
jad com/package/application/*.class
grep onCreate *.jad

That Was Too Easy
Let's head back to apktool's unpacked stuff and check out the "smali" folder. This folder contains the decompiled bytecode of the application. Its folder structure represents the various packages that make up the app, and the .smali files can be opened with any text editor.
Smali is an assembly-like translation of the Dalvik bytecode. This normally sits inside of the APK in a file called classes.dex. Because smali is a direct translation of the app's code, once you understand how it works, you can edit these  files to modify the app. This is commonly how APKs are cracked or repackaged with malware. Conversely, it can also be used to remove advertisements or malicious payloads. This ability to edit and repackage an APK makes Smali worth diving into a bit deeper.

Smali Syntax
This article won't make you fluent in Smali, but this should give you enough information to start hacking on things. Keep a reference guide open as you work.[5]
Smali uses single characters to represent Java's primitive types.
Z - boolean
I - int
C - char
V - void
B - byte
F - float
D - double
J - long
S - short
Arrays are represented as a [ before a variable type. For example, [[I would be a two-dimensional array of ints.
Methods follow a format of methodName(parameters)returnValue. For example, here's a method that takes a char array and int as parameters and returns a boolean:
Smali: method([CI)Z
Java: boolean method(char[], int);
Objects are represented with a capital L followed by the object's package and name. For example, an object of Java's String class looks like:
Ljava/lang/String;
L designates the object, java/lang/ is the package name, and String is the class itself. Object attributes appear as Name:Type. An object's methods and attributes are accessed using the -> operator.
Comments can be added by starting a line with a # character.

Smali Instructions
Smali instructions are human-readable representations of Dalvik opcodes. A reference will usually be necessary to look up exact syntax and functionality of an instruction, but you can generally infer what's happening.[6]
Like assembly, Smali instructions operate on registers. These are represented by a letter, indicating the type of register, and a number. Registers starting with a v, like v2, are local registers, while a p indicates a parameter register.

Smali Examples
Now let's look at some examples and break down each one.
if-nez v0, :label_name
The if-xxx statements are conditionals. if-nez stands for "if not equal zero." This will evaluate to true if our target, v0, is not equal to zero. :label_name is the label for the block of code we'll jump to if our condition is met.
:label_name
const-string v0, "v0 has a nonzero value."
This is a labeled block of code that moves a string constant into the v0 register. This block of code can be jumped to by referencing label_name. After this operation, we can use this string by referencing v0.
invoke-virtual {v9}, Ljava/lang/String;->trim()Ljava/lang/String;
move-result-object v9
invoke-xxx statements are used to call methods. In this code, Java's trim() method is called on the String object located in v9. The resulting String object is then moved into v9, overwriting our original. The v9 register is our reference to Java's "this," or the calling object. The method prototype follows the syntax previously described: the calling object type (String), the method (trim()), then the return object (also a String). move-result-object then moves the previous instruction's return value into the designated register: v9.

Smali can be a bit overwhelming in large doses, so again grep is your friend when hunting for specific functionality. Otherwise, start in the main activity and look for the onCreate method:
.method public onCreate(Landroid/os/Bundle;)V
After you make changes to an app, you can rebuild it using:
apktool b UnpackedAPK
The resulting APK can then be signed[7], via Keytool and Jarsigner, and distributed for installation.

What Now?
Practice makes perfect. You'll learn quite a bit by building basic "hello world" type apps and hacking on them.
Other topics to explore include ProGuard, SQLite, OWASP's GoatDroid Project, binary reversing (for proprietary binary assets, like those used in $vendor's apps), and apktool's debugging features.

Continued Reading
Blog dedicated to android cracking: androidcracking.blogspot.com
Forum for mobile developers: forum.xda-developers.com
Android reversing examples: www.exploit-db.com/papers/21325/

References
[1] www.vogella.com/articles/Android/article.html
[2] www.backtrack-linux.org
[3] developer.android.com/guide/topics/manifest/manifest-intro.html
[4] java.decompiler.free.fr/?q=jdgui
[5] code.google.com/p/smali/wiki/TypesMethodsAndFields
[6] pallergabor.uw.hu/androidblog/dalvik_opcodes.html
[7] developer.android.com/tools/publishing/app-signing.html