Esempio n. 1
0
    def testGenerateArchiveButtonGetsDisabledAfterClick(self):
        pathspec = rdf_paths.PathSpec(path=os.path.join(
            self.base_path, "test.plist"),
                                      pathtype=rdf_paths.PathSpec.PathType.OS)
        for _ in test_lib.TestFlowHelper(flows_transfer.GetFile.__name__,
                                         self.action_mock,
                                         client_id=self.client_id,
                                         pathspec=pathspec,
                                         token=self.token):
            pass

        self.Open("/#c=C.0000000000000001")
        self.Click("css=a[grrtarget='client.flows']")
        self.Click("css=td:contains('GetFile')")
        self.Click("link=Results")
        self.Click("css=button.DownloadButton")

        self.WaitUntil(self.IsElementPresent,
                       "css=button.DownloadButton[disabled]")
        self.WaitUntil(self.IsTextPresent, "Generation has started")
Esempio n. 2
0
    def _RunTSKFileFinder(self, paths):

        image_path = os.path.join(self.base_path, "ntfs_img.dd")
        with utils.Stubber(
                vfs, "VFS_VIRTUALROOTS", {
                    rdf_paths.PathSpec.PathType.TSK:
                    rdf_paths.PathSpec(
                        path=image_path, pathtype="OS", offset=63 * 512)
                }):

            action = file_finder.FileFinderAction.Action.DOWNLOAD
            for _ in test_lib.TestFlowHelper(
                    "FileFinder",
                    self.client_mock,
                    client_id=self.client_id,
                    paths=paths,
                    pathtype=rdf_paths.PathSpec.PathType.TSK,
                    action=file_finder.FileFinderAction(action_type=action),
                    token=self.token):
                pass
Esempio n. 3
0
    def testNormalGrep(self):
        grepspec = rdf_client.BareGrepSpec(
            mode=rdf_client.GrepSpec.Mode.FIRST_HIT, literal="hello")

        for s in test_lib.TestFlowHelper(
                "SearchFileContent",
                self.client_mock,
                client_id=self.client_id,
                paths=["/proc/10/cmdline"],
                pathtype=rdf_paths.PathSpec.PathType.OS,
                token=self.token,
                grep=grepspec):
            session_id = s

        fd = flow.GRRFlow.ResultCollectionForFID(session_id, token=self.token)

        self.assertEqual(len(fd), 1)
        self.assertEqual(fd[0].offset, 3)
        self.assertEqual(fd[0], "ls\x00hello world\'\x00-l")
        self.assertEqual(fd[0].length, 18)
Esempio n. 4
0
    def testShowsGenerateArchiveButtonForGetFileFlow(self):
        pathspec = rdf_paths.PathSpec(path=os.path.join(
            self.base_path, "test.plist"),
                                      pathtype=rdf_paths.PathSpec.PathType.OS)
        with self.ACLChecksDisabled():
            for _ in test_lib.TestFlowHelper("GetFile",
                                             self.action_mock,
                                             client_id=self.client_id,
                                             pathspec=pathspec,
                                             token=self.token):
                pass

        self.Open("/#c=C.0000000000000001")
        self.Click("css=a:contains('Manage launched flows')")
        self.Click("css=td:contains('GetFile')")
        self.Click("link=Results")

        self.WaitUntil(
            self.IsTextPresent,
            "Files referenced in this collection can be downloaded")
Esempio n. 5
0
    def testLogsCanBeOpenedByClickingOnLogsTab(self):
        client_id = rdfvalue.ClientURN("C.0000000000000001")

        # RecursiveTestFlow doesn't send any results back.
        with self.ACLChecksDisabled():
            for _ in test_lib.TestFlowHelper("RecursiveTestFlow",
                                             action_mocks.ActionMock(),
                                             client_id=client_id,
                                             token=self.token):
                pass

            self.GrantClientApproval(client_id)

        self.Open("/#c=C.0000000000000001")
        self.Click("css=a:contains('Manage launched flows')")
        self.Click("css=td:contains('RecursiveTestFlow')")
        self.Click("css=a[renderer=FlowLogView]")

        self.WaitUntil(self.IsTextPresent, "Subflow call 1")
        self.WaitUntil(self.IsTextPresent, "Subflow call 0")
