Category Archives: Security

When 2-Factor Stops Being 2-Factor – Part 2

This is a continuation of my previous post on the failure of two-factor authentication. Let’s look at some case studies:

In late 2012, a version of the Zeuz in the mobile Trojan named “Eurograbber” stole over $46 million from European customers by bypassing the SMS based 2-factor authentication [1].

The way that it works is simple:

  • The attackers successfully execute a phishing or clickjacking attack on the victim and lure them to log into their banking site.
  • The attackers inject javascript that prompts the user to enter their mobile phone number.
  • Victim is sent an SMS message telling them to download a mobile app for security but in reality it is malicious.
  • The malicious app intercepts incoming SMS messages such as the 2-factor security code a bank sends when accessing an account.
  • The attackers intercept the SMS message and gain access to the user’s bank account and withdraw all the funds.

This is another instance of 2-Factor authentication failing and it’s proof that we cannot rely on a mobile operating system that is susceptible to malware and Trojans to act as our second or third factor for authentication. In theory, 2-factor solutions such as Google Authenticator or Authy could also be spoofed by screen grabbing TOTP tokens.

The second case study was just brought to light about a week ago. It is a variation of the ZeusVM and is called Chthonic (try pronouncing that). In true ZeuS fashion, the Trojan uses tried and true web injection methods to trick victims into providing sensitive banking information and then cleaning out their accounts. Over 150 banks have been targeted and I’m sure there’s many more to come [2].

The vast majority of attacks target the everyman. Who is the every man you may ask? In the Simpsons, the Everyman is a “dumpy, unappealing loser” [3] and in literature, the everyman is an “ordinary individual, with whom the audience or reader is supposed to be able to identify easily”. In books and films, the everyman is often put into extraordinary circumstances and often triumphs. However, when he is a target of a cyber attack in the real world, he simply does not have the knowledge or the experience to protect themselves from sophisticated attacks.

Everyman

So why does this happen? First, passwords were shown to be insecure because people make them insecure and can’t remember them. Second, 2-factor authentication has been proven insecure because of how 2-factor authentication is implemented (mobile devices, phones, RSA tokens). Traditional 2-Factor solutions either fall victim to malware or can get lost/stolen.

It seems that our only hope of truly securing the Everyman is 3-Factor authentication. And I don’t mean ridiculous solutions like voice or face recognition that easily fall prey to the same attacks as 2-factor authentication. I’m talking about real biometrics such as fingerprints, hair follicle tests, and retinal scanners. You know, cool stuff from James Bond movies (By the way, Idris Elba should totally be the next Bond)!

The problem however, is that secure biometrics are really, really hard to pull off. They are often expensive both from a financial and computational standpoint. They are also very hard to deploy on a massive scale and I think that’s the main reason they haven’t taken off. Now that we are in 2015 and we are all supposed to have hover boards, I think we are finally at the point where we can realistically pull off a widely distributable 3-Factor authentication scheme.

It's 2015, get with the program folks!

Hell, as Oscar Goldman put it, “we have the technology”! In recent years, biometric fingerprint scanners have become affordable, chips that can process biometrics are small enough, and Bluetooth Low Energy can act as the transmission protocol to put it all together. And by the way, that’s exactly what I’m working on with HYPR-3 and here’s a sneak preview!

HYPR-3

References

[1] Eurograbber, A Smart Trojan Attack
http://www.bankinfosecurity.com/eurograbber-smart-trojan-attack-a-5359/op-1

[2] Trojan programmed based on ZeuS targets 150 banks, can hijack webcams
http://www.itworld.com/article/2861795/trojan-program-based-on-zeus-targets-150-banks-can-hijack-webcams.html

[3] Everyman – Simpsons
http://img4.wikia.nocookie.net/__cb20090819205948/simpsons/images/8/8f/Homerthewhopper.jpg

Share

Why Even Cyber Criminals Need Web App Security

