How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)

Preview:

DESCRIPTION

English version of the workshop slides from PHDays III

Citation preview

How to Develop a Secure Web Application and Stay in Mind?

Vladimir Kochetkovweb applications security researcher

Positive Technologies

Translated into English by @pand0chkaPositive Hack Days III

Synopsis

― The effective development of the secure code requires changes in the mindset of the participants involved.

― The training resources available impose the learning of causes on their consequences and counteraction to consequences instead of causes elimination.

― Following the general approaches, the developer shall become the qualified pentester in order to start writing a secure code.

It doesn’t work!

Why?

GET /api/shop/discount?shopId=3&productId=1584&coupon=1y3z9 HTTP/1.1Host: superdupershop.comCookie: ASP.NET_SessionId=10g5o4zjkmbd2i552d5j3255;.ASPXAUTH= f2d345118221742ee0316d4080a53af014eb8a3161db421d36aa6a86ffea6781b5584f4157ec85ae5956cfc54cc93c34a3f9449c8ef4c70b5b54d46e0def3677cce9a8105340b8ccc6c8e64dfa37ae953f987517

Attention, the black box!

var shopId = Request["shopId"];var productId = Request["productId"];var coupon = Request["coupon"];

var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon);var sqlCommandTxt = string.Format(" SELECT value FROM Discounts WHERE coupon LIKE {0}", coupon);

var cmd = new SqlCommand(sqlCommandTxt, dataConnection);

// Execute query, process result etc...

Attention, the white box!

var shopId = Request["shopId"];var productId = Request["productId"];var coupon = Request["coupon"];

var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon);

var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon LIKE @couponPattern", dataConnection);cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern));

// Execute query, process result etc...

Are vulnerabilities fixed?

var shopId = 0;if (!int.TryParse(Request["shopId"], out shopId)){ throw new InvalidArgumentException();}

var productId = 0;if (!int.TryParse(Request["productId"], out productId)){ throw new InvalidArgumentException();}

var coupon = Request["coupon"];if (!Regex.IsMatch(coupon, "^[A-Za-z0-9]{5}$")){ throw new InvalidArgumentException();}

var couponPattern = string.Format("{0}-{1}-{2}", shopId, productId, coupon);

var cmd = new SqlCommand("SELECT * FROM Discounts WHERE coupon=@couponPattern", dataConnection);cmd.Parameters.Add(new SqlParameter("@couponPattern", couponPattern));

// Execute query, process result etc...

Now - yes!

Glossary

The information system is secured, if a number of properties of all its information flows aren't violated:

• CIA model:—confidentiality—availability—integrity

• STRIDE model – CIA plus:—authenticity—authorization—non-repudiation

Secure information system

― The threat is a thing the attacker can do with information

― The vulnerability stipulated by the weakness is a thing with the help of which he can do it

― The attack is a method how he can do it― The risk is the expectancy of the positive

results and consequences of his actions― The security is a thing which doesn’t let the

attacker to attack― The safety is a thing which minimizes the risk

Quick terms of information security

It is necessary to fight the causes, not the consequences!

Causes and consequences

Weakness Threat

Vulnerability Attack

Risk

Insecurity

Unsafeness

Why a struggle with attacks is more difficult than with weaknesses or ASP.NET Request Validation

versus IRV

http://habrahabr.ru/company/pt/blog/178357/

Demo

Typical mindset

― Focus on the functional requirements

― Knows about:• 10 risks (OWASP Top 10)• 1 threat (deadline violation)• Weaknesses? No, not heard

― Risk-centric

«I know when I’m writing code I’m not thinking about evil, I’m just trying to think about functionality» (с) Scott Hanselman

“Developer”

* based on poll results http://www.rsdn.ru/?poll/3488

Developers awareness*Ab

use

of F

uncti

onal

ity

Brut

e Fo

rce

Buffe

r/Fo

rmat

Str

ing

Ove

rflow

Cont

ent S

poofi

ng

Cred

entia

l/Ses

sion

Pred

iction

Cros

s-Si

te R

eque

st F

orge

ry

Cros

s-Si

te S

crip

ting

Deni

al o

f Ser

vice

Fing

erpr

intin

g

HPP/

HPC

HRS

Inte

ger O

verfl

ows

LDAP

Inje

ction

Mai

l Com

man

d In

jecti

on

Null

Byte

Inje

ction

OS

Com

man

ding

Path

Tra

vers

al

Pred

ictab

le R

esou

rce

Loca

tion

Rem

ote/

Loca

l File

Inclu

sion

Routi

ng D

etou

r

Sess

ion

Fixa

tion

SOAP

Arr

ay A

buse

SQL I

njec

tion

SSI I

njec

tion

URL R

edire

ctor

Abu

se

XML A

ttrib

ute

Blow

up

XML E

ntity

Exp

ansio

n

XML E

xter

nal E

ntitie

s

XML I

njec

tion

XPat

h/XQ

uery

Inje

ction

0.00%

10.00%

20.00%

30.00%

40.00%

50.00%

60.00%

70.00%

80.00%

90.00%

Attacks based on WASC classification Attacks included at OWASP Top 10 risks

Risks are for managers…

… not for developers!

“Security officer”― Focus on security requirements― Distinguishes attacks from the vulnerabilities ― Vulnerability-centric

«If you don't understand the business, you can't see business logic flaws.» (с) OWASP

Functional weaknesses

… are also causes of

vulnerabilities!

Mindset refactoring― «Developer»:

• throw out from the head all security hit-parades• follow a weakness-centric approach

― «Security officer»:• interact with developers• consider the functional specific• follow a threat-centric approach

What is a vulnerability?

A slightly boring theory

Mathematical abstraction representing the universal computing machine.

― Turing machine consists of:• infinite tape divided into cells;• control unit with finite set of states;• table of transitions between states.

― On the each iteration it can:• change content of the current cell;• proceed to another state;• move to a neighboring cell.

Turing machine

TM: a 7-tuple M=(Q,Γ,b,Σ,δ,q0,F) where:

Q is a finite, non-empty set of states;Γ is a finite, non-empty set of the tape alphabet/symbols;b∈Γ is the blank symbol;Σ⊆Γ∖b is the set of input symbols;q0∈Q is the initial state;

F⊆Q is the set of final or accepting states;δ:Q∖F×Γ → Q×Γ×{L,R} is a partial function called the transition function, where

• L is left shift;• R is right shift;

The formal definition of

Halt theorem: there's no algorithm able to determine whether the program halts on a given set of data;

Klini fixed-point theorem: there's no algorithmic transformation of programs that would assign to each program another, nonequivalent one;

Uspenskiy-Rice theorem: there's no algorithm to decide non-trivial properties of programs;

TM Limits

Replaces all occurrences of the character «a»

What happens if the input string will contain an empty symbol or “#”?

Demo

?

Machine with states, in which:

― the transition functions and/or set of states are distorted by the input data;

― the unpredictable transition into incorrect state takes place at each iteration.

The use of weird-machine can give thecomplete or partial control over initial machine.

― ;― на каждой итерации происходит

непредсказуемый переход в некорректное состояние.

Эксплуатация weird-машиныможет дать полный или частичныйконтроль над исходной машиной.

Weird-machine

Configuration: current state, tape contents, head position.

Conditional policy: a set of configurations permitted under certain conditions and do not lead to the implementation of information threats.

Security policy: an union of conditional policies.

Secure TM: a machine, where all runtime configurations meet the security policy.

Secure TM

2-tuple (V, C), where:

― V is an unauthorized configuration that violates the security policy;

― C is the sequence of conditions that describe the computation history, leading to V.

Vulnerability

The complete model of a secure TM«and we need to go deeper» (с)

"Modeling Computer Insecurity" (Sophie Engle, Sean Whalen and Matt Bishop):

It is possible to perform the complete dynamic program’s security analysis only if it is performed at

all possible input data sets.

The development of a secure code is less complicated in comparison with the security analysis of the existed code.

The computability of security problem

The statistical evaluation of a program’s security, even in accordance with the policy defined for it, is the undecidable problem.

The determination of the alignment of a current configuration with security policy is apparently decidable.

The semantics of any discrete process can be described as a set of states and conditions of transition between them.

What for all this?!

Criteria to the input data, leading a process to one or another states, form a set of configurations of an IS.

What for all this?!

Security Policy is formed as a result of the analysis of the threat model and highlighting of unauthorized configurations, leading to the implementation of any of the identified threats.

Elimination of unauthorized configurations forms a complex of countermeasures to ensure the security of IS, any other actions that operate with the «degree of unauthorization», form a complex of countermeasures to ensure the safety of IS.

Code development in accordance with the security

policy: security driven development

What for all this?!

The countermeasures to ensure the security of a typical building blocks of the web applications are already formulated as result of evolution.

A set of practices was developed on their basis, following by which it is possible to avoid the occurrence of weaknesses in architecture and implementation of web applications.

Good news

The building of security policy is usually necessary only for implementation of the business logic layer, in order to avoid the occurrence of logical weaknesses.

Threat modeling

What?The process of threats detection in an application developed

Who?Architects and developers

When?As soon as possible

What for?In order to detect the weaknesses in architecture or model of application environment, which can became vulnerabilities

The Basics

The Process

DFD creation or update

Threats identification

Countermeasures elaboration

Model validation

DFD Creation or Update

Element Figure Examples

External entity UsersExternal systems

Process ExecutablesComponentsOS ServicesWeb-services

Data flow Function callsNetwork data

Data storage DatabasesFilesData structures

Trust boundary ProcessesMachines

DFD Creation or Update

The further decomposition of a model is necessary if :― not all flows passing through the trust boundaries

are described;― there are implicit objects crossing the trust

boundaries;― the word description of a model require the use of

the words «sometimes», «as well as», «except of», etc.:• «Sometimes this data storage is used as…» the

second data storage should be added into the diagram

• «This data flow is always used for transition of business-entities, except the authentication stage» the additional flow should be added

DFD Creation or Update

DFD Creation or Update

― Contextual• Unified components/ products / systems

― 1st level• Separate functional possibilities or scripts

― 2nd level• Functional possibilities, divided into components

― 3rd level• Complete decomposition describing in details the

architecture or domain model

DFD Detail

― The finite source of the data flow may be an external entity, storage or process that creates it.

― If write-only data flows are present in the DFD, that in 90% of cases means its incompleteness.

― Data flows can not be transferred from the storage to storage directly, transmission is possible only through the processes.

― DFD should describe the architecture or domain model, and not their implementation («no» to flowcharts, classes diagrams and calls graphs).

The rules of DFD creation

The STRIDE model describes the threats of violation of 6 information flow properties.

It doesn’t require knowledge of the expert level for its building.

Threat identification

Threat Property

Spoofing Authenticity

Tampering Integrity

Repudiation Non-repudiation

Information Disclosure Confidentiality

Denial of Service Availability

Elevation of privilege Authorization

A set of threats is specific for each DFD element.

* Repudiation is specific only for storages leading a transaction log

Threats specificity

Element S T R I D E

√ √√ √ √ √ √ √

√ √ √√ ?* √ √

The countermeasures elaboration is the final purpose of threat modeling.The countermeasures for each threat should come down to :― redesigning or requirements review

(concentration on threats);― highlighting the configurations leading to threat

implementation and taking measures on eliminating the causes of their occurrence (concentration on vulnerability/weakness);

― creation of requirements to environment for elimination of the possibility of vulnerability use (concentration on attack) or decrease of the possible success of the attack and damage minimization (concentration on risks).

Countermeasures elaboration

Should be performed during all the development cycle.

― Does a model corresponds to the current implementation?

― Have all the threats been enumerated?• minimum: elements crossing the trust boundaries.

― Have the countermeasures been elaborated for each threat?

― Have the countermeasures been implemented correctly?

Model validation

Creation of the threat model for a typical web-application

Example

Default configuration security

Secure by Design, by Default and in Deployment

― implementation of the principle of least rights and privileges;

― minimal set of functionality enabled;

― forced change the default credentials;

― designing of each component on the basis of the proposed compromise all other.

SD3 Principle

Transport layer security

- HTTP over SSL/TLS. It is designed to provide:― the confidentiality and integrity of data

transmitted over HTTP;― the authenticity of the server-side (less

frequently - of the client-side).Or in other words, to protect against MitM attacks.

HTTPS

Static resources used in a document that is transmitted over HTTPS:

― style sheets,― scripts,― objects,

also must be transmitted over a secure channel!

The use of mixed content

Popular approaches:- HTTP by default, HTTPS is user option,- HTTP everywhere, critical entry points through

HTTPS

are inefficient and vulnerable to SSL Stripping attacks.

Inefficient data transmission

Partially counteraction is possible by using:

― site-wide HTTPS without optional HTTP,

― HTTP-header: Strict-Transport-Security: max-age=expireTime [; includeSubdomains]

provided that the first time the user gets to the site over HTTPS.

Inefficient data transmission

- use 2048 private keys;- protect private keys;- ensure sufficient domain name coverage;- obtain certificates from a reliable CA;- ensure that the certificate chain is valid;- use only secure protocols;- use only secure cipher suites;- control cipher suite selection;- disable client-initiated renegotiation;- mitigate known problems.

https://www.ssllabs.com/projects/best-practices/

Deployment phase practices

Error handling

Error messages:

Information disclosure

HTTP-response status codes:

Information disclosure

<customErrors mode="On" />

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/Error.aspx" />

Oracle is a weird-machine, answering the attacker questions within its functionality.

The most famous example: padding oracle.

Oracles creation

― Using custom error handlers and views with universal messages about them.

― The implementation of transaction support at the level of:• methods (try-catch-finally);• workflow states.

― The exclusion of side-channels:• HTTP-response status codes;• time-delays.

Error handling practices

Client-side security

― X-Frame-Options {DENY | SAMEORIGIN | ALLOW-FROM uri} defines the possibility of opening a document in a frame (http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-00)

― X-Content-Security-Policy | Content-Security-Policy | X-WebKit-CSP {…} defines the Content Security Policy (https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html)

4 HTTP-headers

How developers use a CSP

* based on poll results http://www.rsdn.ru/?poll/33884 as of 20 may 2013

Main supported directives:

― (connect|font|frame|img|media|object|script|style)-src uri limits the URI that can be accessed from the tags of the document

― default-src uri defines defaults for all src-directives

― report-uri uri defines the URI for policy violation messages

― sandbox flags defines a sandbox for iframe elements which restricts a set of states for their content (where flags: allow-same-origin | allow-top-navigation | allow-forms | allow-scripts)

Content Security Policy

Access Control

Identification:establishing identity

Authentication:proven establishing identity

Authorization:assigning rights to identity

Phases of access control

Passwords complexity

Password entropy:L=log2(nm),

where n is the size of multiple allowed symbols, m is the actual password length.

Password efficiency the relation of entropy to its actual length (in bits).

The increase of entropy by 1 bit doubles the maximal brute-force iterations number.

The rise of the entropy through the increase of a password is more effective, than through

alphabet power increase.

Passwords complexity

The password complexity should be limited below the entropy, defined in security requirements.

The examples of the entropy increase rules:• a set of maximal available character groups should

be used as source alphabet;• at least one symbol from each group should be in

the password;• the symbols pertaining to one or other group

should not be met on neighbor positions in the password;

• the number of symbols pertaining to each group shall be the same;

• the same symbol shall not be met in password more than once.

Passwords complexity

The user shall have a chance to create a strong password from the first attempt.

The control of dictionary password should be implemented without fanaticism like «guess, which password is not in the list of TOP 30M of internet-passwords».

The password rotation should be avoided except the following:

• privileged accounts;• standard accounts.

Passwords complexity

Account blocking after n unsuccessful login attempts => DoS-condition

The introduction of timed delays or anti-automation measures is more preferable.

Brute-forcing may be performed both through passwords for the definite user, and through users for the definite password.

Authentication form is one of the most popular types of oracles.

Accounts Lockout

Password recovery form should not be the oracle for obtaining the users list.

One field for entering an e-mail address and one message about successful sending of the letter with a link for password reset.

The form for entering the new password, not being the user session, opens upon the click on a link.

Any other implementations lead to occurrence of vulnerabilities!

Passwords Recovering

― secret words;― links for password reset;― session identifiers;― any other data, allowing to obtain authenticated

user session,

are authentication equivalents of passwords,to confidentiality of which the same requirements should be imposed!

Password Equivalents

P = hash(password, salt)

Cryptographic hashing functions are not functions for hashing passwords. PBKDF2, bcrypt, scrypt ,etc. should be used for creation of passwords hashes.

The salt length should be sufficient to ensure entropy >= 128 bits for any password, allowed by the security policy.

The main salt assignment is to prevent the attacks on dictionaries and rainbow tables.

Storing Account Data

Cryptography handmade

The entropy of a session token should not be less than 128 bits (token generation using the SRNG or encryption).

Transfer of token should be made in cookie-parameter with flags httponly and secure.

The new token should be created, and the old one should be deleted, after each authentication attempt and upon time-out expiration.

Token deletion should be implemented both on the client-side and on the server-side.

Session management

Example: session fixation

Example: session fixation

The whole available business logic functionality should be distributed explicitly between the roles. A guest is also the role.

Presentation layer: • information disclosure about unavailable

functionality

Business logic layer:• presence of a functionality before authorization

Data layer:• Access control without consideration of the

requested data

Inefficient authorization

Example: bypassing authorization

Example: bypassing authorization

HTTP - response:

{ "d": { "__type" : "Customer:#Web", "Address" : "3 Childers St", "CustomerID" : "3", "Email" : "brucec@aol.com", "FirstName" : "Bruce", "Postcode" : "3000", "State" : "VIC", "Suburb" : "Melbourne" }}

HTTP - request:

Example: bypassing authorization

Preliminary data handling

― Typing is a creation of the specific object type of input data from the string literal (parsing and deserialization).

― Validation is a data checking for compliance with the established criteria:• grammatical;• semantic.

― Sanitization is a matching of data with grammar permitted by security policy.

Approaches to data handling

Typing and validation are on the input, sanitization is on the output!

Look! Don't confuse…

Input data are the formal language.

Some languages are much harder to recognize than others.

For some, recognition is undecidable.

The more complicated the language, the harder it is to form the criteria toinput data describing a set of systemconfigurations.

The generalized approach

Testing the equivalence of finite automata or deterministic stack automata* is decidable.

Such testing is undecidable for non-deterministic stack automata and more powerful models of computation.

In the first case the complete coverage by tests of the processing data language parser elements or their static analysis is possible.

In the second case it is not!

The generalized approach

Steps on implementation of a secure data handling:

Simplification or decomposition of input data language to the set of regular and deterministic context-free grammars.

Implementation of checking input data in the code (typing/validation) in accordance with their grammar should take place as early as possible in the request processing cycle.

Implementation of sanitizing output data in the code, built in accordance with the grammar of the receiving side, should take place as near as possible to their output.

The generalized approach

The vulnerability criteria to attacks of arbitrary injections

The method of formation of output data DOUTPUT on the basis of input data DINPUT is vulnerable to injection attacks, if the number of nodes in the parse tree DOUTPUT depends on the content of

DINPUT

Application example

Example: LINQ Injection

public AjaxStoreResult GetCustomers(int limit, int start, string dir, string sort){    var query = (from c in this.DBContext.Customers                select new                {                    c.CustomerID,                    c.CompanyName,                    c.ContactName,                    c.Phone,                    c.Fax,                    c.Region                }).OrderBy(string.Concat(sort, " ", dir));

    int total = query.ToList().Count;

    query = query.Skip(start).Take(limit);    return new AjaxStoreResult(query, total);}

Example: LINQ Injection

public AjaxStoreResult GetCustomers(int limit, int start, string dir, string sort){    var query = (from c in this.DBContext.Customers                select new                {                    c.CustomerID,                    c.CompanyName,                    c.ContactName,                    c.Phone,                    c.Fax,                    c.Region                }).OrderBy(string.Concat(sort, " ", dir));

    int total = query.ToList().Count;

    query = query.Skip(start).Take(limit);    return new AjaxStoreResult(query, total);}

Example: LINQ Injection

public AjaxStoreResult GetCustomers(int limit, int start, string dir, string sort){ if (!Regex.IsMatch(dir, "(?-m:)(?i:)^asc|desc$")) dir = "ASC"; if (!Regex.IsMatch(sort, "(?-m:)(?i:)^customerid|companyname|contactname|phone|fax|region$")) sort = "CustomerID";    var query = (from c in this.DBContext.Customers                select new                {                    c.CustomerID,                    c.CompanyName,                    c.ContactName,                    c.Phone,                    c.Fax,                    c.Region                }).OrderBy(string.Concat(sort, " ", dir));

    var total = query.ToList().Count;    query = query.Skip(start).Take(limit);    return new AjaxStoreResult(query, total);}

Example: LINQ Injection

public AjaxStoreResult GetCustomers(int limit, int start, string dir, string sort){ if (!Regex.IsMatch(dir, "(?-m:)(?i:)^asc|desc$")) dir = "ASC"; if (!Regex.IsMatch(sort, "(?-m:)(?i:)^customerid|companyname|contactname|phone|fax|region$")) sort = "CustomerID";    var query = (from c in this.DBContext.Customers                select new                {                    c.CustomerID,                    c.CompanyName,                    c.ContactName,                    c.Phone,                    c.Fax,                    c.Region                }).OrderBy(string.Concat(sort, " ", dir));

    var total = query.ToList().Count;    query = query.Skip(start).Take(limit);    return new AjaxStoreResult(query, total);}

Example: XSS

The ASPX page fragment:

<p>You are now leaving this site - we're no longer responsible!</p> <p><asp:Literal runat="server" ID="litLeavingTag" /></p>

Its code behind fragment:

var newUrl = Request.QueryString["Url"];var tagString = "<a href=" + newUrl + ">continue</a>";litLeavingTag.Text = tagString;

Example: XSS

The ASPX page fragment:

<p>You are now leaving this site - we're no longer responsible!</p> <p><asp:Literal runat="server" ID="litLeavingTag" /></p>

Its code behind fragment:

var newUrl = Request.QueryString["Url"];var tagString = "<a href=" + newUrl + ">continue</a>";litLeavingTag.Text = tagString;

The request result: http://host.domain/?url=><script>alert('XSS')</script:

<p><a

href=><script>alert('XSS')</script>continue</a></p>

Example: XSS

The ASPX page fragment:

<p>You are now leaving this site - we're no longer responsible!</p> <p><asp:Literal runat="server" ID="litLeavingTag" /></p>

Its code behind fragment:

var newUrl = Request.QueryString["Url"];var tagString = "<a href=" + Server.HtmlEncode(newUrl) + ">continue</a>";litLeavingTag.Text = tagString;

Example: XSS

The ASPX page fragment:

<p>You are now leaving this site - we're no longer responsible!</p> <p><asp:Literal runat="server" ID="litLeavingTag" /></p>

Its code behind fragment:

var newUrl = Request.QueryString["Url"];var tagString = "<a href=" + Server.HtmlEncode(newUrl) + ">continue</a>";litLeavingTag.Text = tagString;

The request result: http://host.domain/?url=><script>alert('XSS')</script:

<p><a href=&gt;&lt;script&gt;alert('XSS')&lt;/script>continue</a></p>

Demo: how to blow up NPP through XSS

Workflowcontrol

The workflow is well described through states and transition rules between them.

The security policy should be defined and its forced control implemented for all the workflows.

It is necessary to avoid the occurrence of the recursive ways and cycles in a workflow, and to consider the possibility of integrity violation of the shared data.

The current configuration of the flow need to be stored before trust boundaries, but not after it.

The control of integrity workflow

Authenticity of a request source, initiating the transition on workflow, is subject to the mandatory control.

The widespread approach consists in the use of two tokens on each request (one is kept before the trust boundary, and the other one is transferred outside its scope) in order to control the authenticity by comparing them.

The implementation of the control is necessary only for requests, changing the state of the system.

The authenticity control of the initiator operation

Example: CSRF

Example: CSRF

Example: CSRF

...<input type="button" value="Update status" onclick="return UpdateStatus()" />...<script language="javascript" type="text/javascript">// <![CDATA[ function UpdateStatus() { var service = new Web.StatusUpdateService(); var statusUpdate = document.getElementById('txtStatusUpdate').value; service.UpdateStatus(statusUpdate, onSuccess, null, null); }

function onSuccess(result) { var statusUpdate = document.getElementById('txtStatusUpdate').value = ""; __doPostBack('MainContent_updStatusUpdates', ''); }// ]]></script>

Example: CSRF

[OperationContract] public void UpdateStatus(string statusUpdate) { if (!HttpContext.Current.User.Identity.IsAuthenticated) throw new ApplicationException("Not logged on"); var dc = new VulnerableAppDataContext(); dc.Status.InsertOnSubmit(new Status { StatusID = Guid.NewGuid(), StatusDate = DateTime.Now, Username = HttpContext.Current.User.Identity.Name, StatusUpdate = statusUpdate }); dc.SubmitChanges();}

Example: CSRF

[OperationContract] public void UpdateStatus(string statusUpdate) { if (!HttpContext.Current.User.Identity.IsAuthenticated) throw new ApplicationException("Not logged on"); var dc = new VulnerableAppDataContext(); dc.Status.InsertOnSubmit(new Status { StatusID = Guid.NewGuid(), StatusDate = DateTime.Now, Username = HttpContext.Current.User.Identity.Name, StatusUpdate = statusUpdate }); dc.SubmitChanges();}

Example: CSRF

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="http://localhost:85/ScriptResource.axd?d=4sSlXLx8QpYnLirlbD... <script src="http://localhost:85/ScriptResource.axd?d=oW55T29mrRoDmQ0h2E... <script src="http://localhost:85/StatusUpdateService.svc/jsdebug" type="...

<script language="javascript" type="text/javascript"> // <![CDATA[ var service = new Web.StatusUpdateService(); var statusUpdate = "hacky hacky"; service.UpdateStatus(statusUpdate, null, null, null); // ]]> </script> </head> <body> You've been CSRF'd! </body> </html>

Example: CSRF

Example: CSRFprotected string GetToken(){ if (Session["Token"] == null) { Session["Token"] = Guid.NewGuid(); } return Session["Token"].ToString();}...function UpdateStatus(){ var service = new Web.StatusUpdateService(); var statusUpdate = document.getElementById('txtStatusUpdate').value; var token = "<%= GetToken() %>"; service.UpdateStatus(statusUpdate, token, onSuccess, null, null);}...[OperationContract]public void UpdateStatus(string statusUpdate, string token) { var sessionToken = HttpContext.Current.Session["Token"]; if (sessionToken == null || sessionToken.ToString() != token) { throw new ApplicationException("Invalid token"); }...

Example: CSRFprotected string GetToken(){ if (Session["Token"] == null) { Session["Token"] = Guid.NewGuid(); } return Session["Token"].ToString();}...function UpdateStatus(){ var service = new Web.StatusUpdateService(); var statusUpdate = document.getElementById('txtStatusUpdate').value; var token = "<%= GetToken() %>"; service.UpdateStatus(statusUpdate, token, onSuccess, null, null);}...[OperationContract]public void UpdateStatus(string statusUpdate, string token) { var sessionToken = HttpContext.Current.Session["Token"]; if (sessionToken == null || sessionToken.ToString() != token) { throw new ApplicationException("Invalid token"); }...

Implementation of other business logic

Business logic workflows should possess not only by the properties of necessity and sufficiency for their implementation, but also minimality.

Any states and transition rules, implementing «a little bit» more functionality than it is necessary for the current task should be simplified or restricted.

<?=@`$c`?>

PHP arithmetic expressions calculator (the Turing completeness is the foundation for the future, the

code is minimal by now).

The functional excessiveness

Example: accessing hidden datavar fieldName = Request["field"] ?? "Id"; var minValue = int.Parse(Request["min"]); var maxValue = int.Parse(Request["max"]);

var queryTemplate = string.Format( "SELECT Id, Nickname, Rating, MessageCount, TopicCount FROM Users WHERE {0} >= @minValue AND {0} <= @maxValue ORDER BY {0}", fieldName.Replace("'", string.Empty). Replace(" ", string.Empty). Replace("\\", string.Empty). Replace(",", string.Empty). Replace("(", string.Empty). Replace(")", string.Empty),);

var selectCommand = string.Format(queryTemplate, debugStr);

var cmd = new SqlCommand(selectCommand, dataConnection);

cmd.Parameters.Add(new SqlParameter("@minValue", minValue));cmd.Parameters.Add(new SqlParameter("@maxValue", maxValue));

...

/users/filter.aspx?field={fieldName}&min={minBalue}&max={maxValue}

Example: accessing hidden datavar fieldName = Request["field"] ?? "Id"; var minValue = int.Parse(Request["min"]); var maxValue = int.Parse(Request["max"]);

var queryTemplate = string.Format( "SELECT Id, Nickname, Rating, MessageCount, TopicCount FROM Users WHERE {0} >= @minValue AND {0} <= @maxValue ORDER BY {0}", fieldName.Replace("'", string.Empty). Replace(" ", string.Empty). Replace("\\", string.Empty). Replace(",", string.Empty). Replace("(", string.Empty). Replace(")", string.Empty),);

var selectCommand = string.Format(queryTemplate, debugStr);

var cmd = new SqlCommand(selectCommand, dataConnection);

cmd.Parameters.Add(new SqlParameter("@minValue", minValue));cmd.Parameters.Add(new SqlParameter("@maxValue", maxValue));

...

http://host.domain/users/filter.aspx?field=password&min=a&max=a

Example: mass-assignment

public class User {    public int Id { get; set; }    public string UserName { get; set; }    public string Password { get; set; }    public bool IsAdmin { get; set; }}

public class UserController : Controller{    IUserRepository _userRepository;    public UserController(IUserRepository userRepository) {        _userRepository = userRepository;    }

    public ActionResult Edit(int id) {        var user = _userRepository.GetUserById(id);        return View(user);    }

    [HttpPost]    public ActionResult Edit(int id, FormCollection collection) {        try {            var user = _userRepository.GetUserById(id);            UpdateModel(user);            _userRepository.SaveUser(user);            return RedirectToAction("Index");        } catch {            return View();        }    }}

Model: Controller:

Example: mass-assignment

public class User {    public int Id { get; set; }    public string UserName { get; set; }    public string Password { get; set; }    public bool IsAdmin { get; set; }}

public class UserController : Controller{    IUserRepository _userRepository;    public UserController(IUserRepository userRepository) {        _userRepository = userRepository;    }

    public ActionResult Edit(int id) {        var user = _userRepository.GetUserById(id);        return View(user);    }

    [HttpPost]    public ActionResult Edit(int id, FormCollection collection) {        try {            var user = _userRepository.GetUserById(id);            UpdateModel(user);            _userRepository.SaveUser(user);            return RedirectToAction("Index");        } catch {            return View();        }    }}

Model: Controller:

Example: mass-assignment

public class User {    public int Id { get; set; }    public string UserName { get; set; }    public string Password { get; set; }    public bool IsAdmin { get; set; }}

public class UserController : Controller{    IUserRepository _userRepository;    public UserController(IUserRepository userRepository) {        _userRepository = userRepository;    }

    public ActionResult Edit(int id) {        var user = _userRepository.GetUserById(id);        return View(user);    }

    [HttpPost]    public ActionResult Edit(int id, FormCollection collection) {        try {            var user = _userRepository.GetUserById(id); TryUpdateModel(user, includeProperties: new[] { "UserName", "Password" });            _userRepository.SaveUser(user);            return RedirectToAction("Index");        } catch {            return View();        }    }}

Model: Controller:

Example: mass-assignment

public class User {    public int Id { get; set; }    public string UserName { get; set; }    public string Password { get; set; }    public bool IsAdmin { get; set; }}

public class UserController : Controller{    IUserRepository _userRepository;    public UserController(IUserRepository userRepository) {        _userRepository = userRepository;    }

    public ActionResult Edit(int id) {        var user = _userRepository.GetUserById(id);        return View(user);    }

    [HttpPost]    public ActionResult Edit(int id, FormCollection collection) {        try {            var user = _userRepository.GetUserById(id); TryUpdateModel(user, includeProperties: new[] { "UserName", "Password" });            _userRepository.SaveUser(user);            return RedirectToAction("Index");        } catch {            return View();        }    }}

Model: Controller:

Security Development Lifecycle

Microsoft SDL

SDL practices:

― establish security and privacy requirements;

― create quality gates/bug bars;

― perform security and privacy risk assessments.

Requirements

SDL practices:

― establish design requirements;

― attack surface analysis/reduction;

― threat modeling.

Design

SDL practices:

― use approved tools;

― deprecate unsafe functions;

― perform static analysis.

Implementation

SDL practices:

― perform dynamic analysis;

― fuzz-testing;

― attack surface review.

Verification

SDL practices:

― create an incident response plan:• participants;• patch-management strategy;• plans to securing 3rd-party code.

― conduct final security review.

― certify release and archive.

Release

SDL practices:

― execute incident response plan:• advisory analysis;• risk assessment;• patch release and deployment;• client notification;• information disclosure.

Response

SDL implies linearity of the development process, however, SDL practices are well-adapts to agile approaches through their distribution into three categories:

― one-time,executes once

― per-sprint,executes on every sprint

― bucket,at least one practice from the list (bucket) should be executed on each sprint

SDL and Agile

― establish security and privacy requirements;

― perform security and privacy risk assessments;

― establish design requirements;

― attack surface analysis/reduction;

― create an incident response plan.

One-time practices

― learning;― threat modeling;― use approved tools;― deprecate unsafe functions;― perform static analysis;― conduct final security review;― certify release and archive.

Sprint practices

― create quality gates/bug bars;

― perform dynamic analysis;

― fuzz-testing;

― attack surface review.

Bucket pratcies

Thank you for attention!Any questions?

Vladimir Kochetkov

vkochetkov@ptsecurity.ru@kochetkov_v

web applications security researcherPositive Technologies

Materials of the following works were used in the presentation : ― “OWASP Top 10 for .NET Developers” by Troy

Hunt― “The Science of Insecurity” by Len Sassaman,

Meredith L. Patterson, Sergey Bratus― “

The Essence of Command Injection Attacks in Web Applications” by Zhendong Su, Gary Wassermann

― “Modeling Computer Insecurity” by Sophie Engle, Sean Whalen, Matt Bishop

Copyrights

Recommended