SlideShare a Scribd company logo
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
Coding Security: Code Mania 101
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

More Related Content

What's hot (20)

PPTX
Incident response process
Bhupeshkumar Nanhe
 
PPT
Intro to Web Application Security
Rob Ragan
 
PDF
Simplified Security Code Review Process
Sherif Koussa
 
ODP
OWASP Secure Coding
bilcorry
 
PPTX
Introduction To Vulnerability Assessment & Penetration Testing
Raghav Bisht
 
PPT
Cross Site Request Forgery Vulnerabilities
Marco Morana
 
PPTX
cyber security
NiharikaVoleti
 
PDF
Application Attacks & Application Layer Attacks
LearningwithRayYT
 
PPTX
What is Cryptography and Types of attacks in it
lavakumar Thatisetti
 
PDF
How MITRE ATT&CK helps security operations
Sergey Soldatov
 
PPTX
System hardening - OS and Application
edavid2685
 
PPTX
malware
Deepak Chawla
 
PPTX
OpenVAS
svm
 
PPT
IT Security Awareness-v1.7.ppt
OoXair
 
PPT
Introduction To OWASP
Marco Morana
 
PDF
OWASP Top 10 Web Application Vulnerabilities
Software Guru
 
PDF
Governance Risk Management and Compliance (GRC)
Seta Wicaksana
 
PPTX
Cybersecurity Attack Vectors: How to Protect Your Organization
TriCorps Technologies
 
PDF
Web application security & Testing
Deepu S Nath
 
PDF
Secure software development presentation
Mahdi Dolati
 
Incident response process
Bhupeshkumar Nanhe
 
Intro to Web Application Security
Rob Ragan
 
Simplified Security Code Review Process
Sherif Koussa
 
OWASP Secure Coding
bilcorry
 
Introduction To Vulnerability Assessment & Penetration Testing
Raghav Bisht
 
Cross Site Request Forgery Vulnerabilities
Marco Morana
 
cyber security
NiharikaVoleti
 
Application Attacks & Application Layer Attacks
LearningwithRayYT
 
What is Cryptography and Types of attacks in it
lavakumar Thatisetti
 
How MITRE ATT&CK helps security operations
Sergey Soldatov
 
System hardening - OS and Application
edavid2685
 
malware
Deepak Chawla
 
OpenVAS
svm
 
IT Security Awareness-v1.7.ppt
OoXair
 
Introduction To OWASP
Marco Morana
 
OWASP Top 10 Web Application Vulnerabilities
Software Guru
 
Governance Risk Management and Compliance (GRC)
Seta Wicaksana
 
Cybersecurity Attack Vectors: How to Protect Your Organization
TriCorps Technologies
 
Web application security & Testing
Deepu S Nath
 
Secure software development presentation
Mahdi Dolati
 

Similar to Coding Security: Code Mania 101 (20)

PPTX
Secure coding - Balgan - Tiago Henriques
Tiago Henriques
 
PPTX
OWASP top 10-2013
tmd800
 
PDF
Secure coding presentation Oct 3 2020
Moataz Kamel
 
PDF
Security Awareness
Lucas Hendrich
 
PDF
Hijacking a Pizza Delivery Robot (using SQL injection)
Priyanka Aash
 
PDF
How to Destroy a Database
John Ashmead
 
PPTX
How to Hijack a Pizza Delivery Robot with Injection Flaws
Security Innovation
 
PPTX
Secure Dot Net Programming
Adam Getchell
 
PPT
Survey Presentation About Application Security
Nicholas Davis
 
PPTX
The path of secure software by Katy Anton
DevSecCon
 
PPTX
Security Training: #4 Development: Typical Security Issues
Yulian Slobodyan
 
PDF
2013 OWASP Top 10
bilcorry
 
PPTX
Secure Software Engineering
Rohitha Liyanagama
 
PPTX
State of the information security nation
SensePost
 
PPTX
Application Security 101 (OWASP DC)
mikemcbryde
 
PPTX
OWASP_Top_Ten_Proactive_Controls_v2.pptx
FernandoVizer
 
PPT
Secure code practices
Hina Rawal
 
PPTX
OWASP Top 10 Proactive Controls
Katy Anton
 
PPTX
How to Test for The OWASP Top Ten
Security Innovation
 
PPTX
Ebu class edgescan-2017
Eoin Keary
 
Secure coding - Balgan - Tiago Henriques
Tiago Henriques
 
OWASP top 10-2013
tmd800
 
