Example #1
0
    mode = machine.dis_engine().attrib
    mn = machine.mn()
    instr = mn.fromstring(mn_str, mode)
    asm_instr = [i for i in mn.asm(instr)][0]

    return [struct.unpack("!B", byte)[0] for byte in asm_instr]


def r2m2_dis(opcode):
    """Disassemble an instruction using miasm."""

    machine = Machine("x86_64")
    mode = machine.dis_engine().attrib
    instr = machine.mn().dis(opcode, mode)

    return [instr.l, str(instr)]


def r2m2_ad_plugin(a):

    return { "name": "r2m2_native",
             "arch": "r2m2_native",
             "bits": 32,
             "license": "LGPL3",
             "desc": "miasm2 backend with radare2-bindings",
             "assemble": r2m2_asm,
             "disassemble": r2m2_dis }

# Register the ad plugin
r2lang.plugin("asm", r2m2_ad_plugin)
Example #2
0
            return offset
        if whence == 1:  # CUR
            return offset
        if whence == 2:  # END
            return -1
        return -1

    def _write(offset, data, size):
        p.kb.obj.memory.write_bytes(p.entry, data)
        print("python-write")
        return True

    def _system(cmd):
        r2angr_cmd(cmd)
        return 0

    return {
        "name": "angr",
        "license": "GPL",
        "desc": "IO plugin for Angr (angr://[/path/to/file])",
        "check": _check,
        "open": _open,
        "read": _read,
        "seek": _seek,
        "write": _write,
        "system": _system,
    }


print(r2lang.plugin("io", r2angr))
Example #3
0
		return "A" * size
	def _seek(offset, whence):
		print("python-seek")
		if whence == 0: # SET
			return offset
		if whence == 1: # CUR
			return offset
		if whence == 2: # END
			return 512 
		return 512
	def _write(offset, data, size):
		print("python-write")
		return True
	def _system(cmd):
		print("python-SYSTEM %s"%(cmd))
		return True
	return {
		"name": "pyio",
		"license": "GPL",
		"desc": "IO plugin in python (pyio://3)",
		"check": _check,
		"open": _open,
		"read": _read,
		"seek": _seek,
		"write": _write,
		"system": _system,
	}

print("Registering Python IO plugin...")
print(r2lang.plugin("io", pyio))
Example #4
0
# Example Python Core plugin written in Python
# ===========================================
#  -- pancake 2016
#
# $ r2 -I test-py-core.py -
# > q
# Dont be rude
# > ^D
# $

import r2lang

def pycore(a):
	def _call(s):
		if s == "q":
			print "Dont be rude"
			return 1;
		return 0

	return {
		"name": "PyCore",
		"license": "GPL",
		"desc": "core plugin in python",
		"call": _call,
	}

print "Registering Python core plugin..."
print r2lang.plugin("core", pycore)
Example #5
0
import r2lang

from asm import ba2asm
from anal import ba2anal
from bin import jn5168bin

r2lang.plugin("asm", ba2asm)
r2lang.plugin("anal", ba2anal)
r2lang.plugin("bin", jn5168bin)
Example #6
0
		if whence == 0: # SET
			return offset
		if whence == 1: # CUR
			return offset
		return -1 
	def _write(offset, data, size):
		print "TODO: write in dfu mode"
		return True
	def _system(cmd):
		if cmd == '?':
			print("Usage:")
			print(" =!spi      - read spi flash memory (16 MB long)")
			print(" =!flash    - read the flash memory")
			print(" =!coredump - dump a core file of ram")
			print("TODO: nothing is done yet")
		return True
	return {
		"name": "dfu",
		"license": "MIT",
		"desc": "DFU r2 IO plugin in Python (dfu://VNDR:PRDC)",
		"check": _check,
		"open": _open,
		"read": _read,
		"seek": _seek,
		"write": _write,
		"system": _system,
	}

print "Registering Python IO plugin..."
print r2lang.plugin("io", dfuio)
Example #7
0
import r2lang


def pyasm(a):
    def assemble(s):
        print "Assembling %s" % (s)
        return [1, 2, 3, 4]

    def disassemble(buf):
        try:
            return [2, "opcode %d" % (ord(buf[0]))]
        except:
            print "err"
            print sys.exc_info()
            return [2, "opcode"]

    return {
        "name": "MyPyDisasm",
        "arch": "pyarch",
        "bits": 32,
        "license": "GPL",
        "desc": "disassembler plugin in python",
        "assemble": assemble,
        "disassemble": disassemble,
    }


