Пример #1
0
def get_device(client: AdbClient):
    """
    Gets the Android Device section from the user
    :param client: adb client
    :return: adb device object
    """

    devices = client.devices()
    done = False
    device = None

    # get device selection from the user
    while not done:
        if len(devices) == 0:
            print("No Android Devices Found!")
            exit(1)

        print("Select a device:")
        print("Choice\tSerial #")
        ndx = 0
        for device in devices:
            print("%d\t\t%s" % (ndx, get_serial_number(device)))

        choice = input("\nEnter Choice: ")

        try:
            device = devices[int(choice)]
            done = True
        except Exception as e:
            print(e)
            print("Invalid choice, please try again")

    return device
Пример #2
0
def main():
    try:
        from adb.client import Client as AdbClient
        import sys
        if len(sys.argv) < 3:
            print(
                "Error: Syntax: Python logger.py filename [cache clear (Y/N)]")
        apps = [
            "com.android.chrome", "com.yandex.browser", "com.microsoft.emmx",
            "org.mozilla.firefox"
        ]

        client = AdbClient(host="127.0.0.1", port=5037)
        devices = client.devices()
        isCacheClear = sys.argv[2]
        for device in devices:
            if isCacheClear == 'Y':
                for app in apps:
                    clearAppFromCache(app, device)
            clearLog(device)
            saving_log = save_log(sys.argv[1])
            time = 30
            for i in apps:
                open_app(i, time)
            saving_log.wait()
    except Exception as e:
        print("Error in  main!")
Пример #3
0
 def __init__(self):
     client = AdbClient(host="127.0.0.1", port=5037)
     devices = client.devices()
     if len(devices) <= 0:
         raise ValueError("No device connected")
     self.device = client.device(str(devices[0].get_serial_no()))
     self.settings = Settings("config.cfg")
     self.adbscreen = ADBScreen(self.device)
Пример #4
0
 def adb_connect(self):
     try:
         client = AdbClient(host="127.0.0.1", port=5037)
         self.adb_device = client.devices()[0]
     except Exception as e:
         self.adb_device = ""
         self.err = str(e)
     return self.adb_device
Пример #5
0
    def list_devices(host="127.0.0.1", port=5037):
        client = AdbClient(host=host, port=port)

        try:
            client.version()
        except RuntimeError:
            # Can't connect to the adb server, try to start the adb server by command line.
            Adb._start_adb_server()

        return client.devices()
Пример #6
0
def get_devices():
    adb = subprocess.Popen(
        ['adb', '-P', str(config['adb_port']), 'start-server'],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL)
    client = AdbClient(host="127.0.0.1", port=config['adb_port'])
    print(client)
    devs = []
    for d in client.devices():
        devs.append(AndroidDevice(d))
    return devs
Пример #7
0
    def __init__(self):
        print("program was starting")
        # Default is "127.0.0.1" and 5037
        try:
            client = AdbClient(host="127.0.0.1", port=5037)
            devices = client.devices()
            devices_packages = devices[0].shell("pm list packages")
            get_all_files_from_device(devices[0], devices_packages)

        except Exception as e:
            print(e)
Пример #8
0
class getInstalledApps:

    def __init__(self):
        self.client = AdbClient(host="127.0.0.1", port=5037)
        self.adb_device = self.client.devices()[0]
        self.applist = []
        self.apppath = []
        self.asset = Assets()
        
    def get_Applist(self):
        self.ltemp = self.adb_device.shell("pm list packages ")
        # if search_keword is none, print all lists out.
        temp = self.ltemp.split("\n")
        del temp[len(temp)-1]
        
        self.applist = [x.split(":")[1] for x in temp]
        #print (self.applist)
        return self.applist

    def get_Path(self, pkgid):
        path_temp = self.adb_device.shell("pm path " + pkgid)
        path = path_temp.split(":")[1].strip()
        return path

    def get_app(self, pkgid):
        path = self.get_Path(pkgid)
        tmp_path = os.path.join("./tmp/") + pkgid + '.apk'
        data = self.adb_device.pull(path, tmp_path)
        if self.asset.exist(pkgid) == False:
            self.asset.add(pkgid, "", 0, "")

    def get_SDKApps(self, pkgid):
        apkpath = str(self.get_Path(pkgid))
        apkfinal_path = str("tmp/" + pkgid + ".apk")
            
        self.adb_device.pull(apkpath.strip("\n"), apkfinal_path)

        cprint('[+] Checking AWS_SDK', 'blue')

        s = os.popen('/usr/bin/grep -i "aws-android-sdk" {0}'.format(apkfinal_path)).read()
        if 'matches' in s:
            cprint ("[!] This Application use AWS_SDK", 'blue')
            pass
        else:
            cprint ("[!] NO AWS_SDK FOUND", 'blue')
            os.remove(apkfinal_path)
    def is_AWSSDK(self, pkgid):
        apkfinal_path = os.path.join("./tmp/") + pkgid + '.apk'
        if re.search(b'(?i)aws-android-sdk', open(apkfinal_path,"rb").read()):
            self.asset.exist_sdk(pkgid, True)
            return True
        else:
            self.asset.exist_sdk(pkgid, False)
            return False
