Beispiel #1
0
        def TestAnd(val1, val2, expected):
            self.assertEqual(rdfvalue.RDFBool(val1) & val2, expected)
            self.assertEqual(val1 & rdfvalue.RDFBool(val2), expected)

            value = rdfvalue.RDFBool(val1)
            value &= val2
            self.assertEqual(value, expected)

            value = val1
            value &= rdfvalue.RDFBool(val2)
            self.assertEqual(value, expected)
Beispiel #2
0
        def TestOr(val1, val2, expected):
            self.assertEqual(rdfvalue.RDFBool(val1) | val2, expected)
            self.assertEqual(val1 | rdfvalue.RDFBool(val2), expected)

            value = rdfvalue.RDFBool(val1)
            value |= val2
            self.assertEqual(value, expected)

            value = val1
            value |= rdfvalue.RDFBool(val2)
            self.assertEqual(value, expected)
Beispiel #3
0
    def EnrolFleetspeakClient(self, client_id):
        """Enrols a Fleetspeak-enabled client for use with GRR.

    Args:
      client_id: GRR client-id for the client.

    Returns:
      True if the client is new, and actually got enrolled. This method
      is a no-op if the client already exists (in which case False is returned).
    """
        client_urn = rdf_client.ClientURN(client_id)

        # If already enrolled, return.
        if data_store.RelationalDBEnabled():
            try:
                data_store.REL_DB.ReadClientMetadata(client_id)
                return False
            except db.UnknownClientError:
                pass
        else:
            if aff4.FACTORY.ExistsWithType(client_urn,
                                           aff4_type=aff4_grr.VFSGRRClient,
                                           token=self.token):
                return False

        logging.info("Enrolling a new Fleetspeak client: %r", client_id)

        if data_store.RelationalDBEnabled():
            now = rdfvalue.RDFDatetime.Now()
            data_store.REL_DB.WriteClientMetadata(client_id,
                                                  first_seen=now,
                                                  fleetspeak_enabled=True,
                                                  last_ping=now)

        if data_store.AFF4Enabled():
            # TODO(fleetspeak-team,grr-team): If aff4 isn't reliable enough, we can
            # catch exceptions from it and forward them to Fleetspeak by failing its
            # gRPC call. Fleetspeak will then retry with a random, perhaps healthier,
            # instance of the GRR frontend.
            with aff4.FACTORY.Create(client_urn,
                                     aff4_type=aff4_grr.VFSGRRClient,
                                     mode="rw",
                                     token=self.token) as client:

                client.Set(client.Schema.FLEETSPEAK_ENABLED,
                           rdfvalue.RDFBool(True))

                index = client_index.CreateClientIndex(token=self.token)
                index.AddClient(client)
                if data_store.RelationalDBEnabled():
                    client_obj = rdf_objects.ClientSnapshot(
                        client_id=client_urn.Basename())
                    index = client_index.ClientIndex()
                    index.AddClient(client_obj)

        # Publish the client enrollment message.
        events.Events.PublishEvent("ClientEnrollment",
                                   client_urn,
                                   token=self.token)
        return True
Beispiel #4
0
    def InitFromKeyValue(self, key, value):
        self.key = key

        # Convert primitive types to rdf values so they can be serialized.
        if isinstance(value, float) and not value.is_integer():
            # TODO(user): Do not convert float values here and mark them invalid
            # later. ATM, we do not have means to properly represent floats. Change
            # this part once we have a RDFFloat implementation.
            pass
        elif rdfvalue.RDFInteger.IsNumeric(value):
            value = rdfvalue.RDFInteger(value)
        elif isinstance(value, unicode):
            value = rdfvalue.RDFString(value)
        elif isinstance(value, bytes):
            value = rdfvalue.RDFBytes(value)
        elif isinstance(value, bool):
            value = rdfvalue.RDFBool(value)

        if isinstance(value, rdfvalue.RDFValue):
            self.type = value.__class__.__name__
            self.value = value
        else:
            self.invalid = True

        return self
Beispiel #5
0
 def testRepr(self):
     """Test RDFValue.__repr__."""
     self.assertEqual(repr(rdfvalue.RDFBool(True)), "<RDFBool('1')>")
     self.assertEqual(
         repr(rdfvalue.RDFString(long_string)),
         "<RDFString('\\xe8\\xbf\\x8e\\xe6\\xac\\xa2\\xe8\\xbf\\x8e\\nLorem "
         "ipsum dolor sit amet, consectetur adipiscing elit. Morbi luctus ex "
         "sed dictum volutp...')>")
