It’s been a while since my last post and many things have changed. I’ve started a new job at an awesome place, moved to New York City, learned a ton, and even made a second Android app.

It’s called (after much deliberation) Android Security Score and it does some stuff I haven’t seen other security apps do. It analyzes all the installed apps as well as all important security settings of an Android device. It then gives the user a simple score (A-F) that a person can use to get an idea of where their device is in terms of security.

Here’s some other stuff it does:

  1. Provide the user with permissions an app requests
  2. Give advice on how to make their device more secure/improve their score
  3. List potentially dangerous third party apps
  4. Root detection
  5. Showing apps that are old and out of date
  6. And several other things I can’t think of right now

It can be downloaded from https://play.google.com/store/apps/details?id=com.device.security.analytics.androidsecurityanalyticspro

And if you want the PRO version, which includes a handy dandy PDF report of all your results, you can get it from this here link.

Without further ado, here are some screenshots.

If you have any ideas for improvement or features you’d like to see, please let me know!

Screenshot_2013-08-21-09-28-24-1

Screenshot_2013-08-15-16-17-08

Screenshot_2013-08-15-16-17-35

Screenshot_2013-08-15-16-17-58

Share

This is another installment of using Aspect Oriented Programming techniques to mitigate common vulnerabilities in Java web applications.

First let’s define Cross Site Request Forgery (CSRF) – From OWASP:

CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker’s choosing. A successful CSRF exploit can compromise end user data and operation in case of normal user. If the targeted end user is the administrator account, this can compromise the entire web application.

Lets say you have this scenario:

You work on an super important Java web app with bunches of servlets, controllers, actions, JSP’s, etc…
You just learned how CSRF could be a huge threat to your users and you want to implement code for mitigating it on every POST request throughout.

The problem here is that to implement mitigating measures the ‘ol fashioned way, you have to go to every JSP and put in a CSRF token into every form that gets submitted. After that, you have to validate the token and put a new one up.

Using the technique below, you can mitigate CSRF without having to do any significant leg work. Here’s how!
Note: this is assuming you have AspectJ installed as well as Tomcat 6+

1. First you have to set the AspectJ weaver Java agent to the JVM parameter of your Tomcat startup. This is typically in your /bin/catalina.sh in your installation folder.

Add this to the JAVA_OPTS: -javaagent:C:/aspectj1.6/lib/aspectjweaver.jar (my path)

2. Second, you have to create a couple of aspects. I put these in a com.aspects package under the src folder.

Aspect 1: MitigateCSRFAspect – This aspect will create a pointcut that will intercept all POST requests to the application. Once it does that, it will put a CSRF token on the request and a matching one on the users’ session. It will also validate any CSRF token parameters. Props to Mr. Ricardo Zuasti for his post on some of this stuff.

package com.aspects; 
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.thesis.aop.util.StopWatch;
 
public aspect MitigateCSRFAspect{ 
	Logger logger; 
	StopWatch watch;
	
	//Constuctor for the Aspect. I do some init of loggers and
	//such here.
	public MitigateCSRFAspect(){ 
		//PropertyConfigurator.configure("log4j.properties"); 
		logger = Logger.getLogger("csrfMitigationLogger"); 
		logger.info("CSRF Prevention Aspect Created"); 
		watch = new StopWatch(); 
	} 
	
	
	pointcut csrf_interceptDoPost(HttpServletRequest req, 
		HttpServletResponse resp) :
			execution(* doPost(HttpServletRequest, 
				HttpServletResponse)) && args(req, resp);
	
	//This is the Advice for the above pointcut definition. 
	//It intercepts the response and request parameters.
	Object around(HttpServletRequest req, 
			HttpServletResponse resp): 
		csrf_interceptDoPost(req, resp){
		
		watch.start();
		logger.info("Inside of MitigateCSRF Advice");
		
		//Validation of salt currently on the request
		String saltFromRequest = 
			(String) req.getParameter("csrfSalt");
			Cache<String, Boolean> csrfCacheFromRequest = 
				(Cache<String, Boolean>)
				req.getSession().getAttribute("csrfCache");
		
		
		//If cache on session is not there, then it must be 
		//the first request. Therefore there would be no 
		//csrf token that exists yet.
		if(csrfCacheFromRequest != null){
	        if (saltFromRequest != null &&
	        	csrfCacheFromRequest.
	        	getIfPresent(saltFromRequest) != null){
	 
	            // If the salt is in the cache, we move on
	        	logger.info("SALT IS GOOD! " + saltFromRequest);
	        } else {
	            // Otherwise we log an error
	            logger.info("CSRF detected! Engage panic mode.");
	        }
		}
		
		
		//Setting the new salt
		Cache<String, Boolean> csrfCache = (Cache<String, Boolean>)
			req.getSession().getAttribute("csrfCache");
		
        if (csrfCache == null){
        	csrfCache = CacheBuilder.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .build();
        	
        	logger.info("Setting csrfCache: " + csrfCache);
            req.getSession().setAttribute("csrfCache", csrfCache);
        }
		
        String salt = RandomStringUtils.random(20, 0, 0, 
        		true, true, null, new SecureRandom());
        csrfCache.put(salt, Boolean.TRUE);
        
        //Use this on the JSP
        logger.info("Setting CSRF Salft: " + salt);
        req.setAttribute("csrfSalt", salt);
        
		watch.stop();
		logger.info(thisJoinPoint.getSourceLocation().getFileName() + 
			"_" + thisJoinPoint.getSourceLocation().getLine() + 
			"," + watch.getElapsedTime());	
		
		//This passes in the response object with the new header and
		//continues application execution flow as normal. 
		return proceed(req, resp);
	}
} 

