Esempio n. 1
0
    def SetUpCrashedFlowInHunt(self):
        client_ids = self.SetupClients(10)
        client_mocks = dict([
            (client_id, flow_test_lib.CrashClientMock(client_id, self.token))
            for client_id in client_ids
        ])

        client_rule_set = self._CreateForemanClientRuleSet()
        # Make this not match anything.
        client_rule_set.rules[0].regex.attribute_regex = ""

        with implementation.StartHunt(hunt_name=standard.SampleHunt.__name__,
                                      client_rule_set=client_rule_set,
                                      client_rate=0,
                                      token=self.token) as hunt:
            hunt.Run()

        foreman_obj = foreman.GetForeman(token=self.token)
        for client_id in client_ids:
            self.assertTrue(
                foreman_obj.AssignTasksToClient(client_id.Basename()))
        hunt_test_lib.TestHuntHelperWithMultipleMocks(client_mocks, False,
                                                      self.token)

        return client_ids
Esempio n. 2
0
    def CreateSampleHunt(self,
                         path=None,
                         stopped=False,
                         output_plugins=None,
                         client_limit=0,
                         client_count=10,
                         token=None):
        token = token or self.token
        self.client_ids = self.SetupClients(client_count)

        with implementation.StartHunt(
                hunt_name=standard.GenericHunt.__name__,
                flow_runner_args=rdf_flow_runner.FlowRunnerArgs(
                    flow_name=transfer.GetFile.__name__),
                flow_args=transfer.GetFileArgs(pathspec=rdf_paths.PathSpec(
                    path=path or "/tmp/evil.txt",
                    pathtype=rdf_paths.PathSpec.PathType.OS,
                )),
                client_rule_set=self._CreateForemanClientRuleSet(),
                output_plugins=output_plugins or [],
                client_rate=0,
                client_limit=client_limit,
                token=token) as hunt:
            if not stopped:
                hunt.Run()

        foreman_obj = foreman.GetForeman(token=token)
        for client_id in self.client_ids:
            foreman_obj.AssignTasksToClient(client_id.Basename())

        self.hunt_urn = hunt.urn
        return aff4.FACTORY.Open(hunt.urn,
                                 mode="rw",
                                 token=token,
                                 age=aff4.ALL_TIMES)
Esempio n. 3
0
    def testHuntIsStoppedWhenExpirationTimeIsReached(self):
        client_ids = self.SetupClients(5)

        duration = rdfvalue.Duration("1d")
        expiry_time = rdfvalue.RDFDatetime.Now() + duration

        hunt_id = self._CreateHunt(
            client_rule_set=foreman_rules.ForemanClientRuleSet(),
            client_rate=0,
            duration=duration,
            args=self.GetFileHuntArgs())

        client_mock = hunt_test_lib.SampleHuntMock(failrate=-1)
        foreman_obj = foreman.GetForeman()
        for client_id in client_ids:
            foreman_obj.AssignTasksToClient(client_id.Basename())

        hunt_test_lib.TestHuntHelper(client_mock, client_ids[:3], False)
        hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
        self.assertEqual(hunt_obj.hunt_state,
                         rdf_hunt_objects.Hunt.HuntState.STARTED)

        with test_lib.FakeTime(expiry_time - rdfvalue.Duration("1s")):
            hunt_test_lib.TestHuntHelper(client_mock, client_ids[3:4], False)
            hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
            self.assertEqual(hunt_obj.hunt_state,
                             rdf_hunt_objects.Hunt.HuntState.STARTED)

        with test_lib.FakeTime(expiry_time + rdfvalue.Duration("1s")):
            hunt_test_lib.TestHuntHelper(client_mock, client_ids[4:5], False)
            hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
            self.assertEqual(hunt_obj.hunt_state,
                             rdf_hunt_objects.Hunt.HuntState.COMPLETED)