print "Registering Python asm plugin..."
print r2lang.plugin("asm", pyasm)
Example #8
0
            opcode = get_opcode(buf)
            esilstr = optbl[opcode][2]
            if optbl[opcode][0] == "J":  # it's jump
                analop["type"] = R.R_ANAL_OP_TYPE_JMP
                analop["jump"] = decode_jump(opcode, j_mask)
                esilstr = jump_esil(esilstr, opcode, j_mask)

        except:
            result = analop
        # Don't forget to return proper instruction size!
        return [4, result]

    return {
        "name": "mycpu",
        "arch": "mycpu",
        "bits": 32,
        "license": "GPL",
        "desc": "MYCPU anal",
        "esil": 1,
        "set_reg_profile": set_reg_profile,
        "op": op,
    }


print("Registering MYCPU analysis plugin...")
print(r2lang.plugin("anal", mycpu_anal))
print("Registering MYCPU disasm plugin...")
print(r2lang.plugin("asm", mycpu))

#r2 -I mycpu.py some_file.bin
Example #9
0
                found_taints.append(last_address)
                reg = line.split("{")[1].split("=")[0]
                r.cmd("s " + last_address)
                if "call" in r.cmd("pd 1"):
                    found = True
                    r.cmd("CC-")
                    r.cmd("CC Tainted by malloc")
                    taints["malloc"].append(last_address)
                    print(
                        colored(last_address, "green") + ": tainted by malloc")
        if found:
            print(
                colored("\nAdded comments at instructions tainted by malloc\n",
                        "yellow"))
        else:
            print(colored("No tainted calls found", "yellow"))
        r.cmd("s " + address)

    return {
        "name": "r2bap",
        "licence": "GPLv3",
        "desc":
        "Integrates the taint analysis capabilities of BAP with radare2",
        "call": process
    }


# Register the plugin
if not r2lang.plugin("core", r2bap):
    print("An error occurred while registering r2bap")
Example #10
0
# The r2lang.plugin function exposes a way to register new plugins
# into the RCore instance. This API is only available from RLang.
# You must call with with '#!python test.py' or 'r2 -i test.py ..'

import r2lang

def pyasm(a):
	def assemble(s):
		print "Assembling %s"%(s)
		return [ 1, 2, 3, 4 ]

	def disassemble(buf):
		try:
			return [ 2, "opcode %d"%(ord(buf[0])) ]
		except:
			print "err"
			print sys.exc_info()
			return [ 2, "opcode" ]
	return {
		"name": "MyPyDisasm",
		"arch": "pyarch",
		"bits": 32,
		"license": "GPL",
		"desc": "disassembler plugin in python",
		"assemble": assemble,
		"disassemble": disassemble,
	}

print "Registering Python asm plugin..."
print r2lang.plugin("asm", pyasm)
# Example Python Core plugin written in Python
# ===========================================
#  -- pancake 2016
#
# $ r2 -I test-py-core.py -
# > q
# Dont be rude
# > ^D
# $

import r2lang


def pycore(a):
    def _call(s):
        if s == "q":
            print("Dont be rude")
            return 1
        return 0

    return {
        "name": "PyCore",
        "license": "GPL",
        "desc": "core plugin in python",
        "call": _call,
    }


print("Registering Python core plugin...")
print(r2lang.plugin("core", pycore))
Example #12
0
        binary = r.cmd("i~file").split("\n")[0].split(" ")[-1]

        if not initialized:
            sys.path.append("src/")
            try:
                from r2angr import R2ANGR
                session = R2ANGR(binary, r)
                initialized = True

                session.load_angr()

            except Exception as e:
                print(e)
        try:
            session.run(command[1:])
        except Exception as e:
            print(e)

        try:
            return session.return_value
        except:
            return 1

    return {"name": "r2-angr",
            "licence": "GPLv3",
            "desc": "Integrates angr with radare2",
            "call": process}

if not r2lang.plugin("core", modality):
    print("An error occurred while registering modality")
Example #13
0
        size = len(m["data"])
        data = p.r2p.read_mem(addr, size)
        p.write_mem(addr, data)
        ncache.append({"start": addr, "data": data})
    cache = ncache