Beispiel #6
0
    def EnrolFleetspeakClient(self, client_id):
        """Enrols a Fleetspeak-enabled client for use with GRR."""
        client_urn = rdf_client.ClientURN(client_id)

        # If already enrolled, return.
        if data_store.RelationalDBReadEnabled():
            try:
                data_store.REL_DB.ReadClientMetadata(client_id)
                return
            except db.UnknownClientError:
                pass
        else:
            if aff4.FACTORY.ExistsWithType(client_urn,
                                           aff4_type=aff4_grr.VFSGRRClient,
                                           token=self.token):
                return

        logging.info("Enrolling a new Fleetspeak client: %r", client_id)

        if data_store.RelationalDBWriteEnabled():
            data_store.REL_DB.WriteClientMetadata(client_id,
                                                  fleetspeak_enabled=True)

        # TODO(fleetspeak-team,grr-team): If aff4 isn't reliable enough, we can
        # catch exceptions from it and forward them to Fleetspeak by failing its
        # gRPC call. Fleetspeak will then retry with a random, perhaps healthier,
        # instance of the GRR frontend.
        with aff4.FACTORY.Create(client_urn,
                                 aff4_type=aff4_grr.VFSGRRClient,
                                 mode="rw",
                                 token=self.token) as client:

            client.Set(client.Schema.FLEETSPEAK_ENABLED,
                       rdfvalue.RDFBool(True))

            index = client_index.CreateClientIndex(token=self.token)
            index.AddClient(client)
            if data_store.RelationalDBWriteEnabled():
                index = client_index.ClientIndex()
                index.AddClient(data_migration.ConvertVFSGRRClient(client))

        # Publish the client enrollment message.
        events.Events.PublishEvent("ClientEnrollment",
                                   client_urn,
                                   token=self.token)
Beispiel #7
0
    def testInitFromAff4Object(self):
        state = rdf_protodict.AttributedDict()
        state["quux"] = "norf"
        state["thud"] = "blargh"

        with aff4.FACTORY.Create("aff4:/cron/foo",
                                 aff4_type=cronjobs.CronJob,
                                 mode="w",
                                 token=self.token) as fd:
            args = rdf_cronjobs.CreateCronJobFlowArgs()
            args.periodicity = rdfvalue.Duration("1d")
            args.lifetime = rdfvalue.Duration("30d")
            args.description = "testdescription"

            status = rdf_cronjobs.CronJobRunStatus(status="OK")

            fd.Set(fd.Schema.CURRENT_FLOW_URN,
                   rdfvalue.RDFURN("aff4:/flow/bar"))
            fd.Set(fd.Schema.CRON_ARGS, args)
            fd.Set(fd.Schema.LAST_RUN_TIME, self._DATETIME("2001-01-01"))
            fd.Set(fd.Schema.LAST_RUN_STATUS, status)
            fd.Set(fd.Schema.DISABLED, rdfvalue.RDFBool(True))
            fd.Set(fd.Schema.STATE_DICT, state)

        with aff4.FACTORY.Open("aff4:/cron/foo", mode="r",
                               token=self.token) as fd:
            api_cron_job = cron_plugin.ApiCronJob().InitFromAff4Object(fd)

        self.assertEqual(api_cron_job.cron_job_id, "foo")
        self.assertEqual(api_cron_job.current_run_id, "bar")
        self.assertEqual(api_cron_job.description, "testdescription")
        self.assertEqual(api_cron_job.last_run_time,
                         self._DATETIME("2001-01-01"))
        self.assertEqual(api_cron_job.last_run_status, "FINISHED")
        self.assertEqual(api_cron_job.frequency, rdfvalue.Duration("1d"))
        self.assertEqual(api_cron_job.lifetime, rdfvalue.Duration("30d"))
        self.assertFalse(api_cron_job.enabled)

        api_state_items = {_.key: _.value for _ in api_cron_job.state.items}
        self.assertEqual(api_state_items, {"quux": "norf", "thud": "blargh"})