Aspect 2: JSPCSRFTokenInjection – This aspect will intercept the JspWriter.write and the _jspService  methods. It will take the csrfToken value from the request and stick it in every single form on the page.

package com.aspects; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import org.apache.log4j.Logger;

import com.thesis.aop.util.StopWatch;
 
public aspect JSPCSRFTokenInjection{ 
	Logger logger; 
	StopWatch watch;
	
	private String currentCSRFToken = null;
	 
	//Constuctor for the Aspect. I do some init 
	//of loggers and such here.
	public JSPCSRFTokenInjection(){ 
		logger = Logger.getLogger("csrfMitigationLogger"); 
		logger.info("CSRF Injection Aspect Created"); 
		watch = new StopWatch(); 
	} 
	
	//Capturing the CSRF Token from the request 
	//by intercepting the 
	//_jspService method inside of the JSP
	public pointcut csrf_jspServiceIntercept(HttpServletRequest req, 
		HttpServletResponse resp) : 
	    execution(* *._jspService(HttpServletRequest, 
	    		HttpServletResponse)) 
	    && args(req, resp);
	
	
	before(HttpServletRequest req, HttpServletResponse resp) : 
		csrf_jspServiceIntercept(req, resp){
		currentCSRFToken = (String) req.getAttribute("csrfSalt");
		logger.info("Got CSRF Token from request: " 
				+ currentCSRFToken);
	}
	
	//Pointcut and advice for capturing the writing into a JSP.
	public pointcut csrf_captureFormWriting(String msg) :
		call(public void JspWriter.write(String)) 
		&& args(msg) 
		&& if(msg.toLowerCase().contains("</form>"));

	Object around(String msg) : csrf_captureFormWriting(msg){
		
		msg = msg.replace("</form>", "<input type='hidden' " +
				"name='csrfSalt' value='" 
				+ currentCSRFToken + "'/></form>");
		logger.info("MSG Value: " + msg);
		return proceed(msg);
	}
} 

3. After that, you have to create an XML file that will map your aspects to the files you want to weave at load time. This file will be located in your applications classes folder under a META-INF directory. In my case it was WebGoat/WebContent/WEB-INF/classes/META-INF/aop-ajc.xml

<aspectj>
	<aspects>
		<aspect name="com.aspects.MitigateCSRFAspect"/>
		<aspect name="com.aspects.JSPCSRFTokenInjection"/>
	</aspects>
</aspectj>

4. Compile and Run your application using AJDT or the AspectJ compiler and see the results below. I used the OWASP WebGoat application to test this out. As you can see below in the log files, the CSRF token is being put on the request, put into the JSP’s, taken off the request, and validated.

WARNING: DO NOT ACTUALLY LOG THIS STUFF, IT CAN BITE YOU IF YOUR LOGS ARE COMPROMISED!!!

