138

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

Embed Size (px)

DESCRIPTION

English version of the workshop slides from PHDays III

Citation preview

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

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

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

Synopsis

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

― 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?

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

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!

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

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!

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

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?

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

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!

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

Glossary

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

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

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

― 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

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

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

Causes and consequences

Weakness Threat

Vulnerability Attack

Risk

Insecurity

Unsafeness

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

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

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

Typical mindset

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

― 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”

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

* 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

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

Risks are for managers…

… not for developers!

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

“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

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

Functional weaknesses

… are also causes of

vulnerabilities!

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

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

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

What is a vulnerability?

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

A slightly boring theory

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

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

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

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

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

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

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

Replaces all occurrences of the character «a»

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

Demo

?

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

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

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

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

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

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

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

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

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

"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.

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

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

What for all this?!

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

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?!

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

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?!

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

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.

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

Threat modeling

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

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

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

The Process

DFD creation or update

Threats identification

Countermeasures elaboration

Model validation

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

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

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

DFD Creation or Update

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

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

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

DFD Creation or Update

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

― 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

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

― 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

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

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

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

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

√ √√ √ √ √ √ √

√ √ √√ ?* √ √

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

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

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

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

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

Creation of the threat model for a typical web-application

Example

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

Default configuration security

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

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

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

Transport layer security

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

- 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

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

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

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

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

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

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

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

- 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

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

Error handling

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

Error messages:

Information disclosure

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

HTTP-response status codes:

Information disclosure

<customErrors mode="On" />

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

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

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

The most famous example: padding oracle.

Oracles creation

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

― 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

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

Client-side security

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

― 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

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

How developers use a CSP

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

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

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

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

Access Control

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

Identification:establishing identity

Authentication:proven establishing identity

Authorization:assigning rights to identity

Phases of access control

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

Passwords complexity

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

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

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

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

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

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

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

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

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

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

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

― 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

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

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

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

Cryptography handmade

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

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

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

Example: session fixation

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

Example: session fixation

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

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

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

Example: bypassing authorization

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

Example: bypassing authorization

HTTP - response:

{ "d": { "__type" : "Customer:#Web", "Address" : "3 Childers St", "CustomerID" : "3", "Email" : "[email protected]", "FirstName" : "Bruce", "Postcode" : "3000", "State" : "VIC", "Suburb" : "Melbourne" }}

HTTP - request:

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

Example: bypassing authorization

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

Preliminary data handling

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

― 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

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

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

Look! Don't confuse…

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

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

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

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

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

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

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

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

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

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);}

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

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);}

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

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);}

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

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);}

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

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;

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

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>

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

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;

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

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>

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

Demo: how to blow up NPP through XSS

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

Workflowcontrol

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

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

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

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

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

Example: CSRF

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

Example: CSRF

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

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>

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

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();}

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

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();}

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

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>

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

Example: CSRF

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

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"); }...

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

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"); }...

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

Implementation of other business logic

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

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

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

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}

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

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

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

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:

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

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:

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

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:

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

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:

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

Security Development Lifecycle

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

Microsoft SDL

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

SDL practices:

― establish security and privacy requirements;

― create quality gates/bug bars;

― perform security and privacy risk assessments.

Requirements

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

SDL practices:

― establish design requirements;

― attack surface analysis/reduction;

― threat modeling.

Design

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

SDL practices:

― use approved tools;

― deprecate unsafe functions;

― perform static analysis.

Implementation

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

SDL practices:

― perform dynamic analysis;

― fuzz-testing;

― attack surface review.

Verification

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

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

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

SDL practices:

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

Response

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

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

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

― 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

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

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

Sprint practices

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

― create quality gates/bug bars;

― perform dynamic analysis;

― fuzz-testing;

― attack surface review.

Bucket pratcies

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

Thank you for attention!Any questions?

Vladimir Kochetkov

[email protected]@kochetkov_v

web applications security researcherPositive Technologies

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

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

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