SlideShare a Scribd company logo
Secure Coding Guidelines
HACK IN THE LOCK HACKATHON – JULY 2020
About me
• user@server:/home/user:$ whoami > Zakaria SMAHI
• user@server:/home/user:$ uname -a > Zakaria SMAHI
Software Engineer <linkedin.com/in/zsmahi>
• user@server:/home/user:$ history | grep ‘experience’ | more >
▪ Software Engineer and Information System Security
Enthusiast.
▪ +6 years experience in software development & software
design
▪ Talks and workshops in different IT events slideshare.net/zsmahi
Summary
• State of Software Market
• How &When do Cyber Attacks occur ?
• CommonWeb Attacks - OWASPTop 10.
• Secure coding Lifestyle.
State of Software Market
HOW SOFTWARE MARKET HAS EVOLVED
Market Revolution
Industrial Software
Client-Server Apps
Web Apps
Mobile Apps
IoT
1 Billion
web sites all around
the globe by
Feb. 2014
102
Billions
downloaded mobile
app by 2013
212
Billions
Connected devices
by 2020
Sources: NetCraft 2014, Gartner
Security threats
92 %
Of Forbes Global 2000
have been victims of an
incident by 2012
An average of
13 flaws
are detected on an
application
3,61 $
Is the cost of each non-
secure line code
> 80%
Of Web Apps are
vulnerable
90%
Of vulnerabilities are in the
App, while 80% of
security budget is gone to
secure the infrastructure
Sources: Ponemon Institute 2013, Cenzic 2013
How & When do Cyber Attacks occur ?
HOW SOFTWARE MARKET HAS EVOLVED
How do Cyber attacks occur ?
• In order to answer this question we should understand first the
Software Development Life-Cycle and Attacks Life-Cycle concepts.
• Software Development Life-Cycle (SDLC) (aka Application
Development Life-Cycle) is the process for planning, creating, testing
and deploying an Information System.
• Attacks Life-Cycle (ALC) is the process by which sophisticated attacks
are conducted.
Software Development Life-Cycle – SDLC
1
PLANNING
2 ANALYSIS
3 DESIGN
4
IMPLEMEN
TATION
5TESTING
&
INTEGRATI
ON
6
MAINTENA
NCE
Each new feature passes through this cycle
1. Planning
2. Analysis & Design
3. Implementation
4. Testing
5. Deployment
6. Maintenance → GoTo 1
a) Fixing Bugs
b) Developing extra-feature
Source:Wikipedia
Attacks Life-Cycle – ALC
1 Reconnaissance
2 Initial
Compromise
3 Command &
Control
4 Lateral
Movement
5Target
attainment
6 Exfiltration,
Corruption &
Disruption
The typical steps involved in a breach are
1. Reconnaissance – InformationGathering
2. Initial compromise: Bypassing perimeter
defenses & gaining access to the internal
system
3. Command & Control: downloading &
installing a trojan.
4. Lateral Movement: seeking to
compromise additional accounts
5. Target attainment: the attacker has
multiple remote entry points and he
understands the IT environment.
6. Exfiltration,Corruption & Disruption:
Enjoy “the coffin dance music“!
Source: HelpNetSecurity
How do Cyber attacks occur ?
• After understanding each Life-cycle, we can say that a vulnerability can
appear because of some problems at one (or more) stage(s) of software life-
cycle:
▪ Planning and Analysis : lack of understanding of the need.
▪ Design: no or bad architecture.
▪ Development: No error catching, No user inputs validation, using vulnerable libraries.
▪ Testing : no tests or not enough tests.
▪ Maintenance: creating new bugs when trying to fix old ones.
• In this presentation we’ll focus essentially on development phase and how
to apply secure coding principles.
• Since > 90 % of attacks are on the web and it’s the era of Cloud we’ll focus
our study on web vulnerabilities & web development, but it’s still applicable
on desktop apps.
Common Web Attacks
OWASP TOP 10
OWASP TOP 10
• The OWASPTop 10 is a standard awareness document for developers
and web application security.
• Using this document is the most effective first step to democratize
the secure software development security within your organization.
• It represents a broad consensus about theTOP 10 most critical
security risks to web applications.
• Globally recognized by developers as the first step towards more
secure coding.
1. Injection: (SQL Injections, NoSQL Injections, LDAP injections & OS
Command Injections):This type of attacks occur when user inputs
are not validated before being sent to an interpreter, which
conducts to its execution as a part of a command or a query, the
impact will be the gathering of sensitive data (ex. User accounts,
ServerVersions,…etc.).
• Ex SQL Injection:The query executed for checking a user is:
• SELECT * FROM UsersWhere username = ‘{UserInput}’
• Possible SQL Injection strings :
• SELECT * FROM Users Where username = ‘’OR ‘1’=‘1’ →The attacker can obtain all users.
• SELECT * FROM Users Where username = ‘zsmahi’; DELETE FROM Users Where username =
‘admin’
OWASP TOP 10 Attacks
• Ex OS Command Injection:This code call the
cat command to show the content of a file.
• It’s executed like this : $ ./CommandCat file.txt
• The output will be : “this is the content of
file.txt”
• But what happen if I pass this parameter :
file.txt; ls
• The interpreted command will be cat file.txt; ls
• The output will be:
• “this is the content of file.txt”
• File.txt; anotherFile.txt;
OWASP TOP 10 Attacks
2. Broken Authentication: Due to the poor implementation of
authentication and session management, an attacker can compromise
passwords and sessions to assume other users’ identities temporarily or
permanently .
• Ex: Access to user profiles without being authenticated.
3. Sensitive Data Exposure: Many web applications do not properly protect
sensitive data, such as Personal Information.Attackers may steal or modify such
weakly protected data to conduct frauds, identity theft, …etc. Sensitive data may
be compromised without extra protection (No Encryption).
• Ex:WhenTLS is not used in all pages, an attacker can monitor network traffic and
obtain all your sent data.
4. XML External Entities (XXE): In some old still used apps, this vulnerability can
occur, in fact an attacker can pass an external entity reference (<!ENTITY /> tag)
within the XML Query that will be parsed by XML parser and getting sensitive
data or even engender a Denial of Service.
• Ex: Send to the XML Parser an external reference with no return (Infinite loop).
OWASP TOP 10 Attacks
OWASP TOP 10 Attacks
5. Broken Access Control : Even with a good session management, an
attacker can access unauthorized functionalities or data and perform non
permitted operations normally for a simple user.
• Ex: Access to admin panel with a normal user credentials..
6. Security Misconfiguration : Even if security misconfiguration is not seen,
but it can help an Attacker in his crime by giving him information about
the server, deployed frameworks (Information Gathering).
• Ex: Non secure Http Headers, enabled debug mode in production,Verbose Error
Messages & Exceptions.
7. Cross Site Scripting (XSS): It occurs whenever an application sends data to
web client without proper validation or escaping (Not encoded). XSS
allows hacker to execute scripts in victim’s browser to redirect him to
malicious web site or hijacking his session. It can be reflected or stored.
• Ex: the Script tag: <script>alert(Document.cookies)</script> to steal users' cookies.
OWASP TOP 10 Attacks
8. Insecure Deserialization : Called also Untrusted Deserialization, when an input
can be modified by user, the result will be an untrusted deserialization
vulnerability, in fact the deserialized string can contain a remote malicious code
that will be executed when converted back to binary format
• Ex: CVE-2017-9805Vulnerability discovered in Apache Struts Framework.
9. Using Components with known vulnerabilities: Frameworks, libraries and any
software module run with the same privileges as the caller app, so when we use a
vulnerable component, we may undermine application defenses and enable
various attacks and impacts.
• Ex: Bootstrap 3.4.1 contains an XSS vulnerability <CVE-2019-8331>.
• Ex: SAP NetWeaverAS JAVA (LM ConfigurationWizard) 7.30 contains a broken
authentication <CVE-2020-6287>.
10. Insufficient Logging & Monitoring: Even if it’s not a real attack but without a good
logging strategy and without monitoring, attackers can maintain persistence and
pivot to more systems. Most breach studies show time to detect a breach is over
200 days, typically detected by external parties rather than internal processes or
monitoring.
0
0,5
1
1,5
2
2,5
3
Exploitability
Prevelance
DetectabilityTechnical Impact
Business Impact ****
Comparison between Attacks
Injection XSS XXE BAC * ILM ** CKV ***
- *BAC : Broken Access Control - ** ILM :Insufficient Logging & Monitoring - *** CKV : using Component with KnownVulnerabilities
- ****The business Impact depends on the organization, its size and its data
Secure Coding Lifestyle
/* LIFE RUNS BETTER ON SECURE CODE */
Secure Coding Lifestyle
• Now, after understanding common vulnerabilities and their impact,
it’s high time to change our bad habits and to adopt a new coding
lifestyle.
• In a world where attacks are inevitable, secure coding becomes a
requirement.
• So what should I do to make my code more secure?
Secure Coding Practices
• InputValidation :
▪ Encode data to a common character set before validating (ex. utf-8).
▪ All data should be validated in a trusted system (server-side) using a
standard tested routine for each type of inbound validation.
▪ Centralized the input validation routines for the application. → for
Single Responsibility principle (SOLID principles) and for more
efficiency on validation.
▪ Validate data: check if received data has the expected type (ex. In C#
useTryCast or Cast withinTry-Catch block), with the expected range
and length to avoid IndexOutOfRange Exceptions, Buffer Overflows.
▪ Handle null bytes (0), and specific strings (../ & .. for path) and their
encoded representation.
• Risks addressed:
Injections XSS Unvalidated redirects
and forwards
Secure Coding Practices
• Output Encoding :
▪ All data should be encoded in a trusted system (server-side) using a
standard tested routine for each type of inbound validation.
▪ Modern backend programming languages include different encoding
types (html, css, javascript, url).
▪ Centralized the output encoding routines for the application.
▪ Validate data: Prepare response data before sending them. (check if
it’s really what’s expected → safe serialization).
▪ Handle null bytes (0).
• Risks addressed:
Injections XSS Client-Side
Injection
Secure Coding Practices
• Parametrize Queries:
▪ Parameterize the queries by binding the variables.
▪ $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname,
email)VALUES (?, ?, ?)"); // php code
$stmt->bind_param("sss", $firstname, $lastname, $email);
▪ In general way for more security in database :
▪ The application should use the lowest possible level of privilege when
accessing the database.
▪ Connection strings should not be hard coded within the application but
stored in a separate configuration file on a trusted system and they should
be encrypted.
• Risks addressed:
SQL Injections
Secure Coding Practices
• Implement Identity and Authentication Controls:
▪ Session identifier creation must always be done on server-side.
▪ Implement secure password storage.
▪ Use strong authentication methods, including multi-factor authentication (sms, e-
mail validation) , biometric authentication mechanism.
▪ Implement a secure password recovery mechanism to help users gain access to their
account if they forget their password.
▪ Logout functionality should fully terminate the associated session or connection and
should be available from all pages protected by authorization.
▪ Establish timeout and inactivity periods for every session.
▪ Deny all access if the application cannot access its security configuration information.
▪ Enforce authorization controls on every request, including those made by server-side
scripts.
▪ Restrict access to protected URLs and Functionalities to only authorized users/roles.
▪ Use re-authentication for sensitive or highly secure features.
▪ Use monitoring and analytics to spot suspicious IP addresses and machine IDs.
• Risks addressed:
Broken Authentication
Broken Access Control
Secure Coding Practices
• Protect Data & Information:
▪ Use transport layer security (TLS) to encrypt data in transit.
▪ Don’t reinvent the wheel, most programming languages have their
own implemented crypto-libraries, so use them wisely.
▪ Return only minimum needed data. → Queries like ‘Select *’ should
be avoided as possible.
▪ UseTry-Catch blocks and never return a technical exception.
▪ A well codedTry-Catch block can avoid a DoS.
▪ Technical exception should be logged and return a Business
Exception to users
▪ Never return NullReferenceException but return
SearchedUserNotFoundException.
• Risks addressed:
Sensitive
Data
Exposure
Security
Misconfiguration
Secure Coding Practices
• Other coding best practices:
▪ Use only known maintained well documented libraries and keep
them up-to-date.
▪ Use managed code instead of unmanaged code.
▪ Use explicit variable types.
▪ Pay attention to compiler warnings →The warning of today is the
vulnerability of tomorrow.
▪ Avoid complexity in designing your solution → KISS (Keep It Simple,
Stupid).
▪ Use an extensible logging framework to ensure that all log entries
are consistent → Apache Log4j.
▪ Do Unit tests.
• Risks addressed:
All vulnerabilities
Secure Coding Practices
• Other coding best practices:
▪ Use proper http code error in your API (200 when OK, 401 when
unauthorized, 403 when forbidden,..etc.).
▪ Use secure captcha (ex.Google recaptcha) in forms.
▪ Integrate Security testing in your CI:You can use OWASP ZAProxy,
SonarQube (via its security rules), Nexus LifeCycle.
▪ Never trust user inputs, always validate inputs and encode outputs.
▪ Always code as if the person who ends up maintaining your code is a
violent psychopath who knows where you live.
▪ Never stop learning, because once you stop learning you start dying.
• Risks addressed:
All vulnerabilities
QUESTIONS ?
Further reading
• OWASPTOP 10: https://owasp.org/www-project-top-ten/
• OWASP Secure Coding Practices: https://owasp.org/www-pdf-
archive/OWASP_SCP_Quick_Reference_Guide_v2.pdf
• ANSSI Recommandations : https://www.ssi.gouv.fr/
• 9hours free online training to understand secure coding principles:
https://www.cybrary.it/course/secure-coding/
THANKS FOR YOUR ATTENTION !
Secure coding guidelines

