python web framework Flask - csrf attack

What CSRF that?

  (Cross Site Request Forgery, cross-site request forgery domain) is a network attack, it was listed as one of the big security risk Internet 20 in 2007, also known as "One Click Attack" or Session Riding, usually abbreviated as CSRF or XSRF, is a malicious use of the site is, people known phishing sites. Although it sounds like a cross-site scripting (XSS), but it is very different with XSS, and attack almost at odds. XSS trusted users in the use of the site, while CSRF is disguised by a request from trusted users to take advantage of trusted sites. Compared with XSS attacks, CSRF attacks are often not very popular (and therefore their resources to guard against is quite rare) and difficult to defend, it is considered more dangerous than XSS.

What CSRF you can do?

  You can understand this  CSRF attack: the attacker stole your identity, disguised as you send malicious requests. CSRF can do things include: to send the name of your e-mail, messaging, steal your account, and even the purchase of goods, virtual currency transfer ...... problems caused include: disclosure of personal privacy and property safety.

It is so powerful, then what is the principle?

CSRF principles outlined

  A user visits a site will be information about the user stored in cookies (session can be considered have been encrypted cookies, and then saved to the cookies in), then the user has visited a dangerous website, you will use this site before accessing the site leave cookies to send malicious requests

Way CSRF prevention

  I summed up in two ways prevent CSRF attacks: Background deal directly with CSRF attacks (personal statement) and front-end way ajax request

  Background Processing CSRF attacks

    Very simple, just to increase the value of a name attribute in the form csrf_token, value attribute value {{csrf_token ()}} is a hidden input form tag.

<form class="form-signin" method="post">
        <h2 class="form-signin-heading">请登录</h2>

        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

        <label for="inputEmail" class="sr-only">邮箱:</label>
        <input type="email" id="inputEmail" class="form-control" name="email" placeholder="请输入邮箱地址" required autofocus>
        <label for="inputPassword" class="sr-only">密码:</label>
        <input type="password" id="inputPassword" class="form-control" name="password" placeholder="请输入密码" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" name="remember" value="1"> 记住我
          </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">立即登录</button>
</form>

     csrftoken required background bind to the app, so that the front end of the parameters passed in the form CSRF attacks can not be usual to get post parameters (Part python web framework Flask background login, it is to use this approach to CSRF attacks of)

DEF create_app ():
     "" " 
    main entry file creation app, a blueprint for other use 
    : return: a return to App 
    " "" 
    App = the Flask ( __name__ )
     # prevent csrf injection attacks 
    CSRFProtect (App)
     # registration blueprint module 
    app.register_blueprint ( cms_bp, url_prefix = " / CMS " ) 
    app.register_blueprint (common_bp, url_prefix = " / Common " ) 
    app.register_blueprint (front_bp) 

    # import profile 
    app.config.from_object (config)
     # database db initialization App 
    db.init_app (App )
     #Log login_manager background initialization App 
    cms_login_manager.init_app (App)
     return App 


IF  __name__ == ' __main__ ' : 
    App = create_app () 
    app.run ()

 

  Ajax request distal embodiment

    Front-end Ajax request is to achieve a very good way to refresh the page, but Ajax request will have CSRF attacks. Prevent CSRF attacks are also very simple, just two steps:

      1) adding a name to the current page csrf-token, content of {{csrf_token ()}} meta tags

<meta name="csrf-token" content="{{ csrf_token() }}">

      2) Ajax rewrite request, and returns a request header containing the csrftoken

'use strict';
var cpajax = {
    "get": function(args){
        args["method"] = "get";
        this.ajax(args);
    },
    "post": function(args){
        args["method"] = "post";
        this.ajax(args);
    },
    "ajax": function(args){
        this._ajaxSetup();
        $.ajax(args);
    },
    "_ajaxSetup": function(args){
        $.ajaxSetup({
            "beforeSend": function(xhr, settings){
                if(!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain){
                    var csrftoken = $("meta[name=csrf-token]").attr("content");
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
    }
};

     3) so that the front end can not use $ .post () requests (such a request does not prevent CSRF attacks), but the use of Ajax request our rewritten.

$ ( Function () { 
    $ ( . "#Submit") ON ( "the Click", function (Event) { 
        the event.preventDefault (); 

        var oldpwdE = $ ( "INPUT [name = OLDPWD]" );
         var newpwdE = $ ( "INPUT [name = newpwd]" );
         var newpwd2E = $ ( "INPUT [name = newpwd2]" ); 

        var OLDPWD = oldpwdE.val ();
         var newpwd = newpwdE.val ();
         var newpwd2 = newpwd2E.val (); 

        // 1, to render a csrf-token in the template meta tags 
        // 2, is provided in the head ajax request CSRFtoken-X 
        the console.log ( "AAAAAAA"  );
        cpajax.post({
            "url": "/cms/resetpwd",
            "data": {
                "oldpwd": oldpwd,
                "newpwd": newpwd,
                "newpwd2": newpwd2
            },
            "success": function(data){
                console.log(data)
            },
            "fail": function(error){
                console.log(error)
            }
        })
    })
});

 

 

 

 

 

 

 

 

  

 

Guess you like

Origin www.cnblogs.com/aitiknowledge/p/11653641.html