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
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
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
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
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
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
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
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
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=><script>alert('XSS')</script>continue</a></p>
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
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
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
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