SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
Secure Code? 
- Daniel Deogun, Omegapoint 
Twitter: @DanielDeogun 
Javaforum, Göteborg, 2014-09-18
About… 
• Daniel Deogun! 
• 10+ years in the industry! 
• Developed everything from patient critical software to 
high performant applications with Akka to various web-based 
systems ! 
• TDD, BDD, DDD Specialist! 
• Passionate about high quality code and security 
Manhattan, NY, USA 
Umeå 
Falun 
Stockholm 
Göteborg 
Kalmar 
Malmö
What’s Secure Code? 
• What does secure code look like?! 
! 
• Do we need to think about security all the 
time?
owasp top 10 (2013) 
A1 - Injection 
A2 - Broken Authentication and Session Management 
A3 - Cross-Site Scripting (XSS) 
A4 - Insecure Direct Object References 
A5 - Security Misconfiguration 
A6 - Sensitive Data Exposure 
A7 - Missing Function Level Access Control 
A8 - Cross-Site Request Forgery (CSRF) 
A9 - Using Components with Known Vulnerabilities 
A10 - Unvalidated Redirects and Forwards 
https://www.owasp.org/index.php/Top_10_2013-Top_10
owasp top 10 (2013) 
A1 - Injection 
A3 - Cross-Site Scripting (XSS) 
A4 - Insecure Direct Object References 
A6 - Sensitive Data Exposure 
https://www.owasp.org/index.php/Top_10_2013-Top_10
owasp top 10 (2013) 
A1 - Injection 
A3 - Cross-Site Scripting (XSS) 
A4 - Insecure Direct Object References 
A6 - Sensitive Data Exposure 
https://www.owasp.org/index.php/Top_10_2013-Top_10
A1 - Injection 
“Injection flaws, such as SQL, OS, and LDAP injection 
occur when untrusted data is sent to an interpreter as 
part of a command or query. The attacker’s hostile 
data can trick the interpreter into executing 
unintended commands or accessing data without 
proper authorization.” 
- OWASP top 10
Injection Flaws 
http://areino.com/blog/hackeando/
Example 
public void register(String name, String phoneNumber) {! 
! 
! ! //Do registration stuff! 
! 
}
Example 
public void register(String name, String phoneNumber) {! 
! 
! ! //Do registration stuff! 
! 
} 
A. register(“Daniel”, “Deogun”);! 
! 
! 
B. register(“+46707010101”, “Daniel”);! 
! 
! 
C. register(“Daniel”, “+46707010101”);
Add Some Defense 
public void register(String name, String phoneNumber) {! 
if(name == null || !name.trim().matches("[a-zA-Z]{3,20}")) {! 
throw new IllegalArgumentException("Bad name");! 
}! 
! 
if(phoneNumber == null || !phoneNumber.trim().matches("^[+][0-9]{11}")) {! 
throw new IllegalArgumentException("Bad phone number");! 
}! 
! 
//Do registration stuff ! 
} 
A. register(“Daniel”, “Deogun”);! 
! 
B. register(“+46707010101”, “Daniel”);! 
! 
C. register(“Daniel”, “+46707010101”);
Add Some Defense 
public void register(String name, String phoneNumber) {! 
if(name == null || !name.trim().matches("[a-zA-Z]{3,20}")) {! 
throw new IllegalArgumentException("Bad name");! 
}! 
! 
if(phoneNumber == null || !phoneNumber.trim().matches("^[+][0-9]{11}")) {! 
throw new IllegalArgumentException("Bad phone number");! 
}! 
! 
//Do registration stuff ! 
} 
A. register(“Daniel”, “Deogun”);! 
! 
B. register(“+46707010101”, “Daniel”);! 
! 
C. register(“Daniel”, “+46707010101”);
Map Input to 
Domain Objects 
public void register(Name name, PhoneNumber number) {! 
! 
! ! //Do registration stuff! 
! 
} 
register(new Name(“Daniel”), new PhoneNumber(“+46707010101”));
Value Object with 
Restrictions 
public class Name {! 
private final String value;! 
! 
public Name(final String value) {! 
notNull(value);! 
satisfies(value.trim().matches("[a-zA-Z]{3,20}"));! 
! 
this.value = value.trim();! 
}! 
! 
…
Prepared Statements 
• What about prepared statements?! 
! 
• Do we still need them?
Evil Tests 
http://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Emblem-evil-computer.svg/500px-Emblem-evil-computer.svg.png
@Test! 
public void should_have_X_frame_options_header_set_to_DENY() {! 
assertTrue(headerIsSetTo("X-Frame-Options", "DENY", ! 
! ! ! ! ! ! ! ! restTemplate.getForEntity(url, String.class)));! 
}! 
! 
@Test! 
public void should_have_xss_protection_header_defined() {! 
assertTrue(headerIsSetTo("X-XSS-Protection", "1; mode=block", ! 
! ! ! ! ! ! ! ! restTemplate.getForEntity(url, String.class)));! 
}! 
! 
... 
Testing HTTP Headers
@RunWith(Theories.class)! 
public class NameTest {! 
private interface IllegalName {String value();}! 
! 
! @DataPoints! 
public static IllegalName[] illegalInput() {! 
return new IllegalName[]{! 
() -> null,! 
() -> "",! 
() -> " ",! 
() -> "A",! 
() -> "AA",! 
() -> " AA ",! 
() -> "1234567890",! 
() -> "TwentyOneCharactersXX",! 
() -> "<script>alert('42')</script>",! 
() -> "' or '1'='1"! 
};! 
}! 
! 
@Rule! 
public ExpectedException exception = ExpectedException.none();! 
! 
@Theory! 
public void should_be_illegal(final IllegalName illegal) {! 
exception.expect(IllegalArgumentException.class);! 
! 
new Name(illegal.value());! 
}
A3 - Cross-Site 
Scripting (XSS) 
“XSS flaws occur whenever an application takes 
untrusted data and sends it to a web browser 
without proper validation or escaping. XSS allows 
attackers to execute scripts in the victim’s browser 
which can hijack user sessions, deface web sites, 
or redirect the user to malicious sites.” 
! 
- OWASP top 10
Example - 
Coder’s Blogg… 
• Let’s say we’re running a website where 
anyone can ask questions about code! 
! 
• Is it possible to avoid XSS?
Stored XSS 
<script>alert(’42’)</script> Browser
Stored XSS & 
Broken Context Mapping 
<script>alert(’42’)</script> 
Browser 
Write Context Read Context
Cyclomatic Complexity 
• 1976 publicerade Thomas J. McCabe “A 
Complexity Measure” i IEEE Transactions 
on Software Engineering, Vol. SE-2 No. 4! 
! 
• A measurement of the number of linearly 
independent paths through a 
program's source code.
Cyclomatic Complexity 
public boolean isPositive(final int value) { 
if (value > -1) { 
return true; 
} 
return false; 
} 
cyclomatic complexity =
Cyclomatic Complexity 
public boolean isPositive(final int value) { 
if (value > -1) { 
return true; 
} 
return false; 
} 
cyclomatic complexity = 2
Cyclomatic Complexity 
public boolean isPositive(final int value) { 
return value > -1; 
} 
cyclomatic complexity =
Cyclomatic Complexity 
public boolean isPositive(final int value) { 
return value > -1; 
} 
cyclomatic complexity = 
1
public void reserveRoomFor(String meeting, String owner, String roomName, ! 
! ! ! ! ! ! ! Calendar start, Calendar end, String... invitees) {! 
! 
final List<Booking> bookings = repository.getBookingsFor(roomName);! 
! 
if(bookings != null && !bookings.isEmpty()) { //To make it faster! 
for(Booking booking : bookings) {! 
if(booking.collidesWith(new Booking(start, end, meeting, roomName, owner))) {! 
throw new AlreadyReservedException(start, end, roomName, meeting, owner);! 
}! 
}! 
}! 
! 
repository.store(new Booking(start, end, meeting, roomName, owner));! 
! 
if(dispatcher == null) {! 
dispatcher = Platform.instance().eventDispatcher();! 
}! 
! 
dispatcher.notify(invitees, new Booking(start, end, meeting, roomName, owner));! 
} 
Cyclomatic Complexity
Cyclomatic Complexity 
public void reserveRoomFor(final Meeting meeting, final Room room) {! 
notNull(meeting);! 
notNull(room);! 
! 
repository.store(booking(meeting, room));! 
! 
dispatcher.notify(meeting.invitees, booking(meeting, room));! 
}! 
! 
private Booking booking(final Meeting meeting, final Room room) {! 
return new Booking(meeting, room);! 
}
A4 - Insecure Direct 
Object References 
“A direct object reference occurs when a developer 
exposes a reference to an internal implementation 
object, such as a file, directory, or database key. 
Without an access control check or other protection, 
attackers can manipulate these references to access 
unauthorized data.” 
- OWASP top 10
A6 - Sensitive Data 
Exposure 
“Many web applications do not properly protect 
sensitive data, such as credit cards, tax IDs, and 
authentication credentials. Attackers may steal or 
modify such weakly protected data to conduct credit 
card fraud, identity theft, or other crimes. Sensitive data 
deserves extra protection such as encryption at rest 
or in transit, as well as special precautions when 
exchanged with the browser.” 
- OWASP top 10
Logging 
• The logs are just another view of the system! 
! 
• One needs to design and pay careful attention 
to what data that’s placed in the logs! 
! 
• Access control of logs is extremely important
Code only used by tests 
public class AccountRepository {! 
private Map<AccountNumber, List<Account>> userAccounts = new HashMap<>();! 
! 
public void register(final Account account) {! 
notNull(account);! 
! 
if(!userAccounts.containsKey(account.number())) {! 
userAccounts.put(account.number(), new ArrayList<>());! 
}! 
userAccounts.get(account.number()).add(account);! 
}! 
! 
public Map<AccountNumber, List<Account>> userAccounts() {! 
return userAccounts;! 
}
Stack trace 
java.sql.SQLException: Closed Connectionat oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) 
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146) 
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208) 
at oracle.jdbc.driver.PhysicalConnection.rollback(PhysicalConnection.java:1170) 
at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.rollback(DelegatingConnection.java:368) 
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.rollback(PoolingDataSource.java:323) 
at net.sf.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:86) 
at org.springframework.orm.hibernate.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:529) 
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.753) 
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.
Hide it 
! 
Well, that’s embarrassing! 
We seem to have made an error …
Legacy Code
Legacy Code 
Extract module
Legacy Code 
Design by contract 
Extract module
Legacy Code 
Design by contract 
Map input to domain objects Extract module
Legacy Code 
Dependency injection 
Design by contract 
Map input to domain objects Extract module
Legacy Code 
Dependency injection 
Design by contract 
Map input to domain objects 
Extract module 
Remove defensive code constructs
Legacy Code 
Dependency injection 
Remove code only used by tests 
Design by contract 
Map input to domain objects 
Extract module 
Remove defensive code constructs
Key take Aways 
• Developers cannot think about security all the time! 
! 
• Good design principles will help one to avoid many 
security issues! 
! 
• There is no such thing as just a string (Dr. John Wilander)! 
! 
• Validate input and map everything to domain objects
Thanks 
Twitter: @DanielDeogun

