securing asp.net mvc 5 web applications

46
Independent project in Computer Science Securing ASP.NET MVC 5 Web Applications Preventing and Mitigating 7 Major Hacker Attacks Author: Martin Åhlin Instructor: John Häggerud, Johan Leitet, Mats Loock Examiner: Johan Leitet Date: 2014-06-10 Subject: Computer Science Level: University Diploma Course code: 1DV42E

Upload: martin-ahlin

Post on 16-Jul-2015

613 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Securing ASP.NET MVC 5 Web Applications

Independent project in Computer Science

Securing ASP.NET MVC 5

Web Applications

Preventing and Mitigating 7 Major Hacker Attacks

Author: Martin Åhlin

Instructor: John Häggerud, Johan

Leitet, Mats Loock

Examiner: Johan Leitet

Date: 2014-06-10

Subject: Computer Science

Level: University Diploma

Course code: 1DV42E

Page 2: Securing ASP.NET MVC 5 Web Applications

i

Abstract

Security of web applications is an ever increasing subject, both in importance and in

scope. With every new feature on a web site, new vulnerabilities may appear that could

be exploited by hackers. Caution, research and best practices are paramount in the work

to secure the application.

This paper describes, stops and mitigates seven of the major hacker attacks that can

occur on an ASP.NET MVC 5 web application while mainly using the available

functions inside the framework. Attacks are simulated in experiments along with the

corresponding counter-measures that result in easy-to-implement solutions and code for

the ASP.NET MVC web application.

Key Words

asp.net, security, hacker, attack, vulnerability, xss, csrf, owasp, cwe, 7pk

Page 3: Securing ASP.NET MVC 5 Web Applications

ii

Contents

1 Introduction _________________________________________________________ 1

2 Background _________________________________________________________ 1 2.1 Purpose _________________________________________________________ 1 2.2 Question ________________________________________________________ 2

2.3 Previous research _________________________________________________ 2 2.3.1 Microsoft ____________________________________________________ 2

2.3.2 Seven Pernicious Kingdoms (7PK) ________________________________ 3

2.3.3 OWASP Top Ten ______________________________________________ 4

2.3.4 CWE/SANS Top 25 ____________________________________________ 5

3 Method _____________________________________________________________ 5 3.1 Experiment as method _____________________________________________ 5 3.2 Choosing procedure for hacker attacks ________________________________ 6

3.2.1 Prioritization _________________________________________________ 6

3.3 Final selection of hacker attacks ______________________________________ 7

3.4 Whitebox testing __________________________________________________ 7 3.5 Experiment environment ___________________________________________ 7

3.5.1 Local Windows version _________________________________________ 8

3.5.2 Local Server version ___________________________________________ 8

3.5.3 Database Version _____________________________________________ 8

3.5.4 net MVC Web Application configuration ___________________________ 8

3.5.5 Prior knowledge ______________________________________________ 8

3.6 Result logging ____________________________________________________ 8

3.7 Method discussion ________________________________________________ 9 3.7.1 Internal Validity _______________________________________________ 9

3.7.2 External Validity ______________________________________________ 9

3.7.3 Reliability ___________________________________________________ 9

4 Result _____________________________________________________________ 10 4.1 Object Binding Vulnerability _______________________________________ 10

4.1.1 Theory _____________________________________________________ 10

4.1.2 Tested Attack Vector __________________________________________ 10

4.1.3 Results before amendments _____________________________________ 10

4.1.4 Required amendments _________________________________________ 10

4.1.5 Results after amendments ______________________________________ 11

4.1.6 Documentation ______________________________________________ 11

4.2 Dangerous Uploaded File Type Vulnerability __________________________ 12 4.2.1 Theory _____________________________________________________ 12

4.2.2 Tested Attack Vector __________________________________________ 12

4.2.3 Results before amendments _____________________________________ 12

Page 4: Securing ASP.NET MVC 5 Web Applications

iii

4.2.4 Required amendments _________________________________________ 12

4.2.5 Results after amendments ______________________________________ 13

4.2.6 Documentation ______________________________________________ 13

4.3 Excessive Authentication Attempts Vulnerability _______________________ 13 4.3.1 Theory _____________________________________________________ 13

4.3.2 Tested Attack Vector __________________________________________ 13

4.3.3 Results before amendments _____________________________________ 13

4.3.4 Required amendments _________________________________________ 13

4.3.5 Results after amendments ______________________________________ 14

4.3.6 Documentation ______________________________________________ 14

4.4 XSS Filter Evasion Vulnerability ____________________________________ 14 4.4.1 Theory _____________________________________________________ 14

4.4.2 Tested attack vector ___________________________________________ 14

4.4.3 Results before amendments _____________________________________ 15

4.4.4 Required amendments _________________________________________ 15

4.4.5 Deactivation of built-in defenses _________________________________ 15

4.4.6 Documentation ______________________________________________ 16

4.5 Inclusion of Third Party Scripts Vulnerability __________________________ 16 4.5.1 Theory _____________________________________________________ 16

4.5.2 Tested Attack Vector __________________________________________ 16

4.5.3 Results before amendments _____________________________________ 17

4.5.4 Required amendments _________________________________________ 17

4.5.5 Results after amendments ______________________________________ 17

4.5.6 Documentation ______________________________________________ 17

4.6 Cross-Site Request Forgery (CSRF) Vulnerability ______________________ 17 4.6.1 Theory _____________________________________________________ 17

4.6.2 Tested attack vector ___________________________________________ 18

4.6.3 Results before amendments _____________________________________ 19

4.6.4 Required amendments _________________________________________ 19

4.6.5 Results after amendments ______________________________________ 20

4.6.6 Documentation ______________________________________________ 20

4.7 Open Redirect Vulnerability ________________________________________ 20 4.7.1 Theory _____________________________________________________ 20

4.7.2 Tested attack vector ___________________________________________ 20

4.7.3 Results before amendments _____________________________________ 21

4.7.4 Required amendments _________________________________________ 21

4.7.5 Results after amendments ______________________________________ 21

4.7.6 Documentation ______________________________________________ 21

5 Discussion __________________________________________________________ 22

Page 5: Securing ASP.NET MVC 5 Web Applications

iv

5.1 Relying on external parties for the solution ____________________________ 22

5.2 Failed attacks ___________________________________________________ 22

5.3 General Impression _______________________________________________ 23

5.4 Areas of Improvement ____________________________________________ 23 5.5 Further research _________________________________________________ 23

6 References__________________________________________________________ 24

7 Appendices __________________________________________________________ I 7.1 Appendix A1 - Web application settings ________________________________ I

7.1.1 Contents of packages.config ______________________________________ I

7.1.2 Contents of Global.asax ________________________________________ II

7.1.3 Contents of Web.config _________________________________________ II

7.1.4 Contents of Startup.cs __________________________________________ IV

7.2 Appendix A2 - Object Binding Vulnerability Classes _____________________ V

7.2.1 Entities ______________________________________________________ V

7.2.2 Controller ___________________________________________________ VI

7.3 Appendix A3 - Dangerous Uploaded File Type Vulnerability Classes _______ VI 7.3.1 Controller ___________________________________________________ VI

7.3.2 Uploaded .aspx-file ___________________________________________ VII

7.4 Appendix A4 - Excessive Authentication Attempts Vulnerability Classes ___ VIII 7.4.1 Registration Logic ___________________________________________ VIII

7.4.2 Login Logic __________________________________________________ IX

7.5 Appendix A5 - XSS Filter Evasion Vulnerability Classes __________________ X

7.5.1 Controller ___________________________________________________ X

7.5.2 View ________________________________________________________ XI

7.6 Appendix A6 - Inclusion of Third Party Scripts Vulnerability Files _________ XII

7.6.1 Hosts-file ___________________________________________________ XII

7.7 Appendix A7 - CSRF Vulnerability Classes ___________________________ XII 7.7.1 Controller __________________________________________________ XII

