Learning WCF - Security Note

Fundamental security concepts

Authentication

                -We typically think aboutauthentication as identifying the message sender. Mutual authentication involves authenticating both the sender and themessage receiver toprevent possible man-in-the-middle attacks. 
Authorization 
                -Afterauthenticating the message sender, authorization determines the system features and functionalitythey are entitled to execute
Integrity
                -Messages should be digitally signed to ensurethey have not been altered between sender and receiver.
Confidentiality
                -Sensitive messagesor specific message parts should be encrypted to ensure they cannot be openly viewed on the wire.

WCF provides a rich and configurable environmentfor creating security policies and setting runtime behaviors to controlsecurity features. A variety ofmutual authentication mechanismsare supportedusing token formats such as Windows tokens, username and password,certificates, and issued tokens (in a federated environment).Authorizationcanbebased on Windows roles, ASP.NET roles, or you can provide customauthorization policies.Message protection (integrity and confidentiality) canbebased on symmetric session keys or asymmetric keys for single-hop protection.

Bothbindingsandbehaviorsinfluence aspects ofsecurity related to authentication, authorization, and message protection (alsocalled transfer security). Many of the security settings are exposed as part ofa service security policy that can be consumed by clients.
                -Bindings definethe type of credentials expected for authentication and authorization and overwhat protocol those credentials should be provided.
                -Behaviors describeauthentication and authorization policies that are followed when processingclient credentials. 
                                -e.g.:you can configure UserName tokenauthentication to use the ASP.NET membership provider, and you can controlauthentication rules for certificates
                                -e.g.:Impersonate
               
Binding Security 

Binding configuration has the most significant impact on security policy. For example, forintranetcommunications or systemsbehind the firewall,TCP protocolwith binary message encoding is usuallypreferred. For Internetaccess,HTTPprotocol is a typical choice using text or MTOMencoding (depending on the message size).


Default security settings

NetTcpBinding is secure by default. Specifically,callers must provide Windows credentials for authentication, and all messagepackets are signed and encrypted over TCP protocol.

NetTcpBinding tcpBinding = new NetTcpBinding( );By Default as:

<netTcpBinding> <bindingname="netTcp"> <security mode="Transport"><transport clientCredentialType="Windows" /> </security></binding> </netTcpBinding>


Security mode
                -None: Turnssecurity off. Not recommended.
                -Transport: Usestransport security for mutual authentication and message protection.
                -Message: Usesmessage security for mutual authentication and message protection.
                -Both: Allows you tosupply settings for transport and message level security (only MSMQ supportsthis).
                -TransportWithMessageCredential: Credentials are passed with the message, and message protection and serverauthentication are provided by the transport layer.
                -TransportCredentialOnly: Clientcredentials are passed with the transport layer, and no message protection isapplied.
                -Not all bindingssupport all security modes, so what you'll find is that only a subset of themodes described earlier will be available—depending on the binding you areconfiguring

Client credential type
                -When transportsecurity is enabled, the transport provides a way to pass credentials. Across all bindings that support transport security the following client credentials are supported: None, Basic, Digest, NTLM, Windows, and Certificate. Essentially you have a choice between anonymous credentials, some form of Windowscredential, or a certificate.
                -When messagesecurity is enabled, credentials are included in the SOAP message and followinteroperable standards. Across all bindings that support message security thefollowing client credentials are supported: None, Windows, UserName,Certificate, and IssuedToken. In this case, the choice is to provide nocredentials, Windows credentials (NTLM or Kerberos), username and password,certificate, or a SAML or custom XML token
                               
                -Not all transportand message credential types are supported across all bindings. Your choice ofclient credential type may also affect other configuration settings for theservice—for example,UserName credentials require either transport message protection or a service certificate be used to protect the exchange.
               
Service credentials
                -Services alsoauthenticate to clients.When non-Windows credentials are specified as theauthentication mechanism, the service must provide a service certificate tosatisfy both authentication and message protection needs.

Message Protection
                -Protection levelsettings are controlled by theservice contract,operation contract,messagecontractorfault contract
                -TheProtectionLevel enumeration provides the following options:None, Sign, and EncryptAndSign. None disables message protection, EncryptAndSign provides fullmessage protection, and Sign indicates the message should be signed but notencrypted.
               
Algorithm suite
                -When you configuremessage security for a binding, you can select an algorithm from any one of thealgorithms specified by the SecurityAlgorithmSuite type from theSystem.ServiceModel.Security namespace.
               
                e.g.:
               
 <wsHttpBinding><binding name="wsHttp"> <securitymode="Message"> <messageclientCredentialType="UserName"algorithmSuite="TripleDes"/> </security> </binding>
               
                -The following arevalid settings for the algorithmSuite attribute: Basic128, Basic128Rsa15,Basic128Sha256, Basic128Sha256Rsa15, Basic192, Basic192Rsa15, Basic192Sha256,Basic192Sha256Rsa15, Basic256, Basic256Rsa15, Basic256Sha256,Basic256Sha256Rsa15, TripleDes, TripleDesRsa15, TripleDesSha256, andTripleDesSha256Rsa15. Each of these suite names maps to aSecurityAlgorithmSuite instance, which defines algorithms and key lengths forvarious cryptographic operations.
               
