mid

"""
Cross Site Request Forgery Middleware.

This module provides a middleware that implements protection
against request forgeries from other sites.
"""
from __future__ import unicode_literals

import logging
import re

from django.conf import settings
from django.core.urlresolvers import get_callable
from django.utils.cache import patch_vary_headers
from django.utils.crypto import constant_time_compare, get_random_string
from django.utils.encoding import force_text
from django.utils.http import is_same_domain
from django.utils.six.moves.urllib.parse import urlparse

logger = logging.getLogger(‘django.request‘)

REASON_NO_REFERER = "Referer checking failed - no Referer."
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."

CSRF_KEY_LENGTH = 32

def _get_failure_view():
    """
    Returns the view to be used for CSRF rejections
    """
    return get_callable(settings.CSRF_FAILURE_VIEW)

def _get_new_csrf_key():
    return get_random_string(CSRF_KEY_LENGTH)

def get_token(request):
    """
    Returns the CSRF token required for a POST form. The token is an
    alphanumeric value. A new token is created if one is not already set.

    A side effect of calling this function is to make the csrf_protect
    decorator and the CsrfViewMiddleware add a CSRF cookie and a ‘Vary: Cookie‘
    header to the outgoing response.  For this reason, you may need to use this
    function lazily, as is done by the csrf context processor.
    """
    if "CSRF_COOKIE" not in request.META:
        request.META["CSRF_COOKIE"] = _get_new_csrf_key()
    request.META["CSRF_COOKIE_USED"] = True
    return request.META["CSRF_COOKIE"]

def rotate_token(request):
    """
    Changes the CSRF token in use for a request - should be done on login
    for security purposes.
    """
    request.META.update({
        "CSRF_COOKIE_USED": True,
        "CSRF_COOKIE": _get_new_csrf_key(),
    })

def _sanitize_token(token):
    # Allow only alphanum
    if len(token) > CSRF_KEY_LENGTH:
        return _get_new_csrf_key()
    token = re.sub(‘[^a-zA-Z0-9]+‘, ‘‘, force_text(token))
    if token == "":
        # In case the cookie has been truncated to nothing at some point.
        return _get_new_csrf_key()
    return token

