Use iframe sandbox 属性
sandbox 属性 restricts iframe capabilities, preventing malicious embedded 内容从 accessing 父 page.
- 1
sandbox 属性开 <iframe> applies restrictions 到 embedded 内容. 无 sandbox, iframe 能够: 运行 scripts, access 父's DOM (如果相同-源), submit forms, 加载 plugins, navigate 父. 具有 sandbox="" (否 values), 所有 restrictions 应用. Add 特定 values 到 re-enable individual capabilities: 允许-scripts, 允许-相同-源, 允许-forms, 允许-popups, etc.
- 2 HTML 压缩器 →
压缩 the HTML containing iframes to inspect the sandbox attributes. Verify that each iframe has appropriate sandbox restrictions. Never use allow-scripts + allow-same-origin together on untrusted content — this allows the iframe to escape the sandbox and access the parent.
- 3 HTML 转义器 →
转义 any user-provided URLs before inserting them into iframe src attributes. This prevents javascript: URL injection. Use a whitelist of allowed URL schemes (https only) and domains. Even with sandbox, a javascript: URL can execute if allow-scripts is present.
常见问题
- 什么是 最多 restrictive sandbox?
- sandbox="" (空字符串) applies 所有 restrictions: 否 scripts, 否 forms, 否 popups, 否相同-源 access, 否 plugins, 否 navigation. 此是 safest. Add 仅 capabilities embedded 内容 needs. 为 YouTube embed: sandbox="允许-scripts 允许-相同-源允许-popups 允许-popups-to-escape-sandbox".
- 为什么是 允许-scripts + 允许-相同-源 dangerous?
- 具有两者, iframe 能够运行 scripts 和 access 其 own 源 as 相同-源. 如果 iframe 是相同-源具有父, 它能够 access 父's DOM (document.父), escaping sandbox 整个. Only use 两者为 trusted 相同-源内容. 为 third-party 内容, use 允许-scripts 无允许-相同-源, 或 use 不同源 (subdomain) 为 iframe.