WCF and ASMX services and consuming using IP, Siteminder, Kerberos and SSL Authentication

WCF and
ASMX services and consuming using IP, Siteminder, Kerberos and SSL Authentication…

1.       Proxy

a.       Any type of Proxy (WCF or ASMX) can be created for a ASMX svc

b.      Any type of Proxy (WCF or ASMX) can be created for a WCF svc

2.       To create a proxy, we use VS..Create Ref…

3.       For WCF svc, use …/abc.svc?wsdl to get the wsdl (using which the proxy is generated)

4.       WCF Test Client is a tool to send request to wcf svc and invoke it

5.       For asmx svc u can use fiddler etc to invoke the svc.

6.       To consume a svc using its proxy all u have to do is to instanciate the Client : abcClient
svc = new abcClient(“abcBinding”, endpoint);

And call the remote method: svc.StringEcho(ref
testString); //Getting the response from the StringEcho method.

Authentication

The above pt 6 is valid when the svc does
not have any auth. Enabled, or maybe uses IP Auth.

But there are other auth mechanisms that
need the client to do special thigs:

A.
SITEMINDER
AUTH.

In the web.config, the following should be present:

A.      BINDING

                 <system.serviceModel>
                 <bindings>
                 <basicHttpBinding>
<!--For IP and SM Auth-->
                                   <binding name=" abcBinding " closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                                            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                                            <security mode="None">
                                                     <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
                                                     <message clientCredentialType="UserName" algorithmSuite="Default"/>
                                            </security>

                        </binding>

</basicHttpBinding>

                          </bindings>
<client>
                          <!--For IP and SM Auth-->
                          <endpoint address="" contract="sdsde" name="abcBinding" binding="basicHttpBinding" bindingConfiguration="abcBinding" behaviorConfiguration="abcEndpointBehavior"/>
         </client>
                 <!--ForSiteminder-->
                 <extensions>
                          <behaviorExtensions>
                                   <add name="SMCookieBehavior" type="myNamespace.SM_BehaviorExtensionElement, Service Bus Checks, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
                          </behaviorExtensions>
                 </extensions>
                 <behaviors>
                          <endpointBehaviors>
                                   <behavior name="abcEndpointBehavior">
                                            <SMCookieBehavior asdf="test asdf"/>
                                   </behavior>                                 
                          </endpointBehaviors>
                 </behaviors>
         </system.serviceModel>

B.      Now
for SM auth the code is :

1.  add a Behavior and its Behavior Extension Element for SM Authentication
 
 namespace myNamespace 
{
public class SM_BehaviorExtensionElement : BehaviorExtensionElement
    {

        public override Type BehaviorType
        {
            get
            {
                return typeof(SM_EndpointBehavior);

            }
        }

 
 
        protected override object CreateBehavior()
        {
            return new SM_EndpointBehavior(asdf);
        }

        [ConfigurationProperty("asdf", IsRequired = true)]
        public string ASDF
        {
            get { return (string)base["asdf"]; }
            set { base["asdf"] = value; }
        }
    }
}
2.  Add an Endpoint  Behavior for SM Authentication
    public class SM_EndpointBehavior : IEndpointBehavior
    {
        private string m_asdf;
        public SM_EndpointBehavior(string asdf)
        {
           this.m_asdf = asdf;
        }
        #region IEndpointBehavior Members
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {        }
        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            SM_UserAgentMessageInspector inspector = new SM_UserAgentMessageInspector(this.m_userAgent);
            clientRuntime.MessageInspectors.Add(inspector);
        }
          public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {}
         public void Validate(ServiceEndpoint endpoint)
        {}
        #endregion
    }
 
