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. Contact administrator.');
}
?>

2. 文件只读权限 + 时间戳锁定

结合系统级防护:部署后将关键文件设为只读,并记录最后合法修改时间。

// 部署后执行一次(CLI)
shell_exec('chmod 444 config.php database.php');
file_put_contents('.last_valid_update', date('c')); // 记录可信时间点

// 运行时校验
if (filemtime('config.php') > strtotime(file_get_contents('.last_valid_update'))) {
    trigger_error('Critical file modified after deployment!', E_USER_ERROR);
}

3. 签名式配置加载(高安全场景)

使用私钥签名配置内容,运行时用公钥验证,杜绝未授权变更。

<?php
// 加载前验证签名(需提前生成密钥对)
$config = file_get_contents('config.php.enc');
$signature = file_get_contents('config.php.sig');
$pubKey = openssl_pkey_get_public(file_get_contents('public.key'));

if (!openssl_verify($config, $signature, $pubKey, OPENSSL_ALGO_SHA256)) {
    throw new RuntimeException('Config signature verification failed!');
}
return unserialize($config);
?>
⚠️ 重要提醒: 防篡改 ≠ 防入侵。请务必配合其他安全措施:禁用危险函数(eval, system)、启用Open_basedir、定期审计日志、使用Web应用防火墙(WAF)。哈希清单应存储在Web根目录外,且禁止通过HTTP直接访问。

三者可组合使用:日常用哈希校验 + 部署后加锁 + 核心License模块启用数字签名。安全是纵深防御的艺术——没有银弹,只有层层加固。

```