This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org
Difference between revisions of "Injection Prevention Cheat Sheet"
m (Minor) |
m (added syntaxhighlight lang="java") |
||
Line 108: | Line 108: | ||
; Safe Java Prepared Statement Example | ; Safe Java Prepared Statement Example | ||
The following code example uses a PreparedStatement, Java's implementation of a parameterized query, to execute the same database query. | The following code example uses a PreparedStatement, Java's implementation of a parameterized query, to execute the same database query. | ||
− | + | <syntaxhighlight lang="java"> String custname = request.getParameter("customerName"); // This should REALLY be validated too // perform input validation to detect attacks String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; '''PreparedStatement pstmt = connection.prepareStatement( query );''' '''pstmt.setString( 1, custname);''' ResultSet results = pstmt.executeQuery( ); </syntaxhighlight> | |
We have shown examples in Java, but practically all other languages, including Cold Fusion, and Classic ASP, support parameterized query interfaces. | We have shown examples in Java, but practically all other languages, including Cold Fusion, and Classic ASP, support parameterized query interfaces. | ||
; Safe Java Stored Procedure Example | ; Safe Java Stored Procedure Example | ||
The following code example uses a CallableStatement, Java's implementation of the stored procedure interface, to execute the same database query. The "sp_getAccountBalance" stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. | The following code example uses a CallableStatement, Java's implementation of the stored procedure interface, to execute the same database query. The "sp_getAccountBalance" stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. | ||
− | + | <syntaxhighlight lang="java"> String custname = request.getParameter("customerName"); // This should REALLY be validated try { '''CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance(?)}");''' '''cs.setString(1, custname);''' ResultSet results = cs.executeQuery(); // … result set handling } catch (SQLException se) { // … logging and error handling } </syntaxhighlight> | |
|} | |} | ||
Line 145: | Line 145: | ||
|'''Safe Java for LDAP escaping Example:''' | |'''Safe Java for LDAP escaping Example:''' | ||
− | < | + | <syntaxhighlight lang="java"> public String escapeDN (String name) { //From RFC 2253 and the / character for JNDI final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'}; String escapedStr = new String(name); //Backslash is both a Java and an LDAP escape character, so escape it first escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\"); //Positional characters - see RFC 2253 escapedStr = escapedStr.replaceAll("\^#","\\\\\\\\#"); escapedStr = escapedStr.replaceAll("\^ | $","\\\\\\\\ "); for (int i=0;i < META_CHARS.length;i++) { escapedStr = escapedStr.replaceAll("\\\\"+META_CHARS[i],"\\\\\\\\" + META_CHARS[i]); } return escapedStr; }</syntaxhighlight> |
Note, that the backslash character is a Java String literal and a regular expression escape character. | Note, that the backslash character is a Java String literal and a regular expression escape character. | ||
− | public String escapeSearchFilter (String filter) { //From <nowiki>RFC 2254</nowiki> String escapedStr = new String(filter); escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\5c"); escapedStr = escapedStr.replaceAll("\\\\\*","\\\\\\\\2a"); escapedStr = escapedStr.replaceAll("\\\\(","\\\\\\\\28"); escapedStr = escapedStr.replaceAll("\\\\)","\\\\\\\\29"); escapedStr = escapedStr.replaceAll("\\\\"+Character.toString('\\u0000'), "\\\\\\\\00"); return escapedStr; } | + | <syntaxhighlight lang="java"> public String escapeSearchFilter (String filter) { //From <nowiki>RFC 2254</nowiki> String escapedStr = new String(filter); escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\5c"); escapedStr = escapedStr.replaceAll("\\\\\*","\\\\\\\\2a"); escapedStr = escapedStr.replaceAll("\\\\(","\\\\\\\\28"); escapedStr = escapedStr.replaceAll("\\\\)","\\\\\\\\29"); escapedStr = escapedStr.replaceAll("\\\\"+Character.toString('\\u0000'), "\\\\\\\\00"); return escapedStr; } </syntaxhighlight> |
|} | |} | ||
Line 188: | Line 188: | ||
'''''Correct Usage''''' | '''''Correct Usage''''' | ||
− | Here is an example that starts a process with a modified working directory. The command and each of the arguments are passed separately. This make it easy to validated each term and reduces the risk to insert malicious strings. | + | Here is an example that starts a process with a modified working directory. The command and each of the arguments are passed separately. This make it easy to validated each term and reduces the risk to insert malicious strings. |
− | ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "TrustedArg1", "TrustedArg2"); Map<String, String> env = pb.environment(); pb.directory(new File("TrustedDir")); Process p = pb.start(); | + | |
+ | <syntaxhighlight lang="java"> | ||
+ | ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "TrustedArg1", "TrustedArg2"); | ||
+ | |||
+ | Map<String, String> env = pb.environment(); | ||
+ | |||
+ | pb.directory(new File("TrustedDir")); | ||
+ | |||
+ | Process p = pb.start(); | ||
+ | </syntaxhighlight> | ||
|} | |} | ||
Revision as of 12:46, 25 November 2017
Last revision (mm/dd/yy): 11/25/2017
IntroductionThis article is focused on providing clear, simple, actionable guidance for preventing the entire category of Injection flaws in your applications. Injection attacks, especially SQL Injection, are unfortunately very common. Application accessibility is a very important factor in protection and prevention of injection flaws. Only the minority of all applications within a company/enterprise are developed in house, where as most applications are from external sources. Open source applications give at least the opportunity to fix problems, but closed source applications need a different approach to injection flaws. Injection flaws occur when an application sends untrusted data to an interpreter. Injection flaws are very prevalent, particularly in legacy code, often found in SQL queries, LDAP queries, XPath queries, OS commands, program arguments, etc. Injection flaws are easy to discover when examining code, but more difficult via testing. Scanners and fuzzers can help attackers find them. Depending on the accessibility different actions must be taken in order to fix them. It is always the best way to fix the problem in source code itself, or even redesign some parts of the applications. But if the source code is not available or it is simply uneconomical to fix legacy software only virtual patching makes sense. Application TypesThree classes of applications can usually be seen within a company. Those 3 types are needed to identify the actions which need to take place in order to prevent/fix injection flaws. A1: New ApplicationA new web application in the design phase, or in early stage development. A2: Productive Open Source ApplicationAn already productive application, which can be easily adapted. A Model-View-Controller (MVC) type application is just one example of having a easily accessible application architecture. A3: Productive Closed Source ApplicationA productive application which cannot or only with difficulty be modified. Forms of InjectionThere are several forms of injection targeting different technologies including SQL queries, LDAP queries, XPath queries and OS commands. Query languagesThe most famous form of injection is SQL Injection where an attacker can modify existing database queries. For more information see the SQL Injection Prevention Cheat Sheet. But also LDAP, SOAP, XPath and REST based queries can be susceptible to injection attacks allowing for data retrieval or control bypass. SQL InjectionAn SQL injection attack consists of insertion or "injection" of either a partial or complete SQL query via the data input or transmitted from the client (browser) to the web application. A successful SQL injection attack can read sensitive data from the database, modify database data (insert/update/delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file existing on the DBMS file system or write files into the file system, and, in some cases, issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands. SQL Injection attacks can be divided into the following three classes:
LDAP InjectionLDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements through techniques similar to SQL Injection. LDAP injection attacks could result in the granting of permissions to unauthorized queries, and content modification inside the LDAP tree. For more information on LDAP Injection attacks, visit LDAP injection. LDAP injection attacks are common due to two factors:
XPath InjectionScripting languagesAll scripting languages used in web applications have a form of an eval call which receives code at runtime and executes it. If code is crafted using unvalidated and unescaped user input code injection can occur which allows an attacker to subvert application logic and eventually to gain local access. Every time a scripting language is used, the actual implementation of the 'higher' scripting language is done using a 'lower' language like C. If the scripting language has a flaw in the data handling code 'Null Byte Injection' attack vectors can be deployed to gain access to other areas in memory, which results in a successful attack. Operating System (OS) CommandsOS command injection is a technique used via a web interface in order to execute OS commands on a web server. The user supplies operating system commands through a web interface in order to execute OS commands. Any web interface that is not properly sanitized is subject to this exploit. With the ability to execute OS commands, the user can upload malicious programs or even obtain passwords. OS command injection is preventable when security is emphasized during the design and development of applications.
Network ProtocolsWeb applications often communicate with network daemons (like SMTP, IMAP, FTP) where user input becomes part of the communication stream. Here it is possible to inject command sequences to abuse an established session. Injection Prevention RulesRule #1 (Perform proper input validation):Perform proper input validation. Positive or “whitelist” input validation with appropriate canonicalization is also recommended, but is not a complete defense as many applications require special characters in their input. Rule #2 (Use a safe API):The preferred option is to use a safe API which avoids the use of the interpreter entirely or provides a parameterized interface. Be careful of APIs, such as stored procedures, that are parameterized, but can still introduce injection under the hood. Rule #3 (Contextually escape user data):If a parameterized API is not available, you should carefully escape special characters using the specific escape syntax for that interpreter. Other Injection Cheatsheets SQL Injection Prevention Cheat Sheet Other Cheatsheets |