+ All Categories
Home > Software > Top 10 Bad Coding Practices Lead to Security Problems

Top 10 Bad Coding Practices Lead to Security Problems

Date post: 11-Apr-2017
Category:
Upload: narudom-roongsiriwong-cissp
View: 1,719 times
Download: 0 times
Share this document with a friend
47
Top 10 Bad Coding Pracces Top 10 Bad Coding Pracces Lead to Security Problems Lead to Security Problems Narudom Roongsiriwong, CISSP Narudom Roongsiriwong, CISSP MiSSConf(SP3) Apr 1, 2017 MiSSConf(SP3) Apr 1, 2017 Top 10 Bad Coding Pracces Top 10 Bad Coding Pracces Lead to Security Problems Lead to Security Problems Narudom Roongsiriwong, CISSP Narudom Roongsiriwong, CISSP MiSSConf(SP3) Apr 1, 2017 MiSSConf(SP3) Apr 1, 2017
Transcript

Top 10 Bad Coding Practices Top 10 Bad Coding Practices Lead to Security ProblemsLead to Security ProblemsNarudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP

MiSSConf(SP3) Apr 1, 2017MiSSConf(SP3) Apr 1, 2017

Top 10 Bad Coding Practices Top 10 Bad Coding Practices Lead to Security ProblemsLead to Security ProblemsNarudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP

MiSSConf(SP3) Apr 1, 2017MiSSConf(SP3) Apr 1, 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 ● Contact: [email protected]

Disclaimer

● The Top 10 list is from code review in my organization and may not be applied globally.

● Code example in this presentation is mainly in Java. Specific languages will be notified upon examples

“eval” Function

● Applicable Language: Java, Javascript, Python, Perl, PHP, Ruby and Interpreted Languages

eval(code_to_be_dynamically_executed);

1

“eval” Function - Security Problems

● Confidentiality: The injected code could access restricted data / files.

● Access Control: In some cases, injectable code controls authentication; this may lead to a remote vulnerability.

● Integrity: Code injection attacks can lead to loss of data integrity in nearly all cases as the control-plane data injected is always incidental to data recall or writing.

● Non-Repudiation: Often the actions performed by injected control code are unlogged.

● Additionally, code injection can often result in the execution of arbitrary code. 1

“eval” Function: Reference

● MITRE CWE-95 - CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')

● OWASP Top Ten 2013 Category A3 - Cross-Site Scripting (XSS)

1

Ignore Exception

