A Java implementation of CSRF mitigation using “double submit cookie” pattern

Goal of this articlecsrf

The goal of this article is to present an implementation of the “double submit cookie” pattern used to mitigate the Cross Site Request Forgery (CSRF) attacks. The proposed implementation is a Java filter plus a few auxiliary classes and it is (obviously) suitable for projects using the Java language as back-end technology.

Definition of CSRF and possible mitigations

In the case of a CSRF attack, the browser is tricked into making unauthorized requests on the victim’s behalf, without the victim’s knowledge. The general attack scenario contains the following steps:

  1. the victim connects to the vulnerable web-site, so it have a real, authenticated session.
  2. the hacker force the victim (usually using a spam/fishing email) to navigate to another (evil) web-site containing the CSRF attack.
  3. when the victim browser execute the (evil) web-site page, the browser will execute a (fraudulent) request to the vulnerable web-site using the user authenticated session. The user is not aware at all of the fact that navigating on the (evil) web-site will trigger an action on the vulnerable web-site.

For deeper explanations I strongly recommend  to read chapter 5 of Iron-Clad Java: Building Secure Applications book and/or the OWASP Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet.

Definition of “double submit cookie” pattern

When a user authenticates to a site, the site should generate a (cryptographically strong) pseudo-random value and set it as a cookie on the user’s machine separate from the session id. The server does not have to save this value in any way, that’s why this patterns is sometimes also called Stateless CSRF Defense.

The site then requires that every transaction request include this random value as a hidden form value (or other request parameter). A cross origin attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy.

In the case of this mitigation technique the job of the client is very simple; just retrieve the CSRF cookie from the response and add it into a special header to all the requests:

csrfclient

Client workflow

The job of the server is a little more complex; create the CSRF cookie and for each request asking for a protected resource, check that the CSRF cookie and the CSRF header of the request are matching:

csrfserver

Server workflow

Note that some JavaScript frameworks like AngularJS implements the client worflow out of the box; see Cross Site Request Forgery (XSRF) Protection

Java implementation of “double submit cookie” pattern

The proposed implementation is on the form of a (Java) Servlet filter and can be found here: GenericCSRFFilter GitHub.

In order to use the filter, you must define it into you web.xml file:

<filter>
   <filter-name>CSRFFilter</filter-name>
   <filter-class>com.github.adriancitu.csrf.GenericCSRFStatelessFilter</filter-class>
<filter>

<filter-mapping>
   <filter-name>CSRFFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

 

The filter can have 2 optional initialization parameters: csrfCookieName representing the name of the cookie that will store the CSRF token and csrfHeaderName representing the name of the HTTP header that will be also contains the CSRF token.

The default values for these parameters are “XSRF-TOKEN” for the csrfCookieName and “X-XSRF-TOKEN” for the csrhHeaderName, both of them being the default values that AngularJS is expecting to have in order to implement the CSRF protection.

By default the filter have the following features:

  • works with AngularJS.
  • the CSRF token will be a random UUID.
  • all the resources that are NOT accessed through a GET request method will be CSRF protected.
  • the CSRF cookie is replaced after each non GET request method.

How it’s working under the hood

The most of the functionality is in the GenericCSRFStatelessFilter#doFilter method; here is the sequence diagram that explains what’s happening in this method:

doFilter method sequence diagram

doFilter method sequence diagram

The doFilter method is executed on each HTTP request:

  1. The filter creates an instance of ExecutionContext class; this class is a simple POJO containing the initial HTTP request, the HTTP response, the CSRF cookies (if more than one cookie with the csrfCookieName is present) and implementation of the ResourceCheckerHook , TokenBuilderHook and ResponseBuilderHook .(see the next section for the meaning of this classes).
  2. The filter check the status of the HTTP resource, that status can be:MUST_NOT_BE_PROTECTED, MUST_BE_PROTECTED_BUT_NO_COOKIE_ATTACHED,MUST_BE_PROTECTED_AND_COOKIE_ATTACHED (see ResourceStatus enum) using an instance of ResourceCheckerHook.
  3. If the resource status is ResourceStatus#MUST_NOT_BE_PROTECTED
    ResourceStatus#MUST_BE_PROTECTED_BUT_NO_COOKIE_ATTACHED then
    the filter creates a CSRF cookie having as token the token generated by an instance of TokenBuilderHook.
  4. if the resource status ResourceStatus#MUST_BE_PROTECTED_AND_COOKIE_ATTACHED
    then compute the CSRFStatus of the resource and then use an instance of ResponseBuilderHook to return the response to the client.