Esempio n. 4
0
    def testForemanRulesWorkCorrectlyWithStandardHunt(self):
        client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
            foreman_rules.ForemanClientRule(
                rule_type=foreman_rules.ForemanClientRule.Type.OS,
                os=foreman_rules.ForemanOsClientRule(os_windows=True))
        ])
        hunt_obj = rdf_hunt_objects.Hunt(client_rule_set=client_rule_set,
                                         client_rate=0,
                                         args=self.GetFileHuntArgs())
        hunt_obj.args.hunt_type = hunt_obj.args.HuntType.STANDARD
        data_store.REL_DB.WriteHuntObject(hunt_obj)

        hunt_obj = hunt.StartHunt(hunt_obj.hunt_id)

        # Check matching client.
        client_id = self.SetupClient(0, system="Windows").Basename()
        foreman_obj = foreman.GetForeman()
        foreman_obj.AssignTasksToClient(client_id)

        flows = data_store.REL_DB.ReadAllFlowObjects(client_id=client_id)
        self.assertLen(flows, 1)

        # Check non-matching client.
        client_id = self.SetupClient(1, system="Linux").Basename()
        foreman_obj.AssignTasksToClient(client_id)

        flows = data_store.REL_DB.ReadAllFlowObjects(client_id=client_id)
        self.assertEmpty(flows)
Esempio n. 5
0
 def AssignTasksToClients(self, client_ids=None):
     # Pretend to be the foreman now and dish out hunting jobs to all the
     # clients..
     client_ids = client_ids or self.client_ids
     foreman_obj = foreman.GetForeman(token=self.token)
     for client_id in client_ids:
         foreman_obj.AssignTasksToClient(
             rdf_client.ClientURN(client_id).Basename())
Esempio n. 6
0
  def _RunHunt(self, client_ids, client_mock=None, iteration_limit=None):
    foreman_obj = foreman.GetForeman()
    for client_id in client_ids:
      foreman_obj.AssignTasksToClient(client_id.Basename())

    if client_mock is None:
      client_mock = hunt_test_lib.SampleHuntMock(failrate=2)
    return hunt_test_lib.TestHuntHelper(
        client_mock, client_ids, False, iteration_limit=iteration_limit)
Esempio n. 7
0
    def testOperatingSystemSelection(self):
        """Tests that we can distinguish based on operating system."""
        self.SetupClient(1, system="Windows XP")
        self.SetupClient(2, system="Linux")
        self.SetupClient(3, system="Windows 7")

        with utils.Stubber(flow, "StartAFF4Flow", self.StartFlow):
            # Now setup the filters
            now = rdfvalue.RDFDatetime.Now()
            expires = now + rdfvalue.Duration("1h")
            foreman_obj = foreman.GetForeman(token=self.token)

            # Make a new rule
            rule = foreman_rules.ForemanRule(created=now,
                                             expires=expires,
                                             description="Test rule")

            # Matches Windows boxes
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.OS,
                    os=foreman_rules.ForemanOsClientRule(os_windows=True))
            ])

            # Will run Test Flow
            rule.actions.Append(flow_name="Test Flow",
                                argv=rdf_protodict.Dict(foo="bar"))

            # Clear the rule set and add the new rule to it.
            rule_set = foreman_obj.Schema.RULES()
            rule_set.Append(rule)

            # Assign it to the foreman
            foreman_obj.Set(foreman_obj.Schema.RULES, rule_set)
            foreman_obj.Close()

            self.clients_launched = []
            foreman_obj.AssignTasksToClient(u"C.1000000000000001")
            foreman_obj.AssignTasksToClient(u"C.1000000000000002")
            foreman_obj.AssignTasksToClient(u"C.1000000000000003")

            # Make sure that only the windows machines ran
            self.assertEqual(len(self.clients_launched), 2)
            self.assertEqual(self.clients_launched[0][0],
                             rdf_client.ClientURN(u"C.1000000000000001"))
            self.assertEqual(self.clients_launched[1][0],
                             rdf_client.ClientURN(u"C.1000000000000003"))

            self.clients_launched = []

            # Run again - This should not fire since it did already
            foreman_obj.AssignTasksToClient(u"C.1000000000000001")
            foreman_obj.AssignTasksToClient(u"C.1000000000000002")
            foreman_obj.AssignTasksToClient(u"C.1000000000000003")

            self.assertEqual(len(self.clients_launched), 0)
