Esempio n. 1
0
def main(argv):
    """Main."""
    del argv  # Unused.
    banner = ("\nWelcome to the GRR console\n")

    config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    config.CONFIG.AddContext(
        contexts.CONSOLE_CONTEXT,
        "Context applied when running the console binary.")
    server_startup.Init()

    fleetspeak_connector.Init()

    # To make the console easier to use, we make a default token which will be
    # used in StartFlow operations.
    data_store.default_token = access_control.ACLToken(
        username=getpass.getuser(), reason=flags.FLAGS.reason)

    locals_vars = {
        "__name__": "GRR Console",
        "l": Lister,
        "lc": GetChildrenList,
        "o": aff4.FACTORY.Open,

        # Bring some symbols from other modules into the console's
        # namespace.
        "StartFlowAndWait": flow_utils.StartFlowAndWait,
        "StartFlowAndWorker": console_utils.StartFlowAndWorker,
    }

    locals_vars.update(globals())  # add global variables to console
    if flags.FLAGS.client is not None:
        locals_vars["client"], locals_vars["token"] = console_utils.OpenClient(
            client_id=flags.FLAGS.client)

    if flags.FLAGS.code_to_execute:
        logging.info("Running code from flag: %s", flags.FLAGS.code_to_execute)
        exec(flags.FLAGS.code_to_execute)  # pylint: disable=exec-used
    elif flags.FLAGS.command_file:
        logging.info("Running code from file: %s", flags.FLAGS.command_file)
        with open(flags.FLAGS.command_file, "r") as filedesc:
            exec(filedesc.read())  # pylint: disable=exec-used

    if (flags.FLAGS.exit_on_complete
            and (flags.FLAGS.code_to_execute or flags.FLAGS.command_file)):
        return

    else:  # We want the normal shell.
        locals_vars.update(globals())  # add global variables to console
        ipshell.IPShell(argv=[], user_ns=locals_vars, banner=banner)
Esempio n. 2
0
    def testProcessListingOnlyFleetspeak(self):
        """Test that the ListProcesses flow works with Fleetspeak."""
        client_mock = action_mocks.ListProcessesMock([
            rdf_client.Process(pid=2,
                               ppid=1,
                               cmdline=["cmd.exe"],
                               exe=r"c:\windows\cmd.exe",
                               ctime=1333718907167083)
        ])
        client_mock.mock_task_queue = []

        def SendCallback(fs_msg):
            pb_msg = jobs_pb2.GrrMessage()
            fs_msg.data.Unpack(pb_msg)
            msg = rdf_flows.GrrMessage.FromSerializedString(
                pb_msg.SerializeToString())
            client_mock.mock_task_queue.append(msg)

        service_name = "GRR"
        fake_service_client = _FakeGRPCServiceClient(
            service_name, send_callback=SendCallback)

        fleetspeak_connector.Reset()
        fleetspeak_connector.Init(service_client=fake_service_client)

        with mock.patch.object(
                fake_service_client.outgoing,
                "InsertMessage",
                wraps=fake_service_client.outgoing.InsertMessage):
            flow_urn = flow.StartFlow(
                client_id=self.client_id,
                flow_name=flow_processes.ListProcesses.__name__,
                token=self.token)
            session_id = flow_test_lib.TestFlowHelper(flow_urn,
                                                      client_mock,
                                                      client_id=self.client_id,
                                                      token=self.token)

            fleetspeak_connector.CONN.outgoing.InsertMessage.assert_called()

        # Check the output collection
        processes = flow.GRRFlow.ResultCollectionForFID(session_id)

        self.assertEqual(len(processes), 1)
        process, = processes

        self.assertEqual(process.ctime, 1333718907167083)
        self.assertEqual(process.cmdline, ["cmd.exe"])
