Source:Extraction code: 7UK1

CSRF cross-site request forgery

CSRF stands for Cross Site Request Forgery.

CSRF is when an attacker steals your identity and sends malicious requests on your behalf.

Include: send mail in your name, send a message, steal your account, even buy goods, virtual currency transfer……

Problems: personal privacy leakage and property security.

CSRF request forgery schematic:

CSRF protection

Protection idea:

1. When requesting the transfer page, the server responds to the transfer page and sets a CSRF_Token value (random 48-bit string) in the cookie.

2. When the client makes a POST request, it carries the custom attribute ‘X-CSRFToken’ in the request header, which is the CSRF_Token value in the cookie. (Note that the browser also automatically sends the CSRF_token in the cookie to the server for post requests.)

3. When receiving a POST request, the server first verifies whether the X-CSRFToken value in the response header is consistent with the CSRF_Token value in the cookies. If the value is inconsistent, return is required to end the processing without further work. Complete steps:

Install cookies – first parser

Generate n as a random string:

function getRandomString(n){
    var str="";
    while(str.length<n){
      str+=Math.random().toString(36).substr(2);
    }
    return str.substr(str.length-n)
}
getRandomString(48);  // The call generates cSRF_token
Copy the code

When you get a transfer request page, set a cSRF_Token value (random 48-bit string) in the cookie:!! Remember to install the cookie-parser module

if(req.method=="GET") {// Set cSRF_token in cookie while rendering transfer page
    // Set cookies and sessions
    let csrf_token = getRandomString(48);
    res.cookie('csrf_token', csrf_token); 

    res.render('temp_transfer');
}
Copy the code

Next, in the front page, the POST request carries the custom attribute ‘X-CsrFToken’, which is the cSRF_Token value in the cookie:

$.ajax({
    url:'/transfer'.type:'post'.data:JSON.stringify(params),
    contentType:'application/json'.headers: {'X-CSRFToken':getCookie('csrf_token')},
    success: function (resp) {... }})...function getCookie(name) {   // The function that gets cookies
    var r = document.cookie.match("\\b" + name + "= (/ ^; *)\\b");
    return r ? r[1] : undefined;
}
        
Copy the code

Finally, when the server processes the POST request, check whether the X-CSRFToken value in the response header is consistent with the CSRF_Token value in the cookies. If the value is inconsistent, the CSRF authentication fails and return directly:

.else if(req.method=="POST") {// Compare the x-CsrFToken value in the response header with the CSRF_Token value in the cookies
    console.log(req.headers["x-csrftoken"]);
    console.log(req.cookies["csrf_token"]);

    if((req.headers["x-csrftoken"] === req.cookies["csrf_token"])){
        console.log("CSRF verified!");
    }else{
        res.send("CSRF validation failed!");
        return
    }

    // Post requests can now be processed normally. }Copy the code

Set CSRF protection for each POST request

In fact, not only does a transfer need CSRF protection, but every POST request needs CSRF protection.

App.js in webA project:

const router = express.Router();

router.all('/'.(req, res) = > {
    if(req.method=="GET"){
        res.render('temp_login')}... }); router.all('/transfer'.(req, res) = >{...else if(req.method=="POST") {let {to_account, money} = req.body;
        console.log(to_account, money);
        
        // Perform the transfer function:.... Is omitted
        console.log("Pretend to perform a transfer operation to transfer money from the currently logged user to the specified account.");
        console.log(The transfer has been completed${money}Yuan to account${to_account}`); res.json({to_account,money}); }});function csrfProtect(req, res, next){
    let method = req.method
    if(method=="GET") {let csrf_token = getRandomString(48);
        res.cookie('csrf_token', csrf_token);
        next() // Execution jumps to the next function execution, i.e. App. use(beforeReq,router)
    }else if(method=="POST") {// Compare the x-CsrFToken value in the response header with the CSRF_Token value in the cookies
        console.log(req.headers["x-csrftoken"]);
        console.log(req.cookies["csrf_token"]);
        
        if((req.headers["x-csrftoken"] === req.cookies["csrf_token"])){
            console.log("CSRF verified!");
            next()
        }else{
            res.send("CSRF validation failed! !");
            return
        }
    }
}

app.use(csrfProtect,router)
Copy the code