Back in October 2013, this guy Ross Ulbricht (AKA Dread Pirate Roberts – DPR) who was in charge of the popular website Silk Road was arrested by the FBI in a San Francisco library. His laptop had about 45 million bucks in Bitcoin on it and he was charged with a bunch or stuff ranging from planned murder to breaking just about everything in the Computer Fraud and Abuse Act.

Nice message from FBI we saw when Silk Road was seized

It was a bit of a surprise when he got arrested because he was very careful. He hid behind a bunch of Tor nodes, hid everything he did, and went out of his way to remain anonymous. Many thought that the Tor network was suddenly hackable by the FBI and that they used illegal means to arrest him. Well, the nice folks at the FBI recently told us what really happened; he was a web app security noob of ginormous proportions. But hey, before you start calling him that, remember that you probably are too (heck, this site is built on WordPress).

DPR got caught because he used a captcha on his site as everyone should when authenticating users. However, the captcha verification resolved to his main website server directly instead of going through Tor like the rest of his site (LOL!). This was probably going on for a stupid amount time but no one ever really figured it out. It’s one of those things that are just so stupid that you would never think to check it.

Ok! Ok! I must have, I must have put a decimal point in the wrong place
or something. Shit. I always do that. I always mess up some mundane
detail.

In my professional opinion (if you can call it that), if DPR had taken the time to have security professionals look into the security of his site, he wouldn’t have gotten caught so fast. I guess that even if you’re running a seedy and most likely illegal online enterprise, security should still matter. Probably more than ever.

Here is how the test by a professional would have gone assuming they know anonymity is a priority:

  1. They would setup a proxy for the Silk Road website and observe traffic
  2. They would see that most traffic goes to TOR nodes
  3. It would be easy to see that the Captcha verification always resolves to the same IP
  4. Notify DPR that they know where his site is hosted

Case solved… 45 million bucks saved for the time being.

Share

When Two-Factor Auth Stops Being Two Factors

Recently I got my phone stolen at a busy bar in NYC after attending an OWASP meetup and going to hang out with a few of the fellas afterwards.

Having your phone stolen definitely makes you feel like a victim. I’m not particularly worried about any of my data because my Android phone has remote wipe, a 15 character password, encryption enabled, and a bunch of other stuff.

The following day I got my new Android phone and it was time to start installing everything all over again. This included adding some of the following:

  • 2 factor Authentication apps (Authy, Google Authenticator)
  • Google accounts (business, personal, etc..)
  • Other email accounts
  • Personal banking apps
  • Productivity apps (for expense reports, time management)

I quickly noticed that all the accounts I was putting back onto my phone had two factor authentication (as they should). But I also noticed one common theme, for every account, the second factor was my damn phone. I would add my banking app, and I would have to put in a code I received via SMS. I would add my google account and I would be prompted to put in my Google Authenticator token. It really made me think is two factor still a valid authentication scheme if my second factor is my device? To me it isn’t. What if my phone is compromised via malware? The security validity of second factor suddenly goes out the damn window. Don’t get me wrong, having two factor auth on your mobile device is still better than not having it at all. But it definitely isn’t nearly as effective of a security solution as it is when using it for 2 factor authentication on a computer.

With the meteoric rise in BYOD where employees are adding company and personal accounts on their mobile devices, they are being urged to use two factor authentication. It seems to me that this is becoming more of a “security by obscurity” solution rather than a viable solution to the authentication problem we are faced with. I am seriously considering getting a separate device just to do 2-factor authentication with or just going back to a flip phone 🙂

Share

Favorite Android App Hacking Tools

