Web Security

 

  • SQL Injection =  no sanitizing
  • Cross-site scripting = inject javascript via uri
  • Path Traversal = Allowing for path or directory traversal on your server is an amazingly bad idea. You would be allowing people to list the folders on your server and to navigate from folder to folder. This allows attackers to go to folders with sensitive information or website functionality and have some fun. 
  • Cross-site request forgery (CSRF) = If the script that adds to the database doesn’t check that the form was really sent from your server, I could add an image to any website by doing this:
    • <img src=”https://example.com/add_to_db.php?name=cheap%20rolex&email=susan@hotchicks.com&comment=mortgage%20help” width=”1″ height=”1″>
    • Anybody coming to my website would now be putting another comment into your database. I could use an image or CSS link or script or anything that allows for a URI to be defined and loaded by a browser when the HTML renders. In CSS, this could be a background image.
    • <a href=”/app/delete_entry.php?id=12″>delete</a>

 

Server side best practices

  • Turn off folder listing
  • Harden PHP (or webapp code)
  • Turn off error messages
  • Monitor log files

 

SQL injection attacks by example

http://www.unixwiz.net/techtips/sql-injection.html

“SQL Injection” is subset of the an unverified/unsanitized user input vulnerability (“buffer overflows” are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it’s straightforward to create some real surprises.

Some examples:

SELECT fieldlist FROM table WHERE field = 'x' AND email IS NULL; --';
SELECT email, passwd, login_id, full_name FROM table  WHERE email = 'x' AND 1=(SELECT COUNT(*) FROM tabname); --';
SELECT email, passwd, login_id, full_name FROM members WHERE email = 'x'; DROP TABLE members; --';  -- Boom!
SELECT email, passwd, login_id, full_name FROM members WHERE email = 'x'; INSERT INTO members ('email','passwd','login_id','full_name') VALUES ('steve@unixwiz.net','hello','steve','Steve Friedl');--';

Remediations:
  • Sanitize the input
  • Escape / Quotesafe the input
  • Use bound parameters
  • Limit database permissions and segregate users
  • Use stored procedures for database access
  • Isolate the webserver
  • Configure error reporting

 

Cross Site Request Forgery (CSRF)

https://www.cs.umd.edu/class/spring2016/cmsc414/papers/csrf-intro.pdf

https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

A Cross-Site Request Forgery (CSRF) attack occurs when a malicious web site, email, blog, instant message, or program tricks an authenticated user’s web browser into performing an unwanted action on a trusted site. If a target user is authenticated to the site, unprotected target sites cannot distinguish between legitimate authorized requests and forged authenticated requests.

 

IMPORTANT: Remember that Cross-Site Scripting (XSS) can defeat all CSRF mitigation techniques!

  • See the OWASP XSS Prevention Cheat Sheet for detailed guidance on how to prevent XSS flaws.
  • First, check if your framework has built-in CSRF protection and use it
  • If the framework does not have built-in CSRF protection, add CSRF tokens to all state changing requests (requests that cause actions on the site) and validate them on the backend
  • Stateful software should use the synchronizer token pattern
  • Stateless software should use double submit cookies
  • If an API-driven site can’t use <form> tags, consider using custom request headers
  • Implement at least one mitigation from Defense in Depth Mitigations section
  • SameSite Cookie Attribute can be used for session cookies but be careful to NOT set a cookie specifically for a domain. This action introduces a security vulnerability because all subdomains of that domain will share the cookie, and this is particularly an issue if a subdomain has a CNAME to domains not in your control.
  • Consider implementing user interaction based protection for highly sensitive operations
  • Consider verifying the origin with standard headers
  • Do not use GET requests for state changing operations.
  • If for any reason you do it, protect those resources against CSRF

 

XSS Filter Evasion Cheat Sheet

https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html

 

This attack, which uses normal XSS JavaScript injection, serves as a baseline for the cheat sheet (the quotes are not required in any modern browser so they are omitted here):

<SCRIPT SRC=https://cdn.jsdelivr.net/gh/Moksh45/host-xss.rocks/index.js></SCRIPT>

XSS Locator (Polyglot)

This test delivers a ‘polyglot test XSS payload’ that executes in multiple contexts, including HTML, script strings, JavaScript, and URLs:

javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"`/+/onmouseover=1/+/[*/[]/+alert(42);//'>

 

Cross-Site Request Forgery (CSRF) and Cross-Site Scripting (XSS) are both web security vulnerabilities:

 

  • CSRF tricks the victim into submitting a malicious request. It exploits the trust a site has in the user’s browser, potentially leading to actions like changing user settings or initiating transactions without the user’s consent.
  • XSS involves injecting malicious scripts into content from a trusted website. This script then runs in the context of the user’s browser, allowing attackers to steal data, hijack sessions, or deface websites.

 

The main difference is that CSRF exploits the trust that a site has in the user’s browser, while XSS exploits the trust a user has in a site.

 

SQL Injections

SQL Injection Countermeasures

  • Blacklisting: delete the characters you dont want
    • Downside: “peter o’connor”
  • Whitelisting
    • Check user-provided input is known value
    • Downside – names come from a well-known dictionary
  • Escape characters
  • Underlying Issues
    • This one string combines code and data
    • Similar to buffer overflows

 

Prepared statements and bind variables

  • Decouple the code and data
  • Variable binding

 

Mitigating the Impact

  • Limit privileges
    • Can select, cannot insert
  • Follow principle of least privilege
  • Encryption

 

CSRF, Attack

Forging a request from the user due to the predictable structure of what the server is expecting. This is also due to the nature that a server can take requests from anywhere. 

 

Cookies and Web Authentication

  • Common use of cookies is track users already AuthN
  • Use session cookie with user info
  • Subsequent requests (GET/POST) include cookie in headers or fields
  • Allows server to identify client

 

URLS with Side-Effects

  • GET request should have no side-effects but attacker could do the following

 

Cross-site Request Forgery (CSRF)

  • Target = user to a server where communication has a predictable structure
  • Attack goal = make requests to server look like user intended to make them
  • Attacker tools = get user to visit webpage under attacker control
  • Key tricks = requests to server are predictable structure and using something like <img src= can force victim to send to attacker

 

CSRF, Defense

Defenses

  • Only accept POST requests
  • URL rewriting
  • Same site cookies
  • Cookie-to-header token
  • Secret validation token (synchronizer token pattern)
  • Referrer validation
  • Custom HTTP header
  • Re-Auth
  • See OWASP CSRF prevention Cheat Sheet

 

Same Site Cookies

  • Cookie options:
    • Strict = browser only send cookies if request originated from that website
    • Lax = cookies sent when user navigates to url from external site, for example – by following a link

 

Cookie Header Token

  • JavaScript utilize Same Origin Policy
  • A webapp sets a csrf-token cookie, this is sent in the HEADER of all subsequent requests. The server would validated the token

 

Secret Validation Token

  • Random “challenge” token assigned to track user’s current session
  • These tokens inserted into HTML form and linked to sensitive server-side operations
  • Every request includes hard-to-guess secret
  • Can also randomize CSRF token parameter name/value each request

 

<form action=”/transfer.do” method=”post”> 

<input type=hidden name=“CSRFToken”  

value=OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTV hM2JmNGYxYjJiMGI4MjJjZDE1ZDZMGYwMGEwOA==”> 

…. 

</form>

 

Referer Validation

  • Referer validation is a security measure used to mitigate CSRF attacks by checking the HTTP Referer header of incoming requests. The Referer header is a part of the HTTP request that indicates the URL from which the request originated. By validating this header, a server can determine if the request was made from a trusted domain or not.
  • Part of HTTP header
  • Stateless
  • Validate the origin
    • Reject based on policy = referer header doesnt match expected domains
  • Considered as a weaker defense

 

Custom HTTP Header

  • X‐Requested‐By: XMLHttpRequest 
  • Server checks the presence of header, drops request if not found
  • This is for same-origin requests, doesnt work across domains

 

Reauthentication

  • Require re auth, possibly one time token
  • Very strong defense
  • Used in bank sites, first auth to login, reauth to send money

 

User Defenses

  • Logoff immediately
  • Disable browser save username/password
  • Dont allow sites to remember – sets cookies
  • Do not use tabbed browings
  • Use plugins that make CSRF difficut to exploit

 

Cross Site Scripting XXS

Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into content that is then served to end users. This vulnerability exploits the trust a user has for a particular site, executing the injected script in the user’s browser as if it were part of the site’s content. XSS can be categorized into three main types: 

  • Stored XSS, where the malicious script is permanently stored on the target server; 
  • Reflected XSS, where the script is reflected off the web server, such as in an error message or search result; and 
  • DOM-based XSS, which occurs when the vulnerability is in the client-side script rather than the server-side code. 

Attackers leveraging XSS can steal cookies, session tokens, or other sensitive information stored by the browser and associated with the victim’s session. 

 

To mitigate XSS vulnerabilities, developers should validate and sanitize all user input, use secure programming patterns, and implement Content Security Policy (CSP) headers. Despite being well-known and understood, XSS remains a common and potent threat to web application security.

 

Example:

http://example.com/search?q=userinput

Attack Scenario:

An attacker crafts a malicious URL that includes a script in the “userinput” parameter:

http://example.com/search?q=<script>alert(‘XSS’);</script>

 

If the web application directly reflects the “userinput” back to the user without sanitizing or escaping the input, the browser will execute the JavaScript code within the context of the page. When an unsuspecting user clicks on the crafted URL, the JavaScript code (<script>alert(‘XSS’);</script>) executes, and in this simple example, a pop-up alert with the message “XSS” appears.

 

XSS, Javascript and SOP

Javascript is executed by browser, they can:

  • Atler page contents (DOM)
  • Track events
  • Issue web requests and read replies
  • Maintain persistent connections (AJAX)
  • Read/set cookies

 

Browsers need to confine javascript execution. Attackers can:

  • Attacker can alter layout of  page
  • Read keystrokes
  • Read cookies. 

 

Same Origin Policy (SOP)

  • Browser need to isolate javascript via Same Origin Policy (SOP)
  • Page elements must be from same origin
  • Only scripts received from same origin can have access to page elements
  • This prevens malicious script on one page to access data from a different page
    • Documents on different origins cannot access each other
    • Documents on same origin can access
    • Divides documents into classes
  • Origin is defined as:

 

Cookies

XSS Methods

  • Reflected XSS = attack script reflected back to user as part of page from victim site
  • Stored XSS = attacker stores malicious code in a resource managed by server, ex database
  • DOM based (type of stored based) = injected script is part of page document/attributes

 

XSS, Stored XSS

Example:

  • MySpace hack “Samy is my hero”
    • MySpace allowed string <script> on form
    • Injected something like: <div style=”background:url(‘javascript:alert(1)’)”>
    • Each friend clicking on link caused the cross site call, self propagating worm
    • Gave Samy millions of friends in 24 hours

 

XSS, Reflected XSS

Attacker makes server send some javascript code to user. The user browser executes code which goes to attacker. Could be simple has Echoed Input. 

  • The user input is echoed to another endpoint controlled by attacker

Adobe PDF Viewer Exploit

  • PDF documents can execute javascript
  • Attacker locates PDF file on server
  • Attacker creates URL pointing to PDF, with javascript malware in fragment portion:
    • http://website.com/path/to/file.pdf#s=(javascript:alert(“xss”);)
  • This could also be done for local file copies:
    • file://C:\Mydocuments\file.pdf#s=(javascript…;)

 

XSS, DOM-based XSS

No server needed, the exploit is in the page

 

Document Object Model (DOM)

  • Convention for representing page with objects in HTML/XHTML/XML
  • Follows a tree structure
  • Javascript can
    • Modify DOM
    • Create new DOM
    • Delete DOM
    • Respond to user/time events
    • Submit form data
    • Replace whole document with another

 

XSS, Defenses

Open Web Application Security Project (OWASP)

  • Whitelist = validate all headers, cookies, query strings
  • Dont blacklist = do not attempt to sanitize
  • Principle of fail-safe defaults
    • If fails, its still safe

 

Protecting Servers

  • App should validate all headers, cookies, query, for fields, etc
  • Dont try to sanitize
  • Use positive security policy that specifies what is allowed
    • Negative / dont do policies are difficult to maintain and likely incomplete
  • See OWASP XSS Prevention Cheat Sheet
  • Never trust user input data
    • Remove special characters
    • Allow only safe commands

 

Defense Summary

  • Good Ideas
    • Static analysis tools
    • Taint tracking
    • Framework support
    • Continuous testing
  • Bad Ideas
    • Blacklisting
    • Manual sanitization
  • Cookies must not be easy to guess
    • Random
    • Sufficient length
    • Timeout and delete appropriately

 

XSS vs CSRF

  • Dont confuse the two:
    • XSS = exploit the trust of client browser on data sent from server
    • CSRF = exploit the trust of server on data sent from client

 

 

 

Database

  • Provide data storage and data manipulation
  • Tables and rows
  • Queries
  • Database Management System (DBMS) 
    • Semantics on how organize data
    • Transactions for manipulating
    • Language for query
    • API for interoperate with other languages
    • Management via users and permission

 

Cookies

  • Name value pair
  • Allows server to connect related requests (state management)
  • Size typically < 4KB
  • Domain (server port) and URL (optional) cookie assignment
  • Expiration date
  • Different Types:
    • Session
    • Persistent / Tracking
    • Secure
    • Authentication
    • HttpOnly

 

Sessions

  • Cookies used by server to track sessions
    • Active session
    • Identifier for session
  • Web frameworks often do this work
    • Manage session state
      • Keep state in main memory
      • Store in in files
      • Store in database
      • Server must delete session data

 

Cookies and Web Auth

  • Extremely common use of cookies
    • Track who already Auth
  • If users already visited / session cookie
  • Subsequent requests include cookie in request headers or url fields
  • Server to identify unique user

 

OWASP Top 10

  • A1 injection
  • A2 Broken Auth and Session Management
  • A3 Cross-site scripting
  • A4 Insecure Direct Object Reference
  • A5 Security Misconfiguration
  • A6 Sensitive Data Exposure
  • A7 Missing Function Level Access Control
  • A8 Cross-site Request Forgery
  • A9 Using Components and Known Vulnerabilities
  • A10 Unvalidated Redirects and Forwards

https://owasp.org/www-project-top-ten/