168
Security Filters for Web Servers CONTENTS S.NO TITLE PAGE NO. 1. INTRODUCTION About the project About the organization Need of the Project 2. DEVELOPMENT ENVIRONMENT Hardware Environment Software Environment About the software 3. SYSTEM ANALYSIS Introduction to Analysis Feasibility Study 4. SYSTEM DESIGN Introduction to Design Context Flow Diagrams Data Flow Diagrams UML Diagrams Sequence Diagrams Source Code 5. SYSTEM IMPLEMENTATION Existing System Proposed System 6. SYSTEM TESTING Dept of MCA, KSRMCE

Security Filters Final

Embed Size (px)

Citation preview

Page 1: Security Filters Final

Security Filters for Web Servers

CONTENTS

S.NO TITLE PAGE NO.

1. INTRODUCTIONAbout the projectAbout the organizationNeed of the Project

2. DEVELOPMENT ENVIRONMENTHardware EnvironmentSoftware EnvironmentAbout the software

3. SYSTEM ANALYSIS

Introduction to Analysis Feasibility Study

4. SYSTEM DESIGNIntroduction to Design Context Flow Diagrams Data Flow DiagramsUML DiagramsSequence DiagramsSource Code

5. SYSTEM IMPLEMENTATION

Existing System Proposed System

6. SYSTEM TESTING Testing Specification & Documentation White Box & Black Box Testing Testing approach & Test deliverables

7. SAMPLE SCREENS 8. CONCLUSION

9. BIBLIOGRAPHY

Dept of MCA, KSRMCE

Page 2: Security Filters Final

Security Filters for Web Servers

INTRODUCTION

Dept of MCA, KSRMCE

Page 3: Security Filters Final

Security Filters for Web Servers

To design software, which provides the users with the flexibility of receiving

files from the web server in a secured format. This software design includes the

encryption and compression algorithms for converting the normal text to cipher

text for a secured transfer. The basic aim of the project is to honor the software

engineering principle that “never disturb any code that is working well, instead

extend the code to give it new functionality”. This project helps that situation by

not disturbing the original data or file, but by introducing the compression and

encryption smoothly, in the form of a filters which are based on LZW algorithm

and RSA algorithm. One filter for compressing the data uses LZW(Limpel, Ziv,

and Welch) algorithm. LZW compresses the data from 30% to 90% based on the

type of the data. A file or data compressed in server side that reduced in its size

and at the client side file or data is decompressed. Since the size of the data is

reduced the downloading will become fast and safe. Data compression has varies

advantages, it is easier to maintain many files with in small storage, transmission

time for the compressed file is less over the network, it requires less bandwidth on

data transmission channel. Second filter for encrypting the data uses RSA. RSA is

a public-key cryptosystem developed by MIT professors to help ensure Internet

security. Algorithm converts input data into something unrecognizable

(encryption), and converts the unrecognizable data back to its original form

(decryption)

1.1 ABOUT THE ORGANIZATION

Dept of MCA, KSRMCE

Page 4: Security Filters Final

Security Filters for Web Servers

1.2 About the Project

This project primarily allows J2EE deployers to modify the existing or already deployed Java Servlets or Java Server Pages (JSPs), which are called as web components. This project can modify the existing web components in such a way that they need not be disturbed, need not be re-compiled, and need not be re-deployed. So, the project serves like a plug-in, which can smoothly sit into an existing J2EE middle-tier web component, and change its functionality in various ways.

To design these kinds of plug-in components, Sun Microsystems has introduced a new Application Programming Interface (API) in its servlets 2.3 version. This API is commonly referred to as ‘Filter’ing API.

The following is the new API introduced by the Sun Microsystems in its servlets 2.3 API.

javax.servlet.Filterjavax.servlet.FilterChainjavax.servlet.FilterConfig

These three are the interfaces and two more classes have been introduced, as shown below.

javax.servlet.ServletRequestWrapperjavax.servlet.ServletResponseWrapper

My entire project revolves around this new API.

The following is a sample list of things that a Filter kind of component does.

1) Authentication Filters 2) Logging and Auditing Filters 3) Image conversion Filters Dept of MCA, KSRMCE

Page 5: Security Filters Final

SERVLET

JSP

Security Filters for Web Servers

4) Data compression Filters 5) Encryption Filters 6) Tokenizing Filters 7) Filters that trigger resource access events 8) XSL/T filters 9) Mime-type chain Filter

The list is by no means exhaustive. This is just to have an idea of what filters can do.

This project concentrates on implementing ‘Data Encryption and Decryption Filters’. The following figure and the explanation thereafter, is a brief description of what my project is.

Fig 1a

This figure shows the original request-response model between a web client and a web server. HttpRequest is sent by the web client, like a browser and HttpResponse is sent by the web server in response to the request.

WEBSERVER

MODIFIED

HTTP REQUESTREQUEST

Dept of MCA, KSRMCE

CLIENTBROWSER

SERVLET

JSP

HTTP REQUEST

HTTP RESPONSE

WEB SERVER

CLIENTBROWSER

FILTER1

FILTER2

Page 6: Security Filters Final

Security Filters for Web Servers

MODIFIED

RESPONSE HTTP RESPONSE

Fig 1b

The second figure formally defines a Filter. The filter is a Java component (class) which can modify either the request or the response or both by sitting between the web client and the web server. The modification can be in any manner. For example, all the input coming down from a client in the form of the request may be modified to represent some other data, which otherwise is given normally to the servlet hosted by the web server. In the same way the output going to the client from the web server in the form of a response may be modified to represent some other data than the original data.

Fig 1c

Dept of MCA, KSRMCE

Page 7: Security Filters Final

SERVLET

JSP

CLIENTBROWSER SERVLET

Security Filters for Web Servers

WEBSERVER

HTTP …… REQ

…… HTTP RES

The third figure explains the possibility of cascading the filters. Modifications to either the request or the response may be done at various stages. Each stage represents one filter. In such cases, the output of one filter may be given to the next filter.

Anyway, its up to the J2EE designer whether to modify only request or only the response or both or none at all. The next figure explains what exactly this project attempts to do.

Fig 2a

HREQ WEBSERVER

HRES(10MB)

Assume from the figure that a servlet is delivering to the client some amount of pure text data, originally. Now, by applying filtering on the response, the servlet behaves as if it is delivering cipher or encrypted data to the client, which is shown in the following figure.

Dept of MCA, KSRMCE

CLIENTBROWSER

FILTER1

FILTER n+1

FILTER2

FILTER n

Page 8: Security Filters Final

Security Filters for Web Servers

Fig 2b

HREQ WEBSERVER HRES

4MB 10MB

(FIG2b)

To have this effect in the project, I have designed one filter for encrypting the data using RSA. RSA is a public-key cryptosystem developed by MIT professors: Ronald L. Rivest, Adi Shamir, and Leonard M. Adleman in 1977 in an effort to help ensure internet security. As Steve Burnett of RSA Data Security, Inc. described it, a cryptosystem is simply an algorithm that can convert input data into something unrecognizable (encryption), and convert the unrecognizable data back to its original form (decryption). (Limpel, Ziv, and Welch) algorithm. The other part of the project designs another filter for decryption, which is shown in the figures 3a and 3b.

The second filter may be used to give the original data to the client, if the servlet delivers encrypted data to the client.

Fig 3a and 3b

Dept of MCA, KSRMCE

CLIENTBROWSER SERVLET

COMPRESSIONFILTER

CLIENTBROWSER SERVLET

DECOMPRESSIONFILTER

Page 9: Security Filters Final

Security Filters for Web Servers

HREQ HRES

10MB 4MB

1.3 Need for the Project

The basic aim of this project is to honor the software engineering principle that “never disturb any code that is working well, instead extend the code to give it new functionality”.

For example, there is a servlet, which is working well and delivering some amount of plain data to the requesting client. The people who host the servlet may think in the future that of using the technique of encryption to ensure security of the same data. This project helps that situation by not disturbing the original servlet, but by introducing the encryption smoothly, in the form of a filter.

In the same way, another servlet may be delivering encrypted data to the client. In this case, all the clients accessing this content may not have the tools for decrypting the content. And these clients would like to receive the original content even at the expense of security. This project even helps that situation. Even in this case the decryption happens without disturbing the original software, I mean the original servlet.

Dept of MCA, KSRMCE

Page 10: Security Filters Final

Security Filters for Web Servers

DEVELOPMENT ENVIRONMENT

Dept of MCA, KSRMCE

Page 11: Security Filters Final

Security Filters for Web Servers

HARDWARE ENVIRONMENT:

CPU : Pentium IV RAM : 256 Hard disk : 40GB Monitor : LG color monitor Keyboard : 105 standard and mouse. Server : Tomcat5.0

SOFTWARE ENVIRONMENT

Operating system: Windows 2000 Professional Language : Java, Servlets2.0, Filters,JSP.Driver : Tomcat5.0Browser : Internet Explorer5.0

System Analysis

Dept of MCA, KSRMCE

Page 12: Security Filters Final

Security Filters for Web Servers

Web Components

Web components are either Java servlets or JSPs.

Simply speaking, servlet is a Java class just like any other class with a few differences. The servlet class is coded exclusively for plugging it into the web server to extend its functionality.

A normal web server without any programming extensions (CGI, servlets, ASP etc.) can serve to its client’s only static content. The static content may be just HTML pages. With this kind of static content nothing much serious can be accomplished on the server – side. For example, the hit count of a particular page needs to be displayed, which is not possible just with static HTML pages. There should be some programming extension on the server – side which should continuously update a hit counter with each hit and dynamically deliver this count to the client. This is simplest of the much more robust tasks that are accomplished by a Java servlet.

So, a servlet is a Java class that generates dynamic content on the web pages. A servlet can also be thought of as an applet running on the server – side, but without a face, I mean the GUI (Graphical User Interface). As the servlet is run by a web server, one can say that as an applet is to the web browser, a servlet is to the web server.

A servlet is a Java class to be run as a part of a Java – enabled web server. Java – enabled means, the server should have a Java Virtual Machine (JVM) to run the byte – code of the servlet and the supporting class libraries, for example, javax.servlet.*. Even if a web server is not Java – enabled, one can make it so, by attaching it a container (sometimes called as a servlet engine) that supports JVM, class libraries, and thereby servlets. For example, IIS from Microsoft is not Java – enabled, by default. Servlet runners are available for IIS from third – party vendors, which make IIS capable of running Java servlets.

A web container is responsible for running servlets and performs the following prime tasks.

Manages the life cycle of a servlet. Understands the MIME (Multi Purpose Mail Extensions) encoded requests and

decodes them to be understood by the servlet.

Dept of MCA, KSRMCE

Page 13: Security Filters Final

Security Filters for Web Servers

Frames MIME based responses. Supports HTTP 1.0 / 1.1 request – response paradigm. May support additional protocols such as HTTPS (HTTP over Secured Socket

Layer) Provide sand – box security environment for the servlets to run. Invokes servlets based on the client requests. Supplies request and response objects while invoking servlets.

Java servlet specifications

Sun Microsystems is the authority to issue servlet specifications. The latest spec. is Java servlet API v.2.4 fr, and is available at http://java.sun.com/products/servlet/. The spec. has been finalized and is issued by the Java Community Process (JCP) under the Java Specification Request (JSR-000154). To know more about the JCP program, please visit http://jcp.org/.

The Java servlet API v.2.4 fr is a required API of the Java 2 Platform, Enterprise Edition v.1.4. The J2EE 1.4 specification by itself can be obtained at http://java.sun.com/J2EE/. There are marked changes in this finalized reference (fr), compared to the previous versions viz. 2.0, 2.1, 2.2, and 2.3. Anyway, no comparison is made here across these versions. In fact, it is not necessary to learn the old API unless you’ve some interest in the evolution of the servlet technology.

Servlet containers are upgrading now to support this latest version of the API. A few of them are Apache’s Tomcat 5.0.18 and J2EE 1.4 Application Server from Sun. Generally, for working with servlets, Tomcat is a good beginning place. In the next section, let’s see configuring the Tomcat 5.0.18 to our preferences.

Configuring Tomcat 5.0.18

This is the industry standard container and also Sun’s reference implementation for its servlet 2.4 fr specification. This is also an open – source container and anyone can participate in its development. By the time you read this, there may be a more recent version of this container. We can obtain the more recent version of this container from the URL, http://jakarta.apache.org/tomcat/.

Dept of MCA, KSRMCE

Page 14: Security Filters Final

Security Filters for Web Servers

It’s available in the .exe form and double clicking it starts the installation of the container.

While attending the screens of installation, choose the full setup to optimally use the container.

Screen 1 Items available in Full install

The figure shows the items that are installed under full setup. The default install location is C:\Program Files\Apache Software Foundation\Tomcat 5.0, and go for it.

Dept of MCA, KSRMCE

Page 15: Security Filters Final

Security Filters for Web Servers

Screen 2 Preferences for Tomcat

In one of the screens during installation, choose, The HTTP / 1.1 Connector Port, User Name, and Password. All the three can be chosen on your wish. This requires a JDK of atleast 1.3.1 or above. Once the installation is completed, you must see the following page in the browser, with the URL http://localhost:8080/.

Screen 3 Tomcat 5.0.18 home page

This page is served via browser only if the server is started. The server can be started by choosing ‘Start Tomcat’ from the Start menu group. This is equivalent to running the command C:\Program Files\Apache Software Foundation\Tomcat 5.0\bin\tomcat.exe. Anyway, Tomcat installer offers the facility of starting it as a Windows service. This enables the server to start each time you start the OS.

Dept of MCA, KSRMCE

Page 16: Security Filters Final

Security Filters for Web Servers

In the web page shown in Screen. 3, observe the message at the beginning of the page. So, if you can view this page via your web browser then it’s confirmed that you’ve successfully configured Tomcat container.

Container can be administered by going through the link ‘Tomcat Administration’ in the menu that appears at the left. Servlets and JSPs are managed through the link ‘Tomcat Manager’. These two links are accessible only for the roles ‘admin’ and ‘manager’ respectively. These two roles must have been created at the time of installation of the server. Anyway, if you want to edit these roles, probably for changing the username or password or both, then open the file %CATALINA_HOME%\conf\tomcat-users.xml. The shell variable %CATALINA_HOME% is considered to be the place where the Tomcat is installed, which is C:\Program Files\Apache Software Foundation\Tomcat 5.0. The file tomcat-users.xml has the following snippet.

The highlighted line is what you have to change for changing the credentials. The one’s I’ve chosen have been shown here. You can observe that the same credentials are being used for both the roles ‘admin’ and ‘manager’. If you change the credentials, then the server has to be restarted to recognize the changes.

Similar to the roles configuration, the port at which the Tomcat listens, by default, can be changed by editing another file, %CATALINA_HOME%\conf\server.xml. This is a complete server configuration file. This file specifies different resources, realms, and clusters. Also, this file has different connector ports, for example, non-SSL HTTP / 1.1 at 8080, SSL HTTP / 1.1 at 8443, Proxied HTTP / 1.1 at 8082, and JK2 at 8009. The non-SSL port is what we use by default.