579022 [http-8080-2] INFO  csrfMitigationLogger  :: Inside of MitigateCSRF Advice
579022 [http-8080-2] INFO  csrfMitigationLogger  :: SALT IS GOOD! nLcD6Y02xmy7JprdeEgO
579023 [http-8080-2] INFO  csrfMitigationLogger  :: Setting CSRF Salft: DdEeErMfxOuugPkm3x4Z
579023 [http-8080-2] INFO  csrfMitigationLogger  :: HammerHead.java_120,1
579026 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: DdEeErMfxOuugPkm3x4Z
579030 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:         </select><input type=’hidden’ name=’csrfSalt’ value=’DdEeErMfxOuugPkm3x4Z’/></form>

579068 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: DdEeErMfxOuugPkm3x4Z
580649 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: DdEeErMfxOuugPkm3x4Z
580651 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:             <input type=’hidden’ name=’csrfSalt’ value=’DdEeErMfxOuugPkm3x4Z’/></form>

583787 [http-8080-2] INFO  csrfMitigationLogger  :: Inside of MitigateCSRF Advice
583788 [http-8080-2] INFO  csrfMitigationLogger  :: SALT IS GOOD! DdEeErMfxOuugPkm3x4Z
583788 [http-8080-2] INFO  csrfMitigationLogger  :: Setting CSRF Salft: plZJegGquQaFzcxmjBxX
583789 [http-8080-2] INFO  csrfMitigationLogger  :: HammerHead.java_120,2
583834 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: plZJegGquQaFzcxmjBxX
583836 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:         </select><input type=’hidden’ name=’csrfSalt’ value=’plZJegGquQaFzcxmjBxX’/></form>

583876 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: plZJegGquQaFzcxmjBxX
583876 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: plZJegGquQaFzcxmjBxX
583877 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:             <input type=’hidden’ name=’csrfSalt’ value=’plZJegGquQaFzcxmjBxX’/></form>

587996 [http-8080-2] INFO  csrfMitigationLogger  :: Inside of MitigateCSRF Advice
587996 [http-8080-2] INFO  csrfMitigationLogger  :: SALT IS GOOD! plZJegGquQaFzcxmjBxX
587997 [http-8080-2] INFO  csrfMitigationLogger  :: Setting CSRF Salft: Kwct0YrzeGSVEkb9YzGp
587997 [http-8080-2] INFO  csrfMitigationLogger  :: HammerHead.java_120,2
588017 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: Kwct0YrzeGSVEkb9YzGp
588022 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:         </select><input type=’hidden’ name=’csrfSalt’ value=’Kwct0YrzeGSVEkb9YzGp’/></form>

588073 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: Kwct0YrzeGSVEkb9YzGp
588075 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: Kwct0YrzeGSVEkb9YzGp
588091 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:                         <input type=’hidden’ name=’csrfSalt’ value=’Kwct0YrzeGSVEkb9YzGp’/></form></td>

588104 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:                         <input type=’hidden’ name=’csrfSalt’ value=’Kwct0YrzeGSVEkb9YzGp’/></form>

588115 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:                         <input type=’hidden’ name=’csrfSalt’ value=’Kwct0YrzeGSVEkb9YzGp’/></form>

592720 [http-8080-2] INFO  csrfMitigationLogger  :: Inside of MitigateCSRF Advice
592720 [http-8080-2] INFO  csrfMitigationLogger  :: SALT IS GOOD! Kwct0YrzeGSVEkb9YzGp
592721 [http-8080-2] INFO  csrfMitigationLogger  :: Setting CSRF Salft: 9ojOc5YNuYyPAC6LZ0Ak
592721 [http-8080-2] INFO  csrfMitigationLogger  :: HammerHead.java_120,1
592731 [http-8080-2] INFO  csrfMitigationLogger  :: Got CSRF Token from request: 9ojOc5YNuYyPAC6LZ0Ak
592736 [http-8080-2] INFO  csrfMitigationLogger  :: MSG Value:         </select><input type=’hidden’ name=’csrfSalt’ value=’9ojOc5YNuYyPAC6LZ0Ak’/></form>

Let me know if you have questions and I’ll gladly answer them.

Share

From OWASP:

Clickjacking, also known as a “UI redress attack”, is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. Thus, the attacker is “hijacking” clicks meant for their page and routing them to other another page, most likely owned by another application, domain, or both.

The recommended solution to fixing this is to add the X-FRAME-OPTIONS header value, SAMEORIGIN. This is simple enough. BUT! What if you want to make the change application wide without having to go through hundreds or possibly thousands of files of source code?

This is where AOP and AspectJ in particular can be leveraged to prevent such vulnerabilities. The solution I came up with is to intercept the doGet and doPost calls in the entire application and creating an advice to “wrap” each of these calls. The wrapping would add the necessary header value and than continue the application execution as normal.

