Updated Mvc Web security updated presentation

71
Web Security By John Staveley DDDNorth 01/10/2016 https://uk.linkedin.com/in/johnstaveley/ @johnstaveley

Transcript of Updated Mvc Web security updated presentation

Page 1: Updated Mvc Web security updated presentation

Web Security

By John StaveleyDDDNorth 01/10/2016

https://uk.linkedin.com/in/johnstaveley/@johnstaveley

Page 2: Updated Mvc Web security updated presentation

Overview

Why Security?– (case studies)

Who are the hackers?How?

– (with solutions)SecurityEssentials.sln

(https://github.com/johnstaveley/SecurityEssentials)...and then on the serverFurther resourcesSummaryQuestions

Page 3: Updated Mvc Web security updated presentation

Who am I?

John StaveleyMvc.net developerNot a security expert!

Page 4: Updated Mvc Web security updated presentation

Why Security? - Some headlines

ZdNet 2014, “Hundreds of millions of records have been stolen this year through hacks and data breaches as a result of poor, or flawed security.”

Davos 2015, “Every time we talked to a top 500 company about cyber-security, they'd say to us: 'talk to my technology guy', now the board of directors and the CEOs of the companies pay attention. There is a new sense of urgency" – Head of a security company

FSB 2013, 41% of small businesses are a victim of cyber crime.

Page 5: Updated Mvc Web security updated presentation

Why Security? - Some example breaches

Sony – films, confidential email, payrollTarget – 110 million records lost including credit card details.

Current cost $110mHome Depot – 56m credit card, 53m email addressesJPMorgan – 10s of millions of customers data lostBadUSBICloud celebrity picturesSnapchat – 13Gb of dataEbay – 145 million user records lost. $220m lossHeartbleedetc

Page 6: Updated Mvc Web security updated presentation

Why Security? - and the rest...

Page 7: Updated Mvc Web security updated presentation

Why Security?

Loss of reputationBlacklistingLitigation Fines e.g. Data protection act, PCI complianceSuicides (Ashley Madison)

Page 8: Updated Mvc Web security updated presentation

Who are the hackers?

Script kiddies Hacktivists Insiders Organised Crime – Russian Business Network Advanced Persistent Threat

Page 9: Updated Mvc Web security updated presentation

Who are they? - hackers for hire

Page 10: Updated Mvc Web security updated presentation

What we will/won't cover

WILL: Web application security (MVC) DDOS Social Engineering

WON'T: Physical security Network security Trojans, Worms, Viruses IDS, Firewalls, Honey pots Internal threats Advanced persistent threats

Page 11: Updated Mvc Web security updated presentation

Presentation Approach

OWASP Top 10 Not for profit Cover all technologies Reviewed every 3 years Helps you prioritise

Chapter outline What is the hack? Who has been affected by it? What are the mitigations/countermeasures? Questions

DEMO SecurityEssentials.sln

Page 12: Updated Mvc Web security updated presentation

1 – SQL Injection

Page 13: Updated Mvc Web security updated presentation

SQL Injection – What is it?

Page 14: Updated Mvc Web security updated presentation

SQL Injection – What is it?

string strQry = "SELECT * FROM Users WHERE UserName='" + txtUser.Text + "' AND Password='" + txtPassword.Text + "'";

EXEC strQry

Put in username field: Admin' And 1=1 –SELECT * FROM Users WHERE UserName='Admin'

And 1=1 --' AND Password=''

Put in password field: '; DROP TABLE Users --SELECT * FROM Users WHERE UserName='' AND

Password=''; DROP TABLE Users –'

http://www.not-secure.com/products?Id=14

Havij

Page 15: Updated Mvc Web security updated presentation

SQL Injection - Examples

Sony Playstation 2011 - “Worst gaming community data breach of all-time.” 77 million accounts affected 12 million had unencrypted credit card numbers Site was down for a month

CyberVor, Aug 2014 – Used botnet to steal billion passwords from 400,000 sites

Page 16: Updated Mvc Web security updated presentation

SQL Injection - Countermeasures

Assume all input is evil – validate everything Use an ORM like EF/NHibernate Use stored procedures Don't use EXEC sp_executesql @strQuery Reduce SQL account permissions Concept: Least Privilege

Page 17: Updated Mvc Web security updated presentation

2 - Broken authentication and session management

Password security Session Hijacking Weak Account Management

Page 18: Updated Mvc Web security updated presentation

Password Security

What is it? - Storage, Policy and entry Password storage

Plain text = No security (http://plaintextoffenders.com/) Base64 encoding = No security Avoid Encryption – can be broken Use hashing (password = 5f4dcc3b5aa765d61d8327deb882cf99) Common hashes can be googled Use a salt Don't use RC4, MD4, MD5 and SHA-1 HashCat Use PBKDF2, SCrypt, Bcrypt, (Argon2)

Passwords Policy: Enforce minimum complexity Do not reject special characters Validate passwords against a list of known bad passwords Do not allow personal information in the password

Password Entry: Don't disallow paste on a web page

Page 19: Updated Mvc Web security updated presentation

Password Security - Examples

Case Study: Richard Pryce Case Study: Ebay May 2014

Up to 145 million users affected $200m loss Poor password encryption blamed

Case Study: LinkedIn 2012 6.5 million user accounts stolen by Russian criminals

Page 20: Updated Mvc Web security updated presentation

Password Security - Examples

SecurityEssentials.sln pwd: Hash, checking, strength

Page 21: Updated Mvc Web security updated presentation

Session hijacking – The What

Page 22: Updated Mvc Web security updated presentation

Session Hijacking – The how

Concept – Man In The Middle (MITM) Opening up the browser CSRF Sensitive data exposure DEMO: Session stealing using document.cookie=""

Page 23: Updated Mvc Web security updated presentation

Session Hijacking - Countermeasures

Counter client code access of cookies (Anti-XSS): HttpOnly Counter auth token 'Sniffing' – Use HttpsOnly (MITM) <forms loginUrl="~/Account/Login" timeout="60" requireSSL="true"

slidingExpiration="false"/> Private error logging/trace Reducing session timeout reduces exposure Track sessions - session invalidated during logoff? SecurityEssentials.sln web.config with transforms

Page 24: Updated Mvc Web security updated presentation

Weak account management – What is it?

Account enumeration, Owning the account Why?

– Sensitive data– Admin privileges

Registration Logon Remember me Password reset Change account details Logoff Call Centre

Page 25: Updated Mvc Web security updated presentation

Weak account management – Case Study

Page 26: Updated Mvc Web security updated presentation

Weak account management – Case Study

News contained details Sarah Palin used Yahoo mail Security Information Birthday? 2 minutes on Wikipedia Zip Code? Wallisa only has 2 postcodes Where did you meet your spouse? High School => Password reset

Page 27: Updated Mvc Web security updated presentation

Weak account management – Case Studies

Case Study: Find my phone in iCloud/iBrute 2014

Page 28: Updated Mvc Web security updated presentation

Weak account management - Countermeasures (1)

Account enumeration - Can occur on registration, logon or password reset forms e.g. Password Reset:

Success - “An account reset key has been emailed to you” Failure - “That user account does not exist” Success or Failure - “An account reset key has been

emailed to you” Use Https ([RequireHttps]) to protect sensitive data (MITM)

Page 29: Updated Mvc Web security updated presentation

Weak account management - Countermeasures (2)

Brute force Logon - Do not lock out on incorrect logon – DOS

Brute force Registration/Password reset:– CAPTCHA and/or throttling to prevent brute force

Verify email address by sending an email Re-challenge user on key actions e.g. prompt for old

password when entering new password Log and send email when any account state changes

Page 30: Updated Mvc Web security updated presentation

Weak account management - Countermeasures (3)

Password reset Don't send new password out – DOS Send email with expiring token (1 hour) Security questions: Concise, Specific, has a large range of answers, low

discoverability, constant over time Never roll your own membership provider or session

management – use the default one in the framework Outsource the solution e.g. Azure Active Directory or

OpenId SecurityEssentials.sln – Account Management process,

anti-enumeration and brute force by throttling and CAPTCHA, logging, email verification, email on change, activity log, auto-complete off, increase logon time failure

Page 31: Updated Mvc Web security updated presentation

3 – Cross Site Scripting (XSS)

Page 32: Updated Mvc Web security updated presentation

Cross site scripting (XSS) – What is it?

www.mysite.com/index?name=GuestHello Guest!

www.mysite.com/index?name=<b>Guest<b>Hello Guest!

www.mysite.com/index?name=Guest<script>alert('Gotcha!')</script>Hello Guest!

www.mysite.com/index?name=<script>window.onload = function() {var link=document.getElementsByTagName("a");link[0].href="http://not-real-xssattackexamples.com/";}</script>

www.mysite.com/index?name=<script>Insert evil script here</script>

Page 33: Updated Mvc Web security updated presentation

Cross site scripting (XSS) – What is it?

Encoded data vs unencoded e.g. &lt;b&gt;Guest&lt;\b&gt; vs <b>Guest</b> Cookie theft!<script>alert(document.cookies)</script>Concept: Don't trust your users!Reflected vs Persisted XSSAttack Vector: Social Network, Email etc

Page 34: Updated Mvc Web security updated presentation

Cross site scripting (XSS) – Examples

Case Study: Legal Helpdesk Enabler:

Session stealing DOS Sensitive data exposure

Ebay, Sep 2014 About.com, Oct 2014 – 99.98% of links susceptible

– Mar 2015 – still unpatched

Page 35: Updated Mvc Web security updated presentation

Cross site scripting (XSS) - Countermeasures

Validate untrusted data – don't trust your users!Sources of data – html post, urls, excel/csv import, import of database

Mvc3 - “A potentially dangerous Request.Form value was detected from the client”, except:

What if you want to post HTML? [AllowHTML]Countermeasure: Encode reflected dataMvc3 encodes Html by defaultExcept @Html.Raw(Model.MyStuff)For 'safe' HTML fragments use WPL (AntiXSS) Library for HTML, CSS, URL, JavaScript, LDAP etc

Concept: Black vs White listingSecurityEssentials: Incorporation of AntiXSS LibraryComparison with ASP.Net web forms

Page 36: Updated Mvc Web security updated presentation

4 – Insecure Direct Object References

Page 37: Updated Mvc Web security updated presentation

Insecure direct object references – what is it?

www.mysite.com/user/edit/12345

// Insecurepublic ActionResult Edit(int id) { var user = UnitOfWork.UserRepository.Get(e => e.Id == id); return View("Details", new UserViewModel(user); }

// Securepublic ActionResult Edit(int id) {

var user = UnitOfWork.UserRepository.Get(e => e.Id == id); // Establish user has right to edit the details if (user.Id != UserIdentity.GetUserId()) { HandleErrorInfo error = new HandleErrorInfo(new Exception("INFO: You do not

have permission to edit these details")); return View("Error", error); } return View("Edit", new UserViewModel(user); }

Page 38: Updated Mvc Web security updated presentation

Insecure direct object references - Examples

Immobilise Jan 2015

Citigroup, 2011– 200,000 customer details exposed

Page 39: Updated Mvc Web security updated presentation

Insecure direct object references - Countermeasures

Check the user has permission to see a resource– Don't expose internal keys externally– Map keys to user specific temporary non-guessable ones to

prevent brute force Frequently overlooked:

– Ajax calls– Obfuscation of paths does not work– Passing sensitive data in urls

SecurityEssentials.sln User edit

Page 40: Updated Mvc Web security updated presentation

5 – Security Misconfiguration

Page 41: Updated Mvc Web security updated presentation

Security Misconfiguration – What is it?

Unnecessary features enabled e.g. FTP, SMTP on a web server, ports opened

Default accounts and passwords still enabled and unchanged

Errors reveal internal implementation e.g. Trace.axd

Page 42: Updated Mvc Web security updated presentation

Security Misconfiguration - Examples

Webcams, Nov 2014 Secure Elmah, Google inurl:elmah.axd “error log for”

Page 43: Updated Mvc Web security updated presentation

Security Misconfiguration - Countermeasures

Encrypt connection string Server retail mode Ensure application is set for production – automate using

MVC config transforms SecurityEssentials.sln web.config

Page 44: Updated Mvc Web security updated presentation

6 – Sensitive Data Exposure

Page 45: Updated Mvc Web security updated presentation

Sensitive Data exposure – What is it?

Email addresses Contents of emails Passwords Auth token Credit card details Private pictures

Page 46: Updated Mvc Web security updated presentation

Sensitive Data exposure - Examples

Snapchat Jan 2014– Phone number upload feature brute forced

Tunisian ISP– Login pages for Gmail, Yahoo, and Facebook– Pulls the username and password, and encodes it with a weak

cryptographic algorithm Wifi Pineapple

Page 47: Updated Mvc Web security updated presentation

Sensitive Data exposure - Countermeasures

Use and enforce SSL/TLS – [RequireSSL] Google: “SSL/TLS accounts for less than 1% of the CPU

load, less than 10KB of memory per connection and less than 2% of network overhead.”

StartSSL.com or letsencrypt.org HSTS header and HSTS preload Encrypt sensitive data in storage Disclosure via URL Browser auto-complete Don't store it! e.g. CVV code SecurityEssentials forcing SSL/TLS, HSTS header, prevent

server information disclosure, web.config

Page 48: Updated Mvc Web security updated presentation

7 – Missing Function Level Access Control

Page 49: Updated Mvc Web security updated presentation

Missing Function Level Access Control – What is it?

Checking the user has permission to be there www.mysite.com/admin (Requires admin role!)

Page 50: Updated Mvc Web security updated presentation

Missing Function Level Access Control - Countermeasures

Path level in web.config Method level attribute e.g. [Authorize(Roles=”Admin”)] Controller level Authorize attribute Any point in code using identity features in .net

(System.Web.Security.Roles.IsUserInRole(userName, roleName)

Use [NonAction] Don't show links on UI to unauthorised functions Don't make server side checks depend solely on

information provided by the attacker Obfuscating links is no protection Least Privilege SecurityEssentials.sln unit tests

Page 51: Updated Mvc Web security updated presentation

8 – Cross Site Request Forgery

Page 52: Updated Mvc Web security updated presentation

Cross-Site request forgery - What is it?

Attacker sends malicious link <img src=”www.mysite.com/logoff” /> Requires to be logged on

Page 53: Updated Mvc Web security updated presentation

Cross-Site request forgery - Examples

TP-Link Routers, Mar 2014 300,000 routers reprogrammed DNS Servers changed Exploit known for over a year

Brazil 2011, 4.5m DSL routers reprogrammed

Page 54: Updated Mvc Web security updated presentation

Cross-Site request forgery - Countermeasures

Exploits predictable patterns, tokens add randomness to request

@Html.AntiForgeryToken()<input name="__RequestVerificationToken" type="hidden"

value="NVGfno5qe...... .......yYCzLBc1" /> Anti-forgery token [ValidateAntiForgeryToken] NB: Ajax calls ASP.Net web forms SecurityEssentials (controller and ajax)

Page 55: Updated Mvc Web security updated presentation

9 - Using components with known vulnerabilities

Case Study: WordPress, 2013 3 Year old admin module 10s of thousands of sites affected No Brute force protection

Possible effects: Circumvent access controls SQL Injection, XSS, CSRF Vulnerable to brute force login

NuGet – keep updated Apply Windows Update OWASP Dependency Checker SecurityEssentials.sln NuGet

Page 56: Updated Mvc Web security updated presentation

10 - Unvalidated redirects and forwards – What is it?

Attacker presents victim with an (obfuscated) url e.g.https://www.trustedsite.com/signin?ReturnUrl=http://www.nastysite.com/ User logs into safe, trusted site Redirects to nasty site, malicious content returned Any redirecting url is vulnerable MVC3 vulnerable

Page 57: Updated Mvc Web security updated presentation

Unvalidated redirects and forwards - Countermeasures

MVC4 problem solved (for login):

Page 58: Updated Mvc Web security updated presentation

Form Overposting – What is it?

[HttpPost]public ViewResult Edit(User user){ TryUpdateModel( … }

[HttpPost]public ViewResult Edit([Bind(Include = "FirstName")] User user){ TryUpdateModel( … ,propertiesToUpdate, … }

Page 59: Updated Mvc Web security updated presentation

DDOS – What is it?

Account lock out Site running slow in browser Server unable to fulfil a request

Page 60: Updated Mvc Web security updated presentation

DDOS - Examples

Case Study: Meetup, Mar 2014– $300– Site down for days

Page 61: Updated Mvc Web security updated presentation

DDOS - Examples

ZdNet, 2015: Global DDOS attacks increase 90% on last year

Page 62: Updated Mvc Web security updated presentation

DDOS – How and countermeasures

Protocol exploits such as ICMP, SYN, SSDP floodXSSBeing popularSystem exploits - covered by fixes from MS generallyBotnetsAmbiguous regexNot closing connectionsFilling up error logLong running pageOutsource the solution - Cloudfare

Page 63: Updated Mvc Web security updated presentation

Social Engineering – What is it?

You are the weakest link in the security terrain. e.g phishing, spear phishing (12 emails sent => 90% success rate).

People want to help Nobody thinks they are a target Virtually no trace of the attack

Page 64: Updated Mvc Web security updated presentation

Social Engineering - Examples

Spam Shoulder surfing Found treasure (e.g. USB drive) Case study: Email password reset Denial of service and social engineering

Page 65: Updated Mvc Web security updated presentation

Social Engineering - Countermeasures

Less than 1% of security budget is spent on people Notifications Principle of least privilege Logging and two factor authentication

Page 66: Updated Mvc Web security updated presentation

Securing your site – Code Cheat sheet (1)

Don't trust your users! Use an ORM Use a strong account management process Captcha/throttling Defeat account enumeration Hash passwords, encrypt data Least Privilege Use and enforce SSL Encode all output Secure direct object references [Authorize]/[Authorize(Roles=””)] users Conceal errors and trace Use antiforgery tokens

Page 67: Updated Mvc Web security updated presentation

Securing your site – Code Cheat sheet (2)

Keep components up to date Validate redirects Form overposting DDOS Headers Train staff in social engineering

Page 68: Updated Mvc Web security updated presentation

...and once on the server

Apply a good SSL policy on the server: http://www.ssllabs.com/projects/best-practises/

Poodle, Freak, Drown Encrypt the connection string on the production server Enable retail mode on the production server Patch the server Run on your site to check security standards are enforcedhttps://www.ssllabs.com/ssltest/

Page 69: Updated Mvc Web security updated presentation

Further Resources

OWASP Top 10 Pluralsight courses CEH Certification ZdNet SecurityNow podcast

Page 70: Updated Mvc Web security updated presentation

Summary

Hacks have been increasing in number and sophistication OWASP Top 10 Specific solutions in Mvc (SecurityEssentials.sln)

Page 71: Updated Mvc Web security updated presentation

Any Questions?

@johnstaveley