Exemple #1
0
    def display_pmd_info_strings(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            return

        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data)
                   and not 32 <= byte2int(data[dataptr]) <= 127):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            # pyelftools may return byte-strings, force decode them
            mystring = force_unicode(data[dataptr:endptr])
            rc = mystring.find("PMD_INFO_STRING")
            if rc != -1:
                self.parse_pmd_info_string(mystring[rc:])

            dataptr = endptr
Exemple #2
0
    def search_for_autoload_path(self):
        scanelf = self
        scanfile = None
        library = None

        section = self._section_from_spec(".dynamic")
        try:
            eallib = self.find_librte_eal(section)
            if eallib is not None:
                ldlibpath = os.environ.get('LD_LIBRARY_PATH')
                if ldlibpath is None:
                    ldlibpath = ""
                dtr = self.get_dt_runpath(section)
                library = search_file(
                    eallib,
                    dtr + ":" + ldlibpath + ":/usr/lib64:/lib64:/usr/lib:/lib")
                if library is None:
                    return (None, None)
                if raw_output is False:
                    print("Scanning for autoload path in %s" % library)
                scanfile = open(library, 'rb')
                scanelf = ReadElf(scanfile, sys.stdout)
        except AttributeError:
            # Not a dynamic binary
            pass
        except ELFError:
            scanfile.close()
            return (None, None)

        section = scanelf._section_from_spec(".rodata")
        if section is None:
            if scanfile is not None:
                scanfile.close()
            return (None, None)

        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data)
                   and not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            mystring = bytes2str(data[dataptr:endptr])
            rc = mystring.find("DPDK_PLUGIN_PATH")
            if (rc != -1):
                rc = mystring.find("=")
                return (mystring[rc + 1:], library)

            dataptr = endptr
        if scanfile is not None:
            scanfile.close()
        return (None, None)
Exemple #3
0
    def display_string_dump(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = _section_from_spec(self.elf_file, section_spec)
        if section is None:
            print("Section '%s' does not exist in the file!" % section_spec)
            return None

        data = section.data()
        dataptr = 0

        strs = []
        while dataptr < len(data):
            while dataptr < len(data) and not 32 <= byte2int(
                    data[dataptr]) <= 127:
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            strs.append(
                binascii.b2a_hex(data[dataptr:endptr]).decode().upper())
            dataptr = endptr

        return strs
Exemple #4
0
    def display_pmd_info_strings(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            return

        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data)
                   and not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            mystring = bytes2str(data[dataptr:endptr])
            rc = mystring.find("PMD_INFO_STRING")
            if (rc != -1):
                self.parse_pmd_info_string(mystring)

            dataptr = endptr
Exemple #5
0
    def search_for_autoload_path(self):
        scanelf = self
        scanfile = None
        library = None

        section = self._section_from_spec(".dynamic")
        try:
            eallib = self.find_librte_eal(section)
            if eallib is not None:
                ldlibpath = os.environ.get('LD_LIBRARY_PATH')
                if ldlibpath is None:
                    ldlibpath = ""
                dtr = self.get_dt_runpath(section)
                library = search_file(eallib,
                                      dtr + ":" + ldlibpath +
                                      ":/usr/lib64:/lib64:/usr/lib:/lib")
                if library is None:
                    return (None, None)
                if raw_output is False:
                    print("Scanning for autoload path in %s" % library)
                scanfile = open(library, 'rb')
                scanelf = ReadElf(scanfile, sys.stdout)
        except AttributeError:
            # Not a dynamic binary
            pass
        except ELFError:
            scanfile.close()
            return (None, None)

        section = scanelf._section_from_spec(".rodata")
        if section is None:
            if scanfile is not None:
                scanfile.close()
            return (None, None)

        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data) and
                    not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            mystring = bytes2str(data[dataptr:endptr])
            rc = mystring.find("DPDK_PLUGIN_PATH")
            if (rc != -1):
                rc = mystring.find("=")
                return (mystring[rc + 1:], library)

            dataptr = endptr
        if scanfile is not None:
            scanfile.close()
        return (None, None)
Exemple #6
0
    def display_pmd_info_strings(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            return

        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data) and
                    not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            mystring = bytes2str(data[dataptr:endptr])
            rc = mystring.find("PMD_INFO_STRING")
            if (rc != -1):
                self.parse_pmd_info_string(mystring)

            dataptr = endptr