Esempio n. 8
0
  def testRuleExpiration(self):
    with test_lib.FakeTime(1000):
      foreman_obj = foreman.GetForeman()

      rules = []
      rules.append(
          foreman_rules.ForemanCondition(
              creation_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
              expiration_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1500),
              description="Test rule1",
              hunt_id="H:111111"))
      rules.append(
          foreman_rules.ForemanCondition(
              creation_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
              expiration_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1200),
              description="Test rule2",
              hunt_id="H:222222"))
      rules.append(
          foreman_rules.ForemanCondition(
              creation_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
              expiration_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1500),
              description="Test rule3",
              hunt_id="H:333333"))
      rules.append(
          foreman_rules.ForemanCondition(
              creation_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
              expiration_time=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1300),
              description="Test rule4",
              hunt_id="H:444444"))

      client_id = self.SetupTestClientObject(0x21).client_id

      # Clear the rule set and add the new rules to it.
      for rule in rules:
        # Add some regex that does not match the client.
        rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
            foreman_rules.ForemanClientRule(
                rule_type=foreman_rules.ForemanClientRule.Type.REGEX,
                regex=foreman_rules.ForemanRegexClientRule(
                    field="SYSTEM", attribute_regex="XXX"))
        ])
        data_store.REL_DB.WriteForemanRule(rule)

    for now, num_rules in [(1000, 4), (1250, 3), (1350, 2), (1600, 0)]:
      with test_lib.FakeTime(now):
        data_store.REL_DB.WriteClientMetadata(
            client_id,
            last_foreman=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(100))
        foreman_obj.AssignTasksToClient(client_id)
        rules = data_store.REL_DB.ReadAllForemanRules()
        self.assertLen(rules, num_rules)
Esempio n. 9
0
    def testOperatingSystemSelection(self):
        """Tests that we can distinguish based on operating system."""
        self.SetupTestClientObject(1, system="Windows XP")
        self.SetupTestClientObject(2, system="Linux")
        self.SetupTestClientObject(3, system="Windows 7")

        with utils.Stubber(implementation.GRRHunt, "StartClients",
                           self.StartClients):
            # Now setup the filters
            now = rdfvalue.RDFDatetime.Now()
            expiration_time = now + rdfvalue.Duration("1h")

            # Make a new rule
            rule = foreman_rules.ForemanCondition(
                creation_time=now,
                expiration_time=expiration_time,
                description="Test rule",
                hunt_name=standard.GenericHunt.__name__,
                hunt_id="H:111111")

            # Matches Windows boxes
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.OS,
                    os=foreman_rules.ForemanOsClientRule(os_windows=True))
            ])

            data_store.REL_DB.WriteForemanRule(rule)

            self.clients_started = []
            foreman_obj = foreman.GetForeman()
            foreman_obj.AssignTasksToClient(u"C.1000000000000001")
            foreman_obj.AssignTasksToClient(u"C.1000000000000002")
            foreman_obj.AssignTasksToClient(u"C.1000000000000003")

            # Make sure that only the windows machines ran
            self.assertEqual(len(self.clients_started), 2)
            self.assertEqual(self.clients_started[0][1], u"C.1000000000000001")
            self.assertEqual(self.clients_started[1][1], u"C.1000000000000003")

            self.clients_started = []

            # Run again - This should not fire since it did already
            foreman_obj.AssignTasksToClient(u"C.1000000000000001")
            foreman_obj.AssignTasksToClient(u"C.1000000000000002")
            foreman_obj.AssignTasksToClient(u"C.1000000000000003")

            self.assertEqual(len(self.clients_started), 0)