class CsrfViewMiddleware(object):
    """
    Middleware that requires a present and correct csrfmiddlewaretoken
    for POST requests that have a CSRF cookie, and sets an outgoing
    CSRF cookie.

    This middleware should be used in conjunction with the csrf_token template
    tag.
    """
    # The _accept and _reject methods currently only exist for the sake of the
    # requires_csrf_token decorator.
    def _accept(self, request):
        # Avoid checking the request twice by adding a custom attribute to
        # request.  This will be relevant when both decorator and middleware
        # are used.
        request.csrf_processing_done = True
        return None

    def _reject(self, request, reason):
        logger.warning(‘Forbidden (%s): %s‘, reason, request.path,
            extra={
                ‘status_code‘: 403,
                ‘request‘: request,
            }
        )
        return _get_failure_view()(request, reason=reason)

    def process_view(self, request, callback, callback_args, callback_kwargs):

        if getattr(request, ‘csrf_processing_done‘, False):
            return None

        try:
            csrf_token = _sanitize_token(
                request.COOKIES[settings.CSRF_COOKIE_NAME])
            # Use same token next time
            request.META[‘CSRF_COOKIE‘] = csrf_token
        except KeyError:
            csrf_token = None

        # Wait until request.META["CSRF_COOKIE"] has been manipulated before
        # bailing out, so that get_token still works
        if getattr(callback, ‘csrf_exempt‘, False):
            return None

        # Assume that anything not defined as ‘safe‘ by RFC2616 needs protection
        if request.method not in (‘GET‘, ‘HEAD‘, ‘OPTIONS‘, ‘TRACE‘):
            if getattr(request, ‘_dont_enforce_csrf_checks‘, False):
                # Mechanism to turn off CSRF checks for test suite.
                # It comes after the creation of CSRF cookies, so that
                # everything else continues to work exactly the same
                # (e.g. cookies are sent, etc.), but before any
                # branches that call reject().
                return self._accept(request)

            if request.is_secure():
                # Suppose user visits http://example.com/
                # An active network attacker (man-in-the-middle, MITM) sends a
                # POST form that targets https://example.com/detonate-bomb/ and
                # submits it via JavaScript.
                #
                # The attacker will need to provide a CSRF cookie and token, but
                # that‘s no problem for a MITM and the session-independent
                # nonce we‘re using. So the MITM can circumvent the CSRF
                # protection. This is true for any HTTP connection, but anyone
                # using HTTPS expects better! For this reason, for
                # https://example.com/ we need additional protection that treats
                # http://example.com/ as completely untrusted. Under HTTPS,
                # Barth et al. found that the Referer header is missing for
                # same-domain requests in only about 0.2% of cases or less, so
                # we can use strict Referer checking.
                referer = force_text(
                    request.META.get(‘HTTP_REFERER‘),
                    strings_only=True,
                    errors=‘replace‘
                )
                if referer is None:
                    return self._reject(request, REASON_NO_REFERER)

                referer = urlparse(referer)

                # Make sure we have a valid URL for Referer.
                if ‘‘ in (referer.scheme, referer.netloc):
                    return self._reject(request, REASON_MALFORMED_REFERER)

                # Ensure that our Referer is also secure.
                if referer.scheme != ‘https‘:
                    return self._reject(request, REASON_INSECURE_REFERER)

                # If there isn‘t a CSRF_COOKIE_DOMAIN, assume we need an exact
                # match on host:port. If not, obey the cookie rules.
                if settings.CSRF_COOKIE_DOMAIN is None:
                    # request.get_host() includes the port.
                    good_referer = request.get_host()
                else:
                    good_referer = settings.CSRF_COOKIE_DOMAIN
                    server_port = request.get_port()
                    if server_port not in (‘443‘, ‘80‘):
                        good_referer = ‘%s:%s‘ % (good_referer, server_port)

                # Here we generate a list of all acceptable HTTP referers,
                # including the current host since that has been validated
                # upstream.
                good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
                good_hosts.append(good_referer)

                if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
                    reason = REASON_BAD_REFERER % referer.geturl()
                    return self._reject(request, reason)

            if csrf_token is None:
                # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
                # and in this way we can avoid all CSRF attacks, including login
                # CSRF.
                return self._reject(request, REASON_NO_CSRF_COOKIE)

            # Check non-cookie token for match.
            request_csrf_token = ""
            if request.method == "POST":
                try:
                    request_csrf_token = request.POST.get(‘csrfmiddlewaretoken‘, ‘‘)
                except IOError:
                    # Handle a broken connection before we‘ve completed reading
                    # the POST data. process_view shouldn‘t raise any
                    # exceptions, so we‘ll ignore and serve the user a 403
                    # (assuming they‘re still listening, which they probably
                    # aren‘t because of the error).
                    pass

            if request_csrf_token == "":
                # Fall back to X-CSRFToken, to make things easier for AJAX,
                # and possible for PUT/DELETE.
                request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, ‘‘)

            if not constant_time_compare(request_csrf_token, csrf_token):
                return self._reject(request, REASON_BAD_TOKEN)

        return self._accept(request)

    def process_response(self, request, response):
        if getattr(response, ‘csrf_processing_done‘, False):
            return response

        if not request.META.get("CSRF_COOKIE_USED", False):
            return response

        # Set the CSRF cookie even if it‘s already set, so we renew
        # the expiry timer.
        response.set_cookie(settings.CSRF_COOKIE_NAME,
                            request.META["CSRF_COOKIE"],
                            max_age=settings.CSRF_COOKIE_AGE,
                            domain=settings.CSRF_COOKIE_DOMAIN,
                            path=settings.CSRF_COOKIE_PATH,
                            secure=settings.CSRF_COOKIE_SECURE,
                            httponly=settings.CSRF_COOKIE_HTTPONLY
                            )
        # Content varies with the CSRF cookie, so set the Vary header.
        patch_vary_headers(response, (‘Cookie‘,))
        response.csrf_processing_done = True
        return response

"""
Cross Site Request Forgery Middleware.

This module provides a middleware that implements protection
against request forgeries from other sites.
"""
from __future__ import unicode_literals

import logging
import re

from django.conf import settings
from django.core.urlresolvers import get_callable
from django.utils.cache import patch_vary_headers
from django.utils.crypto import constant_time_compare, get_random_string
from django.utils.encoding import force_text
from django.utils.http import is_same_domain
from django.utils.six.moves.urllib.parse import urlparse

