Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Wednesday, 8 March 2017

Understanding Cross-site scripting (XSS)

Background

As per wiki
             Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
       We will see this in details as to how web applications can be vulnerable to an XSS attack and how can it be safeguarded. This is the most common known security vulnerability. You can use 3rd party produces like IBM App scan to check for security vulnerabilities in your web applications.



Types of XSS attacks

There are many variants of XSS attacks but the major ones are -
  • Reflected or Non persistent XSS attack
  • Stored or persistent XSS attack

Reflected or Non persistent XSS attack

Out of this reflected is most common. In this type if xss malicious script is executed on clients browser and sensitive data might be stolen.

For eg. lets take a search field on some social networking site. You generally type is words their to either search for a particular word in your feed or to search your friend/family members. When you do this in the resultant page you see something like - "Search result for - your search query". Now if your social networking site is not safeguarded from xss attacks, attacker might inject a malicious script in the search query that will get executed when you do a search which will result in the attacker stealing your data. Worst case your authorization cookie is stolen and your account is compromised.

As stated in Wiki - A reflected attack is typically delivered via email or a neutral web site. The bait is an innocent-looking URL, pointing to a trusted site but containing the XSS vector. If the trusted site is vulnerable to the vector, clicking the link can cause the victim's browser to execute the injected script.

So when you get that mail again saying hey please review these bull**** documents please do not click it. It's either a spam or worst - attempt to steal your sensitive data, since you are logged into multiple sites with active sessions. Always see who is it sent from? Do you know that person? Does the link look suspicious? No one will give you money just like that or you will not be selected for a lucky draw without applying for it :). If you are curious as to what it actually is then copy the link and open it in incognito mode which have no active sessions or logins. Now if it asks you to login it's time to turn around.

Now what do we mean by  innocent-looking URL? The URL is infact that for a trusted website. All attacker will do is inject an XSS vector in one of the request parameters. Say search parameter like in example above. He will also encode script tags and other characters so that the victim user will not be able to guess it's the affected URL. Anyway well soon see a real example of this with working code and the fix. Now lets see persistent xss.

Stored or persistent XSS attack

This is even worst that then the reflected one because this xss attack vector is stored on websites server (perhaps in it's persistent DB) and it will get executed every time user navigates to the section that uses this xss affected code. Lets see an example.

Consider a forum used to discuss programming related QnA. Again if the site is not safeguarded against XSS attacks then an attacker can ask a question which seems normal and legit but at the end contains a malicious script/attack vector. Now when he publishes the question it gets stored in the sites persistent storage and when any user tries to visit this question this malicious script will get executed on his/her browser and again your sensitive data can be stolen.

It's not always about the victims sensitive data though. An attacker can use XSS attack to permanently change the websites appearance or change display texts. Consider the damage it can do. For eg. attacker can change the announcement made by a reputed company which can result in it's stock prices crashing.

Enough with the theory let's see a practical example -

Testing for XSS

Code for this demo is available on my git repository  -
It's a web app. So you can download it and run it in a web server like apache tomcat. For this demo I will use my local setup.

NOTE : This web project has multiple workflows. The files you are interested in are -
This demo also assumes you are familiar with webapps, JSP, Java, Spring etc. I have written multiple posts on these topics in the past. You can search those in this blog if you are interested.You can find everything starting from configuring and using ivy dependency management to developing sample Spring application to deploying apps on tomcat. Above web app uses all these.

Once you have deployed the web app you can open it in your browser. It should look like following -



You can add normal text in the search box and do a "Search" or a "Search Xss Protect". Everything should work fine. For eg. when I input - "I am groot!", it just shows me the query I have input -



Now lets do "Search Again" and perform a normal "Search". But this time we will search differently. Enter following query in the search box -
  • I am groot!<script>alert(10)</script>
The result is -



As you can see we do see our normal result but we also see a prompt with 10 in it. Now if you revisit our input query we added a script tag at the end and the browser executed it. This was just for the demo, attackers script will execute silently in the background without prompts and steal/modify your data.

Now lets repeat the same search with text -
  • I am groot!<script>alert(10)</script>
Only this time you press "Search Xss Protect". What do you see?



What happened here? No prompts? That's because we escaped out input so that it is not harmful which is exactly what the fix is. You need to escape your user inputs so that they are not executed by your browser as scripts. Now that you have seen a demo of how XSS behaves and how you could safeguard it lets see how it actually works from code perspective.

Code working

You need to revisit the JSP file -
The main culprit line here is -
  • Your input : <%=query %
This essentially evaluates the query from Java. If this has script tags those will be evaluated too. What do we do? We escape it before this line is reached which is precisely what the code does when you press protected search -

        String xssProtect = request.getParameter("xssProtect");
        if(xssProtect != null && xssProtect.equalsIgnoreCase("yes")) {
            query = ESAPI.encoder().encodeForJavaScript(query);
        } 


NOTE : xssProtect is something I have internally used to differentiate between normal search and protected search for demo purposes. You need not worry about it. In production you should never have a normal search like scenario.

NOTE : ESAPI is a library that OWASP (Open Web Application Security Project) recommends. You can see a bunch of links in the related links section below. But you can technically use any library that escapes html like coverity security lib.

NOTE : Above was an example of reflected or non persistent XSS attack. What if we were storing this search queries in our internal DB and showing search history for a user? In that case it would be a persistent XSS attack.

Though above demo was a means to show you how XSS actually works and how it can be safeguarded you should never code it this way. JSP should never have such logic. All of this should be in backend logic possibly your servlets and controllers.

Related Links

Saturday, 26 December 2015

Serving static resources with Spring MVC 3.0 in Java

Background

Many time we use custom CSS and java script file to add functionality and style to our web pages. We usually refer them in our JSP pages. In this post we will see how we can refer such static resources with Spring 3.0+. We will use Tomcat as our container/server.


Setup

If you are new to Spring then try out a sample Spring program -
Above post is somewhat old but should give you good idea as to get started. Anyhow I will provide the setup xmls here.

Your web.xml file should look as follows -

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Spring Web MVC Demo Application</display-name>
   
   
  <servlet>
      <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
     <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
  
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   

</web-app>



 Important file here is mvc-dispatcher-servlet.xml which forms a part of web application context. Have given a dummy file root-context.xml for root application context but you may not add it in your web.xml file. If you are not familiar with context loading part I suggest read

As I said create file mvc-dispatcher-servlet.xml with following content -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
    <!-- Scan for components under this package -->
    <context:component-scan base-package="com.osfg.test" />



    <mvc:annotation-driven/>
    
</beans>


As you can see the web application context will scan package com.osfg.test to find Spring resources like handler/interceptor. GO ahead create this package and create a controller in it. Lets call it TestController.java. Add following content to it.

package com.osfg.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author athakur
 */
@Controller
public class TestController {
    
    @RequestMapping(value="/test", method=RequestMethod.GET)
    public String welcome() {
        return "test";
    }

}



That's it. We have our controller all setup. This controller returns a logical view name called test. Now if you notice our spring configuration we have already defined InternalResourceViewResolver which provides a JSTL view. So go ahead and create a JSP file at /pages/test.jsp under webapp or webcontent.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>OSFG Test Page</title>
<link href="CSS/test.css" rel="stylesheet">
</head>
<body>

<h1>Hello World from OSFG!</h1>

</body>
</html>


As you can see our JSP references a CSS file called test.css. Create a folder called CSS and then create a file called test.cs  in it. Add following contents to it.
H1 {
color: white; background: teal; FONT-FAMILY: arial; FONT-SIZE: 18pt; FONT-STYLE: normal; FONT-VARIANT: normal
}



Ok we are all set to test now.

Note the Directory structure below -

 


Testing 1.0

Go ahead start up your tomcat server and load following URL
  • http://localhost:8080/TestWebProject/test 



 Oops! what happened? It is not able to find the CSS file.Well lets come to the point. Spring does not directly allow you to access static resources and the very goal of this post is to show you how. So lets see that now.

Add following to your Spring configuration -
<mvc:default-servlet-handler />


This basically allows you to render static resources from root folder (under webapp or webcontent).
It essentially configures a handler for serving static resources by forwarding to the Servlet container's default Servlet (DefaultServletHttpRequestHandler is used).
 Lets test with our new configuration -

Testing 2.0

After restarting the server hit the URL again -



All good? Yup :) There is also alternate way to do this. You can define resource mapping instead of specifying default-servlet-handler.