7.7.2 AngularJS Code _____________________________________________ XIII

7.8 Appendix A8 - Open Redirect Vulnerability Classes ____________________ XIII 7.8.1 Controller _________________________________________________ XIII

Page 6: Securing ASP.NET MVC 5 Web Applications

1

1 Introduction

Security concerns are ever increasing on the web today even as the usage of the web

increases. More sensitive data is stored for every day which demands more security.

The community of web-developers all over the world has a common responsibility to

protect the users from malevolent hacker attacks; if not only for the many hours of

restoration work after an attack, then for the common credibility of their trade.

Hackers always have and always will try to find new ways of acquiring sensitive data.

While not answering the interesting question “Why hackers attack?”, this paper will

partially answer the questions “How they attack?” and more importantly “How can we

better protect ourselves from the attacks?”.

2 Background

2.1 Purpose

ASP.NET web-programmers rely heavily upon the built-in functions in the available

frameworks for authentication, authorization, anti-XSS, anti-CSRF and much more. As

long as no extra features are added to the site, besides the pre-installed ones, most

programmers, including the author would feel rather safe about the application’s

security. However, as soon as database related API’s, custom admin functions and input

user data are added, this feeling is replaced by an eery suspicion that there may be a

security hole left somewhere.

The purpose of this paper is to help ASP.NET web programmers in finding and taking

actions against software weaknesses that may occur when a web application grows

beyond the pre-installed basic functionality.

Whilst this is a very large subject to cover in any paper, the scope of this paper is

narrowed down to ASP.NET MVC 5 programmers. Further it will only touch on a

selection of the most common software vulnerabilities and their associated attack vector

variations.

No list is complete and no application is 100% safe, but by constantly having a security

oriented programming mentality in combination with knowledge of the main hacker

Page 7: Securing ASP.NET MVC 5 Web Applications

2

entry points, the web programmer can minimize the vulnerabilities of the web

application, which this paper has the ambition to assist in.

2.2 Question

How can an ASP.NET MVC 5 Web Application be protected against, or mitigate the

effects of, seven of the main hacker attacks?

2.3 Previous research

Vast amounts of literature and documents are available on the subject of web security.

An important step to take before beginning to examine this information is to find a

suitable categorization of the different kinds of threats and countermeasures and how

they relate to ASP.NET MVC 5.

2.3.1 Microsoft

Since ASP.NET MVC is a Microsoft project, it’s natural to begin at looking how they

have categorized it and what they are saying about their built-in defences and best

practices.

Web security related information can be found in, at least, three places within

Microsoft.

2.3.1.1 Microsoft Developer Network

MSDN is a very wide forum for Microsoft related technologies, covering everything

from XBOX to Windows Phone. They also have a section that covers web application

security. Here they divide the threats into six different categories, that collectively are

referred to as the acronym “STRIDE” [1]

Spoofing

Tampering

Repudiation

Information Disclosure

Denial of Service

Elevation of Privilege

Page 8: Securing ASP.NET MVC 5 Web Applications

3

Microsoft then gives valuable general advice and best practices on how to best protect

your application from these kinds of threats. Although these pieces of advice are very

helpful and should be observed by every programmer, they are not detailed enough to

give a full picture of how the different attacks are conducted, which is essential for any

closer examination. Nor do they directly relate to the MVC 5 framework and how these

threats are foiled or mitigated within this framework.

2.3.1.2 Microsoft ASP.NET

The ASP.NET web-site covers more specific security issues related to the MVC

framework [6]. It explains how to properly use the built-in authentication and

authorization features of MVC 5 as well as some in-depth studies on XSS and CSRF

attacks on the framework. There is also a thorough walkthrough of the OWASP Top

Ten [7] and how to properly defend against those attacks in an ASP.NET environment.

Although this walkthrough is from 2010 and does not focus on MVC 5 explicitly, it still

contains much helpful advice and best practices for the framework.

2.3.1.3 Microsoft SDL

Also worth mentioning is the Microsoft Security Development Lifecycle, which is a

software development process that brings attention to security issues throughout the

entire software project. This resource is more on a management level and does not apply

directly to the different kinds of vulnerabilities in an ASP.NET MVC 5 framework.

Nevertheless it brings attention to the fact that web security is not something that should

be padded on top of the software at the end of the project when all other aspects of the

software is ready. On the contrary, security design requirements, attack surface analysis

and reduction, threat modeling and many more security aspects should continuously be

iterated over throughout the development process.

2.3.2 Seven Pernicious Kingdoms (7PK)

In 2005 three authors from Fortify Software and Cigital joined forces and brought a new

taxonomy to software security errors called “Seven Pernicious Kingdoms” [2] or 7PK

for short. The purpose was to bring security thinking to programmers in an

approachable and meaningful way since they perceived the previous research and

categorization to be difficult to implement in everyday programming. Here the focus is

Page 9: Securing ASP.NET MVC 5 Web Applications

4

more on the technical implementation of common programming tasks. They bring

attention to common mistakes and vulnerabilities in the lives of programmers, which

has made it a popular and well-referenced document. The seven main categories are:

1. Input Validation and Representation

2. API Abuse

3. Security Features

4. Time and State

5. Errors

6. Code Quality

7. Encapsulation

There is also a complete catalogue of commented coding examples [3] based on 7PK for

many different languages, including C#, which makes it even more applicable for

programmers and relevant for this paper.

The advantages of 7PK is the practical categorization of threats and increased detail of

the vulnerabilities, when compared to Microsoft. The coding examples further give

concrete examples of common mistakes that makes valuable reading.

The disadvantage of 7PK, for the purpose of this paper, is that it touches on many areas

that are not applicable on an ASP.NET MVC 5 web application, for instance JAVA and

C++ specific vulnerabilities. The information therefore needs to be filtered before it can

be used according to the question formulation.

Towards the end of 7PK, the authors do a mapping of the vulnerabilities towards

OWASP top ten, which brings us to the next categorization.

2.3.3 OWASP Top Ten

OWASP, or Open Web Application Security Project, is a non-profit community driven

organization that is dedicated to increase web security. Their lists of the “Top Ten

Vulnerabilities” [4] are frequently referred to and should be studied by any programmer

with a focus on security. Updated lists are released on regular intervals, with the latest

version currently from 2013.

Page 10: Securing ASP.NET MVC 5 Web Applications

5

The advantage of OWASP Top Ten is that it’s completely focused on web applications,

it gives concrete examples of vulnerable code and preventions and it offers practical

“Cheat Sheets” for programmers in different languages, including C#.

The disadvantage, with respect to this paper, is that very little is added to what is

already mentioned by Microsoft, where in addition Microsoft is asp.net specific.

2.3.4 CWE/SANS Top 25

CWE, the Common Weakness Enumeration, is a community-developed dictionary of

software weaknesses, sponsored by the US Government. Among the community

companies are Apple, Fortify, Microsoft, SANS, Whitehat and many more [5].

The enumeration is extensive and constantly being revised and expanded. Its authority

in web security can be confirmed by the many referring links to the site’s enumerations,

including from OWASP Top 10 and 7PK Code Examples [3].

The Top 25 Most Dangerous Software Errors [8] is the result of the prioritization of

over 20 software security companies and lists the most widespread and critical errors

found in software today.

The described weaknesses go beyond mainstream vulnerabilities into more rare

situations and exploits and variations of attack vectors. Although these weaknesses

require filtering for the purpose of this paper and lack the clear categorization of the

other research above, they have proven the greatest benefit in finding potential

vulnerabilities in the ASP.NET MVC 5 web application not already documented by

Microsoft.

3 Method

3.1 Experiment as method

To answer the question how a hacker attack can be stopped or mitigated, an actual

ASP.NET MVC web application can be setup and actual attacks be performed against

Page 11: Securing ASP.NET MVC 5 Web Applications

