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: Code Mania 101

Coding Security: Code Mania 101

  • 1.
    Coding SecurityCoding Security NarudomRoongsiriwong, 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
  • 4.
  • 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 InformationSecurity?  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 SoftwareSecurity? ● 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 ConfidentialityIntegrity 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 ensurethat 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 SecurityDevices Protect All Attacks? Source: IBM Software Group, Rational Software
  • 11.
    OWASP Top 102013 Risk Source: OWASP: Open Web Application Security Project
  • 12.
    Security controls cannot dealwith 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 anAfterthought 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 InputValidation ● 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 ValidationExamples ● 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 vsServer 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 ManipulateHTTP 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 ● OWASPTop 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 OutputHandling ● 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 ● OWASPTop 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 ParameterizeQueries ● 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 Concatenationto 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 Concatenationto 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 StringnewName = 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 ● OWASPTop 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 Identityand 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 processof 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 ● Aprocess 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 ● Abroader 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 SecureImplementation ● 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-BasedAuthentication ● 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 PasswordStorage ● 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 PasswordRecovery 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 andExpiration ● 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 forSensitive 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 ● OWASPTop 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 SecureImplementation ● 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 Requeststo 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 LeastPrivilege ● 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 AccessControl 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 RoleBased 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 PermissionBased 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 thecurrent 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 DataShould 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 ● OWASPTop 10 2013 – A4: Insecure Direct Object References – A7: Missing Function Level Access Control ● OWASP Mobile Top 10 2016 – M6: Insecure Authorization
  • 63.
  • 64.
    More Coding SecurityPractices ● Cryptography ● Logging and Intrusion Detection ● Leverage Security Frameworks and Libraries ● Error and Exception Handling ● Data Validation ● Tokenization
  • 65.
    Facebook: OWASP ThailandChapter https://www.facebook.com/groups/owaspthailand/