Esempio n. 6
0
    def testDiskVolumeInfoOSXLinux(self):
        client_mock = action_mocks.UnixVolumeClientMock(
            "StatFile", "ListDirectory")
        with test_lib.Instrument(flow.GRRFlow, "SendReply") as send_reply:
            for _ in test_lib.TestFlowHelper("DiskVolumeInfo",
                                             client_mock,
                                             client_id=self.client_id,
                                             token=self.token,
                                             path_list=["/usr/local",
                                                        "/home"]):
                pass

            results = []
            for _, reply in send_reply.args:
                if isinstance(reply, rdfvalue.Volume):
                    results.append(reply)

            self.assertItemsEqual([x.unix.mount_point for x in results],
                                  ["/", "/usr"])
            self.assertEqual(len(results), 2)
Esempio n. 7
0
  def testLoadDriverWindows(self):
    """Tests the memory driver deployment flow."""
    self.CreateSignedDriver()
    self.CreateClient()

    # Run the flow in the simulated way
    for _ in test_lib.TestFlowHelper("LoadMemoryDriver",
                                     action_mocks.MemoryClientMock(),
                                     token=self.token,
                                     client_id=self.client_id):
      pass

    device_urn = self.client_id.Add("devices/memory")
    fd = aff4.FACTORY.Open(device_urn, mode="r", token=self.token)
    runs = fd.Get(fd.Schema.LAYOUT).runs

    self.assertEqual(runs[0].offset, 0x1000)
    self.assertEqual(runs[0].length, 0x10000)
    self.assertEqual(runs[1].offset, 0x20000)
    self.assertEqual(runs[0].length, 0x10000)
Esempio n. 8
0
    def testListVolumeShadowCopies(self):
        """Test the list Volume Shadow Copies flow."""
        flow_name = "ListVolumeShadowCopies"

        # Run the flow in the simulated way
        for _ in test_lib.TestFlowHelper(flow_name,
                                         TestClient(),
                                         token=self.token,
                                         client_id=self.client_id):
            pass

        fd = aff4.FACTORY.Open(
            self.client_id.Add("fs/tsk/\\\\.\\HarddiskVolumeShadowCopy3"),
            token=self.token)

        children = list(fd.ListChildren())

        self.assertEqual(len(children), 10)
        self.assertEqual([x.Basename() for x in sorted(children)],
                         ["file %s" % i for i in range(10)])
Esempio n. 9
0
  def testIllegalGlobAsync(self):
    # When running the flow asynchronously, we will not receive any errors from
    # the Start method, but the flow should still fail.
    paths = ["Test/%%Weird_illegal_attribute%%"]
    client_mock = action_mocks.ActionMock("Find", "StatFile")

    # Run the flow.
    session_id = None

    # This should not raise here since the flow is run asynchronously.
    for session_id in test_lib.TestFlowHelper(
        "Glob", client_mock, client_id=self.client_id, check_flow_errors=False,
        paths=paths, pathtype=rdf_paths.PathSpec.PathType.OS, token=self.token,
        sync=False):
      pass

    fd = aff4.FACTORY.Open(session_id, token=self.token)
    self.assertTrue(
        "KnowledgeBaseInterpolationError" in fd.state.context.backtrace)
    self.assertEqual("ERROR", str(fd.state.context.state))
Esempio n. 10
0
  def testFlowSerialization2(self):
    """Check that we can unpickle flows."""

    class TestClientMock(object):

      in_rdfvalue = rdf_client.EchoRequest
      out_rdfvalue = rdf_protodict.DataBlob

      def __init__(self):
        # Register us as an action plugin.
        actions.ActionPlugin.classes["ReturnBlob"] = self

      def ReturnBlob(self, unused_args):
        return [rdf_protodict.DataBlob(integer=100)]

    # Run the flow in the simulated way
    for _ in test_lib.TestFlowHelper("FlowResponseSerialization",
                                     TestClientMock(), token=self.token,
                                     client_id=self.client_id):
      pass