Weitere ähnliche Inhalte

Was ist angesagt?

OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewMichael Furman
 
OWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideOWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideLudovic Petit
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applicationsNiyas Nazar
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101Paul Ionescu
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionMikhail Egorov
 
OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesSoftware Guru
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...Lenur Dzhemiliev
 
OWASP API Security Top 10 Examples
OWASP API Security Top 10 ExamplesOWASP API Security Top 10 Examples
OWASP API Security Top 10 Examples42Crunch
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing TechniquesAvinash Thapa
 

Was ist angesagt? (20)

OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
OWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideOWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference Guide
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101
 
Neat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protectionNeat tricks to bypass CSRF-protection
Neat tricks to bypass CSRF-protection
 
OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application Vulnerabilities
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
OWASP Top 10 Vulnerabilities - A5-Broken Access Control; A6-Security Misconfi...
 
SQL injection
SQL injectionSQL injection
SQL injection
 
OWASP API Security Top 10 Examples
OWASP API Security Top 10 ExamplesOWASP API Security Top 10 Examples
OWASP API Security Top 10 Examples
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
OWASP TOP 10 VULNERABILITIS
OWASP TOP 10 VULNERABILITISOWASP TOP 10 VULNERABILITIS
OWASP TOP 10 VULNERABILITIS
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: InjectionOwasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
 
Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
Sql injection
Sql injectionSql injection
Sql injection
 

