当前位置:网站首页>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



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
 Insert picture description here
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

 Insert picture description here
Background printing
 Insert picture description here

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 :

  1. 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 .

  2. If seesion There is no such token, explain token It has been used .

  3. 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 :
 Insert picture description here

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
 Insert picture description here
Click submit to pop up
 Insert picture description here
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
 Insert picture description here

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 .

原网站

版权声明
本文为[likeGhee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/180/202206290810420017.html