Esempio n. 3
0
  def testGetLabelsFromFleetspeak_NoPrefix(self):
    conn = _MockConnReturningClient(_TEST_CLIENT_ID, [
        ("client", "foo-1"),
        ("client", "bar-2"),
        ("service-1", "foo-3"),
        ("service-1", "foo-4"),
        ("client", "foo-5"),
    ])

    with test_lib.ConfigOverrider({
        "Server.fleetspeak_label_map": ["foo-5:baz-5"],
    }):
      with mock.patch.object(fleetspeak_connector, "CONN", conn):
        fleetspeak_connector.Init(conn)
        self.assertListEqual(
            fleetspeak_utils.GetLabelsFromFleetspeak(_TEST_CLIENT_ID),
            ["foo-1", "bar-2", "baz-5"])
Esempio n. 4
0
def main(argv):
    """Main."""
    del argv  # Unused.

    if flags.FLAGS.version:
        print("GRR worker {}".format(config_server.VERSION["packageversion"]))
        return

    config.CONFIG.AddContext(contexts.WORKER_CONTEXT,
                             "Context applied when running a worker.")

    # Initialise flows and config_lib
    server_startup.Init()

    fleetspeak_connector.Init()

    worker_obj = worker_lib.GRRWorker()
    worker_obj.Run()
Esempio n. 5
0
def main(argv):
    """Main."""
    del argv  # Unused.

    if flags.FLAGS.version:
        print("GRR console {}".format(config_server.VERSION["packageversion"]))
        return

    banner = ("\nWelcome to the GRR console\n")

    config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    config.CONFIG.AddContext(
        contexts.CONSOLE_CONTEXT,
        "Context applied when running the console binary.")
    server_startup.Init()

    fleetspeak_connector.Init()

    locals_vars = {
        "__name__": "GRR Console",

        # Bring some symbols from other modules into the console's
        # namespace.
        "StartFlowAndWait": flow_utils.StartFlowAndWait,
    }

    locals_vars.update(globals())  # add global variables to console

    if flags.FLAGS.code_to_execute:
        logging.info("Running code from flag: %s", flags.FLAGS.code_to_execute)
        exec(flags.FLAGS.code_to_execute)  # pylint: disable=exec-used
    elif flags.FLAGS.command_file:
        logging.info("Running code from file: %s", flags.FLAGS.command_file)
        with open(flags.FLAGS.command_file, "r") as filedesc:
            exec(filedesc.read())  # pylint: disable=exec-used

    if (flags.FLAGS.exit_on_complete
            and (flags.FLAGS.code_to_execute or flags.FLAGS.command_file)):
        return

    else:  # We want the normal shell.
        locals_vars.update(globals())  # add global variables to console
        ipshell.IPShell(argv=[], user_ns=locals_vars, banner=banner)
Esempio n. 6
0
def main(argv):
  del argv  # Unused.

  config.CONFIG.AddContext("FleetspeakFrontend Context")

  server_startup.Init()
  server_startup.DropPrivileges()

  fleetspeak_connector.Init()

  fsd = GRRFSServer()
  fleetspeak_connector.CONN.Listen(fsd.Process)

  logging.info("Serving through Fleetspeak ...")

  try:
    while True:
      time.sleep(600)
  except KeyboardInterrupt:
    print("Caught keyboard interrupt, stopping")
Esempio n. 7
0
def main(argv=None):
    del argv  # Unused.

    if flags.FLAGS.version:
        print("GRR API shell {}".format(
            config_server.VERSION["packageversion"]))
        return

    config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    config.CONFIG.AddContext(
        contexts.CONSOLE_CONTEXT,
        "Context applied when running the console binary.")
    server_startup.Init()
    fleetspeak_connector.Init()

    username = flags.FLAGS.username
    if not username:
        username = os.environ["USER"]

    if not username:
        print("Username has to be specified with either --username flag or "
              "USER environment variable.")
        sys.exit(1)

    grrapi = api.GrrApi(connector=api_shell_raw_access_lib.RawConnector(
        context=api_call_context.ApiCallContext(username=username),
        page_size=flags.FLAGS.page_size))

    if flags.FLAGS.exec_code and flags.FLAGS.exec_file:
        print("--exec_code --exec_file flags can't be supplied together.")
        sys.exit(1)
    elif flags.FLAGS.exec_code:
        # pylint: disable=exec-used
        exec(flags.FLAGS.exec_code, dict(grrapi=grrapi))
        # pylint: enable=exec-used
    elif flags.FLAGS.exec_file:
        api_shell_lib.ExecFile(flags.FLAGS.exec_file, grrapi)
    else:
        api_shell_lib.IPShell([sys.argv[0]], user_ns=dict(grrapi=grrapi))
