Presentation is loading. Please wait.

Presentation is loading. Please wait.

Securing ASP.NET 2.0 Web Applications Svetlin Nakov National Academy for Software Development.

Similar presentations


Presentation on theme: "Securing ASP.NET 2.0 Web Applications Svetlin Nakov National Academy for Software Development."— Presentation transcript:

1 Securing ASP.NET 2.0 Web Applications Svetlin Nakov National Academy for Software Development

2 About Me Svetlin NakovSvetlin Nakov Director training and consulting activities, National Academy for Software Development (NASD)Director training and consulting activities, National Academy for Software Development (NASD) 15 years of developer experience15 years of developer experience 8 year as a professional software engineer, trainer and consultant8 year as a professional software engineer, trainer and consultant Author of 4 books, 20 articles, and 50 seminar lecturesAuthor of 4 books, 20 articles, and 50 seminar lectures Lecturer in Sofia University, NBULecturer in Sofia University, NBU

3 Agenda Threat modeling: bang for your buckThreat modeling: bang for your buck Online security resources from P&POnline security resources from P&P Security principles for design and codingSecurity principles for design and coding User input from unlikely placesUser input from unlikely places Control vs. data channelsControl vs. data channels Are you *really* safe?Are you *really* safe? SQL injectionSQL injection Cross-site scripting (XSS)Cross-site scripting (XSS) Tamper detection for client-side stateTamper detection for client-side state

4 Threat Modeling

5 Is Your Application “Secure”? Ever have anyone ask you this?Ever have anyone ask you this? There’s an easy answer: NOThere’s an easy answer: NO There are no “Secure” appsThere are no “Secure” apps But there are apps that are secure enoughBut there are apps that are secure enough How to achieve enough security?How to achieve enough security?

6 What Does “Secure Enough” Mean to You? Nobody has an infinite security budgetNobody has an infinite security budget Many folks would be happy if they had any budgetMany folks would be happy if they had any budget Be practical!Be practical! Get the most bang for your buckGet the most bang for your buck Threat modeling will help you do this!Threat modeling will help you do this!

7 Threat Modeling Threat modeling helps you find what is “secure enough”Threat modeling helps you find what is “secure enough” What are you trying to protect?What are you trying to protect? Who is likely to attack you?Who is likely to attack you? What avenues of attack exist?What avenues of attack exist? Which vulnerabilities are the highest risk?Which vulnerabilities are the highest risk? Go after the high risk vulnerabilities first!Go after the high risk vulnerabilities first!

8 Approaches to Threat Modeling Do you have security modeling expertise?Do you have security modeling expertise? Get a tool and start building threat modelsGet a tool and start building threat models Microsoft has a free threat modeling toolsMicrosoft has a free threat modeling tools us/security/aa aspxhttp://msdn2.microsoft.com/en- us/security/aa aspxhttp://msdn2.microsoft.com/en- us/security/aa aspxhttp://msdn2.microsoft.com/en- us/security/aa aspx Figure out your assets, trust levels, entry points, threats, diagram threat treesFigure out your assets, trust levels, entry points, threats, diagram threat trees Find vulnerabilitiesFind vulnerabilities

9 Microsoft Threat Modeling Tools: Demo

10 Approaches to Threat Modeling Don’t have a security expert?Don’t have a security expert? Use Microsoft Patterns & PracticesUse Microsoft Patterns & Practices Threat Modeling Web ApplicationsThreat Modeling Web Applications us/library/ms aspxhttp://msdn2.microsoft.com/en- us/library/ms aspxhttp://msdn2.microsoft.com/en- us/library/ms aspxhttp://msdn2.microsoft.com/en- us/library/ms aspx Security guidance put together by well- known expertsSecurity guidance put together by well- known experts Complete guide to threat modeling ASP.NET applications; much easier to use than the threat modeling tool!Complete guide to threat modeling ASP.NET applications; much easier to use than the threat modeling tool!

11 Designing and Coding for Security