More Related Content

What's hot (20)

PPT
Secure code practices
Hina Rawal
 
PPT
Introduction to Web Application Penetration Testing
Anurag Srivastava
 
PDF
OWASP Secure Coding Practices - Quick Reference Guide
Ludovic Petit
 
PPTX
API Security Fundamentals
José Haro Peralta
 
PPTX
OWASP Top 10 2021 What's New
Michael Furman
 
PDF
OWASP Top 10 Web Application Vulnerabilities
Software Guru
 
PPT
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Brian Huff
 
PPTX
Secure coding practices
Scott Hurrey
 
PPTX
Threat modelling(system + enterprise)
abhimanyubhogwan
 
PPTX
Introduction to penetration testing
Nezar Alazzabi
 
PPTX
Sensitive Data Exposure
abodiford
 
PDF
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
PPTX
Vulnerabilities in modern web applications
Niyas Nazar
 
PPTX
Penetration Testing
RomSoft SRL
 
PDF
Cyber Threat Intelligence
mohamed nasri
 
PPT
Owasp Top 10 And Security Flaw Root Causes
Marco Morana
 
PPTX
The CIA triad.pptx
GulnurAzat
 
PDF
CSSLP & OWASP & WebGoat
Surachai Chatchalermpun
 
PPTX
SIEM Primer:
Anton Chuvakin
 