logger = logging.getLogger(‘django.request‘)

REASON_NO_REFERER = "Referer checking failed - no Referer."
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."

CSRF_KEY_LENGTH = 32

def _get_failure_view():
    """
    Returns the view to be used for CSRF rejections
    """
    return get_callable(settings.CSRF_FAILURE_VIEW)

def _get_new_csrf_key():
    return get_random_string(CSRF_KEY_LENGTH)

def get_token(request):
    """
    Returns the CSRF token required for a POST form. The token is an
    alphanumeric value. A new token is created if one is not already set.

    A side effect of calling this function is to make the csrf_protect
    decorator and the CsrfViewMiddleware add a CSRF cookie and a ‘Vary: Cookie‘
    header to the outgoing response.  For this reason, you may need to use this
    function lazily, as is done by the csrf context processor.
    """
    if "CSRF_COOKIE" not in request.META:
        request.META["CSRF_COOKIE"] = _get_new_csrf_key()
    request.META["CSRF_COOKIE_USED"] = True
    return request.META["CSRF_COOKIE"]

def rotate_token(request):
    """
    Changes the CSRF token in use for a request - should be done on login
    for security purposes.
    """
    request.META.update({
        "CSRF_COOKIE_USED": True,
        "CSRF_COOKIE": _get_new_csrf_key(),
    })

def _sanitize_token(token):
    # Allow only alphanum
    if len(token) > CSRF_KEY_LENGTH:
        return _get_new_csrf_key()
    token = re.sub(‘[^a-zA-Z0-9]+‘, ‘‘, force_text(token))
    if token == "":
        # In case the cookie has been truncated to nothing at some point.
        return _get_new_csrf_key()
    return token

