Application security

Web Services

Ajay Yadav
March 18, 2013 by
Ajay Yadav

Introduction

Software developers have struggled to create software components that can be called remotely over local networks and the Internet. In this process, several technologies came into light but some of them were not quite successful enough due to many limitations and hurdles such as communicating over an unreliable Internet, or running every type of hardware and operating system in a computer network.

This is where XML web services enter the scene. To interact with a web service, you simply need to send an XML message over HTTP. Because every Internet-enabled device supports HTTP, every programming framework includes a higher level toolkit that makes it possible to communicate with a web service (XML is platform independent). As XML web services are not .NET framework specific, they can also be consumed in other programming frameworks such JAVA, PHP, AJAX, ASP etc.

Distributed Computing Technologies

Distributed computing is the partitioning of application logic into units that are executed on two or more computers in a network. There are numerous technologies that have been developed to allow the distribution and reuse of application logic.

Comparison of different Distributed Technologies

Characteristics

Web Services

DCOM

CORBA

Cross Platform Yes NO Partly

Firewall Friendly LOW HIGH HIGH

Protocol Complexity Yes NO NO

Discovery UDDI Registry Naming Service

Interface Description WSDL IDL IDL

RPC Mechanism HTTP DCE-RPC IIOP

Encoding XML NDR CDR

Distributed application logic has many advantages, such as the following:

  • High Scalability
  • Improved Security
  • Easy Deployment
  • Load Balancing

Problem with Distributed Components

In a major enterprise, very rarely do you find that entire organization and its data repository residing on a single vendor platform. An organization is usually made up of a patchwork of systems, some based on Microsoft, some on UNIX, FREEBSD and others. So there is a big question, how do these disparate systems communicate with each other? Interoperability
and load balancing issues are prevalent in CORBA and DCOM because they are developed before the advent of the Internet. They are fine for building enterprise applications with software running on the same platform but not for those that span different platforms or the Internet.

Advantage of Web Services

  • They are simple to build and are supported on a wide range of platforms.
  • They can extend their interface and add new methods without affecting the client's operations.
  • They are firewall-friendly because all communication happens through HTTP on port 80.
  • They are stateless, since there is no permanent connection which scales up for many clients.

Building Simple Web Services

At this point, I will show you how to create a simple web service executed under .NET. In this example, we define some methods in the UtilityWebService class. They are responsible for adding two integer values and displaying a "hello word" text as follows:

  1. Open a Visual C#.net website in the Visual Studio 2010 IDE.
  2. Right click on the project name from the Solution Explorer and click Add New Item.
  3. Choose a web service from the template and name it UtilityWebService.cs.

    Figure 1.1: Web Service Template

  4. Thereafter, implement the addition method functionality in the class UtilityWebService.cs.

    C# web service code

  5. [c language="#"]using System;

    using System.Collections.Generic;

    using System.Web;

    using System.Web.Services;

    ///

    <summary> /// Summary description for UtilityWebService

    /// </summary>

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

    // [System.Web.Script.Services.ScriptService]

    public class UtilityWebService : System.Web.Services.WebService {

    public UtilityWebService () {

    //Uncomment the following line if using designed components

    //InitializeComponent();

    }

    [WebMethod]

    public string HelloWorld() {

    return "Hello World";

    }

    [WebMethod]

    public int addition(int a,int b)

    {

    return a+b;

    }

    }
    [/c]

  6. It is essential to add the [WebMethod] attribute before any new method definition.
  7. Finally, build the project and see the output in the browser. You will notice the methods here defined in the web service class.

    Figure 1.2: Web Service Output

  8. Now click the addition method, enter some integer values in the text boxes, and invoke the web service class method as follows:

    Figure 1.3: Web Service Method test

  9. Finally, see the addition result in the form of an XML file that is passed over the wire through HTTP and is compatible with almost every platform.

    Figure 1.4: method XML Output

Web Services Components

Web services are a piece of business logic that can be accessed over the Internet. You can reuse someone else's business logic instead of replicating it yourself. This technique is similar to what programmers currently do with a library of APIs, classes and components. The main difference is that web services can be located remotely on another server and managed by another vendor. Google's search engine is a kind of web service - you submit a search expression, it compiles a list of matching websites, and returns the list to your web browser.

There are some key protocol flows that make web services complete:

  • SOAP( Simple Object Access Protocol)
  • DISCO (Discovery)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL ( Web Services Description Language)

SOAP

Web services manipulate objects through XML messages. SOAP enables you to expose and consume complex data structures which include Items such as data sets and tables. The data sets you send or consume can flow over the same Internet wire (HTTP), thereby passing through firewalls. SOAP defines the message you use to exchange the data but it doesn't describe how you send the message. In other words, to communicate with web services, a client opens an HTTP connection and sends a SOAP message. SOAP is XML based; it can be interpreted by a wide range of software on many operating systems.

Here is a typical SOAP message sent from a web service client to a server:

SOAP Request

[xml]<!--?xml version="1.0" encoding="utf-8"?-->

<a>int</a>
<strong>int</strong>

[/xml]

Here is a part of the SOAP reply from the server:

SOAP Response

[xml]HTTP/1.1 200 OK

Content-Type: application/soap+xml; charset=utf-8

Content-Length: length

<!--?xml version="1.0" encoding="utf-8"?-->

int

[/xml]

DISCO