PDF
Secure Coding principles by example: Build Security In from the start - Carlo...
Codemotion
 
Secure code practices
Hina Rawal
 
Introduction to Web Application Penetration Testing
Anurag Srivastava
 
OWASP Secure Coding Practices - Quick Reference Guide
Ludovic Petit
 
API Security Fundamentals
José Haro Peralta
 
OWASP Top 10 2021 What's New
Michael Furman
 
OWASP Top 10 Web Application Vulnerabilities
Software Guru
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Brian Huff
 
Secure coding practices
Scott Hurrey
 
Threat modelling(system + enterprise)
abhimanyubhogwan
 
Introduction to penetration testing
Nezar Alazzabi
 
Sensitive Data Exposure
abodiford
 
Secure Code Review 101
Narudom Roongsiriwong, CISSP
 
Vulnerabilities in modern web applications
Niyas Nazar
 
Penetration Testing
RomSoft SRL
 
Cyber Threat Intelligence
mohamed nasri
 
Owasp Top 10 And Security Flaw Root Causes
Marco Morana
 
The CIA triad.pptx
GulnurAzat
 
CSSLP & OWASP & WebGoat
Surachai Chatchalermpun
 
SIEM Primer:
Anton Chuvakin
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Codemotion
 

Similar to Secure coding guidelines (20)

