Esempio n. 1
0
def createRzPipe():
    try:
        rzproj = rzpipe.open()
        rzproj.cmd("a")  # send a blind command
        return rzproj
    except:
        print("Unexpected error:", sys.exc_info()[0])
        return None
Esempio n. 2
0
def init_rizin(filename):
    rz = rizin.get(filename)
    if rz:
        return rz
    import rzpipe
    rz = rzpipe.open(filename)
    rizin[filename] = rz
    rz.cmd("aaaa")
    return rz
Esempio n. 3
0
    def __init__(self, file_name):
        rflags = ["-dw"]
        if (not test):
            rflags.append("-2")
        r = rzpipe.open(file_name, flags=rflags)
        for _ in range(5):
            r.cmd("dcs read")

        a = r.cmd("dr rip")
        a = int(a, 16)
        self.off = a - 0x12EE
        self.r = r

        self.encode_addr = 0x2E6F + self.off
        self.encode_addr_end = self.encode_addr + 0x4d8

        self.decode_addr = 0x3894 + self.off
        self.decode_addr_end = self.decode_addr + 0x4ef

        self.keyfun_addr = 0x1342 + self.off
        self.keyfun_addr_end = 0x13C7 + self.off

        m = 0x9038 + self.off
        self.mem_addr = int(r.cmdj(f"?j [{m}]")["uint64"])
Esempio n. 4
0
#!/usr/bin/env python
import sys
import rzpipe

rzp = rzpipe.open()
num = int(sys.argv[1])
if num == 0x80:
    r = rzp.cmdj("arj")
    if r["eax"] == 1:
        print("[SYSCALL EXIT] {0:d}", r["ebx"])
    elif r["eax"] == 4:
        msg = rzp.cmd("psz %d@%d" % (r["edx"], r["ecx"]))
        print("[WRITE SYSCALL] ==> {0:s}", msg)
elif num == 3:
    print("[INT3]")
else:
    print("[unhandled SYSCALL {0:d}]", num)
Esempio n. 5
0
#!/usr/bin/env python3
import rzpipe
import sys
import os

rz = rzpipe.open("/bin/ls")
libpath = ["", ".", "/lib", "/usr/lib"]
output = "aa"
# output = 'dot'

done = {}


def findlib(lib):
    if os.path.isfile(lib):
        return lib
    for a in libpath:
        if os.path.isfile("%s/%s" % (a, lib)):
            return "%s/%s" % (a, lib)
    return []


def getlibs(lib):
    return rz.syscmdj("rabin2 -lj %s" % (lib))["libs"]


def filter(s):
    return s.replace("-", "_").replace("+", "x")


def makeNode(name):
Esempio n. 6
0
def verify(title, cmd, expected):
    rz = rzpipe.open("-")
    msg = rz.cmd(cmd)
    test(title, msg, expected)
    rz.quit()
Esempio n. 7
0
"""
Example usage to regenerate traps.json:
    - open the dyld cache in rizin like this:
RZ_DYLDCACHE_FILTER=libsystem_kernel rizin -e bin.usextr=false ~/Library/Developer/Xcode/iOS\ DeviceSupport/12.1.2\ \(16C101\)\ arm64e/Symbols/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64e

    - run the script with this command:
        #!pipe python2 /path/to/this/script.py > traps.json

"""

import json
import re

import rzpipe

r = rzpipe.open("#!pipe")


def walk_back_until(addr, pattern, min_addr):
    cursor = addr
    while cursor >= min_addr:
        op = r.cmdj("aoj@" + str(cursor))[0]["opcode"]
        if re.search(pattern, op) != None:
            return cursor + 4
        if re.search(r"^ret", op) != None:
            return cursor + 4
        if re.search(r"^b ", op) != None:
            return cursor + 4
        cursor -= 4

    return min_addr
Esempio n. 8
0
 def _get_rz(self, index):
     rz = rzpipe.open(self._dex_list[index])
     rz.cmd("aa")
     return rz
Esempio n. 9
0
import json

import rzpipe


def chk(x):
    if x[1]["opcode"] == "svc 0x80":
        name = x[0]["flags"][0][8:]
        sysnum = int(x[0]["opcode"].split(" ")[2], 16)
        print("%d\t%s" % (sysnum, name))


dev_pid = "23f88587e12c30376f8ab0b05236798fdfa4e853/4903"

