SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practicesScott Hurrey
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopSecure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopPaul Ionescu
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTINGNETWORK PENETRATION TESTING
NETWORK PENETRATION TESTINGEr Vivek Rana
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application SecurityRob Ragan
 
Introduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingIntroduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingAnurag Srivastava
 
Thick Client Penetration Testing.pdf
Thick Client Penetration Testing.pdfThick Client Penetration Testing.pdf
Thick Client Penetration Testing.pdfSouvikRoy114738
 
Application Security
Application SecurityApplication Security
Application Securityflorinc
 
CNIT 129S: Ch 6: Attacking Authentication
CNIT 129S: Ch 6: Attacking AuthenticationCNIT 129S: Ch 6: Attacking Authentication
CNIT 129S: Ch 6: Attacking AuthenticationSam Bowne
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on itWSO2
 
Mobile Application Penetration Testing
Mobile Application Penetration TestingMobile Application Penetration Testing
Mobile Application Penetration TestingBGA Cyber Security
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionVishal Kumar
 
Footprinting and reconnaissance
Footprinting and reconnaissanceFootprinting and reconnaissance
Footprinting and reconnaissanceNishaYadav177
 
Malware Static Analysis
Malware Static AnalysisMalware Static Analysis
Malware Static AnalysisHossein Yavari
 
Vulnerability assessment and penetration testing
Vulnerability assessment and penetration testingVulnerability assessment and penetration testing
Vulnerability assessment and penetration testingAbu Sadat Mohammed Yasin
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and AwarenessAbdul Rahman Sherzad
 

Mais procurados (20)

Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopSecure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa Workshop
 
NETWORK PENETRATION TESTING
NETWORK PENETRATION TESTINGNETWORK PENETRATION TESTING
NETWORK PENETRATION TESTING
 
Security testing
Security testingSecurity testing
Security testing
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
 
Introduction to Web Application Penetration Testing
Introduction to Web Application Penetration TestingIntroduction to Web Application Penetration Testing
Introduction to Web Application Penetration Testing
 
A Threat Hunter Himself
A Threat Hunter HimselfA Threat Hunter Himself
A Threat Hunter Himself
 
Thick Client Penetration Testing.pdf
Thick Client Penetration Testing.pdfThick Client Penetration Testing.pdf
Thick Client Penetration Testing.pdf
 
Application Security
Application SecurityApplication Security
Application Security
 
CNIT 129S: Ch 6: Attacking Authentication
CNIT 129S: Ch 6: Attacking AuthenticationCNIT 129S: Ch 6: Attacking Authentication
CNIT 129S: Ch 6: Attacking Authentication
 
Application Security - Your Success Depends on it
Application Security - Your Success Depends on itApplication Security - Your Success Depends on it
Application Security - Your Success Depends on it
 
Mobile Application Penetration Testing
Mobile Application Penetration TestingMobile Application Penetration Testing
Mobile Application Penetration Testing
 
OWASP TOP 10 VULNERABILITIS
OWASP TOP 10 VULNERABILITISOWASP TOP 10 VULNERABILITIS
OWASP TOP 10 VULNERABILITIS
 
Threat Intelligence
Threat IntelligenceThreat Intelligence
Threat Intelligence
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL Injection
 
Footprinting and reconnaissance
Footprinting and reconnaissanceFootprinting and reconnaissance
Footprinting and reconnaissance
 
Malware Static Analysis
Malware Static AnalysisMalware Static Analysis
Malware Static Analysis
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Vulnerability assessment and penetration testing
Vulnerability assessment and penetration testingVulnerability assessment and penetration testing
Vulnerability assessment and penetration testing
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 

Semelhante a 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 version 2
OWASP_Top_Ten_Proactive_Controls version 2OWASP_Top_Ten_Proactive_Controls version 2
OWASP_Top_Ten_Proactive_Controls version 2ssuser18349f1
 
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
 

Semelhante a 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 version 2
OWASP_Top_Ten_Proactive_Controls version 2OWASP_Top_Ten_Proactive_Controls version 2
OWASP_Top_Ten_Proactive_Controls version 2
 
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
 

Último

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

Último (20)

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

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