Esempio n. 10
0
  def AssignTasksToClients(self, client_ids=None, worker=None):
    # Pretend to be the foreman now and dish out hunting jobs to all the
    # clients..
    client_ids = client_ids or self.client_ids
    foreman_obj = foreman.GetForeman(token=self.token)

    def Assign():
      for client_id in client_ids:
        foreman_obj.AssignTasksToClient(
            rdf_client.ClientURN(client_id).Basename())

    if worker is None:
      with flow_test_lib.TestWorker(threadpool_size=0, token=True):
        Assign()
    else:
      Assign()
Esempio n. 11
0
    def testHangingClientsAreCorrectlyAccountedFor(self):
        client_ids = self.SetupClients(10)

        hunt_obj = rdf_hunt_objects.Hunt(
            client_rule_set=foreman_rules.ForemanClientRuleSet(),
            client_rate=0,
            args=self.GetFileHuntArgs())
        hunt.CreateHunt(hunt_obj)
        hunt_obj = hunt.StartHunt(hunt_obj.hunt_id)

        foreman_obj = foreman.GetForeman()
        for client_id in client_ids:
            foreman_obj.AssignTasksToClient(client_id.Basename())

        client_mock = hunt_test_lib.SampleHuntMock(failrate=2)
        hunt_test_lib.TestHuntHelper(client_mock, client_ids[1:9], False)

        hunt_counters = data_store.REL_DB.ReadHuntCounters(hunt_obj.hunt_id)
        self.assertEqual(hunt_counters.num_clients, 10)
        self.assertEqual(hunt_counters.num_successful_clients, 4)
        self.assertEqual(hunt_counters.num_failed_clients, 4)
Esempio n. 12
0
    def testIntegerComparisons(self):
        """Tests that we can use integer matching rules on the foreman."""

        base_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(
            1336480583.077736)
        boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(
            1336300000.000000)

        self.SetupClient(0x11, system="Windows XP", install_time=base_time)
        self.SetupClient(0x12, system="Windows 7", install_time=base_time)
        # This one was installed one week earlier.
        one_week_ago = base_time - rdfvalue.Duration("1w")
        self.SetupClient(0x13, system="Windows 7", install_time=one_week_ago)
        self.SetupClient(0x14, system="Windows 7", last_boot_time=boot_time)

        with utils.Stubber(flow, "StartAFF4Flow", self.StartFlow):
            # Now setup the filters
            now = rdfvalue.RDFDatetime.Now()
            expires = now + rdfvalue.Duration("1h")
            foreman_obj = foreman.GetForeman(token=self.token)

            # Make a new rule
            rule = foreman_rules.ForemanRule(created=now,
                                             expires=expires,
                                             description="Test rule(old)")

            # Matches the old client
            one_hour_ago = base_time - rdfvalue.Duration("1h")
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="INSTALL_TIME",
                        operator=foreman_rules.ForemanIntegerClientRule.
                        Operator.LESS_THAN,
                        value=one_hour_ago.AsSecondsSinceEpoch()))
            ])

            old_flow = "Test flow for old clients"
            # Will run Test Flow
            rule.actions.Append(flow_name=old_flow,
                                argv=rdf_protodict.Dict(dict(foo="bar")))

            # Clear the rule set and add the new rule to it.
            rule_set = foreman_obj.Schema.RULES()
            rule_set.Append(rule)

            # Make a new rule
            rule = foreman_rules.ForemanRule(created=now,
                                             expires=expires,
                                             description="Test rule(new)")

            # Matches the newer clients
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="INSTALL_TIME",
                        operator=foreman_rules.ForemanIntegerClientRule.
                        Operator.GREATER_THAN,
                        value=one_hour_ago.AsSecondsSinceEpoch()))
            ])

            new_flow = "Test flow for newer clients"

            # Will run Test Flow
            rule.actions.Append(flow_name=new_flow,
                                argv=rdf_protodict.Dict(dict(foo="bar")))

            rule_set.Append(rule)

            # Make a new rule
            rule = foreman_rules.ForemanRule(created=now,
                                             expires=expires,
                                             description="Test rule(eq)")

            # Note that this also tests the handling of nonexistent attributes.
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="LAST_BOOT_TIME",
                        operator="EQUAL",
                        value=boot_time.AsSecondsSinceEpoch()))
            ])

            eq_flow = "Test flow for LAST_BOOT_TIME"

            rule.actions.Append(flow_name=eq_flow,
                                argv=rdf_protodict.Dict(dict(foo="bar")))

            rule_set.Append(rule)

            # Assign it to the foreman
            foreman_obj.Set(foreman_obj.Schema.RULES, rule_set)
            foreman_obj.Close()

            self.clients_launched = []
            foreman_obj.AssignTasksToClient(u"C.1000000000000011")
            foreman_obj.AssignTasksToClient(u"C.1000000000000012")
            foreman_obj.AssignTasksToClient(u"C.1000000000000013")
            foreman_obj.AssignTasksToClient(u"C.1000000000000014")

            # Make sure that the clients ran the correct flows.
            self.assertEqual(len(self.clients_launched), 4)
            self.assertEqual(self.clients_launched[0][0],
                             rdf_client.ClientURN(u"C.1000000000000011"))
            self.assertEqual(self.clients_launched[0][1], new_flow)
            self.assertEqual(self.clients_launched[1][0],
                             rdf_client.ClientURN(u"C.1000000000000012"))
            self.assertEqual(self.clients_launched[1][1], new_flow)
            self.assertEqual(self.clients_launched[2][0],
                             rdf_client.ClientURN(u"C.1000000000000013"))
            self.assertEqual(self.clients_launched[2][1], old_flow)
            self.assertEqual(self.clients_launched[3][0],
                             rdf_client.ClientURN(u"C.1000000000000014"))
            self.assertEqual(self.clients_launched[3][1], eq_flow)
