XSS(Cross-site Scripting)

As the most common web language, HTML is very flexible and you can modify it at any time. But this flexibility also gives hackers an opportunity: given abnormal input, a malicious JavaScript script can be inserted into your browser to steal your private information or impersonate you.

There are three types of XSS attacks:

1. Reflective XSS

Reflective XSS produce in front and back end the integration of web applications, the server-side logic will change the final web page code, if the hacker attacks the client, generally is induced users click on a link, http://localhost/index.php? Search =<%2Fh3>

2. DOM based XSS

DOM XSS is generated in the front-end JS code, and hackers take advantage of this by inserting their own scripts into web pages.

3. persistent XSS

Persistent XSS can occur in applications where malicious JavaScript scripts are written to normal server-side databases, clicked to execute by the user under certain conditions, and stored and displayed by the user’s input. For example: search results, comments, blog posts, etc

What a hacker can do with an XSS attack:

1. Stealing cookies

Because the JavaScript code injected by the hacker runs under the domain name server.com, the hacker can obtain cookie information in JavaScript through Document. cookie. For example,

2. Unauthorized operations

Hackers can also take advantage of JavaScript features to directly replace users in HTML operations.

3. Keystroke recording and fishing

JavaScript is powerful enough to record most of the user’s actions in the browser. For example: mouse track, keyboard input information. In other words, the account name and password you enter can be recorded by JavaScript, which can be accessed by hackers. Hackers can modify the DOM and forge a login box to induce users to enter their user names and passwords on pages where they do not need to log in

XSS protection:

The core principle of XSS defense is validation

1. Verify input OR output

The core principle of protection is: No user input can be trusted. It is recommended to verify the user input when it needs output. If the user input is verified immediately, two problems will occur.

  1. You won’t be able to save the user’s original input. This way, when a Bug occurs or you want to trace a hack, you can only “infer”, not accurately capture the user’s original input.
  2. Users’ content may be captured and used in multiple languages, encoded or processed in advance, and will cause unknown problems. For example, in older versions of PHP, there was a vulnerability called “magic Quotes” that caused PHP to crash because it couldn’t handle certain encoded characters.

In HTML, common injection points are:

Injection point The sample
HTML element content <div> Content user </div>
HTML element attributes <input value=” user content “>
URL request parameters http://server.com?search= User content
CSS values Color: user content
JavaScript Var name = “user content”

2. The coding

Is to convert some browser-recognized keywords (such as < and >)

3. Detection and filtration

You can use blacklist and whitelist rules to detect user content. But the ways hackers can attack are endless. By detecting

, the hacker can change it to

(because HTML tags are case insensitive), and sometimes even encode it as j Avascript and so on. Therefore, in the detection, it is recommended to use the whitelist rule. When we find that the content of a user may have XSS attack script, what should we do? At this point, there are two processing options: reject or filter. Rejection will hinder the use process of users. From the perspective of user experience, filtering will be more accepted by users. You can replace and delete sensitive characters directly.

4.CSP

Faced with such a common problem as XSS, W3C proposed Content Security Policy (CSP) to improve the Security of the Web. CSP is defined by adding a Content-security-policy option to the HTTP header returned by the server, and then defining the whitelisted domain name for the resource. The browser recognizes this field and restricts access to non-whitelisted resources.

The Content ws-security - Policy: the default - SRC "none"; Script - the SRC 'self'; Connect - SRC 'self'; Img SRC 'self'; Style - the SRC 'self';Copy the code

Why restrict access to outdomain resources? This is because XSS is often limited in length, preventing hackers from submitting a complete piece of JavaScript code. To solve this problem, the hacker uses a reference to an outdomain JavaScript resource for injection. In addition, by restricting access to outfield resources, hackers are restricted to send GET requests bypassing SOP through resource requests. At present, CSP is still supported by most browsers, as long as the user is using the latest browser, the basic can be very well protected.

SQL injection attack

SQL injection attack:

1. Modify the WHERE statement

SELECT * FROM Users WHERE Username =”” AND Password =”” or “”=”” SELECT * FROM Users WHERE Username =”” AND Password =” or “=”” So, when one or is true, the final result must be true. Therefore, the WHERE statement is always true, so the database will return all the data. The hacker only needs to enter “or””=” on the login page, and can successfully log in to the background without knowing the password. This is also known as the “universal password”.

2. Execute any statement

SELECT * FROM Users WHERE UserId = 1; DROP TABLE Users

Consequences of SQL injection attacks:

1. Bypass validation

“Or “”=” as a universal password, can let hackers do not know the password, through the login authentication.

2. Arbitrarily tamper with data

DROP TABLE Users DROP all Users from the database by inserting DROP TABLE Users.

3. Stealing data