rz = rzpipe.open("frida://" + dev_pid)
print("Importing symbols from libSystem...")
rz.cmd(".=!i*")
rz.cmd(".=!ie* libSystem.B.dylib")
print("Finding syscalls...")
funcs = rz.cmd("pdj 2 @@f:sym.fun.*")

for doc in funcs.split("\n"):
    if len(doc) > 1:
        chk(json.loads(doc))
rz.quit()
print("Thanks for waiting")
Esempio n. 10
0
        for addr in range(start, end, (2 * self.PTR_SIZE)):
            func_addr = self.get_pointer(addr)
            offset = self.get_pointer(addr + self.PTR_SIZE)
            name_str_off = self.get_pointer(base + offset + self.PTR_SIZE)
            name_addr = base + name_str_off
            name = self.rz.cmd('psz @ {}'.format(name_addr))
            name = self.format_name(name)
            if name and len(name) > 2:
                print('Found name {} at 0x{:x}'.format(name, func_addr))
                funcinfo = self.rz.cmdj('afij {}'.format(func_addr))
                self.rz.cmd('af{} {} {}'.format('n' if funcinfo else '', name,
                                                func_addr))

    def format_name(self, name):
        name = name.replace('(', '')
        name = name.replace(')', '')
        name = name.replace('*', '')
        name = name.replace('/', '.')
        name = name.replace(' ', '.')
        name = name.replace(';', '.')
        name = name.replace(',', '.')
        return name.strip()


if __name__ == '__main__':
    rz = rzpipe.open()
    helper = GoLangHelper(rz)
    gopclntab = helper.get_gopclntab()
    print(gopclntab)
    helper.rename_functions()
Esempio n. 11
0
    def __init__(
        self,
        image_path: Optional[str] = None,
        blob: Optional[bytes] = None,
        rizinhome: Optional[str] = None,
    ):
        """UEFI analyzer initialization"""

        self._rz: rzpipe.open = None
        self._shm: Optional[shared_memory.SharedMemory] = None
        self._te: Optional[TerseExecutableParser] = None

        # init rizin
        if image_path:
            self._rz = rzpipe.open(filename=image_path,
                                   flags=["-2"],
                                   rizin_home=rizinhome)
            # analyze image
            self._rz.cmd("aaaa")
            try:
                self._te = TerseExecutableParser(image_path=image_path)
            except TerseExecutableError:
                self._te = None

        if blob and sys.platform in ["linux"]:
            if blob[:2] not in [b"MZ", b"VZ"]:
                raise UefiAnalyzerError("Invalid data format")
            blob_size = len(blob)
            self._shm = shared_memory.SharedMemory(create=True, size=blob_size)
            self._shm.buf[:] = blob[:]
            self._rz = rzpipe.open(
                filename=f"shm://{self._shm.name}/{blob_size:#d}",
                flags=["-2"],
                rizin_home=rizinhome,
            )
            self._rz.cmd("aaaa")
            try:
                self._te = TerseExecutableParser(blob=blob)
            except TerseExecutableError:
                self._te = None

        if self._rz is None:
            raise UefiAnalyzerError(
                "Failed to initialize radare2/rizin analyzing engine")

        # private cache
        self._bs_list_g_bs: Optional[List[UefiService]] = None
        self._bs_prot: Optional[List[UefiService]] = None
        self._rt_list: Optional[List[UefiService]] = None
        self._pei_services: Optional[List[UefiService]] = None
        self._ppi_list: Optional[List[UefiProtocol]] = None
        self._protocols: Optional[List[UefiProtocol]] = None
        self._protocol_guids: Optional[List[UefiProtocolGuid]] = None
        self._nvram_vars: Optional[List[NvramVariable]] = None
        self._info: Optional[Dict[Any, Any]] = None
        self._strings: Optional[List[Any]] = None
        self._sections: Optional[List[Any]] = None
        self._functions: Optional[List[Any]] = None
        self._insns: Optional[List[Any]] = None
        self._g_bs: Optional[List[int]] = None
        self._g_rt: Optional[List[int]] = None
        self._smst_list: Optional[List[int]] = None

        # SMI handlers addresses
        self._swsmi_handlers: Optional[List[SwSmiHandler]] = None
        self._child_swsmi_handlers: Optional[List[ChildSwSmiHandler]] = None
Esempio n. 12
0
from z3 import *
import rzpipe
import subprocess
import os

def uncompress():
    subprocess.call(['rm','surprise.out'])
    subprocess.call(['bzip2', '-d','surprise'])
