Securing ASP NET 2 0 Web Applications Svetlin

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 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: //msdn 2. microsoft. com/enus/security/aa 570411. 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: //msdn 2. microsoft. com/enus/library/ms 978516. 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 & Mc. Graw – Building Secure Software (http: //tinyurl. com/8 tkt 7)

Coding for Security • “What should I think about when I’m coding my Web application? ” – 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 of control channels (think of “sandboxing” it in a data channel)

SQL Injection: Demo

Recognizing Control and Data Channels printf(a, b, c, d) Sql. Command cmd = conn. Create. Command(); cmd. Command. Text = a; cmd. Parameters. Add("@x", b, Sql. Db. Type. Var. Char); Process. Start(a, b);

Case Study: SQL Injection • How would you fix the following BAD CODE? string name = Request. Form["name"]; cmd. Command. Text = "select * from users where name='" + name + "'"; • This is much better: Danger, control channel! Filter string n = Request. Form["name"]; if (!name. Regex. Is. Match(n)) throw. . . cmd. Command. Text = "select * from users where name=@n"; cmd. Parameters. Add("@n", Sql. Db. Type. Var. Char). Value = n; Sandbox

SQL Injection and Stored Procedures • If you always use stored procedures, are you safe? string name = Request. Form["Name"]; cmd. Command. Type = Command. Type. Stored. Procedure; cmd. Command. Text = "find_user"; cmd. Parameters. Add("@name", Sql. Db. Type. Var. Char). 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 validate. Request="false" /> In the ASPX pages: <%# Server. Html. Encode(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"]; Store. Content. In. Database(content); • Unsuspecting developer assumes the data in the DB is trusted… string content = Retrieve. Content. From. Database(); 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 = Retrieve. Content. From. Database(); string cleaned = Server. Html. Encode(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/ Add. To. Cart. aspx? item. Id=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; System. Configuration; System. Security. Cryptography; public static string Add. Tamper. Detection. HMAC(string s) { byte[] data = Encoding. UTF 8. Get. Bytes(s); byte[] hash = Get. Keyed. Hash(). Compute. Hash(data); return Convert. To. Base 64 String(hash) + '|' + s; } static HMACSHA 1 Get. Keyed. Hash() { string skey = Configuration. Settings. App. Settings["key"]; byte[] key = Convert. From. Base 64 String(skey); return new HMACSHA 1(key); } “Hello World” “x. Xy. U/Q 0 a 2 K 5 nb. Mfhzozk 4 Yczt 4 Y=|Hello world”

Simple Tamper Detection Code (2) public static string Check. And. Remove. HMAC(string s) { int i = s. Index. Of('|'); if (i == -1) throw new Exception("Malformed string"); string prefix = s. Substring(0, i); string suffix = s. Substring(i+1); byte[] hash = Convert. From. Base 64 String(prefix); byte[] data = Encoding. UTF 8. Get. Bytes(suffix); byte[] computed. Hash = Get. Keyed. Hash(). Compute. Hash(data); if (!is. Equal(hash, computed. Hash)) throw new Exception("String has been modified!"); return suffix; } public static string Generate. Random. Key() { byte[] rnd = new byte[16]; // 128 bits new RNGCrypto. Service. Provider(). Get. Bytes(rnd); return Convert. To. Base 64 String(rnd); }

References • Online – msdn. com/securityguidance • Books – Threat Modeling (Swiderski & Snyder) – Secure Coding: Principles & Practices (Graff & van Wyk) – Writing Secure Code, 2 nd Edition (Howard & Le. Blanc) – Building Secure Software (Viega & Mc. Graw)

Securing ASP. NET 2. 0 Web Applications: Questions

Securing ASP. NET 2. 0 Web Applications
- Slides: 34