Java Interview Review summary (Mysql article 10) - the Java perspective to talk about SQL injection

Foreword

Range preparation

First, we prepare a web interface service, which can provide information query manager, here we use springboot + jersey to build web services framework, the database is the most commonly used mysql. Below, we prepare the test environment, first create a user table jwtk_admin, SQL as follows:

Then insert the default administrator:

So we have two built-in system administrator, the administrator password using MD5 carried Hash, of course, this is a very simple as to study range of tables, so there is no very wide field.

Next, we create a spring boot + jersey RESTFul web service building, where we provide an interface to query the administrator via the administrator user name specific information, as follows:

SQL Injection Testing

First, we are forward thinking to develop a web service query request to send an administrator, here we send a GET request with PostMan tool

We could not be expected and developers, Web interfaces return the results we want, the user name of admin administrator information. OK, now completed development tasks, Git Push, Jira task point to be tested, then this interface is really no problem? Now we send such a GET request:

After sending the request, we found PostMan not received back, while the back-end Web services began to throw an exception MySQLSyntaxErrorException the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘‘xxxx’’’ at line 1

The reason is that in our inquiry xxxx 'at the sql statement syntax does not lead to correct. Here we not discuss the SQL syntax, we continue to experiment, construct a GET request to query again:

At this point, we were surprised to find, not only query interface not being given, but all the information in our database administrator jwti_admin table are queries out:

What the hell, is also the administrator of the table name = xxxx'or'a '=' a user? This is SQL Injection.

Injection principle analysis

We received a String name parameter in the interface, and is constructed by a query string concatenation manner. Under normal circumstances, the user will pass legal name query, but it will hacker crafted arguments passed, as long as the parameters after the string concatenation is still a valid SQL query, then SQL injection occurs. As the name = xxxx'or'a our above input '=' a splicing our query interface configuration following SQL statement:

When the interface execution sentence SQL, it is equivalent to the background system away to hackers, hacker saw the administrator password hash, do not take up cmd5 checked, directly with the 123456 password to log your back-office systems of. Why? Because md5 hashes 123456 too common, do not laugh, this is the reality of many small sites, weak passwords rampant, do you cry!

Well, now we should understand, SQL Injection reason is because the argument passed to the system has become a legitimate SQL SQL splicing caused, and its essence is the data entered by the user as a code execution. In the system as long as there is a hacker SQL injection point is found, then the hacker can execute SQL statements basically want to execute an arbitrary, such as adding an administrator, query all tables and even "off pants," and so, of course, this article is not to explain SQL injection technique articles, here we only investigate the causes and prevention methods SQL injection occurs.

JDBC preprocessing

In the above interfaces, DAO using JDBC way more basic database operations directly build the JDBC DAO in older systems is still very common, but that does not mean that we will be unsafe to use JDBC, if I will pass parameters xxxx'or'a '=' a whole as a parameter name query, it will not generate SQL injection. In JDBC, provides the PreparedStatement (preprocessing execution statements), it can be parameterized query SQL statement using the pre-code as follows:

Similarly, we use the injection method of injecting the above, we find that at this time, SQL injection failed. Now, let's look at SQL printed after being preprocessed and see what happens:

See? All 'are' escaped out so that you can ensure that the SQL query parameter is the parameter will not be malicious execution, thereby preventing SQL injection.

Mybatis injected under guard

MyBatis is excellent persistence framework to support custom SQL, stored procedures and advanced mapping, which avoids almost all of the JDBC code and manual setting parameters and get the result set. Meanwhile, MyBatis can configure and native Map using simple XML or annotation, the interfaces and Java POJOs (Plain Old Java Objects, ordinary Java Objects) to database records are, therefore mybatis now using the market rate is very high. Here we define as a mapper, implemented by the administrator user name query interface:

Also provides Web access interface:

Next, we tried SQL injection name field, you can find the injection did not succeed, you can see mybatis frame by printing mybatis's Log parameters have been pre-treated to prevent the injection:

Do you just use the mybatis it must avoid the risk of SQL injection? We make the following modifications mapper, the parameter is modified # {name} $ {name}, and using the name = 'xxxx' or 'a' = 'a' GET request as a parameter can be found SQL injection happened:

Well, this is why, where the difference mybatis $ {} and {#} in?

If a declaration originally passed as mybatis SQL parameters, the parameter will not be mybatis pretreatment directly spliced ​​dynamic SQL statements, then there is a risk to be injected, it should be used in the frame persistence avoided as mybatis use

In the form of SQL statement passed parameter, the parameter will not be mybatis pretreatment directly spliced ​​dynamic SQL statements, then there is a risk to be injected, it should be used to avoid frame mybatis as persistent form of an SQL statement passed parameter.

mybatis pretreatment parameters will not be, directly spliced ​​dynamic SQL statements, then there is a risk to be injected, it should be used as the persistent mybatis avoid using the frame form {} parameter passing, if not avoided ( some SQL such as like, in, order by other programmers may still choose to $ {} the way mass participation), it would need to pass parameters to escape the filter itself.

JPA preventive injection

Sun's JPA is used to integrate ORM technology, the world normalized standard definition of ORM Java Persistence API (java persistence API), JPA is just a set of interfaces, the current project will be the introduction of JPA uses Hibernate as its concrete realization, with the with no popular Spring Boot configuration framework, JPA increasingly persistent as the preferred technology because it allows programmers to write less code to complete the existing functionality.

For example, a strong JpaRepository, regular SQL query simply follow the naming rules defined interfaces, you can not write SQL (JPQL / SQL) queries can be achieved operational data from SQL injection prevention point of view, this would throw responsibility for security to frame than to rely on their own insurance programmer control. Therefore, if the project using JPA as a data access layer, you can basically eliminate the risk of SQL injection to a large extent.

But words can not say too dead, in a Spring Boot project I have ever seen, although the use of JPA as a persistence framework, but there is an old programmers are not familiar with the use of JPQL to build a query interface, still using string concatenation way to achieve business, and project security potential problems.

Meticulous security needs, security 100 - Service 1 = 0, even if 99% of your defense to attack, it is also not win, as long as there once was invaded, it has the potential to bring very serious consequences.

About SQL injection JPA, we have not discussed in detail, because injection vulnerability in the framework of the scope of the vulnerability framework belong to (such as CVE-2016-6652), the programmer simply follow the development of the JPA specification, there is no need to worry injection problems, both for the Framework you do the behind the scenes work.

Other ways to prevent SQL injection

Many companies there is older systems have problems risk code of a large number of SQL injection, but because it has a stable support of the company's business for a long time, should not be used the way a large area code update to eliminate injection problems, so it is necessary to consider the use of his way to guard against SQL injection . In addition to preventing SQL injection in SQL implementation, often also by the architecture, or through other ways to achieve the filtering effect of preventing SQL injection.

All inputs are unsafe: call parameters for the interface to match the format, such as interface admin queries by name, Path matching should use the regular match (because there should be no special characters in the user name), so sure that the incoming parameter is a parameter within the range of process control, i.e. accept only input values ​​well known to reject bad input. Note: verification parameter It should be used in conjunction with the output coding techniques.

To avoid the risk of using a hierarchical design: Front static possible, to minimize exposure to DAO access layer interface to a public network environment, if the existing project, difficult to modify existing code injection may consider increasing the web service before WAF filter traffic, of course, the code is not left to the hacker's exploits was the best solution. In the framework can also have nginx, using OpenRestry do traffic filtering, some special characters escaped.

Try using precompiled SQL statement: As a source of dynamic SQL statement caused SQL injection. Use pre-compiled SQL query statement to the assembly.

Scaling: mounting an input for a predetermined codec and outputs filter parameters and then enter the encoding process; reject all non-canonical encoding format.

summary

In fact, with the development of ORM technology, Java web development on the trend is increasingly away from the problem of SQL injection, while the Entity Framework with ASP.NET MVC framework supports a range of cold has always been high. In the current Internet, PHP and Python web applications to build SQL injection is currently the hardest hit. Although this article is from the perspective of research questions JAVA SQL injection, but is equally applicable to other development language on principle, I hope the reader through the text, by analogy.

Cherish data, stitching away, there will be a place to enter the political arena ...

发布了142 篇原创文章 · 获赞 31 · 访问量 2万+

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/103698300