3.  Add a Message Inspector for SM Authentication
 public class SM_MessageInspector : IClientMessageInspector
    { 
        private const string USER_AGENT_HTTP_HEADER = "user-agent"; 
        private string m_asdf;
        public SM_UserAgentMessageInspector(string asdf)
        { 
           this.m_asdf = asdf; 
        }
 
       #region IClientMessageInspector Members
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {        }
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
Console.log("in MessageInspector");
            }
            HttpRequestMessageProperty httpRequestMessage;

            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {                
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;                
                HttpRequest Request = HttpContext.Current.Request;
                string SMCookie = null;
                SMCookie = Request.Headers["Cookie"];
                if (SMCookie != null)
                {
                    Console.write("SMCookie is :" + SMCookie);
                    httpRequestMessage.Headers["Cookie"] = SMCookie;
                    console.log("Cookie added :" + SMCookie);
                }
                else
                {
                   Console.write("SMCookie is null");
                }
            }

            else
            {                
                httpRequestMessage = new HttpRequestMessageProperty();
                HttpRequest Request = HttpContext.Current.Request;
                string SMCookie = null;
                SMCookie = Request.Headers["Cookie"];
                if (SMCookie != null)
                {
                    httpRequestMessage.Headers["Cookie"] = SMCookie;                
                }
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }
            return null;
        } 
        #endregion
    }

C.      To
consume a svc using its proxy over SM
all u have to do is to instanciate
the Client : abcClient svc = new abcClient(“abcBinding”, endpoint);

And call the remote method: svc.StringEcho(ref
testString); //Getting the response from the StringEcho method.

 

B.
KERBEROS
AUTH.

a.       For
this the client needs to do:

A.  WEB.CONFIG
<system.serviceModel>
                 <bindings>
                          <basicHttpBinding>
                                   <binding name="BasicHttpBinding_IKerberosService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                                            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                                            <security mode="TransportCredentialOnly">
                                              <transport clientCredentialType="Windows" realm=""/>
                                              <message clientCredentialType="UserName" algorithmSuite="Default"/>
                                      </security>
                                   </binding>

Now Client:

<client>         
                          <!--For Kerberos Auth-->
                          <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IKerberosService contract="abc.IKerberosService" name="BasicHttpBinding_IKerberosService">
                          </endpoint>

Now in code u have to do:

 EndpointIdentity identity = null;
                identity = EndpointIdentity.CreateSpnIdentity(“HTTP/a.b.com@p.q.r.COM”);
                string endpoint = “http:// a.b.com@p.q.r.COM:1234/abc/MyKerberosService.svc
”;

                EndpointAddress address = null;
                address = new EndpointAddress(new Uri(endpoint), identity);

                MyKerberosService Client client = new MyKerberosServiceClient("BasicHttpBinding_IKerberosService ", address);

                try
                {                    
                    String response = client.echoString("HELLO");

C.  SSL
AUTH

Web.config change:
<system.serviceModel>
                 <bindings>
                          <basicHttpBinding>
         <!--For SSL-->
                                   <binding name="abcSoap">
                                            <security mode="Transport">
                                                    <transport clientCredentialType="Certificate"/>
                                            </security>
                                   </binding>
Then
         <client>                  
                          <!--ForSSL-->
                          <endpoint address="" binding="basicHttpBinding" bindingConfiguration="GetFieldsMulRecSoap" contract="a.b" name="SSLAuthSvc"/>
                 </client>
Code :
1.   
        protected void validateCert(string CertSubject)
//HERE WE ARE SIMPLY ACCEPTING ALL THE SERVER SERTIFICATES THAT CONTAIN THE CERTIFICATE WE ARE LOOKING FOR USING CertSubject. THIS IS JUST BASIC VALIDATION. For PROPER VALIDATION, WE MAY WANT TO CHECK FOR SOME OTHER PROPERTY. Note that THE SERVER’S PUBLIC CERTI IS DEPLOYED IN 
        {
            //trust sender
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => cert.Subject.Contains(CertSubject));
 //cert sub can be found from the cert props.It’s of format: a.b.com
Console.write(“Server Certificate Validated by Subject”);
 
        }
Main Code:
 string CertThumbprint = "12 12 41 c6 39 52 4e 59 6y 78 a6 2u c6 56";
string endpoint = “https://a.b.com:4208/p/q/r”;
var svc = new MySSLSvcClient(“SSLAuthSvc”, endpoint);
response = svc.myMethod(); 
svc.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, CertThumbprint);
 
