SlideShare uma empresa Scribd logo
1 de 34
Something Died Inside Your Git Repo:
Recognizing the Smell of Insecure Code
Cliff Smith, Parameter Security
BSides Huntsville
February 4, 2017
Intro
• Ethical Hacker at Parameter Security in St. Louis, MO
• Co-lead of OWASP Saint Louis
• Programmer with 20+ years’ experience writing bad code (and
nonnegligible experience writing good code)
• Recovering lawyer
Code Smells and Refactoring
• “[Kent Beck and I] have learned
to look for certain structures in
the code that suggest
(sometimes they scream for) the
possibility of refactoring.”
Martin Fowler, Refactoring, p. 63
• Something is wrong and likely to
cause maintenance problems
• Poorly conceived design OR code
that has deviated from its
original design
Code Smells and Security
• Patterns in thought, code structure and application behavior
• Gaps in understanding of security OR bad habits that lead to mistakes
• Something is wrong and is likely to get breached:
• You chose the wrong approach, thereby making the problem harder than it is
• You probably don’t understand the problem, so you probably screwed it up
• You may have shown attackers the weak spots in your code
Code Smells and Security
https://xkcd.com/463/
Pen Test Story - Stored XSS
• Attack: <script>alert(‘XSS’)</script>
Pen Test Story - Stored XSS
• Attack: <script>alert(‘XSS’)</script>
• Fix: reject input containing <script
Pen Test Story - Stored XSS
• Attack: <script>alert(‘XSS’)</script>
• Fix: reject input containing <script
• Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” />
• Fix: reject input matching /<[a-zA-Z].*>/
Pen Test Story - Stored XSS
• Attack: <script>alert(‘XSS’)</script>
• Fix: reject input containing <script
• Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” />
• Fix: reject input matching /<[a-zA-Z].*>/
• Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” (simply omit the
closing bracket)
• Fix: reject input matching /<[a-zA-Z]+ / (space at end)
Pen Test Story - Stored XSS
• Attack: <script>alert(‘XSS’)</script>
• Fix: reject input containing <script
• Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” />
• Fix: reject input matching /<[a-zA-Z].*>/
• Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” (simply omit the
closing bracket)
• Fix: reject input matching /<[a-zA-Z]+ / (space at end)
• Attack: insert <img/onmouseover=“alert(‘XSS’)” (use a slash instead
of a space)
Cat-and-Mouse Games
• Bad guy breaks in, good guy designs a
narrow defense against the exact method
used by the bad guy
• Design your defenses based on the
vulnerability, not based on the attack
• Implement provably, theoretically correct
solutions
Another Stored XSS Example
<script type=“text/javascript”>
$.ready(function() {
Map.init(‘123 Main St.’);
});
</script>
Another Stored XSS Example
<script type=“text/javascript”>
$.ready(function() {
Map.init(‘123 Main St.’);
});
</script>
User data
interpolated
directly into code
– this is as bad as
eval()!
Another Stored XSS Example
<script type=“text/javascript”>
$.ready(function() {
$.get({ /* ... */,
function(response) {
Map.init(response.data);
});
});
</script>
<script type=“text/template”
id=“address”>
MTIzIE1haW4gU3Qu
</script>
<script type=“text/javascript”>
$.ready(function() {
var address =
$(‘#address’).text();
address = atob(address);
Map.init(address);
});
</script>Provably correct and safeWorks, but hurts performance
Church and State
Don’t mix the two!
Code Data
Church and State
• Separate data from code whenever possible (and it’s always possible)
• Use prepared SQL statements
• Use <script type=“text/template”> tags and base 64 encoding
• Never rely on rejecting bad input
• Escaping control characters is a last resort!
Still More Stored XSS Defenses...
• Existing application escaped < > “ with HTML entity encoding before
saving user data to database
• Today I watched &quot;The Pirates of Penzance&quot; by Gilbert &amp; Sullivan.
• Form elements changed from <input> to <textarea> and vice-versa
during page redesigns
• JavaScript replaces form elements with <span>s for printing
• $span.html($textarea.text())?
• $span.text($textarea.html())?
• Like an airport with all security checkpoints at the highway off-ramp
Solutions Decoupled from Problems
• Poor modularity; poor delineation of responsibilities
• Each component has to be aware of the needs of every other component!
• Injection attacks are presentation-layer problems, so solve them in
the presentation layer!
• Data integrity and model state should be enforced in the model
• Easier to maintain, harder to break
Junior’s First Database
• Single text file
• Entire contents rewritten to disk
on every save
• Save operations took about 30
seconds
• Zero concurrency
ENTRY
type=employee
id=1
firstname=John
ENTRY
type=timeentry
id=1
date=20030811
project_id=7
Junior’s First Database
• Single text file
• Entire contents rewritten to disk
on every save
• Save operations took about 30
seconds
• Zero concurrency
• MySQL was eight years old at
this point
ENTRY
type=employee
id=1
firstname=John
ENTRY
type=timeentry
id=1
date=20030811
project_id=7
Solving Important Problems From Scratch
• Important problems are (1) fundamental, (2) easy to get wrong, or (3)
likely to create a vulnerability if you get them wrong
• Or they leave you thinking, “Surely someone has done this before…”
• Stand on the shoulders of giants (or at least on stilts)
• Consider using a reliable, proven third-party solution
• Study the literature
• Examples:
• Parsing HTTP requests and responses
• Crypto and authentication
• OWASP Top 10
The Abstraction Trap
• Abstraction allows the application programmer to interact with an
object at a convenient level of complexity
• That level of complexity defines the object’s interface
• Implementation details are abstracted away
The Abstraction Trap
• Vulnerabilities can be hidden in the details we abstract away
• Examples:
• Plugin that can set the user’s session ID – session fixation
• Mobile applications that inadvertently cache HTTP responses
• RSA Chinese remainder theorem timing leak
• “Not my code” != “not my responsibility”
• Book up on APIs, libraries and other third-party code
• Look out for features you don’t need or don’t expect
• Subject matter knowledge and security expertise are important
Vulnerability in FOSS CMS
def list_users():
authorize_request()
users = User.find(…)
…
def save_user(id):
authorize_request()
user = User.find({‘id’:id})
…
def delete_user(id):
user = User.find({‘id’:id})
…
WET Code
• DRY = don’t repeat yourself
• WET = write everything twice
• WET code leaves you one forgetful moment away from a vulnerability
• DRY code is set it and forget it – solve problems once, not over and again
• TIMTOWTDI versus The Zen of Python
• Make the obvious solution the safe solution
Pen Test Story - Vulnerability in Commercial OSS
function validate_slug($slug) {
if (strpos($slug, ‘<‘) != FALSE || strpos($slug, ‘”’) != FALSE) {
return FALSE;
}
return TRUE;
}
/* … */
<script>
showImage(“<?php echo $slug; ?>”);
</script>
Pen Test Story - Vulnerability in Commercial OSS
function validate_slug($slug) {
if (strpos($slug, ‘<‘) != FALSE || strpos($slug, ‘”’) != FALSE) {
return FALSE;
}
return TRUE;
}
/* … */
<script>
showImage(“<?php echo $slug; ?>”);
</script>
Code Secured by a Single Set of Eyes
• Mistakes happen, but mistakes like this should be caught
• This issue could have been caught with:
• PHPLint
• BurpSuite Scanner, nikto, WebScarab, any other vulnerability scanner or fuzzer
• Unit testing
• Manual code review
• Every organization should have some process in place
Pen Test Story – Mobile Application
GET /account/details?account_number=111111111
HTTP/1.1 200 OK {“message”:”success”,“ssn”:”123-45-6789”}
GET /account/details?account_number=222222222
HTTP/1.1 404 Not Found {“message”:”Invalid account number.”}
GET /account/details?account_number=333333333
HTTP/1.1 403 Access Denied {“message”:”Access violation.”}
Pen Test Story – Mobile Application
POST /account/reticulateSplines {“foo”:”bar”}
HTTP/1.1 200 OK {“message”:”success”}
POST /account/reticulateSplines {“foo”:”</bar>”}
HTTP/1.1 500 Internal Server Error {“message”:”Uncaught exception in
java.xml.parsers.documentbuilder: unexpected closing tag </bar>; expected
</ACCOUNT_OPERATION> at line 3, colum 94.
Stack trace:
…”}
Mind the Information Gap
• Client and server are on a mutual need-to-know basis
• The server should never tell the client something it doesn’t need to know
• Leakage of sensitive information
• Giving the attacker a roadmap
• The client should never tell the server something it already knows
• Access control errors
• Limit detail in error messages
• The fact of the error; how to fix it; how to get help
• Interpreter error messages are for developers, not users
• The client is untrusted!
Summary
• Cat-and-mouse games
• Church and state
• Solutions decoupled from problems
• Solving important problems from scratch
• The abstraction trap
• WET code
• Code secured by a single set of eyes
• Mind the information gap
Final Thoughts
• Understand the conceptual root of each type of vulnerability
• Safe handling of user data is a major source of vulnerabilities
• All exploits run on information, assumptions and trust
• Information should be carefully controlled and rationed
• Identify and manage assumptions
• Don’t be afraid to Google simple questions
• Study the specs
• Programming is an art and a science
• Good code is secure code
Questions?
cliff.smith@parametersecurity.com
@BismthSalamandr

Mais conteúdo relacionado

Mais procurados

BSides Columbus - Lend me your IR's!
BSides Columbus - Lend me your IR's!BSides Columbus - Lend me your IR's!
BSides Columbus - Lend me your IR's!
ThreatReel Podcast
 
The Ultimate IDS Smackdown
The Ultimate IDS SmackdownThe Ultimate IDS Smackdown
The Ultimate IDS Smackdown
Mario Heiderich
 
Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
beched
 
The Future of Web Attacks - CONFidence 2010
The Future of Web Attacks - CONFidence 2010The Future of Web Attacks - CONFidence 2010
The Future of Web Attacks - CONFidence 2010
Mario Heiderich
 

Mais procurados (14)

BSides Columbus - Lend me your IR's!
BSides Columbus - Lend me your IR's!BSides Columbus - Lend me your IR's!
BSides Columbus - Lend me your IR's!
 
The Ultimate IDS Smackdown
The Ultimate IDS SmackdownThe Ultimate IDS Smackdown
The Ultimate IDS Smackdown
 
Vulnerabilities in data processing levels
Vulnerabilities in data processing levelsVulnerabilities in data processing levels
Vulnerabilities in data processing levels
 
The Future of Web Attacks - CONFidence 2010
The Future of Web Attacks - CONFidence 2010The Future of Web Attacks - CONFidence 2010
The Future of Web Attacks - CONFidence 2010
 
Introduction to web security @ confess 2012
Introduction to web security @ confess 2012Introduction to web security @ confess 2012
Introduction to web security @ confess 2012
 
Web Security 101
Web Security 101Web Security 101
Web Security 101
 
DMA - Stupid Cyber Criminal Tricks
DMA - Stupid Cyber Criminal TricksDMA - Stupid Cyber Criminal Tricks
DMA - Stupid Cyber Criminal Tricks
 
Intro to Pentesting Jenkins
Intro to Pentesting JenkinsIntro to Pentesting Jenkins
Intro to Pentesting Jenkins
 
The art of android hacking
The art of  android hackingThe art of  android hacking
The art of android hacking
 
A XSSmas carol
A XSSmas carolA XSSmas carol
A XSSmas carol
 
Ruxmon cve 2012-2661
Ruxmon cve 2012-2661Ruxmon cve 2012-2661
Ruxmon cve 2012-2661
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
Biting into the forbidden fruit. Lessons from trusting Javascript crypto.Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
 
Pentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerPentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A Primer
 

Destaque

How would my magazine be advertised ?
How would my magazine be advertised ?How would my magazine be advertised ?
How would my magazine be advertised ?
Emily Popple
 
De la démarche d’investigation à la démarche de projet
De la démarche d’investigation  à la démarche de projetDe la démarche d’investigation  à la démarche de projet
De la démarche d’investigation à la démarche de projet
Philippe_Jeanjacquot
 

Destaque (18)

Györfi András Media Hack - Csongrád Megyei Kereskedelmi és Iparkamara SZEGED
Györfi András Media Hack - Csongrád Megyei Kereskedelmi és Iparkamara SZEGEDGyörfi András Media Hack - Csongrád Megyei Kereskedelmi és Iparkamara SZEGED
Györfi András Media Hack - Csongrád Megyei Kereskedelmi és Iparkamara SZEGED
 
Εισαγωγή στις αρχές της επιστήμης των ΗΥ κεφ 2 2 4
Εισαγωγή στις αρχές της επιστήμης των ΗΥ κεφ 2 2 4Εισαγωγή στις αρχές της επιστήμης των ΗΥ κεφ 2 2 4
Εισαγωγή στις αρχές της επιστήμης των ΗΥ κεφ 2 2 4
 
Fotos von der agosense.CONNECT 2017
Fotos von der agosense.CONNECT 2017Fotos von der agosense.CONNECT 2017
Fotos von der agosense.CONNECT 2017
 
Tp Utilisation De Stellarium.
Tp Utilisation De Stellarium.Tp Utilisation De Stellarium.
Tp Utilisation De Stellarium.
 
Communication skills by mazhar ali
Communication skills by mazhar aliCommunication skills by mazhar ali
Communication skills by mazhar ali
 
Textual Analysis
Textual Analysis Textual Analysis
Textual Analysis
 
C e0511
C e0511C e0511
C e0511
 
Los medios de comunicaciòn
Los medios de comunicaciònLos medios de comunicaciòn
Los medios de comunicaciòn
 
P2 S Eleves Trevoux2
P2 S Eleves Trevoux2P2 S Eleves Trevoux2
P2 S Eleves Trevoux2
 
How would my magazine be advertised ?
How would my magazine be advertised ?How would my magazine be advertised ?
How would my magazine be advertised ?
 
Como crear una cuenta en Twitter (taller de Twitter para principiantes)
Como crear una cuenta en Twitter (taller de Twitter para principiantes)Como crear una cuenta en Twitter (taller de Twitter para principiantes)
Como crear una cuenta en Twitter (taller de Twitter para principiantes)
 
IMPORT FROM TURKEY
IMPORT FROM TURKEYIMPORT FROM TURKEY
IMPORT FROM TURKEY
 
Grupo 1
Grupo 1Grupo 1
Grupo 1
 
2 2 Understanding Food Additives
2 2 Understanding Food Additives2 2 Understanding Food Additives
2 2 Understanding Food Additives
 
De la démarche d’investigation à la démarche de projet
De la démarche d’investigation  à la démarche de projetDe la démarche d’investigation  à la démarche de projet
De la démarche d’investigation à la démarche de projet
 
Inmaculada Concepción de MaríA (Cmp)
Inmaculada Concepción  de MaríA (Cmp)Inmaculada Concepción  de MaríA (Cmp)
Inmaculada Concepción de MaríA (Cmp)
 
2016 office condo report
2016 office condo report2016 office condo report
2016 office condo report
 
NYC Data Driven Business Meetup - 2.7.17
NYC Data Driven Business Meetup - 2.7.17NYC Data Driven Business Meetup - 2.7.17
NYC Data Driven Business Meetup - 2.7.17
 

Semelhante a Something Died Inside Your Git Repo

OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADFOWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
Brian Huff
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
drewz lin
 

Semelhante a Something Died Inside Your Git Repo (20)

Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101
 
Devbeat Conference - Developer First Security
Devbeat Conference - Developer First SecurityDevbeat Conference - Developer First Security
Devbeat Conference - Developer First Security
 
CQRS / ES & DDD Demystified
CQRS / ES & DDD DemystifiedCQRS / ES & DDD Demystified
CQRS / ES & DDD Demystified
 
null Bangalore meet - Php Security
null Bangalore meet - Php Securitynull Bangalore meet - Php Security
null Bangalore meet - Php Security
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
PHPUG Presentation
PHPUG PresentationPHPUG Presentation
PHPUG Presentation
 
Top Ten Web Application Defenses v12
Top Ten Web Application Defenses v12Top Ten Web Application Defenses v12
Top Ten Web Application Defenses v12
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADFOWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
OWASP Top 10 Security Vulnerabilities, and Securing them with Oracle ADF
 
Hackers vs developers
Hackers vs developersHackers vs developers
Hackers vs developers
 
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
 
Secure Software: Action, Comedy or Drama? (2017 edition)
Secure Software: Action, Comedy or Drama? (2017 edition)Secure Software: Action, Comedy or Drama? (2017 edition)
Secure Software: Action, Comedy or Drama? (2017 edition)
 
Grails vs XSS: Defending Grails against XSS attacks
Grails vs XSS: Defending Grails against XSS attacksGrails vs XSS: Defending Grails against XSS attacks
Grails vs XSS: Defending Grails against XSS attacks
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript Applications
 
Secure WordPress Development Practices
Secure WordPress Development PracticesSecure WordPress Development Practices
Secure WordPress Development Practices
 
Introduction to threat_modeling
Introduction to threat_modelingIntroduction to threat_modeling
Introduction to threat_modeling
 
Appsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaolaAppsec usa2013 js_libinsecurity_stefanodipaola
Appsec usa2013 js_libinsecurity_stefanodipaola
 
How to Destroy a Database
How to Destroy a DatabaseHow to Destroy a Database
How to Destroy a Database
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

Something Died Inside Your Git Repo

  • 1. Something Died Inside Your Git Repo: Recognizing the Smell of Insecure Code Cliff Smith, Parameter Security BSides Huntsville February 4, 2017
  • 2. Intro • Ethical Hacker at Parameter Security in St. Louis, MO • Co-lead of OWASP Saint Louis • Programmer with 20+ years’ experience writing bad code (and nonnegligible experience writing good code) • Recovering lawyer
  • 3. Code Smells and Refactoring • “[Kent Beck and I] have learned to look for certain structures in the code that suggest (sometimes they scream for) the possibility of refactoring.” Martin Fowler, Refactoring, p. 63 • Something is wrong and likely to cause maintenance problems • Poorly conceived design OR code that has deviated from its original design
  • 4. Code Smells and Security • Patterns in thought, code structure and application behavior • Gaps in understanding of security OR bad habits that lead to mistakes • Something is wrong and is likely to get breached: • You chose the wrong approach, thereby making the problem harder than it is • You probably don’t understand the problem, so you probably screwed it up • You may have shown attackers the weak spots in your code
  • 5. Code Smells and Security https://xkcd.com/463/
  • 6. Pen Test Story - Stored XSS • Attack: <script>alert(‘XSS’)</script>
  • 7. Pen Test Story - Stored XSS • Attack: <script>alert(‘XSS’)</script> • Fix: reject input containing <script
  • 8. Pen Test Story - Stored XSS • Attack: <script>alert(‘XSS’)</script> • Fix: reject input containing <script • Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” /> • Fix: reject input matching /<[a-zA-Z].*>/
  • 9. Pen Test Story - Stored XSS • Attack: <script>alert(‘XSS’)</script> • Fix: reject input containing <script • Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” /> • Fix: reject input matching /<[a-zA-Z].*>/ • Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” (simply omit the closing bracket) • Fix: reject input matching /<[a-zA-Z]+ / (space at end)
  • 10. Pen Test Story - Stored XSS • Attack: <script>alert(‘XSS’)</script> • Fix: reject input containing <script • Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” /> • Fix: reject input matching /<[a-zA-Z].*>/ • Attack: <img onerror=“alert(‘XSS’)” src=“error.jpg” (simply omit the closing bracket) • Fix: reject input matching /<[a-zA-Z]+ / (space at end) • Attack: insert <img/onmouseover=“alert(‘XSS’)” (use a slash instead of a space)
  • 11. Cat-and-Mouse Games • Bad guy breaks in, good guy designs a narrow defense against the exact method used by the bad guy • Design your defenses based on the vulnerability, not based on the attack • Implement provably, theoretically correct solutions
  • 12. Another Stored XSS Example <script type=“text/javascript”> $.ready(function() { Map.init(‘123 Main St.’); }); </script>
  • 13. Another Stored XSS Example <script type=“text/javascript”> $.ready(function() { Map.init(‘123 Main St.’); }); </script> User data interpolated directly into code – this is as bad as eval()!
  • 14. Another Stored XSS Example <script type=“text/javascript”> $.ready(function() { $.get({ /* ... */, function(response) { Map.init(response.data); }); }); </script> <script type=“text/template” id=“address”> MTIzIE1haW4gU3Qu </script> <script type=“text/javascript”> $.ready(function() { var address = $(‘#address’).text(); address = atob(address); Map.init(address); }); </script>Provably correct and safeWorks, but hurts performance
  • 15. Church and State Don’t mix the two! Code Data
  • 16. Church and State • Separate data from code whenever possible (and it’s always possible) • Use prepared SQL statements • Use <script type=“text/template”> tags and base 64 encoding • Never rely on rejecting bad input • Escaping control characters is a last resort!
  • 17. Still More Stored XSS Defenses... • Existing application escaped < > “ with HTML entity encoding before saving user data to database • Today I watched &quot;The Pirates of Penzance&quot; by Gilbert &amp; Sullivan. • Form elements changed from <input> to <textarea> and vice-versa during page redesigns • JavaScript replaces form elements with <span>s for printing • $span.html($textarea.text())? • $span.text($textarea.html())? • Like an airport with all security checkpoints at the highway off-ramp
  • 18. Solutions Decoupled from Problems • Poor modularity; poor delineation of responsibilities • Each component has to be aware of the needs of every other component! • Injection attacks are presentation-layer problems, so solve them in the presentation layer! • Data integrity and model state should be enforced in the model • Easier to maintain, harder to break
  • 19. Junior’s First Database • Single text file • Entire contents rewritten to disk on every save • Save operations took about 30 seconds • Zero concurrency ENTRY type=employee id=1 firstname=John ENTRY type=timeentry id=1 date=20030811 project_id=7
  • 20. Junior’s First Database • Single text file • Entire contents rewritten to disk on every save • Save operations took about 30 seconds • Zero concurrency • MySQL was eight years old at this point ENTRY type=employee id=1 firstname=John ENTRY type=timeentry id=1 date=20030811 project_id=7
  • 21. Solving Important Problems From Scratch • Important problems are (1) fundamental, (2) easy to get wrong, or (3) likely to create a vulnerability if you get them wrong • Or they leave you thinking, “Surely someone has done this before…” • Stand on the shoulders of giants (or at least on stilts) • Consider using a reliable, proven third-party solution • Study the literature • Examples: • Parsing HTTP requests and responses • Crypto and authentication • OWASP Top 10
  • 22. The Abstraction Trap • Abstraction allows the application programmer to interact with an object at a convenient level of complexity • That level of complexity defines the object’s interface • Implementation details are abstracted away
  • 23. The Abstraction Trap • Vulnerabilities can be hidden in the details we abstract away • Examples: • Plugin that can set the user’s session ID – session fixation • Mobile applications that inadvertently cache HTTP responses • RSA Chinese remainder theorem timing leak • “Not my code” != “not my responsibility” • Book up on APIs, libraries and other third-party code • Look out for features you don’t need or don’t expect • Subject matter knowledge and security expertise are important
  • 24. Vulnerability in FOSS CMS def list_users(): authorize_request() users = User.find(…) … def save_user(id): authorize_request() user = User.find({‘id’:id}) … def delete_user(id): user = User.find({‘id’:id}) …
  • 25. WET Code • DRY = don’t repeat yourself • WET = write everything twice • WET code leaves you one forgetful moment away from a vulnerability • DRY code is set it and forget it – solve problems once, not over and again • TIMTOWTDI versus The Zen of Python • Make the obvious solution the safe solution
  • 26. Pen Test Story - Vulnerability in Commercial OSS function validate_slug($slug) { if (strpos($slug, ‘<‘) != FALSE || strpos($slug, ‘”’) != FALSE) { return FALSE; } return TRUE; } /* … */ <script> showImage(“<?php echo $slug; ?>”); </script>
  • 27. Pen Test Story - Vulnerability in Commercial OSS function validate_slug($slug) { if (strpos($slug, ‘<‘) != FALSE || strpos($slug, ‘”’) != FALSE) { return FALSE; } return TRUE; } /* … */ <script> showImage(“<?php echo $slug; ?>”); </script>
  • 28. Code Secured by a Single Set of Eyes • Mistakes happen, but mistakes like this should be caught • This issue could have been caught with: • PHPLint • BurpSuite Scanner, nikto, WebScarab, any other vulnerability scanner or fuzzer • Unit testing • Manual code review • Every organization should have some process in place
  • 29. Pen Test Story – Mobile Application GET /account/details?account_number=111111111 HTTP/1.1 200 OK {“message”:”success”,“ssn”:”123-45-6789”} GET /account/details?account_number=222222222 HTTP/1.1 404 Not Found {“message”:”Invalid account number.”} GET /account/details?account_number=333333333 HTTP/1.1 403 Access Denied {“message”:”Access violation.”}
  • 30. Pen Test Story – Mobile Application POST /account/reticulateSplines {“foo”:”bar”} HTTP/1.1 200 OK {“message”:”success”} POST /account/reticulateSplines {“foo”:”</bar>”} HTTP/1.1 500 Internal Server Error {“message”:”Uncaught exception in java.xml.parsers.documentbuilder: unexpected closing tag </bar>; expected </ACCOUNT_OPERATION> at line 3, colum 94. Stack trace: …”}
  • 31. Mind the Information Gap • Client and server are on a mutual need-to-know basis • The server should never tell the client something it doesn’t need to know • Leakage of sensitive information • Giving the attacker a roadmap • The client should never tell the server something it already knows • Access control errors • Limit detail in error messages • The fact of the error; how to fix it; how to get help • Interpreter error messages are for developers, not users • The client is untrusted!
  • 32. Summary • Cat-and-mouse games • Church and state • Solutions decoupled from problems • Solving important problems from scratch • The abstraction trap • WET code • Code secured by a single set of eyes • Mind the information gap
  • 33. Final Thoughts • Understand the conceptual root of each type of vulnerability • Safe handling of user data is a major source of vulnerabilities • All exploits run on information, assumptions and trust • Information should be carefully controlled and rationed • Identify and manage assumptions • Don’t be afraid to Google simple questions • Study the specs • Programming is an art and a science • Good code is secure code