コード例 #1
0
ファイル: qemu_runner.py プロジェクト: lmrs2/T-Fuzz
    def _check_qemu_install(self):
        """
        Check the install location of QEMU.
        """
        btype = binary_type(self.binary)
        if btype == "cgc":
            tname = "cgc-tracer"
        elif btype == "elf":
            self._record_magic = False
            r2 = Radare2(self.binary)
            if r2.arch == "x86" and r2.bits == 64:
                tname = "linux-x86_64"
            elif r2.arch == "x86" and r2.bits == 32:
                tname = "linux-i386"
            else:
                raise RunnerEnvironmentError("Binary type not supported")
        else:
            raise RunnerEnvironmentError("Binary type not supported")

        self._trace_source_path = shellphish_qemu.qemu_path(tname)
        if not os.access(self._trace_source_path, os.X_OK):
            if os.path.isfile(self._trace_source_path):
                error_msg = "%s is not executable" % self.trace_source
                l.error(error_msg)
                raise RunnerEnvironmentError(error_msg)
            else:
                error_msg = "\"%s\" does not exist" % self._trace_source_path
                l.error(error_msg)
                raise RunnerEnvironmentError(error_msg)
コード例 #2
0
ファイル: qemu_runner.py プロジェクト: CAFA1/tracer
    def _check_qemu_install(self):
        """
        Check the install location of QEMU.
        """
        if self.os == "cgc":
            suffix = "tracer" if self._record_trace else "base"
            self.trace_source = "shellphish-qemu-cgc-%s" % suffix
        else:
            self.trace_source = "shellphish-qemu-linux-%s" % self._p.arch.qemu_name

        if self._trace_source_path is None or not os.access(
                self._trace_source_path, os.X_OK):
            if self._trace_source_path is not None:
                l.warning("Problem accessing forced %s. Using our default %s.",
                          self._trace_source_path, self.trace_source)

            self._trace_source_path = shellphish_qemu.qemu_path(
                self.trace_source)

            if not os.access(self._trace_source_path, os.X_OK):
                if os.path.isfile(self._trace_source_path):
                    error_msg = "%s is not executable" % self.trace_source
                    l.error(error_msg)
                    raise RunnerEnvironmentError(error_msg)
                else:
                    error_msg = "\"%s\" does not exist" % self._trace_source_path
                    l.error(error_msg)
                    raise RunnerEnvironmentError(error_msg)
コード例 #3
0
    def _run_qemu(self, payload, args=None):
        if not SHELLPHISH_QEMU:
            raise ModuleNotFoundError("Phuzzer's Extender requires 'shellphish-qemu' to be installed ")

        qemu_path = shellphish_qemu.qemu_path("cgc-tracer")

        pargs  = [qemu_path]

        if isinstance(args, list):
            pargs += args

        pargs += ["-m", "8G"]

        pargs += [self.binary]

        with open("/dev/null", "wb") as devnull:
            p = subprocess.Popen(
                    pargs,
                    stdin=subprocess.PIPE,
                    stdout=devnull,
                    stderr=devnull)

            _, _ = p.communicate(payload)

        return p.wait()
コード例 #4
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.l = logging.getLogger("patcherex.test.test_detourbackend")
     self.bin_location = str(
         os.path.join(os.path.dirname(os.path.realpath(__file__)),
                      '../../binaries/tests/mips64/patchrex'))
     self.qemu_location = shellphish_qemu.qemu_path('mips64')
