How to write secure code?

Protect yourself against Cross-Site Scripting!

I have been working on secure code practices for the past few months and I have been trying to discuss the easy to adopt methods with the community. The amount of insecure code that we see on a daily basis is really shocking and we can all agree that “prevention is better than cure”.

The best way to keep our code and applications secure is to program them properly from the get go. Writing a secure code is not tough or complex, all it needs is the programmer to have the knowledge where to include the security checks. It’s a matter of few extra lines of code, but that alone can fend off a large number of attacks against your application.

Let’s dig in!

So, this particular article of “How to write secure code?” is focused on the Cross-Site Scripting issue.

Cross-Site Scripting flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface websites or redirect the user to malicious sites.

The code below is one of the examples why XSS attack take place, the input taken is not sanitised and it is directly passed into the parameter.

String firstNameParameter=(String)request.getParameter(“firstName”);

The value entered by the user is immediately stored in the local variable firstNameParameter and the value is then sent to browser in HTTP Response without any Output Encoding.

In this article I will go through few different types of attacks and methods, those you face on a daily basis and methods you can use to prevent them :-

1. Reflected XSS

It is trageted for one victim at a time. It can be seen in action when a malicious payload is passed to the victim and they end up clicking on the malicious URL and give the hacker access to their cookies and other data.

Here, is an example of a payload that if executed by the victim the attacker can have access to their details.

// the whole script is to be passed as an url. 
// it has been presented as such to enhance readability.

Another example of it can be when we visit a webpage that is a password generator. At a first glance the page doesn’t look vulnerable to any attack as all we have to do is press the “Generate Password” button.

We open up our burp-suite and intercept the request in our proxy tab. We send it over to the repeater tab to check the request query and the corresponding response query. The image below is the first request that we pass and we can observer that the username that we pass in the request query is reflected back in the response query.

Now that we know, that the username is reflected back to us we can inject the value field with our payload. The only thing that is necessary now is how we design the payload so that we can execute our command as intended.

";catch(e){}alert('injected');try(a="      // our payload

The above image shows the request and the response query with the payload attached to it and it seems to have been succesful. We url-encode the whole payload and then send it again via the proxy tab and check for the result we receive in the browser.

Passing the payload in the proxy tab

As expected we receive the alert box which popped up in out browser that shows that the attack payload has worked .

2. Stored XSS

This attack takes place when a code is injected in the server side program that is being hosted. So that every time a user navigates to the particular webpage or link they are the victim of stored XSS attack.

A stored XSS attack can be carried out as follows, if an image on the page is injected in such a way that whenever the page loads the malicious script (shown below ) is loaded instead of a picture and then grabs the user’s cookie.

// our payload

Another example of the stored XSS is as follows :-

In the login page that is presented beside us we enter test as the username and the password. Each and every thing that we do is recorded in the log database. We can go ahead and check in the log database, where we can see that the failed login attempt for the test username is registered. So if the username is not being sanitised and is directly being saved in the log then we can use that to our advantage to launch a stored XSS attack.

We pass in the following payload in the username field to see if we are able to carry out the XSS attack.


As soon as we pass our payload in the username box and open the log files we can clearly see the cookies being stored there as we intended it to.

So now every time someone opens up the log files their cookie values will be sent over to the capture-data.php page where the data will be then stored.

Defend your code!

We have talked in detail about how our code can be taken advantage of to execute malicious XSS attacks on the websites. The steps we can take are as following :-

Input Validation

  • The validation should be carried out on the server-side only, it should never be done on the client side.
  • White-listing & Black-listing of characters that we can allow the user to use should be done. We can utilise regular regex or framework based anti-XSS functions to enhance the security.
  • Code Sample

Instead of directly using and receiving parameter “firstName”.

String firstNameParameter=(String)request.getParameter(“firstName”);
  • Pass it through a regular expression first, prior to assigning to the variable firstNameParameter
private final String MY_DATAVALIDATION_WHITELIST = “[a-zA-Z]*”;
public boolean mustPassWhiteListCheck(String clientSideParameter) throws
boolean checkValue=false;
checkValue = Pattern.matches(MY_DATAVALIDATION_WHITELIST, clientSideParameter);
 if ( checkValue == false )
throw new WhiteListFailureException (“Possible Attack!!!”);
return checkValue;

Output encoding

  • Neutralises any misinterpreted characters contained in the HTTP response
  • Convert characters to be treated as data instead of executing malicious scripts
  • URL Encoding - Replaces the character in a string with one or more character triplets
  • Triplets: % followed by two other hexadecimal numbers, example : %2e this is for “.”
  • Output Encoding Code Sample

The code below is the one where the encoding is not being carried out.

System.out.println(“<HTML><HEAD><BODY>Hello + “ + request.getParameter(“firstName”) + “</BODY></HTML>”);

Now we will make small modifications to the above code, after the input has been sanitised by our regex sanitiser and we will then pass off the value to the print statement.

System.out.println(“<HTML><HEAD><BODY>Hello + “ + Encoder().encodeForHTML(sanitisedFirstNameVariable) + “</BODY></HTML>”);
  • Output Encoding Web Page contexts

At minimum we need to carry out URL encoding for these values :-

a) HTML Body

b) HTML Attribute

c) URL

d) JavaScript

e) Cascading Stylesheets


XSS is a dangerous attack and the search for XSS can be automated. Stored & Reflected XSS can cause pretty serious damage to the application. One of the most basic ways to prevent these attack is to carry out proper input validation and output encoding. Proper implementation of these two features can help us reduce the XSS attacks to NIL.

Read my other articles regarding “ Secure Coding Practise ”

~ Injection Attacks —
~ Broken Auth & Session Management —

If you enjoyed it please do clap and happy hacking!

Twitter :

LinkedIn :

E-mail :