6

the software vulnerability in question. Then, the results of the attack can be directly

measured before and after any documented amendments to the code.

The desired results of hacker attacks vary; some attacks result in stolen data, whilst

others result in denial of service, redirects, identity hijacking or various other outcomes.

They are all directly and concretely measurable in an experiment environment though,

so by going through the list of hacker attacks and documenting the results for each one,

the question in this paper can be answered.

3.2 Choosing procedure for hacker attacks

By going through the main hacker attacks from OWASP Top 10 [4], CWE Top 25 [8]

and 7PK [3], a sub selection of attacks can be acquired by using the following

questions:

1. Is it applicable to ASP.NET?

2. Is it a possible vulnerability in an ASP.NET MVC web application?

3. Is it possible to stop or mitigate from within the ASP.NET MVC web

application?

Questions 1 and 2 must be positive, whereas question 3 may not. Question 3 may also

require more thorough investigation before answering. Some attacks are stopped at the

IIS, some can only be stopped by changing the behavior of the users. The point of

question 3 is to choose attacks and countermeasures that are limited to the scope of the

web application. The answer should be “Yes”, or “Partially”, but even if the answer is

“No” after investigation, the answer and it’s accompanying research and experiment

still have value and may be included in the paper.

3.2.1 Prioritization

Since time does not allow for all possible hacker attacks to be tested, even in the sub-

selection above, a prioritization must be done. This will be based upon the following

criteria:

1. Frequency of vulnerability: An estimated high frequency gives a higher

prioritization.

Page 12: Securing ASP.NET MVC 5 Web Applications

7

2. Feasibility of prevention and mitigation: No existing solutions or no available

best practices within ASP.NET MVC give a lower prioritization. This is the

same as answering “No” to question 3 above.

3.3 Final selection of hacker attacks

The result of the selection process was:

1. Object Binding Vulnerability

2. Dangerous Uploaded File Type Vulnerability

3. Excessive Authentication Attempts Vulnerability

4. XSS Filter Evasion Vulnerability

5. Inclusion of Third Party Scripts Vulnerability

6. CSRF Vulnerability

7. Open Redirect Vulnerability

3.4 Whitebox testing

For a hacker to search for possible vulnerabilities from outside of a web application

without access to its source code is considered blackbox testing. Chances are then that

the hacker will never find a particular vulnerability in the web application. The purpose

of this paper however, is to test against known vulnerabilities in the code and how to

protect against potential hacker attacks. Therefore the attacks shall be performed with

full knowledge of the source code to allow for maximum exposure of the vulnerability,

as in a worst-case-scenario. This is considered whitebox testing. If the attack is still

stopped or mitigated, it shall have greater value than by simulating blackbox testing.

For each hacker attack a vulnerability in the code shall be exposed, either by the default

settings of the feature in question or by deliberately opening it up in a simulated

programming scenario.

3.5 Experiment environment

The environment is a standard installation of an ASP.NET MVC 5 web application via

Visual Studio 2013. Support for webapi and SignalR has been added to allow for their

Page 13: Securing ASP.NET MVC 5 Web Applications

8

associated vulnerabilities. The application is also installed on Microsoft Azure to allow

on-line testing. Both the local and online version use the same database on Azure.

3.5.1 Local Windows version

Windows 8.0

3.5.2 Local Server version

IIS Express 8.0

3.5.3 Database Version

Windows Azure SQL Database

3.5.4 net MVC Web Application configuration

ASP.NET MVC 5.0

Webapi 2.0

SignalR 2.0.3

Razor 3.0

The complete contents of packages.config, Global.asax, Web.config and Startup.cs can

be found in Appendix A1

3.5.5 Prior knowledge

The procedure of the experiments and the nature of the results require knowledge in the

ASP.NET MVC 5 framework in order to be properly understood, executed and

interpreted. The exact configuration of the Router, Entity Framework and the location of

Views and Models are therefore not explicitly described in the experiments, but should

be derived with knowledge of the framework. Only the classes and code that require

amendment or that play an active role in the attacks are given in detail.

3.6 Result logging

Depending on the type of attack the results will be logged in one of the following ways:

SQL Database

Filesystem

Page 14: Securing ASP.NET MVC 5 Web Applications

9

HTTP transfers

Cookie content

3.7 Method discussion

3.7.1 Internal Validity

Hacker attacks come in many different forms and variations, even within the same

category. For instance, there are endless variations of XSS attacks and even though an

experiment shows how to successfully foil one type of XSS attack, the application is not

immune to all XSS attacks. It’s enough to change one experiment parameter, either on

the application or on the attack, to completely change the result.

The validity of each experiment and how it answers this paper’s question, is therefore

limited to the specific attack vector used in the specific experiment environment.

3.7.2 External Validity

3.7.2.1 Within ASP.NET MVC

Given the prior knowledge to understand and evaluate the experiments, it’s a small step

for an ASP.NET MVC programmer to test for and amend these vulnerabilities on other

applications as well.

3.7.2.2 Outside of ASP.NET MVC

Similar frameworks to ASP.NET MVC in PHP, Ruby, Python etc can benefit from

implementing the suggested solutions to the software vulnerabilities described in the

experiments. Some may already have built-in protection, some may need tweaking the

parameters, but the general principles of the solutions apply and can increase the

security of the web applications.

3.7.3 Reliability

None of the hacker attacks in this paper are based upon unknown parameters, random

parameters, black box testing, arbitrary human input or any other unpredictable data.

When setting up the specified ASP.NET MVC web application in the same

environment, the results of the experiments shall invariably be the same.

Page 15: Securing ASP.NET MVC 5 Web Applications

10

4 Result

4.1 Object Binding Vulnerability

4.1.1 Theory

Mass assignment of properties through ORM allows the programmer to easily match

incoming parameters from the HTTP-request to an object. Typically CRUD operations

are then performed with the object. Although this is a very helpful feature that

accelerates the development process, it requires caution when it’s implemented to avoid

software vulnerabilities. Limitations on the ORM binding are often necessary to avoid

unintended behavior. The default behavior in ASP.NET MVC 5 is to map all incoming

parameters to an object, including any associated objects, which easily can become a

vulnerability.

4.1.2 Tested Attack Vector

The web application allows the creation of new “Routes” (as in logistics), but it puts no

limitations on attaching additional associated objects to the Route object. In the

experiment, the Route object has a parent Company object. This association is

automatically applied on the database structure via Entity Framework as well.

By nesting an additional Company object in the Route create request to the server, a

new Company object, completely under the hacker’s control is parallelly saved to the

database. The posted malevolent JSON-object looked as follows:

{"Name":"some route name","Data":"some route data", "CompanyId": "1",

"Company":{"Name":"Hacked Company"}}

4.1.3 Results before amendments

A new Route as well as a new Company are created with the HTTP-request and saved

to the database.

4.1.4 Required amendments

There are two main solutions for this vulnerability:

1. An architectural solution where a separate object, possibly a parent object , is

used to receive the user input. This object only has the expected properties,

Page 16: Securing ASP.NET MVC 5 Web Applications

11

which are then cast or copied to the final business layer object for CRUD

operations.

2. Setting binding properties on the controller action. This is a built-in function on

the ASP.NET MVC framework which allows black- or white-listing of

properties in the pre-action binding process.

In this experiment the second solution was applied. The new action method signature

looks like the following before and after using binding attributes:

public async Task CreateRouteWithoutBinding(Route maliciousRoute)

public async Task CreateRouteWithBinding([Bind(Exclude = "Company")] Route

maliciousRoute)

The added “Bind” attribute will now remove any incoming related data for the

associated Company object when the Route object is bound.

4.1.4.1 Blacklisting

Stopping unwanted data with "Exclude" in the attribute is called blacklisting, and is

considered less safe. There's always a risk that an unwanted field is forgotten in the

exclude list, especially when the application is under construction. However, it is used