The SSL port may be used for secure connections. Proxied port may be used if you are running behind a proxy. The last one, JK2 port is used to attach the Tomcat container with the other web servers like Microsoft’s IIS (Internet Information Server 5 or above). All these ports, of course, may be changed at your wish. Again, the server needs a restart if you change any of the ports.

The non-SSL HTTP / 1.1 connector port is specified as follows.

<!-- Define a non-SSL Coyote HTTP/1.1 Connector on the port specified during installation -->

Dept of MCA, KSRMCE

Page 17: Security Filters Final

Security Filters for Web Servers

<Connector port="8080" maxThreads="150" minSpareThreads="25"

maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" />

<!-- Note : To disable connection timeouts, set connectionTimeout value

to -1 -->

These basic configuration issues now make you to take off to work with servlets and JSPs. All other advanced issues of the server are considered in detail, at a later time. Don’t forget to restart the server if you’ve made any changes to these files.

Web Applications

The purpose of this section is to introduce you the terminology associated with servlets and JSP in the current context of Java 2 Enterprise Edition 1.4. When you create either a servlet or a JSP, you are really creating a web application. The term ‘web application’ has been introduced in the servlets 2.2 specification for the first time.

A web application is a dynamic extension to the web server. It is a collection of servlets, JSPs, HTMLs, resource files like images, audio, and video files, utility classes or 3rd party JARs referred to as class libraries, and XML files describing different things, called descriptors. In different examples, we find different combinations of these components constituting a web application.

All the legal content of a web application may be categorized into two viz. presentation – oriented and service – oriented. For example, HTML, images, and other resources constitute parts of a presentation – oriented web application. Servlets and JSPs constitute parts of a service – oriented web application. A typical web application is a combination of both these. More often JSPs lean themselves on the presentation – oriented part of a web application. You understand this when we begin JSP.

Servlets and JSPs are also termed as web components.

Dept of MCA, KSRMCE

Page 18: Security Filters Final

Security Filters for Web Servers

Different components of a web application may be developed by different communities like, web designers or HTML programmers, Java programmers etc. Finally, all the components may be bundled into a single deployable unit, which is Web ARchive, referred to as WAR file with an extension of .war. WAR files may be built using the JAR utility available with any standard JDK.

While creating the single deployable unit, another important file that should be a part of the unit is deployment descriptor file. This file is usually written by the web app developer in XML. This file is read by the container on which you are deploying the web app and the container behaves accordingly.

Development of a web application may be described in the following simple steps.

Design and develop web components viz. servlets and JSPs. Design and develop presentation logic viz. HTML and resources. Write a single web application deployment descriptor, using XML. Create a hierarchical folder structure for placing the components developed so

far. Package the folder structure as – is into a single deployable unit (WAR). Deploy the unit on an appropriate container, like Tomcat. Access the service of the web application, to test, through URLs.

WARs may be deployed on a container like Tomcat, which is described in the last section. The container provides the services like, client request dispatching, security, threading model, and life cycle management. These services become evident as you look at the example web applications.

Structure of a Web Application

I made a mention about a hierarchical folder structure in the last section, which is discussed now, here.

A web application exists as a structured hierarchy of directories. The root of this hierarchy is referred to as document root or the context root. For example, I may create a root with the name ‘my-web-app’ at a location of my

Dept of MCA, KSRMCE

Page 19: Security Filters Final

Security Filters for Web Servers

interest. Once the root folder is created, all other components that constitute the web application may be structured into this root. Let’s assume the root is created in C:\my-web-app. In the following discussion this root directory is referred to as root for convenience.

Now, whatever is directly under the root is public area, I mean, visible directly to the client – side browser. And, create a private area under the root, which is not visible to the client directly, but visible to the container on the server – side.

The private area is root\WEB-INF folder, which is the place for servlet classes and other utility classes.

The location of different components constituting a web application is as described below.

HTML, Cascaded Style Sheets (CSS), Java Script files, any resource files like images, audio, and video files may be placed directly under the root or a sub directory thereof. All these documents are public in nature and they are directly visible to the client.

Even JSPs are placed under the public area of the root or any sub directory thereof.

Servlets are placed in the private area, root\WEB-INF\classes. This is also the place for any of the utility classes, like JSP bean classes. Anyway, compressed JARs are not allowed here. The classes available here may be loaded by the application class loader. If you organize the classes placed here in a package format, then the root package must be made available under the ‘classes’ directory.

For example, root\WEB-INF\classes\com\mycompany\purpose\MyClass.class is a class qualified as com.mycompany.purpose.MyClass.class.

JARs, third – party JARs, and JDBC drivers may be loaded in root\WEB-INF\lib.

Deployment descriptor is placed under root\WEB-INF\web.xml.

Dept of MCA, KSRMCE

Page 20: Security Filters Final

Security Filters for Web Servers

While resolving a class definition, the web application class loader should first check ‘classes’ and then ‘lib’ directories in that order. And, if a client requests for any resource in the private area of the document root, then the container should respond with a message SC_NOT_FOUND (404).

So, whatever you’ve under root\WEB-INF is for the web container directly or for other parts of your web application and not for the public, I mean, clients.

Packaging a Web Application

After designing and developing the individual components of a web application it’s a good idea to pack the entire web application into a deployable unit called as WAR file. Note that almost every web container including Tomcat accepts web application for deployment in an unpacked form. But servlets 2.2 or later specifications require containers to accept web apps in the packaged form, I mean WAR form. So, a container compatible with J2EE spec. must accept WAR packaged web app. And accepting an unpackaged web app. is up to the container. Also, there are certain benefits working with WARs than with unpackaged web apps, listed here.

Remote deployment of a web application is easy, because of the compression in WAR format.

Manageability of the web application will be under control. WAR format is universal amongst all J2EE compatible web containers.

Anyway, when you give a WAR packaged web application to a container, it unpacks the WAR and create the folder structure as – is in a sub directory under root\webapps (specific to Tomcat series, and other containers may have this unpacking at a different place). The name of the sub directory is chosen to be the name of the .war file you deploy on the server.

For example, a very simple web application (not really), which just consists of a HTML file, may be planned as shown. Let’s set the document root of the web application to be ‘simple-app’. The HTML document that I keep in this folder is index.html, listed here.

<H3> My First Web Application </H3>

Dept of MCA, KSRMCE

Page 21: Security Filters Final

Security Filters for Web Servers

The following is the folder hierarchy.

C:\|____simple-app |________index.html

To compress this structure into a .war file, use JAR utility from your JDK distribution.

C:\simple-app>jar -cvf simple-app.war .added manifestadding: index.html(in = 35) (out= 36)(deflated -2%)

Because, the HTML file has very little content, there is no real compression, which is confirmed by a compression ratio of -2%.

There are three options used with the jar command. The first is c, which specifies a new archive to be created. The second is v, which is a verbose option. The third is f, which specifies the first in the command list to be used as the name of the archive. After the name of the archive you may specify the individual component list to be added to the archive for compression. Here a ‘.’ Is used, which tells jar to include all the contents of the current directory (simple-app).

The result is the creation of the simple-app.war file in the current directory. This makes the stage set for the deployment of this unit on an appropriate web container. Here, the .war file name has been chosen to be same as the folder in which the web application contents are present. Anyway, it can be anything.

Deploying a Web Application

There are a couple of ways to deploy a web application on the Tomcat container. Note that the deployment may be done either with or without a .war file. Anyway, with the benefits discussed in the last section, it is always

Dept of MCA, KSRMCE

Page 22: Security Filters Final

Security Filters for Web Servers

preferred to deploy using WARs. Also, Sun’s J2EE spec. stresses on deploying a web application using compressed archives, I mean WARs.

Here is the list of ways to deploy a web application.

Tomcat Web Application Manager allows you to deploy, start, stop, and reload any web application. It may be accessed by the URL http://localhost:8080/manager/html. This manager application itself is a web application deployed by the container at the context path ‘/manager’. You can access this web application only when you assume the role of a manager. Refer to section 1.6 for a discussion on the roles. When you logged into, as a manager, by supplying proper credentials, the following screen appears.

Note that you must have started the Tomcat container to access this web application.

Screen 4 Tomcat Web Application Manager

Dept of MCA, KSRMCE

Page 23: Security Filters Final

Security Filters for Web Servers

The screen shows the list of all deployed web applications in the first column of the table, by their context paths or document roots. Observe the web application simple-app deployed by us at the context path /simple-app. The last column of the table specifies a list of command you may execute on the web applications. Also, observe that all the web applications have already been started, which is indicated by the disabled Start command. When a web application is started, you may access it as a client through a URL. Stop on a web application stops serving the client. Reload takes care of any changes in web application without restarting the server. Undeploy removes the uncompressed web application folder altogether.

The other columns of the table in Fig. 4 are discussed soon. Now, look at the following screen, which is used to deploy our web application graphically.

In the screen, Fig. 5, the deployment section is divided into two. The first is to deploy a web application (WAR or unpacked folder structure) located on the server itself. To be clear, Tomcat and the web application are on the same server machine and you are on a client machine deploying the web application.

Dept of MCA, KSRMCE

Page 24: Security Filters Final

Security Filters for Web Servers

Screen 5 Tomcat Deployment section

The second section is used when WAR (only WAR; no unpacked folder structure) is on your side, I mean client – side, and you are deploying it on the remote server on which Tomcat container is running.

For example, using first section of deployment, we can deploy our sample web application created in the last section, by setting the following.

Context Path (optional): /yourchoiceWAR or Directory URL: file:/c:/simple-app

After setting these two parameters, click the Deploy button. You find a message at the top of the screen, as shown below.

Dept of MCA, KSRMCE

Page 25: Security Filters Final

Security Filters for Web Servers

Screen 6 Message confirming successful deployment

This message confirms the successful deployment of the web application at the context path /yourchoice. Now, you can start accessing this application by pointing your browser to the URL; http://localhost:8080/yourchoice/index.html.

Screen 7 Running the web application

Now, let’s take a look at the second section used for deployment. Here a WAR is required and context path is not your choice. Set the following to deploy.

Select WAR file to upload: c:\simple-app\simple-app.war

We simply specified the absolute path of the WAR file and then click the Deploy button. You get a message as shown here.

Screen 8 Message confirming successful deployment

The message says that the web application has been deployed at the context path /simple-app, which is same as the .war file name. So, here in the second section the context path is decided by the Tomcat container based on the .war file name. Now, the access URL for this deployment is http://localhost:8080/simple-app/index.html. Hope this discussion has given you the idea.

Dept of MCA, KSRMCE

Page 26: Security Filters Final

Security Filters for Web Servers

The next way of deploying a web application is to copy a WAR file directly into a folder %CATALINA_HOME%\webapps. This folder is the right place for the document roots of the deployed web applications. I’ve already explained the creation of a WAR in the section 1.9. Now, place the created WAR in the web apps folder. After such copying, restart the container, which unpacks the WAR and creates the original folder structure, you’ve created.

So, the two methods of deploying a web application have been discussed here. Next, we proceed to creating more complicated web applications. This requires many items to be a part of the web application. We begin with the servlets part.

Servlet life cycle

Basics of the servlet have already been discussed. Now, in the coming sections we make servlets part of a web application and look at different aspects of a servlet. Anyway, just to refresh, a servlet is a piece of Java code managed by a container, like Tomcat. Section 1.4 discussed the tasks of a web container towards a servlet. One of the tasks is to manage the life cycle of a servlet.

javax.servlet.* is the API given by the Sun to develop and manage servlets. The Servlet interface from this package is the central abstraction of the entire API, which describes the phases of life of a servlet. If you plan to write a servlet, you have to define a class that implements javax.servlet.Servlet interface, either directly or indirectly.

Direct implementation of the interface is rarely accomplished as this forces you to provide implementation for all the methods (five, in number) of the Servlet interface, whether you require all of them or not. The following shows a template for direct implementation.

import javax.servlet.*;public class MyServlet implements Servlet{ // you may have a no – arg constructor // implement all the five methods of the Servlet interface}

Dept of MCA, KSRMCE

Page 27: Security Filters Final

Security Filters for Web Servers

Indirect implementation of the Servlet interface is the preferred way as you’re not forced to implement all the methods of the interface. This is accomplished by extending your class from either of the following classes.

javax.servlet.GenericServletjavax.servlet.http.HttpServlet

This works out because the first class implements Servlet interface directly and the second implements it indirectly by extending from the GenericServlet class. The following shows another way of defining your own servlets.

Once a servlet is defined in one of the discussed ways, you need to consider how it is executed by the container. The following is a typical sequence of a servlet being executed by the web container.

Client requests a servlet through an URL. Based on URL mapping rules (described soon) the container identifies the servlet being requested by the client. The .class file of the servlet is loaded by a Java class loader, just like any other class in Java.

After loading the class, the container instantiates the class. While instantiating, default constructor of the servlet class gets called. So, if you plan to have a constructor in a servlet class, ensure that it is a no – argument constructor, otherwise the container doesn’t know how to call it.

Next, the servlet gets initialized. This makes the servlet available to the clients for service. During this phase, container calls the following method specified by Servlet interface and implemented by your class.

public void init(ServletConfig config) throws ServletException

The servlet container calls the init exactly once after instantiating the servlet. The init must complet successfully before the servlet can receive any request.

The servlet container cannot place the servlet into service if the init method1) Throws a ServletException

Dept of MCA, KSRMCE

Page 28: Security Filters Final

Security Filters for Web Servers

2) Does not return within a time period specified by the container

The argument to init is used to pass any information to the initializing servlet via javax.servlet.ServletConfig object. This is explained soon.

After initialization, the servlet is ready to accept requests of the client. Another task of a web container (see section 1.4) is to understand MIME encoded requests from the client and frame MIME based responses to the client. These two are handed over to a servlet by the container by calling the service method specified by Servlet interface and implemented by your class.

public void service(ServletRequest req, ServletResponse res)

throws ServletException, java.io.IOException

The two arguments to the service method are javax.servlet.ServletRequest and javax.servlet.ServletResponse type of objects. These two are interfaces, which are explained soon. For now, just remember that the first denotes the client request and the second encapsulates the response to be given to the client.

As the name of this method suggests, it is a place for coding the services you’d like your servlet to deliver to the accessing clients.

The last phase in the life cycle of a servlet is to destroy the servlet. This happens only when the service method of a servlet is not being accessed by any client currently or after a timeout period has passed. When on of this happens, the container calls the following method.

public void destroy()

Once the container calls this method, it will not call the service method again on this particular instance of the servlet.

This method gives the servlet an opportunity to clean up any resources that are being held, for example, memory, file handles, and threads etc.

Dept of MCA, KSRMCE

Page 29: Security Filters Final

Security Filters for Web Servers

That completes the life cycle of a servlet. If a client requests for the same servlet again, the whole cycle repeats for that servlet on a new instance.

While concluding this section, remember that the init method of a servlet is used for any one – time activities, like opening streams to the files, opening connections to the database, or to read initial configuration data passed onto the init method via ServletConfig object etc.

Another method, service is used to deliver the real service to the clients accessing the servlet. ServletRequest and ServletResponse objects are passed to this method. This method may be called any number of times by the container, which depends on the number of clients visiting the servlet.

