* ASP.NET Web Security SQL Injection, XSS, CSRF, Parameter Tampering, DoS Attacks, Session Hijacking ASP.NET MVC Telerik Software Academy http://academy.telerik.com.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Telerik School Academy ASP.NET MVC.
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
C# Fundamentals – Part I
Welcome to the JSON-stores world Telerik Software Academy Databases.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Accessing SQL Server and MySQL – Live Demo Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
CSCI 6962: Server-side Design and Programming Secure Web Programming.
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Telerik Software Academy ASP.NET Web Forms.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer
Telerik Software Academy End-to-end JavaScript Applications.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Web Security SQL Injection, XSS, CSRF, Parameter Tampering, DoS Attacks, Session Hijacking SoftUni Team Technical Trainers Software University
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Web Security SQL Injection, XSS, CSRF, Parameter Tampering, DoS Attacks, Session Hijacking ASP.NET MVC SoftUni Team Technical Trainers Software University.
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

* ASP.NET Web Security SQL Injection, XSS, CSRF, Parameter Tampering, DoS Attacks, Session Hijacking ASP.NET MVC Telerik Software Academy http://academy.telerik.com (c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Table of Contents Web Security Main Concepts * Table of Contents Web Security Main Concepts Main Security Problems with Examples SQL Injection Cross Site Scripting (XSS) Cross-Site Request Forgery (CSRF) Parameter Tampering Other Threats (c) 2008 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Web Security Main Concepts

Feature or Bug Is Software Security a Feature? Most people consider software security as a necessary feature of a product Is Security Vulnerability a Bug? If the software "failed" and allowed a hacker to see personal info, most users would consider that a software bug Advanced Software Testing Vol. 1

Reasons for Failures In the real world, software failures usually happen spontaneously Without intentional mischief Failures can be result of malicious attacks For the Challenge/Prestige Curiosity driven Aiming to use resources Vandalizing Stealing Software Security Testing, Gary McGraw + Software Testing, Ron Patton

Golden Rules! Maximum Simplicity Secure the Weakest Link More complicated – greater chance for mistakes Secure the Weakest Link Hackers attack where the weakest link is (!) Limit the Publicly Available Resources (!) Incorrect Until Proven Correct Consider each user input as incorrect (!) The Principle of the "Weakest Privilege" Security in Errors (Remain stable) Provide Constant Defense (also use backups)

What is SQL Injection and How to Prevent It?

What is SQL Injection? Try the following queries: '  crashes protected void ButtonSearch_Click(object sender, EventArgs e) { string searchString = this.TextBoxSearch.Text; string searchSql = "SELECT * FROM Messages WHERE MessageText LIKE '%" + searchString + "%'"; MessagesDbContext dbContext = new MessagesDbContext(); var matchingMessages = dbContext.Database.SqlQuery<Message>(searchSql).ToList(); this.ListViewMessages.DataSource = matchingMessages; this.DataBind(); } Try the following queries: '  crashes '; INSERT INTO Messages(MessageText, MessageDate) VALUES ('Hacked!!!', '1.1.1980')  injects a message

How Does SQL Injection Work? The following SQL commands are executed: Usual search (no SQL injection): SQL-injected search (matches all records): SQL-injected INSERT command: SELECT * FROM Messages WHERE MessageText LIKE '%nakov%'" SELECT * FROM Messages WHERE MessageText LIKE '%%%%'" SELECT * FROM Messages WHERE MessageText LIKE '%' or 1=1 --%'" SELECT * FROM Messages WHERE MessageText LIKE '%'; INSERT INTO Messages(MessageText, MessageDate) VALUES ('Hacked!!!', '1.1.1980') --%'"

Another SQL Injection Example Original SQL Query: String sqlQuery = "SELECT * FROM user WHERE name = '" + username + "' AND pass='" + password + "'" Setting username to John & password to ' OR '1'= '1 produces String sqlQuery = SELECT * FROM user WHERE name = 'Admin' AND pass='' OR '1'='1' The result: If a user Admin exists – he is logged in without password

Preventing SQL Injection Ways to prevent the SQL injection: SQL-escape all data coming from the user: Not recommended: use as last resort only! Preferred approach: Use ORM (e.g. Entity Framework) Use parameterized queries string searchSql = @"SELECT * FROM Messages WHERE MessageText LIKE {0} ESCAPE '~'"; string searchString = "%" + TextBoxSearch.Text.Replace("~", "~~").Replace("%", "~%") + "%"; MessagesDbContext dbContext = new MessagesDbContext(); var matchingMessages = dbContext.Database.SqlQuery<Message>(searchSql, searchString);

SQL Injection and Prevention Live Demo

Cross Site Scripting (XSS) What is XSS and How to Prevent It?

XSS Attack Cross-site scripting (XSS) is a common security vulnerability in Web applications Web application is let to display a JavaScript code that is executed at the client's browser Crackers could take control over sessions, cookies, passwords, and other private data How to prevent from XSS? Validate the user input (built-in in ASP.NET) Perform HTML escaping when displaying text data in a Web control

XSS Cross-site scripting attack Cookie theft Account hijacking Modify content Modify user settings Download malware Submit CRSF attack Password prompt Execute the script on visiting the page Submits script on an unsafe form

