Installation Guide

The only prerequisite is a Jailbroken device, with the following packages installed:

  • Cydia
  • Apt 0.7 Strict

Install the Needle Agent

  • If the setup process is successful, you’ll find the NeedleAgent app on the home screen

2. Workstation Setup

Get a copy of Needle

git clone https://github.com/mwrlabs/needle.git

Install Dependencies

Kali
# Unix packages
sudo apt-get install python2.7 python2.7-dev sshpass sqlite3 lib32ncurses5-dev

# Python packages
sudo pip install readline paramiko sshtunnel frida mitmproxy biplist

Start NeedleAgent

  • Open the NeedleAgent app on your device.
  • Then, tap on Listen in the top left corner and it will start listening on port 4444 by default. This can be changed using the field in the top right.

Start Needle

Standard usage

To launch Needle, just open a console and type:

$ python needle.py
      __  _ _______ _______ ______         ______
      | \ | |______ |______ | \     |      |______
      | \_| |______ |______ |_____/ |_____ |______
                  Needle v1.0 [mwr.to/needle] 
    [MWR InfoSecurity (@MWRLabs) - Marco Lancini (@LanciniMarco)]

[needle] > help
Commands (type [help|?] <topic>):
---------------------------------
back exit info kill pull reload search shell show use
exec_command help jobs load push resource set shell_local unset

[needle] > show options
Name          Current Value   		Required   Description
------------  -------------   		--------   -----------
AGENT_PORT    4444                  yes       Port on which the Needle Agent is listening
APP                            		no        Bundle ID of the target application (e.g., com.example.app). Leave empty to launch wizard
DEBUG         False            		yes       Enable debugging output
IP            127.0.0.1        		yes       IP address of the testing device (set to localhost to use USB)
OUTPUT_FOLDER /root/.needle/output  yes       Full path of the output folder, where to store the output of the modules
PASSWORD      ******           		yes       SSH Password of the testing device
PORT          2222             		yes       Port of the SSH agent on the testing device (needs to be != 22 to use USB)
PUB_KEY_AUTH  True                  yes       Use public key auth to authenticate to the device. Key must be present in the ssh-agent if a 
SAVE_HISTORY  True                  yes       Persists command history across sessions
USERNAME      root             		yes       SSH Username of the testing device
VERBOSE       True             		yes       Enable verbose output

[needle] >

You will be presented with Needle’s command line interface.

The tool has some global options (listed with the “show options” command, and set with the “set <option> <value>” command):

  • USERNAME, PASSWORD: SSH credentials of the testing device (set by default to “root” and “alpine”, respectively)
  • PUB_KEY_AUTH: Use public key authentication to authenticate to the device. Key must be present in the ssh-agent if a passphrase is used
  • IP, PORT: the session manager embedded in the core of Needle is able to handle SSH connections over Wi-Fi or USB. If SSH-over-USB is the chosen method, the IP option must be set to localhost (“set IP 127.0.0.1”), and PORT set to anything different from 22 (“set PORT 2222”)
  • AGENT_PORT: Port on which the NeedleAgent installed on the device is listening to
  • APP: this is the bundle identifier of the app to analyse (e.g., “com.example.app”). If it is not known beforehand, this field can be left empty. In this case, Needle will launch a wizard which prompts the user to select an app among those already installed on the device
  • OUTPUT_FOLDER: this is the full path of the output folder, where Needle will store the output of the modules
  • SAVE_HISTORY: if set to True, the command history will be persisted across sessions
  • VERBOSE, DEBUG: if set to True, they will enable verbose and debug logging, respectively
Device Dependencies

Note that installation of dependencies has now been moved to its own module (use device/dependency_installer).

Automated, using a resource file

Configuration of the global options can also be automated, using a resource file. First, create a resource file with the commands you want to have automatically executed. For example:

$ cat config.txt
# This is a comment, it won't be executed
set DEBUG False
set VERBOSE False

set IP 192.168.0.10
set PORT 5555
set APP com.example.app
use binary/info/metadata

Then, launch Needle and instruct it to load the resource file:

python needle.py -r config.txt

Command Reference

Command Description
<cmd> Execute a command on the local workstation
<push\pull> <src> <dst> Push/pull files on the device
exec_command <cmd> Execute a single command on the remote device
exit Terminate the needle session
help Display help about a particular command or module
jobs List running background jobs
kill <num> Kill the specified background job
run Executes a module
search <query> Search available modules that matches the query
set Store a value in a variable
shell Start an interactive shell on the device
show [options\source\info\globals] Show details of a particular module, once selected
show modules Show a list of all needle modules that can be executed
unset Remove a named variable
use <module_name> Load the specified module

Modules Usage

The “show modules” command can be used to list all the modules currently available in the framework.