Esempio n. 13
0
    def testIntegerComparisons(self):
        """Tests that we can use integer matching rules on the foreman."""

        base_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(
            1336480583.077736)
        boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(
            1336300000.000000)

        self.SetupTestClientObject(0x11,
                                   system="Windows XP",
                                   install_time=base_time)
        self.SetupTestClientObject(0x12,
                                   system="Windows 7",
                                   install_time=base_time)
        # This one was installed one week earlier.
        one_week_ago = base_time - rdfvalue.Duration("1w")
        self.SetupTestClientObject(0x13,
                                   system="Windows 7",
                                   install_time=one_week_ago)
        self.SetupTestClientObject(0x14,
                                   system="Windows 7",
                                   last_boot_time=boot_time)

        with utils.Stubber(implementation.GRRHunt, "StartClients",
                           self.StartClients):
            now = rdfvalue.RDFDatetime.Now()
            expiration_time = now + rdfvalue.Duration("1h")

            # Make a new rule
            rule = foreman_rules.ForemanCondition(
                creation_time=now,
                expiration_time=expiration_time,
                description="Test rule(old)",
                hunt_name=standard.GenericHunt.__name__,
                hunt_id="H:111111")

            # Matches the old client
            one_hour_ago = base_time - rdfvalue.Duration("1h")
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="INSTALL_TIME",
                        operator=foreman_rules.ForemanIntegerClientRule.
                        Operator.LESS_THAN,
                        value=one_hour_ago.AsSecondsSinceEpoch()))
            ])

            data_store.REL_DB.WriteForemanRule(rule)

            # Make a new rule
            rule = foreman_rules.ForemanCondition(
                creation_time=now,
                expiration_time=expiration_time,
                description="Test rule(new)",
                hunt_name=standard.GenericHunt.__name__,
                hunt_id="H:222222")

            # Matches the newer clients
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="INSTALL_TIME",
                        operator=foreman_rules.ForemanIntegerClientRule.
                        Operator.GREATER_THAN,
                        value=one_hour_ago.AsSecondsSinceEpoch()))
            ])

            data_store.REL_DB.WriteForemanRule(rule)

            # Make a new rule
            rule = foreman_rules.ForemanCondition(
                creation_time=now,
                expiration_time=expiration_time,
                description="Test rule(eq)",
                hunt_name=standard.GenericHunt.__name__,
                hunt_id="H:333333")

            # Note that this also tests the handling of nonexistent attributes.
            rule.client_rule_set = foreman_rules.ForemanClientRuleSet(rules=[
                foreman_rules.ForemanClientRule(
                    rule_type=foreman_rules.ForemanClientRule.Type.INTEGER,
                    integer=foreman_rules.ForemanIntegerClientRule(
                        field="LAST_BOOT_TIME",
                        operator="EQUAL",
                        value=boot_time.AsSecondsSinceEpoch()))
            ])

            data_store.REL_DB.WriteForemanRule(rule)

            foreman_obj = foreman.GetForeman()

            self.clients_started = []
            foreman_obj.AssignTasksToClient(u"C.1000000000000011")
            foreman_obj.AssignTasksToClient(u"C.1000000000000012")
            foreman_obj.AssignTasksToClient(u"C.1000000000000013")
            foreman_obj.AssignTasksToClient(u"C.1000000000000014")

            # Make sure that the clients ran the correct flows.
            self.assertEqual(len(self.clients_started), 4)
            self.assertEqual(self.clients_started[0][1], u"C.1000000000000011")
            self.assertEqual("H:222222", self.clients_started[0][0].Basename())
            self.assertEqual(self.clients_started[1][1], u"C.1000000000000012")
            self.assertEqual("H:222222", self.clients_started[1][0].Basename())
            self.assertEqual(self.clients_started[2][1], u"C.1000000000000013")
            self.assertEqual("H:111111", self.clients_started[2][0].Basename())
            self.assertEqual(self.clients_started[3][1], u"C.1000000000000014")
            self.assertEqual("H:333333", self.clients_started[3][0].Basename())