Exemple #7
0
    def elf_file_header(self):
        elf_header = {}

        def add_info(key, value):
            elf_header[key] = value

        header = self.elffile.header
        e_ident = header['e_ident']

        add_info(
            'Magic',
            ' '.join('%2.2x' % byte2int(b) for b in self.elffile.e_ident_raw))
        add_info('Class', describe_ei_class(e_ident['EI_CLASS']))
        add_info('Data', describe_ei_data(e_ident['EI_DATA']))
        add_info('Version', e_ident['EI_VERSION'])
        add_info('OS/ABI', describe_ei_osabi(e_ident['EI_OSABI']))
        add_info('ABI Version', e_ident['EI_ABIVERSION'])
        add_info('Type', describe_e_type(header['e_type']))
        add_info('Machine', describe_e_machine(header['e_machine']))
        add_info('Version_e', describe_e_version_numeric(header['e_version']))
        add_info('Entry point address', self._format_hex(header['e_entry']))
        add_info('Start of program headers', header['e_phoff'])
        add_info('Start of section headers', header['e_shoff'])
        add_info('Flags', [
            self._format_hex(header['e_flags']),
            self.decode_flags(header['e_flags'])
        ])
        add_info('Size of this header', header['e_ehsize'])
        add_info('Size of program headers', header['e_phentsize'])
        add_info('Number of program headers', header['e_phnum'])
        add_info('Size of section headers', header['e_shentsize'])
        add_info('Number of section headers', header['e_shnum'])
        add_info('Section header string table index', header['e_shstrndx'])

        return elf_header
Exemple #8
0
    def display_hex_dump(self, section_spec):
        """ Display a hex dump of a section. section_spec is either a section
            number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            self._emitline("Section '%s' does not exist in the file!" %
                           (section_spec))
            return

        self._emitline("\nHex dump of section '%s':" % bytes2str(section.name))
        self._note_relocs_for_section(section)
        addr = section['sh_addr']
        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            bytesleft = len(data) - dataptr
            # chunks of 16 bytes per line
            linebytes = 16 if bytesleft > 16 else bytesleft

            self._emit('  %s ' % self._format_hex(addr, fieldsize=8))
            for i in range(16):
                if i < linebytes:
                    self._emit('%2.2x' % byte2int(data[dataptr + i]))
                else:
                    self._emit('  ')
                if i % 4 == 3:
                    self._emit(' ')

            for i in range(linebytes):
                c = data[dataptr + i:dataptr + i + 1]
                if byte2int(c[0]) >= 32 and byte2int(c[0]) < 0x7f:
                    self._emit(bytes2str(c))
                else:
                    self._emit(bytes2str(b'.'))

            self._emitline()
            addr += linebytes
            dataptr += linebytes

        self._emitline()
Exemple #9
0
    def display_hex_dump(self, section_spec):
        """ Display a hex dump of a section. section_spec is either a section
            number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            self._emitline("Section '%s' does not exist in the file!" % (
                section_spec))
            return

        self._emitline("\nHex dump of section '%s':" % bytes2str(section.name))
        self._note_relocs_for_section(section)
        addr = section['sh_addr']
        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            bytesleft = len(data) - dataptr
            # chunks of 16 bytes per line
            linebytes = 16 if bytesleft > 16 else bytesleft

            self._emit('  %s ' % self._format_hex(addr, fieldsize=8))
            for i in range(16):
                if i < linebytes:
                    self._emit('%2.2x' % byte2int(data[dataptr + i]))
                else:
                    self._emit('  ')
                if i % 4 == 3:
                    self._emit(' ')

            for i in range(linebytes):
                c = data[dataptr + i : dataptr + i + 1]
                if byte2int(c[0]) >= 32 and byte2int(c[0]) < 0x7f:
                    self._emit(bytes2str(c))
                else:
                    self._emit(bytes2str(b'.'))

            self._emitline()
            addr += linebytes
            dataptr += linebytes

        self._emitline()