ef get_xorvalues(arch):
    r = rzpipe.open("surprise.out")
    offsets={ "4":0x10020130, "0":[0x0202020,0x0202060], "2":[0x3020,0x3060] , "1":0x011008, "3":0x0012010}#need to recheck offsets for each arch before running script
    if arch == '0' or arch == '2':
        arch_offset1='pf 14d @'+str(offsets[arch][0])
        arr = r.cmd(arch_offset1) #offset has to checked with ida after every 20 iters when the arch of the binary changes
        arr=[int(i) for i in arr.strip().split()[5::7]]
        xor1=arr
        arr=[]
        arch_offset2='pf 14d @'+str(offsets[arch][1])
        arr = r.cmd(arch_offset2) #offset has to checked with ida after every 20 iters when the arch of the binary changes
        arr=[int(i) for i in arr.strip().split()[5::7]]
        xor2=arr
        print(xor1,xor2)
        return xor1,xor2
    else:
        print(offsets[arch],arch)
        arch_offset='pf 28d @'+str(offsets[arch])
        arr = r.cmd(arch_offset) #offset has to checked with ida after every 20 iters when the arch of the binary changes
        arr=[int(i) for i in arr.strip().split()[5::7]]
        xor1=arr[:14]
        xor2=arr[14:]
    print(xor1,xor2)
Esempio n. 13
0
# /usr/bin/env python

import rzpipe
from os import system
import time

if __name__ == "__main__":
    print("[+] Spawning rizin tcp and http servers")
    system("pkill rizin")
    system("rizin -qc.:9080 /bin/ls &")
    system("rizin -qc=h /bin/ls &")
    time.sleep(1)

    # Test rzpipe with local process
    print("[+] Testing python rzpipe local")
    rlocal = rzpipe.open("/bin/ls")
    print(rlocal.cmd("pi 5"))
    # print rlocal.cmd("pn")
    info = rlocal.cmdj("ij")
    print("Architecture: " + info["bin"]["machine"])

    # Test rzpipe with remote tcp process (launch it with "rizin -qc.:9080 myfile")
    print("[+] Testing python rzpipe tcp://")
    rremote = rzpipe.open("tcp://127.0.0.1:9080")
    disas = rremote.cmd("pi 5")
    if not disas:
        print("Error with remote tcp conection")
    else:
        print(disas)

    # Test rzpipe with remote http process (launch it with "rizin -qc=H myfile")
Esempio n. 14
0
#!/usr/bin/env python3
import rzpipe

rz = rzpipe.open("ccall:///bin/ls")
# rz = rzpipe.open("/bin/ls")
# rz.cmd("o /bin/ls")
print(rz.cmd("pd 10"))
rz.quit()
import rzpipe
from malduck import rc4
import sys

args = sys.argv
print(args)
if len(args) < 5:
    print('wrong')
    sys.exit()
r2 = rzpipe.open()
base = args[1]
off = args[2]
kl = args[3]
cl = args[4]

cmd = f'pxj {kl} @ {base} + {off}'
print(cmd)
key = r2.cmdj(cmd)

cmd = f'pxj {cl} @ {base} + {off} + {kl}'
print(cmd)
ct = r2.cmdj(cmd)
print(key)
print(ct)

pt = rc4(bytes(key), bytes(ct))
print(pt)
if b'\x00' in pt:
    print(pt.decode('utf-16'))
