ASP.NET Core中使用Csp標頭對抗Xss攻擊

  • 2019 年 10 月 3 日
  • 筆記

內容安全策略(CSP)是一個增加的安全層,可幫助檢測和緩解某些類型的攻擊,包括跨站點腳本(XSS)和數據注入攻擊。這些攻擊用於從數據竊取到站點破壞或惡意軟體分發的所有內容(深入CSP

簡而言之,CSP是網頁控制允許載入哪些資源的一種方式。例如,頁面可以顯式聲明允許從中載入JavaScript,CSS和影像資源。這有助於防止跨站點腳本(XSS)攻擊等問題。

它也可用於限制協議,例如限制通過HTTPS載入的內容。CSP通過 Content-Security-Policy HTTP響應中的標頭實現。

啟用CSP,您需要配置Web伺服器以返回Content-Security-PolicyHTTP標頭。那麼在這篇文章中,我們將要嘗試將CSP添加到ASP.NET Core應用程式中。

app.Use(async (ctx, next) =>              {                  ctx.Response.Headers.Add("Content-Security-Policy",                              "default-src 'self'; report-uri /cspreport");                  await next();              });  

  在Home/Index中引入cdn文件,然後我們啟動項目,看看會發生什麼!

運行並觀察錯誤。載入頁面時,瀏覽器拒絕從遠程源載入。

 

 所以我們可以組織CSP來控制我們的白名單,在配置當中需要填寫來源以及內容,以下是常用限制的選項。

來源:

*: 允許任何網址。  ‘self’: 允許所提供頁面的來源。請注意,單引號是必需的。  ‘none’: 不允許任何來源。請注意,單引號是必需的。  Host: 允許指定的互聯網主機(按名稱或IP地址)。通配符(星號字元)可用於包括所有子域,例如http://*.foo.comunsafe-line’: 允許內聯腳本  ‘nonce-[base64-value]’: 允許具有特定nonce的內聯腳本(使用一次的數字)。對於每個HTTP請求/響應,應該對nonce進行加密和唯一。

 指令:

script-src:定義有效的JavaScript源  style-src:定義樣式表的有效來源  img-src:定義有效的影像源  connect-src:定義可以進行AJAX調用的有效源  font-src:定義有效的字體來源  object-src:定義<object>,<embed>和<applet>元素的有效源  media-src:定義有效的音頻和影片源  form-action:定義可用作HTML <form>操作的有效源。  default-src:指定載入內容的默認策略

我們可以在可重用的中間件中封裝構建和添加CSP頭。以下是一個讓您入門的示例。你可以根據需要擴展它。首先,創建一個用於保存源的類。

public class CspOptions      {          public List<string> Defaults { get; set; } = new List<string>();          public List<string> Scripts { get; set; } = new List<string>();          public List<string> Styles { get; set; } = new List<string>();          public List<string> Images { get; set; } = new List<string>();          public List<string> Fonts { get; set; } = new List<string>();          public List<string> Media { get; set; } = new List<string>();      }

 開發一個中間件一定是需要一個構造器的,這將用於.net core 的注入到運行環境中。

public sealed class CspOptionsBuilder   {       private readonly CspOptions options = new CspOptions();         internal CspOptionsBuilder() { }         public CspDirectiveBuilder Defaults { get; set; } = new CspDirectiveBuilder();       public CspDirectiveBuilder Scripts { get; set; } = new CspDirectiveBuilder();       public CspDirectiveBuilder Styles { get; set; } = new CspDirectiveBuilder();       public CspDirectiveBuilder Images { get; set; } = new CspDirectiveBuilder();       public CspDirectiveBuilder Fonts { get; set; } = new CspDirectiveBuilder();       public CspDirectiveBuilder Media { get; set; } = new CspDirectiveBuilder();         internal CspOptions Build()       {           this.options.Defaults = this.Defaults.Sources;           this.options.Scripts = this.Scripts.Sources;           this.options.Styles = this.Styles.Sources;           this.options.Images = this.Images.Sources;           this.options.Fonts = this.Fonts.Sources;           this.options.Media = this.Media.Sources;           return this.options;       }   }     public sealed class CspDirectiveBuilder   {       internal CspDirectiveBuilder() { }         internal List<string> Sources { get; set; } = new List<string>();         public CspDirectiveBuilder AllowSelf() => Allow("'self'");       public CspDirectiveBuilder AllowNone() => Allow("none");       public CspDirectiveBuilder AllowAny() => Allow("*");         public CspDirectiveBuilder Allow(string source)       {           this.Sources.Add(source);           return this;       }   }  

 好了,我們創建一個中間件。

namespace XSSDefenses.XSSDefenses.MiddlerWare  {      public sealed class CspOptionMiddlerWare      {          private const string HEADER = "Content-Security-Policy";          private readonly RequestDelegate next;          private readonly CspOptions options;            public CspOptionMiddlerWare(              RequestDelegate next, CspOptions options)          {              this.next = next;              this.options = options;          }            public async Task Invoke(HttpContext context)          {              context.Response.Headers.Add(HEADER, GetHeaderValue());              await this.next(context);          }            private string GetHeaderValue()          {              var value = "";              value += GetDirective("default-src", this.options.Defaults);              value += GetDirective("script-src", this.options.Scripts);              value += GetDirective("style-src", this.options.Styles);              value += GetDirective("img-src", this.options.Images);              value += GetDirective("font-src", this.options.Fonts);              value += GetDirective("media-src", this.options.Media);              return value;          }          private string GetDirective(string directive, List<string> sources)              => sources.Count > 0 ? $"{directive} {string.Join(" ", sources)}; " : "";      }  }

 以及設置它的擴展方法。

namespace XSSDefenses.XSSDefenses.Extensions  {      public static class CspMiddlewareExtensions      {          public static IApplicationBuilder UseCsp(               this IApplicationBuilder app, Action<CspOptionsBuilder> builder)          {              var newBuilder = new CspOptionsBuilder();              builder(newBuilder);                var options = newBuilder.Build();              return app.UseMiddleware<CspOptionMiddlerWare>(options);          }      }  }  

我們現在可以在Startup類中配置中間件。

app.UseCsp(builder =>              {                  builder.Styles.AllowSelf()                  .Allow(@"https://ajax.aspnetcdn.com/");              });

 啟動發現,觀察網路資源。瀏覽器已經允許本地和遠程資源。

 Github地址 https://github.com/zaranetCore/-.NET-Core-And-XSSDefensesSolucation