How to extend the default behavior

It is possible to extend or overwrite the default behavior by implementing the hooks interfaces. All the hooks implementations must be thread safe.

  1. The ResourceCheckerHook is used to check the status of a requested resource. The default implementation is DefaultResourceCheckerHookImpl and it will return ResourceStatus#MUST_NOT_BE_PROTECTED for any HTTP GET method, for all the other request types, it will return [email protected] ResourceStatus#MUST_BE_PROTECTED_BUT_NO_COOKIE_ATTACHED if any CSRF cookie is present in the query or ResourceStatus#MUST_BE_PROTECTED_BUT_NO_COOKIE_ATTACHED otherwise.The interface signature is the following one:
    public interface ResourceCheckerHook extends Closeable {
        ResourceStatus checkResourceStatus(ExecutionContext executionContext);
    }  
  2. The TokenBuilderHook hook is used to generate the token that will be used to create the CSRF cookie. The default implementation  is DefaultTokenBuilderHookImpl and it uses a call to UUID.randomUUID to fetch a token. The interface signature is the following one:
    public interface TokenBuilderHook extends Closeable {
        String buildToken(ExecutionContext executionContext);
    }
  3. The ResponseBuilderHook is used to generate the response to the client depending of the CSRFStatus of the resource. The default implementation is DefaultResponseBuilderHookImpl and it throws a SecurityException if the CSRF status is CSRFStatus#COOKIE_NOT_PRESENT, CSRFStatus#HEADER_TOKEN_NOT_PRESENT or CSRFStatus#COOKIE_TOKEN_AND_HEADER_TOKEN_MISMATCH. If the CSRF status is CSRFStatus#COOKIE_TOKEN_AND_HEADER_TOKEN_MATCH then the old CSRF cookies are deleted and a new CSRF cookie is created. The interface signature is the following one:
    public interface ResponseBuilderHook extends Closeable {
        ServletResponse buildResponse(ExecutionContext executionContext,
                                      CSRFStatus status);
    }
    

The hooks are instantiated inside the GenericCSRFStatelessFilter#init method using the ServiceLoader Java 6 loading facility. So if you want to use your implementation of one of the hooks then you have to create a  META-INF/services directory that contains a text file whose name matches the fully-qualified interface class name of the hook that you want to replace.

Here is the sequence diagram representing the hooks initializations:

initmethod

Book review : Practical Anonymity: Hiding in Plain Sight Online

This is a review of the Practical Anonymity: Hiding in Plain Sight Online book.

Conclusion

This is not a technical book about the inner workings of Tor or Tails and I think a better title would be “How to use Tor and Tails for dummies”. Almost all the information present in the book can be found in the official documentation, the only positive point is that all the needed information is present in one single place.

Chapter 1. Anonymity and Censorship Circumvention

This first chapter is an introduction to what is on-line anonymity, why (the on-line anonymity ) is important for some people and how it can be achieved using Tor. The chapter contains also the fundamentals of how Tor is working, what it can do to on-line anonymity and some advises about how it can be used safely.

Chapter 2. Using the Tor Browser Bundle

The chapter is presenting the TBB (Tor Browser Bundle) in detail. The TBB is composed of three components; Vidalia which is the control panel for Tor, the Tor software itself and Mozilla Firefox browser. Each of this tree components are described from the user point of view, each of the possible configuration options are presented in detail.

Chapter 3. Using Tails

Tails is a is a Linux distribution that includes Tor and other softwares to provide an operating system that enhances privacy. The Tails network stack has been modified so that all Internet connectivity is routed through the Tor network.

