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

PDF
Secure Coding principles by example: Build Security In from the start - Carlo...
PPT
Secure code practices
PPTX
Application Security Architecture and Threat Modelling
PDF
Secure Code Review 101
PPTX
Secure coding practices
PDF
Owasp top 10
ODP
OWASP Secure Coding
PDF
Secure Software Development Lifecycle - Devoxx MA 2018
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure code practices
Application Security Architecture and Threat Modelling
Secure Code Review 101
Secure coding practices
Owasp top 10
OWASP Secure Coding
Secure Software Development Lifecycle - Devoxx MA 2018

What's hot (20)

PPTX
Secure coding practices
PPTX
OWASP Top 10 2021 Presentation (Jul 2022)
PDF
OWASP Top 10 Web Application Vulnerabilities
PPTX
Secure Coding 101 - OWASP University of Ottawa Workshop
PPT
Top 10 Web Security Vulnerabilities (OWASP Top 10)
PPTX
OWASP Top 10 2021 What's New
PDF
Web Application Security and Awareness
PDF
Secure coding presentation Oct 3 2020
PDF
Web Application Penetration Testing
PPT
Introduction to Web Application Penetration Testing
PPT
OWASP Top Ten
PDF
Penetration Testing Tutorial | Penetration Testing Tools | Cyber Security Tra...
PDF
Introduction to Software Security and Best Practices
PDF
Penetration testing & Ethical Hacking
PDF
OWASP API Security Top 10 - API World
PPTX
System hacking
 
PPTX
Introduction to penetration testing
PPTX
Cyber security
PPT
Introduction To OWASP
PDF
Cyber Security Awareness
Secure coding practices
OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 Web Application Vulnerabilities
Secure Coding 101 - OWASP University of Ottawa Workshop
Top 10 Web Security Vulnerabilities (OWASP Top 10)
OWASP Top 10 2021 What's New
Web Application Security and Awareness
Secure coding presentation Oct 3 2020
Web Application Penetration Testing
Introduction to Web Application Penetration Testing
OWASP Top Ten
Penetration Testing Tutorial | Penetration Testing Tools | Cyber Security Tra...
Introduction to Software Security and Best Practices
Penetration testing & Ethical Hacking
OWASP API Security Top 10 - API World
System hacking
 
Introduction to penetration testing
Cyber security
Introduction To OWASP
Cyber Security Awareness
Ad

Similar to Secure coding guidelines (20)

PPTX
Owasp top 10 2017
PDF
Application Security - Your Success Depends on it
PPT
30ITSecurityThreatsVulnerabilitiesandCountermeasuresV1.ppt
PPTX
Web_Appication_Security_Training_For_Developers.pptx
PDF
OWASP Top 10 List Overview for Web Developers
PPTX
Security is not a feature
PDF
Owasp Top 10
PDF
OWASP Top Ten in Practice
PPTX
CyberSecurityppt. pptx
PPTX
Owasp top 10 vulnerabilities
PDF
Owasp top 10_openwest_2019
DOCX
supraja technologies material for secure coding
PPTX
owasp features in secure coding techniques
PPTX
OWASP top 10-2013
PDF
Ab cs of software security
PDF
Security Awareness
PPT
Discovering the Value of Verifying Web Application Security Using IBM Rationa...
PPT
Owasp top 10 & Web vulnerabilities
PDF
Top 10 web application security risks akash mahajan
PPTX
Owasp top 10 2017
Application Security - Your Success Depends on it
30ITSecurityThreatsVulnerabilitiesandCountermeasuresV1.ppt
Web_Appication_Security_Training_For_Developers.pptx
OWASP Top 10 List Overview for Web Developers
Security is not a feature
Owasp Top 10
OWASP Top Ten in Practice
CyberSecurityppt. pptx
Owasp top 10 vulnerabilities
Owasp top 10_openwest_2019
supraja technologies material for secure coding
owasp features in secure coding techniques
OWASP top 10-2013
Ab cs of software security
Security Awareness
Discovering the Value of Verifying Web Application Security Using IBM Rationa...
Owasp top 10 & Web vulnerabilities
Top 10 web application security risks akash mahajan
Ad

More from Zakaria SMAHI (12)

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

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Introduction to Artificial Intelligence
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
history of c programming in notes for students .pptx
PDF
AI in Product Development-omnex systems
PDF
System and Network Administraation Chapter 3
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
Nekopoi APK 2025 free lastest update
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Digital Strategies for Manufacturing Companies
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Odoo POS Development Services by CandidRoot Solutions
How to Migrate SBCGlobal Email to Yahoo Easily
How to Choose the Right IT Partner for Your Business in Malaysia
Introduction to Artificial Intelligence
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
history of c programming in notes for students .pptx
AI in Product Development-omnex systems
System and Network Administraation Chapter 3
Online Work Permit System for Fast Permit Processing
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
ManageIQ - Sprint 268 Review - Slide Deck
How Creative Agencies Leverage Project Management Software.pdf
L1 - Introduction to python Backend.pptx
Nekopoi APK 2025 free lastest update
PTS Company Brochure 2025 (1).pdf.......
Digital Strategies for Manufacturing Companies
CHAPTER 2 - PM Management and IT Context
ISO 45001 Occupational Health and Safety Management System
Odoo POS Development Services by CandidRoot Solutions

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 !