示例#1
0
def FileFactory(filename, session=None):
    """Return the correct FileInformation class from the filename.

    Currently we only support OS API accessible files, but in the future we will
    also support NTFS files.
    """
    # Ensure this is a valid file spec.
    filespec = FileSpec(filename)

    handler = FILE_SPEC_DISPATCHER.get(filespec.filesystem)
    if handler:
        try:
            return handler.from_stat(filespec, session=session)
        except (IOError, OSError):

            return obj.NoneObject("Cant open %s", filespec)

    raise RuntimeError("Unsupported file spec type %s" % filespec.filesystem)
示例#2
0
    def live(self):
        phys_as = obj.NoneObject("Unable to access physical memory")

        if self.plugin_args.mode == "Memory":
            try:
                phys_as = pmem.MacPmemAddressSpace(
                    session=self.session, filename=self.plugin_args.device)
            except IOError as e:
                self.session.logging.debug("%s", e)
                self.load_driver()
                phys_as = pmem.MacPmemAddressSpace(
                    session=self.session, filename=self.plugin_args.device)

        self.session.physical_address_space = phys_as
        with self.session:
            self.session.SetParameter("live_mode", self.plugin_args.mode)
            self.session.SetParameter("session_name",
                                      "Live (%s)" % self.plugin_args.mode)
示例#3
0
    def reflect(self, vm=None):
        """Reflect this list element by following its Flink and Blink.

        This is basically the same as Flink.Blink except that it also checks
        Blink.Flink. It also ensures that Flink and Blink are dereferences to
        the correct type in case the vtypes do not specify them as pointers.

        Returns:
          the result of Flink.Blink.
        """
        result = self.m(self._forward).dereference_as(
            self.obj_type, vm=vm).m(self._backward).dereference_as(
                self.obj_type)

        if not result:
            return obj.NoneObject("Flink not valid.")

        return result
示例#4
0
文件: plugin.py 项目: scudette/rekall
    def GetActivePlugin(self, plugin_name):
        results = []
        for command_metadata in self.db.get(plugin_name, []):
            plugin_cls = command_metadata.plugin_cls
            if plugin_cls.is_active(self.session):
                results.append(command_metadata)

        # We assume there can only be one active plugin implementation. It
        # is an error to have multiple implementations active at the same
        # time.
        if len(results) > 1:
            raise RuntimeError("Multiple plugin implementations for %s: %s" %
                               (plugin_name, [x.plugin_cls for x in results]))

        if results:
            return results[0]

        return obj.NoneObject("Plugin not active")
示例#5
0
    def render(self, renderer):
        dtb_map = {}
        pslist_plugin = self.session.plugins.pslist()
        for task in pslist_plugin.filter_processes():
            dtb = task.Pcb.DirectoryTableBase.v()
            dtb_map[dtb] = task

        symbols = ["nt", "nt!MmGetPhysicalMemoryRanges"]
        if self.session.profile.metadata("arch") == "AMD64":
            dtb_step = 0x1000
            # Add _KUSER_SHARED_DATA
            symbols.append(0xFFFFF78000000000)
        else:
            dtb_step = 0x20
            symbols.append(0xFFDF0000)

        symbol_checks = []
        for symbol in symbols:
            vaddr = self.session.address_resolver.get_address_by_name(symbol)
            paddr = self.session.kernel_address_space.vtop(vaddr)
            symbol_checks.append((vaddr, paddr))

        renderer.table_header([
            ("DTB", "dtb", "[addrpad]"),
            dict(name="Process", type="_EPROCESS"),
        ])

        descriptor = self.profile.get_constant_object(
            "MmPhysicalMemoryBlock",
            target="Pointer",
            target_args=dict(target="_PHYSICAL_MEMORY_DESCRIPTOR", ))

        for memory_range in descriptor.Run:
            start = memory_range.BasePage * 0x1000
            length = memory_range.PageCount * 0x1000

            for page in range(start, start + length, dtb_step):
                self.session.report_progress("Checking %#x", page)
                test_as = self.session.kernel_address_space.__class__(
                    dtb=page, base=self.physical_address_space)

                if self.TestVAddr(test_as, vaddr, symbol_checks):
                    renderer.table_row(
                        page, dtb_map.get(page, obj.NoneObject("Unknown")))
