gaprogman / owaspheaders.core Goto Github PK
View Code? Open in Web Editor NEWInject OWASP recommended HTTP Headers for increased security in a single line
Home Page: https://www.nuget.org/packages/OwaspHeaders.Core/
License: MIT License
Inject OWASP recommended HTTP Headers for increased security in a single line
Home Page: https://www.nuget.org/packages/OwaspHeaders.Core/
License: MIT License
Headers contain the following
X-Content-Type-Options: nosniff
Headers does not contain the above
Hello,
as 2.1 is the latest LTS version of .Net Core we are currently using this version and not .Net Core 2.2. Unfortunately the latest version of the nuget package references Microsoft.AspNetCore.Http.Abstractions
in version 2.2.0 - this does cause version conflicts in .Net Core 2.1 that I am not able to resolve.
I don't know if it's possible to fix this by downgrading the minimal required version or if it's needed - but it'd be great if you could check ;)
Thanks & best regards,
Christoph
The HTTP Cross-Origin-Embedder-Policy (COEP) response header configures embedding cross-origin resources into the document.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy
OWASP recommended value (as of May 11th, 2023): Cross-Origin-Embedder-Policy: require-corp
This value means that "A document can only load resources from the same origin, or resources explicitly marked as loadable from another origin."
As pointed out in this post on the Chromium support portal, HPKP is being deprecated in Chrome - with firefox likely to follow suit
This will first remove support for HTTP-based PKP (“dynamic pins”), in which the user-agent learns of pin-sets for hosts by HTTP headers. We would like to do this in Chrome 67, which is estimated to be released to Stable on 29 May 2018.
This means that, effectively, this header is deprecated and should be marked in the code as such. This particular header should only be enabled if the consumer sets up their configuration file to reflect it.
(i.e. do not instantiate and empty HPKP object and use that in the header injection code).
possibly requires to some thought and communication with other (more intelligent) people about how to handle this. A tweet has been sent (with OWASP mentioned) asking the community about this:
https://twitter.com/dotNetCoreBlog/status/928258899794382848
The following comes directly from the OWASP Secure Headers Project (as of May 11th, 2023):
Deprecated.
⚠️ Warning: The X-XSS-Protection header has been deprecated by modern browsers and its use can introduce additional security issues on the client side. As such, it is recommended to set the header as X-XSS-Protection: 0 in order to disable the XSS Auditor, and not allow it to take the default behavior of the browser handling the response. Please use Content-Security-Policy instead.
Source: https://owasp.org/www-project-secure-headers/#x-xss-protection
The MDN page for X-XSS-Protection goes into further detail:
Warning: Even though this feature can protect users of older web browsers that don't yet support CSP, in some cases, XSS protection can create XSS vulnerabilities in otherwise safe websites. See the section below for more information.
They also say this, perhaps add this to documentation:
Note:
Chrome has removed their XSS Auditor
Firefox has not, and will not implement X-XSS-Protection
Edge has retired their XSS filter
This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.
This is an issue to discuss the Pull Request I am to file soon.
There are different sources about if it is a good idea to add the X-Content-Security-Policy-header.
https://content-security-policy.com/ says Note: It is known that having both Content-Security-Policy and X-Content-Security-Policy or X-Webkit-CSP causes unexpected behaviours on certain versions of browsers. Please avoid using deprecated X-* headers.
I did not find out what this "unexpected behaviour" is and sources like stackexchange or stackoverflow tell that this header is the only way to make Internet Explorer a bit more secure, although not all properties work.
Well-respected products like IdentityServer also set this header in their Quickstart-Guide, to the same value as the normal Content-Security-Policy header.
In my understanding it does not hurt to set it to the same value and by adding "sandbox" and optionally "allow-scripts" "allow-forms" it should help with IE. I did not find a good source about "allow-same-origin".
I am currently working on adding an optional config.UseXContentSecurityPolicy - property (set to false by default) that will just put the content of the Content-Security-Policy-Header to the X-Content-Security-Policy-Header as well. Also on the TODO is to test that I can add "sandbox allow-scripts allow-same-origin allow-forms" to this header.
I am not quite sure if this is the right route to go, so if anyone has any better ideas feel free to add those here.
Pull request will come soon.
The unit tests don't actually run if there is an error in the setup phase or the parts executing this. I think the "if"-clauses in the tests should be assertions instead. I also found one test where this caused the test to not do anything at all as there was passed a HeaderPresentConfig in a HeaderNotPresent-Test:
[Fact]
public async Task Invoke_ExpectCtHeaderName_HeaderIsNotPresent()
{
// arrange
var headerPresentConfig = SecureHeadersMiddlewareBuilder.CreateBuilder()
.UseExpectCt("https://test.com/report").Build();
var secureHeadersMiddleware = new SecureHeadersMiddleware(_onNext, headerPresentConfig);
// act
await secureHeadersMiddleware.Invoke(_context);
// assert
if (!headerPresentConfig.UseExpectCt)
{
Assert.False(_context.Response.Headers.ContainsKey(Constants.ExpectCtHeaderName));
}
}
I did change all tests to assert instead of not run if they are set up wrong. PR is coming right after this issue.
The OwaspHeaders.Core middleware does not yet include support for Expect-CT which is a header related to Certificate Transparency.
Description from MDN:
The Expect-CT header allows sites to opt in to reporting and/or enforcement of Certificate Transparency requirements, which prevents the use of misissued certificates for that site from going unnoticed. When a site enables the Expect-CT header, they are requesting that the browser check that any certificate for that site appears in public CT logs.
Source: Excpect-CT on MDN
How can the middleware be configured to allow certain domains and their subdomains?
As good as the Builder Pattern is, it might be more explicit to consumers if the middleware uses the OptionsBuilder pattern.
This will greatly increase visibility of exactly which values are being set for the different headers.
Hi,
Could you add a changelog.md
file to explain features/fixes for each new version?
I've seen that the NuGet package has been updated (several times) about 6 days ago, yet I do not see any description (other than the commits themselves) explaining what those versions contain and if any breaking changes, security fixes, etc have been introduced.
Also, the GitHub release page contains only one version while the NuGet contains about 20. Any reason for that discrepancy?
Thanks!
The HTTP Cross-Origin-Resource-Policy response header conveys a desire that the browser blocks no-cors cross-origin/cross-site requests to the given resource.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy
OWASP recommended value (as of May 11th, 2023): Cross-Origin-Resource-Policy: same-origin
This value means that "Only requests from the same Origin (i.e. scheme + host + port) can read the resource."
Hi there,
although you mention to support netstandard2.0 here the project is built against netcoreapp2.0, not netstandard2.0 - I had to make 2 small changes to make it work with my .Net Core-project built against the 4.6.1 framework. You can have a look at the changes here - should I commit a pull request? I didn't test it against a full netcoreapp2.0, but it should work.
Thanks & best regards,
Christoph
It would be cool if we could use this in azure functions
The set-cookie header can be used to ensure that cookies are only sent via HTTPS and that they are not available in JavaScript via document.cookie
- amongst other things.
With the release of .NET Core 2.0 (and all of the related libraries and features) it is required that OwaspHeaders.Core is upgraded to .NET Core 2.0 (and by extension .NET Standard 2.0 compatible).
There is already a branch for this, and all development work should happen in that branch before being merged into Master.
Attention should be paid to ensure that the AppVeyor build and releases do not break.
Regarding to the spec the report uri directive is optional:
The OPTIONAL report-uri directive indicates the URI to which the UA SHOULD report Expect-CT failures (Section 2.4). The UA POSTs the reports to the given URI as described in Section 3.
The report-uri directive is REQUIRED to have a directive value, for which the syntax is defined in Figure 2.
Whereas in OwaspHeaders.Core it is required
if (string.IsNullOrWhiteSpace(reportUri))
throw new ArgumentException("Must supply value of reportUri in SecureHeadersMiddleware");
To be able to use this header with the required report-uri in the default config there is a hard-coded reportUri.
.UseExpectCt("https://gaprogman.com/report", 86400, true)
I think the parameter should be optional and no URI should be hard-coded.
Thanks & best regards,
Christoph
I get this error
Cannot create instance of type 'Models.HstsConfiguration' because it is missing a public parameterless constructor
any help?
Headers contain the following (example)
X-Permitted-Cross-Domain-Policies: none
Headers does not contain the above
Use the Default Secure Headers Config builder, run a server with the middleware set up on it, put in a request to a page on the server and CSP is not used.
Although the CSP is set up correctly, however in the UseContentDefaultSecurityPolicy
method (and those which follow it in the layout of the file), does not set the value of config.UseContentSecurityPolicy
The NuGet package for this project is missing a lot of meta data, which could be useful for those who consume it.
Create a nuspect file and include it in the dotnet pack
command (used in the appveyor.yml file) via a NuGet metadata property which are passed in similarly to the following:
dotnet pack /p:PackageVersion=2.1.0
source: dotnet pack documentation
The current version of the project uses a config file (see secureHeaderSettings.json for an example). This could prove to be difficult for some users, as they would have to create the file and learn the schema.
Move towards a Fluent Interface with Builder Pattern for building an instance of the middleware and inserting it into the pipeline.
Example:
app.UseSecureHeadersMiddleware()
.WithHsts("any relevant config in here")
.WithCsp("content security policy string here")
.Build();
All arguments will be nullable, with defaults and XML documentation provided. Only the headers which have been dot supplied will be built, and an explicit call to Build()
will be required as the final part of the middleare
In the above example, the only extra headers inserted would be HSTS and CSP.
Consider renaming the extension method which includes the middleware. Something like:
app.UseOwaspHeaders()
app.OwaspHeadersConfig()
app.IncludeSecureHeaders()
The OwaspHeaders.Core middleware does not yet include support for Feature-Policy which is a header related to enabling or disabling certain JavaScript API features.
Quote from Scott Helme's blog:
TheFeature Policy is being created to allow site owners to enable and disable certain web platform features on their own pages and those they embed. Being able to restrict the features your site can use is really nice but being able to restrict features that sites you embed can use is an even better protection to have.
Source: A new security header: Feature Policy
As the Chromium team have announced their plan to deprecate the XSSAuditor in Chrome, along with it having been removed from Edge in October, 2018, the X-XSS-Protection header should be removed from the default builder. However, since legacy browsers still support the header, it should still be possible to add the header via an extension method.
Removing UseXSSProtection() from the BuildDefaultConfiguration extension method will get us part way to fixing this issue.
By adding a dependency to Microsoft.AspNetCore.All
in version 3.3.0 you also implictly added a dependency to .NET Core 2.0. As a direct result you excluded projects targetting .NET Standard 2.0. This prevents us from upgrading to the latest version.
You should consider just adding the specific packages you require as a dependency instead of the ominous .All
package. Most ASP.NET Core packages target .NET Standard, and not .NET Core.
Clear Site-Data is a new header which can be used to tell the browser to wipe out cookies and tokens automatically when a user logs out. This can be useful in stopping Session Hijacking once a user has logged out.
Adding support for the Clear Site-Data header will require some form of controller attribute, perhaps. This is because we don't want Clear Site-Data to be included in every response from the server, only those responses which are generated by logging out.
This will require some thought and planning before implementation.
Headers contain the following (example)
Content-Security-Policy: script-src 'self'
Headers does not contain the above
The following comes directly from the OWASP Secure Headers Project (as of May 11th, 2023):
Deprecated.
⚠️ Warning: This header will likely become obsolete in June 2021. Since May 2018 new certificates are expected to support SCTs by default. Certificates before March 2018 were allowed to have a lifetime of 39 months, those will all be expired in June 2021.
source: https://owasp.org/www-project-secure-headers/#expect-ct
The MDN page for Expect-CT goes into this further:
Note: The Expect-CT is mostly obsolete since June 2021. Since May 2018, all new TLS certificates are expected to support SCTs by default. Certificates issued before March 2018 were allowed to have a lifetime of 39 months, so they had expired in June 2021. Chromium plans to deprecate Expect-CT header and to eventually remove it.
Rather than remove it, perhaps set its default value to disabled.
Headers contain the following (example)
Referrer-Policy: no-referrer
Headers does not contain the above
This library was originally designed to be used by ASP .NET Core applications which use either .NET Framework or .NET Core. However, as of ASP .NET Core 3.0, .NET Framework is no longer supported. See this announcement for details.
This will also help to fix the transient vulnerability that the library has due to it using ASP .NET Core 2.2's Microsoft.AspNetCore.Http.Abstractions
. Details on the vulnerabilities can be found here and here.
I explored the options for removing support for both ASP .NET Core on .NET Framework and ASP .NET Core 2.2 in the second half of this stream.
We'll also need a way to communicate to users that the new version of the library (version 8) will not longer be supported by ASP .NET Core on .NET Framework. But that's more of an infrastructure problem for me.
Add a CSP (assumes that #16 is fixed) which uses a domain rather than a command (i.e. www.gaprogman.com versus using 'self') and the reported CSP in the browser will be broken.
All values for CSP directives are added without the use of single quotes (i.e. '
) - which are needed for all directive values which are not domains (i.e. 'self'
) but not for domains (i.e. www.gaprogman.com
). This is done in the [BuildValuesForDirective](https://github.com/GaProgMan/OwaspHeaders.Core/blob/5f2ab0bdc7ef4e7d56e01397706193990bfdb181/src/Extensions/StringBuilderExtentions.cs)
method
The uris are added to the [ContentSecurityPolicyConfiguration](https://github.com/GaProgMan/OwaspHeaders.Core/blob/5f2ab0bdc7ef4e7d56e01397706193990bfdb181/src/Models/ContentSecurityPolicyConfiguration.cs)
as lists of strings. Replace this with a model which has an enum (csp command, domain name) and a uri/command as a string.
For example:
public enum CspCommandType
{
CspCommand,
Uri
}
In the [BuildValuesForDirective](https://github.com/GaProgMan/OwaspHeaders.Core/blob/5f2ab0bdc7ef4e7d56e01397706193990bfdb181/src/Extensions/StringBuilderExtentions.cs)
method, separate the directive values by CspCommandType
and add them using the following logic:
'
chars (i.e. 'self'
)'
chars (i.e. www,gaprogman.com)Offer an option to make the SecureHeadersMiddlewareBuilder.UseContentSecurityPolicy() produce the Content Security Policy Report Only header. This would facilitate setting up the proper CSP for production during development phase.
font-src, style, img etc. has the possibility for blob: or data: or *. However when creating an ContenSecurityPolicyElement the value is always capsulated with quotes but this is not valid for browsers (like Chrome) which ignores the CSP rule.
I think it will be good when setting a value, you can exclude the quotes. I will make a pull request for this.
Edit: good to show my configuration:
new ContenSecurityPolicyElement { CommandType = CspCommandType.Directive, DirectiveOrUri = "blob:" };
The HTTP Cross-Origin-Opener-Policy (COOP) response header allows you to ensure a top-level document does not share a browsing context group with cross-origin documents.
COOP will process-isolate your document and potential attackers can't access your global object if they were to open it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks.
If a cross-origin document with COOP is opened in a new window, the opening document will not have a reference to it, and the window.opener property of the new window will be null. This allows you to have more control over references to a window than rel=noopener, which only affects outgoing navigations.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
OWASP recommended value (as of May 11th, 2023): Cross-Origin-Opener-Policy: same-origin
This value means that "Isolates the browsing context exclusively to same-origin documents. Cross-origin documents are not loaded in the same browsing context."
When using a custom configuration to determine the Content Security Policy e.g.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseSecureHeadersMiddleware(CustomConfiguration());
...
}
private static SecureHeadersMiddlewareConfiguration CustomConfiguration()
{
var safeScripts = new List<ContentSecurityPolicyElement>
{
ContentSecurityPolicyHelpers.CreateSelfDirective(),
new ContentSecurityPolicyElement()
{
CommandType = CspCommandType.Uri,
DirectiveOrUri = "https://safeaddress.com/"
}
};
var safeStyles = new List<ContentSecurityPolicyElement>
{
ContentSecurityPolicyHelpers.CreateSelfDirective(),
new ContentSecurityPolicyElement()
{
CommandType = CspCommandType.Uri,
DirectiveOrUri = "https://safeaddress.com/"
},
new ContentSecurityPolicyElement()
{
CommandType = CspCommandType.Uri,
DirectiveOrUri = "https://fonts.googleapis.com/"
}
};
var safeFonts = new List<ContentSecurityPolicyElement>
{
ContentSecurityPolicyHelpers.CreateSelfDirective(),
new ContentSecurityPolicyElement()
{
CommandType = CspCommandType.Uri,
DirectiveOrUri = "https://fonts.googleapis.com/"
}
};
return SecureHeadersMiddlewareBuilder
.CreateBuilder()
.UseHsts()
.UseXFrameOptions()
.UseXSSProtection()
.UseContentTypeOptions()
.UseContentSecurityPolicy(null, true, true, null, null)
.SetCspUris(safeScripts, CspUriType.Script)
.SetCspUris(safeStyles, CspUriType.Style)
.SetCspUris(safeFonts, CspUriType.Font)
.UsePermittedCrossDomainPolicies()
.UseReferrerPolicy()
.Build();
}
The Policy Elements that are marked as CspCommandType.Uri
are being quoted as well being written as unquoted in the HEADER
e.g.
content-security-policy: script-src 'self' 'https://safeaddress.com/' https://safeaddress.com/;style-src 'self' 'https://safeaddress.com/' 'https://fonts.googleapis.com/' https://safeaddress.com/ https://fonts.googleapis.com/;font-src 'self' 'https://fonts.googleapis.com/' https://fonts.googleapis.com/;block-all-mixed-content; upgrade-insecure-requests;
I may be wrong but I understand the header should be returned with only the directives being quoted.
content-security-policy: script-src 'self' https://safeaddress.com/;style-src 'self' https://safeaddress.com/ https://fonts.googleapis.com/;font-src 'self' https://fonts.googleapis.com/;block-all-mixed-content; upgrade-insecure-requests;
Example, Startup.cs:
.UseContentSecurityPolicy() .SetCspUris(new List<ContentSecurityPolicyElement>{ new ContentSecurityPolicyElement() { CommandType = CspCommandType.Directive, DirectiveOrUri = "self" }, new ContentSecurityPolicyElement() { CommandType = CspCommandType.Uri, DirectiveOrUri = "cdnjs.cloudflare.com" } }, CspUriType.Style)
In StringBuilderExtensions.BuildValuesForDirective, the second if statement (direvtiveValues.Any(), line 67) re-adds any Uri directives, so that cdnjs.cloudflare.com shows up twice in the policy. Probably don't need the two ifs (lines 48/67), and can just use the two wheres (lines 51/52 and 56/61)
The X-Powered-By header is still exposed in server generated responses. OwaspHeaders.Core should have the ability to remove this, if included in the SecureHeadersMiddlewareConfig.
This may require re-writing how the headers are added in the Invoke method to enable removal of headers.
This can be implemented by doing something like:
context.Response.Headers.Remove("HeaderName");
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.