[Tip]06. about how to prevent SQL injection, not using preprocessing

Source: Internet
Author: User
Tags assert how to prevent sql injection object object

In a phase, two stage, some students, for SQL statements always use the concatenation of strings, this is a bad problem, this greatly affects the security of our program, so we generally recommend preprocessing mode, for this mode of students do not want to learn to study hard, I would like to introduce another way to prevent SQL injection, I hope to help you!

It should be said that even if you do not deal with the special characters of HTML or JavaScript, there is no disastrous consequences, but if you do not dynamically construct SQL statements to deal with the special characters in the variable, it can lead to a program vulnerability, data theft, data corruption and other serious security issues. There are a lot of articles about SQL injection in the network, and interested readers can search the relevant data in-depth research.

Although the consequences of SQL injection are serious, this problem can be avoided as long as the variable of the dynamically constructed SQL statement is handled with special character escaping . Consider a classic example of a security breach:

SELECT COUNT (userId) from T_user WHERE username= ' "+username+" ' and password = ' "+password+" '

The SQL statements above determine whether the login information provided by the user is correct based on the number of results returned, and if the UserName variable is merged directly into the SQL statement without special character escapes, the hacker can bypass using the UserName by setting the "1 ' or ' 1 ' = ' 1" User name/password check directly into the system.

So unless necessary, it is generally recommended to construct dynamic SQL statements in a way that preparedstatement parameter bindings, because this approach avoids potential security problems with SQL injection. However, it is often difficult to completely avoid the way in which dynamic SQL statements are constructed by stitching strings in the application. To prevent others from using special SQL characters to break the SQL statement structure or to implant malicious operations, special characters must be escaped before the variable is stitched into the SQL statement.

The results are as follows:SELECT COUNT (userId) from T_user WHERE username= ' 1 ' or ' 1 ' = ' 1 ' and password = ' 123456 '

in fact, stringescapeutils not only provides the function of SQL special character escaping, but also provides the method of escaping and restoring HTML, XML, JavaScript and Java special characters. If you do not mind introducing the Jakarta Commons Lang Class package, we recommend that you use the stringescapeutils tool class to complete the work of special character escaping .

------------------------------

Method into the parameter detection Tool class

Web apps need to be checked for legitimacy after they accept the data submitted by the form, and if the form data is illegal, the request will be dismissed. Similarly, when we write a method of a class, we often need to check the validity of the method's entry, and if the incoming parameter does not meet the requirements, the method will reject the subsequent processing by throwing an exception. As an example: there is a way to get the input stream based on the file name: InputStream getData (String file), in order for the method to execute successfully, you must ensure that the file entry parameter cannot be null or white space character, otherwise no subsequent processing is necessary. At this point the writer of the method usually writes a piece of code that detects the incoming parameter at the very front of the method body, as follows:

Public InputStream getData (String file) {
if (file = = NULL | | file.length () = = 0| | File.replaceall ("s", ""). Length () = = 0) {
throw new IllegalArgumentException ("File entry is not a valid document address");
}
...
}

The code that resembles the above detection methods is very common, but it is not a good idea to use manual detection logic in each method. Reading the spring source, you will find that spring uses a Org.springframework.util.Assert generic class to accomplish this task.

The assert translates to Chinese as "assertion," and the reader, who has used JUnit, is familiar with the concept, which determines that an actual running value is the same as expected, or throws an exception. Spring's detection of method parameters borrows this concept, and the Assert class provided has many methods to assert the method's parameters according to the rules, which can satisfy the requirements of most methods ' incoming parameter detection. These assertion methods throw illegalargumentexception when the incoming parameter does not meet the requirements. Let's take a look at the common assertion methods in the Assert class:


Assertion Method Description
Notnull (Object object) throws an exception when object is not NULL, and the Notnull (object object, String message) method allows you to customize exception information through a message. The opposite of the Notnull () method assertion rule is isNull (Object object)/isnull (Object object, String message), which requires that the entry parameter must be null;
IsTrue (Boolean expression)/IsTrue (Boolean expression, String message) when expression does not throw an exception for true;
Notempty (Collection Collection)/Notempty (Collection Collection, String message) throws an exception when the collection contains no elements. Notempty (map map)/notempty (map map, string message) and Notempty (object[] array, string message)/Notempty (object[] Array , String message) to determine the entry of the Map and object[] types, respectively;
Haslength (string text)/Haslength (string text, String message) throws an exception when text is null or has a length of 0;
HasText (string text)/HasText (string text, string message) text cannot be null and must contain at least one character that is not a space, otherwise throws an exception;
Isinstanceof (class Clazz, Object obj)/isinstanceof (class type, object obj, String message) If obj cannot be properly styled as clazz specified Class will throw an exception;
Isassignable (class Supertype, class subtype)/Isassignable (class Supertype, class subtype, String message) subtype must be The supertype can be matched by type, otherwise an exception will be thrown;



Use the Assert assertion class to simplify code for method-in-parameter detection, such as InputStream getData (String file) after applying the Assert assertion class, its code can be simplified to the following form:

Public InputStream getData (String file) {
Assert.hastext (file, "filename entry is not a valid document address");
① using Spring assertion classes for method-in-parameter detection
...
}

It can be seen that the simplicity of the method is improved with the use of Spring's Assert instead of the import parameter detection logic of the self-coding implementation. Assert does not depend on the Spring container, you can boldly use this tool class in your own application

--------------Code--------------

    • Import Org.apache.commons.lang.StringEscapeUtils;
    • Public class Escapestring {
    • public static void Main (string[] args) throws Exception {
    • String str = "China";
    • System.out.println ("The string after escaping with the Escapejava method is:" +stringescapeutils.escapejava (str));
    • System.out.println (thestring after which the Unescapejava method is reversed is: "+stringescapeutils.unescapejava (  Stringescapeutils.escapejava (str));
    • System.out.println ("The string after escaping with the Escapehtml method is:" +stringescapeutils.escapehtml (str));
    • System.out.println (thestring after which the Unescapehtml method is reversed is: "+stringescapeutils.unescapehtml (  Stringescapeutils.escapehtml (str));
    • System.out.println ("The string after escaping with the EscapeXML method is:" +stringescapeutils.escapexml (str));
    • System.out.println (thestring after which the Unescapexml method is reversed is: "+stringescapeutils.unescapexml (Stringescapeutils.escapexml (  STR));
    • System.out.println ("The string after escaping with the Escapejavascript method is:" +stringescapeutils.escapejavascript (str));
    • System.out.println (thestring after which the Unescapejavascript method is reversed is: "+stringescapeutils.unescapejavascript (  Stringescapeutils.escapejavascript (str));
    • /** output results are as follows:
    • The string after escaping with the Escapejava method is:/u4e2d/u56fd/u5171/u4ea7/u515a
    • The string after which the Unescapejava method is reversed is: China
    • The string after escaping with the Escapehtml method is: China
    • The string after which the Unescapehtml method is reversed is: China
    • The string after escaping with the EscapeXML method is: China
    • The string after which the Unescapexml method is reversed is: China
    • The string after escaping with the Escapejavascript method is:/u4e2d/u56fd/u5171/u4ea7/u515a
    • The string after which the Unescapejavascript method is reversed is: China */
    • }
    • }

[Tip]06. about how to prevent SQL injection, not using preprocessing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.