Below is a list of some of my favorite tools to use for hacking android applications. Each one has its particular usefulness and can be fun to use. Most of them are open source projects so feel free to reach out to the developers on Github to ask for help or even contribute. I’ve found it that they are very helpful.

  1. Android SDK
    • http://developer.android.com/sdk/index.html
    • This is a must have for obvious reasons
    • Main SDK used to interact with android. Particular tools of interest are Android Debug Bridge (ADB) and AAPT.
    • Used to gain shell access to a device. Allows for an array of actions via command line.
  2. Android Backup Extractor
    • https://github.com/nelenkov/android-backup-extractor
    • Used to extract android application backups. Apps with the flag allowBackups=”true” in their AndroidManifest.xml can be backed up. The backup will include information such as preferences, the APK itself, and any database files that are stored on that application. This often times contains PII and passwords, unfortunately.
    • Backups will not retrieve data for an application that is on external storage. You will have to access the external storage separately to access any data that may be stored outside of the application’s context.
    • Doesn’t work very well if the device has encryption turned on. Depends on the device.
  3. APK Tool
    • https://code.google.com/p/android-apktool/
    • Used to decompile an APK and commonly used for reverse engineering.
    • Useful for looking for hardcoded passwords or encryption keys when source code is not available.
    • You can look at the resulting android manifest file to see which services and activities can be called. Checking for restrictions can be useful.
    • Check resulting android manifest file for any particular URIs that an application accepts. It may be an entry point.
  4. Fastboot
    • http://elinux.org/Android_Fastboot
    • Used to manipulate partitions on the device
    • Let’s you reset partitions and also flash the device with other images.
    • Keep in mind that flashing the system partition does NOT remove the app partition where application data is stored. This can be useful when working with an Mobile Device Management (MDM) where the MDM is installed on the system partition and prevents access at the App partition level. If you flash the system partition, the MDM will be gone and you’ll have unrestricted access to data on the App partition.
  5. Burp Suite Pro
    • http://portswigger.net/burp/
    • Favorite proxy tool for anything really
    • Keep in mind that some applications use WebSockets so keep an eye on that tab
    • When proxying Android apps, you may need to accept other MIME types that aren’t on by default.
  6. OWASP Dependency Check
  7. Dex2Jar
    • https://code.google.com/p/dex2jar/
    • When reverse engineering an android APK, you can use this tool to get the java code for the outputs provided by the APK tool above.
    • This can also be used to decompile an APK, modify it, and then re-package it. Keep in mind this will ruin the signature of the APK but it will remain the same otherwise.
    • Can be buggy
  8. SQLite Database Browser
  9. Towel Root
    • https://towelroot.com/
    • Used to root Android devices. Can root just about anything except for a few I’ve already reported to the developer.
    • Root access = game over 99% of the time.
Share

H.O.P.E Conference Tidbits