Esempio n. 14
0
    def testRuleExpiration(self):
        with test_lib.FakeTime(1000):
            foreman_obj = foreman.GetForeman(token=self.token)
            hunt_id = rdfvalue.SessionID("aff4:/hunts/foremantest")

            rules = []
            rules.append(
                foreman_rules.ForemanRule(
                    created=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
                    expires=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1500),
                    description="Test rule1"))
            rules.append(
                foreman_rules.ForemanRule(
                    created=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
                    expires=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1200),
                    description="Test rule2"))
            rules.append(
                foreman_rules.ForemanRule(
                    created=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
                    expires=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1500),
                    description="Test rule3"))
            rules.append(
                foreman_rules.ForemanRule(
                    created=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1000),
                    expires=rdfvalue.RDFDatetime.FromSecondsSinceEpoch(1300),
                    description="Test rule4",
                    actions=[foreman_rules.ForemanRuleAction(hunt_id=hunt_id)
                             ]))

            client_id = u"C.0000000000000021"
            fd = aff4.FACTORY.Create(client_id,
                                     aff4_grr.VFSGRRClient,
                                     token=self.token)
            fd.Close()

            # Clear the rule set and add the new rules to it.
            rule_set = foreman_obj.Schema.RULES()
            for rule in rules:
                # Add some regex that does not match the client.
                rule.client_rule_set = foreman_rules.ForemanClientRuleSet(
                    rules=[
                        foreman_rules.ForemanClientRule(
                            rule_type=foreman_rules.ForemanClientRule.Type.
                            REGEX,
                            regex=foreman_rules.ForemanRegexClientRule(
                                field="SYSTEM", attribute_regex="XXX"))
                    ])
                rule_set.Append(rule)
            foreman_obj.Set(foreman_obj.Schema.RULES, rule_set)
            foreman_obj.Close()

        fd = aff4.FACTORY.Create(client_id,
                                 aff4_grr.VFSGRRClient,
                                 token=self.token)
        for now, num_rules in [(1000, 4), (1250, 3), (1350, 2), (1600, 0)]:
            with test_lib.FakeTime(now):
                fd.Set(fd.Schema.LAST_FOREMAN_TIME(100))
                fd.Flush()
                foreman_obj = foreman.GetForeman(token=self.token)
                foreman_obj.AssignTasksToClient(client_id)
                rules = foreman_obj.Get(foreman_obj.Schema.RULES)
                self.assertEqual(len(rules), num_rules)

        # Expiring rules that trigger hunts creates a notification for that hunt.
        with queue_manager.QueueManager(token=self.token) as manager:
            notifications = manager.GetNotificationsForAllShards(
                hunt_id.Queue())
            self.assertEqual(len(notifications), 1)
            self.assertEqual(notifications[0].session_id, hunt_id)