Esempio n. 8
0
 def Start(self):
     self._previous_conn = fleetspeak_connector.CONN
     self._previous_label_map = fleetspeak_connector.label_map
     self._previous_unknown_label = fleetspeak_connector.unknown_label
     fleetspeak_connector.Init(self._conn)
Esempio n. 9
0
 def testGetLabelsFromFleetspeak_NoLabels(self):
   conn = _MockConnReturningClient(_TEST_CLIENT_ID, [("service-1", "foo-3")])
   with mock.patch.object(fleetspeak_connector, "CONN", conn):
     fleetspeak_connector.Init(conn)
     self.assertEmpty(
         fleetspeak_utils.GetLabelsFromFleetspeak(_TEST_CLIENT_ID))
Esempio n. 10
0
    def testReceiveMessagesFleetspeak(self):
        service_name = "GRR"
        fake_service_client = _FakeGRPCServiceClient(service_name)

        fleetspeak_connector.Reset()
        fleetspeak_connector.Init(service_client=fake_service_client)

        fsd = fs_frontend_tool.GRRFSServer()

        grr_client_nr = 0xab
        grr_client_id_urn = self.SetupClient(grr_client_nr)

        flow_obj = self.FlowSetup(flow_test_lib.FlowOrderTest.__name__,
                                  grr_client_id_urn)

        num_msgs = 9

        session_id = flow_obj.session_id
        messages = [
            rdf_flows.GrrMessage(request_id=1,
                                 response_id=i,
                                 session_id=session_id,
                                 payload=rdfvalue.RDFInteger(i))
            for i in range(1, num_msgs + 1)
        ]

        fs_client_id = "\x10\x00\x00\x00\x00\x00\x00\xab"
        # fs_client_id should be equivalent to grr_client_id_urn
        self.assertEqual(
            fs_client_id,
            fleetspeak_utils.GRRIDToFleetspeakID(grr_client_id_urn.Basename()))

        fs_messages = [
            fs_common_pb2.Message(message_type="GrrMessage",
                                  source=fs_common_pb2.Address(
                                      client_id=fs_client_id,
                                      service_name=service_name))
            for _ in range(num_msgs)
        ]
        for fs_message, message in itertools.izip(fs_messages, messages):
            fs_message.data.Pack(message.AsPrimitiveProto())

        for msg in fs_messages:
            fsd.Process(msg, None)

        # Make sure the task is still on the client queue
        manager = queue_manager.QueueManager(token=self.token)
        tasks_on_client_queue = manager.Query(grr_client_id_urn, 100)
        self.assertEqual(len(tasks_on_client_queue), 1)

        want_messages = [message.Copy() for message in messages]
        for want_message in want_messages:
            # This is filled in by the frontend as soon as it gets the message.
            want_message.auth_state = (
                rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED)
            want_message.source = grr_client_id_urn

        stored_messages = data_store.DB.ReadResponsesForRequestId(
            session_id, 1)

        self.assertEqual(len(stored_messages), len(want_messages))

        stored_messages.sort(key=lambda m: m.response_id)
        # Check that messages were stored correctly
        for stored_message, want_message in itertools.izip(
                stored_messages, want_messages):
            stored_message.timestamp = None
            self.assertRDFValuesEqual(stored_message, want_message)