Ejemplo n.º 1
0
def main():
    disas_path = idc.AskFile(1, '*.disas', 'Save basic blocks')
    do_exit = False

    if not disas_path:
        basename = idc.GetInputFile()
        disas_path = '%s.disas' % basename
        idc.GenerateFile(idc.OFILE_ASM, '%s.asm' % basename, 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, '%s.lst' % basename, 0, idc.BADADDR, 0)
        do_exit = True

    # Get basic blocks
    bbs = _get_basic_blocks()

    # Get the module's base address
    base_addr = idaapi.get_imagebase()

    # Get the module's end address
    segs = sorted(idautils.Segments())
    end_addr = idc.SegEnd(segs[-1])

    disas_info = {
        'bbs': bbs,
        'base_addr': base_addr,
        'end_addr': end_addr,
    }

    with open(disas_path, 'w') as disas_file:
        json.dump(disas_info, disas_file)

    if do_exit:
        idc.Exit(0)
Ejemplo n.º 2
0
def extract_bbs():
    filename = idc.AskFile(1, "*.*", "Save list of basic blocks")
    exit = False
    if not filename:
        basename = idc.GetInputFile()
        filename = basename + ".bblist"
        idc.GenerateFile(idc.OFILE_ASM, basename + ".asm", 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, basename + ".lst", 0, idc.BADADDR, 0)
        exit = True
    fp = open(filename, 'w')
    funcs = idautils.Functions()
    for f in funcs:
        cls_main(fp, f)
    if exit:
        idc.Exit(0)
Ejemplo n.º 3
0
def extract_functions():
    filename = idc.AskFile(1, "*.*", "Save list of functions")
    exit = False
    if not filename:
        basename = idc.GetInputFile()
        filename = basename + ".fcn"
        idc.GenerateFile(idc.OFILE_ASM, basename + ".asm", 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, basename + ".lst", 0, idc.BADADDR, 0)
        exit = True
    fp = open(filename, 'w')
    funcs = idautils.Functions()
    for f in funcs:
        print >> fp, "%#010x %s" % (f, GetFunctionName(f))
    if exit:
        idc.Exit(0)
Ejemplo n.º 4
0
def save_file(output_file):
    """ Save the patched file """
    DIFF_RE = re.compile(r'([A-F0-9]+): ([A-F0-9]+) ([A-F0-9]+)')

    idc.GenerateFile(idaapi.OFILE_DIF, output_file, 0, idc.MaxEA(), 0)
    diff_file = open(output_file, "rb").read()
    orig_file = open(idc.GetInputFilePath(), "rb").read()
    print "OK"
    diff_file = diff_file.split("\n")
    total = 0
    success = 0
    for line in diff_file:
        match = DIFF_RE.match(line)
        if match:
            groups = match.groups()
            total += 1
            offset = int(groups[0], 16)
            orig_byte = groups[1].decode('hex')
            new_byte = groups[2].decode('hex')
            if orig_file[offset] == orig_byte:
                orig_file = orig_file[:offset] + new_byte + orig_file[offset +
                                                                      1:]
                success += 1
            else:
                print "Error matching %02x at offset %x..." % (groups[1],
                                                               offset)

    new_file = open(output_file, 'wb')
    new_file.write(orig_file)
    new_file.close()
    print "%i/%i patches applied" % (success, total)
Ejemplo n.º 5
0
def extract_bbs():
    filename = idc.AskFile(1, '*.*', 'Save list of basic blocks')
    do_exit = False

    if not filename:
        basename = idc.GetInputFile()
        filename = '%s.bblist' % basename
        idc.GenerateFile(idc.OFILE_ASM, '%s.asm' % basename, 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, '%s.lst' % basename, 0, idc.BADADDR, 0)
        do_exit = True

    with open(filename, 'w') as fp:
        funcs = idautils.Functions()
        for func in funcs:
            cls_main(fp, func)

    if do_exit:
        idc.Exit(0)
Ejemplo n.º 6
0
    def export(self, filename='', type='LIST'):
        if filename == '':
            filename = idc.GetInputFile() + ".lst"

        tmp_filename = 'tmp.lst'
        idc.GenerateFile(idc.OFILE_LST, tmp_filename, 0, idc.BADADDR, 0)

        rfd = open(tmp_filename, 'r')
        fd = open(filename, 'a')
        fd.write(rfd.read())
        rfd.close()
        fd.close()