PPTX
Owasp top 10 2017
ibrahimumer2
 
PDF
Application Security - Your Success Depends on it
WSO2
 
PPT
30ITSecurityThreatsVulnerabilitiesandCountermeasuresV1.ppt
Kaukau9
 
PPTX
Web_Appication_Security_Training_For_Developers.pptx
xobewe1102
 
PDF
OWASP Top 10 List Overview for Web Developers
Benjamin Floyd
 
PPTX
Security is not a feature
Elizabeth Smith
 
PDF
Owasp Top 10
Shivam Porwal
 
PDF
OWASP Top Ten in Practice
Security Innovation
 
PPTX
CyberSecurityppt. pptx
iamayesha2526
 
PPTX
Owasp top 10 vulnerabilities
OWASP Delhi
 
PDF
Owasp top 10_openwest_2019
Sean Jackson
 
DOCX
supraja technologies material for secure coding
Sri Latha
 
PPTX
owasp features in secure coding techniques
Sri Latha
 
PPTX
OWASP top 10-2013
tmd800
 
PDF
Ab cs of software security
David Klassen
 
PDF
Security Awareness
Lucas Hendrich
 
PPT
Discovering the Value of Verifying Web Application Security Using IBM Rationa...
Alan Kan
 
PPT
Owasp top 10 & Web vulnerabilities
RIZWAN HASAN
 