示例#6
0
文件: misc.py 项目: wiredrat/rekall
    def calculate(self):
        if not self.session.physical_address_space:
            return None

        if self.session.physical_address_space.volatile:
            return obj.NoneObject("No fingerprint for volatile image.")

        result = []
        profile = self.session.profile
        phys_as = self.session.physical_address_space

        address_space = self.session.GetParameter("default_address_space")

        label = profile.get_constant_object("NtBuildLab", "String")
        result.append((address_space.vtop(label.obj_offset), label.v()))

        label = profile.get_constant_object("NtBuildLabEx", "String")
        result.append((address_space.vtop(label.obj_offset), label.v()))

        kuser_shared = profile.get_constant_object("KI_USER_SHARED_DATA",
                                                   "_KUSER_SHARED_DATA")

        system_time_offset = address_space.vtop(
            kuser_shared.SystemTime.obj_offset)

        result.append((system_time_offset, phys_as.read(system_time_offset,
                                                        8)))

        tick_time_offset = address_space.vtop(
            kuser_shared.multi_m("TickCountQuad", "TickCountLow").obj_offset)
        result.append((tick_time_offset, phys_as.read(tick_time_offset, 8)))

        # List of processes should also be pretty unique.
        for task in self.session.plugins.pslist().filter_processes():
            name = task.name.cast("String", length=30)
            task_name_offset = address_space.vtop(name.obj_offset)

            # Read the raw data for the task name. Usually the task name is
            # encoded in utf8 but then we might not be able to compare it
            # exactly - we really want bytes here.
            result.append((task_name_offset, name.v()))

        return dict(hash=hashlib.sha1(str(result).encode("utf8")).hexdigest(),
                    tests=result)
示例#7
0
    def build_local_profile(self, profile_name=None, force=False):
        """Fetch and build a local profile from the symbol server."""
        if profile_name is None:
            profile_name = self.detect_profile_name()

        mode = self.session.GetParameter("autodetect_build_local")
        if force or mode == "full" or (mode == "basic" and self.name
                                       in self.session.GetParameter(
                                           "autodetect_build_local_tracked")):
            build_local_profile = self.session.plugins.build_local_profile()
            try:
                self.session.logging.debug("Will build local profile %s",
                                           profile_name)
                build_local_profile.fetch_and_parse(profile_name)
                return self.session.LoadProfile(profile_name, use_cache=False)
            except IOError:
                pass

        return obj.NoneObject()
示例#8
0
  def GetData(self, name, raw=False, default=None):
    # Cant load the profile, we need to ask the server for it.
    self.session.logging.info("Asking server for profile %s", name)
    UPLOADED_PROFILES.pop(name, None)

    self.session.action.SendReply(rekall_types.RekallResponse(
        missing_profile=name,
        repository_version=constants.PROFILE_REPOSITORY_VERSION,))

    # Wait for the server to wake us up. When we wake up the server should
    # have sent the profile over by calling the WriteRekallProfile.
    self.session.action.Suspend()

    # We expect the profile to be here if all went well.
    result = UPLOADED_PROFILES.get(name, obj.NoneObject()).payload
    if result:
      return self.Decoder(result)

    return result
示例#9
0
    def open_file(self):
        """Returns an address space which maps the content of the file's data.

        If this MFT does not contain any $DATA streams, returns a NoneObject().

        The returned address space is formed by joining all $DATA streams' run
        lists in this MFT into a contiguous mapping.
        """
        runlists = []
        data_size = 0

        # Combine the runlists from all the $DATA attributes into one
        # big runlist.
        for attribute in self.attributes:
            if attribute.type == "$DATA":
                if attribute.is_resident:
                    return attribute.data

                if data_size == 0:
                    data_size = attribute.size

                # Some sanity checking. The runlist should agree with the VCN
                # fields.
                run_length = (attribute.runlist_vcn_end -
                              attribute.runlist_vcn_start + 1)
                run_list = list(attribute.RunList())

                if sum(x[1] for x in run_list) != run_length:
                    self.logging.error(
                        "NTFS_ATTRIBUTE %s-%s: Not all runs found!",
                        self.mft_entry, attribute)

                runlists.extend(attribute.RunList())

        if runlists:
            return RunListAddressSpace(
                run_list=runlists,
                base=self.obj_session.physical_address_space,
                session=self.obj_session,
                name=self.full_path,
                size=data_size)

        return obj.NoneObject("No data")
