+ All Categories
Home > Documents > Security Implementation in Web Applications · is an example of an application layer vulnerability,...

Security Implementation in Web Applications · is an example of an application layer vulnerability,...

Date post: 30-Mar-2020
Category:
Upload: others
View: 8 times
Download: 0 times
Share this document with a friend
46
1 Security Implementation in Web Applications Contents Security Implementation in Web Application........................................................................................... 2 Cross Site Scripting.................................................................................................................................... 3 Cross Frame Scripting (CSRF) .................................................................................................................... 7 Weak Session Management.................................................................................................................... 11 Denial Of Service ..................................................................................................................................... 16 Form Manipulation ................................................................................................................................. 20 Transport Layer Protection ..................................................................................................................... 25 Secure Session Flag ................................................................................................................................. 36 ClickJacking/Cross Frame Scripting ......................................................................................................... 37 Information Disclosure............................................................................................................................ 40 Email Addresses Disclosed ...................................................................................................................... 46
Transcript
Page 1: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

1

Security Implementation in Web Applications

Contents

Security Implementation in Web Application ........................................................................................... 2

Cross Site Scripting .................................................................................................................................... 3

Cross Frame Scripting (CSRF) .................................................................................................................... 7

Weak Session Management .................................................................................................................... 11

Denial Of Service ..................................................................................................................................... 16

Form Manipulation ................................................................................................................................. 20

Transport Layer Protection ..................................................................................................................... 25

Secure Session Flag ................................................................................................................................. 36

ClickJacking/Cross Frame Scripting ......................................................................................................... 37

Information Disclosure............................................................................................................................ 40

Email Addresses Disclosed ...................................................................................................................... 46

Page 2: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

2

Security Implementation in Web Application Security is fundamentally about protecting assets. Assets may be tangible items, such as a Web page or

your customer database — or they may be less tangible, such as your company's reputation.

Security is a path, not a destination. As you analyze your infrastructure and applications, you identify

potential threats and understand that each threat presents a degree of risk. Security is about risk

management and implementing effective countermeasures.

The following are the reasons that you must make your application secure.

Threats: A threat is any potential occurrence, malicious or otherwise, that could harm an asset. In other

words, a threat is any bad thing that can happen to your assets.

Vulnerabilities: Vulnerability is a weakness that makes a threat possible. This may be because of poor

design, configuration mistakes, or inappropriate and insecure coding techniques. Weak input validation

is an example of an application layer vulnerability, which can result in input attacks.

Attack: An attack is an action that exploits vulnerability or enacts a threat. Examples of attacks include

sending malicious input to an application or flooding a network in an attempt to deny service.

So each of this will be related to one another, a threat is a potential event that can adversely affect an

asset, whereas a successful attack exploits vulnerabilities in your system.

So we need to make sure that our application is completely secure and be away from attacks and

vulnerabilities.

In this document we are going to learn about the Top Vulnerabilities, its causes and how to prevent our

application for those vulnerabilities.

The following are the list of the vulnerabilities that we are going to learn in this document.

Page 3: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

3

Cross Site Scripting: Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications.

XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site

scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy.

The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may

also include HTML, Flash, or any other type of code that the browser may execute. The variety of attacks

based on XSS is almost limitless, but they commonly include transmitting private data, like cookies or

other session information, to the attacker, redirecting the victim to web content controlled by the

attacker, or performing other malicious operations on the user's machine under the guise of the

vulnerable site.

There are two types for Cross Site Scripting.

Stored and Reflected XSS Attacks:

XSS attacks can generally be categorized into two categories: stored and reflected. There is a third, much

less well known type of XSS attack called DOM Based XSS.

Stored XSS Attacks:

Stored attacks are those where the injected script is permanently stored on the target servers, such as in

a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious

script from the server when it requests the stored information. Stored XSS is also sometimes referred to

as Persistent or Type-I XSS.

Page 4: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

4

Reflected XSS Attacks:

Reflected attacks are those where the injected script is reflected off the web server, such as in an error

message, search result, or any other response that includes some or all of the input sent to the server as

part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail

message, or on some other web site. When a user is tricked into clicking on a malicious link, submitting a

specially crafted form, or even just browsing to a malicious site, the injected code travels to the

vulnerable web site, which reflects the attack back to the user’s browser. The browser then executes the

code because it came from a "trusted" server. Reflected XSS is also sometimes referred to as Non-

Persistent or Type-II XSS.

Page 5: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

5

Prevention:

Escaping XSS:

Escaping user input can be done by using the escape_special function to change characters that are not

