PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

SQL injection

A malicious user experiments on a form to gain information about a database. The SQL query ignores everything after the # and successfully returns all records!
 
<form method="POST">
    <input type="text" name="username" value="username' OR 1 = 1 #"/>
    <input type="password" name="password" />
    <input type="submit" name="btn_submit" value="Log In"/>
</form>
 
if (isset($_POST['btn_submit'])) {

    // no database filtering
    $username = $_POST['username'];
    $password = md5($_POST['password']);
    $sql = "
        SELECT * FROM users 
        WHERE username='{$username}' AND password='{$password}'
    ";

    echo $sql; 
        // SELECT * FROM users 
        // WHERE username='username' OR 1 = 1 #' AND ...
... 6 lines
 
Defence - filter input
 
if (isset($_POST['btn_submit'])) {
    
    // driver-specific db filtering
    $username = mysql_escape_string($_POST['username']);
    $password = md5(mysql_escape_string($_POST['password']));
    $sql = "
        SELECT * FROM users 
        WHERE username='{$username}' AND password='{$password}'
    ";
    
    echo $sql; 
        // Will add slashes to username quote
        // resulting in SQL syntax error 
}
... 7 lines
 

Bind parameters

To escape output for an SQL query, use the driver-specific *_escape_string() functions. If possible, use bound parameters. Use a placeholder like ? and provide the actual values using a separate API call.

Two reasons

There are, two good reasons to use bind parameters in programs: Bind variables are the best way to prevent SQL injection. Not using bind parameters is like recompiling a program every time.
Questions    
Session fixation

        A B C D E F
🔔
1/1