in this example because of terse syntax and better overview.

4.1.4.2 Whitelisting

By explicitly listing allowed fields with "Include" instead of "Exclude" in the attribute

(whitelisting), there's a smaller risk of human error in the securing process. This

approach is especially suitable when only a small number of fields should be included.

4.1.5 Results after amendments

The same JSON object was sent to the server as previously. This time a new Route was

correctly created and saved to database, but no new Company.

4.1.6 Documentation

Details of the involved classes in this experiment can be found in Appendix A2.

This hacker attack is further documented in the API Abuse category in 7PK [9]

Page 17: Securing ASP.NET MVC 5 Web Applications

12

4.2 Dangerous Uploaded File Type Vulnerability

4.2.1 Theory

Allowing users to upload files can be a great feature that enriches the content and user

experience of the web site. However, it also opens up for vulnerabilities and requires

caution in the implementation. Uploaded files can sometimes be executed via HTTP-

requests and run harmful code on the server.

4.2.2 Tested Attack Vector

The web application allows uploading of images to the server for displaying to visitors.

Uploaded files are saved in the public folder “/Images”. By uploading an .aspx-file with

arbitrary ASP.NET code instead of an image-file, the server could come under the

control of the hacker.

An aspx-file was prepared and uploaded as “hackedPage.aspx”. It was then potentially

executed via a GET-request to “/Images/hackedPage.aspx”.

4.2.3 Results before amendments

The .aspx-file was uploaded to the server and executed in the “/Images”-folder with

ASP.NET code of choice.

4.2.4 Required amendments

There are two main ways of stopping this attack:

1. Using a blacklist of forbidden file-extensions and reject all files that have a

matching extension. This is not recommended though, because black-lists are

not guaranteed to be complete and can still let some kinds of dangerous files slip

by.

2. Using a whitelist of allowed file-extensions and reject all files that do not match

the extensions. This is much safer method that gives complete control of

incoming files. In some cases it can also be required to check the actual meta-

information in the file header to confirm the file-type, which requires reading an

initial byte-stream of the file and matching on a binary basis. In the case of this

experiment it is enough to match the file-extension though, since the attack

depends only on the file-type being executable.

Page 18: Securing ASP.NET MVC 5 Web Applications

13

4.2.5 Results after amendments

The same .aspx-file was uploaded to the server but without being saved to disk.

4.2.6 Documentation

Details of the involved classes in this experiment can be found in Appendix A3.

This hacker attack is further documented on the CWE [10].

4.3 Excessive Authentication Attempts Vulnerability

4.3.1 Theory

Depending on the password policy of a web-site, a password can be more or less hard to

guess. Hackers can further increase their chances of guessing passwords by techniques

such as Dictionary Attack [27], Phishing [23], Social Engineering [11], Inference [28]

or just plain Brute Force [26]. Whatever the case, the more guesses a hacker gets, the

higher the risk for a security breach. Therefore some kind of control mechanism for

repeatedly failed logins should be applied.

4.3.2 Tested Attack Vector

The site receives POST requests for login at “/api/user/login”. An unlimited amount of

login attempts are allowed for any user. Using the hacker techniques in the theory

above, it’s only a matter of time before the login security is breached.

4.3.3 Results before amendments

An unlimited number of login attempts could be performed via the login api without

interruption.

4.3.4 Required amendments

There are several ways of stopping this attack, where the world-leading email service

suppliers such as google and yahoo have worked out very sophisticated models. A

simple but powerful way of stopping this within ASP.NET MVC 5 though, is to use the

Identity 2.0 system [13].

Identity 2.0 supports “temporary lockout” and “max number of tries”, but it’s not

automatically activated in the templates. To activate these security features the Account

Page 19: Securing ASP.NET MVC 5 Web Applications

14

controller needs to be amended with logic in the registration and login action methods

that blocks an account after excessive login attempts and notifies the user and/or admin.

4.3.4.1 Special cases

In some cases the hacker attack consists of blocking the account (Account lockout

attack) [14]. Then additional measures need to be taken, e.g. blocking specific IP’s,

which in turn is vulnerable for an IP spoofing attack [15]. These special cases require

thorough investigation and are beyond the scope of this paper.

4.3.5 Results after amendments

After five failed login attempts, the account was blocked for 10 minutes and an email

was sent to notify the admin of the attack.

4.3.6 Documentation

Details of the involved classes in this experiment can be found in Appendix A4.

This hacker attack is further documented on the CWE [12].

4.4 XSS Filter Evasion Vulnerability

4.4.1 Theory

As soon as any kind of user input is distributed to the website’s visitors, there’s a

potential danger of an XSS attack via harmful input. Harmful input typically consists of

JavaScript in different forms with the intention to steal session information for

unauthorized access of user accounts.

Proper filtering must be applied to all user input to prevent this attack, but creating

filters that cover all kinds of XSS attacks is difficult and a hacker will try a large

number of creative ways to evade them.

4.4.2 Tested attack vector

The site receives user input for linked images, which are then displayed to the visitors.

The user input is rendered inside the src-attribute in the img-element. By posting a

JavaScript directive instead of an URL, harmful code can be executed on all visiting

Page 20: Securing ASP.NET MVC 5 Web Applications

15

browsers. Alternatively by closing the src-attribute and opening an onmouseover-

attribute via the input, the same goal can be achieved upon hovering over the image.

The entire list of XSS Filter Evasions on OWASP [16] was tested on the MVC

Controller with the goal of displaying an alert window.

4.4.3 Results before amendments

None of the evading attempts were successful, but were all automatically thwarted by

the MVC framework, and the alert window was never shown.

4.4.4 Required amendments

No amendments to the default MVC classes and configurations are required to stop this

attack.

4.4.5 Deactivation of built-in defenses

The built-in XSS filter of ASP.NET MVC 5 can be deactivated for an action method by

adding the attribute “ValidateInput(false)”. This should never be used without full

awareness of the consequences. When this attribute was added to the action method in

the experiment, the harmful input was accepted by the controller and could be saved

into a database.

However, even with the XSS filter turned off, the attack was not successful since there’s

one more layer of built-in protection. The Razor-engine automatically escapes all output

strings and effectively neutralizes XSS-attacks that come to the View. In order for the

attack to succeed, the dangerous Html.Raw - helper method must be used. Which,

again, never should be used without understanding the consequences.

After deactivating the XSS-filter and applying the Html.Raw helper, the alert-window

was successfully displayed while using the following user input:

(first displaying real image, then closing the tag, then inserting script, then finishing

with a suitable tag that matches the remaining part of the original img-element.)

http://www.theblacktechreport.com/wp-

content/uploads/2011/01/hacked.jpg"%20/><script>alert(%27XSS%27);</script><br%

20class="

Page 21: Securing ASP.NET MVC 5 Web Applications

16

Note: The attacked worked in Firefox and IE, but not in Chrome because of a built-in

XSS-defence in the browser.

4.4.6 Documentation

Details of the involved classes in this experiment can be found in Appendix A5.

This hacker attack is further documented on the CWE [12].

4.5 Inclusion of Third Party Scripts Vulnerability

4.5.1 Theory

Using CDN’s and including third party resources and scripts is often effective and

sometimes necessary. The website in the experiment uses the Google Maps JavaScript

API library for some crucial functions. This library must be loaded directly from

Google with a call to their server, but including third party scripts opens up for

vulnerabilities that should be considered.

4.5.1.1 A combination attack

For this attack to work, the hacker can either replace the file on the destination server or

redirect the client to another server under the hacker’s control. In this experiment the

latter alternative was chosen.

This kind of server redirection is also called DNS spoofing and can be accomplished in

many ways. Either by controlling the DNS server or any router on the way, or by

performing a DNS Cache Poisoning attack [18]. In a local Windows environment an

entry in the hosts-file in the “C:\Windows\System32\Drivers\etc” folder will accomplish

