ASP.NET MVC 3 Authentication cookies not working on iFrame - authentication

We are distributing an ASP.NET MVC 3.0 application (C# and .NET 4.0), and some customers had an iframe over it for some customizations, but now it has stopped working. I thought that it was related with some security changes we have made:
Set "Content-Security-Policy" to "frame-ancestors 'self'"
Force cookies properties (in global.asax.cs cause in 4.0 there isn't any other way to set the samesite property):
SameSite: Strict
Secure: true
HttpOnly: true
And after remove "Content-Security-Policy" and the cookie rewriting rule it has worked. But then, when I try to authenticate (user/password) the authentication cookie is not sent, and I can't rewrite them because they don't come with the request.
I see the following message on Cookie tab of network request/response:
"This attempt to set a cookie via a Set-Cookie header was blocked because it had the "SameSite=Lax" attibute but came from a cross-site response which was not the response to a top-level navigation".
I've read that it's related with "recent" browsers security updates and/or Windows/ASP.NET security patches, but after some research no solutions worked for me...

I've found the solution(s):
Upgrade to .NET Framework 4.7.2: Ok, I'm on 4.0, and I've plans to upgrade to 4.8 this year. I've tested on a branch, and changing some of the new cookie properties of that framework, it works.
But I've a customer that is using iframes over our website, and it isn't easy neither fast to migrate to 4.8, so I've found the solution with the URL Rewrite module of IIS. And I've included a rule for Content Security Policy to add my (their) iFrame page host. I've followed those links:
https://www.petefreitag.com/item/850.cfm
https://stackoverflow.com/a/60357945/803195
And my latest version of web.config for that customer:
<rewrite>
<outboundRules>
<preConditions>
<!-- Checks User Agent to identify browsers incompatible with SameSite=None -->
<preCondition name="IncompatibleWithSameSiteNone" logicalGrouping="MatchAny">
<add input="{HTTP_USER_AGENT}" pattern="(CPU iPhone OS 12)|(iPad; CPU OS 12)" />
<add input="{HTTP_USER_AGENT}" pattern="(Chrome/5)|(Chrome/6)" />
<add input="{HTTP_USER_AGENT}" pattern="( OS X 10_14).*(Version/).*((Safari)|(KHTML, like Gecko)$)" />
</preCondition>
</preConditions>
<!-- Adds or changes SameSite to None for the session cookie -->
<!-- Note that secure header is also required by Chrome and should not be added here -->
<rule name="SessionCookieAddNoneHeader">
<!-- Use this regex if your OS/framework/app adds SameSite=Lax automatically to the end of the cookie -->
<match serverVariable="RESPONSE_Set-Cookie" pattern="((.*)(ASP.NET_SessionId[^=]*)(=.*))(?=SameSite)" />
<action type="Rewrite" value="{R:1}; SameSite=None; Secure=true" />
</rule>
<!-- Adds or changes SameSite to None for the session cookie -->
<!-- Note that secure header is also required by Chrome and should not be added here -->
<rule name="FormsCookieAddNoneHeader">
<!-- Use this regex if your OS/framework/app adds SameSite=Lax automatically to the end of the cookie -->
<match serverVariable="RESPONSE_Set-Cookie" pattern="((.*)(ASPXFORMSAUTH[^=]*)(=.*))(?=SameSite)" />
<action type="Rewrite" value="{R:1}; SameSite=None; Secure=true" />
</rule>
<rule name="RewriteContentSecurityPolicy">
<match serverVariable="RESPONSE_Content-Security-Policy" pattern="(.*)" />
<action type="Rewrite" value="{R:0} iframehost" />
</rule>
<!-- Removes SameSite=None header from all cookies, for most incompatible browsers -->
<rule name="CookieRemoveSameSiteNone" preCondition="IncompatibleWithSameSiteNone">
<match serverVariable="RESPONSE_Set-Cookie" pattern="(.*)(SameSite=None)" />
<action type="Rewrite" value="{R:1}" />
</rule>
</outboundRules>
</rewrite>

Related

How add security headers to azure app service for containers

Im having limited success finding how to add custom http security headers (like HSTS) to an Azure app service when deployed as a docker container (linux). Im not sure if this is possible directly on the app service or something like an application gateway is required.
If using kubernetes or swarm i could do this on the reverse proxy ingress, but how can i accomplish this on an app service?
2 solutions :
Go to azure portal and under :
Your Function App -> Platform Features -> Custom Domain and set HTTPS
Only to the desired value (On).
Add this to the web.config
<outboundRules>
<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
<match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>

Static code analysis tool for .NET Core

I'm trying to find a static code analysis tool for the new .NET Core. There is ReSharper but I think .NET Core support is not really there yet. I'm not sure about other althernatives?
My search via Calculate Code Metrics for .NET Core Projects? and other investigation got me to the conclusion that we have to wait until the tooling from Microsoft, Jetbrains or others is ready.
In Resharper 2016.2 (RC version is now available) some initial work has been done; but unit tests and code analysis is announce for the post 2016.2 version. I am eager for the Early Access Versions.
NDepend and Microsoft-Tooling are lacking support today, too. I hope to see this tooling until the end of this year.
How to do this with .Net Core Analyzers...
Spent a few hours today figuring this out for myself. My answer is not authoritative, your mileage may vary.
Step 1. Install the nuget Microsoft.NetCore.Analysis into your .Net Core project.
(Code Analysis will now work).
Step 2: (Nearly inevitable) Configuring Rules
In NetFx apps you can right click on Analyzers, and edit your current ruleset. However, in .Net Core you must do this manually (AFAIK).
a. Create a File {Projectname}.ruleset next to your project file
b. Include the *.ruleset file in your project and set the build action to “C# analyzer additional file” (If you are using another language, translate for yourself).
c. Edit your project file and include:
<CodeAnalysisRuleSet>{ProjectName}.ruleset</CodeAnalysisRuleSet> in your project file.
Step 3+ rinse and repeat for each project...
(I put this just below <TargetFramework>netcoreapp2.1\</TargetFramework> but it works in individual build target environments as well).
For those used to doing this in NetFx, <runcodeanalysis>true</runcodeanalysis> is neither required, nor has any affect.
But, you say, "I dont' have a ruleset to start from, how do I get started", neither did I. Here is my manual, use at your own risk content for the *.ruleset file:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Default Code Analysis Rules for .Net Core projects" Description="Rules for {ProjectName}.csproj." ToolsVersion="15.0">
<Rules AnalyzerId="Microsoft.NetCore.Analyzers" RuleNamespace="Microsoft.NetCore.Analyzers">
<!--CA1304: Specify CultureInfo -->
<Rule Id="CA1304" Action="Warning" />
<!--CA1305: Specify IFormat provider -->
<Rule Id="CA1305" Action="Warning" />
<!--CA1307: Specify StringComparison -->
<Rule Id="CA1307" Action="Warning" />
<!--CA1308: Normalize strings to uppercase -->
<Rule Id="CA1308" Action="Warning" />
<!--CA1401: P/Invokes should not be visible -->
<Rule Id="CA1401" Action="Warning" />
<!--CA1813: Avoid unsealed attributes -->
<Rule Id="CA1813" Action="Warning" />
<!--CA1816: Dispose methods should not call SuppressFinalize -->
<Rule Id="CA1816" Action="Warning" />
<!--CA1820: Test for empty strings using string length -->
<Rule Id="CA1820" Action="Warning" />
<!--CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly -->
<Rule Id="CA1826" Action="Warning" />
<!--CA2002: Do not lock on objects with weak identity -->
<Rule Id="CA2002" Action="Warning" />
<!--CA2008: Do not create tasks without passing a TaskScheduler -->
<Rule Id="CA2008" Action="Warning" />
<!--CA2009: Do not call ToImmutableCollection on an ImmutableCollection -->
<Rule Id="CA2009" Action="Warning" />
<!--CA2101: Specify marshaling for P/Invoke string arguments -->
<Rule Id="CA2101" Action="Warning" />
<!--CA2208: Instantiate argument exceptions correctly -->
<Rule Id="CA2208" Action="Warning" />
<!--CA2216: Disposable types should declare finalizer -->
<Rule Id="CA2216" Action="Warning" />
<!--CA2241: Provide correct arguments to formatting methods -->
<Rule Id="CA2241" Action="Warning" />
<!--CA2242: Test for NaN correctly-->
<Rule Id="CA2242" Action="Warning" />
<!--CA2243: Attribute string literals should parse correctly -->
<Rule Id="CA2243" Action="Warning" />
<!--CA9999: Analyzer version mismatch -->
<Rule Id="CA9999" Action="Warning" />
</Rules>
<Rules AnalyzerId="Microsoft.NetCore.CSharp.Analyzers" RuleNamespace="Microsoft.NetCore.CSharp.Analyzers">
<!--CA1309: Use ordinal StringComparison -->
<Rule Id="CA1309" Action="Warning" />
<!--CA1414: Mark boolean PInvoke arguments with MarshalAs -->
<Rule Id="CA1414" Action="Warning" />
<!--CA1601: Do not use timers that prevent power state changes -->
<Rule Id="CA1601" Action="Warning" />
<!--CA1810: Initialize reference type static fields inline -->
<Rule Id="CA1810" Action="Warning" />
<!--CA1824: Mark assemblies with NeutralResourcesLanguageAttribute -->
<Rule Id="CA1824" Action="Warning" />
<!--CA1825: Avoid zero-length array allocations -->
<Rule Id="CA1825" Action="Warning" />
<!--CA2010: Always consume the value returned by methods marked with PreserveSigAttribute -->
<Rule Id="CA2010" Action="Warning" />
<!--CA2201: Do not raise reserved exception types -->
<Rule Id="CA2201" Action="Warning" />
<!--CA2205: Use managed equivalents of win32 api -->
<Rule Id="CA2205" Action="Warning" />
<!-- CA2207: Initialize value type static fields inline -->
<Rule Id="CA2207" Action="Warning" />
<!--CA2215: Dispose Methods Should Call Base Class Dispose -->
<Rule Id="CA2215" Action="Warning" />
<!--CA5350: Do Not Use Weak Cryptographic Algorithms (TripleDES, SHA-1, RIPEMD160)-->
<Rule Id="CA5350" Action="Warning" />
<!--CA5350: Do Not Use Broken Cryptographic Algorithms (MD5, DES, RC2)-->
<Rule Id="CA5351" Action="Warning" />
<Rules>
</RuleSet>

Redirect HTTPS to HTTP (Without SSL cert)

I was using a SSL Certificate for my website and ranked it highly in search engines. Now the SSL has expired and I no longer want to use it, is there some way to redirect my users to HTTP instead of HTTPS?
What I've tried so far is to make a personal certificate and then added a rule to transfer the users in web.config using this code
<rewrite>
<rules>
<rule name="Redirect to HTTP" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^ON$" />
</conditions>
<action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
This resulted in an error page saying my connection is not safe (Becuse of the bad SSL).
Without a certificate, no SSL/TLS connection can be made. Then how can you send a HTTP redirect response with no request over a connection? Thus, it is technically impossible to do so.
You can probably generate a self signed certificate temporarily, which means if the users accept this certificate, they can at least still visit your site, and be redirected by you to HTTP. I am not sure if a self signed certificate works for Google search spider or any other search engine though.
If possible, switch to a service provider such as CloudFlare, who offers free HTTPS certificates. That can resolve your issue without you paying a CA.

SessionAuthenticationModule Cookie Handler not creating HttpOnly secure cookie

I am using System.IdentityModel to authenticate users in an ASP.NET MVC4 web application using forms auth with a claims principal. (code based on this article: http://brockallen.com/2013/01/26/replacing-forms-authentication-with-wifs-session-authentication-module-sam-to-enable-claims-aware-identity/)
My ClaimsBasedAuthenticationService class issues the SAM cookie from the SessionSecurityToken, and all has been well...except that I just now noticed that it is not creating the session cookies as HTTPOnly or requiring them to require SSL. When I debug the code, I can see those properties on the CookieHandler object are set correctly in the debugger, but the final session cookie that is created simply doesn't have the HTTPOnly and Secure flags marked.
I have the web.config lines to set these to true explicitly as such:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
<authentication mode="Forms">
<forms ... requireSSL="true" />
</authentication>
...
</system.web>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="true" hideFromScript="true" />
</federationConfiguration>
</system.identityModel.services>
Can someone tell me if there's something else I am missing in order for my FedAuth cookies to be hidden from script (HTTPOnly) and require SSL?
I am using the same implementation and do not see your issue using Fiddler2. However maybe the issue is related to your debugging tool? In IE10 debugging tools the secure and http only flags are only displayed when the cookies are first received. If you check using Chrome debugging tools you should see the flags displayed correctly on all requests.
Did you get this working? I've been using basically the same code and it's all fine.
I can't see that the following suggestions have anything to do with anything, but the only things I can suggest, are to set the cookie lifetime
<cookieHandler hideFromScript="true" requireSsl="true" persistentSessionLifetime="30" />
<forms loginUrl="/Whereever" timeout="30" requireSSL="true" />
and
<system.webServer>
<modules>
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
</modules>
</system.webServer>

Application Initialization Module for IIS 7.5 issue

As a part of Proof of Concept utilizing the Application Initialization Module for IIS 7.5 to increase the speed of web apps initialization, I have created a simple web application hosted on IIS 7.5 (Windows Server 2008 R2) with SSL enabled. Please see global and local settings below.
If I understand correctly the way the Application Initialization Module works, I am expecting IIS to issue a request to appinit.aspx (https://localhost/alwaysrunning/appinit.aspx) to initialize the web application. This is however never happening.
Any ideas?
What is the purpose of the attribute initializationPage?
Any help with this would be greatly appreciated.
EDIT: When I disable SSL the Application Initialization Module issues a request to appinit.aspx as expected. I need to get this to work with SSL enabled though.
Zen
Global settings in the applicationHost.config file:
<add name="appinit" autoStart="true" startMode="AlwaysRunning">
<recycling logEventOnRecycle="Time, Requests, Schedule, Memory, IsapiUnhealthy, OnDemand, ConfigChange, PrivateMemory">
<periodicRestart requests="0" time="00:05:00">
<schedule>
<clear />
</schedule>
</periodicRestart>
</recycling>
<processModel identityType="NetworkService" idleTimeout="00:00:00" />
</add>
<application path="/alwaysrunning" preloadEnabled="true" applicationPool="appinit">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\alwaysrunnig" />
</application>
Local settings in application's web.config file:
<applicationInitialization remapManagedRequestsTo="splashscreen.htm" skipManagedModules="true" >
<add initializationPage="/appinit.aspx" />
</applicationInitialization>
(I know, stale question, but it's unanswered & came up in my own Google search on the subject.)
Refer to the following article from Microsoft Support:
Application Initialization module fails when web site requires SSL (KB2843964). Quote:
Cause
This behavior is by design.
Resolution
To workaround this limitation, you may consider enabling HTTP (uncheck
the "Require SSL" setting in IIS Manager/SSL Settings) and use a URL
Rewrite rule to redirect HTTP requests to HTTPS with the exception of
the request coming from the warmup module :
<rewrite>
<rules>
<rule name="No redirect on warmup request (request from localhost with warmup user agent)" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" />
<add input="{HTTP_USER_AGENT}" pattern="Initialization" />
</conditions>
<action type="Rewrite" url="{URL}" />
</rule>
<rule name="HTTP to HTTPS redirect for all requests" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
Gotta love "This behavior is by design." Sigh. Sadly, the top search results I found about this Application Initialization feature fail to mention this limitation — unless one interprets "HTTP request" as strictly meaning non-secure requests.