示例#10
0
    def phys_addr(self, va):
        """Returns the physical address of a given virtual address va.

        NOTE: This only works for kernel virtual addresses obviously.

        Linux has a direct mapping between the kernel virtual address space and
        the physical memory. This is the difference between the virtual and
        physical addresses (aka PAGE_OFFSET). This is defined by the __va macro:

        #define __va(x) ((void *)((unsigned long) (x) + PAGE_OFFSET))
        """
        va_addr = obj.Pointer.integer_to_address(va)
        page_offset_addr = obj.Pointer.integer_to_address(
            self.GetPageOffset())

        if va_addr >= page_offset_addr:
            return (va_addr - page_offset_addr)
        else:
            return obj.NoneObject("Unable to translate VA 0x%x", va)
示例#11
0
文件: registry.py 项目: imclab/rekall
    def _decode_data(self, data):
        """Decode the data according to our type."""
        valtype = str(self.Type)

        if valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]:
            if len(data) != struct.calcsize(self.value_formats[valtype]):
                return obj.NoneObject(
                    "Value data did not match the expected data "
                    "size for a {0}".format(valtype))

        if valtype in ["REG_SZ", "REG_EXPAND_SZ", "REG_LINK"]:
            data = data.decode('utf-16-le', "ignore")

        elif valtype == "REG_MULTI_SZ":
            data = data.decode('utf-16-le', "ignore").split('\0')

        elif valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]:
            data = struct.unpack(self.value_formats[valtype], data)[0]

        return data
示例#12
0
    def render(self, renderer):
        renderer.table_header([("Session", "session", "10"),
                               ("WindowStation", "window_station", "12"),
                               ("Format", "format", "18"),
                               ("Handle", "handle", "[addr]"),
                               ("Object", "object", "[addrpad]"),
                               ("Data", "data", "50"),
                               ])

        for session, wndsta, clip, handle in self.calculate():
            # If no tagCLIP is provided, we do not know the format
            if not clip:
                fmt = obj.NoneObject("Format unknown")
            else:
                # Try to get the format name, but failing that, print
                # the format number in hex instead.
                if clip.fmt.v() in constants.CLIPBOARD_FORMAT_ENUM:
                    fmt = str(clip.fmt)
                else:
                    fmt = hex(clip.fmt.v())

            # Try to get the handle from tagCLIP first, but
            # fall back to using _HANDLEENTRY.phead. Note: this can
            # be a value like DUMMY_TEXT_HANDLE (1) etc.
            handle_value = clip.hData or handle.phead.h

            clip_data = ""
            if handle and "TEXT" in fmt:
                clip_data = handle.reference_object().as_string(fmt)

            renderer.table_row(session.SessionId,
                               wndsta.Name,
                               fmt,
                               handle_value,
                               handle.phead.v(),
                               clip_data)

            # Print an additional hexdump if --verbose is specified
            if self.verbose and handle:
                hex_dump = handle.reference_object().as_hex()
                outfd.write("{0}".format(hex_dump))
示例#13
0
文件: basic.py 项目: he0x/rekall
    def Decompose(self, instructions=10, size=None):
        """A generator for instructions of this object.

        How much to decompose is can be specified either by the total number
        of instructions or the total size to decompose.

        Args:
          instructions: Stop after reaching this many instructions. The
            parameter is ignored when size is specified.

          size: Stop after decoding this much data. If specified we ignore
            the instructions parameter.
        """
        overlap = 0x100
        data = ''
        offset = self.obj_offset
        count = 0

        while 1:
            data = self.obj_vm.read(offset, overlap)

            op = obj.NoneObject()
            for op in distorm3.Decompose(offset, data, self.distorm_mode):
                if op.address - offset > len(data) - 40:
                    break

                if not op.valid:
                    continue

                # Exit if we read as much as was required.
                if size is not None and op.address - self.obj_offset > size:
                    return

                yield op

                if size is None and count > instructions:
                    return

                count += 1

            offset = op.address
