def testEmailClientApprovalRequestLinkLeadsToACorrectPage(self): with self.ACLChecksDisabled(): client_id = self.SetupClients(1)[0] messages_sent = [] def SendEmailStub(unused_from_user, unused_to_user, unused_subject, message, **unused_kwargs): messages_sent.append(message) # Request client approval, it will trigger an email message. with utils.Stubber(email_alerts, "SendEmail", SendEmailStub): flow.GRRFlow.StartFlow( client_id=client_id, flow_name="RequestClientApprovalFlow", reason="Please please let me", subject_urn=client_id, approver="test", token=rdfvalue.ACLToken(username="******", reason="test")) self.assertEqual(len(messages_sent), 1) # Extract link from the message text and open it. m = re.search(r"href='(.+?)'", messages_sent[0], re.MULTILINE) link = urlparse.urlparse(m.group(1)) self.Open(link.path + "?" + link.query + "#" + link.fragment) # Check that requestor's username and reason are correctly displayed. self.WaitUntil(self.IsTextPresent, "iwantapproval") self.WaitUntil(self.IsTextPresent, "Please please let me") # Check that host information is displayed. self.WaitUntil(self.IsTextPresent, str(client_id)) self.WaitUntil(self.IsTextPresent, "HOSTNAME") self.WaitUntil(self.IsTextPresent, "MAC_ADDRESS")
def SecurityCheck(self, func, request, *args, **kwargs): """A decorator applied to protected web handlers.""" request.event_id = "1" request.user = self.username request.token = rdfvalue.ACLToken(username="******", reason="Just a test") return func(request, *args, **kwargs)
def setUp(self): super(HashFileStoreExportPluginTest, self).setUp() client_ids = self.SetupClients(1) self.client_id = client_ids[0] data_store.default_token = rdfvalue.ACLToken(username="******", reason="reason")
def setUp(self): super(CollectionExportPluginTest, self).setUp() client_ids = self.SetupClients(1) self.client_id = client_ids[0] self.out = self.client_id.Add("fs/os") data_store.default_token = rdfvalue.ACLToken(username="******", reason="reason")
def ApprovalCreateRaw(aff4_path, reason="", expire_in=60 * 60 * 24 * 7, token=None, approval_type="ClientApproval"): """Creates an approval with raw access. This method requires raw datastore access to manipulate approvals directly. This currently doesn't work for hunt or cron approvals, because they check that each approver has the admin label. Since the fake users don't exist the check fails. Args: aff4_path: The aff4_path or client id the approval should be created for. reason: The reason to put in the token. expire_in: Expiry in seconds to use in the token. token: The token that will be used. If this is specified reason and expiry are ignored. approval_type: The type of the approval to create. Returns: The token. Raises: RuntimeError: On bad token. """ if approval_type == "ClientApproval": urn = rdfvalue.ClientURN(aff4_path) else: urn = rdfvalue.RDFURN(aff4_path) if not token: expiry = time.time() + expire_in token = rdfvalue.ACLToken(reason=reason, expiry=expiry) if not token.reason: raise RuntimeError("Cannot create approval with empty reason") if not token.username: token.username = getpass.getuser() approval_urn = flow.GRRFlow.RequestApprovalWithReasonFlow.ApprovalUrnBuilder( urn.Path(), token.username, token.reason) super_token = access_control.ACLToken(username="******") super_token.supervisor = True approval_request = aff4.FACTORY.Create(approval_urn, approval_type, mode="rw", token=super_token) # Add approvals indicating they were approved by fake "raw" mode users. approval_request.AddAttribute( approval_request.Schema.APPROVER("%s1-raw" % token.username)) approval_request.AddAttribute( approval_request.Schema.APPROVER("%s-raw2" % token.username)) approval_request.Close(sync=True)
def setUp(self): super(FileExportPluginTest, self).setUp() client_ids = self.SetupClients(1) self.client_id = client_ids[0] self.out = self.client_id.Add("fs/os") data_store.default_token = rdfvalue.ACLToken(username="******", reason="reason") self.GrantClientApproval(self.client_id, token=data_store.default_token)
def testSetsSettingsForUserCorrespondingToToken(self): settings = rdfvalue.GUISettings(mode="ADVANCED", canary_mode=True, docs_location="REMOTE") # Render the request - effectively applying the settings for user "foo". result = self.renderer.Render(settings, token=rdfvalue.ACLToken(username="******")) self.assertEqual(result["status"], "OK") # Check that settings for user "foo" were applied. fd = aff4.FACTORY.Open("aff4:/users/foo", token=self.token) self.assertEqual(fd.Get(fd.Schema.GUI_SETTINGS), settings)
def main(unused_argv): """Main.""" config_lib.CONFIG.AddContext( "Commandline Context", "Context applied for all command line tools") startup.Init() data_store.default_token = rdfvalue.ACLToken(username="******", reason="export") # If subcommand was specified by the user in the command line, # corresponding subparser should have initialized "func" argument # with a corresponding export plugin's Run() function. flags.FLAGS.func(flags.FLAGS)
def main(unused_argv): """Main.""" banner = ("\nWelcome to the GRR console\n" "Type help<enter> to get help\n\n") config_lib.CONFIG.AddContext("Commandline Context") config_lib.CONFIG.AddContext( "Console Context", "Context applied when running the console binary.") startup.Init() # To make the console easier to use, we make a default token which will be # used in StartFlow operations. data_store.default_token = rdfvalue.ACLToken(username=getpass.getuser(), reason=flags.FLAGS.reason) locals_vars = { "hilfe": Help, "help": Help, "__name__": "GRR Console", "l": Lister, "o": aff4.FACTORY.Open, # Bring some symbols from other modules into the console's # namespace. "StartFlowAndWait": flow_utils.StartFlowAndWait, "StartFlowAndWorker": debugging.StartFlowAndWorker, "RunEndToEndTests": end_to_end_tests.RunEndToEndTests, } 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) execfile(flags.FLAGS.command_file) 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)
def testRendersSettingsForUserCorrespondingToToken(self): with aff4.FACTORY.Create(aff4.ROOT_URN.Add("users").Add("foo"), aff4_type="GRRUser", mode="w", token=self.token) as user_fd: user_fd.Set( user_fd.Schema.GUI_SETTINGS, rdfvalue.GUISettings(mode="ADVANCED", canary_mode=True, docs_location="REMOTE")) result = self.renderer.Render(None, token=rdfvalue.ACLToken(username="******")) self.assertEqual(result["value"]["mode"]["value"], "ADVANCED") self.assertEqual(result["value"]["canary_mode"]["value"], True) self.assertEqual(result["value"]["docs_location"]["value"], "REMOTE")
def SecurityCheck(self, func, request, *args, **kwargs): """Wrapping function.""" event_id = log.LOGGER.GetNewEventId() # Modify request adding an event_id attribute to track the event request.event_id = event_id request.user = "" authorized = False try: auth_type, authorization = request.META.get( "HTTP_AUTHORIZATION", " ").split(" ", 1) if auth_type == "Basic": user, password = authorization.decode("base64").split(":", 1) token = rdfvalue.ACLToken(username=user) fd = aff4.FACTORY.Open("aff4:/users/%s" % user, aff4_type="GRRUser", token=token) crypted_password = fd.Get(fd.Schema.PASSWORD) if crypted_password and crypted_password.CheckPassword(password): authorized = True # The password is ok - update the user request.user = user except (IndexError, KeyError, IOError): pass if not authorized: result = http.HttpResponse("Unauthorized", status=401) result["WWW-Authenticate"] = "Basic realm='Secure Area'" return result # Modify this to implement additional checking (e.g. enforce SSL). response = func(request, *args, **kwargs) return response
def GetToken(): # Extend for user authorization return rdfvalue.ACLToken(username="******").SetUID()
def main(unused_argv): config_lib.CONFIG.AddContext("Commandline Context", "Context applied for all command line tools") startup.Init() if fuse is None: logging.critical("""Could not start! fusepy must be installed to run fuse_mount.py! Try: sudo pip install fusepy""") sys.exit(1) if not flags.FLAGS.mountpoint: Usage() sys.exit(1) # We multiple inherit from GRRFuse and fuse.Operations. In the # case that fuse is present, we run the actual FUSE layer, since we have # fuse.Operations. In the case that fuse is not present, we have already # exited by now if we were run from the command line, and if we were not run # from the command line, we've been imported, and we run the tests using a # mock fuse. class FuseOperation(GRRFuse, fuse.Operations): pass root = flags.FLAGS.aff4path username = flags.FLAGS.username or getpass.getuser() token = rdfvalue.ACLToken(username=username, reason=flags.FLAGS.reason or "fusemount") # If we're exporting a path inside a client, check to see if we have access to # that client and get the appropriate token. client_id = client.GetClientURNFromPath(root) if client_id is not None: token = security.Approval.GetApprovalForObject(client_id, token=token, username=username) data_store.default_token = token logging.info("fuse_mount.py is mounting %s at %s....", root, flags.FLAGS.mountpoint) refresh_policy = flags.FLAGS.refresh_policy if refresh_policy == "always": max_age_before_refresh = datetime.timedelta(0) elif refresh_policy == "never": # Set the max age to be the maximum possible time difference. max_age_before_refresh = datetime.timedelta.max elif refresh_policy == "if_older_than_max_age": max_age_before_refresh = datetime.timedelta( seconds=flags.FLAGS.max_age_before_refresh) else: # Otherwise, a flag outside the enum was given and the flag validator threw # an execption. pass fuse_operation = FuseOperation( root=root, token=token, max_age_before_refresh=max_age_before_refresh, ignore_cache=flags.FLAGS.ignore_cache, force_sparse_image=flags.FLAGS.force_sparse_image, sparse_image_threshold=flags.FLAGS.sparse_image_threshold, timeout=flags.FLAGS.timeout) fuse.FUSE(fuse_operation, flags.FLAGS.mountpoint, foreground=not flags.FLAGS.background)