hack proofing your microsoft asp.net web forms and...

35
Hack Proofing Your Microsoft ASP.NET Web Forms and MVC Applications Adam Tuliper Software Architect - Cegedim www.secure-coding.com DEV333

Upload: dangnguyet

Post on 05-Apr-2018

215 views

Category:

Documents


2 download

TRANSCRIPT

Hack Proofing Your Microsoft ASP.NET Web Forms and MVC Applications

Adam TuliperSoftware Architect - Cegedimwww.secure-coding.com

DEV333

The SkinnyDescribe each main attack

Demo how the attack works

Fix our poor vulnerable application!

Why Script Kiddies, Why?

Click to Hack

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter Tampering Information LeakageEncryptionThe fastest way into your systems

Select * from pwned

'

SQL Injection - What is it?• Control code injected into the

data channel• Values are altered to create SQL

commands where only data is expected

Dangerous?Network enumerationAccount creating/crackingDatabase Copying over port 80Data TamperingCode DownloadBackdoors

Expected Input Unexpected Input

'

How Is It Exploited?URI tampering

Parameter Tampering

Cookie Tampering Set-Cookie: DefaultSearchLanguage=EN-US' union x,x,x--; path=/;

How Do You Prevent It?ALL calls are parameterized

No dynamic strings

Escape/Whitelist input.

Audit table permissions!

Use Entity Framework!!

DEMO - Permissions checker code

But I Need My Dynamic SQL!

1. Usually not – dynamic where clauses with static SQL:WHERE CustomerId = Coalesce(@customerId, CustomerId)

2. Dynamic Order By using RANK3. Regex/whitelist everything possible + parameterized queries4. Avoid exec instead of sp_executesql because of the lack of

parameter support.

SQL Injection Misconceptions

I am safe if always using stored procs: FALSE

If I replace only -- and ' you are safe: FALSE

If I have an error page I’m safe: FALSE

Proper permissions will always protect me: FALSE

Parameterized queries will protect me: Potentially

Together these help make the app safER

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter Tampering Encryption / Protecting Credentials Information LeakageWhen CSS isn’t cool

XSS – What is it?

Script injected into: Page Database CookiesTwo types – reflected and persistentAccess DOM, steal cookies, send form data, and more

Candidate Names Included:Unauthorized Site ScriptingUnofficial Site ScriptingURL Parameter Script InsertionCross Site ScriptingSynthesized ScriptingFraudulent Scripting

Script Injected to Web PageEvil Script User Visits Page