Authentication, Authorization, and Identities
                -Access toresources during a service operation is influenced by three key elements
                                -Process identity
                                                -Service operationsare executed under the process identity of the service host. For ASP.NET hosts,this is usually the ASP.NET (on Windows XP) orNETWORK SERVICE(on WindowsVista and Windows Server 2003) account, and for self-hosting, you mayallocatea different account. This process identity is the Windows account that governswhat the service code can do at run time when attempting to access Windowsresources, such as the database, registry, or filesystem.
                                -Security principal
                                                -there is asecurity principal attached to each executing thread.That security principalholds the caller's identity, which may be tied to a Windows account or a customdatabase credential, and its roles.
                                -ServiceSecurityContext
                                                -This type providesruntime access to other relevant information about the security context for aservice operation. The ServiceSecurityContext is a runtime type that includesidentities, a set of claims, and authorization policies.
                                                -For every messageprocessed by the service model, the ServiceSecurityContext is populated withinformation about the authenticated caller and the policies used toauthenticate that caller.The key properties of the ServiceSecurityContext typeare:
                                                               -PrimaryIdentity: Containsa reference to an IIdentity type such as WindowsIdentity or GenericIdentity,representing the authenticated caller.
                                                               -WindowsIdentity: Containsa reference to the same identity as the PrimaryIdentity if it is aWindowsIdentity type.
                                                               -AuthorizationContext
                                                               -AuthorizationPolicies

                                                               
                                               -You can access theServiceSecurityContext through the current OperationContext
                                                               e.g.:ServiceSecurityContextcontext = OperationContext.Current.ServiceSecurityContext;
                                                OR
                                               -TheServiceSecurityContext type also supplies a Current property:
                                                               e.g.:ServiceSecurityContextcontext = ServiceSecurityContext.Current;
                                                               
                                                Note:The same identity is wrapped in the executing request thread's security principal— an IPrincipal object accessible through the thread's CurrentPrincipal property asshown here: 
                                                if(Thread.CurrentPrincipal.Identity.IsAuthenticated) userName =Thread.CurrentPrincipal.Identity.Name;
                                                It is the thread'ssecurity principal that is used for role-based security;

Security tokens and authentication
                -To authenticate to a service, client credentials are passed in thesecurity headersof a messageand validated against the service security policy. The serialized representationof a credential is often referred to as a security token.
                                -e.g.:
                                                -WindowsSecurityToken
                                                -UserNameSecurityToken
                                                -X509SecurityToken
                -**Regardless ofthe configuration, successful token authentication results in an identity attached to the security context and a security principal attached to therequest thread for role-based authorization

Role-based authorization
                -The default role provideris Windows;
                -If you aren'texpecting Windows credentials, you can change the role provider by providing aServiceAuthorization behavior and specifying an alternate role provider.
                                -e.g.:
                                               
<behaviorname="serviceBehavior"> <serviceAuthorization principalPermissionMode="UseAspNetRoles"/></behavior>

               
Impersonation
                -When Windowscredentials are used, the service can be configured to impersonate callers sothat the request thread operates under the impersonated Windows token. Thismakes it possible for services to access protected Windows resources under theidentity of the caller instead of the process identity of the service—for thatrequest
                                -ImpersonationOption
                                                -NotAllowed
                                                -Allowed
                                                -Required
                -Clients can (andshould) also control impersonation, to prevent services from using theiridentity to access resources.
                                -TokenImpersonationLevel
                                                -None
                                                -Anonymous
                                                -Identification
                                                -Impersonate
                                                -Delegate


Lifecycle of a secure request. 
                -Clients initializethe channel with the right credentials, as required by the binding, 
                -which are then serialized as a security token in the SOAP message. 
                -The serviced eserializes these tokens and authenticates them according to the type of tokenand related service behaviors

                -then initializes thesecurity context for role-based security.

 

Additional Information

TransportWithMessageCredential確保了傳輸上的安全,並提供了客戶端憑據。

http://www.cnblogs.com/artech/archive/2011/05/22/authentication_01.html

TLS/SSL幫助我們解決兩個問題:客戶端對服務端的驗證,以及通過對傳輸層傳輸的數據段(Segment)進行加密確保消息的機密性。

在Transport安全模式下,意味着我們不得不在傳輸層而不能在應用層解決對客戶端的認證,這就決定了可供選擇的認證方式不如Message模式多。例如,transport 不支持username 和 password

安全傳輸旨在解決三個問題:認證、消息一致性和機密性,而認證既包括服務端對客戶端的認證,也包括客戶端對服務端的認證。對於混合安全模式,消息的一致性、機密性和客戶端對服務端的認證通過Transport安全模式來實現,而採用Message安全模式實現服務端對客戶端的認證。

 As soon as you useusername/password you need some sort of secure channel. However you don't need certificates on the clients; only on the server.

e.g.:

Service Bindings with following code will throw a exception

<bindings>
      <wsHttpBinding>
        <binding  name="SocialConfig">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>


Service Binding with following code will success

 <bindings>
      <wsHttpBinding>
        <binding  name="SocialConfig">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章