def testProcessCollectedArtifacts(self):
        """Test downloading files from artifacts."""
        self.client_id = self.SetupClient(0,
                                          system="Windows",
                                          os_version="6.2")

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                           vfs_test_lib.FakeFullVFSHandler):
                self._testProcessCollectedArtifacts()
示例#2
0
    def setUp(self):
        super(GrrKbWindowsTest, self).setUp()
        self.SetupClients(1, system="Windows", os_version="6.2", arch="AMD64")

        self.os_overrider = vfs_test_lib.VFSOverrider(
            rdf_paths.PathSpec.PathType.OS, vfs_test_lib.FakeFullVFSHandler)
        self.reg_overrider = vfs_test_lib.VFSOverrider(
            rdf_paths.PathSpec.PathType.REGISTRY,
            vfs_test_lib.FakeRegistryVFSHandler)
        self.os_overrider.Start()
        self.reg_overrider.Start()
示例#3
0
    def testInterrogateWindows(self):
        """Test the Interrogate flow."""
        self.client_id = self.SetupClient(0,
                                          system="Windows",
                                          kernel="10.0.14393",
                                          os_version="6.2",
                                          arch="AMD64")

        data_store.REL_DB.WriteClientMetadata(self.client_id.Basename(),
                                              fleetspeak_enabled=False)

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                           vfs_test_lib.FakeFullVFSHandler):

                client_mock = action_mocks.InterrogatedClient()
                client_mock.InitializeClient(system="Windows",
                                             version="6.1.7600",
                                             kernel="6.1.7601")

                # Run the flow in the simulated way
                for _ in flow_test_lib.TestFlowHelper(
                        discovery.Interrogate.__name__,
                        client_mock,
                        token=self.token,
                        client_id=self.client_id):
                    pass

                self.fd = aff4.FACTORY.Open(self.client_id, token=self.token)
                self._CheckBasicInfo("test_node.test", "Windows",
                                     100 * 1000000)
                self._CheckClientInfo()
                self._CheckGRRConfig()
                self._CheckNotificationsCreated()
                self._CheckClientSummary("Windows",
                                         "6.1.7600",
                                         kernel="6.1.7601")

                # jim parsed from registry profile keys
                self._CheckUsers(["jim", "kovacs"])
                self._CheckNetworkInfo()
                self._CheckVFS()
                self._CheckLabels()
                self._CheckLabelIndex()
                self._CheckWindowsDiskInfo()
                self._CheckRegistryPathspec()
                self._CheckClientKwIndex(["Linux"], 0)
                self._CheckClientKwIndex(["Windows"], 1)
                self._CheckClientKwIndex(["Label2"], 1)
                self._CheckMemory()
示例#4
0
    def testRegistryNoKeysArtifact(self):
        """Test the basic Registry Key collection."""

        source = rdf_artifact.ArtifactSource(
            type=self.source_type.REGISTRY_KEY, attributes={
                "keys": [],
            })
        request = GetRequest(source, "TestRegistryKey")

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                           vfs_test_lib.FakeFullVFSHandler):
                collected_artifact = self.RunArtifactCollector(request)
                self.assertEmpty(collected_artifact.action_results)
    def testProcessCollectedArtifacts(self):
        """Tests downloading files from artifacts."""
        self.client_id = self.SetupClient(0,
                                          system="Windows",
                                          os_version="6.2")

        client_mock = action_mocks.FileFinderClientMock()

        artifact_list = ["WindowsPersistenceMechanismFiles"]
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with test_lib.Instrument(transfer.MultiGetFile,
                                     "Start") as getfile_instrument:
                flow_test_lib.TestFlowHelper(
                    collectors.ArtifactCollectorFlow.__name__,
                    client_mock,
                    artifact_list=artifact_list,
                    knowledge_base=self._GetKB(),
                    creator=self.test_username,
                    client_id=self.client_id,
                    split_output_by_artifact=True)

                # Check MultiGetFile got called for our runkey files
                # TODO(user): RunKeys for S-1-5-20 are not found because users.sid
                # only expands to users with profiles.
                pathspecs = getfile_instrument.args[0][0].args.pathspecs
                self.assertCountEqual([x.path for x in pathspecs],
                                      [u"C:\\Windows\\TEMP\\A.exe"])