How Is XSS Exploited?Page processes malicious data as scriptURIs, Form Fields, Cookies, and Databases all sources of dataTricky to catch all combinations:<DIV STYLE="width: expression(alert('XSS'));“>"/<script((\s+\w+(\s*=\s*(?:"(.)*?"|'(.)*?'|[^'">\s]+))?)+\s*|\s*)src/i". UTF 7 Encoding (IE6 only) +ADw-SCRIPT+AD4-alert('XSS');+ADw-/SCRIPT+AD4-Without <script> tags<body onload=alert('test1')>

How Do You Prevent XSS?1. HtmlEncode or AttributeEncode all output: @, <%:, HtmlEncode(), HtmlAttributeEncode() Warning: <:#

No dynamic attributes - <div onclick={dynamic text} >2. Avoid ValidateRequest=false3. WYSIWYG Editing or HTML-

• Encode output before POST (Telerik, etc support this)• MVC3 - [AllowHtml] on Model Property – No [ValidateInput(false)]

4. ASP.Net 4 <httpRuntime encoderType> - Use Anti-Xss

Preventing XSS - AdditionalShould you store data encoded?Not encoded, but sanitized.

Encoding & storing can lead to double encoding:< &lt; &amp;lt; &amp;amp;let

AntiXss Sanitizer’s GetSafeHtml/GetSafeHtmlFragmentTest controls - inject script, special characters.Audit all locations data is dynamically displayed ex: <%, <%#Goodbye IE6 – Prevent yee I shall!

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter Tampering Encryption / Protecting Credentials Information LeakageForgery makes developers unhappy : (

CSRF – What Is It?

Attacker uses the fact the victim is authenticated to a website

Attacker crafts a request the user executes

Can be very simple - image tag in an email, script on a blog

Identifying the attacker can be difficult

CSRF – How Is It Exploited?Requests are generally repeatableImage - can be embedded in an email  <img src="http://host/CreateUser?JaneDoe">Attacked via XSS   <script src="http://host/CreateUser?JaneDoe">  <iframe src="http://host/CreateUser?JaneDoe">Invisible actions via the 'Image' Objectvar foo = new Image(); foo.src = "http://host/CreateUser?JaneDoe";

CSRF – How Do You Prevent It? 1/2All ‘actions’ through POST onlyGET requests only return data

Use Hidden Form TokenToken required on POST

GET Request

Data Returned-No Action

POST Request with Token

Token Check->Action!

CSRF – How Do You Prevent It 2/2MVC

• [HttpPost]• Html.AntiForgeryToken() & [ValidateAntiForgeryToken]

Web Forms• ViewStateUserKey = SessionId• Do not turn off: EnableViewStateMac=true

Hi, I’m The One-Click Attack

Web Forms Assumptions:Button commands are only processed on post events? FALSE

ViewState only processed if posted? FALSE

Page.IsPostBack means there definitely been a post? FALSE

Demo

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter Tampering Encryption / Protecting Credentials Information LeakageTaking advantage of page trust

Client contains key field

Attacker alters data (userId) on

POST

Wrong data updated based on new key

Tampering Gone WILD! (What Is It?)

UserId=59 UserId=1

Preventing TamperingValidate data on serverHash key field for comparison

secure-coding.com’s [ValidateAntiModelInjectionFor()]Web Forms – Built in protection!

EnableEventValidationprotects Hidden textboxProtection often disabled because of validation issues

Web Farm Considerations

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter TamperingEncryption / Protecting Credentials Information LeakageTaking advantage of page trust

EncryptionEncrypt sensitive config settings

Hash or Encrypt ALL Passwords

Encrypt all sensitive private information

Additional Code Demos for download

aspnet_regiis.exe -pe "connectionStrings" -app "/security“

Encrypt AFTER deployment to avoid machine key issues

Protecting Credentials• ALL pages use SSL• Intranet applications too!• Credentials / token usually sent

on every request• httpOnly cookies prevent client

script access – use always• Forms authentication requireSSL• No session info in the URI• Session Hijacking only takes

one cookie value

Forms Authentication

TokensBasic

Credentials

Cookies NTLM

SQL InjectionCross Site ScriptingCross Site Request ForgeryParameter TamperingEncryption / Protecting CredentialsInformation LeakageCaptain – She’s sprung a leak!!!!!

Information Leakage1. Implement <customErrors>

2. Test various types of errors (404, 500, etc)

3. Ensure ALL tracing is disabled• Disable all page level tracing • Search for tracing in web.config • Try accessing trace.axd

Simplest Implementation in web.config

TOOLS / RESOURCESAll links at: http://bit.ly/mlml1B

PluralSite OnDemand Training Library – Free Trial!!

OWASP: The Open Web Application Security Project

Security Tools

Microsoft Anti-Cross Site Scripting Library V4.0 (4.1 in beta!)

Microsoft Code Analysis Tool .NET (CAT.NET) v1 CTP - 32 bit

Related Content

SIM404 Hey, You! Get Off My Network!

SIM302 Lessons from Hackwarts Vol 1: Defense against the Dark Arts 2011

COS374-INT Security Considerations with the Cloud

DEV356 Integrating Security Roles into Microsoft Silverlight Applications

Thanks!!Please fill out evaluations on the way out

[email protected]

CompleteDevelopment.blogspot.com

Twitter: @AdamTuliper

Free Trial http://www.pluralsight-training.net/microsoft/

Visit me afterwards in the dev learning center – web stand

Web Track Resources

http://www.asp.net/http://www.silverlight.net/http://www.microsoft.com/web/gallery/http://www.iis.net/http://weblogs.asp.net/Scottgu/http://www.hanselman.com/blog/

Resources

www.microsoft.com/teched

Sessions On-Demand & Community Microsoft Certification & Training Resources

Resources for IT Professionals Resources for Developers

www.microsoft.com/learning

http://microsoft.com/technet http://microsoft.com/msdn

Learning

http://northamerica.msteched.com

Connect. Share. Discuss.

Complete an evaluation on CommNet and enter to win!

Scan the Tag to evaluate this session now on myTech•Ed Mobile