IBM DB Boolean based blind sql injection

This attack is applicable to IBM DB database in your server. SQL Injection is a kind of method used by hackers to access, modify and delete the data inside the database. By leveraging SQL Injection hackers will also be able to bypass authentication and access unauthorized data from databases. In some cases, it can even be used to execute commands on the operating system, potentially allowing an attacker to escalate to more damaging attacks inside the network where the application is hosted. Based on different strategies used by the hackers for injecting the SQL commands there are different categories like In Band SQL Injection, Inferential SQL Injection and Out of band SQL injection. Boolean based SQL injection is a kind of Inferential SQL Injection.

Boolean based SQL Blind Injection

It is a technique which relies on sending an SQL query to the database which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result. Depending on the result, the content within the HTTP response will change, or remain the same. This allows an attacker to infer if the payload used returned true or false, even though no data from the database is returned. Even though it is a slow attack this will help the hacker to enumerate the database.

Example

http://newspaper.com/items.php?id=2

A vulnerable data access layer of an application can build an SQL query as shown below from the above URL request.

      SELECT title, description, body FROM items WHERE ID = 2 and 1=2

   

If the application is vulnerable to SQL injection probably it will not return anything and the hacker will next inject a query with a true condition (1=1). If the content of the page is different than the page that returned during false condition, then the hacker is able to infer that, SQL injection is working. Now the hacker is able to verify it he all set to use other SQL Injection methods.

Impact

Depending on the back-end database configuration, its privilege setup and the operating system, a hacker can mount one or more of the following type of attacks :

  • Reading, updating and deleting arbitrary data/tables from the database
  • Executing commands on the underlying operating system

Mitigation / Precaution

Primary Defenses:

  • Use of Prepared Statements (with Parameterized Queries)
  • Use of Stored Procedures
  • White List Input Validation
  • Escaping All User Supplied Input

Additional Defenses:

  • Also: Enforcing Least Privilege
  • Also: Performing White List Input Validation as a Secondary Defense

Unsafe Example

SQL injection flaws typically look like this:

The following (Java) example is UNSAFE and is a typical example.

      String query = "SELECT ex_bal FROM usr_dt WHERE usr_nme = "
      + request.getParameter("cusName");
      
      try {
         Statement stat = connection.createStatement(  );
         ResultSet reslt = statement.executeQuery( query );
      }

   

Primary Defenses

Defense Option 1: Prepared Statements (with Parameterized Queries)

In a prepared statement with the parameterized query, the developer has to define all the SQL code and then pass in each parameter to the query later. This helps the database to differentiate between code and data, regardless of the input.

This statement prevents an attacker from changing the intent of a query even if SQL commands are inserted by him.

Language Specific Recomandations

  • Java EE – PreparedStatement() using variables.
  • PHP – PDO using bindParam()
  • .NET – Use SqlCommand() or OledDbCommand() using bind variables.
  • SQLite – Use sqlite3_prepare() to create a statement object.
  • Hibernate – Use CreateQuery() with bind variables

Safe Java Prepared Statement Example

      String custname = request.getParameter("custName");
      // perform input validation to detect attacks
      String query = "SELECT acc_bal FROM usr_dat WHERE usr_nme = ? ";
      
      PreparedStatement p = connection.prepareStatement( query );
      p.setString( 1, custname);
      ResultSet res = p.executeQuery( );

   

Safe C# .NET Prepared Statement Example

      String query = "SELECT acc_bal FROM usr_dat WHERE usr_nme = ?";
      try {
         OleDbCommand comm = new OleDbCommand(query, connection);
         comm.Parameters.Add(new OleDbParameter("custName", CustName Name.Text));
         OleDbDataReader rdr = comm.ExecuteReader();
         // …
      } catch (OleDbException se) {
         // error handling
      }

   

Hibernate Query Language (HQL) Examples

      Query unsafHQLQry = session.createQuery("from Inventory where productID='"+userSuppliedParameter+"'");
      
      Query safHQLQry = session.createQuery("from Inventory where productID=:productid");
      safHQLQry.setParameter("productid", userSuppliedParameter);

   

Defense Option 2: Stored Procedures

Stored procedures are not always trustworthy in all types of SQL injecton. A stored procedure gives the same effect of a parameterized querry, if it is implemented correctly. A stored procedure language requires the developer to build SQL statements with parameters. SQL code for a stored procedure is defined and stored in the database itself. This is then called from the application. Both of these techniques have the same effectiveness. The implementation is dependent on your organization.

Safe Java Stored Procedure Example

      String custnme = request.getParameter("custName"); // This should REALLY be validated
      try {
         CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance(?)}");
         cs.setString(1, custname);
         ResultSet res = cs.executeQuery();     
         // … result set handling
      } catch (SQLException se) {           
         // … logging and error handling
      }

   

Safe VB .NET Stored Procedure Example

   Try
      Dim command As SqlCommand = new SqlCommand("sp_getAccBal", connection)
      command.CommandType = CommandType.StoredProcedure
      command.Parameters.Add(new SqlParameter("@CustName", CustName.Text))
      Dim reader As SqlDataReader = command.ExecuteReader()
      ‘ …
   Catch se As SqlException
      ‘ error handling
   End Try

   

Defense Option 3: White List Input Validation

There are many non legal locations for the use of bind variables., such as the names of tables or columns and sort order indicator. For this, whitelist input validation is the most appropriate defense. The name of tables or columns are usually extracted from code and not from user parameters. But, it uses parameter values are used instead of this, then parameter values should be mapped to the legal expected table or column names to make sure invalidated user input doesn’t get run in the query.

      String tabNam;
      switch(PARAM):
      case "Value1": tabNam = "fooTable";
                     break;
      case "Value2": tabNam = "barTable";
                     break;
         ...
      default      : throw new InputValidationException("unexpected value provided for table name");

   

For a sort order, it is best if the user supplied input is converted into boolean, and then that boolean is used to select the safe value to append to the query. This is important in dynamic query creation. For example:

      public String someMethod(boolean sortOrder) {
      
      String SQLquery = "some SQL ... order by Salary " + (sortOrder ? "ASC" : "DESC");

   

Defense Option 4: Escaping All User-Supplied Input

This technique is used, if any other injection prevention techniques are unusable. It is probably a better choice even though, the methodology is weak compared to the defenses and cannot guarantee it will prevent al SQL injection in all situations. This is usually recommended to retrofit legacy code when implementing input validation isn’t effective.

In this technique, each DBMS supports one or more characters escaping schemes specific to certain kinds of queries. If admin logs in then escape all user supplied input using the proper escaping scheme for the database. The DBMS will not confuse that input with SQL code written b the developer, thus avoiding any possible SQL injection vulnerabilities.

Latest Articles