示例#6
0
 def setUp(self):
   super().setUp()
   vfs_overrider = vfs_test_lib.VFSOverrider(
       rdf_paths.PathSpec.PathType.OS, vfs_test_lib.ClientVFSHandlerFixture)
   vfs_overrider.Start()
   self.addCleanup(vfs_overrider.Stop)
   self.client_id = self.SetupClient(0)
示例#7
0
 def setUp(self):
   super(RegistryFlowTest, self).setUp()
   vfs_overrider = vfs_test_lib.VFSOverrider(
       rdf_paths.PathSpec.PathType.REGISTRY,
       vfs_test_lib.FakeRegistryVFSHandler)
   vfs_overrider.Start()
   self.addCleanup(vfs_overrider.Stop)
示例#8
0
    def testKnowledgeBaseRetrievalDarwin(self):
        """Check we can retrieve a Darwin kb."""
        self.ClearKB()
        with test_lib.ConfigOverrider(
            {"Artifacts.knowledge_base": ["MacOSUsers"]}):
            with vfs_test_lib.VFSOverrider(
                    rdf_paths.PathSpec.PathType.OS,
                    vfs_test_lib.ClientVFSHandlerFixture):

                for _ in flow_test_lib.TestFlowHelper(
                        artifact.KnowledgeBaseInitializationFlow.__name__,
                        self.client_mock,
                        client_id=self.client_id,
                        token=self.token):
                    pass
                client = aff4.FACTORY.Open(self.client_id,
                                           token=self.token,
                                           mode="rw")

                kb = artifact.GetArtifactKnowledgeBase(client)
                self.assertEqual(kb.os_major_version, 10)
                self.assertEqual(kb.os_minor_version, 9)
                # scalzi from /Users dir listing.
                self.assertItemsEqual([x.username for x in kb.users],
                                      ["scalzi"])
                user = kb.GetUser(username="******")
                self.assertEqual(user.homedir, "/Users/scalzi")
    def testDownloadDirectoryUnicode(self):
        """Test a FileFinder flow with depth=1."""
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       vfs_test_lib.ClientVFSHandlerFixture):
            # Mock the client actions FileFinder uses.
            client_mock = action_mocks.FileFinderClientMock()

            flow_test_lib.TestFlowHelper(
                compatibility.GetName(file_finder.FileFinder),
                client_mock,
                client_id=self.client_id,
                paths=["/c/Downloads/*"],
                action=rdf_file_finder.FileFinderAction.Download(),
                token=self.token)

            # There should be 6 children:
            expected_filenames = [
                "a.txt", "b.txt", "c.txt", "d.txt", "sub1", "中国新闻网新闻中.txt"
            ]

            children = data_store.REL_DB.ListChildPathInfos(
                self.client_id, rdf_objects.PathInfo.PathType.OS,
                ["c", "Downloads"])
            filenames = [child.components[-1] for child in children]
            self.assertCountEqual(filenames, expected_filenames)
示例#10
0
    def testVFSVirtualRoot(self):

        # Let's open a file in the virtual root.
        os_root = "os:%s" % self.base_path
        with test_lib.ConfigOverrider({"Client.vfs_virtualroots": [os_root]}):
            # We need to reset the vfs.VFS_VIRTUALROOTS too.
            vfs.VFSInit().Run()

            fd = vfs.VFSOpen(
                rdf_paths.PathSpec(path="/morenumbers.txt",
                                   pathtype=rdf_paths.PathSpec.PathType.OS))
            data = fd.read(10)
            self.assertEqual(data, "1\n2\n3\n4\n5\n")

        # This should also work with TSK.
        tsk_root = "tsk:%s" % os.path.join(self.base_path, "test_img.dd")
        with test_lib.ConfigOverrider({"Client.vfs_virtualroots": [tsk_root]}):
            vfs.VFSInit().Run()

            image_file_ps = rdf_paths.PathSpec(
                path=u"איןד ןד ש אקדא/איןד.txt",
                pathtype=rdf_paths.PathSpec.PathType.TSK)

            fd = vfs.VFSOpen(image_file_ps)

            data = fd.read(10)
            self.assertEqual(data, "1\n2\n3\n4\n5\n")

            # This should not influence vfs handlers other than OS and TSK.
            reg_type = rdf_paths.PathSpec.PathType.REGISTRY
            os_handler = vfs.VFS_HANDLERS[rdf_paths.PathSpec.PathType.OS]
            with vfs_test_lib.VFSOverrider(reg_type, os_handler):
                with self.assertRaises(IOError):
                    image_file_ps.pathtype = reg_type
                    vfs.VFSOpen(image_file_ps)
