Esempio n. 1
0
    def testWriteClientSnapshotHistory(self):
        client_id = self.InitializeClient()

        client_a = objects.ClientSnapshot(client_id=client_id)
        client_a.kernel = "1.2.3"
        client_a.startup_info.client_info.client_version = 42
        client_a.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-01-01")

        client_b = objects.ClientSnapshot(client_id=client_id)
        client_b.kernel = "4.5.6"
        client_b.startup_info.client_info.client_version = 108
        client_b.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-02-01")

        client_c = objects.ClientSnapshot(client_id=client_id)
        client_c.kernel = "7.8.9"
        client_c.startup_info.client_info.client_version = 707
        client_c.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-03-01")

        self.db.WriteClientSnapshotHistory([client_a, client_b, client_c])

        # Check whether the client history has been recorded correctly.
        history = self.db.ReadClientSnapshotHistory(client_id)
        self.assertEqual(len(history), 3)

        self.assertEqual(history[0].kernel, "7.8.9")
        self.assertEqual(history[0].startup_info.client_info.client_version,
                         707)
        self.assertEqual(history[0].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-03-01"))

        self.assertEqual(history[1].kernel, "4.5.6")
        self.assertEqual(history[1].startup_info.client_info.client_version,
                         108)
        self.assertEqual(history[1].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-02-01"))

        self.assertEqual(history[2].kernel, "1.2.3")
        self.assertEqual(history[2].startup_info.client_info.client_version,
                         42)
        self.assertEqual(history[2].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-01-01"))

        # Check whether the snapshot history has been recorded correctly.
        history = self.db.ReadClientStartupInfoHistory(client_id)
        self.assertEqual(len(history), 3)

        self.assertEqual(history[0].client_info.client_version, 707)
        self.assertEqual(history[0].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-03-01"))

        self.assertEqual(history[1].client_info.client_version, 108)
        self.assertEqual(history[1].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-02-01"))

        self.assertEqual(history[2].client_info.client_version, 42)
        self.assertEqual(history[2].timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-01-01"))
Esempio n. 2
0
    def testWriteClientSnapshotHistoryUpdatesOnlyLastClientTimestamp(self):
        client_id = self.InitializeClient()

        client_old = objects.ClientSnapshot(client_id=client_id)
        client_old.kernel = "1.0.0"
        client_old.startup_info.client_info.client_name = "foo"
        self.db.WriteClientSnapshot(client_old)

        old_timestamp = self.db.ReadClientSnapshot(client_id).timestamp

        startup_info = rdf_client.StartupInfo()
        startup_info.client_info.client_name = "bar"
        self.db.WriteClientStartupInfo(client_id, startup_info)

        startup_timestamp = self.db.ReadClientStartupInfo(client_id).timestamp

        client_new = objects.ClientSnapshot(client_id=client_id)
        client_new.kernel = "2.0.0"
        client_new.startup_info.client_info.client_name = "baz"
        client_new.timestamp = rdfvalue.RDFDatetime.Lerp(
            0.5, start_time=old_timestamp, end_time=startup_timestamp)
        self.db.WriteClientSnapshotHistory([client_new])

        info = self.db.ReadClientFullInfo(client_id)
        last_snapshot = info.last_snapshot
        last_startup_info = info.last_startup_info
        self.assertEqual(last_snapshot.kernel, "2.0.0")
        self.assertEqual(last_snapshot.startup_info.client_info.client_name,
                         "baz")
        self.assertEqual(last_snapshot.timestamp, client_new.timestamp)
        self.assertEqual(last_startup_info.client_info.client_name, "bar")
        self.assertEqual(last_startup_info.timestamp, startup_timestamp)
Esempio n. 3
0
    def testWriteClientSnapshotHistoryRaiseValueErrorOnNonUniformIds(self):
        client_id_a = self.InitializeClient()
        client_id_b = self.InitializeClient()

        client_a = objects.ClientSnapshot(client_id=client_id_a)
        client_a.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-05-12")

        client_b = objects.ClientSnapshot(client_id=client_id_b)
        client_b.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-06-12")

        with self.assertRaisesRegexp(ValueError, "client id"):
            self.db.WriteClientSnapshotHistory([client_a, client_b])
Esempio n. 4
0
    def testInvalidClientID(self):

        # No id.
        with self.assertRaises(ValueError):
            objects.ClientSnapshot()

        # One digit short.
        with self.assertRaises(ValueError):
            objects.ClientSnapshot(client_id="C.000000000000000")

        with self.assertRaises(ValueError):
            objects.ClientSnapshot(client_id="not a real id")

        objects.ClientSnapshot(client_id="C.0000000000000000")
Esempio n. 5
0
  def testReadAllClientsFullInfoReadsMultipleClientsWithMultipleLabels(self):
    d = self.db

    for i in range(10):
      client_id = "C.000000005000000%d" % i
      self._InitializeClient(client_id)

      cl = objects.ClientSnapshot(
          client_id=client_id,
          knowledge_base=rdf_client.KnowledgeBase(
              fqdn="test%d.examples.com" % i),
          kernel="12.3.%d" % i)
      d.WriteClientSnapshot(cl)
      d.WriteClientMetadata(client_id, certificate=CERT)
      si = rdf_client.StartupInfo(boot_time=i)
      d.WriteClientStartupInfo(client_id, si)
      d.AddClientLabels(
          client_id, "test_owner",
          ["test_label-a-%d" % i, "test_label-b-%d" % i])

    c_infos = sorted(
        d.ReadAllClientsFullInfo(), key=lambda c: c.last_snapshot.client_id)
    for i, full_info in enumerate(c_infos):
      self.assertEqual(full_info.last_snapshot.client_id,
                       "C.000000005000000%d" % i)
      self.assertEqual(full_info.metadata.certificate, CERT)
      self.assertEqual(full_info.last_startup_info.boot_time, i)
      self.assertEqual(
          sorted(full_info.labels, key=lambda l: l.name), [
              objects.ClientLabel(
                  owner="test_owner", name="test_label-a-%d" % i),
              objects.ClientLabel(
                  owner="test_owner", name="test_label-b-%d" % i)
          ])
Esempio n. 6
0
    def testClientStartupInfo(self):
        """StartupInfo is written to a separate table, make sure the merge works."""
        d = self.db

        client_id = self.InitializeClient()

        client = objects.ClientSnapshot(client_id=client_id, kernel="12.3")
        client.startup_info = rdf_client.StartupInfo(boot_time=123)
        client.knowledge_base.fqdn = "test1234.examples.com"
        d.WriteClientSnapshot(client)

        client = d.ReadClientSnapshot(client_id)
        self.assertEqual(client.startup_info.boot_time, 123)

        client.kernel = "12.4"
        client.startup_info = rdf_client.StartupInfo(boot_time=124)
        d.WriteClientSnapshot(client)

        client.kernel = "12.5"
        client.startup_info = rdf_client.StartupInfo(boot_time=125)
        d.WriteClientSnapshot(client)

        hist = d.ReadClientSnapshotHistory(client_id)
        self.assertEqual(len(hist), 3)
        startup_infos = [cl.startup_info for cl in hist]
        self.assertEqual([si.boot_time for si in startup_infos],
                         [125, 124, 123])

        # StartupInfos written using WriteClient show up in the StartupInfoHistory.
        history = d.ReadClientStartupInfoHistory(client_id)
        self.assertEqual(len(history), 3)
        self.assertEqual(startup_infos, history)
Esempio n. 7
0
  def Start(self):
    """Start off all the tests."""

    # Create the objects we need to exist.
    self.Load()

    client_id = self.client_id.Basename()
    self.state.client = rdf_objects.ClientSnapshot(client_id=client_id)
    self.state.fqdn = None
    self.state.os = None

    # Make sure we always have a VFSDirectory with a pathspec at fs/os
    pathspec = rdf_paths.PathSpec(
        path="/", pathtype=rdf_paths.PathSpec.PathType.OS)
    urn = pathspec.AFF4Path(self.client_id)
    with aff4.FACTORY.Create(
        urn, standard.VFSDirectory, mode="w", token=self.token) as fd:
      fd.Set(fd.Schema.PATHSPEC, pathspec)

    self.CallClient(server_stubs.GetPlatformInfo, next_state="Platform")
    self.CallClient(server_stubs.GetMemorySize, next_state="StoreMemorySize")
    self.CallClient(server_stubs.GetInstallDate, next_state="InstallDate")
    self.CallClient(server_stubs.GetClientInfo, next_state="ClientInfo")
    self.CallClient(
        server_stubs.GetConfiguration, next_state="ClientConfiguration")
    self.CallClient(
        server_stubs.GetLibraryVersions, next_state="ClientLibraries")
    self.CallClient(
        server_stubs.EnumerateInterfaces, next_state="EnumerateInterfaces")
    self.CallClient(
        server_stubs.EnumerateFilesystems, next_state="EnumerateFilesystems")
Esempio n. 8
0
    def testClientWriteToUnknownClient(self):
        d = self.db
        client_id = "C.fc413187fefa1dcf"

        with self.assertRaises(db.UnknownClientError) as context:
            d.WriteClientSnapshot(objects.ClientSnapshot(client_id=client_id))
        self.assertEqual(context.exception.client_id, client_id)
Esempio n. 9
0
    def SetupTestClientObject(self,
                              client_nr,
                              add_cert=True,
                              arch="x86_64",
                              last_boot_time=None,
                              fqdn=None,
                              kernel="4.0.0",
                              memory_size=None,
                              os_version="buster/sid",
                              ping=None,
                              system="Linux",
                              labels=None):
        """Prepares a test client object."""
        client_id = "C.1%015x" % client_nr

        client = objects.ClientSnapshot(client_id=client_id)
        client.startup_info.client_info = self._TestClientInfo()
        if last_boot_time is not None:
            client.startup_info.boot_time = last_boot_time

        client.knowledge_base.fqdn = fqdn or "Host-%x.example.com" % client_nr
        client.knowledge_base.os = system
        client.knowledge_base.users = [
            rdf_client.User(username="******"),
            rdf_client.User(username="******"),
        ]
        client.os_version = os_version
        client.arch = arch
        client.kernel = kernel

        client.interfaces = self._TestInterfaces(client_nr)

        client.hardware_info = rdf_client.HardwareInfo(
            system_manufacturer="System-Manufacturer-%x" % client_nr,
            bios_version="Bios-Version-%x" % client_nr)

        if memory_size is not None:
            client.memory_size = memory_size

        ping = ping or rdfvalue.RDFDatetime.Now()
        if add_cert:
            cert = self.ClientCertFromPrivateKey(
                config.CONFIG["Client.private_key"])
        else:
            cert = None

        data_store.REL_DB.WriteClientMetadata(client_id,
                                              last_ping=ping,
                                              certificate=cert,
                                              fleetspeak_enabled=False)
        data_store.REL_DB.WriteClientSnapshot(client)

        client_index.ClientIndex().AddClient(client)

        if labels:
            data_store.REL_DB.AddClientLabels(client_id, "GRR", labels)
            client_index.ClientIndex().AddClientLabels(
                client_id, data_store.REL_DB.ReadClientLabels(client_id))

        return client
Esempio n. 10
0
def ConvertVFSGRRClient(client):
  """Converts from `VFSGRRClient` to `rdfvalues.objects.ClientSnapshot`."""
  snapshot = rdf_objects.ClientSnapshot(client_id=client.urn.Basename())

  snapshot.filesystems = client.Get(client.Schema.FILESYSTEM)
  snapshot.hostname = client.Get(client.Schema.HOSTNAME)
  snapshot.fqdn = client.Get(client.Schema.FQDN)
  snapshot.system = client.Get(client.Schema.SYSTEM)
  snapshot.os_release = client.Get(client.Schema.OS_RELEASE)
  snapshot.os_version = utils.SmartStr(client.Get(client.Schema.OS_VERSION))
  snapshot.arch = client.Get(client.Schema.ARCH)
  snapshot.install_time = client.Get(client.Schema.INSTALL_DATE)
  snapshot.knowledge_base = client.Get(client.Schema.KNOWLEDGE_BASE)
  snapshot.startup_info.boot_time = client.Get(client.Schema.LAST_BOOT_TIME)
  snapshot.startup_info.client_info = client.Get(client.Schema.CLIENT_INFO)

  conf = client.Get(client.Schema.GRR_CONFIGURATION) or []
  for key in conf or []:
    snapshot.grr_configuration.Append(key=key, value=utils.SmartStr(conf[key]))

  lib = client.Get(client.Schema.LIBRARY_VERSIONS) or []
  for key in lib or []:
    snapshot.library_versions.Append(key=key, value=utils.SmartStr(lib[key]))

  snapshot.kernel = client.Get(client.Schema.KERNEL)
  snapshot.volumes = client.Get(client.Schema.VOLUMES)
  snapshot.interfaces = client.Get(client.Schema.INTERFACES)
  snapshot.hardware_info = client.Get(client.Schema.HARDWARE_INFO)
  snapshot.memory_size = client.Get(client.Schema.MEMORY_SIZE)
  snapshot.cloud_instance = client.Get(client.Schema.CLOUD_INSTANCE)

  return snapshot
Esempio n. 11
0
  def testClientSummary(self):
    d = self.db

    client_id_1 = "C.0000000000000001"
    client_id_2 = "C.0000000000000002"
    client_id_3 = "C.0000000000000003"
    self._InitializeClient(client_id_1)
    self._InitializeClient(client_id_2)
    self._InitializeClient(client_id_3)

    d.WriteClientSnapshot(
        objects.ClientSnapshot(
            client_id=client_id_1,
            knowledge_base=rdf_client.KnowledgeBase(
                fqdn="test1234.examples.com"),
            kernel="12.3"))
    d.WriteClientSnapshot(
        objects.ClientSnapshot(
            client_id=client_id_1,
            knowledge_base=rdf_client.KnowledgeBase(
                fqdn="test1234.examples.com"),
            kernel="12.4"))

    d.WriteClientSnapshot(
        objects.ClientSnapshot(
            client_id=client_id_2,
            knowledge_base=rdf_client.KnowledgeBase(
                fqdn="test1235.examples.com"),
            kernel="12.4"))

    hist = d.ReadClientSnapshotHistory(client_id_1)
    self.assertEqual(len(hist), 2)

    # client_3 should be excluded - no snapshot yet
    res = d.ReadClientsSnapshot([client_id_1, client_id_2, client_id_3])
    self.assertEqual(len(res), 3)
    self.assertIsInstance(res[client_id_1], objects.ClientSnapshot)
    self.assertIsInstance(res[client_id_2], objects.ClientSnapshot)
    self.assertIsInstance(res[client_id_1].timestamp, rdfvalue.RDFDatetime)
    self.assertIsNotNone(res[client_id_2].timestamp)
    self.assertEqual(res[client_id_1].knowledge_base.fqdn,
                     "test1234.examples.com")
    self.assertEqual(res[client_id_1].kernel, "12.4")
    self.assertEqual(res[client_id_2].knowledge_base.fqdn,
                     "test1235.examples.com")
    self.assertFalse(res[client_id_3])
Esempio n. 12
0
    def testWriteClientSnapshotHistoryUpdatesLastTimestampIfNewer(self):
        client_id = self.InitializeClient()

        client_old = objects.ClientSnapshot(client_id=client_id)
        client_old.kernel = "1.0.0"
        self.db.WriteClientSnapshot(client_old)

        old_timestamp = self.db.ReadClientSnapshot(client_id).timestamp

        client_new = objects.ClientSnapshot(client_id=client_id)
        client_new.kernel = "2.0.0"
        client_new.timestamp = rdfvalue.RDFDatetime.Now()
        self.db.WriteClientSnapshotHistory([client_new])

        info = self.db.ReadClientFullInfo(client_id)
        self.assertEqual(info.last_snapshot.kernel, "2.0.0")
        self.assertGreater(info.last_snapshot.timestamp, old_timestamp)
        self.assertGreater(info.last_startup_info.timestamp, old_timestamp)
Esempio n. 13
0
    def testWriteClientSnapshotHistoryDoesNotUpdateLastTimestampIfOlder(self):
        client_id = self.InitializeClient()

        client_new = objects.ClientSnapshot(client_id=client_id)
        client_new.kernel = "2.0.0"
        self.db.WriteClientSnapshot(client_new)

        new_timestamp = self.db.ReadClientSnapshot(client_id).timestamp

        client_old = objects.ClientSnapshot(client_id=client_id)
        client_old.kernel = "1.0.0"
        client_old.timestamp = new_timestamp - rdfvalue.Duration("1d")
        self.db.WriteClientSnapshotHistory([client_old])

        info = self.db.ReadClientFullInfo(client_id)
        self.assertEqual(info.last_snapshot.kernel, "2.0.0")
        self.assertEqual(info.last_snapshot.timestamp, new_timestamp)
        self.assertEqual(info.last_startup_info.timestamp, new_timestamp)
Esempio n. 14
0
  def testWriteClientSnapshotHistoryRaiseOnNonExistingClient(self):
    client_id = "C.0000000000000000"

    client = objects.ClientSnapshot(client_id=client_id)
    client.kernel = "1.2.3"
    client.timestamp = rdfvalue.RDFDatetime.FromHumanReadable("2001-01-01")

    with self.assertRaises(db.UnknownClientError):
      self.db.WriteClientSnapshotHistory([client])
Esempio n. 15
0
    def testWriteClientSnapshotHistoryRaiseAttributeError(self):
        client_id = self.InitializeClient()

        client = objects.ClientSnapshot(client_id=client_id)
        client.kernel = "1.2.3"
        client.startup_info.client_info.client_version = 42

        with self.assertRaisesRegexp(AttributeError, "timestamp"):
            self.db.WriteClientSnapshotHistory([client])
Esempio n. 16
0
    def _ResponseToClientsFullInfo(self, response):
        c_full_info = None
        prev_cid = None
        for row in response:
            (cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts,
             last_crash_ts, last_startup_ts, client_obj, client_startup_obj,
             last_startup_obj, label_owner, label_name) = row

            if cid != prev_cid:
                if c_full_info:
                    yield _IntToClientID(prev_cid), c_full_info

                metadata = objects.ClientMetadata(
                    certificate=crt,
                    fleetspeak_enabled=fs,
                    first_seen=_MysqlToRDFDatetime(first),
                    ping=_MysqlToRDFDatetime(ping),
                    clock=_MysqlToRDFDatetime(clk),
                    ip=_StringToRDFProto(rdf_client.NetworkAddress, ip),
                    last_foreman_time=_MysqlToRDFDatetime(foreman),
                    startup_info_timestamp=_MysqlToRDFDatetime(
                        last_startup_ts),
                    last_crash_timestamp=_MysqlToRDFDatetime(last_crash_ts))

                if client_obj is not None:
                    l_snapshot = objects.ClientSnapshot.FromSerializedString(
                        client_obj)
                    l_snapshot.timestamp = _MysqlToRDFDatetime(last_client_ts)
                    l_snapshot.startup_info = rdf_client.StartupInfo.FromSerializedString(
                        client_startup_obj)
                    l_snapshot.startup_info.timestamp = l_snapshot.timestamp
                else:
                    l_snapshot = objects.ClientSnapshot(
                        client_id=_IntToClientID(cid))

                if last_startup_obj is not None:
                    startup_info = rdf_client.StartupInfo.FromSerializedString(
                        last_startup_obj)
                    startup_info.timestamp = _MysqlToRDFDatetime(
                        last_startup_ts)
                else:
                    startup_info = None

                prev_cid = cid
                c_full_info = objects.ClientFullInfo(
                    metadata=metadata,
                    labels=[],
                    last_snapshot=l_snapshot,
                    last_startup_info=startup_info)

            if label_owner and label_name:
                c_full_info.labels.append(
                    objects.ClientLabel(name=label_name, owner=label_owner))

        if c_full_info:
            yield _IntToClientID(prev_cid), c_full_info
Esempio n. 17
0
  def testClientWriteToUnknownClient(self):
    d = self.db
    client_id = "C.fc413187fefa1dcf"

    with self.assertRaises(db.UnknownClientError):
      d.WriteClientSnapshot(objects.ClientSnapshot(client_id=client_id))

    # fleetspeak_enabled not set means update.
    with self.assertRaises(db.UnknownClientError):
      d.WriteClientMetadata(client_id, first_seen=rdfvalue.RDFDatetime.Now())
Esempio n. 18
0
def MakeClient():
    client = objects.ClientSnapshot(client_id="C.0000000000000000")

    base_pb = objects_pb2.ClientSnapshot()
    # pylint: disable=line-too-long
    text_format.Merge(
        """
    os_release: "Ubuntu"
    os_version: "14.4"
    interfaces: {
      addresses: {
        address_type: INET
        packed_bytes: "\177\000\000\001"
      }
      addresses: {
        address_type: INET6
        packed_bytes: "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"
      }
    }
    interfaces: {
    mac_address: "\001\002\003\004\001\002\003\004\001\002\003\004"
      addresses: {
        address_type: INET
        packed_bytes: "\010\010\010\010"
      }
      addresses: {
        address_type: INET6
        packed_bytes: "\376\200\001\002\003\000\000\000\000\000\000\000\000\000\000\000"
      }
    }
    knowledge_base: {
      users: {
        username: "******"
        full_name: "Good Guy Joe"
      }
      users: {
        username: "******"
        full_name: "Ok Guy Fred"
      }
      fqdn: "test123.examples.com"
      os: "Linux"
    }
    cloud_instance: {
      cloud_type: GOOGLE
      google: {
        unique_id: "us-central1-a/myproject/1771384456894610289"
      }
    }
    """, base_pb)
    # pylint: enable=line-too-long

    client.ParseFromString(base_pb.SerializeToString())
    return client
Esempio n. 19
0
    def _SetupLastPingClients(self, now):
        time_past = now - rdfvalue.Duration("1d")

        client_ids_to_ping = {}
        for i in range(10):
            client_id = self.InitializeClient()

            self.db.WriteClientSnapshot(
                objects.ClientSnapshot(client_id=client_id))
            ping = (time_past if i % 2 == 0 else now)
            self.db.WriteClientMetadata(client_id, last_ping=ping)

            client_ids_to_ping[client_id] = ping

        return client_ids_to_ping
Esempio n. 20
0
    def testWriteClientSnapshotHistoryUpdatesLastTimestampIfNotSet(self):
        client_id = self.InitializeClient()

        client_new = objects.ClientSnapshot(client_id=client_id)
        client_new.kernel = "1.0.0"
        client_new.timestamp = rdfvalue.RDFDatetime.FromHumanReadable(
            "2010-01-01")
        self.db.WriteClientSnapshotHistory([client_new])

        info = self.db.ReadClientFullInfo(client_id)
        self.assertEqual(info.last_snapshot.kernel, "1.0.0")
        self.assertEqual(info.last_snapshot.timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-01-01"))
        self.assertEqual(info.last_startup_info.timestamp,
                         rdfvalue.RDFDatetime.FromHumanReadable("2010-01-01"))
Esempio n. 21
0
    def _SetupFullInfoClients(self):
        for i in range(10):
            client_id = self.InitializeClient("C.000000005000000%d" % i)

            cl = objects.ClientSnapshot(
                client_id=client_id,
                knowledge_base=rdf_client.KnowledgeBase(
                    fqdn="test%d.examples.com" % i),
                kernel="12.3.%d" % i)
            self.db.WriteClientSnapshot(cl)
            self.db.WriteClientMetadata(client_id, certificate=CERT)
            si = rdf_client.StartupInfo(boot_time=i)
            self.db.WriteClientStartupInfo(client_id, si)
            self.db.AddClientLabels(
                client_id, "test_owner",
                ["test_label-a-%d" % i,
                 "test_label-b-%d" % i])
Esempio n. 22
0
  def testClientSnapshotHistory(self):
    d = self.db

    client_id = "C.fc413187fefa1dcf"
    self._InitializeClient(client_id)

    client = objects.ClientSnapshot(client_id=client_id, kernel="12.3")
    client.knowledge_base.fqdn = "test1234.examples.com"
    d.WriteClientSnapshot(client)
    client.kernel = "12.4"
    d.WriteClientSnapshot(client)

    hist = d.ReadClientSnapshotHistory(client_id)
    self.assertEqual(len(hist), 2)
    self.assertIsInstance(hist[0], objects.ClientSnapshot)
    self.assertIsInstance(hist[1], objects.ClientSnapshot)
    self.assertGreater(hist[0].timestamp, hist[1].timestamp)
    self.assertIsInstance(hist[0].timestamp, rdfvalue.RDFDatetime)
    self.assertEqual(hist[0].kernel, "12.4")
    self.assertEqual(hist[1].kernel, "12.3")
Esempio n. 23
0
    def _SetUpReadClientSnapshotHistoryTest(self):
        d = self.db

        self.client_id = self.InitializeClient()

        timestamps = [rdfvalue.RDFDatetime.Now()]

        client = objects.ClientSnapshot(client_id=self.client_id,
                                        kernel="12.3")
        client.knowledge_base.fqdn = "test1234.examples.com"
        d.WriteClientSnapshot(client)
        timestamps.append(d.ReadClientSnapshot(self.client_id).timestamp)

        timestamps.append(rdfvalue.RDFDatetime.Now())

        client.kernel = "12.4"
        d.WriteClientSnapshot(client)
        timestamps.append(d.ReadClientSnapshot(self.client_id).timestamp)

        timestamps.append(rdfvalue.RDFDatetime.Now())

        return timestamps
Esempio n. 24
0
    def testReadClientFullInfoReturnsCorrectResult(self):
        d = self.db

        client_id = self.InitializeClient()

        cl = objects.ClientSnapshot(client_id=client_id,
                                    knowledge_base=rdf_client.KnowledgeBase(
                                        fqdn="test1234.examples.com"),
                                    kernel="12.3")
        d.WriteClientSnapshot(cl)
        d.WriteClientMetadata(client_id, certificate=CERT)
        si = rdf_client.StartupInfo(boot_time=1)
        d.WriteClientStartupInfo(client_id, si)
        d.AddClientLabels(client_id, "test_owner", ["test_label"])

        full_info = d.ReadClientFullInfo(client_id)
        self.assertEqual(full_info.last_snapshot, cl)
        self.assertEqual(full_info.metadata.certificate, CERT)
        self.assertEqual(full_info.last_startup_info, si)
        self.assertEqual(
            full_info.labels,
            [objects.ClientLabel(owner="test_owner", name="test_label")])
Esempio n. 25
0
  def testReadAllClientsFullInfoFiltersClientsByLastPingTime(self):
    d = self.db

    now = rdfvalue.RDFDatetime.Now()
    time_past = now - rdfvalue.Duration("1d")

    expected_client_ids = set()
    for i in range(10):
      client_id = "C.000000005000000%d" % i
      self._InitializeClient(client_id)

      d.WriteClientSnapshot(objects.ClientSnapshot(client_id=client_id))
      d.WriteClientMetadata(
          client_id, last_ping=(time_past if i % 2 == 0 else now))

      if i % 2 != 0:
        expected_client_ids.add(client_id)

    c_ids = set(
        c.last_snapshot.client_id for c in d.ReadAllClientsFullInfo(
            min_last_ping=now - rdfvalue.Duration("1s")))
    self.assertEqual(expected_client_ids, c_ids)
Esempio n. 26
0
    def testAnalyzeClient(self):
        index = client_index.ClientIndex()

        client = objects.ClientSnapshot(client_id="C.0000000000000000")
        client.knowledge_base.os = "Windows"
        client.startup_info.client_info.client_name = "grr monitor"
        client.startup_info.client_info.labels = ["client-label-23"]
        kb = client.knowledge_base
        kb.users = [
            rdf_client.User(
                username="******",
                full_name="Eric (Bertrand ) 'Russell' \"Logician\" Jacobson"),
            rdf_client.User(username="******", full_name="Steve O'Bryan")
        ]
        keywords = index.AnalyzeClient(client)

        # Should not contain an empty string.
        self.assertNotIn("", keywords)

        # OS of the client
        self.assertIn("windows", keywords)

        # Users of the client.
        self.assertIn("bert", keywords)
        self.assertIn("bertrand", keywords)
        self.assertNotIn(")", keywords)
        self.assertIn("russell", keywords)
        self.assertIn("logician", keywords)
        self.assertIn("ernie", keywords)
        self.assertIn("eric", keywords)
        self.assertIn("jacobson", keywords)
        self.assertIn("steve o'bryan", keywords)
        self.assertIn("o'bryan", keywords)

        # Client information.
        self.assertIn("grr monitor", keywords)
        self.assertIn("client-label-23", keywords)
Esempio n. 27
0
    def _SetupClients(self, n):
        res = {}
        for i in range(1, n + 1):
            client_id = "C.100000000000000%d" % i
            client = objects.ClientSnapshot(client_id=client_id)
            client.knowledge_base.os = "Windows"
            client.knowledge_base.fqdn = "host-%d.example.com" % i

            client.interfaces = [
                rdf_client.Interface(addresses=[
                    rdf_client.NetworkAddress(
                        address_type=rdf_client.NetworkAddress.Family.INET,
                        packed_bytes=ipv6_utils.InetPtoN(
                            socket.AF_INET, "192.168.0.%d" % i)),
                    rdf_client.NetworkAddress(
                        address_type=rdf_client.NetworkAddress.Family.INET6,
                        packed_bytes=ipv6_utils.InetPtoN(
                            socket.AF_INET6, "2001:abcd::%d" % i))
                ],
                                     mac_address=("aabbccddee0%d" %
                                                  i).decode("hex"))
            ]
            res[client_id] = client
        return res
Esempio n. 28
0
    def testClientWriteToUnknownClient(self):
        d = self.db
        client_id = "C.fc413187fefa1dcf"

        with self.assertRaises(db.UnknownClientError):
            d.WriteClientSnapshot(objects.ClientSnapshot(client_id=client_id))