Esempio n. 11
0
  def testCreatorPropagation(self):

    # Instantiate the flow using one username.
    session_id = flow.GRRFlow.StartFlow(
        client_id=self.client_id, flow_name="ParentFlow", sync=False,
        token=access_control.ACLToken(username="******",
                                      reason="testing"))

    # Run the flow using another user ("test").
    for _ in test_lib.TestFlowHelper(session_id, ClientMock(),
                                     client_id=self.client_id,
                                     token=self.token):
      pass

    self.assertEqual(ParentFlow.success, True)
    subflows = list(aff4.FACTORY.Open(
        session_id, token=self.token).ListChildren())
    self.assertEqual(len(subflows), 1)
    child_flow = aff4.FACTORY.Open(subflows[0], token=self.token)
    self.assertEqual(child_flow.GetRunner().context.creator, "original_user")
Esempio n. 12
0
    def Run(self):
        failing_descriptor = output_plugin.OutputPluginDescriptor(
            plugin_name=standard_test.FailingDummyHuntOutputPlugin.__name__)

        with test_lib.FakeTime(42):
            flow_urn = flow.GRRFlow.StartFlow(
                flow_name=DummyFlowWithSingleReply.__name__,
                client_id=self.client_id,
                output_plugins=[failing_descriptor],
                token=self.token)

        with test_lib.FakeTime(43):
            for _ in test_lib.TestFlowHelper(flow_urn, token=self.token):
                pass

        self.Check("GET",
                   "/api/clients/%s/flows/%s/output-plugins/"
                   "FailingDummyHuntOutputPlugin_0/errors" %
                   (self.client_id.Basename(), flow_urn.Basename()),
                   replace={flow_urn.Basename(): "W:ABCDEF"})
