UNION-Based

The UNION command in SQL is meant to join a query which allows you to two queries as long as the number of columns line up between the two tables. In SQL injection, the purpose is to forge part of the query so it pulls data from somewhere else.

For example:

SELECT ID, Account, Password FROM Users WHERE uname = $uname

This is a basic query.
If want to gather info from another table, say SSNs, we can put in something like this:

SELECT ID, Account, Password FROM Users WHERE uname = 1 UNION ALL SELECT SSN,1,1 FROM SSNTable

As you can see, the columns match up. In the original query there were 3 columns (ID, Account, Password) and in the malicious query it’s SSN,1,1. 1,1 won’t return anything but the SSN parameter should if that column exists in that table.

In Mutillidae, this can be exploited.

At the user lookup page, we enter the username as a query:

 'union select null --

sql6.PNG

And we get a syntax error

sql5

As you can see, the error message is the SELECT statements have a different number of columns, so this is now a matter of entering enough nulls so the columns align.

The magic number was 7. The query looked like this

' union select null,null,null,null,null,null,null --

sql7.PNG

Next is fuzzing to see how the columns line up. Just  because there’s 7 columns doesn’t mean they will all appear, as you can see there’s only three that show up. Replacing null with 1 should show how the columns align.

sql8.PNG

So replacing the first null with 1 didn’t show up. Let’s try the second.

sql9.PNG

There it is! So now what? Well there’s a lot.

Variable/Function Output
@@hostname : Current Hostname
@@tmpdir : Tept Directory
@@datadir : Data Directory
@@version : Version of DB
@@basedir : Base Directory
user() : Current User
database() : Current Database
version() : Version
schema() : current Database
UUID() : System UUID key
current_user() : Current User
current_user : Current User
system_user() : Current Sustem user
session_user() : Session user
@@GLOBAL.have_symlink : Check if Symlink Enabled or Disabled
@@GLOBAL.have_ssl : Check if it have ssl or not
Source: http://securityidiots.com/Web-Pentest/SQL-Injection/Basic-Union-Based-SQL-Injection.html

If we enter @@version instead of 1 we get the version of the DB

sql10.PNG

and so on.