Exemple #1
0
    def testSystemArtifactOverwrite(self):
        content = """
name: WMIActiveScriptEventConsumer
doc: here's the doc
sources:
- type: COMMAND
  attributes:
    args: ["-L", "-v", "-n"]
    cmd: /sbin/iptables
supported_os: [Linux]
"""
        artifact_registry.REGISTRY.ClearRegistry()
        artifact_registry.REGISTRY.ClearSources()
        artifact_registry.REGISTRY._CheckDirty()

        # System artifacts come from the test file.
        self.LoadTestArtifacts()

        # Uploaded files go to this collection.
        artifact_store_urn = aff4.ROOT_URN.Add("artifact_store")
        artifact_registry.REGISTRY.AddDatastoreSources([artifact_store_urn])

        # WMIActiveScriptEventConsumer is a system artifact, we can't overwrite it.
        with self.assertRaises(rdf_artifacts.ArtifactDefinitionError):
            artifact.UploadArtifactYamlFile(content)

        # Override the check and upload anyways. This simulates the case
        # where an artifact ends up shadowing a system artifact somehow -
        # for example when the system artifact was created after the
        # artifact was uploaded to the data store for testing.
        artifact.UploadArtifactYamlFile(content,
                                        overwrite_system_artifacts=True)

        # The shadowing artifact is at this point stored in the
        # collection. On the next full reload of the registry, there will
        # be an error that we can't overwrite the system artifact. The
        # artifact should automatically get deleted from the collection to
        # mitigate the problem.
        with self.assertRaises(rdf_artifacts.ArtifactDefinitionError):
            artifact_registry.REGISTRY._ReloadArtifacts()

        # As stated above, now this should work.
        artifact_registry.REGISTRY._ReloadArtifacts()

        # Make sure the artifact is now loaded and it's the version from the file.
        self.assertIn("WMIActiveScriptEventConsumer",
                      artifact_registry.REGISTRY._artifacts)
        artifact_obj = artifact_registry.REGISTRY.GetArtifact(
            "WMIActiveScriptEventConsumer")
        self.assertStartsWith(artifact_obj.loaded_from, "file:")

        # The artifact is gone from the collection.
        coll = artifact_registry.ArtifactCollection(artifact_store_urn)
        self.assertNotIn("WMIActiveScriptEventConsumer", coll)
Exemple #2
0
  def testArtifactRemovedFromFormsImmediatelyAfterDeletion(self):
    with open(self.json_file, "rb") as fd:
      artifact.UploadArtifactYamlFile(fd.read())

    client_id = self.SetupClient(0).Basename()
    self.RequestAndGrantClientApproval(client_id)

    # Test that we have TestDrivers available.
    self.Open("/#/clients/%s/launch-flow" % client_id)
    self.Click("css=#_Collectors a")
    self.Click("link=ArtifactCollectorFlow")
    self.WaitUntil(self.IsTextPresent, "TestDrivers")

    # Upload the artifact.
    self.Click("css=a[grrtarget=artifacts]")
    self.Click("css=grr-artifact-manager-view tr:contains('TestDrivers') "
               "input[type=checkbox]")
    self.Click("css=grr-artifact-manager-view button[name=DeleteArtifact]")
    self.Click("css=grr-delete-artifacts-dialog button[name=Proceed]")
    self.WaitUntil(self.IsTextPresent, "Artifacts were deleted successfully.")
    self.Click("css=grr-delete-artifacts-dialog button[name=Close]")

    # Test now we can choose TestDrivers in the form.
    self.Click("css=a[grrtarget='client.launchFlows']")
    self.Click("css=#_Collectors a")
    self.Click("link=ArtifactCollectorFlow")
    self.WaitUntil(self.IsTextPresent, "Artifact list")
    self.WaitUntilNot(self.IsTextPresent, "Loading artifacts...")
    self.WaitUntilNot(self.IsTextPresent, "TestDrivers")