The last method destroy allows any clean – up to be performed. Releasing file streams and closing database connections etc.

System Analysis – RSA Algorithm

RSA is a public-key cryptosystem developed by MIT professors: Ronald L. Rivest, Adi Shamir, and Leonard M. Adleman in 1977 in an effort to help ensure internet security. As Steve Burnett of RSA Data Security, Inc. described it, a cryptosystem is simply an algorithm that can convert input data into something unrecognizable (encryption), and convert the unrecognizable data back to its original form (decryption).

To encrypt data, enter the data ("plaintext") and an encryption key to the encryption portion of the algorithm. To decrypt the "ciphertext," a proper decryption key is used at the decryption portion of the algorithm. Those keys, which contains simply a string of numbers, are called public key and private key, respectively. For example, suppose Alice intends to send e-mail to Bob. Through a public-key directory, she finds his public key. Then, she encrypts her message using the key and send it to Bob. This public key, however, will not decrypt the ciphertext. Knowledge of Bob's public key will not help an eavesdropper. In order for Bob to decrypt his ciphertext, he must use his private key. If Bob wants to respond to Alice, he encrypts his message using her public key.

The challenge of public-key cryptography is developing a system in which it is impossible to determine the private key. This is accomplished

Dept of MCA, KSRMCE

Page 30: Security Filters Final

Security Filters for Web Servers

through the use of a one-way function. With a one-way function, it is relatively easy to compute a result given some input values. However, it is extremely difficult, nearly impossible, to determine the original values if you start with the result. In mathematical terms, given x, computing f(x) is easy, but given f(x), computing x is nearly impossible. The one-way function used in RSA is multiplication of prime numbers. It is easy to multiply two big prime numbers, but for most very large primes, it is exremely time-consuming to factor them. Public-key cryptography uses this function by building a cryptosystem which uses two large primes to build the private key and the product of those primes to build the public key.

Servlet filters are powerful tools that are available to J2EE application developers using the Servlet 2.3 specification or above. Filters are designed to be able to manipulate a request or response (or both) that is sent to a J2EE application, yet provide this functionality in a method that won't affect servlets and JSPs being used by the J2EE application unless that is the desired effect. A good way to think of servlet filters is as a chain of steps that a request and response must go through before reaching a servlet, JSP, or static resource such as an HTML page in a J2EE application. Figure 4a shows the commonly used illustration of this concept.

Dept of MCA, KSRMCE

Page 31: Security Filters Final

Security Filters for Web Servers

Fig 4a The servlet filter concept

The large gray box is a J2EE application that has some endpoints, such as JSP, and some filters applied to intercept all requests and responses. The filters are shown in a stack, three high, that each request and response must pass through before reaching an endpoint. At each filter, custom Java code would have a chance to manipulate the request or response, or anything that has to do with either of those objects.

Understand that a user's request for a J2EE application resource can be forced to go through any number of filters, in a given order, and any of the filters may manipulate the request, including stopping it altogether, and respond in a variety of different ways. This is important to understand because later in this article, two filters will be presented that manipulate the HttpServletRequest and HttpServletResponse objects to provide some very convenient functionality. Don't worry if you don't know anything about coding a filter -- it would certainly help if you understood the code, but in the end of the article, all of the code is provided in a JAR that can easily be used without knowing a thing about how it was made.

Dept of MCA, KSRMCE

Page 32: Security Filters Final

Security Filters for Web Servers

Encrypting Content Using a Servlet Filter

Here's the relatively easy to understand math behind RSA public key encryption.

1. Find P and Q, two large (e.g., 1024-bit) prime numbers. 2. Choose E such that E is greater than 1, E is less than PQ, and E and (P-1)(Q-

1) are relatively prime, which means they have no prime factors in common. E does not have to be prime, but it must be odd. (P-1)(Q-1) can't be prime because it's an even number.

3. Compute D such that (DE - 1) is evenly divisible by (P-1)(Q-1). Mathematicians write this as DE = 1 (mod (P-1)(Q-1)), and they call D the multiplicative inverse of E. This is easy to do -- simply find an integer X which causes D = (X(P-1)(Q-1) + 1)/E to be an integer, then use that value of D.

4. The encryption function is C = (T^E) mod PQ, where C is the ciphertext (a positive integer), T is the plaintext (a positive integer), and ^ indicates exponentiation. The message being encrypted, T, must be less than the modulus, PQ.

5. The decryption function is T = (C^D) mod PQ, where C is the ciphertext (a positive integer), T is the plaintext (a positive integer), and ^ indicates exponentiation.

Your public key is the pair (PQ, E). Your private key is the number D (reveal it to no one). The product PQ is the modulus (often called N in the literature). E is the public exponent. D is the secret exponent.

You can publish your public key freely, because there are no known easy methods of calculating D, P, or Q given only (PQ, E) (your public key). If P and Q are each 1024 bits long, the sun will burn out before the most powerful computers presently in existence can factor your modulus into P and Q.

Cryptography

As the field of cryptography has advanced, the dividing lines for what is and what is not cryptography have become blurred. Cryptography today might be summed up as the study of techniques and applications that depend on the

Dept of MCA, KSRMCE

Page 33: Security Filters Final

Security Filters for Web Servers

existence of difficult problems. Cryptanalysis is the study of how to compromise (defeat) cryptographic mechanisms, and cryptology (from the Greek kryptos logos, meaning ``hidden word'') is the discipline of cryptography and cryptanalysis combined. To most people, cryptography is concerned with keeping communications private. Indeed, the protection of sensitive communications has been the emphasis of cryptography throughout much of its history.However, this is only one part of today's cryptography. Encryption is the transformation of data into a form that is as close to impossible as possible to read without the appropriate knowledge (a key; see below). Its purpose is to ensure privacy by keeping information hidden from anyone for whom it is not intended, even those who have access to the encrypted data. Decryption is the reverse of encryption; it is the transformation of encrypted data back into an intelligible form. Encryption and decryption generally require the use of some secret information, referred to as a key.For some encryption mechanisms, the same key is used for both encryption and decryption; for other mechanisms, the keys used for encryption and decryption are different. Today's cryptography is more than encryption and decryption. Authentication is as fundamentally a part of our lives as privacy. We use authentication throughout our everyday lives -- when we sign our name to some document for instance -- and, as we move to a world where our decisions and agreements are communicated electronically, we need to have electronic techniques for providing authentication.

Popular techniques of Cryptography

There are two types of cryptosystems: secret-key and public-key cryptography and. In secret-key cryptography, also referred to as symmetric cryptography, the same key is used for both encryption and decryption. The most popular secret-key cryptosystem in use today is the Data Encryption Standard In public-key cryptography, each user has a public key and a private key. The public key is made public while the private key remains secret. Encryption is performed with the public key while decryption is done with the private key. The RSA public-key cryptosystem is the most popular form of public-key cryptography. RSA stands for Rivest, Shamir, and Adleman, the inventors of the RSA cryptosystem.

Dept of MCA, KSRMCE

Page 34: Security Filters Final

Security Filters for Web Servers

The Digital Signature Algorithm is also a popular public-key technique, though it can only be used only for signatures, not encryption. Elliptic curve cryptosystems are cryptosystems based on mathematical objects known as elliptic curves.

Elliptic curve cryptography has been gaining in popularity recently. Lastly, the Diffie-Hellman key agreement protocol is a popular public-key technique for establishing secret keys over an insecure channel.

How is Cryptography Applied?

Cryptography is extremely useful; there is a multitude of applications, many of which are currently in use. A typical application of cryptography is a system built out of the basic techniques. Such systems can be of various levels of complexity. Some of the more simple applications are secure communication, identification, authentication, and secret sharing. More complicated applications include systems for electronic commerce, certification, secure electronic mail, key recovery, and secure computer access.

In general, the less complex the application, the more quickly it becomes a reality. Identification and authentication schemes exist widely, while electronic commerce systems are just beginning to be established. However, there are exceptions to this rule; namely, the adoption rate may depend on the level of demand. For example, SSL-encapsulated HTTP gained a lot more usage much more quickly than simpler link-layer encryption has ever achieved. The adoption rate may depend on the level of demand.

Secure Communication

Secure communication is the most straightforward use of cryptography. Two people may communicate securely by encrypting the messages sent between them. This can be done in such a way that a third party eavesdropping may never be able to decipher the messages. While secure communication has existed for centuries, the key management problem has prevented it from becoming commonplace. Thanks to the development of public-key cryptography, the tools exist to create a large-scale network of people who can communicate securely with one another even if they had never communicated before.

Identification and Authentication

Dept of MCA, KSRMCE

Page 35: Security Filters Final

Security Filters for Web Servers

Identification and authentication are two widely used applications of cryptography. Identification is the process of verifying someone's or something's identity. For example, when withdrawing money from a bank, a teller asks to see identification (for example, a driver's license) to verify the identity of the owner of the account. This same process can be done electronically using cryptography. Every automatic teller machine (ATM) card is associated with a ``secret'' personal identification number (PIN), which binds the owner to the card and thus to the account. When the card is inserted into the ATM, the machine prompts the cardholder for the PIN. If the correct PIN is entered, the machine identifies that person as the rightful owner and grants access. Another important application of cryptography is authentication. Authentication is similar to identification, in that both allow an entity access to resources (such as an Internet account), but authentication is broader because it does not necessarily involve identifying a person or entity. Authentication merely determines whether that person or entity is authorized for whatever is in question.

Secret Sharing

Another application of cryptography, called secret sharing, allows the trust of a secret to be distributed among a group of people. For example, in a (k; n)-threshold scheme, information about a secret is distributed in such a way that any k out of the n people (k _ n) have enough information to determine the secret, but any set of k _1 people do not. In any secret sharing scheme, there are designated sets of people whose cumulative information suffices to determine the secret. In some implementations of secret sharing schemes, each participant receives the secret after it has been generated. Implementations, the actual secret is never made visible to the participants, although the purpose for which they sought the secret (for example, access to a building or permission to execute a process) is allowed.

Electronic Commerce

Over the past few years there has been a growing amount of business conducted over the Internet -- this form of business is called electronic commerce or e-commerce. E-commerce is comprised of online banking, online brokerage accounts, and Internet shopping, to name a few of the many applications. One can book plane tickets, make hotel reservations, rent a car, transfer money from one account to another, buy compact disks (CDs), clothes, books and so on all while sitting in front of a computer. However, simply entering a credit card number on the Internet leaves one open to fraud. One cryptographic

Dept of MCA, KSRMCE

Page 36: Security Filters Final

Security Filters for Web Servers

solution to this problem is to encrypt the credit card number (or other private information) when it is entered online, another is to secure the entire session. When a computer encrypts this information and sends it out on the Internet, it is incomprehensible to a third party viewer. The web server (``Internet shopping center'') receives the encrypted information, decrypts it, and proceeds with the sale without fear that the credit card number (or other personal information) slipped into the wrong hands. As more and more business is conducted over the Internet, the need for protection against fraud, theft, and corruption of vital information increases.

Certification

Another application of cryptography is certification; certification is a scheme by which trusted agents such as certifying authorities vouch for unknown agents, such as users. The trusted agents issue vouchers called certificates which each have some inherent meaning. Certification technology was developed to make identification and authentication possible on a large scale.

Key Recovery

Key recovery is a technology that allows a key to be revealed under certain circumstances without the owner of the key revealing it. This is useful for two main reasons: first of all, if a user loses or accidentally deletes his or her key, key recovery could prevent a disaster. Secondly, if a law enforcement agency wishes to eavesdrop on a suspected criminal without the suspect's knowledge (akin to a wiretap), the agency must be able to recover the key. Key recovery techniques are in use in some instances; however, the use of key recovery as a law enforcement technique is somewhat controversial.

Remote Access

Secure remote access is another important application of cryptography. The basic system of passwords certainly gives a level of security for secure access, but it may not be enough in some cases. For instance, passwords can be eavesdropped, forgotten, stolen, or guessed. Many products supply cryptographic methods for remote access with a higher degree of security.

Other Applications

Dept of MCA, KSRMCE

Page 37: Security Filters Final

Security Filters for Web Servers

Cryptography is not confined to the world of computers. Cryptography is also used in cellular (mobile) phones as a means of authentication; that is, it can be used to verify that a particular phone has the right to bill to a particular phone number. This prevents people from stealing (``cloning'') cellular phone numbers and access codes. Another application is to protect phone calls from eavesdropping using voice encryption.

Cryptography Standards

Cryptography standards are needed to create interoperability in the information security world. Essentially they are conditions and protocols set forth to allow uniformity within communication, transactions and virtually all computer activity. The continual evolution of information technology motivates the development of more standards, which in turn helps guide this evolution. The main motivation behind standards is to allow technology from different manufacturers to ``speak the same language'', that is, to interact effectively. Perhaps this is best seen in the familiar standard VHS for video cassette recorders (VCRs). A few years ago there were two competing standards in the VCR industry, VHS and BETA. A VHS tape could not be played in a BETA machine and vice versa; they were incompatible formats. Imagine the chaos if all VCR manufacturers had different formats. People could only rent movies that were available on the format compatible with their VCR.

Standards are necessary to insure that products from different companies are compatible.

In cryptography standardization serves an additional purpose; it can serve as a proving ground for cryptographic techniques because complex protocols are prone to design flaws. By establishing a well-examined standard, the industry can produce a more trustworthy product. Even a safe protocol is more trusted by customers after it becomes a standard, because of the ratification process involved.

The government, private industry, and other organizations contribute to the vast collection of standards on cryptography. A few of these are ISO, ANSI, IEEE, NIST, and IETF.

Dept of MCA, KSRMCE

Page 38: Security Filters Final

Security Filters for Web Servers

There are many types of standards, some used within the banking industry, some internationally and others within the government. Standardization helps developers design new products. Instead of spending time developing a new standard, they can follow a pre-existing standard throughout the development process. With this process in place consumers have the chance to choose among competing products or services.

Importance of Cryptography

Cryptography allows people to carry over the confidence found in the physical world to the electronic world, thus allowing people to do business electronically without worries of deceit and deception. Every day hundreds of thousands of people interact electronically, whether it is through e-mail, e-commerce (business conducted over the Internet), ATM machines, or cellular phones. The perpetual increase of information transmitted electronically has lead to an increased reliance on cryptography.

Cryptography on the Internet

The Internet, comprised of millions of interconnected computers, allows nearly instantaneous communication and transfer of information, around the world. People use e-mail to correspond with one another. The World Wide Web is used for online business, data distribution, marketing, research, learning, and a myriad of other activities.

Cryptography makes secure web sites and electronic safe transmissions possible.

For a web site to be secure all of the data transmitted between the computers where the data is kept and where it is received must be encrypted. This allows people to do online banking, online trading, and make online purchases with their credit cards, without worrying that any of their account information is being compromised. Cryptography is very important to the continued growth of the Internet and electronic commerce.

E-commerce is increasing at a very rapid rate. By the turn of the century, commercial transactions on the Internet are expected to total hundreds of billions of dollars a year. This level of activity could not be supported without cryptographic security. It has been said that one is safer using a credit card over the Internet than within a store or restaurant. It requires much more work to seize credit card numbers over computer networks than it does to simply walk by a table

Dept of MCA, KSRMCE

Page 39: Security Filters Final

Security Filters for Web Servers

in a restaurant and lay hold of a credit card receipt. These levels of security, though not yet widely used, give the means to strengthen the foundation with which e-commerce can grow.

People use e-mail to conduct personal and business matters on a daily basis. E-mail has no physical form and may exist electronically in more than one place at a time. This poses a potential problem as it increases the opportunity for an eavesdropper to get a hold of the transmission. Encryption protects e-mail by rendering it very difficult to read by any unintended party. Digital signatures can also be used to authenticate the origin and the content of an e-mail message.

Authentication

In some cases cryptography allows you to have more confidence in your electronic transactions than you do in real life transactions. For example, signing documents in real life still leaves one vulnerable to the following scenario. After signing your will, agreeing to what is put forth in the document, someone can change that document and your signature is still attached. In the electronic world this type of falsification is much more difficult because digital signatures are built using the contents of the document being signed.

Access Control

Cryptography is also used to regulate access to satellite and cable TV. Cable TV is set up so people can watch only the channels they pay for. Since there is a direct line from the cable company to each individual subscriber's home, the Cable Company will only send those channels that are paid for. Many companies offer pay-per-view channels to their subscribers. Pay-per-view cable allows cable subscribers to ``rent'' a movie directly through the cable box. What the cable box does is decode the incoming movie, but not until the movie has been ``rented.'' If a person wants to watch a pay-per-view movie, he/she calls the cable company and requests it. In return, the Cable Company sends out a signal to the subscriber's cable box, which unscrambles (decrypts) the requested movie.

Satellite TV works slightly differently since the satellite TV companies do not have a direct connection to each individual subscriber's home. This means that anyone with a satellite dish can pick up the signals. To alleviate the problem of people getting free TV, they use cryptography. The trick is to allow only those who have paid for their service to unscramble the transmission; this is done with receivers (``unscramblers''). Each subscriber is given a receiver; the satellite

Dept of MCA, KSRMCE

Page 40: Security Filters Final

Security Filters for Web Servers

transmits signals that can only be unscrambled by such a receiver (ideally). Pay-per-view works in essentially the same way as it does for regular cable TV. As seen, cryptography is widely used. Not only is it used over the Internet, but also it is used in phones, televisions, and a variety of other common household items. Without cryptography, hackers could get into our e-mail, listen in on our phone conversations, tap into our cable companies and acquire free cable service, or break into our bank/brokerage accounts.

Public Key Cryptography

In traditional cryptography, the sender and receiver of a message know and use the same secret key; the sender uses the secret key to encrypt the message, and the receiver uses the same secret key to decrypt the message. This method is known as secret key or symmetric cryptography. The main challenge is getting the sender and receiver to agree on the secret key without anyone else finding out. If they are in separate physical locations, they must trust a courier, a phone system, or some other transmission medium to prevent the disclosure of the secret key.

Anyone who overhears or intercepts the key in transit can later read, modify, and forge all messages encrypted or authenticated using that key. The generation, transmission and storage of keys is called key management; all cryptosystems must deal with key management issues. Because all keys in a secret-key cryptosystem must remain secret, secret-key cryptography often has difficulty providing secure key management, especially in open systems with a large number of users.

In order to solve the key management problem, Whitfield Diffie and Martin Hellman introduced the concept of public-key cryptography in 1976. Public-key cryptosystems have two primary uses, encryption and digital signatures. In their system, each person gets a pair of keys, one called the public key and the other called the private key. The public key is published, while the private key is kept secret. The need for the sender and receiver to share secret information is eliminated; all communications involve only public keys, and no private key is ever transmitted or shared. In this system, it is no longer necessary to trust the security of some means of communications. The only requirement is that public keys be associated with their users in a trusted (authenticated) manner (for instance, in a trusted directory). Anyone can send a confidential message by just using public information, but the message can only be decrypted with a private key, which is in the sole possession of the intended recipient. Furthermore, public-key cryptography can be used not only for privacy (encryption), but also for authentication (digital signatures) and other various techniques.

Dept of MCA, KSRMCE

Page 41: Security Filters Final

Security Filters for Web Servers

In a public-key cryptosystem, the private key is always linked mathematically to the public key. Therefore, it is always possible to attack a public-key system by deriving the private key from the public key. Typically, the defense against this is to make the problem of deriving the private key from the public key as difficult as possible. For instance, some public-key cryptosystems are designed such that deriving the private key from the public key requires the attacker to factor a large number, it this case it is computationally infeasible to perform the derivation. This is the idea behind the RSA public-key cryptosystem.

Encryption

When Alice wishes to send a secret message to Bob, she looks up Bob's public key in a directory, uses it to encrypt the message and sends it off. Bob then uses his private key to decrypt the message and read it. No one listening in can decrypt the message. Anyone can send an encrypted message to Bob, but only Bob can read it (because only Bob knows Bob's private key).

