Static code analysis tool for .NET Core - asp.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>

Related

ASP.NET MVC 3 Authentication cookies not working on iFrame

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>

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>

Creating referral policies in openam through ssoadm

In openam I created a subRealm named TestRealm .In order to create policies in TestRealm there should be a referral policy. Im trying to create a policies for TestRealm with the help of ssoadm command, but its throwing a error Cannot create policy. No referral exists to the organization. Im using the following policy.xml to create policies under the root realm.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Policies PUBLIC "-//OpenSSO Policy Administration DTD//EN" "jar://com/sun/identity/policy/policyAdmin.dtd">
<!-- New policy, same as the old policy -->
<Policies>
<Policy name="Test Policy" referralPolicy="false" active="true" >
<Rule name="Test Allow GET with parameters">
<ServiceName name="iPlanetAMWebAgentService" />
<ResourceName name="http://www.test.com/demo/*?*" />
<AttributeValuePair>
<Attribute name="GET" />
<Value>allow</Value>
</AttributeValuePair>
</Rule>
<Rule name="Vidz Ref Allow GET and POST">
<ServiceName name="iPlanetAMWebAgentService" />
<ResourceName name="http://www.test.com/demo/*" />
<AttributeValuePair>
<Attribute name="POST" />
<Value>allow</Value>
</AttributeValuePair>
<AttributeValuePair>
<Attribute name="GET" />
<Value>allow</Value>
</AttributeValuePair>
</Rule>
<Subjects name="Subjects" description="Everybody authenticated">
<Subject name="All Authenticated Users" type="AuthenticatedUsers" includeType="inclusive">
</Subject>
</Subjects>
</Policy>
</Policies>
How to modify the above one to create a referral policy??
The easiest way would be to simply create an example referral in the top level realm, and then just export it via ssoadm for subsequent imports. Also you should use very generic rules in referrals, like http://www.test.demo.com/* and http://www.test.demo.com/*?*, having complex rules in referrals will only slow down policy evaluation without much of a point (the referred policies will be used to make the allow/deny decision in the end anyways).

Infinispan Initial State Transfer Hangs and times out

I'm trying to cluster a pair of servers with a shared Infinispan cache (Replicated Asynchronously). One always starts successfully, and registers itself properly with the JDBC database. When the other starts, it registers properly with the database, and I see a bunch of chatter between them, then, while waiting on a response from the second server, I get
`org.infinispan.commons.CacheException: Initial statue transfer timed out`
I think it's just an issue of configuration, but I'm not sure how to debug my configuration issues. I've spent several days configuring and re-configuring my Infinispan XML, and my JGroups.xml:
Infinispan:
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:infinispan:config:6.0"
xsi:schemaLocation="urn:infinispan:config:6.0 http://www.infinispan.org/schemas/infinispan-config-6.0.xsd
urn:infinispan:config:remote:6.0 http://www.infinispan.org/schemas/infinispan-cachestore-remote-config-6.0.xsd"
xmlns:remote="urn:infinispan:config:remote:6.0"
>
<!-- *************************** -->
<!-- System-wide global settings -->
<!-- *************************** -->
<global>
<shutdown hookBehavior="DEFAULT"/>
<transport clusterName="DSLObjectCache">
<properties>
<property name="configurationFile" value="jgroups.xml"/>
</properties>
</transport>
<globalJmxStatistics enabled="false" cacheManagerName="Complex.com"/>
</global>
<namedCache name="ObjectCache">
<transaction transactionMode="TRANSACTIONAL" />
<locking
useLockStriping="false"
/>
<invocationBatching enabled="true"/>
<clustering mode="replication">
<async asyncMarshalling="true" useReplQueue="true" replQueueInterval="100" replQueueMaxElements="100"/>
<stateTransfer fetchInMemoryState="true" />
</clustering>
<eviction strategy="LIRS" maxEntries="500000"/>
<expiration lifespan="86400000" wakeUpInterval="1000" />
</namedCache>
<default>
<!-- Configure a synchronous replication cache -->
<locking
useLockStriping="false"
/>
<clustering mode="replication">
<async asyncMarshalling="true" useReplQueue="true" replQueueInterval="100" replQueueMaxElements="100"/>
<stateTransfer fetchInMemoryState="true" />
</clustering>
<eviction strategy="LIRS" maxEntries="500000"/>
<expiration lifespan="86400000" wakeUpInterval="1000" />
<persistence>
<cluster remoteCallTimeout="60000" />
</persistence>
</default>
</infinispan>
Jboss.xml:
<config xmlns="urn:org:jgroups"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:org:jgroups http://www.jgroups.org/schema/JGroups-3.0.xsd">
<!-- Default the external_addr to #DEADBEEF so we can see errors coming through
on the backend -->
<TCP
external_addr="${injected.external.address:222.173.190.239}"
receive_on_all_interfaces="true"
bind_addr="0.0.0.0"
bind_port="${injected.bind.port:12345}"
conn_expire_time="0"
reaper_interval="0"
sock_conn_timeout="20000"
tcp_nodelay="true"
/>
<JDBC_PING
datasource_jndi_name="java:jboss/datasources/dsl/control"
/>
<MERGE2 max_interval="30000" min_interval="10000"/>
<FD_SOCK
external_addr="${injected.external.address:222.173.190.239}"
bind_addr="0.0.0.0"
/>
<FD timeout="10000" max_tries="5"/>
<VERIFY_SUSPECT timeout="1500"
bind_addr="0.0.0.0"
/>
<pbcast.NAKACK use_mcast_xmit="false"
retransmit_timeouts="300,600,1200,2400,4800"
discard_delivered_msgs="true"/>
<UNICAST3 ack_batches_immediately="true"
/>
<RSVP ack_on_delivery="true"
throw_exception_on_timeout="true"
timeout="1000"
/>
<pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000"
max_bytes="400000"/>
<pbcast.GMS print_local_addr="true" join_timeout="5000"
view_bundling="true" view_ack_collection_timeout="5000"/>
<FRAG2 frag_size="60000"/>
<pbcast.STATE_SOCK
bind_port="54321"
external_addr="${injected.external.address:222.173.190.239}"
bind_addr="0.0.0.0"
/>
<pbcast.FLUSH timeout="1000"/>
</config>
I've tried, frankly, every configuration option I can think of, and I'm not sure why the replication keeps timing out. All communication between these servers is wide open. Sorry to just dump so much XML, but I'm not even sure how to collect more information.
Continued exploration indicated that Infinispan was pushing logs to the server.log, but - due to my configuration, this was not duplicated on the console. Further inspection revealed that I left a single element in my cache objects unserializable - making it impossible for it to be written to the wire and transferred. The logs are very specific, making this actually a very easy problem to track down once I realized where the logs were being written.
If you come here from the future, my advice is to just tail every single log you can on the working server, and see what comes up.

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.