SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
Top 10 Bad Coding PracticesTop 10 Bad Coding Practices
Lead to Security ProblemsLead to Security Problems
Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP
MiSSConf(SP3) Apr 1, 2017MiSSConf(SP3) Apr 1, 2017
Top 10 Bad Coding PracticesTop 10 Bad Coding Practices
Lead to Security ProblemsLead to Security Problems
Narudom 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: narudom@owasp.org
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.15
float 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 Comparison
bool 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_data
WHERE 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
Top 10 Bad Coding Practices Lead to Security Problems

Weitere ähnliche Inhalte

Was ist angesagt?

Methods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall EngMethods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall Eng
Dmitry Evteev
 

Was ist angesagt? (20)

OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
 
RESTfulとは
RESTfulとはRESTfulとは
RESTfulとは
 
Spring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のことSpring Bootをはじめる時にやるべき10のこと
Spring Bootをはじめる時にやるべき10のこと
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
Uuidはどこまでuuidか試してみた
Uuidはどこまでuuidか試してみたUuidはどこまでuuidか試してみた
Uuidはどこまでuuidか試してみた
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
OAuth 2.0 Web Messaging Response Mode - OpenID Summit Tokyo 2015
 
SSRF For Bug Bounties
SSRF For Bug BountiesSSRF For Bug Bounties
SSRF For Bug Bounties
 
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Springドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
ドメインロジックに集中せよ 〜ドメイン駆動設計 powered by Spring
 
Methods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall EngMethods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall Eng
 
PHPでマルチスレッド
PHPでマルチスレッドPHPでマルチスレッド
PHPでマルチスレッド
 
PHP AST 徹底解説
PHP AST 徹底解説PHP AST 徹底解説
PHP AST 徹底解説
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang Bhatnagar
 
Outlook and Exchange for the bad guys
Outlook and Exchange for the bad guysOutlook and Exchange for the bad guys
Outlook and Exchange for the bad guys
 
世界一わかりやすいClean Architecture
世界一わかりやすいClean Architecture世界一わかりやすいClean Architecture
世界一わかりやすいClean Architecture
 
Lightweight static code analysis with semgrep
Lightweight static code analysis with semgrepLightweight static code analysis with semgrep
Lightweight static code analysis with semgrep
 
JIT のコードを読んでみた
JIT のコードを読んでみたJIT のコードを読んでみた
JIT のコードを読んでみた
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
 

Andere mochten auch

Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
Nawanan Theera-Ampornpunt
 
"Физика в походе". Повторение темы "Тепловые явления"
"Физика в походе". Повторение темы "Тепловые явления""Физика в походе". Повторение темы "Тепловые явления"
"Физика в походе". Повторение темы "Тепловые явления"
sveta7940
 
Презентація: Фізика і криміналістика
Презентація: Фізика і криміналістикаПрезентація: Фізика і криміналістика
Презентація: Фізика і криміналістика
sveta7940
 
Презентація:Ознаки рівності трикутників
Презентація:Ознаки рівності трикутниківПрезентація:Ознаки рівності трикутників
Презентація:Ознаки рівності трикутників
sveta7940
 
Презентація:Фізика в прислів"ях, приказках, загадках
Презентація:Фізика в прислів"ях, приказках, загадкахПрезентація:Фізика в прислів"ях, приказках, загадках
Презентація:Фізика в прислів"ях, приказках, загадках
sveta7940
 
Презентация:Физика в походе.
Презентация:Физика в походе. Презентация:Физика в походе.
Презентация:Физика в походе.
sveta7940
 
Задачи по теме "Тепловые явления"
Задачи по теме "Тепловые явления"Задачи по теме "Тепловые явления"
Задачи по теме "Тепловые явления"
sveta7940
 
КВН по теме "Тепловые явления"
КВН по теме "Тепловые явления"КВН по теме "Тепловые явления"
КВН по теме "Тепловые явления"
sveta7940
 
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
StorageCraft Benelux
 