Ejemplo n.º 7
0
def controller():
    funcs_id = dict()  # to store functions and their IDs
    callees = dict()
    func_num = 0
    func_id = 0
    cg_adjmat = []
    info_filename = idc.AskFile(1, "*.*", "Extract Binary File Info")

    basename = idc.GetInputFile()
    info_filename = basename + ".info"
    asm_filename = basename + ".asm"
    asmplus_filename = basename + ".asmplus"
    idc.GenerateFile(idc.OFILE_ASM, basename + ".asm", 0, idc.BADADDR, 0)
    idc.GenerateFile(idc.OFILE_LST, basename + ".asmplus", 0, idc.BADADDR, 0)

    output_file = open(info_filename, 'w')
    asm_file = open(asm_filename, 'r')
    asmplus_file = open(asm_filename, 'r')

    funcs = idautils.Functions()
    funcs_iterator = idautils.Functions()

    # scan all functions to extract number of functions and add them to the funcs_id
    for i in funcs_iterator:
        func_name = GetFunctionName(i)
        funcs_id.update({func_name: func_id})
        func_num += 1
        func_id += 1
        cg_adjmat.append([])

    for f in funcs:
        func_name = GetFunctionName(f)
        function_extract(output_file, f, cg_adjmat, funcs_id, callees,
                         asm_filename)  # extract functions data
        BB_extract(
            output_file, f, asmplus_filename
        )  # extract basic blocks data, CFG and CFG adjacency matrices

    cg_extract(output_file, cg_adjmat, funcs_id, callees,
               func_num)  # extract CG and CG adjacency matrix
Ejemplo n.º 8
0
        generateDefFile(outdef, eps)

        outstub = path.join(outpath, "{0}_exportstub.c".format(myname))
        sys.stdout.write("Output export stub file: {0}\n".format(outstub))
        generateExportStub(outstub, eps)

        outbat = path.join(outpath, "{0}.bat".format(myname))
        sys.stdout.write("Output build .BAT: {0}\n".format(outbat))
        generateBatFile(outbat, eps)


    if args.output:
        outf = args.output
    else:
        cfgname = path.join(outpath, myname + "_ida.cfg")
        cfgpath = path.join(outpath, cfgname)
        outf = open(cfgpath, 'wb')

    sys.stdout.write("CFG Output File file: {0}\n".format(outf.name))
    recoverCfg(eps, outf, args.exports_are_apis)

    lstfile = os.path.join(outpath, os.path.basename(myname)) + '.lst'

    if args.generate_lst:
        idc.GenerateFile(idc.OFILE_LST, lstfile, 0, idc.BADADDR, 0)

    #for batch mode: exit IDA when done
    if args.batch:
        idc.Exit(0)

Ejemplo n.º 9
0
import idautils
import idc

for ea in idautils.Segments():

    segend = idc.GetSegmentAttr(ea, idc.SEGATTR_END)
    start = ea
    while start < segend:
        idc.MakeCode(start)
        start = idc.FindUnexplored(start + 1, idc.SEARCH_DOWN)

idc.GenerateFile(idc.OFILE_ASM, idc.GetInputFile() + ".asm", 0, idc.BADADDR, 0)

idc.Exit(0)

# Here it is. Run it with idal -c -A -S./script.py ./test.bin
Ejemplo n.º 10
0
    sys.stdout = sys.stderr = ToFileStdOut(
        os.path.join(outputDir, "stdout.txt"))
    print "Starting analysis..."

    output_json = args.json

    if args.flirt_sig is not None:
        idc.ApplySig(args.flirt_sig)

    idc.Wait()

    basename = os.path.join(outputDir, idc.GetInputFile())

    bb_printer = BasicBlockPrinter()
    bb_extractor = BasicBlockExtractor(basename + ".bbinfo")
    cfg_extractor = CFGExtractor(basename + ".cfg")

    scanner = BBScanner()
    scanner.add_callback(bb_printer)
    scanner.add_callback(bb_extractor)
    scanner.add_callback(cfg_extractor)
    scanner.scan()

    #Generate the final assembly after more advanced decoding
    #and analysis is done
    if args.generate_lst:
        idc.GenerateFile(idc.OFILE_LST, basename + ".lst", 0, idc.BADADDR, 0)

    idc.Exit(0)
Ejemplo n.º 11
0
names = map(lambda x : x[0], idautils.Names())
names = filter(lambda x : idc.isData(idc.GetFlags(x)), names)

for n in names:
  idc.MakeUnknown(n, 1, 0)

with open(basename + ".cfg", "w") as out:
    prev = sys.stdout
    sys.stdout = out # comment to dump the json into console
    get_file_range()
    print ("{")
    print ("  segments:[")
    print_section_list()
    print ("  ],")
    print ("  cli:[")
    print ("    \"-parse\", \"%s.asm\"," % (basename))
    print ("    \"-save\",  \"%s.cico\"," % (basename))
    print ("    \"-load\",  \"%s.cico\"," % (basename))
    print ("    \"-functions\", \"all\",")
    print ("    \"-export\", \"%s.cpp\" " % (basename))
    print ("  ],")
    print ("  hints:{")
    print ("    start:{comment:\"Entry function\"},")
    print ("  }")
    print ("}")
    sys.stdout = prev
    print ("Cico configuration generated in %s.cfg" % basename)

idc.GenerateFile(idc.OFILE_ASM, basename+".asm", 0, idc.BADADDR, 0)
print("Assembly generated in %s" % (basename+".asm"))