Coding Security: Code Mania 101

66
Coding Security Coding Security Narudom Roongsiriwong, CISSP Narudom Roongsiriwong, CISSP Code Mania 101, June 17, 2017 Code Mania 101, June 17, 2017 Coding Security Coding Security Narudom Roongsiriwong, CISSP Narudom Roongsiriwong, CISSP Code Mania 101, June 17, 2017 Code Mania 101, June 17, 2017

Transcript of Coding Security: Code Mania 101

Page 1: Coding Security: Code Mania 101

Coding SecurityCoding SecurityNarudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP

Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017

Coding SecurityCoding SecurityNarudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP

Code Mania 101, June 17, 2017Code Mania 101, June 17, 2017

Page 2: Coding Security: Code Mania 101

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]

Page 3: Coding Security: Code Mania 101
Page 4: Coding Security: Code Mania 101

Software Security Fundamental

Page 5: Coding Security: Code Mania 101

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

Page 6: Coding Security: Code Mania 101

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

Page 7: Coding Security: Code Mania 101

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.

Page 8: Coding Security: Code Mania 101

Security Concepts

Security Concepts

Core

Design

Confidentiality Integrity Availibility

Authentication Authorization Accountability

Need to Know Least PrivilegeSeparation of

Duties

Defense in DepthFail Safe / Fail Secure

Economy of Mechanisms

Complete Mediation

Open Design Least Common Mechanisms

Psychological Acceptability

Weakest LinkLeveraging Existing

Components

Page 9: Coding Security: Code Mania 101

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

Page 10: Coding Security: Code Mania 101

Do Network Security Devices Protect All Attacks?

Source: IBM Software Group, Rational Software

Page 11: Coding Security: Code Mania 101

OWASP Top 10 2013 Risk

Source: OWASP: Open Web Application Security Project

Page 12: Coding Security: Code Mania 101

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 vsIncrease Security Controls

Source: OWASP: Open Web Application Security Project

Page 13: Coding Security: Code Mania 101

Security as an Afterthought

Relative cost of security fixes, based on time of detectionImplementation Challenges

Source: The National Institute of Standards and Technology (NIST)

Page 14: Coding Security: Code Mania 101

Coding Security Practices #1Input Validation

Page 15: Coding Security: Code Mania 101

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

Page 16: Coding Security: Code Mania 101

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

Page 17: Coding Security: Code Mania 101

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")

Page 18: Coding Security: Code Mania 101

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)

Page 19: Coding Security: Code Mania 101

How to Manipulate HTTP Request

● Using Web Proxy (Burp Suite, Paros, WebScarab,OWASP: Zed Attack Proxy (ZAP))

Page 20: Coding Security: Code Mania 101

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.

Page 21: Coding Security: Code Mania 101

Vulnerabilities Prevented

● OWASP Top 10 2013 – A1: Injection– A3: Cross-Site Scripting (XSS)

● OWASP Mobile Top 10 2016– M7: Client Side Injection

Page 22: Coding Security: Code Mania 101

Coding Security Practices #2Output Handling

Page 23: Coding Security: Code Mania 101

Goal of Output Handling

● Prevent the output data from our application being unintended interpretation at the destination systems (web browser, database, LDAP, web service)

Page 24: Coding Security: Code Mania 101

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.

Page 25: Coding Security: Code Mania 101

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

Page 26: Coding Security: Code Mania 101

Vulnerabilities Prevented

● OWASP Top 10 2013 – A1: Injection– A3: Cross-Site Scripting (XSS)

● OWASP Mobile Top 10 2016– M7: Client Side Injection

Page 27: Coding Security: Code Mania 101

Coding Security Practices #3Parameterize Queries

Page 28: Coding Security: Code Mania 101

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.

Page 29: Coding Security: Code Mania 101

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';

Page 30: Coding Security: Code Mania 101

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;--'

Page 31: Coding Security: Code Mania 101

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);

Page 32: Coding Security: Code Mania 101

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

Page 33: Coding Security: Code Mania 101

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

Page 34: Coding Security: Code Mania 101

Vulnerabilities Prevented

● OWASP Top 10 2013– A1: Injection

● OWASP Mobile Top 10 2014– M1: Weak Server Side Controls

Page 35: Coding Security: Code Mania 101

Coding Security Practices #4Identity and Authentication Controls

Page 36: Coding Security: Code Mania 101

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

Page 37: Coding Security: Code Mania 101

Three Different Terms

● Authentication● Session Management● Identity Management

Page 38: Coding Security: Code Mania 101

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

Page 39: Coding Security: Code Mania 101

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

Page 40: Coding Security: Code Mania 101

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

Page 41: Coding Security: Code Mania 101

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

Page 42: Coding Security: Code Mania 101

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

Page 43: Coding Security: Code Mania 101

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

Page 44: Coding Security: Code Mania 101

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

Page 45: Coding Security: Code Mania 101

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

Page 46: Coding Security: Code Mania 101

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

Page 47: Coding Security: Code Mania 101

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

Page 48: Coding Security: Code Mania 101

Vulnerabilities Prevented

● OWASP Top 10 2013 – A2: Broken Authentication and Session Management

● OWASP Mobile Top 10 2016– M4: Insecure Authentication

Page 49: Coding Security: Code Mania 101

Coding Security Practices #5Access Controls

Page 50: Coding Security: Code Mania 101

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

Page 51: Coding Security: Code Mania 101

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

Page 52: Coding Security: Code Mania 101

Force All Requests to Go Through Access Control Checks

https://projects.spring.io/spring-security/

Page 53: Coding Security: Code Mania 101

Deny by Default

● Consider denying all access control checks for features that have not been configured for access control

Page 54: Coding Security: Code Mania 101

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

Page 55: Coding Security: Code Mania 101

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

Page 56: Coding Security: Code Mania 101

Hard-coded role checks

RBAC

if (user.hasRole("ADMIN")) || (user.hasRole("MANAGER")) {deleteAccount();

}

if (user.hasAccess("DELETE_ACCOUNT")) {deleteAccount();

}

Code to the ActivityRBAC (Role Based Access Control)

Page 57: Coding Security: Code Mania 101

[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

Page 58: Coding Security: Code Mania 101

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/

Page 59: Coding Security: Code Mania 101

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/

Page 60: Coding Security: Code Mania 101

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/

Page 61: Coding Security: Code Mania 101

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

Page 62: Coding Security: Code Mania 101

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

Page 63: Coding Security: Code Mania 101

Other Coding Security Practices

Page 64: Coding Security: Code Mania 101

More Coding Security Practices

● Cryptography● Logging and Intrusion Detection● Leverage Security Frameworks and Libraries● Error and Exception Handling● Data Validation● Tokenization

Page 65: Coding Security: Code Mania 101

Facebook: OWASP Thailand Chapter

https://www.facebook.com/groups/owaspthailand/

Page 66: Coding Security: Code Mania 101