Tuesday, November 28, 2017

Dynamic Binary Analysis Using Hopper Disassembler on OS X

Dynamic code analysis in reverse engineering binaries is where we execute the binary for analysis, adding breakpoints, inspecting processor state and such. This is very useful to understand the program's algorithm and values much easier than static binary analysis. However when we analyse malware, running them is dangerous. But we can have an isolated machine where the program can be run and analysed remotely. This is an explanation of these techniques as well as a tutorial on how to reverse OS X crackme challenge (1-Sandwitch.zip | mirror).
This is a small app (by HAWKE, 2009) which requires us to find the correct serial key. The goal is to produce a keygen as opposed to patching. Patching is just easy as changing one instruction.

1. Load the Sandwich.app in Hopper Disassembler, choose the default and proceed to disassembly screen.
2. Instead of remote server, we will connect to the current system using Hopper Debugger Server. Download, install and run the app which will launch the debug server locally.

3. Now in the Hopper, navigate to Debug->Select Debugger... and the server will be listed under local servers section. Double click to launch the server window.
4. The path will be auto filled to something like /Users/.../Sandwich.app/Contents/MacOS/Sandwich. Click the Play icon under controls which will run the Sandwich.app under the debugger.
5. Check the left pane for the available methods. We can see -[SandwichAppDelegate validateSerial:] method. Check the pseudo code to get an idea of the algorithm.

6. Now is the time to add breakpoints so that we can step and check register values as the program runs. So add to the initial address 00001b2d 55 push ebp under that section.
7. Go back to the running program and enter some serial number and click validate, which will make the debugger stop at the breakpoint.
8. The first conditional check is cmp eax, 0x13 which checks if the serial number is 19 decimals long.

9. Second check is mov dword [esp+0x28+var_20], 0x2034 ; @"-" which then checks the number of components separated by - and compares it with cmp eax, 0x4, which means, the serial key has four dashes in it. So the format is xxxx-xxxx-xxxx-xxxxx

10. If all the above passes, it gets each block (chunk separated by dash) and check if length is four.

11. Next it takes the first block 0x0 gets the int value and place it into esi register mov esi, eax.

12. Then it takes the second block 0x1, get the int value and adds it to the block 1 esi value from above step and place it into esi register itself.

13. There is no check for third block which means it can be any random characters of length four.
14. The last block is constructed by computing shift arithmetic right by two of the current esi sar esi, 0x2 from step 12 and then subtracting it from 0x19c5 the HEX for 6597 loaded into edx and then comparing the obtained value to the last block from the serial key loaded into eax

15. If it match, the serial key is correct and a success dialog will be shown. Now that we know the algorithm, we can write the keygen.

The keygen code