PDF
Top 10 web application security risks akash mahajan
Akash Mahajan
 
PPTX
Owasp
penetration Tester
 
Owasp top 10 2017
ibrahimumer2
 
Application Security - Your Success Depends on it
WSO2
 
30ITSecurityThreatsVulnerabilitiesandCountermeasuresV1.ppt
Kaukau9
 
Web_Appication_Security_Training_For_Developers.pptx
xobewe1102
 
OWASP Top 10 List Overview for Web Developers
Benjamin Floyd
 
Security is not a feature
Elizabeth Smith
 
Owasp Top 10
Shivam Porwal
 
OWASP Top Ten in Practice
Security Innovation
 
CyberSecurityppt. pptx
iamayesha2526
 
Owasp top 10 vulnerabilities
OWASP Delhi
 
Owasp top 10_openwest_2019
Sean Jackson
 
supraja technologies material for secure coding
Sri Latha
 
owasp features in secure coding techniques
Sri Latha
 
OWASP top 10-2013
tmd800
 
Ab cs of software security
David Klassen
 
Security Awareness
Lucas Hendrich
 
Discovering the Value of Verifying Web Application Security Using IBM Rationa...
Alan Kan
 
Owasp top 10 & Web vulnerabilities
RIZWAN HASAN
 
Top 10 web application security risks akash mahajan
Akash Mahajan
 
Ad

More from Zakaria SMAHI (12)

PPTX
Bootstrap 3
Zakaria SMAHI
 
PPTX
Sécurité des web services soap
Zakaria SMAHI
 
PPTX
Formation python micro club.net
Zakaria SMAHI
 
PDF
Securisation des web services soap contre les attaques par injection
Zakaria SMAHI
 
PPTX
Sécurisation des Web Services SOAP contre les attaques par injection par la m...
Zakaria SMAHI
 
PDF
Buffer Overflow exploitation
Zakaria SMAHI
 
PPTX
Owasp webgoat
Zakaria SMAHI
 
PPTX
Javascript 2.0
Zakaria SMAHI
 
PPTX
Javascript 1.0
Zakaria SMAHI
 
PDF
workshop initiation ssh
Zakaria SMAHI
 
PDF
JQuery
Zakaria SMAHI
 
PDF
Guide d'utilisation de nmap par smahi zakaria
Zakaria SMAHI
 
Bootstrap 3
Zakaria SMAHI
 
Sécurité des web services soap
Zakaria SMAHI
 
Formation python micro club.net
Zakaria SMAHI
 
Securisation des web services soap contre les attaques par injection
Zakaria SMAHI
 
Sécurisation des Web Services SOAP contre les attaques par injection par la m...
Zakaria SMAHI
 
Buffer Overflow exploitation
Zakaria SMAHI
 
Owasp webgoat
Zakaria SMAHI
 
Javascript 2.0
Zakaria SMAHI
 
Javascript 1.0
Zakaria SMAHI
 
workshop initiation ssh
Zakaria SMAHI
 
Guide d'utilisation de nmap par smahi zakaria
Zakaria SMAHI
 
Ad

Recently uploaded (20)

PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PPTX
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
PPTX
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
 
PPTX
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PPTX
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PDF
>Wondershare Filmora Crack Free Download 2025
utfefguu
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
computer forensics encase emager app exp6 1.pptx
ssuser343e92
 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
Rewards and Recognition (2).pdf
ethan Talor
 
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
 
Seamless-Image-Conversion-From-Raster-to-wrt-rtx-rtx.pptx
Quick Conversion Services
 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
Automated Test Case Repair Using Language Models
Lionel Briand
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
Automatic_Iperf_Log_Result_Excel_visual_v2.pptx
Chen-Chih Lee
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
>Wondershare Filmora Crack Free Download 2025
utfefguu
 