Пример #9
0
 def __init__(self, init=False):
     client = AdbClient(host="127.0.0.1", port=5037)
     devices = client.devices()
     if len(devices) <= 0:
         raise ValueError("No device connected")
     self.device = client.device(str(devices[0].get_serial_no()))
     self.settings = Settings("config.cfg", init=init)
     self.adbscreen = ADBScreen(self.device)
     self.ENDC = '\033[0m'
     self.WARNING = '\033[93m'
     self.BLUE = '\033[94m'
     self.RED = '\033[91m'
     pytesseract.pytesseract.tesseract_cmd = self.settings.tesseract_dir
Пример #10
0
class PurpleScouter(object):
    """
    Handles the main user loop.
    """

    def __init__(self, adb_ip, adb_port, config):
        """
        Starts the connection with the adb server.
        """
        try:
            self.__adb = AdbClient(host=adb_ip, port=adb_port)
            self.__adb.devices()
        except Exception:
            with colored(colors.RED):
                print "adb server isn't running, opening."
                subprocess.Popen([config.get("adb", "adb_location"), "start-server"])

        self.__config = config

    def start(self):
        """
        Starts the infinite loop.
        """
        print "Welcome to:"
        with colored(colors.PURPLE):
            print "Purple Scouter!"
        time.sleep(1)

        while True:
            devices = self.__adb.devices()
            if devices:
                with colored(colors.BLUE):
                    print "\nFound {len} connected devices!".format(len=len(devices))

                for device in devices:
                    FilePuller(device, self.__config).move_all_scouting_files_from_phone()

            animate_loading()
Пример #11
0
class AdbUtils:
    def __init__(self, ip="127.0.0.1", port=5037):
        subprocess.run(["adb", "devices"])
        self.client = AdbClient(host=ip, port=port)
        self.devices = []

    def get_client_version(self):
        return self.client.version()

    def list_all_devices(self):
        for device in self.client.devices():
            self.devices.append(device.serial)
        return self.devices

    # Exemple "example.package"
    def is_installed_apk(self, device, apk_package):
        return device.is_installed(apk_package)

    def install_apk(self, device, apk_path):
        device.install(apk_path)

    # Exemple "example.package"
    def uninstall_apk(self, device, apk_package):
        device.install(apk_package)
        return self.is_installed_apk(device, apk_package)

    def get_device_name(self, device):
        model = device.shell("getprop ro.product.model")
        manufacturer = device.shell("getprop ro.product.manufacturer")
        full_name = manufacturer + " " + model
        return full_name.replace("\n", "").replace("\r", "")

    def _dump_logcat(connection):
        while True:
            data = connection.read(1024)
            if not data:
                break
            print(data.decode('utf-8'))
        connection.close()

    def get_device_logcat(self, device):
        return device.shell("logcat", handler=self._dump_logcat)

    def get_screen_shot(self, device):
        result = device.screencap()
        with open(
                datetime.datetime.now().replace(" ", "").replace(
                    "-", "").replace(":", "").replace(".", "") + ".png",
                "wb") as fp:
            fp.write(result)
Пример #12
0
    def __init__(self, ini_name,init = False):
        #Loading config.cfg
        cparser = configparser.ConfigParser()
        dirname = os.path.dirname(__file__)
        ini_file = Path(os.path.join(dirname, "..\conf\\"+ini_name))

        if ini_file.is_file():
            cparser.read(ini_file)
        else:
            raise ValueError("Config file name not valid")
        self.language = "DE"
        #loads the config information
        try:
            self.language = cparser.get("custom", "language")
            self.speed_multi = cparser.getfloat("custom", "speed_multi")
            self.selected_raid = cparser.get("custom", "selected_raid")
            self.round_robin_raids = eval(cparser.get("custom", "round_robin_raids"), {}, {})
            self.round_robin = cparser.getboolean("custom", "round_robin")
            self.tesseract_dir = cparser.get("custom", "tesseract_directory")
            self.rounds = cparser.getint("custom", "rounds")
            self.rounds_per_raid = cparser.getint("custom", "rounds_per_raid")
            self.debug = cparser.getboolean("custom", "debug")
            self.autodetect_buttons = cparser.get("screen", "autodeteckt_buttons")
            self.taps_resultscreen = cparser.getint("custom", "taps_resultscreen")
            self.auto_remove_pkmn = cparser.getboolean("custom", "auto_remove_pkmn")
        except Exception as e:
            raise ValueError("Couldn´t read config file")

        try:
            with open(os.path.join(dirname, '../conf/languages.json')) as json_file:
                data = json.load(json_file)
                self.language_pack = data[self.language]
        except Exception:
            raise ValueError("Language not found. Check your config file and update the languages.json")

        client = AdbClient(host="127.0.0.1", port=5037)
        devices = client.devices()
        if len(devices) <= 0:
            raise ValueError("No device connected")

        adbscreen = ADBScreen(client.device(str(devices[0].get_serial_no())))
        if not init:
            try:
                with open(os.path.join(dirname, '../conf/screens/'+str(adbscreen.get_model_name()+".json"))) as json_file:
                    data = json.load(json_file)
                    self.screen = data
            except Exception:
                raise ValueError("Screenconfig not found. Start the python script with the --init argument to create a config.")

            self.check_screen_values()
Пример #13
0
def get_devices():
    for attempt in range(2):
        try:
            client = AdbClient(host="127.0.0.1", port=5037)
            client.version()  # a random call to check if adb server is up
        except Exception as err:
            print(str(err))
            print("⚡ Starting ADB server...")
            subprocess.run(["adb", "start-server"])

    devices = client.devices()
    if len(devices) == 0:
        print("⚠️  no devices connected!")
    return devices