Automatic Request Validation ASP.NET applies automatic request validation Controlled by the ValidateRequest attribute of Page directive Checks all input data against a hard-coded list of potentially dangerous values The default is true Using it could harm the normal work on most applications E.g. a user posts JavaScript code in a forum Escaping is a better way to handle the problem 500 Internal Server Error: A potentially dangerous Request.Form value was detected from the client (…)

Disable Request Validation ASP.NET WebForms Disable the HTTP request validation for all pages in Web.config (in <system.web>): ASP.NET MVC Using the ValidateInput filter we can disable validation for an action or entire controller <httpRuntime requestValidationMode="2.0" /> <pages validateRequest="false" /> [ValidateInput(false)] public ActionResult XssMvc(string someInput) { … }

What is HTML Escaping? HTML escaping is the act of replacing special characters with their HTML entities Escaped characters are interpreted as character data instead of mark up Typical characters to escape <, > – start / end of HTML tag & – start of character entity reference ', " – text in single / double quotes …

HTML Character Escaping Each character could be presented as HTML entity escaping sequence Numeric character references: 'λ' is λ, λ or λ Named HTML entities: 'λ' is λ '<' is < '>' is > '&' is & " (double quote) is "

How to Encode HTML Entities? HttpServerUtility.HtmlEncode HTML encodes a string and returns the encoded (html-safe) string Example (in ASPX): HTML Output: Web browser renders the following: <%: "The image tag: <img>" %> <%response.write(Server.HtmlEncode("The image tag: <img>"))%> The image tag: <img> The image tag: <img>

Preventing XSS in ASP.NET MVC The Razor template engine in ASP.NET MVC escapes everything by default: To render un-escaped HTML in MVC view use: @{ ViewBag.SomeText = "<script>alert('hi')</script>"; } @ViewBag.SomeText <script>alert('hi')</script> @{ ViewBag.SomeText = "<script>alert('hi')</script>"; } @Html.Raw(ViewBag.SomeText) <script>alert('hi')</script>

HTML Escaping in Web Forms and MVC Apps * * 4/21/201707/16/96 4/21/201707/16/96 HTML Escaping in Web Forms and MVC Apps Live Demo (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* 22##

Cross-Site Request Forgery What is CSRF and How to Prevent It?

What is CSRF? Cross-Site Request Forgery (CSRF / XSRF) is a web security attack over the HTTP protocol Allows executing unauthorized commands on behalf of some authenticated user E.g. to transfer some money in a bank system The user has valid permissions to execute the requested command The attacker uses these permissions to send a forged HTTP request unbeknownst to the user Through a link / site / web form that the user is allured to open

CSRF Explained How does CSRF work? The user has a valid authentication cookie for the site victim.org (remembered in the browser) The attacker asks the user to visit some evil site, e.g. http://evilsite.com The evil site sends HTTP GET / POST to victim.org and does something evil Through a JavaScript AJAX request Using the browser's authentication cookie The victim.org performs the unauthorized command on behalf of the authenticated user

CSRF Cross-site request forgery attack Evil.com MySite.com User <form action=“mysite.com/ChangePassword”> MySite.com Authentication cookie Login Submit data on behalf of User User

Cross-Site Request Forgery Live Demo

Prevent CSRF in ASP.NET MVC To prevent CSRF attacks in MVC apps use anti-forgery tokens Put the anti-CSRF token in the HTML forms: Verify the anti-CSRF token in each controller action that should be protected: @using (@Html.BeginForm("Action", "Controller")) { … @Html.AntiForgeryToken() } [ValidateAntiForgeryToken] public ActionResult Action(…) { … }

Prevent CSRF in AJAX Requests In jQuery AJAX requests use code like this: Send the token in the AJAX requests: <%-- used for ajax in AddAntiForgeryToken() --%> <form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form> $.ajax({ type: "post", dataType: "html", url: …, data: AddAntiForgeryToken({ some-data }) });

Anti-CSRF in MVC Apps Live Demo

Prevent CSRF in Web Forms In Web Forms just add the following code in your Site.Master.cs: It changes the VIEWSTATE encryption key for all pages when there is a logged-in user In the VS 2013 Web Forms app template, there is already CSRF protection in Site.master.cs protected override void OnInit(EventArgs e) { base.OnInit(e); if (Page.User.Identity.IsAuthenticated) { Page.ViewStateUserKey = Session.SessionID; }

What is Parameter Tampering and How to Prevent It?

What is Parameter Tampering? Malicious user alters the HTTP request parameters in unexpected way Altered query string (in GET requests) Altered request body (form fields in POST requests) Altered cookies (e.g. authentication cookie) Skipped data validation at the client-side Injected parameter in MVC apps

Parameter Tampering Live Demo

Other Threats Semantic URL attacks Man in the Middle (MiTM) URL Manipulation Man in the Middle (MiTM) Session Hijacking (easy if part of the URL) Always use SSL when sending sensitive data Insufficient Access Control Error messages can reveal information Denial of Service (DoS and DDos) Brute force (use CAPTCHA!) Phishing Security flows in other software you are using Social Engineering

ASP.NET Web Security http://academy.telerik.com

Free Trainings @ Telerik Academy "Web Design with HTML 5, CSS 3 and JavaScript" course @ Telerik Academy html5course.telerik.com Telerik Software Academy academy.telerik.com Telerik Academy @ Facebook facebook.com/TelerikAcademy Telerik Software Academy Forums forums.academy.telerik.com