Secure coding guidelines

  • 1. Secure Coding Guidelines HACK IN THE LOCK HACKATHON – JULY 2020
  • 2. About me • user@server:/home/user:$ whoami > Zakaria SMAHI • user@server:/home/user:$ uname -a > Zakaria SMAHI Software Engineer <linkedin.com/in/zsmahi> • user@server:/home/user:$ history | grep ‘experience’ | more > ▪ Software Engineer and Information System Security Enthusiast. ▪ +6 years experience in software development & software design ▪ Talks and workshops in different IT events slideshare.net/zsmahi
  • 3. Summary • State of Software Market • How &When do Cyber Attacks occur ? • CommonWeb Attacks - OWASPTop 10. • Secure coding Lifestyle.
  • 4. State of Software Market HOW SOFTWARE MARKET HAS EVOLVED
  • 5. Market Revolution Industrial Software Client-Server Apps Web Apps Mobile Apps IoT 1 Billion web sites all around the globe by Feb. 2014 102 Billions downloaded mobile app by 2013 212 Billions Connected devices by 2020 Sources: NetCraft 2014, Gartner
  • 6. Security threats 92 % Of Forbes Global 2000 have been victims of an incident by 2012 An average of 13 flaws are detected on an application 3,61 $ Is the cost of each non- secure line code > 80% Of Web Apps are vulnerable 90% Of vulnerabilities are in the App, while 80% of security budget is gone to secure the infrastructure Sources: Ponemon Institute 2013, Cenzic 2013
  • 7. How & When do Cyber Attacks occur ? HOW SOFTWARE MARKET HAS EVOLVED
  • 8. How do Cyber attacks occur ? • In order to answer this question we should understand first the Software Development Life-Cycle and Attacks Life-Cycle concepts. • Software Development Life-Cycle (SDLC) (aka Application Development Life-Cycle) is the process for planning, creating, testing and deploying an Information System. • Attacks Life-Cycle (ALC) is the process by which sophisticated attacks are conducted.
  • 9. Software Development Life-Cycle – SDLC 1 PLANNING 2 ANALYSIS 3 DESIGN 4 IMPLEMEN TATION 5TESTING & INTEGRATI ON 6 MAINTENA NCE Each new feature passes through this cycle 1. Planning 2. Analysis & Design 3. Implementation 4. Testing 5. Deployment 6. Maintenance → GoTo 1 a) Fixing Bugs b) Developing extra-feature Source:Wikipedia
  • 10. Attacks Life-Cycle – ALC 1 Reconnaissance 2 Initial Compromise 3 Command & Control 4 Lateral Movement 5Target attainment 6 Exfiltration, Corruption & Disruption The typical steps involved in a breach are 1. Reconnaissance – InformationGathering 2. Initial compromise: Bypassing perimeter defenses & gaining access to the internal system 3. Command & Control: downloading & installing a trojan. 4. Lateral Movement: seeking to compromise additional accounts 5. Target attainment: the attacker has multiple remote entry points and he understands the IT environment. 6. Exfiltration,Corruption & Disruption: Enjoy “the coffin dance music“! Source: HelpNetSecurity
  • 11. How do Cyber attacks occur ? • After understanding each Life-cycle, we can say that a vulnerability can appear because of some problems at one (or more) stage(s) of software life- cycle: ▪ Planning and Analysis : lack of understanding of the need. ▪ Design: no or bad architecture. ▪ Development: No error catching, No user inputs validation, using vulnerable libraries. ▪ Testing : no tests or not enough tests. ▪ Maintenance: creating new bugs when trying to fix old ones. • In this presentation we’ll focus essentially on development phase and how to apply secure coding principles. • Since > 90 % of attacks are on the web and it’s the era of Cloud we’ll focus our study on web vulnerabilities & web development, but it’s still applicable on desktop apps.
  • 13. OWASP TOP 10 • The OWASPTop 10 is a standard awareness document for developers and web application security. • Using this document is the most effective first step to democratize the secure software development security within your organization. • It represents a broad consensus about theTOP 10 most critical security risks to web applications. • Globally recognized by developers as the first step towards more secure coding.
  • 14. 1. Injection: (SQL Injections, NoSQL Injections, LDAP injections & OS Command Injections):This type of attacks occur when user inputs are not validated before being sent to an interpreter, which conducts to its execution as a part of a command or a query, the impact will be the gathering of sensitive data (ex. User accounts, ServerVersions,…etc.). • Ex SQL Injection:The query executed for checking a user is: • SELECT * FROM UsersWhere username = ‘{UserInput}’ • Possible SQL Injection strings : • SELECT * FROM Users Where username = ‘’OR ‘1’=‘1’ →The attacker can obtain all users. • SELECT * FROM Users Where username = ‘zsmahi’; DELETE FROM Users Where username = ‘admin’ OWASP TOP 10 Attacks
  • 15. • Ex OS Command Injection:This code call the cat command to show the content of a file. • It’s executed like this : $ ./CommandCat file.txt • The output will be : “this is the content of file.txt” • But what happen if I pass this parameter : file.txt; ls • The interpreted command will be cat file.txt; ls • The output will be: • “this is the content of file.txt” • File.txt; anotherFile.txt; OWASP TOP 10 Attacks
  • 16. 2. Broken Authentication: Due to the poor implementation of authentication and session management, an attacker can compromise passwords and sessions to assume other users’ identities temporarily or permanently . • Ex: Access to user profiles without being authenticated. 3. Sensitive Data Exposure: Many web applications do not properly protect sensitive data, such as Personal Information.Attackers may steal or modify such weakly protected data to conduct frauds, identity theft, …etc. Sensitive data may be compromised without extra protection (No Encryption). • Ex:WhenTLS is not used in all pages, an attacker can monitor network traffic and obtain all your sent data. 4. XML External Entities (XXE): In some old still used apps, this vulnerability can occur, in fact an attacker can pass an external entity reference (<!ENTITY /> tag) within the XML Query that will be parsed by XML parser and getting sensitive data or even engender a Denial of Service. • Ex: Send to the XML Parser an external reference with no return (Infinite loop). OWASP TOP 10 Attacks
  • 17. OWASP TOP 10 Attacks 5. Broken Access Control : Even with a good session management, an attacker can access unauthorized functionalities or data and perform non permitted operations normally for a simple user. • Ex: Access to admin panel with a normal user credentials.. 6. Security Misconfiguration : Even if security misconfiguration is not seen, but it can help an Attacker in his crime by giving him information about the server, deployed frameworks (Information Gathering). • Ex: Non secure Http Headers, enabled debug mode in production,Verbose Error Messages & Exceptions. 7. Cross Site Scripting (XSS): It occurs whenever an application sends data to web client without proper validation or escaping (Not encoded). XSS allows hacker to execute scripts in victim’s browser to redirect him to malicious web site or hijacking his session. It can be reflected or stored. • Ex: the Script tag: <script>alert(Document.cookies)</script> to steal users' cookies.
  • 18. OWASP TOP 10 Attacks 8. Insecure Deserialization : Called also Untrusted Deserialization, when an input can be modified by user, the result will be an untrusted deserialization vulnerability, in fact the deserialized string can contain a remote malicious code that will be executed when converted back to binary format • Ex: CVE-2017-9805Vulnerability discovered in Apache Struts Framework. 9. Using Components with known vulnerabilities: Frameworks, libraries and any software module run with the same privileges as the caller app, so when we use a vulnerable component, we may undermine application defenses and enable various attacks and impacts. • Ex: Bootstrap 3.4.1 contains an XSS vulnerability <CVE-2019-8331>. • Ex: SAP NetWeaverAS JAVA (LM ConfigurationWizard) 7.30 contains a broken authentication <CVE-2020-6287>. 10. Insufficient Logging & Monitoring: Even if it’s not a real attack but without a good logging strategy and without monitoring, attackers can maintain persistence and pivot to more systems. Most breach studies show time to detect a breach is over 200 days, typically detected by external parties rather than internal processes or monitoring.
  • 19. 0 0,5 1 1,5 2 2,5 3 Exploitability Prevelance DetectabilityTechnical Impact Business Impact **** Comparison between Attacks Injection XSS XXE BAC * ILM ** CKV *** - *BAC : Broken Access Control - ** ILM :Insufficient Logging & Monitoring - *** CKV : using Component with KnownVulnerabilities - ****The business Impact depends on the organization, its size and its data
  • 20. Secure Coding Lifestyle /* LIFE RUNS BETTER ON SECURE CODE */
  • 21. Secure Coding Lifestyle • Now, after understanding common vulnerabilities and their impact, it’s high time to change our bad habits and to adopt a new coding lifestyle. • In a world where attacks are inevitable, secure coding becomes a requirement. • So what should I do to make my code more secure?
  • 22. Secure Coding Practices • InputValidation : ▪ Encode data to a common character set before validating (ex. utf-8). ▪ All data should be validated in a trusted system (server-side) using a standard tested routine for each type of inbound validation. ▪ Centralized the input validation routines for the application. → for Single Responsibility principle (SOLID principles) and for more efficiency on validation. ▪ Validate data: check if received data has the expected type (ex. In C# useTryCast or Cast withinTry-Catch block), with the expected range and length to avoid IndexOutOfRange Exceptions, Buffer Overflows. ▪ Handle null bytes (0), and specific strings (../ & .. for path) and their encoded representation. • Risks addressed: Injections XSS Unvalidated redirects and forwards
  • 23. Secure Coding Practices • Output Encoding : ▪ All data should be encoded in a trusted system (server-side) using a standard tested routine for each type of inbound validation. ▪ Modern backend programming languages include different encoding types (html, css, javascript, url). ▪ Centralized the output encoding routines for the application. ▪ Validate data: Prepare response data before sending them. (check if it’s really what’s expected → safe serialization). ▪ Handle null bytes (0). • Risks addressed: Injections XSS Client-Side Injection
  • 24. Secure Coding Practices • Parametrize Queries: ▪ Parameterize the queries by binding the variables. ▪ $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)VALUES (?, ?, ?)"); // php code $stmt->bind_param("sss", $firstname, $lastname, $email); ▪ In general way for more security in database : ▪ The application should use the lowest possible level of privilege when accessing the database. ▪ Connection strings should not be hard coded within the application but stored in a separate configuration file on a trusted system and they should be encrypted. • Risks addressed: SQL Injections
  • 25. Secure Coding Practices • Implement Identity and Authentication Controls: ▪ Session identifier creation must always be done on server-side. ▪ Implement secure password storage. ▪ Use strong authentication methods, including multi-factor authentication (sms, e- mail validation) , biometric authentication mechanism. ▪ Implement a secure password recovery mechanism to help users gain access to their account if they forget their password. ▪ Logout functionality should fully terminate the associated session or connection and should be available from all pages protected by authorization. ▪ Establish timeout and inactivity periods for every session. ▪ Deny all access if the application cannot access its security configuration information. ▪ Enforce authorization controls on every request, including those made by server-side scripts. ▪ Restrict access to protected URLs and Functionalities to only authorized users/roles. ▪ Use re-authentication for sensitive or highly secure features. ▪ Use monitoring and analytics to spot suspicious IP addresses and machine IDs. • Risks addressed: Broken Authentication Broken Access Control
  • 26. Secure Coding Practices • Protect Data & Information: ▪ Use transport layer security (TLS) to encrypt data in transit. ▪ Don’t reinvent the wheel, most programming languages have their own implemented crypto-libraries, so use them wisely. ▪ Return only minimum needed data. → Queries like ‘Select *’ should be avoided as possible. ▪ UseTry-Catch blocks and never return a technical exception. ▪ A well codedTry-Catch block can avoid a DoS. ▪ Technical exception should be logged and return a Business Exception to users ▪ Never return NullReferenceException but return SearchedUserNotFoundException. • Risks addressed: Sensitive Data Exposure Security Misconfiguration
  • 27. Secure Coding Practices • Other coding best practices: ▪ Use only known maintained well documented libraries and keep them up-to-date. ▪ Use managed code instead of unmanaged code. ▪ Use explicit variable types. ▪ Pay attention to compiler warnings →The warning of today is the vulnerability of tomorrow. ▪ Avoid complexity in designing your solution → KISS (Keep It Simple, Stupid). ▪ Use an extensible logging framework to ensure that all log entries are consistent → Apache Log4j. ▪ Do Unit tests. • Risks addressed: All vulnerabilities
  • 28. Secure Coding Practices • Other coding best practices: ▪ Use proper http code error in your API (200 when OK, 401 when unauthorized, 403 when forbidden,..etc.). ▪ Use secure captcha (ex.Google recaptcha) in forms. ▪ Integrate Security testing in your CI:You can use OWASP ZAProxy, SonarQube (via its security rules), Nexus LifeCycle. ▪ Never trust user inputs, always validate inputs and encode outputs. ▪ Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. ▪ Never stop learning, because once you stop learning you start dying. • Risks addressed: All vulnerabilities
  • 30. Further reading • OWASPTOP 10: https://owasp.org/www-project-top-ten/ • OWASP Secure Coding Practices: https://owasp.org/www-pdf- archive/OWASP_SCP_Quick_Reference_Guide_v2.pdf • ANSSI Recommandations : https://www.ssi.gouv.fr/ • 9hours free online training to understand secure coding principles: https://www.cybrary.it/course/secure-coding/
  • 31. THANKS FOR YOUR ATTENTION !