コード例 #5
0
    def trace(self):
        if not SHELLPHISH_QEMU_INSTALLED:
            raise ImportError(
                "The module 'shellphish-qemu' is not found, but it is required for tracing."
            )
        if self._trace is not None:
            return self._trace

        with open(self.filepath, 'rb') as sf:
            cmd_args = [
                'timeout', '2',
                shellphish_qemu.qemu_path('cgc-tracer'), '-d', 'exec',
                self.hierarchy._fuzzer.binary_path
            ]
            #print("cat %s | %s" % (self.filepath, ' '.join(cmd_args)))
            process = subprocess.Popen(cmd_args,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            _, you = process.communicate(sf.read())

        trace = []
        for tline in you.split(b'\n'):
            result = re.match(b'Trace 0x[0-9a-fA-F]* \\[([0-9a-fA-F]*)\\]',
                              tline.strip())
            if not result:
                continue
            trace.append(int(result.group(1), base=16))

        self._trace = trace
        return trace
コード例 #6
0
ファイル: hierarchy.py プロジェクト: ruaronicola/phuzzer
    def trace(self):
        if self._trace is not None:
            return self._trace

        with open(self.filepath, 'rb') as sf:
            cmd_args = [
                'timeout', '2',
                shellphish_qemu.qemu_path('cgc-tracer'), '-d', 'exec',
                self.hierarchy._fuzzer.target
            ]
            #print("cat %s | %s" % (self.filepath, ' '.join(cmd_args)))
            process = subprocess.Popen(cmd_args,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            _, you = process.communicate(sf.read())

        trace = []
        for tline in you.split(b'\n'):
            result = re.match(b'Trace 0x[0-9a-fA-F]* \\[([0-9a-fA-F]*)\\]',
                              tline.strip())
            if not result:
                continue
            trace.append(int(result.group(1), base=16))

        self._trace = trace
        return trace
コード例 #7
0
    def output(self):
        with open('/dev/null', 'w') as tf, open(self.filepath) as sf:
            cmd_args = [
                'timeout', '60', shellphish_qemu.qemu_path('cgc-tracer'),
                self.hierarchy._fuzzer.binary_path
            ]
            process = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=tf)
            f**k, _ = process.communicate(sf.read())

        return f**k
コード例 #8
0
ファイル: crs.py プロジェクト: firebitsbr/manual-interaction
def add_test_or_crash(args):
    p = subprocess.Popen([shellphish_qemu.qemu_path('cgc-base'), args.cb],
                         stdin=subprocess.PIPE)
    p.poll()
    test = ""

    if args.batch:
        test = sys.stdin.read()
        p.communicate(test)
    else:
        try:
            while p.returncode is None:
                r, _, _ = select([sys.stdin], [], [], 0.05)
                if r is not None:
                    b = sys.stdin.read(1)
                    test += b
                    p.stdin.write(b)

                p.poll()
        except KeyboardInterrupt:
            p.returncode = 0
        except IOError:
            p.returncode = 1

    if p.returncode == 0:
        print "Finished test, inserting now..."
        cs = CS.select().where(CS.name == args.cs)

        # first we have to make a fake job
        job = Job.create(cs=cs,
                         completed_at=datetime.datetime.now(),
                         worker="garbage")

        Test.create(cs=cs, job=job, blob=test)
        print "Test inserted!"
    else:
        print "Found a crash, inserting now..."

        qc = QuickCrash(args.cb, test)
        print "appears to be of type " + qc.kind

        print "cs = " + args.cs
        cs = CS.select().where(CS.name == args.cs)

        # first we have to make a fake job
        job = Job.create(cs=cs,
                         completed_at=datetime.datetime.now(),
                         worker="garbage")

        Crash.create(cs=cs, job=job, blob=test, kind=qc.kind)
        print "Crash inserted!"
コード例 #9
0
    def try_bin_with_input(path, tinput, seed=123):
        pipe = subprocess32.PIPE
        qemu_location = shellphish_qemu.qemu_path('cgc-nxtracer')
        main_args = [qemu_location, "-seed", str(seed)]
        if bitflip:
            used_args = main_args + ["-bitflip"]
        else:
            used_args = main_args

        final_args = used_args + [os.path.realpath(path)]
        print " ".join(final_args)
        p = subprocess32.Popen(final_args,
                               stdin=pipe,
                               stdout=pipe,
                               stderr=pipe,
                               preexec_fn=process_killer)
        status = "ok"
        try:
            try:
                stdout, stderr = p.communicate(tinput, timeout=10)
                print stdout
                print stderr
                print p.returncode
            except OSError:
                print "OSError"
                # I have seen: "OSError: [Errno 32] Broken pipe"
                # likely because the process dies before it reads all the input
                # I just "pass", the code later on will check if it is a crash or normal exit
                if p.returncode == None:
                    # returncode == None means the process is still running
                    # this means the process did not terminate
                    # I am not even sure this is possible, but I am going to terminate it to be sure
                    p.terminate()
            p.wait(
            )  # either communicate has finished or I called terminate, so wait will not stall
            # 46 is the special error code value used in cgc-nxtracer used to indicate
            # execution attempt of not executable memory
            if p.returncode < 0 or p.returncode == 46:
                status = "crash"
        except subprocess32.TimeoutExpired:
            print "Timeout"
            status = "halt"
            p.terminate()
            p.wait()
        print status
        return status
コード例 #10
0
    def _check_qemu_install(self):
        """
        check the install location of qemu
        """

        if self.os == "cgc":
            self.tracer_qemu = "shellphish-qemu-cgc-%s" % (
                "tracer" if self._record_trace else "base")

        self.tracer_qemu_path = shellphish_qemu.qemu_path(self.tracer_qemu)

        if not os.access(self.tracer_qemu_path, os.X_OK):
            if os.path.isfile(self.tracer_qemu_path):
                l.error("%s is not executable", self.tracer_qemu)
                raise TracerEnvironmentError
            else:
                l.error("\"%s\" does not exist", self.tracer_qemu_path)
                raise TracerEnvironmentError
コード例 #11
0
    def output(self):
        if not SHELLPHISH_QEMU_INSTALLED:
            raise ImportError(
                "The module 'shellphish-qemu' is not found, but it is required for the output functionality."
            )
        with open('/dev/null', 'w') as tf, open(self.filepath) as sf:
            cmd_args = [
                'timeout', '60',
                shellphish_qemu.qemu_path('cgc-tracer'),
                self.hierarchy._fuzzer.binary_path
            ]
            process = subprocess.Popen(cmd_args,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=tf)
            f**k, _ = process.communicate(sf.read())

        return f**k
コード例 #12
0
def monitor_interaction(oname, rname, result_callback):
    proc = subprocess.Popen("stdbuf -i0 -o0 python -u %s/fixup_input.py %s | stdbuf -i0 -o0 tee %s 2>/dev/null | (%s %s; sleep 2; killall -2 tee 2>/dev/null; kill -2 $PPID 2>/dev/null) | %s ./color" % (
        os.path.dirname(__file__), os.path.basename(args.binary),
        oname, shellphish_qemu.qemu_path('cgc-tracer'), args.binary, sys.executable
    ), shell=True)
    last_size = -1
    try:
        while proc.poll() is None:
            time.sleep(1)
            new_size = os.path.getsize(oname)
            if new_size != last_size:
                last_size = new_size
                with open(rname, 'a') as rf:
                    r = result_callback(oname)
                    r['output_file'] = oname
                    json.dump(r, rf)
                    rf.write('\n')
    except KeyboardInterrupt:
        pass
コード例 #13
0
def execute_binary(iname, oname, tname, trace_blocks=True, trace_syscalls=True):
    infile = open(iname)
    outfile = open(oname, 'w')
    tracefile = open(tname, 'w') if tname != oname else outfile

    cmd_args = [ "timeout", "60", shellphish_qemu.qemu_path('cgc-tracer') ]
    if trace_blocks:
        cmd_args += [ '-d', 'exec' ]
    if trace_syscalls:
        cmd_args += [ '-strace' ]
    if trace_blocks and not trace_syscalls:
        tracefile.close()
        cmd_args += [ '-D', tname ]
        tracefile = open('/dev/null', 'w')
    cmd_args += [ args.binary ]

    process = subprocess.Popen(cmd_args, stdin=infile, stdout=outfile, stderr=tracefile)
    process.wait()
    return process.pid
コード例 #14
0
    def _check_qemu_install(self):
        '''
        check the install location of qemu
        '''

        if self.os == "cgc":
            self.tracer_qemu = "shellphish-qemu-cgc-tracer"
            qemu_platform = 'cgc-tracer'
        elif self.os == "unix":
            self.tracer_qemu = "shellphish-qemu-linux-%s" % self._p.arch.qemu_name
            qemu_platform = self._p.arch.qemu_name

        self.tracer_qemu_path = shellphish_qemu.qemu_path(qemu_platform)

        if not os.access(self.tracer_qemu_path, os.X_OK):
            if os.path.isfile(self.tracer_qemu_path):
                l.error("tracer-qemu-cgc is not executable")
                raise TracerEnvironmentError
            else:
                l.error("\"%s\" does not exist", self.tracer_qemu_path)
                raise TracerEnvironmentError
コード例 #15
0
    def _run_qemu(self, payload, args=None):

        qemu_path = shellphish_qemu.qemu_path("cgc-tracer")

        pargs = [qemu_path]

        if isinstance(args, list):
            pargs += args

        pargs += ["-m", "8G"]

        pargs += [self.binary]

        with open("/dev/null", "wb") as devnull:
            p = subprocess.Popen(pargs,
                                 stdin=subprocess.PIPE,
                                 stdout=devnull,
                                 stderr=devnull)

            _, _ = p.communicate(payload)

        return p.wait()
コード例 #16
0
ファイル: seeker_stats.py プロジェクト: ucsb-seclab/hacrs
def execute_binary(binary_path,
                   iname,
                   oname,
                   tname,
                   blocks=True,
                   syscalls=True):
    infile = open(iname)
    outfile = open(oname, 'w')
    tracefile = open(tname, 'w') if tname != oname else outfile

    cmd_args = [shellphish_qemu.qemu_path('cgc-tracer')]
    if blocks:
        cmd_args += ['-d', 'exec']
    if syscalls:
        cmd_args += ['-strace']
    cmd_args += [binary_path]

    print cmd_args
    process = subprocess.Popen(cmd_args,
                               stdin=infile,
                               stdout=outfile,
                               stderr=tracefile)
    process.wait()
    return process.pid
コード例 #17
0
def analyze_single(tar_path):
    if "nrfin00056" in tar_path or "NRFIN_00056" in tar_path:
        return

    print "analyze_single", tar_path
    bin_name = os.path.basename(os.path.dirname(tar_path))
    res_dir = os.path.dirname(tar_path)
    experiment_name = "-".join(os.path.basename(tar_path).split("-")[1:])
    experiment_name = experiment_name.split(".tar.gz")[0]
    print "experiment name", experiment_name
    if os.path.exists(os.path.join(res_dir, "over_time-" + experiment_name)):
        print "already done"
        return

    # get the cfgfast # of block
    # coverage out of cfgfast
    p = os.path.join("/results/bins", bin_name)
    import angr
    b = angr.Project(p)
    cfg = b.analyses.CFG()
    num_nodes = len([
        n.addr for n in cfg.graph.nodes()
        if not n.is_syscall and not n.is_simprocedure
    ])

    # unpack tar
    try:
        shutil.rmtree("/home/angr/tmp")
    except:
        pass
    tar = tarfile.open(tar_path, "r:gz")
    tar.extractall(path="/home/angr")
    tar.close()
    # get all inputs to run to analyze coverage
    fuzzer_dir = "/home/angr/tmp/afl_sync/fuzzer-master/queue/"

    min_time = None
    trace_to_time = dict()
    for x in os.listdir(fuzzer_dir):
        # print x, t, type(t)
        if not x.startswith("id"):
            continue
        # if not x.endswith(".seed"):
        #    continue
        x = os.path.join(fuzzer_dir, x)
        t = os.path.getmtime(x)

        if min_time is None or t < min_time:
            min_time = t
        trace_to_time[x] = t

    # do it multiprocessing
    sorted_traces = sorted(trace_to_time.items(), key=operator.itemgetter(1))

    sorted_traces = [
        x for x in sorted_traces if trace_to_time[x[0]] - min_time < 60 * 60
    ]
    to_run = []
    for x, t in sorted_traces:
        # print seconds
        # input_path, qemu_path, binary_path
        tracer_path = shellphish_qemu.qemu_path('cgc-tracer')
        to_run.append((x, tracer_path, p))

    print "first to run:", to_run[0]
    print "path exits:", [os.path.exists(x) for x in to_run[0]]

    pool = Pool(8)
    traces_iter = pool.imap(get_trace, to_run, chunksize=2)

    blocks_hit = set()
    block_fraction_over_time = list()
    count = 0
    for a, trace in itertools.izip(sorted_traces, traces_iter):
        count += 1
        if count % 10 == 0:
            print "count:", count, "/", len(sorted_traces)
        path, t = a
        blocks, transitions = trace
        blocks_hit.update(blocks)
        block_fraction_over_time.append(
            ((t - min_time), float(len(blocks_hit)) / num_nodes))

    pool.close()

    with open(os.path.join(res_dir, "over_time-" + experiment_name),
              "wb") as f:
        for a, b in block_fraction_over_time:
            f.write(str(int(a)) + ", " + str(b) + "\n")

    with open(os.path.join(res_dir, "fraction-" + experiment_name), "wb") as f:
        f.write(str(float(len(blocks_hit)) / num_nodes) + "\n")
コード例 #18
0
def try_one_patch(args):
    test, patch_type, td = args
    print "=" * 5, "test", test, patch_type, "started"
    inputs = ["", "A", "\x00", "\nA\x00 " * 50]
    # if ("fidget"  not in patch_type): continue
    pm = PatchMaster(test)
    patched_bin, nrule = pm.create_one_patch(patch_type)

    if ((os.path.basename(test), patch_type) in PATCH_TYPES_EXPECTED_FAIL):
        nose.tools.assert_true(patched_bin == None)
        return None
    else:
        nose.tools.assert_true(patched_bin != None)

    tmp_fname = os.path.join(td, os.path.basename(test) + "_" + patch_type)
    save_patch(tmp_fname, patched_bin)
    # save_patch("/tmp/aaa",patched_bin)
    # save_patch(os.path.join("/tmp/cfe1",os.path.basename(test)+"_"+patch_type),patched_bin)

    fp = open(test)
    ocontent = fp.read()
    fp.close()
    fp = open(tmp_fname)
    pcontent = fp.read()
    fp.close()

    if patch_type not in PATCH_TYPES_AS_ORIGINAL:
        # it is not impossible that a patched binary is exactly as the original
        # but it is worth investigation
        nose.tools.assert_true(ocontent != pcontent)
    else:
        nose.tools.assert_equal(ocontent, pcontent)

    nose.tools.assert_equal(type(patched_bin), str)
    nose.tools.assert_equal(type(nrule), str)

    if patch_type in PATCH_TYPES_WITH_RULES:
        nose.tools.assert_true(len(nrule) > 0)
    else:
        nose.tools.assert_true(len(nrule) == 0)

        if "bitflip" in nrule:
            bitflip = True
        else:
            bitflip = False
        # see: https://git.seclab.cs.ucsb.edu/cgc/qemu/issues/5
        pov_tester = CGCPovSimulator(
            qemu=shellphish_qemu.qemu_path("cgc-nxtracer"))
        res = pov_tester.test_binary_pov(backdoor_pov_location,
                                         tmp_fname,
                                         bitflip=bitflip)
        if patch_type in PATCH_TYPES_WITH_BACKDOOR:
            nose.tools.assert_true(res)
        else:
            nose.tools.assert_equal(res, False)

    for stdin in inputs:
        # TODO: test properly multi-cb, right now they are tested as separate binaries
        pipe = subprocess.PIPE
        p = subprocess.Popen([qemu_location, test],
                             stdin=pipe,
                             stdout=pipe,
                             stderr=pipe)
        res = p.communicate(stdin)
        expected = (res[0], p.returncode)
        print expected

        print "testing:", os.path.basename(test), "input:", stdin[:10].encode(
            "hex"), patch_type
        #save_patch("/tmp/",patch)
        nose.tools.assert_true(os.path.getsize(tmp_fname) > 1000)

        argv = [qemu_location, tmp_fname]
        if "bitflip" in nrule:
            argv = [argv[0]] + ["-bitflip"] + argv[1:]
        p = subprocess.Popen(argv, stdin=pipe, stdout=pipe, stderr=pipe)
        # very very partial support to network rules
        # TODO if we add other "interesting rules", handle them here
        res = p.communicate(stdin)
        real = (res[0], p.returncode)
        # there may be special cases in which the behavior changes
        # because the patch prevent exploitation
        # this is unlikely, given the naive inputs
        nose.tools.assert_equal(real, expected)
        print "=" * 5, "test", test, patch_type, "ended"
        return (True, (test, patch_type), pcontent)
コード例 #19
0
import patcherex.utils as utils
import patcherex
import shellphish_qemu
from patcherex.patch_master import PatchMaster
from povsim import CGCPovSimulator

l = logging.getLogger("patcherex.test.test_patch_master")
bin_location = str(
    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                 '../test_binaries'))