示例#11
0
  def setUp(self):
    super(TestSearchFileContentWithFixture, self).setUp()

    self.client_mock = action_mocks.GrepClientMock()
    self.vfs_overrider = vfs_test_lib.VFSOverrider(
        rdf_paths.PathSpec.PathType.OS, vfs_test_lib.ClientVFSHandlerFixture)
    self.vfs_overrider.Start()
示例#12
0
    def setUp(self):
        super(FindTest, self).setUp()

        # Install the mock
        self.vfs_overrider = vfs_test_lib.VFSOverrider(
            rdf_paths.PathSpec.PathType.OS, MockVFSHandlerFind)
        self.vfs_overrider.Start()
示例#13
0
 def setUp(self):
     super(TestFindFlow, self).setUp()
     self.vfs_overrider = vfs_test_lib.VFSOverrider(
         rdf_paths.PathSpec.PathType.OS,
         vfs_test_lib.ClientVFSHandlerFixture)
     self.vfs_overrider.Start()
     self.client_id = self.SetupClient(0)
示例#14
0
    def testFleetspeakClient(self, mock_labels_fn):
        mock_labels_fn.return_value = ["foo", "bar"]
        client_id = "C.0000000000000001"
        data_store.REL_DB.WriteClientMetadata(client_id,
                                              fleetspeak_enabled=True)
        client_mock = action_mocks.InterrogatedClient()
        client_mock.InitializeClient(fqdn="fleetspeak.test.com",
                                     system="Linux",
                                     release="Ubuntu",
                                     version="14.4")

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       vfs_test_lib.FakeTestDataVFSHandler):
            flow_test_lib.TestFlowHelper(discovery.Interrogate.__name__,
                                         client_mock,
                                         token=self.token,
                                         client_id=client_id)

        snapshot = data_store.REL_DB.ReadClientSnapshot(client_id)
        self.assertEqual(snapshot.knowledge_base.fqdn, "fleetspeak.test.com")
        self.assertEqual(snapshot.knowledge_base.os, "Linux")
        self._CheckClientInfo(snapshot)
        self._CheckGRRConfig(snapshot)
        self._CheckNotificationsCreated(self.token.username, client_id)
        self._CheckRelease(snapshot, "Ubuntu", "14.4")
        self._CheckNetworkInfo(snapshot)
        labels = data_store.REL_DB.ReadClientLabels(client_id)
        self.assertCountEqual([l.name for l in labels], ["foo", "bar"])
示例#15
0
  def testInterrogateCloudMetadataLinux(self):
    """Check google cloud metadata on linux."""
    client_id, client_urn = self._SetupMinimalClient()
    with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                   vfs_test_lib.FakeTestDataVFSHandler):
      with test_lib.ConfigOverrider({
          "Artifacts.knowledge_base": [
              "LinuxWtmp", "NetgroupConfiguration", "LinuxRelease"
          ],
          "Artifacts.netgroup_filter_regexes": [r"^login$"]
      }):
        client_mock = action_mocks.InterrogatedClient()
        client_mock.InitializeClient()
        with test_lib.SuppressLogs():
          flow_test_lib.TestFlowHelper(
              discovery.Interrogate.__name__,
              client_mock,
              token=self.token,
              client_id=client_id)

    if data_store.RelationalDBReadEnabled():
      client = self._OpenClient(client_id)
      self._CheckCloudMetadataRelational(client)
    else:
      client = aff4.FACTORY.Open(client_urn, token=self.token)
      self._CheckCloudMetadataAFF4(client)