Esempio n. 16
0
    def __init__(self, file_path, structure_path=None):
        if structure_path is None:
            structure_path = pkg_resources.resource_filename(
                "quark.core.axmlreader", "axml_definition")

        if not os.path.isfile(structure_path):
            raise AxmlException(f"Cannot find printing format definition file"
                                f" of Rizin in {structure_path}")

        self._rz = rzpipe.open(file_path)
        self._rz.cmd(f"pfo {structure_path}")

        self._file_size = int(self._rz.cmd("i~size[1]"), 16)
        self._ptr = 0

        self._cache = {}

        if self._file_size > 0xFFFF_FFFF:
            raise AxmlException("Filesize exceeds theoretical upper bound.")
        elif self._file_size < 8:
            raise AxmlException("Filesize exceeds theoretical lower bound.")

        # File Header
        header = self._rz.cmdj("pfj axml_ResChunk_header @ 0x0")

        self._data_type = header[0]["value"]
        self._axml_size = header[2]["value"]
        header_size = header[1]["value"]

        if self._data_type != RES_XML_TYPE or header_size != 0x8:
            raise AxmlException(
                f"Error parsing first header(type: {self._data_type},"
                f" size: {header_size}).")

        if self._axml_size > self._file_size:
            raise AxmlException(f"Decleared size ({self._axml_size} bytes) is"
                                f" larger than total size({self._file_size}).")

        self._ptr += 8
        if self._ptr >= self._axml_size:
            return

        # String Pool
        string_pool_header = self._rz.cmdj("pfj axml_ResStringPool_header @ 8")

        string_pool_size = string_pool_header[0]["value"][2]["value"]

        if string_pool_size > self._axml_size - self._ptr:
            raise AxmlException(
                f"Error parsing string pool, there should"
                f" be {string_pool_size}"
                f" bytes but only {self._axml_size - self._ptr} bytes.")

        header = string_pool_header[0]["value"]
        header_type = header[0]["value"]
        header_size = header[1]["value"]

        if header_type != RES_STRING_POOL_TYPE:
            raise AxmlException(
                f"Error parsing string pool, expect string pool"
                f" data at {self._ptr} bytes.")

        if header_size != 28:
            raise AxmlException(
                f"Error parsing string pool, heardsize should "
                f"be 16 bytes rather than { header_size } bytes.")

        self._stringCount = string_pool_header[1]["value"]
        stringStart = string_pool_header[4]["value"]

        self._rz.cmd(f"f string_pool_header @ 0x8 ")
        string_pool_index = header_size + self._ptr
        self._rz.cmd(f"f string_pool_index @ { string_pool_index }")
        string_pool_data = stringStart + self._ptr
        self._rz.cmd(f"f string_pool_data @ { string_pool_data }")

        self._ptr += string_pool_size
        if self._ptr >= self._axml_size:
            return

        # Resource Map (Optional)
        header = self._rz.cmdj(f"pfj axml_ResChunk_header @ {self._ptr}")

        header_type = header[0]["value"]
        if header_type == RES_XML_RESOURCE_MAP_TYPE:
            map_size = header[2]["value"]

            # Skip all the resource map

            if map_size > self._axml_size - self._ptr:
                raise AxmlException(
                    f"Map size should be {map_size} bytes rather"
                    f" than {self._axml_size - self._ptr} bytes.")

            self._ptr += map_size
            if self._ptr >= self._axml_size:
                return
Esempio n. 17
0
FILENAMES = [
    "bins/elf/_Exit (42)", "bins/pe/winver.exe", "bins/mach0/mach0_2-x86_64"
]

for fname in FILENAMES:
    with open(fname, "rb") as f:
        data = f.read()
        data_size = len(data)
        shm = shared_memory.SharedMemory(create=True, size=data_size)
        print("Copying %s..." % fname)
        shm.buf[:data_size] = data[:]
        print("Copied %s succesfully" % fname)
        print("-------------")
        print("Shared buffer size 0x{0:x}".format(data_size))
        print("-------------")

        rzp = rzpipe.open("shm://{0:s}/{1:d}".format(shm.name, data_size))
        rzp.cmd("e scr.color=0")
        rzp.cmd("e scr.utf8=false")
        rzp.cmd("e scr.interactive=false")
        infoj = rzp.cmdj("ij")
        print(infoj["bin"])
        print(rzp.cmd("px 16"))
        rzp.cmd("aaa")
        print(rzp.cmd("afl"))
        print(rzp.cmd("pdf @ entry0"))
        rzp.quit()
        shm.close()
        shm.unlink()
Esempio n. 18
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

"""
Example usage to regenerate traps.json:
    - open the dyld cache in rizin like this:
RZ_DYLDCACHE_FILTER=libsystem_kernel rizin -e bin.usextr=false ~/Library/Developer/Xcode/iOS\ DeviceSupport/12.1.2\ \(16C101\)\ arm64e/Symbols/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64e

    - run the script with this command:
        #!pipe python2 /path/to/this/script.py > traps.json

"""

import rzpipe, json, re

r = rzpipe.open('#!pipe')

def walk_back_until (addr, pattern, min_addr):
    cursor = addr
    while cursor >= min_addr:
        op = r.cmdj('aoj@' + str(cursor))[0]['opcode']
        if re.search(pattern, op) != None:
            return cursor + 4
        if re.search(r'^ret', op) != None:
            return cursor + 4
        if re.search(r'^b ', op) != None:
            return cursor + 4
        cursor -= 4

    return min_addr