Ejemplo n.º 1
0
    def test_security_check(self, password="******"):
        login_url = reverse("djangocg.contrib.auth.views.login")

        # Those URLs should not pass the security check
        for bad_url in ("http://example.com", "https://example.com", "ftp://exampel.com", "//example.com"):

            nasty_url = "%(url)s?%(next)s=%(bad_url)s" % {
                "url": login_url,
                "next": REDIRECT_FIELD_NAME,
                "bad_url": urlquote(bad_url),
            }
            response = self.client.post(nasty_url, {"username": "******", "password": password})
            self.assertEqual(response.status_code, 302)
            self.assertFalse(bad_url in response["Location"], "%s should be blocked" % bad_url)

        # These URLs *should* still pass the security check
        for good_url in (
            "/view/?param=http://example.com",
            "/view/?param=https://example.com",
            "/view?param=ftp://exampel.com",
            "view/?param=//example.com",
            "https:///",
            "//testserver/",
            "/url%20with%20spaces/",
        ):  # see ticket #12534
            safe_url = "%(url)s?%(next)s=%(good_url)s" % {
                "url": login_url,
                "next": REDIRECT_FIELD_NAME,
                "good_url": urlquote(good_url),
            }
            response = self.client.post(safe_url, {"username": "******", "password": password})
            self.assertEqual(response.status_code, 302)
            self.assertTrue(good_url in response["Location"], "%s should be allowed" % good_url)
Ejemplo n.º 2
0
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s', request.path,
                        extra={
                            'status_code': 403,
                            'request': request
                        }
                    )
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0] and
                not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
                    urlresolvers.is_valid_path("%s/" % request.path_info, urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s%s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.is_secure() and 'https' or 'http',
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            newurl += '?' + request.META['QUERY_STRING']
        return http.HttpResponsePermanentRedirect(newurl)
Ejemplo n.º 3
0
 def test_urlquote(self):
     self.assertEqual(urlquote('Paris & Orl\xe9ans'),
         'Paris%20%26%20Orl%C3%A9ans')
     self.assertEqual(urlquote('Paris & Orl\xe9ans', safe="&"),
         'Paris%20&%20Orl%C3%A9ans')
     self.assertEqual(
         urlunquote('Paris%20%26%20Orl%C3%A9ans'),
         'Paris & Orl\xe9ans')
     self.assertEqual(
         urlunquote('Paris%20&%20Orl%C3%A9ans'),
         'Paris & Orl\xe9ans')
     self.assertEqual(urlquote_plus('Paris & Orl\xe9ans'),
         'Paris+%26+Orl%C3%A9ans')
     self.assertEqual(urlquote_plus('Paris & Orl\xe9ans', safe="&"),
         'Paris+&+Orl%C3%A9ans')
     self.assertEqual(
         urlunquote_plus('Paris+%26+Orl%C3%A9ans'),
         'Paris & Orl\xe9ans')
     self.assertEqual(
         urlunquote_plus('Paris+&+Orl%C3%A9ans'),
         'Paris & Orl\xe9ans')
Ejemplo n.º 4
0
def urlencode(value, safe=None):
    """
    Escapes a value for use in a URL.

    Takes an optional ``safe`` parameter used to determine the characters which
    should not be escaped by Django's ``urlquote`` method. If not provided, the
    default safe characters will be used (but an empty string can be provided
    when *all* characters should be escaped).
    """
    kwargs = {}
    if safe is not None:
        kwargs['safe'] = safe
    return urlquote(value, **kwargs)
Ejemplo n.º 5
0
 def render(self, context):
     try:
         expire_time = self.expire_time_var.resolve(context)
     except VariableDoesNotExist:
         raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var)
     try:
         expire_time = int(expire_time)
     except (ValueError, TypeError):
         raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
     # Build a key for this fragment and all vary-on's.
     key = ':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])
     args = hashlib.md5(force_bytes(key))
     cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())
     value = cache.get(cache_key)
     if value is None:
         value = self.nodelist.render(context)
         cache.set(cache_key, value, expire_time)
     return value
Ejemplo n.º 6
0
 def get_absolute_url(self):
     return "/users/%s/" % urlquote(self.name)
Ejemplo n.º 7
0
 def urls(self, plugin_name, easy_instance_field):
     if easy_instance_field.field in self.field_dict(easy_instance_field.model.model).values():
         return ['%s%s/%s/%s/' % (
             easy_instance_field.model.url(),
             plugin_name, easy_instance_field.field.name,
             urlquote(easy_instance_field.raw_value, safe=''))]