In order to enhance privacy, Tails is delivered with the following packages :

  • Firefox
  • Pidgin
  • GNU Privacy Guard
  • Metadata Anonymization Toolkit
  • Unsafe Web Browser

Detailed instructions are presented about how to create a bootable DVD and a bootable USB stick and how to run and configure the operating system. The persistent storage feature of Tails is presented in detail so that the reader can understand what are the benefits and the drawbacks.

Chapter 4. Tor Relays, Bridges and Obfsproxy

The chapter is about how the Tor adversaries can disrupt the network and how the Tor developers are trying to find new technique to workaround these disruptions.

One way to forbid to the user the access to the Tor network is to filter the (nine) Tor directory authorities, that are servers that distribute information about active Tor entry points. One way to avoid this restriction is the use of Tor bridge relays. A bridge relay is like any other Tor transit relay, the  only difference is that it is not publicly listed and it is used only for entering the Tor network from places where public Tor relays are blocked. There are different mechanisms to retrieve the list of this bridge relays, like a web page on the Tor website or emails sent by email.

Another way to disrupt the Tor network is to filter the Tor traffic knowing that the Tor protocol packages have a distinguished signature. One way to avoid the package filtering is to conceal the Tor packages in  other kind of packages. The framework that can be used to implement this kind of functionality is called Obfsproxy (obfuscated proxy). Some of the plug-ins that are using Pbfsproxy: StegoTorus, Dust, SkypeMorph.

Chapter 5. Sharing Tor Resources

This chapter describes how a user can share his bandwidth becoming a Tor bridge relay, a Tor transit relay or a Tor exit relay. Detailed settings descriptions are made for each type of relays and also the incurred risks for the user.

Chapter 6. Tor Hidden Services

A (Tor) hidden service is a server that can be accessed by other clients within the anonymity network, while the actual location (IP address) of the server remains anonymous. The hidden service protocol is briefly presented followed by how to set up a hidden service. For the set up a hidden service the main takeaways are:

  • install Tor and the service that you need on a VM.
  • run the VM on a VPS (virtoual private server)  hosted  in a country having privacy-friendly legislation in place.
  • the VM can/should be encrypted, be power cycled and that has no way to know what IP address or domain name of the computer on which it is running.

Chapter 7. Email Security and Anonymity practices.

This last chapter is about the email anonymity in general and how the use of Tor can improve the email anonymity. The main takeaways :

  • choose a email provider that do not require another email address or a mobile phone.
  • choose an email provider that supports HTTPS.
  • encrypt the content of your emails.
  • register and connect to the email box using ALWAYS Tor.

 

 

(My) BruCON 2016 notes (3)

Here are my quick notes from the BruCON 2016 conference. All the slides can be found here.

NO EASY BREACH:Challenges and Lessons Learned from an Epic Investigation bruCon

The attack started with a phishing email; the attack compromised more that 2 000 systems, 50 000 emails.

How the attack took place:

1. fast-paced attacher

  • 10-25 systems infected every day.
  • the attacker steal information every day.

response

  • develop indicators to aid triage.
  • focus on : lateral movements, pivoting, recon, new tools or back-doors.
  • streamlined documentation.

lessons learned

  • be fast and flexible.

2. stealthy attacks

  • used anti-forensics techniques to hide endpoint and network activity.
  • altered communication scheme + strong crypto.
  • mass activity to obscure the real target.
  • data theft using only legitimate us-based services – gmail, google drives, one drive.

response

  • maximize the utility of trace forensics artifacts.
  • some attacker behavior recovered from sdelete.
  • took time and patience to filter out the network noise.
  • deployed additional open-source tech

lessons learned

  • improve visibility and don’t stop looking.
  • map attacker activity ti potential data sources.
  • network times provides reliable chronology.

3. rapidly evolving tactics

  • seven unique persistence mechanism.
  • seven distinct back-door families.
  • minimal re-use of meta-data commonly tracked and shared as indicator.