logging.getLogger("povsim.cgc_pov_simulator").setLevel('DEBUG')

patcherex_main_folder = str(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), '../patcherex'))
qemu_location = shellphish_qemu.qemu_path('cgc-tracer')
self_location_folder = os.path.dirname(os.path.realpath(__file__))
backdoor_pov_location = os.path.join(self_location_folder,
                                     "../backdoor_stuff/backdoor_pov.pov")

GLOBAL_PATCH_TYPES = [
    "medium_reassembler_optimized", "medium_detour", "medium_reassembler"
]

PATCH_TYPES_WITH_RULES = []
PATCH_TYPES_WITH_BACKDOOR = [
    "medium_reassembler_optimized", "medium_detour", "medium_reassembler"
]
PATCH_TYPES_AS_ORIGINAL = []
PATCH_TYPES_EXPECTED_FAIL = [('KPRCA_00044', 'medium_reassembler'),
                             ('KPRCA_00044', 'medium_reassembler_optimized')]
コード例 #20
0
megabyte = 1024 * kilobyte
gigabyte = 1024 * megabyte

4
CHALLENGE_BLACKLIST = [
    ('finals', 'KPRCA_00064', 'pov_0'),
    ('finals', 'KPRCA_00064', 'pov_4'),
    ('qualifiers', 'KPRCA_00034', 'pov_0'),
    ('qualifiers', 'KPRCA_00034', 'pov_1'),
    ('qualifiers', 'KPRCA_00038', 'pov_4'),
    ('qualifiers', 'KPRCA_00044', 'pov_0'),
    ('qualifiers', 'KPRCA_00047', 'pov_0'),
    ('qualifiers', 'KPRCA_00047', 'pov_1'),
]

