SlideShare a Scribd company logo
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

More Related Content

What's hot (15)

PDF
Windows İşletim Sistemi Yetki Yükseltme Çalışmaları
BGA Cyber Security
 
PDF
Bilgi Güvenliği ve Log Yönetimi Sistemlerinin Analizi
Ertugrul Akbas
 
PDF
SINIFLANDIRMA TEMELLİ KORELASYON YAKLAŞIMI
Ertugrul Akbas
 
DOCX
Sizma testine giris - Fuat Ulugay
Fuat Ulugay, CISSP
 
PDF
Web Güvenlik Açıkları ve Kullanımı (Geniş Anlatım)
Mehmet Kelepçe
 
PPTX
Managing Open Source in Application Security and Software Development Lifecycle
Black Duck by Synopsys
 
PDF
Cyber Security Extortion: Defending Against Digital Shakedowns
CrowdStrike
 
PPTX
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 13, 14, 15
BGA Cyber Security
 
PDF
BGA Pentest Hizmeti
BGA Cyber Security
 
PPTX
Secure Code Warrior - Authentication
Secure Code Warrior
 
PPTX
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 1, 2, 3
BGA Cyber Security
 
DOCX
WEB ve MOBİL SIZMA TESTLERİ
BGA Cyber Security
 
PPTX
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 19
BGA Cyber Security
 
PDF
Beyaz Şapkalı Hacker başlangıç noktası eğitimi
Kurtuluş Karasu
 
PDF
Analysis of ChIP-Seq Data
Phil Ewels
 
Windows İşletim Sistemi Yetki Yükseltme Çalışmaları
BGA Cyber Security
 
Bilgi Güvenliği ve Log Yönetimi Sistemlerinin Analizi
Ertugrul Akbas
 
SINIFLANDIRMA TEMELLİ KORELASYON YAKLAŞIMI
Ertugrul Akbas
 
Sizma testine giris - Fuat Ulugay
Fuat Ulugay, CISSP
 
Web Güvenlik Açıkları ve Kullanımı (Geniş Anlatım)
Mehmet Kelepçe
 
Managing Open Source in Application Security and Software Development Lifecycle
Black Duck by Synopsys
 
Cyber Security Extortion: Defending Against Digital Shakedowns
CrowdStrike
 
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 13, 14, 15
BGA Cyber Security
 
BGA Pentest Hizmeti
BGA Cyber Security
 
Secure Code Warrior - Authentication
Secure Code Warrior
 
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 1, 2, 3
BGA Cyber Security
 
WEB ve MOBİL SIZMA TESTLERİ
BGA Cyber Security
 
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 19
BGA Cyber Security
 
Beyaz Şapkalı Hacker başlangıç noktası eğitimi
Kurtuluş Karasu
 
Analysis of ChIP-Seq Data
Phil Ewels
 

Viewers also liked (20)

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

Similar to Top 10 Bad Coding Practices Lead to Security Problems (20)

PPTX
1606125427-week8.pptx
SumbalIlyas1
 
DOCX
NDSU CSCI 717Software ConstructionDefensive Programming.docx
vannagoforth
 
PPTX
Software construction and development.pptx
FaizanAli393009
 
PDF
Secure Programming With Static Analysis
ConSanFrancisco123
 
PPTX
20101017 program analysis_for_security_livshits_lecture03_security
Computer Science Club
 
PPTX
information system security --internet cyber security
VivekSinghShekhawat2
 
PDF
Chapter 2 program-security
Vamsee Krishna Kiran
 
PPTX
Enhancing Cybersecurity: Mitigating Common Threats
VivekSinghShekhawat2
 
PDF
Defencive programming
Asha Sari
 
PPTX
Appsec2013 assurance tagging-robert martin
drewz lin
 
PPTX
Fundamental Principles of Software Development
Nitin Bhide
 
PDF
Designing software with security in mind?
Omegapoint Academy
 
PDF
IT6701 Information Management - Unit II
pkaviya
 
PPTX
Common Sofftware Errors
Rebecca Craine
 
PPTX
Security Training: #4 Development: Typical Security Issues
Yulian Slobodyan
 
PPTX
Eirtight writing secure code
Kieran Dundon
 
PPT
Writing Secure Code – Threat Defense
amiable_indian
 
PPTX
Static analysis works for mission-critical systems, why not yours?
Rogue Wave Software
 
PPTX
No liftoff, touchdown, or heartbeat shall miss because of a software failure
Rogue Wave Software
 
PPTX
Reverse Engineering Project
Nicole Gaehle, MSIST
 
1606125427-week8.pptx
SumbalIlyas1
 
NDSU CSCI 717Software ConstructionDefensive Programming.docx
vannagoforth
 
Software construction and development.pptx
FaizanAli393009
 
Secure Programming With Static Analysis
ConSanFrancisco123
 
20101017 program analysis_for_security_livshits_lecture03_security
Computer Science Club
 
information system security --internet cyber security
VivekSinghShekhawat2
 
Chapter 2 program-security
Vamsee Krishna Kiran
 
Enhancing Cybersecurity: Mitigating Common Threats
VivekSinghShekhawat2
 
Defencive programming
Asha Sari
 
Appsec2013 assurance tagging-robert martin
drewz lin
 
Fundamental Principles of Software Development
Nitin Bhide
 
Designing software with security in mind?
Omegapoint Academy
 
IT6701 Information Management - Unit II
pkaviya
 
Common Sofftware Errors
Rebecca Craine
 
Security Training: #4 Development: Typical Security Issues
Yulian Slobodyan
 
Eirtight writing secure code
Kieran Dundon
 
Writing Secure Code – Threat Defense
amiable_indian
 
Static analysis works for mission-critical systems, why not yours?
Rogue Wave Software
 
No liftoff, touchdown, or heartbeat shall miss because of a software failure
Rogue Wave Software
 
Reverse Engineering Project
Nicole Gaehle, MSIST
 
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
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
PDF
Secure Software Development Adoption Strategy
Narudom Roongsiriwong, CISSP
 
PDF
AnyID and Privacy
Narudom Roongsiriwong, CISSP
 
PDF
OWASP Top 10 A4 – Insecure Direct Object Reference
Narudom Roongsiriwong, CISSP
 
PDF
Database Firewall with Snort
Narudom Roongsiriwong, CISSP
 
PPTX
Business continuity & disaster recovery planning (BCP & DRP)
Narudom Roongsiriwong, CISSP
 
PPT
Risk Management in Project Management
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
 
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
Secure Software Development Adoption Strategy
Narudom Roongsiriwong, CISSP
 
AnyID and Privacy
Narudom Roongsiriwong, CISSP
 
OWASP Top 10 A4 – Insecure Direct Object Reference
Narudom Roongsiriwong, CISSP
 
Database Firewall with Snort
Narudom Roongsiriwong, CISSP
 
Business continuity & disaster recovery planning (BCP & DRP)
Narudom Roongsiriwong, CISSP
 
Risk Management in Project Management
Narudom Roongsiriwong, CISSP
 

Recently uploaded (20)

PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Perfecting XM Cloud for Multisite Setup.pptx
Ahmed Okour
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Import Data Form Excel to Tally Services
Tally xperts
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Perfecting XM Cloud for Multisite Setup.pptx
Ahmed Okour
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 

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