response

  •  fought to keep network visibility on all malware families.
  • spent time analyzing system with unknown activity.
  • create indicators for every stage of attack life-cycle.
  • develop flexible & resilient indicators

lessons learned

  • enhance and test your best indicators even when they’re working.

4. advanced attack techniques

  • attacker leveraged PowerShell.
  • used Windows Management Instrumentation.
  • attacker used Kerberos tickets attacks which made tracking lateral movement difficult.

response

  • searched for WMI persistence.
  • identified evidence of attacker code in WMI repository.
  • parsed out embedded scripts and malware.
  • updated the environment to power shell 3.0 and enabled logging.
  • turned attacker power shell usage from a threat to a benefit by logging and iocs to made findings attacker activity much easier.
  • worked around Kerberos attacks: looked for remote Kerberos logons around the time of attacker activity.

Hacking KPN: Lessons from the trenches

The presentation was about 3 different vulnerabilities discovered by the kpn read team.

  1. vulnerability linked to the Java de-serialisation vulnerability.
    1. the kpn team did a java deserialization burp plug-in fork
  2. Citrix Netscaler
    1. Netscaler login vulnerabiilty
  3. reverse-engineering cryptography from binary

New Adventures in Active Defense, Offensive Countermeasures and Hacking Back

The idea was that the security industry are doing the same things over and over again, very often as a defender we build very static walls. So the presenter propose to an “active defense”:

Active defense is not about :

  • hacking back
  • about one technical solution
  • revenge

Active defense is about:

  • have a range of solutions.

All the proposed solutions and demos are part of the advanced defense harbinger distribution which is a Linux distribution based on Ubuntu LTS that it comes with many tools aimed at active defense pre-installed and configured. Some demos of the following components:

  • weblabyrinth
  • honey ports
  • honey badger
  • jarcombiner

(My) BruCON 2016 notes (2)

Here are my quick notes from the BruCON 2016 conference. All the slides can be found here.

What Does the Perfect Door or Padlock Look Like?bruCon

The talk was about how (some) doors and padlocks can be easily opened. The presentation was full of videos and explanatory schemes. For the doors the following parts can be attacked:

  • hinge removal – to fix, use jam pins
  • the latch
  • the inside handle
  • key boxes
  • edge baps – request to exit sensors
  • the bottom gap
  • the door frame

Anti-Forensics AF

The presentation contained the following topics:

  • memory anti-forencics
    • the goal is to inhibit the acquisition and analysis
    • for windows, removing PE header from disk (once the executable is loaded in memory).
    • for windows, zero the header from disk (once the executable is loaded in memory).
    • for linux, remove the EMF header
    • for linux, zero the header (memeset)
  • android anti-forestics
    • use encryption to protect.
    • power down the device.
    • leverage device sensors; foe ex: if the phone is moving, then shut down the device
  • fun with sd cards
    • demo of the SDTool tool that modifies the SD card firmware to write/or not the card or in memory.

Esoteric Web application vulnerabilities

The sql injection vulnerability is dead due to the massive use of the ORM frameworks, the same for the XSS injections due to the mvc, templates and default HTML So, as a hacker you must find new vulnerabilities; here are 5 (esoteric) vulnerabilities:

  1. aggressive input decoding; nosql injection using ruby on rails and MongoDB
  2. call me to verify my identity; try to hack the phone activation procedure for a 2 FA functionality.
  3. password reset implementation feature; try to hack the password reset feature for a 2 FA
  4. hack around the usage of the Paypal IPN protoco
  5. just missed that one; it happen even to the best of us.

Scraping Leaky browsers for Fun and Password

The idea is to retrieve passwords stored by the browsers (in RAM) by scrapping the RAM content. Do to this a plug-in to Volatility framework was created (the plug-in will be available soon on GitHub).

The best browser is Chrome with 67% chances to expose the passwords; the worst browser is Firefox with 81% changes to expose the passwords.

Vendors response to this findings; Microsoft created a CVE and the path will be pushed in October/November, Google and Mozilla are denying that’s a real issue.

 

