SlideShare une entreprise Scribd logo
1  sur  66
Télécharger pour lire hors ligne
Coding SecurityCoding Security
Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP
Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017
Coding SecurityCoding Security
Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP
Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017
WhoAmI
● Lazy Blogger
– Japan, Security, FOSS, Politics, Christian
– http://narudomr.blogspot.com
● Information Security since 1995
● Web Application Development since 1998
● Head of IT Security and Solution Architecture, Kiatnakin Bank
PLC (KKP)
● Consultant for OWASP Thailand Chapter
● Committee Member of Cloud Security Alliance (CSA), Thailand
Chapter
● Consulting Team Member for National e-Payment project
● Committee Member of Thailand Banking Sector CERT (TB-CERT)
● Contact: narudom@owasp.org
Software Security Fundamental
What is Security?
 “The quality or state of being secure—to be free
from danger”
 A successful organization should have multiple
layers of security in place:

Physical security

Personal security

Operations security

Communications security

Network security

Information security
What is Information Security?
 The protection of information and its critical
elements, including systems and hardware that
use, store, and transmit that information
 Necessary tools: policy, awareness, training,
education, technology
What Is Software Security?
● Reliability: Functions as it is expected to.
● Resiliency: Does not violate any security policy and
is able to withstand the actions of threat agents that
are posed intentionally (attacks and exploits) or
accidentally (user errors).
● Recoverability: The software is able to restore
operations to what the business expects by
containing and limiting the damage caused by
threats that materialize.
Security Concepts
Security Concepts
Core
Design
Confidentiality Integrity Availibility
Authentication Authorization Accountability
Need to Know Least Privilege
Separation of
Duties
Defense in Depth
Fail Safe /
Fail Secure
Economy of
Mechanisms
Complete
Mediation
Open Design
Least Common
Mechanisms
Psychological
Acceptability
Weakest Link
Leveraging Existing
Components
Confidentiality-Integrity-Availability (CIA)
To ensure that
information and
vital services are
accessible for use
when required
To ensure the accuracy and completeness of information
to protect business processes
To ensure
protection against
unauthorized
access to or use of
confidential
information
Do Network Security Devices Protect All Attacks?
Source: IBM Software Group, Rational Software
OWASP Top 10 2013 Risk
Source: OWASP: Open Web Application Security Project
Security controls cannot
deal with broken business
logic such as A2, A4 and A7
Security controls cannot
deal with broken business
logic such as A2, A4 and A7
Software weaknesses
reduction down to zero is
possible
Software weaknesses
reduction down to zero is
possible
Reduce Security Weaknesses vs
Increase Security Controls
Source: OWASP: Open Web Application Security Project
Security as an Afterthought
Relative cost of security fixes, based on time of detection
Implementation Challenges
Source: The National Institute of Standards and Technology (NIST)
Coding Security Practices #1
Input Validation
Goal of Input Validation
● Ensure only properly formed data is entering the
workflow in an information system
● Prevent malformed data from persisting in the
system or triggering malfunction of various
downstream components (injection)
● Validate all data from untrusted source
Input Validation Strategies
● Syntactic – Enforce correct syntax of structured
fields (e.g. Citizen ID, date, currency symbol)
● Semantic – Enforce correctness of their values in
the specific business context (e.g. start date is
before end date, price is within expected range)
● Prevent attacks as early as possible in the
processing of the user’s (attacker's) request
● Detect unauthorized input before it is processed by
the application
Implementing Input Validation Examples
● Data type validators available natively in web application
frameworks (such as Django Validators, Apache Commons
Validators etc)
● Validation against JSON Schema and XML Schema (XSD) for
input in these formats
● Type conversion (e.g. Integer.parseInt() in Java, int() in
Python) with strict exception handling
● Minimum and maximum value range check for numerical
parameters and dates, minimum and maximum length check
for strings
● Array of allowed values for small sets of string parameters
(e.g. days of week)
● Regular expressions for any other structured data covering
the whole input string (^...$) and not using "any character"
wildcard (such as "." or "S")
Client Side vs Server Side Validation
● Client-side validation is to provide a better user
experience by responding quickly at the browser
level but not actually mandatory
● Server-side validation is mandatory due to the fact
that client-side validation can be completely
bypassed (by turning off JavaScript, manipulating
HTTP request via web proxy)
How to Manipulate HTTP Request
● Using Web Proxy (Burp Suite, Paros,
WebScarab,OWASP: Zed Attack Proxy (ZAP))
Whitelist vs Blacklist
● It is a common mistake black list validation in order
to try to detect possibly dangerous characters (e.g.
the apostrophe ' character, the string 1=1, or the
<script> tag)
● White list validation is appropriate for all input
fields provided by the user
– Defining exactly what is authorized, and by definition,
everything else is not authorized
– If it's well structured data, like dates, social security
numbers, zip codes, e-mail addresses, etc. pattern
matching validation is perfect.
– If the input field comes from a fixed set of options, like a
drop down list or radio buttons, then the exact match is
perfect.
Vulnerabilities Prevented
● OWASP Top 10 2013
– A1: Injection
– A3: Cross-Site Scripting (XSS)
● OWASP Mobile Top 10 2016
– M7: Client Side Injection
Coding Security Practices #2
Output Handling
Goal of Output Handling
● Prevent the output data from our application being
unintended interpretation at the destination
systems (web browser, database, LDAP, web service)
Output Handling Strategies
● Sanitization: Transforming data from its original
form to an acceptable form either by removal of
that data, or by encoding or decoding it.
– Common encoding methods used in web applications
include the HTML entity encoding and URL Encoding
schemes
● Filtering: Acceptance or the rejection of output
based on predefined criteria.
Output Handling Examples
● Conduct all encoding on a trusted system (e.g., the server)
● Utilize a standard, tested routine for each type of outbound
encoding
● Contextually output encode all data returned to the client
that originated outside the application's trust boundary.
– HTML entity encoding is one example, but does not work in all
cases
● Encode all characters unless they are known to be safe for
the intended interpreter
● Contextually sanitize all output of untrusted data to queries
for SQL, XML, and LDAP
● Sanitize all output of untrusted data to operating system
commands
Vulnerabilities Prevented
● OWASP Top 10 2013
– A1: Injection
– A3: Cross-Site Scripting (XSS)
● OWASP Mobile Top 10 2016
– M7: Client Side Injection
Coding Security Practices #3
Parameterize Queries
Goal of Parameterize Queries
● Prevent user or untrusted input from being
interpreted as part of a SQL command
SQL Injection is one of the most dangerous web application
risks. SQL Injection is easy to exploit with many open source
automated attack tools available. SQL injection can also
deliver an impact to your application that is devastating.
Why String Concatenation to Construct SQL
Statement is Evil?
The following C# code dynamically constructs and executes a SQL
query that searches for items matching a specified name. The query
restricts the items displayed to those where owner matches the user
name of the currently-authenticated user.
...
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = "'"
+ userName + "' AND itemname = '"
+ ItemName.Text + "'";
sda = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
...
The query that this code intends to execute follows:
SELECT * FROM items WHERE owner = 'someone' AND
itemname = 'something';
Why String Concatenation to Construct SQL
Statement is Evil? (cont’d)
If an attacker with the user name hacker enters the string "name');
DELETE FROM items; --" for itemName, then the query becomes the
following two queries:
SELECT * FROM items WHERE owner = 'hacker' AND
itemname = 'name';
DELETE FROM items;
--'
Parameterize Query Example
String newName = request.getParameter("newName");
int id = Integer.parseInt(request.getParameter("id"));
PreparedStatement pstmt = con.prepareStatement(
"UPDATE EMPLOYEES SET NAME = ? WHERE ID = ?");
pstmt.setString(1, newName);
pstmt.setInt(2, id);
Java
PHP using PDO
$stmt = $dbh>prepare(”update users set email=:new_email
where id=:user_id”);
$stmt>bindParam(':new_email', $email);
$stmt>bindParam(':user_id', $id);
Parameterize Query Example (cont’d)
email = REQUEST[‘email’]
id = REQUEST[‘id’]
cur.execute(update users set email=:new_email where
id=:user_id”, {"new_email": email, "user_id": id})
Python
string sql = "SELECT * FROM Customers WHERE CustomerId =
@CustomerId";
SqlCommand command = new SqlCommand(sql);
command.Parameters.Add(new SqlParameter("@CustomerId",
System.Data.SqlDbType.Int));
command.Parameters["@CustomerId"].Value = 1;
C# .NET
Object-Relational Mapping (ORM)
● Abstract communication with database
● Used in many development framework such as Rails
(Ruby), Django (Python), Node.js, Hibernate (Java),
Entity (ADO.NET) etc.
● Provide automatic query parameterization when
using programmatic methods to retrieve and modify
data
● CAUTION: User input into object queries (OQL/HQL)
or other advanced queries supported by the
framework may cause the injection
Vulnerabilities Prevented
● OWASP Top 10 2013
– A1: Injection
● OWASP Mobile Top 10 2014
– M1: Weak Server Side Controls
Coding Security Practices #4
Identity and Authentication Controls
Goal of Identity and Authentication
Controls
● Tying an system identity to an individual user by the
use of a credential
● Providing reasonable authentication controls as per
the application’s risk
● Denying access to attackers who use various
methods to attack the authentication system
Three Different Terms
● Authentication
● Session Management
● Identity Management
Authentication
● The process of verifying that an individual or an
entity is who it claims to be
● Commonly performed by submitting a user name or
ID and one or more items of private information
that only a given user should know, should have or
should be
Session Management
● A process by which a server maintains the state of
an entity interacting with it
● This is required for a server to remember how to
react to subsequent requests throughout a
transaction.
● Sessions are maintained on the server by a session
identifier which can be passed back and forth
between the client and server when transmitting
and receiving requests.
● Sessions should be unique per user and
computationally impossible to predict
Identity Management
● A broader topic
● Not only includes
authentication and
session management
● But also covers
advanced topics like
identity federation,
single sign on,
password management
tools, delegation,
identity repositories
and more
Recommendation for Secure Implementation
● Use Multi-Factor Authentication
● Mobile Application: Token-Based Authentication
● Implement Secure Password Storage
● Implement Secure Password Recovery Mechanism
● Session Generation and Expiration
● Require Reauthentication for Sensitive Features
Using Multi-Factor Authentication
● Multi-factor authentication (MFA) ensures that
users are who they claim to be by requiring them to
identify themselves with a combination of:
– Something they know – password or PIN
– Something they have – token or phone
– Something they are – biometrics, such as a fingerprint
Mobile Application: Token-Based Authentication
● Avoid storing/persisting authentication credentials locally
on the device
● Perform initial authentication and then generate a short-
lived access token which can be used to authenticate a
client request without sending the user's credentials
Implement Secure Password Storage
● An application must securely store user credentials
● Cryptographic controls should be in place such that if
a credential (e.g. a password) is compromised
● The best secure password storage is “Salted Password
Hashing”
– DO NOT WRITE YOUR OWN CRYPTO! The problem of
storing passwords has already been solved. Use either use
either phpass, the PHP, C#, Java, and Ruby implementations
in defuse/password-hashing, or libsodium.
https://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
Implement Secure Password Recovery
Mechanism
● Step 1) Gather Identity Data or Security Questions
● Step 2) Verify Security Questions
● Step 3) Send a Token Over a Side-Channel (Out of
Band)
● Step 4) Allow user to change password in the
existing session
● Step 5) Logging
https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet
Session: Generation and Expiration
● On any successful authentication and
reauthentication the software should generate a
new session and session ID
● Set expiration timeouts for every session, after a
specified period of inactivity
● The length of timeout should be inversely
proportional with the value of the data protected
Require Reauthentication for Sensitive Features
● For sensitive transactions, it is important to require
the user to reauthenticate and if feasible, to
generate a new session ID upon successful
authentication.
● When to do
– Changing password
– Changing the shipping address for a purchase
– Changing email address for notification
Vulnerabilities Prevented
● OWASP Top 10 2013
– A2: Broken Authentication and Session Management
● OWASP Mobile Top 10 2016
– M4: Insecure Authentication
Coding Security Practices #5
Access Controls
Goal of Authorization (Access Control)
● The process where requests to access a particular
feature or resource should be granted or denied
● Not equivalent to authentication (verifying identity)
● Access control design requirements should be
considered at the initial stages of application
development
Recommendation for Secure Implementation
● Force All Requests to go Through Access Control
Checks
● Deny by Default
● Principle of Least Privilege
● Avoid Hard-Coded Access Control Checks
● Code to the Activity
● Server-Side Trusted Data Should Drive Access
Control
Force All Requests to Go Through Access
Control Checks
https://projects.spring.io/spring-security/
Deny by Default
● Consider denying all access control checks for
features that have not been configured for access
control
Principle of Least Privilege
● When designing access controls, each user or
system component should be allocated the
minimum privilege required to perform an action
for the minimum amount of time
● Benefits of the principle include:
– Better system stability
– Better system security
– Ease of deployment
Avoid Hard-Coded Access Control Checks
● Hard-coded access control makes auditing or
proving the security of that software very difficult
and time consuming
● Access control policy and application code, when
possible, should be separated
● On the other hand, enforcement layer (checks in
code) and access control decision making process
(the access control "engine") should be separated
when possible
Hard-coded role checks
RBAC
if (user.hasRole("ADMIN")) || (user.hasRole("MANAGER")) {
deleteAccount();
}
if (user.hasAccess("DELETE_ACCOUNT")) {
deleteAccount();
}
Code to the Activity
RBAC (Role Based Access Control)
[Authorize(Roles = "Jedi", "Sith")]
public ActionResult WieldLightsaber() {
return View();
}
Role Based Authorization
[ClaimAuthorize(Permission="CanWieldLightsaber")]
public ActionResult WieldLightsaber()
{
return View();
}
Claim Based Authorization
ASP.NET Roles vs Claims Authorization
Apache Shiro Role Based Access Control
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
Checks heck if the current use have specific role or not:
http://shiro.apache.org/
Apache Shiro Permission Based Access Control
Check if the current user have a permission to act on a certain type of entity
if ( currentUser.isPermitted( "lightsaber:wield" ) ) {
log.info("You may use a lightsaber ring. Use it
wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz
masters only.");
}
http://shiro.apache.org/
Check if the current user have access to a specific instance of a type : instance-level permission check
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the " +
'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys: have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the " +
'eagle5' winnebago!");
}
Apache Shiro Permission Based Access Control
http://shiro.apache.org/
Server-Side Trusted Data Should Drive Access
Control
● The only client-side data that is needed for access
control is the ID or IDs of the data being accessed
● Most all other data needed to make an access
control decision should be retrieved server-side
Vulnerabilities Prevented
● OWASP Top 10 2013
– A4: Insecure Direct Object References
– A7: Missing Function Level Access Control
● OWASP Mobile Top 10 2016
– M6: Insecure Authorization
Other Coding Security Practices
More Coding Security Practices
● Cryptography
● Logging and Intrusion Detection
● Leverage Security Frameworks and Libraries
● Error and Exception Handling
● Data Validation
● Tokenization
Facebook: OWASP Thailand Chapter
https://www.facebook.com/groups/owaspthailand/
Coding Security Fundamentals