the same result.

After the server redirect a hacked javascript file will be served back to the client and

finish off the combo-attack with an XSS attack of choice.

4.5.2 Tested Attack Vector

The DNS spoofing was done by adding an entry to the hosts-file in the local Windows

environment. An additional web-server was set up with the IP given in the hosts-entry.

The server delivered a javascript file with identical path, name and contents as the

Page 22: Securing ASP.NET MVC 5 Web Applications

17

corresponding file on Google, but with the addition of a self-executing function with the

XSS-code inside.

4.5.3 Results before amendments

Upon a GET request of the web-page, the client’s request for the Google library was

directed to the tampered IP and the hacked javascript file was served and executed on

the client.

4.5.4 Required amendments

4.5.4.1 Https protocol

If possible, external javascript resources should always be acquired via the HTTPS

protocol. The SSL certificate, its private key and the initial handshake procedure is

difficult to simulate by a fake server. The browser will immediately stop the request and

warn the user if any anomalies are found.

In the case of Google, the Google Maps API JavaScript library is available via https.

The solution was then to switch protocol on the GET request to:

https://maps.googleapis.com/maps/api/js

4.5.5 Results after amendments

When the protocol was switched to https, the fake server could no longer deliver the

hacked javascript file. It could not complete the handshake with the client and the

request was aborted.

4.5.6 Documentation

This hacker attack is further documented on the CWE[19]

The altered hosts-file is available in Appendix A6.

4.6 Cross-Site Request Forgery (CSRF) Vulnerability

4.6.1 Theory

The built-in browser behavior is to send any related cookies to a site with every new

request to the site. This allows for automatic authentication of the request when the

Page 23: Securing ASP.NET MVC 5 Web Applications

18

authentication information is in the cookie. Although this may be very practical and an

easy authentication model to implement, it opens up for CSRF vulnerabilities.

By preparing an HTTP request to a website that performs an action of choice, and by

tricking an authenticated user to send the request, the hacker can perform this action via

the user with the user’s own authentication. Tricking a user to do a GET request is very

easily achievable through image loads and by sending links, which may be on

completely legitimate sites, and even keeping the user unaware of the attack. Other

types of HTTP requests (POST, PUT, DELETE) from the user are typically achieved

through javascript and XMLHttpRequests, which require the user to visit a page under

the hacker’s control, e.g. through an XSS attack.

4.6.1.1 ASP.NET MVC 5 Authentication

The default authentication in ASP.NET MVC 5 is through cookies. Incoming requests

are automatically checked for authentication information and user sessions are resolved

before arriving at the controller. User authorization is then simply applied by adding the

“Authorize”-attribute to the controller and/or action method. This applies to all requests,

including SignalR-hubs.

4.6.2 Tested attack vector

The website is an SPA (Single Page Application) with a set of API-commands and

SignalR methods to handle the data transport. The API includes an authorized POST-

request, “/api/user/logout”, that performs a logout for the current user. This action was

open for CSRF-attacks and could be performed from outside the web-site, e.g. through

Postman [20]. It was tested by first logging in via the website and then sending the

request from the browser’s Postman-plugin that includes any existing cookies in the

request.

4.6.2.1 SignalR

The web application also uses SignalR for both User and CRUD operations. SignalR is

a Websocket/SSE/Longpolling framework for ASP.NET with high abstraction. It uses

the same authentication process as controllers and is potentially also vulnerable for

CSRF-attacks. However, SignalR has CORS (Cross-Origin Resource Sharing) turned

off by default, which makes it unreachable for CSRF-attacks. CORS could be turned on

Page 24: Securing ASP.NET MVC 5 Web Applications

19

manually, but since it’s an obvious vulnerability it should only be done with a complete

understanding of the security implications.

4.6.3 Results before amendments

The logout-action was successfully called and performed from outside the website using

the authentication of the current user.

4.6.4 Required amendments

ASP.NET MVC 5 has a built in feature to stop CSRF-attacks. It’s a filter called

“ValidateAntiForgeryToken” and it’s implemented by default in the AccountController

in the Visual Studio 2013 templates. The solution is to also apply this filter to the API

controllers.

For the filter to work, it needs an implementation on the client side that creates a unique

token which is sent with the request to the server. If the token is missing or incorrect,

the request is rejected. Since it’s not stored in the cookie, but sent afresh in every HTTP

request, it effectively stops CSRF-attacks.

Implementing the filter in Views is a one-line procedure through the Razor helper-

method “@Html.AntiForgeryToken()”, which automatically handles the logic and

creates a hidden input-element with the token as a value inside the POST-form.

Implementing it in an SPA that shall send multiple API requests to the server, will

require some additional work though. The Razor engine must be asked to create and

save the token in the initial SPA-view, and from there it must be distributed to the rest

of the SPA. In the experiment, AngularJS was used and the AntiForgeryToken was

made accessible via a Value-provider. The token was then sent with every POST-

request.

Note that content-type must be set to 'application/x-www-form-urlencoded', for the

MVC framework to accept the token.

Finally, the “ValidateAntiForgeryToken”-attribute was added to the logout-action to

complete the setup.

Page 25: Securing ASP.NET MVC 5 Web Applications

20

4.6.5 Results after amendments

When sending the same logout-request to the server as before the amendment, it was

now rejected from outside the website, but accepted from within the web application.

4.6.6 Documentation

This hacker attack is further documented on the CWE[21]

The CSRF for websockets (SignalR) is further documented on 7PK[22]

The AngularJS code and ASP.NET Controllers for the experiment are available in

Appendix A7.

4.7 Open Redirect Vulnerability

4.7.1 Theory

Sometimes it’s necessary to redirect from one controller to another within the website.

This is a predictable procedure as long as no user input is involved in the process, but as

soon as any external data is used for the redirection, vulnerabilities may appear.

The classical example is the login redirect, where a user tries to access a restricted area

without logging in first, is then redirected to the login-page, and then redirected again to

the original page. The original url is typically provided in the query-string, which opens

up for phishing attacks.

4.7.2 Tested attack vector

A controller with a redirect action was set up. The redirect URL-parameter was fetched

from the query string by the action method.

The action method was then requested with an external URL as parameter.

4.7.2.1 Why is this a vulnerability?

Phishing attacks are all about trust [23]. By distributing links with a trusted domain

name and a malicious redirect link, users may follow the link and expect the content to

be trusted. By obfuscating the malicious link, e.g. via hexadecimal html characters, even

experienced users will not be able to directly see the actual destination. By using

identical layout and a very similar domain name, e.g. “cittibank.com” instead of

Page 26: Securing ASP.NET MVC 5 Web Applications

21

“citibank.com”, the malicious site may succeed in a phishing attack, e.g. by asking for

user credentials via a false login form.

4.7.3 Results before amendments

When calling the action method with an external URL the request was redirected

outside the website to any URL of choice.

4.7.4 Required amendments

Open redirects should be avoided when possible. If they have to be implemented the

amendments can be divided into two categories:

1. External redirects

2. Internal redirects

4.7.4.1 External redirects

A whitelist of accepted sites should be provided, either in list-form or by using regular

expressions. Alternatively an allowed list of acceptable sites could be mapped to GUID-

identifiers. The action method could then accept the GUID as user input.

4.7.4.2 Internal redirects

ASP.NET MVC 5 has built-in methods for identifying internal URLs via the “URL”

helper object on the Controller class. The solution in this experiment is to verify the

redirect-string with URL object’s IsLocalUrl-method before performing the redirect.

4.7.5 Results after amendments

When calling the action method with the same external URL as previously, the

controller redirected to the site’s root page instead of the external URL.

4.7.6 Documentation

This hacker attack is further documented on the CWE[24]

An example of how this attack was possible on the ASP.NET MVC version 1 & 2

AccountController is available on ASP.NET [25]

The Controller for the experiment is available in Appendix A8.

