Python idc.get_wide_byte() Examples

The following are 19 code examples of idc.get_wide_byte(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module idc , or try the search function .
Example #1
Source File: code_grafter.py    From flare-ida with Apache License 2.0 6 votes vote down vote up
def revert_patch(va, nr):
    """Unpatch the opcodes at @va, reverting them to their original value.

    Args:
        va (numbers.Integral): Address of the location of the patch to revert
        nr (numbers.Integral): Number of bytes to scan and revert

    Returns:
        bool: True if patched bytes were restored
    """
    ret = False

    orig = [ida_bytes.get_original_byte(va + i) for i in range(nr)]
    current = [idc.get_wide_byte(va + i) for i in range(nr)]

    for i in range(len(orig)):
        if orig[i] != current[i]:
            ret = True
            idaapi.patch_byte(va + i, orig[i])

    return ret 
Example #2
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 6 votes vote down vote up
def get_native_function(self):

		ecx = idc.get_reg_value("ECX")
		esp = idc.get_reg_value("ESP")

		method_name = self.get_method_name(esp)
		
		if (idc.get_wide_byte(idc.get_wide_dword(ecx + 8) + 0x38) != 0):
			function = idc.get_wide_dword(idc.get_wide_dword(esp + 4) + 0x28)
		else:
			function = idc.get_wide_dword(idc.get_wide_dword(esp + 4) + 0x24)
		
		print("Resolved native function: 0x%x - %s" % (function, method_name))

		if ((method_name not in self.ignore and not self.ignore_all) or
			(method_name in self.debug_if_equals) or 
			(any(x for x in self.debug_if_contains if method_name is not None and x in method_name))):
			self.traced.append({"name": method_name, "ea": function, "type": "native", "hit": 0})
			idc.add_bpt(function) 
Example #3
Source File: strings.py    From Karta with MIT License 6 votes vote down vote up
def nextGlobalString(self, ea):
        """Find the next possible address for a global string, given the beginning of the current global string.

        Args:
            ea (int): effective start address of the current global string.

        Return Value:
            Possible start address for the next global string
        """
        str_content = self.getAsciiString(ea)
        if str_content is None:
            return ea + self._global_alignment
        elif idc.get_wide_byte(ea + len(str_content)) != ord('\0'):
            return ea + max(self._global_alignment, pad(len(str_content), self._global_alignment))
        else:
            for offset in range(len(str_content) - 1, -1, -1):
                if chr(str_content[offset]) not in string.printable:
                    return ea + max(self._global_alignment, pad(offset, self._global_alignment))
        return ea + self._global_alignment 
Example #4
Source File: util.py    From mcsema with Apache License 2.0 6 votes vote down vote up
def read_leb128(ea, signed):
  """ Read LEB128 encoded data
  """
  val = 0
  shift = 0
  while True:
    byte = idc.get_wide_byte(ea)
    val |= (byte & 0x7F) << shift
    shift += 7
    ea += 1
    if (byte & 0x80) == 0:
      break

    if shift > 64:
      DEBUG("Bad leb128 encoding at {0:x}".format(ea - shift/7))
      return idc.BADADDR

  if signed and (byte & 0x40):
    val -= (1<<shift)
  return val, ea 
Example #5
Source File: bin_stream_ida.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def _getbytes(self, start, l=1):
        out = []
        for ad in range(l):
            offset = ad + start + self.base_address
            if not is_mapped(offset):
                raise IOError("not enough bytes")
            out.append(int_to_byte(get_wide_byte(offset)))
        return b''.join(out) 
Example #6
Source File: klfdb.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def get_func_end(self, start):

		if (idc.add_func(start)):
			return idc.find_func_end(start)

		ea = start
		while (idc.get_wide_byte(ea) != 0xCC):
			idc.create_insn(ea)
			ea += idc.get_item_size(ea)

			if (ea - start > self.jit_max_size):
				return 0

		return ea 
Example #7
Source File: swf.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def read_rect_size(li):

    nbits = idc.get_wide_byte(8) >> 3
    return ((5 + 4*nbits) + 7) / 8 
Example #8
Source File: as3.py    From ActionScript3 with GNU General Public License v3.0 5 votes vote down vote up
def read_byte(insn=None):

        if (insn):
            b = insn.get_next_byte()
        else:
            b = idc.get_wide_byte(Reader.pos)
            Reader.pos += 1
        return b 
Example #9
Source File: IdaProxy.py    From apiscout with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getByte(self, ea):
        if idaapi.IDA_SDK_VERSION < 700:
            return idc.Byte(ea)
        else:
            return idc.get_wide_byte(ea) 
Example #10
Source File: utils.py    From UEFI_RETool with MIT License 5 votes vote down vote up
def get_header_idb():
    """get file header from idb"""
    if idc.get_segm_name(0) == 'HEADER':
        header = bytearray(
            [idc.get_wide_byte(ea) for ea in range(0, idc.get_segm_end(0))])
        return header
    return bytearray(b'') 
Example #11
Source File: utils.py    From UEFI_RETool with MIT License 5 votes vote down vote up
def get_guid(address):
    """get GUID located by address"""
    guid = []
    guid.append(idc.get_wide_dword(address))
    guid.append(idc.get_wide_word(address + 4))
    guid.append(idc.get_wide_word(address + 6))
    for addr in range(address + 8, address + 16, 1):
        guid.append(idc.get_wide_byte(addr))
    return guid 
Example #12
Source File: util.py    From mcsema with Apache License 2.0 5 votes vote down vote up
def read_bytes_slowly(start, end):
  bytestr = []
  for i in xrange(start, end):
    if idc.has_value(idc.get_full_flags(i)):
      bt = idc.get_wide_byte(i)
      bytestr.append(chr(bt))
    else:
      bytestr.append("\x00")
  return "".join(bytestr) 
Example #13
Source File: function.py    From Karta with MIT License 5 votes vote down vote up
def extractFunctionTypeSample(self, ea):
        """Extract features for a "code type" sample.

        Args:
            ea (int): effective address to be sampled

        Return Value:
            feature set (list of byte values)
        """
        return list(map(lambda o: idc.get_wide_byte(ea + o), self._classifier_type_offsets)) 
Example #14
Source File: function.py    From Karta with MIT License 5 votes vote down vote up
def extractFunctionMixedSample(self, ea, code_type):
        """Extract features for a "function start/end" sample.

        Args:
            ea (int): effective address to be sampled
            code_type (int): code type of the wanted sample

        Return Value:
            feature set (list of byte values)
        """
        return list(map(lambda o: idc.get_wide_byte(ea + o), self._classifiers_mixed_offsets[code_type])) 
Example #15
Source File: function.py    From Karta with MIT License 5 votes vote down vote up
def extractFunctionEndSample(self, ea, code_type):
        """Extract features for a "function end" sample.

        Args:
            ea (int): effective address to be sampled
            code_type (int): code type of the wanted sample

        Return Value:
            feature set (list of byte values)
        """
        return list(map(lambda o: idc.get_wide_byte(ea + o), self._classifiers_end_offsets[code_type])) 
Example #16
Source File: function.py    From Karta with MIT License 5 votes vote down vote up
def extractFunctionStartSample(self, ea, code_type):
        """Extract features for a "function start" sample.

        Args:
            ea (int): effective address to be sampled
            code_type (int): code type of the wanted sample

        Return Value:
            feature set (list of byte values)
        """
        return list(map(lambda o: idc.get_wide_byte(ea + o), self._classifiers_start_offsets[code_type])) 
Example #17
Source File: pattern_observer.py    From Karta with MIT License 4 votes vote down vote up
def decide(self):
        """Sum up the information from all of the seen records, and decide what is the alignment pattern.

        Return Value:
            (alignment, pad byte) if found a full pattern, (alignment, None) if no padding, and None for errors.
        """
        # Sanity check
        if len(self._records) < 2:
            return None
        # Now check for a basic alignment rule
        seen_eas = list(map(lambda x: x[0], self._records))
        # Deterministic results per binary, but still random
        random.seed(struct.unpack("!I", ida_nalt.retrieve_input_file_md5()[:4])[0])
        while True:
            # Check against two random candidates, and always make sure the representative isn't rare
            measure_candidate = seen_eas[random.randint(0, len(seen_eas) - 1)]
            measure_candidate_alt = seen_eas[random.randint(0, len(seen_eas) - 1)]
            gcds = list(map(lambda x: gcd(measure_candidate, x), seen_eas))
            gcds_alt = list(map(lambda x: gcd(measure_candidate_alt, x), seen_eas))
            alignment = min(gcds)
            alignment_alt = min(gcds_alt)
            if alignment > alignment_alt:
                alignment = alignment_alt
                measure_candidate = measure_candidate_alt
                try_again = True
            elif alignment != alignment_alt:
                try_again = True
            else:
                try_again = False
            # Try to check if removing outliers will improve the alignment
            if try_again or gcds.count(alignment) <= len(gcds) * 0.01:
                # pick the next element, and try to improve the result
                seen_eas = list(filter(lambda x: gcd(measure_candidate, x) != alignment, seen_eas))
            # we can't improve the results
            else:
                break
        # We shouldn't look for padding bytes (we have no size)
        if self._records[0][1] is None:
            return alignment
        # Alignment is 1, there is no padding to be found
        if alignment == 1:
            return (alignment, None)
        # Check if there is a common padding byte (skip the outliers)
        pad_byte = None
        for ea, size in filter(lambda x: x[0] % alignment == 0, self._records):
            for offset in range((alignment - ((ea + size) % alignment)) % alignment):
                test_byte = idc.get_wide_byte(ea + size + offset)
                if pad_byte is None:
                    pad_byte = test_byte
                # Failed to find a single padding byte...
                elif pad_byte != test_byte:
                    return (alignment, None)
        # Found a padding byte :)
        if pad_byte is not None:
            return (alignment, pad_byte)
        # There were no gaps to be padded, no padding is needed
        else:
            return (alignment, None) 
Example #18
Source File: analyser.py    From UEFI_RETool with MIT License 4 votes vote down vote up
def get_data_guids(self):
        """rename GUIDs in idb"""
        EFI_GUID = 'EFI_GUID *'
        EFI_GUID_ID = idc.get_struc_id('EFI_GUID')
        segments = ['.text', '.data']
        for segment in segments:
            seg_start, seg_end = 0, 0
            for seg in idautils.Segments():
                if idc.get_segm_name(seg) == segment:
                    seg_start = idc.get_segm_start(seg)
                    seg_end = idc.get_segm_end(seg)
                    break
            ea = seg_start
            while (ea <= seg_end - 15):
                prot_name = ''
                if idc.get_name(ea, ida_name.GN_VISIBLE).find('unk_') != -1:
                    find = False
                    cur_guid = []
                    cur_guid.append(idc.get_wide_dword(ea))
                    cur_guid.append(idc.get_wide_word(ea + 4))
                    cur_guid.append(idc.get_wide_word(ea + 6))
                    for addr in range(ea + 8, ea + 16, 1):
                        cur_guid.append(idc.get_wide_byte(addr))
                    if cur_guid == [0] * 11:
                        ea += 1
                        continue
                    for guid_place in [
                            'ami_guids', 'asrock_guids', 'dell_guids',
                            'edk_guids', 'edk2_guids', 'lenovo_guids'
                    ]:
                        for name in self.Protocols[guid_place]:
                            if self.Protocols[guid_place][name] == cur_guid:
                                prot_name = '{}_{:#x}'.format(name, ea)
                                record = {
                                    'address': ea,
                                    'service': 'unknown',
                                    'guid': cur_guid,
                                    'protocol_name': name,
                                    'protocol_place': guid_place
                                }
                                find = True
                                break
                            if find:
                                break
                    if find and (idc.get_name(ea, ida_name.GN_VISIBLE) !=
                                 prot_name):
                        idc.SetType(ea, EFI_GUID)
                        self.apply_struct(ea, 16, EFI_GUID_ID)
                        idc.set_name(ea, prot_name)
                        self.Protocols['data'].append(record)
                ea += 1 
Example #19
Source File: strings.py    From Karta with MIT License 4 votes vote down vote up
def isLocalAsciiString(self, ea, check_refs=True):
        r"""Check if the given address is the beginning of a valid local string.

        Args:
            ea (int): effective address to be checked

        Notes
        -----
            0. If selected, the string must have a data reference to it.
            1. The string should be aligned (local alignment).
            2. The string should only contain chars from our alpha-bet.
            3. The string should be '\0' terminated.
            4. If applicable, the string should be padded with the correct padding byte.
            5. The string's length must follow one of the following rules:
                a) Larger than the local alignment.
                b) At least 2 bytes, and the first is '%' (for short format strings).
                c) Exactly one byte, and it should be a punctuation char.
                d) At least 3 bytes.

        Return Value:
            True iff the given address could be the start of a local string
        """
        # line should be referenced (as data)
        if check_refs and not self._analyzer.locals_identifier.isDataConstant(ea):
            return False
        str_content = self.getAsciiString(ea)
        # check each of the chars
        if str_content is None or len(list(filter(lambda x: chr(x) in self._valid_alphabet, str_content))) != len(str_content):
            return False
        # check for a '\0' terminator
        if idc.get_wide_byte(ea + len(str_content)) != ord('\0'):
            return False
        # check for the correct padding
        if self._local_pad is not None:
            end_address = ea + len(str_content) + 1
            for offset in range(padSize(end_address, self._local_alignment)):
                if idc.get_wide_byte(end_address + offset) != self._local_pad:
                    return False
        # filtering heuristic
        if len(str_content) > self._local_alignment:
            return True
        elif len(str_content) > 1 and chr(str_content[0]) == '%':
            return True
        elif len(str_content) == 1 and chr(str_content[0]) in string.punctuation:
            return True
        else:
            return len(str_content) > 2

    # TODO: unused for now