Пример #14
0
class Clicking(PyKeyboardEvent):
    def __init__(self, interval=0):
        super(Clicking, self).__init__()
        self.interval = interval
        self.client = AdbClient(host="127.0.0.1", port=5037)
        self.device = self.client.devices()[0]

        self.x, self.y = None, None

    def get_position(self):
        def dump(connection):
            while self.x is None or self.y is None:
                data = connection.read(1024)
                if not data:
                    break
                for line in data.decode('utf-8').strip().split('\n'):
                    try:
                        line = line.split(' ')
                        if line[0] == '/dev/input/event1:':
                            if line[2] == '0035':
                                self.x = int(line[3], 16)
                            elif line[2] == '0036':
                                self.y = int(line[3], 16)
                    except Exception:
                        pass
            connection.close()

        print('Please tap your phone screen.')
        self.device.shell('getevent', handler=dump)
        print(self.x, self.y)

    def click(self):
        while CLICK_FLAG:
            self.device.shell('input tap {} {}'.format(self.x, self.y))
            sleep(self.interval)

    def tap(self, keycode, character, press):
        global CLICK_FLAG
        if keycode == 74:
            if press:
                print('Start clicking!')
                CLICK_FLAG = True
                Thread(target=self.click).start()
        elif keycode == 75:
            if press:
                print('Stop clicking!')
                CLICK_FLAG = False
Пример #15
0
 def get(self):
     from adb.client import Client as AdbClient
     client = AdbClient()
     devices = client.devices()
     ret = {"success": True, "devices": []}
     if not devices:
         self.write({"success": False})
         return
     for device in devices:
         data = {}
         data["serial"] = device.serial
         data["status"] = device.get_state()
         if device.shell("getprop ro.arch").strip() == "x86":
             data["emulator"] = True
         else:
             data["emulator"] = False
         ret["devices"].append(data)
     self.write(ret)
Пример #16
0
    def get(self):
        from uiautomator2.__main__ import _init_with_serial
        from uiautomator2.version import __apk_version__, __atx_agent_version__
        print("start...")
        from adb.client import Client as AdbClient
        client = AdbClient()
        devices = client.devices()
        for d in devices:
            print(d.serial)
        if not devices:
            self.write({
                "success": False,
                "serial": "",
                "deviceId": "",
            })
            return
        for d in devices:
            serial = d.get_serial_no()
            if d.get_state() != 'device':
                print("Skip invalid device: %s %s", serial, d.get_state())
                continue
            print("Init device %s", serial)
            # todo:初始化代码优化
            try:
                device = _AndroidDevice(serial)

            except BaseException:
                _init_with_serial(serial=serial,
                                  apk_version=__apk_version__,
                                  agent_version=__atx_agent_version__,
                                  server=None,
                                  reinstall=False)
                device = _AndroidDevice(serial)
            # serial = device._d.wlan_ip + ":7912"
            id = str(uuid.uuid4())
            cached_devices[id] = device
            socket_url = device._d._host + ":" + str(device._d._port)
            self.write({
                "success": True,
                "serial": serial,
                "deviceId": id,
                "socket_url": socket_url
            })
            return
from adb.client import Client as AdbClient  # Adb client that allows adb in python
import sys  # Allows access to system.
import os  # Operating system access
import datetime  # Gets the date and the time
import time  # Imports the system time
import csv

os.system(
    'adb start-server'
)  # Automatically starts the adb server if it is not already running.

client = AdbClient(
    host="127.0.0.1",
    port=5037)  # Opens the adb gateway. Default is "127.0.0.1" and 5037
devices = client.devices(
)  # This calls adb devices to see all the devices connected
watch_count = 2  # Number of watch given to each individual
origin = None  # Initializes the origin variable
destination = None  # Initializes the destination variable
downloadtime = None  # Initializes the download time variable
previousrun = None  # Initializes the previous run variable
patient_1_time = "Never"  # Initializes the patient-1 variable
patient_2_time = "Never"  # Initializes the patient-2 variable
caregiver_1_time = "Never"  # Initializes the caregiver-1 variable
caregiver_2_time = "Never"  # Initializes the caregiver-2 variable

# ----------------------------------------------------------------------SET-UP----------------------------------------------------------------------- #

Deployment_Identification = "P2D3"  # Name of the deployment