示例#16
0
    def testIteratedDirectoryListing(self):
        """Test that the client iterator works."""
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       MockVFSHandler):
            path = "/"
            # Run the flow in the simulated way
            client_mock = action_mocks.ActionMock(
                standard.IteratedListDirectory)
            for _ in flow_test_lib.TestFlowHelper(
                    filesystem.IteratedListDirectory.__name__,
                    client_mock,
                    client_id=self.client_id,
                    pathspec=rdf_paths.PathSpec(
                        path="/", pathtype=rdf_paths.PathSpec.PathType.OS),
                    token=self.token):
                pass

            fd = aff4.FACTORY.Open(self.client_id.Add("fs/os").Add(path),
                                   token=self.token)
            directory = [ch for ch in fd.OpenChildren()]
            pb = rdf_paths.PathSpec(path=path,
                                    pathtype=rdf_paths.PathSpec.PathType.OS)
            directory2 = list(vfs.VFSOpen(pb).ListFiles())
            directory.sort()
            result = [x.Get(x.Schema.STAT) for x in directory]

            # Make sure that the resulting directory is what it should be
            for x, y in zip(result, directory2):
                self.assertEqual(x.st_mode, y.st_mode)
                self.assertRDFValuesEqual(x, y)
示例#17
0
    def testArtifactOutput(self):
        """Check we can run command based artifacts."""
        client_id = test_lib.TEST_CLIENT_ID
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       vfs_test_lib.FakeTestDataVFSHandler):
            # Will raise if something goes wrong.
            self.RunCollectorAndGetResults(["TestFilesArtifact"],
                                           client_mock=self.client_mock,
                                           client_id=client_id)

            # Will raise if something goes wrong.
            self.RunCollectorAndGetResults(["TestFilesArtifact"],
                                           client_mock=self.client_mock,
                                           client_id=client_id,
                                           split_output_by_artifact=True)

            # Test the error_on_no_results option.
            with self.assertRaises(RuntimeError) as context:
                with test_lib.SuppressLogs():
                    self.RunCollectorAndGetResults(
                        ["NullArtifact"],
                        client_mock=self.client_mock,
                        client_id=client_id,
                        split_output_by_artifact=True,
                        error_on_no_results=True)
            if "collector returned 0 responses" not in str(context.exception):
                raise RuntimeError("0 responses should have been returned")
示例#18
0
    def testDiskVolumeInfoWindows(self):
        self.client_id = self.SetupClient(0, system="Windows")
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):

            client_mock = action_mocks.WindowsVolumeClientMock()
            session_id = flow_test_lib.TestFlowHelper(
                compatibility.GetName(filesystem.DiskVolumeInfo),
                client_mock,
                client_id=self.client_id,
                token=self.token,
                path_list=[r"D:\temp\something", r"/var/tmp"])

            results = flow_test_lib.GetFlowResults(self.client_id, session_id)

            # We asked for D and we guessed systemroot (C) for "/var/tmp", but only
            # C and Z are present, so we should just get C.
            self.assertCountEqual(
                [x.windowsvolume.drive_letter for x in results], ["C:"])

            session_id = flow_test_lib.TestFlowHelper(compatibility.GetName(
                filesystem.DiskVolumeInfo),
                                                      client_mock,
                                                      client_id=self.client_id,
                                                      token=self.token,
                                                      path_list=[r"Z:\blah"])

            results = flow_test_lib.GetFlowResults(self.client_id, session_id)
            self.assertCountEqual(
                [x.windowsvolume.drive_letter for x in results], ["Z:"])
示例#19
0
  def testKnowledgeBaseRetrievalLinuxNoUsers(self):
    """Cause a users.username dependency failure."""
    self.ClearKB()
    with test_lib.ConfigOverrider({
        "Artifacts.knowledge_base": [
            "NetgroupConfiguration", "NssCacheLinuxPasswdHomedirs",
            "LinuxRelease"
        ],
        "Artifacts.netgroup_filter_regexes": ["^doesntexist$"]
    }):

      with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                     vfs_test_lib.FakeTestDataVFSHandler):

        for _ in flow_test_lib.TestFlowHelper(
            artifact.KnowledgeBaseInitializationFlow.__name__,
            self.client_mock,
            require_complete=False,
            client_id=self.client_id,
            token=self.token):
          pass
        client = aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw")
        kb = artifact.GetArtifactKnowledgeBase(client)
        self.assertEqual(kb.os_major_version, 14)
        self.assertEqual(kb.os_minor_version, 4)
        self.assertItemsEqual([x.username for x in kb.users], [])
