Sunday, July 23, 2017

True Tales of XSS: Function Hoisting

A simplified version of the code:
<script>
func().val('<?php echo htmlspecialchars($input, ENT_COMPAT, 'UTF-8'); ?>');
</script>
Overview: user-supplied $input is echoed into a JavaScript context after having HTML entities encoded. The func() JavaScript function is undefined, causing an exception and halting execution before any injected payload can be executed. We can't inject additional script tags due to the HTML encoding, so an XSS vector isn't immediately apparent.

But it's there.

To gain execution, we'll need to make sure func() is defined. We'll use a JavaScript feature called function hoisting. Hoisting allows a function to be defined after it's been used. The JavaScript interpreter will look ahead for an appropriate function definition and "hoist" it up in the code, so the function call can execute correctly.

We'll use the following payload:
'); function func() {payload}; //
In this payload, we'll finish the val() call, supplying an empty string. Next, we'll provide a definition of func() for the interpreter to hoist. We can insert our payload into func()'s definition and let the original call execute it. Lastly, we'll comment out the trailing "');" that's been left over from the original code.

Now the func() function is defined and will execute with our injected payload. You read a bit more about hoisting here and here.

Stay beautiful, XSS Rangers.

Saturday, March 25, 2017

True Tales of XSS: jQuery's text() Function

A simplified version of the code:
<div id="foo">
<?php echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); ?>
</div>

<script>
var bar = $('#foo').text();
$('#foo').html('<b>' + bar + '</b>');
</script>

Overview: user-supplied $input is echoed after having HTML entities encoded. Next, it's read by jQuery's text(), some decorative tags are added, and written back with html(). Although there's usually little reason to do this in jQuery, it doesn't appear to be vulnerable to XSS.

And yet, it is.

1. We feed a standard XSS test to $input:
<script>alert(1);</script>
2. The $input is encoded with htmlspecialchars(), effectively preventing our XSS from functioning:
 &lt;script&gt;alert(1);&lt;/script&gt;
 3. Our encoded $input is read by jQuery's text() method, which should remove tags and only return the text contents of HTML elements. So, at this point, we could assume our $input would still be:
&lt;script&gt;alert(1);&lt;/script&gt;
Or, if it also removes encoded tags, possibly:
alert(1);
However, text() actually decodes HTML entities and will happily return valid HTML, restoring our $input to its original state:
<script>alert(1);</script>
4. Decorative formatting tags are added to the $input:
<b><script>alert(1);</script></b>
5. The $input is written back to the page with html(), which will also execute our script tag and launch our test payload.

So, keep an eye out for the next time you see text() handling user input, XSS Rangers.

Sunday, January 29, 2017

Flora and Neopixel Ring Quickstart Guide

To celebrate Micro Center carrying Adafruit products, I picked up a Flora V3 and a NeoPixel Ring. Here's a quick guide for making the Flora light that Ring up.

Note: you'll need a micro-B USB cable and some wires. Most of this guide should also work for the NeoPixel strips but your wiring will differ a bit.

Get the Arduino IDE
If you don't already have it, get the Arduino IDE. Download the most recent version of the IDE from the Arduino website and follow the installation instructions (links: Linux, Windows, Mac).

Add Flora Support
Follow the steps to add the Adafruit Board Support package, which will let us use the Flora. Then follow Adafruit's OS-specific instructions (links: Linux, Windows, Mac).

I used IDE version 1.8.1 on Ubuntu 16.04 LTS. As mentioned in the Linux instructions linked above, I also had to add udev rules to make everything jive.

Add NeoPixel Support
Next, you'll need to add the Adafruit NeoPixel library. This will let us use the Flora's on-board NeoPixel as well as the Ring. The easiest way is via the IDE's Library Manager.

You can do this by navigating to "Sketch," then "Include Library," then "Manage Libraries." Search for "neopixel" and install the "Adafruit NeoPixel" library.

Verify Your Setup Works
Verify your Flora + NeoPixel setup by blinking the Flora's onboard NeoPixel.

Save the linked demo code in your current sketch. Under the "Tools" menu, ensure "Board" is set to "Adafruit Flora" and the correct "Port" is selected (mine was /dev/ttyACM0).

Under the "Sketch" menu, select "Verify/Compile," which should complete without errors. Then select "Upload" to push the code to your Flora.

Once it finishes, your Flora should put on a small light show.

Wire Up Your Ring
Now we're ready to wire the Ring to the Flora. I'm lazy, so I used alligator clips. If you're going to go this route, you'll probably want to solder small leads onto the Ring, as it can be a bit difficult to get a solid connection with the clips.

You'll want to connect the Flora's "3.3V" to the Ring's "PWR," the Flora's "GND" to the Ring's "GND," and the Flora's "#9" to the Ring's "IN."