@pimp.pimpcmd("peek")
def cmd_peek(p, a):
    size = p.r2p.integer(a[0])
    addr = p.r2p.integer(a[1])
    print "{:#x}".format(p.peek(addr, size))


@pimp.pimpcmd("poke")
def cmd_poke(p, a):
    value = p.r2p.integer(a[0])
    size = p.r2p.integer(a[1])
    addr = p.r2p.integer(a[2])
    p.poke(addr, size, value)


@pimp.pimpcmd("input_type")
def cmd_input_type(p, a):
    p.input_type = a[0]

success = r2lang.plugin("core", pimp.plugin)
if not success:
    print "[!] Failed loading pimp plugin"
else:
    print "[*] Pimp plugin loaded, available commands are:\n\t{}".format(", ".join(pimp.commands))
Example #14
0
            return offset
        if whence == 1:  # CUR
            return offset
        if whence == 2:  # END
            return 512
        return 512

    def _write(offset, data, size):
        print "python-write"
        return True

    def _system(cmd):
        print "python-SYSTEM %s" % (cmd)
        return True

    return {
        "name": "pyio",
        "license": "GPL",
        "desc": "IO plugin in python (pyio://3)",
        "check": _check,
        "open": _open,
        "read": _read,
        "seek": _seek,
        "write": _write,
        "system": _system,
    }


print "Registering Python IO plugin..."
print r2lang.plugin("io", pyio)
Example #15
0
        pass
        #self.project = angr.Project(r2.cmdj['ij']['core']['file'])

    def _call(self, s):
        s = s.lower()

        # Not for us
        if not s.startswith('symb'):
            return

        print('doing it')
        p = angr.Project(r2.cmdj('ij')['core']['file'])
        #p = threading.Thread(target=angr.Project, args=[r2.cmdj('ij')['core']['file']])
        print('blerg')
        #p.start()
        #p.join()
        #print('blerg')
        #self.project = angr.Project(r2.cmdj['ij']['core']['file'])

    def plugin(self, a):
        return {
            "name": "R2Symbion",
            "licence": "GPLv3",
            "desc": "Integration plugin for angr Symbion.",
            "call": self._call,
        }


r2symb = R2Symbion()
success = r2lang.plugin("core", r2symb.plugin)
Example #16
0
             "os" : "OS/2",
             "subsystem" : "CLI",
             "machine" : "IBM",
             "arch" : "x86",
             "has_va" : 0,
             "bits" : 32,
             "big_endian" : 0,
             "dbg_info" : 0,
             }]

 return {
            "name" : "le",
            "desc" : "OS/2 LE/LX format",
            "license" : "GPL",
            "load" : load,
            "load_bytes" : load_bytes,
            "destroy" : destroy,
            "check_bytes" : check_bytes,
            "baddr" : baddr,
            "entries" : entries,
            "sections" : sections,
            "imports" : imports,
            "symbols" : symbols,
            "relocs" : relocs,
            "binsym" : binsym,
            "info" : info,
    }

print("Registering OS/2 LE/LX plugin...")
print(r2lang.plugin("bin", le_format))
Example #17
0
        # Convert hex bytes to binary
        _, fname = tempfile.mkstemp()
        fdesc = open(fname, "w")
        fdesc.write(data)
        fdesc.close()
        data = convert_dump(fname)
        os.remove(fname)

    except Exception:
        data = '\x00' * size

    return data[:size]


def flashair_io_plugin(a):

    return {
        "name": "flashair",
        "license": "LGPL3",
        "desc": "flashair IO plugin (flashair://)",
        "check": flashair_check,
        "open": flashair_open,
        "seek": flashair_seek,
        "read": flashair_read
    }


# Register the IO plugin
r2lang.plugin("io", flashair_io_plugin)
Example #18
0
    print(msg)


def esplugin(a):
    def _call(s):
        #print(s)
        args = shlex.split(s)
        if args[0] in es.commands:
            try:
                es.command(args)
            except Exception as e:
                print("error: %s" % str(e))

            return 1

        return 0

    return {
        "name": "ESILSolve",
        "license": "GPL",
        "desc": "plugin for esil-based symbolic execution",
        "call": _call,
    }


if r2p != None:
    es = ESILSolvePlugin(r2p)
    #r2print(r2p, " -- registering ESILSolve plugin... enter %saesx?%s for help" % \
    #    (colorama.Fore.YELLOW, colorama.Style.RESET_ALL))
    r2lang.plugin("core", esplugin)