Andere mochten auch (20)

Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
Security Management ของโรงพยาบาลไทย: เมื่อไรจะไล่ทัน Sector อื่น?
 
OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)
 
Securing the Internet from Cyber Criminals
Securing the Internet from Cyber CriminalsSecuring the Internet from Cyber Criminals
Securing the Internet from Cyber Criminals
 
AnyID: Security Point of View
AnyID: Security Point of ViewAnyID: Security Point of View
AnyID: Security Point of View
 
Application Security: Last Line of Defense
Application Security: Last Line of DefenseApplication Security: Last Line of Defense
Application Security: Last Line of Defense
 
Payment Card System Overview
Payment Card System OverviewPayment Card System Overview
Payment Card System Overview
 
Python Course #1
Python Course #1Python Course #1
Python Course #1
 
"Физика в походе". Повторение темы "Тепловые явления"
"Физика в походе". Повторение темы "Тепловые явления""Физика в походе". Повторение темы "Тепловые явления"
"Физика в походе". Повторение темы "Тепловые явления"
 
Презентація: Фізика і криміналістика
Презентація: Фізика і криміналістикаПрезентація: Фізика і криміналістика
Презентація: Фізика і криміналістика
 
Презентація:Ознаки рівності трикутників
Презентація:Ознаки рівності трикутниківПрезентація:Ознаки рівності трикутників
Презентація:Ознаки рівності трикутників
 
Презентація:Фізика в прислів"ях, приказках, загадках
Презентація:Фізика в прислів"ях, приказках, загадкахПрезентація:Фізика в прислів"ях, приказках, загадках
Презентація:Фізика в прислів"ях, приказках, загадках
 
Презентация:Физика в походе.
Презентация:Физика в походе. Презентация:Физика в походе.
Презентация:Физика в походе.
 
Задачи по теме "Тепловые явления"
Задачи по теме "Тепловые явления"Задачи по теме "Тепловые явления"
Задачи по теме "Тепловые явления"
 
КВН по теме "Тепловые явления"
КВН по теме "Тепловые явления"КВН по теме "Тепловые явления"
КВН по теме "Тепловые явления"
 
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
Slide presentation storage_craft_backup_disaster_recovery_for_microsoft_syste...
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
El Valor de construir First Party Data Orgánico a través del Ecosistema Digit...
El Valor de construir First Party Data Orgánico a través del Ecosistema Digit...El Valor de construir First Party Data Orgánico a través del Ecosistema Digit...
El Valor de construir First Party Data Orgánico a través del Ecosistema Digit...
 
Information system managment disaster recovery
Information system managment disaster recoveryInformation system managment disaster recovery
Information system managment disaster recovery
 
Backup, Restore, and Disaster Recovery
Backup, Restore, and Disaster RecoveryBackup, Restore, and Disaster Recovery
Backup, Restore, and Disaster Recovery
 
Unlock Security Insight from Machine Data
Unlock Security Insight from Machine DataUnlock Security Insight from Machine Data
Unlock Security Insight from Machine Data
 

Ähnlich wie Top 10 Bad Coding Practices Lead to Security Problems

Secure coding - Balgan - Tiago Henriques
Secure coding - Balgan - Tiago HenriquesSecure coding - Balgan - Tiago Henriques
Secure coding - Balgan - Tiago Henriques
Tiago Henriques
 
Security engineering 101 when good design & security work together
Security engineering 101  when good design & security work togetherSecurity engineering 101  when good design & security work together
Security engineering 101 when good design & security work together
Wendy Knox Everette
 

Ähnlich wie Top 10 Bad Coding Practices Lead to Security Problems (20)

Survey Presentation About Application Security
Survey Presentation About Application SecuritySurvey Presentation About Application Security
Survey Presentation About Application Security
 
Cypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationCypress Best Pratices for Test Automation
Cypress Best Pratices for Test Automation
 
Mobile security recipes for xamarin
Mobile security recipes for xamarinMobile security recipes for xamarin
Mobile security recipes for xamarin
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on it
 
Agile Secure Development
Agile Secure DevelopmentAgile Secure Development
Agile Secure Development
 
Secure coding - Balgan - Tiago Henriques
Secure coding - Balgan - Tiago HenriquesSecure coding - Balgan - Tiago Henriques
Secure coding - Balgan - Tiago Henriques
 
Building Efficient Software with Property Based Testing
Building Efficient Software with Property Based TestingBuilding Efficient Software with Property Based Testing
Building Efficient Software with Property Based Testing
 
Don't get stung - an introduction to the OWASP Top 10
Don't get stung - an introduction to the OWASP Top 10Don't get stung - an introduction to the OWASP Top 10
Don't get stung - an introduction to the OWASP Top 10
 
Threat Modeling for Web Applications (and other duties as assigned)
Threat Modeling for Web Applications (and other duties as assigned)Threat Modeling for Web Applications (and other duties as assigned)
Threat Modeling for Web Applications (and other duties as assigned)
 
Java application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developerJava application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developer
 
Conf2014_SplunkSecurityNinjutsu
Conf2014_SplunkSecurityNinjutsuConf2014_SplunkSecurityNinjutsu
Conf2014_SplunkSecurityNinjutsu
 
OWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risksOWASP Top 10 - 2017 Top 10 web application security risks
OWASP Top 10 - 2017 Top 10 web application security risks
 
Secure develpment 2014
Secure develpment 2014Secure develpment 2014
Secure develpment 2014
 
How to Destroy a Database
How to Destroy a DatabaseHow to Destroy a Database
How to Destroy a Database
 
Security engineering 101 when good design & security work together
Security engineering 101  when good design & security work togetherSecurity engineering 101  when good design & security work together
Security engineering 101 when good design & security work together
 
Security .NET.pdf
Security .NET.pdfSecurity .NET.pdf
Security .NET.pdf
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
 
Applying formal methods to existing software by B.Monate
Applying formal methods to existing software by B.MonateApplying formal methods to existing software by B.Monate
Applying formal methods to existing software by B.Monate
 
How to secure your web applications with NGINX
How to secure your web applications with NGINXHow to secure your web applications with NGINX
How to secure your web applications with NGINX
 
Open Source and Secure Coding Practices
Open Source and Secure Coding PracticesOpen Source and Secure Coding Practices
Open Source and Secure Coding Practices
 

Mehr von Narudom Roongsiriwong, CISSP

Mehr von Narudom Roongsiriwong, CISSP (20)

Biometric Authentication.pdf
Biometric Authentication.pdfBiometric Authentication.pdf
Biometric Authentication.pdf
 
Security Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdfSecurity Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdf
 
Secure Design: Threat Modeling
Secure Design: Threat ModelingSecure Design: Threat Modeling
Secure Design: Threat Modeling
 
Security Patterns for Software Development
Security Patterns for Software DevelopmentSecurity Patterns for Software Development
Security Patterns for Software Development
 
How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19
 
Secure Software Design for Data Privacy
Secure Software Design for Data PrivacySecure Software Design for Data Privacy
Secure Software Design for Data Privacy
 
Blockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for DummiesBlockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for Dummies
 
DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
National Digital ID Platform Technical Forum
National Digital ID Platform Technical ForumNational Digital ID Platform Technical Forum
National Digital ID Platform Technical Forum
 
IoT Security
IoT SecurityIoT Security
IoT Security
 
Embedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryEmbedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment Industry
 
Secure Your Encryption with HSM
Secure Your Encryption with HSMSecure Your Encryption with HSM
Secure Your Encryption with HSM
 
Application Security Verification Standard Project
Application Security Verification Standard ProjectApplication Security Verification Standard Project
Application Security Verification Standard Project
 
