Source Code Analysis SQL Injection


Slack Group

Before we get started I have started a slack group dedicated to hacking. We welcome everyone from beginner to advanced to join. I will be on everyday answer questions, doing CTFs, and talking about cool hacks. If you enjoy hacking and are looking for like minded people join below:

NEW Hacking Group Slack Channel

Introduction

SQL injection has been around since the begging of time. It has consistently been on the OWASP top 10 list and shows no signs of slowing down. Almost every application interacts with a back end database in some way so it’s no surprise that its one of the most popular vulnerabilities out there. When doing a black box engagement you might place a or mark every where to see if the page errors out, if it does you most likely got SQL injection. If you have access to the source code you will go about finding this a little differently.

String Concatenation

So many vulnerabilities are caused by string concatenation. Buffer overflows, XSS, SQL Injection, and a lot of other vulnerabilities can arise when you improperly combine strings together.

buffer_Overflow = string1 + user_supplied_string

XSS = string1 + user_supplied_string + string2

SQL_Injection = string1 + user_supplied_string + string2

If you ever see user supplied input being combined with a string you should always take a second and check for known vulnerabilities.

SQL Injection Basics

SQL injection occurs when user supplied input is improperly passed to the back end database. If you’r looking for SQL injection in source code one of the first things I look for is common SQL strings as shown below:

SELECT column_name from table_name where username = user_input

UPDATE column_name set column_name = "s" where username = user_input

I often find myself grepping for the word “SELECT” which will normally show you the majority of the database calls. It really doesn’t matter what programming language the application uses SQL injection can be found in anything that communicates with a database.

Another technique is to search for common function names. Every program language has specific functions which are used to communicate with the backend database. Instead of searching for common database strings you can search for common functions which are used to communicate with a database. For example PHP uses the “mysql_query” function to make database calls. So if your dealing with an PHP application you can search for that specific function which should point you in the right direction. There are several other functions as well and SQL injection isn’t limited to just MYSQL.

As I mentioned earlier string concatenation can lead to all kinds of problems. If you see user supplied input being concatenated with a database query you most likely got SQL injection as shown below:

def search():
    code = request.args.get('code')
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    try:
        statement = "select * from data where data='" + code + "'"
        c.execute(statement)
        found = c.fetchall()
        if found == []:
            return f"Invalid Code<br>{statement}"
        else:
            return f"Wifi Connection Established<br>{statement}"
    except sqlite3.Error as e:
        return str(e) + f"<br>{statement}

The above code is written in python. One of the first things you want to do is identify user supplied input. As you can see we can pass a GET parameter called “code” which will be saved to a variable.

code = request.args.get('code')

The next step is to identify if this variable is being improperly passed to a database query string which it is as shown below:

statement = "select * from data where data='" + code + "'"

You can clearly see the variable “code” is being combined with the query string. There is no sanitization checks or anything like that. This is a strong indicated of SQL injection.

Example

For this example i’m going to be using PHP code from:

https://github.com/bchazalet/web-app-security-examples/tree/master/sql-injection-examples

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php echo '<p>SQL injection demo 1</p>'; ?>
    <?php
      $con = mysql_connect("localhost","sqli","sqli");
      if (!$con) {
        die('Could not connect: ' . mysql_error());
      }
      mysql_select_db("sqliexample", $con);
      $id = $_GET['id']; // No input validation!!
      $result = mysql_query("SELECT name FROM user WHERE id=$id", $con);
    
      mysql_close($con);
      $num = mysql_num_rows($result);
      $i=0;
      while ($i < $num) {
        $name = mysql_result($result, $i, "name");
        echo "Hello " . $name;
        echo "<br/>";
        $i++;
      }
    ?>

  </body>
</html>

Now that you know what to look for this vulnerability to jump out at you. You can clearly see that user supplied input is being passed to a database string as shown below:

      $id = $_GET['id']; // No input validation!!
      $result = mysql_query("SELECT name FROM user WHERE id=$id"

This may be a PHP application but it looks identically to the python example we previously worked through. We have user supplied input being passed directly to a database query string with out validation. This application is clearly vulnerable to sql injection.

Conclusion

SQL injection is one of the oldest and most popular vulnerabilities out there. If you have access to the applications source code finding this vulnerability can be very easy. If you see user supplied input being combined with a database query string you most likely got SQL injection.

Leave a Reply

Your email address will not be published. Required fields are marked *