ASP.NET Core 6 修正風險,Header 增加 X-Frame-Options

HI 還是我,上一篇 透過隱藏 IIS 版本號碼增加網站安全性 已經解決弱點掃描的一個問題,現在來解決另一個。
Missing X-Frame-Options Header
Netsparker detected a missing X-Frame-Optionsheader which means that this website could be at risk of a clickjacking attack.
The X-Frame-OptionsHTTP header field indicates a policy that specifies whether the browser should render the transmitted
resource within a frameor an iframe. Servers can declare this policy in the header of their HTTP responses to prevent clickjacking
attacks, which ensures that their content is not embedded into other pages or frames.
Clickjacking is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on
a framed page when they were intending to click on the top level page. Thus, the attacker is "hijacking" clicks meant for their page
and routing them to other another page, most likely owned by another application, domain, or both.
Using a similar technique, keystrokes can also be hijacked. With a carefully crafted combination of stylesheets, iframes, and text
boxes, a user can be led to believe they are typing in the password to their email or bank account, but are instead typing into an
invisible frame controlled by the attacker.

X-Frame-Options 是一個 HTTP 回應標頭,主要用來防止點擊劫持攻擊(clickjacking),這種攻擊通常會利用頁面鑲嵌,讓使用者點擊時跳轉到攻擊者指定路徑。

X-Frame-Options 內容有三種:
  • DENY: 拒絕所有嵌入
  • SAMEORIGIN: 只允許同源網站嵌入
  • ALLOW-FROM: 只允許特定網站嵌入,因有安全風險已被廢棄

ASP.NET Core 在所有 HTTP 回應上加入 Header

要解決很簡單,在 Program.cs 中加入下面的程式碼即可將全部都加上 X-Frame-Options
var app = builder.Build();

app.Use(async (context, next) =>
    context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
    await next();

確認 X-Frame-Options Header

可以使用 Windows 下的「命令提示字元」查看:
(PowerShell 的 curl 使用方式不同)

curl -I
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/html
Date: Wed, 29 Mar 2023 23:59:59 GMT
X-Frame-Options: SAMEORIGIN

Wiki - 點擊劫持