Coding Security: Code Mania 101
Coding Security: Code Mania 101Coding Security: Code Mania 101
Coding Security: Code Mania 101
 
Secure Software Development Adoption Strategy
Secure Software Development Adoption StrategySecure Software Development Adoption Strategy
Secure Software Development Adoption Strategy
 
AnyID and Privacy
AnyID and PrivacyAnyID and Privacy
AnyID and Privacy
 
OWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceOWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object Reference
 
Database Firewall with Snort
Database Firewall with SnortDatabase Firewall with Snort
Database Firewall with Snort
 
Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)
 
Risk Management in Project Management
Risk Management in Project ManagementRisk Management in Project Management
Risk Management in Project Management
 

Kürzlich hochgeladen

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Top 10 Bad Coding Practices Lead to Security Problems

  • 1. Top 10 Bad Coding PracticesTop 10 Bad Coding Practices Lead to Security ProblemsLead to Security Problems Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP MiSSConf(SP3) Apr 1, 2017MiSSConf(SP3) Apr 1, 2017 Top 10 Bad Coding PracticesTop 10 Bad Coding Practices Lead to Security ProblemsLead to Security Problems Narudom Roongsiriwong, CISSPNarudom Roongsiriwong, CISSP MiSSConf(SP3) Apr 1, 2017MiSSConf(SP3) Apr 1, 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 ● Contact: narudom@owasp.org
  • 3. 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
  • 4. “eval” Function ● Applicable Language: Java, Javascript, Python, Perl, PHP, Ruby and Interpreted Languages eval(code_to_be_dynamically_executed); 1
  • 5. “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
  • 6. “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
  • 7. Ignore Exception class Foo implements Runnable {   public void run() {     try {       Thread.sleep(1000);     } catch (InterruptedException e) {       // Ignore     }   } } 2
  • 8. 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
  • 9. 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
  • 10. Ignore Exception: Reference ● CERT, ERR00-J. - Do not suppress or ignore checked exceptions 2
  • 11. 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
  • 12. Throw Generic Exception - Security Problems ● Integrity: A caller cannot examine the exception to determine why it was thrown and consequently cannot attempt recovery 3
  • 13. 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
  • 14. Throw Generic Exception: Reference ● MITRE, CWE-397 - Declaration of Throws for Generic Exception ● CERT, ERR07-J. - Do not throw RuntimeException, Exception, or Throwable 3
  • 15. 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#
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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.15 float b = 0.1 + 0.2 if(a == b) // can be false! if(a >= b) // can also be false! 5
  • 20. 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
  • 21. 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 Comparison bool isEqual = fabs(f1 – f2) <= epsilon; 5
  • 22. 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
  • 23. 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
  • 24. Not Validate Input: Security Problems ● As data is parsed, an injected/absent/malformed delimiter may cause the process to take unexpected actions 6
  • 25. 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
  • 26. Not Validate Input: Reference ● OWASP Top Ten 2013 Category A1 - Injection ● OWASP Top Ten 2013 Category A3 - Cross-Site Scripting (XSS) 6
  • 27. 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
  • 28. 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?
  • 29. Using a Pointer Without Checking the Return Value String cmd = System.getProperty("cmd"); cmd = cmd.trim(); What if no property “cmd”? 7
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. Not Use Parameterized Query String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'"; http://example.com/app/accountView?id=' or '1'='1 8
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. Safe C# .NET Parameterized Query Example String query = "SELECT account_balance FROM user_data WHERE 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
  • 39. 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
  • 40. Hard-Coded Credentials public final Connection getConnection() throws SQLException { return DriverManager.getConnection( "jdbc:mysql://localhost/dbName", "username", "password"); } 9
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. 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
  • 45. Back-Door or Secret Page: Reference ● MITRE, CWE-489 - Leftover Debug Code 10
  • 46. 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