Contenu connexe

Tendances

XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricksGarethHeyes
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5Shreeraj Shah
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?Yurii Bilyk
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101Paul Ionescu
 
Introduction to DevSecOps on AWS
Introduction to DevSecOps on AWSIntroduction to DevSecOps on AWS
Introduction to DevSecOps on AWSAmazon Web Services
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Codingbilcorry
 
OWASP API Security Top 10 - API World
OWASP API Security Top 10 - API WorldOWASP API Security Top 10 - API World
OWASP API Security Top 10 - API World42Crunch
 
OWASP based Threat Modeling Framework
OWASP based Threat Modeling FrameworkOWASP based Threat Modeling Framework
OWASP based Threat Modeling FrameworkChaitanya Bhatt
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewMichael Furman
 
Learn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPLearn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPPaul Ionescu
 
DevSecOps: Minimizing Risk, Improving Security
DevSecOps: Minimizing Risk, Improving SecurityDevSecOps: Minimizing Risk, Improving Security
DevSecOps: Minimizing Risk, Improving SecurityFranklin Mosley
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0Mika Koivisto
 
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021Amazon Web Services Korea
 
Simplified Security Code Review Process
Simplified Security Code Review ProcessSimplified Security Code Review Process
Simplified Security Code Review ProcessSherif Koussa
 