Watch_Main_Directory = "BESI-C"  # Name of the folder directory where all the data is stored on the watch
Пример #18
0
class Adb(object):
    def __init__(self, serial=None, host="127.0.0.1", port=5037):
        self._serial = serial
        self._client = AdbClient(host=host, port=port)

        try:
            self._client.version()
        except RuntimeError:
            # Can't connect to the adb server, try to start the adb server by command line.
            self._start_adb_server()

        if self._serial:
            self._device = self._client.device(serial)
        else:
            # The serial can be None only when there is only one device/emulator.
            devices = self._client.devices()
            if len(devices) == 0:
                raise RuntimeError("Can't find any android device/emulator")
            elif len(devices) > 1:
                raise RuntimeError(
                    "more than one device/emulator, please specify the serial number"
                )
            else:
                device = devices[0]
                self._serial = device.get_serial_no()
                self._device = device

    @staticmethod
    def list_devices(host="127.0.0.1", port=5037):
        client = AdbClient(host=host, port=port)

        try:
            client.version()
        except RuntimeError:
            # Can't connect to the adb server, try to start the adb server by command line.
            Adb._start_adb_server()

        return client.devices()

    @staticmethod
    def _start_adb_server():
        adb_path = whichcraft.which("adb")
        if adb_path is None:
            raise EnvironmentError(
                "Can't find the adb, please install adb on your PC")

        cmd = [adb_path, "start-server"]
        cmdline = subprocess.list2cmdline(cmd)
        try:
            return subprocess.check_output(cmdline,
                                           stderr=subprocess.STDOUT,
                                           shell=True).decode('utf-8')
        except subprocess.CalledProcessError as e:
            raise EnvironmentError("subprocess", cmdline,
                                   e.output.decode('utf-8', errors='ignore'))

    def devices(self, states=['device', 'offline']):
        """
        Returns:
            [($serial1, "device"), ($serial2, "offline")]
        """
        # TODO: not really checking anything
        return [(d, "device") for d in self.list_devices()]
        output = subprocess.check_output([self.adb_path(), 'devices'])
        pattern = re.compile(r'(?P<serial>[^\s]+)\t(?P<status>device|offline)')
        matches = pattern.findall(output.decode())
        return [(m[0], m[1]) for m in matches]

    @property
    def serial(self):
        return self._serial

    def forward(self, local, remote, rebind=True):
        if isinstance(local, int):
            local = 'tcp:%d' % local
        if isinstance(remote, int):
            remote = 'tcp:%d' % remote

        return self._device.forward(local, remote, norebind=not rebind)

    def forward_list(self):
        """
        Only return tcp:<int> format forwards
        Returns:
            {
                "{RemotePort}": "{LocalPort}"
            }
        """
        forward_list = self._device.list_forward()

        ret = {}

        for local, remote in forward_list.items():
            ltype, lport = local.split(":")
            rtype, rport = remote.split(":")

            if ltype == "tcp" and rtype == "tcp":
                ret[int(rport)] = int(lport)

        return ret

    def forward_port(self, remote_port):
        forwards = self.forward_list()
        lport = forwards.get(remote_port)
        if lport:
            return lport
        free_port = find_free_port()
        self.forward(free_port, remote_port)
        return free_port

    def shell(self, *args, **kwargs):
        return self._device.shell(" ".join(args))

    def getprop(self, prop):
        return self.shell('getprop', prop).strip()

    def push(self, src, dst, mode=0o644):
        self._device.push(src, dst, mode=mode)

    def install(self, apk_path):
        sdk = self.getprop('ro.build.version.sdk')
        if int(sdk) <= 23:
            self._device.install(apk_path, reinstall=True, downgrade=True)
            return
        try:
            # some device is missing -g
            self._device.install(apk_path,
                                 reinstall=True,
                                 downgrade=True,
                                 grand_all_permissions=True)
        except InstallError:
            self._device.install(apk_path, reinstall=True, downgrade=True)

    def uninstall(self, pkg_name):
        return self._device.uninstall(pkg_name)

    def package_info(self, pkg_name):
        output = self.shell('dumpsys', 'package', pkg_name)
        m = re.compile(r'versionName=(?P<name>[\d.]+)').search(output)
        version_name = m.group('name') if m else None
        m = re.search(r'PackageSignatures\{(.*?)\}', output)
        signature = m.group(1) if m else None
        if version_name is None and signature is None:
            return None
        return dict(version_name=version_name, signature=signature)
Пример #19
0
import io
import time

from PIL import Image
from screenshot.screencapture import screenshot_window

from adb.client import Client as AdbClient

file = '/tmp/player_shoot.png'

# not so good
def screenshoot():
    screenshot_window("player", filename='/tmp/player_shoot.png')
    player = Image.open('/tmp/player_shoot.png')
    player = player.crop((84, 112, 1044, 1713))
    player.thumbnail((480,800), Image.ANTIALIAS)
    return player

def screencap(device):
    return Image.open(io.BytesIO(device.screencap()))

if __name__ == '__main__':
    client = AdbClient(host="127.0.0.1", port=5037)
    devices = client.devices()
    print(devices)
    device = devices[0]
    while True:
        s = time.time()
        screencap(device)
        print(time.time() - s)
Пример #20
0
def devices():
    client = AdbClient(host='127.0.0.1',
                       port=5037)  # TODO(ssx): should get HOST from env
    return client.devices()