Ähnlich wie Secure code

Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programmingAnte Gulam
 
Secure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsSecure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsBallerina
 
Secure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSecure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSebastien Gioria
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Jim Manico
 
Protecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksProtecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksKevin Alcock
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Penetration Testing with Improved Input Vector Identification
Penetration Testing with Improved Input Vector IdentificationPenetration Testing with Improved Input Vector Identification
Penetration Testing with Improved Input Vector IdentificationShauvik Roy Choudhary, Ph.D.
 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxOWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxnmk42194
 
Designing software with security in mind
Designing software with security in mindDesigning software with security in mind
Designing software with security in mindOmegapoint Academy
 
Designing software with security in mind?
Designing software with security in mind?Designing software with security in mind?
Designing software with security in mind?Omegapoint Academy
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsIvan Novikov
 
Fighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsFighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsddeogun
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxcgt38842
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxjohnpragasam1
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxazida3
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net ProgrammingAdam Getchell
 
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesSecurity Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesLionel Briand
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with RealmChristian Melchior
 

Ähnlich wie Secure code (20)

Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programming
 
Secure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsSecure by Design Microservices & Integrations
Secure by Design Microservices & Integrations
 
Secure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSecure Coding For Java - Une introduction
Secure Coding For Java - Une introduction
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
 
Protecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacksProtecting your data from SQL Injection attacks
Protecting your data from SQL Injection attacks
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Penetration Testing with Improved Input Vector Identification
Penetration Testing with Improved Input Vector IdentificationPenetration Testing with Improved Input Vector Identification
Penetration Testing with Improved Input Vector Identification
 
Spa Secure Coding Guide
Spa Secure Coding GuideSpa Secure Coding Guide
Spa Secure Coding Guide
 
OWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptxOWASP_Top_Ten_Proactive_Controls_v32.pptx
OWASP_Top_Ten_Proactive_Controls_v32.pptx
 
Designing software with security in mind
Designing software with security in mindDesigning software with security in mind
Designing software with security in mind
 
Designing software with security in mind?
Designing software with security in mind?Designing software with security in mind?
Designing software with security in mind?
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
Fighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsFighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsets
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
OWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptxOWASP_Top_Ten_Proactive_Controls_v2.pptx
OWASP_Top_Ten_Proactive_Controls_v2.pptx
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net Programming
 
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection VulnerabilitiesSecurity Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
Security Slicing for Auditing XML, XPath, and SQL Injection Vulnerabilities
 
Painless Persistence with Realm
Painless Persistence with RealmPainless Persistence with Realm
Painless Persistence with Realm
 