示例#14
0
    def FormatName(self, root_dentry):
        # For sockets we need more info.
        if len(self.path_components) >= self.MAX_DEPTH:
            return obj.NoneObject(
                u"Depth exceeded at %s" % "/".join(self.path_components))

        if self.mount_point == "socket:":
            return "{0}/{1}[{2}]".format(
                self.mount_point, root_dentry.d_name.name.deref(),
                self.start_dentry.d_inode.i_ino)

        elif self.mount_point == "pipe:":
            return "{0}[{1}]".format(
                self.mount_point, self.start_dentry.d_inode.i_ino)

        elif self.mount_point == "anon_inode:":
            return u"anon_inode:%s" % self.start_dentry.d_name.name.deref()

        # This is the normal condition for files.
        else:
            return re.sub("/+", "/", self.__unicode__())
示例#15
0
文件: linux.py 项目: tklengyel/rekall
    def phys_addr(self, va):
        """Returns the physical address of a given virtual address va.

        Linux has a direct mapping between the kernel virtual address space and
        the physical memory. This is the difference between the virtual and
        physical addresses (aka PAGE_OFFSET). This is defined by the __va macro:

        #define __va(x) ((void *)((unsigned long) (x) + PAGE_OFFSET))

        However, the kernel can be rebased when CONFIG_RELOCATABLE is active.
        phys_addr detects the relocation and returns the correct physical
        address.
        """
        va_addr = obj.Pointer.integer_to_address(va)
        page_offset_addr = obj.Pointer.integer_to_address(
            self.GetPageOffset())

        if va_addr >= page_offset_addr:
            return (va_addr - page_offset_addr + self.GetRelocationDelta())
        else:
            return obj.NoneObject("Unable to translate VA 0x%x", va)
示例#16
0
    def from_stat(cls, filespec, session=None):
        filespec = FileSpec(filespec)
        result = FileInformation(filename=filespec, session=session)

        try:
            s = os.lstat(filespec.os_path())
        except (IOError, OSError) as e:
            return obj.NoneObject("Unable to stat %s", e)

        result.st_mode = Permissions(s.st_mode)
        result.st_ino = s.st_ino
        result.st_size = s.st_size
        result.st_dev = s.st_dev
        result.st_nlink = s.st_nlink
        result.st_uid = User.from_uid(s.st_uid)
        result.st_gid = Group.from_gid(s.st_gid)
        result.st_mtime = s.st_mtime
        result.st_atime = s.st_atime
        result.st_ctime = s.st_ctime

        return result
示例#17
0
    def module_name_from_hook(self, global_atom_table, session, hook):
        ihmod = hook.ihmod
        if ihmod == -1:
            # Return the owner process.
            process = self.get_owner(session, hook)
            if process:
                # We need to resolve the address using the process AS.
                self.cc.SwitchProcessContext(process)
                return self.session.address_resolver.format_address(
                    hook.offPfn, max_distance=1e6)

            return obj.NoneObject()

        atom_num = self.atom_number_from_ihmod(session, ihmod)
        module_name = global_atom_table.get(atom_num)
        if module_name:
            module_name = module_name.Name
        else:
            module_name = ihmod

        return module_name
示例#18
0
    def GetPageOffset(self):
        """Gets the page offset."""
        # This calculation needs to be here instead of the LinuxPageOffset
        # parameter hook because it is used during profile autodetection, where
        # a profile is not yet set on the session object.
        self.session.logging.debug("Calculating page offset...")

        if self.metadata("arch") == "I386":
            return (self.get_constant("_text", False) -
                    self.get_constant("phys_startup_32", False))

        elif self.metadata("arch") == "AMD64":
            # We use the symbol phys_startup_64. If it's not present in the
            # profile and it's different than the default, we should be able
            # to autodetect the difference via kernel_slide.
            phys_startup_64 = (self.get_constant("phys_startup_64", False)
                               or 0x1000000)

            return self.get_constant("_text", False) - phys_startup_64

        elif self.metadata("arch") == "MIPS":
            return 0x80000000

        elif self.metadata("arch") == "ARM":
            # This might not be always the same. According to arm/Kconfig,
            # this only seems to be accurate with the default split in linux
            # (VMSPLIT_3G). See arm/Kconfig. TODO: Use the VMSPLIT_3G config
            # variable here.

            # 1563 config PAGE_OFFSET
            # 1564         hex
            # 1565         default PHYS_OFFSET if !MMU
            # 1566         default 0x40000000 if VMSPLIT_1G
            # 1567         default 0x80000000 if VMSPLIT_2G
            # 1568         default 0xC0000000

            return 0xc0000000

        else:
            return obj.NoneObject("No profile architecture set.")