(My) BruCON 2016 notes (1)

Here are my quick notes from the BruCON 2016 conference. All the slides can be found here.

Keynote –  inventing defensivebruCon

The keynote was quite entertaining mainly because it used references to the Greek and Babylonian mythology but on the other side  it was very difficult to really understand the message and the ideas that the presenter tried to promote.
But here some ideas that I was able to catch:

  • assume compromise
  • business people do not understand the security goals
  • perimeter defense; you have to win every time; one single mistake and the perimeter can be breach.
  • attackers are using the speed; the defenders have never the initiative.

Security through design

The presenter believes that the security is seen by the casual user/client as a burden. The security peoples should try to understand why the users try to circumvent the security, try to understand how the peoples are working and must try to adapt the security to fit the user needs.

The possible solutions are not from the IT world; try to apply the design thinking. A good design solution should have the following properties:

  •  is innovative
  • makes a product useful
  • makes a product understandable
  • is long-lasting
  • is unobtrusive

Some examples of products/companies that are trying to understand better the client: 2g Tuesday at Facebook

Building a Successful Internal Adversarial Simulation Team

The problems with the security testing today :

  • limited metrics
  • increase technical debt.
  • gives limited experience.

Another major problem is that the read team and blue team are acting independently, do not really share knowledge.

The speakers proposed some solutions to this problem; some of the interesting points that I was able to catch:

  • predict the likelihood of successful attacks before they happen.
  • creation of an information sharing platform and knowledge base.
  • assemble your team and tools
  • create defensive measurements/metrics.

ElasticSearch:How to enable scripting on the embedded server

The goalelastic

In this ticket I will present all the required steps in order to enable the scripting on an embedded elasticsearch server. I will not explain how to create and use an embedded server but if you need more infos you can read this ticket Embedded Elasticsearch Server for Tests.

If you execute a script within the embedded server the following exception will be thrown;

Caused by: java.lang.IllegalArgumentException: script_lang not supported [xxxxx]
    at  org.elasticsearch.script.ScriptService.getScriptEngineServiceForLang(ScriptService.java:211)

 Code changes

 The easiest way to create an embedded server is the following one:

 Node node = NodeBuilder.nodeBuilder()
              .local (true)
              .settings(
               //add settings here
               )
              .node ();

The problem with this approach is that the NodeBuilder.node() method it will create a node class with an empty list of plug-ins; see the NodeBuilder.node code:

   /*
    * Builds the node without starting it.
    */
    public Node build() {
        return new Node(settings.build());
    }
    //Node(Settings) constructor
     /**
     * Constructs a node with the given settings.
     *
     * @param preparedSettings Base settings to configure the node with
     */
     public Node(Settings preparedSettings) {
        this(InternalSettingsPreparer
                .prepareEnvironment(preparedSettings, null),
             Version.CURRENT,
             Collections.<Class<? extends Plugin>>emptyList());
     }

In order to create a node having a list of desired plug-ins the second constructor of the Node class should be used:

protected Node(
                Environment tmpEnv, 
                Version version, 
                Collection<Class<? extends Plugin>> classpathPlugins)

The problem with this (second) constructor is that it is protected so we will need to extend the Node class to be able to use the protected constructor and we will need to extend also the NodeBuilder class in order to use the new Node class.

And here is the code:

  //PluginNode class 
  private static class PluginNode extends Node {
      public PluginNode(Settings preparedSettings, List<Class<? extends Plugin>> plugins) {
         super(InternalSettingsPreparer.prepareEnvironment(preparedSettings, null), Version.CURRENT, plugins);
      }
  }

  //PluginNodeBuilder class
  public class PluginNodeBuilder extends NodeBuilder {
        private List<Class<? extends Plugin>> plugins = new ArrayList<>();
        
        public PluginNodeBuilder() {
            super();
        }
        //new method to add plug-ins       
        public PluginNodeBuilder addPlugin(Class<? extends Plugin> plugin) {
            plugins.add(plugin);
            return this;
        }

        @Override
        //use the new PluginNode to build a node 
        public Node build() {
            return new PluginNode(settings().build(), plugins);
        }
    };