Example #19
0
# The r2lang.plugin function exposes a way to register new plugins
# into the RCore instance. This API is only available from RLang.
# You must call with with '#!python test.py' or 'r2 -i test.py ..'

import r2lang

def pyasm(a):
	def assemble(s):
		print("Assembling %s"%(s))
		return [ 1, 2, 3, 4 ]

	def disassemble(buf):
		try:
			return [ 2, "opcode %d"%(ord(buf[0])) ]
		except:
			print("err")
			print(sys.exc_info())
			return [ 2, "opcode" ]
	return {
		"name": "MyPyDisasm",
		"arch": "pyarch",
		"bits": 32,
		"license": "GPL",
		"desc": "disassembler plugin in python",
		"assemble": assemble,
		"disassemble": disassemble,
	}

print("Registering Python asm plugin...")
print(r2lang.plugin("asm", pyasm))
Example #20
0
                from session import Session
                session = Session(binary, r)
                initialized = True
            except Exception as e:
                print(e)
        else:
            try:
                if initialized:
                    session.run(command[1:])
                else:
                    print("r2angr not initialized")
            except Exception as e:
                print(e)

        # Parse arguments
        #tmp = command.split(" ")
        #print(str(tmp))
        return 1

    return {
        "name": "r2-angr",
        "licence": "GPLv3",
        "desc": "Integrates angr with radare2",
        "call": process
    }


# Register the plugin
if not r2lang.plugin("core", r2angr):
    print("An error occurred while registering r2angr")
Example #21
0
import r2lang


def pyasm(a):
    def assemble(s):
        print("Assembling %s" % (s))
        return [1, 2, 3, 4]

    def disassemble(buf, buflen, pc):
        try:
            return [2, f"opcode {buf[0]}"]
        except:
            print("err")
            print(sys.exc_info())
            return [2, "opcode"]

    return {
        "name": "MyPyDisasm",
        "arch": "pyarch",
        "bits": 32,
        "license": "GPL",
        "desc": "disassembler plugin in python",
        "assemble": assemble,
        "disassemble": disassemble,
    }


if not r2lang.plugin("asm", pyasm):
    print("Failed to register the python asm plugin.")
Example #22
0
	def _read(offset, size):
		return "".join(p.kb.obj.memory.read_bytes(0+offset, size))
	def _seek(offset, whence):
		if whence == 0: # SET
			return offset
		if whence == 1: # CUR
			return offset
		if whence == 2: # END
			return -1 
		return -1
	def _write(offset, data, size):
		p.kb.obj.memory.write_bytes(p.entry, data)
		print "python-write"
		return True
	def _system(cmd):
		r2angr_cmd(cmd)
		return 0 
	return {
		"name": "angr",
		"license": "GPL",
		"desc": "IO plugin for Angr (angr://[/path/to/file])",
		"check": _check,
		"open": _open,
		"read": _read,
		"seek": _seek,
		"write": _write,
		"system": _system,
	}

print r2lang.plugin("io", r2angr)
Example #23
0
        else:
            command = "p8 @ %d" % address
        data = R2P.cmd(command)

        # Look for a valid Scapy layer
        layer = [l for l in conf.layers if l.__name__ == protocol]
        if not layer:
            print("Error: protocol '%s' is not a valid Scapy layer !" % protocol)
            return 1

        # Decode data
        try:
            packet = layer[0](data.decode("hex"))
        except Exception as e:
            print("Error: an exception occurred while decoding data:\n  %s" % e)
            return 1

        # Display the command that can produce the same packet
        print(packet.command())


    return {"name": "r2scapy",
            "licence": "GPLv3",
            "desc": "decode packets with Scapy",
            "call": process}


# Register the plugin
if not r2lang.plugin("core", r2scapy):
    print("An error occurred while registering r2scapy !")
Example #24
0
# into the RCore instance. This API is only available from RLang.
# You must call with with '#!python test.py' or 'r2 -i test.py ..'

import r2lang

def pyasm(a):
	def assemble(s):
		print("Assembling %s"%(s))
		return [ 1, 2, 3, 4 ]

	def disassemble(buf, buflen, pc):
		try:
			return [ 2, f"opcode {buf[0]}" ]
		except:
			print("err")
			print(sys.exc_info())
			return [ 2, "opcode" ]
	return {
		"name": "MyPyDisasm",
		"arch": "pyarch",
		"bits": 32,
		"license": "GPL",
		"desc": "disassembler plugin in python",
		"assemble": assemble,
		"disassemble": disassemble,
	}