示例#19
0
    def calculate(self):
        if self.session.physical_address_space.volatile:
            return obj.NoneObject("No fingerprint for volatile image.")

        result = []
        profile = self.session.profile
        phys_as = self.session.physical_address_space

        label = profile.get_constant_object("_osversion", "String")
        result.append(
            (self.session.kernel_address_space.vtop(label.obj_offset),
             label.v()))

        label = profile.get_constant_object("_version", "String")
        result.append(
            (self.session.kernel_address_space.vtop(label.obj_offset),
             label.v()))

        label = profile.get_constant_object("_sched_tick",
                                            "String",
                                            length=8,
                                            term=None)
        result.append(
            (self.session.kernel_address_space.vtop(label.obj_offset),
             label.v()))

        catfish_offset = self.session.GetParameter("catfish_offset")
        result.append((catfish_offset, phys_as.read(catfish_offset, 8)))

        # List of processes should also be pretty unique.
        for task in self.session.plugins.pslist().filter_processes():
            name = task.name.cast("String", length=30)
            task_name_offset = self.session.kernel_address_space.vtop(
                name.obj_offset)

            result.append((task_name_offset, name.v()))

        return dict(hash=hashlib.sha1(
            unicode(result).encode("utf8")).hexdigest(),
                    tests=result)
示例#20
0
    def reference_object(self):
        """Reference the object this handle represents.

        If the object's type is not in our map, we don't know
        what type of object to instantiate so its filled with
        obj.NoneObject() instead.
        """

        object_map = dict(
            TYPE_WINDOW="tagWND",
            TYPE_HOOK="tagHOOK",
            TYPE_CLIPDATA="tagCLIPDATA",
            TYPE_WINEVENTHOOK="tagEVENTHOOK",
            TYPE_TIMER="tagTIMER",
            )

        object_type = object_map.get(str(self.bType))
        if object_type is None:
            return obj.NoneObject("Cannot reference object type")

        return self.obj_profile.Object(
            object_type, offset=self.phead, vm=self.obj_vm)
示例#21
0
    def get_constant_object(self, name, target=None, **kwargs):
        """Instantiate the named constant with these args.

        This method is the main entry point for instantiating constants. It is
        preferred than calling the profile's method of the same name directly
        since it will be responsible with loading the right profile.
        """
        self._EnsureInitialized()

        # Parse the name
        components = self._ParseAddress(name)
        if not components["symbol"]:
            raise ValueError("No symbol name specified.")

        module = self._modules_by_name.get(components["module"])
        if module is not None:
            # Just delegate to the module's profile.
            if module.profile:
                return module.profile.get_constant_object(
                    components["symbol"], target=target, **kwargs)

        return obj.NoneObject("Profile for name %s unknown." % name, log=True)
示例#22
0
    def GetParameter(self, item, default=obj.NoneObject(), cached=True):
        """Retrieves a stored parameter.

        Parameters are managed by the Rekall session in two layers. The state
        containers contains those parameters which are deliberately set by the
        user.

        Some parameters are calculated by plugins and are used in order to speed
        up further calculations. These are cached in the state as well.

        It is important to never override a user selection by the cached
        results. Since the user must be allowed to override all parameters - for
        example through the GUI or the command line. Therefore when resolving a
        parameter, we first check in the state, and only if the parameter does
        not exist, we check the cache.
        """
        result = self.state.get(item)
        if result is not None:
            return result

        # None in the state dict means that the cache is empty. This is
        # different from a NoneObject() returned (which represents a cacheable
        # failure).
        if cached:
            result = self.cache.Get(item)
            if result is not None:
                return result

        # We don't have or didn't look in the cache for the result. See if we
        # can get if from a hook.
        try:
            result = self._RunParameterHook(item)
            if result is not None:
                return result
        except RecursiveHookException:
            pass

        return default
