تولید هدرهای Content Security Policy توسط ASP.NET Core برای برنامههای Angular
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۴/۲۴ ۱۵:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace AngularTemplateDrivenFormsLab.Utils
{
public class ContentSecurityPolicyMiddleware
{
private readonly RequestDelegate _next;
public ContentSecurityPolicyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
string[] csp =
{
"default-src 'self'",
"style-src 'self' 'unsafe-inline'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
"font-src 'self'",
"img-src 'self' data:",
"connect-src 'self'",
"media-src 'self'",
"object-src 'self'",
"report-uri /api/CspReport/Log" //TODO: Add api/CspReport/Log
};
context.Response.Headers.Add("Content-Security-Policy", string.Join("; ", csp));
return _next(context);
}
}
public static class ContentSecurityPolicyMiddlewareExtensions
{
/// <summary>
/// Make sure you add this code BEFORE app.UseStaticFiles();,
/// otherwise the headers will not be applied to your static files.
/// </summary>
public static IApplicationBuilder UseContentSecurityPolicy(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ContentSecurityPolicyMiddleware>();
}
}
} public void Configure(IApplicationBuilder app)
{
app.UseContentSecurityPolicy(); context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN"); context.Response.Headers.Add("X-Xss-Protection", "1; mode=block"); context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); string[] csp =
{
"default-src 'self'",
"style-src 'self' 'unsafe-inline'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
"font-src 'self'",
"img-src 'self' data:",
"connect-src 'self'",
"media-src 'self'",
"object-src 'self'",
"report-uri /api/CspReport/Log" //TODO: Add api/CspReport/Log
};
context.Response.Headers.Add("Content-Security-Policy", string.Join("; ", csp)); Set-Cookie: sess=abc123; path=/; SameSite
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<rewrite>
<outboundRules>
<clear />
<!-- https://scotthelme.co.uk/csrf-is-dead/ -->
<rule name="Add SameSite" preCondition="No SameSite">
<match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
<action type="Rewrite" value="{R:0}; SameSite=lax" />
<conditions></conditions>
</rule>
<preConditions>
<preCondition name="No SameSite">
<add input="{RESPONSE_Set_Cookie}" pattern="." />
<add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=lax" negate="true" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>
</system.webServer>
</configuration> "report-uri /api/CspReport/Log" //TODO: Add api/CspReport/Log
{
"csp-report": {
"document-uri": "http://localhost:5000/untypedSha",
"referrer": "",
"violated-directive": "script-src",
"effective-directive": "script-src",
"original-policy": "default-src 'self'; style-src 'self'; script-src 'self'; font-src 'self'; img-src 'self' data:; connect-src 'self'; media-src 'self'; object-src 'self'; report-uri /api/Home/CspReport",
"disposition": "enforce",
"blocked-uri": "eval",
"line-number": 21,
"column-number": 8,
"source-file": "http://localhost:5000/scripts.bundle.js",
"status-code": 200,
"script-sample": ""
}
} class CspPost
{
[JsonProperty("csp-report")]
public CspReport CspReport { get; set; }
}
class CspReport
{
[JsonProperty("document-uri")]
public string DocumentUri { get; set; }
[JsonProperty("referrer")]
public string Referrer { get; set; }
[JsonProperty("violated-directive")]
public string ViolatedDirective { get; set; }
[JsonProperty("effective-directive")]
public string EffectiveDirective { get; set; }
[JsonProperty("original-policy")]
public string OriginalPolicy { get; set; }
[JsonProperty("disposition")]
public string Disposition { get; set; }
[JsonProperty("blocked-uri")]
public string BlockedUri { get; set; }
[JsonProperty("line-number")]
public int LineNumber { get; set; }
[JsonProperty("column-number")]
public int ColumnNumber { get; set; }
[JsonProperty("source-file")]
public string SourceFile { get; set; }
[JsonProperty("status-code")]
public string StatusCode { get; set; }
[JsonProperty("script-sample")]
public string ScriptSample { get; set; }
} namespace AngularTemplateDrivenFormsLab.Controllers
{
[Route("api/[controller]")]
public class CspReportController : Controller
{
[HttpPost("[action]")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> Log()
{
CspPost cspPost;
using (var bodyReader = new StreamReader(this.HttpContext.Request.Body))
{
var body = await bodyReader.ReadToEndAsync().ConfigureAwait(false);
this.HttpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
cspPost = JsonConvert.DeserializeObject<CspPost>(body);
}
//TODO: log cspPost
return Ok();
}
}
} Refused to execute script from '<URL>' because its MIME type ('') is not executable, and strict MIME type checking is enabled. var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
}); Content Security Policy: The page’s settings blocked the loading of a resource at https://mdbootstrap.com/img/Photos/Others/sidenav3.jpg (“img-src”).
In Firefox and IE X-Frame-Options: allow-from https://example.com/ In Chrome and Safari: Content-Security-Policy: frame-ancestors domain.com
"img-src 'self' data: blob: https://trustseal.enamad.ir",
خطری ایجاد نمیکنه
Refused to connect to ws: because it violates the Content Security Policy directive
{
"csp-report":{
"document-uri":"http://localhost:5051/",
"referrer":"",
"violated-directive":"connect-src",
"effective-directive":"connect-src",
"original-policy":"default-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' ; font-src 'self'; img-src 'self' data: blob:; connect-src 'self'; media-src 'self'; object-src 'self' blob:; report-uri /api/CspReport/Log",
"disposition":"enforce",
"blocked-uri":"wss://localhost:52837",
"line-number":234,
"column-number":25,
"source-file":"http://localhost:5051/_framework/aspnetcore-browser-refresh.js",
"status-code":200,
"script-sample":""
}
} connect-src 'self' wss://localhost:*