Exemple #3
0
  def testArtifactDeletion(self):
    with open(self.json_file, "rb") as fd:
      artifact.UploadArtifactYamlFile(fd.read())

    self.Open("/#main=ArtifactManagerView")

    # Check that test artifact is displayed.
    self.WaitUntil(self.IsTextPresent, "TestDrivers")

    # Click on TestDrivers checkbox and click Delete.
    self.Click("css=grr-artifact-manager-view tr:contains('TestDrivers') "
               "input[type=checkbox]")
    self.Click("css=grr-artifact-manager-view button[name=DeleteArtifact]")

    # Check that dialog mentions TestDrivers and click on Proceed, then Close.
    self.WaitUntil(self.IsTextPresent, "Delete Selected Artifacts")
    self.WaitUntil(self.IsElementPresent,
                   "css=grr-delete-artifacts-dialog:contains('TestDrivers')")
    self.Click("css=grr-delete-artifacts-dialog button[name=Proceed]")
    self.WaitUntil(self.IsTextPresent, "Artifacts were deleted successfully.")
    self.Click("css=grr-delete-artifacts-dialog button[name=Close]")

    # Check that artifact is indeed deleted.
    self.WaitUntilNot(self.IsTextPresent, "Delete Selected Artifacts")
    self.WaitUntilNot(self.IsTextPresent, "Loading...")
    self.WaitUntilNot(self.IsTextPresent, "TestDrivers")
Exemple #4
0
    def testUploadArtifactYamlFileAndDumpToYaml(self):
        artifact_registry.REGISTRY.ClearRegistry()
        artifact_registry.REGISTRY.ClearSources()
        artifact_registry.REGISTRY._CheckDirty()

        try:

            test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                               "artifacts",
                                               "test_artifacts.json")
            filecontent = open(test_artifacts_file, "rb").read()
            artifact.UploadArtifactYamlFile(filecontent)
            loaded_artifacts = artifact_registry.REGISTRY.GetArtifacts()
            self.assertGreaterEqual(len(loaded_artifacts), 20)
            self.assertIn("DepsWindirRegex",
                          [a.name for a in loaded_artifacts])

            # Now dump back to YAML.
            yaml_data = artifact_registry.REGISTRY.DumpArtifactsToYaml()
            for snippet in [
                    "name: TestFilesArtifact",
                    "urls: ['https://msdn.microsoft.com/en-us/library/aa384749%28v=vs.85",
                    "returned_types: [SoftwarePackage]",
                    "args: [--list]",
                    "cmd: /usr/bin/dpkg",
            ]:
                self.assertIn(snippet, yaml_data)
        finally:
            artifact.ArtifactLoader().RunOnce()
Exemple #5
0
    def testUploadArtifactYamlFileAndDumpToYaml(self):
        artifact_registry.REGISTRY.ClearRegistry()
        artifact_registry.REGISTRY.ClearSources()
        artifact_registry.REGISTRY._CheckDirty()

        try:

            test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                               "artifacts",
                                               "test_artifacts.json")

            with io.open(test_artifacts_file, mode="r",
                         encoding="utf-8") as filedesc:
                artifact.UploadArtifactYamlFile(filedesc.read())
            loaded_artifacts = artifact_registry.REGISTRY.GetArtifacts()
            self.assertGreaterEqual(len(loaded_artifacts), 20)
            self.assertIn("DepsWindirRegex",
                          [a.name for a in loaded_artifacts])

            # Now dump back to YAML.
            yaml_data = artifact_registry.REGISTRY.DumpArtifactsToYaml()
            for snippet in [
                    "name: TestFilesArtifact",
                    "urls:\\s*- https://msdn.microsoft.com/en-us/library/",
                    "returned_types:\\s*- SoftwarePackage",
                    "args:\\s*- --list",
                    "cmd: /usr/bin/dpkg",
            ]:
                self.assertRegexpMatches(yaml_data, snippet)
        finally:
            artifact.LoadArtifactsOnce()