示例#23
0
    def physical_offset(self):
        """The physical offset of the page represented by this page struct."""

        # mem_map is used in 32-bit kernels.
        mem_map = self.obj_profile.get_constant_object("mem_map", "Pointer")

        if mem_map == None:
            if self.obj_profile.get_constant("mem_section"):
                # The VMEMMAP starts at this address in 64-bit kernels.
                # arch/x86/include/asm/pgtable_64_types.h
                mem_map = obj.Pointer.integer_to_address(0xffffea0000000000)
            else:
                logging.error("Unable to determine physical address of page. "
                              "NUMA is not supported.")
                return obj.NoneObject("NUMA is unsupported.")

        # Linux stores an array of struct page starting at mem_map.
        # To find the physical address of a given page, we need to find its
        # index within the array which corresponds to the Page Frame Number
        # and shift it left by the PAGE_SIZE.
        pfn = (self.obj_offset - mem_map) / self.size()
        phys_offset = pfn << 12
        return phys_offset
示例#24
0
文件: registry.py 项目: imclab/rekall
    def DecodedData(self):
        """Returns the data for this key decoded according to the type."""
        # When the data length is 0x80000000, the value is stored in the type
        # (as a REG_DWORD).
        if self.DataLength == 0x80000000:
            return self.Type.v()

        # If the high bit is set, the data is stored inline
        elif self.DataLength & 0x80000000:
            return self._decode_data(self.obj_vm.read(
                    self.m("Data").obj_offset, self.DataLength & 0x7FFFFFFF))

        elif self.DataLength > 0x4000:
            return obj.NoneObject("Big data not supported.")

            big_data = self.obj_profile._CM_BIG_DATA(
                self.Data, vm=self.obj_vm)

            return self._decode_data(big_data.Data)

        else:
            return self._decode_data(self.obj_vm.read(
                    int(self.m("Data")), self.DataLength))
示例#25
0
    def vad(self):
        """Returns a cached RangedCollection() of vad ranges."""

        # If this dtb is the same as the kernel dtb - there are no vads.
        if self.dtb == self.session.GetParameter("dtb"):
            return

        # If it is already cached, just return that.
        if self._vad is not None:
            return self._vad

        # We can not run plugins in recursive context.
        if not self._resolve_vads:
            return obj.NoneObject("vads not available right now")

        try:
            # Prevent recursively calling ourselves. We might resolve Prototype
            # PTEs which end up calling plugins (like the VAD plugin) which
            # might recursively translate another Vad Prototype address. This
            # safety below ensures we cant get into infinite recursion by
            # failing more complex PTE resolution on recursive calls.
            self._resolve_vads = False

            # Try to map the dtb to a task struct so we can look up the vads.
            if self.task == None:
                # Find the _EPROCESS for this dtb - we need to consult the VAD
                # for some of the address transition.
                self.task = self.session.GetParameter("dtb2task").get(self.dtb)

            self._vad = utils.RangedCollection()
            task = self.session.profile._EPROCESS(self.task)
            for vad in task.RealVadRoot.traverse():
                self._vad.insert(vad.Start, vad.End, vad)

            return self._vad
        finally:
            self._resolve_vads = True
示例#26
0
    def SearchForPoolHeader(self, offset, search=0x100):
        """Search backwards from offset for a pool header."""
        pool_alignment = self.session.profile.get_constant("PoolAlignment")
        offset = int(offset) - offset % pool_alignment

        # Cant use xrange() on windows since it must fit into a long.
        for o in itertools.count(offset, -pool_alignment):
            if o < offset - search:
                break

            pool_header = self.session.profile._POOL_HEADER(o)

            # If this is the pool header for this allocation it must be big
            # enough to contain it.
            if pool_header.BlockSize < old_div(
                (offset - o), pool_alignment) + 1:
                continue

            #if not pool_header.PoolType.is_valid():
            #    continue

            # Verify it.
            if pool_header.PreviousSize > 0:
                previous_pool_header = self.session.profile._POOL_HEADER(
                    o - pool_alignment * pool_header.PreviousSize)

                if previous_pool_header.BlockSize == pool_header.PreviousSize:
                    return pool_header

            # Check the next allocation.
            next_pool_header = self.session.profile._POOL_HEADER(
                o + pool_alignment * pool_header.BlockSize)

            if next_pool_header.PreviousSize == pool_header.BlockSize:
                return pool_header

        return obj.NoneObject("No pool tag found")