SELECT * FROM Users WHERE UserId = 1 UNION SELECT * FROM Users WHERE UserId = 1

4. Consume resources

A hacker can use WHILE to create an infinite loop, or define a stored procedure, trigger an infinite iteration, and so on. In these cases, the database server is unable to respond to other requests in a timely manner because the CPU is rapidly filled to 100%.

SQL Injection Protection

1. Using a PreparedStatement

With precompilation, an execution plan is generated for SQL statements before input is inserted, and no additional logic is executed by the database, no matter what changes are made to the parameters submitted by the hacker.

2. Use stored procedures

The principle of PreparedStatement is similar to that of PreparedStatement. It separates the parsing and execution of SQL statements. The difference is that stored procedure injection prevention moves the process of parsing SQL from the database to the database itself.

3. Verify the input

For verification input, especially in complex scenarios, its protection effect is the weakest.

CSRF/SSRF (Cross-site Request Forgery)

XSS and SQL injection. They tamper with the original HTML and SQL logic, respectively

CSRF attack modes:

Hackers write malicious JavaScript scripts to lure you to web pages by “phishing” them. The hacker then uses these JavaScript scripts to steal your identity saved on a web page and, by impersonating you, get your browser to make bogus requests and ultimately perform the actions defined by the hacker. Basic conditions of CSRF attack:

  1. Use cookies for authentication.
  2. The parameters do not contain any privacy information.

Like XSS, CSRF can impersonate a user’s request to perform some functional operations, such as changing passwords, transferring money, and so on, which is equivalent to bypassing authentication and performing unauthorized operations. Although CSRF does not have as many operations as XSS, CSRF has lower propagation and attack costs than XSS. This means that even if your web page does not have any injection vulnerabilities, it can be exploited by CSRF if the interface is not configured properly. And hackers only need to set up a leading web page in their own domain name, so that any users who visit the web page can be subjected to CSRF attack

CSRF protection:

CSRFToken CSRF attacks by automatically submitting a form. Therefore, in the previous transfer example, the hacker can analyze the parameters required by the http://bank.com/transfer interface by capturing the packet and construct the corresponding form form. Therefore, we can effectively prevent CSRF by adding a parameter to the interface that the hacker cannot guess (the server randomly generates and returns to the browser every time the user normally visits the page). This is how the CSRF Token works.

2. Secondary verification The hacker initiates a transfer on your behalf through a CSRF attack. At the time of payment, the bank will launch a new page to further verify the payment password.

SSRF Server Side Request Forgery:

The same principle occurs on the server side. The server also has the function of proxy request: the user enters a URL (such as an image resource) in the browser, and then the server sends a request to this URL to complete the normal display of the page by accessing other server resources. In this case, as long as the hacker submits an Intranet URL in the input, the server can initiate an Intranet request defined by the hacker to obtain Intranet data. This is what we call Intranet penetration.

Consequences of SSRF attacks:

1. Intranet detection

Baidu SouTu example, we request the address is: https://image.baidu.com/search/detail?objurl=http://s1.sinaimg.cn/picture.jpg. Because http://s1.sinaimg.cn/picture.jpg will return to a normal images, so the page will display the corresponding pictures. We assume a server-side logic that during this request, the server will determine whether the Content Type of the data returned by the objURL is image/ JPEG. Then, there are three possible returns: “Yes,” which shows the image; If no, “Format error” is returned. If there is no response, “Image not found” is returned. Based on the three returned to logic, hackers can construct a malicious request address: https://image.baidu.com/search/detail?objurl=127.0.0.1:3306. If the server returns “Format error”, it indicates that port 3306 on the server is available. If “image not found” is returned, it is unavailable.

2. Read files

The server does not judge the validity of the image proxy, nor does it judge the validity of many other proxies, and returns the proxy results directly to the front end. We call this situation “SSRF with echo”. In this case, the hacker will know not only whether the request was successful, but also exactly what was returned. file:// is simply reading local files. By typing file://etc/passwd, a hacker can obtain the local passwd file with a single request and thus know which users are present locally. With constant trial and error, hackers can pull files from the entire server, including extremely sensitive information such as keys and source code.

SSRF protection:

Because THE SSRF vulnerability originated from the normal functional requirements of the business (such as baidu pictures image request, etc.). So it’s hard to really eliminate it.

1. Whitelist restrictions

Whitelist restrictions are always the simplest and most efficient defense. The whitelist in the SSRF limits the target URL submitted by the user. For example, only urls in the same domain name can be allowed. It can be understood that the proxy service of Baidu Picture only allows the PROXY of Baidu.com URL.

2. Restrict protocols and resource types

For protocols, only HTTP or HTTPS is allowed. For returned content, only content in image format is allowed.

3. Cooperation on the request side