Exemple #10
0
def display_elf_fh(elf, out):
    header = elf.header
    e_ident = header['e_ident']
    if (out == "None"):
        print("\n----------ELF_HEADER----------")
        print("Magic:                             {}".format(' '.join('%2.2x' % byte2int(b) for b in elf.e_ident_raw)))
        print("Class:                             {}".format(describe_ei_class(e_ident['EI_CLASS'])))
        print("Data:                              {}".format(describe_ei_data(e_ident['EI_DATA'])))
        print("Version:                           {}".format(describe_ei_version(e_ident['EI_VERSION'])))
        print("OS | ABI:                          {}".format(describe_ei_osabi(e_ident['EI_OSABI'])))
        print("ABI version:                       {}".format(e_ident['EI_ABIVERSION']))
        print("Type:                              {}".format(describe_e_type(header['e_type'])))
        print("Machine:                           {}".format(describe_e_machine(header['e_machine'])))
        print("Version:                           {}".format(describe_e_version_numeric(header['e_version'])))
        print("Entry Point:                       {}".format(_format_hex(header['e_entry'], elf)))
        print("Program Header Start:              {} (bytes in)".format(header['e_phoff']))
        print("Section Header Start:              {} (bytes in)".format(header['e_shoff']))
        print("Flags:                             {}{}".format(_format_hex(header['e_flags'], elf), decode_flags(header['e_flags'], elf)))
        print("Header Size:                       {}".format(header['e_ehsize']))
        print("Program Headers Size:              {}".format(header['e_phentsize']))
        print("Program Header Count:              {}".format(header['e_phnum']))
        print("Section Headers Size:              {}".format(header['e_shentsize']))
        print("Section Header Count:              {}".format(header['e_shnum']))
        print("Section Header String Table Index: {}".format(header['e_shstrndx']))
    else:
        try:
            with open(str(out, "utf-8"), "w") as outfile:
                outfile.write("----------ELF_HEADER----------\n")
                outfile.write("Magic:                             {}\n".format(' '.join('%2.2x' % byte2int(b) for b in elf.e_ident_raw)))
                outfile.write("Class:                             {}\n".format(describe_ei_class(e_ident['EI_CLASS'])))
                outfile.write("Data:                              {}\n".format(describe_ei_data(e_ident['EI_DATA'])))
                outfile.write("Version:                           {}\n".format(describe_ei_version(e_ident['EI_VERSION'])))
                outfile.write("OS | ABI:                          {}\n".format(describe_ei_osabi(e_ident['EI_OSABI'])))
                outfile.write("ABI version:                       {}\n".format(e_ident['EI_ABIVERSION']))
                outfile.write("Type:                              {}\n".format(describe_e_type(header['e_type'])))
                outfile.write("Machine:                           {}\n".format(describe_e_machine(header['e_machine'])))
                outfile.write("Version:                           {}\n".format(describe_e_version_numeric(header['e_version'])))
                outfile.write("Entry Point:                       {}\n".format(_format_hex(header['e_entry'], elf)))
                outfile.write("Program Header Start:              {} (bytes in)\n".format(header['e_phoff']))
                outfile.write("Section Header Start:              {} (bytes in)\n".format(header['e_shoff']))
                outfile.write("Flags:                             {}{}\n".format(_format_hex(header['e_flags'], elf), decode_flags(header['e_flags'], elf)))
                outfile.write("Header Size:                       {}\n".format(header['e_ehsize']))
                outfile.write("Program Headers Size:              {}\n".format(header['e_phentsize']))
                outfile.write("Program Header Count:              {}\n".format(header['e_phnum']))
                outfile.write("Section Headers Size:              {}\n".format(header['e_shentsize']))
                outfile.write("Section Header Count:              {}\n".format(header['e_shnum']))
                outfile.write("Section Header String Table Index: {}\n".format(header['e_shstrndx']))
                outfile.close()
        except PermissionError as pErr:
        	print("[Disassimpl][MAIN] - Permission denied on file")
        	return False
        except Exception as e:
            print("[Disassimpl][MAIN] - Error {}".format(e))
            return False