Exemple #6
0
 def Handle(self, args, token=None):
     # TODO: Make `ApiUploadArtifactArgs` be a unicode string rather
     # than byte string.
     content = args.artifact.decode("utf-8")
     artifact.UploadArtifactYamlFile(content,
                                     overwrite=True,
                                     overwrite_system_artifacts=False)
Exemple #7
0
    def testUploadArtifactYamlFileMissingDoc(self):
        content = """name: Nodoc
sources:
- type: GREP
  attributes:
    paths: [/etc/blah]
    content_regex_list: ["stuff"]
supported_os: [Linux]
"""
        with self.assertRaises(rdf_artifacts.ArtifactDefinitionError):
            artifact.UploadArtifactYamlFile(content)
Exemple #8
0
    def testUploadArtifactBadDependencies(self):
        yaml_artifact = """
name: InvalidArtifact
doc: An artifact group with invalid dependencies.
sources:
- type: ARTIFACT_GROUP
  attributes:
    names:
      - NonExistingArtifact
"""
        with self.assertRaises(rdf_artifacts.ArtifactDependencyError):
            artifact.UploadArtifactYamlFile(yaml_artifact)
Exemple #9
0
    def testUploadArtifactYamlFileBadList(self):
        content = """name: BadList
doc: here's the doc
sources:
- type: GREP
  attributes:
    paths: /etc/blah
    content_regex_list: ["stuff"]
supported_os: [Linux]
"""
        with self.assertRaises(rdf_artifacts.ArtifactDefinitionError):
            artifact.UploadArtifactYamlFile(content)
Exemple #10
0
    def testUploadArtifactYamlFileMissingNamesAttribute(self):
        content = """name: BadGroupMissingNames
doc: broken
sources:
- type: ARTIFACT_GROUP
  attributes:
    - 'One'
    - 'Two'
supported_os: [Linux]
"""

        with self.assertRaises(rdf_artifacts.ArtifactDefinitionError):
            artifact.UploadArtifactYamlFile(content)
Exemple #11
0
    def testCommandArgumentOrderIsPreserved(self):
        content = """name: CommandOrder
doc: here's the doc
sources:
- type: COMMAND
  attributes:
    args: ["-L", "-v", "-n"]
    cmd: /sbin/iptables
supported_os: [Linux]
"""
        artifact.UploadArtifactYamlFile(content)
        artifact_obj = artifact_registry.REGISTRY.GetArtifacts(
            name_list=["CommandOrder"]).pop()
        arglist = artifact_obj.sources[0].attributes.get("args")
        self.assertEqual(arglist, ["-L", "-v", "-n"])

        # Check serialize/deserialize doesn't change order.
        serialized = artifact_obj.SerializeToBytes()
        artifact_obj = rdf_artifacts.Artifact.FromSerializedBytes(serialized)
        arglist = artifact_obj.sources[0].attributes.get("args")
        self.assertEqual(arglist, ["-L", "-v", "-n"])
Exemple #12
0
 def Handle(self, args, token=None):
   artifact.UploadArtifactYamlFile(
       args.artifact, overwrite=True, overwrite_system_artifacts=False)