Digital Signatures

To sign a message, Alice does a computation involving both her private key and the message itself. The output is called a digital signature and is attached to the message. To verify the signature, Bob does a computation involving the message, the purported signature, and Alice's public key. If the result is correct according to a simple, prescribed mathematical relation, the signature is verified to be genuine; otherwise, the signature is fraudulent, or the message may have been altered.

Secret Key Cryptography

Secret-key cryptography is sometimes referred to as symmetric cryptography. It is the more traditional form of cryptography, in which a single key can be used to encrypt and decrypt a message. Secret-key cryptography not only deals with encryption, but it also deals with authentication. One such technique is called message authentication codes.

The main problem with secret-key cryptosystems is getting the sender and receiver to agree on the secret key without anyone else finding out. This requires a method by which the two parties can communicate without fear of eavesdropping. However, the advantage of secret-key cryptography is that it is generally faster than public-key cryptography.

Dept of MCA, KSRMCE

Page 42: Security Filters Final

Security Filters for Web Servers

Comparison of Public Vs Secret

The primary advantage of public-key cryptography is increased security and convenience: private keys never need to be transmitted or revealed to anyone. In a secret-key system, by contrast, the secret keys must be transmitted (either manually or through a communication channel) since the same key is used for encryption and decryption. A serious concern is that there may be a chance that an enemy can discover the secret key during transmission. Another major advantage of public-key systems is that they can provide digital signatures that cannot be repudiated. Authentication via secret-key systems requires the sharing of some secret and sometimes requires trust of a third party as well. As a result, a sender can repudiate a previously authenticated message by claiming the shared secret was somehow compromised by one of the parties sharing the secret. For example, the Kerberos secret-key authentication system involves a central database that keeps copies of the secret keys of all users; an attack on the database would allow widespread forgery. Public-key authentication, on the other hand, prevents this type of repudiation; each user has sole responsibility for protecting his or her private key. This property of public-key authentication is often called non-repudiation.

A disadvantage of using public-key cryptography for encryption is speed. There are many secret-key encryption methods that are significantly faster than any currently available public-key encryption method. Nevertheless, public-key cryptography can be used with secret-key cryptography to get the best of both worlds. For encryption, the best solution is to combine public- and secret-key systems in order to get both the security advantages of public-key systems and the speed advantages of secret-key systems. Such a protocol is called a digital envelope.

Public-key cryptography may be vulnerable to impersonation, even if users' private keys are not available. A successful attack on a certification authority (see Question 4.1.3.14) will allow an adversary to impersonate whomever he or she chooses by using a public-key certificate from the compromised authority to bind a key of the adversary's choice to the name of another user. In some situations, public-key cryptography is not necessary and secret-key cryptography alone is sufficient. These include environments where secure secret key distribution can take place, for example, by users meeting in private. It also includes environments where a single authority knows and manages all the keys, for example, a closed banking system. Since the authority knows everyone's keys already, there is not much advantage for some to be ``public'' and others to be ``private.'' Note, however, that such a system may become impractical if the number of users Dept of MCA, KSRMCE

Page 43: Security Filters Final

Security Filters for Web Servers

becomes large; there are not necessarily any such limitations in a public-key system.

Public-key cryptography is usually not necessary in a single-user environment. For example, if you want to keep your personal files encrypted, you can do so with any secret key encryption algorithm using, say, your personal password as the secret key. In general, public-key cryptography is best suited for an open multi-user environment.

Public-key cryptography is not meant to replace secret-key cryptography, but rather to supplement it, to make it more secure. The first use of public-key techniques was for secure key establishment in a secret-key system ; this is still one of its primary functions. Secret-key cryptography remains extremely important and is the subject of much ongoing study and research. Some secret-key cryptosystems are discussed in the sections on block ciphers and stream ciphers.

In other compression to a decent-sized J2EE page often results in saving several seconds of time.

Now, the theory is nice, but the practice is nicer. This theoretical compression isn't something you have to labor over each time you go to code a servlet, JSP, or any other part of a J2EE application. You can obtain very effective compression by having a servlet filter conditionally pipe whatever your J2EE application produces to a GZIP-compressed file. Why GZIP? Because the HTTP protocol, the protocol used to transmit J2EE pages, allows for GZIP compression. Why conditionally? Because not every browser supports GZIP compression, but almost every single modern J2EE browser does. If you blindly send GZIP-compressed content to an old browser, the user might get nothing but gibberish. Since checking for GZIP compression support is nearly trivial, it is no problem to have a filter send GZIP-compressed content to only those users that can handle it.

I'm saying this GZIP compression stuff is good. But how good? GZIP compression will usually get you around a 6:1 compression ratio; it depends on how much content you are sending and what the content is. In practice, this means you will send content to a user up to six times faster if you simply use GZIP compression whenever you can. The only trick is that you need to be able to convert normal content in to GZIP-compressed content. Thankfully, the standard Java API provides code for doing exactly this: the java.util.zip package. The task is as easy as sending output sent in a J2EE application's response

Dept of MCA, KSRMCE

Page 44: Security Filters Final

Security Filters for Web Servers

conditionally through the java.util.zip.GZIPOutputStream class. Here is some code for doing exactly that.

As with most every filter, three classes are needed to do the job. A customized implementation of the javax.servlet.Filter interface, a customized implementation of the javax.servlet.ServletOutputStream class, and a customized implementation of the javax.servlet.http.HttpServletResponse class. Full source code for these three classes is provided at the end of the article; for now I will focus only on the relevant code. First, a check needs to be made if a user has support for GZIP-compressed content. This check is best done in the implementation of the Filter class.

Information about GZIP support is conveyed using the accept-encoding HTTP header. This header can be accessed using the HttpServletRequest object's getHeader() method. The conditional part of the code need be nothing more than an if statement that either sends the response as is or sends the response off to be GZIP compressed.

The next important part of the GZIP filter code is compressing normal content with GZIP compression. This code occurs after the above filter has found that the user does know how to handle GZIP-compressed content, and the code is best placed in a customized version of the ServletOutputStream class. Normally, the ServletOutputStream class handles sending text or non-text content to a user while ensuing appropriate character encoding is used. However, we want to have the ServletOutputStream class send content though a GZIPOutputStream before sending it to a client. This can be accomplished by overriding the write() methods of the ServletOutputStream class to GZIP content before sending it off in an HTTP response.

There are also a few loose ends to tie up, such as setting the content's encoding to be the MIME type for GZIP, and ensuring the subclass of ServletOutputStream has implementations of the flush() and close() methods that work with the changes to the write() methods. However, all of these changes are minor, and you may see code that does them by looking at the source code provided at the end of this article. The most important point to understand is that the filter has altered the response to ensure that all content is GZIP compressed.

Dept of MCA, KSRMCE

Page 45: Security Filters Final

Security Filters for Web Servers

Unfortunately, there is really no good way you can tell if content displayed by your browser was GZIP compressed or not. Part of the process working is that it is unnoticeable if the content was compressed or not. In order to test out the compression, we need to spoof some HTTP requests and see what exactly is returned.

This can be done relatively easily by tossing some code in a JSP; here is such a JSP.

Save the above JSP in the same J2EE application, and browse to the page. You will see an HTML form that requests a URL.

The JSP works by taking a URL and spoofing two HTTP requests to that URL. One request spoofs an HTTP request that doesn't accept GZIP content. The other request spoofs an HTTP request that does accept GZIP-compressed content. Compression is quantified by counting the number of bytes each request returned. If the given URL (i.e., J2EE app) provides support for GZIP compression, the second request should be smaller. Try out the JSP by filling in the form; any URL will do, but something you know has GZIP support is ideal

The compression saved just over 60%. That means the compressed content was sent roughly 60% faster to my J2EE browser, allowing it to start rendering the page 60% sooner. The end result is that a user would probably see this page about twice as fast as a non-GZIP-compressed page. However, the benefit is not only on the user's end. The J2EE application sending this page is sitting on a server(s) and that server(s) only has so much bandwidth to work with. Reducing the number of bytes you need to transmit per page also means you can have one server sending out more pages using the same amount of bandwidth. The tradeoff is processing power (running the compression algorithm) versus the number of bytes you need to send to a user. In almost every case, your server will have a far faster processor than a network card, and it is well worth always trying to compress content -- especially if you also cache compressed content (we'll see how to do this a little later).

Compression Filtering Tips

You should almost always try to compress content. Compression is good for the bandwidth of both the end user and your server. However, like most things, it pays to not blindly compress everything your J2EE application produces. Compression

Dept of MCA, KSRMCE

Page 46: Security Filters Final

Security Filters for Web Servers

works by eliminating redundancies in content. Text content (basically anything a JSP produces) can usually be compressed quite well, but already compressed content (e.g., a JPG image) or randomized content (e.g., anything encrypted) cannot be so easily compressed. In the latter case of already compressed or randomized content, it often does not pay to attempt to apply something such as a GZIP filter. You will spend a noticeable amount of processing power to achieve an unnoticeable amount of compression. For general use, only apply a compression filter to any resources in the J2EE application that are text-producing, namely all JSP and HTML pages.

Not bad at all! Especially considering you can add the given compression filter to just about any J2EE application you have ever made and you will reap the rewards of compression instantly. Note: the given code is completely free for use both commercially and non-commercially, Another point to always remember about compression filters, especially GZIP, is that not all J2EE browsers are able to understand the format. Be sure to always explicitly check, as the above code did, before sending back compressed content. While this may seem intuitive, it is really easy to forget this point when working with more than one filter. For example, next, a cache filter is introduced that keeps a copy of a response so that it can be reused for other users that later request the same resource. If you were to place the cache filter before the compression filter, then you might cache a GZIP-compressed response. Next time someone requested the same resource. the cached copy would be returned by the cache filter -- without performing a check to see if the user supports GZIP compression. Trouble would ensue if the cache filter ended up returning GZIP-compressed content to a browser that didn't understand the GZIP format.

The take-home message is that a GZIP compression filter (or any compression filter, for that matter) is a powerful tool that is easy to use and that you should almost always use. By compressing content, you can optimize the amount of bytes that need be sent across the World Wide J2EE, resulting in benefits for both your server and the user.

Caching Content Using a Servlet Filter

