当前位置:网站首页>Closed training (25) basic web security
Closed training (25) basic web security
2022-06-29 09:34:00 【likeGhee】
It's not particularly difficult , Mainly to accumulate experience
To learn springboot Went to the , What a delay . Over your face
List of articles
What are the common attacks ?
SQL Inject ,XSS,CSRF( Repeating a submission with a form is a type )
The most basic WEB Safety precautions : The password is set to English + Numbers + Special symbols , Visit the white list
Form resubmission
Form resubmission is very common ,
The main reason for the repeated submission of forms is the network delay
The simple solution is to use the front end token
But it can't prevent simulation http request
First simulate the problem
Write a form.jsp
<html>
<head>
<title>$form$</title>
</head>
<form action="${pageContext.request.contextPath}/DoFormServlet" method="post">
user name :<input type="text" name="userName">
<input type="submit" value=" Submit " id="submit">
</form>
<body>
</body>
</html>
Write a servlet Used to invoke
@WebServlet("/DoFormServlet")
public class DoFormServlet extends HttpServlet {
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("userName");
Thread.sleep(3000);
System.out.println(" insert data ..");
resp.getWriter().println("success");
}
}
Launch page 
Input 123 Submit ,Thread.sleep(3000); It's delayed 3 second , Simulate network latency , The page will not jump immediately , You can click the submit button several times , Cause the form to be submitted repeatedly

Background printing 
Front end solutions
After submission , The button turns gray , One more sign to judge , This approach can , But there are limitations , It does not prevent repeated submissions from refreshing reloads
<html>
<head>
<title>form</title>
</head>
<script type="text/javascript"> let submitFlag = false // No click for false function isNoSubmit() {
// Not submitted yet true if (!submitFlag) {
submitFlag = true return true } // Submitted and returned false return false } </script>
<form action="${pageContext.request.contextPath}/DoFormServlet" method="post" onsubmit="return isNoSubmit()">
user name :<input type="text" name="userName"/>
<input type="submit" value=" Submit " id="submit"/>
</form>
<body>
</body>
</html>
Use token To solve
token Identity token , Proof of validity and identity
Ideas :
Request one Sevlet Generate token Store in session in , Forwarding to form.jsp, here jsp Take a token And attach the form to submit , To DoFormServlet, Judge token Whether it works ,DoFormServlet The judgment steps are as follows :
If from session Obtained in token, It is consistent with the form , It is the first time to send a request , Delete after processing sessiom Of token, Express this token Has lapsed .
If seesion There is no such token, explain token It has been used .
If it comes token Empty or with session Of token atypism , The description was maliciously forged token
Write ToFromServlet Generate token And forward
@WebServlet("/ToFromServlet")
public class ToFromServlet extends HttpServlet {
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String token = UUID.randomUUID().toString();
System.out.println(" Generate Token:"+token);
req.getSession().setAttribute("sessionToken", token);
req.getRequestDispatcher("form.jsp").forward(req, resp);
}
}
modify form.jsp, Add one hidden Domain
<html>
<head>
<title>form</title>
</head>
<script type="text/javascript"> let submitFlag = false // No click for false function isNoSubmit() {
// Not submitted yet true if (!submitFlag) {
submitFlag = true return true } // Submitted and returned false return false } </script>
<form action="${pageContext.request.contextPath}/DoFormServlet" method="post" onsubmit="return isNoSubmit()">
<input type="hidden" value="${sessionToken}" name="sessionToken">
user name :<input type="text" name="userName"/>
<input type="submit" value=" Submit " id="submit"/>
</form>
<body>
</body>
</html>
Last in doFormServlet add to session Judge
@WebServlet("/DoFormServlet")
public class DoFormServlet extends HttpServlet {
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!isFlag(req,resp)){
resp.getWriter().println("fail");
System.out.println(" Has submitted ...");
return;
}
req.setCharacterEncoding("utf-8");
String username = req.getParameter("userName");
Thread.sleep(3000);
System.out.println(" insert data ..");
resp.getWriter().println("success");
}
public boolean isFlag(HttpServletRequest req, HttpServletResponse resp){
String sessionToken = req.getParameter("sessionToken");
String sessionToken1 = (String) req.getSession().getAttribute("sessionToken");
if(StringUtils.isNullOrEmpty(sessionToken)){
System.out.println("sessionToken by null");
return false;
}
if (StringUtils.isNullOrEmpty(sessionToken1)){
System.out.println("sessionToken1 by null");
return false;
}
if(!sessionToken1.equals(sessionToken)){
System.out.println(" forge token");
return false;
}
req.getSession().removeAttribute("sessionToken");
return true;
}
}
visit /ToFromServlet that will do
test , Background printing :
How interfaces prevent emulation http request
close token, Guarantee uniqueness , Difficult to forge . But generate token Methods can be cracked , Or can I impersonate a request , How to solve this problem ?
Use verification code , Prove that you are not a robot
token+ The verification code is completely resolved to prevent analog requests
Use Filter prevent XSS attack
What is? XSS attack ?
XSS Also called script injection
XXSS Attacks often occur in : There is a form in the page , When submitted , Parameter submission , Let the data be displayed on the page , A pop-up window or page jump occurs suddenly
For example, the content I injected is location.href, When you visit a page, you immediately jump to the phishing site , The user login interface is exactly the same .( I went out to guard against all )
simulation XSS attack
We write scripts to inject 
Click submit to pop up 
Think about if this script is in the message area / Comments section , Other users will pop up when they click in .
XSS Page Jump is also written in
<script>alert(' Successful attack ');window.location.href='http://www.baidu.com';</script>"
It is good for others to visit a page , Then suddenly jump to the login interface , The interface is as like as two peas. , This is phishing attacks , It's also XSS A kind of
How to prevent ?
The principle is XSS The label of is html Parsed , We can escape the tag .
Inherit HttpServletRequest rewrite getParameter Method
public class XssHttpServletRequest extends HttpServletRequestWrapper {
HttpServletRequest request;
public XssHttpServletRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
if (!StringUtils.isEmpty(value)){
value = StringEscapeUtils.escapeHtml4(value);
}
return value;
}
}
Write Filter, Take us XssHttpServletRequest Transfer the past , such getParameter Can escape characters
@WebFilter(filterName = "XSSFilter", urlPatterns = {
"/*" })
public class XSSFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
XssHttpServletRequest xssHttpServletRequest = new XssHttpServletRequest(req);
chain.doFilter(xssHttpServletRequest, response);
}
public void destroy() {
}
}
The test again , such <> Is escaped , The label is broken 
SQL Inject
There is nothing to say ,
There are several ways to prevent :
1、PreparedStatement
2、 Use regular expressions to filter the incoming parameters
3、 String filtering
4、 Check whether the package letter has illegal characters
Then he stood up with a snap , Soon! , Then there is a port scan , A brute force password cracking , One big kill everywhere . I'll keep them all out , Guard out , ah . After going out, it's a tradition to stop at points , I was careless , No flash .
Let's open a new column later , The column of closed door cultivation is here 25 All .
边栏推荐
- pytorch总结学习系列-操作
- Western Polytechnic University, one of the "seven national defense schools", was attacked by overseas networks
- 3DMax 卡死、白屏、渲染死机问题总结
- KiCad学习笔记--快捷键
- YOLACT实时实例分割
- 第十二章 信号(二)- 生产者消费者示例
- Uber 前安全主管面临欺诈指控,曾隐瞒数据泄露事件
- Iso16000-9 testing of volatile organic compounds in building products and furniture
- Twinmotion beginner tutorial
- What is hyperfusion? What is the difference with traditional architecture
猜你喜欢