Tendances (20)

XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 
Secure coding-guidelines
Secure coding-guidelinesSecure coding-guidelines
Secure coding-guidelines
 
Api security-testing
Api security-testingApi security-testing
Api security-testing
 
Cloud Security (AWS)
Cloud Security (AWS)Cloud Security (AWS)
Cloud Security (AWS)
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?XSS - Do you know EVERYTHING?
XSS - Do you know EVERYTHING?
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101
 
Introduction to DevSecOps on AWS
Introduction to DevSecOps on AWSIntroduction to DevSecOps on AWS
Introduction to DevSecOps on AWS
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
HTTP Security Headers
HTTP Security HeadersHTTP Security Headers
HTTP Security Headers
 
OWASP API Security Top 10 - API World
OWASP API Security Top 10 - API WorldOWASP API Security Top 10 - API World
OWASP API Security Top 10 - API World
 
OWASP based Threat Modeling Framework
OWASP based Threat Modeling FrameworkOWASP based Threat Modeling Framework
OWASP based Threat Modeling Framework
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
Learn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPLearn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAP
 
DevSecOps: Minimizing Risk, Improving Security
DevSecOps: Minimizing Risk, Improving SecurityDevSecOps: Minimizing Risk, Improving Security
DevSecOps: Minimizing Risk, Improving Security
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Introduction to SAML 2.0
Introduction to SAML 2.0Introduction to SAML 2.0
Introduction to SAML 2.0
 
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
AWS를 활용해서 글로벌 게임 런칭하기 - 박진성 AWS 솔루션즈 아키텍트 :: AWS Summit Seoul 2021
 