Exemple #13
0
    def testPsCmdParserValidation(self, registry):
        """Test the PsCmdParser pass Validation() method."""
        test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                           "artifacts", "test_artifacts.json")
        registry.AddFileSource(test_artifacts_file)

        parser = linux_cmd_parser.PsCmdParser

        # Test with no ps cmd artifact.
        parser.Validate()

        # Test with good ps artifacts.
        content_good1 = """name: GoodPsArgs1
doc: "ps with the default/typical non-specified format."
sources:
- type: COMMAND
  attributes:
    cmd: "/bin/ps"
    args: ["-ef"]
supported_os: [Linux]
"""
        content_good2 = """name: GoodPsArgs2
doc: "ps where we specify the format."
sources:
- type: COMMAND
  attributes:
    cmd: "/bin/ps"
    args: ["h", "-ewwo", "pid,ppid,uid,comm,cmd"]
supported_os: [Linux]
"""
        artifact.UploadArtifactYamlFile(content_good1)
        artifact.UploadArtifactYamlFile(content_good2)
        # Add these new artifacts to the supported ones for the parser.
        parser.supported_artifacts.extend(["GoodPsArgs1", "GoodPsArgs2"])
        parser.Validate()

        # Now add a bad ones. This should cause the validator to raise an error.
        content_bad1 = """name: BadPsArgsDuplicateCmd
doc: "ps command with 'cmd' specified more than once."
sources:
- type: COMMAND
  attributes:
    cmd: "/bin/ps"
    args: ["h", "-ewwo", "pid,ppid,uid,cmd,comm,cmd"]
supported_os: [Linux]
"""
        content_bad2 = """name: BadPsArgsCmdNotAtEnd
doc: "ps command with 'cmd' specified, but not at the end."
sources:
- type: COMMAND
  attributes:
    cmd: "/bin/ps"
    args: ["-ewwo", "pid,ppid,uid,cmd,comm"]
supported_os: [Linux]
"""
        artifact.UploadArtifactYamlFile(content_bad1)
        artifact.UploadArtifactYamlFile(content_bad2)
        orig = parser.supported_artifacts
        for bad_artifact in ["BadPsArgsDuplicateCmd", "BadPsArgsCmdNotAtEnd"]:
            with self.assertRaises(lib_parser.ParserDefinitionError):
                # Reset and add the new artifacts to the supported ones for the parser.
                parser.supported_artifacts = list(orig)
                parser.supported_artifacts.append(bad_artifact)
                parser.Validate()
