Ejemplo n.º 1
0
  def _UploadFile(self, args):
    with test_lib.ConfigOverrider({"Client.server_urls": [self.base_url]}):
      client = comms.GRRHTTPClient(
          ca_cert=config.CONFIG["CA.certificate"],
          private_key=config.CONFIG.Get("Client.private_key", default=None),
          worker_cls=worker_mocks.DisabledNannyClientWorker)

      client.server_certificate = config.CONFIG["Frontend.certificate"]

      def MockSendReply(_, reply):
        self.reply = reply

      @classmethod
      def FromPrivateKey(*_):
        """Returns the correct client id.

        The test framework does not generate valid client ids (which should be
        related to the client's private key. We therefore need to mock it and
        override.

        Returns:
          Correct client_id
        """
        return self.client_id

      with utils.MultiStubber(
          (standard.UploadFile, "SendReply", MockSendReply),
          (rdf_client.ClientURN, "FromPrivateKey", FromPrivateKey)):
        action = standard.UploadFile(client.client_worker)
        action.Run(args)

      return self.reply
Ejemplo n.º 2
0
def main(unused_args):
    # Allow per platform configuration.
    config.CONFIG.AddContext(
        contexts.CLIENT_CONTEXT,
        "Context applied when we run the client process.")

    client_startup.ClientInit()

    if flags.FLAGS.install:
        installer.RunInstaller()

    errors = config.CONFIG.Validate(["Client", "CA", "Logging"])

    if errors and list(iterkeys(errors.keys)) != ["Client.private_key"]:
        raise config_lib.ConfigFormatError(errors)

    if config.CONFIG["Client.fleetspeak_enabled"]:
        raise ValueError(
            "This is not a Fleetspeak client, yet 'Client.fleetspeak_enabled' is "
            "set to 'True'.")

    enrollment_necessary = not config.CONFIG.Get("Client.private_key")
    # Instantiating the client will create a private_key so we need to use a flag.
    client = comms.GRRHTTPClient(ca_cert=config.CONFIG["CA.certificate"],
                                 private_key=config.CONFIG.Get(
                                     "Client.private_key", default=None))

    if enrollment_necessary:
        logging.info("No private key found, starting enrollment.")
        client.InitiateEnrolment()

    if flags.FLAGS.break_on_start:
        pdb.set_trace()
    else:
        client.Run()
Ejemplo n.º 3
0
  def _RunClientFileFinder(self,
                           paths,
                           action,
                           network_bytes_limit=None,
                           client_id=None):
    client_id = client_id or self.SetupClient(0)
    with test_lib.ConfigOverrider({"Client.server_urls": [self.base_url]}):
      client = comms.GRRHTTPClient(
          ca_cert=config.CONFIG["CA.certificate"],
          private_key=config.CONFIG.Get("Client.private_key", default=None),
          worker_cls=worker_mocks.DisabledNannyClientWorker)
      client.client_worker = worker_mocks.FakeThreadedWorker(client=client)
      client.server_certificate = config.CONFIG["Frontend.certificate"]

      for s in flow_test_lib.TestFlowHelper(
          file_finder.ClientFileFinder.__name__,
          action_mocks.ClientFileFinderClientMock(
              client_worker=client.client_worker),
          client_id=client_id,
          paths=paths,
          pathtype=rdf_paths.PathSpec.PathType.OS,
          action=action,
          process_non_regular_files=True,
          network_bytes_limit=network_bytes_limit,
          token=self.token):
        session_id = s

      return session_id