示例#20
0
  def testKnowledgeBaseRetrievalLinux(self):
    """Check we can retrieve a Linux kb."""
    self.ClearKB()
    with test_lib.ConfigOverrider({
        "Artifacts.knowledge_base": [
            "LinuxWtmp", "NetgroupConfiguration", "LinuxPasswdHomedirs",
            "LinuxRelease"
        ],
        "Artifacts.netgroup_filter_regexes": ["^login$"],
        "Artifacts.netgroup_user_blacklist": ["isaac"]
    }):
      with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                     vfs_test_lib.FakeTestDataVFSHandler):

        for _ in flow_test_lib.TestFlowHelper(
            artifact.KnowledgeBaseInitializationFlow.__name__,
            self.client_mock,
            client_id=self.client_id,
            token=self.token):
          pass
        client = aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw")
        kb = artifact.GetArtifactKnowledgeBase(client)
        self.assertEqual(kb.os_major_version, 14)
        self.assertEqual(kb.os_minor_version, 4)
        # user 1,2,3 from wtmp. yagharek from netgroup.
        self.assertItemsEqual([x.username for x in kb.users],
                              ["user1", "user2", "user3", "yagharek"])
        user = kb.GetUser(username="******")
        self.assertEqual(user.last_logon.AsSecondsFromEpoch(), 1296552099)
        self.assertEqual(user.homedir, "/home/user1")
示例#21
0
    def testFleetspeakClient_OnlyGRRLabels(self, mock_labels_fn):
        mock_labels_fn.return_value = []
        client_id = "C.0000000000000001"
        data_store.REL_DB.WriteClientMetadata(client_id,
                                              fleetspeak_enabled=True)
        client_mock = action_mocks.InterrogatedClient()
        client_mock.InitializeClient(fqdn="fleetspeak.test.com",
                                     system="Linux",
                                     release="Ubuntu",
                                     version="14.4")

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       vfs_test_lib.FakeTestDataVFSHandler):
            with self.assertStatsCounterDelta(
                    1, discovery.FLEETSPEAK_UNLABELED_CLIENTS):

                flow_test_lib.TestFlowHelper(discovery.Interrogate.__name__,
                                             client_mock,
                                             token=self.token,
                                             client_id=client_id)

        rdf_labels = data_store.REL_DB.ReadClientLabels(client_id)
        expected_labels = [
            action_mocks.InterrogatedClient.LABEL1,
            action_mocks.InterrogatedClient.LABEL2,
        ]
        self.assertCountEqual([l.name for l in rdf_labels], expected_labels)
示例#22
0
    def testInterrogateWindows(self):
        """Test the Interrogate flow."""
        client_id = self._SetupMinimalClient()
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                           vfs_test_lib.FakeFullVFSHandler):

                client_mock = action_mocks.InterrogatedClient()
                client_mock.InitializeClient(system="Windows",
                                             version="6.1.7600",
                                             kernel="6.1.7601")

                with test_lib.ConfigOverrider({
                        "Artifacts.non_kb_interrogate_artifacts":
                    ["WMILogicalDisks"],
                }):
                    # Run the flow in the simulated way
                    flow_test_lib.TestFlowHelper(
                        discovery.Interrogate.__name__,
                        client_mock,
                        token=self.token,
                        client_id=client_id)

        client = self._OpenClient(client_id)
        self._CheckBasicInfo(client, "test_node.test", "Windows",
                             100 * 1000000)
        self._CheckClientInfo(client)
        self._CheckGRRConfig(client)
        self._CheckNotificationsCreated(self.token.username, client_id)
        self._CheckClientSummary(client_id,
                                 client.GetSummary(),
                                 "Windows",
                                 "6.1.7600",
                                 kernel="6.1.7601")
        # jim parsed from registry profile keys
        self._CheckUsers(client, ["jim", "kovacs"])
        self._CheckNetworkInfo(client)
        # No VFS test for the relational db.
        self._CheckLabels(client_id)
        self._CheckLabelIndex(client_id)
        self._CheckWindowsDiskInfo(client)
        # No registry pathspec test for the relational db.
        self._CheckClientKwIndex(["Linux"], 0)
        self._CheckClientKwIndex(["Windows"], 1)
        self._CheckClientKwIndex(["Label2"], 1)
        self._CheckMemory(client)