Exemple #14
0
def main(argv):
    """Main."""
    del argv  # Unused.

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

    token = config_updater_util.GetToken()
    grr_config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    grr_config.CONFIG.AddContext(contexts.CONFIG_UPDATER_CONTEXT)

    if flags.FLAGS.subparser_name == "initialize":
        config_lib.ParseConfigCommandLine()
        if flags.FLAGS.noprompt:
            config_updater_util.InitializeNoPrompt(grr_config.CONFIG,
                                                   token=token)
        else:
            config_updater_util.Initialize(grr_config.CONFIG, token=token)
        return

    server_startup.Init()

    try:
        print("Using configuration %s" % grr_config.CONFIG)
    except AttributeError:
        raise RuntimeError("No valid config specified.")

    if flags.FLAGS.subparser_name == "generate_keys":
        try:
            config_updater_util.GenerateKeys(
                grr_config.CONFIG, overwrite_keys=flags.FLAGS.overwrite_keys)
        except RuntimeError as e:
            # GenerateKeys will raise if keys exist and overwrite_keys is not set.
            print("ERROR: %s" % e)
            sys.exit(1)
        grr_config.CONFIG.Write()

    elif flags.FLAGS.subparser_name == "repack_clients":
        upload = not flags.FLAGS.noupload
        repacking.TemplateRepacker().RepackAllTemplates(upload=upload,
                                                        token=token)

    elif flags.FLAGS.subparser_name == "show_user":
        maintenance_utils.ShowUser(flags.FLAGS.username, token=token)

    elif flags.FLAGS.subparser_name == "update_user":
        try:
            maintenance_utils.UpdateUser(flags.FLAGS.username,
                                         flags.FLAGS.password,
                                         flags.FLAGS.add_labels,
                                         flags.FLAGS.delete_labels,
                                         token=token)
        except maintenance_utils.UserError as e:
            print(e)

    elif flags.FLAGS.subparser_name == "delete_user":
        maintenance_utils.DeleteUser(flags.FLAGS.username, token=token)

    elif flags.FLAGS.subparser_name == "add_user":
        labels = []
        if not flags.FLAGS.noadmin:
            labels.append("admin")

        if flags.FLAGS.labels:
            labels.extend(flags.FLAGS.labels)

        try:
            maintenance_utils.AddUser(flags.FLAGS.username,
                                      flags.FLAGS.password,
                                      labels,
                                      token=token)
        except maintenance_utils.UserError as e:
            print(e)

    elif flags.FLAGS.subparser_name == "upload_python":
        python_hack_root_urn = grr_config.CONFIG.Get("Config.python_hack_root")
        content = open(flags.FLAGS.file, "rb").read(1024 * 1024 * 30)
        aff4_path = flags.FLAGS.dest_path
        platform = flags.FLAGS.platform
        if not aff4_path:
            aff4_path = python_hack_root_urn.Add(platform.lower()).Add(
                os.path.basename(flags.FLAGS.file))
        if not str(aff4_path).startswith(str(python_hack_root_urn)):
            raise ValueError("AFF4 path must start with %s." %
                             python_hack_root_urn)
        context = ["Platform:%s" % platform.title(), "Client Context"]
        maintenance_utils.UploadSignedConfigBlob(content,
                                                 aff4_path=aff4_path,
                                                 client_context=context,
                                                 token=token)

    elif flags.FLAGS.subparser_name == "upload_exe":
        content = open(flags.FLAGS.file, "rb").read(1024 * 1024 * 30)
        context = [
            "Platform:%s" % flags.FLAGS.platform.title(), "Client Context"
        ]

        if flags.FLAGS.dest_path:
            dest_path = rdfvalue.RDFURN(flags.FLAGS.dest_path)
        else:
            dest_path = grr_config.CONFIG.Get(
                "Executables.aff4_path",
                context=context).Add(os.path.basename(flags.FLAGS.file))

        # Now upload to the destination.
        maintenance_utils.UploadSignedConfigBlob(content,
                                                 aff4_path=dest_path,
                                                 client_context=context,
                                                 token=token)

        print("Uploaded to %s" % dest_path)

    elif flags.FLAGS.subparser_name == "set_var":
        config = grr_config.CONFIG
        print("Setting %s to %s" % (flags.FLAGS.var, flags.FLAGS.val))
        if flags.FLAGS.val.startswith("["):  # Allow setting of basic lists.
            flags.FLAGS.val = flags.FLAGS.val[1:-1].split(",")
        config.Set(flags.FLAGS.var, flags.FLAGS.val)
        config.Write()

    elif flags.FLAGS.subparser_name == "upload_raw":
        if not flags.FLAGS.dest_path:
            flags.FLAGS.dest_path = aff4.ROOT_URN.Add("config").Add("raw")
        uploaded = config_updater_util.UploadRaw(flags.FLAGS.file,
                                                 flags.FLAGS.dest_path,
                                                 token=token)
        print("Uploaded to %s" % uploaded)

    elif flags.FLAGS.subparser_name == "upload_artifact":
        yaml.load(open(flags.FLAGS.file, "rb"))  # Check it will parse.
        try:
            artifact.UploadArtifactYamlFile(
                open(flags.FLAGS.file, "rb").read(),
                overwrite=flags.FLAGS.overwrite_artifact)
        except rdf_artifacts.ArtifactDefinitionError as e:
            print("Error %s. You may need to set --overwrite_artifact." % e)

    elif flags.FLAGS.subparser_name == "delete_artifacts":
        artifact_list = flags.FLAGS.artifact
        if not artifact_list:
            raise ValueError("No artifact to delete given.")
        artifact_registry.DeleteArtifactsFromDatastore(artifact_list,
                                                       token=token)
        print("Artifacts %s deleted." % artifact_list)

    elif flags.FLAGS.subparser_name == "download_missing_rekall_profiles":
        print("Downloading missing Rekall profiles.")
        s = rekall_profile_server.GRRRekallProfileServer()
        s.GetMissingProfiles()

    elif flags.FLAGS.subparser_name == "set_global_notification":
        notification = aff4_users.GlobalNotification(
            type=flags.FLAGS.type,
            header=flags.FLAGS.header,
            content=flags.FLAGS.content,
            link=flags.FLAGS.link)
        if flags.FLAGS.show_from:
            notification.show_from = rdfvalue.RDFDatetime(
            ).ParseFromHumanReadable(flags.FLAGS.show_from)
        if flags.FLAGS.duration:
            notification.duration = rdfvalue.Duration().ParseFromHumanReadable(
                flags.FLAGS.duration)

        print("Setting global notification.")
        print(notification)

        with aff4.FACTORY.Create(
                aff4_users.GlobalNotificationStorage.DEFAULT_PATH,
                aff4_type=aff4_users.GlobalNotificationStorage,
                mode="rw",
                token=token) as storage:
            storage.AddNotification(notification)
    elif flags.FLAGS.subparser_name == "rotate_server_key":
        print("""
You are about to rotate the server key. Note that:

  - Clients might experience intermittent connection problems after
    the server keys rotated.

  - It's not possible to go back to an earlier key. Clients that see a
    new certificate will remember the cert's serial number and refuse
    to accept any certificate with a smaller serial number from that
    point on.
    """)

        if builtins.input("Continue? [yN]: ").upper() == "Y":
            if flags.FLAGS.keylength:
                keylength = int(flags.FLAGS.keylength)
            else:
                keylength = grr_config.CONFIG["Server.rsa_key_length"]

            maintenance_utils.RotateServerKey(cn=flags.FLAGS.common_name,
                                              keylength=keylength)
