`

Preventing SQL Injection in Java

 
阅读更多

Preventing SQL Injection in Java

 
 

Contents

 [hide

Status

Released 14 Jan 2008

Overview

As the name implies, SQL injection vulnerabilities allow an attacker to inject (or execute) SQL commands within an application. It is one of the most wide spread and dangerous application vulnerability. The CLASP project provides a good overview of SQL injection.

Example of SQL injection

The following Java servlet code, used to perform a login function, illustrates the vulnerability by accepting user input without performing adequate input validation or escaping meta-characters:

conn = pool.getConnection( );
String sql = "select * from user where username='" + username +"' and password='" + password + "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
loggedIn = true;
	out.println("Successfully logged in");
} else {
	out.println("Username and/or password not recognized");
}

It is possible for attackers to provide a username containing SQL meta-characters that subvert the intended function of the SQL statement. For example, by providing a username of:

admin' OR '1'='1

and a blank password, the generated SQL statement becomes:

select * from user where username='admin' OR '1'='1' and password=' '

This allows an attacker to log in to the site without supplying a password, since the ‘OR’ expression is always true. Using the same technique attackers can inject other SQL commands which could extract, modify or delete data within the database.

Attack techniques

For more information on SQL injection attacks see:

Defense Strategy

To prevent SQL injection:

  • All queries should be parametrized.
  • All dynamic data should be explicitly bound to parametrized queries.
  • String concatenation should never be used to create dynamic SQL.

For more details, see the OWASP SQL Injection Prevention Cheat Sheet.

Parameterized Queries

All data access techniques provide some means for escaping SQL meta-characters automatically. The following sections detail how to perform input validation and meta-character escaping using popular data access technologies.

Prepared Statements

Variables passed as arguments to prepared statements will automatically be escaped by the JDBC driver.
Example: ps.1

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

Although Prepared Statements helps in defending against SQL Injection, there are possibilities of SQL Injection attacks through inappropriate usage of Prepared Statements. The example below explains such a scenario where the input variables are passed directly into the Prepared Statement and thereby paving way for SQL Injection attacks. 
Example: ps.2

String strUserName = request.getParameter("Txt_UserName"); 
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");

Stored Procedures

TODO

Hibernate

According to this forum thread hibernate uses prepared statements, so it is protected from direct sql injection, but it could still be vulnerable to injecting HQL statements.

Variable Binding

It is critical to use Bind Variables as mentioned in the example ps.1 above. Usage of PreparedStatement with Bind variables defends SQL Injection attacks and improves the performance.

 

Dynamic Queries via String Concatenation

The important thing to remember is to never construct SQL statements using string concatenation of unchecked input values. Creating of dynamic queries via the java.sql.Statement class leads to SQL Injection.

References

分享到:
评论

相关推荐

    SQL注入文献.zip

    4. **2017-一种新颖的防止SQL注入方法**(2017-A Novel Method for Preventing SQL Injection.pdf):该文献介绍了一种新的防御技术,可能涉及动态SQL参数化、输入验证或使用安全的数据库接口,以防止恶意SQL注入。...

    SQL Prompt_9.5.2.9464 含注册机

    Fixed an issue which was preventing SQL Prompt from launching when upgrading from a previous version. SP-7560 : Fixed an issue which would sometimes cause unwanted newlines to be inserted into scripts...

    Preventing bit stuffing in CAN Using bit-stuffing distributions in CAN analysis

    在"Preventing bit stuffing in CAN"这篇论文中,作者探讨了如何在CAN分析中有效地预防比特位填充错误。这些错误可能由于硬件设计缺陷、软件实现错误或者电磁干扰等因素导致。论文可能涉及了错误检测和恢复策略,如...

    Pro PHP Security(Pro)

    3. **Preventing SQL Injection Attacks**: SQL injection is a common attack vector that involves inserting malicious SQL statements into input fields. The book offers strategies for sanitizing input and...

    java面试题英文版及其答案

    In Java, encapsulation is achieved by declaring class members as private, preventing direct access from outside the class. Public methods (getters and setters) are then provided to manipulate these ...

    SQL21日自学通

    Using Reserved Words in Your SQL statement 486 The Use of DISTINCT When Selecting Multiple Columns487 Dropping an Unqualified Table 487 The Use of Public Synonyms in a Multischema Database488 The ...

    entlibcontrib2009-05src_sample

    4. High security level, preventing from SQL Injection Attack. 5. Other features. System Requirements * Supported Operating Systems: Windows Server 2003; Windows Vista; Windows XP Note: If you ...

    反虚拟货币诈骗资料素材-Preventing-Financial-Crime-in-Cryptoassets

    报告“Preventing Financial Crime in Cryptoassets”关注的是如何在虚拟货币领域防止金融犯罪,特别是针对非法资金流动的调查。这份资料对于执法机构来说是至关重要的工具,因为它详细介绍了多种涉及虚拟货币的诈骗...

    微软内部资料-SQL性能优化3

    An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the ...

    modsecurity handbook

    They can be very effective in preventing application security attacks, such as cross-site scripting, SQL injection, remote file inclusion, and others. Considering that most web sites today suffer ...

    Improving neural networks by preventing co-adaptation of feature detectors

    Hinton在2012年提出的Improving neural networks by preventing co-adaptation of feature detectors也就是dropout,常用于防止训练过拟合,主要是通过随机选择一部分神经元训练,而直接丢弃其他神经元.

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    2.5.1. Referencing XML configuration in JavaConfig 2.5.2. Referencing JavaConfig in XML configuration 2.6. Summary Chapter 3. Advanced wiring 3.1. Environments and profiles 3.1.1. Configuring profile ...

    11g_plsql_user_guide_and_reference.pdf

    ### PL/SQL Features in Oracle 11g Release 1 (11.1) #### Enhancements to Regular Expression Built-In SQL Functions In Oracle 11g Release 1, the regular expression built-in SQL functions have been ...

    vue-springboot高中信息技术课程在线测试系统java毕业论文.docx

    Its structured query language (SQL) support makes it easy to retrieve, update, and manage the various types of information stored in the system. To ensure security, the system should implement ...

    preventing reverse.pdf

    对于Android应用而言,通常涉及到将APK文件中的Dalvik字节码(.dex文件)转换成Java源代码。 - **调试**:是指开发者通过特殊工具对程序进行逐步执行,以检查其内部状态的过程。在Android环境中,开发者可以利用...

    Beginning PHP 5.3

    - **Preventing SQL Injection:** Techniques for preventing SQL injection attacks when handling form data. **Chapter 10: Preserving State With Query Strings, Cookies, and Sessions** - **Session ...

    Laravel开发-sanitization-filters .zip

    4. **Preventing SQL Injection** - 使用Eloquent ORM或者`DB`类的查询构造器,Laravel会自动防止SQL注入,因为它会自动转义参数。 - 避免直接使用`raw` SQL查询,除非你确信输入是安全的,并且使用了参数绑定。 ...

    SCJP6 Sun Certificated Programmer for Java 6 Study Guide (Exam 310-065) 英文原版

    In the first chapter, the focus is on understanding declarations and access control within Java. Key concepts include: - **Variable Declarations**: This section covers the basics of declaring ...

    数学建模-2005 C O Preventing the Hydrocalypse获奖作品.zip

    《数学建模-2005 C O Preventing the Hydrocalypse获奖作品》是一个与数学建模相关的压缩包,其中包含了一份2005年的获奖论文。这份论文的主题是“防止水灾末日”(Preventing the Hydrocalypse),明显是针对水资源...

Global site tag (gtag.js) - Google Analytics