Пример #21
0
def main():
    phone = None
    source_device = None
    sdk = AndroidSDK()
    parser = argparse.ArgumentParser(prog="WhatsDump")

    parser.add_argument(
        "--install-sdk",
        action="store_true",
        help="Download & extract latest Android SDK emulator packages")
    parser.add_argument("--msgstore",
                        help="Location of msgstore database to decrypt")
    parser.add_argument(
        "--wa-phone",
        help=
        "WhatsApp phone number associated with msgstore database from which "
        "you will receive verification SMS (with prefix, ex. +393387182291)")
    parser.add_argument("--wa-verify",
                        choices=["sms", "call"],
                        help="Phone verification method to use")
    parser.add_argument("--verbose",
                        action="store_true",
                        help="Show verbose (debug) output")
    parser.add_argument("--show-emulator",
                        action="store_true",
                        help="Show emulator screen (by default headless)")
    parser.add_argument(
        "--no-accel",
        action="store_true",
        help="Disable hardware acceleration (very slow emulator!)")

    args = parser.parse_args()

    print("""
 _    _ _           _      ______
| |  | | |         | |     |  _  \
| |  | | |__   __ _| |_ ___| | | |_   _ _ __ ___  _ __
| |/\| | '_ \ / _` | __/ __| | | | | | | '_ ` _ \| '_ \
\  /\  / | | | (_| | |_\__ \ |/ /| |_| | | | | | | |_) |
 \/  \/|_| |_|\__,_|\__|___/___/  \__,_|_| |_| |_| .__/
                                                 | |
                                                 |_|
                        v0.2 beta
    """)

    # Setup logging
    logging.basicConfig(
        format=
        "%(asctime)s - %(levelname)s - %(name)s - [%(funcName)s]: %(message)s",
        datefmt="%d/%m/%Y %H:%M:%S",
        stream=sys.stdout)
    logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)

    # TODO: CHECK IF JAVA IS INSTALLED

    # SDK Checks
    is_avd_installed = sdk.is_avd_installed()

    if args.install_sdk:
        if is_avd_installed:
            logger.error(
                "WhatsDump AVD already installed! Remove android-sdk/ directory to reinstall Android SDK"
            )
            sys.exit(1)

        # download&install
        if not sdk.install():
            logger.error("Failed to install Android SDK")
            sys.exit(1)

        logger.info("\nAndroid AVD successfully installed")
        sys.exit(0)
    else:
        if not is_avd_installed:
            logger.error(
                "Cannot find WhatsDump AVD; install Android SDK and emulator packages with --install-sdk"
            )
            sys.exit(1)

    # Connect / Start ADB server
    adb_client = AdbClient()

    try:
        logger.info("Connected to ADB (version %d) @ 127.0.0.1:5037" %
                    adb_client.version())
    except:
        logger.info("Attempting to start ADB server...")

        if sdk.start_adb():
            logger.info("ADB server started successfully")
            adb_client = AdbClient()

            logger.info("Connected to ADB (version %d) @ 127.0.0.1:5037" %
                        adb_client.version())
        else:
            logger.error("Could not connect/start ADB server")
            sys.exit(1)

    # Require msgstore or connected device
    if args.msgstore:
        # Check if file exists
        if not os.path.isfile(args.msgstore):
            logger.error(
                "Msgstore location is not valid (file does not exist)")
            sys.exit(1)
    else:
        logger.info(
            "Msgstore location not provided, attempting to find connected devices with ADB...\n"
        )

        devices = adb_client.devices()
        i = 0

        # If no devices and no msgstore, quit
        if len(devices) == 0:
            logger.error("Cannot find any connected devices")
            sys.exit(1)

        # Show all devices
        for device in devices:
            print("\t[%d] %s (%s)" %
                  (i, device.serial,
                   device.shell("getprop ro.product.name").rstrip()))
            i += 1

        print("\n")
        while source_device is None:
            dev_index = int(
                input(
                    "\n>> Which device number you want to extract msgstore from?: "
                ))

            if dev_index < 0 or dev_index + 1 > len(devices):
                continue

            source_device = devices[dev_index]
            print("\n")

    # Validate required phone
    if not args.wa_phone:
        logger.error(
            "Please provide the phone number associated with msgstore")
        sys.exit(1)
    else:
        # Add "+" if not given
        if args.wa_phone[0] != "+":
            args.wa_phone = "+" + args.wa_phone

        try:
            phone = phonenumbers.parse(args.wa_phone)
        except NumberParseException:
            pass

        if not phone:
            logger.error("Provided phone number is NOT valid")
            sys.exit(1)

    if not args.wa_verify:
        logger.error("Please provide a WhatsApp verification method")
        sys.exit(1)

    # recap
    if source_device:
        logger.info("Extract WhatsApp database from device >> %s",
                    source_device.serial)
    else:
        logger.info("Using msgstore database from path: %s", args.msgstore)

    logger.info("Using WhatsApp phone number: +%d %d", phone.country_code,
                phone.national_number)
    logger.info("Using WhatsApp verification method: %s",
                args.wa_verify.upper())

    # yn = input("\n>> Continue? (y/n): ")

    # if yn != 'y':
    #     sys.exit(0)

    # create phone directory tree where to store results
    dst_path = os.path.join(os.path.abspath("output"),
                            str(phone.national_number))
    if not os.path.exists(dst_path):
        try:
            os.makedirs(dst_path)
        except OSError:
            logging.error("Cannot create output directory tree")
            sys.exit(1)

    log_formatter = logging.Formatter(
        "%(asctime)s - %(levelname)s - %(name)s - [%(funcName)s]: %(message)s",
        datefmt="%d/%m/%Y %H:%M:%S")
    file_handler = logging.FileHandler(os.path.join(dst_path, "log.txt"))
    file_handler.setFormatter(log_formatter)
    logger.addHandler(file_handler)

    # Extract msgstore.db from source device, if any
    msgstore_path = args.msgstore

    if msgstore_path:
        logger.info("Provided msgstore.db SHA-256 hash: %s",
                    sha256(args.msgstore))

    if source_device:
        logger.info(
            "Extracting msgstore.db.crypt from phone to output/%ld/ ..." %
            phone.national_number)

        wa = WhatsApp(source_device)
        msgstore_path = wa.extract_msgstore(dst_path)

        if not msgstore_path:
            logger.error(
                "Could not find/extract msgstore database from device (is WhatsApp installed?)"
            )
            sys.exit(1)

        logger.info("Extracted msgstore.db SHA-256 hash: %s",
                    sha256(msgstore_path))

    # Start emulator and connect to it
    logger.info("Starting emulator...")

    if args.no_accel:
        logger.warn(
            "Hardware acceleration disabled! Device might be very slow")

    emulator_device = sdk.start_emulator(adb_client, args.show_emulator,
                                         args.no_accel)

    if not emulator_device:
        logger.error("Could not start emulator!")
        sys.exit(1)

    if args.show_emulator:
        logger.info("Do not interact with the emulator!")

    logger.info(
        "Trying to register phone on emulator... (may take few minutes)")

    # Attempt to register phone using provided msgstore
    wa_emu = WhatsApp(emulator_device)
    sdk.adb_root()  # Allowing adb as root

    time.sleep(10)

    try:
        wa_emu.register_phone(msgstore_path, phone.country_code,
                              phone.national_number)

        # Verify by call or SMS
        if args.wa_verify == "sms":
            logger.info("You should receive a SMS by WhatsApp soon")
            wa_emu._verify_by_sms(wa_code_callback)
        else:
            logger.info("You should receive a call by WhatsApp soon")
            wa_emu._verify_by_call(wa_code_callback)

        wa_emu.complete_registration(phone.country_code, phone.national_number)

    except WaException as e:
        logger.info("Exception in verification: %s", e.reason)
        code.interact(local=locals())
        sys.exit(1)

    logger.info("Phone registered successfully!")
    logger.info("Extracting key...")

    # Extract private key
    if not wa_emu.extract_priv_key(dst_path):
        logger.error("Could not extract private key!")
        sys.exit(1)

    logger.info("Private key extracted in %s", os.path.join(dst_path, "key"))