The second filter addresses is a cache filter. Caching is helpful because it saves time and processing power. The basic idea is that it takes time for a J2EE application to generate content, and in many situations, the content won't change between different requests to a particular servlet or JSP. Therefore, if you simply save the exact output (e.g., HTML) that is produced for a given URI, you can

Dept of MCA, KSRMCE

Page 47: Security Filters Final

Security Filters for Web Servers

recycle this content several times before having the J2EE application generate it again. Assuming your cache is faster then the J2EE application -- it almost always is -- the end result is that you save a large amount of the time and processing power required to generate a dynamic response. Currently, there is no official standard for caching J2EE application content. However, building a simple, generic caching system is a straightforward process.

In general, caching at the filter level is most helpful, as it allows you to save the entire response any particular JSP or servlet generates. However, it is worth considering that you can certainly try to cache elsewhere; for instance, using a set of custom tags that auto-cache any content placed between them, or using a custom Java class to cache information retrieved from a database. Caching possibilities are endless, but for practical purposes we shall focus on implementing caching at the filter level.

Before seeing some code, let's make sure what I mean by "caching at the filter level" is clear. "Caching at the filter level" simply means using a standard servlet filter that will intercept all requests to a J2EE application and attempt to intelligently use the cache. Should a valid cached copy of content exist in a cache, the filter will immediately respond to the request by sending a copy of the cache. However, if no cache exists, the filter will pass the request on to its intended endpoint, usually a servlet or JSP, and the response will be generated as it normally is. Once a response is successfully generated, it will also be cached, so that on future requests to the same resource, the cache may be used.

Understand that as this filter is intended to be used on an entire J2EE application, it can cache all of the various responses from different servlets and JSPs. Think about how this is possible: each servlet or JSP will likely produce a different response. The filter will need to be able to distinguish between different responses, store the appropriate content somewhere, and correctly match a cached copy of the content to an incoming request. Doing all of this is no problem at all -- different requests can almost always be distinguished by the requested URI, and the same information can be used to identify cached resources. Cached content can be stored either in memory, on the hard disk, or via any other method your server allows for -- usually, the hard disk is a great solution. With all of that said, here is the code for a filter that caches content in the J2EE application's temporary directory. The full code is given below, and important parts of the code are highlighted after the listing.

Dept of MCA, KSRMCE

Page 48: Security Filters Final

Security Filters for Web Servers

The next thing I'd like to draw attention to is how the servlet identifies caches and saves them to the local hard disk. As mentioned before the code, the filter uses the request URI and any parameters in the query string to generate a unique name for the cache.

String id = request.getRequestURI()+request.getQueryString();

Once the filter has this unique name, it uses the name to check if the resource exists in the J2EE application's cache. If it does, the cached copy is sent and the filter does not pass the request and response down the filter chain. If no cache exists, the filter passes the request and response down the filter chain so that the desired JSP or servlet can generate a response. Once the response is made, the cache filter sends it to the client and makes a copy of the response in the J2EE application's cache.

And that is a basic cache filter. Two support classes are needed -- CacheResponseStream and CacheResponseWrapper -- but they are nothing more than implementations of the ServletOutputStream class and HttpServletResponseWrapper class that are appropriate for CacheFilter.java. The full source code for everything is given at the end of this article, but to keep things moving along, I'll have you use a JAR file that includes the compiled cache filter. If you didn't already for the compression filter, grab the code and put it in the J2EE-INF/lib directory of your favorite J2EE application and deploy the filter to intercept all requests going to resources ending in .jsp, and reload the J2EE application for the changes to take effect. Next we will make a simple JSP to test the code.

Here is the complete code for a simple JSP that tests the cache filter. The JSP wastes time and processing power by executing several loops. Save the following as TimeMonger.jsp somewhere in your J2EE application.

Browse to TimeMonger.jsp for the ever-so-sophisticated cache test. Notice how long it takes to generate the page; it should take several seconds due to the embedded for loops. Now browse to the page once again; notice that it appears near-instantly. Continue browsing to the page and notice it will continue to appear near-instantly. This is the cache filter in action. After the page is generated once, a copy is saved in your J2EE application's temporary work directory (on Tomcat, this is in a subdirectory of ./work), and on subsequent requests, this cache is used instead of executing the JSP. You can test this by deleting the cache file located in Dept of MCA, KSRMCE

Page 49: Security Filters Final

Security Filters for Web Servers

your J2EE application's temporary directory, and browsing to the page. Once again it will take several seconds to load. We can quantify the time difference by making a simple JSP that spoofs two HTTP requests and measuring the time it takes for each request to be answered. To ensure that the test works, we will have to delete the cache before running the JSP. This will force the first HTTP request to execute the JSP and allow the second request to hit the cache. Here is the code for the needed JSP.

Save the above code in your J2EE application. Next, delete the temporary directory of that J2EE application in order to ensure that there is no cache. Now browse to the cache test page. Initially, a blank page appears with a simple HTML form, as shown here.

Cache Filter Summary

A filter that is incredibly helpful and near-trivial to use. Caching can save enormous amounts of your server's time and processing power, and caching is as easy to implement as putting a copy of code in J2EE application's J2EE-INF/lib directory and deploying the filter to intercept requests to any resource you want to cache. It is suggested to use a caching filter as much as possible in order to speed your J2EE application up to peak performance.

While caching can save a J2EE application a lot of time and processing power, and it can make even the most complex server-side code appear to execute unbelievably fast, caching is not suitable for everything. Some pages can't be cached because the page's content must be dynamically generated each time the page is viewed -- for instance, a J2EE site that lists stock quotes. Often, though, resources that are supposedly always dynamic can really be cached for short periods of time. , consider content is cached for a few minutes at a time to save server-side resources, but the cache is updated quick enough to make the site appear to be completely dynamic. In the given cache filter code, you can configure whether the filter caches a particular resource at all, and how long the filter uses a cache before updating it. Both of these are initial configuration elements.

To tell the cache filter that a resource shouldn't be cached, set an initial configuration element of the same name as the resource's request URI to have a value of nocache. To configure how long the filter waits before updating cached content change the cacheTimeout initial configuration parameter to have a numerical value that represents the number of minutes a cache is valid. Both of these features are specific only to this cache filter.

Dept of MCA, KSRMCE

Page 50: Security Filters Final

Security Filters for Web Servers

In general, a cache filter is a very powerful enhancement to add to a J2EE application. Cached content can be served to users as fast as the server can read files from disk (or memory, if you keep the cache in RAM), which is almost always much faster than executing a servlet or JSP, especially complex, database-driven pages. However, caching must be done in an intelligent manner. Some pages simply can't be cached, or they can only be cached for a few minutes at a time. Make sure you cache as much of your J2EE application's content for as long as you can, and be sure to configure the cache filter to appropriately handle pages that either shouldn't be cached or should only be cached for short periods of time.

Conclusion

Every J2EE application should have a caching filter and a compression filter. These two filters optimize how quickly a J2EE application generates content and how long it takes the content to be sent across the World Wide Web, both of which are arguably the most important tasks a J2EE application performs.

. RSA Algorithm1. Consider 2 prime numbers2. Calculate the product n=p*q3. Also calculate Ф(n)=(p-1)(q-1)4. Select an integer “d” such that gcd[d,Ф(n)]=1

d*e mod Ф(n) = 1e=1*dֿ¹mod Ф(n)

e=public keyd=private key

1) c=m pow e2) m=e pow d

c=cyfer textd=plain text

Encryption:C= m pow e mod nDecryption : M= c pow d mod nDept of MCA, KSRMCE

Page 51: Security Filters Final

Security Filters for Web Servers

But e & d values should not exceed n E<n (or) D<nThat’s why we are use mod We multiply with mod nY=E kra (x)Z=E kvb (y)=Ekvb(Ekra(x))At the reciver the message is decrypted with receverss private key ,then decrypted

with senders public key.Y=Dkrb(z)X=Dkva(y)=Dkva(Dkrb(z))

RSA algorithm is developed by three scientists Revist, Shamir,Adelman

The procedure for RSA algorithm two large prime number there are are P and QCalculate the product of n=p*q and also calculate Ф(n)=(p-1)*(q-1)Select an integer ‘e’ such that It is a relative prime to Ф(n) that is gcd Ф((n),e)=1Calculate n integer d as d=e pow -1 mod Ф(n)Or e*d mod Ф(n)=1Public key ku={e,n}Private key kr={d,n}

Encryption: Plaintext m<n ,that cyber text is calculated by using public key as c=m pow e mod nDecryption: Similarly decryption can perform to calculate plain text m by using private key (d,n) as m=c pow d mod n

This both sender and receiver must know the value of n and also sender must know the value of e and only the receiver knows the value of d. Thus the public key encryption algorithm uses

Public key ku={e,n}

Dept of MCA, KSRMCE

Page 52: Security Filters Final

Security Filters for Web Servers

Private key kr={d,n}

For this algorithm to be satisfied of public key requirement. The following requirements are needed.1.It is possible to find the values of e, d,n such that m power ed=m mod n. for all m<n 2.It is easy to calcualate m pow e and c pow d for all the values m <n 3.It is infeasible to determine for given e and d to determine the relationship of public key and private key consider Eulers theorm as for as given two prime numbers p,q &two integers n and m such that n=p *q and the relationship m pow k. Ф(n)+1=m pow k((p-1)(q-1)) =m mod nwhere Ф(n) is the ‘Eulers totient function’ which is number of positive integers less than n and relative prime number to n.This can we achieve desired relationship is Ed=k Ф(n)+1 Ed congruent to 1 mod Ф(n)

Security of RSA

There are three possible approaches to attack the RSA algorithm. 1.Bruteforce This involves trying all possible private keys.This protection from

Bruteforce attack is same for RSA,as for as other cryptosystems by using large key space.Thus the large number of bits in (e,d) then more protection,because the calculations involved in both key generations and in encrypltion and decryption will more complex.

2.Mathmatical attack It is involves in factoring the product of the prime numbers. Factor n into

its two prime number factors, from which we can able to calculate Ф(n)=(p-1)(q-1) ,in terms able to determine d=eֿ¹modn Ф(n).thus the private key can be calculated.

3.Timeout attack It involves in calculating total amount of time. This is as if different

users are using the same key then timeout attack will be occurred.

Dept of MCA, KSRMCE

Page 53: Security Filters Final

Security Filters for Web Servers

Compression

The LZW compression algorithm in its simplest form is shown in Figure 1. A quick examination of the algorithm shows that LZW is always trying to output codes for strings that are already known. And each time a new code is output, a new string is added to the string table.

Routine LZW_COMPRESS

STRING = get input character WHILE there are still input characters DO CHARACTER = get input character IF STRING+CHARACTER is in the string table then STRING = STRING+character ELSE output the code for STRING add STRING+CHARACTER to the string table STRING = CHARACTER END of IF END of WHILE output the code for STRINGThe Compression AlgorithmFigure 1

A sample string used to demonstrate the algorithm is shown in Figure 2. The input string is a short list of English words separated by the '/' character. Stepping through the start of the algorithm for this string, you can see that the first pass through the loop, a check is performed to see if the string "/W" is in the table. Since it isn't, the code for '/' is output, and the string "/W" is added to the table. Since we have 256 characters already defined for codes 0-255, the first string definition can be assigned to code 256. After the third letter, 'E', has been read in, the second string code, "WE" is added to the table, and the code for letter 'W' is output. This continues until in the second word, the characters '/' and 'W' are read in, matching string number 256. In this case, the code 256 is output, and a three character string is added to the string table. The process continues until the string is exhausted and all of the codes have been output.

Dept of MCA, KSRMCE

Page 54: Security Filters Final

Security Filters for Web Servers

Input String = /WED/WE/WEE/WEB/WET

Character Input Code Output New code value New String

/W / 256 /W

E W 257 WE

D E 258 ED

/ D 259 D/

WE 256 260 /WE

/ E 261 E/

WEE 260 262 /WEE

/W 261 263 E/W

EB 257 264 WEB

/ B 265 B/

WET 260 266 /WET

EOF T

The Compression ProcessFigure 2

The sample output for the string is shown in Figure 2 along with the resulting string table. As can be seen, the string table fills up rapidly, since a new string is added to the table each time a code is output. In this highly redundant input, 5 code substitutions were output, along with 7 characters. If we were using 9 bit codes for output, the 19 character input string would be reduced to a 13.5 byte output string. Of course, this example was carefully chosen to demonstrate code substitution. In real world examples, compression usually doesn't begin until a sizable table has been built, usually after at least one hundred or so bytes have been read in.

Decompression

The companion algorithm for compression is the decompression algorithm. It needs to be able to take the stream of codes output from the compression algorithm, and use them to exactly recreate the input stream. One reason for the efficiency of the LZW algorithm is that it does not need to pass the string table to the decompression code. The table can be built exactly as it was during compression, using the input stream as data. This is possible because the compression algorithm always outputs the STRING and CHARACTER

Dept of MCA, KSRMCE

Page 55: Security Filters Final

Security Filters for Web Servers

components of a code before it uses it in the output stream. This means that the compressed data is not burdened with carrying a large string translation table.

Routine LZW_DECOMPRESS

Read OLD_CODE output OLD_CODE WHILE there are still input characters DO Read NEW_CODE STRING = get translation of NEW_CODE output STRING CHARACTER = first character in STRING add OLD_CODE + CHARACTER to the translation table OLD_CODE = NEW_CODE END of WHILEThe Decompression AlgorithmFigure 3

The algorithm is shown in Figure 3. Just like the compression algorithm, it adds a new string to the string table each time it reads in a new code. All it needs to do in addition to that is translate each incoming code into a string and send it to the output.

Figure 4 shows the output of the algorithm given the input created by the compression earlier in the article. The important thing to note is that the string table ends up looking exactly like the table built up during compression. The output string is identical to the input string from the compression algorithm. Note that the first 256 codes are already defined to translate to single character strings, just like in the compression code.

Input Codes: / W E D 256 E 260 261 257 B 260 T

Input/NEW_CODE

OLD_CODESTRING/Output

CHARACTER New table entry

/ / /

W / W W 256 = /W

E W E E 257 = WE

D E D D 258 = ED

256 D /W / 259 = D/

Dept of MCA, KSRMCE

Page 56: Security Filters Final

Security Filters for Web Servers

E 256 E E 260 = /WE

260 E /WE / 261 = E/

261 260 E/ E 262 = /WEE

257 261 WE W 263 = E/W

B 257 B B 264 = WEB

260 B /WE / 265 = B/

T 260 T T 266 = /WET

The Decompression ProcessFigure 4

The Catch

Unfortunately, the nice simple decompression algorithm shown in Figure 4 is just a little too simple. There is a single exception case in the LZWcompression algorithm that causes some trouble to the decompression side. If there is a string consisting of a (STRING,CHARACTER) pair already defined in the table, and the input stream then sees a sequence of STRING, CHARACTER, STRING, CHARACTER, STRING, the compression algorithm will output a code before the decompressor gets a chance to define it.

A simple example will illustrate the point. Imagine the the string JOEYN is defined in the table as code 300. Later on, the sequence JOEYNJOEYNJOEY occurs in the table. The compression output will look like that shown in Figure 5.

Input String: ...JOEYNJOEYNJOEY

Character Input New Code/String Code Output