Page 27: Securing ASP.NET MVC 5 Web Applications

22

5 Discussion

Generally, the answer to this paper’s question can be found in the “Required

amendments” subchapter of each vulnerability. Combined with the succeeding “Results

after amendments” subchapter the efficiency of the amendments is documented and

answers the question if the attack is stopped or just mitigated. Although all amendments

resulted in stopping or mitigating the hacker attacks, some particulars about specific

results need to be clarified and elaborated.

5.1 Relying on external parties for the solution

One of the criteria for choosing hacker attacks in the method was that the

countermeasure preferably should be limited within the scope of the web application.

The findings of the experiments were that all tested attacks could be stopped or

mitigated from within the ASP.NET MVC web application with the exception of the

“Inclusion of Third Party Scripts Vulnerability”, where the solution was to get the

external Javascript file via https instead of http, which completely depends on the

availability of an SSL-connection with the external supplier (Google).

This puts a limitation on what third party suppliers could be used in a web application,

which is less than optimal. It would be better to find a solution that could verify the

authenticity of the third party script within the web application while not relying on

SSL. I had some thoughts about letting the web application parse, cache and serve the

external JavaScript file, while acting as a proxy and doing security checks on the file.

No similar solutions were found when I searched for it, so I made the conclusion that

this was not a good practice. Neither could I find any other recommended practices in

similar situations. The conclusion in this paper must therefore be that only SSL-

connections shall be used when fetching third party scripts in order to stop this attack,

and that this limitation is motivated and necessary.

5.2 Failed attacks

The attack on the “XSS Filter Evasion Vulnerability” failed and the web application

could not be compromised even with whitebox testing. Although this is a good

indication for the framework, it did not contribute with any additional best practice or

Page 28: Securing ASP.NET MVC 5 Web Applications

23

code amendments. Has Microsoft thought of all possible attack variations or are there

still ways to evade the built-in XSS filter?

The list of XSS filter evasions from OWASP [16] that was tested in the experiment has

been compiled by security experts and there’s little that can be added to that list. The

conclusion in this paper must therefore be that the filter currently may be trusted, to the

extent of our knowledge, without the need for any additional measures.

5.3 General Impression

The ASP.NET MVC framework gives a solid and safe impression where security is

increased with every new version. Some of the major attacks were never even

considered since they are automatically and thoroughly stopped by the framework, for

instance the SQL injection attacks, which are a non-issue with Entity Framework.

Further, the XSS protection was higher than anticipated and the CSRF-token was very

easily applied.

5.4 Areas of Improvement

The biggest concern in the paper is probably the Object Binding Vulnerability. The

default behavior is to bind all incoming fields to objects, which is everything but safe.

Microsoft would do right in reviewing and changing this behavior, perhaps by following

the example of "strong parameters" in Ruby On Rails.

5.5 Further research

In the “Excessive Authentication Attempts Vulnerability” the solution opened up for

new attacks, which were beyond the scope of this paper but nevertheless very potential

threats. The “Account lockout attack” would serve as a good candidate for further

research.

Page 29: Securing ASP.NET MVC 5 Web Applications

24

6 References

[1] “Overview of Web Application Security Threats,” Microsoft Developer Network,

[Online]. Available: http://msdn.microsoft.com/en-us/library/ft0y04t6(v=vs.71).aspx.

[Accessed: Apr. 9, 2014]

[2] K. Tsipenyuk and B. Chess and G. McGraw, “Seven Pernicious Kingdoms: A

Taxonomy of Software Security Errors,” Security & Privacy, vol. 3, no. 6, p. 81 - 84,

Nov-Dec 2005, [Online]. Available:

https://cwe.mitre.org/documents/sources/SevenPerniciousKingdoms.pdf. [Accessed:

Apr. 23, 2014]

[3] “HP Fortify Taxonomy: Software Security Errors,” HP Enterprise Security,

[Online]. Available:

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/index.html. [Accessed: Apr.

23, 2014]

[4] “Top 10 2013,” OWASP, Jun. 23, 2013. [Online]. Available:

https://www.owasp.org/index.php/Top_10_2013-Top_10. [Accessed: Apr. 23, 2014]

[5] “A Community Initiative,” Common Weakness Enumeration, Feb. 14, 2013.

[Online]. Available: http://cwe.mitre.org/community/index.html. [Accessed: Apr. 23,

2014]

[6] “Security”, Microsoft, [Online]. Available:

http://www.asp.net/mvc/overview/security. [Accessed: Apr. 24, 2014]

[7] T. Hunt, “OWASP Top 10 for .NET developers part 1: Injection,” troyhunt.com,

May 12, 2010. [Online]. Available: http://www.troyhunt.com/2010/05/owasp-top-10-

for-net-developers-part-1.html. [Accessed: Apr. 24, 2014]

[8] “Top 25 Most Dangerous Software Errors,” Common Weakness Enumeration, Sep.

13, 2011. [Online]. Available: http://cwe.mitre.org/top25/index.html. [Accessed: Apr.

24, 2014]

Page 30: Securing ASP.NET MVC 5 Web Applications

25

[9] “HP Fortify Taxonomy: Software Security Errors,” HP Enterprise Security,

[Online]. Available:

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/dotnet_mvc_bad_practi

ces_request_parameters_bound_into_persisted_objects.html. [Accessed: May. 13, 2014]

[10] “CWE-434: Unrestricted Upload of File with Dangerous Type,” Common

Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/434.html. [Accessed: May. 16, 2014]

[11] Tetri P, Vuorinen J. “Dissecting social engineering.” Behaviour & Information

Technology, vol 32, no 10, October 2013. [Online]. Available:

http://www.tandfonline.com.proxy.lnu.se/doi/full/10.1080/0144929X.2013.763860#.U4

O0EPl_t8E [Accessed: May. 26, 2014]

[12] “CWE-307: Improper Restriction of Excessive Authentication Attempts,” Common

Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/307.html. [Accessed: May. 20, 2014]

[13] “Announcing RTM of ASP.NET Identity 2.0.0” Microsoft Developer Network,

[Online]. Available: http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-

announcing-rtm-of-asp-net-identity-2-0-0.aspx. [Accessed: May. 21, 2014]

[14] “Account lockout attack,” OWASP, Aug. 12, 2013. [Online]. Available:

https://www.owasp.org/index.php/Account_lockout_attack. [Accessed: May. 21, 2014]

[15] “CWE-291: Reliance on IP Address for Authentication,” Common Weakness

Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/291.html. [Accessed: May. 21, 2014]

[16] “XSS Filter Evasion Cheat Sheet,” OWASP, Apr. 26, 2014. [Online]. Available:

https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet. [Accessed: May.

21, 2014]

Page 31: Securing ASP.NET MVC 5 Web Applications

26

[17] “CWE-82: Improper Neutralization of Script in Attributes of IMG Tags in a Web

Page,” Common Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/82.html. [Accessed: May. 21, 2014]

[18] “CWE-350: Reliance on Reverse DNS Resolution for a Security-Critical Action,”

Common Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/350html. [Accessed: May. 23, 2014]

[19] “CWE-829: Inclusion of Functionality from Untrusted Control Sphere,” Common

Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/829.html. [Accessed: May. 23, 2014]

[20] “Postman - a powerful HTTP client to test web services”.

Available: http://www.getpostman.com/. [Accessed: May. 25, 2014]

[21] “CWE-352: Cross-Site Request Forgery (CSRF),” Common Weakness

Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/352.html. [Accessed: May. 26, 2014]

[22] “Cross-Site WebSocket Hijacking,” HP Enterprise Security, [Online]. Available:

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/cross_site_websocket_h

ijacking.html. [Accessed: May. 26, 2014]

[23] “Phishing,” OWASP, Apr. 14, 2009. [Online]. Available:

https://www.owasp.org/index.php/Phishing. [Accessed: May. 26, 2014]