Пример #22
0
class ADBConnect(object):
    def __init__(self, args):
        self._args = args
        self._useadb = args.use_adb
        self._client = None
        if self._useadb:
            try:
                from adb.client import Client as AdbClient
            except ImportError:
                pass
            self.check_adblib = 'adb.client' in sys.modules
            if not self.check_adblib:
                logger.warning(
                    "Could not find pure-python-adb library - no support for ADB."
                    "If you have no idea what ADB is or not planning to use it - IGNORE :)"
                )
                self._useadb = False
            else:
                self._client = AdbClient(
                    host=self._args.adb_server_ip, port=self._args.adb_server_port)

    def check_adb_status(self, adb):
        if not self._useadb:
            return None
        try:
            if self._client.device(adb) is not None:
                self._client.device(adb).shell('echo checkadb')
                return True
        except RuntimeError as e:
            logger.exception(
                'MADmin: Exception occurred while checking adb status ({}).', str(adb))
        return None

    def return_adb_devices(self):
        if not self._useadb:
            return []
        try:
            return self._client.devices()
        except Exception as e:
            logger.exception(
                'MADmin: Exception occurred while getting adb clients: {}.', e)
        return []

    def send_shell_command(self, adb, origin, command):
        try:
            device = self._client.device(adb)
            if device is not None:
                logger.info(
                    'MADmin: Using ADB shell command ({})', str(origin))
                device.shell(command)
                return True
        except Exception as e:
            logger.exception(
                'MADmin: Exception occurred while sending shell command ({}): {}.', str(origin), e)
        return False

    def make_screenshot(self, adb, origin, extenstion):
        try:
            device = self._client.device(adb)
            if device is not None:
                logger.info('MADmin: Using ADB ({})', str(origin))
                result = device.screencap()
                # TODO: adjust with devicesettings
                with open(os.path.join(self._args.temp_path, 'screenshot_%s.png' % str(origin)), "wb") as fp:
                    fp.write(result)
                if extenstion == "jpg":
                    pngtojpg(os.path.join(self._args.temp_path, 'screenshot_%s.png' % str(origin)))
                return True
        except Exception as e:
            logger.exception(
                'MADmin: Exception occurred while making screenshot ({}): {}.', str(origin), e)
        return False

    def make_screenclick(self, adb, origin, x, y):
        try:
            device = self._client.device(adb)
            if device is not None:
                device.shell("input tap " + str(x) + " " + str(y))
                logger.info('MADMin ADB Click x:{} y:{} ({})',
                            str(x), str(y), str(origin))
                time.sleep(1)
                return True
        except Exception as e:
            logger.exception(
                'MADmin: Exception occurred while making screenclick ({}): {}.', str(origin), e)
        return False

    def make_screenswipe(self, adb, origin, x, y, xe, ye):
        try:
            device = self._client.device(adb)
            if device is not None:
                device.shell("input swipe " + str(x) + " " +
                             str(y) + " " + str(xe) + " " + str(ye) + " 100")
                logger.info('MADMin ADB Swipe x:{} y:{} xe:{} ye:{}({})', str(
                    x), str(y), str(xe), str(ye), str(origin))
                time.sleep(1)
                return True
        except Exception as e:
            logger.exception(
                'MADmin: Exception occurred while making screenswipe ({}): {}.', str(origin), e)
        return False
Пример #23
0
def connectAndGetDevices():
    # Connect to devices Default is "127.0.0.1" and 5037
    client = AdbClient(host="127.0.0.1", port=5037)
    devices = client.devices()
    return devices
Пример #24
0
    def __init__(self):
        c = Client()

        self.device = c.devices()[0]

        self.pkgs = []