class CsrfViewMiddleware(object):
    """
    Middleware that requires a present and correct csrfmiddlewaretoken
    for POST requests that have a CSRF cookie, and sets an outgoing
    CSRF cookie.

    This middleware should be used in conjunction with the csrf_token template
    tag.
    """
    # The _accept and _reject methods currently only exist for the sake of the
    # requires_csrf_token decorator.
    def _accept(self, request):
        # Avoid checking the request twice by adding a custom attribute to
        # request.  This will be relevant when both decorator and middleware
        # are used.
        request.csrf_processing_done = True
        return None

    def _reject(self, request, reason):
        logger.warning(‘Forbidden (%s): %s‘, reason, request.path,
            extra={
                ‘status_code‘: 403,
                ‘request‘: request,
            }
        )
        return _get_failure_view()(request, reason=reason)

    def process_view(self, request, callback, callback_args, callback_kwargs):

        if getattr(request, ‘csrf_processing_done‘, False):
            return None

        try:
            csrf_token = _sanitize_token(
                request.COOKIES[settings.CSRF_COOKIE_NAME])
            # Use same token next time
            request.META[‘CSRF_COOKIE‘] = csrf_token
        except KeyError:
            csrf_token = None

        # Wait until request.META["CSRF_COOKIE"] has been manipulated before
        # bailing out, so that get_token still works
        if getattr(callback, ‘csrf_exempt‘, False):
            return None

        # Assume that anything not defined as ‘safe‘ by RFC2616 needs protection
        if request.method not in (‘GET‘, ‘HEAD‘, ‘OPTIONS‘, ‘TRACE‘):
            if getattr(request, ‘_dont_enforce_csrf_checks‘, False):
                # Mechanism to turn off CSRF checks for test suite.
                # It comes after the creation of CSRF cookies, so that
                # everything else continues to work exactly the same
                # (e.g. cookies are sent, etc.), but before any
                # branches that call reject().
                return self._accept(request)

            if request.is_secure():
                # Suppose user visits http://example.com/
                # An active network attacker (man-in-the-middle, MITM) sends a
                # POST form that targets https://example.com/detonate-bomb/ and
                # submits it via JavaScript.
                #
                # The attacker will need to provide a CSRF cookie and token, but
                # that‘s no problem for a MITM and the session-independent
                # nonce we‘re using. So the MITM can circumvent the CSRF
                # protection. This is true for any HTTP connection, but anyone
                # using HTTPS expects better! For this reason, for
                # https://example.com/ we need additional protection that treats
                # http://example.com/ as completely untrusted. Under HTTPS,
                # Barth et al. found that the Referer header is missing for
                # same-domain requests in only about 0.2% of cases or less, so
                # we can use strict Referer checking.
                referer = force_text(
                    request.META.get(‘HTTP_REFERER‘),
                    strings_only=True,
                    errors=‘replace‘
                )
                if referer is None:
                    return self._reject(request, REASON_NO_REFERER)

                referer = urlparse(referer)

                # Make sure we have a valid URL for Referer.
                if ‘‘ in (referer.scheme, referer.netloc):
                    return self._reject(request, REASON_MALFORMED_REFERER)

                # Ensure that our Referer is also secure.
                if referer.scheme != ‘https‘:
                    return self._reject(request, REASON_INSECURE_REFERER)

                # If there isn‘t a CSRF_COOKIE_DOMAIN, assume we need an exact
                # match on host:port. If not, obey the cookie rules.
                if settings.CSRF_COOKIE_DOMAIN is None:
                    # request.get_host() includes the port.
                    good_referer = request.get_host()
                else:
                    good_referer = settings.CSRF_COOKIE_DOMAIN
                    server_port = request.get_port()
                    if server_port not in (‘443‘, ‘80‘):
                        good_referer = ‘%s:%s‘ % (good_referer, server_port)

                # Here we generate a list of all acceptable HTTP referers,
                # including the current host since that has been validated
                # upstream.
                good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
                good_hosts.append(good_referer)

                if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
                    reason = REASON_BAD_REFERER % referer.geturl()
                    return self._reject(request, reason)

            if csrf_token is None:
                # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
                # and in this way we can avoid all CSRF attacks, including login
                # CSRF.
                return self._reject(request, REASON_NO_CSRF_COOKIE)

            # Check non-cookie token for match.
            request_csrf_token = ""
            if request.method == "POST":
                try:
                    request_csrf_token = request.POST.get(‘csrfmiddlewaretoken‘, ‘‘)
                except IOError:
                    # Handle a broken connection before we‘ve completed reading
                    # the POST data. process_view shouldn‘t raise any
                    # exceptions, so we‘ll ignore and serve the user a 403
                    # (assuming they‘re still listening, which they probably
                    # aren‘t because of the error).
                    pass

            if request_csrf_token == "":
                # Fall back to X-CSRFToken, to make things easier for AJAX,
                # and possible for PUT/DELETE.
                request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, ‘‘)

            if not constant_time_compare(request_csrf_token, csrf_token):
                return self._reject(request, REASON_BAD_TOKEN)

        return self._accept(request)

    def process_response(self, request, response):
        if getattr(response, ‘csrf_processing_done‘, False):
            return response

        if not request.META.get("CSRF_COOKIE_USED", False):
            return response

        # Set the CSRF cookie even if it‘s already set, so we renew
        # the expiry timer.
        response.set_cookie(settings.CSRF_COOKIE_NAME,
                            request.META["CSRF_COOKIE"],
                            max_age=settings.CSRF_COOKIE_AGE,
                            domain=settings.CSRF_COOKIE_DOMAIN,
                            path=settings.CSRF_COOKIE_PATH,
                            secure=settings.CSRF_COOKIE_SECURE,
                            httponly=settings.CSRF_COOKIE_HTTPONLY
                            )
        # Content varies with the CSRF cookie, so set the Vary header.
        patch_vary_headers(response, (‘Cookie‘,))
        response.csrf_processing_done = True
        return response

  

时间: 2024-12-22 17:07:05

mid的相关文章

35.MID() 函数

MID() 函数 MID() 函数 MID 函数用于从文本字段中提取字符. SQL MID() 语法 SELECT MID(column_name,start[,length]) FROM table_name 参数 描述 column_name 必需.要提取字符的字段. start 必需.规定开始位置(起始值是 1). length 可选.要返回的字符数.如果省略,则 MID() 函数返回剩余文本. SQL MID() 实例 我们拥有下面这个 "Persons" 表: Id Last

微博地址url(id)与mid的相互转换 Java版