Kürzlich hochgeladen

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Kürzlich hochgeladen (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Secure code

  • 1. Secure Code? - Daniel Deogun, Omegapoint Twitter: @DanielDeogun Javaforum, Göteborg, 2014-09-18
  • 2. About… • Daniel Deogun! • 10+ years in the industry! • Developed everything from patient critical software to high performant applications with Akka to various web-based systems ! • TDD, BDD, DDD Specialist! • Passionate about high quality code and security Manhattan, NY, USA Umeå Falun Stockholm Göteborg Kalmar Malmö
  • 3. What’s Secure Code? • What does secure code look like?! ! • Do we need to think about security all the time?
  • 4. owasp top 10 (2013) A1 - Injection A2 - Broken Authentication and Session Management A3 - Cross-Site Scripting (XSS) A4 - Insecure Direct Object References A5 - Security Misconfiguration A6 - Sensitive Data Exposure A7 - Missing Function Level Access Control A8 - Cross-Site Request Forgery (CSRF) A9 - Using Components with Known Vulnerabilities A10 - Unvalidated Redirects and Forwards https://www.owasp.org/index.php/Top_10_2013-Top_10
  • 5. owasp top 10 (2013) A1 - Injection A3 - Cross-Site Scripting (XSS) A4 - Insecure Direct Object References A6 - Sensitive Data Exposure https://www.owasp.org/index.php/Top_10_2013-Top_10
  • 6. owasp top 10 (2013) A1 - Injection A3 - Cross-Site Scripting (XSS) A4 - Insecure Direct Object References A6 - Sensitive Data Exposure https://www.owasp.org/index.php/Top_10_2013-Top_10
  • 7. A1 - Injection “Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.” - OWASP top 10
  • 9. Example public void register(String name, String phoneNumber) {! ! ! ! //Do registration stuff! ! }
  • 10. Example public void register(String name, String phoneNumber) {! ! ! ! //Do registration stuff! ! } A. register(“Daniel”, “Deogun”);! ! ! B. register(“+46707010101”, “Daniel”);! ! ! C. register(“Daniel”, “+46707010101”);
  • 11. Add Some Defense public void register(String name, String phoneNumber) {! if(name == null || !name.trim().matches("[a-zA-Z]{3,20}")) {! throw new IllegalArgumentException("Bad name");! }! ! if(phoneNumber == null || !phoneNumber.trim().matches("^[+][0-9]{11}")) {! throw new IllegalArgumentException("Bad phone number");! }! ! //Do registration stuff ! } A. register(“Daniel”, “Deogun”);! ! B. register(“+46707010101”, “Daniel”);! ! C. register(“Daniel”, “+46707010101”);
  • 12. Add Some Defense public void register(String name, String phoneNumber) {! if(name == null || !name.trim().matches("[a-zA-Z]{3,20}")) {! throw new IllegalArgumentException("Bad name");! }! ! if(phoneNumber == null || !phoneNumber.trim().matches("^[+][0-9]{11}")) {! throw new IllegalArgumentException("Bad phone number");! }! ! //Do registration stuff ! } A. register(“Daniel”, “Deogun”);! ! B. register(“+46707010101”, “Daniel”);! ! C. register(“Daniel”, “+46707010101”);
  • 13. Map Input to Domain Objects public void register(Name name, PhoneNumber number) {! ! ! ! //Do registration stuff! ! } register(new Name(“Daniel”), new PhoneNumber(“+46707010101”));
  • 14. Value Object with Restrictions public class Name {! private final String value;! ! public Name(final String value) {! notNull(value);! satisfies(value.trim().matches("[a-zA-Z]{3,20}"));! ! this.value = value.trim();! }! ! …
  • 15. Prepared Statements • What about prepared statements?! ! • Do we still need them?
  • 17. @Test! public void should_have_X_frame_options_header_set_to_DENY() {! assertTrue(headerIsSetTo("X-Frame-Options", "DENY", ! ! ! ! ! ! ! ! ! restTemplate.getForEntity(url, String.class)));! }! ! @Test! public void should_have_xss_protection_header_defined() {! assertTrue(headerIsSetTo("X-XSS-Protection", "1; mode=block", ! ! ! ! ! ! ! ! ! restTemplate.getForEntity(url, String.class)));! }! ! ... Testing HTTP Headers
  • 18. @RunWith(Theories.class)! public class NameTest {! private interface IllegalName {String value();}! ! ! @DataPoints! public static IllegalName[] illegalInput() {! return new IllegalName[]{! () -> null,! () -> "",! () -> " ",! () -> "A",! () -> "AA",! () -> " AA ",! () -> "1234567890",! () -> "TwentyOneCharactersXX",! () -> "<script>alert('42')</script>",! () -> "' or '1'='1"! };! }! ! @Rule! public ExpectedException exception = ExpectedException.none();! ! @Theory! public void should_be_illegal(final IllegalName illegal) {! exception.expect(IllegalArgumentException.class);! ! new Name(illegal.value());! }
  • 19. A3 - Cross-Site Scripting (XSS) “XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.” ! - OWASP top 10
  • 20. Example - Coder’s Blogg… • Let’s say we’re running a website where anyone can ask questions about code! ! • Is it possible to avoid XSS?
  • 22. Stored XSS & Broken Context Mapping <script>alert(’42’)</script> Browser Write Context Read Context
  • 23. Cyclomatic Complexity • 1976 publicerade Thomas J. McCabe “A Complexity Measure” i IEEE Transactions on Software Engineering, Vol. SE-2 No. 4! ! • A measurement of the number of linearly independent paths through a program's source code.
  • 24. Cyclomatic Complexity public boolean isPositive(final int value) { if (value > -1) { return true; } return false; } cyclomatic complexity =
  • 25. Cyclomatic Complexity public boolean isPositive(final int value) { if (value > -1) { return true; } return false; } cyclomatic complexity = 2
  • 26. Cyclomatic Complexity public boolean isPositive(final int value) { return value > -1; } cyclomatic complexity =
  • 27. Cyclomatic Complexity public boolean isPositive(final int value) { return value > -1; } cyclomatic complexity = 1
  • 28. public void reserveRoomFor(String meeting, String owner, String roomName, ! ! ! ! ! ! ! ! Calendar start, Calendar end, String... invitees) {! ! final List<Booking> bookings = repository.getBookingsFor(roomName);! ! if(bookings != null && !bookings.isEmpty()) { //To make it faster! for(Booking booking : bookings) {! if(booking.collidesWith(new Booking(start, end, meeting, roomName, owner))) {! throw new AlreadyReservedException(start, end, roomName, meeting, owner);! }! }! }! ! repository.store(new Booking(start, end, meeting, roomName, owner));! ! if(dispatcher == null) {! dispatcher = Platform.instance().eventDispatcher();! }! ! dispatcher.notify(invitees, new Booking(start, end, meeting, roomName, owner));! } Cyclomatic Complexity
  • 29. Cyclomatic Complexity public void reserveRoomFor(final Meeting meeting, final Room room) {! notNull(meeting);! notNull(room);! ! repository.store(booking(meeting, room));! ! dispatcher.notify(meeting.invitees, booking(meeting, room));! }! ! private Booking booking(final Meeting meeting, final Room room) {! return new Booking(meeting, room);! }
  • 30. A4 - Insecure Direct Object References “A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.” - OWASP top 10
  • 31. A6 - Sensitive Data Exposure “Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.” - OWASP top 10
  • 32. Logging • The logs are just another view of the system! ! • One needs to design and pay careful attention to what data that’s placed in the logs! ! • Access control of logs is extremely important
  • 33. Code only used by tests public class AccountRepository {! private Map<AccountNumber, List<Account>> userAccounts = new HashMap<>();! ! public void register(final Account account) {! notNull(account);! ! if(!userAccounts.containsKey(account.number())) {! userAccounts.put(account.number(), new ArrayList<>());! }! userAccounts.get(account.number()).add(account);! }! ! public Map<AccountNumber, List<Account>> userAccounts() {! return userAccounts;! }
  • 34. Stack trace java.sql.SQLException: Closed Connectionat oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208) at oracle.jdbc.driver.PhysicalConnection.rollback(PhysicalConnection.java:1170) at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.rollback(DelegatingConnection.java:368) at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.rollback(PoolingDataSource.java:323) at net.sf.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:86) at org.springframework.orm.hibernate.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:529) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.753) at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.
  • 35. Hide it ! Well, that’s embarrassing! We seem to have made an error …
  • 38. Legacy Code Design by contract Extract module
  • 39. Legacy Code Design by contract Map input to domain objects Extract module
  • 40. Legacy Code Dependency injection Design by contract Map input to domain objects Extract module
  • 41. Legacy Code Dependency injection Design by contract Map input to domain objects Extract module Remove defensive code constructs
  • 42. Legacy Code Dependency injection Remove code only used by tests Design by contract Map input to domain objects Extract module Remove defensive code constructs
  • 43. Key take Aways • Developers cannot think about security all the time! ! • Good design principles will help one to avoid many security issues! ! • There is no such thing as just a string (Dr. John Wilander)! ! • Validate input and map everything to domain objects