<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>saurabs</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/saurabs/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/saurabs/feed.xml</link>
    <description />
    <lastBuildDate>Mon, 18 Jun 2018 18:15:00 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>WCF: Verbose PII Tracing</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcf-verbose-pii-tracing</link>
      <pubDate>Mon, 18 Jun 2018 18:15:00 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=1055</guid>
      <description><![CDATA[WCF PII Verbose tracing
====

Depending on app built, update the machine.config file

Add...]]></description>
      <content:encoded><![CDATA[WCF PII Verbose tracing
====

Depending on app built, update the machine.config file

Add line:
&lt;machineSettings enableLoggingKnownPii="true"/&gt;

&nbsp;

&lt;!-- Sample --&gt;
&lt;system.serviceModel&gt;
&lt;machineSettings enableLoggingKnownPii="true"/&gt;

&nbsp;

<strong>OUTSIDE &lt;System.ServiceModel&gt; tag add below lines:</strong>

&lt;system.diagnostics&gt;
&lt;sources&gt;
&lt;source logKnownPii="true" name="System.ServiceModel.MessageLogging"
switchValue="Verbose,ActivityTracing"&gt;
&lt;listeners&gt;
&lt;add type="System.Diagnostics.DefaultTraceListener" name="Default"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;add name="ServiceModelMessageLoggingListener"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing"&gt;
&lt;listeners&gt;
&lt;add type="System.Diagnostics.DefaultTraceListener" name="Default"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;add name="ServiceModelTraceListener"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;/sources&gt;
&lt;sharedListeners&gt;
&lt;add initializeData="c:\temp\app_messages.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelMessageLoggingListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;add initializeData="c:\temp\app_tracelog.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"&gt;
&lt;filter type="" /&gt;
&lt;/add&gt;
&lt;/sharedListeners&gt;
&lt;/system.diagnostics&gt;

&nbsp;

&nbsp;

<strong>INSIDE &lt;System.ServiceModel&gt; tag add below lines:</strong>

&lt;system.serviceModel&gt;
&lt;diagnostics&gt;
&lt;messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" /&gt;
&lt;endToEndTracing propagateActivity="true" activityTracing="true"
messageFlowTracing="true" /&gt;
&lt;/diagnostics&gt;

&nbsp;

&nbsp;

<strong>ONCE DONE, we should see following entry in Event logs</strong>
============
PII logging has been turned on. Sensitive information will be logged in the clear.
Process Name: ConsoleApplication1.vshost
Process ID: 5996

&nbsp;

&nbsp;

- &lt;Event xmlns="https://schemas.microsoft.com/win/2004/08/events/event"&gt;
- &lt;System&gt;
&lt;Provider Name="System.ServiceModel 4.0.0.0" /&gt;
&lt;EventID Qualifiers="49153"&gt;107&lt;/EventID&gt;
&lt;Level&gt;4&lt;/Level&gt;
&lt;Task&gt;7&lt;/Task&gt;
&lt;Keywords&gt;0x80000000000000&lt;/Keywords&gt;
&lt;TimeCreated SystemTime="2018-02-06T00:56:31.835601400Z" /&gt;
&lt;EventRecordID&gt;133301&lt;/EventRecordID&gt;
&lt;Channel&gt;Application&lt;/Channel&gt;
&lt;Computer&gt;CC.XX.XXX.XXX&lt;/Computer&gt;
&lt;Security UserID="XXX.XXX" /&gt;
&lt;/System&gt;
- &lt;EventData&gt;
&lt;Data&gt;ConsoleApplication1.vshost&lt;/Data&gt;
&lt;Data&gt;5996&lt;/Data&gt;
&lt;/EventData&gt;
&lt;/Event&gt;

&nbsp;

I hope this helps :)

Thanks

SS]]></content:encoded>
    </item>
    <item>
      <title>WS/WCF: Remove Server Header</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wswcf-remove-server-header</link>
      <pubDate>Mon, 18 Dec 2017 14:06:51 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=1046</guid>
      <description><![CDATA[Requirement:
Need to suppress all instances of the HTTP ‘Server’ header from all HTTP responses...]]></description>
      <content:encoded><![CDATA[<strong>Requirement:</strong>
Need to suppress all instances of the HTTP ‘Server’ header from all HTTP responses including invalid requests that never even reach the application process.

<strong>Why we need this:</strong>
Exposing Server headers as part of response payload is security vulnerability documented under https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html section 14.38.

<strong>Workaround for Self Host WCF Services:</strong>
Set below registry flag to: <strong>2</strong>
<em>HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\DisableServerHeader</em>

Setting this to 2 will ensure that self host WCF services no longer sends the SERVER header and thus ensure we are security compliant.
Please note that this disables ALL server headers. 

The default value of 0 enables the header, and the value of 1 disables server header from DRIVER (http.sys), but app can still have headers.


<strong>Workaround for IIS hosted applications</strong>
1. Stop the World Wide Web Publishing Service (if IIS services are not required on the server).
2. If they are required, then we would need to use the IIS URL Rewrite module and delete the server header itself.
Refer: https://blogs.msdn.microsoft.com/varunm/2013/04/23/remove-unwanted-http-response-headers/ 


I hope this helps!


Thanks
Saurabh Somani
]]></content:encoded>
    </item>
    <item>
      <title>WCF/WS: SSL Mutual Client Cert Authentication 403.16 or 403.7</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcfws-ssl-mutual-client-cert-authentication-403-16-or-403-7</link>
      <pubDate>Mon, 12 Jun 2017 11:24:34 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=1005</guid>
      <description><![CDATA[Problem
When attempting to use a certificate to authenticate to an IIS website or self hosted WCF...]]></description>
      <content:encoded><![CDATA[<strong>Problem</strong>
When attempting to use a certificate to authenticate to an IIS website or self hosted WCF service over SSL/TLS channel, we receive a 403.16 error code. 

<strong>Troubleshooting</strong>
We can collect server side System.Net Traces or WCF Activity Traces
https://blogs.msdn.microsoft.com/saurabs/2017/06/12/system-net-tracing-collection-steps/
https://blogs.msdn.microsoft.com/saurabs/2017/06/12/wcf-tracing/

<strong>Observation from System.Net Traces:</strong>
You might observe the GetClientCertificate API was successful and Client Cert was received at server side.
From WCF traces you might see a native error (0X109) being sent with below stack.


https://msdn.microsoft.com/en-US/library/System.ServiceModel.Channels.HttpsClientCertificateInvalid.aspx
Client certificate is invalid with native error code 0x109 (see https://go.microsoft.com/fwlink/?LinkId=187517 for details).
Process.exe
System.ServiceModel.Channels.HttpsChannelListener`1[System.ServiceModel.Channels.IReplyChannel]/11268815
Keep-Alive
text/html, application/xhtml+xml, */*
gzip, deflate
en-US
X.X.X.X:YY
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
https://Service/Method
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Diagnostics.TraceEventCache.get_Callstack()
at System.Diagnostics.XmlWriterTraceListener.WriteFooter(TraceEventCache eventCache)
at System.Diagnostics.XmlWriterTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data)
at System.Diagnostics.TraceSource.TraceData(TraceEventType eventType, Int32 id, Object data)
at System.ServiceModel.Diagnostics.LegacyDiagnosticTrace.TraceEvent(TraceEventType type, Int32 code, String msdnTraceCode, String description, TraceRecord trace, Exception exception, Object source)
at System.ServiceModel.Diagnostics.TraceUtility.TraceEvent(TraceEventType severity, Int32 traceCode, String traceDescription, TraceRecord extendedData, Object source, Exception exception)
at System.ServiceModel.Channels.HttpsChannelListener`1.ValidateAuthentication(HttpListenerContext listenerContext)
at System.ServiceModel.Channels.HttpRequestContext.ListenerHttpContext.ValidateAuthentication()
at System.ServiceModel.Channels.HttpRequestContext.ProcessAuthentication()
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.Authenticate()
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SharedHttpTransportManager.EnqueueContext(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult listenerContextResult)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.ListenerAsyncResult.IOCompleted(ListenerAsyncResult asyncResult, UInt32 errorCode, UInt32 numBytes)
at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)



<strong>Cause</strong>
The cause of this was due to having non-self-signed certs in the Trusted Root Certificate Authority store on the IIS server.  
https://support.microsoft.com/en-us/kb/2802568

If we have a non-self-signed certificates in the Trusted Root certificate store. We can run this command to check:
Get-Childitem cert:\LocalMachine\root -Recurse | Where-Object {$_.Issuer -ne $_.Subject} | Format-List * | Out-File "c:\computer_filtered.txt"

Only self-signed certs should be located in this store. If there are any non self-signed, then they should be exported for backup and deleted from the trusted roost certificate authority store. Computer_filtered.txt should not have any certs listed in it. 

ClientAuthTrustMode controls how client cert are validated at S-Channel level.

Value	Trust Mode	Description
0	Machine Trust (default)	Requires that the client certificate is issued by a certificate in the trusted issuers list.
1	Exclusive Root Trust	Requires that a client certificate is chained to a root certificate that is contained in the caller-specified trusted issuer store. The certificate must also be issued from the trusted issuers list.
2	Exclusive CA Trust	Requires that a client certificate is chained to an intermediate CA certificate or to a root certificate in the caller-specified trusted issuer store.


<strong>Resolution</strong>
If there are non-self signed certs in the trusted root store but we do not want to delete them, the work around would be setting this reg key and then rebooting the server. 
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL ClientAuthTrustMode =dword:00000002

Changing it to a value of 2 means the client cert has to chain to a intermediate CA cert or Root CA cert in the caller-specified trusted issuer store. Even if we have not specified a specifc cert trust list store (CTL store). In that case, we will still use the Trusted Root CA store. However, because value 2 states it can chain to a “intermediate CA cert” or “root certificate”, then we do not run into the issue of having subCA certs in the root CA store. 

The preferred method would be to keep the value to 0 and remove the unneeded certs from the Root CA store. However, if we feel that is not possible, then changing this to a value of 2 should fix this issue. 
From my research the only effect this has is, it allows the application / http.sys binding to specify a different trusted issuer store other then the Root CA store. In case we do not specify it, s-channel just bypasses the check to look for non-self-signed certs in the Root CA store. 


<strong>Other Information</strong>
Client Authentication mapping
https://msdn.microsoft.com/en-us/library/aa292114(v=vs.71).aspx
https://www.iis.net/configreference/system.webserver/security/authentication/iisclientcertificatemappingauthentication
https://support.microsoft.com/en-us/kb/907274
https://technet.microsoft.com/en-us/library/cc770480(v=ws.10).aspx


I hope this helps!

Thanks
Saurabh Somani]]></content:encoded>
    </item>
    <item>
      <title>WCF Tracing</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcf-tracing</link>
      <pubDate>Mon, 12 Jun 2017 11:14:12 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=1045</guid>
      <description><![CDATA[WCF Tracing can be configured at three different levels.

1. WCF Verbose Traces: Recommended for...]]></description>
      <content:encoded><![CDATA[<strong>WCF Tracing can be configured at three different levels.</strong>

<strong>1. WCF Verbose Traces: Recommended for DEV issue (captures activities and messages).</strong>
<pre>INCLUDE THIS SECTION INSIDE CONFIGURATION FILE OF WCF SERVICE / CLIENT APPLICATION. 
IF ALREADY A SIMILAR SECTION IS AVAILABLE, THEN DELETE THE EXISTING SECTION FIRST.
SET VALUE OF 'initializeData' UNDER '&lt;sharedListeners&gt;' TO POINT AT AN ABSOLUTE FOLDER PATH. EXAMPLE : C:\TEMP\app_messages.svclog
===================================================================================================================================

    &lt;system.diagnostics&gt;
        &lt;sources&gt;
            &lt;source name="System.ServiceModel.MessageLogging" switchValue="Verbose,ActivityTracing"&gt;
                &lt;listeners&gt;
                    &lt;add type="System.Diagnostics.DefaultTraceListener" name="Default"&gt;
                        &lt;filter type="" /&gt;
                    &lt;/add&gt;
                    &lt;add name="ServiceModelMessageLoggingListener"&gt;
                        &lt;filter type="" /&gt;
                    &lt;/add&gt;
                &lt;/listeners&gt;
            &lt;/source&gt;
            &lt;source name="System.ServiceModel" switchValue="Verbose,ActivityTracing"
                propagateActivity="true"&gt;
                &lt;listeners&gt;
                    &lt;add type="System.Diagnostics.DefaultTraceListener" name="Default"&gt;
                        &lt;filter type="" /&gt;
                    &lt;/add&gt;
                    &lt;add name="ServiceModelTraceListener"&gt;
                        &lt;filter type="" /&gt;
                    &lt;/add&gt;
                &lt;/listeners&gt;
            &lt;/source&gt;
        &lt;/sources&gt;
        &lt;sharedListeners&gt;
            &lt;add initializeData="web_messages.svclog"
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                name="ServiceModelMessageLoggingListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"&gt;
                &lt;filter type="" /&gt;
            &lt;/add&gt;
            &lt;add initializeData="web_tracelog.svclog"
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                name="ServiceModelTraceListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"&gt;
                &lt;filter type="" /&gt;
            &lt;/add&gt;
        &lt;/sharedListeners&gt;
    &lt;/system.diagnostics&gt;

THIS PART WILL GO INSIDE &lt;system.servicemodel&gt; SECTION
=============================================================================================
    &lt;diagnostics&gt;
      &lt;messageLogging logEntireMessage="true" logMalformedMessages="true"
        logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
        maxSizeOfMessageToLog="52428800" /&gt;
    &lt;/diagnostics&gt;

EXAMPLE :
=========
&lt;system.serviceModel&gt;
        &lt;diagnostics&gt;
            &lt;messageLogging logEntireMessage="true" logMalformedMessages="true"
                logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
                maxSizeOfMessageToLog="26214445" /&gt;
        &lt;/diagnostics&gt;
        &lt;bindings&gt;
    .
    .</pre>
<strong>2. WCF Activity Traces: Recommended for Performance issues (captures only activities).</strong>
<pre>INCLUDE THIS SECTION INSIDE CONFIGURATION FILE OF WCF SERVICE / CLIENT APPLICATION. 
IF ALREADY A SIMILAR SECTION IS AVAILABLE, THEN DELETE THE EXISTING SECTION FIRST.
SET VALUE OF 'initializeData' UNDER '&lt;sharedListeners&gt;' TO POINT AT AN ABSOLUTE FOLDER PATH. EXAMPLE : C:\TEMP\web_tracelog.svclog
===================================================================================================================================

  &lt;system.diagnostics&gt;
    &lt;sources&gt;
      &lt;source name="System.ServiceModel" switchValue="Verbose,ActivityTracing"
        propagateActivity="true"&gt;
        &lt;listeners&gt;
          &lt;add type="System.Diagnostics.DefaultTraceListener" name="Default"&gt;
            &lt;filter type="" /&gt;
          &lt;/add&gt;
          &lt;add name="ServiceModelTraceListener"&gt;
            &lt;filter type="" /&gt;
          &lt;/add&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
    &lt;/sources&gt;
    &lt;sharedListeners&gt;
      &lt;add initializeData="web_tracelog.svclog"
        type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        name="ServiceModelTraceListener" traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack"&gt;
        &lt;filter type="" /&gt;
      &lt;/add&gt;
    &lt;/sharedListeners&gt;
  &lt;/system.diagnostics&gt;</pre>
<strong>3. WCF Warning level traces: Recommended for Production server (captures only warning/exceptions).</strong>
<pre>https://docs.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/recommended-settings-for-tracing-and-message-logging
</pre>

<strong>Special: WCF+System.Net Traces</strong>
<pre>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;system.diagnostics&gt;
    &lt;sources&gt;
      &lt;source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" propagateActivity="true" &gt;
        &lt;listeners&gt;
          &lt;add name="xml"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
      &lt;source name="System.ServiceModel.MessageLogging"&gt;
        &lt;listeners&gt;
          &lt;add name="xml"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
      &lt;source name="System.Net"&gt;
        &lt;listeners&gt;
          &lt;add name="System.Net"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
      &lt;source name="System.Net.HttpListener"&gt;
        &lt;listeners&gt;
          &lt;add name="System.Net"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
      &lt;source name="System.Net.Sockets"&gt;
        &lt;listeners&gt;
          &lt;add name="System.Net"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
      &lt;source name="System.Net.Cache"&gt;
        &lt;listeners&gt;
          &lt;add name="System.Net"/&gt;
        &lt;/listeners&gt;
      &lt;/source&gt;
    &lt;/sources&gt;
    &lt;sharedListeners&gt;
      &lt;add name="xml"
               type="System.Diagnostics.XmlWriterTraceListener"
                     initializeData="C:\temp\WCFTraces.svclog" /&gt;
      &lt;add name="System.Net" type="System.Diagnostics.TextWriterTraceListener"
      initializeData="c:\temp\SNtrace.log" traceOutputOptions = "DateTime" /&gt;
    &lt;/sharedListeners&gt;

    &lt;switches&gt;
      &lt;add name="System.Net" value="Verbose" /&gt;
      &lt;add name="System.Net.Sockets" value="Verbose" /&gt;
      &lt;add name="System.Net.Cache" value="Verbose" /&gt;
      &lt;add name="System.Net.HttpListener" value="Verbose" /&gt;
    &lt;/switches&gt;

  &lt;/system.diagnostics&gt;
  &lt;system.serviceModel&gt;
    &lt;diagnostics&gt;
      &lt;messageLogging logEntireMessage="true" logMalformedMessages="true"
          logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" /&gt;
    &lt;/diagnostics&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;</pre>
&nbsp;

I hope this helps!

Thanks
Saurabh Somani]]></content:encoded>
    </item>
    <item>
      <title>System.Net Tracing collection Steps</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/system-net-tracing-collection-steps</link>
      <pubDate>Mon, 12 Jun 2017 11:02:33 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=1025</guid>
      <description><![CDATA[Ask:
System.Net Tracing is very helpful to review SSL/TLS and socket level connection/communication...]]></description>
      <content:encoded><![CDATA[<strong>Ask:</strong>
System.Net Tracing is very helpful to review SSL/TLS and socket level connection/communication failure.

<strong>To enabled tracing<code>:</code></strong>

&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
&lt;system.diagnostics&gt;
&lt;trace autoflush="true" /&gt;
&lt;sources&gt;
&lt;source name="System.Net"&gt;
&lt;listeners&gt;
&lt;add name="System.Net"/&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;source name="System.Net.HttpListener"&gt;
&lt;listeners&gt;
&lt;add name="System.Net"/&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;source name="System.Net.Sockets"&gt;
&lt;listeners&gt;
&lt;add name="System.Net"/&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;source name="System.Net.Cache"&gt;
&lt;listeners&gt;
&lt;add name="System.Net"/&gt;
&lt;/listeners&gt;
&lt;/source&gt;
&lt;/sources&gt;
&lt;sharedListeners&gt;
&lt;add
name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\traces\System.Net.trace.log"
traceOutputOptions="DateTime"
/&gt;
&lt;/sharedListeners&gt;
&lt;switches&gt;
&lt;add name="System.Net" value="Verbose" /&gt;
&lt;add name="System.Net.Sockets" value="Verbose" /&gt;
&lt;add name="System.Net.Cache" value="Verbose" /&gt;
&lt;add name="System.Net.HttpListener" value="Verbose" /&gt;
&lt;/switches&gt;
&lt;/system.diagnostics&gt;
&lt;/configuration&gt;

<code> </code><strong>Trace Location:</strong>
Set the below path.
initializeData="c:\traces\System.Net.trace.log"

<strong>To review:</strong>
I would recommend using Notepad++.
Few pointers:
https://blogs.msdn.microsoft.com/saurabs/2012/08/16/wcf-troubleshooting-socket-abort-errors/
https://blogs.msdn.microsoft.com/saurabs/2016/03/07/wcf-review-system-net-and-network-traces-for-windows-authenticationdelegation-based-troubleshooting/
https://blogs.msdn.microsoft.com/webapps/2012/11/05/use-system-net-trace-and-ssl-alert-protocol-to-troubleshoot-ssl-connection-issue/

I hope this helps!
Saurabh Somani]]></content:encoded>
    </item>
    <item>
      <title>ASMX/WS/WCF Web Service:  System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/asmxwswcf-web-service-system-net-sockets-socketexception-an-existing-connection-was-forcibly-closed-by-the-remote-host</link>
      <pubDate>Mon, 05 Jun 2017 13:44:57 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=995</guid>
      <description><![CDATA[Issue:
Intermittent Socket exception seen on client application trying to fetch data from MS web...]]></description>
      <content:encoded><![CDATA[<strong>Issue:</strong>
Intermittent Socket exception seen on client application trying to fetch data from MS web services.

<strong>Troubleshooting:</strong>
I recommend collecting application level traces to collect the stack trace information. In addition we can collect the System.Net traces or memory dumps on specific exceptions.

<strong>Detailed stack from dump:</strong>
0:000&gt; !dumpstack
OS Thread Id: 0x1708 (0)
Current frame: KERNELBASE!RaiseException+0x58
ChildEBP RetAddr  Caller, Callee
002dd7fc 7503c54f KERNELBASE!RaiseException+0x58, calling ntdll!RtlRaiseException
002dd82c 72440769 (MethodDesc 7228a444 +0x401 System.Net.ConnectStream.CloseInternal(Boolean, Boolean)), calling (MethodDesc 722f5b60 +0 System.Net.ConnectStream.CallDone(System.Net.ConnectionReturnResult))
002dd844 7402a769 clr!RaiseTheExceptionInternalOnly+0x27c, calling kernel32!RaiseExceptionStub
002dd8e0 7402af54 clr!IL_Throw+0x138, calling clr!RaiseTheExceptionInternalOnly
002dd944 7402aea1 clr!IL_Throw+0x3c, calling clr!LazyMachStateCaptureState
002dd94c 7402c4a4 clr!IL_Rethrow+0x27, calling clr!LazyMachStateCaptureState
002dd950 72887df0 (MethodDesc 722f5ca4 +0x140 System.Net.ConnectStream.IOError(System.Exception, Boolean)), calling (MethodDesc 722f5b60 +0 System.Net.ConnectStream.CallDone(System.Net.ConnectionReturnResult))
002dd970 723f6845 (MethodDesc 722f5bb4 +0xc5 System.Net.ConnectStream.ReadWithoutValidation(Byte[], Int32, Int32, Boolean)), calling clr!IL_Rethrow
002dd9a8 723f6726 (MethodDesc 7228a3dc +0x136 System.Net.ConnectStream.Read(Byte[], Int32, Int32)), calling clr!IL_Throw
002ddaa0 73018a56 (MethodDesc 72d67e88 +0xe2 System.IO.StreamReader.ReadBuffer(Char[], Int32, Int32, Boolean ByRef))
002ddac0 7301893b (MethodDesc 72d67e34 +0x7b System.IO.StreamReader.Read(Char[], Int32, Int32)), calling (MethodDesc 72d67e88 +0 System.IO.StreamReader.ReadBuffer(Char[], Int32, Int32, Boolean ByRef))
002ddae8 7010c168 (MethodDesc 70069474 +0xe8 System.Xml.XmlTextReaderImpl.ReadData())

The code, clearly indicates that we are indeed running in a catch block and thus error is thrown.
https://referencesource.microsoft.com/#System/net/System/Net/_ConnectStream.cs,17c93c1ab8aca75d 


<strong>To mitigate the issue, following workaround is suggested (please review with your network admin before trying them):</strong>

<em>Command to disable SNP features :</em>
netsh interface tcp set global chimney=disabled
netsh interface tcp set global rss=disabled
netsh int tcp set global autotuning=disabled
netsh int tcp set global congestion=none
netsh int tcp set global netdma=Disabled
 
<em>For disabling the offloading:</em>
Open NCPA.cpl on command prompt and open NIC properties and disable the following features :
ARP offload                                     -----Disable
Jumbo packet                                    -----Disable
ipv4 Checksum Offload                           -----Disable                                         
Jumbo packet                                    -----Disable
Large send Offload V2 (ipv4)                    -----Disable
Large send Offload V2 (ipv6)                    -----Disable
NS offload-                                     ----Disable
TCP Checksum Offload (ipv4)                     -----Disable
TCP Checksum Offload (ipv6)                     -----Disable
UDP Checksum Offload (ipv4)                     -----Disable
UDP Checksum Offload (Ipv6)                     -----Disable


<strong>References:</strong>
https://blogs.technet.com/b/onthewire/archive/2014/01/21/tcp-offloading-chimney-amp-rss-what-is-it-and-should-i-disable-it.aspx
https://support.microsoft.com/en-us/help/951037/information-about-the-tcp-chimney-offload,-receive-side-scaling,-and-network-direct-memory-access-features-in-windows-server-2008


Hope this helps!

Thanks
Saurabh Somani
]]></content:encoded>
    </item>
    <item>
      <title>WCF/WS/TLS: Get .Net Framework 4.0 application use TLS 1.2 as default protocol</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcfwstls-get-net-framework-4-0-application-use-tls-1-2-as-default-protocol</link>
      <pubDate>Thu, 01 Jun 2017 10:59:03 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=985</guid>
      <description><![CDATA[Issue:
By default, .net application built on framework 4.0 will use SSL3.0 or TLS1.0 as default...]]></description>
      <content:encoded><![CDATA[<strong>Issue:</strong>
By default, .net application built on framework 4.0 will use SSL3.0 or TLS1.0 as default protocol. 

<strong>Ask:</strong>
If we need to force it to use TLS1.2 protocol, review below workarounds.

<strong>Workaround 1:</strong>
Use below link just before Https call is attempted.
      <strong>ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;</strong>

<strong>Workaround 2:</strong>
Migrate the existing application to supported framework 4.6.2. After migrating client app will be default use the TLS1.2 protocol.
However, I observed that it works well for console app but not for ASMX web service migration.

<strong>Error:</strong>
We might observe below error in S-Channel event logs:
Event Id: 36871
A fatal error occurred while creating an SSL client credential. The internal error state is 10013.

<strong>Schannel error state 10013 = Cred_InitEnabledProtocolsFailed </strong>
Basically this means that the application requested a protocol that is not enabled (TLS 1.0). This seems to mean that the application can only use TLS 1.0. DOT NET has an out of the box hard set for lower crytpo. 

<strong>From System.Net Traces</strong>
System.Net Information: 0 : [1828] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
    DateTime=2017-06-15T20:33:31.4129394Z
System.Net Error: 0 : [1828] AcquireCredentialsHandle() failed with error 0X80090331.

Please review below steps to get web service (any .net app) use TLS 1.2 by default to make outbound calls.
https://blogs.msdn.microsoft.com/tdevere/2014/11/11/ssl-handshake-clienthello-receives-encrypted-alert/
https://technet.microsoft.com/en-us/library/mt791311(v=office.16).aspx

Set the registry key "SchUseStrongCrypto" to 1. Which will force .net application to avoid using SSL3.0 or TLS1.0 and it will always use TLS1.2

I hope this helps!


Thanks
Saurabh Somani
]]></content:encoded>
    </item>
    <item>
      <title>WIF: WIF10201: No valid key mapping found for securityToken:</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wif-wif10201-no-valid-key-mapping-found-for-securitytoken</link>
      <pubDate>Thu, 27 Apr 2017 20:49:22 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=975</guid>
      <description><![CDATA[Issue:
WIF10201: No valid key mapping found for securityToken:
This exception is observed on a...]]></description>
      <content:encoded><![CDATA[<strong>Issue</strong>:
<em>WIF10201: No valid key mapping found for securityToken:</em>
This exception is observed on a federated application(web app / mvc / asmx / wcf) using WIF pipeline to authenticate the user.

<strong>Stack</strong>:
[SecurityTokenValidationException: WIF10201: No valid key mapping found for securityToken: 'System.IdentityModel.Tokens.X509SecurityToken' and issuer: 'LocalSTS'.]
System.IdentityModel.Tokens.SamlSecurityTokenHandler.ValidateToken(SecurityToken token) +987
System.IdentityModel.Tokens.SecurityTokenHandlerCollection.ValidateToken(SecurityToken token) +73
System.IdentityModel.Services.TokenReceiver.AuthenticateToken(SecurityToken token, Boolean ensureBearerToken, String endpointUri) +110
System.IdentityModel.Services.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequestBase request) +527
System.IdentityModel.Services.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +381
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +69

<strong>Root cause:</strong>
This error is triggered because of the mandatory code validation in WIF module to check the incoming request Signing token.

// System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry
public override string GetIssuerName(SecurityToken securityToken)
{
if (securityToken == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityToken");
}
X509SecurityToken x509SecurityToken = securityToken as X509SecurityToken;
if (x509SecurityToken != null)
{
<strong>  string thumbprint = x509SecurityToken.Certificate.Thumbprint;  &lt;----------------</strong>
if (this._configuredTrustedIssuers.ContainsKey(thumbprint))
{
string text = this._configuredTrustedIssuers[thumbprint];
text = (string.IsNullOrEmpty(text) ? x509SecurityToken.Certificate.Subject : text);
if (TD.GetIssuerNameSuccessIsEnabled())
{
TD.GetIssuerNameSuccess(EventTraceActivity.GetFromThreadOrCreate(false), text, securityToken.Id);
}
return text;
}
}
if (TD.GetIssuerNameFailureIsEnabled())
{
TD.GetIssuerNameFailure(EventTraceActivity.GetFromThreadOrCreate(false), securityToken.Id);
}
return null;
}

<strong>Summary:</strong>
<pre>So eventually we try to read the current token associated with the request
<span style="text-decoration: underline">string thumbprint = x509SecurityToken.Certificate.Thumbprint</span>

And then compare it with the config file entry for our project.
<span style="text-decoration: underline">string text = this._configuredTrustedIssuers[thumbprint];</span>

Two checks done:
===========
1. Validate if the existing request security token's thumbprint is already present inside the in memory dictionary object
<strong>this._configuredTrustedIssuers</strong>.

2. If it is not there, we return Null.
3. If it is there, we compare the  subject name of incoming token with in memory value and pass from there..

All these check are to make sure that we receive the request signed from same issuer which was initially trusted on the main app.


<strong>Solution:</strong>
To solve this error we need to make sure we have added proper key inside the Federated app configuration file to respective issuer.

</pre>
<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">system.identityModel</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">identityConfiguration</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">audienceUris</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">add</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">value</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">https://localhost:1442/</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> /&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">audienceUris</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">issuerNameRegistry</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">type</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">authority</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">name</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">LocalSTS</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">keys</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<strong><span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">add</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">thumbprint</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">9B74CB2F320F7AAFC156E1252270B1DC01EF40D1</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> /&gt;</span></strong>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">keys</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">validIssuers</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">add</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">name</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">LocalSTS</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> /&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">validIssuers</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">authority</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">issuerNameRegistry</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;</span><span style="color: #a31515;font-family: Consolas;font-size: small">certificateValidation</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> </span><span style="color: #ff0000;font-family: Consolas;font-size: small">certificateValidationMode</span><span style="color: #0000ff;font-family: Consolas;font-size: small">=</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small">None</span><span style="font-family: Consolas;font-size: small">"</span><span style="color: #0000ff;font-family: Consolas;font-size: small"> /&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">identityConfiguration</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>

<span style="color: #0000ff;font-family: Consolas;font-size: small"> &lt;/</span><span style="color: #a31515;font-family: Consolas;font-size: small">system.identityModel</span><span style="color: #0000ff;font-family: Consolas;font-size: small">&gt;</span>
<pre>If the thumbprint used here is invalid and does not match with the incoming Token - Base 4 encoded value. It fails!


<strong>Solution:</strong>
To get it working, we would need to extract and use the correct thumbprint.

1. Check the Base 64 encoded value of incoming request via fiddler or Freb logs and find the correct Signing Cert at STS. Get the thumbprint.
2. Use below code to create Thumbprint out of base 64 encoded value.

</pre>
<span style="font-family: Consolas;font-size: small"> </span><span style="color: #0000ff;font-family: Consolas;font-size: small">string</span><span style="font-family: Consolas;font-size: small"> _publicKey = </span><span style="color: #a31515;font-family: Consolas;font-size: small">"Base64encodedString"</span><span style="font-family: Consolas;font-size: small">;</span>

<span style="font-family: Consolas;font-size: small"> </span><span style="color: #0000ff;font-family: Consolas;font-size: small">var</span><span style="font-family: Consolas;font-size: small"> cert = </span><span style="color: #0000ff;font-family: Consolas;font-size: small">new</span><span style="font-family: Consolas;font-size: small"> </span><span style="color: #2b91af;font-family: Consolas;font-size: small">X509Certificate2</span><span style="font-family: Consolas;font-size: small">(</span><span style="color: #2b91af;font-family: Consolas;font-size: small">Convert</span><span style="font-family: Consolas;font-size: small">.FromBase64String(_publicKey), </span><span style="color: #a31515;font-family: Consolas;font-size: small">"password"</span><span style="font-family: Consolas;font-size: small">, </span><span style="color: #2b91af;font-family: Consolas;font-size: small">X509KeyStorageFlags</span><span style="font-family: Consolas;font-size: small">.PersistKeySet);</span>

<span style="font-family: Consolas;font-size: small"> </span><span style="color: #0000ff;font-family: Consolas;font-size: small">if</span><span style="font-family: Consolas;font-size: small"> (cert != </span><span style="color: #0000ff;font-family: Consolas;font-size: small">null</span><span style="font-family: Consolas;font-size: small">)</span>

{

<span style="font-family: Consolas;font-size: small"> </span><span style="color: #008000;font-family: Consolas;font-size: small">//use Cert</span>

}
<pre>I hope this helps everyone stuck with same error.

Thanks
Saurabh Somani</pre>]]></content:encoded>
    </item>
    <item>
      <title>WCF: Federating WCF with WIF</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcf-federating-wcf-with-wif</link>
      <pubDate>Mon, 24 Apr 2017 19:19:00 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=935</guid>
      <description><![CDATA[Ask:

Federate WCF service via WIF

&nbsp;

Traditional approach:

For normal web app or MVC...]]></description>
      <content:encoded><![CDATA[<strong>Ask:</strong>

Federate WCF service via WIF

&nbsp;

<strong>Traditional approach:</strong>

For normal web app or MVC app, we follow the concept of FedAuth cookie.

Client -&gt; Federated Application, gets redirected to STS

Client -&gt; STS, get claims

Client -&gt; Federated Application validates claims and issue a Fed Auth Cookie.

Client -&gt; This time call made with Fed Auth cookie and Federated application serves the request.

&nbsp;

<strong>Approach for WCF Service:</strong>

WCF service by default uses the ws2007FederationHttpBinding.

This is a special binding designed to federate the WCF service. However, it does not work on above traditional approach. Rather this works on WCF Message Security principle.

Client -&gt; Federated Application, get redirected to STS

Client -&gt; Does Security Negotiation to get the SCT (Security Context Token) via RST/Issue Action.

Client (using SCT Token and Claims received via STS) -&gt; Federated Application, here claims can be checked.

<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled41.png"><img width="720" height="210" class="alignleft size-full wp-image-937" alt="untitled4" src="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled41.png" /></a>

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;


In above screen we can see that there is only one RST/Issue or SCT call made between two calls to “GetData()” method. Because with WCF federation, we work on concept of using the WCF channel or SCT token negotiated with STS. There is no concept of FedAuth cookie, because WCF Federation is all about using Message Security protocol.

&nbsp;

<a href="https://msdn.microsoft.com/en-us/library/bb675187(v=vs.110).aspx">https://msdn.microsoft.com/en-us/library/bb675187(v=vs.110).aspx</a>

WsFederation2007HttpBindindm only support Message Level security.

&lt;ws2007FederationBinding&gt;

&lt;binding &gt;

&lt;security mode="None/Message/TransportWithMessageCredential"&gt;

&lt;message negotiateServiceCredential="Boolean"

algorithmSuite="Basic128/Basic192/Basic256/Basic128Rsa15/ Basic256Rsa15/TripleDes/TripleDesRsa15/Basic128Sha256/Basic192Sha256/TripleDesSha256/Basic128Sha256Rsa15/Basic192Sha256Rsa15/Basic256Sha256Rsa15/TripleDesSha256Rsa15"

defaultProtectionLevel="none/sign/EncryptAndSign"

issuedTokenType="string"

issuedKeyType="SymmetricKey/PublicKey"

&lt;/message&gt;

&lt;/security&gt;

&lt;/binding&gt;

&lt;/ws2007FederationBinding&gt;

From below screen shot, we can see client doing message security negotiation with the ADFS STS and not the actual Federated WCF application:

<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled3.png"><img width="723" height="393" class="alignleft size-full wp-image-945" alt="untitled" src="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled3.png" />
</a>

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

<span style="color: #000000;font-family: Calibri">But, also check that the Body contains the actual address of the Federated WCF application or in other words our relying party address.</span>

<span style="color: #000000;font-family: Calibri">Once negotiation completes client received the SAML Assertion token from the ADFS or our custom STS.</span>

<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Purush.png"><img width="723" height="397" class="alignleft size-full wp-image-955" alt="purush" src="https://msdnshared.blob.core.windows.net/media/2017/04/Purush.png" /></a>

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

<span style="color: #000000;font-family: Calibri">Once received, client can now present the Claims along with the SCT token negotiated with the ADFS STS to the federated WCF application.</span>

<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled5.png"><img width="666" height="449" class="alignleft size-full wp-image-965" alt="untitled5" src="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled5.png" /></a>

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;

Unfortunately, WCF traces truncates the Claims in WCF traces, so we cannot see it. However, we can clearly see the SAML Assertion ID.

Simple WCF-WIF Federation sample can be created by following the below blog: <a href="https://blogs.msdn.microsoft.com/napegadie_kones_msft_blog/2015/02/09/claims-aware-wcf-using-wif-in-net-4-5/">https://blogs.msdn.microsoft.com/napegadie_kones_msft_blog/2015/02/09/claims-aware-wcf-using-wif-in-net-4-5/</a>

&nbsp;

<strong>Client application configuration: Caller to Federated WCF service</strong>

&lt;system.serviceModel&gt;

&lt;diagnostics&gt;

&lt;messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true"

logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" /&gt;

&lt;/diagnostics&gt;

&lt;bindings&gt;

&lt;wsHttpBinding&gt;

&lt;binding name="https://adfs.contoso.com/adfs/services/trust/13/windowstransport"&gt;

&lt;security mode="Transport" /&gt;

&lt;/binding&gt;

&lt;/wsHttpBinding&gt;

&lt;ws2007FederationHttpBinding&gt;

&lt;binding name="WS2007FederationHttpBinding_IService1"&gt;

&lt;security mode="TransportWithMessageCredential"&gt;

&lt;message establishSecurityContext="false" negotiateServiceCredential="false"&gt;

&lt;issuer address="https://adfs.contoso.com/adfs/services/trust/13/windowstransport"

binding="wsHttpBinding" bindingConfiguration="https://adfs.contoso.com/adfs/services/trust/13/windowstransport"&gt;

&lt;identity&gt;

&lt;servicePrincipalName value="host/adfs.contoso.com" /&gt;

&lt;/identity&gt;

&lt;/issuer&gt;

&lt;issuerMetadata address="https://adfs.contoso.com/adfs/services/trust/mex" /&gt;

&lt;tokenRequestParameters&gt;

&lt;trust:SecondaryParameters xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;

&lt;trust:KeyType xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey&lt;/trust:KeyType&gt;

&lt;trust:KeySize xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;256&lt;/trust:KeySize&gt;

&lt;trust:KeyWrapAlgorithm xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p&lt;/trust:KeyWrapAlgorithm&gt;

&lt;trust:EncryptWith xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://www.w3.org/2001/04/xmlenc#aes256-cbc&lt;/trust:EncryptWith&gt;

&lt;trust:SignWith xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://www.w3.org/2000/09/xmldsig#hmac-sha1&lt;/trust:SignWith&gt;

&lt;trust:CanonicalizationAlgorithm xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://www.w3.org/2001/10/xml-exc-c14n#&lt;/trust:CanonicalizationAlgorithm&gt;

&lt;trust:EncryptionAlgorithm xmlns:trust="https://docs.oasis-open.org/ws-sx/ws-trust/200512"&gt;https://www.w3.org/2001/04/xmlenc#aes256-cbc&lt;/trust:EncryptionAlgorithm&gt;

&lt;/trust:SecondaryParameters&gt;

&lt;/tokenRequestParameters&gt;

&lt;/message&gt;

&lt;/security&gt;

&lt;/binding&gt;

&lt;/ws2007FederationHttpBinding&gt;

&lt;/bindings&gt;

&lt;client&gt;

&lt;endpoint address="https://aadconnect.contoso.com/WcfService1/Service1.svc"

binding="ws2007FederationHttpBinding" bindingConfiguration="WS2007FederationHttpBinding_IService1"

contract="ServiceReference1.IService1" name="WS2007FederationHttpBinding_IService1" /&gt;

&lt;/client&gt;

&lt;/system.serviceModel&gt;

&nbsp;

<strong>WCF Federated Service configuration:</strong>

&lt;system.identityModel&gt;

&lt;identityConfiguration&gt;

&lt;audienceUris&gt;

&lt;add value="https://aadconnect.contoso.com/WcfService1/Service1.svc" /&gt;

&lt;/audienceUris&gt;

&lt;issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry"&gt;

&lt;authority name="https://adfs.contoso.com/adfs/services/trust"&gt;

&lt;keys&gt;

&lt;add thumbprint="FBB1052A9E412FFBEB0032D190DECE12E32C4689" /&gt;

&lt;/keys&gt;

&lt;validIssuers&gt;

&lt;add name="https://adfs.contoso.com/adfs/services/trust" /&gt;

&lt;/validIssuers&gt;

&lt;/authority&gt;

&lt;/issuerNameRegistry&gt;

&lt;!--certificationValidationMode set to "None" by the the Identity and Access Tool for Visual Studio. For development purposes.--&gt;

&lt;certificateValidation certificateValidationMode="None" /&gt;

&lt;/identityConfiguration&gt;

&lt;/system.identityModel&gt;

&lt;configSections&gt;

&lt;section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /&gt;

&lt;/configSections&gt;

&lt;appSettings&gt;

&lt;add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /&gt;

&lt;add key="ida:FederationMetadataLocation" value="https://adfs.contoso.com/federationmetadata/2007-06/federationmetadata.xml" /&gt;

&lt;add key="ida:ProviderSelection" value="productionSTS" /&gt;

&lt;/appSettings&gt;

&lt;location path="FederationMetadata"&gt;

&lt;system.web&gt;

&lt;authorization&gt;

&lt;allow users="*" /&gt;

&lt;/authorization&gt;

&lt;/system.web&gt;

&lt;/location&gt;

&lt;system.serviceModel&gt;

&lt;behaviors&gt;

&lt;serviceBehaviors&gt;

&lt;behavior&gt;

&lt;serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /&gt;

&lt;serviceDebug includeExceptionDetailInFaults="false" /&gt;

&lt;serviceCredentials useIdentityConfiguration="true"&gt;

&lt;serviceCertificate findValue="CN=localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectDistinguishedName" /&gt;

&lt;/serviceCredentials&gt;

&lt;/behavior&gt;

&lt;/serviceBehaviors&gt;

&lt;/behaviors&gt;

&lt;protocolMapping&gt;

&lt;add scheme="https" binding="ws2007FederationHttpBinding" /&gt;

&lt;/protocolMapping&gt;

&lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /&gt;

&lt;bindings&gt;

&lt;ws2007FederationHttpBinding&gt;

&lt;binding name=""&gt;

&lt;security mode="TransportWithMessageCredential"&gt;

&lt;message establishSecurityContext="false" negotiateServiceCredential="false"&gt;

&lt;issuerMetadata address="https://adfs.contoso.com/adfs/services/trust/mex" /&gt;

&lt;/message&gt;

&lt;/security&gt;

&lt;/binding&gt;

&lt;/ws2007FederationHttpBinding&gt;

&lt;/bindings&gt;

&lt;/system.serviceModel&gt;

<strong> </strong>

<strong>Sample Application:</strong>

<a href="https://1drv.ms/f/s!ArgnWb8iHXB6gqYXvg53egkGHFxdvw">https://1drv.ms/f/s!ArgnWb8iHXB6gqYXvg53egkGHFxdvw</a>]]></content:encoded>
    </item>
    <item>
      <title>WCF: Message Security limitation with TLS 1.2 protocol</title>
      <link>https://docs.microsoft.com/archive/blogs/saurabs/wcf-message-security-limitation-with-tls-1-2-protocol</link>
      <pubDate>Thu, 13 Apr 2017 18:15:25 GMT</pubDate>
      <dc:creator><![CDATA[Saurabh Somani]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/saurabs/?p=895</guid>
      <description><![CDATA[Issue:
WCF Message Security breaks when using or forced to use TLS 1.1 or TLS 1.2...]]></description>
      <content:encoded><![CDATA[<pre><strong>Issue:</strong>
WCF Message Security breaks when using or forced to use TLS 1.1 or TLS 1.2 protocol.

<strong>Re-pro code:</strong>
https://1drv.ms/f/s!ArgnWb8iHXB6gqcg43hmT5jjbKJ-IA

We can disable SSL 3.0 and TLS 1.0 inside server key and we get below failure stack.

<strong>Failure Stack:
</strong>    29 clr!IL_Throw+0x184
    2a System_IdentityModel_ni!System.IdentityModel.SspiWrapper.AcquireCredentialsHandle(System.String, System.IdentityModel.CredentialUse, System.IdentityModel.SecureCredential)+0xd71ca
    2b System_ServiceModel_ni!System.ServiceModel.Security.TlsSspiNegotiation.AcquireDummyCredentials()+0x73
    2c System_ServiceModel_ni!System.ServiceModel.Security.TlsSspiNegotiation..ctor(System.String, Boolean, System.IdentityModel.SchProtocols, System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography.X509Certificates.X509Certificate2, Boolean)+0xfc
    2d System_ServiceModel_ni!System.ServiceModel.Security.TlsnegoTokenProvider.CreateTlsSspiState(System.IdentityModel.Tokens.X509SecurityToken)+0x75
    2e System_ServiceModel_ni!System.ServiceModel.Security.TlsnegoTokenProvider.CreateNegotiationState(System.ServiceModel.EndpointAddress, System.Uri, System.TimeSpan)+0x41
    2f System_ServiceModel_ni!System.ServiceModel.Security.IssuanceTokenProviderBase`1[[System.__Canon, mscorlib]].DoNegotiation(System.TimeSpan)+0xd6
    30 System_ServiceModel_ni!System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(System.TimeSpan)+0x68
    31 System_ServiceModel_ni!System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(System.TimeSpan)+0xcb</pre>

<strong>Reason:</strong>
<pre>WCF does have these hard coded values..
TlsSspiNegotiation tlsNegotiation = new TlsSspiNegotiation(String.Empty, SchProtocols.Ssl3Client | SchProtocols.TlsClient, clientCertificate);
     internal enum SchProtocols
    {
        Zero = 0,
        Ssl2Client = 0x00000008,
        Ssl2Server = 0x00000004,
        Ssl2 = (Ssl2Client | Ssl2Server),
        Ssl3Client = 0x00000020,
        Ssl3Server = 0x00000010,
        Ssl3 = (Ssl3Client | Ssl3Server),
        TlsClient = 0x00000080,
        TlsServer = 0x00000040,
        Tls = (TlsClient | TlsServer),
        Ssl3Tls = (Ssl3 | Tls),
    };

<strong>Problem documentation and plan for fix:</strong>
Problem will be addressed and fixed in new framework release 4.7
https://github.com/Microsoft/dotnet-apiport/pull/395
https://github.com/Microsoft/dotnet/blob/master/releases/net47/dotnet47-changes.md#wcf

<strong>Workaround for existing framework 4.6.2
</strong>1. Add the configuration file setting: 
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
 &lt;startup&gt;
 &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" /&gt;
 &lt;/startup&gt;
 &lt;runtime&gt;
<strong> &lt;AppContextSwitchOverrides value="Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols=false" /&gt;</strong>
 &lt;/runtime&gt;
&lt;/configuration&gt;

2. Get the private DLL from following location:
https://1drv.ms/f/s!ArgnWb8iHXB6gqRCG5I4nCw1vWbz8g 

3. Path to copy them:
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\
And
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\


<strong>More details:</strong>
Private build is added with support for TLS 1.1 and TLS 1.2 protocol.
<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled1.png"><img src="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled1.png" alt="untitled" width="219" height="488" class="alignleft size-full wp-image-905" /></a>
<strong></strong></pre>

<pre>I have tested the above private DLL for <strong>self host WCF service</strong>, but got new error when testing against <strong>IIS hosted WCF service</strong>.

<strong>Error for IIS hosted WCF Service:
<a href="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled4.png"><img src="https://msdnshared.blob.core.windows.net/media/2017/04/Untitled4.png" alt="untitled4" width="1508" height="289" class="alignleft size-full wp-image-915" /></a>
</pre>

<pre>Workaround:
</strong>We can try to set the "EstablishSecurityContext" and "NegotiateServiceCredentials" to false at Message Security level and it should help us use WCF message security over TLS 1.1 / 1.2 protocol.
<strong>&lt;message clientCredentialType="Certificate" establishSecurityContext="false"  negotiateServiceCredential="false" /&gt;

negotiateServiceCredential:
</strong>A Boolean value that specifies whether the service credential is provisioned at the client out of band, or is obtained from the service to the client through a process of negotiation. Such a negotiation is a precursor to the usual message exchange.
If the clientCredentialType attribute equals to None, Username, or Certificate, setting this attribute to false implies that the service certificate is available at the client out of band and that the client needs to specify the service certificate (using the &lt;serviceCertificate&gt;) in the &lt;serviceCredentials&gt; service behavior. 
This mode is interoperable with SOAP stacks which implement WS-Trust and WS-SecureConversation.

If the ClientCredentialType attribute is set to Windows, setting this attribute to false specifies Kerberos based authentication. 
This means that the client and service must be part of the same Kerberos domain. This mode is interoperable with SOAP stacks which implement the Kerberos token profile (as defined at OASIS WSS TC) as well as WS-Trust and WS-SecureConversation.

***When this attribute is true, it causes a .NET SOAP negotiation that tunnels SPNego exchange over SOAP messages. The default is true.


I hope this information helps to use WCF Message security correctly with TLS protocol.

Thanks
Saurabh Somani</pre>]]></content:encoded>
    </item>
  </channel>
</rss>