Before you can use a web services, you need to know where to find them. The DISCO standard creates a single file that is the repository of all related web services. You can publish a DISCO file that contains links to all the web services the server provides. The client then simply needs to request this file to find all the available web services. When you set a Web Reference inside .NET, the software automatically handles the details of discovery for you, but you can also get into the details of the process yourself by using disco.exe as follows:

disco http://localhost:2186/TestWS/WebService.asmx

The tool disco.exe contacts the web service and creates two additional files with .discomap and .wsdl extensions. These are XML files that will show you the names of the other files and their URLs.

UDDI

UDDI is a centralized directory where web services are published. This is the place where a potential client can search for their specific needs. Different organizations may use different UDDI registries. To retrieve information from a UDDI directory, you use a web service interface.

WSDL

Before consuming a web service, knowledge of the SOAP message that it can send and receive is required. WSDL is a standard by which a web service can tell clients what messages it accepts and what results it will return. It defines everything about the public interface of a web service such as data types, the methods it exposes, and the URL through which those methods can be accessed.

Consuming Web Service

Before consuming a web service, we need to generate a Proxy class which wraps the call to the web service's methods. It takes care of generating the correct SOAP message format and managing the transmission of the message over the wire using HTTP on port 80. When it gets the response message back, it also converts the results back to the corresponding .NET data types.

We can generate a Proxy class in .NET in two ways:

  1. Visual Studio IDE web reference feature
  2. Command line utility Wsdl.exe

Generating the Proxy class with VS IDE

    1. Design the default.aspx with two textboxes , three labels and a single button server control.
    2. Right click over the client project in the Solution Explorer, select Add Service reference, click on the Advance button in the dialog box, and finally click Add Web Reference.
    3. Copy the Web Service URL from image 1.2, paste it into the URL text box and hit Enter. This operation will browse your web service.

      Figure 1.5: Add Web Reference Dialog box

    4. The web service test page will appear in a window with the entire methods list and the Add Reference button enabled:

      Figure 1.6: Adding a Web Reference

    5. In the Web Reference name text box, you can change the namespace in which the proxy class will be generated.
    6. Click the Add Reference button.
    7. Now the web reference will appear in your project's Solution Explorer under the Web References group:

      Figure 1.7: Web Reference in Solution Explorer

    8. Open the Default.aspx.cs file and add a button click handler and the following code:
    9. [c language="#"]public partial class _Default : System.Web.UI.Page

      {

      protected void btnAdd_Click(object sender, EventArgs e)

      {

      int x, y, Result;

      x = Convert.ToInt32(TextBox1.Text);

      y = Convert.ToInt32(TextBox2.Text);

      //web service class instantiation
      localhost.UtilityWebService obj = new localhost.UtilityWebService();

      //Method call
      Result=obj.addition(x, y);

      //Output

      Label3.Text = Result.ToString();

      }

      }

      [/c]

    10. Finally, run the project and enter two integer type values in the given text boxes. Hit the Addition button to call the web service:

      Figure 1.8: Addition Web Reference Result

    Generating the Proxy Class WSDL.EXE

    This utility takes the WSDL file and generates a corresponding proxy class that you can use to invoke the web service. This tool does not require the web service client to use .NET IDE.

    1. Open command prompt from Start-> All Programs-> MS Visual Studio 10-> Visual Studio Tools.
    2. Then navigate to the folder that contains the WSDL file and fire this command:
    3. wsdl /out:UtilityWebServiceProxy.cs http://localhost:2186/TestWS/UtilityWebService.asmx

      By default, the generated class is in C#, but you can change it by adding the /language:vb parameter.

    4. If you browse your project directory, you will notice that the UtilityWebServiceProxy.cs file is added there.
    5. Now copy this file to your project App_Code folder by selecting Add Existing Item from Solution Explorer.
    6. Finally, instantiate the web service class again.

    Note: If a client is already consuming the web service and you made any changes to it later, you won't need to perform the whole process again. Just go to the Solution Explorer, right click over the Web References folder and select Update reference. All new definitions are reflected automatically.

    Refining Web Services

    There are other web service features such as session state, data caching and transactions. The secret of applying these features is the WebMethod attribute. However, several other WebMethod properties exist such as those described in this table:

    Arguments

    Description

    CacheDuration Depicts the number of seconds that the method response will be maintained in cache.

    Description Elaborates the method description.

    EnableSession Configures the method to access information in the session collection.

    TransactionOption Gets or Sets the transaction type such as allowed, Not Supported, Required, Supported, etc.

    BufferResponse Determines whether the method response is buffered; set to True by default.

    Cache duration

    [c language="#"][WebMethod(CacheDuration=50)]

    public int addition(int a, int b)

    {

    ..

    }

    [/c]

    Description

    [c language="#"][WebMethod(Description="Retrun the addition of two integer")]

    public int addition(int a, int b)

    {

    ..

    }

    [/c]

    Session

    [c language="#"][WebMethod(EnableSession=true)]

    public int addition(int a, int b)

    {

    ..

    }

    [/c]

    Transaction Option

    [c language="#"][WebMethod(TransactionOption=TransactionOption.RequiresNew)]

    public int addition(int a, int b)

    {

    ..

    }

    [/c]

    Buffer Response

    [c language="#"][WebMethod(BufferResponse=false)]

    public int addition(int a, int b)

    {

    ..

    }

    [/c]

Ajay Yadav
Ajay Yadav

Ajay Yadav is an author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with abundant premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming and Exploit Development.

He is a regular contributor to programming journal and assistance developer community with blogs, research articles, tutorials, training material and books on sophisticated technology. His spare time activity includes tourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com