Python django.core.exceptions.DisallowedHost() Examples

The following are 8 code examples of django.core.exceptions.DisallowedHost(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.exceptions , or try the search function .
Example #1
Source File: request.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def get_host(self):
        """Return the HTTP host using the environment or request headers."""
        host = self._get_raw_host()

        # There is no hostname validation when DEBUG=True
        if settings.DEBUG:
            return host

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, settings.ALLOWED_HOSTS):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_host_validation_in_debug_mode(self):
        """
        If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
        allowed.
        """
        valid_hosts = ['localhost', '127.0.0.1', '[::1]']
        for host in valid_hosts:
            request = HttpRequest()
            request.META = {'HTTP_HOST': host}
            self.assertEqual(request.get_host(), host)

        # Other hostnames raise a DisallowedHost.
        with self.assertRaises(DisallowedHost):
            request = HttpRequest()
            request.META = {'HTTP_HOST': 'example.com'}
            request.get_host() 
Example #3
Source File: request.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_host(self):
        """Returns the HTTP host using the environment or request headers."""
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and (
                'HTTP_X_FORWARDED_HOST' in self.META):
            host = self.META['HTTP_X_FORWARDED_HOST']
        elif 'HTTP_HOST' in self.META:
            host = self.META['HTTP_HOST']
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = self.META['SERVER_NAME']
            server_port = str(self.META['SERVER_PORT'])
            if server_port != ('443' if self.is_secure() else '80'):
                host = '%s:%s' % (host, server_port)

        # There is no hostname validation when DEBUG=True
        if settings.DEBUG:
            return host

        domain, port = split_domain_port(host)
        if domain and validate_host(domain, settings.ALLOWED_HOSTS):
            return host
        else:
            msg = "Invalid HTTP_HOST header: %r." % host
            if domain:
                msg += " You may need to add %r to ALLOWED_HOSTS." % domain
            else:
                msg += " The domain name provided is not valid according to RFC 1034/1035."
            raise DisallowedHost(msg) 
Example #4
Source File: middleware.py    From django-user-activity-log with MIT License 5 votes vote down vote up
def process_response(self, request, response):
        try:
            self._write_log(request, response, getattr(request, 'saved_body', ''))
        except DisallowedHost:
            return HttpResponseForbidden()
        return response 
Example #5
Source File: middleware.py    From django-user-activity-log with MIT License 5 votes vote down vote up
def process_response(self, request, response):
        try:
            self._write_log(request, response, getattr(request, 'saved_body', ''))
        except DisallowedHost:
            return HttpResponseForbidden()
        return response 
Example #6
Source File: middleware.py    From zulip with Apache License 2.0 5 votes vote down vote up
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
        if getattr(response, "asynchronous", False):
            # This special Tornado "asynchronous" response is
            # discarded after going through this code path as Tornado
            # intends to block, so we stop here to avoid unnecessary work.
            return response

        try:
            request.get_host()
        except DisallowedHost:
            # If we get a DisallowedHost exception trying to access
            # the host, (1) the request is failed anyway and so the
            # below code will do nothing, and (2) the below will
            # trigger a recursive exception, breaking things, so we
            # just return here.
            return response

        if (not request.path.startswith("/static/") and not request.path.startswith("/api/") and
                not request.path.startswith("/json/")):
            subdomain = get_subdomain(request)
            if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
                try:
                    get_realm(subdomain)
                except Realm.DoesNotExist:
                    return render(request, "zerver/invalid_realm.html", status=404)
        return response 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_host_suggestion_of_allowed_host(self):
        """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
        msg_invalid_host = "Invalid HTTP_HOST header: %r."
        msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
        msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035"

        for host in [  # Valid-looking hosts
            'example.com',
            '12.34.56.78',
            '[2001:19f0:feee::dead:beef:cafe]',
            'xn--4ca9at.com',  # Punycode for öäü.com
        ]:
            request = HttpRequest()
            request.META = {'HTTP_HOST': host}
            with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)):
                request.get_host()

        for domain, port in [  # Valid-looking hosts with a port number
            ('example.com', 80),
            ('12.34.56.78', 443),
            ('[2001:19f0:feee::dead:beef:cafe]', 8080),
        ]:
            host = '%s:%s' % (domain, port)
            request = HttpRequest()
            request.META = {'HTTP_HOST': host}
            with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)):
                request.get_host()

        for host in self.poisoned_hosts:
            request = HttpRequest()
            request.META = {'HTTP_HOST': host}
            with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host):
                request.get_host()

        request = HttpRequest()
        request.META = {'HTTP_HOST': "invalid_hostname.com"}
        with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"):
            request.get_host() 
Example #8
Source File: client.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_data_from_request(self, request, event_type):
        result = {
            "env": dict(get_environ(request.META)),
            "method": request.method,
            "socket": {"remote_address": request.META.get("REMOTE_ADDR"), "encrypted": request.is_secure()},
            "cookies": dict(request.COOKIES),
        }
        if self.config.capture_headers:
            request_headers = dict(get_headers(request.META))

            for key, value in request_headers.items():
                if isinstance(value, (int, float)):
                    request_headers[key] = str(value)

            result["headers"] = request_headers

        if request.method in constants.HTTP_WITH_BODY:
            capture_body = self.config.capture_body in ("all", event_type)
            if not capture_body:
                result["body"] = "[REDACTED]"
            else:
                content_type = request.META.get("CONTENT_TYPE")
                if content_type == "application/x-www-form-urlencoded":
                    data = compat.multidict_to_dict(request.POST)
                elif content_type and content_type.startswith("multipart/form-data"):
                    data = compat.multidict_to_dict(request.POST)
                    if request.FILES:
                        data["_files"] = {field: file.name for field, file in compat.iteritems(request.FILES)}
                else:
                    try:
                        data = request.body
                    except Exception as e:
                        self.logger.debug("Can't capture request body: %s", compat.text_type(e))
                        data = "<unavailable>"
                if data is not None:
                    result["body"] = data

        if hasattr(request, "get_raw_uri"):
            # added in Django 1.9
            url = request.get_raw_uri()
        else:
            try:
                # Requires host to be in ALLOWED_HOSTS, might throw a
                # DisallowedHost exception
                url = request.build_absolute_uri()
            except DisallowedHost:
                # We can't figure out the real URL, so we have to set it to
                # DisallowedHost
                result["url"] = {"full": "DisallowedHost"}
                url = None
        if url:
            result["url"] = get_url_dict(url)
        return result