Pages

Thursday, June 14, 2012

WCF Security Best Practices

From OWASP(https://www.owasp.org/index.php/WCF_Security_Best_Practices)
From WCF 3.5 Security Guidelines
(@Codeplex by J.D. Meier , Jason Taylor , Prashant Bansode , Carlos Farre, Madhu Sundararajan, Steve Gregersen.)

Design Considerations
  • Design your service as a wrapper
  • If you are coming from ASMX then use basicHttpBinding to support your existing clients
  • If you are coming from DCOM then, use netTcpBinding
  • If your clients are deployed within intranet then choose transport security
  • If your clients are deployed over the internet then choose message security
  • Know your Authentication options
  • Know your binding options
  • If you need to Interop with non MS clients, use basicHttpBinding or wsHttpBinding
  • If your non-MS clients understand WS stack, use wsHttpBinding

Auditing and Logging
  • Use WCF auditing to audit your service
  • If non-repudiation is important, consider setting SuppressAuditFailure property to false
  • Use message logging to log operations on your service
  • Instrument for user management events
  • Instrument for significant business operations
  • Protect log files from unauthorized access
  • Do not log sensitive information

Authentication
  • Know your authentication options
  • Use Windows Authentication when you can
  • If you support non-WCF clients using windows authentication and message security, consider using the Kerberos direct option
  • If your users are in AD, but you can’t use windows authentication, consider using username authentication
  • If you are using username authentication, use Membership Provider instead of custom authentication
  • If your users are in a SQL membership store, use the SQL Membership Provider
  • If your users are in a custom store, consider using username authentication with a custom validator
  • If your clients have certificates, consider using client certificate authentication
  • If your partner applications need to be authenticated when calling WCF services, use client certificate authentication.
  • If you are using username authentication, validate user login information
  • Do not store passwords directly in the user store
  • Enforce strong passwords
  • Protect access to your credential store
  • If you are using Windows Forms to connect to WCF, do not cache credentials

Authorization
  • If you store role information in Windows Groups, consider using the WCF PrincipalPermissionAttribute class for roles authorization
  • If you use ASP.NET roles, use the ASP.NET Role Provider
  • If you use windows groups for authorization, use ASP.NET Role Provider with AspNetWindowsTokenRoleProvider
  • If you store role information in SQL, consider using the SQL Server Role Provider for roles authorization
  • If you store role information in ADAM, use the Authorization Store Role Provider for roles authorization
  • If you need to authorize access to WCF operations, use declarative authorization
  • If you need to perform fine-grained authorization based on business logic, use imperative authorization

Binding
  • If you need to support clients over the internet, consider using wsHttpBinding.
  • If you need to expose your WCF service to legacy clients as an ASMX web service, use basicHttpBinding
  • If you need to support remote WCF clients within an intranet, consider using netTcpBinding.
  • If you need to support local WCF clients, consider using netNamedPipeBinding.
  • If you need to support disconnected queued calls, use netMsmqBinding.
  • If you need to support bidirectional communication between WCF Client and WCF service, use wsDualHttpBinding.

Configuration Management
  • Use Replay detection to protect against message replay attacks
  • If you host your service in a Windows service, expose a metadata exchange (mex) binding
  • If you don’t want to expose your WSDL, turn off HttpGetEnabled and metadata exchange (mex)
  • Manage bindings and endpoints in config not code
  • Associate names with the service configuration when you create service behavior, endpoint behavior, and binding configuration
  • Encrypt configuration sections that contain sensitive data

Exception Management
  • Use structured exception handling
  • Do not divulge exception details to clients in production
  • Use a fault contract to return error information to clients
  • Use a global exception handler to catch unhandled exceptions

Hosting
  • If you are hosting your service in a Windows Service, use a least privileged custom domain account
  • If you are hosting your service in IIS, use a least privileged service account
  • Use IIS to host your service unless you need to use a transport that IIS does not support

Impersonation and Delegation
  • Know the impersonation options
  • If you have to flow the original caller, use constrained delegation
  • Consider LogonUser when you need to impersonate but you don’t have trusted delegation
  • Consider S4U when you need a Windows token and you don’t have the original caller’s credentials
  • Use programmatic impersonation to impersonate based on business logic
  • When impersonating programmatically be sure to revert to original context
  • Only impersonate on operations that require it
  • Use OperationBehavior to impersonate declaratively

Input/Data Validation
  • If you need to validate parameters, use parameter inspectors
  • If your service has operations that accept message or data contracts, use schemas to validate your messages
  • If you need to do schema validation, use message inspectors
  • Validate operation parameters for length, range, format and type
  • Validate parameter input on the server
  • Validate service responses on the client
  • Do not rely on client-side validation
  • Avoid user-supplied file name and path input
  • Do not echo untrusted input

Proxy Considerations
  • Publish your metadata over HTTPS to protect your clients from proxy spoofing
  • If you turn off mutual authentication, be aware of service spoofing

Deployment considerations
  • Do not use temporary certificates in production
  • If you are using a custom domain account in the identity pool for your WCF application, create an SPN for Kerberos to authenticate the client.
  • If you are using a custom service account and need to use trusted for delegation, create an SPN
  • If you are hosting your service in a Windows Service, using a custom domain identity, and ASP.NET needs to use constrained trusted for delegation when calling the service, create an SPN
  • Use IIS to host your service unless you need to use a transport that IIS does not support
  • Use a least privileged account to run your WCF service
  • Protect sensitive data in your configuration files 

Tuesday, June 5, 2012

Properties and Indexers in C#

Abstract
Properties are known as smart fields and enable access to the fields of a class. Indexers are also called smart arrays in C# and can be used to use an object as an array. This article discusses both of these concepts with simple code examples.


Property
A property is like a "virtual field" that contains get and set accessors and provides an interface to the members of a class. They can be used to get and set values to and from the class members. Properties can be static or instance members of a class. The get accessor does not accept any parameter; rather it returns the value of the member that it is associated with. The set accessor contains an implicit parameter called 'value'. The following code example illustrates a simple property.

Listing 1 - Implementing properties

using System;
namespace ConsoleApplication
{
  class Test
  {
    private int number;
    public int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test test = new Test();
      test.MyProperty = 100;
      Console.WriteLine(test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows a static property. The static property MyProperty can be accessed without instantiating the class. A static property can access static members of a class only.

Listing 2 - Implementing a static property
using System;
namespace ConsoleApplication
{
  class Test
  {
    private static int number;
    public static int MyProperty
    {
      get { return number; }
      set { number = value; }
    }
    [STAThread]static void Main(string[]args)
    {
      Test.MyProperty = 100;
      Console.WriteLine(Test.MyProperty);
      Console.ReadLine();
    }
  }
}
The following code shows how the visibility of the get and the set accessors has been restricted to the current assembly only by using the keyword "internal".

Listing 3 - Restricting the visibility
public class Employee
{
  private int empID;
  private string empName;
 
  internal int ID
  {
    get { return empID; }
    set { empID = value; }
  }
  internal string Name
  {
    get { return empName; }
    set { empName = value; }
  }
}
 
public class Test
{
  public static void Main(string[]args)
  {
    Employee emp = new Employee();
    emp.Name = "Joydip";
    emp.ID = 259;
    System.Console.WriteLine("The id is:" + emp.ID);
    System.Console.WriteLine("The name is:" + emp.Name);
  }
}
The keyword “internal” implies that the property's ID and Name can be accessed from the current assembly only as they are “internal” to the assembly in which they have been declared.
----------------------------------------------------------------------------------------------------
Indexer
Indexers are also called smart arrays in C# and can be used to treat an object as an array. An indexer allows an instance of a class or a struct to be indexed as an array, which is useful for looping or iterating or data binding operations.
The following is the syntax of an indexer declaration.
<Modifier> <Return type> this[arguments]
{
  get { }
  Set { }
}
The modifier can be one of the following
·         private
·         public
·         protected
·         internal
All indexers should accept at least one parameter. Indexers cannot be static. This is because static methods do not have access to ‘this’. The ‘this’ keyword indicates an instance of the current class. Look at the code given below.

Listing 4 - A simple indexer
namespace ConsoleApplication
{
  using System;
  class Employee
  {
    private string[]name = new string[10];
    public string this[int index]
    {
      get { return name[index]; }
      set { name[index] = value; }
    }
  }
 
  class Test
  {
    public static void Main()
    {
      Employee emp = new Employee();
      emp[0] = "Joydip";
      emp[1] = "Manashi";
      emp[2] = "Jini";
      Console.WriteLine("The namesare:--");
      for (int i = 0; i < 3;Console.WriteLine(emp[i++]))
        ;
      Console.ReadLine();
    }
  }
}
The output of the program is
The names are:--
Joydip
Manashi
Jini

Indexers in inheritance
The indexers of the base class are inherited to its derived classes. This is illustrated in the code shown below.

Listing 5 - Indexers in inheritance
using System;
class Base
{
  public int number;
  public int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base{}
class Test
{
  public static void Main()
  {
    Derived d = new Derived();
    d[0] = 500;
    Console.WriteLine("The value is: "+ d[0]);
  }
}
The program displays the string “Set of the base class. Get of the base class. The value is: 500”.
Indexers can be polymorphic. We can have the same indexer in the base and the derived classes. Such indexers are ‘overridden indexers’ and require the keyword virtual to be stated in their declaration in the base class. The following program illustrates this.

Listing 6 - Indexers can be polymorphic
using System;
class Base
{
  protected int number;
 
  public virtual int this[int index]
  {
    get
    {
      Console.Write("Get of the baseclass.");
      return number;
    }
    set
    {
      Console.Write("Set of the baseclass.");
      number = value;
    }
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get
    {
      Console.Write("Get of the derivedclass.");
      return base.number;
    }
    set
    {
      Console.Write("Set of the derivedclass.");
      base.number = value;
    }
  }
}
 
class Test
{
  public static void Main()
  {
    Base obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is “Set of the derived class. Get of the derived class. The value is: 500”.

Abstract indexers
Indexers can be abstract. We can have abstract indexers in a base class that need to be implemented by the class subclassing (inheriting from) it. The abstract indexer like an abstract method does not contain any code in its get or set. This is shown in the example below.

Listing 7 - Indexers can be abstract
using System;
abstract class Base
{
  protected int number;
 
  public abstract int this[int index]
  {
    get;
    set;
  }
}
 
class Derived: Base
{
  public override int this[int index]
  {
    get { return number; }
    set { number = value; }
  }
}
 
class Test
{
  public static void Main()
  {
    Derived obj = new Derived();
    obj[0] = 500;
    Console.WriteLine("The value is: "+ obj[0]);
  }
}
The output of the program is "The value is: 500".

Comparison between properties and indexers
Properties are accessed by names but indexers are accessed using indexes. Properties can be static but we cannot have static indexers. Indexers should always be instance members of the class. The get accessor of a property does not accept any parameter but the same of the indexer accepts the same formal parameters as the indexer. The set accessor of a property contains an implicit parameter called "value". The set accessor of an indexer contains the same formal parameters as that of the indexer and also the "value" as an implicit parameter.

Conclusion
Properties and indexers are two of the most important concepts in C#. This article has discussed both these concepts with code examples. I would highly appreciate any comments and or suggestions from the readers related to this article. Please post your comments and or suggestions if you have any. Happy reading!