How is epoll encapsulated in golang?

Instance error iopub data rate exceeded

Western Polytechnic University, one of the "seven national defense schools", was attacked by overseas networks

【目标检测】|指标 A probabilistic challenge for object detection

Factory mode

LFFD:一种用于边缘检测的轻量化快速人脸检测器

SSD改進CFENet

数据处理时代,数据质量建设才是企业的生存之道

AugFPN:改进多尺度特征学习用于目标检测

Highlight in the middle of the navigation bar at the bottom of wechat applet
随机推荐
Simplicity studio does not recognize the new JLINK V9 solution
Research progress of target detection in the era of deep convolutional neural network
Mongodb persistence
Chapter 12 signals (II) - examples of producers and consumers
Go deep into RC, RS, daemonset and statefulset (VII)
UE4 编译单个文件(VS与编辑器分别启动)
爱快安装或重置后,PC或手机端获取不到ip
HB5470民用飞机机舱内部非金属材料燃烧测试
KiCad学习笔记--快捷键
Detailed version of two-stage target detection principle
(transfer) mysql: error 1071 (42000): specified key was too long; max key length is 767 bytes
After aikuai is installed or reset, the PC or mobile terminal cannot obtain IP
Instance error iopub data rate exceeded
Simple use of promise method
UE4 VS的Visual Assist插件设置
Which securities company is good for opening a mobile account? Is it safe to open an account online?
1.4 机器学习方法之回归问题
MySQL uses union all to count the total number of combinations of multiple tables and the number of tables respectively
MH/T 6040航空材料烟密度试验
Wechat applet project: wechat applet page layout