示例#23
0
    def testAppliesLiteralConditionWhenMemoryPathTypeIsUsed(self):
        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                       vfs_test_lib.FakeTestDataVFSHandler):
            with vfs_test_lib.VFSOverrider(
                    rdf_paths.PathSpec.PathType.MEMORY,
                    vfs_test_lib.FakeTestDataVFSHandler):
                paths = ["/var/log/auth.log", "/etc/ssh/sshd_config"]

                cmlc = rdf_file_finder.FileFinderContentsLiteralMatchCondition
                literal_condition = rdf_file_finder.FileFinderCondition(
                    condition_type=rdf_file_finder.FileFinderCondition.Type.
                    CONTENTS_LITERAL_MATCH,
                    contents_literal_match=cmlc(
                        mode="ALL_HITS",
                        bytes_before=10,
                        bytes_after=10,
                        literal="session opened for user dearjohn"))

                # Check this condition with all the actions. This makes sense, as we may
                # download memeory or send it to the socket.
                for action in self.CONDITION_TESTS_ACTIONS:
                    for s in flow_test_lib.TestFlowHelper(
                            file_finder.FileFinder.__name__,
                            self.client_mock,
                            client_id=self.client_id,
                            paths=paths,
                            pathtype=rdf_paths.PathSpec.PathType.MEMORY,
                            conditions=[literal_condition],
                            action=rdf_file_finder.FileFinderAction(
                                action_type=action),
                            token=self.token):
                        session_id = s

                    self.CheckFilesInCollection(["auth.log"],
                                                session_id=session_id)

                    fd = flow.GRRFlow.ResultCollectionForFID(session_id,
                                                             token=self.token)
                    self.assertEqual(fd[0].stat_entry.pathspec.CollapsePath(),
                                     paths[0])
                    self.assertEqual(len(fd), 1)
                    self.assertEqual(len(fd[0].matches), 1)
                    self.assertEqual(fd[0].matches[0].offset, 350)
                    self.assertEqual(
                        fd[0].matches[0].data,
                        "session): session opened for user dearjohn by (uid=0")
示例#24
0
 def testFilesArtifact(self):
   """Check GetFiles artifacts."""
   with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                  vfs_test_lib.FakeTestDataVFSHandler):
     self.RunCollectorAndGetCollection(
         ["TestFilesArtifact"], client_mock=self.client_mock)
     urn = self.client_id.Add("fs/os/").Add("var/log/auth.log")
     aff4.FACTORY.Open(urn, aff4_type=aff4_grr.VFSBlobImage, token=self.token)
示例#25
0
    def setUp(self):
        super(GrepTest, self).setUp()

        # Install the mock
        self.vfs_overrider = vfs_test_lib.VFSOverrider(
            rdf_paths.PathSpec.PathType.OS, MockVFSHandlerFind)
        self.vfs_overrider.Start()
        self.filename = "/mock2/directory1/grepfile.txt"
示例#26
0
    def setUp(self):
        super().setUp()

        # Install the mock
        vfs_overrider = vfs_test_lib.VFSOverrider(
            rdf_paths.PathSpec.PathType.OS, MockVFSHandlerFind)
        vfs_overrider.Start()
        self.addCleanup(vfs_overrider.Stop)
示例#27
0
    def testBasicRegistryKeyArtifact(self):
        """Test that a registry key artifact can be collected."""

        artifact_list = ["TestRegistryKey"]

        self.cleanup = InitGRRWithTestSources(r"""
name: TestRegistryKey
doc: A sample registry key artifact.
sources:
- type: REGISTRY_KEY
  attributes:
    keys: [
      'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager'
    ]
""")

        with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                       vfs_test_lib.FakeRegistryVFSHandler):
            with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                           vfs_test_lib.FakeFullVFSHandler):

                # Run the ArtifactCollector to get the expected result.
                session_id = flow_test_lib.TestFlowHelper(
                    aff4_flows.ArtifactCollectorFlow.__name__,
                    action_mocks.FileFinderClientMock(),
                    artifact_list=artifact_list,
                    token=self.token,
                    client_id=self.client_id,
                    apply_parsers=False)
                results = flow_test_lib.GetFlowResults(self.client_id,
                                                       session_id)
                expected = results[0]
                self.assertIsInstance(expected, rdf_client_fs.StatEntry)

                # Run the ClientArtifactCollector to get the actual result.
                cac_results = self._RunFlow(
                    aff4_flows.ClientArtifactCollector,
                    artifact_collector.ArtifactCollector,
                    artifact_list,
                    apply_parsers=False)
                artifact_response = cac_results[0]
                self.assertIsInstance(artifact_response,
                                      rdf_client_fs.StatEntry)

                self.assertEqual(results, cac_results)