qemu_path = shellphish_qemu.qemu_path('cgc-tracer')

base_dir = DESKTOP_BASE_DIR

for event in EVENTS:
    results_dir = get_results_dir(base_dir, event)

    challenges = os.listdir(results_dir)
    for i, challenge_name in enumerate(challenges):

        print "Progress: {}/{}".format(i, len(challenges))

        binary_path = os.path.join(results_dir, challenge_name, 'bin',
                                   challenge_name)
        pov_results_dir_path = os.path.join(results_dir, challenge_name, 'pov')
コード例 #21
0
ファイル: cgc_pov_simulator.py プロジェクト: anthrax3/povsim
    def _test_binary_pov(self,
                         pov_filename,
                         cb_path,
                         enable_randomness=True,
                         debug=False,
                         bitflip=False,
                         timeout=15):
        # Test the binary pov
        # sanity checks
        if not os.path.isfile(pov_filename):
            raise ValueError("pov is does not exist")

        if not os.access(pov_filename, os.X_OK):
            raise ValueError("pov is not executable")

        if not os.path.isfile(cb_path):
            raise ValueError("cb does not exist")

        if not os.access(cb_path, os.X_OK):
            raise ValueError("cb is not executable")

        # create the communication pipes
        pov_r, pov_w = os.pipe()
        challenge_r, challenge_w = os.pipe()
        negotiation_pov, negotiation_infra = socket.socketpair()

        if self.forced_qemu == None:
            qemu_path = shellphish_qemu.qemu_path('cgc-base')
        else:
            qemu_path = self.forced_qemu

        # create directory for core files
        directory = tempfile.mkdtemp(prefix='rex-test-', dir='/tmp')
        cb_path = os.path.realpath(cb_path)

        # fork off the challenge binary
        challenge_bin_pid = os.fork()
        if challenge_bin_pid == 0:
            try:
                # cd in tempdir
                os.chdir(directory)

                # set up core dumping, only used by type1 though

                # pylint:disable=no-member
                resource.setrlimit(
                    resource.RLIMIT_CORE,
                    (resource.RLIM_INFINITY, resource.RLIM_INFINITY))

                devnull = open('/dev/null', 'w')
                # close the other entry
                os.close(pov_w)
                os.close(challenge_r)
                os.dup2(pov_r, 0)  # read from pov as stdin
                os.dup2(challenge_w, 1)  # write to the pov
                if not debug:
                    os.dup2(devnull.fileno(), 2)  # silence segfault message)
                if enable_randomness:
                    random.seed()
                    seed = str(random.randint(0, 100000))
                    argv = [
                        qemu_path, "-seed", seed, "-magicdump", "magic",
                        cb_path
                    ]
                else:
                    argv = [qemu_path, "-magicdump", "magic", cb_path]
                if bitflip:
                    argv = [argv[0]] + ["-bitflip"] + argv[1:]
                # argv = [argv[0]] + ["-d","in_asm","-D","/tmp/log1.txt","-singlestep"] + argv[1:]
                os.execve(qemu_path, argv, os.environ)
            finally:
                l.error(
                    "an exception happened in the child code (trying to run the cb)"
                )
                sys.exit(1)

            assert False, "failed to execute target binary %s" % cb_path

        # fork off the pov binary
        pov_pid = os.fork()
        if pov_pid == 0:
            try:
                # close the other entry
                os.close(pov_r)
                os.close(challenge_w)

                os.dup2(challenge_r, 0)  # read from challenge's stdout
                os.dup2(pov_w, 1)  # write to challenge's stdin

                # file descriptor 3 is the negotiation server
                os.dup2(negotiation_pov.fileno(), 3)

                random.seed()
                seed = str(random.randint(0, 100000))
                argv = [qemu_path, "-seed", seed, pov_filename]
                os.execve(qemu_path, argv, os.environ)
            finally:
                l.error(
                    "an exception happened in the child code (trying to run the pov)"
                )
                sys.exit(1)

        # clean up the pipes in the host
        os.close(challenge_r)
        os.close(challenge_w)
        os.close(pov_r)
        os.close(pov_w)

        l.debug("challenge_r: %d", challenge_r)
        l.debug("challenge_w: %d", challenge_w)
        l.debug("pov_r: %d", pov_r)
        l.debug("pov_w: %d", pov_w)
        l.debug("pov_pid: %d", pov_pid)
        l.debug("challenge_bin_pid: %d", challenge_bin_pid)

        # negiotation is specific to type1 / type2
        result = self._do_binary_negotiation(negotiation_infra, directory,
                                             challenge_bin_pid, timeout)

        # try to reap child pov, if it's not dead, kill it
        self._reap_pid(pov_pid)

        # clean up test directory
        shutil.rmtree(directory)

        return result