JOEYN 300 = JOEYN 288 (JOEY)

A 301 = NA N

. . .

. . .

. . .

JOEYNJ 400 = JOEYNJ 300 (JOEYN)

JOEYNJO 401 = JOEYNJO 400 (???)

A problemFigure 5

Dept of MCA, KSRMCE

Page 57: Security Filters Final

Security Filters for Web Servers

When the decompression algorithm sees this input stream, it first decodes the code 300, and outputs the JOEYN string. After doing the output, it will add the definition for code 399 to the table, whatever that may be. It then reads the next input code, 400, and finds that it is not in the table. This is a problem, what do we do?

Fortunately, this is the only case where the decompression algorithm will encounter an undefined code. Since it is in fact the only case, we can add an exception handler to the algorithm. The modified algorithm just looks for the special case of an undefined code, and handles it. In the example in Figure 5, the decompression routine sees a code of 400, which is undefined. Since it is undefined, it translates the value of OLD_CODE, which is code 300. It then adds the CHARACTER value, which is 'J', to the string. This results in the correct translation of code 400 to string "JOEYNJ".

Routine LZW_DECOMPRESS

Read OLD_CODEoutput OLD_CODECHARACTER = OLD_CODEWHILE there are still input characters DO Read NEW_CODE IF NEW_CODE is not in the translation table THEN STRING = get translation of OLD_CODE STRING = STRING+CHARACTER ELSE STRING = get translation of NEW_CODE END of IF output STRING CHARACTER = first character in STRING add OLD_CODE + CHARACTER to the translation table OLD_CODE = NEW_CODEEND of WHILEThe Modified Decompression AlgorithmFigure 6

The Implementation Blues

The concepts used in the compression algorithm are very simple -- so simple that the whole algorithm can be expressed in only a dozen lines. Implementation of this

Dept of MCA, KSRMCE

Page 58: Security Filters Final

Security Filters for Web Servers

algorithm is somewhat more complicated, mainly due to management of the string table.

In the code accompanying this article, I have used code sizes of 12, 13, and 14 bits. In a 12 bit code program, there are potentially 4096 strings in the string table. Each and every time a new character is read in, the string table has to be searched for a match. If a match is not found, then a new string has to be added to the table. This causes two problems. First, the string table can get very large very fast. If string lengths average even as low as three or four characters each, the overhead of storing a variable length string and its code could easily reach seven or eight bytes per code.

In addition, the amount of storage needed is indeterminate, as it depends on the total length of all the strings.

The second problem involves searching for strings. Each time a new character is read in, the algorithm has to search for the new string formed by STRING+CHARACTER. This means keeping a sorted list of strings. Searching for each string will take on the order of log2 string compares. Using 12 bit words means potentially doing 12 string compares for each code. The computational overhead caused by this would be prohibitive.

The first problem can be solved by storing the strings as code/character combinations. Since every string is actually a combination of an existing code and an appended character, we can store each string as single code plus a character. For example, in the compression example shown, the string "/WEE" is actually stored as code 260 with appended character E. This takes only three bytes of storage instead of 5 (counting the string terminator). By backtracking, we find that code 260 is stored as code 256 plus an appended character E. Finally, code 256 is stored as a '/' character plus a 'W'.

Doing the string comparisons is a little more difficult. Our new method of storage reduces the amount of time for a string comparison, but it doesn't cut into the the number of comparisons needed to find a match. This problem is solved by storing strings using a hashing algorithm. What this means is that we don't store code 256 in location 256 of an array. We store it in a location in the array based on an address formed by the string itself. When we are trying to locate a given string, we can use the test string to generate a hashed address, and with luck can find the target string in one search.

Dept of MCA, KSRMCE

Page 59: Security Filters Final

Security Filters for Web Servers

Since the code for a given string is no longer known merely by its position in the array, we need to store the code for a given string along with the string data. In the attached program, there are three array elements for each string. They are code_value[i], prefix_code[i], and append_character[i].

When we want to add a new code to the table, we use the hashing function in routine "find_match" to generate the correct i. Find_match generates an address, then checks to see if the location is already in use by a different string. If it is, it performs a secondary probe until an open location is found.

The hashing function in use in this program is a straightforward "xor" type hash function. The prefix code and appended character are combined to form an array address. If the contents of the prefix code and character in the array are a match, the correct address is returned. If that element in the array is in use, a fixed offset probe is used to search new locations. This continues until either an empty slot is found, or a match is found. By using a table about 25% larger than needed, the average number of searches in the table usually stays below 3. Performance can be improved by increasing the size of the table. Note that in order for the secondary probe to always work, the size of the table needs to be a prime number. This is because the probe can be any integer between 0 and the table size. If the probe and the table size were not mutually prime, a search for an open slot could fail even if there were still open slots available.

Implementing the decompression algorithm has its own set of problems. One of the problems from the compression code goes away. When we are compressing, we need to search the table for a given string. During decompression, we are looking for a particular code. This means that we can store the prefix codes and appended characters in the table indexed by their string code. This eliminates the need for a hashing function, and frees up the array used to store code values.

Unfortunately, the method we are using of storing string values causes the strings to be decoded in reverse order. This means that all the characters for a given string have to be decoded into a stack buffer, then output in reverse order. In the program here this is done in the "decode_string" function. Once this code is written, the rest of the algorithm turns into code very easily.

One problem encountered when reading in data streams is determining when you have reached the end of the input data stream. In this particular implementation, I have reserved the last defined code, MAX_VALUE, as a special end of data indicator. While this may not be necessary when reading in data files, it is very

Dept of MCA, KSRMCE

Page 60: Security Filters Final

Security Filters for Web Servers

helpful when reading compressed buffers out of memory. The expense of losing one defined code is minimal in comparison to the convenience.

Results

It is somewhat difficult to characterize the results of any data compression technique. The level of compression achieved varies quite a bit depending on several factors. LZW compression excels when confronted with data streams that have any type of repeated strings. Because of this, it does extremely well when compressing English text. Compression levels of 50% or better should be expected. Likewise, compressing saved screens and displays will generally show very good results.

Trying to compress binary data files is a little more risky. Depending on the data, compression may or may not yield good results. In some cases, data files will compress even more than text. A little bit of experimentation will usually give you a feel for whether your data will compress well or not.

Your Implementation

The code accompanying this article works. However, it was written with the goal of being illuminating, not efficient. Some parts of the code are relatively inefficient. For example, the variable length input and output routines are short and easy to understand, but require a lot of overhead. An LZW program using fixed length 12 bit codes could experience real improvements in speed just by recoding these two routines.

One problem with the code listed here is that it does not adapt well to compressing files of differing sizes. Using 14 or 15 bit codes gives better compression ratios on large files, (because they have a larger string table to work with), but actually has poorer performance on small files. Programs like ARC get around this problem by using variable length codes. For example, while the value of "next_code" is between 256 and 511, ARC inputs and outputs 9 bit codes. When the value of next_code increases to the point where 10 bit codes are needed, both the compression and decompression routines adjust the code size. This means that the 12 bit and 15 bit versions of the program will do equally well on small files.

Another problem on long files is that frequently the compression ratio begins to degrade as more of the file is read in. The reason for this is simple. Since the string table is of finite size, after a certain number of strings have been defined,

Dept of MCA, KSRMCE

Page 61: Security Filters Final

Security Filters for Web Servers

no more can be added. But the string table is only good for the portion of the file that was read in while it was built. Later sections of the file may have different characteristics, and really need a different string table.

The conventional way to solve this problem is to monitor the compression ratio. After the string table is full, the compressor watches to see if the compression ratio degrades. After a certain amount of degradation, the entire table is flushed, and gets rebuilt from scratch. The expansion code is flagged when this happens by seeing a special code from the compression routine.

An alternative method would be to keep track of how frequently strings are used, and to periodically flush values that are rarely used. An adaptive technique like this may be too difficult to implement in a reasonably sized program.

One final technique for compressing the data is to take the LZW codes and run them through an adaptive Huffman coding filter. This will generally exploit a few more percentage points of compression, but at the cost of considerable more complexity in the code, as well as quite a bit more run time.

Portability

The code shown was written and tested on MS-DOS machines, and has successfully compiled and executed with several C compilers. It should be portable to any machine that supports 16 integers and 32 bit longs in C. MS-

DOS C compilers typically have trouble dealing with arrays larger than 64 Kbytes, preventing an easy implementation of 15 or 16 bit codes in this

Dept of MCA, KSRMCE

Page 62: Security Filters Final

Security Filters for Web Servers

program. On machines using different processors, such as a VAX, these restrictions are lifted, and using larger code sizes becomes much simpler.

In addition, porting this code to assembly language should be fairly simple on any machine that supports 16 and 32 bit math. Significant performance improvements could be seen this way. Implementations in other high level languages should be straightforward.

Dept of MCA, KSRMCE

Page 63: Security Filters Final

Security Filters for Web Servers

SYSTEM DESIGN

INTRODUCTION TO DESIGN:

Dept of MCA, KSRMCE

Page 64: Security Filters Final

Security Filters for Web Servers

4.1 Introduction:

System designing is a solution ,”how to “ approach to the creation of a new system. This important phase provides the understanding and procedural details necessary for implementing the system recommend in the feasible study. The design step produces a data design , an architectural design and a procedural design.

The data Design transform the information domain model created during

analysis into data structures that will be required to implemement the software.

The architectural design defines the relationship among the major structural components into a procedural description of the software. Source code is generated and testing is conducted to integrate and validate the software.

From a project Management of view, Software design is conducted in two steps.

Their preliminary design is concern with the transformation in to data and Software architecture.

Detailed design focuses on refinement to the architectural representation that lead to detailed data structure and algorithmic representations for software.

DATA DESIGN:

Data design is the first of the three design activities that are conducted during software engineering. The impact of the data structure and procedural complexity causes data design to have a profound influence on the software quality. The Concepts of information hiding and data abstraction provides the foundation for an approach to data design.

ARCHITECTURAL DESIGN:

The primary objective of the architectural design is to develop a modular program structure and represent the control relationship between modules. In addition, architectural design melds program structure and data defining interfaces that enable data to flow through out the program.

Dept of MCA, KSRMCE

Page 65: Security Filters Final

Security Filters for Web Servers

PROCEDURAL DESIGN:

The primary design occurs after data and program structure has been established. Procedural detail can be specific sing either of the following:

Structured programming. Flowchart constructs. Decision tables. Structured English.

DATAFLOW DIAGRAM

DATA FLOWS AND THE DATA STORES:

Dept of MCA, KSRMCE

Page 66: Security Filters Final

Security Filters for Web Servers

Data flows are data structures in motion, while data stores are data structures. Data flows are paths or ‘pipe lines’, along which data structures travel, where as the data stores are place where data structures are kept until needed.

Data flows are data structures in motion, while data stores are data structures at rest. Hence it is possible that the data flow and the data store would be made up of the same data structure.

Data flow diagrams is a very handy tool for the system analyst because it gives the analyst the overall picture of the system, it is a diagrammatic approach.

A DFD is a pictorial representation of the path which data takesFrom its initial interaction with the existing system until it completes any integration.The diagram will describe the logical data flows dealing the movements of any physical items. The DFD also gives the insight into the data that is used in the system i.e., who actually uses it is temporarily stored.

A DFD does not show a sequence of steps. A DFD only shows what the different process in a system is and what data flows between them.

RULES FOR DFD:

Fix the scope of the system by means of context diagrams.

Organize the DFD so that the main sequence of the actions reads left to right and top to bottom.

Identify all inputs and outputs.

Identify and label each process internal to the system with rounded circles.

A process is required for all the data transformation and transfers.Therefore, never connect a data store to a data source or the destinations or another data store with just a data flow arrow.

Do not indicate hardware and ignore control information.

Make sure the names of the processes accurately convey everything the process is done.

Dept of MCA, KSRMCE

Page 67: Security Filters Final

Security Filters for Web Servers

There must not be unnamed process.

Indicate external sources and destinations of the data, with squares.

Number each occurrence of repeated external entities.

Identify all data flows for each process step, except simpleRecord retrievals.

Label data flow on each arrow.

Use details flow on each arrow.

Use the details flow arrow to indicate data movements.

There can’t be unnamed data flow.

A data flow can’t connect two external entities.

LEVELS OF DFD:

The complexity of the business system means that it is a responsible to represent the operations of any system of single data flow diagram. At the top level ,anOverview of the different systems in an organization is shown by the way of context analysis diagram. When exploded into DFD

They are represented by:

LEVEL-0 : SYSTEM INPUT/OUTPUT LEVEL-1 : SUBSYSTEM LEVEL DATAFLOW

FUNCTIONAL LEVEL-2 : FILE LEVEL DETAIL DATA FLOW.

The input and output data shown should be consistent from one level to the next.

Dept of MCA, KSRMCE

Page 68: Security Filters Final

Security Filters for Web Servers

LEVEL-0: SYSTEM INPUT/OUTPUT LEVEL

A level-0 DFD describes the system-wide boundaries, dealing inputs to and outputs from the system and major processes. This diagram is similar to the combined user-level context diagram.

LEVEL-1: SUBSYSTEM LEVEL DATA FLOW

A level-1 DFD describes the next level of details within the system, detailing the data flows between subsystems, which makeup the whole.

LEVEL-2: FILE LEVEL DETAIL DATA FLOW

All the projects are feasible given unlimited resources and infinite time. It is both necessary and prudent to evaluate the feasibility of the project at the earliest possible time. Feasibility and the risk analysis are pertained in many ways. If project risk is great.

The following are some DFD symbols used in the project

SYMBOL DESCRIPTION

ENTITY:

An information outside the bounds System to be module.

Dept of MCA, KSRMCE

Page 69: Security Filters Final

Security Filters for Web Servers

PROCESS:

A transaction of Information that resides within the bounds of the system to be module.

DATASTORE:

A expositry Of data that is to be stored for use by one or more processes,may be as simple as a buffer of quque or as a relational database.

To indicate the flow of data.

FLOW CHARTS

Introduction:-

Dept of MCA, KSRMCE

Page 70: Security Filters Final

Security Filters for Web Servers

Before solving a problem with the the help of a computer, it is essential to plan The solution in a step-by-step manner. Such a planning is represented symbolically with the help of flow chart. It is an important tool of system analysts andProgrammers for tracing the information flow and the logical sequence in data processingLogic is the essence of a flow chart.

A flow chart is the symbolic representation of step-by-step solution of a given problem, and it indicates flow of entire process, the sequence of the data input, operations, computations, decisions, results and other relevant information.

Pertaining to a particular problem . A flow chart helps us in the complete understanding of the logical structure of a complicated problem and in docume-- nting the method used.

It would be seen that the flow chart is a very convenient method of organizing the logical steps and deciding what, when and how to proceed with various pr--ocesses. The logic should be depicted in the flow charts. Co mputerization of the data without a flow chart is like constructing the building without a proper design and detaileddrawings.

Kinds of the flow charts

1. System Flow Chart The system analyst to describe data flow and operations for the data processing cycle uses these. A system flow chart defines the broad processing in the organizations, showing the origin of the data, filling structure,

