Application Security and Hardening

Geekwise Academy


Week 02 - SQL Injection and Cross Site Scripting (XSS)


Instructors:

Corey Shuman


Slack Channel:

#application-security

Github Repo:

https://github.com/coreyshuman/GeekwiseApplicationSecurity

Lecture Notes:

http://coreyshuman.github.io/GeekwiseApplicationSecurity/LectureNotes



Table of Contents:



    Goals for Week 2

    • Begin exploring application security fundamentals, particularly SQL Injection and XSS.
    • Practice performing these attacks on our app and then harden it from these vulnerabilities.
    • Explore additional resources for application security.

    Topics We Will Cover

    • SQL Injection
    • SQL Parameterization
    • Cross Site Scripting (XSS)
    • User Data Sanitization

    Assignment Review

    • Adding a field to our basic app
    • Building our simple blogging app

    Insecure Blogging Application Part 1

    Our basic application will give us an intruduction to NodeJS, Postgres, Postico, Postman, and Docker.

    Click Here to go to the application page.

    Brief Introduction to SQL

    Resource: https://www.w3schools.com/sql/

    SQL Injection Attacks

    Resource: https://www.w3schools.com/sql/sql_injection.asp

    Try It: Attempt the Following SQL Injections

    • Change the Make of all cars to 'Junk'
    • Delete all entries from the database
    • Add or remove columns from the table

    SQL Injection Prevention and Defenses

    Resource: [OWASP SQL Injection Prevention Cheat Sheet](https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet)

    Prepared Statements (Parameterized Queries)

    Resource: [OWASP Query Parameterization Cheat Sheet](https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet)

    Prepared statements are static queries that use placeholders (variables) to pass parameters into the query. This style allows the database to distinguish between code and data regardless of the payload (user input).

    Prepared statements ensure an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker.

    NodeJS (pg-promise):

    db.any("SELECT * FROM product WHERE price BETWEEN $1 AND $2", [1, 10])

    PHP:

    ASP.NET:

    Whitelist Input Validation

    Various parts of SQL queries aren't legal locations for the use of bind variables, such as the names of tables or columns, and the sort order indicator (ASC or DESC). In such situations, input validation or query redesign is the most appropriate defense. For the names of tables or columns, ideally those values come from the code, and not from user parameters. But if user parameter values are used to make different for table names and column names, then the parameter values should be mapped to the legal/expected table or column names to make sure unvalidated user input doesn't end up in the query.

    Whitelist validation for table selection:

    Whitelist validation for Sort Order:

    More examples are provided in the [OWASP Input Validation Cheat Sheet](https://www.owasp.org/index.php/Input_Validation_Cheat_Sheet)

    Escaping All User-Supplied Input (Last Resort)

    Why is this option challenging? https://www.postgresql.org/docs/8.3/static/sql-syntax-lexical.html

    Also see [[User Data Validation (Sanitization)]]

    Assignment: SQL Parameterization

    Use SQL parameterization to harden our Basic Insecure Web Application and Blogging Application.

    • Save your new version of the Basic Insecure App as BasicWebAppParameterized
    • Save your new version of the Blog App as BasicBlogParameterized

    Cross Site Scripting (XSS)

    [Cross-Site Scripting Sandbox](../../Applications/Week-02/02-CrossSiteScriptingSandbox)

    Cross Site Scripting is a type of attack where a script is injected into a website or web application so that it is run client-side for other users when the view the infected page. For example, if a user saves a script on a forum page, all users who view that page will have the script run on their web browser. These scripts can cause a variety of issues ranging from vandalism to credential theft.

    Types of Cross Site Scripting

    Stored XSS Attacks

    A stored attack has the script payload permanently stored to the web server, usually in a database. The script is then sent to the user as part of a result, text field, error message, etc.

    Reflected XSS Attacks

    A reflected attack is one where the script is not stored on the web server. Instead the server is used to distribute the injected script without the need for storage. The malicious script is transported to the victims via e-mail, a malicious link, a specially crafted form, or from the malicious site itself.

    Examples of XSS

    Basic Script Insertion

    DOM Attribute Insertion

    click me!

    Encoded URI Schemes

    XSS Using Encoding


    Additional Resources:

    https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

    Reflected Attack Example

    Let's assume that we have an error page, which is handling requests for a non existing pages, a classic 404 error page. We may use the code below as an example to inform user about what specific page is missing:

    This link will open the page for us:

    http://localhost:8080/some_fake_page_name

    http://192.168.99.100:8080/some_fake_page_name

    Now let's manipulate this page to execute code on the client machine

    http://localhost:8080/<script>alert("TEST");</script>

    http://192.168.99.100:8080/<script>alert("TEST");</script>


    If you are using Chrome, it might block it with the following error: ERR_BLOCKED_BY_XSS_AUDITOR. Firefox does not appear to block this request.

    Defending Against XSS

    https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

    XSS prevention could be a class on it's own. The link above provides a ton of information and strategies to protect your applications. Here I will summarize some of the major points to consider while planning and developing your web interface.

    Have an XSS Prevention Model

    A significant part of XSS prevention is carefully controlling where and when untrusted data is allowed to be put on your application. Depending on where untrusted data goes, it changes the concerns and vulnerabilities you open yourself up to. For example, untrusted data in a <script> tag is more vulnerable than data in a DOM attribute, which in turn is more vulnerable than data in a <div>, etc. The link above follows a slotted "whitelist" model.

    Sanitize User (Untrusted) Data

    It is important to sanitize all untrusted input from users, other apps, etc. If you used HTML entity encoding and only put untrusted data in the body of a document (such as a <div> tag) it would likely be ok. However, if untrusted data can make it into <script> tags, CSS, or URLs, even that isn't enough. As a result, the rules below are additional things you must consider to harden your application.

    Remember that the encoding for HTML content, attributes, scripts, CSS, and URLs will each be different!

    Use a Security Encoding Library

    Writing an encoding library is not simple and requires a lot of experience, knowledge, and testing to get right. I recommend you start with a well known and tested library if at all possible. For example, .NET users can utilize the Microsoft Anti-Cross Site Scripting Library and Java develoeprs can look into the OWASP Java Encoder Project.

    XSS Prevention Rules

    These rules can be found in detail with examples

    HERE

    RULE #0 - Never Insert Untrusted Data Except in Allowed Locations

    RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content

    RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes

    RULE #3 - JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values

    RULE #3.1 - HTML escape JSON values in an HTML context and read the data with JSON.parse

    RULE #4 - CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values

    RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values

    RULE #6 - Sanitize HTML Markup with a Library Designed for the Job

    RULE #7 - Prevent DOM-based XSS

    https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet

    XSS Filter Evasion Cheat Sheet

    https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet

    User Data Validation (Sanitization)

    Related to our discussion above, it is important to filter all untrusted data so that our application is robust against invalid or malicious input, whether obtained from users, infrastructure, databases, or external entities.

    As usual, the OWASP website has a great resource on Data Validation

    Here are the different types of data validations we will look into:

    Data encoding and sanitization

    Make sure data that will be presented to the user's browser is encoding untrusted data (see XSS info above)

    Integrity Checks

    Ensure that the data has not been tampered with. For example, if a user id is provided to change a password, make sure other items aren't changed in the payload (such as name, email, etc)

    Integrity checks must be included wherever data passes from a trusted to a less trusted boundary, such as from the application to the user's browser in a hidden field, or to a third party payment gateway, such as a transaction ID used internally upon return.

    The type of integrity control (checksum, HMAC, encryption, digital signature) should be directly related to the risk of the data transiting the trust boundary.

    Validation

    Ensure that the data is strongly typed, correct syntax, within length boundaries, contains only permitted characters, or that numbers are correctly signed and within range boundaries.

    Validation must be performed on every tier. However, validation should be performed as per the function of the server executing the code. For example, the web / presentation tier should validate for web related issues, persistence layers should validate for persistence issues such as SQL / HQL injection, directory lookups should check for LDAP injection, and so on.

    Business Rule Validation

    Ensure that data is not only validated, but business rule correct. For example, interest rates fall within permitted boundaries.


    Validation should be applied at all tiers of the application!

    For example, if the front-end is enforcing a 20 character max on a string length, the API and the Database should also respect and validate that rule.

    Delimiter and Special Characters

    Here is a partial list of special charactes that mean something to the various programs and languages involved in your web app. These are the characters which will often lead to issues or vulnerabilities in your app. This is not a comprehensive list.

    • NULL (zero) %00
    • LF - ANSI chr(10) "\r"
    • CR - ANSI chr(13) "\n"
    • CRLF - "\n\r"
    • CR - EBCDIC 0x0f
    • Quotes " '
    • Commas, slashes spaces and tabs and other white space - used in CSV, tab delimited output, and other specialist formats
    • <> - XML and HTML tag markers, redirection characters
    • ; & - Unix and NT file system continuance
    • @ - used for e-mail addresses
    • 0xff

    Assignment: XSS Prevention

    Apply the techniques we have learned to harden our Blog from Cross Site Scripting.



    Resources