How to do it...

  1. The first thing to do in order to prevent injection attacks is to properly validate inputs. On the server side, this can be done by writing your own validation routines, although the best option is using the language's own validation routines, as they are more widely used and tested. A good example is filter_var in PHP or the validation helper in ASP.NET. For example, an email validation in PHP would look similar to this:
function isValidEmail($email){  
    return filter_var($email, FILTER_VALIDATE_EMAIL); 
} 
  1. On the client side, validation can be achieved by creating JavaScript validation functions, using regular expressions. For example, an email validation routine would be as follows:
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; 
} 
  1. For SQL Injection, it is also useful to avoid concatenating input values to queries. Instead, you should use parameterized queries, also called prepared statements. Each programming language has its own version:
    • 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( );
  1. Following a Defense in Depth approach, it is also useful to restrict the amount of damage that can be done in case an injection is successful. To do this, use a low-privileged system user to run the database and web servers. Make sure that the user that the applications allow to connect to the database server is not a database administrator.
  2. Disable or delete the stored procedures and commands that allow an attacker to execute system commands or escalate privileges, such as xp_cmdshell in MS SQL Server.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151