Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jpk/report to #41

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Joonasw.AspNetCore.SecurityHeaders.Hpkp.Builder;
using Joonasw.AspNetCore.SecurityHeaders.Hsts;
using Joonasw.AspNetCore.SecurityHeaders.ReferrerPolicy;
using Joonasw.AspNetCore.SecurityHeaders.ReportTo;
using Joonasw.AspNetCore.SecurityHeaders.XContentTypeOptions;
using Joonasw.AspNetCore.SecurityHeaders.XFrameOptions;
using Joonasw.AspNetCore.SecurityHeaders.XXssProtection;
Expand Down Expand Up @@ -103,6 +104,13 @@ public static IApplicationBuilder UseHpkp(this IApplicationBuilder app)
return app.UseMiddleware<HpkpMiddleware>();
}

public static IApplicationBuilder UseReportTo(
this IApplicationBuilder app,
ReportToOptions options)
{
return app.UseMiddleware<ReportToMiddleware>(new OptionsWrapper<ReportToOptions>(options));
}

/// <summary>
/// Sets the X-Frame-Options header to DENY by default
/// </summary>
Expand Down
8 changes: 8 additions & 0 deletions src/Joonasw.AspNetCore.SecurityHeaders/CspOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ public class CspOptions
/// The URL where violation reports should be sent.
/// </summary>
public string ReportUri { get; set; }
/// <summary>
/// The group where violation reports should be sent.
/// </summary>
public string ReportTo { get; set; }

public bool IsNonceNeeded => Script.AddNonce || Style.AddNonce;

Expand Down Expand Up @@ -210,6 +214,10 @@ public CspOptions()
{
values.Add("report-uri " + ReportUri);
}
if (!string.IsNullOrWhiteSpace(ReportTo))
{
values.Add("report-to " + ReportTo);
}

string headerValue = string.Join(";", values.Where(s => s.Length > 0));

Expand Down
6 changes: 6 additions & 0 deletions src/Joonasw.AspNetCore.SecurityHeaders/HpkpOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class HpkpOptions
public bool IncludeSubDomains { get; set; }
public bool ReportOnly { get; set; }
public string ReportUri { get; set; }
public string ReportTo { get; set; }

public string HeaderName => ReportOnly ? ReportOnlyHeaderName : BlockingHeaderName;

Expand All @@ -32,6 +33,11 @@ public string HeaderValue
value += "; report-uri=\"" + ReportUri + "\"";
}

if (!string.IsNullOrWhiteSpace(ReportTo))
jpknoll marked this conversation as resolved.
Show resolved Hide resolved
{
value += "; report-to=" + ReportTo;
}

return value;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<!-- /Source Link support-->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-18618-05" PrivateAssets="All" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace Joonasw.AspNetCore.SecurityHeaders.ReportTo
{
public class ReportToMiddleware
{
private const string HeaderName = "Report-To";
private readonly RequestDelegate _next;
private readonly string _headerValue;

public ReportToMiddleware(RequestDelegate next, IOptions<ReportToOptions> options)
{
_next = next;
_headerValue = options.Value.BuildHeaderValue();
}

public async Task Invoke(HttpContext context)
{
// Check if a CSP header has already been added to the response
// This can happen for example if a middleware re-executes the pipeline
if (!ContainsReportToHeader(context.Response))
{
context.Response.Headers.Add(HeaderName, _headerValue);
}
await _next(context);
}

private bool ContainsReportToHeader(HttpResponse response)
{
return response.Headers.Any(h => h.Key.Equals(HeaderName, StringComparison.OrdinalIgnoreCase));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Newtonsoft.Json;
using System;

namespace Joonasw.AspNetCore.SecurityHeaders.ReportTo
{
internal static class ReportToOptionsExtensions
{
public static string BuildHeaderValue(this ReportToOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

if (options.Groups == null || options.Groups.Count <= 0)
{
throw new ArgumentOutOfRangeException(nameof(options.Groups), "ReportToOptions must have at least one group");
}

var values = new string[0];
for (var i = 0; i < options.Groups.Count; i++)
{
var group = options.Groups[i];

if (group.MaxAgeSeconds <= 0)
{
throw new ArgumentOutOfRangeException(nameof(group.MaxAgeSeconds), "ReportTo max age must be positive");
}

if (group.Endpoints == null || group.Endpoints.Count <= 0)
{
throw new ArgumentNullException(nameof(group.Endpoints), "At least one endpoint required");
}

for (var j = 0; j < group.Endpoints.Count; j++)
{
var e = group.Endpoints[j];

if (string.IsNullOrWhiteSpace(e.Url))
{
throw new ArgumentException($"{nameof(group.Endpoints)}[{j}].Url", "Url for endpoint required");
}

if (e.Priority.HasValue && e.Priority <= 0)
{
throw new ArgumentException($"{nameof(group.Endpoints)}[{j}].Priority", "Priority must be positive if present");
}

if (e.Weight.HasValue && e.Weight <= 0)
{
throw new ArgumentException($"{nameof(group.Endpoints)}[{j}].Weight", "Weight must be positive if present");
}
}

values[i] = JsonConvert.SerializeObject(group);
jpknoll marked this conversation as resolved.
Show resolved Hide resolved
}

return string.Join(",\r\n", values);
}
}
}
37 changes: 37 additions & 0 deletions src/Joonasw.AspNetCore.SecurityHeaders/ReportToOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Joonasw.AspNetCore.SecurityHeaders
{
public class ReportToOptions
{
public IList<Group> Groups { get; set; } = new List<Group>();

public class Group
{
[JsonProperty("group")]
public string GroupName { get; set; }

[JsonProperty("include_subdomains")]
public bool IncludeSubdomains { get; set; }

[JsonProperty("max_age")]
public int MaxAgeSeconds { get; set; }

[JsonProperty("endpoints")]
public IList<Endpoint> Endpoints { get; set; } = new List<Endpoint>();

public class Endpoint
{
[JsonProperty("url")]
public string Url { get; set; }

[JsonProperty("priority")]
public int? Priority { get; set; }

[JsonProperty("weight")]
public int? Weight { get; set; }
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Joonasw.AspNetCore.SecurityHeaders.ReportTo;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Xunit;

namespace Joonasw.AspNetCore.SecurityHeaders.Tests
{
public class ReportToMiddlewareTests
{
[Fact]
public async Task ReportToHeaderSetCorrectly()
{
bool reportToHeaderExists = false;
RequestDelegate mockNext = (HttpContext ctx) =>
{
reportToHeaderExists = ctx.Response.Headers.ContainsKey("Report-To");
return Task.CompletedTask;
};
var options = new ReportToOptions()
{
Groups = new[]
{
new ReportToOptions.Group {
GroupName = "a",
MaxAgeSeconds = 60,
Endpoints = new []
{
new ReportToOptions.Group.Endpoint() { Url = "a" },
}
},
},
};

var sut = new ReportToMiddleware(mockNext, Options.Create(options));
var mockContext = new DefaultHttpContext();

await sut.Invoke(mockContext);

Assert.True(reportToHeaderExists);
}
}
}