"""Sandwich OS X crackme keygen by qlisp.

App: https://reverse.put.as/wp-content/uploads/2010/05/1-Sandwich.zip
Tue 28 Nov 17

import random

class SandwichKeygen:
"""Sandwich key generator."""

__block_3_mn = 6597 # block 3 magic number

def _gen_random(self):
"""Return random number in range of 4 digits."""
return random.randrange(1000, 9999)

def _get_block(self):
"""Get a block containing 4 digits."""
return str(self._gen_random())

def _get_block_3(self, block_1, block_2):
"""Generate the last block from block 1."""
sar_2 = (int(block_1) + int(block_2)) >> 2
return str(self.__block_3_mn - sar_2)

def generate(self):
"""Generates the key."""
block_0 = self._get_block()
block_1 = self._get_block()
return '-'.join([block_0, block_1, str(self._gen_random()), self._get_block_3(block_0, block_1)])

if __name__ == '__main__':
keygen = SandwichKeygen()
print keygen.generate()

# Few keys

Tuesday, November 21, 2017

Functional Conf 2017

I attended Functional Conf 2017 held at Fortune Park, Bangalore. This was one kind of an event. I attended the pre-conf worksop by Francesco Cesarini, Founder and Director of Erlang Solutions, on Reactive Systems & Microservices Architecture, where he talked about building fault tolerant, scalable system architectures. It was an amazing session. This event was the first Erlang & Elixir Factory Lite Conference in India where I got to meet visionaries from the industry. I met with Robert Virding, the co-inventor of the Erlang programming language and attended his post-conf session on Deep Dive into Erlang Ecosystem where he talked about Erlang, its history, the Erlang Virtual Machine, OTP and such. I also met with Martin Thompson, well known for LMAX Disruptor and mechanical sympathy. These were fun filled sessions with meaningful discussions. Had a great experience.

And I came to know that Robert Virding's favourite programming language is LFE, which is Lisp Flavoured Erlang and he is born in Bombay (now Mumbai), India. Francesco specifically told me to ask Robert tough questions for the discussions :D
Finally we greeted goodbyes till next time. Amazing people!

Tuesday, November 14, 2017

Cherry Blossoms with CherryPy

CherryPy is a python web framework which I really like. It is minimalistic in nature, is very pleasant to work with, and still we can accomplish much. Below I will detail a basic web app setup with CherryPy demonstrating basic usage which one can expand further.
# blossoms.py
"""A blossoms server with CherryPy."""

import cherrypy
import os

class CherryBlossom(object):
"""The server route handler methods."""

def __init__(self):

def index(self):
"""The root url, when not mapped to static response, this action will be invoked."""
return self.about()

def about(self):
return 'Enjoy cherry blossoms.'

def get_greeting_message(self, name):
"""Return greetings to the given name in JSON format."""
return {'msg': 'Greetings %s' % name'}

@cherrypy.tools.register('before_finalize', priority=60)
def secureheaders():
"""Update server response headers."""
headers = cherrypy.response.headers
headers['X-Frame-Options'] = 'DENY'
headers['X-XSS-Protection'] = '1; mode=block'
headers['X-Powered-By'] = 'Cherry Blossoms'
headers['Server'] = 'Sakura'

class Blossoms(object):
"""Server configuration and initialisation."""

def __init__(self):

def start(self):
"""Start the service."""
blossom = CherryBlossom()
# routes
dispatcher = cherrypy.dispatch.RoutesDispatcher()
dispatcher.explicit = False
dispatcher.connect('home', '/', blossom.index)
dispatcher.connect('about', '/about/', controller=blossom, action='about', conditions=dict(method=['GET']))
dispatcher.connect('greetings', '/greet/{name}/', controller=blossom, action='greet', conditions=dict(method=['GET']))
# config
root_dir = os.path.dirname(os.path.abspath(__file__))
global_conf = root_dir + '/blossoms.conf'
conf = {
'/': {
'request.dispatch' : dispatcher,
'tools.staticdir.dir': root_dir
app = cherrypy.tree.mount(None, '/', global_conf)
if hasattr(cherrypy.engine, "signal_handler"):
if hasattr(cherrypy.engine, "console_control_handler"):
# pyserver.py
from blossoms import Blossoms

blossom = Blossoms()
The configuration are present in the blossoms.conf file.
server.socket_host: ''
server.socket_port: 1729
server.thread_pool: 8

tools.gzip.on: True
tools.staticdir.on: True
tools.staticdir.index: 'index.html'
tools.staticdir.debug: True,
tools.secureheaders.on = True,
tools.response_headers.on: True,
tools.response.stream: True,
tools.sessions.on = True
tools.sessions.secure = True
tools.sessions.httponly = True
log.screen: True
Calling the /, FQDN alone is configured to serve static content. The GET endpoints are /greet/{name} and /about/. The RoutesDispatcher uses routes package to do the dispatch. The requirements.txt is below.
We load the config and merge it with few updated setting from the code before starting the server. We have a server that handles static content, does REST based routing, custom response headers, JSON, html responses, with configurable settings. Enjoy cherry blossoms.

Saturday, November 11, 2017

Erlang on Android with Termux

Termux is a terminal emulator and Linux environment app for Android. This app, I would say is one of the best things ever happened on an Android platform. It helps us to install packages as in Maemo. The erlang package is available and can be installed using pkg install erlang. It currently installs Erlang/OTP 20, pretty nice.

Wednesday, November 8, 2017

Accessing private functions in Clojure

Nothing in Clojure is truly private. The defn- is more of a way to convey that it is private to the readers. We can access private method by using var quote syntax.
The var special form or the #' reader macro (see Reader) can be used to get an interned Var object instead of its current value.
user=> (ns private)
private=> (defn- secret[] "oops")

private=> (ns user)
user=> (private/secret)
CompilerException java.lang.IllegalStateException: var: #'private/secret is not public, compiling:(NO_SOURCE_PATH:4:1)

user=> (#'private/secret)

Sunday, November 5, 2017

Monkey Patching with Clojure intern Function

The intern function in Clojure is a powerful construct. This is similar to MOP in Groovy. It really comes in handy in many situations. I particularly use it in unit tests to mock (provide override) implementation of data layer methods and to monkey patch third party libraries dynamically.
; com.external.core.clj
(ns com.external.core)

(defn tangle
"An internal method which takes an argument but always return the tangle string"
Now let us say that this is a third party library that we included from maven (or clojars) as project dependency. And we found an issue, the issue being it should return "untangle" instead of "tangle" but we do not have the luxury of upgrading the library to the latest version which has the fix. This is where intern comes in handy.
; com.example.init.clj
(ns com.example.init)

(defn untangle
"Function that fixes a bug in an function that lives in an external namespace"

;; Update the binding, means all callers will see the new patched function, even callers in other any libraries
(intern 'com.external.core 'tangle untangle)
What happens here is that the intern updates the binding of function tangle in the namespace com.external.core to the untangle function defined in com.example.init namespace. From now on any call to the original function will use the updated patched function instead. This is very neat in certain situations where we need to monkey patch. This is not function override, because this change is global as in the entire app sees the new definition. Note that the function signature must be the same. Else it will break the callers.

This is also helpful in unit testing Clojure code. Say we have a service layer and calls into data layer. But we do not want to hit the DB or API methods, as we are not really performing integration tests. So we can provide mock methods inside the deftest with mock results, which will easily help in testing our service layer code.

There is a caveat. This does not work well with Clojure macros, as macros are compile time which generates code. So at runtime, there really is no macro code binding that we can override.