Basically what happens here is the Aspect created will weave in code to add the X-FRAME-OPTIONS header in any place that a doPost or doGet call is made.

What I did to show that this works is take the OWASP WebGoat project and test it out.

First, I created the aspect and placed it in the project. It looks like this:

package com.aspects; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.thesis.aop.util.StopWatch;
 
public aspect ClickJackingAspect{ 
	Logger logger; 
	StopWatch watch; 
	 
	//Constuctor for the Aspect. I do some init of loggers and
	//such here.
	public ClickJackingAspect(){ 
		PropertyConfigurator.configure("log4j.properties"); 
		logger = Logger.getLogger("clickJackingLogger"); 
		logger.info("Click Jacking Prevention Aspect Created"); 
		watch = new StopWatch(); 
	} 

	//Pointcut definition for the doGet method.
	// Notice I'm intercepting all calls to doGet and specifying the 
	// request and response parameters.
	pointcut clickJacking_addHeaderDoGet(HttpServletRequest req, 
		HttpServletResponse resp) : 
		execution(* doGet(HttpServletRequest, 
			HttpServletResponse)) && 
		args(req, resp);
		
	//This is the Advice for the above pointcut definition. 
	//It intercepts the response and request parameters.
	Object around(HttpServletRequest req, HttpServletResponse resp): 
		clickJacking_addHeaderDoGet(req, resp){
		watch.start();
		//Adding the header to the response object
		resp.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" ); 
		
		watch.stop();
		logger.info(thisJoinPoint.getSourceLocation().getFileName() + 
			"_" + thisJoinPoint.getSourceLocation().getLine() + 
			"," + watch.getElapsedTime());			
		//This passes in the response object with the new header and
		//continues application execution flow as normal. 
		return proceed(req, resp);
	}
	
	//Below is the same as above but for the doPost method.
	
	pointcut clickJacking_addHeaderDoPost(HttpServletRequest req, 
		HttpServletResponse resp) : 
		execution(* doPost(HttpServletRequest, HttpServletResponse)) 
		&& args(req, resp);
		
	Object around(HttpServletRequest req, HttpServletResponse resp): 
		clickJacking_addHeaderDoPost(req, resp){
		watch.start();

		resp.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" ); 
		
		watch.stop();
		logger.info(thisJoinPoint.getSourceLocation().getFileName() + 
		thisJoinPoint.getSourceLocation().getLine() + "," + 
		watch.getElapsedTime());			
		return proceed(req, resp);
	}
} 

Second, I compiled the project using the AspectJ Compiler and tested it out. I used the Tamper Data plugin for Firefox to verify that the new header was on every response (Click thumbnail):

 

 

There you have it! Under 50 lines of code (which is very little considering this is Java) and clickjacking is mitigated in your web application. Feel free to contact me with any questions and good luck!

 

Share

My thesis on “Eliminating SQL Injection and Cross Site Scripting Using Aspect Oriented Programming” (I know, it’s a mouthful) has been approved for publishing!

Click this to download if you’re interested in the whole thing.

If anyone wants to discuss it, feel free to contact me. I’d love to hear your ideas.

I hope to further develop it to mitigate some of the other items in the OWASP top 10 in the near future and port it out to a few other programming languages besides Java.

Abstract:

Cross Site scripting (XSS) and SQL injection are two of the most common vulnerabilities found in applications. According to a study done by the Web Application Security Consortium (WASC) on 12,186 web applications, the percentage of sites with these vulnerabilities is 38 and 13 percent, respectively [3]. The fundamental reason these vulnerabilities exist in web applications are critical design flaws which lead to security issues across entire projects. It is typical in the case of web applications that developers continue to write insecure code and only fix these issues when they are noticed or become a problem [4]. Using Aspect Oriented Programming (AOP), modules can be created to address these security vulnerabilities across an entire application without modifying existing source code. This paper will explain in detail how the use of AOP and AspectJ in particular can be leveraged to create a tool for eliminating these two major security vulnerabilities in open source Java web applications. The implications of a tool for successfully eliminating these vulnerabilities would lead to a significant improvement in web application security by uncovering fundamental design flaws, providing sanity checks for programmers and architects, and make applications compliant with PCI DSS Standard with respect to XSS and SQL Injection.

Share

Although I have worked on several Android applications, this was my first deployment. I found the steps really easy especially when exporting via Eclipse.

