preface
In our daily development, many partners tend to ignore security vulnerabilities and think that as long as the normal implementation of business logic is ok. In fact, safety is the most important thing. This article will learn common security vulnerabilities with you, I hope to help you ha. If there are any mistakes in this article, I hope you put forward ha, thank you ~
- Public number: a boy picking up snails
- Github address, thanks to each star
Github.com/whx123/Java…
1. SQL injection
1.1 What is SQL Injection?
SQL injection is a code injection technique that is commonly used to attack Web applications. By passing some special parameter characters into the Web application interface, it can deceive the application server and execute malicious SQL commands to obtain system information illegally. It is one of the most commonly used methods for hackers to attack databases.
1.2 How is SQL injection attacked?
An example of a common business scenario is to enter an employee’s name in the search box of a Web form, and then query the corresponding employee’s name in the background.
In this scenario, the front-end page usually sends a name parameter name to the background, and then the background queries the result through SQL
Name = "name "; Select * from staff where name=" + name; Select * from staff where name = 'staff'Copy the code
Because SQL is concatenated directly, if we fully trust the parameters passed from the front end. If ” or ‘1’=’1′, the SQL will look like this.
select * from staff where name='' or '1'='1';
Copy the code
This SQL query will find all employee information, so the user has exceeded his authority. The requester has access to all employees’ information, which is already exposed.
1.3 How can I Prevent SQL Injection problems
1.3.1 Using #{} instead of ${}
Using #{} instead of ${} in MyBatis largely prevents SQL injection.
- because
# {}
Is a parameter placeholder that is automatically appended with “” for string types but not for other types. As adopted by MybatisprecompiledThe subsequent parameters are no longer SQL compiled, so SQL injection is somewhat prevented. The ${}
Is a simple string substitution, whatever the string is, will be parsed into what, SQL injection risk
1.3.2 Do not expose unnecessary logs or security information, such as avoid directly responding to some SQL exception information.
If an SQL exception occurs, do not expose this information to the user in response. You can customize the exception to respond
1.3.3 Do not trust any external input parameters, filter some database keywords contained in the parameters
Can add a parameter verification filter method, filter union, or database keywords
1.3.4 Appropriate permission control
Before you query information, verify that the current user has this permission. For example, when implementing the code, you can ask the user to send an enterprise Id or obtain the session information of the current user. Before querying, check whether the current user belongs to the enterprise and so on. If so, you can have the right to query employees.
2. JSON deserialization vulnerability — such as the Fastjson security vulnerability
2.1 What is JSON serialization
- Serialization: The process of converting an object into a sequence of bytes
- Antisequence: The process of restoring a sequence of bytes to Java objects
Json serialization is converting an object to a JSON-formatted string, and Json deserialization is converting a Json string to an object
2.2 How is JSON deserialization vulnerability attacked?
Insecure deserialization can lead to remote code execution, replay attacks, injection attacks, or privilege escalation attacks. In Fastjson 1.2.24, a deserialization vulnerability is commonly exploited by implementing RCE through JNDI injection.
Let’s start with a simple example of fastjson deserialization:
public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) {system.out.println (" name "); this.name = name; } public int getAge() { return age; } public void setAge(int age) {system.out.println (" age "); this.age = age; } public static void main(String[] args) { String str = "{\" @ type \ ": \" cn. Eovie. Beans. User \ "and \" age \ ": 26, \" name \ ": \" pick up tianluo boy \ "} "; User user = JSON.parseObject(str,User.class); }}Copy the code
Running results:
I called the age method and I called the name methodCopy the code
The @type attribute calls the setXXX method of the corresponding object, which specifies deserialization to a class. If we can find a class in which a setXXX method can complete command execution through our careful construction, we can achieve the purpose of attack.
Com. Sun. Rowset. JdbcRowSetImpl is similar to a class, so it has two set method, party setAutoCommit and setDataSourceName
Interested partners, you can look at its source code
public void setDataSourceName(String var1) throws SQLException { if (this.getDataSourceName() ! = null) { if (! this.getDataSourceName().equals(var1)) { super.setDataSourceName(var1); this.conn = null; this.ps = null; this.rs = null; } } else { super.setDataSourceName(var1); } } public void setAutoCommit(boolean var1) throws SQLException { if (this.conn ! = null) { this.conn.setAutoCommit(var1); } else { this.conn = this.connect(); this.conn.setAutoCommit(var1); } } private Connection connect() throws SQLException { if (this.conn ! = null) { return this.conn; } else if (this.getDataSourceName() ! = null) { try { InitialContext var1 = new InitialContext(); DataSource var2 = (DataSource)var1.lookup(this.getDataSourceName()); return this.getUsername() ! = null && ! this.getUsername().equals("") ? var2.getConnection(this.getUsername(), this.getPassword()) : var2.getConnection(); } catch (NamingException var3) { throw new SQLException(this.resBundle.handleGetObject("jdbcrowsetimpl.connect").toString()); } } else { return this.getUrl() ! = null ? DriverManager.getConnection(this.getUrl(), this.getUsername(), this.getPassword()) : null; }}Copy the code
SetDataSourceName simply sets the value of dataSourceName. SetAutoCommit has the connect operation, and the connect method has the typical JNDI lookup call. The parameter is exactly the dataSourceName set in setDataSourceName.
Therefore, the anti-sequence code with vulnerabilities can be implemented as follows:
public class FastjsonTest { public static void main(String[] argv){ testJdbcRowSetImpl(); } public static void testJdbcRowSetImpl(){//JDK 8u121 requires system variables to be set System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "true"); //RMI String payload2 = "{\"@type\":\"com.sun.rowset.JdbcRowSetImpl\",\"dataSourceName\":\"rmi://localhost:1099/Exploit\"," + " \"autoCommit\":true}"; JSONObject.parseObject(payload2); }}Copy the code
The process of vulnerability reappearance is as follows:
Reference code source here ha, Fastjson vulnerability code test
How to solve json deserialization vulnerability
- You can upgrade versions, such as later versions of Fastjson, to enhance the security of AutoType when opened fastjson, add AutoType blacklist, etc., to address these security vulnerabilities.
- Deserialization has fastjson, Gson, Jackson, and so on, and can be replaced.
- Upgrade + Open Safemode
3. XSS attacks
What is XSS?
The full name for XSS Scripting is cross-site Scripting, which is confused with the abbreviation for Cascading Style Sheets (CSS), hence the acronym XSS. It refers to the malicious attacker inserts malicious HTML code into the Web page. When the user browses the page, the HTML code embedded in the Web will be executed, so as to achieve the special purpose of malicious attack on the user. XSS attacks fall into three types: storage, reflection, and DOM XSS attacks
How does XSS attack?
Take the reflective type as an example. The flow chart is as follows:
Let’s do some simple code examples. First, the normal HTML page is as follows:
<input type="text" name="name" /> <input type="submit" value=" http://127.0.0.1/search? name="> </body>Copy the code
- Users enter the search information, click the search button, is to reach the normal server. If the hacker added the following malicious attack code in the parameters after the URL.
http://127.0.0.1/search?keyword= "< a href =" http://www.baidu.com "> < script > alert (' XSS); </script></a>Copy the code
-
When a user opens a URL with malicious code, a normal server will parse the request parameter name, resulting in “”, which will be spliced into HTML and returned to the browser. The following HTML is formed:
-
The user’s browser parses the response and the malicious code is also executed.
4. The link I wrote here is baidu search page. In fact, when hackers attacked, they lured users to enter some important information and then jumped to their own servers to steal the content information submitted by users.
How do I resolve XSS attacks
- Don’t trust the user’s input, filter the input, filter the labels, etc., and only allow valid values.
- HTML escaping
- For link jumps, e.g
<a href="xxx"
To verify content, prohibit illegal links that start with script. - Limit input length and so on
4. CSRF attacks
What is a CSRF attack?
CSRF, or cross-site Request forgery, simply means that an attacker steals your identity and sends a malicious request on your behalf. In contrast to cross-site scripting (XSS), which exploits the user’s trust in a given site, CSRF exploits the site’s trust in the user’s Web browser.
How does CSRF attack?
Let’s take a look at this example.
-
- Tom logs in the bank, but does not log out. The browser contains Tom’s identity authentication information in the bank.
-
- Hacker Jerry will fake the transfer request, contained in the post
-
- Tom browses the post while still logged into the bank’s website
-
- Send the fake transfer request to the bank’s website, along with your identity information
-
- The bank website saw the identity authentication information and thought it was Tom’s legitimate operation, which finally caused Tom’s capital loss.
How do I resolve CSRF attacks
- Check the Referer field. The HTTP header has a Referer field that identifies the address from which the request came.
- Add a verification token.
5. File upload and download vulnerability
File upload vulnerability
File upload vulnerability means that a user uploads an executable script file and obtains the ability to execute server-side commands through the script file. A common scenario is that a Web server allows users to upload images or ordinary text files for storage, and users bypass the upload mechanism to upload malicious code and execute it to control the server.
The solution is usually:
- Restrict the permission of the server related file directory
- Verify uploaded files, for example, files whose name extensions do not allow uploading malicious codes
- Do not use front-end uploaded file names
File download vulnerability
File download vulnerability, for example, using.. “, so that the application can read the contents of files in other directories than the specified directory, which may read other important information about the server.
6. Sensitive data leaks
This is relatively easy to understand. Generally, sensitive information includes passwords, users’ MOBILE ID information, financial data and so on. As web applications or apis are not encrypted or carelessly protected, these data can be easily used by hackers. Therefore, we need to protect users’ privacy data, such as user password encryption and storage, HTTPS encryption for requests, important third-party interfaces using signature verification, server logs do not print sensitive data and so on.
7. XXE loopholes
What is a XXE
XXE is XML external entity injection. When external entities are allowed to be referenced, malicious content may result in arbitrary file reading, system command execution, port detection on the Intranet, and attacks on Intranet websites.
XXE Three attack scenarios
- Scenario 1. The attacker attempts to extract data from the server
<? The XML version = "1.0"? > <! DOCTYPE foo [ <!ELEMENT foo (#ANY)> <!ENTITY file SYSTEM "file:///etc/passwd">]> ]> <foo>&xxe; </foo>Copy the code
- Scenario 2. The attacker probes the server’s private network by changing the entity row above to the following
<! The ENTITY xxe SYSTEM "https://192.168.1.1/private" >] >Copy the code
- Scenario 3. The attacker uses malicious files to perform denial of service attacks
<! ENTITY xxe SYSTEM "file:///dev/random">]>Copy the code
How to defend against XXE
- Use methods provided by the development language to disable external entities
- Filtering user-submitted XML data, filtering
8. DDoS attacks
What is a DDos attack
Distributed Denial of Service (DDoS) is a Distributed Denial of Service attack. Generally speaking, the attacker launches a large number of requests to the target website in a short period of time, consuming the host resources of the target website on a large scale and making it unable to serve normally. Online games, Internet finance and other sectors are prone to DDoS attacks.
To facilitate understanding, let me quote a very classic example from Zhihu
I opened a 50 – seat Chongqing hot – pot restaurant, because of the material quality, treat the customer without deceit. Usually crowded, business is particularly prosperous, and the opposite two dogs home hot pot restaurant but no one. Two dogs in order to deal with me, think of a way, called 50 people to my hot pot restaurant to sit but do not order, so that other guests can not eat.
How do I deal with DDoS attacks?
- High defense server, that is, can independently hard defense more than 50Gbps server, can help website denial of service attacks, regular scanning network master nodes and so on
- The blacklist
- DDoS cleaning
- The CDN to accelerate
9. Framework or application bugs
- Struts framework vulnerability: Remote command execution vulnerability and open redirection vulnerability
- QQ Browser 9.6: API permission control issues lead to disclosure of privacy mode
- Oracle GlassFish Server: REST CSRF
- WebLogic: Unauthorized command execution vulnerability
- Unauthorized access to the Hacking Docker: Registry API
- WordPress 4.7/4.7.1: REST API content injection vulnerability
10. Permission-related vulnerabilities such as weak passwords, certificate validity verification, internal interface exposure on the public network, and no authentication
Weak password
- Talk to
- The password contains less than 8 characters
- Passwords should not be consecutive characters (QQQQQQ)
- The account and password are the same (for example, root: root).
- The password is the opposite of the account (e.g. Root: toor)
- Password pure digits (e.g. 112312324234, phone number)
- Password pure letters (e.g. Asdjfhask)
- The password has been replaced by a number instead of a letter (example: Hello word, hell0 w0rd)
- Passwords use continuous combinations (e.g. 123456, abcdef, 654321, fedcba)
- Default service/device factory password
Certificate validity verification vulnerability
If the certificate is not validated, HTTPS is useless.
- If the certificate is generated by the client, a trust chain needs to be established with the system trusted root CA. Therefore, you cannot trust all certificates on the client in the client code to solve the SSL certificate error problem.
- If the certificate is about to expire, replace it in advance.
Permission-related vulnerabilities such as non-authentication
You are advised to authenticate some important interfaces. For example, if you check the transfer record of an account, you must verify whether the account belongs to the operator.
Reference and thanks
- Jndi injection in Fastjson
- Summary of file upload vulnerability for Web penetration
- XXE exploit skills: from XML to remote code execution
- A list of 15 common WEB application security vulnerabilities
- What is a DDoS attack?
- Weak passwords summary (What are weak passwords)