コード例 #22
0
ファイル: fun.py プロジェクト: Wan-YunPeng/maeg
    def __init__(self,
                 binary,
                 input=None,
                 simprocedures=None,
                 preconstrain_input=True,
                 preconstrain_flag=True,
                 resiliency=True,
                 add_options=None,
                 remove_options=None,
                 trim_history=True):
        """
        :param binary: path to the binary to be traced
        :param input: concrete input string to feed to binary
        :param povfile: CGC PoV describing the input to trace
        :param hooks: A dictionary of hooks to add
        :param simprocedures: dictionary of replacement simprocedures
        :param seed: optional seed used for randomness, will be passed to QEMU
        :param preconstrain_input: should the path be preconstrained to the
            provided input
        :param preconstrain_flag: should the path have the cgc flag page
            preconstrained
        :param resiliency: should we continue to step forward even if qemu and
            angr disagree?
        :param chroot: trace the program as though it were executing in a
            chroot
        :param add_options: add options to the state which used to do tracing
        :param remove_options: remove options from the state which is used to
            do tracing
        :param trim_history: Trim the history of a path.
        """

        self.binary = binary
        self.input = input
        self.preconstrain_input = preconstrain_input
        self.preconstrain_flag = preconstrain_flag
        self.simprocedures = {} if simprocedures is None else simprocedures
        self.resiliency = resiliency
        self.add_options = set() if add_options is None else add_options
        self.trim_history = trim_history
        self.constrained_addrs = []

        cm = LocalCacheManager(
        ) if GlobalCacheManager is None else GlobalCacheManager
        # cache managers need the tracer to be set for them
        self._cache_manager = cm
        self._cache_manager.set_tracer(self)

        # set by a cache manager
        self._loaded_from_cache = False

        if remove_options is None:
            self.remove_options = set()
        else:
            self.remove_options = remove_options

        # internal project object, useful for obtaining certain kinds of info
        self._p = angr.Project(self.binary)
        # try to find the install base
        self.os = self._p.loader.main_bin.os
        self.base = shellphish_qemu.qemu_base()
        self.tracer_qemu = "shellphish-qemu-linux-%s" % self._p.arch.qemu_name
        qemu_platform = self._p.arch.qemu_name

        self.tracer_qemu_path = shellphish_qemu.qemu_path(qemu_platform)
        self.qemu_path = {}
        self.trace = self.dynamic_trace()
