none
Error during connection to wcf service by ssl RRS feed

  • Question

  • Hello to everybody,

        I've done a wcf service, that is published (I can connect to it by browser and I can see the wsdl) but when I try to consume it by a client program that I've written, I obtain an "An error occurred when verifying security for the message" message. 

    Some detail: consumer and server are on the same machine (so this isn't the case of out-of-sync time between consumer and server), I use a self signed certificate, the service is put in a subsection of a greater solution, and it has a dedicated web.config that overrides the solution one.

    Web.config files are the same both on the service side than on consumer side (I've simply done a copy and paste from service to consumer file). Consumer uses basicHttpBinding and TransportWithMessageCredential connection and, after several attempts, even if I've created a service reference to the service by Visual Studio tool, in the consumer code I specify again both the binding type than the endpoint address.

    As I've already said, the service uses a self signed certificate, and I've implemented a validation class to validate a non trusted certificate.

    When I create the proxy object in my consumer class I don't get any error, I receive it only when I try to consume any method on my service. I've set up the tracelog, but it doesn't seem to show any error, for what I can understand:

    <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
    	<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
    		<EventID>262165</EventID>
    		<Type>3</Type>
    		<SubType Name="Information">0</SubType>
    		<Level>8</Level>
    		<TimeCreated SystemTime="2014-10-30T10:41:32.4017455Z" />
    		<Source Name="System.ServiceModel" />
    		<Correlation ActivityID="{43c6480e-e3fe-4916-b3a3-efaa10881db5}" />
    		<Execution ProcessName="w3wp" ProcessID="7004" ThreadID="6" />
    		<Channel />
    		<Computer>WKR1007R</Computer>
    	</System>
    	<ApplicationData>
    		<TraceData>
    			<DataItem>
    				<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Information">
    				<TraceIdentifier>http://msdn.microsoft.com/it-IT/library/System.ServiceModel.Channels.RequestChannelReplyReceived.aspx</TraceIdentifier>
    				<Description>Ricevuta risposta tramite il canale di richiesta</Description>
    				<AppDomain>/LM/W3SVC/1/ROOT/PBEWS_Client_Test-1-130591392918713557</AppDomain>
    				<Source>System.ServiceModel.Channels.BufferedMessage/2733477</Source>
    				<ExtendedData xmlns="http://schemas.microsoft.com/2006/08/ServiceModel/MessageTraceRecord">
    					<MessageProperties>
    						<Encoder>text/xml; charset=utf-8</Encoder>
    						<AllowOutputBatching>False</AllowOutputBatching>
    						<Security>
    							<IsAnonymous>False</IsAnonymous>
    							<WindowsIdentityUsed>False</WindowsIdentityUsed>
    						</Security>
    					</MessageProperties>
    					<MessageHeaders></MessageHeaders>
    				</ExtendedData>
    			</TraceRecord>
    		</DataItem>
    	</TraceData>
    </ApplicationData>
    </E2ETraceEvent>

    Only using Fiddler I can find an error:

    <span><H1>Errore server nell'applicazione '/PBEWS_Client_Test'.<hr width=100% size=1 color=silver></H1>
                <h2> <i>Errore durante la verifica della sicurezza del messaggio.</i> </h2></span>
                <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
                <b> Descrizione: </b>Eccezione non gestita durante l'esecuzione della richiesta Web corrente. Per ulteriori informazioni sull'errore e sul suo punto di origine nel codice, vedere la traccia dello stack.
                <br><br>
    
                <b> Dettagli eccezione: </b>System.ServiceModel.FaultException: Errore durante la verifica della sicurezza del messaggio.<br><br>
    
                <b>Errore nel codice sorgente:</b> <br><br>
    
                <table width=100% bgcolor="#ffffcc">
                   <tr>
                      <td>
                          <code><pre>
    
    Riga 584:        
    Riga 585:        public R...Contracts.PolPolizza RecuperaPolizza(int idPolizza, bool modalita) {
    <font color=red>Riga 586:            return base.Channel.RecuperaPolizza(idPolizza, modalita);
    </font>Riga 587:        }
    Riga 588:        </pre></code>
    
                      </td>
                   </tr>
                </table>
    
                <br>
    
                <b> File di origine: </b> c:\..\PBEWS_Client_Test\Service References\ServiceReference1\Reference.cs<b> &nbsp;&nbsp; Riga: </b> 586
                <br><br>
    
                <b>Traccia dello stack:</b> <br><br>
    
                <table width=100% bgcolor="#ffffcc">
                   <tr>
                      <td>
                          <code><pre>
    
    [FaultException: Errore durante la verifica della sicurezza del messaggio.]
       System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14799942
       System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) +622
       PBEWS_Client_Test.ServiceReference1.PBEWS.RecuperaPolizza(Int32 idPolizza, Boolean modalita) +0
       PBEWS_Client_Test.ServiceReference1.PBEWSClient.RecuperaPolizza(Int32 idPolizza, Boolean modalita) in c:\Progetti RGI\Rgi.PassBroker\PBEWS_Client_Test\Service References\ServiceReference1\Reference.cs:586
       PBEWS_Client_Test.PBEWS_TestForm.Button1_Click(Object sender, EventArgs e) in c:\Progetti RGI\Rgi.PassBroker\PBEWS_Client_Test\PBEWS_TestForm.aspx.cs:103
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
    </pre></code>
    
                      </td>
                   </tr>
                </table>

    It says "An error occurred when verifying security for the message" and refers to Reference.cs, that is the file that has been created by Visual Studio tool when setting up the service reference. Lines from 577 to 590 contains the following code:

    public PBEWS_Client_Test.ServiceReference1.MRAnaAnagraficaBaseList RicercaAnagrafiche(System.Collections.Generic.List<Rgi.PassBroker.WCF.Contracts.CriterioRicercaWS> criteri) {
                return base.Channel.RicercaAnagrafiche(criteri);
            }
            
            public System.Threading.Tasks.Task<PBEWS_Client_Test.ServiceReference1.MRAnaAnagraficaBaseList> RicercaAnagraficheAsync(System.Collections.Generic.List<Rgi.PassBroker.WCF.Contracts.CriterioRicercaWS> criteri) {
                return base.Channel.RicercaAnagraficheAsync(criteri);
            }
            
            public Rgi.PassBroker.WCF.Contracts.PolPolizza RecuperaPolizza(int idPolizza, bool modalita) {
                return base.Channel.RecuperaPolizza(idPolizza, modalita);
            }
            
            public System.Threading.Tasks.Task<Rgi.PassBroker.WCF.Contracts.PolPolizza> RecuperaPolizzaAsync(int idPolizza, bool modalita) {
                return base.Channel.RecuperaPolizzaAsync(idPolizza, modalita);
            }

    Does anyone have a suggestion that can help me to solve this error?

    Thanx in andvance.

    Tuesday, November 4, 2014 8:17 AM

All replies

  • Hello bancho74,

    Apologies if I misunderstood your question, but I believe you need to override the validation of the self-signed certificate.  You do not need to do this if it is signed by a known authority.

    ServicePointManager.ServerCertificateValidationCallback +=
                new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);
    bool CertCheck(object sender, X509Certificate cert,
            X509Chain chain, System.Net.Security.SslPolicyErrors error)
    {
        return true;
    }

    This post should point you in the right direction: http://stackoverflow.com/questions/2792539/is-it-possible-to-force-the-wcf-test-client-to-accept-a-self-signed-certificate


    Jeff

    Wednesday, November 5, 2014 3:15 AM
  • Hello Jeff,

       Thank you for your answer, but I'm afraid it isn't what I'm looking for: as said in my post I've implemented a validation class, following the guidelines that I've found for this kind of scenario:

    public class PermissiveCertificatePolicy
        {
            string subjectName;
            static PermissiveCertificatePolicy currentPolicy;
            PermissiveCertificatePolicy(string subjectName)
            {
                this.subjectName = subjectName;
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidate);
            }
    
            public static void Enact(string subjectName)
            {
                currentPolicy = new PermissiveCertificatePolicy(subjectName);
            }
    
            bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
            {
                if (cert.Subject == subjectName)
                {
                    return true;
                }
    
                return false;
            }
        }

    As you can see, it's the same way you're showing to me.

    Thanks again,

    bancho74

     

    Wednesday, November 5, 2014 8:21 AM
  • Understand now.  You said you have the save config for both the service and client.  Can you post those as there might be a subtle spelling mistake or something?  I assume that a breakpoint on the server never gets called.

    Also does the RemoteCertValidate ever get called?


    Jeff

    Wednesday, November 5, 2014 6:38 PM
  • Hi Jeff,

         this is the service web.config:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
    
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
      </system.web>
    
      <location path="BasicClassicLongTimeout2">
        <system.web>
          <authorization>
            <allow users="?"/>
          </authorization>
        </system.web>
      </location>
      
      <connectionStrings>
        ...
      </connectionStrings>
    
      <appSettings>
        <add key="UrlRgiPasswordUsers" value="https://localhost/.../Password/Services/UserService.svc" />
      </appSettings>
    
      <system.net>
        <settings>
          <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
        </settings>
      </system.net>
    
      <system.diagnostics>
      <sources>
          <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
            <listeners>
                     <add name="messages" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\Logs\messages.svclog" />
              </listeners>
          </source>
        </sources>
    </system.diagnostics>
        
      <system.serviceModel>
        <diagnostics>
        <messageLogging logEntireMessage="true" logMalformedMessages="false" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" maxMessagesToLog="3000" maxSizeOfMessageToLog="2000" />
      </diagnostics>
      
        <bindings>
          <basicHttpBinding>
            <binding name="BasicClassicLongTimeout2" sendTimeout="00:20:00" openTimeout="00:10:00">
              <security mode="TransportWithMessageCredential">
                <message clientCredentialType="UserName" />
                <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
              </security>
            </binding>
          </basicHttpBinding>
        </bindings>
    
        <services configSource="PBEWS.config" />
        
        <extensions>
          <behaviorExtensions>
            <add type="....WCF.Extensions.SilverlightFaultBehavior,....WCF.Extensions" name="SilverlightFaultBehavior" />
            <add type="....Extensions.SessionBehaviorExtensionElement,....WCF.Extensions" name="sessionBehaviorExtensionElement" />
          </behaviorExtensions>
        </extensions>
    
        <behaviors>
          <serviceBehaviors>
            <behavior name="PBEWSBehavior">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true" />
              <serviceAuthorization principalPermissionMode="Custom">
                <authorizationPolicies>
                  <add policyType="....Extensions.RgiExternalAuthorizationPolicy2,Rgi.PassBroker.WCF.Extensions" />
                </authorizationPolicies>
              </serviceAuthorization>
    
              <serviceCredentials>
                <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="....WCF.ServiceHost.Aspnet.CustomValidationService, Rgi.PassBroker.WCF.ServiceHost.Aspnet" />
                <!--<serviceCertificate findValue="CertificatoPerSviluppo" storeLocation = "LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>-->
              </serviceCredentials>
            </behavior>
          </serviceBehaviors>
    
    
          <endpointBehaviors>
            <behavior name="PBEWSBehavior">
              <clientCredentials>
                <serviceCertificate>
                  <!--In questo modo dico a WCF di fidarsi di questo certificato farlocco-->
                  <authentication certificateValidationMode="None" revocationMode="NoCheck" />
                </serviceCertificate>
              </clientCredentials>
            </behavior>
          </endpointBehaviors>
          
        </behaviors>
      </system.serviceModel>
    
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
        <system.webServer>
            <directoryBrowse enabled="true" />
        </system.webServer>
    </configuration>

    (I've masked the initial part of some istructions: they contain internal path and are not useful for problem comprehension).

    PBEWS.Config contains the endpoint definition:

    <?xml version="1.0" encoding="utf-8" ?>
    
    <services>
      <service name="....WCF.Services.PBEWS" behaviorConfiguration="PBEWSBehavior" >
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingNamespace="https://wkr1007r.ad.com:999/.../ExternalFederation/PBEWS.svc"
                  bindingConfiguration="BasicClassicLongTimeout2"
                  contract="....WCF.ServiceContracts.IPBEWS"/>
      </service>
    </services>


    Client web.config instead contains:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    
        <system.web>
          <compilation debug="true" targetFramework="4.5" />
          <httpRuntime targetFramework="4.5" />
        </system.web>
    
        <system.diagnostics>
          <sources>
            <source name="System.ServiceModel"
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
              <listeners>
                <add name="traceListener"
                    type="System.Diagnostics.XmlWriterTraceListener"
                    initializeData="c:\Logs\Traces.svclog"  />
              </listeners>
            </source>
          </sources>
        </system.diagnostics>
      
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_PBEWS">
                      <security mode="TransportWithMessageCredential" />
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="https://wkr1007r.ad.com:999/.../ExternalFederation/PBEWS.svc"
                    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_PBEWS"
                    contract="ServiceReference1.PBEWS" name="BasicHttpBinding_PBEWS" />
            </client>
        </system.serviceModel>
    </configuration>
    

    The Remote certificate is called, and returns true, so I think the problem is somewhere in credential validation (if I set Transport instead of TransportWithMessageCredential everything works fine)

    Thank you for your aid.

    Best regards,

    bancho

    Thursday, November 6, 2014 9:40 AM
  • Hello bancho,

    This is pretty hard to identify just by reading the config but here are a couple things I would try changing from basichttpbinding to wshttpbinding.  I believe basicHttpBinding will only work with transport level security.

    If that does not help then I am at a loss.  I would start with a basic sample project and then start to add your project to it until it breaks.  Painful...

    Here are some references:

    http://msdn.microsoft.com/en-us/library/ff648840.aspx

    http://msdn.microsoft.com/en-us/library/ff650785.aspx#_Step_4:_Configur


    Jeff

    Thursday, November 6, 2014 7:32 PM
  • Hi Jeff,

         Unluckily, I've to merge my service in the active project, so develop as a standalone service is useless for me. I've tested my service with Transport security, and I know that it works, and I've read enough documentation to know that, even if it's better to use wsHttpBinding with TransportWitheMessageCredential, it may be used with basicHttpBinding, too (and for me it's mandatory to use it).

    Thank you for your aid.

    Have a nice week end,

    bancho

    • Proposed as answer by Mankdng Nef Monday, November 17, 2014 9:40 AM
    Friday, November 7, 2014 3:35 PM
  • Mark it if you solve it.
    Monday, November 17, 2014 9:40 AM