Ejemplo n.º 4
0
def main(unused_args):
    client_plugins.RegisterPlugins()

    if flags.FLAGS.remote_debugging_port:
        _start_remote_debugging(flags.FLAGS.remote_debugging_port)
    elif flags.FLAGS.break_on_start:
        pdb.set_trace()

    if (flags.FLAGS.unprivileged_server_pipe_input != -1
            and flags.FLAGS.unprivileged_server_pipe_output != -1
            and flags.FLAGS.unprivileged_server_interface):
        communication.Main(
            communication.Channel.FromSerialized(
                pipe_input=flags.FLAGS.unprivileged_server_pipe_input,
                pipe_output=flags.FLAGS.unprivileged_server_pipe_output),
            interface_registry.GetConnectionHandlerForInterfaceString(
                flags.FLAGS.unprivileged_server_interface),
            flags.FLAGS.unprivileged_user, flags.FLAGS.unprivileged_group)
        return

    # Allow per platform configuration.
    config.CONFIG.AddContext(
        contexts.CLIENT_CONTEXT,
        "Context applied when we run the client process.")

    client_startup.ClientInit()

    if flags.FLAGS.install:
        installer.RunInstaller()
        sys.exit(0)

    if config.CONFIG["Client.fleetspeak_enabled"]:
        fleetspeak_client.GRRFleetspeakClient().Run()
        return

    errors = config.CONFIG.Validate(["Client", "CA", "Logging"])

    if errors and list(errors.keys()) != ["Client.private_key"]:
        raise config_lib.ConfigFormatError(errors)

    if config.CONFIG["Client.fleetspeak_enabled"]:
        raise ValueError(
            "This is not a Fleetspeak client, yet 'Client.fleetspeak_enabled' is "
            "set to 'True'.")

    enrollment_necessary = not config.CONFIG.Get("Client.private_key")
    # Instantiating the client will create a private_key so we need to use a flag.
    client = comms.GRRHTTPClient(ca_cert=config.CONFIG["CA.certificate"],
                                 private_key=config.CONFIG.Get(
                                     "Client.private_key", default=None))

    if enrollment_necessary:
        logging.info("No private key found, starting enrollment.")
        client.InitiateEnrolment()

    client.Run()
Ejemplo n.º 5
0
def main(unused_args):
    client_plugins.RegisterPlugins()

    if flags.FLAGS.remote_debugging_port:
        _start_remote_debugging(flags.FLAGS.remote_debugging_port)
    elif flags.FLAGS.break_on_start:
        pdb.set_trace()

    # Allow per platform configuration.
    config.CONFIG.AddContext(
        contexts.CLIENT_CONTEXT,
        "Context applied when we run the client process.")

    client_startup.ClientInit()

    if flags.FLAGS.install:
        installer.RunInstaller()
        sys.exit(0)

    is_pyinstaller_binary = getattr(sys, "frozen", False)
    if is_pyinstaller_binary and platform.system() == "Windows":
        # Since `Client.install_path` is shared with the Sandbox, Sandbox
        # initialization makes only sense if we run from a proper installation.
        # This is the case if this is a PyInstaller binary.
        sandbox.InitSandbox(
            "{}_{}".format(config.CONFIG["Client.name"],
                           config.CONFIG["Source.version_string"]),
            [config.CONFIG["Client.install_path"]])

    if config.CONFIG["Client.fleetspeak_enabled"]:
        fleetspeak_client.GRRFleetspeakClient().Run()
        return

    errors = config.CONFIG.Validate(["Client", "CA", "Logging"])

    if errors and list(errors.keys()) != ["Client.private_key"]:
        raise config_lib.ConfigFormatError(errors)

    if config.CONFIG["Client.fleetspeak_enabled"]:
        raise ValueError(
            "This is not a Fleetspeak client, yet 'Client.fleetspeak_enabled' is "
            "set to 'True'.")

    enrollment_necessary = not config.CONFIG.Get("Client.private_key")
    # Instantiating the client will create a private_key so we need to use a flag.
    client = comms.GRRHTTPClient(ca_cert=config.CONFIG["CA.certificate"],
                                 private_key=config.CONFIG.Get(
                                     "Client.private_key", default=None))

    if enrollment_necessary:
        logging.info("No private key found, starting enrollment.")
        client.InitiateEnrolment()

    client.Run()
Ejemplo n.º 6
0
  def testClientConnectionErrors(self):
    client_obj = comms.GRRHTTPClient(
        worker_cls=worker_mocks.DisabledNannyClientWorker)
    # Make the connection unavailable and skip the retry interval.
    with utils.MultiStubber(
        (requests, "request", self.RaiseError),
        (client_obj.http_manager, "connection_error_limit", 8)):
      # Simulate a client run. The client will retry the connection limit by
      # itself. The Run() method will quit when connection_error_limit is
      # reached. This will make the real client quit.
      client_obj.Run()

      self.assertEqual(client_obj.http_manager.consecutive_connection_errors, 9)
Ejemplo n.º 7
0
  def __init__(self, ca_cert=None, private_key=None, fast_poll=False):
    """Constructor."""
    super(PoolGRRClient, self).__init__()
    self.private_key = private_key
    self.daemon = True

    self.client = comms.GRRHTTPClient(ca_cert=ca_cert, private_key=private_key)
    if fast_poll:
      self.client.timer.FastPoll()

    self.stop = False
    # Is this client already enrolled?
    self.enrolled = False
