PHP防篡改保护机制

```html PHP防篡改保护机制:保障核心文件与数据完整性

PHP防篡改保护机制

在Web应用安全中,防止关键PHP文件(如配置文件、核心类库、许可证模块)被恶意修改至关重要。本文介绍三种实用、轻量且可落地的防篡改保护机制。

1. 文件内容哈希校验(推荐)

对敏感文件生成SHA-256哈希值并定期比对,是最直接有效的防篡改手段。

<?php
// config/integrity_check.php
define('INTEGRITY_FILE', __DIR__ . '/integrity.json');
define('PROTECTED_FILES', [
    __DIR__ . '/config.php',
    __DIR__ . '/database.php',
    __DIR__ . '/vendor/autoload.php'
]);

function generateFileHashes(): array {
    $hashes = [];
    foreach (PROTECTED_FILES as $file) {
        if (file_exists($file)) {
            $hashes[basename($file)] = hash_file('sha256', $file);
        }
    }
    return $hashes;
}

function saveIntegrityManifest(): void {
    file_put_contents(INTEGRITY_FILE, json_encode(generateFileHashes(), JSON_PRETTY_PRINT));
}

function verifyIntegrity(): bool {
    if (!file_exists(INTEGRITY_FILE)) return false;
    $expected = json_decode(file_get_contents(INTEGRITY_FILE), true);
    foreach (PROTECTED_FILES as $file) {
        $name = basename($file);
        if (!isset($expected[$name])) continue;
        $actual = hash_file('sha256', $file) ?? '';
        if ($actual !== $expected[$name]) {
            error_log("[SECURITY] Tampering detected in {$file}");
            return false;
        }
    }
    return true;
}

// 启动时校验(建议放在入口文件 index.php 开头)
if (!verifyIntegrity()) {
    http_response_code(500);
    die('System integrity check failed. Please contact administrator.');
}
?>

2. 文件时间戳+权限双重锁定

结合文件修改时间与系统权限,防止非授权写入:

<?php
function lockCriticalFiles(array $files): void {
    foreach ($files as $file) {
        if (file_exists($file)) {
            // 设置只读(Linux/macOS)
            chmod($file, 0444);
            // 记录初始mtime(用于运行时比对)
            $mtime = filemtime($file);
            if ($mtime > time() - 3600) { // 1小时内修改?可疑!
                trigger_error("Unexpected recent modification to {$file}", E_USER_WARNING);
            }
        }
    }
}
?>

3. 运行时内存校验(高级防护)

在关键函数执行前动态校验自身代码完整性:

<?php
function guardFunction(string $funcName): void {
    $ref = new ReflectionFunction($funcName);
    $source = file_get_contents($ref->getFileName());
    $start = strpos($source, 'function ' . $funcName);
    $end = strpos($source, '}', $start);
    $body = substr($source, $start, $end - $start + 1);
    $hash = hash('sha256', $body);
    // 对比预存白名单哈希(从加密配置加载)
    $whitelist = require __DIR__ . '/hash_whitelist.php';
    if (!isset($whitelist[$funcName]) || $whitelist[$funcName] !== $hash) {
        throw new RuntimeException("Critical function '{$funcName}' has been tampered!");
    }
}
?>
⚠️ 重要提醒:所有校验逻辑应部署在可信环境;哈希清单需通过安全渠道分发;生产环境禁用eval()create_function();配合Web服务器文件权限控制(如chown www-data:www-data + chmod 644)效果更佳。

防篡改不是“一劳永逸”,而是持续验证的过程。将哈希校验集成至CI/CD流程、配合日志审计与入侵检测,才能构建纵深防御体系。

```