1. Malicious attackers insert malicious Script code into a Web page. When a user browses the page, the Script code embedded in the Web page will be executed, thereby achieving the purpose of maliciously attacking the user.
1. Workflow
a. Malicious users enter some text in some public areas (for example, the input form of the suggestion submission form or the message public board), which is seen by other users. , but these texts are not only the text they want to input, but also include some scripts that can be executed on the client side. For example:
<script>'Not Safe'</script>
c. Other users see this page containing malicious scripts and execute them to obtain the user's cookies, etc. Sensitive information.
2. Example - Failure to prevent XSS attacks

1 pinglu = [] # 评论列表 2 3 #提交表单 4 def commit(request): 5 if request.method == 'GET': 6 return render(request, 'commit.html') 7 else: 8 com = request.POST.get('commit') 9 pinglu.append(com)10 return redirect('/index.html/')11 12 13 #查看评论页面14 def index(request):15 return render(request, 'index.html', {'commit': pinglu})

1 nbsp;html> 2 3 4 <meta> 5 <title>Title</title> 6 7 8 <h1 id="评论">评论</h1> 913 14


1 nbsp;html> 2 3 4 <meta> 5 <title>Title</title> 6 7 8 <h1 id="评论">评论</h1> 9 {% for item in commit %}10{{ item|safe }}11 {# item后加safe,默认数据安全,django不会做特殊处理#}12 {% endfor %}13 14


<script> alert('恶意脚本') </script>will execute this line of code on the index page, and a warning box will pop up (if it contains malicious code, it will be executed)
3. Prevent XSS attacks
- The most direct way is not to use safe
-
{# <div>{{ item|safe }}</div>#}<div>{{ item }}</div>
## for uncontrollable input in the html page
-
def commit(request):if request.method == 'GET':return render(request, 'commit.html')else: com = request.POST.get('commit')if '<script>' in com: # 过滤“<script>”关键字,防止恶意代码的提交return render(request, 'commit.html', {'error': '此条评论有毒,已被和谐'})else: pinglu.append(com)return redirect('/index.html/')</script>
2. CSRF
CSRF (Cross-site request forgery) cross-site request forgery, also known as "One Click Attack" or Session Riding, often abbreviated as CSRF or XSRF, is a malicious exploitation of a website. Although it sounds like cross-site scripting (XSS), it is very different from XSS, which exploits trusted users within a site, while CSRF exploits trusted websites by disguising requests from trusted users. Compared with XSS attacks, CSRF attacks tend to be less popular (so resources to prevent them are also quite scarce) and difficult to prevent, so they are considered more dangerous than XSS.
1. Workflow
The attack works by including links or scripts in pages accessed by authorized users:
2. How to prevent in django
Django implements the function of preventing cross-site request forgery for users, which is completed through the middleware django.middleware.csrf.CsrfViewMiddleware. The anti-cross-site request forgery function in Django is divided into global and local.
Global:
Enable middleware django.middleware.csrf.CsrfViewMiddlewarefrom django.views.decorators.csrf import csrf_exempt,csrf_protect

@csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件
@csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
3. django中的具体应用方法
form表单中添加
{
%
csrf_token
%
}
若form表单中未添加{
%
csrf_token
%
},则会报403错误。
#settings.py中打开MIDDLEWARE设置'django.middleware.csrf.CsrfViewMiddleware',


1 from django.shortcuts import render, HttpResponse, redirect2 3 def csrf_test(request):4 if request.method == 'GET':5 return render(request, 'csrf_test.html')6 else:7 return HttpResponse('ok')


1 nbsp;html> 2 3 4 <meta> 5 <title>csef_test</title> 6 7 812 13 14
修改csef_test.html:


1 nbsp;html> 2 3 4 <meta> 5 <title>csef_test</title> 6 7 813 14 15
全站禁用,即将settings.py中的 'django.middleware.csrf.CsrfViewMiddleware' 注释掉即可
基于FBV视图的局部禁用和使用


1 #settings.py 2 #启用 'django.middleware.csrf.CsrfViewMiddleware', 3 4 5 from django.views.decorators.csrf import csrf_exempt 6 7 8 @csrf_exempt 9 def csrf_test(request):10 if request.method == 'GET':11 return render(request, 'csrf_test.html')12 else:13 return HttpResponse('ok')


1 #settings.py 2 #禁用 #'django.middleware.csrf.CsrfViewMiddleware', 3 4 5 from django.views.decorators.csrf import csrf_protect 6 7 8 @csrf_protect 9 def csrf_test(request):10 if request.method == 'GET':11 return render(request, 'csrf_test.html')12 else:13 return HttpResponse('ok')
基于CBV视图的(只能局部使用或禁用类,不能在类方法里局部使用或禁用


1 #settings.py 2 #禁用 'django.middleware.csrf.CsrfViewMiddleware', 3 4 5 from django.views import View 6 from django.views.decorators.csrf import csrf_protect 7 from django.utils.decorators import method_decorator 8 9 10 @method_decorator(csrf_protect, name='dispatch')11 class Foo(View):12 def get(self, request):13 pass14 15 def post(self, request):16 pass


1 #settings.py 2 #启用 'django.middleware.csrf.CsrfViewMiddleware', 3 4 5 from django.views import View 6 from django.views.decorators.csrf import csrf_exempt 7 from django.utils.decorators import method_decorator 8 9 10 @method_decorator(csrf_exempt, name='dispatch')11 class Foo(View):12 def get(self, request):13 pass14 15 def post(self, request):16 pass
Ajax提交数据时,携带CSRF


1 nbsp;html> 2 3 4 <meta> 5 <title>csef_test</title> 6 7 814 15 <script></script>16 <script>17 function submitForm() {18 var csrf = $("input[name='csrfmiddlewaretoken']").val()19 var user = $("#user").val()20 $.ajax({21 url: '/csrf_test.html/',22 type: 'POST',23 data: {"user": user, "csrfmiddlewaretoken": csrf},24 success: function (arg) {25 console.log(arg);26 }27 })28 }29 </script>30 31


1 nbsp;html> 2 3 4 <meta> 5 <title>csef_test</title> 6 7 814 15 <script></script>16 {#专门处理cookie的插件,提取cookie字符串#}17 <script></script>18 19 {#csrf数据放于data中#}20 {#<script>#}21 {# function submitForm() {#}22 {# var csrf = $("input[name='csrfmiddlewaretoken']").val();#}23 {# var user = $("#user").val();#}24 {# $.ajax({#}25 {# url: '/csrf_test.html/',#}26 {# type: 'POST',#}27 {# data: {"user": user, "csrfmiddlewaretoken": csrf},#}28 {# success: function (arg) {#}29 {# console.log(arg);#}30 {# }#}31 {# })#}32 {# }#}33 {#</script>#}34 35 {#csrf数据放于请求头中#}36 <script>37 function submitForm() {38 var csrf = $.cookie('csrftoken');39 var user = $("#user").val();40 $.ajax({41 url: '/csrf_test.html/',42 type: 'POST',43 headers: {'X-CSRFToken': csrf},44 data: {"user": user},45 success: function (arg) {46 console.log(arg);47 }48 })49 }50 </script>51 52 53 54 55
注意:{
%
csrf_token
%
}和cookie中的csrftoken值不一样。
form表单中的隐藏csrf_token
cookie中
The above is the detailed content of Detailed introduction to XSS and CSRF. For more information, please follow other related articles on the PHP Chinese website!

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
