当前位置:网站首页>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
- 1 ) Set up... On the target site cookie add same-site attribute
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');
- You can go directly through setcookie function , Such as
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
边栏推荐
- Easyrecovery15 free data recovery software
- 第三章运输层
- 一文带你了解GaussDB(DWS) 【这次高斯不是数学家】
- 处理链加载数据出错的可能原因-process chain loading error
- After ten years of deep cultivation, Xuanwu cloud technology finally sits firmly at the leading position of FMCG SaaS
- Execution engine - (compiler, JIT)
- Course design of network sniffer design based on C language
- 10 useful flutter widgets
- 首家BMW i品牌专属体验店开业,全面展示宝马电动产品的魅力
- redis中数据结构的学习笔记
猜你喜欢

Flink CDC + Hudi 海量数据入湖在顺丰的实践

TemplateDoesNotExist at /users/register/

TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者

CTF platform marsctf after graduation

redis中的string类型是怎么组织的?

Tencent, Shanghai Jiao Tong and Zhejiang University proposed pyramid clip to align the semantic within the hierarchy and cross hierarchy relationship. The zero shot effect is better than clip

Computer selection 1

【基础知识】~ 硬核/软核/固核、PWM/SPWM、斐波那契数列、大端模式存储、傅里叶变换、奈奎斯特采样定律、芯片选型、基尔霍夫定律、FIR/IIR 滤波器

字符串切割 group by

执行引擎-(编译器、JIT)
随机推荐
More than observation | Alibaba cloud observable Technology Summit officially launched
SQL2008数据库
福建土楼沟文化旅游开发有限公司6%股权转让,来自塔米狗分享
Quartz多个调度器+线程池模式分别调度任务
Easyrecovery15 free data recovery software
MKS H3615NS 直流电机驱动 使用说明书
Is it safe for the securities company with the lowest fees to open an account
Possible causes of processing chain loading error -process chain loading error
Course design of network sniffer design based on C language
Leetcode 159 Longest substring containing at most two different characters (2022.06.08)
【基础知识】~ 硬核/软核/固核、PWM/SPWM、斐波那契数列、大端模式存储、傅里叶变换、奈奎斯特采样定律、芯片选型、基尔霍夫定律、FIR/IIR 滤波器
PHP redis common operation manual
MOS tube from entry to mastery
RDMA Verbs API
Comparison and evaluation of code on cloud - devcloud
[buuctf.reverse] 109_[FlareOn6]FlareBear,110_[INSHack2018]Tricky-Part1
Ref reference usage
基于华为云君可归烈士寻亲系统开发实战【华为云至简致远】
Quartz multiple schedulers + thread pool mode to schedule tasks separately
Camtasia 2022最新版新增功能