You are on page 1of 109

AS‐801

Fundamentals of .NET
Application Security

Stop the Attacks. Secure the Code.

1 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Objectives
Introduction to Secure Programming Securing .NET Session Management 
What is Software Security? Securing .NET Cryptography
Roles in End‐to‐End Software  Securing .NET Exception Handling
Security
Securing .NET Configuration
Common Security Threats on .NET
.NET Secure Code Review
Securing .NET Input Validation
.NET Secure Development Lifecycle 
.NET Framework security (SDL)
Securing .NET Authentication and 
Authorization

2 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

3 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
What is Secure Programming?

Secure programming is a state of  Secure programming practices 
practice for developing robustly  help in protecting data from 
secure software in such a way  theft or corruption due to 
that it should withstand any type  logical exploitation and 
of possible attacks program crashes

An insecure program can be 
exploited by an attacker to take  According to the CERT/CC 
control of a server or a user's  vulnerability reports, small 
computer and launch different  programming errors can cause 
types of host/network attacks  serious vulnerabilities in the 
such as denial‐of‐service, identity  application
theft, malware attacks, etc.

4 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Software Security
Software security involves protecting it’s restricted resources and 
secrets from malicious or unauthorized use

Restricted Resources Secrets

Restricted resource is any object, feature, or  Secret is any data created or processed 
function of an application that should not  by the application that should be kept 
be accessed by the unauthorized person secret with itself and can be used to 
authenticate the user
The restricted resources may include:
The secret may include:
Disk files
Passwords 
Software functions
Credit card numbers 
Hardware resources
PIN codes, etc.
External services

5 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Software Security (Cont’d)

The user supplies his/her identity 
and secret only if he/she knows

Secret

Identification  Authentication
Information

User The user is authenticated 
by checking the veracity of 
the secret 
Protected 
Resource

Protected 
Resource
Authorization
Protected 
Resource The user is authorized to use one or more protected 
resources
The set of resources that the user is authorized to use 
defines the level of trust granted to the user

6 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Desktop Application Security Vs. Web Application Security

Desktop Application Web Application


Security Security

Desktop application is stand‐alone application Web application are distributed applications
that resides and works on the single computer  where application’s components may reside 
system on different locations over the internet 
The security of such desktop applications 
Example, client may resides on one 
involves imposing system security as well as 
physical security to protect the application 
machine and server may resides on the 
from unauthorized or malicious use another machine on the internet
A system administrator is responsible for  As these are distributed applications, 
imposing system security by setting secret  providing physical security and system 
credentials in order to restricts unauthorized  security to such applications does not make 
access any sense because these applications can be 
A security guard is responsible for  access from anywhere over the internet
implementing physical security of the system 
by creating physical barriers such as locks,  This distributed nature put these 
surveillance cameras, etc. to avoid unauthorized  applications at risk of being attacked by the 
access to the premises in which system running  attacker
desktop application is located An application programmer, system 
Attacks on such desktop application are fewer  administrator, network administrator, web 
as system security and physical security are  administrator together are responsible to 
insurmountable develop secure web application

7 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Providing End-to-End Software Security
An end‐to‐end security should be used to develop secure .NET applications

It involves providing security 
at the following stages:

Application  System Physical Channel Firewall Web Server


Security  Security  Security  Security  Security  Security 

The people involved in providing end to end security has different roles 
at each stages

Application  System Physical Channel Firewall Web Server


Security  Security  Security  Security  Security  Security 

8 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Roles Involved in Providing End-to-End Software Security
The people who influences software security in development and deployment of .NET application involves:

Business Sponsor
Business sponsors defines expectations of software security depending upon the domain of the application and 
purpose behind developing it

Project Architect
Project architects assesses the security needs depending upon the security requirements specified by the sponsors and 
creates security policies that supposed to be followed by the programmers during the development of the project

Programmer
Programmer is responsible for implementing secure coding principles and security features provided by the .NET 
Framework in order to meet the software security goals specified in the design

Security Tester
Security tester is responsible for simulating the actions of an attacker in order to reveal behaviors that would bypass 
the software security measures. This test helps them to validate the software security measures designed by the 
project architect and implemented by the programmer

Administrators
Administrators such as system administrator, network administrator, web administrator are responsible for providing 
security to the applications by configuring and managing various types of securities such as firewall security, webserver 
security, channel security, etc.

9 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
.NET Application Security

The security of .NET application  The security of .NET application  The initial design of the 


depends on vigilance of the  can be maintained by constantly  application plays an important 
programmer at the design and  examining application against  role for creating secure 
coding phase potential security threats application

1 2 3

10 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Need for .NET Application Security

.NET application security includes securing the following types of applications developed 
using the .NET platform
Mobile Applications

Distributed .NET Applications  With increasing popularity of mobile devices, 
security concerns increase for these devices
These applications can also be 
vulnerable to most common Internet 
threats though they deployed on an 
intranet

Security
Concerns

Web Applications
Desktop Applications A poorly programmed web 
application can compromise 
The vulnerable desktop application can  integrity and security of an entire 
exploit the security of the computer  server or network
system 

11 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Why are Security Mistakes
Made?
Improper application of security principles (privileges) at the 
architectural stage of the entire code
Most of the programming curriculum often do not 
include security issues

Improper handling of flawed input data at the design stage

Missing some of the flaws at the testing stage, 
because of improper testing

Minor flaws in the code gives space to various vulnerabilities, 
resulting in serious damage to system

Writing secure code requires extra time, cost, and effort

Moreover, no proper guidance on secure coding to the code 
developers at every stage of the project development

12 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 .NET Framework
Security Namespaces
The .NET framework provides the following namespaces to develop a secure .NET application

Security Exception, 
System.Web.Security System.Security other Attributes

Windows, Forms and Passport 
authentication for web 
applications, URL and files 
authorization
System.Security.Policy

Code‐Based Security

System.Security. System.Security.
Cryptography Permissions
Encryption, Decryption, Hashing,  Code‐Based Security
Random Numbers

System.Security.Principal

Code‐Based Security

13 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Secure Coding Principles
List of security coding principles to prevent common security vulnerabilities
Security through obscurity Protect sensitive data
Secure the weakest link Exception handling
Use least privilege principle Secure memory management
Secure by default Protect memory or storage secrets
Fail securely Fundamentals of control granularity
Apply defense in depth Fault tolerance
Do not trust user input Fault detection
Reduce attack surface Fault removal
Enable auditing and logging Fault avoidance
Keep security simple Loose coupling
Separation of duties High cohesion
Fix security issues correctly Change management 
and version control
Apply security in design phase

14 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

15 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Common Security Threats on .NET
Category Vulnerability Attacks
Buffer overflow
Non‐validated input usage in the HTML output stream
Cross‐site scripting
Non‐validated input usage generating SQL queries
SQL injection
Dependence on client‐side validation
Cross‐site request forgery
Input and Data  Usage of input files names, URLs, or usernames for security decisions
Canonicalization attacks
Validation Application‐only filters usage for malicious input
Query string manipulation
Trusting data read from databases, file shares, network resources, etc.
Form field manipulation
Non‐validation of input from all sources such as cookies, query string 
Cookie manipulation
parameters, HTTP headers, etc.
HTTP header manipulation

Using weak passwords
Credential theft
Mixing personalization with authentication
Eavesdropping
Insecure authentication form settings
Brute‐force and dictionary attacks
Authentication Allowing over‐privileged accounts
Cookie replay attacks
Storing clear text information in configuration files
Account hijacking
Passing clear text information over the network
Information leakage
Allowing prolonged session lifetime

Accessing sensitive data in storage
Passing vital data in clear text over networks
and memory
Privacy and Data  Storing secrets unnecessarily
Data tampering
Compromise Storing secrets in code and clear text
Network eavesdropping
Access to sensitive data in storage
Information disclosure

16 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Common Security Threats on .NET (Cont’d)
Category Vulnerability Attacks

Dependence on a single gatekeeper Privilege escalation
Insufficient separation usage of privileges Disclosure of confidential data
Authorization
Not providing locks to system resources for particular application Data tampering
Failed to restrict database access for particular stored procedures Luring attacks

Inserting session identifiers in query strings Session hijacking
Session  Using unencrypted channels for passing session identifiers Session fixation 
Management Allowing extended session lifetime Session replay
Insecure session state stores Man‐in‐middle attacks

Disclosure of sensitive 
Exception  Not succeeding in using structured exception handling
information
Management Providing detailed error information to the user
Denial‐of‐service attacks

Application  Salvage of clear text 
Using process and service accounts with higher privileges
Configuration configuration data

17 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Common Security Threats on .NET (Cont’d)
Category Vulnerability Attacks
Insecure administration interface usage Illegal access to administration 
Over‐privileged process and service accounts utilization Interfaces
Configuration 
Insecure configuration stores usage Illegal access to configuration stores
Management
Stores clear text configuration information  Salvage of clear text configuration 
Too many administrators secrets

Weak encryption
Insecure distribution of keys
Not succeeding in secure encryption keys
Loss of decryption keys
Cryptography Lack of robust key generation or key management
WEP Encryption cracking
Custom cryptography usage
Wrong algorithm usage or utilizing a key size that is too small
Utilization of the same key for an extended period of time

Denial of performing an operation 
Not succeeding in auditing failed logons by user
Auditing and 
Not succeeding in securing audit files Exploitation of an application by an 
Logging attacker without trace
Not succeeding auditing across application tiers
Covering tracks
Using weak passwords Virus, Trojan, worm attacks
Allowing prolonged session lifetime Arbitrary code execution
Machine Threats
Not using anti‐virus and anti‐spyware Password attacks
Unauthorized access to machine

18 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

19 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Input Attacks Methodology
Common input attacks include XSS attacks, SQL injection attacks, buffer overflow attacks, 
DoS attacks, etc.
In such attacks, attacker enters malicious or bogus data in the input fields of the application
The entered data is unexpected to the application resulting either application crash or 
security breach
This helps an attacker to evade the security mechanism to reveal the sensitive information

Enters malicious or 
bogus data in the entry  Accesses  the sensitive 
point of the applications information

Attacker Application
Crashes /shutdowns  
the application

20 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Cross Site Scripting (XSS) Attacks
XSS attacks exploit vulnerabilities in dynamically generated Web pages, which enables attackers 
to inject client‐side script into web pages viewed by other users
In an XSS attack, the attacker injects the malicious script to form data or URL and tries to bypass 
the site's security mechanisms
http://www.juggyboy.com/<script>alert(“WARNING: The application has encountered
an error");</script> in URL
<script>alert(‘WARNING: The application has encountered an error')</script> in
input text field

http://www.juggyboy.com/Login.aspx
http://www.juggyboy.com/Login.aspx
<script>alert(“WARNING: The application
has encountered an error");</script>
JuggyBoy.com
Injects the malicious script into URL

Once malicious script is executed, attacker 
Attacker bypasses login mechanism of site and gets 
unauthorized access to the website  Web Server

Exploit vulnerabilities Injects the malicious script Invalidated input data

21 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
SQL Injection Attacks
SQL injection attacks use a series of malicious SQL queries to directly manipulate 
the database
These attacks are possible only when the application executes dynamic SQL 
statements and stored procedures with arguments based on the user input
The escape characters are used to perform SQL injection attacks

When this username is sent to the server, 
http://www.juggyboy.com/Login.aspx condition always gets true, which allows 
attacker to gain access to database and 
executes the query 
JuggyBoy.com

SqlDataAdapter my_query = new


:a’ or ‘a’='a SqlDataAdapter(
********** "SELECT accountbalance FROM
userdata WHERE username
Internet = ?“,the_connection);
Attacker

Web browser Server‐side vulnerable code

22 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Buffer Overflow Attacks
Buffer overflow occurs when an attacker intentionally enters 
value beyond the range of the input field
A buffer overflow attack allows an attacker to crash the 
application

aaaaaaaaaaaa

Attacker Attacker enters  Buffer overflow attack  Application 


large string vulnerable .NET code  Crashes 

23 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Denial-of-Service (DoS) Attack

To perform denial‐of‐service attack, attacker sends fake request or 
uploads large files to send the application into indefinite state 

It causes the application to shut down its services, thereby keeping 
legitimate users away from accessing the application services

Keeps the  Legitimate user 


Sends large number  application busy  unable to access the 
of fake requests or  or sends it to  application services
uploads large files indefinite state

Attacker Application in  Application in  Legitimate 


Running state indefinite state user

24 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Why Input Validation?
Improper validation of input may provide  Firewalls cannot prevent the attacks caused 
path to the attacker to perform injection  by malicious or invalid input, and 
attacks such as cross site scripting  processing of these inputs without 
attacks and SQL injection attacks  validation can make the application 
on the web application  vulnerable to the attacks

The attacker may use an  The application receives inputs 
improper input validation  from various sources such as 
vulnerability by inputting bogus 
human users, software agents 
data to crash the system, maliciously 
(browsers), and network/peripheral 
manipulate the database, and corrupt 
devices that can be suspicious or untrusted
the database of the application

25 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Input Validation

Input validation is a process of verifying and 
testing the user inputs of the application that 
come from untrusted data sources

It is the simplest defensive technique used to secure 
web applications from injection attacks

Proper input validation techniques are used to 
eliminate the vulnerabilities in the web applications

26 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Input Validation Specification
The input should be 
Data type (string,  Allowed  Minimum and 
validated against: integer, real, etc.) character set maximum length

Whether  Whether duplicates 
Numeric range
null is allowed are allowed

Whether the parameter 
is required or not

Specific legal values 
(enumeration)
Specific patterns 
(regular expressions)

27 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Input Validation Approaches
The developer can take two approaches to perform input validation
Client‐side Input Validation
A client‐side language is used to perform client side validation 
that includes languages such as javaScript, VB Script, etc.
Server‐side Input Validation
A server‐side language is used to perform server‐side validation 
that includes languages such as ASP, PHP, JSP, etc.

28 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Client-side Input Validation
The client‐side script for input validation executes at the client 
side and validates the input data from the user and sends the 
validated data to the server for further processing
This approach takes less bandwidth and time to validate the 
input data 
It displays the errors one by one

http://www.juggyboy.com/Login.aspx

JuggyBoy.com Client‐ Sends validated 


side  input data to the server
validation 
script

Client Server

29 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Server-side Input Validation
The server‐side script for input validation executes on the server and validates the 
input coming from the client
Client sends the input data to server and waits for the response from the server
Server validates input data and sends acknowledgement to client about wrong input data
The client again sends the corrected input data to the server 
This process continues until valid data is entered
Server‐side input validation consumes extra time and bandwidth
It increases server load and network traffic

http://www.juggyboy.com/Login.aspx
Sends input 
data to the server
JuggyBoy.com Server‐
side 
validation 
script
Server sends acknowledgement 
about data  Server
Client

30 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Client-Server Input Validation Reliability
Client‐side validation is not reliable as the attacker can easily bypass client‐side 
input validation script by disabling it
Server‐side input validation is the reliable form of input validation
It is recommended that both client‐side and server‐side input validation should be 
implemented to secure the application
The following are the examples of input validation at both levels

Non‐trusted Code (Client‐side Script)  Trusted Code (Server‐side Validation Mechanism) 
protected void
1: script type="text/javascript">
1: ValidateEmpID2_ServerValidate(object source,
2: function EmpIDClientValidate(ctl, args) ServerValidateEventArgs args)
2: {
3: {
3: try
4: // The value is a multiple of 5 if the module by 5 is 0 4: {
5: args.IsValid=(int.Parse(args.Value)%5==0);
5: args.IsValid=(args.Value % 5 == 0);
6: }
6: } 7: catch
8: {
7: </script>
9: args.IsValid = false;
10: }
Client‐side validation mechanism is not reliable as it 
can be easily bypassed by disabling it  Server‐side validation mechanism is reliable as it resides 
on the server and can not be bypassed

31 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Validation Controls
ASP.NET Frameworks provide a set of 
validation controls that are used to 
validate the user inputs against errors It is used to validate user input on 
HTML forms on the server side 

It allows custom messages for errors 
to be displayed These validation controls are added 
while creating the web form and bind 
it to the specific server control

It reduces the use of JavaScript written 
It assists the browser in detecting the 
for each type of validation
errors on the client side when an invalid
input is entered and displays the error 
message without requesting the server

32 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Set of ASP.NET Validation Controls
RequiredField Validation Control

Range Validation Control

Comparison Validation Control

RegularExpression Validation Control

Custom Validation Control

Validation Summary Control

33 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Advantages of ASP.NET
Validation Controls

It allows developer to write their own custom errors messages 
when input validation fails

It reduces the use of JavaScript written for each type of validation

It assists the browser in detecting the errors on the client side and 
displays the error message without requesting the server

34 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Output Encoding
1 Output encoding is a technique in which characters are treated as 
data instead of characters by themselves

2 Unlike input validation, it does not checks the user input for specified 
condition instead it allows and accepts user input 

3
It then checks, if entered input contains harmful text and if present, 
renders them as harmless text back to the user

4
It converts the input characters into their equivalent encoded values, 
which are then sent to web pages 

5
It informs the relevant interpreter that data is not intended to be 
executed

35 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Controls with Encoding Support
Control Name Property Name Encoding Type
System.Web.UI.Page Title HTML
System.Web.UI.WebControls.CheckBox Text HTML

System.Web.UI.WebControls.CompareValidator Text HTML

System.Web.UI.WebControls.CustomValidator Text HTML

System.Web.UI.WebControls.DropDownList Text HTML

System.Web.UI.WebControls.HyperLink Text HTML

System.Web.UI.WebControls.Label Text HTML

System.Web.UI.WebControls.LinkButton Text HTML

System.Web.UI.WebControls.ListBox Text HTML

System.Web.UI.WebControls.ListControl Text HTML

System.Web.UI.WebControls.Literal Text HTML

System.Web.UI.WebControls.RadioButton Text HTML

System.Web.UI.WebControls.RadioButtonList Text HTML

System.Web.UI.WebControls.RangeValidator Text HTML

System.Web.UI.WebControls.RegularExpressionValidator Text HTML

System.Web.UI.WebControls.RequiredFieldValidator Text HTML

36 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Input Attacks Best Practices
SQL Injection
XSS Attack Best
Attack Best
Practices
Practices

Perform input validation on  Replace single quote with double 
input field, query strings, and  quote for all user input in the SQL 
cookies query

Check for the scripting tags Always check the user input for 


present in the input and filter it  escape characters
Use regular expression to validate 
Use regular expressions to  the user input
perform input validation
Set the appropriate privileges to 
Use output encoding to sanitize  execute database command
output data  Use parameterized stored 
procedures when stored 
procedures are executed using 
arguments
Use the parameterized queries
and stored procedures while 
taking inputs from the user

37 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

38 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
.NET Framework Architecture

Microsoft Intermediate Unified Class


Language (MSIL) Library

Common Language Runtime (CLR)

Native Code
User

.NET Framework 

39 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
How .NET Framework Helps Developer
/Administrator to Build a Secure Application

.NET Framework allows developer  It handles critical security decisions 
and administrator to apply various  by itself that allows developers to 
security controls to secure their  concentrate on developing secure 
application from different types of  application rather than making 
attacks critical security decisions 

It provides various powerful, easy to  The managed code paradigm of 


use tools and techniques to  .NET Framework helps in providing 
implement security features such  convenient solution to various 
as authentication, authorization,  application risks
cryptography, etc. in the application

It provides inbuilt security for .NET 
application so that it can 
automatically eliminates some of 
the major concerns caused by using 
flawed code such as buffer 
overflows

40 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Basic Components of .NET Framework
Common Language Runtime (CLR)

The CLR provides an execution environment that manages running 
code and provides services, such as automatic memory 
management, cross‐language integration, and interoperability with 
existing code and systems that make software development easier

Class Libraries

The .NET Framework class library is a collection of reusable 
classes, interfaces, and value types that provides access to 
utilize system functionality

Assembly

Assemblies are the building blocks of .NET
applications used for deployment, versioning, 
and security

41 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.

Key Elements of .NET Framework
Architecture Security
Evidence‐based Security Code Access Security (CAS)
The important elements of .NET  CAS ensures security for the assembly 
evidence‐based security include  code while accessing it based on 
policies, permissions and evidence permissions

The Verification Process Role‐based Security
The .NET managed code will be  The resources of a .NET application can 
ensured by using verification  be monitored by using identity, which is 
process at runtime as the final step achieved by role‐based security

Cryptography Application Domains
The confidential data can be secured with  Integrated memory areas are useful to 
the help of encryption, digital signatures,  run .NET applications in their own 
hashing, and random number generation  memory locations  without any 
mechanisms in .NET applications disturbances  to other applications 
running on the same machine

42 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Best Practices for .NET Framework Security
1 Sign an assembly with Authenticode

2 Sign an assembly with an X.509 certificate

3 Set up permissions to write to the event log

4 Inspect for dangerous unmanaged APIs

5 Use the safe CRT libraries

6 Use code access security

7 Use a digital certificate

8 Use security demands

9 Apply security policy

43 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

44 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
He is John

home.aspx
Authentication Authorization

(Who are  (What rights 
you?) you have)
admin.aspx
User

He is an admin 
and has access to 
all pages on the website

45 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Introduction

Authentication Authorization

Authentication is the process of  Authorization is the process of giving a 
verifying a user's identity with an  specific rights to the authenticate user
application by using some sort of  to perform specific tasks 
credentials For example: Administrator is 
For example: Username and password  authorized person and has privileges 
are used to authenticate the user and rights to add or delete any user 
with the system account 

Note: Authentication is always performed before authorization

46 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Authentication and Authorization
Threats
Account Hijacking Unauthorized Access
Accessing the account of a legitimate   Gaining access to the restricted  
user by guessing or stealing the  resources though he/she has no rights 
legitimate user's credentials to obtain  to do so
or tamper with sensitive information
Information Leakage
Man‐in‐the‐middle 
Using unprotected or revealed 
Intercepting the traffic to read or  information to compromise the system
modify the data during transmission
Privilege Escalation
Phishing
Luring the legitimate user to enter his  Acquiring higher‐level privileges for an 
credentials through fake website links  account
that looks like a legitimate website Sniffing
Intercepting passwords or confidential 
information that travels across the 
network by using sniffing tools

47 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Authentication
ASP.NET provides a flexible set of alternatives for authentication

It can be performed through coding or by delegating authentication
to the other authorities

ASP.NET provides two separate layers of authentication mechanisms as 


the ASP.NET layer is placed just below the Internet Information Service (IIS) 
level in the web application security architecture

All requests go through the IIS layer before they are passed to the 


ASP.NET layer

The IIS layer can decide to deny access without passing the request to the 


ASP.NET layer

48 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Authentication Modes
ASP.NET provides various modes of authentication used for validating a user’s credentials and 
implements other security measures

There are four types of modes available in the ASP.NET authentication 

ASP.NET authentication modes 
Forms Authentication are specified in the Web.config file:

1: <configuration>

Passport Authentication 2: <system.web>

3: <authentication mode =
"[Windows|Forms|Passport|None]">
None Authentication 4: </authentication>
5: </system.web>

Windows Authentication 6: </configuration>

49 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Authorization
Once authentication of the user is performed, the user need to be authorized for the specific operation or to 
access specific resources 
It allows define roles and interaction of those roles with the application’s operation or resources
ASP.NET provides the following authorization options to authorize the client

Code-based URL Authorization


Authorization

.NET File Authorization


Roles

50 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Identifying Authentication and
Authorization Details

An Identity object is used to obtain authentication details
The Principal object is used to obtain authorization details of 
a particular Identity

Principal Authentication

Authorization Identity Username

Authentication 
Roles
Type

51 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Secure Development Checklists:
Authentication
Check for 
Check whether the 
authentication and 
Use SSL instead of the  user’s accounts are 
identity management 
GET method to secure  locked after a certain 
standards (i.e. SAML, 
credentials number of failed 
WS‐Security, LDAP,
attempts
NTLM, and Kerberos)

Check whether the 
Check whether stored password complexity 
Validate the 
passwords are  rules (minimum length, 
user’s credentials
encrypted /hashed or  non‐guessable words, 
regularly
not  special characters, 
numbers) are enforced

52 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Use file authorization only with Windows authentication

Configure appropriate ACLs on website files

Use role manager for roles authorization
Secure
Development Use role caching if role store lookup is too costly
Checklists:
Authorization Restrict authorization cookies to HTTPS connections by using
the requireSSL attribute

Set createPersistentCookie attribute to false

Protect the authorization cookie for tampering and reading information

53 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Guidelines for Secure Authentication
and Authorization Coding
The encrypted channels such as SSL should be used for authentication

A generic message should be used in case of  invalid username or
password

The user credentials should not be sent in clear text, including email

The password reset functionality should be provided that allows the user 
to change the password upon first login
Cookies should not be used to provide authentication or authorization 
details beyond a session 
The authentication information should not be stored in source code files of 
remote systems
The application should not be run through root or administrative privilege 
accounts
The user's principal data should be used to identify authorization
information instead of a single common account

The isolation should be provided for the processes whenever possible

54 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

55 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Session Management
Session management is the mechanism of tracking the entire interaction between client and 
server as it appears like a seamless connection with the server
The server can maintain session with two basic types of tokens:

Session Tokens Authentication Tokens


This session tokens are usually maintained  The user sends the first request to the server and 
through cookies as they provide an easy way to  gets authenticated with credentials; the server 
store information about a client issues an authentications token, which then is 
It may be either session cookies or persistent  used to authenticate subsequent requests from 
cookies and need to be secured as they may  the same user 
provide a path to attacker Once the session is maintained, there is no need 
to send credentials for each request from the 
same user to the server
This authentication token is sensitive as it 
contains actual credentials

56 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Rules of thumb for Securing
Session/Authentication Tokens

The token should uniquely recognize the client 
1 to the server

Any client outside the scope of the application 
2 should not use tokens in particular applications

The token should not be used by anyone else for 
3 malicious uses

57 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Common Attacks on Sessions
Session Hijacking Attack  Session Replay Attack
Stealing a particular user’s token in  Listening to conversation between the 
order to gain access to the user's  user and server and capturing the 
account authentication token of the user

Cross Site Request Forgery Attack Session Fixation Attack

Gaining access to the website by placing  Stealing a known fixed token of a particular 
a malicious link or image on the target  user and using it to authenticate with the 
website application, thereby gaining access to that 
user's session
Cross‐Site Scripting Attack Token Prediction Attack

Injecting a malicious script in the URLs to  Guessing or predicting the valid session 


hijack the user’s cookie, session token, or  tokens as the tokens follow some 
account credentials sequential or predictable pattern

58 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Recommendations to Prevent
Session Hijacking Attack

Avoid specifying cookie modes to 
Implementing SSL to encrypt cookies
AutoDetect

Setting a limited time period for  Avoid specifying cookie modes to 


expiration UseDeviceProfile

Enabling regenerateExpiredSessionID
Avoid using cookieless sessions
for cookieless sessions

Avoid using UseUri cookieless Resetting the session when user 


sessions logs out

59 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Recommendations to Prevent Token
Prediction Attack and XSS Attack

Token Prediction Attack XSS Attack

• Generate the unique session  • Implement URL Rewriting 
tokens mechanism using using GUID
• Generate undeterministic session  • Expire the URL of the application 
tokens  automatically using Timestamp
• Do not use the Globally Unique  • Set the httpOnlyCookie attribute 
Identifiers (GUIDs) to generate  to true in the web.config file 
session tokens
• Use cryptographic service 
provider to generate session 
tokens

60 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Recommendation to Prevent Session
Replay Attack

Avoid storing session information on the client side

Re‐authenticate the user if some critical function is being performed

Set expiration time for cookies

Secure cookies using SSL

Do not allow multiple and concurrent authenticated sessions to the application

Synchronize the timestamp of the sending request with the server timestamp
and disallow the request that does not match timestamps of the server

Issue pseudo random tokens to the user when the user first requests 

61 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Misconceptions, Reality and Recommendations
to Prevent Session Fixation attacks
ASP.NET_SessionId cookie will be deleted after 
executing Session.Abandon() in the log out 
method
ASP.NET_SessionId cookie will be deleted after 
executing Session.RemoveAll() in the log out 
method
ASP.NET_SessionId cookie will be deleted 
after executing Session.Clear() in the log 
out method

Define separate logic to validate 
ASP.NET_SessionId to validated the cookies  ASP.NET_SessionId cookie will be still in the 
client’s browser even though one of the above 
Now if attackers steals ASP.NET_SessionId cookie, the 
or all methods are executed in log out method, 
cookies will be validated and expired cookies will not be 
any one can steal these cookies to establish 
accepted anymore 
unauthorized session

62 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Recommendation to Prevent Cross Site Request
Forgery Attack

Do not turn on Remember Me feature of the  Limit the lifetime of cookies
authentication
Check whether the HTTP Referer header or 
Do not click external links or images that  HTTP Origin header is not sending by the 
look suspicious browser for each request
Ensure that no clientaccesspolicy.xml file 
Use browser extensions supporting 
should grant unintended access to 
RequestPolicy, which provides default‐deny 
Silverlight controls
policy for cross‐site requests
Ensure that no crossdomain.xml file should 
Use secret and user‐specific authentication  grant unintended access to Flash movies
tokens for each request
Check whether the request headers contains 
Re‐authenticate with website an X‐Requested‐With

63 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
General Guidelines for Secure Session Management

Always  store  Employ security 
Use built‐in  Invalidate the 
the session data for data that is  Use short session 
session  session on the 
on the server  stored in  timeout intervals
framework server
side  sessions

Enable the Avoid using or 
Regenerate 
Secure and  reusing session‐
session‐ids Use valid SSL 
HTTPonly ids for 
when privilege  certification
attributes on  any other 
changes
cookies purpose

Do not trust 
Regenerate  Secure the  client‐side state  Do not mix 
session‐ids when  sensitive pages  management  session tokens 
transferring from   with proper  options because  and 
HTTP to  HTTPS authentication information can be  authentication
tampered tokens

64 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

65 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
What is Cryptography?
Cryptography is an art of protecting information by 
conversing data into a scrambled code that is decrypted and 
transforming it in such a way that the resulting transformed 
form is unreadable to an unauthorized party Encryption

The cryptographic primitive classes present in the 
stream‐based managed code libraries are used to   Basic Areas of
implement cryptography in the .NET application  Cryptography

Digital
Hashing
Signatures
Encryption algorithm uses a key to perform a 
transformation on the data

Encryption

Plain Text  Unreadable 
Data  format 
Hashing Digital  Data 
Signatures

66 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Goals of Cryptography
Cryptography is used to achieve the following goals: 

Confidentiality Integrity Non-repudiation Authentication

Cryptography is used  Cryptography is used  Cryptography is used  Cryptography is used 


to save the sensitive to ensure that the to prove the user  to authenticate the 
information from  data is not altered made requests
users to the legitimate 
prying eyes during transmission 
or storage application

67 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Common Threats on Cryptography and Their
Mitigation Techniques

Threats Mitigation Techniques Example Algorithms

Data encryption using a symmetric RC2, Rc4, DES, 3DES, AES
Information Disclosure
cipher (Rijndael)

Data and message integrity using  SHA‐1, SHA‐256, SHA‐384, 


hash functions, message SHA‐512, MD4, MD5, 
Tampering
authentication codes, or digital  HMAC, RSA digital 
signatures signatures, XML DSig

Public key certificates and 
Spoofing Authenticate data from the sender
digital signatures

68 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Attacker’s Scenarios for Cryptography Attacks
Attacker tries out the following scenarios to carry out cryptography attacks:

Identify and exploit weaknesses in the 
Guess or attain the secret key using brute 
cryptographic algorithm using the 
force attack/theft
cryptanalysis method

Identify and exploit weaknesses of  Gain the secret key using social 
software bugs that implement  engineering and blackmailing as 
cryptographic solutions  humans are vulnerable to these attacks

Obtain the secret key by taking advantage  Gain physical access to the computer 
of side‐channel leakage such as accessing  and discover the secret key by installing 
and evaluating timing, power consumption  key loggers
and dissipation, electromagnetic radiation, 
heat radiation, or other side channels

69 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
.NET Cryptography Namespaces
System.Security.Cryptography
The System.Security.Cryptography namespace offers 
cryptographic services, used for secure encoding and decoding of 
data, hashing, message authentication, and random number 
generation

System.Security.Cryptography.X509Certificate

The System.Security.Cryptography.X509Certificate
namespace contains the CLR implementation of authenticode X.509
certificate; this certificate identifies the holder of the certificate when it 
is signed with the private key

System.Security.Cryptography.Xml

The System.Security.Cryptography.Xml namespace 
contains classes that support the creation and validation of XML 
digital signature in .NET

70 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Symmetric Encryption
@##^%% Encrypted  Both sender and receiver share the  Decrypted  Hello
How are
$$##%$
Message  Message 
same key to encrypt and decrypt data you?

Sender Receiver
(Sender uses the secret key to encrypt the  (Receiver decrypts the data using the secret 
confidential message and sends it to the receiver) key and reads the confidential message)

Symmetric encryption is  It is called symmetric  It is used to encrypt  The 


the oldest cryptographic  encryption as a single  large amounts of  SymmetricAlgori
technique used to  key is used for  data   thm class is used to 
encrypt digital data in  encrypting and  perform symmetric 
order to ensure data  decrypting the data encryption on data in 
confidentiality .NET

71 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 Securing Symmetric Encryption

Strong symmetric encryption algorithm Cipher mode


Use strong algorithms to encrypt the  Set strong cipher mode on encryption 
information in order to prevent the  algorithm so that resultant cipher text is 
application from the cryptographic attacks not deterministic

Key size Padding mode


Set the key size on encryption algorithm  Set correct padding mode on encryption 
as large as possible to prevent it from  algorithm so that it should not conflict 
the brute force attacks with original data

Block size Non-predictable cryptographic keys


Set the block size value on encryption  Use RNGCryptoServiceProvider
algorithm as large as possible to avoid  to generate non predictable keys instead 
cryptanalys is attacks  of Random class or manual generation

Secret Keys Storage


Access Control Lists (ACLs)
Store the secret keys in secure place such 
Use ACLs to protect  the secret keys 
as Windows Registry, Application Configu
when  it is stored in Windows Registry
ration Files, etc. 

72 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Asymmetric Encryption
Asymmetric encryption (public‐key) uses different encryption keys for 
encryption and decryption. These keys are known as public and private keys

It is used to encrypt small amount of data

The Asymmetric Algorithm class is used to perform asymmetric encryption 
on data in .NET

Public Key Receiver selects a public and private key  Private Key


Confidential and sends the public key to the sender Confidential
Message Message

Sender Receiver
Sender uses the public key to encrypt the  Receiver decrypts the data using the 
message and sends it to the receiver private key and reads the message

73 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Securing Asymmetric Encryption
Use only those asymmetric encryption algorithm that produces
large keys

If require, set the key size as large as possible explicitly 

Use container to store private keys securely

Exchange the public keys securely 

Use OAEP padding mode on asymmetric encryption algorithm

Use secure channel such as SSL for key exchange 

74 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Hashing
User sends the  Confidential
Hashing is one of the forms of cryptography that  message and the  Message
hash code to receiver
transforms the information into a fixed‐length  Sender 10010010
value or key that represents the original 
Hash Code
information
1001
0010

The hashing technique ensures the security of 
information by checking the integrity of 
information on both the sender and receiver  1001
side  0010

Receiver checks the  Confidential
hash code to ensure  Message
that the message has 
not been altered
Receiver 10010010
Hash Code

75 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Securing Hashing
Use proper message Use keyed hashing
Set proper
size to produce algorithms such as
hash code length
secure hash code HMAC-SHA-1

If you set the size of message  Security of the hash code  Keyed hashing algorithms 


beyond the limit, then the  increases with length of the  prevents the hash code
resultant hash code will be  hash code as it is directly  from replacing it by the 
less secure and vulnerable  proportional to the hash  attacker, as he/she do not 
to various attacks  code length know the secret key
It should be set within limit   Select the hashing algorithm 
i.e. below 264 bits that creates large hash code

76 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Digital Signatures
Sender uses the private key  Private Key
to "sign" the message and 
sends the message and 
Digital signature used asymmetric  signature to receiver Confidential
Message
cryptography to simulate the security 
properties of a signature in digital,  10010010
rather than written form Sender
Hash Code
A specific signature function is added 
to the asymmetric algorithm at the 
1001
sender's side to digitally sign the  Sender selects a public and  0010
message and a specific verification  private key and sends the 
public key to receiver
function is added to verify the 
signature to ensure message integrity 
at the recipient side Public Key

The asymmetric algorithms that 
Confidential
support these two functions are called  Message
digital signature algorithms 
Receiver verifies the signature 
using the public key and then  10010010
reads the message
Receiver
Hash Code

77 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Security Features of Digital Signatures
The total security of the digital signature depends on the security of the secret key and hash code as:

The attacker cannot create a fake signature until he/she knows the 
private key of the sender 

The attacker cannot reuse the sender’s digital signatures until 
both messages create the same hash code

The attacker cannot alter the signed message until both 
messages produce the same hash code

The sender cannot deny signing a message as the 
secret key is known to himself only

78 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

79 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Beware !!!! An Error Message is
Worth a Thousand Attacks!

The detailed error message may give information about the internal structure 
of the application that gives a path to the attacker to commit the attack
The error messages can also help the attacker to constrain the search space to 
commit attacks
Parameters to be Considered while Designing
Secure Error Messages!

How will you ask the
user to solve an
What type of 
error?
information does 
the application need 
from the user to deal 
with an error? What information 
should be shared
with the user?

81 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Need of Error/Exception Handling

Improper error or exception handling may crash the 
1 whole system or may fail in the middle of important 
operations

It may affect confidentiality, integrity, and availability
2 of sensitive data in an application

Insecure handling may give a path to the attacker to 
3 commit an attack on the application 

82 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Secure Exception Handling
The error handling mechanism needs to be secure so that it should prevent the
application from entering in to the unknown state

The Principles of Secure Error Handling

No Critical Activities until the  No Disclosure or Tampering
Failing to Secure State
Application in Unknown State of Important Information 
The error handling mechanism   The execution of critical tasks The important information 
should recover the application  should not be interrupted  about the inner structure
to the secure state if any  when the application enters  should not be disclosed in the 
erroneous condition occurs into an unknown state error messages
The unsecured resources These error messages should be 
should be reverted back to  generic so attackers are not 
their default level of security allowed to find sensitive 
information about the 
application

83 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Handling Exceptions in an
Application
Page‐Level Exception 
Handling
There are three different 
levels of exception handling 
in ASP.NET

Class‐Level Exception  Application‐Level 
Handling Exception Handling

84 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Best Practices for Coding Exceptions Safely
Avoid using exception handling 
Avoid storing sensitive information  mechanism  for returning 
on the error message field information from a method

Put separate try/catch block  Provide exceptions to errors 
for each thread that cannot be ignored

Change the exception 
Avoid catching more than 
only when semantic value
one exception per thread
needs to be added

Use using keyword in association 
with Dispose() method to prevent  Make the exception serializable 
resource leaks

Throw an exception rather 
Avoid returning special values
than the asserting in 
on error conditions
doubtful conditions

Make at least three 
Do not use exception conditions 
original constructors 
that represent resource absence
for each exception class

85 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Do’s and Don’ts in Exception Handling
Do’s Don’ts

• Use the ActionListener method to catch the   Do not use a single try block for all 


exception and show a proper message to the  supporting methods
user  Never use unnecessary catch blocks with 
• Throw the exception from all supporting  exceptions in a supporting method
methods  Do not suppress an exception
• Use catch block only when the exception is   Do not skip any exception to be logged into 
anticipated the logging system
• Try to create custom exceptions for all   Do not wait for an exception to occur; handle 
business rules it in early stages
• Check the business rule before throwing the  Try to avoid encountering exceptions 
exception

86 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Guidelines for Proper Exception Handling
Structured exception‐handling provides an efficient, clean, and unobtrusive way of handling 
exceptions in the application. Here are some of the techniques for handling exceptions properly

Use single try and many  Arrange the catch blocks from 
catches specific to general
Try to use a single try and many  Make sure that the different types of 
catch statements in a program,  exceptions are placed from most 
which may increase the  specific to most general
readability of your code

Always reach to valid state  Throw the closest match
Ensure that the objects in code are  While handing more than one 
returned to a valid state after an  exception for representing the same 
exception. This can be done by  errors, use closely matching error 
implementing the necessary cleanup  conditions
under the finally block

87 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Guidelines for Proper Exception
Handling (Cont’d)

Do not through exceptions for normal  Do not create lightly
occurring events  Use the existing exceptions that are well 
Do not use exceptions for commonly occurring  defined in the .NET Framework rather than 
events; instead, throw exceptions only when  creating new exceptions
something out of the ordinary happens
Name appropriately
Extend the ApplicationException class, not  After creating any Exception class, name it with 
the Base Exception class the word ending ‘Exception’ so that there will 
Never extend  the base class System.Exception;  not be any conflicts
always try to extend the ApplicationException
class
Use the inner exception property 
when re‐throwing
Use the base System.Exception class to wrap 
another new exception from throwing that 
checks the Inner Exception property, 
determining the cause of the problem

88 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Check whether exception handling mechanisms are used consistently

When an application fails, all the sensitive information such as session
IDs, cookies, etc. must be cleared

When an error is encountered, process “open transactions” 
appropriately

Error Check whether error messages reveal system internals or other 

Handling
sensitive information

Security Test the return values of functions for “function‐based error 
Checklists handling” techniques

Check whether any specific exceptions are caught when writing 
exception‐based error handling mechanisms

Manage and log all the exceptions that are caught

89 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

90 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Configuration Management

Configuration Management (CM) is a process of creating and 
maintaining uniformity of a product’s performance and features 
with its requirements, design, and operational information 
throughout the application life cycle

.NET Framework’s configuration management includes a wide 
range of settings to manage and secure web applications

.NET Framework provides various configuration files to 
configure an ASP.NET applications

91 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
What is Configuration Files?

Developers manipulates 
Configuration files are the 
configuration files  to 
XML files that are used to 
configure and manage all 
store configurations 
web applications and their 
management settings
environments

These settings either  XML configuration files are 
controls machine‐specific  case sensitive and can be 
configurations or  edited with any Notepad 
application‐specific  or XML editors
configurations

92 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Why do Developers Need to Apply
Secure Configuration Settings?
Developers often concentrate on writing secure code and 
neglect the configuration settings consequences  

This negligence mislead them to apply vulnerable configuration 
setting in the configuration files of web applications

Vulnerable configuration settings may create various 
threats to the web applications

If the web application is not configured properly, attacker 
may gain access to the web applications

The developer need to apply secure configuration settings along 
with wring secure code to secure the web application completely

93 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
ASP.NET Configuration Files Model
Configuration Files

Machine  Applications  Code Access Security 


Configuration Files Configuration Files Configuration Files

Machine.config 1. Web.config
2. app.exe.config

Enterprise  Machine and 
ASP.NET Policy
Policy User Policy

Enterprisesec.config Security.config 1. Web_hightrust.config


2. Web_mediumtrust.config
3. Web_lowtrust.config
4. Web_minimaltrust.config

94 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Applying Secure Configuration Settings

1 Use allowOverride="false" in the <location> element of Machine.config file

2 Set customErrors mode="On" in web.config file

3 Set trace enabled=“false" and localOnly=“true" to disable the tracing

4 Use debug="false" to disable the debugging

5 Use httpOnlyCookies="true" to prevent XSS attacks on coookies
1. Use enableEventValidation=“true" to prevent attacker from entering 
6 Set cookieless="UseCookies" to store session identifier in cookies
unexpected values in the list controls
7 Use requireSSL=“true" to use SSL for communication

8 Apply slidingExpiration=“false“ to set the session time out settings

9 Do not provide hardcoded credentials in <credentials> element
Use enableEventValidation=“true" to prevent attacker from entering unexpected 
10
values in the list controls
11 Set passwordFormat="Hashed" to secure passwords

95 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Applying Secure Configuration Settings (Cont’d)
Set minRequiredPasswordLength
Use validateRequest=“true" to 
and minRequiredNonalphanumeric
prevent the application from XSS 
Characters to suitable value to 
attacks
create strong passwords

Set maxRequestLength attribute 
Use enableViewStateMac=“true" 
value to as small as possible to avoid 
to prevent ViewState attacks
DoS attacks

Use validation="AES" to secure  Set the ValidationKey attribute to 


ViewState large value to secure ViewState

Limit number of form keys and 
Set viewStateEncryptionMode="Auto" 
JSON payload members to 1000 in 
to secure ViewState
App.exe.config file 

96 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

97 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Secure Code Review

Security code review is a 
process of software security  It helps to find and resolve 
testing that identifies the  a large number of security 
vulnerabilities in application  issues
source code

It is the most effective 
It is the combination of  method for detecting security 
human effort and technology  vulnerabilities or security 
support flaws in application source 
code

98 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Why Secure Code Review?
1 It ensures that secure application is developed though secure programming practices

2
It detects poor coding techniques in application source code which a malicious user 
uses to launch the attack

3 It verifies that the appropriate security controls are present or not and whether they 
work as framed and invoked in all exact places

4 It ensures that the application defends itself in the given environment and follows the 
secure coding best practices

5 It assures the software developers who are following secure development techniques

6
It states particular methodology and framework for carrying out code reviews and 
security audits

7
It evaluates the security issues related to particular technologies and individual 
framework

99 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
 What should you Understand
before Secure Code Review?

Aware of the bad or vulnerable code patch used in the code

Familiar with the security objectives defined before secure code 
review

Able to analyze the priorities of particular vulnerability in the 
code based on security objectives 

100 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Security Code Review Process

Step 1 Step 2

Identify security  Perform 
code review  preliminary 
objectives scan

Step 3 Step 4

Review code  Review for security 
for security  issues unique to 
issues the architecture

101 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Flow
Secure  Common 
Securing  .NET 
Programming  Security 
.NET Input  Framework 
and Software  Threats on 
Validation security
Security .NET

Securing .NET 
Securing .NET 
Authentication  Securing .NET 
Session 
and  Cryptography
Management 
Authorization

Securing .NET  .NET Secure 
Securing .NET  .NET Secure 
Exception  Development 
Configuration Code Review
Handling Lifecycle (SDL)

102 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
What is SDL?

Secure Development Lifecycle  It provides a complete set  It enhances the software 


(SDL) is a security assurance  of security guidelines to  development process by 
process that integrates  develop secure software integrating security 
security and privacy measures
throughout all phases of 
project development lifecycle

1 2 3

103 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Why SDL?
When SDL is not used, final secure code review is done at the later stage of the 
project development lifecycle

If insecure design and vulnerable code is found at the later stage of the project 
development life cycle, redesigning and patchwork coding is very expensive process 

SDL avoids expensive redesign and patchwork coding efforts caused by insecure 
design and flawed code implementation

SDL allows developers to perform ad‐hoc security review during the project 
implementation phase itself

It reduces the number of security design and coding flaws and minimizes the severity 
of flaws that are unnoticed 

104 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Secure Development Lifecycle (SDL) Process
Security Development Lifecycle is a process developed by the Microsoft for developing 
secure applications
This process is divided into seven phases and provides information about security practices, 
guidelines, and technologies

Training Design Verification Response

Core security  Establish design  Dynamic analysis Execute incident 


training requirements Fuzz testing response plan
Analyze attack 
Attack surface 
surface
review
Threat modeling 

Requirement Implementation Release


Establish security  Use approved  Incident response 
requirements tools plan
Create quality  Deprecate unsafe  Final security 
gates/bug bars functions review
Security and privacy Static analysis Release archive
risk assessment

105 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Security in the Design Stage: Threat Modeling

Threat modeling is a process of identifying, analyzing, and mitigating the 
threats to the application

It is performed at the  It is a structured approach  It is an iterative process that 


design phase of the  that allows the developer  starts from the design phase 
secure development  to rate the threats based  of the application and 
lifecycle on architecture and  iterates throughout the 
implementation of the  application lifecycle until all 
application  possible threats to the 
applications are identified

106 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Guidelines for Applying Security in
Implementation Phase of SDL
Do not use the unsafe or deprecated function

Use the updated compiler tools 

Use static and dynamic analysis tools

Perform the manual code review

Validate all the inputs coming from the user and encode outputs

Use anti‐cross site scripting libraries

Do no use string concatenation for dynamic SQL

Eliminate weak encryption 

107 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Security Testing
Security Testing Recommendations

The security tester should not limit his/her 
Security testing is  hacking attempts to those that are expected 
performed before  from the attacker
deployment of the  The attempt of attacks should not be limited to 
application the application. He/she should test the security 
of the systems on which application depends 
such as database, directory, email servers
The security tester should test the application 
beyond the application design as it does not 
offer many insights into security failures
The security should be updated with current 
trends in real attacks so that he/she can 
attempt number of possible attack on the 
application 

Security tester prepares  It helps to reduce the security
security test cases for  holes in the application as 
breaking the security of the  well as detects flaws in the 
application application design

108 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.
Module Summary

 Secure Programming is a state of practice for developing robustly secure software in such a way that it 
should withstand any type of possible attacks
 Software security involves protecting it’s restricted resources and secrets from malicious or unauthorized use
 The security of .NET application depends on vigilance of the programmer at the design and coding phase
 Input validation is a process of verifying and testing the user inputs of the application that come from untrusted data sources
 Output encoding is a technique in which characters are treated as data instead of characters by themselves
 Authentication is the process of 
verifying a user's identity with an application by using some sort of credentials 
 Authorization is the process of giving a specific rights to the authenticate user to perform specific tasks 
 Session management is the mechanism of tracking the entire interaction between client and server as it appears like a seamless 
connection with the server
 Cryptography is an art of protecting information by conversing data into a scrambled code that is decrypted and transforming it in 
such a way that the resulting transformed form is unreadable to an unauthorized party
 .NET Framework’s configuration management includes a wide range of settings to manage and secure web applications
 Security code review is a process of software security testing that identifies the vulnerabilities in application source code
 Secure Development Lifecycle (SDL) is a security assurance process that integrates security and privacy throughout all phases
of project development lifecycle

109 Copyright © by EC-Council
All Rights Reserved. Reproduction is Strictly Prohibited.

You might also like