当前位置:网站首页>About CSRF and its defense

About CSRF and its defense

2022-06-09 11:33:00 Johnny, me

About CSRF

  • CSRF(Cross Site Request Forgy) Cross-site request forgery
  • Without the user's knowledge , Other websites send requests to the target website
  • for instance , For example, you click in through a link , Posted an update on other websites
  • That is, identity theft , This is a very terrible thing
  • CSRF There is another name called " It explodes at one point ", even to the extent that , No need to click , For example, refresh
  • As long as the request can be generated CSRF The possibility of attack
  • CSRF The attacks can be varied
    • It can be a form , Links, pictures, etc
    • A refresh , One click triggers
    • Can pass GET and POST Request , and GET Request more lethal , More widespread
  • commonly CSRF It can be called a kind of Internet worm , It's very contagious
  • Take a specific code example
    //  Create a form 
    document.write(` <form name="commentForm" target="csrf" method="post" action=" An interface address of the target website "> <input name="postId" type="hidden" value="1"> <textarea name="content"> come from CSRF!</textarea> </form>`
    );
    //  Create a iframe
    var iframe = document.createElement('iframe');
    iframe.name = 'csrf';
    iframe.style.display = 'none'; //  Hidden state 
    document.body.appendChild(iframe);
    
    //  Submit the form after the page is loaded 
    setTimeout(function(){
          
        //  Form target yes iframe, Will be in iframe Submit and jump within ,  The current page has not changed 
        document.querySelector('[name=commentForm]').submit();
    }, 1000);
    

CSRF Principle attacks

  • It mainly involves two websites , One is the target website , One is the attacker's website
  • The user logs in to the target website , There will be login status session And some voucher information such as cookies
  • The attacker will use some means , Like links , Use the user's identity on the target website in the form of pictures , Send data to the target website
  • Note that this bypasses the front end of the target site , Directly requested the interface of the target website , Take a specific example :
    • Users only need to log in to the target website under a browser A, Will be in A Store your ID under the website , Such as cookie
    • If an attacker passes an email , Let the user click on a link in the email , This link opens the same browser
    • The link is A Some interface of the website , At the same time, some data that the attacker wants to submit
    • Because the user has logged in A Website , At this point, as soon as you click this link, you will automatically send the data that the attacker wants to submit

CSRF The harm of the attack

  • Without the user's knowledge , Using user login status
  • Complete business request , Such as stealing user funds ( Transfer accounts , consumption )
  • Another example , Posing as a user to post , User back pot , This is a direct hazard
  • Also indirectly damage the reputation of the target website

CSRF Attack cases

  • QQ There is a flaw in the interface for purchasing props , Lead to continuous purchase of props , Users' money is constantly being consumed
  • QQ Music sharing to Tencent Weibo song list , Send a microblog message with worm , It's being spread
  • Of course , These vulnerabilities have been fixed , We should be alert to similar cases

CSRF How to defend

  • adopt CSRF The principle of the attack is to know when visiting the target website referer For the attacker website
  • We can use this feature to make defense , generally speaking , We can do this
    • 1 ) Set up... On the target site cookie add same-site attribute
      • SameSite Property has two values :Strict, Lax
      • Strict Means the strictest , Third parties... Are totally prohibited Cookie, Cross site , Under no circumstances will it be sent Cookie
      • Lax It means that the third party is not sent in most cases Cookie, But navigate to the target site Get Except for requests
      • Set up Strict or Lax in the future , Basically put an end to CSRF attack , Of course , The premise is that the user browser supports SameSite attribute
      • The site can choose to close explicitly SameSite attribute , Set it to None
      • however , The premise is that you have to set Secure attribute (Cookie Only through HTTPS Protocol delivery ), Otherwise it will not work
      • however SameSite Property compatibility is not very optimistic , So it is not a universal solution CSRF attack
      • stay koajs Set in SameSite Example
        ctx.cookies.set('userId', user.id, {
                  sameSite: 'strict'})
        
    • 2 ) On the target website referer The filter , Only legitimate requests are allowed
      • Where to initiate the request ,referer Who is the , For instance from A Jump to B, that B Of referer Namely A
      • If referer It's a legal address , We'll pass , If it's not legal, we refuse
      • You can customize the legal referer list , Code is also very good implementation , Just make a rigorous judgment
      • Be careful , If it is file Protocol access is not available referer Of , To pass the http The form of the agreement will have referer
    • 3 ) Add verification information to the front end of the target website : Verification Code
      • Each submission must have a verification code , And the verification codes are equal
      • stay nodejs There is no native method to generate graphic verification code in ccap The library of
      • At this time, it can effectively hinder CSRF attacked , But it is impossible for all form requests to do verification code verification
      • The verification code can be used to defend against , But it is not ideal to use in the production environment , Experience is very poor , The code does not give an example , More trouble
    • 4 ) Add verification information to the front end of the target website :token
      • The attacker can not obtain directly after making a request , Must go through the front end of the website
      • The back end generates a csrftoken, That is, a random string
      • A form placed on the page , One placed in cookies in
      • check cookies Medium token And... In the form token Is it consistent
      • Consistent means correct direct release , Inconsistencies indicate errors or attacks
      • Django That's how the framework handles CSRF The attack
      • Also in common ajax It can also be verified in the request , We can see on the page meta On storage token
      • In normal transmission ajax Get... On request token And send cookies The value in is passed to the backend for verification
      • There is a problem that only the form of the latest open page can be submitted under multiple pages , Because of... On multiple pages token atypism , and cookie Dynamic change
      • There are many solutions , Like pages token invalid , The verification is inconsistent , Request a new page again token, Can effectively solve the problem
      • Notice here our two token: One is on the page token, One is cookies Medium token

PHP defense CSRF

1 ) PHP Use in samesite This cookies attribute

  • PHP Hit middle cookies There are two ways :
    • You can go directly through setcookie function , Such as setcookie('test', '123') There is no support for SameSite Property settings
    • Can pass header Function to set cookies, Such as header('Set-Cookie: test=123; SameSite=Lax');

2 ) according to HTTP referer head

  • obtain referer head :var_dump($_SERVER['HTTP_REFERER'])
  • Specific usage can refer to
    if($_SERVER['HTTP_REFERER']) {
          
        //  Judge referer Whether it conforms to the legal domain name ,  There can be multiple implementations , Support to define the domain name list , Only one is provided below 
        $isLegal = strpos($_SERVER['HTTP_REFERER'], 'http://localhost') === 0;
        var_dump(isLegal); //  Whether to output to the page 
    }
    

3 ) according to token Handle

  • Refer to code
    $csrfToken = rand(1000,9999); //  Define a token,  random number ,  Of course, it's better to make it more complicated ,  This is just an example 
    setcookie('csrfToken', $csrfToken); //  Make relevant marks for the site cookie
    
    if($_POST['csrfToken'] === $_COOKIE['csrfToken']) {
          
        // ...  Match the , Deal with your own logic 
    }
    
    <form method='post'>
        <input type='text' name='csrfToken' value="<?php echo $csrfToken;?>">
        <textarea name='content'>hello</textarea>
        <button type='submit'> Submit </button>
    </form>
    

4 ) Process according to the verification code

  • Because the user experience of the verification code scheme is not very good , Processing in any language should be the final solution
  • Not recommended here
原网站

版权声明
本文为[Johnny, me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091046492005.html