This past weekend I attended the Hackers of Planet Earth (HOPE) conference in New York City (http://hope.net/)

There were over 90 scheduled talks and most of them were pretty amazing. Here are some of my highlights.

Edward Snowden and Daniel Ellsberg Keynote

The keynote was packed with people! I managed to get a seat near the back about 2 hours before the keynote and when I looked behind me a few minutes later there were a sea of people who were overflowing into the other room. They announced that people were piling out the doors on the first floor of the hotel so that they can see the feed on the first floor. Amazing. I was also amazed at just how little BO there was considering the audience.

Snowden and Ellsberg had a great conversation about where they see the whistleblowing going in the future. Ellsberg wanted to get the point across that more people in the government and corporate industries should take the risk and leak information. Snowden was more focused on enabling these people to leak information and stay anonymous at the same time so they don’t go into exile like himself. I personally don’t have an opinion on this since I tend to focus more on the technology and try to steer clear of the politics. However, I cannot imagine everyday people risking their families, lives, and friends to leak information that may not be nearly as earth-shattering as Snowden’s leaks.

Identifying Back Doors, Attack Points, and Surveillance Mechanisms in iOS Devices

This was one of the most interesting talks to me. The speaker did a great job of showing some real security concerns about the IOS security infrastructure. Apple has put in many back doors to exfiltrate data from devices that are locked and assumably encrypted. Most IOS users think their data is encrypted on their device with either their PIN or fingerprint if they have one of the newer IOS devices. But it’s not.

Apple puts this back door to get data out of a device in the event a company person is deceased which makes sense. If this is used by the wrong people, the feature can be very dangerous. I am definitely re-visiting my stance on IOS vs Android security after this talk. The Google Play Store may be full of malware but at least Google isn’t putting back doors into my device. How do I know this? Because Android is open source!

North Korea – Using Social Engineering and Concealed Electronic Devices to Gather Information in the World’s Most Restrictive Nation

I only have two words for this talk. Simply Amazing. The speaker did an absolutely amazing job presenting his findings that he gathered from his multiple trips to North Korea. I’ve been following the North Korea stories pretty closely so I wasn’t really expecting to learn anything new. Man, was I wrong. The DPRK is basically a country of 24 million people who are willing to die at a moment’s notice for some crazy guy. Every morning, propaganda is played as people wake up, go to work, as they work, and before they go to sleep. The only television is NK TV that’s on a couple hours a day. The radios in homes do not have dials for stations (they can never be entirely turned down either) and those that do, unapproved frequencies are jammed by the government.

I will continue to watch the fascinating events that unfold in North Korea. The shit in the country will eventually hit the fan and we’ll all watch in fascination as millions of brainwashed people have to adapt to the world around them. If they survive.

Share

Engineers Perspective of The NYDFS BitLicense Regulatory Framework

A few minutes ago, Ben Lawsky from NYDFS released the Proposed BitLicense Regulatory Framework. I’m sure lots of very smart lawyers, regulators, and finance folks will have a thorough analysis of the proposal. However, I wanted to check it out to see how this proposal would affect virtual currency related implementations for engineers.

There is no doubt that this will affect business and regulatory requirements for many Bitcoin software and hardware startups. So lets look at some of the points.

Anti Money Laundering & Cyber Security

  1. Provide for independent testing for compliance with, and the effectiveness of, the anti-money laundering program to be conducted by qualified personnel of the Licensee or by a qualified outside party, at least annually – This will affect almost every Bitcoin based business. Engineers will have to implement a robust logging and auditing feature that monitors all their business’ transactions so that at the end of the year they can provide a complete log of what went on. There are many security implications for this. For one, this will most likely contain Personally Identifiable Information (PII) and will have to be kept safe. I could see potential businesses popping up just to provide this service for Bitcoin companies.
  2. Provide ongoing training for appropriate personnel to ensure they have a fulsome understanding of anti-money laundering requirements – Yeah, that won’t happen anywhere. If it does, it will be some e-learning program that everyone forgets within minutes of watching it. But hey, that’s compliance!
  3. Records of Virtual Currency transactions. Each Licensee shall maintain the following information for all transactions involving the payment, receipt, exchange or conversion, purchase, sale, transfer, or transmission of Virtual Currency: the identity and physical addresses of the parties involved, the amount or value of the transaction, including in what denomination purchased, sold, or transferred, the method of payment, the date(s) on which the transaction was initiated and completed, and a description of the transaction – This is a doozie. I think this is what will give companies the most headache. The two that give me the most pause is the fact that you have to have the physical address of the parties involved and a description of the transaction. It basically means that if you’re a BitLicense holder and you’re doing business with a person or entity, they not only have to provide you with their address but also a description of what the transaction is for. We’re already seeing this added at companies like Coinbase where whenever you take BTC out of your wallet, they ask you where it’s going. It seems quite intrusive to me and might turn away many people from Bitcoin. On the technical side of things, engineers will have to make sure that the data they collect is valid and compensate for the fact that transactions just went from simply putting in a Bitcoin address and hitting send to having to provide physical addresses and detailed descriptions. How do you validate these descriptions? There will need to be a protocol or system in place that allows merchants and businesses to whitelist Bitcoin addresses and that leads to a huge privacy issue in itself.
  4. Each Licensee shall file Suspicious Activity Reports – This is hard. Engineering this can be a total nightmare. There will be a lot of false positives and Bitcoin startups will struggle to keep up with the customer relations nightmare this might cause.
  5. Each Licensee shall establish and maintain an effective cyber security program to ensure the availability and functionality of the Licensee’s electronic systems and to protect those systems and any sensitive data stored on those systems from unauthorized access, use, or tampering. – Thank you Jesus! This is probably the most important aspect of this entire section. Unfortunately Fortune 500 businesses fail miserably at this, what makes us think Bitcoin startups with college dropouts for Engineers can do it? I actually have more faith in them than I do in the financial industry.
  6. Each Licensee shall designate a qualified employee to serve as the Licensee’s Chief Information Security Officer (“CISO”) – This is a neat idea. This expense will be huge for small Bitcoin companies. They simply cannot afford penetration tests, code reviews, and other items in this section. A huge amount of their funding may have to be spent on security which in turn might reduce time to market significantly if not done extremely efficiently.

Overall thoughts

I think NYDFS definitely took a lot of caution when writing this. It’s a thin line for sure because if they are too strict with their framework it will drive innovation and jobs out of the state and possibly this country. As a New York resident, I’m not terribly disappointed by the proposal. It seems doable. The simple fact of the matter is that most people will have no issue adhering to this BitLicense. None of the items seem to be any more intrusive than the credit card industry and the merchants still get the benefit of irreversible transactions that protect them from chargebacks and fraud.

Engineers will have their work cut out for them as they should. The security items outlined in the proposal are robust. While it will definitely increase cost from both a staffing and infrastructure perspective, it will encourage Bitcoin companies to think about security before something bad happens. Frameworks will have to be put in place to secure, audit, and monitor all virtual currency activity in an organization. This will be tough at first but I think services and tools will become available to aid businesses in doing this.

I think the Bitcoin community is innovative enough to find cost effective solutions to meet all these proposed regulations in a way that does not stifle innovation too much. However, I also think that the process to meet these regulations will “separate the men from the boys” when people start thinking about starting a Bitcoin business.

You can view the full thing here: http://www.dfs.ny.gov/about/press2014/pr1407171-vc.pdf

Share

Freezing, Cold, Brisk, Warm, and Hot Bitcoin Storage

I get a lot of people asking me about the proper way to do cold storage of their Bitcoins. These are commonly folks who are building a Bitcoin startup and are taking preventative measures. I like to think these are the people that will be successful. Unlike Mt. Gox and many other Bitcoin startups who neglect to think about their customers.

Anyway, I’ve devised a scheme for this on the Bitcoin Security Project organization that I run. In my security engineer duties I’ve had to design many secure architectures and I certainly think that this is one of them. If you disagree, contact me.

The scheme is a multi-tier architecture that I believe to be suitable for small to large Bitcoin companies. The basics are simple:

  1. Keep only a small amount in hot storage that wouldn’t ruin you if you lose it.
  2. Require strong authorization and authentication from multiple people when moving Bitcoin between tiers.
  3. Give some training to the folks who have control of your Bitcoin, please.
  4. Use common sense and do not automate withdrawal from cold storage. Servers get hacked all the time ya know.

Below is the scheme if you’re too lazy to check out the link above.

Multi Tiered Cold Storage Solution

Share

The Aegis Bitcoin Wallet

I’ve been using Bitcoin for a couple of years now. It’s gone from a curiosity to somewhat of an obsession. Anyway, my mobile device of choice is an Android and I haven’t been able to find a wallet that I can use and trust at the same time. So I decided to create one.

I designed it from the ground up for security. Lots of help was given by the guys at specularX.com especially in the NFC department. They also did an awesome job coordinating and coming through on the UI design. Admittedly, I am more of an engineer and definitely not a UI designer.

The wallet has a ton of features. For security, it encrypts all keys that are on the device. In order to send money, you either have to provide a password or an NFC tag that has an encryption value stored on it.

You can download the wallet at the play store or you can visit the site here: http://aegiswallet.com

You can check out the code on github at https://github.com/bsimic0001/AegisWallet. Please contribute if you can. All help is appreciated.

Aegis Home Screen

Share

CSRF Mitigation With AspectJ and AOP

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

Mitigating Clickjacking in Java with AOP & AspectJ

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