allowed (usually <, >, &, and ") into characters that are allowed as input. The output displayed on a page

can also be escaped to prevent visitors to your site from being victimized by XSS attacks launched from

your site. For example, turning <script> into &lt;script&gt; disables an attackers ability to use your web

site to attack your visitors.

i.e & --> &amp

< --> &lt;

> --> &gt;

" --> &quot;

' --> &#x27;

/ --> &#x2F;

Validation is even easier. Validation makes sure the input is legal. You can whitelist input, for example

only allowing a text string or you can validate legal input is by blacklisting. In a scenario where

blacklisting is used, if your site request a text string, you can blacklist numbers and special characters as

input.

We can also use ESAPI implementation for Encoding and Decoding HTML Entities.

String Safe = ESAPI.encoder().encodeForHTMLAttribute(request.getParameter(“input”));

Html Entity Encoding:

This technique has the advantage that html entity escaping is widely supported and helps separate data

from server side code without crossing any context boundaries. Consider placing the JSON block on the

page as a normal element and then parsing the innerHTML to get the contents. The javascript that reads

the span can live in an external file, thus making the implementation of CSP enforcement easier.

<script id="init_data" type="application/json">

<%= html_escape(data.to_json) %>

</script>

Page 6: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

6

For external JS file,

var dataElement = document.getElementById('init_data');

// unescape the content of the span

var jsonText = dataElement.textContent || dataElement.innerText

var initData = JSON.parse(html_unescape(jsonText));

Filtering XSS:

All XSS attacks infect your web site via some form of User Input. XSS attack code could come from a

simple <FORM> submitted by your users, or could take a more complex route such as a JSON script, XML

web service or even an exploited cookie. In all cases the web developer should be aware that the data is

coming from an external source and therefore must not be trusted.

The simplest and arguably the easiest form of XSS protection would be to pass all external data through

a filter which will remove dangerous keywords, such as the infamous <SCRIPT> tag, JavaScript

commands, CSS styles and other dangerous HTML markup (such as those that contain event handlers.)

Below is a diagram visually representing the internet boundary and where filtering and escaping must

happen to ensure XSS protection.

Page 7: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

7

Cross Frame Scripting (CSRF): Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, email, blog,

instant message, or program causes a user’s Web browser to perform an unwanted action on a trusted

site for which the user is currently authenticated.

The impact of a successful cross-site request forgery attack is limited to the capabilities exposed by the

vulnerable application. For example, this attack could result in a transfer of funds, changing a password,

or purchasing an item in the user's context. In effect, CSRF attacks are used by an attacker to make a

target system perform a function (funds Transfer, form submission etc.) via the target's browser without

knowledge of the target user, at least until the unauthorized function has been committed.

Page 8: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

8

Prevention

Using a Secret Cookie

Remember that all cookies, even the secret ones, will be submitted with every request. All

authentication tokens will be submitted regardless of whether or not the end-user was tricked into

submitting the request. Furthermore, session identifiers are simply used by the application container to

associate the request with a specific session object. The session identifier does not verify that the end-

user intended to submit the request.

Only Accepting POST Requests

Applications can be developed to only accept POST requests for the execution of business logic. The

misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be

executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can

trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's

Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered

by the victim who thinks the form will do something else.

Multi-Step Transactions

Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or

deduce each step of the completed transaction, then CSRF is possible.

URL Rewriting

This might be seen as a useful CSRF prevention technique as the attacker cannot guess the victim's

session ID. However, the user’s credential is exposed over the URL.

Challenge-Response

Challenge-Response is another defense option for CSRF. The following are some examples of challenge-

response options.

CAPTCHA

Re-Authentication (password)

One-time Token

While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does

impact user experience. For applications in need of high security, tokens (transparent) and challenge-

response should be used on high risk functions.

Page 9: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

9

For the application in .NET or MVC we have separate NuGet package for preventing CSRF vulnerabilities,

Following steps are needs to perform for installing the NuGet packages,

#1

Page 10: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

10

#2

#3

#4

Implementation in Code,

Page 11: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

11

Weak Session Management: Authentication and session management includes all aspects of handling user authentication and

managing active sessions. While authentication itself is critical aspect to secure, even solid

authentication mechanisms can be undermined by flawed credential management functions, including

password change, "forgot my password", "remember my password", account update, and other related

functions. Because "walk by" attacks are likely for many web applications, all account management

functions should require re-authentication even if the user has a valid session id, in case an attacker has

discovered a session where the original user has failed to log out.

Usually the Session Management follows the below flow:

Let’s consider simple supplier-consumer application,

Supplier-Consumer Flow

Page 12: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

12

So this is the basic flow for the client and server. The hacker can able to tamper your session id if it was

not secured and can shop instead of you.

Let’s consider a simple application with Sessions.

When user enter the user name and password

He has successfully login to the page.

From there Page2. After he logs out.

Page 13: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

13

The ASP.NET Session Id will be still available in the Client side as well as Server Side.

While using the Tampering Data Tools we can intercept the same Session Id which is taken from the

John Smith Session and reproduce the same page without login.

Page 14: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

14

In ASP.NET, session state is a pretty simple concept,

Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table,

e.g. key-value pairs, which can be set and read for the duration of a user's session.

If we are set value in Page render or anywhere in that application,

protected void Page_PreRender(object sender, EventArgs e) { Session["Test"] = test; }

We can remove the Session in many ways,

protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { Session.Contents.Remove("Test"); Session.Abandon(); Session.Clear(); Session.Remove("Test"); Session.RemoveAll(); } else { test = true; // Set at the PageLoad the var to true. } }

All the Method above will clear the session in the Client Side. But still the Server Side Session will be

active.

To Clear the Server Side Session we can use the following code in EndSession,

[WebMethod()] public static void EndSession() { HttpContext.Current.Session.Abandon(); }

We can also clear the session in Ajax or Javascript like below,

<script> window.onbeforeunload = function (e) { Logout(); }; </script>

Page 15: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

15

While logging off or closing the browser the above script will call the Logout() function and the function

will reach the server before the browser is closed.

function Logout { { $.ajax({ url: "/Logout/SessionAbandon", type: "POST", dataType: "json", data: true, success: function (data) { if (data) { alert("Session will get Cleared Completely."); } else { alert("Session not cleared"); } }, });

PS:

If you have SSO Configured in your application then you need to follow the below steps to clear all the

sessions. We need to change the Configuration file in the Server where SSO has been deployed.

These are the two files are need to change the settings, Webagent.conf and SmHost.conf

In those config files we need to change the UseSecureCookies as “yes”.

Page 16: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

16

Denial of Service: In a denial-of-service (DoS) attack, an attacker attempts to prevent legitimate users from accessing

information or services. By targeting your computer and its network connection, or the computers and

network of the sites you are trying to use, an attacker may be able to prevent you from accessing email,

websites, online accounts (banking, etc.), or other services that rely on the affected computer.

The most common and obvious type of DoS attack occurs when an attacker "floods" a network with

information. When you type a URL for a particular website into your browser, you are sending a request

to that site's computer server to view the page. The server can only process a certain number of

requests at once, so if an attacker overloads the server with requests, it can't process your request. This

is a "denial of service" because you can't access that site.

The hackers follow many methods in DOS to hack the system,

Ping Flooding:

Ping flood works by sending the target an overwhelming number of ping packets, usually using

the "ping" command. It is very simple to launch and by creating traffic that exceeds the web site’s

bandwidth availability, the attack is a success.

Peer-to-peer attacks:

Peer-to-Peer attacks are launched when the attacker causes users to disconnect from their

peer-to-peer network and to connect to the victim’s website instead.

Page 17: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

17

Application level floods:

While most Denial of Service attacks exploit bandwidth, some rely on software related exploits

such as buffer overflows. These attacks cause confusion in the application causing it to fill the disk space

or consume all available memory or CPU cycles.

Simple programming might be effective for Denial of Service Attack:

for( int i = 0; i < 100000; i ++ )

{

WebClient client = new WebClient();

client.DownloadString("http://www.myapplication/page.aspx");

}

In your great surprise, you will notice that, after a couple of call, you don't get valid response. It’s not

that you have succeeded in bringing down the server.

Prevention:

Denial of Service attacks is often random when they are launched against small and medium sized web

sites. When a web site is attacked that does not fall into the category of a high profile target (large

corporation, government site, or activist site), the reason usually falls within one or more of the

following categories:

• Grudge: An unscrupulous competitor or disgruntled former business partner or employee may

wish to cripple a business's Web site for the purpose of financial gain or revenge.

• Name Confusion: The Web site's name may closely resemble one used by a well-known

enterprise or personality.

• Easy Target: Most mega-corporations have already installed anti-DoS safeguards — such as

security technologies and extra server and connectivity power — on their sites. Smaller

businesses, with fewer resources at their disposal, are tempting targets for DoS attackers,

especially those looking to hone their skills.

• Bad Luck: Sometimes there's no apparent reason for a DoS attack. An attacker may simply pick a

business's domain at random, or because they like the sound of its name or the way it looks.

Attackers, by nature, can be highly irrational.

Basic steps or basic remediation that we can do to avoid Denial of Service are:

•Install and maintain anti-virus software.

•Install a firewall, and configure it to restrict traffic coming into and leaving your comp.

Page 18: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

18

•Follow good security practices for distributing your email. Applying email filters may help you manage

unwanted traffic.

Pattern Recognition: The Pattern Recognition web application security engine employed by

dotDefender effectively protects against malicious behavior such as Denial of Service attacks. The

patterns are regular expression-based and designed to efficiently and accurately identify a wide array of

application-level attack methods.

Code wise Restriction:

We can also restrict the application code wise but we can able to restrict with some limitations.

First step to identifying the Client Ip Address,

public static bool IsValid( ActionTypeEnum actionType ) { HttpContext context = HttpContext.Current; if( context.Request.Browser.Crawler ) return false; string key = actionType.ToString() + context.Request.UserHostAddress; HitInfo hit = (HitInfo)(context.Cache[key] ?? new HitInfo()); if( hit.Hits > (int)actionType ) return false; else hit.Hits ++; if( hit.Hits == 1 ) context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); return true; }

The key variable will have the user ip address and also it will count how many hits that particular IP

Address is hitting to our server.

protected override void OnInit(EventArgs e) { base.OnInit(e); // Check if revisit is valid or not if( !base.IsPostBack ) { // Block cookie less visit attempts if( Profile.IsFirstVisit ) { if(!ActionValidator.IsValid(ActionValidator.ActionTypeEnum.FirstVisit) Response.End(); } else

Page 19: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

19

{ if(!ActionValidator.IsValid(ActionValidator.ActionTypeEnum.ReVisit) ) Response.End(); } } else { // Limit number of postbacks if( !ActionValidator.IsValid(ActionValidator.ActionTypeEnum.Postback) Response.End(); } }

Using the above code we can identify the user whether he/she is first visit or Re-Visit or Post back to

our application.

We can then set the definition for users like how many times the user allowed for Revisit or first visit.

public enum ActionTypeEnum { None = 0, FirstVisit = 100, // The most expensive one, choose the value wisely. Revisit = 1000, // Welcome to revisit as many times as user likes Postback = 5000, // Not must of a problem for us AddNewWidget = 100, AddNewPage = 100, }

PS:

But even this coding technique has some restrictions, if the hacker generate a random IP Address

through UNIX coding then this code won’t prevent the Denial of Service attack because each time the

server hit by a New IP Address.

Page 20: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

20

Form Manipulation: Form manipulation is one of web parameter tampering attacks and is a kind of input validation

vulnerability. The vulnerability can be exploited on integrity and logic validation. Mechanism errors,

which can result in other consequences including XSS, SQL Injection, file inclusion, and path disclosure

attacks.

When a web application uses hidden fields to store status information, a malicious user can tamper with

the values stored on his browser and change the referred information. For example, an e-commerce

shopping site uses hidden fields to refer to its items, as follows:

<input type=”hidden” id=”1008” name=”cost” value=”70.00”>

In this example, an attacker can modify the “value” information of a specific item, thus lowering its

cost.

Manipulating the data sent between the browser and the web application to an attacker's advantage

has long been a simple but effective way to make applications do things in a way the user often

shouldn't be able to. In a badly designed and developed web application, malicious users can modify

things like prices in web carts, session tokens or values stored in cookies and even HTTP headers.

No data sent to the browser can be relied upon to stay the same unless cryptographically protected at

the application layer. Cryptographic protection in the transport layer (SSL) in no way protects one from

attacks like parameter manipulation in which data is mangled before it hits the wire. Parameter

tampering can often be done with:

Cookies

Form Fields

URL Query Strings

HTTP Headers

Cookie Manipulation:

Cookies are the preferred method to maintain state in the stateless HTTP protocol. They are however

also used as a convenient mechanism to store user preferences and other data including session tokens.

Both persistent and non-persistent cookies, secure or insecure can be modified by the client and sent to

the server with URL requests. Therefore any malicious user can modify cookie content to his advantage.

There is a popular misconception that non-persistent cookies cannot be modified but this is not true. SSL

also only protects the cookie in transit.

The extent of cookie manipulation depends on what the cookie is used for but usually ranges from

session tokens to arrays that make authorization decisions. (Many cookies are Base64 encoded; this is

an encoding scheme and offers no cryptographic protection).

Page 21: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

21

Example let our cookies will be like this,

Cookie: lang=en-us; ADMIN=no; y=1 ; time=10:30GMT ;

The attacker can simply modify the cookie to,

Cookie: lang=en-us; ADMIN=yes; y=1 ; time=12:30GMT ;

HTTP Header Manipulation:

HTTP headers are control information passed from web clients to web servers on HTTP requests and

from web servers to web clients on HTTP responses. Each header normally consists of a single line of

ASCII text with a name and a value. Sample headers from a POST request follow.

Host: www.someplace.org

Pragma: no-cache

Cache-Control: no-cache

User-Agent: Lynx/2.8.4dev.9 libwww-FM/2.14

Referrer: http://www.someplace.org/login.php

Content-type: application/x-www-form-urlencoded

Content-length: 49

Often HTTP headers are used by the browser and the web server software only. Most web applications

pay no attention to them. However some web developers choose to inspect incoming headers, and in

those cases it is important to realize that request headers originate at the client side, and they may thus

be altered by an attacker.

Form Field Manipulation:

When a user makes selections on an HTML page, the selection is typically stored as form field values and

sent to the application as an HTTP request (GET or POST). HTML can also store field values as Hidden

Fields, which are not rendered to the screen by the browser but are collected and submitted as

parameters during form submissions.

Whether these form fields are pre-selected (drop down, check boxes etc.), free form or hidden, they can

all be manipulated by the user to submit whatever values he/she chooses. In most cases this is as simple

as saving the page using "view source", "save", editing the HTML and re-loading the page in the web

browser.

Page 22: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

22

The hackers or even user can enter the malicious data into the text box field which saves in to the

database without validating in the frontend.

Take the same application. Behind the login form may have been the HTML tag,

<input name="masteraccess" type="hidden" value="N">

By manipulating the hidden value to a Y, the application would have logged the user in as an

Administrator. Hidden form fields are extensively used in a variety of ways and while it's easy to

understand the dangers they still are found to be significantly vulnerable in the wild.

URL Manipulation:

URL Manipulation comes with all of the problems stated above about Hidden Form Fields, and creates

some new problems as well.

HTML Forms may submit their results using one of two methods: GET or POST. If the method is GET, all

form element names and their values will appear in the query string of the next URL the user sees.

Tampering with hidden form fields is easy enough, but tampering with query strings is even easier. One

need only look at the URL in the browser's address bar.

Say for example,

http://www.mybank.com/example?accountnumber=12345&debitamount=1

Can be modified as,

http://www.mybank.com/example?accountnumber=67891&creditamount=999999999

The new parameters would be sent to the application and be processed accordingly.

Page 23: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

23

Prevention:

We can prevent the vulnerabilities from different manipulations in the following ways.

Cookie Manipulation:

One common technique is to simply use one session token to reference properties stored in a

server-side cache. This is by far the most reliable way to ensure that data is sane on return:

simply do not trust user input for values that you already know. When an application needs to

check a user property, it checks the userid with its session table and points to the user’s data

variables in the cache / database. This is by far the correct way to architect a cookie based

preferences solution.

Send an encrypted cookie.

Using Timestamp identify the cookies are tampered or not.

Form Manipulation:

Using Regular Expression: using Regular expression as per need to the input field so that the

user can able to enter only the text that the text box needed.

We can validate the textbox using the Javascript file,

var regex = /^[a-zA-Z0-9 ]*$/; //Only Numeric and Alphabets accepted

if (regex.test($("Name").val())) { $("#Name").removeClass('errorHighlightText'); } else { $("Name").addClass('errorHighlightText'); errorMessage = errorMessage + "Special characters are not allowed in Name \n "; returnFlag = -1; }

Using Parameterized queries we can avoid the tampering of data in-between before the data

reaching to the server.

Instead of using queries like,

DataTable dt = SqlComm.SqlDataTable( "SELECT * FROM Users WHERE UserName = login.Text AND Password = password.Text ",);

Page 24: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

24

Use parameterized objects,

DataTable dt = SqlComm.SqlDataTable( "SELECT * FROM Users WHERE UserName = @UserName AND Password = @Password", new Dictionary<string, object> { { "UserName", login.Text }, { "Password", password.Text }, } );

Instead of using Select statement using Store Procedures.

When the values stored in the DB. Cross Check the value in DB Level.

Header Manipulation:

Simply put headers cannot be relied upon without additional security measures. If a header originated

server-side such as a cookie it can be cryptographically protected. If it originated client-side such as a

referrer it should not be used to make any security decisions.

URL Manipulation:

Solving URL manipulation problems takes planning. Different techniques can be used in different

situations. The best solution is to avoid putting parameters into a query string.

Avoid Parameterized Query String.

If a sensitive parameter cannot be removed from a URL, it must be cryptographically protected.

Cryptographic protection can be implemented in one of two ways. The better method is to

encrypt an entire query string (or all hidden form field values). This technique both prevents a

user from setting the value and from seeing the value.

Page 25: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

25

Transport Layer Protection: (TLS) Transport Layer Security (TLS) is a protocol that ensures privacy between communicating applications

and their users on the Internet. When a server and client communicate, TLS ensures that no third party

may eavesdrop or tamper with any message. TLS is the successor to the Secure Sockets Layer (SSL).

TLS is composed of two layers: the TLS Record Protocol and the TLS Handshake Protocol. The TLS Record

Protocol provides connection security with some encryption method such as the Data Encryption

Standard (DES). The TLS Record Protocol can also be used without encryption. The TLS Handshake

Protocol allows the server and client to authenticate each other and to negotiate an encryption

algorithm and cryptographic keys before data is exchanged.

Major drawback without Secured Transport layer is Man in Middle Attack. The Hackers can collection

information before it reaches to server.

By implementing a Secure Layer in-between the client and server. The hackers can’t identify or collect

the information because all the information that hacker received are encrypted and non-understandable

format.

To facilitate SSL or TLS encryption between any two computers, an X.509 Digital Certificate is required

on at least one end of the connection. The Digital Certificate is usually installed at the Server end

because it makes it simple for any end user to make a secure SSL or TLS connection to the server

without a Digital Certificate on the client end. A trusted third party called a CA (Certificate Authority)

asserts the authenticity of the Digital Certificate with a Digital Signature so that the client knows that the

Server isn't fake. This trust comes from the fact that these Certificate Authorities have their Root

Certificates with Public Keys pre-installed in every nearly every Operating System and Application on the

market.

Page 26: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

26

Digital Certificate:

The Certificate Authority will have to verify that you're authorized to buy a certificate for the domain

name that you're requesting and they do this by sending email verification to the administrator of the

domain listed under whois.

The certificate will be like this,

You can take that entire chunk of text and paste it in to a text file called MyCertificate.txt. Once it's

pasted, you'll want to rename it to MyCertificate.cer or anything ending with the ".cer" extension. This

way you can immediately open it in Windows and it will look like the following.

Page 27: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

27

Now Installing the Digital Certificate,

Once you've created the Digital Certificate by cutting/pasting it in to a text file and you've renamed it

with a .cer extension, you'll need to install that Digital Certificate on the machine you generated the CSR

on before you can ultimately export it.

To begin, you'll need to open an MMC console by clicking Start | Run. Then type "mmc" and OK. You'll

need to do a UAC escalation and you will see the following console appear. From there, you'll click

"ADD/Remove Snap-in."

Page 28: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

28

You'll then see this screen where you will need to select Certificates and hit the "Add" button.

Click "Computer account" and hit "Next".

Select "Local computer" and click "Finish".

Page 29: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

29

Next you'll expand out the Certificate Console and Import the Certificate

Hit next on the Certificate Import Wizard

Page 30: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

30

Browse or type in the name of the Certificate you purchased. Hit "Next".

Hit "Next". Then hit "Finish" on the following screen.

Page 31: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

31

Now we can Export the Digital Certificate,

The newly exported Digital Certificate will contain both the Public Key and the Private Key which means

it can be installed on any number of Servers that will host your secure application. So long as the Server

is being used for the same purpose or hosting the same website, you can use an identical Digital

Certificate on as many Servers as you like. You will need to carefully protect this file containing the

Public and Private Key keeping it secret since anyone who possesses the Private Key can decrypt.

To export the Certificate along with the Private Key, right click on the Certificate you purchased shown in

the screen shot below and choose "All Tasks" and "Export".

Page 32: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

32

Hit "Next" at the Certificate Export Wizard screen.

Here you'll need to select the "export the private key" option

Page 33: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

33

Hit next on the following screen. You might want to choose the "Delete the private key if the export is

successful" option because you don't want to leave this Certificate and Private Key on this computer.

Ultimately the Certificate needs to be transferred to the Server that will use it.

Page 34: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

34

You'll have to type a password to secure this Certificate. Be sure to remember it because you won't be

able to import this Certificate if you don't know the password.

Next you'll need to pick a filename for the Certificate

Next you'll hit the "Finish" button

Page 35: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

35

Since the Certificate doesn't belong on our workstation, we can delete the Certificate along with the

Private Key. Simply highlight the Certificate shown below and click the red X button that I circled.

Now that we have the exported Digital Certificate containing the Private Key, we can transfer that to any

number of Servers that will be using the Common Name we selected for our Digital Certificate.

Page 36: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

36

Secure Session Flag: Cookies are a useful mechanism for managing state in web applications but are often configured in a

non-secure fashion. The purpose of the secure flag is to prevent cookies from being observed by

unauthorized parties due to the transmission of the cookie in clear text.

To accomplish this goal, browsers which support the secure flag will only send cookies with the secure

flag when the request is going to a HTTPS page. Said in another way, the browser will not send a cookie

with the secure flag set over an unencrypted HTTP request.

If we already implement the Transport Security Layer then it is simple way to make our application has a

secure one with simple single line of coding in Web.Config file.

<httpCookies requireSSL="true" />

However, during User authentication, I get the following exception thrown when calling

System.Web.Security.FormsAuthentication.SetAuthCookie():

Then you also need to configure in authentication tag in Web.Config file,

<httpCookies httpOnlyCookies="true" requireSSL="true" />

You’ll also need to add HTTPS to the list of allowedServerVariables in the applicationHost.config (or

through the URL Rewrite config), If still the SSL is not working with the Web.Config file changes.

<rewrite>

<allowedServerVariables>

<add name="HTTPS" />

</allowedServerVariables>

</rewrite>

Page 37: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

37

ClickJacking/Cross Frame Scripting (XSF): Cross-Frame Scripting (XFS) is an attack related to cross-site scripting (XSS) and is commonly

misunderstood from both offensive and defensive standpoints.

XFS exploits a bug in specific browsers that allows a parent frame to be exposed to events in an

embedded iFrame inside of it. The exposure is limited to events only, and does not give full JavaScript

cross domain access.

Frame busting is the act of preventing another site from including your site in an iFrame on their site.

This is commonly done via JavaScript with code such as:

Let’s have an example that how the Cross Frame Scripting attacks cause the vulnerability to the

application.

We have application with the Parent Page.

In summary, there are 3 HTML pages are involved here,

Page Name Description

Parent.Html The top level frame which load the frames.

Topframe.html The top frame which may be hosting your third party application.

Bottomframe.html The bottom frame which may be hosting your in-house application.

Page 38: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

38

Parent.Html

<html> <frameset rows="25%,75%"> <frame name="topframe" src="TopFrame.html" /> <frame name="bottomframe" src="BottomFrame.html" /> </frameset> </html>

Topframe.Html

<html> <head> <script language="javascript"> document.write("Top Frame - domain is <b>"+ document.domain + "</b>"); </script> </head> <body> <!-- Let's get the policy number as input manually since it is not a real world call application--> <form> Policy Number : <input type="text" id="policyNumber"/><br/> <input name="Submit" value="submit" type="button" onclick="top.bottomframe.processCall(policyNumber.value)" /> </form> </body> </html>

Bottomframe.Html

<html> <head> <script language="javascript"> document.write("Bottom Frame - domain is <b>"+ document.domain + "</b>"); function processCall(policyNumber) { alert("The policy number received by bottom frame is :"+ policyNumber); } </script> </head> </html>

Here top is a Javascript keyword which denotes the parent, in our case it is Parent.html. The

document.domain provides the domain name of the resource. To mimic the incoming call I have placed

a text field where you can type the policy number and then submit which should call the bottom frame

with the policy number.

The processCall() JavaScript function will be called by the top frame and the call will be only successful if

both frames are from the same domain. Let’s start by deploying the HTML as a web app using your

favorite’s web container. When you run locally you can see that the document.domain comes as

Page 39: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

39

localhost since the URL begins with localhost. Here the top and bottom frames are from the same

domain (i.e. localhost) the browser has no issues allowing the cross frame scripting.

So while clicking the submit button we get the policy number in a different frame.

Prevention:

Cross Frame Scripting can be prevented by many ways but it is simple to avoiding the frame scripting in

our application. So using javascript itself we can avoid the multiple framing using in the application.

#1

#2

void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("x-frame-options", "DENY"); }

By the way blocking the frames we can avoid the leakage of private data to others.

Page 40: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

40

Information Disclosure: The information disclosure is simply say like leakage of information. It is not going to make you full

secure but make the server type harder to identify for the hackers.

We do this not because any one single piece of information is going to bring us undone, but rather we

try not to broadcast anything which may be used to take advantage of us.

The above information in the image shows you the type of server that application is using and

application is developed with the version and along with IIS details.

There are plenty of ways available to clear this information in the response headers, let’s have a look

one by one.

Page 41: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

41

To Remove X-Powered-By Header tag we can use the following ways,

We can also remove this through coding,

<system.web> <httpRuntime enableVersionHeader="false" /> </system.web>

Page 42: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

42

MVC Version Header:

For removing MVC Version Header we need add coding in the Global.asax file in the Application_Start

event.

protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; }

Removing ASPNet Version:

To remove ASPNet Version we need to add a header tag in the web.config file.

<system.web>

<httpRuntime enableVersionHeader="false" />

</system.web>

Removing Server version:

To remove the Server version that is lots and lots of way to do that, Removing server is one of the

toughest part in the Information Disclosure. Because it is not that simple to remove the Server Header

from the Response Header like the above tags.

There are many possible ways to remove header. Some might works and some might not works due to

the conditions of your application.

PreSendrequestHeader Tag:

You need to create an HTTP Module that creates an event handler for the PreSendRequestHeaders

event. In that event handler you'd write code similar to the following to remove the Server header:

HttpContext.Current.Response.Headers.Remove("Server");

Http Module:

Creating the class with the Server tag as a module.

public class IDHttpHeaderModule : IHttpModule { private List<string> headersToCloak; public IDHttpHeaderModule() {

Page 43: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

43

this.headersToCloak = new List<string> { "Server", }; } }

Then during the application initialization calling this header module in the application.

private void OnPreSendRequestHeaders(object sender, EventArgs e) { this.headersToCloak.ForEach(h =>HttpContext.Current.Response.Headers.Remove(h)); }

Jquery Web Activator:

Installing the Jquery Webactivator Tool from Jquery Plugin will remove the Server header from the

Response header tag.

Begin Request:

void Application_BeginRequest (object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("x-frame-options", "DENY"); var application = sender as HttpApplication; if (application != null && application.Context != null) { application.Context.Response.Headers.Remove("Server"); Response.Headers.Remove("Server"); } }

Registry Key:

Create a DWORD entry called DisableServerHeader in the following Registry key and set the value to 1.

HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters

Page 44: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

44

After adding the Registry key, restart the HTTP service using the net stop http command and the

net start http command. If the HTTP service doesn’t start up then use the iisreset command. If

that also doesn’t work then you can restart the server.

Please note that this method is used only when the Server header comes as “Microsoft-

HTTPAPI/2.0”.

When the request comes to IIS, it is first goes to http.sys driver. HTTP.SYS driver either handle

the request on its own or send it to User mode for further processing. When the request goes to

User mode that’s the time it returns the server header as “Microsoft-IIS/7.5.”.

However when the request returns from the HTTP.SYS driver then the server header comes as

“Microsoft-HTTPAPI/2.0”. By placing the above registry key it will remove this specific header.

URL Scan:

We need to install the URL Scan tool from website. After installing URLScan, open the

URLScan.ini file typically located in the %WINDIR%\System32\Inetsrv\URLscan folder. After

opening it, search for the key RemoveServerHeader . By default it is set to 0, but to remove the

Server header, change the value to 1.Doing so will remove the Server header Server: Microsoft-

IIS/7.5 from the User mode response.

Page 45: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

45

Request Filtering Module:

For removing Header, using request filtering module which is the part of IIS.

PS:

All the method above will remove the Server Tag in Response header for only IIS 6.0+ and also only to

the Integrated Pipeline mode. The Classic mode won’t support all those method and we can’t remove

the Server Tag in Classic mode for inbuilt security reason in IIS.

Page 46: Security Implementation in Web Applications · is an example of an application layer vulnerability, which can result in input attacks. Attack: An attack is an action that exploits

46

Email Addresses Disclosed: Email addresses of developers and other individuals (whether appearing on-screen or hidden within

page source) may disclose information that is useful to an attacker.

E-mail addresses discovered within the application can be used by both spam email engines and also

brute force tools. Furthermore valid email addresses may lead to social engineering attacks.

Prevention:

Use generic email addresses such as contact@ or info@ for general communications, remove

user/people specific e-mail addresses from the web site, should this be required use submission forms

for this purpose.

Conclusion:

So every developer or Programmer targeting to achieve 100% secured web application. Hope this

document helps you in achieving some percentages in that target.


Recommended