[24] “CWE-601: URL Redirection to Untrusted Site ('Open Redirect'),” Common

Weakness Enumeration, Feb. 18, 2014. [Online]. Available:

http://cwe.mitre.org/data/definitions/601.html. [Accessed: May. 26, 2014]

[25] “Preventing Open Redirection Attacks,” Microsoft, Feb. 27, 2014. [Online].

Available: http://www.asp.net/mvc/tutorials/security/preventing-open-redirection-

attacks. [Accessed: May. 26, 2014]

Page 32: Securing ASP.NET MVC 5 Web Applications

27

[26] “Brute Force Attack,” OWASP, Aug. 12, 2013. [Online]. Available:

https://www.owasp.org/index.php/Brute_force_attack. [Accessed: May. 26, 2014]

[27] “Online Dictionary Attack With Hydra,” Infosec Institute, Sep. 13, 2013. [Online].

Available: http://resources.infosecinstitute.com/online-dictionary-attack-with-hydra/.

[Accessed: May. 26, 2014]

[28] EC-Council, Penetration Testing: Network Threat Testing, Course Technology,

2010, p. 2-2

Page 33: Securing ASP.NET MVC 5 Web Applications

I

7 Appendices

7.1 Appendix A1 - Web application settings

7.1.1 Contents of packages.config

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

<packages>

<package id="Antlr" version="3.4.1.9004" targetFramework="net451" />

<package id="bootstrap" version="3.0.0" targetFramework="net451" />

<package id="EntityFramework" version="6.1.0" targetFramework="net451" />

<package id="jQuery" version="1.10.2" targetFramework="net451" />

<package id="jQuery.Validation" version="1.11.1" targetFramework="net451" />

<package id="Microsoft.AspNet.Identity.Core" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.Identity.Owin" version="1.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.Mvc" version="5.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.Razor" version="3.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.SignalR" version="2.0.3" targetFramework="net451" />

<package id="Microsoft.AspNet.SignalR.Core" version="2.0.3" targetFramework="net451" />

<package id="Microsoft.AspNet.SignalR.JS" version="2.0.3" targetFramework="net451" />

<package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.0.3" targetFramework="net451" />

<package id="Microsoft.AspNet.Web.Optimization" version="1.1.1" targetFramework="net451" />

<package id="Microsoft.AspNet.WebApi" version="5.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net451" />

<package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net451" />

<package id="Microsoft.AspNet.WebApi.Owin" version="5.1.2" targetFramework="net451" />

<package id="Microsoft.AspNet.WebApi.WebHost" version="5.0.0" targetFramework="net451" />

<package id="Microsoft.AspNet.WebPages" version="3.0.0" targetFramework="net451" />

<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.0.0" targetFramework="net451" />

<package id="Microsoft.Owin" version="2.1.0" targetFramework="net451" />

<package id="Microsoft.Owin.Host.SystemWeb" version="2.0.2" targetFramework="net451" />

<package id="Microsoft.Owin.Security" version="2.0.2" targetFramework="net451" />

<package id="Microsoft.Owin.Security.Cookies" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Owin.Security.Facebook" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Owin.Security.Google" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Owin.Security.OAuth" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Owin.Security.Twitter" version="2.0.0" targetFramework="net451" />

<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net451" />

<package id="Modernizr" version="2.6.2" targetFramework="net451" />

<package id="Newtonsoft.Json" version="6.0.2" targetFramework="net451" />

<package id="Owin" version="1.0" targetFramework="net451" />

<package id="Respond" version="1.2.0" targetFramework="net451" />

<package id="WebGrease" version="1.5.2" targetFramework="net451" />

Page 34: Securing ASP.NET MVC 5 Web Applications

II

</packages>

7.1.2 Contents of Global.asax

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110);

GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);

GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);

AreaRegistration.RegisterAllAreas();

GlobalConfiguration.Configure(WebApiConfig.Register);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

}

}

7.1.3 Contents of Web.config

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

<configuration>

<configSections>

<section name="entityFramework"

type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0,

Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

</configSections>

<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name="">

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

</behaviors>

<connectionStrings>

<add name="DefaultConnection" connectionString="Server=***,1433;Database=***;User

ID=***;Password=***;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"

providerName="System.Data.SqlClient"/>

</connectionStrings>

<appSettings>

<add key="webpages:Version" value="3.0.0.0"/>

Page 35: Securing ASP.NET MVC 5 Web Applications

III

<add key="webpages:Enabled" value="false"/>

<add key="ClientValidationEnabled" value="true"/>

<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

</appSettings>

<system.web>

<authentication mode="None"/>

<compilation debug="true" targetFramework="4.5.1"/>

<httpRuntime targetFramework="4.5.1"/>

</system.web>

<system.webServer>

<modules>

<remove name="FormsAuthenticationModule"/>

</modules>

<handlers>

<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>

<remove name="OPTIONSVerbHandler"/>

<remove name="TRACEVerbHandler"/>

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"

type="System.Web.Handlers.TransferRequestHandler"

preCondition="integratedMode,runtimeVersionv4.0"/>

</handlers></system.webServer>

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity

name="System.Net.Http.Formatting" publicKeyToken="31BF3856AD364E35" culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-

5.1.0.0" newVersion="5.1.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity

name="System.Web.Http" publicKeyToken="31BF3856AD364E35" culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-

5.1.0.0" newVersion="5.1.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity

name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-

6.0.0.0" newVersion="6.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>

</dependentAssembly>

Page 36: Securing ASP.NET MVC 5 Web Applications

IV

<dependentAssembly>

<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-2.1.0.0" newVersion="2.1.0.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"

culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0"/>

</dependentAssembly>

<dependentAssembly>

<assemblyIdentity name="Microsoft.AspNet.Identity.Core" publicKeyToken="31bf3856ad364e35"

culture="neutral"/>

<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

<entityFramework>

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,

EntityFramework">

<parameters>

<parameter value="v11.0"/>

</parameters>

</defaultConnectionFactory>

<providers>

<provider invariantName="System.Data.SqlClient"

type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>

</providers>

</entityFramework>

</configuration>

7.1.4 Contents of Startup.cs

public partial class Startup

{

Page 37: Securing ASP.NET MVC 5 Web Applications

V

public void Configuration(IAppBuilder app)

{

ConfigureAuth(app);

app.MapSignalR();

}

}

7.2 Appendix A2 - Object Binding Vulnerability Classes

7.2.1 Entities

public partial class Company

{

[Key]

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

public int Id { get; set; }

public string Name { get; set; }

public virtual ICollection<Route> RouteList

{

get;

set;

}

}

public partial class Route

{

[Key]

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

public int Id { get; set; }

[Required(ErrorMessage="Du måste ange ett namn på rutten")]

[MaxLength(128, ErrorMessage="Namnet får vara högst 128 tecken långt")]

public string Name { get; set; }

[Required(ErrorMessage = "Du måste ange ruttens waypoints")]

public string Data { get; set; }

public int CompanyId { get; set; }

[ForeignKey("Id")]

[Newtonsoft.Json.JsonIgnore]

public virtual Company Company { get; set; }

}

Page 38: Securing ASP.NET MVC 5 Web Applications

VI

7.2.2 Controller

public class TestController : Controller

{

private IUnitOfWork _uow;

public TestController()

:this(new UnitOfWork())

{

}

public TestController(IUnitOfWork uow)

{

_uow = uow;

}

public async Task CreateRouteWithoutBinding(Route maliciousRoute)

{

_uow.RouteRepository.Insert(maliciousRoute);

await _uow.Save();

}

public async Task CreateRouteWithBinding([Bind(Exclude = "Company")] Route maliciousRoute)

{

_uow.RouteRepository.Insert(maliciousRoute);

await _uow.Save();

}

}

7.3 Appendix A3 - Dangerous Uploaded File Type Vulnerability

Classes

7.3.1 Controller

public class DangerousFileUploadController : Controller

