Skip to main content

Trying to understand more about XSS


Cross site scripting


What is cross site scripting (XSS)?

Cross site scripting attack is an attack done by an attacker by exploiting the vulnerability of a website by injecting Javascript codes into the website. This code will then act as the content of the website itself and used to steal confidential information from the users visiting the website.Java script is a client side language , so when the code is executed on the client, on the person, who is browsing the infected website.


Different types of XSS Vulnerabilities.

Stored/Persistent xss : This attack occurs, when the code that is injected by the attacker is stored on the target server,such as in the database, in a message forum , comment field etc, so each time the site or the corresponding page is loaded the injected code will also be executed.

Reflected/Non Persistent xss : This attack occurs, when the code that is given by the attacker is returned immediately by the web application, in an error message, search result, without permanently storing the user provided data. So an attacker can then inject creapy javascript code at the end of such urls and provide that link to any victim, and the codes will be executed in the victims browser when he clicks on that link. So this vulnerability occurs when the web application has rendered the input given by the attacker without proper validation.

Dom Based xss : Here the entire tainted data flow from source to sink takes place in the browser, i.e., the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser. DOM(Document Object Model) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the style, content and structure of a document.

Here the javascript code is interprited and executed in the client side without having any communication with the web server. This could be very dangerous, as in some cases the web server will do some filterings to mitigate the xss vulnerabilities, but in DOM based there is no communication with the web server for the execution and it will completely run from the browser.

Server & Client XSS
 

Server XSS means that the data comes directly from the server onto the page. For example, the data containing the unsanitized text is from the HTTP response that made up the vulnerable page. In this case, the entire vulnerability is in server-side code, and the browser is simply rendering the response and executing any valid script embedded in it.Server XSS occurs when untrusted user supplied data is included in an HTML response generated by the server. The source of this data could be from the request, or from a stored location. As such, you can have both Reflected Server XSS and Stored Server XSS.


Client XSS means that the data comes from JavaScript which has manipulated the page. So it is JavaScript that has added the unsanitized text to the page, rather than it being in the page at that location when it was first loaded in the browser.Client XSS occurs when untrusted user supplied data is used to update the DOM with an unsafe JavaScript call. A JavaScript call is considered unsafe if it can be used to introduce valid JavaScript into the DOM. The ultimate source of the data could have been from a request, or from a stored location on the client.As such, you can have both Reflected Client XSS and Stored Client XSS.

Importance of fixing XSS vulnerability?


The ability to execute arbitrary JavaScript in another user's browser allows an attacker to perform the following types of attacks:

Cookie theft

The attacker can access the victim's cookies associated with the website using document.cookie, send them to his own server, and use them to extract sensitive information like session Ids.

Keylogging

The attacker can register a keyboard event listener using addEventListener and then send all of the user's keystrokes to his own server, potentially recording sensitive information such as passwords and credit card numbers.

Phishing

The attacker can insert a fake login form into the page using DOM manipulation, set the form's action attribute to target his own server, and then trick the user into submitting sensitive information.

Mitigating XSS



Preventing XSS Attacks (Server Side)

1) Header of cookie as HttpOnly & Secure

Implementation Procedure

First ensure you have mod_headers.so enabled in Apache instance

You can check if headers module is loaded or not using the below command.


httpd -M | grep headers

headers_module (static) 
 Syntax OK


After that insert the below codes to httpd.conf file

For httpd < 2.2.4


Header set Set-Cookie HttpOnly;Secure


For httpd >= 2.2.4


Header always edit Set-Cookie (.*) "$1;HttpOnly;Secure"


Here the HttpOnly will make sure client side scripts will not access the cookie


Secure , makes sure that cookie should only be sent across HTTPS requests.


2) X-XSS-Protection in Header.


In order to improve the security of your site against some types of XSS (cross-site scripting) attacks, it is recommended that you add the following header to your site


Implementation Procedure


Add the following entry in httpd.conf of your apache web server


Header set X-XSS-Protection "1; mode=block" // This will enable XSS filter and

will sanitize the page if attack detected.


3 ) Content Security Policy


CSP is an additional layer of security delivered via HTTP Header. This policy will define content sources which are approved, thus only allowing the browser from loading from the approved sources. This will prevent XSS, clickjacking etc

Preventing XSS Attack (Developer Side)


1) HTML Escape Before Inserting Untrusted Data into HTML Element Content

Escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, ", '), the forward slash is included as it helps to end an HTML entity

String safe = ESAPI.encoder().encodeForHTML( request.getParameter("input")); // HTML entity escaping and unescaping using ESAPI

2) Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes

Putting untrusted data into typical attribute values like width, name, value, etc. This should not be used for complex attributes like href, src, style, or any of the event handlers like onmouseover.Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The reason this rule is so broad is that developers frequently leave attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote. Unquoted attributes can be broken out of with many characters, including [space] % * + , - / ; < = > ^ and |.

String safe = ESAPI.encoder().encodeForHTMLAttribute(request.getParameter("input"));// HTML entity escaping and unescaping for Attributes

3) JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values


This rule concerns dynamically generated JavaScript code - both script blocks and event-handler attributes. If an event handler is properly quoted, breaking out requires the corresponding quote. However, we have intentionally made this rule quite broad because event handler attributes are often left unquoted. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, a
closing tag will close a script block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser.

String safe = ESAPI.encoder().encodeForJavaScript(request.getParameter("input")); // Javascript escaping and unescaping.

4) CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values

This is is for when you want to put untrusted data into a stylesheet or a style tag. CSS is surprisingly powerful, and can be used for numerous attacks. Therefore, it's important that you only use untrusted data in a property value and not into other places in style data. You should stay away from putting untrusted data into complex properties like url, behavior, and custom
String safe = ESAPI.encoder().encodeForCSS( request.getParameter("input"));// CSS escaping and unescaping.


5) URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values

This rule is for when you want to put untrusted data into HTTP GET parameter value.
 
String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) ); // URL escaping and unescaping.



6) Sanitize HTML Markup with a Library Designed for the Job


If your application handles markup -- untrusted input that is supposed to contain HTML -- it can be very difficult to validate. Encoding is also difficult, since it would break all the tags that are supposed to be in the input. Therefore, you need a library that can parse and clean HTML formatted text. There are several available at OWASP that are simple to use:

HtmlSanitizer - https://github.com/mganss/HtmlSanitizer 

.NET Library
###########
var sanitizer = new HtmlSanitizer(); 
sanitizer.AllowedAttributes.Add("class"); 
var sanitized = sanitizer.Sanitize(html);

OWASP Java HTML Sanitizer 
###################

import org.owasp.html.Sanitizers; 
import org.owasp.html.PolicyFactory; 
PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS); 
String cleanResults = sanitizer.sanitize("Hello, World!");

Ruby on Rails SanitizeHelper 
###################

<%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>



Comments

Popular posts from this blog

K8s External Secrets integration between AWS EKS and Secrets Manager(SM) using IAM Role.

What is K8s External Secrets and how it will make your life easier? Before saying about External Secrets we will say about k8s secrets and how it will work. In k8s secrets we will create key value pairs of the secrets and set this as either pod env variables or mount them as volumes to pods. For more details about k8s secrets you can check my blog http://jinojoseph.blogspot.com/2020/08/k8s-secrets-explained.html   So in this case if developers wants to change the ENV variables , then we have to edit the k8s manifest yaml file, then we have to apply the new files to the deployment. This is a tiresome process and also chances of applying to the wrong context is high if you have multiple k8s clusters for dev / stage and Prod deployments. So in-order to make this easy , we can add all the secrets that is needed in the deployment, in the AWS Secret Manager and with the help of External secrets we can fetch and create those secrets in the k8s cluster. So what is K8s external Secret? It i...

Password reset too simplistic/systematic issue

Some time when we try to reset the password of our user in linux it will show as simple and systematic as below: BAD PASSWORD: it is too simplistic/systematic no matter how hard password you give it will show the same. Solution: ######### Check if your password is Ok with the below command, jino@ndz~$ echo 'D7y8HK#56r89lj&8*&^%&^%#56rlKJ!789l' | cracklib-check D7y8HK#56r89lj&8*&^%&^%#56rlKJ!789l: it is too simplistic/systematic Now Create a password with the below command : jino@ndz~$ echo $(tr -dc '[:graph:]' 7\xi%!W[y*S}g-H7W~gbEB4cv,9:E:K; You can see that this password will be ok with the cracklib-check. jino@ndz~$ echo '7\xi%!W[y*S}g-H7W~gbEB4cv,9:E:K;' | cracklib-check                 7\xi%!W[y*S}g-H7W~gbEB4cv,9:E:K;: OK Thats all, Thanks.

Setting /etc/hosts entries during the initial deployment of an Application using k8s yaml file

Some times we have to enter specific hosts file entries to the container running inside the POD of a kubernetes deployment during the initial deployment stage itself. If these entries are not in place, the application env variables mentioned in the yaml file , as hostnames , will not resolve to the IP address and the application will not start properly. So to make sure the /etc/hosts file entries are already there after the spin up of the POD you can add the below entries in your yaml file. cat > api-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: spec:   template:     metadata:     spec:       volumes:       containers:       - image: registryserver.jinojoseph.com:5000/jinojosephimage:v1.13         lifecycle:           postStart:             exec:               command:...