Anyway, the app is a simple round timer that is color coordinated and easy to use. I decided to make it when I needed something loud to let me know when to stop working etc…

If anyone is interested, you can find it Here.

Share

One of the simplest AOP libraries for Javascript is jquery-aop.

There are a million reasons to use Aspect Oriented Programming; even in Javascript. One such case I came across recently was a requirement that came across to make the web application I’m working on accessible to screen readers such as JAWS.

For example, when displaying a modal window, it becomes necessary to switch the focus of the screen reader to the top of the modal. So instead of making changes to the modal library (in this case, simplemodal), AOP was used to switch the focus of the screen reader to the top of the modal div that had an anchor with the same value as the ID.

$.aop.around( {target: $, method: 'modal'},
		  function(invocation) {
		if(this === undefined)
			return false;
		var divId = $(this)[0].id;	
		invocation.proceed();
		window.location = "#" + divId;
		}
	);

A similar advice can be created for closing the overlay as well.

This is just a very small example but very useful. I have also found the library useful in debugging Javascript when dealing with browser specific issues on IE6 and IE7 where Firebug is unavailable.

Share

I have read just about every tutorial and gone through several books on AspectJ and never saw more then a couple of sentences on constructors for aspects. I am working on code that generates aspects and need to initialize several properties inside the constructor.

Below is an example for logging exceptions along with a constructor for the aspect.

package aspects.exceptions;

public aspect ExceptionLoggingAspect {

	//Aspect attributes can be created like in a regular class.
	public HashMap<String, String> properties;
	
	//Aspect constructor
	//The constructor cannot take any arguments and cannot 
	//throw any checked exceptions!
	public ExceptionLoggingAspect(){
		//You can initialize attributes and such here
	}
	
	//Pointcut for intercepting exceptions
	pointcut exceptionHandler(Exception e): 
		handler(Exception+) && args(e);
	
	//Pointcut for defining calls to .toUpperCase
	pointcut upperCall(): call(* *.toUpperCase(..));
	
	//Advice for exceptionHandler
	//This will be executed for any exception in the entire application
    before (Exception e): exceptionHandler(e) {
    	
        System.err.println("Caught by aspect: " + e.toString());
		System.out.println(thisJoinPoint.getSourceLocation().getWithinType() 
		+ " " + thisJoinPoint.getSourceLocation() + "  FILE: " + 
		thisJoinPoint.getSourceLocation().getFileName() + "   LINE: " +
		thisJoinPoint.getSourceLocation().getLine());
        e.printStackTrace();
    }
    
    //Advice for above pointcut "upperCall" 
    //Surrounds the function execution in a try/catch and catches any exceptions
    //This is useful so that you don't have to put exception coding in your classes
    Object around() : upperCall(){
    	try{
    		proceed();
    	}
    	catch (Exception e){
    		System.err.println("Caught by aspect: " + e.toString());
    	}
    	return null;
    }
   
	declare error : call(public * java.sql.Statement+.execute*(String, ..)) : 
		"You are making a call to a Dynamic SQL LIbrary!!! Can result in SQL injection!!!";
}

Share

Simple fix for simple problem.

I’ve recently ran into an issue where I needed different jQuery dialogs to have different widths other then the default. The issue was that different browsers had problems with solutions that used autoResize, width: auto, etc…

Since the div’s that I needed to create dialogs from already had width CSS attributes, I used the following:

First, create a “wrapper” function for your dialog creation in jQuery:

	$.fn.dialogFunction=function(options){
		var divId = $(this)[0].id;
                //Check if dialog already exists, and if so just open it
                //This solves the can't open same dialog twice issue.
		if($("#" + divId).is(':data(dialog)')){
			$("#" + divId).dialog("open");
		}
		else{
	        $("#" + divId).dialog({
	            draggable : false,
	            resizable : true,
	            close : function(e){
	                $('#dialogTrigger').focus()
	                }
	            ,autoOpen : false,
	            width: $("#" + divId).css("width"),
	            describedBy : "dialogDescription",
	            modal : true});
			$("#" + divId).dialog("open").find(":input").eq(0).focus();
		}
	};

Now you can basically just do $(“#divId”).dialogFunction();

If you look at line 16, that will create your dialog with the css width attribute attached to the div you’re creating the modal for.

Share

First Post!

It is February 2012 and this is the launch of my WP blog/site. It is mostly to make some of the discoveries I’ve made while programming available so that they may help others.

Share