Simplified Security Code Review Process
Simplified Security Code Review ProcessSimplified Security Code Review Process
Simplified Security Code Review Process
 

Similaire à Coding Security Fundamentals

Application Security
Application SecurityApplication Security
Application Securityflorinc
 
Neoito — Secure coding practices
Neoito — Secure coding practicesNeoito — Secure coding practices
Neoito — Secure coding practicesNeoito
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on itWSO2
 
Solvay secure application layer v2015 seba
Solvay secure application layer v2015   sebaSolvay secure application layer v2015   seba
Solvay secure application layer v2015 sebaSebastien Deleersnyder
 
OWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risksOWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risksKun-Da Wu
 
Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)mikemcbryde
 
Security Incident machnism Security Incident machnismSecurity Incident machni...
Security Incident machnism Security Incident machnismSecurity Incident machni...Security Incident machnism Security Incident machnismSecurity Incident machni...
Security Incident machnism Security Incident machnismSecurity Incident machni...karthikvcyber
 
Top web apps security vulnerabilities
Top web apps security vulnerabilitiesTop web apps security vulnerabilities
Top web apps security vulnerabilitiesAleksandar Bozinovski
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Moataz Kamel
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net ProgrammingAdam Getchell
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017Eoin Keary
 
Applying Auto-Data Classification Techniques for Large Data Sets
Applying Auto-Data Classification Techniques for Large Data SetsApplying Auto-Data Classification Techniques for Large Data Sets
Applying Auto-Data Classification Techniques for Large Data SetsPriyanka Aash
 
20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASPchadtindel
 
Software Security Engineering
Software Security EngineeringSoftware Security Engineering
Software Security EngineeringMarco Morana
 
A Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web ServicesA Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web ServicesRafael Brinhosa
 
The Golden Rules - Detecting more with RSA Security Analytics
The Golden Rules  - Detecting more with RSA Security AnalyticsThe Golden Rules  - Detecting more with RSA Security Analytics
The Golden Rules - Detecting more with RSA Security AnalyticsDemetrio Milea
 

