Auditing and Logging

patterns & practices Developer Center

  • How to: Audit Security Events
  • How to: Enable WCF Message Logging
  • How to: Enable WCF Tracing
  • How to: Use Health Monitoring in WCF
  • How to: Filter Sensitive Data from Your Logs
  • How to: View Log Information
  • How to: View Trace Information
  • How to: Log Traces to a WMI Provider
  • How to: Turn Off Audit Failure Suppression

How to: Audit Security Events

You can use the auditing feature in WCF to audit security events such as authentication and authorization failures. WCF service auditing can allow you to detect an attack that has occurred or is in progress. In addition, auditing can help you debug security-related problems. For example, if an error in the configuration of the authorization or checking policy accidentally denies access to an authorized user, you can discover and isolate the cause of this error by examining the auditing events in the event log.

Perform the following steps to enable auditing of authentication and authorization for your WCF service:

  1. Open the web.config file of the WCF service by using the Configuration Editor tool (SvcConfigEditor.exe).

  2. In the Configuration Editor, navigate to the Advanced node.

  3. Select the Behavior: ServiceBehavior section and add a new service behavior extension element.

  4. In the Adding Behavior Element Extension Sections dialog box, select serviceSecurityAudit and then click Add.

  5. In the Configuration section, under Service Behaviors, select the serviceSecurityAudit option.

  6. Set the MessageAuthenticationAuditLevel attribute to SuccessOrFailure by choosing this option from the drop-down list.

  7. Set the ServiceAuthorizationAuditLevel attribute to SuccessOrFailure by choosing this option from the drop-down list.

  8. In the Configuration Editor, on the File menu, click Save.

  9. In Microsoft Visual Studio, verify your configuration. The configuration should look as follows.

    …
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
            <serviceSecurityAudit messageAuthenticationAuditLevel="SuccessOrFailure" />
            <serviceSecurityAudit serviceAuthorizationAuditLevel="SuccessOrFailure" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    …
    

Additional Resources

You can enable message logging to log the messages processed by your service. Message logging can be used to diagnose your applications and analyze the root cause of problems. Message logging is not turned on by default; turn on message logging by setting attributes on the <messagelogging> element in your configuration file and then add a trace listener to log the events to a file.

How to: Enable WCF Message Logging

Perform the following steps to enable WCF message logging:

  1. Open the web.config file of the WCF service by using the Configuration Editor tool (SvcConfigEditor.exe).

  2. In the Configuration Editor, navigate to the Diagnostics node and then click the Enable Message Logging link.

    This enables message logging for your service and also creates a listener (ServiceModelMessageLoggingListener) and a source (System.ServiceModel.MessageLogging) under the Listeners and Sources folders, respectively.

Configuring Message Logging Levels

You can configure message logging levels at both the service and transport levels. Perform the following steps to configure the message logging levels:

  1. In the left pane of the Configuration editor, select MessageLogging under the Diagnostics node.

  2. Set the LogMessagesAtServiceLevel attribute to True by choosing this option from the drop-down list.

    The LogMessagesAtTransportLevel attribute is True by default.

Determining Where Messages Will Be Logged

Perform the following step to determine where the messages will be logged:

  • Select ServiceModelMessageLoggingListener under the Listeners node and note the value of the InitData attribute. The default location where messages are logged is c:\inetpub\wwwroot\WCFService\web_messages.svclog.

    The configuration file should look as follows:

        <system.diagnostics>
            <sources>
                <source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
                    <listeners>
                        <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                            <filter type="" />
                        </add>
                        <add name="ServiceModelMessageLoggingListener">
                            <filter type="" />
                        </add>
                    </listeners>
                </source>
            </sources>
            <sharedListeners>
                <add initializeData="c:\inetpub\wwwroot\auditingwcf\web_messages.svclog"
                    type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                    name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
                    <filter type="" />
                </add>
            </sharedListeners>
        </system.diagnostics>
    
    
     <system.serviceModel>
        <diagnostics>
          <messageLogging logMalformedMessages="true" logMessagesAtServiceLevel="true"
            logMessagesAtTransportLevel="true" />
        </diagnostics>
    