The end result of SSRF is data leakage on the server receiving the proxy request. Therefore, SSRF protection involves not only server detection receiving URL, but also the cooperation of server receiving proxy request. In this case, we need to use requester-side restrictions. In SSRF (and most Web attacks), making a POST request is much more difficult than making a GET request. Through SSRF, hackers can only initiate requests and cannot obtain authentication information (such as authentication keys and secret) stored at the server end.

Deserialization vulnerability:

Deserialization vulnerability generation:

Deserialization operation to turn a string or byte stream into an object. In the process of converting data into objects, the application needs to call specific methods based on the content of the data. Hackers use this logic to embed custom code (such as executing a system command) in the data. This code is executed when an application deserializes data, allowing a hacker to take control of the entire application and server.

Consequences of deserialization vulnerability:

By deserializing the vulnerability, a hacker can call runtime.exec () for command execution. In other words, hackers can already execute arbitrary commands on servers, or launch denial-of-service attacks: By referring to each other in a HashSet, a 100-layer HashSet is constructed, which contains 200 instances of HashSet and 100 strings. For multi-layer nested objects, the number of methods that Java needs to call increases exponentially during deserialization. So, even though the serialized array is only about 6KB, the number of methods Java needs to execute with 100 layers of data is nearly infinite (n to the power of 100). A hacker can drain CPU resources and affect server availability by building a small volume of data and increasing the number of methods an application needs to call during deserialization.

Deserialization vulnerability protection:

1. Authentication and signature

Many serialized and deserialized services are not provided to the user, but to the service itself. The source of the call is authenticated by signing stored data. As long as the hacker cannot obtain the key information, it cannot send data to the deserialized service interface.

2. Restrict serialization and deserialization classes

Maintains a blacklisted list of method classes that might execute code. These classes are utility classes that are commonly used but not serialized, so we can blacklist them and not allow applications to deserialize them. In everyday use of Fastjson or any other JSON conversion tool, be careful to avoid serializing and deserializing interface classes. This is equivalent to whitelist filtering: only certain classes are allowed to be deserialized.

3. The RASP detection

RASP (Runtime Application self-protection) adds a rule detection in the call of these key functions by hook, etc. This rule determines whether the application executes logic other than the application itself and can intercept deserialization vulnerability attacks without modifying the code. RASP is the best way to detect deserialization attacks. If authentication and restriction classes are used for detection, it is necessary to cover possible vulnerability points one by one, which is very time-consuming and energy consuming. RASP, on the other hand, directly monitors the entire application by hook. As a result, more coverage and fewer code changes can be achieved. Because RASP hooks applications, it’s like stepping into the normal flow of an application. However, THE RASP detection rules are not efficient, so it will bring some performance loss to the application, and is not suitable for high concurrency scenarios.

Iv. Information leakage:

Where information can be leaked:

1. Error messages leak code logic

When a hacker logs in to a page, he or she enters a single quotation mark in the user name and a g in the password. The error information is displayed directly in the front end. The hacker can use the error information to determine the SQL used in the background for SQL injection attacks. On the one hand, correct configuration files should be used to prevent error information from being displayed in the front end. On the other hand, to detect error messages, you need to use “black box” detection.

2. Return information leakage

If the entered user name and password are correct, the login succeeds. If the application does not have this user, the user name does not exist is returned. If the entered user name and password do not match, incorrect password is displayed. This logic also exposes too much information to the hacker. Hackers can easily guess the correct password by simply making repeated login requests and knowing that the user name is present in the application and then trying to iterate through the common weak passwords. Too explicit a return message is more of a product-level bug than a code-level bug. Therefore, theoretically, there is no technical means to detect such vulnerabilities, which can only be avoided by artificial analysis audit. The solution is also relatively simple: directly blur and unify the returned information. For example, in the preceding login scenario, you can change the returned information of two login failures to “the user name does not exist or the password is incorrect”.

3. Comment information is leaked