示例#28
0
  def testInterrogateCloudMetadataWindows(self):
    """Check google cloud metadata on windows."""
    client_id = self._SetupMinimalClient()
    with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                   vfs_test_lib.FakeRegistryVFSHandler):
      with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                     vfs_test_lib.FakeFullVFSHandler):
        client_mock = action_mocks.InterrogatedClient()
        client_mock.InitializeClient(
            system="Windows", version="6.1.7600", kernel="6.1.7601")
        with mock.patch.object(platform, "system", return_value="Windows"):
          flow_test_lib.TestFlowHelper(
              discovery.Interrogate.__name__,
              client_mock,
              token=self.token,
              client_id=client_id)

    client = self._OpenClient(client_id)
    self._CheckCloudMetadata(client)
示例#29
0
  def testInterrogateCloudMetadataWindows(self):
    """Check google cloud metadata on windows."""
    self.SetupClients(1, system="Windows", os_version="6.2", arch="AMD64")
    with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.REGISTRY,
                                   vfs_test_lib.FakeRegistryVFSHandler):
      with vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                     vfs_test_lib.FakeFullVFSHandler):
        client_mock = action_mocks.InterrogatedClient()
        client_mock.InitializeClient(
            system="Windows", version="6.1.7600", kernel="6.1.7601")
        with mock.patch.object(platform, "system", return_value="Windows"):
          for _ in flow_test_lib.TestFlowHelper(
              discovery.Interrogate.__name__,
              client_mock,
              token=self.token,
              client_id=self.client_id):
            pass

        self.fd = aff4.FACTORY.Open(self.client_id, token=self.token)
        self._CheckCloudMetadata()
示例#30
0
class VFSMultiOpenTest(absltest.TestCase):

    _VFS_OVERRIDER = vfs_test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                               files.File)

    def setUp(self):
        self._VFS_OVERRIDER.Start()

    def tearDown(self):
        self._VFS_OVERRIDER.Stop()

    def testMultipleFiles(self):
        with temp.AutoTempDirPath(remove_non_empty=True) as tempdir:
            foo_path = os.path.join(tempdir, "foo")
            bar_path = os.path.join(tempdir, "bar")
            baz_path = os.path.join(tempdir, "baz")

            self._Touch(foo_path, b"FOO")
            self._Touch(bar_path, b"BAR")
            self._Touch(baz_path, b"BAZ")

            foo_pathspec = rdf_paths.PathSpec(
                pathtype=rdf_paths.PathSpec.PathType.OS, path=foo_path)
            bar_pathspec = rdf_paths.PathSpec(
                pathtype=rdf_paths.PathSpec.PathType.OS, path=bar_path)
            baz_pathspec = rdf_paths.PathSpec(
                pathtype=rdf_paths.PathSpec.PathType.OS, path=baz_path)

            pathspecs = [foo_pathspec, bar_pathspec, baz_pathspec]
            with vfs.VFSMultiOpen(pathspecs) as filedescs:
                self.assertLen(filedescs, 3)
                self.assertEqual(filedescs[0].Read(), b"FOO")
                self.assertEqual(filedescs[1].Read(), b"BAR")
                self.assertEqual(filedescs[2].Read(), b"BAZ")

    def testProgressCallback(self):
        with temp.AutoTempFilePath() as temppath:
            self._Touch(temppath, b"QUUX")

            pathspec = rdf_paths.PathSpec(
                pathtype=rdf_paths.PathSpec.PathType.OS, path=temppath)

            func = mock.MagicMock()

            with vfs.VFSMultiOpen([pathspec],
                                  progress_callback=func) as filedescs:
                self.assertLen(filedescs, 1)
                self.assertEqual(filedescs[0].Read(), b"QUUX")

            self.assertTrue(func.called)

    def _Touch(self, filepath, content=b""):
        with io.open(filepath, mode="wb") as filedesc:
            filedesc.write(content)