Similaire à Coding Security Fundamentals (20)

Application Security
Application SecurityApplication Security
Application Security
 
Neoito — Secure coding practices
Neoito — Secure coding practicesNeoito — Secure coding practices
Neoito — Secure coding practices
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on it
 
Solvay secure application layer v2015 seba
Solvay secure application layer v2015   sebaSolvay secure application layer v2015   seba
Solvay secure application layer v2015 seba
 
OWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risksOWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risks
 
Security testing
Security testingSecurity testing
Security testing
 
Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)Application Security 101 (OWASP DC)
Application Security 101 (OWASP DC)
 
Security Incident machnism Security Incident machnismSecurity Incident machni...
Security Incident machnism Security Incident machnismSecurity Incident machni...Security Incident machnism Security Incident machnismSecurity Incident machni...
Security Incident machnism Security Incident machnismSecurity Incident machni...
 
Top web apps security vulnerabilities
Top web apps security vulnerabilitiesTop web apps security vulnerabilities
Top web apps security vulnerabilities
 
ASP.NET security vulnerabilities
ASP.NET security vulnerabilitiesASP.NET security vulnerabilities
ASP.NET security vulnerabilities
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
 
Secure Design: Threat Modeling
Secure Design: Threat ModelingSecure Design: Threat Modeling
Secure Design: Threat Modeling
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net Programming
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017
 
Applying Auto-Data Classification Techniques for Large Data Sets
Applying Auto-Data Classification Techniques for Large Data SetsApplying Auto-Data Classification Techniques for Large Data Sets
Applying Auto-Data Classification Techniques for Large Data Sets
 
20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP20160211 OWASP Charlotte RASP
20160211 OWASP Charlotte RASP
 
Secure Software Engineering
Secure Software EngineeringSecure Software Engineering
Secure Software Engineering
 
Software Security Engineering
Software Security EngineeringSoftware Security Engineering
Software Security Engineering
 
A Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web ServicesA Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web Services
 
The Golden Rules - Detecting more with RSA Security Analytics
The Golden Rules  - Detecting more with RSA Security AnalyticsThe Golden Rules  - Detecting more with RSA Security Analytics
The Golden Rules - Detecting more with RSA Security Analytics
 

Plus de Narudom Roongsiriwong, CISSP

How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19Narudom Roongsiriwong, CISSP
 
Embedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryEmbedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryNarudom Roongsiriwong, CISSP
 
Application Security Verification Standard Project
Application Security Verification Standard ProjectApplication Security Verification Standard Project
Application Security Verification Standard ProjectNarudom Roongsiriwong, CISSP
 
Top 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsTop 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsNarudom Roongsiriwong, CISSP
 
OWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceOWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceNarudom Roongsiriwong, CISSP
 

Plus de Narudom Roongsiriwong, CISSP (20)

Biometric Authentication.pdf
Biometric Authentication.pdfBiometric Authentication.pdf
Biometric Authentication.pdf
 
Security Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdfSecurity Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdf
 
Security Patterns for Software Development
Security Patterns for Software DevelopmentSecurity Patterns for Software Development
Security Patterns for Software Development
 
How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19
 
Secure Software Design for Data Privacy
Secure Software Design for Data PrivacySecure Software Design for Data Privacy
Secure Software Design for Data Privacy
 
Blockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for DummiesBlockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for Dummies
 
DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
National Digital ID Platform Technical Forum
National Digital ID Platform Technical ForumNational Digital ID Platform Technical Forum
National Digital ID Platform Technical Forum
 
IoT Security
IoT SecurityIoT Security
IoT Security
 
Embedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryEmbedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment Industry
 
Secure Your Encryption with HSM
Secure Your Encryption with HSMSecure Your Encryption with HSM
Secure Your Encryption with HSM
 
Application Security Verification Standard Project
Application Security Verification Standard ProjectApplication Security Verification Standard Project
Application Security Verification Standard Project
 
Top 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsTop 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security Problems
 
OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)
 
Securing the Internet from Cyber Criminals
Securing the Internet from Cyber CriminalsSecuring the Internet from Cyber Criminals
Securing the Internet from Cyber Criminals
 
Secure Software Development Adoption Strategy
Secure Software Development Adoption StrategySecure Software Development Adoption Strategy
Secure Software Development Adoption Strategy
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Application Security: Last Line of Defense
Application Security: Last Line of DefenseApplication Security: Last Line of Defense
Application Security: Last Line of Defense
 
AnyID and Privacy
AnyID and PrivacyAnyID and Privacy
AnyID and Privacy
 
OWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceOWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object Reference
 