原理: 新浪微博的URL都是如:http://weibo.com/2480531040/z8ElgBLeQ这样三部分. 第一部分(绿色部分)为新浪微博的域名,第二部分(红色部分)为博主Uid,第三部分(蓝色)为一串貌似随机的字符串. 如果通过方法能计算出蓝色字串与返回的数组里的对应关系则好解决多了. 首先分组蓝色字串 ,从后往前4个字符一组,得到以下三组字符:z8ElgBLeQ 将它们分别转换成62进制的数值则为 35, 2061702, 8999724  将它们组合起来就是一串 3520617

CString类常用方法----Left(),Mid(),Right() .

CString Left( int nCount ) const;                   //从左边1开始获取前 nCount 个字符 CString Mid( int nFirst ) const;                      //从左边第 nCount+1 个字符开始,获取后面所有的字符 CString Mid( int nFirst, int nCount ) const;    //从左边第 nFirst+1 个字符开始,获取后面  nCount 个字符 CS

EXCEL的IF+MID函数结合找出班级信息

如下图所示,我们编号列,其中第3位第4位代表的所在的班级,01代表的是1班,02代表的是2班,03代表的是3班.我们通过EXCEL函数如何找到对应的班级呢.我们从上边分析知道3,4位代表是班级.所以我们要先找出3,4位,EXCEL中提供了MID函数就是专门查找字符串指定位置的字符进行截取,下边是该函数语法MID(查找的字符串,查找字符串开始的位置,需要字符串个数)我们根据这个可以写出公式MID(C3,3,2),最后返回结果就是01,那么EXCEL函数就解决了第一个问题.找到了代表班级的编号了.下

MID(s,n,len)

MID(s,n,len) 用于获取指定位置的子字符串 mysql> SELECT MID('breakfast',5) AS col1, # 从第5个字符串开始获取 -> MID('breakfast',5,3) AS col2, # 从第5个字符串开始,获取3个 -> MID('breakfast',-5) AS col3, # (倒向)从第5个字符串开始获取 -> MID('breakfast',-5,3) AS col4; # (倒向)从第5个字符串开始获取,获取3个 +--

数据库sql联合查询mid类型的分页数据取不了全部的值错误

USE [Travel]GO/****** Object:  StoredProcedure [dbo].[NoticeGetPagedData]    Script Date: 06/13/2014 20:44:51 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[NoticeGetPagedData]@pageIndex int = 1,--页码@pageSize int =10,--页容量

常用笔记: 与VBS当中的Mid()类似的substr()小记

VBS当中有Mid函数,一般形式为:Mid(str,start,len)   对应于JS就类似于:str.substr(start,len) 不过区别的是:VBS中start从1开始,而JS从0开始. <script> //substr(start,length) : 从字符串的start个开始截取,截取length个 //如果忽略length,则截取到尾.如果length为0或负,则返回空字符串 //从第0个开始截取,截取到尾(相当于作白用功,基本不这么调用!) var e1 = ( (e1

Excel中使用MID函数获取身份证中的出生年月日

MID字符串函数,作用是从一个字符串中截取出指定数量的字符 MID(text, start_num, num_chars)   text被截取的字符 start_num从左起第几位开始截取(用数字表达)   num_chars从左起向右截取的长度是多少(用数字表达) 此例子是提取身份证号码中的出生年月日. A1单元格为522222199009091010 在B1单元格输入公式 =MID(A1,7,8) 被截取的字符串为A1单元格,从第七位开始向右截取8个数字. 得到出生年月日: 19900909

vb mid 函数使用说明

Mid就是从一个字符串中取子字符串,比如a="aabbcc",我们想取出"bb"就可以用Mid("aabbcc",3,2)Mid有3个参数,第一参数是要从哪个字符串中取第二个参数是指从第几个开始取第三个参数是指取几个例如:Mid("aabbcc",3,2)就是指从"aabbcc"的第3个字符开始,取2个字符,因此返回值为"bb".

C语言实现字符串截取函数left、mid和right

作者:iamlaosong C语言字符串截取需要自己编程实现,不过,网络时代,自然不用自己从头写了,网上各种方法的实现代码已经多如牛毛了,这儿抄录一个感觉不错的备案. #include <stdio.h> #include <string.h> /*从字符串的左边截取n个字符*/ char * left(char *dst,char *src, int n) { char *p = src; char *q = dst; int len = strlen(src); if(n>