{

[HttpPost]

[ActionName("post")]

public void Post(HttpPostedFileBase file)

{

string path = Path.Combine(Server.MapPath("~/Images"),

Path.GetFileName(file.FileName));

file.SaveAs(path);

}

Page 39: Securing ASP.NET MVC 5 Web Applications

VII

[HttpPost]

[ActionName("postWithWhiteList")]

public void PostWithWhiteList(HttpPostedFileBase file)

{

var fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();

List<string> allowedTypes = new List<string>()

{

".jpg",

".jpeg",

".gif",

".png"

};

if (!allowedTypes.Contains(fileExtension))

{

return; //Possible error message here

}

//File extension is OK.

string path = Path.Combine(Server.MapPath("~/Images"),

Path.GetFileName(file.FileName));

file.SaveAs(path);

}

}

7.3.2 Uploaded .aspx-file

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Hacked Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h1>Hacked Page</h1>

<%= Server.MachineName.ToString() %>

</div>

</form>

</body>

</html>

Page 40: Securing ASP.NET MVC 5 Web Applications

VIII

7.4 Appendix A4 - Excessive Authentication Attempts Vulnerability

Classes

7.4.1 Registration Logic

7.4.1.1 Default Logic

public async Task<ActionResult> Register(RegisterViewModel model)

{

if (ModelState.IsValid)

{

var user = new ApplicationUser() { UserName = model.UserName };

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)

{

await SignInAsync(user, isPersistent: false);

return RedirectToAction("Index", "Home");

}

else

{

AddErrors(result);

}

}

// If we got this far, something failed, redisplay form

return View(model);

}

7.4.1.2 Amended Logic

public async Task<ActionResult> Register(RegisterViewModel model)

{

if (ModelState.IsValid)

{

var user = new ApplicationUser() { UserName = model.UserName };

UserManager.UserLockoutEnabledByDefault = true;

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)

{

await SignInAsync(user, isPersistent: false);

return RedirectToAction("Index", "Home");

}

else

{

AddErrors(result);

Page 41: Securing ASP.NET MVC 5 Web Applications

IX

}

}

// If we got this far, something failed, redisplay form

return View(model);

}

7.4.2 Login Logic

7.4.2.1 Default Logic in MVC 5 Account Controller

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

{

if (ModelState.IsValid)

{

var user = await UserManager.FindAsync(model.UserName, model.Password);

if (user != null)

{

await SignInAsync(user, model.RememberMe);

return RedirectToLocal(returnUrl);

}

else

{

ModelState.AddModelError("", "Invalid username or password.");

}

}

// If we got this far, something failed, redisplay form

return View(model);

}

7.4.2.2 Amended Logic for the experiment’s API controller

public async Task<IHttpActionResult> Login(LoginModel model)

{

if (model == null

|| String.IsNullOrWhiteSpace(model.UserName)

|| String.IsNullOrWhiteSpace(model.Password))

{

return BadRequest("You must enter username and password");

}

else

{

UserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10);

UserManager.MaxFailedAccessAttemptsBeforeLockout = 5;

var user = await UserManager.FindByNameAsync(model.UserName);

Page 42: Securing ASP.NET MVC 5 Web Applications

X

if (user != null)

{

if (await UserManager.IsLockedOutAsync(user.Id))

{

return BadRequest("Account has been locked for 10 minutes due to excessive incorrect

logins.");

//Inform the user and/or admin about the lockout

//SMTP-service instantiates here...

}

if (await UserManager.FindAsync(model.UserName, model.Password) != null)

{

await UserManager.ResetAccessFailedCountAsync(user.Id);

var owinContext = Request.GetOwinContext();

await SignInAsync(user, owinContext.Authentication);

return Ok(String.Format("You are now logged in as {0}", user.UserName));

}

else

{

await UserManager.AccessFailedAsync(user.Id);

}

}

return BadRequest("Incorrect username or password.");

}

}

7.5 Appendix A5 - XSS Filter Evasion Vulnerability Classes

7.5.1 Controller

7.5.1.1 With default settings

public class XSSController : Controller

{

[HttpGet]

public ActionResult Get(string imageUrl)

{

ViewBag.imageUrl = imageUrl;

return View("index");

}

}

7.5.1.2 With deactivated XSS Filter

public class XSSController : Controller

{

[HttpGet]

[ValidateInput(false)]

public ActionResult Get(string imageUrl)

Page 43: Securing ASP.NET MVC 5 Web Applications

XI

{

ViewBag.imageUrl = imageUrl;

return View("index");

}

}

7.5.2 View

7.5.2.1 With default rendering

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<title>XSS attack</title>

</head>

<body>

<div>

<img src="@ViewBag.imageUrl" />

</div>

</body>

</html>

7.5.2.2 With Html.Raw rendering

@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<title>XSS attack</title>

</head>

<body>

<div>

<img src="@Html.Raw(ViewBag.imageUrl)" />

</div>

</body>

</html>

Page 44: Securing ASP.NET MVC 5 Web Applications

XII

7.6 Appendix A6 - Inclusion of Third Party Scripts Vulnerability Files

7.6.1 Hosts-file

Found in C:\Windows\System32\Drivers\etc

# Copyright (c) 1993-2009 Microsoft Corp.

#

# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.

#

# This file contains the mappings of IP addresses to host names. Each

# entry should be kept on an individual line. The IP address should

# be placed in the first column followed by the corresponding host name.

# The IP address and the host name should be separated by at least one

# space.

#

# Additionally, comments (such as these) may be inserted on individual

# lines or following the machine name denoted by a '#' symbol.

#

# For example:

#

# 102.54.94.97 rhino.acme.com # source server

# 38.25.63.10 x.acme.com # x client host

# localhost name resolution is handled within DNS itself.

# 127.0.0.1 localhost

# ::1 localhost

#DNS Spoofing Attack here!

127.0.0.1 maps.googleapis.com

7.7 Appendix A7 - CSRF Vulnerability Classes

7.7.1 Controller

[Authorize]

public class UserController : Controller

[... abbreviated content ...]

// POST: /api/user/logout

[HttpPost]

[ActionName("logout")]

[ValidateAntiForgeryToken]

public string Logout()

{

Request.GetOwinContext().Authentication.SignOut();

Page 45: Securing ASP.NET MVC 5 Web Applications

XIII

return "You have been logged out.";

}

}

7.7.2 AngularJS Code

7.7.2.1 Initiation of antiForgeryToken

angular.module(‘app’)

.value('GDC_API_CONFIG', {

baseUrl: '/api/',

antiForgeryToken: ''

})

.run(['GDC_API_CONFIG',

function (GDC_API_CONFIG) {

//************ Get CSRF AntiForgeryToken from Razor generated input element **************

var antiForgeryToken = document.getElementsByName("__RequestVerificationToken")[0].value;

GDC_API_CONFIG.antiForgeryToken = antiForgeryToken;

}

7.7.2.2 POST-request with antiForgeryToken

var params = $.param({ __RequestVerificationToken: GDC_API_CONFIG.antiForgeryToken });

return $http({

method: 'POST',

url: GDC_API_CONFIG.baseUrl + 'user/logout',

data: params,

headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

});

7.8 Appendix A8 - Open Redirect Vulnerability Classes

7.8.1 Controller

public class OpenRedirectController : Controller

{

// GET: /OpenRedirect/verified

[HttpGet]

[ActionName("verified")]

public ActionResult Verified(string returnUrl)

{

if (Url.IsLocalUrl(returnUrl))

{

return Redirect(returnUrl);

}

else

Page 46: Securing ASP.NET MVC 5 Web Applications

XIV

{

return RedirectToAction("Index", "Home");

}

}

// GET: /OpenRedirect/unverified

[HttpGet]

[ActionName("unverified")]

public ActionResult UnVerified(string returnUrl)

{

return Redirect(returnUrl);

}

}