12 Design for Security What should I be thinking about when I’m designing a Web application?What should I be thinking about when I’m designing a Web application? Software is as secure as its weakest linkSoftware is as secure as its weakest link Run with least privilegeRun with least privilege Keep it simpleKeep it simple Promote privacyPromote privacy Hiding secrets is hardHiding secrets is hard Prepare for failurePrepare for failure For more detail, see Viega & McGrawFor more detail, see Viega & McGraw Building Secure Software (http://tinyurl.com/8tkt7)Building Secure Software (http://tinyurl.com/8tkt7)http://tinyurl.com/8tkt7

13 Coding for Security “What should I think about when I’m coding my Web application?”“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 importantNo, that’s not a typo – it’s really important If the user can touch it, he’ll tamper with itIf the user can touch it, he’ll tamper with it Filter and sandbox input (more on this later)Filter and sandbox input (more on this later) Pay close attention to filenames and pathsPay close attention to filenames and paths

14 User Input Is Evil!

15 User Input from Unlikely Places Form fieldsForm fields URLURL Query stringQuery string CookiesCookies View stateView state Database recordsDatabase records File contentsFile contents

16 Filtering and Sandboxing Input Filter inputFilter input Use strong typesUse strong types Range check numerical data (including dates)Range check numerical data (including dates) Use regular expressions to check stringsUse regular expressions to check strings Look for what is good, not what you think is bad!Look for what is good, not what you think is bad! Sandbox inputSandbox input Look for control and data channelsLook for control and data channels Keep untrusted input out of control channels (think of “sandboxing” it in a data channel)Keep untrusted input out of control channels (think of “sandboxing” it in a data channel) int age = int.Parse(Request.Form[“age”])

17 SQL Injection: Demo

18 Recognizing Control and Data Channels printf(a, b, c, d) SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = a; b, SqlDbType.VarChar); Process.Start(a, b);

19 Case Study: SQL Injection How would you fix the following BAD CODE?How would you fix the following BAD CODE? string name = Request.Form["name"]; cmd.CommandText = "select * from users where name='" + name + "'"; string n = Request.Form["name"]; if (!nameRegex.IsMatch(n)) throw... cmd.CommandText = "select * from users where SqlDbType.VarChar).Value = n; SqlDbType.VarChar).Value = n; Filter Sandbox Danger, control channel! This is much better:This is much better:

20 SQL Injection and Stored Procedures If you always use stored procedures, are you safe?If you always use stored procedures, are you safe? This code unnecessary dynamic SQL and allows SQL injection!This code unnecessary dynamic SQL and allows SQL injection! string name = Request.Form["Name"]; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "find_user"; SqlDbType.VarChar).Value = name; SqlDbType.VarChar).Value = name; create proc varchar(200)) as exec('select * from users where name=''' + exec('select * from users where name=''' + + '''')

21 Cross-Site Scripting (XSS)

22 XSS is where a website allows a user to inject arbitrary HTML codeXSS is where a website allows a user to inject arbitrary HTML code Attacker submits some data containing HTMLAttacker submits some data containing HTML This HTML might include undesirable graphics, text, and/or malicious scriptsThis HTML might include undesirable graphics, text, and/or malicious scripts Victim requests a page and gets the attacker’s HTML along with the pageVictim requests a page and gets the attacker’s HTML along with the page

23 ASP.NET Protects Me From XSS, Right? ASP.NET has some built-in protection to help deter XSS attacksASP.NET has some built-in protection to help deter XSS attacks Will it save you? Nope!Will it save you? Nope! Don’t assume that some piece of infrastructure will “protect” youDon’t assume that some piece of infrastructure will “protect” you Turn it off and escape the output:Turn it off and escape the output: In Web.config: In the ASPX pages:

24 Cross-Site Scripting: Demo

25 XSS Vulnerability “I want users to be able to include some markup in their content, so I allow HTML”“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…Unsuspecting developer assumes the data in the DB is trusted… …and an XSS vulnerability is born!…and an XSS vulnerability is born! string content = Request.Form["Content"]; StoreContentInDatabase(content); string content = RetrieveContentFromDatabase(); Response.Write(content);

26 Fixing the XSS Vulnerability...while still allowing certain types of markup!...while still allowing certain types of markup! The most effective solution is to filter outputThe most effective solution is to filter output Any untrusted data injected into your HTML stream should be encoded!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>", " "); cleaned = cleaned.Replace("<i>", " "); Response.Write(cleaned);

27 Tamper Detection

28 Cookies and URL Mangling Do you use cookies or URL mangling to stash state on the user’s computer?Do you use cookies or URL mangling to stash state on the user’s computer? What would happen if a clever user manipulated that state?What would happen if a clever user manipulated that state? What you need is tamper detectionWhat you need is tamper detection AddToCart.aspx?itemId=22&price= AddToCart.aspx?itemId=22&price=449.90

29 Tamper Detection via HMAC HMAC is a great way to protect yourselfHMAC is a great way to protect yourself Hashed Message Authentication CodeHashed Message Authentication Code What it is:What it is: HMAC hashes the data along with a secret key that only your Web server knowsHMAC hashes the data along with a secret key that only your Web server knows Resulting hash is included as part of the stateResulting hash is included as part of the state Web server validates the hash to ensure the state is not tamperedWeb server validates the hash to ensure the state is not tampered Forms authentication does this for cookies encryptionForms authentication does this for cookies encryption

30 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[] data = Encoding.UTF8.GetBytes(s); byte[] hash = GetKeyedHash().ComputeHash(data); byte[] hash = GetKeyedHash().ComputeHash(data); return Convert.ToBase64String(hash) + '|' + s; return Convert.ToBase64String(hash) + '|' + s;} static HMACSHA1 GetKeyedHash() { string skey = ConfigurationSettings.AppSettings["key"]; string skey = ConfigurationSettings.AppSettings["key"]; byte[] key = Convert.FromBase64String(skey); byte[] key = Convert.FromBase64String(skey); return new HMACSHA1(key); return new HMACSHA1(key);} “Hello World”  “xXyU/Q0a2K5nbMfhzozk4Yczt4Y=|Hello world” “xXyU/Q0a2K5nbMfhzozk4Yczt4Y=|Hello world”

31 Simple Tamper Detection Code (2) public static string CheckAndRemoveHMAC(string s) { int i = s.IndexOf('|'); int i = s.IndexOf('|'); if (i == -1) throw new Exception("Malformed string"); if (i == -1) throw new Exception("Malformed string"); string prefix = s.Substring(0, i); string prefix = s.Substring(0, i); string suffix = s.Substring(i+1); string suffix = s.Substring(i+1); byte[] hash = Convert.FromBase64String(prefix); byte[] hash = Convert.FromBase64String(prefix); byte[] data = Encoding.UTF8.GetBytes(suffix); byte[] data = Encoding.UTF8.GetBytes(suffix); byte[] computedHash = GetKeyedHash().ComputeHash(data); byte[] computedHash = GetKeyedHash().ComputeHash(data); if (!isEqual(hash, computedHash)) if (!isEqual(hash, computedHash)) throw new Exception("String has been modified!"); throw new Exception("String has been modified!"); return suffix; return suffix;} public static string GenerateRandomKey() { byte[] rnd = new byte[16]; // 128 bits byte[] rnd = new byte[16]; // 128 bits new RNGCryptoServiceProvider().GetBytes(rnd); new RNGCryptoServiceProvider().GetBytes(rnd); return Convert.ToBase64String(rnd); return Convert.ToBase64String(rnd);}

32 References OnlineOnline msdn.com/securityguidancemsdn.com/securityguidance BooksBooks Threat Modeling (Swiderski & Snyder)Threat Modeling (Swiderski & Snyder) Secure Coding: Principles & Practices (Graff & van Wyk)Secure Coding: Principles & Practices (Graff & van Wyk) Writing Secure Code, 2 nd Edition (Howard & LeBlanc)Writing Secure Code, 2 nd Edition (Howard & LeBlanc) Building Secure Software (Viega & McGraw)Building Secure Software (Viega & McGraw)

33 Securing ASP.NET 2.0 Web Applications: Questions

34 Securing ASP.NET 2.0 Web Applications


Download ppt "Securing ASP.NET 2.0 Web Applications Svetlin Nakov National Academy for Software Development."

Similar presentations


Ads by Google