Пример #25
0
def main():
    phone = None
    source_device = None
    sdk = AndroidSDK()
    parser = argparse.ArgumentParser(prog='WhatsDump')

    parser.add_argument(
        '--install-sdk',
        action='store_true',
        help='Download & extract latest Android SDK emulator packages')
    parser.add_argument('--msgstore',
                        help='Location of msgstore database to decrypt')
    parser.add_argument(
        '--wa-phone',
        help=
        'WhatsApp phone number associated with msgstore database from which '
        'you will receive verification SMS (with prefix, ex. +393387182291)')
    parser.add_argument('--wa-verify',
                        choices=['sms', 'call'],
                        help='Phone verification method to use')
    parser.add_argument('--verbose',
                        action='store_true',
                        help='Show verbose (debug) output')
    parser.add_argument('--show-emulator',
                        action='store_true',
                        help='Show emulator screen (by default headless)')
    parser.add_argument(
        '--no-accel',
        action='store_true',
        help='Disable hardware acceleration (very slow emulator!)')

    args = parser.parse_args()

    print('''
 _    _ _           _      ______                       
| |  | | |         | |     |  _  \                      
| |  | | |__   __ _| |_ ___| | | |_   _ _ __ ___  _ __  
| |/\| | '_ \ / _` | __/ __| | | | | | | '_ ` _ \| '_ \ 
\  /\  / | | | (_| | |_\__ \ |/ /| |_| | | | | | | |_) |
 \/  \/|_| |_|\__,_|\__|___/___/  \__,_|_| |_| |_| .__/ 
                                                 | |    
                                                 |_|    
                        v0.1 beta
    ''')

    # Setup logging
    logging.basicConfig(format='[%(levelname)s] %(message)s',
                        stream=sys.stdout)
    logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)

    # TODO: CHECK IF JAVA IS INSTALLED

    # SDK Checks
    is_avd_installed = sdk.is_avd_installed()

    if args.install_sdk:
        if is_avd_installed:
            logger.error(
                "WhatsDump AVD already installed! Remove android-sdk/ directory to reinstall Android SDK"
            )
            exit(1)

        # download&install
        if not sdk.install():
            logger.error('Failed to install Android SDK')
            exit(1)

        logger.info('\nAndroid AVD successfully installed')
        exit(0)
    else:
        if not is_avd_installed:
            logger.error(
                "Cannot find WhatsDump AVD; install Android SDK and emulator packages with --install-sdk"
            )
            exit(1)

    # Connect / Start ADB server
    adb_client = AdbClient()

    try:
        logger.info("Connected to ADB (version %d) @ 127.0.0.1:5037" %
                    adb_client.version())
    except:
        logger.info("Attempting to start ADB server...")

        if sdk.start_adb():
            logger.info("ADB server started successfully")
            adb_client = AdbClient()

            logger.info("Connected to ADB (version %d) @ 127.0.0.1:5037" %
                        adb_client.version())
        else:
            logger.error('Could not connect/start ADB server')
            exit(1)

    # Require msgstore or connected device
    if args.msgstore:
        # Check if file exists
        if not os.path.isfile(args.msgstore):
            logger.error(
                "Msgstore location is not valid (file does not exist)")
            exit(1)
    else:
        logger.info(
            "Msgstore location not provided, attempting to find connected devices with ADB...\n"
        )

        devices = adb_client.devices()
        i = 0

        # If no devices and no msgstore, quit
        if len(devices) == 0:
            logger.error("Cannot find any connected devices")
            exit(1)

        # Show all devices
        for device in devices:
            print("\t[%d] %s (%s)" %
                  (i, device.serial,
                   device.shell('getprop ro.product.name').rstrip()))
            i += 1

        print('\n')
        while source_device is None:
            dev_index = int(
                raw_input(
                    "\n>> Which device number you want to extract msgstore from?: "
                ))

            if dev_index < 0 or dev_index + 1 > len(devices):
                continue

            source_device = devices[dev_index]
            print('\n')

    # Validate required phone
    if not args.wa_phone:
        logger.error(
            "Please provide the phone number associated with msgstore")
        exit(1)
    else:
        # Add "+" if not given
        if args.wa_phone[0] != '+':
            args.wa_phone = '+' + args.wa_phone

        try:
            phone = phonenumbers.parse(args.wa_phone)
        except NumberParseException:
            pass

        if not phone:
            logger.error("Provided phone number is NOT valid")
            exit(1)

    if not args.wa_verify:
        logger.error("Please provide a WhatsApp verification method")
        exit(1)

    # recap
    if source_device:
        logger.info('Extract WhatsApp database from device >> %s',
                    source_device.serial)
    else:
        logger.info('Using msgstore database from path: %s', args.msgstore)

    logger.info('Using WhatsApp phone number: +%d %d', phone.country_code,
                phone.national_number)
    logger.info('Using WhatsApp verification method: %s',
                args.wa_verify.upper())

    yn = raw_input("\n>> Continue? (y/n): ")

    if yn != 'y':
        exit(0)

    # create phone directory tree where to store results
    dst_path = os.path.join(os.path.abspath('output'),
                            str(phone.national_number))
    if not os.path.exists(dst_path):
        try:
            os.makedirs(dst_path)
        except OSError:
            logging.error('Cannot create output directory tree')
            exit(1)

    log_formatter = logging.Formatter(
        "%(asctime)s - [%(levelname)s]: %(message)s")
    file_handler = logging.FileHandler(os.path.join(dst_path, 'log.txt'))
    file_handler.setFormatter(log_formatter)
    logger.addHandler(file_handler)

    # Extract msgstore.db from source device, if any
    msgstore_path = args.msgstore

    if msgstore_path:
        logger.info('Provided msgstore.db SHA-256 hash: %s',
                    sha256(args.msgstore))

    if source_device:
        logger.info(
            'Extracting msgstore.db.crypt from phone to output/%ld/ ...' %
            phone.national_number)

        wa = WhatsApp(source_device)
        msgstore_path = wa.extract_msgstore(dst_path)

        if not msgstore_path:
            logger.error(
                'Could not find/extract msgstore database from device (is WhatsApp installed?)'
            )
            exit(1)

        logger.info('Extracted msgstore.db SHA-256 hash: %s',
                    sha256(msgstore_path))

    # Start emulator and connect to it
    logger.info('Starting emulator...')

    if args.no_accel:
        logger.warn(
            'Hardware acceleration disabled! Device might be very slow')

    emulator_device = sdk.start_emulator(adb_client, args.show_emulator,
                                         args.no_accel)

    if not emulator_device:
        logger.error('Could not start emulator!')
        exit(1)

    if args.show_emulator:
        logger.info('Do not interact with the emulator!')

    logger.info(
        'Trying to register phone on emulator... (may take few minutes)')

    # Attempt to register phone using provided msgstore
    wa_emu = WhatsApp(emulator_device)

    try:
        wa_emu.register_phone(msgstore_path, phone.country_code,
                              phone.national_number, args.wa_verify,
                              wa_code_callback)
    except WaException, e:
        logger.error('Exception in verification: %s', e.reason)
        exit(1)