Esempio n. 15
0
    def testLabelsHuntRuleMatchesCorrectClients(self):
        client_ids = self.SetupClients(10)

        self.AddClientLabel(client_ids[1], u"owner1", u"foo")
        self.AddClientLabel(client_ids[1], u"owner2", u"bar")
        self.AddClientLabel(client_ids[7], u"GRR", u"bar")

        self.Open("/#main=ManageHunts")
        self.Click("css=button[name=NewHunt]")

        # Select "List Processes" flow.
        self.Click("css=#_Processes > i.jstree-icon")
        self.Click("link=ListProcesses")

        # Click 'Next' to go to the output plugins page, hunt parameters page
        # and then to hunt rules page.
        self.Click("css=grr-new-hunt-wizard-form button.Next")
        self.WaitUntil(self.IsElementPresent,
                       "css=grr-wizard-form:contains('Hunt parameters')")
        self.Click("css=grr-new-hunt-wizard-form button.Next")
        self.WaitUntil(
            self.IsElementPresent,
            "css=grr-wizard-form:contains('How to process results')")
        self.Click("css=grr-new-hunt-wizard-form button.Next")
        self.WaitUntil(self.IsElementPresent,
                       "css=grr-wizard-form:contains('Where to run?')")

        # Select 'Clients With Label' rule.
        self.Click("css=grr-configure-rules-page button[name=Add]")
        self.Select("css=grr-new-hunt-wizard-form div.well select", "Label")
        self.Select(
            "css=grr-new-hunt-wizard-form div.well .form-group "
            ".form-group:has(label:contains('Label')):nth-last-of-type(1) "
            "select", "foo")
        self.Click("css=grr-new-hunt-wizard-form div.well .form-group "
                   ".form-group:has(label:contains('Add label')) button")
        self.Select(
            "css=grr-new-hunt-wizard-form div.well .form-group "
            ".form-group:has(label:contains('Label')):nth-last-of-type(1) "
            "select", "bar")
        self.Select(
            "css=grr-new-hunt-wizard-form div.well .form-group "
            ".form-group:has(label:contains('Match mode')) select",
            "Match any")

        # Click 'Next' to go to hunt overview page.  Then click 'Next' to go to
        # submit the hunt and wait until it's created.
        self.Click("css=grr-new-hunt-wizard-form button.Next")
        self.Click("css=grr-new-hunt-wizard-form button.Next")
        self.WaitUntil(self.IsElementPresent,
                       "css=grr-wizard-form:contains('Created Hunt')")

        hunts_root = aff4.FACTORY.Open("aff4:/hunts", token=self.token)
        hunts_list = list(hunts_root.OpenChildren(mode="rw"))
        hunt = hunts_list[0]

        hunt.Run()  # Run the hunt so that rules are added to the foreman.

        foreman_obj = foreman.GetForeman(token=self.token)
        for client_id in client_ids:
            tasks_assigned = foreman_obj.AssignTasksToClient(
                client_id.Basename())
            if client_id in [client_ids[1], client_ids[7]]:
                self.assertTrue(tasks_assigned)
            else:
                self.assertFalse(tasks_assigned)