<mvc:resources mapping="/resources/**" location="/CSS/" />

Then you also need to make change in JSP as follows

<link href="resources/test.css" rel="stylesheet">

So when you reference resources it will go and pick up from CSS. You can use classpath references in location as well. Here ResourceHttpRequestHandler is used to serve request based on location provided.


Related Links





Friday, 3 April 2015

Difference between JSPs and Servlets

Background

Both JSPs and Servlets are server side technologies based on Java to generate web content dynamically that is then rendered on the requesting client which is typically your web browser. In this post we will see How JSPs work and what is exactly the difference between JSPs and Servlets.



Java Servlet

Servlet is a Java module that listens for HTTP requests like GET, POST etc. Once request is received by the servlet it will return appropriate response for it. A server code would look like - 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* @author athakur
*/
public class TestServlet extends HttpServlet {

  public void init() throws ServletException
  {
      //Servlet initialization code go here
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
  {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<b>Hello World!</b>");
  }
  
  public void destroy()
  {
      // Any code to be executed when servlet is destroyed
  }
}

and your web.xml will have mapping of this servlet and the URL the servlet handles - 

    <servlet>
        <servlet-name>TestServletName</servlet-name>
        <servlet-class>TestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>TestServletName</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping> 

So when ever tomcat server receives a request for URL like http://localhost:8080/projectName/HelloWorld you should see response as Hello World! in bold on a webpage that is rendered on your web browser.



As I said before think of a servlet as Java module that intercepts HTTP request and provides the response for it. It is like HTML in Java .

JSP pages

JSP  (Java server pages) - They are like Java in HTML. A simple JSP would look like below - 

<html>
<head><title>Test JSP</title></head>
<body>
  <%
    String greeting = "Hello World!";
  %>
  <b><%= greeting %></b>
</body>
</html>


As you can see it is  HTML content with embedded Java logic. Lets now see how JSPs actually work?

How JSPs work?

  1. When JSP container gets request for a JSP (Request URL would be something like http://localhost:8080/projectName/greetings.jsp) it checks whether JSP is compiled or not. If it is compiled it check for last modification time. If JSP page is modified after the JSP was previously compiled then JSP will be compiled again.
  2. Before compilation JSP is actually converted to a java servlet. This generated content is in Java just like a normal servlet we saw above. This servlet is then compiled into a class file.
  3. Request is then forwarded to this generated servlet which then handles the request and returns the response.

 The relevant generated servlet content in step 2 above for JSP same page that I have described above would be something like -

out.write("<html>\r\n  ");
String greeting = "Hello World!";
out.write("<b>");
out.print( greeting );
out.write("</b> \r\n");
out.write("</html>\r\n");

 You should be able to see the generated java file under 
  • work\Catalina\localhost\ProjectName\greetings.java



Related Links

t> UA-39527780-1 back to top