[needle][install] > show modules

Binary
  ------
    binary/info/checksums
    binary/info/compilation_checks
    binary/info/metadata
    binary/info/provisioning_profile
    binary/info/universal_links
    binary/installation/install
    binary/installation/pull_ipa
    binary/reversing/class_dump
    binary/reversing/class_dump_frida_enum-all-methods
    binary/reversing/class_dump_frida_enum-classes
    binary/reversing/class_dump_frida_find-class-enum-methods
    binary/reversing/shared_libraries
    binary/reversing/strings

  Comms
  -----
    comms/certs/delete_ca
    comms/certs/export_ca
    comms/certs/import_ca
...

Otherwise, the “search <query>” command can be used to search available modules that match the query.

[needle] > search binary
[*] Searching for "binary"...

Binary
------
    binary/info/checksums
    binary/info/compilation_checks
    binary/info/metadata
    binary/info/provisioning_profile
    binary/info/universal_links
    binary/installation/install
    binary/installation/pull_ipa
    binary/reversing/class_dump
    binary/reversing/class_dump_frida_enum-all-methods
    binary/reversing/class_dump_frida_enum-classes
    binary/reversing/class_dump_frida_find-class-enum-methods
    binary/reversing/shared_libraries
    binary/reversing/strings

Storage
-------
    storage/data/files_binarycookies 

Once selected, the “info” command can be used to show details of a particular module.

[needle] > use binary/reversing/strings
[needle][strings] > info

Name: Strings
Path: modules/binary/reversing/strings.py
Author: @LanciniMarco (@MWRLabs)

Description:
Find strings in the (decrypted) application binary, then try to extract URIs and ViewControllers

Options:
 Name     Current Value                    Required   Description
 -------  -------------                    --------   -----------
 ANALYZE  True                             no         Analyze recovered strings and try to recover URI
 FILTER                                    no         Filter the output (grep)
 LENGTH   10                               yes        Minimum length for a string to be considered
 OUTPUT   /root/.needle/tmp/strings.txt    no         Full path of the output file 

Or, to only get the available options:

[needle][strings] > show options
 Name     Current Value                    Required   Description
 -------  -------------                    --------   -----------
 ANALYZE  True                             no         Analyze recovered strings and try to recover URI
 FILTER                                    no         Filter the output (grep)
 LENGTH   10                               yes        Minimum length for a string to be considered
 OUTPUT   /root/.needle/tmp/strings.txt    no         Full path of the output file 

Like the global options, even module-specific ones can be edited with the “set” and “unset” commands.

[needle][strings] > set FILTER password
FILTER => password
[needle][strings] > show options
 Name     Current Value                    Required   Description
 -------  -------------                    --------   -----------
 ANALYZE  True                             no         Analyze recovered strings and try to recover URI
 FILTER   password                         no         Filter the output (grep)
 LENGTH   10                               yes        Minimum length for a string to be considered
 OUTPUT   /root/.needle/tmp/strings.txt    no         Full path of the output file 

When all the options are set as preferred, the “run” command can be used to start the module’s execution. If a target app has not been selected yet (with the global option “TARGET_APP” still unset), Needle will first launch a wizard that will help the user in selecting a target.

[needle][strings] > run
[*] Checking connection with device...
[+] Already connected to: 127.0.0.1
[V] Creating temp folder: /var/root/needle/
[*] Target app not selected. Launching wizard...
[V] Refreshing list of installed apps...
[+] Apps found:
    0 - com.highaltitudehacks.dvia
    1 - uk.co.bbc.newsuk
Please select a number: 0
[+] Target app: com.highaltitudehacks.dvia
[*] Decrypting the binary...
[?] The app might be already decrypted. Trying to retrieve the IPA...
[V] Decrypted IPA stored at: /var/root/needle/decrypted.ipa
[*] Unpacking the decrypted IPA...
[V] Analyzing binary...
[+] The following strings has been found: 
     %@: Unable to get password of credential %@
     %s -- Cannot be used in OpenSSL mode. An IV or password is required
     Both password and the key (%d) or HMACKey (%d) are set.
     CFHTTPMessageAddAuthentication(httpMsg, _responseMsg, (__bridge CFStringRef)_credential.user, (__bridge CFStringRef)password, kCFHTTPAuthenticationSchemeBasic, _httpStatus == 407)
     Cannot sign up without a password.
     Congrats! You've found the right username and password!
     Huh, couldn't get password of %@; trying again
     Please enter a password
     T@"NSString",&,N,V_password
     T@"NSString",C,N,V_password
     T@"UITextField",&,N,V_passwordTextField
     ...
[*] Saving output to file: /root/.needle/tmp/strings.txt