Пример #26
0
import logging
import os
import time
from io import BytesIO

import numpy as np
from PIL import Image
from adb.client import Client as AdbClient

client = AdbClient(host="127.0.0.1", port=5037)

device = client.devices()[0]

baseline = {}

SCREEN_PATH = 'screen.png'

hero_anchor = (10, 134, 5)

MODE = "COIN"

tap_cords = {
    'restart': (1000, 635, 1170, 690),
    'continue': (560, 630, 720, 657),
    'start': (880, 555, 1035, 611),
    'skip0': (1190, 12, 1260, 45),
    'skip1': (1190, 12, 1260, 45),
    'exit': (
        1153,
        43,
        1264,
Пример #27
0
class Executer:
    def __init__(self):
        self.client = AdbClient(host="127.0.0.1", port=5037)

    def load_devices(self, only_number=False):
        try:
            adb_devices = self.client.devices()
            # details not needed, we only need the number of connecting devices
            if only_number:
                return [device.get_serial_no() for device in adb_devices]

            devices = []
            for dev in adb_devices:
                # adb shell getprop ro.boot.serialno
                # adb shell getprop ro.build.version.release
                # adb shell getprop ro.build.version.sdk
                # adb shell getprop ro.build.version.security_patch
                # adb shell getprop ro.debuggable
                # adb shell getprop ro.product.cpu.abi
                # adb shell getprop ro.product.model
                # adb shell getprop ro.secure

                # pure-python-adb supplies device.get_properties()
                # props_str = str(dev.shell("getprop"))
                # trantab = props_str.maketrans('', '', '[] \r')
                # props_list = props_str.translate(trantab).split('\n')
                # props_list = [props for props in props_list if props != '']
                # keys = [props.split(':')[0] for props in props_list]
                # values = [props.split(':')[1] for props in props_list]
                # props = dict(zip(keys, values))
                props = dev.get_properties()
                # adb shell cat /proc/version
                proc_version = str(dev.shell("cat /proc/version")).strip()
                name = dev.get_serial_no()
                # adb shell getenforce
                enforce = str(dev.shell("getenforce")).strip()
                device = Device(name=name,
                                model=props.get('ro.product.model', ''),
                                sdk=props.get('ro.build.version.sdk', ''),
                                security_patch=props.get(
                                    'ro.build.version.security_patch', ''),
                                release=props.get('ro.build.version.release',
                                                  ''),
                                debuggable=props.get('ro.debuggable', ''),
                                abi=props.get('ro.product.cpu.abi', ''),
                                proc_version=proc_version,
                                secure=props.get('ro.secure', ''),
                                enforce=enforce)
                devices.append(device)

            return devices
        except BaseException as e:
            utils.nl_print(e)

    def exec_poc(self, device_name, binary):
        device = self.client.device(device_name)

        dst = consts.DEVICE_TMP + binary.split('/')[-1]

        device.push(binary, dst)

        device.shell("chmod 777 %s" % dst)
        # run poc on device
        res = str(
            device.shell("cd %s; %s &>/dev/null; echo $?" %
                         (consts.DEVICE_TMP, dst))).strip()

        return res
Пример #28
0
import subprocess

from .noti import *
from adb.client import Client as AdbClient
from pathlib import Path

# More Better Solution...?
client = AdbClient(host='127.0.0.1', port=5037)

if Path.is_dir(Path.cwd() / 'backup') is False:
    Path.mkdir(Path.cwd() / 'backup')

try:
    list_device = client.devices()
except RuntimeError:
    err_printer('adb_not')
    subprocess.run(['adb', 'start-server'])
    list_device = client.devices()