萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP HTML 屬性過濾器:白名單機制防 XSS 保留合法屬性

一、核心需求

用戶提交的 HTML 內容(如富文本編輯器輸出)需過濾危險屬性(onclick、onload、style 等),同時保留安全屬性(class、id、href、src 等)。

二、HtmlAttributeFilter 類設計

核心功能:

  • 白名單機制:全局允許屬性 + 標籤級特例白名單
  • 忽略標籤:完全跳過特定標籤的屬性過濾
  • 白名單保護:佔位符替換法保護白名單內容不被誤刪

三、完整類實現

<?php
/**
 * HTML 屬性過濾器
 * 基於正則解析,支持白名單、特例、忽略標籤
 */
class HtmlAttributeFilter {
    private $_str = '';
    private $_allow = [];      // 全局允許屬性:['class', 'id', 'title']
    private $_exception = [];  // 標籤特例:['a'=>['href','target'], 'img'=>['src','alt']]
    private $_ignore = [];     // 忽略標籤:['script', 'style']
    private $_LTAG = '[[##';   // 白名單保護佔位符前綴
    private $_RTAG = '##]]';   // 白名單保護佔位符後綴

    public function setAllow(array $attrs) { $this->_allow = $attrs; }
    public function setException(array $exceptions) { $this->_exception = $exceptions; }
    public function setIgnore(array $tags) { $this->_ignore = $tags; }

    /** 主入口:過濾 HTML 字符串
     * @param string $html 原始 HTML
     * @return string 過濾後 HTML
     */
    public function strip($html) {
        $this->_str = $html;
        if (!is_string($this->_str) || $this->_str === '') return $this->_str;

        $this->_str = strtolower($this->_str); // 統一小寫處理
        $elements = $this->findElements();
        if (is_string($elements)) return $elements; // 無標籤直接返回

        $nodes = $this->findAttributes($elements);
        $this->removeAttributes($nodes);
        return $this->_str;
    }

    /** 尋找所有標籤:返回 [標籤名 => [完整標籤字符串, 屬性字符串]] */
    private function findElements() {
        $nodes = [];
        // 匹配   不匹配   
        if (preg_match_all('/<([^!\/\s>]+)([^>]*)>/i', $this->_str, $matches)) {
            foreach ($matches[1] as $i => $tag) {
                $attrStr = $matches[2][$i];
                if ($attrStr !== '') {
                    $nodes[strtolower($tag)][] = [$matches[0][$i], $attrStr];
                }
            }
        }
        return $nodes;
    }

    /** 解析屬性字符串為鍵值對 */
    private function findAttributes($elements) {
        $result = [];
        foreach ($elements as $tag => $list) {
            foreach ($list as $item) {
                $fullTag = $item[0];
                $attrStr = $item[1];
                $attrs = [];
                // 匹配 attr="value" attr='value' attr=value 無引號
                preg_match_all('/(\w+)\s*=\s*(".*?"|\'.*?\'|\S+)/', $attrStr, $attrMatches);
                foreach ($attrMatches[1] as $j => $name) {
                    $attrs[strtolower($name)] = $attrMatches[2][$j];
                }
                $result[] = [$tag, $fullTag, $attrs];
            }
        }
        return $result;
    }

    /** 核心過濾邏輯 */
    private function removeAttributes($nodes) {
        foreach ($nodes as $node) {
            list($tag, $fullTag, $attrs) = $node;
            
            // 忽略標籤直接跳過
            if (in_array($tag, $this->_ignore)) continue;

            $newAttrs = [];
            foreach ($attrs as $name => $value) {
                $keep = false;
                // 1. 全局白名單
                if (in_array($name, $this->_allow)) $keep = true;
                // 2. 標籤特例白名單
                if (isset($this->_exception[$tag]) && in_array($name, $this->_exception[$tag])) $keep = true;
                
                if ($keep) {
                    // 保護白名單值:替換特殊字符防止二次解析干擾
                    $newAttrs[] = $name . '=' . $this->protect($value);
                }
            }
            // 重構標籤
            $newTag = '<' . $tag . ($newAttrs ? ' ' . implode(' ', $newAttrs) : '') . '>';
            $this->_str = str_replace($fullTag, $newTag, $this->_str);
        }
        // 還原被保護的白名單值
        $this->_str = str_replace([$this->_LTAG, $this->_RTAG], ['', ''], $this->_str);
    }

    /** 特殊字符保護:將引號、尖括號替換為佔位符 */
    private function protect($str) {
        return str_replace(
            ['"', "'", '<', '>'],
            [$this->_LTAG . 'quot' . $this->_RTAG, $this->_LTAG . 'apos' . $this->_RTAG, 
             $this->_LTAG . 'lt' . $this->_RTAG, $this->_LTAG . 'gt' . $this->_RTAG],
            $str
        );
    }
}
?>

四、使用示例

<?php
require 'HtmlAttributeFilter.class.php';

$html = '<div class="box" onclick="alert(1)" id="main" data-x="1">內容</div>
<a href="https://evil.com" target="_blank" onclick="steal()">鏈接</a>
<img src="logo.png" onerror="hack()" alt="logo">
<script src="evil.js" data-id="1"></script>';

$filter = new HtmlAttributeFilter();
// 全局允許
$filter->setAllow(['class', 'id', 'title', 'alt']);
// 標籤特例
$filter->setException([
    'a' => ['href', 'target', 'rel'],
    'img' => ['src', 'width', 'height'],
    'input' => ['type', 'name', 'value']
]);
// 完全忽略 script/style 標籤屬性
$filter->setIgnore(['script', 'style']);

echo $filter->strip($html);
?>

輸出結果

<div class="box" id="main">內容</div>
<a href="https://evil.com" target="_blank" rel="">鏈接</a>
<img src="logo.png" alt="logo" width="" height="">
<script src="evil.js" data-id="1"></script>

效果:

  • 移除所有 onclick、onerror、data-x 等非白名單屬性
  • 保留 a[href|target|rel]、img[src|width|height] 等特例
  • script 標籤屬性保持原樣(忽略列表)

五、局限性與生產替代方案

限制風險替代方案
正則解析 HTML 不完備嵌套標籤、註釋、CDATA、畸形 HTML 可能繞過使用 HTMLPurifier(業界標準,基於 HTML5 解析器)
不處理 CSS expression/URL 注入style="background:url(javascript:...)"HTMLPurifier 內建 CSS 過濾
大文本效能較差preg_match_all 全文掃描流式解析或異步隊列處理
編碼繞過風險實體編碼、Unicode 變體HTMLPurifier 統一規格化處理

六、生產環境推薦:HTMLPurifier

<?php
require_once 'HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'div[class|id],a[href|target|rel],img[src|alt|width|height],p,br,strong,em,ul,ol,li');
$config->set('CSS.AllowedProperties', 'color,font-size,text-align,margin,padding');
$config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube\.com|player\.vimeo\.com)/%');

$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);
?>

自研過濾器適合學習理解與簡單場景,面向用戶的富文本內容必須使用 HTMLPurifier 等成熟庫保障安全。

copyright © 萬盛學電腦網 all rights reserved