Tuesday, 28 November 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
#!/usr/bin/python

"""Sandwich OS X crackme keygen by kadaj.

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
1111-2222-0000-5764
2681-8944-2259-3691
6773-1497-8343-4530
5903-2519-1731-4492
9613-1094-3343-3921

Tuesday, 14 November 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):
        pass

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

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

    @cherrypy.expose(['greet'])
    @cherrypy.tools.json_out()
    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):
        pass

    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'
        cherrypy.config.update(global_conf)
        conf = {
            '/': {
                'request.dispatch' : dispatcher,
                'tools.staticdir.dir': root_dir
            }
        }
        app = cherrypy.tree.mount(None, '/', global_conf)
        app.merge(conf)
        if hasattr(cherrypy.engine, "signal_handler"):
            cherrypy.engine.signal_handler.subscribe()
        if hasattr(cherrypy.engine, "console_control_handler"):
            cherrypy.engine.console_control_handler.subscribe()
        cherrypy.engine.start()
        cherrypy.engine.block()
# pyserver.py
from blossoms import Blossoms

blossom = Blossoms()
blossom.start()
The configuration are present in the blossoms.conf file.
[global]
server.socket_host: '127.0.0.1'
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.
cherrypy==11.1.0
routes==2.4.1
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, 11 November 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, 8 November 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)
nil
private=> (defn- secret[] "oops")
#'private/secret

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

user=> (#'private/secret)
"oops"

Monday, 6 November 2017

Functional Conf 2017

Functional Conf 2017 is happening in Bangalore this year, which is also hosting the first Erlang & Elixir Factory Lite Conference in India. Also there are separate workshops we can register.

I am attending Reactive Systems & MicroServices Architecture by Francesco Cesarini, along with all Functional Conf sessions with all access pass, and Deep Dive into Erlang Ecosystem by Robert Virding.

Update: The workshops and discussions were so very amazing.

Sunday, 5 November 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"
  [msg]
  "tangle")
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"
  [x]
  "untangle")

;; 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.