Light Up The Ring

Now we can modify the demo code to use the Ring. We'll need to tell it that we have more LEDs and we're now using the #9 pin. Change the PIN constant from 8 to 9. Change the first parameter of "Adafruit_NeoPixel" from 1 to 12 (or however many LEDs your Ring contains). That's it.
#include <Adafruit_NeoPixel.h>
#define PIN 9
Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, PIN, NEO_GRB + NEO_KHZ800);
As before, "Verify/Compile" then "Upload." The light show should be a bit better now.

That Was Too Easy
Check out the NeoPixel library reference.

Here's some neat projects that use these things. Check out their code to get more ideas:

Saturday, February 27, 2016

Naming Variables: A Short Story

On the Importance of Naming Variables
~a short story~

During the last semester of my engineering degree, I took a class on information retrieval (IR), which focused on search engine internals and file matching. I was taking the class in parallel with a "capstone" course. The capstone was the last requirement for graduation, where teams of students were paired up to work on a project for an actual client company. Capstone was a notorious timesink, so most other courses were put on the back-burner.

The final project for the IR class was to make a program that would accept an image, process it for patterns, and match it to similar images from a corpus. The project was split into two halves: building the searchable corpus and building the front-end. We were grouped into pairs and I happened to wind up with a fellow capstoner, Jim. We talked briefly and I took the corpus half.

We had well over a month to complete the project but, like most college projects, it was ignored until the weekend before the due date. The icing on the cake was the realization that the program for corpus generation took well over an hour to run, even with a small subset of images. This made testing tedious and slow.

An all-nighter ensued, and when I finally passed out, the process was quietly humming away, abusing images and collecting patterns. Without the front-end to actually accept input and match images, I could only hope that corpus would be correct.

The next day, I asked Jim for some testing but received only vague responses. It was clear he hadn't completed the front-end yet. No sweat, we've all been there. I sent him my half of the project so he could finish up.

Finals came and went. IR was last, and the final would be a class presentation of our image-matching projects. It was officially the last thing I ever needed to do for my degree. Excitement ran high. Jim said that our image results were weird, but was positive they were correct. Right, sure thing.

Classmates demonstrated their projects, and it quickly became clear that our results were definitely not correct. An image of the American flag should not have been matched as similar to an image of a kitten. We fumbled through our presentation, realizing we had failed.

Feeling what I assume was frustration and pity, the professor decided to give us until the end of the day to repent. We would receive a just-technically-passing grade on the project if we could fix the matching. The last class of our college careers was now officially over but we were not done. We ran to the lab and furiously opened vim terminals.

I poured over my code, comparing implementations to documentation. It was dark outside now. No breaks, no dinner. The code looked solid. This was my personal nightmare scenario. At least an obvious error would have meant we were done.

Jim was having no luck, either, so we started doubling up on the code. I rolled my chair over to Jim's desk and realized something was wrong. There were no functions, no classes - just a single large block of code in a single large file. I tried to dig into it. Variables were named single sequential letters: a, b, c, etc. Soon the letters doubled: af, ag, ah. I was now in "ba" territory. Jim noticed my horror, and explained that this style of coding saved him significant time during his development. Somehow, I was doubtful.

An hour later, all hope seemed lost. It was past 9:30pm now. From a few feet away, Jim began to laugh. I assumed he'd gone insane. No, he'd found the error! In one of the crucial pattern matching functions, he'd passed in "af," a buffer of pre-processed image data, when it should have been "ag," a buffer of processed pattern data. So obvious, we both should have caught it straight away, I was informed.

A wave of relief as Jim sent an email to the professor, followed by a wave of anger as I debated killing him with the heavy mechanical keyboard. The next morning, technically our first day of post-college, was spent with the professor, demonstrating our now-working program. He was rightly skeptical of our explanation (read: completely pissed off), but passed us with a promised low score. It was a sad way to end, but we were done.

When I asked him what he was thinking with his variable naming, Jim was confused. "This is a common programming problem." No, it really isn't. Words were exchanged, ways were parted, and I'm not sure what happened to Jim after that. As a farewell gift, this story has always stuck with me, and I hope the same is true for him, too.

So, please, for everyone's sake, the next time you're working on a team project, take an extra two seconds to name your variable "image_data_buffer" instead of "af." It may not seem important now but you'll thank yourself if shit hits the fan.

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

Wednesday, April 23, 2014

Refactor Avoidance Driven Development (RADD)

Refactor-Avoidance-Driven Development (RADD) is a software development process that emphasizes the eventual Pull Request that the code will generate. In RADD, care is taken to design commits such that no legacy code shows up in the Pull Request's diff. This is done to expedite the Pull Request and ensure that the developer does not become responsible for refactoring legacy code.
It is a type of development anti-pattern. Compare to Test-Driven Development (TDD).