According to OWASP, the most critical type of vulnerability found in Web applications is the injection of some type of code, such as SQL injection, OS command injection, HTML injection, and so on.
These vulnerabilities are usually caused by a poor input validation by the application. In this recipe, we will cover some of the best practices when processing user inputs and constructing queries that make use of them.
filter_var
in PHP or the validation helper in ASP.NET. For example, an e-mail validation in PHP would be similar to this:function isValidEmail($email){ return filter_var($email, FILTER_VALIDATE_EMAIL); }
function isValidEmail (input) { var result=false; var email_regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+.)+[a-zA-Z0-9.-]{2,4}$/; if ( email_regex.test(input) ) { result = true; } return result; }
PHP with MySQLi:
$query = $dbConnection->prepare('SELECT * FROM table WHERE name = ?'); $query->bind_param('s', $name); $query->execute();
C#:
string sql = "SELECT * FROM Customers WHERE CustomerId = @CustomerId"; SqlCommand command = new SqlCommand(sql); command.Parameters.Add(new SqlParameter("@CustomerId", System.Data.SqlDbType.Int)); command.Parameters["@CustomerId"].Value = 1;
Java:
String custname = request.getParameter("customerName"); String query = "SELECT account_balance FROM user_data WHERE user_name =? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( );
xp_cmdshell
in MS SQL Server.The main part of preventing any kind of code injection attack is always a proper input validation, both on the client-side and server-side.
For SQL Injection also, always use parameterized or prepared queries instead of concatenating SQL sentences and inputs. Parameterized queries insert function parameters in specified places of an SQL sentence, eliminating the need for programmers to construct the query themselves, by concatenation.
In this recipe, we have used the language's built-in validation functions, but you can create your own if you need to validate some special type of input by using regular expressions.
Apart from doing a correct validation, we also need to reduce the impact of the compromise in case somebody manages to inject some code. This is done by properly configuring a user's privileges in the context of an operating system for a Web server and for both database and OS in the context of a database server.
The most useful tool when it comes to data validation is Regular Expressions; they also make the life of a penetration tester much easier when it comes to processing and filtering large amounts of information, so it is very convenient to have a good knowledge of them, I would recommend a couple of sites to take a look at:
13.58.51.36