Dept of MCA, KSRMCE

Page 71: Security Filters Final

Security Filters for Web Servers

processing to be performed, output that is to generate and necessity of the offline operation.

2. Program Flow Chart (or) Computer Procedure flow chart

The progarammers to describe the sequence of operations and

the decision of a particular problem normally use these. A program flow chart plans the

Program structure and also serves the purpose of documentation for a program, whi- -ch is to be retained and used at a later date either by the original programmer or others.

Advantages:

Apart from, the DFDS the flow charts has been helping the programmer to develop the programming logic and to serve as the documentation for a Completed program, it has the following advantages

1. They help for the easy understanding of the logic of a process or a procedure

2. It is a better communicating tool than writing in words.

Dept of MCA, KSRMCE

Page 72: Security Filters Final

Security Filters for Web Servers

3. It is easy to find the conditions, which are responsible for the actions.

4. It is an important tool for planning and designing the new system.

5. It clearly indicates the role-played at each level.

6. It provides an overview of the system and also demonstrates the relatin ship between the various steps.

7. It facilitates troubleshooting.

8. It promotes logical accuracy.

Disadvantages:

1. Communication lines are not always easy to show.

2. The charts are sometimes complicated.

3. Reproduction is difficult.

4. They are hard to modify.

Symbols used in the flow charts:

TERMINAL POINT (START/STOP)

DECISION BOX

Dept of MCA, KSRMCE

Page 73: Security Filters Final

Security Filters for Web Servers

PROCESS

ALTERNATE PROCESS

DATA

PRE DEFINED PROCESS

Dept of MCA, KSRMCE

Page 74: Security Filters Final

Security Filters for Web Servers

DOCUMENT (PRINT OUT)

MULTIDOCUMENT

CONNECTOR

DISPLAY

FLOW LINE

MANUAL INPUT

Dept of MCA, KSRMCE

Page 75: Security Filters Final

Security Filters for Web Servers

UML (UNIFIED MODELLING LANGUAGE)

The unified modeling language is a standard language for specifying, Visualizing, Constructing and Documenting the software system and its components. It is a graphical language which provides a vocabulary and set of semantics and rules. The UML focuses on the conceptual and physical representation of the system. It captures the decisions and understandings about systems that must be constructed. It is used to understand , design , configure, maintain and control information about the systems. Visualizing :

Through UML we see or visualize an existing system and ultimately we visualize how the system is going to be after implementation. Unless we think we cannot implement.

UML helps to visualize how the components of the system communicate and interact with each other.

Specifying : Specifying means building models that are precise, unambiguous and complete UML addresses the specification of all the important Analysis Design, Implementation decisions that must be made in developing and deploying a software system.

Constructing :

UML’s models can be directly connected to a variety of programming language through mapping a model from UML to a programming language like Java or C++ or VB. Forward Engineering and Reverse Engineering is possible through UML.

Documenting: The deliverables of a project apart from coding are some artifacts

Dept of MCA, KSRMCE

Page 76: Security Filters Final

Security Filters for Web Servers

which are critical in controlling, measuring and communicating about a system during its development viz. Requirements, Architecture, Design, Source code, Project plans, Tests, Prototypes, Releases etc.

Diagrams in UML :

Diagrams are graphical presentation of set of elements. Diagrams Projects a system, or visualize a system from different angles and perspectives.

The UML has Nine diagrams these diagrams can be classified into the following groups.

Static:1. Class diagrams.2. Object diagrams.3. Component diagrams.4. Deployment diagrams

Dynamic:1. Use case diagram.2. Sequence diagram.3. Collaboration diagram.4. State chart diagram.5. Activity diagram.

Static or structural diagrams :Class diagram :

This shows a set of classes, interfaces, collaborations and their relationships. There are the most common diagrams in modeling the object oriented systems and are used to give the static view of a system.

Object diagram:

Shows a set of objects and their relationships and are used to show the data structures, the static snapshots of instances of the elements in a class diagram. Like class diagram, the object diagrams also address the static design view or process view of a system.

Dept of MCA, KSRMCE

Page 77: Security Filters Final

Security Filters for Web Servers

Component diagram:

Shows a set of components and their relationships and are used to illustrate the static implementation view of a system. They are related to class diagrams where in components map to one or more classes, interfaces of collaborations.

Deployment diagram:

Shows a set of nodes and their relationships. They are used to show the static deployment view of the architecture of a system. They are related to the component diagrams where a node encloses one or more components.

Dynamic or behavioral diagrams:

Use Case diagram:

Shows a set of use cases and actors and their relationships. These diagrams illustrate the static use case view of a system and are important in organizing and modeling the behaviors of a system.

Sequence diagram & collaboration diagram:These two diagrams are semantically same i.e. the dynamics of a system can

be modeled using one diagram and transform it to the other kind of diagram without loss of information. Both form the, Interaction diagram.

Sequence diagram:

Sequence diagram is an interaction diagram which focuses on the time ordering of messages it shows a set of objects and messages exchange between these objects. This diagram illustrates the dynamic view of a system.

Collaboration diagram:

This diagram is an interaction diagram that stresses or emphasizes the structural organization of the objects that send and receive messages. It shows a set of objects, links between objects and messages send and received by those objects. There are used to illustrate the dynamic vies of a system.

Dept of MCA, KSRMCE

Page 78: Security Filters Final

Security Filters for Web Servers

State Chart Diagram and Activity Diagrams:

These Diagrams are semantically similar. State chart diagram shows a state machine consisting of states, transitions and activities these illustrates the dynamic view of a system. They focuses on the event ordered behavior of an object.

Activity Diagrams:

Activity diagram shows the flow from one activity to another within a system. The activities may be sequential or branching objects that act and are acted upon. These also show the dynamic view of the system.

4.2 CONTEXT LEVEL DIAGRAM

4.3 DATA FLOW DIAGRAM COMPRESSION

Dept of MCA, KSRMCE DECOMPOSE INTO CHARACTERS

CONSTRUCT TREE

TEXT

WRITE TO A FILE

PURE TEXT

RSAENGINE

ORIGINAL

DATA

Page 79: Security Filters Final

Security Filters for Web Servers

DECOMPRESSION

Dept of MCA, KSRMCE

OBSERVE DUPLICATES

NOTE FREQUENCY

TRAVERSE TREE

compressedFile

ENCRYPTED

FILE

OPEN

FILE Apply Public Key (PQ, E)

Apply Private Key

D

DECRYPTED

FILE

Page 80: Security Filters Final

Security Filters for Web Servers

ENCRYPTION

Dept of MCA, KSRMCEFind P and Q, two large primes (1024 bits)

Find E, such that1 < E < PQ

Find C, such thatC = (T^E) mod PQ

Find T, such that T = (C^D) mod PQ

Find D, such that D = (X(P-1)(Q-1) + 1)/E

TEXT WRITE

TO A FILE

Encrypted

FILE

Page 81: Security Filters Final

Security Filters for Web Servers

4.4 UML DIAGRAM

Dept of MCA, KSRMCE

Page 82: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

USER check file Application Server

MOBILE

ENCRYPT

COMPUTER

Page 83: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

USER check file Application Server

MOBILE

DECRYPT

COMPUTER

Page 84: Security Filters Final

Security Filters for Web Servers

SEQUENCE DIAGRAM

Dept of MCA, KSRMCE

Page 85: Security Filters Final

Security Filters for Web Servers

Source Code

import java.io.*;public class BitStreamInputStream extends FilterInputStream {final static int EIGHT = 8; // 8 bits per byteprotected short buffer; // our BYTE bitstream read-ahead // buffer declared as short to cope with EOFprotected int bitsInCache; // how many unread bits left in our byteprotected int fieldSize; // current size of bitstream read fields

//------------------------------------------------------------------public BitStreamInputStream(InputStream in) {

this(in, EIGHT); // default to a normal byte stream}//------------------------------------------------------------------public BitStreamInputStream(InputStream in, int bitFieldSize) { super(in); setBitFieldSize(bitFieldSize); bitsInCache = 0; // we haven't got any cached bits}//------------------------------------------------------------------// Set the current bitfield size.//------------------------------------------------------------------public void setBitFieldSize(int bits) throws IllegalArgumentException { if (bits>32 || bits<1) throw new IllegalArgumentException ( "BitField size ("+ bits + ") no good. Has to be between 1 and 32." ); this.fieldSize = bits;}//------------------------------------------------------------------public int getBitFieldSize() { return this.fieldSize;}//------------------------------------------------------------------// Read a bitfield from the input stream. The number of bits read is// the current bitfield length. Bitfield can be on arbitrary bit boundaries.

Dept of MCA, KSRMCE

Page 86: Security Filters Final

Security Filters for Web Servers

//------------------------------------------------------------------public long readBitField() throws IOException {

int bitField; // what we're going to return to callerint bitsToRead; // remaining bits to assemble into BFint availableNumberOfBits;int OR_position;int rightAlignedBFPartial; bitField = 0; // start with empty jigsaw bitsToRead = fieldSize; OR_position = fieldSize;

while (bitsToRead > 0) { if (bitsInCache == 0) { if ( (buffer = (short) in.read()) == -1) { return -1; // reached EOF } bitsInCache = EIGHT; // we've got a full byte again } availableNumberOfBits = Math.min( bitsToRead, bitsInCache ); rightAlignedBFPartial = buffer >> (EIGHT - availableNumberOfBits); // always keep next partial left aligned and clean buffer <<= availableNumberOfBits; buffer &= 255; OR_position -= availableNumberOfBits; // add bitfield subfield bitField |= rightAlignedBFPartial << OR_position; // track # of cached bits // track how much left to do

bitsInCache -= availableNumberOfBits; bitsToRead -= availableNumberOfBits; } return bitField;} //--------------------------------------------- // The remaining methods are methods we override // from our parent class: FilterInputStream //---------------------------------------------

Dept of MCA, KSRMCE

Page 87: Security Filters Final

Security Filters for Web Servers

//------------------------------------------------------------------// Overridden read() still reads a byte, but on any bit boundary.//------------------------------------------------------------------public int read() throws IOException {int previousBFSize;int theByte; previousBFSize = getBitFieldSize(); setBitFieldSize( EIGHT ); try { theByte = (int) readBitField(); } finally { setBitFieldSize( previousBFSize ); } return theByte;}//------------------------------------------------------------------// Override block read() methods to use basic read() as building block.// The implementation we want for this read() is the same as that// for class InputStream.// According to the Java language spec, two elegant (and short// solution should work:// ((InputStream) this).read(..) // i.e. a cast// InputStream.read(..) // i.e. fully specifiying// Unfortunately neither work, so I am forced to paste in the// original code for InputStream.read(byte b[], int off, int len).//------------------------------------------------------------------

public int read(byte b[], int off, int len) throws IOException {

if (len <= 0) { return 0; } int c = read(); if (c == -1) { return -1; } b[off] = (byte)c;

Dept of MCA, KSRMCE

Page 88: Security Filters Final

Security Filters for Web Servers

int i = 1; try { for (; i < len ; i++) { c = read(); if (c == -1) { break; } if (b != null) { b[off + i] = (byte)c; } } } catch (IOException ee) {} return i;}//------------------------------------------------------------------// Overridden FilterInputStream.read(byte b[])//------------------------------------------------------------------public int read(byte b[]) throws IOException { return read(b, 0, b.length);}//------------------------------------------------------------------// Overridden FilterInputStream.skip(long n)// If any client relies heavily on skipping multi-byte strings in// the bitstream, then this method has to be re-implemented to be more// efficient. Current implementation is functional but highly inefficient.//------------------------------------------------------------------public long skip(long n) throws IOException {long i;

for(i=0; i < n; i++) { if (read() == -1) break; } return i;}} // End of Class BitStreamInputStream

import java.io.*;

Dept of MCA, KSRMCE

Page 89: Security Filters Final

Security Filters for Web Servers

