Coder Social home page Coder Social logo

withsecurelabs / drozer Goto Github PK

View Code? Open in Web Editor NEW
3.6K 178.0 760.0 125.82 MB

The Leading Security Assessment Framework for Android.

Home Page: https://labs.withsecure.com/tools/drozer

License: Other

Makefile 0.06% Python 94.61% C 0.77% Shell 0.35% JavaScript 0.25% Java 2.36% HTML 0.81% Batchfile 0.68% Dockerfile 0.12%
drozer android security pentesting java mobile mwr mobsec withsecure

drozer's Introduction

drozer

drozer is a security testing framework for Android.

drozer allows you to search for security vulnerabilities in apps and devices by assuming the role of an app and interacting with the Android Runtime, other apps' IPC endpoints and the underlying OS.

drozer provides tools to help you use, share and understand public Android exploits.

drozer is open source software, maintained by WithSecure, and can be downloaded from: https://labs.withsecure.com/tools/drozer/

NOTE

This is an BETA release of a rewritten drozer version; this version is updated to support python3.

Currently, the following known issues are present:

  • Building of custom agents functionality will crash the drozer client. This functionality is considered out of scope for the beta release of the revived drozer project.

Docker Container

To help with making sure drozer can be run on all systems, a Docker container was created that has a working build of drozer.

  • The Docker container and basic setup instructions can be found here.
  • Instructions on building your own Docker container can be found here.

Manual Building and Installation

Software pre-requisites

  1. Python3.8
  2. Protobuf 4.25.2 or greater
  3. Pyopenssl 22.0.0 or greater
  4. Twisted 18.9.0 or greater
  5. Distro 1.8.0 or greater
  6. Java Development Kit 11 or greater

Installing

You can use pip or pipx (preferably, if available) to install the latest release of drozer from our releases:

pipx install ./drozer-*.whl

If you haven't already, consider running:

pipx ensurepath

to ensure pipx-installed packages appear in your PATH

Building

To build drozer from source you can run.

git clone https://github.com/WithSecureLabs/drozer.git
cd drozer
pip install .

To build the Android native components against a specific SDK you can set the ANDROID_SDK environment variable to the path. For example:

Linux/macOS:

export ANDROID_SDK=/home/drozerUser/Android/Sdk/platforms/android-34/android.jar

Windows - PowerShell:

New-Item -Path Env:\ANDROID_SDK -Value 'C:\Users\drozerUser\AppData\Local\Android\sdk\platforms\android-34\android.jar'

Windows - cmd:

set ANDROID_SDK = "C:\Users\drozerUser\AppData\Local\Android\sdk\platforms\android-34\android.jar"

The location of the d8 tool used can also be changed by setting D8.

Usage

Installing the Agent

drozer can be installed using Android Debug Bridge (adb).

Download the latest drozer Agent here.

adb install drozer-agent.apk

Setup for session

You should now have the drozer Console installed on your PC, and the Agent running on your test device. Now, you need to connect the two and you’re ready to start exploring.

We will use the server embedded in the drozer Agent to do this.

You need to set up a suitable port forward so that your PC can connect to a TCP socket opened by the Agent inside the device or emulator. By default, drozer uses port 31415:

adb forward tcp:31415 tcp:31415`

Now, launch the Agent, select the "Embedded Server" option and tap "Enable" to start the server. You should see a notification that the server has started.

Start a session - running drozer on host

On your PC, connect using the drozer Console:

drozer console connect

If using a real device, the IP address of the device on the network must be specified:

drozer console connect --server 192.168.0.10

You should be presented with a drozer command prompt:

selecting f75640f67144d9a3 (unknown sdk 4.1.1)  
dz>

The prompt confirms the Android ID of the device you have connected to, along with the manufacturer, model and Android software version.

Command Reference

Command Description
run Executes a drozer module
list Show a list of all drozer modules that can be executed in the current session. This hides modules that you do not have suitable permissions to run.
shell Start an interactive Linux shell on the device, in the context of the Agent process.
cd Mounts a particular namespace as the root of session, to avoid having to repeatedly type the full name of a module.
clean Remove temporary files stored by drozer on the Android device.
contributors Displays a list of people who have contributed to the drozer framework and modules in use on your system.
echo Print text to the console.
exit Terminate the drozer session.
help Display help about a particular command or module.
load Load a file containing drozer commands, and execute them in sequence.
module Find and install additional drozer modules from the Internet.
permissions Display a list of the permissions granted to the drozer Agent.
set Store a value in a variable that will be passed as an environment variable to any Linux shells spawned by drozer.
unset Remove a named variable that drozer passes to any Linux shells that it spawns.

License

drozer is released under a 3-clause BSD License. See LICENSE for full details.

Contacting the Project

drozer is Open Source software, made great by contributions from the community.

For full source code, to report bugs, suggest features and contribute patches please see our Github project:

https://github.com/WithSecureLabs/drozer

Bug reports, feature requests, comments and questions can be submitted here.

drozer's People

Contributors

0xbc avatar agnivesh avatar agreenbhm avatar amarekano avatar cybermilosz avatar dnet avatar droidmannn avatar henryhoggard avatar ikelos avatar jalvarezz13 avatar jduck avatar jihoi-kim avatar josephredfern avatar metall0id avatar mmmds avatar nezza avatar nixawk avatar noraj avatar nyaalex avatar pstoeckle avatar rvantonder avatar sam-b avatar samcorbin avatar tombrium avatar vanhoefm avatar x11x avatar yogehi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

drozer's Issues

Communication protocol redesign

We are looking at redesigning the communications protocol to take this project to the next level.

The communication protocol is rather simple at the moment and is using a defined XML communication in 1 direction only, from client to server. In order to reach a point where Mercury can be used for many purposes, the following would need to be supported by the communications protocol:

  • Encryption - I suspect something like SSL would be best
  • Bi-directional communications. The ability to have the server connect back to the client OR the client connect to the server would (i.e. Reverse and bind connections) be needed in many applications of Mercury.

By implementing these, it would be the most flexible. Examples of when a bind connection is needed: current "assessment suite". Examples of when a reverse connection is needed: full exploitation suite

Any ideas are welcome
Tyrone

Client->Server XML malformed on Fedora

An issue has been reported on Fedora 17 Python 2.7.3 that causes the XML sent from the client to the server to contain newline characters where there shouldn't be. This causes XML parsing errors on the server.

A ping request to the server has been reported to look like:

<?xml version="1.0" ?>
<transmission><command><section>core</section><function>ping</function><arguments/></command></transmission>

instead of:

<?xml version="1.0" ?><transmission><command><section>core</section><function>ping</function><arguments/></command></transmission>

Python 2.7 + Windows 7 x64 Install of Mercury

It seems rather tricky to get Mercury up and running with W7x64 and Python2.7, the way I have got it to work is as follows:

easy_install.exe protobuf==2.4.1 (2.5.0 is the latest so you need to specify with the command line or change it within the code)
easy_install.exe pyreadline
easy_install.exe twisted==10.2.0
easy_install.exe pyOpenSSL
(this will fail)

After that I just installed the eGenix pyOpenSSL distribution from http://www.egenix.com/products/python/pyOpenSSL/

Also added adb to the path, then followed the rest of the guide

Note I had to install via the distributable installer rather than doing python setup.py install. If I don't I get the following:
mercury> run scanner.provider.injection
Scanning android...
Mercury could not find or compile a required extension library.

-AM

Core.unzip - hardcoded zip entry to unzip

Inside Core.java, the "unzip" function is hardcoded to only unzip the classes.dex file.

It needs to be changed to accept a file entry as an argument e.g. AndroidManifest.xml

This will make it more flexible in the future.

Showing query failed when querying for content providers

Even with Read and Write permissions null for various applications, whenever i try to query for a content provider, say

After querying for notepad3 permissions

Package name: com.android.demo.notepad3
Authority: com.android.demo.notepad3.SuggestionProvider
Required Permission - Read: null
Required Permission - Write: null
Grant Uri Permissions: false
Multiprocess allowed: false

when i try

mercury#provider> query content://com.android.demo.notepad3

"Query failed"

Anything I'm doing wrong?

sFlagBinaries does not work

On 2.1, I get the following where trying to run the sFlagBinary module:

mercury> run scanner.misc.sflagbinaries
Found suid/sgid binaries:
/data/data/com.mwr.droidhg.agent/busybox: 1: Syntax error: word unexpected (expecting ")")

Mercury hangs on connect

When typing connect the console hangs on some devices. It has been noted to do this on the Galaxy Nexus. It could be all Ice Cream Sandwich devices as well.

It is believed that this happens when loading libjackpal-androidterm3.so

app.provider.delete does not work.

Under Delete

  1. Remove dest from parser:
def add_arguments(self, parser):
    parser.add_argument("uri", nargs="?", help="the content provider uri to query")
    parser.add_argument("--selection", default=None, metavar="<rows>")
    parser.add_argument("--selection-args", default=None, metavar="<arg>", nargs="*")
  1. Remove 's' from arguments as follows:

    def execute(self, argument):
    c = self.contentResolver().delete(argument.uri, argument.selection, argument.selection_args)

app.provider.read error

mercury> run app.provider.read content://com.mwr.example.sieve.FileBackupProvider/../../../../../system/etc/hosts
unsupported operand type(s) for +: 'ReflectedNull' and 'str'

Don't think this is right...

Galaxy S3 Privilege Escalation Exploit

I was going to do this myself, but I seem to never get around to doing it. Would be awesome for Mercury :)

The privilege escalation described in this post by Andre Moulu allows an unprivileged application (like Mercury) to install a package on the phone: http://sh4ka.fr/android/galaxys3/from_0perm_to_INSTALL_PACKAGES_on_galaxy_S3.html

At the beginning of the exploit, Mercury could check if the device is patched by checking whether the Kies broadcast receiver has the android.permission.KIES_BNR permission set on it.

Try append / to the end of Content URIs when searching for accessible URIs

Recently I've noted a couple of places where PATH_LITERAL is used to enforce permissions to a content provider. In some cases this can be trivially bypassed; but Mercury doesn't pick this up.

For instance, in Sieve:

mercury> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Keys
Permission Denial: reading com.mwr.example.sieve.DBContentProvider uri content://com.mwr.example.sieve.DBContentProvider/Keys from pid=646, uid=10044 requires com.mwr.example.sieve.READ_KEYS, or grantUriPermission()
mercury> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Keys/
| Password         | pin  |
| thisismypassword | 9876 |

mercury.py SyntaxError: invalid syntax line 66 while running on Windows 7

Hi,
After an attempt to run mercury.py file on Windows I receive below error:

C:\apps\mercury\client>python mercury.py
File "mercury.py", line 66
print "\nMercury Client v" + mercury_version
^
SyntaxError: invalid syntax

Mercury version 1.1
OS: Windows 7 (x86)

Can you please help to find out the solution?
Thanks.

Obj files in repository.

I noticed that the git repo for mercury includes a bunch intermediate files that are generated during the compilation process, such as the ones in server/obj and most of the ones in server/bin .
Is there any good reason for those files to be there? I makes it much more complicated to analyse diffs and generate clean patches than it should be.
Locally i work with a custom gitignore to avoid ignore those files, just wanted to hear from you if this could be ported to the main repo.

VulnerabilityScanner Modules

I am busy making a scanner module that checks exploit.root. in order to search for root exploits that will work on a device.

At the moment - we require that a label is set inside each Vulnerability module that is being checked by the VulnerabilityScanner otherwise the following error is thrown: 'ClassnameX' object has no attribute 'label'

In the absence of a label should we print out the namespace path instead e.g. exploit.root.cmdclient - Vulnerable or is the use of a label something that we would like to enforce?

Motorola Xoom FE Root

Could someone please run the following test on their Motorola Xoom FE:

From Mercury shell->persistent type the following:

cmdclient ec_skunumber '; sh;

Now check if you are system by typing:

id

Please let me know the result if you have tried this.

Credits: Dan Rosenberg @ http://vulnfactory.org/

OpenSSL Import error

Hi,

When i try to launch mercury, then command console throwing an error message as " ImportError: No Module named OpenSSL"

Environment: win 7, Mercury 2.1.0 win installer

OpenSSL_Import Error

Attached a screenshot, please do help me.

Regards
Kiran

Handling of `exit` inside a shell

Typing exit inside a shell session quits the shell regardless of if a new shell session with elevated privileges has been opened inside. I will demonstrate what I mean.

The normal workflow of a shell on a PC is as follows:

user@machine:~$ su 
root@machine:/home/user# exit
user@machine:~$

You are dropped back into your last shell, whereas with a Mercury shell:

mercury> run shell.start
$ su
# exit
mercury>

At the moment, we don't have a way to navigate back. Maybe we can look at ways of detecting that the shell session no longer exists and only exiting at that point?

Windows Readline internal error when expanding package names

Using tab expansion on Windows generates a readline internal error when specifying a package name:

mercury> run app.package.attacksurface comReadline internal error
Traceback (most recent call last):
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\console\console.py", line 761, in hook_wrapper_23
    res = ensure_str(readline_hook(prompt))
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\rlmain.py", line 567, in readline
    self._readline_from_keyboard()
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\rlmain.py", line 532, in _readline_from_keyboard

    if self._readline_from_keyboard_poll():
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\rlmain.py", line 552, in _readline_from_keyboard_poll
    result = self.mode.process_keyevent(event.keyinfo)
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\modes\emacs.py", line 242, in process_keyevent
    r = self.process_keyevent_queue[-1](keyinfo)
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\modes\emacs.py", line 285, in _process_keyevent
    r = dispatch_func(keyinfo)
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\modes\basemode.py", line 255, in complete
    completions = self._get_completions()
  File "c:\users\jwright\appdata\local\temp\easy_install-ajrusb\pyreadline-1.7.1-py2.7-win32.egg.tmp\pyreadline\modes\basemode.py", line 198, in _get_completions
    r = ensure_unicode(self.completer(text, i))
  File "C:\Python27\lib\site-packages\mercury-2.1.0-py2.7.egg\mwr\common\cmd_ext.py", line 136, in complete
    return self.completion_matches[state]
TypeError: 'NoneType' object is not subscriptable

Running on Windows 7 with Python 2.7 and pyreadline 1.7.1.

Mercury panic in handling non-ascii letters in query results

If there is non-ascii letters in query results of content provider, such as Chinese characters, there will be an error like "UnicodeEncodeError: 'ascii' codec can't encode characters in position 505-506: ordinal not in range(128)".

Please add support for non-ascii letters, or just use utf-8 encoding.

Two screenshots are given, the first one is what Mercury complains, the second one shows the characters causing error.

Screen Shot 2013-04-01 at 5 35 08 PM

20130401_173337

registerReceiver feature

Suggestion of a new module to register a receiver in order to be possible to listen to an Intent.

The usage for this module would be something like this:

mercury> run app.broadcast.register --action  <some action>
Listening to: [some action]
[*] Intent received: [action]
       Intent extras:
                [extra name]: [extra value]
                [extra name]: [extra value]
                [extra name]: [extra value]
                [extra name]: [extra value]

This would be useful to check which information is included in some specific Intent.

Include localroot for 4.0.3 <

Current public releases of mempodipper most recent local root for android devices based on /proc/pid/mem arbitrary write only supports a few handsets, as the exploit requires you pass it offsets for setuid() and for exit(), and these have only been determined for a number of devices. nesquick95 @ xda developers devised a method for obtaining these offsets, and I have merged his code into the mempodipper exploit. Cross compile for arm, and then run on a vulnerable device:

./mempodipper < address to exit> < address to setuid> <-command>

or now alternatively:

./mempodipper - - <-command>

The dynamic version of mempodipper is relatively untested, and likely needs some work before it is ready to be incorporated into mercury, however most of the work is already done.

source here:
http://pastebin.com/RM4zyy9a

Broadcast Receiver Intent Filters are not always returned correctly

Intent Filters are not correctly reported in app.broadcast.info if the Manifest specifies the FQN of the implementing class. For instance, in the following example:

        <receiver
            android:name="com.example.receivers.ReceiverOne"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>
        <receiver
            android:name=".ReceiverTwo"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>

only ReceiverTwo is correctly identified.

The offending piece of code seems to be:

return map(lambda r: r.attrib['name'], xml.findall("./application/receiver[@name='" + str(receiver.name)[len(receiver.packageName):] + "']/intent-filter/action"))

which forceably strips the package name from the beginning of the receiver.

Python 2.x xrange/range optimization

xrange is replaced by range in Python 3.x, but Mercury is currently compatible with 2.7, perhaps it is worthwhile to change the following to xrange:

$ grep -r "[^x]range(" src/*
src/mwr/droidhg/repoman/installer.py:        for i in range(len(directories)):
src/mwr/droidhg/repoman/manager.py:            for i in range(len(repositories)):
src/mwr/droidhg/modules/auxiliary/web_content_resolver.py:            for i in range(len(rows[0])):
src/mwr/droidhg/modules/auxiliary/web_content_resolver.py:                for i in range(len(r)):
src/mwr/droidhg/modules/common/formatter.py:        for i in range(len(rows[0])):
src/mwr/droidhg/modules/common/formatter.py:            for i in range(len(r)):
src/mwr/droidhg/modules/common/formatter.py:            for i in range(len(headers)):
src/mwr/droidhg/modules/common/provider.py:                for i in range(len(columns)):
src/mwr/droidhg/modules/common/package_manager.py:            for i in range(packages.size()): 
src/mwr/droidhg/modules/common/package_manager.py:            for i in range(providers.size()):
src/mwr/droidhg/modules/common/package_manager.py:            for i in range(activities.size()):
src/mwr/droidhg/modules/scanner/misc/secretcodes.py:        for i in range(packages.size()):

Connection Error Messages

If you connect to a password protected server with no --password it returns "error:"

If you connect to an SSL encrypted server with no --ssl it returns "Received an empty response from the Agent. This normally means the remote service has crashed."

Both of these errors should rather give suggestions of what could have gone wrong and things to try because sometimes you forget that you have set these security parameters :)

Support for Android 2.1 (Eclair)

Some functionality in the Mercury agent require API level 8 or higher. However, some 3.8% of Android devices are reportedly running Eclair or lower.

Reducing the minimum SDK version to 7 would allow us to support an additional 3.6% of the market share.

crash on empty input to server

From @timb_machine on Twitter -

echo | nc

Results in:

E/AndroidRuntime(32602): FATAL EXCEPTION: Thread-820
E/AndroidRuntime(32602): java.lang.NullPointerException
E/AndroidRuntime(32602): at com.mwr.mercury.XML.parseXML(XML.java:72)
E/AndroidRuntime(32602): at com.mwr.mercury.XML.(XML.java:29)
E/AndroidRuntime(32602): at com.mwr.mercury.SessionThread.handleCommand(SessionThread.java:45)
E/AndroidRuntime(32602): at com.mwr.mercury.SessionThread.run(SessionThread.java:35)
W/ActivityManager( 2010): Force finishing activity com.mwr.mercury/.Main

Dump Android Logs Module

Often when testing logs need to be checked for information disclosure issues. It would be handy to have a mercury module to make this easier.

A module with which you can:

  • Dump all logs (e.g. radio, events etc.) to a file
  • Clear all logs, then dump all logs - so you get the logs for the period you are interested in
  • Output logs to screen
  • Output logs to a file on laptop

Use different readline buffers in Android and interactive Python shells

When entering an Android or interactive Python shell, readline is left enabled. This means that we still provide readline support, but the buffer is shared with the main Mercury application. This sucks, because we start providing Mercury commands in the Linux shell and vice-versa.

We also provide Mercury command-line completion where it is not appropriate.

It would be better if we could distingush between different environments, and swap out the completer with a more appropriate one.

Network error while connecting to mercuryserver

I am getting a network error while using command connect, below is the full details

Environment:

VM player installed in windows 7 with Ubuntu 64 as guest OS
Installed Suntoku Linux distro and from that actually invoking the mercury

Steps followed

  1. Installed the mercury agent.apk in android emulator
  2. Set it o enabled (I can see the message that its listening to port 31415)
  3. tcp forwarded the adb to 31415
  4. Did netstat to verify the local host listening to 31415 as well
    Getting network error when below mentioned combination of command are used to connect

connect 10.0.2.2
connect 127.0.0.1

NOTE: The toll goes blank if i use command connect localhost or connect 127.0.0.1

Please suggest me if i am doing something wrong or suggest further on this.

Regards
Kiran

Bug in app.provider.query

Trying to query a content provider URL containing a trailing single quote will crash the console:

mercury#app> run provider.query content://my.app/path/'
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/EGG-INFO/scripts/mercury-console", line 13, in
Console().run(sys.argv[1::])
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/mwr/droidhg/console/console.py", line 47, in run
self.__invokeCommand(arguments)
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/mwr/droidhg/console/console.py", line 181, in _invokeCommand
getattr(self, "do
" + command)(arguments)
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/mwr/droidhg/console/console.py", line 87, in do_connect
session.cmdloop()
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/mwr/common/cmd_ext.py", line 80, in cmdloop
stop = self.onecmd(line)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cmd.py", line 219, in onecmd
return func(arg)
File "/Library/Python/2.7/site-packages/mercury-2.0.0-py2.7.egg/mwr/droidhg/console/session.py", line 278, in do_run
argv = shlex.split(args, comments=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 279, in split
return list(lex)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 269, in next
token = self.get_token()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 96, in get_token
raw = self.read_token()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 172, in read_token
raise ValueError, "No closing quotation"
ValueError: No closing quotation
huberts-MacBook-Pro:~ hubert$

Error in Printing Path Permissions

In src/mwr/droidhg/modules/app/provider.py, __print_provider(self, provider):

210    if provider.uriPermissionPatterns != None:
211        self.stdout.write("    Uri Permission Patterns:\n")
212        for pattern in provider.uriPermissionPatterns:
213            self.stdout.write("      Path: %s\n" % permission.getPath())
213            self.stdout.write("        Type: %s\n" % Info.PatternMatcherTypes[int(permission.getType())])

I have no idea where @Permission@ is supposed to come from on lines 213, 214.

Pretty Print XML output

Everyone seems to copy XML output (for example from app.package.manifest) to file and open in firefox to make it readable.

Would be awesome if this could be printed in a readable way right from mercury. Perhaps even colourised?

app.provider.update function

When using app.provider.update theres no place to specify what row has to be updates.
Needs something like a --where clause as in version 1.0 . Perhaps give an example?

MWR Code licence

Hi,
We are a little bit worried about the license of Mercury. Since it is not a well known license we are not sure if we will be allowed to keep working on it in the future.
I'm sure the people that work on Mercury would be more confortable if it is licensed under a well known license such as Apache or GPL. And maybe more people would be interested to contribute to the project.

Autocompletion of actions and categories

All of the actions and categories are incorrectly autocompleted to have a prepended ACTION_ and **CATEGORY_**before the actual action or category. I discovered this by attempting to do:

mercury> run app.activity.start --action android.intent.action.ACTION_VIEW --data-uri http://www.google.co.za

The action was autocompleted to android.intent.action.ACTION_VIEW whereas it should be android.intent.action.VIEW.

This is the case for all actions and categories

EDIT: This seems to be the case with extras as well. These are all defined in mercury/src/mwr/droidhg/android.py

startActivityForResult() Module

A fairly common Android pattern is to start an Activity that will return some information as it finish()es.

It would be nice to have a module that performs this interaction with an exported activity, app.activity.startforresult alongside app.activity.start. This would intercept the reply and make the Intent available for inspection.

Installer does not find Python

The Installer only looks for python at the following keys in the registry:

HKLM\Software\Wow6432Node\Python\PythonCore
HKCU\Software\Python\PythonCore

However, for me the installer would have found python at:

HKLM\Software\Python\PythonCore (HKLM instead of HKCU)

Please just add this location, thanks

Some apps can crash scanner.provider.* modules

An installation of Adobe Flash Player causes a crash when unzipped (possibly corrupt installation)

exception in module: ReflectionException: java.util.zip.ZipException: unknown format (EXTSIG=4034b50)
.
.
    for uri in self.findAllContentUris(arguments.package_or_uri):
  File "mercury/src/mwr/droidhg/modules/common/provider.py", line 95, in findAllContentUris
    uris = uris.union(self.__search_package(package))  
  File "mercury/src/mwr/droidhg/modules/common/provider.py", line 177, in __search_package
    for (path, content_uris) in self.findContentUris(package.packageName):
  File "mercury/src/mwr/droidhg/modules/common/provider.py", line 116, in findContentUris
    dex_file = self.extractFromZip("classes.dex", path, self.cacheDir())
  File "/home/user/rai/devel/mercury/src/mwr/droidhg/modules/common/zip_file.py", line 15, in extractFromZip
    return ZipUtil.unzip(target, source, destination)
  File "mercury/src/mwr/droidhg/reflection/types.py", line 331, in _invoker
    result = self._reflector.invoke(self, method_name, *map(lambda arg: ReflectedType.fromNative(arg, reflector=self._reflector), args), **kwargs)
  File "mercury/src/mwr/droidhg/reflection/reflector.py", line 83, in invoke
    raise ReflectionException(response.reflection_response.errormessage)
ReflectionException: java.util.zip.ZipException: unknown format (EXTSIG=4034b50)

This does not break modules such as app.package.info or app.package.manifest.

I fixed this by changing findAllContentUris in provider.py to skip over the package when receiving ReflectionException, this may or may not be the solution we are looking for:

    def findAllContentUris(self, package):
        """
        Search a package (or packages) for content providers, by searching the
        manifest and looking for content:// paths in the binary.
        """

        uris = set([])

        # collect content uris by enumerating all authorities, and uris detected
        # in the source

        if package == None:
            for package in self.packageManager().getPackages(PackageManager.GET_PROVIDERS):
                try:
                    uris = uris.union(self.__search_package(package))
                except ReflectionException:
                    sys.stdout.write("--> SKIPPING package %s, it seems to be corrupt!\n" % package.applicationInfo.packageName)
        else:
                package = self.packageManager().getPackageInfo(package, PackageManager.GET_PROVIDERS)

                try:
                    uris = uris.union(self.__search_package(package))
                except ReflectionException:
                    sys.stdout.write("--> SKIPPING package %s, it seems to be corrupt!\n" % package.applicationInfo.packageName)

A little hard to reproduce, but very annoying when you lose results of the entire scan if it breaks. Screenie (no stop/uninstall action):
device-2013-01-14-124807

Mercury crashes when running in background

Steps to reproduce:

  • Start the Mercury Android agent
  • Press the "back" button on the device so that Mercury is running in the background
  • Use the device, opening apps and various activities etc.

At some stage the app stops working (almost like it has been garbage collected?)

Autocomplete package names

At startup you could scan all installed packages and then autocomplete package names, bit of a pain re-typing them all the time.

Perhaps provide a way to create aliases for package names so I could do:

p = com.mwr.mercury.agent
app.activity.info -a p

would save loads of time...

Bundle extras can only be Strings

using run app.activity.start with --extra the extra can only be of type string. Trying to request extras of type integer/boolean etc. doesn't work

Example:
mercury> run app.activity.start --component com.test.this .part.activity --extra integer value 1
putInt for class android.os.Bundle

Enable server button on home screen

Dev-ing a POC, keeps crashing native code so I need to restart mercury constantly.

Would make things easier if enable button was on the initial screen.

app.package.attacksurface does not gracefully handle lack of package name

Running app.package.attacksurface with no arguments generates an Unknown Exception error:

mercury> run app.package.attacksurface
Unknown Exception

This is user failure, but should be handled with usage or a more descriptive error. Very low priority.

Running on Windows 7 with Python 2.7, Mercury v2.1.

Root exploits

Here is a list of all the exploits that I could find to obtain root on Android. We would like to port as many of these as possible into drozer. Please feel free to correct or contribute to this list, but more importantly to help us port them :) A list of all known root exploit is maintained (not by me) @ https://docs.google.com/spreadsheet/pub?key=0Am5hHW4ATym7dGhFU1A4X2lqbUJtRm1QSWNRc3E0UlE&single=true&gid=0&output=html

Exploit Reference Possible to port to drozer? Comment
Exploid CVE-2009-1185 Yes
Gingerbreak CVE-2011-1823 Yes Requires drozer with READ_LOGS permission
Mempodroid CVE-2012-0056 Yes Needs a SUID binary that writes something deterministic to a file descriptor. But run-as only works as root or shell user, hence on stock Android this will not work from an app
Wunderbar CVE-2009-2692 Yes
ZergRush CVE-2011-3874 Yes Requires drozer with READ_LOGS permission
Zimperlich / Zygote c-skills blog Yes Exploits the zygote setuid() bug
Exynos CVE-2012-6422 Yes Done - testing completed on Galaxy S3 + S2
ZTE sync_agent CVE-2012-2949 Yes Done - still requires testing
cmdclient xdadevelopers / Dan Rosenburg Yes Done - still requires testing
HTC Butterfly diag Yes
Levitator CVE-2011-1352 Unclear Requires access to /dev/pvrsrvkm - what are the permissions on this?
Thinkpad Tablet Dan Rosenburg Unclear Runs thinkpwn binary
Droid 4 (motofail) Dan Rosenburg Unclear Runs motofail binary
XYBoard/Xoom 2 Dan Rosenburg Unclear Runs xyz binary
KillingInTheNameOf CVE-2010-743C No Remap Android property space to writeable which gives root shell from shell user
rageagainstthecage No Exploits the adb setuid() bug
psneuter CVE-2011-1149 No Disables access to the property service and so ADB starts as root (Android assumes ro.secure is off)
Samsung Admire Dan Rosenburg No Requires privileges held by shell user
Droid 3 Dan Rosenburg No Requires privileges held by shell user
LG Spectrum Dan Rosenburg No Requires privileges held by shell user
LG Esteem Dan Rosenburg No Requires privileges held by shell user
Sony Tablet S Dan Rosenburg No Requires privileges held by shell user

Backgrounding of shells

Sometimes you would like to keep a specific shell instance but need to do something else quickly, especially after obtaining a privileged context.

If you could type background when inside a shell, then you should exit the shell prompt but not destroy it. When another shell is opened, a new shell is not made and the backgrounded one is used instead. This is because it is natural that when you obtain a privileged shell using some exploit that you want to keep this shell context. Or if you would like to place a binary that permanently allows you access to root on demand then you do the following workflow:

mercury> run exploit.root.whatever
# background
mercury> run tools.setup.minimalsu
[+] Uploaded minimal-su
[+] Uploaded install-minimal-su.sh
[+] chmod 770 /data/data/com.mwr.droidhg.agent/install-minimal-su.sh
[+] Ready! Execute /data/data/com.mwr.droidhg.agent/install-minimal-su.sh from root context to install minimal-su
mercury> run shell.start
# /data/data/com.mwr.droidhg.agent/install-minimal-su.sh
Done. You can now use `su` from a shell.
# exit
$ su
# exit
$ exit
mercury> 

The above workflow seems smooth in my mind but any suggestions/alterations are very welcome. You will see that the above workflow includes the changes from Issue #67 as well

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.