Additional Resources

How to: Enable WCF Tracing

Use WCF tracing to help debug your WCF service by logging all operations on your service.

Enabling Tracing

Perform the following steps to enable tracing:

  1. Open the web.config file of the WCF service by using the Configuration Editor tool (SvcConfigEditor.exe).

  2. In the Configuration Editor, navigate to the Diagnostics node and then click the Enable Tracing link.

    This enables tracing of your WCF service and also creates a listener (ServiceModelTraceListener) and a source (SystemServiceModel) under the Listeners and Sources folders, respectively.

Determining Where Traces Will Be Written

Perform the following step to determine where the traces will be written:

  • Select ServiceModelTraceListener under the Listeners node and note the value of the InitData attribute. The default location where trace messages are written is c:\inetpub\wwwroot\auditingwcf\web_tracelog.svclog.

    The configuration file should look as follows:

        <system.diagnostics>
            <sources>
                <source name="System.ServiceModel" 
                        switchValue="Warning, ActivityTracing"
                        propagateActivity="true">
                    <listeners>
                        <add type="System.Diagnostics.DefaultTraceListener" 
                             name="Default">
                            <filter type="" />
                        </add>
                        <add name="ServiceModelTraceListener">
                            <filter type="" />
                        </add>
                    </listeners>
                </source>
            </sources>
    
    
            <sharedListeners>
                <add 
              initializeData="c:\inetpub\wwwroot\auditingwcf\web_tracelog.svclog"
                    type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                    name="ServiceModelTraceListener"       
                    traceOutputOptions="Timestamp">
                    <filter type="" />
                </add>
            </sharedListeners>
        </system.diagnostics>
    

Additional Resources

How to: Use Health Monitoring in WCF

You can use the health monitoring feature in WCF to log custom events in your service based on business logic. You can use health monitoring to instrument your application and monitor user-management events around authentication and authorization. This instrumentation can help you to detect and react to potentially suspicious behavior. It also enables you to gather data on operations; for example, to track who is accessing your application and when user account passwords need to be reset.

Perform the following high-level steps to configure your WCF service to use health monitoring:

  1. Create a custom health monitoring event.
  2. Configure your WCF service for health monitoring.
  3. Instrument your application to raise a custom event.

Each of these steps is detailed below.

  1. Create a custom health monitoring event.

    Create a custom user management Web event by first creating a class library and then creating a class that inherits from WebAuditEvent, as follows:

    using System.Web.Management;
    
     public class MyEvent : WebAuditEvent
        {
    
            public MyEvent(string msg, object eventSource, int eventCode)
                : base(msg, eventSource, eventCode)
            {
            }
    
            public MyEvent(string msg, object eventSource, int eventCode, 
                           int eventDetailCode)
                : base(msg, eventSource, eventCode, eventDetailCode)
            {
            }
           public override void FormatCustomEventDetails(WebEventFormatter    
                formatter)
            {
                base.FormatCustomEventDetails(formatter);
    
                // Display some custom event message
                formatter.AppendLine("Some Critical Event Fired");
            } 
    }
    
  2. Configure your WCF Service for health monitoring.

    Add a health monitoring element to your configuration file as follows:

    …
    <system.web>
    <healthMonitoring>
    <eventMappings>
    <add name="Some Custom Event" 
                        type="MyEventLibrary.MyEvent, MyEventLibrary"/>
    </eventMappings>
    <rules>
    <add name="Custom event" 
                        eventName="Some Custom Event" 
                        provider="EventLogProvider" 
                        minInterval="00:00:01"/>
    </rules>
    </healthMonitoring>
    </system.web>
    …
    
  3. Instrument your application to raise a custom event.

    Instrument the WCF service by raising the custom event in a service contract as follows.

    [OperationContract]
    string InvokeCriticalEvent();
    
    public string InvokeCriticalEvent()
        {
            MyEvent obj = new MyEvent("Invoking Some Custom Event", 
                                this, WebEventCodes.WebExtendedBase + 1);
            obj.Raise();
            return "Critical event invoked";
        }
    