public class BitStreamOutputStream extends FilterOutputStream {

final static int EIGHT = 8; // 8 bits per byte

protected short buffer; // our BYTE bitstream write bufferprotected int bitsInCache; // how many cached bits in our byteprotected int fieldSize; // current size of bitstream fieldsprotected long maxFieldValue; // max value that fits bitfield//------------------------------------------------------------------

public BitStreamOutputStream(OutputStream out) { this(out, EIGHT); // default to a normal byte stream}//------------------------------------------------------------------public BitStreamOutputStream(OutputStream out, int bitFieldSize) { super(out); // call FilterOutputStream constr. setBitFieldSize(bitFieldSize); bitsInCache = 0; // we haven't got any cached bits buffer = 0; // start w/ clean buffer (for ORs !)}//------------------------------------------------------------------public void setBitFieldSize(int bits) throws IllegalArgumentException { if (bits>32 || bits<1) throw new IllegalArgumentException ( "BitField size ("+ bits + ") no good. Has to be between 1 and 32." ); this.fieldSize = bits; this.maxFieldValue = (1L << bits) - 1; // precalc max bf value}//------------------------------------------------------------------public int getBitFieldSize() { return this.fieldSize;}//------------------------------------------------------------------// Write a bitfield to the output stream. The number of bits written is// the current bitfield length. Bitfield can be on arbitrary bit boundaries.//------------------------------------------------------------------public void writeBitField(int bf) throws IOException {

Dept of MCA, KSRMCE

Page 90: Security Filters Final

Security Filters for Web Servers

int bitsToWrite; // how many bits left to writeint capacity; // how many bits fit in write bufferint partial, partialSize; // partial bitfield and its size in bitsint bfExtractPos; // bitfield extract position (bit number)

// check that bitfield fits in current bitfield size if (bf > maxFieldValue ) { throw new IllegalArgumentException ( "Can not pack bitfield " + bf + " in " + fieldSize + " bits." ); } bitsToWrite = fieldSize; bfExtractPos = fieldSize; // a single bitfield might have to be written out in several // passes since the lot has to pass through the single byte // write buffer. This inefficient situation is a result of // the complex aligning required to append any bitfield to // the currently written stream. while (bitsToWrite > 0) { if (bitsInCache != EIGHT) { // if capacity left capacity = EIGHT - bitsInCache; // in write buffer...

partialSize = Math.min( bitsToWrite, capacity); bfExtractPos -= partialSize;

partial = extract (bf, partialSize, bfExtractPos); buffer |= partial << (capacity - partialSize); bitsToWrite -= partialSize; bitsInCache += partialSize; } if (bitsInCache == EIGHT) { // if write buffer full, out.write((int) buffer); // send it on its way bitsInCache = 0; // and continue with buffer = 0; // clean buffer } }}

Dept of MCA, KSRMCE

Page 91: Security Filters Final

Security Filters for Web Servers

//------------------------------------------------------------------// extract a bitfield of length 'bits' from an integer source.// bitfield starts at bit 'pos' and is returned right-aligned to bitpos 0//------------------------------------------------------------------private int extract (int source, int bits, int pos) {

source = source >> pos; // align bitfield to bit 0 int mask = ~( (-1) << bits);// create a mask to get clean bitfld return source & mask; // return bitfield (0 bits padded)} //--------------------------------------------- // The remaining methods are methods we override from // our parent class: FilterOutputStream //---------------------------------------------//------------------------------------------------------------------// Override write() method to write a byte on any bit boundary.//------------------------------------------------------------------public void write(int b) throws IOException {int previousBFSize;

previousBFSize = getBitFieldSize(); setBitFieldSize(EIGHT); try { writeBitField( b & 0xFF ); } // if writeBitField threw an exception, make sure we reset // the current bitfield size before letting the exception thru finally { setBitFieldSize(previousBFSize); }}

//------------------------------------------------------------------// Override block write() methods to use basic write() as building block.//------------------------------------------------------------------public void write(byte b[], int off, int len) throws IOException { for (int i = 0 ; i < len ; i++) { write(b[off + i]); }

Dept of MCA, KSRMCE

Page 92: Security Filters Final

Security Filters for Web Servers

}public void write(byte b[]) throws IOException { write(b, 0, b.length);}

//------------------------------------------------------------------// Override flush() method.//------------------------------------------------------------------public void flush() throws IOException {

// REFUSE to flush as this advances file pointer of underlying stream !} //------------------------------------------------------------------// Override close() method to correctly flush any remaining bitfields// in write buffer before closing output chain.//------------------------------------------------------------------public void close() throws IOException { if (bitsInCache != 0) { out.write((int) buffer); } out.flush(); out.close();} } // End of class BitStreamOutputStream

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.sql.*;

public class CompFilter implements Filter {

public void init(FilterConfig config) { System.out.println("Second Filter");

Dept of MCA, KSRMCE

Page 93: Security Filters Final

Security Filters for Web Servers

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws ServletException,IOException {

try{

// encrypt code RSA rsa = new RSA(); rsa.genKeyPair(1024); String pub = rsa.getPublic(); String pri = rsa.getPrivate(); FileOutputStream fos1 = new FileOutputStream("c:/pubKey"); FileOutputStream fos2 = new FileOutputStream("c:/priKey"); fos1.write(pub.getBytes()); fos1.flush(); fos2.write(pri.getBytes()); fos2.flush(); fos1.close(); fos2.close();//C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\ROOT FileInputStream fis = new FileInputStream("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/ROOT/key.imp"); int i = -1; String originalText = ""; for(; (i = fis.read()) != -1; ){ originalText = originalText + (char)i; }

String cipherText = rsa.encode(originalText);

FileOutputStream fos3 = new FileOutputStream("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/ROOT/enckey.imp");

fos3.write(cipherText.getBytes()); fos3.flush(); fos3.close();

//end of encrypt code// start of comp code

Dept of MCA, KSRMCE

Page 94: Security Filters Final

Security Filters for Web Servers

FileInputStream fis1 = new FileInputStream("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/ROOT/enckey.imp");FileOutputStream fos = new FileOutputStream("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/ROOT/compressed.cmp");LZW l= new LZW();l.compress(fis1,fos);

}catch(Exception e){System.out.println(e.toString());}

// end of comp code System.out.println("dofilter of Second Filter");chain.doFilter(request, response);}

/** * This method called by the web container to indicate to a filter * that it is being taken out of service. */ public void destroy() { System.out.println("#### FILTER2'S DESTROY#### ");

}}

Dept of MCA, KSRMCE

Page 95: Security Filters Final

Security Filters for Web Servers

SYSTEM ANALYSIS

Dept of MCA, KSRMCE

Page 96: Security Filters Final

Security Filters for Web Servers

INRODUCTON TO ANALASIS:

SYSTEM ANALYSIS

INTRODUCTION TO ANALYSIS:System analysis is a logical process. The objective of this

phase is not actually solving the problem, but to determine exactly

what must be done to solve the problem. during analysis, the System

Analysis work with the user to develop a logical model of the system

using such tools as data Flow Diagrams, Data Dictionary and rough

description of relevant algorithms.

System Analysis is about understanding situations, not

solving problems. Therefore the emphasis should be made on

investigation and questioning to learn how a system currently operates

and to identify the requirements users have for a new or modified one.

Requirement Determination:

The first in carrying out System Analysis is requirements

determination. This involves studying the current system and where

improvements should be made.

Dept of MCA, KSRMCE

Page 97: Security Filters Final

Security Filters for Web Servers

System studies result in an evaluation of how current method’s

are working and whether adjustments are necessary as possible. The

following are the main activities that have to be carried out in

requirement determination.

Requirement Anticipation:

Study and documentation of the current system, using fact

finding techniques, data Flow analysis and decision analysis.

Requirement Specification:

Analysis of data describing the system to determine how well it

is performing, what requirements must be met and strategies for

fulfilling them.

FEASIBILITY STUDY

Project feasibility is the likelihood that the system will be

useful to the organization. Simply stated this test of feasibility asks if

the system will works when is developed and installed. These tests of

feasibility are studied operational, technical and financial.

Operational feasibility:

Proposed projects are beneficial only if they can be

turned into information systems that will meet the requirements. As

there was sufficient support for the business methods are not

acceptable to the users in terms of speed, timely and accurate results,

users welcomed a change that will bring about a more operational and

useful system. With the rarely involvement is reduced the chances of

resistance to the system and change in general and increased the

likelihood of project successfully.

Technical feasibility:

Dept of MCA, KSRMCE

Page 98: Security Filters Final

Security Filters for Web Servers

The system can be expanded as the need arises. That is

the reason Oops based java programming concepts are used. With the

obtained technology there are guaranteed of accuracy, reliability ease

of access and security of Data.

Economical feasibility:

During the study many costs are considered like costs

of hardware and software for the class of application, benefits in the

form of reduced cost like client side with minimum configuration,

system compatibility of any H/W, which leads to benefits the client in

terms of finance.

Since the proposed system is feasible in all aspects,

the study is thus extended to system analysis.

Dept of MCA, KSRMCE

Page 99: Security Filters Final

Security Filters for Web Servers

SYSTEM IMPLEMENTATION

SYSTEM IMPLEMENTATION

The system “Encryption & data compression plug _ins for j2ee

systems” is an interface between the client and server existing in the

Dept of MCA, KSRMCE

Page 100: Security Filters Final

Security Filters for Web Servers

computer system. As the number of clients are growing day by day, the

need for a single server.

Therefore the concerned management wants to

computerize the existing system.

5.1 Existing System

Until the advent of the new API from the Sun Microsystems, there was no way that we can change the functionality of an existing J2EE web component, without really disturbing it. So, I can perfectly claim that this is the first attempt at such an aspect using the Sun’s new API.

The only way to modify the functionality of an existing servlet, before servlets version 2.3, is only modifying the original servlet, which requires the entire process of deploying the servlets on the web container to be repeated.

5.2 Proposed System

As I have claimed in the last section that this is the first of its kind of project, which honors the principle of ‘Software Reuse’.

The detailed discussion of the proposed system and its design has been given in the chapter 2.

There are three Modules in the system on a whole.

Module1:- In this module I have implemented RSA algorithm in the form of java

classes. which have got two methods.

Public byte [] compress(byte[])

Public byte [] decompress(byte[])

Module2:-In this module I have implemented java filters.one for

compression another for decompression and a couple of GUI screens for

configuring those filters.

Dept of MCA, KSRMCE

Page 101: Security Filters Final

Security Filters for Web Servers

Configure means given the filter name of the servelet to which it has to

be attached xml file location. The domain name, the port number.

Module3:- In this module I have implemented two java filters one for

Encryption another for Decryption.

Public byte [] encryption(byte[])

Public byte [] decryption(byte[])

In the client side we have an applet for GUI screen.So we have to

arrange proper communication between this applet and the servlet.

RSA algorithm is head of my project. The main them behind

RSA is that it is difficult to make a wide guess on the result of dividing the

large prime number with another large prime number. The result of such a

division is choosen to the public key and the another result of the same kind

of choosen to be a private key by applying those two keys. The component is

scambled. This scambled content is sent to the client. The public is sent to

the client via web. But private key is sent to separate to the client

personally. The scambled content and the public key reaches the client side

applet, the client needs to give the private key, so that the client is

descrambled or decrypted.

Dept of MCA, KSRMCE

Page 102: Security Filters Final

Security Filters for Web Servers

SYSTEM TESTING

SYSTEM TESTING

Testing Specification & Documentation

Testing is a process of executing with the intent of finding an

error. Testing was done to check for the proper functioning of system.

Dept of MCA, KSRMCE

Page 103: Security Filters Final

Security Filters for Web Servers

System was tested at various levels to attain the goal and the system to be

problem free.

The following testing strategies are performed.

Unit testing:

Unit testing focuses verification errors on the smallest unit of software design-the module. Using the procedural design description as a guide, important control paths are tested to uncover errors within the boundary of the module.

Every module interface is tested to ensure the information

properly flows into and out of it.

The local data structure is examined to ensure that data

stored temporarily maintains its integrity during all steps

in algorithm’s execution.

Boundary conditions are tested to ensure that the module

operates properly at boundaries established to limit or

restrict processing.

All independent paths through the control structure are

exercised to ensure that all statements in a module have

been executed at least once.

All error-handling paths are tested properly.

Because a module is not a standalone program, stub software must be

developed for each unit test. In our case this stub software is nothing more

than a “Main Program” that accepts test data, passes such data to the

module and prints the relevant results. Unit testing performs verification on

the smallest unit of software design in the module. Using the procedural

design description as a guide, important control paths are tested to uncover

errors with in the boundary of the module scope established for unit testing.

The unit testing is normally white box oriented and the step can be

conducted in parallel for multiple modules.

The module interface is tested to ensure that information

properly flows into and out of the programs unit under test. Boundary

Dept of MCA, KSRMCE

Page 104: Security Filters Final

Security Filters for Web Servers

conditions are tested to ensure that the module operates properly at the

boundaries established to limit or restrict processing.

Integration Testing:

Integration testing is a systematic technique for

constructing the program structure while conducting tests to uncover errors

associated with interfacing. The objective is to take unit tested modules and

build a program structure that has been dictated by design. There are mainly

two types of integration.

1. Top-Down integration

2. Bottom-Up integration

Top-Down integration is an incremental approach to construction of

program structure. Modules are integrated by moving downward through the

control hierarchy, beginning with the main control module (main program).

Bottom-Up integration testing, as its name implies, begins

construction and testing with automatic modules (i.e. modules at lowest

levels in the program structure). Because modules are integrated from the

bottom-up, processing required for modules sub-ordinate to a given level is

always available and the need for stubs is eliminated. Because of this

advantage of Bottom-Up integration, we adopted this method integration

testing is a systematic technique for constructing the program structure

while conducting tests to uncover error associated with interfacing. The

objective is to take unit tested modules and build a program structure that

has been dictated by the design.

At this stage of integrating testing best results can be achieved if the

incremental integration technique is adopted. In this process the program is

constructed and tested in small fragments where errors are easy to be

tested completely; and a systematic approach may be applied.

In the present “JDBC Editor”, we used Black Box testing for

finding errors in the following categories.

Incorrect or missing functions.

Dept of MCA, KSRMCE

Page 105: Security Filters Final

Security Filters for Web Servers

Interface errors.

Errors in database access.

Initialization and termination errors.

Desired out put for given input.

I/O error.

White-Box & Black Box Testing:

White-Box testing is sometimes called Glass Box testing, is a test case

design that uses a control structure of the procedural design to drive the test

case. Using White-Box testing methods, the software engineer can drive test

cases that

Guarantee that logical decisions on their true and false sides.

Exercise all logical decisions on their true and false sides.

Execute all loops at their boundaries and with in

their operational bounds.

Exercise internal data structure to assure their validity.

Acceptance testing:

Finally when the completely software builds a series of acceptance

tests are conducted to enable the client to validate all requirements. The

user conducts these tests rather than the system developer, which can range

from informal test drive to a planned and systematical executed series of

tests.

These acceptance tests are conducted over a period of weeks or

months, thereby uncovering cumulative errors that might degrade the

system order time. In this process Alpha testing and Beta testing are used to

uncover the errors that only the end user seems able to find.

Alpha Test:

Dept of MCA, KSRMCE

Page 106: Security Filters Final

Security Filters for Web Servers

The customer conducts the Alpha Test at the developer’s site. The client

noted the errors and usage problems and give report to the developer. Alpha

tests are conducted in a control environment.

Beta Test:

The Beta Test is conducted at one or more customer’s sites by the end user’s

of the software. Unlike the Alpha Testing the developer is not present. Therefore a

Beta Test is a “live” application of the software in the environment that cannot be

developed by the developer. The customer records all the problem (real and

imagine) that is encountered during the Beta Testing and reports these to the

developer at regular intervals. As a result the problems reported during the Beta

Test; the software developer makes the modification and then prepares for released

of the software product to entire customer best.

Approach for Testing:

The goal is to achieve branch coverage of more than 95%. System

testing will be largely functional in nature.

Test deliverables:

The following documents are produced:

Unit test report for each unit.

1. Test case specification for system testing.

2. Test report for system unit testing, structural testing on Branch

coverage criteria will be used.

3. Error report.

The test case specification for system testing has to be

submitted for review before system testing commences.

Dept of MCA, KSRMCE

Page 107: Security Filters Final

Security Filters for Web Servers

SAMPLE SCREENSDept of MCA, KSRMCE

Page 108: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 109: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 110: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 111: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 112: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 113: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 114: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 115: Security Filters Final

Security Filters for Web Servers

Dept of MCA, KSRMCE

Page 116: Security Filters Final

Security Filters for Web Servers

CONCLUSION

Dept of MCA, KSRMCE

Page 117: Security Filters Final

Security Filters for Web Servers

RESULT OF THE PROJECT:

The Lempel, Ziv and Welch (LZW) algorithm is an efficient compression and decompression algorithm with a compression ratio of 30 to 90 percent. The compression ratio is given by the size of the compressed filedivided by the size of the original file. The scientists Revist, Shamir,Adelman (RSA) algorithm is an efficient compression and decompression algorithm with a compression ratio of 30 to 90 percent. The encreyption ratio is given by the size of the encrypted filedivided by the size of the original file

The efficiency of the algorithm depends on the repetition of bits in the file. If the bits are frequently repeated then the compression ratio is less and it is efficient.

LIMITATIONS OF THE PROJECT

The limitation of this project is it does not work on audio and video files. In these type of files each pixel is to be notede , which is very complicated than the compression of text data.

In the text data each character is considered and the algorithm works well, where as in the video files each pixel is to be considered which is very difficult and inefficient.

Dept of MCA, KSRMCE

Page 118: Security Filters Final

Security Filters for Web Servers

9. BIBLIOGRAPHY

JAVA SERVLETS

Karl Moss

TATA McGraw HILL

SOFTWARE ENGINEERING

 A Practitioner's Approach

- McGraw-Hill Publications

- Roger S. Pressman.

[J2EE-Overview] - http://java.sun.com/j2ee/overview.html

[JS-NET] - http://developer.netscape.com/docs/manuals/communicator/jsref/contents.htm

[J2EE-Home] - http://java.sun.com/j2ee/

[J2EE-Components] - http://java.sun.com/j2ee/blueprints/platform_technologies/component/

index.html

[SUN-Developer] - http://developer.java.sun.com/developer/

Dept of MCA, KSRMCE