Exemple #11
0
    def display_string_dump(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            self._emitline("Section '%s' does not exist in the file!" %
                           (section_spec))
            return

        self._emitline("\nString dump of section '%s':" %
                       bytes2str(section.name))

        found = False
        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while (dataptr < len(data)
                   and not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            found = True
            self._emitline('  [%6x]  %s' %
                           (dataptr, bytes2str(data[dataptr:endptr])))

            dataptr = endptr

        if not found:
            self._emitline('  No strings found in this section.')
        else:
            self._emitline()
Exemple #12
0
    def display_string_dump(self, section_spec):
        """ Display a strings dump of a section. section_spec is either a
            section number or a name.
        """
        section = self._section_from_spec(section_spec)
        if section is None:
            self._emitline("Section '%s' does not exist in the file!" % (
                section_spec))
            return

        self._emitline("\nString dump of section '%s':" % bytes2str(section.name))

        found = False
        data = section.data()
        dataptr = 0

        while dataptr < len(data):
            while ( dataptr < len(data) and
                    not (32 <= byte2int(data[dataptr]) <= 127)):
                dataptr += 1

            if dataptr >= len(data):
                break

            endptr = dataptr
            while endptr < len(data) and byte2int(data[endptr]) != 0:
                endptr += 1

            found = True
            self._emitline('  [%6x]  %s' % (
                dataptr, bytes2str(data[dataptr:endptr])))

            dataptr = endptr

        if not found:
            self._emitline('  No strings found in this section.')
        else:
            self._emitline()
Exemple #13
0
 def display_file_header(self):
     """ Display the ELF file header
     """
     self._emitline('ELF Header:')
     self._emit('  Magic:   ')
     self._emitline(' '.join('%2.2x' % byte2int(b)
                                 for b in self.elffile.e_ident_raw))
     header = self.elffile.header
     e_ident = header['e_ident']
     self._emitline('  Class:                             %s' %
             describe_ei_class(e_ident['EI_CLASS']))
     self._emitline('  Data:                              %s' %
             describe_ei_data(e_ident['EI_DATA']))
     self._emitline('  Version:                           %s' %
             describe_ei_version(e_ident['EI_VERSION']))
     self._emitline('  OS/ABI:                            %s' %
             describe_ei_osabi(e_ident['EI_OSABI']))
     self._emitline('  ABI Version:                       %d' %
             e_ident['EI_ABIVERSION'])
     self._emitline('  Type:                              %s' %
             describe_e_type(header['e_type']))
     self._emitline('  Machine:                           %s' %
             describe_e_machine(header['e_machine']))
     self._emitline('  Version:                           %s' %
             describe_e_version_numeric(header['e_version']))
     self._emitline('  Entry point address:               %s' %
             self._format_hex(header['e_entry']))
     self._emit('  Start of program headers:          %s' %
             header['e_phoff'])
     self._emitline(' (bytes into file)')
     self._emit('  Start of section headers:          %s' %
             header['e_shoff'])
     self._emitline(' (bytes into file)')
     self._emitline('  Flags:                             %s%s' %
             (self._format_hex(header['e_flags']),
             self.decode_flags(header['e_flags'])))
     self._emitline('  Size of this header:               %s (bytes)' %
             header['e_ehsize'])
     self._emitline('  Size of program headers:           %s (bytes)' %
             header['e_phentsize'])
     self._emitline('  Number of program headers:         %s' %
             header['e_phnum'])
     self._emitline('  Size of section headers:           %s (bytes)' %
             header['e_shentsize'])
     self._emitline('  Number of section headers:         %s' %
             header['e_shnum'])
     self._emitline('  Section header string table index: %s' %
             header['e_shstrndx'])
Exemple #14
0
 def display_file_header(self):
     """ Display the ELF file header
     """
     self._emitline('ELF Header:')
     self._emit('  Magic:   ')
     self._emitline(' '.join('%2.2x' % byte2int(b)
                             for b in self.elffile.e_ident_raw))
     header = self.elffile.header
     e_ident = header['e_ident']
     self._emitline('  Class:                             %s' %
                    describe_ei_class(e_ident['EI_CLASS']))
     self._emitline('  Data:                              %s' %
                    describe_ei_data(e_ident['EI_DATA']))
     self._emitline('  Version:                           %s' %
                    describe_ei_version(e_ident['EI_VERSION']))
     self._emitline('  OS/ABI:                            %s' %
                    describe_ei_osabi(e_ident['EI_OSABI']))
     self._emitline('  ABI Version:                       %d' %
                    e_ident['EI_ABIVERSION'])
     self._emitline('  Type:                              %s' %
                    describe_e_type(header['e_type']))
     self._emitline('  Machine:                           %s' %
                    describe_e_machine(header['e_machine']))
     self._emitline('  Version:                           %s' %
                    describe_e_version_numeric(header['e_version']))
     self._emitline('  Entry point address:               %s' %
                    self._format_hex(header['e_entry']))
     self._emit('  Start of program headers:          %s' %
                header['e_phoff'])
     self._emitline(' (bytes into file)')
     self._emit('  Start of section headers:          %s' %
                header['e_shoff'])
     self._emitline(' (bytes into file)')
     self._emitline('  Flags:                             %s' %
                    self._format_hex(header['e_flags']))
     self._emitline('  Size of this header:               %s (bytes)' %
                    header['e_ehsize'])
     self._emitline('  Size of program headers:           %s (bytes)' %
                    header['e_phentsize'])
     self._emitline('  Number of program headers:         %s' %
                    header['e_phnum'])
     self._emitline('  Size of section headers:           %s (bytes)' %
                    header['e_shentsize'])
     self._emitline('  Number of section headers:         %s' %
                    header['e_shnum'])
     self._emitline('  Section header string table index: %s' %
                    header['e_shstrndx'])
def return_parsed_section(filename, secname):
    with open(filename, 'rb') as f:
        elffile = ELFFile(f)
        
        #ll=elffile.iter_sections()        
        #for x in ll:
        #    print x.name
            
        section=elffile.get_section_by_name(str2bytes(secname))

        if section is None:
            print 'ERROR! Section '+secname+' does not exist in the file!'

        #print 'Name of section is: '+bytes2str(section.name)
        
        ##assuming no relocation section for now
        #self._note_relocs_for_section(section)
        addr = section['sh_addr']
        data = section.data()
        dataptr = 0
        
        
        setStartAddress('  %s ' % _format_hex(addr, elffile, fieldsize=8 ))        
                    
        toreturn=[]
        while dataptr < len(data):
            bytesleft = len(data) - dataptr
            # chunks of 16 bytes per line
            linebytes = 16 if bytesleft > 16 else bytesleft

            #not adding addresses in beginning of 4 * 4 bytes
            #toreturn+='  %s ' % _format_hex(addr, elffile, fieldsize=8 )
            for i in range(16):
                if i < linebytes:
                    toreturn.append('%2.2x' % byte2int(data[dataptr + i]))
                else:
                    pass
                    #not doing anything
                    #toreturn+='  '
                if i % 4 == 3:
                    pass
                    #not doing anything  
                    #toreturn+=' '

            for i in range(linebytes):
                c = data[dataptr + i : dataptr + i + 1]
                if byte2int(c[0]) >= 32 and byte2int(c[0]) < 0x7f:
                    pass
                    #removing not used info 
                    #toreturn+=bytes2str(c)
                else:
                    pass
                    #removing not used info
                    #toreturn+=(bytes2str(b'.'))

            #again not adding string or newline
            #toreturn+='\n'
            addr += linebytes
            dataptr += linebytes
        
        for x in range(len(toreturn)%4):
            toreturn.append('')        
        
        if toreturn==[]:
            print'No data to display in '+secname+' section'
            return
        global little
        little=isLittleEndian(elffile)
        finalreturn= arrangeData(toreturn, isLittleEndian(elffile))
        setNumOfInst(len(finalreturn))
        return finalreturn
Exemple #16
0
def return_parsed_section(filename, secname):
    with open(filename, 'rb') as f:
        elffile = ELFFile(f)

        #ll=elffile.iter_sections()
        #for x in ll:
        #    print x.name

        section = elffile.get_section_by_name(str2bytes(secname))

        if section is None:
            print 'ERROR! Section ' + secname + ' does not exist in the file!'

        #print 'Name of section is: '+bytes2str(section.name)

        ##assuming no relocation section for now
        #self._note_relocs_for_section(section)
        addr = section['sh_addr']
        data = section.data()
        dataptr = 0

        setStartAddress('  %s ' % _format_hex(addr, elffile, fieldsize=8))

        toreturn = []
        while dataptr < len(data):
            bytesleft = len(data) - dataptr
            # chunks of 16 bytes per line
            linebytes = 16 if bytesleft > 16 else bytesleft

            #not adding addresses in beginning of 4 * 4 bytes
            #toreturn+='  %s ' % _format_hex(addr, elffile, fieldsize=8 )
            for i in range(16):
                if i < linebytes:
                    toreturn.append('%2.2x' % byte2int(data[dataptr + i]))
                else:
                    pass
                    #not doing anything
                    #toreturn+='  '
                if i % 4 == 3:
                    pass
                    #not doing anything
                    #toreturn+=' '

            for i in range(linebytes):
                c = data[dataptr + i:dataptr + i + 1]
                if byte2int(c[0]) >= 32 and byte2int(c[0]) < 0x7f:
                    pass
                    #removing not used info
                    #toreturn+=bytes2str(c)
                else:
                    pass
                    #removing not used info
                    #toreturn+=(bytes2str(b'.'))

            #again not adding string or newline
            #toreturn+='\n'
            addr += linebytes
            dataptr += linebytes

        for x in range(len(toreturn) % 4):
            toreturn.append('')

        if toreturn == []:
            print 'No data to display in ' + secname + ' section'
            return
        global little
        little = isLittleEndian(elffile)
        finalreturn = arrangeData(toreturn, isLittleEndian(elffile))
        setNumOfInst(len(finalreturn))
        return finalreturn