Esempio n. 13
0
  def testKnowledgeBaseRetrievalDarwin(self):
    """Check we can retrieve a Darwin kb."""
    self.ClearKB()
    with test_lib.ConfigOverrider({"Artifacts.knowledge_base": ["OSXUsers"]}):
      with test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                 test_lib.ClientVFSHandlerFixture):

        for _ in test_lib.TestFlowHelper(
            "KnowledgeBaseInitializationFlow", 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")
Esempio n. 14
0
  def testGlobRegistry(self):
    """Test that glob works on registry."""
    paths = ["HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT"
             "\\CurrentVersion\\ProfileList\\ProfilesDirectory",
             "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT"
             "\\CurrentVersion\\ProfileList\\AllUsersProfile"]

    for _ in test_lib.TestFlowHelper(
        "Glob", self.client_mock, paths=paths,
        pathtype=rdf_paths.PathSpec.PathType.REGISTRY,
        client_id=self.client_id, token=self.token):
      pass

    path = paths[0].replace("\\", "/")

    fd = aff4.FACTORY.Open(self.client_id.Add("registry").Add(path),
                           token=self.token)
    self.assertEqual(fd.__class__.__name__, "VFSFile")
    self.assertEqual(fd.Get(fd.Schema.STAT).registry_data.GetValue(),
                     "%SystemDrive%\\Users")
Esempio n. 15
0
    def testSystemRootFallback(self):
        with test_lib.VFSOverrider(rdf_paths.PathSpec.PathType.OS,
                                   test_lib.ClientVFSHandlerFixture):
            client_mock = action_mocks.ActionMock("ListDirectory", "StatFile")

            for _ in test_lib.TestFlowHelper(
                    "SystemRootSystemDriveFallbackFlow",
                    client_mock,
                    client_id=self.client_id,
                    token=self.token,
                    artifact_name="SystemRoot",
                    output="systemroot"):
                pass

            output_fd = aff4.FACTORY.Open(self.client_id.Add("systemroot"),
                                          token=self.token)

            self.assertEqual(len(output_fd), 1)
            self.assertEqual(str(output_fd[0].registry_data.GetValue()),
                             r"C:\WINDOWS")
Esempio n. 16
0
  def ReadTestImage(self, size_threshold):
    path = os.path.join(self.base_path, "test_img.dd")

    urn = rdfvalue.RDFURN(self.client_id.Add("fs/os").Add(path))

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

    client_mock = action_mocks.ActionMock("FingerprintFile", "HashBuffer",
                                          "HashFile", "StatFile", "Find",
                                          "TransferBuffer", "ReadBuffer")

    # Get everything as an AFF4SparseImage
    for _ in test_lib.TestFlowHelper(
        "MakeNewAFF4SparseImage", client_mock, client_id=self.client_id,
        token=self.token, size_threshold=size_threshold, pathspec=pathspec):
      pass

    fd = aff4.FACTORY.Open(urn, token=self.token)
    return fd
Esempio n. 17
0
    def testGRRVersionBreakDown(self):
        """Check that all client stats cron jobs are run.

    All machines should be in All once.
    Windows machines should be in Label1 and Label2.
    There should be no stats for UserLabel.
    """
        for _ in test_lib.TestFlowHelper("GRRVersionBreakDown",
                                         token=self.token):
            pass

        histogram = aff4_stats.ClientFleetStats.SchemaCls.GRRVERSION_HISTOGRAM
        self._CheckVersionStats("All", histogram, [0, 0, 20, 20])
        self._CheckVersionStats("Label1", histogram, [0, 0, 10, 10])
        self._CheckVersionStats("Label2", histogram, [0, 0, 10, 10])

        # This shouldn't exist since it isn't a system label
        aff4.FACTORY.Open("aff4:/stats/ClientFleetStats/UserLabel",
                          aff4.AFF4Volume,
                          token=self.token)
Esempio n. 18
0
    def testNotifiesUserWithDownloadFileNotification(self):

        with utils.Stubber(email_alerts.EMAIL_ALERTER, "SendEmail",
                           self.SendEmailMock):
            self.email_messages = []
            for _ in test_lib.TestFlowHelper("ExportHuntResultFilesAsArchive",
                                             None,
                                             hunt_urn=self.hunt_urn,
                                             token=self.token):
                pass

            self._CheckEmailMessage(self.email_messages)

        user_fd = aff4.FACTORY.Open(aff4.ROOT_URN.Add("users").Add("test"),
                                    token=self.token)
        notifications = user_fd.Get(user_fd.Schema.PENDING_NOTIFICATIONS)
        self.assertEqual(len(notifications), 1)
        self.assertEqual(notifications[0].type, "DownloadFile")
        self.assertTrue(notifications[0].message.startswith(
            "Hunt results ready for download (archived 2 out of 2 results"))
Esempio n. 19
0
    def testDoesNotFetchDuplicates(self):
        process = "\\WINDOWS\\bar.exe"
        client_mock = ListVADBinariesActionMock([process, process])

        for s in test_lib.TestFlowHelper("ListVADBinaries",
                                         client_mock,
                                         client_id=self.client_id,
                                         fetch_binaries=True,
                                         token=self.token):
            session_id = s

        fd = flow.GRRFlow.ResultCollectionForFID(session_id, token=self.token)
        binaries = list(fd)

        self.assertEqual(len(binaries), 1)
        self.assertEqual(binaries[0].pathspec.CollapsePath(),
                         "/C:/WINDOWS/bar.exe")
        fd = aff4.FACTORY.Open(binaries[0].AFF4Path(self.client_id),
                               token=self.token)
        self.assertEqual(fd.Read(1024), "just bar")
Esempio n. 20
0
  def testHashesAreDisplayedCorrectly(self):
    with self.ACLChecksDisabled():
      for _ in test_lib.TestFlowHelper(
          "FlowWithOneHashEntryResult",
          self.action_mock,
          client_id=self.client_id,
          token=self.token):
        pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneHashEntryResult')")
    self.Click("css=li[heading=Results]")

    self.WaitUntil(self.IsTextPresent,
                   "9e8dc93e150021bb4752029ebbff51394aa36f069cf19901578"
                   "e4f06017acdb5")
    self.WaitUntil(self.IsTextPresent,
                   "6dd6bee591dfcb6d75eb705405302c3eab65e21a")
    self.WaitUntil(self.IsTextPresent, "8b0a15eefe63fd41f8dc9dee01c5cf9a")
    def RunFlow(self, artifact_list=None, use_tsk=False):
        if artifact_list is None:
            artifact_list = ["WindowsRunKeys"]

        urn = flow.GRRFlow.StartFlow(flow_name="ArtifactFilesDownloaderFlow",
                                     client_id=self.client_id,
                                     artifact_list=artifact_list,
                                     use_tsk=use_tsk,
                                     token=self.token)
        for _ in test_lib.TestFlowHelper(urn, token=self.token):
            pass

        try:
            results_fd = aff4.FACTORY.Open(
                urn.Add(flow_runner.RESULTS_SUFFIX),
                aff4_type=sequential_collection.GeneralIndexedCollection,
                token=self.token)
            return list(results_fd)
        except aff4.InstantiationError:
            return []
Esempio n. 22
0
    def testGlobWithStarStarRootPath(self):
        """Test ** expressions with root_path."""

        # Add some usernames we can interpolate later.
        client = aff4.FACTORY.Open(self.client_id, mode="rw", token=self.token)
        kb = client.Get(client.Schema.KNOWLEDGE_BASE)
        kb.MergeOrAddUser(rdf_client.User(username="******"))
        kb.MergeOrAddUser(rdf_client.User(username="******"))
        client.Set(kb)
        client.Close()

        client_mock = action_mocks.ActionMock("Find", "StatFile")

        # Glob for foo at a depth of 4.
        path = os.path.join("foo**4")
        root_path = rdf_paths.PathSpec(path=os.path.join(
            self.base_path, "test_img.dd"),
                                       pathtype=rdf_paths.PathSpec.PathType.OS)
        root_path.Append(path="/", pathtype=rdf_paths.PathSpec.PathType.TSK)

        # Run the flow.
        for _ in test_lib.TestFlowHelper(
                "Glob",
                client_mock,
                client_id=self.client_id,
                paths=[path],
                root_path=root_path,
                pathtype=rdf_paths.PathSpec.PathType.OS,
                token=self.token):
            pass

        output_path = self.client_id.Add("fs/tsk").Add(
            self.base_path.replace("\\", "/")).Add("test_img.dd/glob_test/a/b")

        children = []
        fd = aff4.FACTORY.Open(output_path, token=self.token)
        for child in fd.ListChildren():
            children.append(child.Basename())

        # We should find some files.
        self.assertEqual(children, ["foo"])
Esempio n. 23
0
    def LaunchRekallPlugin(self, request):
        """Launch AnalyzeClientMemory flow and return its output as a string.

    Args:
      request: A RekallRequest() proto.
    """
        # For this test we force the client to write the profile cache in the temp
        # directory. This forces the profiles to always be downloaded from the
        # server (since each test run gets a new temp directory).
        with test_lib.ConfigOverrider(
            {"Client.rekall_profile_cache_path": self.temp_dir}):
            image_path = os.path.join(self.base_path, "win7_trial_64bit.raw")
            request.device.path = image_path

            self.CreateClient()

            # Allow the real RekallAction to run against the image.
            for _ in test_lib.TestFlowHelper("AnalyzeClientMemory",
                                             action_mocks.MemoryClientMock(
                                                 "RekallAction",
                                                 "WriteRekallProfile",
                                                 "DeleteGRRTempFiles"),
                                             token=self.token,
                                             client_id=self.client_id,
                                             request=request,
                                             output="analysis/memory"):
                pass

            # Check that the profiles are also cached locally.
            test_profile_dir = os.path.join(config_lib.CONFIG["Test.data_dir"],
                                            "profiles")
            self.assertEqual(
                json.load(gzip.open(os.path.join(self.temp_dir,
                                                 "v1.0/pe.gz"))),
                json.load(
                    gzip.open(os.path.join(test_profile_dir, "v1.0/pe.gz"))))

            p_name = "v1.0/nt/GUID/F8E2A8B5C9B74BF4A6E4A48F180099942.gz"
            self.assertEqual(
                json.load(gzip.open(os.path.join(self.temp_dir, p_name))),
                json.load(gzip.open(os.path.join(test_profile_dir, p_name))))
Esempio n. 24
0
    def testVFSFileStartsNewMultiGetFileWhenLockingFlowHasFinished(self):
        """A new MultiFileGet can be started when the locking flow has finished."""
        client_id = self.SetupClients(1)[0]
        test_lib.ClientFixture(client_id, token=self.token)
        # We need to choose a file path having a pathsepc.
        path = "fs/os/c/bin/bash"

        with aff4.FACTORY.Create(client_id.Add(path),
                                 aff4_type=aff4_grr.VFSFile,
                                 mode="rw",
                                 token=self.token) as file_fd:
            # Starts a MultiGetFile flow.
            first_update_flow_urn = file_fd.Update()

        # Check that there is exactly one flow on the client.
        flows_fd = aff4.FACTORY.Open(client_id.Add("flows"), token=self.token)
        flows = list(flows_fd.ListChildren())
        self.assertEqual(len(flows), 1)

        # Finish the flow holding the lock.
        client_mock = action_mocks.ActionMock()
        for _ in test_lib.TestFlowHelper(flows[0],
                                         client_mock,
                                         client_id=client_id,
                                         token=self.token):
            pass

        # The flow holding the lock has finished, so Update() should start a new
        # flow.
        second_update_flow_urn = file_fd.Update()

        # There should be two flows now.
        flows_fd = aff4.FACTORY.Open(client_id.Add("flows"), token=self.token)
        flows = list(flows_fd.ListChildren())
        self.assertEqual(len(flows), 2)

        # Make sure that each Update() started a new flow and that the second flow
        # is holding the lock.
        self.assertNotEqual(first_update_flow_urn, second_update_flow_urn)
        self.assertEqual(second_update_flow_urn,
                         file_fd.Get(file_fd.Schema.CONTENT_LOCK))
Esempio n. 25
0
    def testLastRunStatusGetsUpdatedOnEveryRun(self):
        cron_manager = cronjobs.CronManager()
        cron_args = cronjobs.CreateCronJobFlowArgs()
        cron_args.flow_runner_args.flow_name = "OccasionallyFailingFakeCronJob"
        cron_args.periodicity = "30s"

        cron_job_urn = cron_manager.ScheduleFlow(cron_args=cron_args,
                                                 token=self.token)

        for fake_time in [0, 60]:
            with test_lib.FakeTime(fake_time):
                # This call should start a new cron job flow
                cron_manager.RunOnce(token=self.token)
                cron_job = aff4.FACTORY.Open(cron_job_urn,
                                             aff4_type=cronjobs.CronJob,
                                             token=self.token)
                cron_flow_urn = cron_job.Get(cron_job.Schema.CURRENT_FLOW_URN)
                for _ in test_lib.TestFlowHelper(cron_flow_urn,
                                                 check_flow_errors=False,
                                                 token=self.token):
                    pass
                # This RunOnce call should determine that the flow has finished
                cron_manager.RunOnce(token=self.token)

        cron_job = aff4.FACTORY.Open(cron_job_urn,
                                     age=aff4.ALL_TIMES,
                                     token=self.token)
        statuses = list(
            cron_job.GetValuesForAttribute(cron_job.Schema.LAST_RUN_STATUS))

        statuses = sorted(statuses, key=lambda x: x.age)
        self.assertEqual(len(statuses), 2)

        self.assertEqual(statuses[0].age,
                         rdfvalue.RDFDatetime().FromSecondsFromEpoch(0))
        self.assertEqual(statuses[1].age,
                         rdfvalue.RDFDatetime().FromSecondsFromEpoch(60))
        self.assertEqual(statuses[0].status,
                         grr_rdf.CronJobRunStatus.Status.OK)
        self.assertEqual(statuses[1].status,
                         grr_rdf.CronJobRunStatus.Status.ERROR)
Esempio n. 26
0
  def testExecuteBinariesWithArgs(self):
    client_mock = action_mocks.ActionMock("ExecuteBinaryCommand")

    code = "I am a binary file"
    upload_path = config_lib.CONFIG["Executables.aff4_path"].Add("test.exe")

    maintenance_utils.UploadSignedConfigBlob(code,
                                             aff4_path=upload_path,
                                             token=self.token)

    # This flow has an acl, the user needs to be admin.
    user = aff4.FACTORY.Create("aff4:/users/%s" % self.token.username,
                               mode="rw",
                               aff4_type=users.GRRUser,
                               token=self.token)
    user.SetLabels("admin", owner="GRR")
    user.Close()

    with utils.Stubber(subprocess, "Popen", test_lib.Popen):
      for _ in test_lib.TestFlowHelper("LaunchBinary",
                                       client_mock,
                                       client_id=self.client_id,
                                       binary=upload_path,
                                       command_line="--value 356",
                                       token=self.token):
        pass

      # Check that the executable file contains the code string.
      self.assertEqual(test_lib.Popen.binary, code)

      # At this point, the actual binary should have been cleaned up by the
      # client action so it should not exist.
      self.assertRaises(IOError, open, test_lib.Popen.running_args[0])

      # Check the binary was run with the correct command line.
      self.assertEqual(test_lib.Popen.running_args[1], "--value")
      self.assertEqual(test_lib.Popen.running_args[2], "356")

      # Check the command was in the tmp file.
      self.assertTrue(test_lib.Popen.running_args[0].startswith(
          config_lib.CONFIG["Client.tempdir_roots"][0]))
Esempio n. 27
0
  def testInterrogateWindows(self):
    """Test the Interrogate flow."""

    test_lib.ClientFixture(self.client_id, token=self.token)

    vfs.VFS_HANDLERS[
        rdfvalue.PathSpec.PathType.REGISTRY] = test_lib.FakeRegistryVFSHandler
    vfs.VFS_HANDLERS[
        rdfvalue.PathSpec.PathType.OS] = test_lib.FakeFullVFSHandler

    client_mock = action_mocks.InterrogatedClient("TransferBuffer", "StatFile",
                                                  "Find", "HashBuffer",
                                                  "ListDirectory",
                                                  "FingerprintFile")

    self.SetWindowsClient()
    client_mock.InitializeClient(system="Windows", version="6.1.7600")

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

    self.fd = aff4.FACTORY.Open(self.client_id, token=self.token)
    self._CheckAFF4Object("test_node", "Windows", 100 * 1000000)
    self._CheckClientInfo()
    self._CheckClientIndex(".*Host.*")
    self._CheckGRRConfig()
    self._CheckNotificationsCreated()
    self._CheckClientSummary("Windows", "6.1.7600")

    # users Bert and Ernie added by the fixture should not be present (USERS
    # overriden by kb)
    # jim parsed from registry profile keys
    self._CheckUsers(["jim", "kovacs"])
    self._CheckNetworkInfo()
    self._CheckVFS()
    self._CheckLabelIndex()
    self._CheckWindowsDiskInfo()
    self._CheckRegistryPathspec()
Esempio n. 28
0
    def testProcessListingFilterConnectionState(self):
        p1 = rdf_client.Process(pid=2,
                                ppid=1,
                                cmdline=["cmd.exe"],
                                exe="c:\\windows\\cmd.exe",
                                ctime=long(1333718907.167083 * 1e6),
                                connections=rdf_client.NetworkConnection(
                                    family="INET", state="CLOSED"))
        p2 = rdf_client.Process(pid=3,
                                ppid=1,
                                cmdline=["cmd2.exe"],
                                exe="c:\\windows\\cmd2.exe",
                                ctime=long(1333718907.167083 * 1e6),
                                connections=rdf_client.NetworkConnection(
                                    family="INET", state="LISTEN"))
        p3 = rdf_client.Process(pid=4,
                                ppid=1,
                                cmdline=["missing_exe.exe"],
                                ctime=long(1333718907.167083 * 1e6),
                                connections=rdf_client.NetworkConnection(
                                    family="INET", state="ESTABLISHED"))
        client_mock = ListProcessesMock([p1, p2, p3])

        flow_urn = flow.GRRFlow.StartFlow(
            client_id=self.client_id,
            flow_name="ListProcesses",
            connection_states=["ESTABLISHED", "LISTEN"],
            token=self.token)
        for s in test_lib.TestFlowHelper(flow_urn,
                                         client_mock,
                                         client_id=self.client_id,
                                         token=self.token):
            session_id = s

        processes = flow.GRRFlow.ResultCollectionForFID(session_id,
                                                        token=self.token)
        self.assertEqual(len(processes), 2)
        states = set()
        for process in processes:
            states.add(str(process.connections[0].state))
        self.assertItemsEqual(states, ["ESTABLISHED", "LISTEN"])
Esempio n. 29
0
  def testInterrogateLinuxWithWtmp(self):
    """Test the Interrogate flow."""
    test_lib.ClientFixture(self.client_id, token=self.token)

    vfs.VFS_HANDLERS[
        rdf_paths.PathSpec.PathType.OS] = test_lib.FakeTestDataVFSHandler

    config_lib.CONFIG.Set("Artifacts.knowledge_base", ["LinuxWtmp",
                                                       "NetgroupConfiguration",
                                                       "LinuxRelease"])
    config_lib.CONFIG.Set("Artifacts.netgroup_filter_regexes", [r"^login$"])
    self.SetLinuxClient()
    client_mock = action_mocks.InterrogatedClient(
        "TransferBuffer", "StatFile", "Find", "HashBuffer",
        "ListDirectory", "FingerprintFile", "GetLibraryVersions")
    client_mock.InitializeClient()

    for _ in test_lib.TestFlowHelper("Interrogate", client_mock,
                                     token=self.token,
                                     client_id=self.client_id):
      pass

    self.fd = aff4.FACTORY.Open(self.client_id, token=self.token)
    self._CheckAFF4Object("test_node", "Linux", 100 * 1000000)
    self._CheckClientInfo()
    self._CheckClientIndex(".*test.*")
    self._CheckGRRConfig()
    self._CheckNotificationsCreated()
    self._CheckClientSummary("Linux", "14.4", release="Ubuntu",
                             kernel="3.13.0-39-generic")
    self._CheckRelease("Ubuntu", "14.4")

    # users 1,2,3 from wtmp
    # users yagharek, isaac from netgroup
    self._CheckUsers(["yagharek", "isaac", "user1", "user2", "user3"])
    self._CheckNetworkInfo()
    self._CheckVFS()
    self._CheckLabelIndex()
    self._CheckClientKwIndex(["Linux"], 1)
    self._CheckClientKwIndex(["Label2"], 1)
    self._CheckClientLibraries()
Esempio n. 30
0
    def RunFlowAndCheckResults(self,
                               conditions=None,
                               action=rdfvalue.FileFinderAction.Action.STAT,
                               expected_files=None,
                               non_expected_files=None):

        conditions = conditions or []
        expected_files = expected_files or []
        non_expected_files = non_expected_files or []

        for fname in expected_files + non_expected_files:
            aff4.FACTORY.Delete(self.FileNameToURN(fname), token=self.token)

        with test_lib.Instrument(flow.GRRFlow, "SendReply") as send_reply:
            for _ in test_lib.TestFlowHelper(
                    "FileFinder",
                    self.client_mock,
                    client_id=self.client_id,
                    paths=[self.path],
                    pathtype=rdfvalue.PathSpec.PathType.OS,
                    action=rdfvalue.FileFinderAction(action_type=action),
                    conditions=conditions,
                    token=self.token,
                    output=self.output_path):
                pass

            self.CheckReplies(send_reply.args, action, expected_files)

        self.CheckFilesInCollection(expected_files)

        if action == rdfvalue.FileFinderAction.Action.STAT:
            self.CheckFilesNotDownloaded(expected_files + non_expected_files)
            self.CheckFilesNotHashed(expected_files + non_expected_files)
        elif action == rdfvalue.FileFinderAction.Action.DOWNLOAD:
            self.CheckFilesDownloaded(expected_files)
            self.CheckFilesNotDownloaded(non_expected_files)
            # Downloaded files are hashed to allow for deduping.
        elif action == rdfvalue.FileFinderAction.Action.HASH:
            self.CheckFilesNotDownloaded(expected_files + non_expected_files)
            self.CheckFilesHashed(expected_files)
            self.CheckFilesNotHashed(non_expected_files)