Exemple #15
0
def main(argv):
    """Main."""
    del argv  # Unused.

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

    token = config_updater_util.GetToken()
    grr_config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    grr_config.CONFIG.AddContext(contexts.CONFIG_UPDATER_CONTEXT)

    if flags.FLAGS.subparser_name == "initialize":
        config_lib.ParseConfigCommandLine()
        if flags.FLAGS.noprompt:
            config_updater_util.InitializeNoPrompt(grr_config.CONFIG,
                                                   token=token)
        else:
            config_updater_util.Initialize(grr_config.CONFIG, token=token)
        return

    server_startup.Init()

    try:
        print("Using configuration %s" % grr_config.CONFIG)
    except AttributeError:
        raise RuntimeError("No valid config specified.")

    if flags.FLAGS.subparser_name == "generate_keys":
        try:
            config_updater_util.GenerateKeys(
                grr_config.CONFIG, overwrite_keys=flags.FLAGS.overwrite_keys)
        except RuntimeError as e:
            # GenerateKeys will raise if keys exist and overwrite_keys is not set.
            print("ERROR: %s" % e)
            sys.exit(1)
        grr_config.CONFIG.Write()

    elif flags.FLAGS.subparser_name == "repack_clients":
        upload = not flags.FLAGS.noupload
        repacking.TemplateRepacker().RepackAllTemplates(upload=upload,
                                                        token=token)

    elif flags.FLAGS.subparser_name == "show_user":
        if flags.FLAGS.username:
            print(config_updater_util.GetUserSummary(flags.FLAGS.username))
        else:
            print(config_updater_util.GetAllUserSummaries())

    elif flags.FLAGS.subparser_name == "update_user":
        config_updater_util.UpdateUser(flags.FLAGS.username,
                                       password=flags.FLAGS.password,
                                       is_admin=flags.FLAGS.admin)

    elif flags.FLAGS.subparser_name == "delete_user":
        config_updater_util.DeleteUser(flags.FLAGS.username)

    elif flags.FLAGS.subparser_name == "add_user":
        config_updater_util.CreateUser(flags.FLAGS.username,
                                       password=flags.FLAGS.password,
                                       is_admin=flags.FLAGS.admin)

    elif flags.FLAGS.subparser_name == "upload_python":
        config_updater_util.UploadSignedBinary(
            flags.FLAGS.file,
            rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK,
            flags.FLAGS.platform,
            upload_subdirectory=flags.FLAGS.upload_subdirectory,
            token=token)

    elif flags.FLAGS.subparser_name == "upload_exe":
        config_updater_util.UploadSignedBinary(
            flags.FLAGS.file,
            rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE,
            flags.FLAGS.platform,
            upload_subdirectory=flags.FLAGS.upload_subdirectory,
            token=token)

    elif flags.FLAGS.subparser_name == "set_var":
        config = grr_config.CONFIG
        print("Setting %s to %s" % (flags.FLAGS.var, flags.FLAGS.val))
        if flags.FLAGS.val.startswith("["):  # Allow setting of basic lists.
            flags.FLAGS.val = flags.FLAGS.val[1:-1].split(",")
        config.Set(flags.FLAGS.var, flags.FLAGS.val)
        config.Write()

    elif flags.FLAGS.subparser_name == "upload_artifact":
        yaml.load(open(flags.FLAGS.file, "rb"))  # Check it will parse.
        try:
            artifact.UploadArtifactYamlFile(
                open(flags.FLAGS.file, "rb").read(),
                overwrite=flags.FLAGS.overwrite_artifact)
        except rdf_artifacts.ArtifactDefinitionError as e:
            print("Error %s. You may need to set --overwrite_artifact." % e)

    elif flags.FLAGS.subparser_name == "delete_artifacts":
        artifact_list = flags.FLAGS.artifact
        if not artifact_list:
            raise ValueError("No artifact to delete given.")
        artifact_registry.DeleteArtifactsFromDatastore(artifact_list,
                                                       token=token)
        print("Artifacts %s deleted." % artifact_list)

    elif flags.FLAGS.subparser_name == "download_missing_rekall_profiles":
        print("Downloading missing Rekall profiles.")
        s = rekall_profile_server.GRRRekallProfileServer()
        s.GetMissingProfiles()

    elif flags.FLAGS.subparser_name == "rotate_server_key":
        print("""
You are about to rotate the server key. Note that:

  - Clients might experience intermittent connection problems after
    the server keys rotated.

  - It's not possible to go back to an earlier key. Clients that see a
    new certificate will remember the cert's serial number and refuse
    to accept any certificate with a smaller serial number from that
    point on.
    """)

        if builtins.input("Continue? [yN]: ").upper() == "Y":
            if flags.FLAGS.keylength:
                keylength = int(flags.FLAGS.keylength)
            else:
                keylength = grr_config.CONFIG["Server.rsa_key_length"]

            maintenance_utils.RotateServerKey(cn=flags.FLAGS.common_name,
                                              keylength=keylength)
