# Rekall Memory Forensics
# Copyright (c) 2010, 2011, 2012 Michael Ligh <michael.ligh@mnin.org>
# Copyright 2013 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

from rekall import obj
from rekall import plugin
from rekall import testlib
from rekall.plugins import core
from rekall.plugins.windows import common


class Malfind(core.DirectoryDumperMixin, common.WinProcessFilter):
    "Find hidden and injected code"

    __name = "malfind"

    dump_dir_optional = True
    default_dump_dir = None

    def _is_vad_empty(self, vad, address_space):
        """
        Check if a VAD region is either entirely unavailable
        due to paging, entirely consiting of zeros, or a
        combination of the two. This helps ignore false positives
        whose VAD flags match task._injection_filter requirements
        but there's no data and thus not worth reporting it.

        @param vad: an MMVAD object in kernel AS
        @param address_space: the process address space
        """

        PAGE_SIZE = 0x1000
        all_zero_page = "\x00" * PAGE_SIZE

        offset = 0
        while offset < vad.Length:
            next_addr = vad.Start + offset
            if (address_space.is_valid_address(next_addr) and
                    address_space.read(next_addr, PAGE_SIZE) != all_zero_page):
                return False
            offset += PAGE_SIZE

        return True

    def _injection_filter(self, vad, task_as):
        """Detects injected vad regions.

        This looks for private allocations that are committed,
        memory-resident, non-empty (not all zeros) and with an
        original protection that includes write and execute.

        It is important to note that protections are applied at
        the allocation granularity (page level). Thus the original
        protection might not be the current protection, and it
        also might not apply to all pages in the VAD range.

        @param vad: an MMVAD object.

        @returns: True if the MMVAD looks like it might
        contain injected code.
        """
        # Try to find injections.
        protect = str(vad.u.VadFlags.ProtectionEnum)
        write_exec = "EXECUTE" in protect and "WRITE" in protect

        # The Write/Execute check applies to everything
        if not write_exec:
            return False

        # This is a typical VirtualAlloc'd injection
        if ((vad.u.VadFlags.PrivateMemory == 1 and
             vad.Tag == "VadS") or

                # This is a stuxnet-style injection
                (vad.u.VadFlags.PrivateMemory == 0 and
                 protect != "EXECUTE_WRITECOPY")):
            return not self._is_vad_empty(vad, task_as)

        return False

    def render(self, renderer):
        cc = self.session.plugins.cc()
        for task in self.filter_processes():
            task_as = task.get_process_address_space()
            if not task_as:
                continue

            with cc:
                cc.SwitchProcessContext(task)
                for vad in task.RealVadRoot.traverse():
                    self.session.report_progress("Checking %r of pid %s",
                                                 vad, task.UniqueProcessId)

                    if self._injection_filter(vad, task_as):
                        renderer.section()
                        renderer.format(
                            "Process: {0} Pid: {1} Address: {2:#x}\n",
                            task.ImageFileName, task.UniqueProcessId, vad.Start)

                        renderer.format("Vad Tag: {0} Protection: {1}\n",
                                        vad.Tag, vad.u.VadFlags.ProtectionEnum)

                        renderer.format("Flags: {0}\n", vad.u.VadFlags)
                        renderer.format("\n")

                        dumper = self.session.plugins.dump(
                            suppress_headers=True,
                            offset=vad.Start, rows=4)
                        dumper.render(renderer)

                        renderer.format("\n")

                        disassembler = self.session.plugins.dis(
                            suppress_headers=True,
                            offset=vad.Start, length=0x40)
                        disassembler.render(renderer)

                        if self.dump_dir:
                            filename = "{0}.{1:d}.{2:08x}-{3:08x}.dmp".format(
                                task.ImageFileName, task.pid, vad.Start,
                                vad.End)

                            with renderer.open(directory=self.dump_dir,
                                               filename=filename,
                                               mode='wb') as fd:
                                self.session.report_progress(
                                    "Dumping %s" % filename)

                                self.CopyToFile(task_as, vad.Start, vad.End, fd)



class LdrModules(plugin.VerbosityMixIn, common.WinProcessFilter):
    "Detect unlinked DLLs"

    __name = "ldrmodules"

    def list_mapped_files(self, task):
        """Iterates over all vads and returns executable regions.

        Yields:
          vad objects which are both executable and have a file name.
        """
        self.session.report_progress("Inspecting Pid %s",
                                     task.UniqueProcessId)

        for vad in task.RealVadRoot.traverse():
            try:
                file_obj = vad.ControlArea.FilePointer
                protect = str(vad.u.VadFlags.ProtectionEnum)
                if "EXECUTE" in protect and "WRITE" in protect:
                    yield vad, file_obj.FileName
            except AttributeError:
                pass

    def render(self, renderer):
        output_style = self.session.GetParameter("output_style")
        if output_style == "full":
            renderer.table_header([
                dict(type="_EPROCESS", cname="_EPROCESS"),
                ("Base", "base_address", "[addrpad]"),
                ("InLoad", "in_load", "5"),
                ("InLoadPath", "in_load_path", "80"),
                ("InInit", "in_init", "5"),
                ("InInitPath", "in_init_path", "80"),
                ("InMem", "in_mem", "5"),
                ("InMemPath", "in_mem_path", "80"),
                ("MappedPath", "mapped_filename", "")
                ])

        else:
            renderer.table_header([
                ("Pid", "pid", "8"),
                ("Process", "process", "20"),
                ("Base", "base_address", "[addrpad]"),
                ("InLoad", "in_load", "5"),
                ("InInit", "in_init", "5"),
                ("InMem", "in_mem", "5"),
                ("MappedPath", "mapped_filename", "")
                ])

        for task in self.filter_processes():
            # Build a dictionary for all three PEB lists where the
            # keys are base address and module objects are the values
            inloadorder = dict((mod.DllBase.v(), mod)
                               for mod in task.get_load_modules())

            ininitorder = dict((mod.DllBase.v(), mod)
                               for mod in task.get_init_modules())

            inmemorder = dict((mod.DllBase.v(), mod)
                              for mod in task.get_mem_modules())

            # Build a similar dictionary for the mapped files
            mapped_files = dict((vad.Start, name)
                                for vad, name in self.list_mapped_files(task))

            # For each base address with a mapped file, print info on
            # the other PEB lists to spot discrepancies.
            for base in mapped_files.keys():
                if output_style == "full":
                    renderer.table_row(
                        task,
                        base,
                        base in inloadorder,
                        inloadorder.get(base, obj.NoneObject()).FullDllName,
                        base in ininitorder,
                        ininitorder.get(base, obj.NoneObject()).FullDllName,
                        base in inmemorder,
                        inmemorder.get(base, obj.NoneObject()).FullDllName,
                        mapped_files[base])
                else:
                    renderer.table_row(
                        task.UniqueProcessId,
                        task.ImageFileName,
                        base,
                        base in inloadorder,
                        base in ininitorder,
                        base in inmemorder,
                        mapped_files[base])

                    if self.verbosity > 5:
                        for mod_list, name in ([inloadorder, "Load"],
                                               [ininitorder, "Init"],
                                               [inmemorder, "Mem"]):

                            if base in mod_list:
                                load_mod = mod_list[base]
                                renderer.format("  {0} Path: {1} : {2}\n",
                                                name, load_mod.FullDllName,
                                                load_mod.BaseDllName)


class TestLdrModules(testlib.SimpleTestCase):
    PARAMETERS = dict(
        commandline="ldrmodules --pid %(pid)s"
        )