class Foo implements Runnable {  public void run() {    try {      Thread.sleep(1000);    } catch (InterruptedException e) {      // Ignore    }  }}

2

Ignore Exception - Security Problems

● An attacker could utilize an ignored error condition to place the system in an unexpected state that could lead to the execution of unintended logic and could cause other unintended behavior.

● Many conditions lead to application level DoS (Denial of Service)

2

Ignore Exception: How to Avoid

● Catch all relevant exceptions.● Ensure that all exceptions are handled in such a way

that you can be sure of the state of your system at any given moment.

volatile boolean validFlag = false;do {

try {// If requested file does not exist,// throws FileNotFoundException// If requested file exists, sets validFlag to true

validFlag = true;} catch (FileNotFoundException e) {

// Ask the user for a different file name}

} while (validFlag != true);// Use the file

2

Ignore Exception: Reference

● CERT, ERR00-J. - Do not suppress or ignore checked exceptions

2

Throw Generic Exception

● Applicable Language: C++, Java, C# and other .NET languages

public void doExchange() throws Exception {…

}

if (s == null) {throw new RuntimeException("Null String");

}

3

Throw Generic Exception - Security Problems

● Integrity: A caller cannot examine the exception to determine why it was thrown and consequently cannot attempt recovery

3

Throw Generic Exception: How to Avoid

● Declares a more specific exception class in the throws clause of the method

● Methods can throw a specific exception subclassed from Exception or RuntimeException.

public void doExchange() throws IOException {…

}

if (s == null) {throw new NullPointerException

("Null String");}

3

Throw Generic Exception: Reference

● MITRE, CWE-397 - Declaration of Throws for Generic Exception

● CERT, ERR07-J. - Do not throw RuntimeException, Exception, or Throwable

3

Expose Sensitive Data or Debug Statement

● Debug statements are always useful during development.

● But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information.

private void DoSomething (){ // ... Console.WriteLine

("so far, so good..."); // ...}

4

C#

Expose Sensitive Data or Debug Statement:Security Problems

● In some cases the error message tells the attacker precisely what sort of an attack the system will be vulnerable to

4

Expose Sensitive Data or Debug Statement:How to Avoid

● Do not leave debug statements that could be executed in the source code

● Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area

4

Expose Sensitive Data or Debug Statement:Reference

● OWASP Top Ten 2013 Category A6 - Sensitive Data Exposure

● MITRE, CWE-215 - Information Exposure Through Debug Information

4

Compare Floating Point with Normal Operator

● Due to rounding errors, most floating-point numbers end up being slightly imprecise.

● However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.

float a = 0.15 + 0.15float b = 0.1 + 0.2

if(a == b) // can be false!if(a >= b) // can also be false!

5

Compare Floating Point with Normal Operator:Security Problems

● Integrity: Comparing two floating point numbers to see if they are equal is usually not what you want

5

Compare Floating Point with Normal Operator:How to Avoid

● No silver bullet, choose the solution that closes enough to your intention

● How to compare– Integer Comparison

bool isEqual = (int)f1 == (int)f2;bool isEqual = (int)(f1*100) == (int)(f2*100);

// multiply by 100 for 2-digit comparison

– Epsilon Comparisonbool isEqual = fabs(f1 – f2) <= epsilon;

5

Compare Floating Point with Normal Operator:Reference

● MISRA C:2004, 13.3 - Floating-point expressions shall not be tested for equality or inequality.

● MISRA C++:2008, 6-2-2 - Floating-point expressions shall not be directly or indirectly tested for equality or inequality

5

Not Validate Input

● The software receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component.

6

Not Validate Input: Security Problems

● As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions

6

Not Validate Input: How to Avoid

● Assume all input is malicious.● Use an "accept known good" input validation

strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications.

● Reject any input that does not strictly conform to specifications, or transform it into something that does

6

Not Validate Input: Reference

● OWASP Top Ten 2013 Category A1 - Injection● OWASP Top Ten 2013 Category A3 - Cross-Site

Scripting (XSS)

6

Dereference to Null Object

● Occurs when the application dereferences a pointer that it expects to be valid, but is NULL or disposed

● 3 major cases are– Using an improperly initialized pointer– Using a pointer without checking the return value– Using a pointer to destroyed or disposed object

● Applicable Language: C, C++, Java, C# and other .NET languages

7

Using An Improperly Initialized Pointer

7

private User user;public void someMethod() {

// Do something interesting....

// Throws NPE if user hasn't been properly initialized.String username = user.getName();

}

What will “username” is?

Using a Pointer Without Checking the Return Value

String cmd = System.getProperty("cmd");cmd = cmd.trim();

What if no property “cmd”?

7

Using a Pointer to Destroyed Or Disposed Object

public FileStream WriteToFile(string path, string text){ using (var fs = File.Create(path)) { var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); return fs; }}

What will be returned?

C#

7

Dereference to Null Object: Security Problems

● Availability: Failure of the process unless exception handling (on some platforms) is available, very difficult to return the software to a safe state of operation.

● Integrity: In some circumstances and environments, code execution is possible but when the memory resource is limited and reused, errors may occur.

7

Dereference to Null Object: How to Avoid

● Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment.

● This solution does not handle the use of improperly initialized variables (CWE-665).

7

Dereference to Null Object: Reference

● MITRE, CWE-476 - NULL Pointer Dereference● CERT, EXP34-C. - Do not dereference null pointers● CERT, EXP01-J. - Do not use a null in a case where an

object is required

7

Not Use Parameterized Query

String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'";

http://example.com/app/accountView?id=' or '1'='1

8

Not Use Parameterized Query :Security Problems● SQL Injection is one of the most dangerous web

vulnerabilities. So much so that it's the #1 item in the OWASP Top 10.

● It represents a serious threat because SQL Injection allows evil attacker code to change the structure of a web application's SQL statement in a way that can– Steal data– Modify data– Potentially facilitate command injection to the

underlying OS

8

What is Parameterized Query?

● Prepared statements with variable binding● All developers should first be taught how to write

database queries.● Parameterized queries force the developer to first

define all the SQL code, and then pass in each parameter to the query later.

● This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.

● Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker.

8

Safe Java Parameterized Query Example

String custname = request.getParameter("customerName");String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement(query);pstmt.setString(1, custname); ResultSet results = pstmt.executeQuery( );

8

Safe C# .NET Parameterized Query Example

String query = "SELECT account_balance FROM user_dataWHERE user_name = ?";

try { OleDbCommand cmd = new OleDbCommand(query, conn); cmd.Parameters.Add(new OleDbParameter("customerName",

CustomerName Name.Text)); OleDbDataReader reader = cmd.ExecuteReader(); // …} catch (OleDbException se) { // error handling}

8

Not Use Parameterized Query: Reference

● MITRE, CWE-89 - Improper Neutralization of Special Elements used in an SQL Command

● MITRE, CWE-564 - SQL Injection: Hibernate● MITRE, CWE-20 - Improper Input Validation● MITRE, CWE-943 - Improper Neutralization of

Special Elements in Data Query Logic● CERT, IDS00-J. - Prevent SQL injection● OWASP Top Ten 2013 Category A1 - Injection● SANS Top 25 - Insecure Interaction Between

Components

8

Hard-Coded Credentials

public final Connection getConnection() throws SQLException { return DriverManager.getConnection( "jdbc:mysql://localhost/dbName", "username", "password");}

9

Hard-Coded Credentials: Security Problems

● If an attacker can reverse-engineer a software and see the hard-coded credential, he/she can break any systems those contain that software

● Client-side systems with hard-coded credentials propose even more of a threat, since the extraction of a credential from a binary is exceedingly simple.

9

9) Hard-Coded Credentials: Reference

● MITRE, CWE-798 - Use of Hard-coded Credentials● MITRE, CWE-259 - Use of Hard-coded Password● SANS Top 25 - Porous Defenses● CERT, MSC03-J. - Never hard code sensitive

information● OWASP Top Ten 2013 Category A2 - Broken

Authentication and Session Management

9

Back-Door or Secret Page

● Developers may add "back door" code for debugging or testing (or misuse) purposes that is not intended to be deployed with the application.

● These create security risks because they are not considered during design or testing and fall outside of the expected operating conditions of the application.

10

Back-Door or Secret Page: Security Problems

● The severity of the exposed debug application will depend on the particular instance.

● It will give an attacker sensitive information about the settings and mechanics of web applications on the server

● At worst, as is often the case, it will allow an attacker complete control over the web application and server, as well as confidential information that either of these access.

10

Back-Door or Secret Page: Reference

● MITRE, CWE-489 - Leftover Debug Code

10

Top 10 Bad Coding Practice

1. “eval” Function

2. Ignore Exception

3. Throw Generic Exception

4. Expose Sensitive Data or Debug Statement

5. Compare Floating Point with Normal Operator

6. Not validate Input

7. Dereference to Null Object

8. Not Use Parameterized Query

9. Hard-Coded Credentials

10. Back-Door or Secret Page


Recommended