コード例 #23
0
qemu_name = {
    'x86_64': None,
    'i386': 'qemu-i386',
    'ppc': 'qemu-ppc',
    'ppc64': 'qemu-ppc64',
    'armel': 'qemu-arm',
    'armhf': 'qemu-arm',
    'aarch64': 'qemu-aarch64',
    'mips': 'qemu-mips',
    'mipsel': 'qemu-mipsel',
    'mips64': 'qemu-mips64'
}

qemu_path = {
    'x86_64': None,
    'i386': shellphish_qemu.qemu_path('i386'),
    'ppc': shellphish_qemu.qemu_path('ppc'),
    'ppc64': shellphish_qemu.qemu_path('ppc64'),
    'armel': shellphish_qemu.qemu_path('arm'),
    'armhf': shellphish_qemu.qemu_path('arm'),
    'aarch64': shellphish_qemu.qemu_path('aarch64'),
    'mips': shellphish_qemu.qemu_path('mips'),
    'mipsel': shellphish_qemu.qemu_path('mipsel'),
    'mips64': shellphish_qemu.qemu_path('mips64')
}

ld_name = {
    'x86_64': 'ld-linux-x86-64.so.2',
    'i386': 'ld-linux.so.2',
    'ppc': 'ld.so.1',
    'ppc64': 'ld64.so.1',