And how to use the new node builder:

 Node node = new PluginNodeBuilder()
                .addPlugin(ExpressionPlugin.class)
                .addPlugin(GroovyPlugin.class)
                .local (true)
                .settings(
                 //add settings here
                 )
                .node ();

Enable scripting feature

Using the previous Java code it will not be sufficient to execute the scripts; you must also use the right settings at the server creation and add the (Maven) dependencies to your classpath.

Server settings

 Node node = new PluginNodeBuilder()
                .addPlugin(ExpressionPlugin.class)
                .addPlugin(GroovyPlugin.class)
                .local (true)
                .settings (Settings.settingsBuilder ()
                     ...
                     //this is common for all languages
                     .put ("script.inline", true)
                     //this are the settings for the groovy language
                     .put ("script.engine.groovy.inline.mapping", true)
                     .put ("script.engine.groovy.inline.search", true)
                     .put ("script.engine.groovy.inline.update", true)
                     .put ("script.engine.groovy.inline.plugin", true)
                     .put ("script.engine.groovy.inline.aggs", true)
                      
                     //this are the settings for the expression language
                     .put ("script.engine.expression.inline.mapping", true)
                     .put ("script.engine.expression.inline.search", true)
                     .put ("script.engine.expression.inline.update", true)
                     .put ("script.engine.expression.inline.plugin", true)
                     .put ("script.engine.expression.inline.aggs", true)

If you more details about all the possible settings options you can look to the ElasticSearch Scripting documentation.

Maven dependencies

For the expression language:

       <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-expressions</artifactId>
            <version>5.5.2</version>
            <scope>compile</scope>
        </dependency>

       <dependency>
            <groupId>org.elasticsearch.module</groupId>
            <artifactId>lang-expression</artifactId>
            <version>2.2.0</version>
            <scope>compile</scope>
        </dependency>

For the groovy language:

<dependency>
    <groupId>org.elasticsearch.module</groupId>
    <artifactId>lang-groovy</artifactId>
    <version>2.3.2</version>
</dependency>

(My) OWASP Belgium Chapter meeting notes

CloudPiercer: Bypassing Cloud-based Security Providers (by Thomas Vissers, iMinds-DistriNet-KU Leuven)

The goal of the presentation was to show how the CBSP (Cloud Based Security owasp_logoProviders) are protecting the applications and how this protections can be circumvented.

The most common attacks on the web applications are the DDOS.

2 types of DDOS attacks:

  • volumetric attacks – no more network bandwidth
  • application level attacks – servers are targeted

How the CBSP are protecting the web application ?

CBSP reroute and filter the customer traffic through their cloud (see the following picture).

cbsp

The secrecy of the origin server IP address is crucial because, (if discovered) the server can be hit directly and the CBSP protection is useless.

Vulnerabilities, or how the origin server IP can be found

  1. subdomains – administrators can create a specific subdomain, such as origin.example.com, that directly resolves to the origin’s IP address; they need it in order to easily connect to the server for non http services (SSH, FTP)
  2. dns records – other DNS records might still reveal your origin.; ex TXT records, MX records
  3. SSL certificates – it concerns the https connection between CBSP and origin server. If an attacker is able to scan all IP addresses and retrieve all SSL certificates, he can find the IP addresses of hosts with certificates that are associated with the domain he is trying to expose.
  4. IP history – companies constantly track DNS changes
  5. sensitive files on the (target) web application; error messages, files containing IP information
  6. outbound connections – force the origin to connect to you.

Defenses/what can i do to protect ?

  • request a new ip address when activating the CBSP.
  • block all non-CBSP requests with your firewall
  • choose a CBSB that assignes a dedicated IP address to you
  • use cloudpiercer.org to scan your website

If interested you can read Bypassing Cloud-based Security Providers – DistriNet – KU Leuven

Hackers! Do we shoot or do we hug? (by Edwin van Andel, Zerocopter)

For me the presentation was a (very) funny pleading for an ethical hacking.