Ejemplo n.º 8
0
  def testUpdateConfiguration(self):
    """Test that we can update the config."""
    # A unique name on the filesystem for the writeback.
    self.config_file = os.path.join(self.temp_dir, "ConfigActionTest.yaml")

    # In a real client, the writeback location should be set to something real,
    # but for this test we make it the same as the config file..
    config.CONFIG.SetWriteBack(self.config_file)

    # Make sure the file is gone
    self.assertRaises(IOError, open, self.config_file)

    location = [u"http://www.example1.com/", u"http://www.example2.com/"]
    request = rdf_protodict.Dict()
    request["Client.server_urls"] = location
    request["Client.foreman_check_frequency"] = 3600

    result = self.RunAction(admin.UpdateConfiguration, request)

    self.assertEqual(result, [])
    self.assertEqual(config.CONFIG["Client.foreman_check_frequency"], 3600)

    # Test the config file got written.
    with io.open(self.config_file, "r") as filedesc:
      data = filedesc.read()

    server_urls = """
Client.server_urls:
- http://www.example1.com/
- http://www.example2.com/
"""
    self.assertIn(server_urls, data)

    self.urls = []

    # Now test that our location was actually updated.

    def FakeUrlOpen(url=None, data=None, **_):
      self.urls.append(url)
      response = requests.Response()
      response.status_code = 200
      response._content = data
      return response

    with utils.Stubber(requests, "request", FakeUrlOpen):
      client_context = comms.GRRHTTPClient(worker_cls=MockClientWorker)
      client_context.MakeRequest("")

    # Since the request is successful we only connect to one location.
    self.assertIn(location[0], self.urls[0])
Ejemplo n.º 9
0
def main(unused_args):
  if flags.FLAGS.remote_debugging_port:
    _start_remote_debugging(flags.FLAGS.remote_debugging_port)
  elif flags.FLAGS.break_on_start:
    pdb.set_trace()

  if flags.FLAGS.filesystem_server_socket != -1:
    communication.Main(flags.FLAGS.filesystem_server_socket,
                       server_lib.Dispatch)
    return

  # Allow per platform configuration.
  config.CONFIG.AddContext(contexts.CLIENT_CONTEXT,
                           "Context applied when we run the client process.")

  client_startup.ClientInit()

  if flags.FLAGS.install:
    installer.RunInstaller()
    sys.exit(0)

  if config.CONFIG["Client.fleetspeak_enabled"]:
    fleetspeak_client.GRRFleetspeakClient().Run()
    return

  errors = config.CONFIG.Validate(["Client", "CA", "Logging"])

  if errors and list(errors.keys()) != ["Client.private_key"]:
    raise config_lib.ConfigFormatError(errors)

  if config.CONFIG["Client.fleetspeak_enabled"]:
    raise ValueError(
        "This is not a Fleetspeak client, yet 'Client.fleetspeak_enabled' is "
        "set to 'True'.")

  enrollment_necessary = not config.CONFIG.Get("Client.private_key")
  # Instantiating the client will create a private_key so we need to use a flag.
  client = comms.GRRHTTPClient(
      ca_cert=config.CONFIG["CA.certificate"],
      private_key=config.CONFIG.Get("Client.private_key", default=None))

  if enrollment_necessary:
    logging.info("No private key found, starting enrollment.")
    client.InitiateEnrolment()

  client.Run()
Ejemplo n.º 10
0
  def __init__(self,
               ca_cert=None,
               private_key=None,
               fast_poll=False,
               send_foreman_request=False):
    """Constructor."""
    super().__init__()
    self.private_key = private_key
    self.daemon = True

    self.client = comms.GRRHTTPClient(ca_cert=ca_cert, private_key=private_key)
    if fast_poll:
      self.client.timer.FastPoll()

    if send_foreman_request:
      self.client.SendForemanRequest()

    self.stop = False
    # Is this client already enrolled?
    self.enrolled = False
Ejemplo n.º 11
0
 def CreateClientCommunicator(self):
   self.client_communicator = comms.GRRHTTPClient(
       ca_cert=config.CONFIG["CA.certificate"],
       worker_cls=worker_mocks.DisabledNannyClientWorker)