Secure coding presentation Oct 3 2020
Moataz Kamel
 
Security Awareness
Lucas Hendrich
 
Hijacking a Pizza Delivery Robot (using SQL injection)
Priyanka Aash
 
How to Destroy a Database
John Ashmead
 
How to Hijack a Pizza Delivery Robot with Injection Flaws
Security Innovation
 
Secure Dot Net Programming
Adam Getchell
 
Survey Presentation About Application Security
Nicholas Davis
 
The path of secure software by Katy Anton
DevSecCon
 
Security Training: #4 Development: Typical Security Issues
Yulian Slobodyan
 
2013 OWASP Top 10
bilcorry
 
Secure Software Engineering
Rohitha Liyanagama
 
State of the information security nation
SensePost
 
Application Security 101 (OWASP DC)
mikemcbryde
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
FernandoVizer
 
Secure code practices
Hina Rawal
 
OWASP Top 10 Proactive Controls
Katy Anton
 
How to Test for The OWASP Top Ten
Security Innovation
 
Ebu class edgescan-2017
Eoin Keary
 
Ad

More from Narudom Roongsiriwong, CISSP (20)

PDF
Biometric Authentication.pdf
Narudom Roongsiriwong, CISSP
 
PDF
Security Shift Leftmost - Secure Architecture.pdf
Narudom Roongsiriwong, CISSP
 
PDF
Secure Design: Threat Modeling
Narudom Roongsiriwong, CISSP
 
PDF
Security Patterns for Software Development
Narudom Roongsiriwong, CISSP
 
PDF
How Good Security Architecture Saves Corporate Workers from COVID-19
Narudom Roongsiriwong, CISSP
 
PDF
Secure Software Design for Data Privacy
Narudom Roongsiriwong, CISSP
 
PDF
Blockchain and Cryptocurrency for Dummies
Narudom Roongsiriwong, CISSP
 
PPTX
National Digital ID Platform Technical Forum
Narudom Roongsiriwong, CISSP
 
PDF
Embedded System Security: Learning from Banking and Payment Industry
Narudom Roongsiriwong, CISSP
 
PDF
Secure Your Encryption with HSM
Narudom Roongsiriwong, CISSP
 
PDF
Application Security Verification Standard Project
Narudom Roongsiriwong, CISSP
 
PDF
Top 10 Bad Coding Practices Lead to Security Problems
Narudom Roongsiriwong, CISSP
 
PDF
OWASP Top 10 Proactive Control 2016 (C5-C10)
Narudom Roongsiriwong, CISSP
 
PDF
Securing the Internet from Cyber Criminals
Narudom Roongsiriwong, CISSP
 
PDF
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
PDF
Secure Software Development Adoption Strategy
Narudom Roongsiriwong, CISSP
 
PDF
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
PDF
Application Security: Last Line of Defense
Narudom Roongsiriwong, CISSP
 
Biometric Authentication.pdf
Narudom Roongsiriwong, CISSP
 
Security Shift Leftmost - Secure Architecture.pdf
Narudom Roongsiriwong, CISSP
 
Secure Design: Threat Modeling
Narudom Roongsiriwong, CISSP
 
Security Patterns for Software Development
Narudom Roongsiriwong, CISSP
 
How Good Security Architecture Saves Corporate Workers from COVID-19
Narudom Roongsiriwong, CISSP
 
Secure Software Design for Data Privacy
Narudom Roongsiriwong, CISSP
 
Blockchain and Cryptocurrency for Dummies
Narudom Roongsiriwong, CISSP
 
National Digital ID Platform Technical Forum
Narudom Roongsiriwong, CISSP
 
Embedded System Security: Learning from Banking and Payment Industry
Narudom Roongsiriwong, CISSP
 
Secure Your Encryption with HSM
Narudom Roongsiriwong, CISSP
 
Application Security Verification Standard Project
Narudom Roongsiriwong, CISSP
 
Top 10 Bad Coding Practices Lead to Security Problems
Narudom Roongsiriwong, CISSP
 
OWASP Top 10 Proactive Control 2016 (C5-C10)
Narudom Roongsiriwong, CISSP
 
Securing the Internet from Cyber Criminals
Narudom Roongsiriwong, CISSP
 
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
Secure Software Development Adoption Strategy
Narudom Roongsiriwong, CISSP
 
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
Application Security: Last Line of Defense
Narudom Roongsiriwong, CISSP
 
Ad

Recently uploaded (20)

PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 

Coding Security: Code Mania 101

  • 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: [email protected]
  • 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/