Because almost all front-end code is displayed in a browser without compilation, hackers can easily see the comments in the front-end code. However, if key information such as server IP, database address, and authentication password appears in the comment information. Once these key information is leaked, it will cause very serious consequences. To avoid critical comment information in online code, use white-box detection. Get the source code directly online and scan it. The principle of “white box” scanning annotation information is relatively simple, because annotations in each language have special tags (such as /* in Java, etc.) that can be accurately identified.

4. Direct leakage

  1. Hidden files in the version management tool

As long as you don’t delete the.git directory when you go live, this means that hackers can access all files in.git through the URL. The hacker can then trace back to a full version of the code by executing a simple script. We can also restrict partial sensitive paths in HTTP services. For example, configure the following in Apache HTTPD to prevent hackers from accessing the.svn and.git directories.

Order allow,deny Deny from all

Five, plug-in vulnerability:

It’s not just the code itself that can cause bugs, but everything else. From OpenSSL, a tool that provides encryption and decryption functions, to Structs 2, a framework that provides network services, and even Linux, the underlying operating system, various vulnerabilities can occur.

Establish a protection system for plug-in vulnerabilities

1. Organize plug-ins and eliminate useless plug-ins

The Maven Dependency Plugin helps you automatically analyze the plug-in Dependency tree. Analysis via MVN Dependency: Analyze.

2. Manage patch updates of plug-ins

Check for Version updates with the Version Maven Plugin. Run the MVN version:display-dependency-updates command. But the following problems arise. Patch availability is insufficient. Not all plug-in vulnerabilities can be updated and maintained in a timely manner with the latest patch. Coverage is limited, and not all languages do plug-in analysis well, which means that operations people don’t have control over all the plug-ins used in the company. Update delay: During the patch update cycle, the company’s applications are left unprotected. To solve these problems, virtual patches should be used, which effectively block attack traffic without upgrading the application plug-in. The implementation principle is also very simple, that is, in the front network or system, the attack traffic for plug-in vulnerability can be detected and intercepted.

3. Use a public vulnerability library

CVE (Common Vulnerabilities &Exposures) CWE (Common Weaknesses Enumeration, Common Vulnerability Scoring System (CVSS) National Vulnerability Database (NVD) CNVD(China National Vulnerability Database) OWASP Dependency Check is a special tool for Vulnerability detection of plug-ins. It compares plug-ins within the project with a public vulnerability library. As a result, a report is generated in the form of a web page that allows you to see plugin bugs in your project at a glance.

Vi. Permission promotion and Persistence:

Permission promotion:

In an application or system, hackers or users controlled by hackers usually gain the rights of other users through vulnerability attacks or weak passwords. After obtaining the new user rights, the hacker can steal and tamper with data as the new user and carry out illegal operations. That’s a Privilege Escalation. Hackers can constantly acquire new identities to expand (or improve) their authority, expand the impact of attacks, and finally achieve control of the entire system. A level up is when a hacker gains access to another “level” user. Although the level of access remained the same, the hackers were able to gain access to new data and permissions because the identities of the users they controlled were changed. For example, the common theft of ordinary users is a level up. Vertical lift is even more damaging. Through vertical overreach, the hacker can gain a higher level of authority, typically the administrator of the application or ROOT of the system.

Permission persistence:

1. The back door

When a hacker successfully obtains a high-level permission through permission promotion, in order to retain this permission, the hacker will leave a hidden process in the application. As long as the hacker wants to enter the application again, he can communicate through this process without bypassing various security processes again.

2. The way the back door works

All of the attacks that we’ve talked about in the previous class are usually designed to cause some kind of explicit attack. The purpose of a backdoor is different. A backdoor tries to hide itself from others. Therefore, “back doors” are often in the form of Trojan horses. Trojans are seemingly normal services and processes that cause damage to applications and systems. Can a Trojan hide itself without attaching itself to an application? B: Sure. Then the “back door” evolved into a Rootkit. Typically, a Rootkit is embedded in the kernel and modifies the kernel logic to provide “backdoor” functionality. Because the kernel has high permissions, rootkits can destroy secure processes such as antivirus software without being easily detected. Also, because rootkits reside in the kernel, there is theoretically no better way to root out backdoors than by reinstalling the system. In addition to running a “back door” in the form of a hidden process, a hacker can also leave a “back door” in a normal Web service, which becomes a WebShell.

3. Insert a back door into the system

The most direct way is through permission promotion, that is, hackers directly obtain the command execution permission of the system, and then download the “back door” program from the cloud through the network. In addition, a hacker can upload a program to a server through a file upload vulnerability. When using an application, users often need to upload some files. Most of the time, developers will directly store the uploaded files in the current directory, that is, the directory of the Web service, for convenience. At this point, if the hacker uploads a PHP file, the PHP file will be placed in the directory of the Web service. Thus, a hacker can successfully implant a “back door” by simply uploading a PHP file containing WebShell. Hackers also need to make the “back door” persistent. Therefore, the “back door” needs to reside in the background of the system, and can be activated with the system on and off. To achieve this, hackers usually add “backdoor” execution commands to the configuration of scheduled tasks (crontab) or boot options (inittab, rC.local).

Protection against permission promotion and persistence:

1. Minimum rights

2. IDS (Intrusion Detection System)

IDS detects attacks by analyzing the similarities and differences between normal users and hackers at the network layer or host layer. For example, normal users do not connect to irrelevant hosts on the Intranet, while hackers must scan to explore the Intranet.

In security, the idea of defense in depth: to defend different layers so that even if the previous layer leaks, the next layer can still be defended.