萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

歷史回顧:曾用 CSS Expression 防禦網頁掛馬的五種方案與現代替代方案

背景

IE5-7 時代,CSS expression() 允許在樣式中執行 JavaScript,有人嘗試用它阻擋惡意 iframe 與外部腳本注入(俗稱「掛馬」)。以下五種方案純屬歷史產物,**現代瀏覽器均不支援**,且存在嚴重效能與安全風險。

五種歷史方案(僅供參考)

方案一:清空 src 與 outerHTML

iframe { n1ifm: expression(this.src='about:blank', this.outerHTML=''); }
script { nojs1: expression((this.src.toLowerCase().indexOf('http')==0)? document.write('木馬被成功隔離!') : ''); }

方案二:強制關閉 document.write

iframe { nifm2: expression(this.src='about:blank', this.outerHTML=''); }
script { no2js: expression((this.src.toLowerCase().indexOf('http')==0)? document.close() : ''); }

方案三:模擬瀏覽器「停止」按鈕

iframe { ni3fm: expression(this.src='about:blank', this.outerHTML=''); }
script { n3ojs: expression((this.src.toLowerCase().indexOf('http')==0)? document.execCommand('stop') : ''); }

方案四:重寫 src 指向本地錯誤頁

iframe { nif4m: expression(this.src='about:blank', this.outerHTML=''); }
script { noj4s: expression(if(this.src.indexOf('http')==0) this.src='res://ieframe.dll/dnserror.htm'); }

方案五:白名單機制(需 HTML 配合 id)

iframe { nifm5: expression(this.src='about:blank', this.outerHTML=''); }
script { noj5s: expression((this.id.toLowerCase().indexOf('vok')!=-1)? document.write('木馬被成功隔離!') : ''); }

HTML 需加白名單 id:<script src="..." id="lhSearchJSapi"></script>。

為何不可用於現代專案

  • expression() 僅 IE5-7 支援,IE8+ 已移除。
  • 嚴重阻塞渲染、導致 CPU 飆高、記憶體洩漏。
  • 屬於「黑名單」防禦,無法覆蓋所有攻擊向量。
  • 違反 CSP(內容安全策略)原則。

現代防禦最佳實踐

  1. CSP (Content-Security-Policy):script-src 'self' https://trusted.cdn.com; 禁止內聯腳本與非信任來源。
  2. 輸入過濾與輸出編碼:後端過濾 XSS、前端渲染時自動轉義。
  3. Subresource Integrity (SRI):<script src="..." integrity="sha384-..." crossorigin="anonymous"> 確保第三方資源未被篡改。
  4. iframe sandbox:<iframe sandbox="allow-scripts allow-same-origin"> 限制權限。
copyright © 萬盛學電腦網 all rights reserved