示例#27
0
    def __init__(self, env=None, use_config_file=True, **kwargs):
        """Creates an interactive session.

        Args:
          env: If passed we use this dict as the local environment.

          use_config_file: If True we merge the system's config file into the
             session. This helps set the correct profile paths for example.

          kwargs: Arbitrary parameters to store in the session.

        Returns:
          an interactive session object.
        """
        self._locals = env or {}

        # These are the command plugins which we exported to the local
        # namespace.
        self._start_time = time.time()

        # These keep track of the last run plugin.
        self._last_plugin = None

        # Fill the session with helpful defaults.
        self.pager = obj.NoneObject("Set this to your favourite pager.")

        self.help_profile = None

        super(InteractiveSession, self).__init__()
        with self:
            if use_config_file:
                config.MergeConfigOptions(self.state)

            for k, v in kwargs.items():
                self.SetParameter(k, v)

            self.UpdateFromConfigObject()
示例#28
0
    def display(self, custom_tz=None, utc_shift=None):
        try:
            arw = self.as_arrow()
            if custom_tz:
                try:
                    arw = arw.to(custom_tz)
                except RuntimeError:
                    pass
            elif utc_shift is not None:
                arw = arw.to(ShiftedTimezone(int(utc_shift)))

            else:
                arw = arw.to(self.obj_session.GetParameter("timezone", "UTC"))

            # Mark UTC timezone with a Z
            formatted_date = arw.format(self.timeformat)
            formatted_tz = arw.format("Z")
            if formatted_tz in ("-0000", "+0000"):
                formatted_tz = "Z"

            return formatted_date + formatted_tz

        except ValueError as e:
            return obj.NoneObject("Error: %s", e)
示例#29
0
    def find_vnode_object(self):
        """Find the underlying vnode object for the given vm_map_entry.

        xnu-2422.1.72/osfmk/vm/bsd_vm.c: 1339.
        """
        if not self.is_sub_map.v():
            #/*
            #* The last object in the shadow chain has the
            #* relevant pager information.
            #*/

            top_object = self.object.vm_object

            if top_object:
                object = top_object
                while object.shadow:
                    object = object.shadow

                if (object and not object.internal.v() and
                    object.pager_ready.v() and
                    not object.terminating.v() and
                    object.alive.v()):
                    memory_object = object.pager
                    pager_ops = memory_object.mo_pager_ops

                    # If this object points to the vnode_pager_ops, then we
                    # found what we're looking for.  Otherwise, this
                    # vm_map_entry doesn't have an underlying vnode and so we
                    # fall through to the bottom and return NULL.

                    if pager_ops == self.obj_profile.get_constant(
                        "_vnode_pager_ops"):
                        return object.pager.dereference_as(
                            "vnode_pager").vnode_handle

        return obj.NoneObject("VNode not found")
示例#30
0
    def __init__(self, **kwargs):
        self._parameter_hooks = {}

        # Store user configurable attributes here. These will be read/written to
        # the configuration file.
        kwargs.setdefault("cache", Cache())
        self.state = Configuration(self, **kwargs)

        self.progress = ProgressDispatcher()
        self.profile = obj.NoneObject("Set this to a valid profile "
                                      "(e.g. type profiles. and tab).")

        # Cache the profiles we get from LoadProfile() below.
        # TODO: This should probably be also done on disk somewhere to avoid
        # having to hit the profile repository all the time.
        self.profile_cache = {}

        self.entities = entity.EntityManager(session=self)

        self.inventories = {}
        with self:
            self.UpdateFromConfigObject()

        self._configuration_parameters = [x[2] for x in config.OPTIONS]