예제 #1
0
파일: client.py 프로젝트: stephanas50/grr
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 errors.keys() != ["Client.private_key"]:
        raise config_lib.ConfigFormatError(errors)

    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()
 def __init__(self, ca_cert=None, private_key=None):
     super(GRRClient, self).__init__()
     ca_cert = ca_cert or config_lib.CONFIG["CA.certificate"]
     private_key = private_key or config_lib.CONFIG.Get(
         "Client.private_key", default=None)
     self.client = comms.GRRHTTPClient(ca_cert=ca_cert,
                                       private_key=private_key)
예제 #3
0
    def _RunClientFileFinder(self,
                             paths,
                             action,
                             network_bytes_limit=None,
                             client_id=None):
        client_id = client_id or self.SetupClients(1)[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))
            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
예제 #4
0
def InstallerNotifyServer():
  """An emergency function Invoked when the client installation failed."""
  # We make a temporary emergency config file to contain the new client id. Note
  # that the notification callback does not really mean anything to us, since
  # the client is not installed and we dont have basic interrogate information.
  config_lib.CONFIG.SetWriteBack("temp.yaml")

  try:
    log_data = open(config_lib.CONFIG["Installer.logfile"], "rb").read()
  except (IOError, OSError):
    log_data = ""

  # Start the client and send the server a message, then terminate. The
  # private key may be empty if we did not install properly yet. In this case,
  # the client will automatically generate a random client ID and private key
  # (and the message will be unauthenticated since we never enrolled.).
  comms.CommsInit().RunOnce()

  client = comms.GRRHTTPClient(
      ca_cert=config_lib.CONFIG["CA.certificate"],
      private_key=config_lib.CONFIG.Get("Client.private_key"))

  client.client_worker.SendReply(
      session_id=rdf_flows.FlowSessionID(flow_name="InstallationFailed"),
      message_type=rdf_flows.GrrMessage.Type.STATUS,
      request_id=0,
      response_id=0,
      rdf_value=rdf_flows.GrrStatus(
          status=rdf_flows.GrrStatus.ReturnedStatus.GENERIC_ERROR,
          error_message="Installation failed.",
          backtrace=log_data[-10000:]))

  client.RunOnce()
예제 #5
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))

            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
예제 #6
0
  def __init__(self, ca_cert=None, private_key=None):
    """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)
    self.stop = False
    # Is this client already enrolled?
    self.enrolled = False
예제 #7
0
  def testClientConnectionErrors(self):
    client_obj = comms.GRRHTTPClient()
    # Make the connection unavailable and skip the retry interval.
    with utils.Stubber(requests, "request", self.RaiseError):
      with test_lib.ConfigOverrider({"Client.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,
                         config_lib.CONFIG["Client.connection_error_limit"] + 1)
예제 #8
0
    def CreateNewClientObject(self):
        self.client_communicator = comms.GRRHTTPClient(
            ca_cert=config_lib.CONFIG["CA.certificate"],
            worker=comms.GRRClientWorker)

        # Disable stats collection for tests.
        self.client_communicator.client_worker.last_stats_sent_time = (
            time.time() + 3600)

        # Build a client context with preloaded server certificates
        self.client_communicator.communicator.LoadServerCertificate(
            self.server_certificate, config_lib.CONFIG["CA.certificate"])
예제 #9
0
  def testClientConnectionErrors(self):
    client_obj = comms.GRRHTTPClient()
    # 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)
예제 #10
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_lib.CONFIG.SetWriteBack(self.config_file)

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

        location = ["http://www.example1.com/", "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_lib.CONFIG["Client.foreman_check_frequency"],
                         3600)

        # Test the config file got written.
        data = open(self.config_file, "rb").read()
        self.assertTrue("server_urls: {0}".format(",".join(location)) in 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=MockClientWorker())
            client_context.MakeRequest("")

        # Since the request is successful we only connect to one location.
        self.assertTrue(location[0] in self.urls[0])
예제 #11
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_lib.CONFIG.SetWriteBack(self.config_file)

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

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

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

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

        # Test the config file got written.
        data = open(self.config_file).read()
        self.assertTrue("control_urls: {0}".format(",".join(location)) in data)

        self.urls = []

        # Now test that our location was actually updated.

        def FakeUrlOpen(req, timeout=10):
            _ = timeout
            self.urls.append(req.get_full_url())
            return StringIO.StringIO()

        comms.urllib2.urlopen = FakeUrlOpen
        client_context = comms.GRRHTTPClient(worker=MockClientWorker)
        client_context.MakeRequest("", comms.Status())

        self.assertTrue(location[0] in self.urls[0])
        self.assertTrue(location[1] in self.urls[1])
예제 #12
0
 def CreateClientCommunicator(self):
   self.client_communicator = comms.GRRHTTPClient(
       ca_cert=config_lib.CONFIG["CA.certificate"],
       worker=comms.GRRThreadedWorker(start_worker_thread=False))
예제 #13
0
 def CreateClientCommunicator(self):
   self.client_communicator = comms.GRRHTTPClient(
       ca_cert=config_lib.CONFIG["CA.certificate"],
       worker=comms.GRRClientWorker())
예제 #14
0
 def CreateClientCommunicator(self):
   self.client_communicator = comms.GRRHTTPClient(
       ca_cert=config.CONFIG["CA.certificate"],
       worker_cls=worker_mocks.DisabledNannyThreadedWorker)