Dernier

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Dernier (20)

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Coding Security Fundamentals

  • 1. Coding SecurityCoding Security Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017 Coding SecurityCoding Security Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017
  • 2. WhoAmI ● Lazy Blogger – Japan, Security, FOSS, Politics, Christian – http://narudomr.blogspot.com ● Information Security since 1995 ● Web Application Development since 1998 ● Head of IT Security and Solution Architecture, Kiatnakin Bank PLC (KKP) ● Consultant for OWASP Thailand Chapter ● Committee Member of Cloud Security Alliance (CSA), Thailand Chapter ● Consulting Team Member for National e-Payment project ● Committee Member of Thailand Banking Sector CERT (TB-CERT) ● Contact: narudom@owasp.org
  • 3.
  • 5. What is Security?  “The quality or state of being secure—to be free from danger”  A successful organization should have multiple layers of security in place:  Physical security  Personal security  Operations security  Communications security  Network security  Information security
  • 6. What is Information Security?  The protection of information and its critical elements, including systems and hardware that use, store, and transmit that information  Necessary tools: policy, awareness, training, education, technology
  • 7. What Is Software Security? ● Reliability: Functions as it is expected to. ● Resiliency: Does not violate any security policy and is able to withstand the actions of threat agents that are posed intentionally (attacks and exploits) or accidentally (user errors). ● Recoverability: The software is able to restore operations to what the business expects by containing and limiting the damage caused by threats that materialize.
  • 8. Security Concepts Security Concepts Core Design Confidentiality Integrity Availibility Authentication Authorization Accountability Need to Know Least Privilege Separation of Duties Defense in Depth Fail Safe / Fail Secure Economy of Mechanisms Complete Mediation Open Design Least Common Mechanisms Psychological Acceptability Weakest Link Leveraging Existing Components
  • 9. Confidentiality-Integrity-Availability (CIA) To ensure that information and vital services are accessible for use when required To ensure the accuracy and completeness of information to protect business processes To ensure protection against unauthorized access to or use of confidential information
  • 10. Do Network Security Devices Protect All Attacks? Source: IBM Software Group, Rational Software
  • 11. OWASP Top 10 2013 Risk Source: OWASP: Open Web Application Security Project
  • 12. Security controls cannot deal with broken business logic such as A2, A4 and A7 Security controls cannot deal with broken business logic such as A2, A4 and A7 Software weaknesses reduction down to zero is possible Software weaknesses reduction down to zero is possible Reduce Security Weaknesses vs Increase Security Controls Source: OWASP: Open Web Application Security Project
  • 13. Security as an Afterthought Relative cost of security fixes, based on time of detection Implementation Challenges Source: The National Institute of Standards and Technology (NIST)
  • 14. Coding Security Practices #1 Input Validation
  • 15. Goal of Input Validation ● Ensure only properly formed data is entering the workflow in an information system ● Prevent malformed data from persisting in the system or triggering malfunction of various downstream components (injection) ● Validate all data from untrusted source
  • 16. Input Validation Strategies ● Syntactic – Enforce correct syntax of structured fields (e.g. Citizen ID, date, currency symbol) ● Semantic – Enforce correctness of their values in the specific business context (e.g. start date is before end date, price is within expected range) ● Prevent attacks as early as possible in the processing of the user’s (attacker's) request ● Detect unauthorized input before it is processed by the application
  • 17. Implementing Input Validation Examples ● Data type validators available natively in web application frameworks (such as Django Validators, Apache Commons Validators etc) ● Validation against JSON Schema and XML Schema (XSD) for input in these formats ● Type conversion (e.g. Integer.parseInt() in Java, int() in Python) with strict exception handling ● Minimum and maximum value range check for numerical parameters and dates, minimum and maximum length check for strings ● Array of allowed values for small sets of string parameters (e.g. days of week) ● Regular expressions for any other structured data covering the whole input string (^...$) and not using "any character" wildcard (such as "." or "S")
  • 18. Client Side vs Server Side Validation ● Client-side validation is to provide a better user experience by responding quickly at the browser level but not actually mandatory ● Server-side validation is mandatory due to the fact that client-side validation can be completely bypassed (by turning off JavaScript, manipulating HTTP request via web proxy)
  • 19. How to Manipulate HTTP Request ● Using Web Proxy (Burp Suite, Paros, WebScarab,OWASP: Zed Attack Proxy (ZAP))
  • 20. Whitelist vs Blacklist ● It is a common mistake black list validation in order to try to detect possibly dangerous characters (e.g. the apostrophe ' character, the string 1=1, or the <script> tag) ● White list validation is appropriate for all input fields provided by the user – Defining exactly what is authorized, and by definition, everything else is not authorized – If it's well structured data, like dates, social security numbers, zip codes, e-mail addresses, etc. pattern matching validation is perfect. – If the input field comes from a fixed set of options, like a drop down list or radio buttons, then the exact match is perfect.
  • 21. Vulnerabilities Prevented ● OWASP Top 10 2013 – A1: Injection – A3: Cross-Site Scripting (XSS) ● OWASP Mobile Top 10 2016 – M7: Client Side Injection
  • 22. Coding Security Practices #2 Output Handling
  • 23. Goal of Output Handling ● Prevent the output data from our application being unintended interpretation at the destination systems (web browser, database, LDAP, web service)
  • 24. Output Handling Strategies ● Sanitization: Transforming data from its original form to an acceptable form either by removal of that data, or by encoding or decoding it. – Common encoding methods used in web applications include the HTML entity encoding and URL Encoding schemes ● Filtering: Acceptance or the rejection of output based on predefined criteria.
  • 25. Output Handling Examples ● Conduct all encoding on a trusted system (e.g., the server) ● Utilize a standard, tested routine for each type of outbound encoding ● Contextually output encode all data returned to the client that originated outside the application's trust boundary. – HTML entity encoding is one example, but does not work in all cases ● Encode all characters unless they are known to be safe for the intended interpreter ● Contextually sanitize all output of untrusted data to queries for SQL, XML, and LDAP ● Sanitize all output of untrusted data to operating system commands
  • 26. Vulnerabilities Prevented ● OWASP Top 10 2013 – A1: Injection – A3: Cross-Site Scripting (XSS) ● OWASP Mobile Top 10 2016 – M7: Client Side Injection
  • 27. Coding Security Practices #3 Parameterize Queries
  • 28. Goal of Parameterize Queries ● Prevent user or untrusted input from being interpreted as part of a SQL command SQL Injection is one of the most dangerous web application risks. SQL Injection is easy to exploit with many open source automated attack tools available. SQL injection can also deliver an impact to your application that is devastating.
  • 29. Why String Concatenation to Construct SQL Statement is Evil? The following C# code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user. ... string userName = ctx.getAuthenticatedUserName(); string query = "SELECT * FROM items WHERE owner = "'" + userName + "' AND itemname = '" + ItemName.Text + "'"; sda = new SqlDataAdapter(query, conn); DataTable dt = new DataTable(); sda.Fill(dt); ... The query that this code intends to execute follows: SELECT * FROM items WHERE owner = 'someone' AND itemname = 'something';
  • 30. Why String Concatenation to Construct SQL Statement is Evil? (cont’d) If an attacker with the user name hacker enters the string "name'); DELETE FROM items; --" for itemName, then the query becomes the following two queries: SELECT * FROM items WHERE owner = 'hacker' AND itemname = 'name'; DELETE FROM items; --'
  • 31. Parameterize Query Example String newName = request.getParameter("newName"); int id = Integer.parseInt(request.getParameter("id")); PreparedStatement pstmt = con.prepareStatement( "UPDATE EMPLOYEES SET NAME = ? WHERE ID = ?"); pstmt.setString(1, newName); pstmt.setInt(2, id); Java PHP using PDO $stmt = $dbh>prepare(”update users set email=:new_email where id=:user_id”); $stmt>bindParam(':new_email', $email); $stmt>bindParam(':user_id', $id);
  • 32. Parameterize Query Example (cont’d) email = REQUEST[‘email’] id = REQUEST[‘id’] cur.execute(update users set email=:new_email where id=:user_id”, {"new_email": email, "user_id": id}) Python string sql = "SELECT * FROM Customers WHERE CustomerId = @CustomerId"; SqlCommand command = new SqlCommand(sql); command.Parameters.Add(new SqlParameter("@CustomerId", System.Data.SqlDbType.Int)); command.Parameters["@CustomerId"].Value = 1; C# .NET
  • 33. Object-Relational Mapping (ORM) ● Abstract communication with database ● Used in many development framework such as Rails (Ruby), Django (Python), Node.js, Hibernate (Java), Entity (ADO.NET) etc. ● Provide automatic query parameterization when using programmatic methods to retrieve and modify data ● CAUTION: User input into object queries (OQL/HQL) or other advanced queries supported by the framework may cause the injection
  • 34. Vulnerabilities Prevented ● OWASP Top 10 2013 – A1: Injection ● OWASP Mobile Top 10 2014 – M1: Weak Server Side Controls
  • 35. Coding Security Practices #4 Identity and Authentication Controls
  • 36. Goal of Identity and Authentication Controls ● Tying an system identity to an individual user by the use of a credential ● Providing reasonable authentication controls as per the application’s risk ● Denying access to attackers who use various methods to attack the authentication system
  • 37. Three Different Terms ● Authentication ● Session Management ● Identity Management
  • 38. Authentication ● The process of verifying that an individual or an entity is who it claims to be ● Commonly performed by submitting a user name or ID and one or more items of private information that only a given user should know, should have or should be
  • 39. Session Management ● A process by which a server maintains the state of an entity interacting with it ● This is required for a server to remember how to react to subsequent requests throughout a transaction. ● Sessions are maintained on the server by a session identifier which can be passed back and forth between the client and server when transmitting and receiving requests. ● Sessions should be unique per user and computationally impossible to predict
  • 40. Identity Management ● A broader topic ● Not only includes authentication and session management ● But also covers advanced topics like identity federation, single sign on, password management tools, delegation, identity repositories and more
  • 41. Recommendation for Secure Implementation ● Use Multi-Factor Authentication ● Mobile Application: Token-Based Authentication ● Implement Secure Password Storage ● Implement Secure Password Recovery Mechanism ● Session Generation and Expiration ● Require Reauthentication for Sensitive Features
  • 42. Using Multi-Factor Authentication ● Multi-factor authentication (MFA) ensures that users are who they claim to be by requiring them to identify themselves with a combination of: – Something they know – password or PIN – Something they have – token or phone – Something they are – biometrics, such as a fingerprint
  • 43. Mobile Application: Token-Based Authentication ● Avoid storing/persisting authentication credentials locally on the device ● Perform initial authentication and then generate a short- lived access token which can be used to authenticate a client request without sending the user's credentials
  • 44. Implement Secure Password Storage ● An application must securely store user credentials ● Cryptographic controls should be in place such that if a credential (e.g. a password) is compromised ● The best secure password storage is “Salted Password Hashing” – DO NOT WRITE YOUR OWN CRYPTO! The problem of storing passwords has already been solved. Use either use either phpass, the PHP, C#, Java, and Ruby implementations in defuse/password-hashing, or libsodium. https://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
  • 45. Implement Secure Password Recovery Mechanism ● Step 1) Gather Identity Data or Security Questions ● Step 2) Verify Security Questions ● Step 3) Send a Token Over a Side-Channel (Out of Band) ● Step 4) Allow user to change password in the existing session ● Step 5) Logging https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet
  • 46. Session: Generation and Expiration ● On any successful authentication and reauthentication the software should generate a new session and session ID ● Set expiration timeouts for every session, after a specified period of inactivity ● The length of timeout should be inversely proportional with the value of the data protected
  • 47. Require Reauthentication for Sensitive Features ● For sensitive transactions, it is important to require the user to reauthenticate and if feasible, to generate a new session ID upon successful authentication. ● When to do – Changing password – Changing the shipping address for a purchase – Changing email address for notification
  • 48. Vulnerabilities Prevented ● OWASP Top 10 2013 – A2: Broken Authentication and Session Management ● OWASP Mobile Top 10 2016 – M4: Insecure Authentication
  • 49. Coding Security Practices #5 Access Controls
  • 50. Goal of Authorization (Access Control) ● The process where requests to access a particular feature or resource should be granted or denied ● Not equivalent to authentication (verifying identity) ● Access control design requirements should be considered at the initial stages of application development
  • 51. Recommendation for Secure Implementation ● Force All Requests to go Through Access Control Checks ● Deny by Default ● Principle of Least Privilege ● Avoid Hard-Coded Access Control Checks ● Code to the Activity ● Server-Side Trusted Data Should Drive Access Control
  • 52. Force All Requests to Go Through Access Control Checks https://projects.spring.io/spring-security/
  • 53. Deny by Default ● Consider denying all access control checks for features that have not been configured for access control
  • 54. Principle of Least Privilege ● When designing access controls, each user or system component should be allocated the minimum privilege required to perform an action for the minimum amount of time ● Benefits of the principle include: – Better system stability – Better system security – Ease of deployment
  • 55. Avoid Hard-Coded Access Control Checks ● Hard-coded access control makes auditing or proving the security of that software very difficult and time consuming ● Access control policy and application code, when possible, should be separated ● On the other hand, enforcement layer (checks in code) and access control decision making process (the access control "engine") should be separated when possible
  • 56. Hard-coded role checks RBAC if (user.hasRole("ADMIN")) || (user.hasRole("MANAGER")) { deleteAccount(); } if (user.hasAccess("DELETE_ACCOUNT")) { deleteAccount(); } Code to the Activity RBAC (Role Based Access Control)
  • 57. [Authorize(Roles = "Jedi", "Sith")] public ActionResult WieldLightsaber() { return View(); } Role Based Authorization [ClaimAuthorize(Permission="CanWieldLightsaber")] public ActionResult WieldLightsaber() { return View(); } Claim Based Authorization ASP.NET Roles vs Claims Authorization
  • 58. Apache Shiro Role Based Access Control if ( currentUser.hasRole( "schwartz" ) ) { log.info("May the Schwartz be with you!" ); } else { log.info( "Hello, mere mortal." ); } Checks heck if the current use have specific role or not: http://shiro.apache.org/
  • 59. Apache Shiro Permission Based Access Control Check if the current user have a permission to act on a certain type of entity if ( currentUser.isPermitted( "lightsaber:wield" ) ) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } http://shiro.apache.org/
  • 60. Check if the current user have access to a specific instance of a type : instance-level permission check if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the " + 'winnebago' with license plate (id) 'eagle5'. " + "Here are the keys: have fun!"); } else { log.info("Sorry, you aren't allowed to drive the " + 'eagle5' winnebago!"); } Apache Shiro Permission Based Access Control http://shiro.apache.org/
  • 61. Server-Side Trusted Data Should Drive Access Control ● The only client-side data that is needed for access control is the ID or IDs of the data being accessed ● Most all other data needed to make an access control decision should be retrieved server-side
  • 62. Vulnerabilities Prevented ● OWASP Top 10 2013 – A4: Insecure Direct Object References – A7: Missing Function Level Access Control ● OWASP Mobile Top 10 2016 – M6: Insecure Authorization
  • 64. More Coding Security Practices ● Cryptography ● Logging and Intrusion Detection ● Leverage Security Frameworks and Libraries ● Error and Exception Handling ● Data Validation ● Tokenization
  • 65. Facebook: OWASP Thailand Chapter https://www.facebook.com/groups/owaspthailand/