//OK, SO WHAT WE ARE DOING HERE IS SIMPLY FINDING OUR OWN CERTIFICATE IN “StoreLocation.LocalMachine, StoreName.My”. NOTE THAT StoreName.My ACTUALLY REFERS TO PERSONAL FOLDER IN THE CERT STORE…
FINALLY WE ARE SENDING THE CERT WITH EVERY REQUEST
 
GENERAL DEPLOYMENT INSTRUCTIONSINSTALLATION:

1. Create a New Virtual Directory in IIS to host the site.
2. Create a new App Pool and run it under a sepcific service account (if needed)
3. Associate the VD with this App Pool
4. Convert the VD to Application from its Properties in intemgr.

 

DEPLOYMENT INSTRUCTIONS SPECIFIC TO CERT INSTALLATION:
  1. Install the
    Certificate of the Service Account under which the Application Will Run by
    running install.cmd*
  2. Next Install
    the Public Certificate of SERVER (Certificate Name: A.B.com.cer, in the location:
    storeName=”TrustedPeople” storeLocation=”LocalComputer”.

Note THAT IF YOU ARE RUNNING YOUR APPLICATION VD UNDER A SPECIFIC USER, CREATE A NEW APP
POOL AND IN THAT GIVE THE SPECIFIC  USER’S CREDENTIALS AND THEN RUN THE VD
UNDER THAT NEW APP POOL

ALSO, Add
the SPECIFIC USER account to the local IIS_WPG group.

* NOTE That
install.cmd is :

@echo off

certutil
-addstore ROOT QWER.cer  <THIS IS THE PARENT OF CLIENT CERTI>

certutil
-addstore ROOT ASDF.cer  <THIS IS THE PARENT OF SERVER CERTI>

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -i MY_CERT.pfx
-c LOCAL_MACHINE\MY -p test -a administrators

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a MY_CERT

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a Administrators

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a System

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -l -c
LOCAL_MACHINE\MY -s ” MY_CERT”

pause

 

Wireshark Tips

Wireshark Tips

1. Filters

a. tcp.port eq 25

b. (ip.dst == xxx.xxx.xxx.xxx && ip.src == xxx.xxx.xxx.xxx) || (ip.dst == xxx.xxx.xxx.xxx && ip.src == xxx.xxx.xxx.xxx) && http

ref: http://wiki.wireshark.org/DisplayFilters

http://wiki.wireshark.org/CaptureFilters

Workflow:

1. Interface options

2. Select the right interface (INTEL) *

3. Start Capture

4. Filter using commands

*In Case WinPcap is not installed this would not work…

WCF Soap over HTTP vs REST over HTTP

Basically I want to share that with WCF, every endpoint (web Method) has a distinct URL and

calling it is a new http request…Here’s the wiki
description:

The
Architecture

WCF is a tool often used to implement and deploy a service-oriented architecture (SOA).
It is designed using service-oriented architecture principles to support
distributed computing where services have remote consumers. Clients can consume
multiple services; services can be consumed by multiple clients. Services are
loosely coupled to each other. Services typically have a WSDL interface (Web
Services Description Language) that any WCF client can use to consume the
service, regardless of which platform the service is hosted on. WCF implements
many advanced Web services (WS) standards such as WS-Addressing,
WS-ReliableMessaging and WS-Security. With the release of .NET Framework 4.0,
WCF also provides RSS Syndication Services, WS-Discovery, routing and better
support for REST services.

Endpoints

A WCF client
connects to a WCF service via an Endpoint. Each service exposes its contract
via one or more endpoints. An endpoint has an address (which is a URL
specifying where the endpoint can be accessed) and binding properties that
specify how the data will be transferred.

The mnemonic
“ABC” can be used to remember address / binding / Contract. Binding
specifies what communication protocols are used to access the service, whether
security mechanisms are to be used, and the like. WCF includes predefined
bindings for most common communication protocols such as SOAP over HTTP, SOAP
over TCP, and SOAP over Message Queues, etc. Interaction between WCF endpoint
and client is done using a SOAP envelope. SOAP envelopes are in simple XML
form, which makes WCF platform-independent. When a client wants to access the
service via an endpoint, it not only needs to know the contract, but it also
has to adhere to the binding specified by the endpoint. Thus, both client and
server must have compatible endpoints.

 

With the
release of the .NET Framework 3.5 in November 2007, Microsoft released an
encoder that added support for the JSON serialization format to WCF.[3] This
allows WCF service endpoints to service requests from AJAX-powered Web pages
which only accept JSON

 

Behaviors

Behaviors
are just types that modify or extend service or client functionality. Behaviors
allow the developer to create custom processing, transformation, or inspection
that is applied to messages as they are sent or received. Some examples of uses
for behaviors are:

 

Controlling
whether metadata is published with a service.

Adding
security features to a service, such as impersonation, authorization, or
managing tokens

Recording information
about messages, such as tracking, tracing, or logging

Message and
validation.

Invoking all
additional operations when messages are received–such as notifying users when
certain messages arrive

Behaviors
implement the IServiceBehavior interface for service extensions, the
IEndpointBehavior for endpoints, the IContractBehavior interface for service
contracts, or the IOperationBehavior for operations. Service behaviors are used
for message processing across a service, rather than processing that would be
specific to a single operation.

 

 

 

 

–>

Wireshark Tips

1.       Filters

a.       tcp.port
eq 25

b.       (ip.dst
== xxx.xxx.xxx.xxx && ip.src == xxx.xxx.xxx.xxx) || (ip.dst ==
xxx.xxx.xxx.xxx && ip.src == xxx.xxx.xxx.xxx) && http

ref: http://wiki.wireshark.org/DisplayFilters

        http://wiki.wireshark.org/CaptureFilters

Workflow:

1.       Interface
options

2.       Select
the right interface (INTEL) *

3.       Start
Capture

4.       Filter
using commands

*In Case WinPcap is not installed this would not
work…

 

 

–>

SSH Basics

What is it?

1.       http://en.wikipedia.org/wiki/Ssh://

a.       Secure
Shell (SSH) is a cryptographic network protocol for secure data communication,
remote command-line login, remote command execution, and other secure network
services between two networked computers that connects, via a secure channel
over an insecure network, a server and a client (running SSH server and SSH
client programs, respectively).[1] The protocol specification distinguishes
between two major versions that are referred to as SSH-1 and SSH-2.

b.      The
best-known application of the protocol is for access to shell accounts on
Unix-like operating systems, but it can also be used in a similar fashion for
accounts on Windows. It was designed as a replacement for Telnet and other
insecure remote shell protocols such as the Berkeley rsh and rexec protocols,
which send information, notably passwords, in plaintext, rendering them
susceptible to interception and disclosure using packet analysis.[2] The
encryption used by SSH is intended to provide confidentiality and integrity of
data over an unsecured network, such as the Internet.

c.       SSH
uses public-key cryptography to authenticate the remote computer and allow it
to authenticate the user, if necessary

d.      SSH
is typically used to log into a remote machine and execute commands, but it
also supports tunneling, forwarding TCP ports and X11 connections; it can
transfer files using the associated SSH file transfer (SFTP) or secure copy
(SCP) protocols.

e.      The
standard TCP port 22 has been assigned for contacting SSH servers

f.       
An SSH client program is typically used for establishing connections to
an SSH daemon accepting remote connections. Both are commonly present on most
modern operating systems, including Mac OS X, most distributions of GNU/Linux,
OpenBSD, FreeBSD, NetBSD, Solaris and OpenVMS. Notably, Windows is one of the
few modern desktop/server OSs that does not include SSH by default.
Proprietary, freeware and open source versions of various levels of complexity
and completeness exist.

g.       SSH
is important in cloud computing to solve connectivity problems, avoiding the
security issues of exposing a cloud-based virtual machine directly on the
Internet. An SSH tunnel can provide a secure path over the Internet, through a
firewall to a virtual machine

2.       Windows
Clients:

a.       OpenSSH

b.      PuTTY

It’s better to use PuTTY as the experience is
better and more native.

 

Task Parallel Library (TPL)

Getting Started:

 

 

–>