if not r2lang.plugin("asm", pyasm):
	print("Failed to register the python asm plugin.")
	
Example #25
0
def cmd_peek(p, a):
    size = p.r2p.integer(a[0])
    addr = p.r2p.integer(a[1])
    print "{:#x}".format(p.peek(addr, size))


@pimp.pimpcmd("poke")
def cmd_poke(p, a):
    value = p.r2p.integer(a[0])
    size = p.r2p.integer(a[1])
    addr = p.r2p.integer(a[2])
    p.poke(addr, size, value)


@pimp.pimpcmd("input_type")
def cmd_input_type(p, a):
    p.input_type = a[0]


@pimp.pimpcmd("breakpoint")
def cmd_break(p, a):
    p.add_bp(p.r2p.integer(a[0]))


success = r2lang.plugin("core", pimp.plugin)
if not success:
    print "[!] Failed loading pimp plugin"
else:
    print "[*] Pimp plugin loaded, available commands are:\n\t{}".format(
        ", ".join(pimp.commands))
Example #26
0
            return offset
        if whence == 1:  # CUR
            return offset
        if whence == 2:  # END
            return ROM_SIZE
        return ROM_SIZE

    def _write(offset, data, length):
        print("TODO: python-write")
        return True

    def _system(cmd):
        print("pwndfu://%s" % (cmd))
        return True

    return {
        "name": "pwndfu",
        "license": "GPL",
        "desc": "pwndfu IO plugin (pwndfu://3)",
        "check": _check,
        "open": _open,
        "read": _read,
        "seek": _seek,
        "write": _write,
        "system": _system,
    }


print("Registering Python IO plugin...")
print(r2lang.plugin("io", pyio))
Example #27
0
            return offset
        if whence == 1:  # CUR
            return offset
        if whence == 2:  # END
            return -1
        return -1

    def _write(offset, data, size):
        p.kb.obj.memory.write_bytes(p.entry, data)
        print "python-write"
        return True

    def _system(cmd):
        r2angr_cmd(cmd)
        return 0

    return {
        "name": "angr",
        "license": "GPL",
        "desc": "IO plugin for Angr (angr://[/path/to/file])",
        "check": _check,
        "open": _open,
        "read": _read,
        "seek": _seek,
        "write": _write,
        "system": _system,
    }


print r2lang.plugin("io", r2angr)
Example #28
0
                               "aGCw"):
                return 0

            # Parse arguments
            if command == "aG":
                aG()
            elif command.startswith("aGx"):
                aGx(command)
            elif command.startswith("aGc"):
                aGc(command)
            elif command.startswith("aGC"):
                aGC(command)
        except Exception as e:
            print(traceback.format_exc())

        return 1

    return {
        "name": "r2xrefs",
        "author": "s0i37",
        "version": 0.10,
        "licence": "GPLv3",
        "desc": "radare2 cross reference visualization",
        "call": process
    }


# Register the plugin
if not r2lang.plugin("core", r2xrefs):
    print("An error occurred while registering r2xrefs plugin !")
Example #29
0
        try:
            response_json = response.json()
            print("Architecture:", response_json["prediction"]["architecture"],
                  "\nEndianness:", response_json["prediction"]["endianness"],
                  "\nWord size:", response_json["prediction"]["wordsize"],
                  "\nPrediction probabilty:",
                  response_json["prediction_probability"])
        except Exception:
            print("Unable to identify architecture")

        # Set radare variables for architecture, endianness and word size
        # based on the predicted values
        R2P.cmd("e asm.arch=%s" % response_json["prediction"]["architecture"])
        if response_json["prediction"]["endianness"] == "big":
            R2P.cmd("e cfg.bigendian=true")
        else:
            R2P.cmd("e cfg.bigendian=false")
        R2P.cmd("e asm.bits=%s" % response_json["prediction"]["wordsize"])

    return {
        "name": "isadetect",
        "license": "MIT",
        "desc":
        "radare2 plugin to call APIs that provide ISA detection for binary code/sequences",
        "call": process
    }


if not r2lang.plugin("core", r2isadetect):
    print("An error occurred while registering r2isadetect!")