Finally, the “show source” command can be used to inspect the actual source code of the selected module.

[needle][strings] > show source
 1|from core.framework.module import BaseModule
 2|
 3|
 4|class Module(BaseModule):
 5|    meta = {
 6|           'name': 'Strings',
 7|           'author': '@LanciniMarco (@MWRLabs)',
 8|           'description': 'Find strings in the (decrypted) application binary, then try to extract URIs and ViewControllers',
 9|           'options': (
10|                      ('length', 10, True, 'Minimum length for a string to be considered'),
11|                      ('filter', '', False, 'Filter the output (grep)'),
12|                      ('output', True, False, 'Full path of the output file'),
13|                      ('analyze', True, False, 'Analyze recovered strings and try to recover URI'),
14|          ),
15|    }
16|
17|    # ====================================================================
18|    # UTILS
19|    # ====================================================================
20|    def __init__(self, params):
21|        BaseModule.__init__(self, params)
...

Feature List

Area What Command Description Demo
[CORE] CLI interface python needle.py
[CORE] Use resource file python -r <path to file> Executes commands from a resource file
[CORE] Session manager SSH, USB over SSH
[CORE] Device auto-configuration set SETUP_DEVICE True On launch, Needle checks if all the tools needed are already on the device, otherwise it will install them
[CORE] Modular approach show modules, use <module_name>, show [options\source\info\globals] Show details of a particular module, once selected
[CORE] Background jobs jobs, kill <num> List running jobs and kill them
[CORE] Search search <query> Search available modules
[CORE] Local command <cmd> Execute a command on the local workstation
[CORE] Drop shell shell Drop a shell on the remote device
[CORE] Do command exec_command <cmd> Execute a single command on the remote device
[CORE] Push/pull <push\pull> <src> <dst> Push/pull files on the device
[BINARY] Checksums use binary/info/checksums Compute different checksums of the application binary: MD5, SHA1, SHA224, SHA256, SHA384, SHA512
[BINARY] Compilation Checks use binary/info/compilation_checks Check for protections (PIE, ARC, stack canaries, binary encryption)
[BINARY] App Metadata use binary/info/metadata Display the app’s metadata (UUID, app name/version, bundle name/id, bundle/data/binary directory, binary path/name, entitlements, url handlers, architectures, platform/sdk/os version), ATS settings, app extensions
[BINARY] Provisioning Profile use binary/info/provisioning_profile Inspect the provisioning profile of the application
[BINARY] Universal Links use binary/info/universal_links Display an applications universal links. Can also determine if apple-app-site-association is signed or not
[BINARY] Install IPA use binary/installation/install Automatically upload and install an IPA on the device
[BINARY] Pull IPA use binary/info/pull_ipa Decrypt and pull the application’s IPA from the device
[BINARY] Class Dump use binary/reversing/class_dump Dump the class interfaces
[BINARY] Enumerate All Methods (Frida) use binary/reversing/class_dump_frida_enum-all-methods Enumerate all methods from all classes in the application
[BINARY] Enumerate Classes (Frida) use binary/reversing/class_dump_frida_enum-classes Enumerate available classes
[BINARY] Enumerate Methods (Frida) use binary/reversing/class_dump_frida_find-class-enum-methods Find the target class specified and enumerate its methods
[BINARY] Shared Libraries use binary/reversing/shared_libraries List the shared libraries used by the application
[BINARY] Strings use binary/reversing/strings Find strings in the (decrypted) application binary and resources, then try to extract URIs and ViewControllers
[COMMS] Delete Installed Certificates use comms/certs/delete_ca Delete one (or more) certificates installed on device
[COMMS] Export Installed Certificates use comms/certs/export_ca Export one (or more) certificates installed on device
[COMMS] Import Installed Certificates use comms/certs/import_ca Import a certificate from a file in PEM format
[COMMS] Install Burp Proxy CA Certificate use comms/certs/install_ca_burp Install the CA Certificate of Burp on the device
[COMMS] Install MitmProxy CA Certificate use comms/certs/install_ca_mitm Install the CA Certificate of MitmProxy on the device
[COMMS] List Installed Certificates use comms/certs/list_ca List the certificates installed on device
[COMMS] View Server Certificate use comms/certs/view_cert View details of TLS certificate presented by a specified site
[COMMS] TLS Pinning Bypass (Frida) comms/proxy/pinning_bypass_frida Disable TLS Certificate Pinning for the target application
[COMMS] Intercepting Proxy use comms/proxy/proxy_regular Intercept the traffic generated by the device
[DEVICE] Agent Client use device/agent_client Send commands to the Needle Agent on the device
[DEVICE] Clean Storage use device/clean_storage Clean device storage from leftovers artefacts of other tools (e.g., Frida)
[DEVICE] Dependency Installer use device/dependency_installer Automatically checks if all the dependencies needed are already present on the device, otherwise it will install them
[DEVICE] Hosts File use device/hosts Show the content of the device’s /etc/hosts file, and offer the chance to edit it
[DEVICE] List Installed Applications use device/list_apps Provide a list of the bundle IDs of all the apps installed on the device
[DYNAMIC] Jailbreak Detection use dynamic/detection/jailbreak_detection Verify that the app cannot be run on a jailbroken device
[DYNAMIC] Frida Jailbreak Detection Bypass use dynamic/detection/script_jailbreak-detection-bypass Hooks native function calls to hide common jailbreak packages and binaries. Also hooks ObjC jailbreak detection classes
[DYNAMIC] URI Handler use dynamic/ipc/open_uri Test IPC attacks by launching URI Handlers
[DYNAMIC] Heap Dump use dynamic/memory/heap_dump Dump memory regions of the app and look for strings
[DYNAMIC] Monitor File changes use dynamic/monitor/files Monitor the app data folder and keep track of modified files
[DYNAMIC] Monitor OS Pasteboard use dynamic/monitor/pasteboard Monitor the OS Pasteboard and dump its content
[DYNAMIC] Syslog Monitor use dynamic/monitor/syslog Monitor the syslog in background and dump its content
[DYNAMIC] Syslog Watch use dynamic/watch/syslog Watch the syslog in realtime
[HOOKING] Cycript shell use hooking/cycript/cycript_shell Spawn a Cycript shell attached to the target app
[HOOKING] Cycript TouchID use hooking/cycript/cycript_touchid Circumvent Touch ID when implemented using LocalAuthentication framework
[HOOKING] Frida launcher use hooking/frida/frida_launcher Run Frida scripts (JS payloads)
[HOOKING] Frida shell use hooking/frida/frida_shell Spawn a Frida shell attached to the target app
[HOOKING] Frida trace use hooking/frida/frida_trace Trace the specified functions using frida-trace
[HOOKING] Anti Hooking Check use hooking/frida/script_anti-hooking-check Display an Alert in the target application. Can be used as simple proof that there are no anti-hooking checks in place
[HOOKING] Dump UI use hooking/frida/script_dump-ui Print the view hierarchy
[HOOKING] Frida Touch Id Bypass use hooking/frida/script_touch-id-bypass Bypasses Touch Id authentication using frida instead. Can be used on devices that do not support cycript
[HOOKING] List Tweaks use hooking/theos/list_tweaks List all the Tweaks installed using Needle
[HOOKING] Theos Tweak use hooking/theos/theos_tweak Automate management of THEOS Tweaks
[MDM] MDM Effective User Settings use mdm/effective_user_settings Extract and compare the configuration of the device against a supplied configuration file, and present a summary of any conflicts found between the two configurations along with recommended changes
[STATIC] Code Checks use static/code_checks Static analysis of the apps’s source code. Aims to find usage of potentially insecure functions. Can be applied to a whole folder or, if SECONDARY_FOLDER is specified, only to the diffs computed among the 2 versions of the same codebase.
[STORAGE] iCloud Content (Frida) use storage/backup/icloud_content_frida List files within the “Documents” directory not excluded from iCloud Backups
[STORAGE] Keyboard Autocomplete Caching use storage/caching/keyboard_autocomplete Dump the content of the keyboard’s autocomplete databases in order to help identify if sensitive information input into the application could be cached
[STORAGE] Screenshot Caching use storage/caching/screenshot Test if a screenshot of the application’s main window is cached when the application’s process is moved to the background
[STORAGE] Application Container use storage/data/container Print and clone the Bundle and Data folder of the target application
[STORAGE] Binary Cookies Files use storage/data/files_binarycookies List Binary Cookies files contained in the app folders, alongside with their Data Protection Class. Plus, offers the chance to pull and inspect them with BinaryCookieReader
[STORAGE] Cache.db Files use storage/data/files_cachedb List Cache.db files contained in the app folders, alongside with their Data Protection Class. Plus, offers the chance to pull and inspect them with SQLite3
[STORAGE] Plist Files use storage/data/files_plist List plist files contained in the app folders, alongside with their Data Protection Class. Plus, offers the chance to inspect them with Plutil
[STORAGE] SQL Files use storage/data/files_sql List SQL files contained in the app folders, alongside with their Data Protection Class. Plus, offers the chance to pull and inspect them with SQLite3
[STORAGE] Dump Keychain use storage/data/keychain_dump Dump the keychain
[STORAGE] Dump Keychain (Frida) use storage/data/keychain_dump_frida Retrieve all the keychain items belonging to the target application

 

 

 

 

Needle IOS Pentesting

Post navigation


Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest