SlideShare ist ein Scribd-Unternehmen logo
1 von 138
How to Develop a Secure Web
Application and Stay in Mind?
Vladimir Kochetkov
web applications security researcher
Positive Technologies
Translated into English by @pand0chka
Positive 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.1
Host: superdupershop.com
Cookie: ASP.NET_SessionId=10g5o4zjkmbd2i552d5j3255;.ASPXAUTH=
f2d345118221742ee0316d4080a53af014eb8a3161db421d36aa6a86ffea6781b558
4f4157ec85ae5956cfc54cc93c34a3f9449c8ef4c70b5b54d46e0def3677cce9a810
5340b8ccc6c8e64dfa37ae953f987517
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*
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
AbuseofFunctionality
BruteForce
Buffer/FormatStringOverflow
ContentSpoofing
Credential/SessionPrediction
Cross-SiteRequestForgery
Cross-SiteScripting
DenialofService
Fingerprinting
HPP/HPC
HRS
IntegerOverflows
LDAPInjection
MailCommandInjection
NullByteInjection
OSCommanding
PathTraversal
PredictableResourceLocation
Remote/LocalFileInclusion
RoutingDetour
SessionFixation
SOAPArrayAbuse
SQLInjection
SSIInjection
URLRedirectorAbuse
XMLAttributeBlowup
XMLEntityExpansion
XMLExternalEntities
XMLInjection
XPath/XQueryInjection
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 the
complete or partial control over initial machine.
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 Users
External systems
Process Executables
Components
OS Services
Web-services
Data flow Function calls
Network data
Data storage Databases
Files
Data structures
Trust boundary Processes
Machines
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-Content-Type-Options {nosniff} disables MIME-type
recognition in the IE
(http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-
security-part-v-comprehensive-protection.aspx)
― X-XSS-Protection {0 | 1 | 1; mode=block} controls XSS-
filter in the IE
(http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/
controlling-the-internet-explorer-xss-filter-with-the-x-xss-
protection-http-header.aspx)
4 HTTP-headers
― 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 to
input data describing a set of system
configurations.
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
Workflow
control
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: CSRF
protected 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: CSRF
protected 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 data
var 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 data
var 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
Recommended topics:
― Pre-SDL:
• Introduction to the SDL;
• Essential Software Security Training for the Microsoft
SDL .
― Requirements phase:
• Privacy in Software Development;
Training
Recommended topics:
― Design, implementation and :
• Basics of Secure Design, Development and Testing;
• Introduction to Threat Modeling;
• SDL Quick Security References;
• SDL Developer Starter Kit.
Training
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 researcher
Positive 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
How to Develop a Secure Web Application and Stay in Mind? (PHDays 3)

Weitere ähnliche Inhalte

Was ist angesagt?

Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by defaultSecuRing
 
introduction to jsrsasign
introduction to jsrsasignintroduction to jsrsasign
introduction to jsrsasignKenji Urushima
 
Java EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank KimJava EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank Kimjaxconf
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Derrick Isaacson
 
Locking the Throneroom 2.0
Locking the Throneroom 2.0Locking the Throneroom 2.0
Locking the Throneroom 2.0Mario Heiderich
 
На страже ваших денег и данных
На страже ваших денег и данныхНа страже ваших денег и данных
На страже ваших денег и данныхPositive Hack Days
 
The Ultimate IDS Smackdown
The Ultimate IDS SmackdownThe Ultimate IDS Smackdown
The Ultimate IDS SmackdownMario Heiderich
 
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方Hiroshi Tokumaru
 
Внедрение безопасности в веб-приложениях в среде выполнения
Внедрение безопасности в веб-приложениях в среде выполненияВнедрение безопасности в веб-приложениях в среде выполнения
Внедрение безопасности в веб-приложениях в среде выполненияPositive Hack Days
 
Do WAFs dream of static analyzers
Do WAFs dream of static analyzersDo WAFs dream of static analyzers
Do WAFs dream of static analyzersVladimir Kochetkov
 
Hack any website
Hack any websiteHack any website
Hack any websitesunil kumar
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developersMichel Schudel
 
How to get rid of terraform plan diffs
How to get rid of terraform plan diffsHow to get rid of terraform plan diffs
How to get rid of terraform plan diffsYukiya Hayashi
 
Advanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection ProtectionAdvanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection Protectionamiable_indian
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindAndreas Czakaj
 
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...Jakub Kałużny
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeAndrey Karpov
 
Java Secure Coding Practices
Java Secure Coding PracticesJava Secure Coding Practices
Java Secure Coding PracticesOWASPKerala
 

Was ist angesagt? (20)

Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
introduction to jsrsasign
introduction to jsrsasignintroduction to jsrsasign
introduction to jsrsasign
 
Java EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank KimJava EE Web Security By Example: Frank Kim
Java EE Web Security By Example: Frank Kim
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015
 
Locking the Throneroom 2.0
Locking the Throneroom 2.0Locking the Throneroom 2.0
Locking the Throneroom 2.0
 
На страже ваших денег и данных
На страже ваших денег и данныхНа страже ваших денег и данных
На страже ваших денег и данных
 
The Ultimate IDS Smackdown
The Ultimate IDS SmackdownThe Ultimate IDS Smackdown
The Ultimate IDS Smackdown
 
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方
SSRF対策としてAmazonから発表されたIMDSv2の効果と破り方
 
Внедрение безопасности в веб-приложениях в среде выполнения
Внедрение безопасности в веб-приложениях в среде выполненияВнедрение безопасности в веб-приложениях в среде выполнения
Внедрение безопасности в веб-приложениях в среде выполнения
 
Secure coding in C#
Secure coding in C#Secure coding in C#
Secure coding in C#
 
Do WAFs dream of static analyzers
Do WAFs dream of static analyzersDo WAFs dream of static analyzers
Do WAFs dream of static analyzers
 
Hack any website
Hack any websiteHack any website
Hack any website
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 
How to get rid of terraform plan diffs
How to get rid of terraform plan diffsHow to get rid of terraform plan diffs
How to get rid of terraform plan diffs
 
Advanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection ProtectionAdvanced Topics On Sql Injection Protection
Advanced Topics On Sql Injection Protection
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
 
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the code
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
Java Secure Coding Practices
Java Secure Coding PracticesJava Secure Coding Practices
Java Secure Coding Practices
 

Andere mochten auch

Dr Dobbs Example
Dr  Dobbs ExampleDr  Dobbs Example
Dr Dobbs Examplecpshively
 
An Exceptionally Simple Theory of AppSec .NET
An Exceptionally Simple Theory of AppSec .NETAn Exceptionally Simple Theory of AppSec .NET
An Exceptionally Simple Theory of AppSec .NETMikhail Shcherbakov
 
Mythbusters - Web Application Security
Mythbusters - Web Application SecurityMythbusters - Web Application Security
Mythbusters - Web Application SecurityMikhail Shcherbakov
 
Hacker, you shall not pass!
Hacker, you shall not pass!Hacker, you shall not pass!
Hacker, you shall not pass!Cláudio André
 
URLs and Domains (SMX East 2008)
URLs and Domains (SMX East 2008)URLs and Domains (SMX East 2008)
URLs and Domains (SMX East 2008)Nathan Buggia
 
Безопасная разработка для руководителей
Безопасная разработка для руководителейБезопасная разработка для руководителей
Безопасная разработка для руководителейPositive Development User Group
 
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)Vladimir Kochetkov
 
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya Palla
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya PallaAdobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya Palla
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya PallaKrishna Chaitanya Palla
 
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)Vladimir Kochetkov
 
Прикладная теория Application Security
Прикладная теория Application SecurityПрикладная теория Application Security
Прикладная теория Application SecurityVladimir Kochetkov
 
How to Choose a Domain Name (tips to buy and register the best domains)
How to Choose a Domain Name (tips to buy and register the best domains) How to Choose a Domain Name (tips to buy and register the best domains)
How to Choose a Domain Name (tips to buy and register the best domains) Pickaweb
 
Современные подходы к SAST
Современные подходы к SASTСовременные подходы к SAST
Современные подходы к SASTVladimir Kochetkov
 
Философия Application Security
Философия Application SecurityФилософия Application Security
Философия Application SecurityVladimir Kochetkov
 
Подводные камни прикладной криптографии, I
Подводные камни прикладной криптографии, IПодводные камни прикладной криптографии, I
Подводные камни прикладной криптографии, IVladimir Kochetkov
 
Infrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryInfrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryCarlo Bonamico
 
Автоматическая генерация патчей для уязвимого исходного кода
Автоматическая генерация патчей для уязвимого исходного кодаАвтоматическая генерация патчей для уязвимого исходного кода
Автоматическая генерация патчей для уязвимого исходного кодаVladimir Kochetkov
 
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Carlo Bonamico
 

Andere mochten auch (20)

Dr Dobbs Example
Dr  Dobbs ExampleDr  Dobbs Example
Dr Dobbs Example
 
.NET for hackers
.NET for hackers.NET for hackers
.NET for hackers
 
An Exceptionally Simple Theory of AppSec .NET
An Exceptionally Simple Theory of AppSec .NETAn Exceptionally Simple Theory of AppSec .NET
An Exceptionally Simple Theory of AppSec .NET
 
Mythbusters - Web Application Security
Mythbusters - Web Application SecurityMythbusters - Web Application Security
Mythbusters - Web Application Security
 
Hacker, you shall not pass!
Hacker, you shall not pass!Hacker, you shall not pass!
Hacker, you shall not pass!
 
International SEO
International SEOInternational SEO
International SEO
 
URLs and Domains (SMX East 2008)
URLs and Domains (SMX East 2008)URLs and Domains (SMX East 2008)
URLs and Domains (SMX East 2008)
 
Безопасная разработка для руководителей
Безопасная разработка для руководителейБезопасная разработка для руководителей
Безопасная разработка для руководителей
 
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)
Как разработать защищенное веб-приложение и не сойти при этом с ума (вебинар)
 
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya Palla
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya PallaAdobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya Palla
Adobe AEM(6.0-6.1)_AEM Forms(6.1-6.2)_Developer_KrishnaChaitanya Palla
 
Error codes & custom 404s
Error codes & custom 404sError codes & custom 404s
Error codes & custom 404s
 
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)
Как разработать защищенное веб-приложение и не сойти при этом с ума? (PHDays 3)
 
Прикладная теория Application Security
Прикладная теория Application SecurityПрикладная теория Application Security
Прикладная теория Application Security
 
How to Choose a Domain Name (tips to buy and register the best domains)
How to Choose a Domain Name (tips to buy and register the best domains) How to Choose a Domain Name (tips to buy and register the best domains)
How to Choose a Domain Name (tips to buy and register the best domains)
 
Современные подходы к SAST
Современные подходы к SASTСовременные подходы к SAST
Современные подходы к SAST
 
Философия Application Security
Философия Application SecurityФилософия Application Security
Философия Application Security
 
Подводные камни прикладной криптографии, I
Подводные камни прикладной криптографии, IПодводные камни прикладной криптографии, I
Подводные камни прикладной криптографии, I
 
Infrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryInfrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous Delivery
 
Автоматическая генерация патчей для уязвимого исходного кода
Автоматическая генерация патчей для уязвимого исходного кодаАвтоматическая генерация патчей для уязвимого исходного кода
Автоматическая генерация патчей для уязвимого исходного кода
 
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
 

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

Threat modelling(system + enterprise)
Threat modelling(system + enterprise)Threat modelling(system + enterprise)
Threat modelling(system + enterprise)abhimanyubhogwan
 
Monitoring your organization against threats - Critical System Control
Monitoring your organization against threats - Critical System ControlMonitoring your organization against threats - Critical System Control
Monitoring your organization against threats - Critical System ControlMarc-Andre Heroux
 
Phi 235 social media security users guide presentation
Phi 235 social media security users guide presentationPhi 235 social media security users guide presentation
Phi 235 social media security users guide presentationAlan Holyoke
 
Security engineering 101 when good design & security work together
Security engineering 101  when good design & security work togetherSecurity engineering 101  when good design & security work together
Security engineering 101 when good design & security work togetherWendy Knox Everette
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare ☁
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare ☁
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare ☁
 
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?Izar Tarandach
 
How to Perform Continuous Vulnerability Management
How to Perform Continuous Vulnerability ManagementHow to Perform Continuous Vulnerability Management
How to Perform Continuous Vulnerability ManagementIvanti
 
user centric machine learning framework for cyber security operations center
user centric machine learning framework for cyber security operations centeruser centric machine learning framework for cyber security operations center
user centric machine learning framework for cyber security operations centerVenkat Projects
 
111.pptx
111.pptx111.pptx
111.pptxJESUNPK
 
Appsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martinAppsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martindrewz lin
 
Security architecture, engineering and operations
Security architecture, engineering and operationsSecurity architecture, engineering and operations
Security architecture, engineering and operationsPiyush Jain
 
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...idsecconf
 
Endpoint Modeling 101 - A New Approach to Endpoint Security
Endpoint Modeling 101 - A New Approach to Endpoint SecurityEndpoint Modeling 101 - A New Approach to Endpoint Security
Endpoint Modeling 101 - A New Approach to Endpoint SecurityObservable Networks
 
Security Patterns - An Introduction
Security Patterns - An IntroductionSecurity Patterns - An Introduction
Security Patterns - An IntroductionMarcel Winandy
 
Project Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docxProject Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docxwkyra78
 

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

Threat modelling(system + enterprise)
Threat modelling(system + enterprise)Threat modelling(system + enterprise)
Threat modelling(system + enterprise)
 
Monitoring your organization against threats - Critical System Control
Monitoring your organization against threats - Critical System ControlMonitoring your organization against threats - Critical System Control
Monitoring your organization against threats - Critical System Control
 
Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011
 
Phi 235 social media security users guide presentation
Phi 235 social media security users guide presentationPhi 235 social media security users guide presentation
Phi 235 social media security users guide presentation
 
Security engineering 101 when good design & security work together
Security engineering 101  when good design & security work togetherSecurity engineering 101  when good design & security work together
Security engineering 101 when good design & security work together
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?
O'Reilly SACon 2019 - (Continuous) Threat Modeling - What works?
 
How to Perform Continuous Vulnerability Management
How to Perform Continuous Vulnerability ManagementHow to Perform Continuous Vulnerability Management
How to Perform Continuous Vulnerability Management
 
user centric machine learning framework for cyber security operations center
user centric machine learning framework for cyber security operations centeruser centric machine learning framework for cyber security operations center
user centric machine learning framework for cyber security operations center
 
111.pptx
111.pptx111.pptx
111.pptx
 
Appsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martinAppsec2013 assurance tagging-robert martin
Appsec2013 assurance tagging-robert martin
 
Security architecture, engineering and operations
Security architecture, engineering and operationsSecurity architecture, engineering and operations
Security architecture, engineering and operations
 
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...
idsecconf2023 - Mangatas Tondang, Wahyu Nuryanto - Penerapan Model Detection ...
 
Endpoint Modeling 101 - A New Approach to Endpoint Security
Endpoint Modeling 101 - A New Approach to Endpoint SecurityEndpoint Modeling 101 - A New Approach to Endpoint Security
Endpoint Modeling 101 - A New Approach to Endpoint Security
 
ISAA
ISAAISAA
ISAA
 
Security Patterns - An Introduction
Security Patterns - An IntroductionSecurity Patterns - An Introduction
Security Patterns - An Introduction
 
Security engineering
Security engineeringSecurity engineering
Security engineering
 
Project Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docxProject Quality-SIPOCSelect a process of your choice and creat.docx
Project Quality-SIPOCSelect a process of your choice and creat.docx
 

Mehr von Vladimir Kochetkov

Практическое использование средств криптографии в .NET, Java и PHP
Практическое использование средств криптографии в .NET, Java и PHPПрактическое использование средств криптографии в .NET, Java и PHP
Практическое использование средств криптографии в .NET, Java и PHPVladimir Kochetkov
 
AppSec -- хакерский путь
AppSec -- хакерский путьAppSec -- хакерский путь
AppSec -- хакерский путьVladimir Kochetkov
 
Подводные камни System.Security.Cryptography
Подводные камни System.Security.CryptographyПодводные камни System.Security.Cryptography
Подводные камни System.Security.CryptographyVladimir Kochetkov
 
Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Vladimir Kochetkov
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Vladimir Kochetkov
 
Automated Patching for Vulnerable Source Code
Automated Patching for Vulnerable Source CodeAutomated Patching for Vulnerable Source Code
Automated Patching for Vulnerable Source CodeVladimir Kochetkov
 
Исключительно простая теория AppSec .NET
Исключительно простая теория AppSec .NETИсключительно простая теория AppSec .NET
Исключительно простая теория AppSec .NETVladimir Kochetkov
 

Mehr von Vladimir Kochetkov (7)

Практическое использование средств криптографии в .NET, Java и PHP
Практическое использование средств криптографии в .NET, Java и PHPПрактическое использование средств криптографии в .NET, Java и PHP
Практическое использование средств криптографии в .NET, Java и PHP
 
AppSec -- хакерский путь
AppSec -- хакерский путьAppSec -- хакерский путь
AppSec -- хакерский путь
 
Подводные камни System.Security.Cryptography
Подводные камни System.Security.CryptographyПодводные камни System.Security.Cryptography
Подводные камни System.Security.Cryptography
 
Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!
 
Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible! Hack an ASP .NET website? Hard, but possible!
Hack an ASP .NET website? Hard, but possible!
 
Automated Patching for Vulnerable Source Code
Automated Patching for Vulnerable Source CodeAutomated Patching for Vulnerable Source Code
Automated Patching for Vulnerable Source Code
 
Исключительно простая теория AppSec .NET
Исключительно простая теория AppSec .NETИсключительно простая теория AppSec .NET
Исключительно простая теория AppSec .NET
 

Kürzlich hochgeladen

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 

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

  • 1.
  • 2. How to Develop a Secure Web Application and Stay in Mind? Vladimir Kochetkov web applications security researcher Positive Technologies Translated into English by @pand0chka Positive Hack Days III
  • 4. ― 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?
  • 5. GET /api/shop/discount?shopId=3&productId=1584&coupon=1y3z9 HTTP/1.1 Host: superdupershop.com Cookie: ASP.NET_SessionId=10g5o4zjkmbd2i552d5j3255;.ASPXAUTH= f2d345118221742ee0316d4080a53af014eb8a3161db421d36aa6a86ffea6781b558 4f4157ec85ae5956cfc54cc93c34a3f9449c8ef4c70b5b54d46e0def3677cce9a810 5340b8ccc6c8e64dfa37ae953f987517 Attention, the black box!
  • 6. 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!
  • 7. 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?
  • 8. 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!
  • 10. 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
  • 11. ― 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
  • 12. It is necessary to fight the causes, not the consequences! Causes and consequences Weakness Threat Vulnerability Attack Risk Insecurity Unsafeness
  • 13. 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
  • 15. ― 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”
  • 16. * based on poll results http://www.rsdn.ru/?poll/3488 Developers awareness* 0.00% 10.00% 20.00% 30.00% 40.00% 50.00% 60.00% 70.00% 80.00% 90.00% AbuseofFunctionality BruteForce Buffer/FormatStringOverflow ContentSpoofing Credential/SessionPrediction Cross-SiteRequestForgery Cross-SiteScripting DenialofService Fingerprinting HPP/HPC HRS IntegerOverflows LDAPInjection MailCommandInjection NullByteInjection OSCommanding PathTraversal PredictableResourceLocation Remote/LocalFileInclusion RoutingDetour SessionFixation SOAPArrayAbuse SQLInjection SSIInjection URLRedirectorAbuse XMLAttributeBlowup XMLEntityExpansion XMLExternalEntities XMLInjection XPath/XQueryInjection Attacks based on WASC classification Attacks included at OWASP Top 10 risks
  • 17. Risks are for managers… … not for developers!
  • 18. “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
  • 19. Functional weaknesses … are also causes of vulnerabilities!
  • 20. 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
  • 21. What is a vulnerability?
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. Replaces all occurrences of the character «a» What happens if the input string will contain an empty symbol or “#”? Demo ?
  • 27. 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 the complete or partial control over initial machine. Weird-machine
  • 28. 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
  • 29. 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
  • 30. The complete model of a secure TM «and we need to go deeper» (с)
  • 31. "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.
  • 32. The semantics of any discrete process can be described as a set of states and conditions of transition between them. What for all this?!
  • 33. 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?!
  • 34. 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?!
  • 35. 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.
  • 37. 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
  • 38. The Process DFD creation or update Threats identification Countermeasures elaboration Model validation
  • 39. DFD Creation or Update Element Figure Examples External entity Users External systems Process Executables Components OS Services Web-services Data flow Function calls Network data Data storage Databases Files Data structures Trust boundary Processes Machines
  • 40. DFD Creation or Update
  • 41. 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
  • 42. DFD Creation or Update
  • 43. ― 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
  • 44. ― 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
  • 45. 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
  • 46. 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 √ √ √ √ √ √ √ √ √ √ √ √ ?* √ √
  • 47. 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
  • 48. 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
  • 49. Creation of the threat model for a typical web-application Example
  • 51. 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
  • 53. - 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
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. - 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
  • 60. HTTP-response status codes: Information disclosure <customErrors mode="On" /> <customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/Error.aspx" />
  • 61. Oracle is a weird-machine, answering the attacker questions within its functionality. The most famous example: padding oracle. Oracles creation
  • 62. ― 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
  • 64. ― X-Content-Type-Options {nosniff} disables MIME-type recognition in the IE (http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8- security-part-v-comprehensive-protection.aspx) ― X-XSS-Protection {0 | 1 | 1; mode=block} controls XSS- filter in the IE (http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/ controlling-the-internet-explorer-xss-filter-with-the-x-xss- protection-http-header.aspx) 4 HTTP-headers
  • 65. ― 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
  • 66. How developers use a CSP * based on poll results http://www.rsdn.ru/?poll/33884 as of 20 may 2013
  • 67. 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
  • 69. Identification: establishing identity Authentication: proven establishing identity Authorization: assigning rights to identity Phases of access control
  • 71. 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
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. 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
  • 76. ― 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
  • 77. 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
  • 79. 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
  • 82. 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
  • 84. 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:
  • 87. ― 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
  • 88. Typing and validation are on the input, sanitization is on the output! Look! Don't confuse…
  • 89. 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 to input data describing a set of system configurations. The generalized approach
  • 90. 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
  • 91. 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
  • 92. 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
  • 93. 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); }
  • 94. 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); }
  • 95. 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); }
  • 96. 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); }
  • 97. 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;
  • 98. 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>
  • 99. 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;
  • 100. 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>
  • 101. Demo: how to blow up NPP through XSS
  • 103. 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
  • 104. 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
  • 107. 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>
  • 108. 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(); }
  • 109. 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(); }
  • 110. 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>
  • 112. Example: CSRF protected 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"); } ...
  • 113. Example: CSRF protected 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"); } ...
  • 115. 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
  • 116. Example: accessing hidden data var 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}
  • 117. Example: accessing hidden data var 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
  • 118. 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:
  • 119. 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:
  • 120. 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:
  • 121. 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:
  • 124. Recommended topics: ― Pre-SDL: • Introduction to the SDL; • Essential Software Security Training for the Microsoft SDL . ― Requirements phase: • Privacy in Software Development; Training
  • 125. Recommended topics: ― Design, implementation and : • Basics of Secure Design, Development and Testing; • Introduction to Threat Modeling; • SDL Quick Security References; • SDL Developer Starter Kit. Training
  • 126. SDL practices: ― establish security and privacy requirements; ― create quality gates/bug bars; ― perform security and privacy risk assessments. Requirements
  • 127. SDL practices: ― establish design requirements; ― attack surface analysis/reduction; ― threat modeling. Design
  • 128. SDL practices: ― use approved tools; ― deprecate unsafe functions; ― perform static analysis. Implementation
  • 129. SDL practices: ― perform dynamic analysis; ― fuzz-testing; ― attack surface review. Verification
  • 130. 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
  • 131. SDL practices: ― execute incident response plan: • advisory analysis; • risk assessment; • patch release and deployment; • client notification; • information disclosure. Response
  • 132. 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
  • 133. ― 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
  • 134. ― learning; ― threat modeling; ― use approved tools; ― deprecate unsafe functions; ― perform static analysis; ― conduct final security review; ― certify release and archive. Sprint practices
  • 135. ― create quality gates/bug bars; ― perform dynamic analysis; ― fuzz-testing; ― attack surface review. Bucket pratcies
  • 136. Thank you for attention! Any questions? Vladimir Kochetkov vkochetkov@ptsecurity.ru @kochetkov_v web applications security researcher Positive Technologies
  • 137. 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