コード例 #1
0
    def setUp(self):
        super().setUp()

        config_overrider = test_lib.ConfigOverrider({
            "AdminUI.firebase_auth_domain":
            "foo-bar.firebaseapp.com",
            "API.DefaultRouter":
            "DisabledApiCallRouter"
        })
        config_overrider.Start()
        self.addCleanup(config_overrider.Stop)

        self.manager = webauth.FirebaseWebAuthManager()
        self.success_response = http_response.HttpResponse("foobar")

        self.checked_request = None
コード例 #2
0
    def _HandleHomepageV2(self, request):
        """Renders GRR home page for the next-get UI (v2)."""

        del request  # Unused.

        context = {
            "is_development": contexts.DEBUG_CONTEXT in config.CONFIG.context,
            "is_test": contexts.TEST_CONTEXT in config.CONFIG.context,
        }

        env = jinja2.Environment(loader=jinja2.FileSystemLoader(
            config.CONFIG["AdminUI.template_root"]),
                                 autoescape=True)
        template = env.get_template("base-v2.html")
        response = http_response.HttpResponse(template.render(context),
                                              mimetype="text/html")

        return response
コード例 #3
0
    def testLogHttpAdminUIAccess(self):
        request = wsgiapp.HttpRequest({
            "wsgi.url_scheme": "http",
            "SERVER_NAME": "foo.bar",
            "SERVER_PORT": "1234"
        })
        request.user = "******"

        response = http_response.HttpResponse(
            status=202,
            headers={"X-API-Method": "TestMethod"},
            context=api_call_context.ApiCallContext(
                username=request.user,
                approval=acl_test_lib.BuildClientApprovalRequest(
                    reason="foo/test1234", requestor_username=request.user)))

        self.l.LogHttpAdminUIAccess(request, response)
        self.assertIn("foo/test1234", self.log)
コード例 #4
0
    def _HandleHomepage(self, request):
        """Renders GRR home page by rendering base.html Jinja template."""

        _ = request

        env = jinja2.Environment(loader=jinja2.FileSystemLoader(
            config.CONFIG["AdminUI.template_root"]),
                                 autoescape=True)

        create_time = psutil.Process(os.getpid()).create_time()
        template_context = {
            "heading":
            config.CONFIG["AdminUI.heading"],
            "report_url":
            config.CONFIG["AdminUI.report_url"],
            "help_url":
            config.CONFIG["AdminUI.help_url"],
            "timestamp":
            "%.2f" % create_time,
            "use_precompiled_js":
            config.CONFIG["AdminUI.use_precompiled_js"],
            # Used in conjunction with FirebaseWebAuthManager.
            "firebase_api_key":
            config.CONFIG["AdminUI.firebase_api_key"],
            "firebase_auth_domain":
            config.CONFIG["AdminUI.firebase_auth_domain"],
            "firebase_auth_provider":
            config.CONFIG["AdminUI.firebase_auth_provider"],
            "grr_version":
            config.CONFIG["Source.version_string"]
        }
        template = env.get_template("base.html")
        response = http_response.HttpResponse(
            template.render(template_context), mimetype="text/html")

        # For a redirect-based Firebase authentication scheme we won't have any
        # user information at this point - therefore checking if the user is
        # present.
        try:
            StoreCSRFCookie(request.user, response)
        except RequestHasNoUser:
            pass

        return response
コード例 #5
0
  def _BuildResponse(self,
                     status,
                     rendered_data,
                     method_name=None,
                     headers=None,
                     content_length=None,
                     context=None,
                     no_audit_log=False):
    """Builds HttpResponse object from rendered data and HTTP status."""

    # To avoid IE content sniffing problems, escape the tags. Otherwise somebody
    # may send a link with malicious payload that will be opened in IE (which
    # does content sniffing and doesn't respect Content-Disposition header) and
    # IE will treat the document as html and execute arbitrary JS that was
    # passed with the payload.
    str_data = json.Dump(
        rendered_data, encoder=JSONEncoderWithRDFPrimitivesSupport)
    # XSSI protection and tags escaping
    rendered_str = ")]}'\n" + str_data.replace("<", r"\u003c").replace(
        ">", r"\u003e")

    response = http_response.HttpResponse(
        rendered_str,
        status=status,
        content_type="application/json; charset=utf-8",
        context=context)
    response.headers[
        "Content-Disposition"] = "attachment; filename=response.json"
    response.headers["X-Content-Type-Options"] = "nosniff"

    if method_name:
      response.headers["X-API-Method"] = method_name
    if no_audit_log:
      response.headers["X-No-Log"] = "True"
    if context:
      response.headers["X-API-User"] = context.username

    for key, value in (headers or {}).items():
      response.headers[key] = value

    if content_length is not None:
      response.content_length = content_length

    return response
コード例 #6
0
    def _RedirectToRemoteHelp(self, path):
        """Redirect to GitHub-hosted documentation."""
        allowed_chars = set(string.ascii_letters + string.digits + "._-/")
        if not set(path) <= allowed_chars:
            raise RuntimeError("Unusual chars in path %r - "
                               "possible exploit attempt." % path)

        target_path = os.path.join(config.CONFIG["AdminUI.docs_location"],
                                   path)

        # We have to redirect via JavaScript to have access to and to preserve the
        # URL hash. We don't know the hash part of the url on the server.
        return http_response.HttpResponse("""
<script>
var friendly_hash = window.location.hash;
window.location = '%s' + friendly_hash;
</script>
""" % target_path,
                                          mimetype="text/html")
コード例 #7
0
ファイル: webauth.py プロジェクト: jaegeral/grr
    def SecurityCheck(self, func, request, *args, **kwargs):
        """Wrapping function."""
        request.user = u""

        authorized = False
        try:
            auth_type, authorization = request.headers.get(
                "Authorization", " ").split(" ", 1)

            if auth_type == "Basic":
                authorization_string = base64.b64decode(authorization).decode(
                    "utf-8")
                user, password = authorization_string.split(":", 1)

                try:
                    user_obj = data_store.REL_DB.ReadGRRUser(user)
                    if user_obj.password.CheckPassword(password):
                        authorized = True

                        # The password is ok - update the user
                        request.user = user

                except db.UnknownGRRUserError:
                    pass

        except access_control.UnauthorizedAccess as e:
            logging.warning("UnauthorizedAccess: %s for %s", e, request)
        except (IndexError, KeyError, IOError):
            pass

        if not authorized:
            result = http_response.HttpResponse("Unauthorized", status=401)
            result.headers["WWW-Authenticate"] = "Basic realm='Secure Area'"
            return result

        # Modify this to implement additional checking (e.g. enforce SSL).
        return func(request, *args, **kwargs)
コード例 #8
0
        def Handler(request, *args, **kwargs):
            del args, kwargs  # Unused.

            self.assertEqual(request.user, user)
            return http_response.HttpResponse(b"foobar", status=200)
コード例 #9
0
        def Handler(request, *args, **kwargs):
            del args, kwargs  # Unused.

            self.assertEqual(request.user, "temp")
            return http_response.HttpResponse("success", status=200)
コード例 #10
0
        def Handler(request, *args, **kwargs):
            del request, args, kwargs  # Unused.

            return http_response.HttpResponse("foobar", status=200)
コード例 #11
0
    def setUp(self):
        super().setUp()

        self.manager = webauth.RemoteUserWebAuthManager()
        self.success_response = http_response.HttpResponse("foobar")
コード例 #12
0
ファイル: webauth.py プロジェクト: jaegeral/grr
 def AuthError(self, message):
     return http_response.HttpResponse(message, status=403)