Beispiel #8
0
 def testComparableToPrimitiveBooleans(self):
     self.assertEqual(rdfvalue.RDFBool(True), True)
     self.assertNotEqual(rdfvalue.RDFBool(True), False)
     self.assertEqual(rdfvalue.RDFBool(False), False)
     self.assertNotEqual(rdfvalue.RDFBool(False), True)
Beispiel #9
0
 def GenerateSample(self, number=0):
     return rdfvalue.RDFBool(number % 2)
Beispiel #10
0
 def testStr(self):
     """Test RDFValue.__str__."""
     self.assertEqual(str(rdfvalue.RDFBool(True)), "1")
     self.assertEqual(str(rdfvalue.RDFString(long_string)), long_string)
Beispiel #11
0
    def _SetupClientImpl(self,
                         client_nr,
                         index=None,
                         arch="x86_64",
                         fqdn=None,
                         install_time=None,
                         last_boot_time=None,
                         kernel="4.0.0",
                         os_version="buster/sid",
                         ping=None,
                         system="Linux",
                         memory_size=None,
                         add_cert=True,
                         fleetspeak_enabled=False):
        client_id_urn = rdf_client.ClientURN("C.1%015x" % client_nr)

        with aff4.FACTORY.Create(client_id_urn,
                                 aff4_grr.VFSGRRClient,
                                 mode="rw",
                                 token=self.token) as fd:
            if add_cert:
                cert = self.ClientCertFromPrivateKey(
                    config.CONFIG["Client.private_key"])
                fd.Set(fd.Schema.CERT, cert)

            fd.Set(fd.Schema.CLIENT_INFO, self._TestClientInfo())
            fd.Set(fd.Schema.PING, ping or rdfvalue.RDFDatetime.Now())
            if fqdn is not None:
                fd.Set(fd.Schema.HOSTNAME(fqdn.split(".", 1)[0]))
                fd.Set(fd.Schema.FQDN(fqdn))
            else:
                fd.Set(fd.Schema.HOSTNAME("Host-%x" % client_nr))
                fd.Set(fd.Schema.FQDN("Host-%x.example.com" % client_nr))
            fd.Set(
                fd.Schema.MAC_ADDRESS("aabbccddee%02x\nbbccddeeff%02x" %
                                      (client_nr, client_nr)))
            fd.Set(
                fd.Schema.HOST_IPS("192.168.0.%d\n2001:abcd::%x" %
                                   (client_nr, client_nr)))

            if system:
                fd.Set(fd.Schema.SYSTEM(system))
            if os_version:
                fd.Set(fd.Schema.OS_VERSION(os_version))
            if arch:
                fd.Set(fd.Schema.ARCH(arch))
            if kernel:
                fd.Set(fd.Schema.KERNEL(kernel))
            if memory_size:
                fd.Set(fd.Schema.MEMORY_SIZE(memory_size))

            if last_boot_time:
                fd.Set(fd.Schema.LAST_BOOT_TIME(last_boot_time))
            if install_time:
                fd.Set(fd.Schema.INSTALL_DATE(install_time))
            if fleetspeak_enabled:
                fd.Set(fd.Schema.FLEETSPEAK_ENABLED, rdfvalue.RDFBool(True))

            kb = rdf_client.KnowledgeBase()
            kb.fqdn = fqdn or "Host-%x.example.com" % client_nr
            kb.users = [
                rdf_client.User(username="******"),
                rdf_client.User(username="******"),
            ]
            artifact.SetCoreGRRKnowledgeBaseValues(kb, fd)
            fd.Set(fd.Schema.KNOWLEDGE_BASE, kb)

            fd.Set(fd.Schema.INTERFACES(self._TestInterfaces(client_nr)))

            hardware_info = fd.Schema.HARDWARE_INFO()
            hardware_info.system_manufacturer = ("System-Manufacturer-%x" %
                                                 client_nr)
            hardware_info.bios_version = ("Bios-Version-%x" % client_nr)
            fd.Set(fd.Schema.HARDWARE_INFO, hardware_info)

            fd.Flush()

            index.AddClient(fd)

        return client_id_urn
Beispiel #12
0
def SetAFF4FSEnabledFlag(grr_id, token):
    with aff4.FACTORY.Create(grr_id,
                             aff4.AFF4Object.classes["VFSGRRClient"],
                             mode="w",
                             token=token) as client:
        client.Set(client.Schema.FLEETSPEAK_ENABLED, rdfvalue.RDFBool(True))