Exemple #16
0
 def _UploadCustomArtifacts(self):
     artifact_registry.REGISTRY.ClearRegistry()
     test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                        "artifacts", "test_artifacts.json")
     with open(test_artifacts_file, "rb") as fd:
         artifact.UploadArtifactYamlFile(fd.read())
Exemple #17
0
 def UploadTestArtifacts(self):
     test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                        "artifacts", "test_artifacts.json")
     with open(test_artifacts_file, "rb") as fd:
         artifact.UploadArtifactYamlFile(fd.read())
Exemple #18
0
 def UploadTestArtifacts(self):
     test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"],
                                        "artifacts", "test_artifacts.json")
     with io.open(test_artifacts_file, mode="r", encoding="utf-8") as fd:
         artifact.UploadArtifactYamlFile(fd.read())
Exemple #19
0
def main(args):
    """Main."""
    grr_config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
    grr_config.CONFIG.AddContext(contexts.CONFIG_UPDATER_CONTEXT)

    if args.subparser_name == "initialize":
        config_lib.ParseConfigCommandLine()
        if args.noprompt:
            config_updater_util.InitializeNoPrompt(
                grr_config.CONFIG,
                external_hostname=args.external_hostname,
                admin_password=args.admin_password,
                mysql_hostname=args.mysql_hostname,
                mysql_port=args.mysql_port,
                mysql_username=args.mysql_username,
                mysql_password=args.mysql_password,
                mysql_db=args.mysql_db,
                mysql_client_key_path=args.mysql_client_key_path,
                mysql_client_cert_path=args.mysql_client_cert_path,
                mysql_ca_cert_path=args.mysql_ca_cert_path,
                redownload_templates=args.redownload_templates,
                repack_templates=not args.norepack_templates)
        else:
            config_updater_util.Initialize(
                grr_config.CONFIG,
                external_hostname=args.external_hostname,
                admin_password=args.admin_password,
                redownload_templates=args.redownload_templates,
                repack_templates=not args.norepack_templates)
        return

    server_startup.Init()

    try:
        print("Using configuration %s" % grr_config.CONFIG)
    except AttributeError:
        raise RuntimeError("No valid config specified.")

    if args.subparser_name == "generate_keys":
        try:
            config_updater_keys_util.GenerateKeys(
                grr_config.CONFIG, overwrite_keys=args.overwrite_keys)
        except RuntimeError as e:
            # GenerateKeys will raise if keys exist and overwrite_keys is not set.
            print("ERROR: %s" % e)
            sys.exit(1)
        grr_config.CONFIG.Write()

    elif args.subparser_name == "repack_clients":
        upload = not args.noupload
        repacking.TemplateRepacker().RepackAllTemplates(upload=upload)

    elif args.subparser_name == "show_user":
        if args.username:
            print(config_updater_util.GetUserSummary(args.username))
        else:
            print(config_updater_util.GetAllUserSummaries())

    elif args.subparser_name == "update_user":
        config_updater_util.UpdateUser(args.username,
                                       password=args.password,
                                       is_admin=args.admin)

    elif args.subparser_name == "delete_user":
        config_updater_util.DeleteUser(args.username)

    elif args.subparser_name == "add_user":
        config_updater_util.CreateUser(args.username,
                                       password=args.password,
                                       is_admin=args.admin)

    elif args.subparser_name == "upload_python":
        config_updater_util.UploadSignedBinary(
            args.file,
            rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK,
            args.platform,
            upload_subdirectory=args.upload_subdirectory)

    elif args.subparser_name == "upload_exe":
        config_updater_util.UploadSignedBinary(
            args.file,
            rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE,
            args.platform,
            upload_subdirectory=args.upload_subdirectory)

    elif args.subparser_name == "set_var":
        var = args.var
        val = args.val

        config = grr_config.CONFIG
        print("Setting %s to %s" % (var, val))
        if val.startswith("["):  # Allow setting of basic lists.
            val = val[1:-1].split(",")
        config.Set(var, val)
        config.Write()

    elif args.subparser_name == "switch_datastore":
        config_updater_util.SwitchToRelDB(grr_config.CONFIG)
        grr_config.CONFIG.Write()

    elif args.subparser_name == "upload_artifact":
        with io.open(args.file, "r") as filedesc:
            source = filedesc.read()
        try:
            artifact.UploadArtifactYamlFile(source,
                                            overwrite=args.overwrite_artifact)
        except rdf_artifacts.ArtifactDefinitionError as e:
            print("Error %s. You may need to set --overwrite_artifact." % e)

    elif args.subparser_name == "delete_artifacts":
        artifact_list = args.artifact
        if not artifact_list:
            raise ValueError("No artifact to delete given.")
        artifact_registry.DeleteArtifactsFromDatastore(artifact_list)
        print("Artifacts %s deleted." % artifact_list)

    elif args.subparser_name == "rotate_server_key":
        print("""
You are about to rotate the server key. Note that:

  - Clients might experience intermittent connection problems after
    the server keys rotated.

  - It's not possible to go back to an earlier key. Clients that see a
    new certificate will remember the cert's serial number and refuse
    to accept any certificate with a smaller serial number from that
    point on.
    """)

        if input("Continue? [yN]: ").upper() == "Y":
            if args.keylength:
                keylength = int(args.keylength)
            else:
                keylength = grr_config.CONFIG["Server.rsa_key_length"]

            maintenance_utils.RotateServerKey(cn=args.common_name,
                                              keylength=keylength)