Title: Securing ASP.NET 2.0 Web Applications
1Securing ASP.NET 2.0 Web Applications
Svetlin Nakov National Academy for Software
Development
2About Me
- Svetlin Nakov
- Director training and consulting activities,
National Academy for Software Development (NASD) - 15 years of developer experience
- 8 year as a professional software engineer,
trainer and consultant - Author of 4 books, 20 articles, and 50 seminar
lectures - Lecturer in Sofia University, NBU
3Agenda
- Threat modeling bang for your buck
- Online security resources from PP
- Security principles for design and coding
- User input from unlikely places
- Control vs. data channels
- Are you really safe?
- SQL injection
- Cross-site scripting (XSS)
- Tamper detection for client-side state
4 5Is Your Application Secure?
- Ever have anyone ask you this?
- Theres an easy answer NO
- There are no Secure apps
- But there are apps that are secure enough
- How to achieve enough security?
6What Does Secure Enough Mean to You?
- Nobody has an infinite security budget
- Many folks would be happy if they had any budget
- Be practical!
- Get the most bang for your buck
- Threat modeling will help you do this!
7Threat Modeling
- Threat modeling helps you find what is secure
enough - What are you trying to protect?
- Who is likely to attack you?
- What avenues of attack exist?
- Which vulnerabilities are the highest risk?
- Go after the high risk vulnerabilities first!
8Approaches to Threat Modeling
- Do you have security modeling expertise?
- Get a tool and start building threat models
- Microsoft has a free threat modeling tools
- http//msdn2.microsoft.com/en-us/security/aa570411
.aspx - Figure out your assets, trust levels, entry
points, threats, diagram threat trees - Find vulnerabilities
9- Microsoft Threat Modeling Tools Demo
10Approaches to Threat Modeling
- Dont have a security expert?
- Use Microsoft Patterns Practices
- Threat Modeling Web Applications
- http//msdn2.microsoft.com/en-us/library/ms978516.
aspx - Security guidance put together by well-known
experts - Complete guide to threat modeling ASP.NET
applications much easier to use than the threat
modeling tool!
11- Designing and Coding for Security
12Design for Security
- What should I be thinking about when Im
designing a Web application? - Software is as secure as its weakest link
- Run with least privilege
- Keep it simple
- Promote privacy
- Hiding secrets is hard
- Prepare for failure
- For more detail, see Viega McGraw
- Building Secure Software (http//tinyurl.com/8tkt7
)
13Coding for Security
- What should I think about when Im coding my Web
application? - User input is evil until proven otherwise!
- User input is evil until proven otherwise!
- No, thats not a typo its really important
- If the user can touch it, hell tamper with it
- Filter and sandbox input (more on this later)
- Pay close attention to filenames and paths
14 15User Input from Unlikely Places
- Form fields
- URL
- Query string
- Cookies
- View state
- Database records
- File contents
16Filtering and Sandboxing Input
- Filter input
- Use strong types
- Range check numerical data (including dates)
- Use regular expressions to check strings
- Look for what is good, not what you think is bad!
- Sandbox input
- Look for control and data channels
- Keep untrusted input out of control channels
(think of sandboxing it in a data channel)
int age int.Parse(Request.Formage)
17 18Recognizing Control and Data Channels
printf(a, b, c, d)
SqlCommand cmd conn.CreateCommand() cmd.Command
Text a cmd.Parameters.Add("_at_x", b,
SqlDbType.VarChar)
Process.Start(a, b)
19Case Study SQL Injection
- How would you fix the following BAD CODE?
string name Request.Form"name" cmd.CommandTex
t "select from users where name'" name
"'"
Danger, control channel!
string n Request.Form"name" if
(!nameRegex.IsMatch(n)) throw ... cmd.CommandText
"select from users where name_at_n" cmd.Paramet
ers.Add("_at_n", SqlDbType.VarChar).Value n
20SQL Injection and Stored Procedures
- If you always use stored procedures, are you
safe? - This code unnecessary dynamic SQL and allows SQL
injection!
string name Request.Form"Name" cmd.CommandTyp
e CommandType.StoredProcedure cmd.CommandText
"find_user" cmd.Parameters.Add("_at_name",
SqlDbType.VarChar).Value name
create proc find_user(_at_name varchar(200)) as
exec('select from users where name'''
_at_name '''')
21- Cross-Site Scripting (XSS)
22Cross-Site Scripting (XSS)
- XSS is where a website allows a user to inject
arbitrary HTML code - Attacker submits some data containing HTML
- This HTML might include undesirable graphics,
text, and/or malicious scripts - Victim requests a page and gets the attackers
HTML along with the page
23ASP.NET Protects Me From XSS, Right?
- ASP.NET has some built-in protection to help
deter XSS attacks - Will it save you? Nope!
- Dont assume that some piece of infrastructure
will protect you - Turn it off and escape the output
In Web.config
ltpages validateRequest"false" /gt
In the ASPX pages
lt Server.HtmlEncode(text) gt
24- Cross-Site Scripting Demo
25XSS Vulnerability
- I want users to be able to include some markup
in their content, so I allow HTML - Unsuspecting developer assumes the data in the DB
is trusted - and an XSS vulnerability is born!
string content Request.Form"Content" StoreCon
tentInDatabase(content)
string content RetrieveContentFromDatabase() Re
sponse.Write(content)
26Fixing the XSS Vulnerability
- ...while still allowing certain types of markup!
- The most effective solution is to filter output
- Any untrusted data injected into your HTML stream
should be encoded!
string tainted RetrieveContentFromDatabase() st
ring cleaned Server.HtmlEncode(tainted) //
Allow a bit of safe markup through cleaned
cleaned.Replace("ltbgt", "ltbgt") cleaned
cleaned.Replace("ltigt", "ltigt") Response.Wri
te(cleaned)
27 28Cookies and URL Mangling
- Do you use cookies or URL mangling to stash state
on the users computer? - What would happen if a clever user manipulated
that state? - What you need is tamper detection
http//www.expensive-shop.com/ AddToCart.aspx?item
Id22price449.90
29Tamper Detection via HMAC
- HMAC is a great way to protect yourself
- Hashed Message Authentication Code
- What it is
- HMAC hashes the data along with a secret key that
only your Web server knows - Resulting hash is included as part of the state
- Web server validates the hash to ensure the state
is not tampered - Forms authentication does this for cookies
encryption
30Sample Tamper Detection Code
using System.Text using System.Configuration usi
ng System.Security.Cryptography public static
string AddTamperDetectionHMAC(string s)
byte data Encoding.UTF8.GetBytes(s)
byte hash GetKeyedHash().ComputeHash(data)
return Convert.ToBase64String(hash) ''
s static HMACSHA1 GetKeyedHash() string
skey ConfigurationSettings.AppSettings"key"
byte key Convert.FromBase64String(skey)
return new HMACSHA1(key)
Hello World ? xXyU/Q0a2K5nbMfhzozk4Yczt4Y
Hello world
31Simple Tamper Detection Code (2)
public static string CheckAndRemoveHMAC(string s)
int i s.IndexOf('') if (i -1)
throw new Exception("Malformed string")
string prefix s.Substring(0, i) string
suffix s.Substring(i1) byte hash
Convert.FromBase64String(prefix) byte data
Encoding.UTF8.GetBytes(suffix) byte
computedHash GetKeyedHash().ComputeHash(data)
if (!isEqual(hash, computedHash))
throw new Exception("String has been
modified!") return suffix public static
string GenerateRandomKey() byte rnd new
byte16 // 128 bits new RNGCryptoServiceProv
ider().GetBytes(rnd) return
Convert.ToBase64String(rnd)
32References
- Online
- msdn.com/securityguidance
- Books
- Threat Modeling (Swiderski Snyder)
- Secure Coding Principles Practices (Graff
van Wyk) - Writing Secure Code, 2nd Edition (Howard
LeBlanc) - Building Secure Software (Viega McGraw)
33Securing ASP.NET 2.0 Web Applications Questions
34Securing ASP.NET 2.0 Web Applications