Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Securing ASP.NET 2.0
Web Applications
Svetlin Nakov
National Academy for
Software Development
About 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
Agenda
• Threat modeling: bang for your buck
• Online security resources from P&P
• 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
Threat Modeling
Is Your Application
“Secure”?
• Ever have anyone ask you this?
• There’s an easy answer: NO
• There are no “Secure” apps
• But there are apps that are secure
enough
• How to achieve enough security?
What 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!
Threat 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!
Approaches 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/enus/security/aa570411.aspx
• Figure out your assets, trust levels, entry
points, threats, diagram threat trees
• Find vulnerabilities
Microsoft Threat
Modeling Tools:
Demo
Approaches to Threat
Modeling
• Don’t have a security expert?
• Use Microsoft Patterns & Practices
• Threat Modeling Web Applications
• http://msdn2.microsoft.com/enus/library/ms978516.aspx
• Security guidance put together by wellknown experts
• Complete guide to threat modeling
ASP.NET applications; much easier to
use than the threat modeling tool!
Designing and
Coding for Security
Design for Security
• What should I be thinking about when I’m
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)
Coding for Security
• “What should I think about when I’m
coding my Web application?”
• User input is evil until proven otherwise!
• User input is evil until proven otherwise!
• No, that’s not a typo – it’s really important
• If the user can touch it, he’ll tamper with it
• Filter and sandbox input (more on this
later)
• Pay close attention to filenames and paths
User Input Is Evil!
User Input from
Unlikely Places
•
•
•
•
•
•
•
Form fields
URL
Query string
Cookies
View state
Database records
File contents
Filtering and
Sandboxing Input
• Filter input
• Use strong types
int age = int.Parse(Request.Form[“age”])
• 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)
SQL Injection:
Demo
Recognizing Control
and Data Channels
printf(a, b, c, d)
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = a;
cmd.Parameters.Add("@x", b, SqlDbType.VarChar);
Process.Start(a, b);
Case Study: SQL
Injection
• How would you fix the following BAD
CODE?
string name = Request.Form["name"];
cmd.CommandText = "select * from users
where name='" + name + "'";
• This is much better:
Danger, control channel!
Filter
string n = Request.Form["name"];
if (!nameRegex.IsMatch(n)) throw ...
cmd.CommandText = "select * from users
where name=@n";
cmd.Parameters.Add("@n",
SqlDbType.VarChar).Value = n;
Sandbox
SQL Injection and
Stored Procedures
• If you always use stored procedures,
are you safe?
string name = Request.Form["Name"];
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "find_user";
cmd.Parameters.Add("@name",
SqlDbType.VarChar).Value = name;
create proc find_user(@name varchar(200)) as
exec('select * from users where name=''' +
@name + '''')
• This code unnecessary dynamic SQL
and allows SQL injection!
Cross-Site
Scripting (XSS)
Cross-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
attacker’s HTML along with the page
ASP.NET Protects Me
From XSS, Right?
• ASP.NET has some built-in protection
to help deter XSS attacks
• Will it save you? Nope!
• Don’t assume that some piece of
infrastructure will “protect” you
• Turn it off and escape the output:
In Web.config:
<pages validateRequest="false" />
In the ASPX pages:
<%# Server.HtmlEncode(text) %>
Cross-Site
Scripting: Demo
XSS Vulnerability
• “I want users to be able to include some
markup in their content, so I allow HTML”
string content = Request.Form["Content"];
StoreContentInDatabase(content);
• Unsuspecting developer assumes the
data in the DB is trusted…
string content = RetrieveContentFromDatabase();
Response.Write(content);
• …and an XSS vulnerability is born!
Fixing 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();
string cleaned = Server.HtmlEncode(tainted);
// Allow a bit of safe markup through
cleaned = cleaned.Replace("<b>", "<b>");
cleaned = cleaned.Replace("<i>", "<i>");
Response.Write(cleaned);
Tamper Detection
Cookies and URL
Mangling
• Do you use cookies or URL mangling
to stash state on the user’s computer?
http://www.expensive-shop.com/
AddToCart.aspx?itemId=22&price=449.90
• What would happen if a clever user
manipulated that state?
• What you need is tamper detection
Tamper 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
Sample Tamper
Detection Code
using System.Text;
using System.Configuration;
using 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”
Simple 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(i+1);
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 byte[16]; // 128 bits
new RNGCryptoServiceProvider().GetBytes(rnd);
return Convert.ToBase64String(rnd);
}
References
• 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)
Securing ASP.NET 2.0 Web
Applications: Questions
Securing ASP.NET 2.0
Web Applications