After completing these steps, you can verify that the custom events are in the system event log after calling the service method from a test client.

Additional Resources

How to: Filter Sensitive Data from Your Logs

You can use message filters to log messages that match the filter criteria. For example, you could use a message filter to remove personally identifiable information (PII) before it can get into log files.

Filters support the full XPath syntax. The following code shows how to configure a filter that records only messages that have a Simple Object Access Protocol (SOAP) header section:

<messageLogging logEntireMessage="true"
    logMalformedMessages="true" 
    logMessagesAtServiceLevel="true"
    logMessagesAtTransportLevel="true"
    maxMessagesToLog="420">
    <filters>
        <add nodeQuota="10" 
             xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
                 /soap:Envelope/soap:Header
        </add>
     </filters>
</messageLogging>

Filters provide a safety feature using the nodeQuota attribute, which limits the maximum number of nodes in the XPath Document Object Model (DOM) that can be examined to match the filter.

Additional Resources

How to: View Log Information

You can use the SvcTraceViewer.exe utility to view both message log files and trace files. You can find this tool at <Drive Name>:\Program Files\Microsoft SDKs\Windows\v6.0\Bin.

This tool gives you a comprehensive analysis of the step-by-step process of the WCF service, showing each interaction with the WCF run time and the clients. It shows the object activities, messages, and all errors that occurred in the host's life. It also provides you a graphical view of the log or trace data.

Additional Resources

How to: View Trace Information

Perform the following steps to view trace information:

  1. Enable tracing by adding configuration information to the application web.config or app.config file; for example:

    <system.diagnostics>
        <trace autoflush="true" />
        <sources>
                <source name="System.ServiceModel" 
                        switchValue="Information, ActivityTracing"
                        propagateActivity="true">
                <listeners>
                   <add name="sdt" 
                       type="System.Diagnostics.XmlWriterTraceListener" 
                       initializeData= "WCFTraceLog.svclog" />
                </listeners>
             </source>
        </sources>
    </system.diagnostics>
    
  2. Navigate to the SvcTraceViewer.exe installation location (C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin) and run SvcTraceViewer.exe.

  3. On the File menu, click Open and then navigate to the location where your trace files are stored.

  4. Double-click the trace log file to open it.

Additional Resources

How to: Log Traces to a WMI Provider

Perform the following steps to enable a Windows Management Instrumentation (WMI) provider for your service:

  1. Open the web.config file of the WCF service by using the Configuration Editor tool (SvcConfigEditor.exe).

  2. In the Configuration Editor, navigate to the Diagnostics node and then click the Enable WMI Provider link. The configuration file should look as follows.

      <system.serviceModel>
        <diagnostics wmiProviderEnabled="true">
        ...
        </diagnostics>
        ...
      </system.serviceModel>
    
  3. To view the WMI trace information, you need to install WMI CIM Studio so that you can view the WMI interactions. WMI CIM Studio is a Microsoft ActiveX component that plugs into Microsoft Internet Explorer. You can get this as a free download available from Microsoft.

Additional Resources

How to: Turn Off Audit Failure Suppression

By default, WCF will ignore audit failures and allow the service to continue running by setting the SuppressAuditFailure property to true. You can set this property to false, which will turn off audit failure suppression, thereby throwing an exception when there has been an auditing failure.

Perform the following step to turn off audit failure suppression:

  • Set the suppressAuditFailure property to false as follows:

    <configuration>
      <system.serviceModel>
        <behaviors>
          <behavior>
            <serviceSecurityAudit
                      auditLogLocation="Application"
                      suppressAuditFailure="false"
                      serviceAuthorizationAuditLevel="Failure"
                      messageAuthenticationAuditLevel="SuccessOrFailure" /> 
          </behavior>
        </behaviors>
      </system.serviceModel>
    </configuration>
    

Additional Resources