Bypass CSRF Protection via XSS

In this post I will show why anti-CSRF tokens are useless as soon as there is an XSS vulnerability in the target site. This post contains all the example scripts necessary to reproduce bypassing CSRF protection via XSS vulnerabilities. The code is meant for educational purposes only.

Basic Terms: CSRF and XSS

CSRF means Cross-Site Request Forgery. The idea is to get a user that is logged in at a website to perform actions on that site they do not actually want to perform. This can be achieved by getting the victim to visit a website (possibly – but not necessarily – owned by the attacker) that contains specially crafted HTML code created by the attacker. CSRF is possible with POST as well as GET requests (although as per REST, GET requests shouldn’t actually change data on the server).

Anti-CSRF token is the recommended way to prevent CSRF. A one time token is stored in the session as well as the form when creating it, and when the form is submitted, the submitted token is compared to the session token. If they match, there is no CSRF attack.

XSS means cross-site scripting, and it allows an attacker to execute arbitrary JavaScript in the victims browser in the context of the vulnerable website.

Continue

MongoDB: NoSQL Injection & Security

A list of resources about NoSQL injection in general and PHP and MongoDB security specifically.

Intro: NoSQL Databases

NoSQL databases such as MongoDB are used more and more, but there isn’t a lot of information about the security of specific NoSQL databases or the security of NoSQL in general. The direction it seems to be going is: It’s not SQL, so SQL injection is not possible, so it is secure. This is of course not true at all. The damage that can be achieved with NoSQL injections does seem to be smaller than that of SQL injection, but that does not mean that developers should not care about it. Continue

Java Timing Code: Compare Execution Times of Methods

Often times, you will have two Java functions, and you will want to know which one performs better. You can use this Java class to time multiple methods to find out which one is faster.

Example Usage: Java Timing Code

Let’s say you have these two functions and want to know which one is faster:

    public static String function1(String i) {
        return i + i;
    }

    public static String function2(String i) {
        StringBuilder sb = new StringBuilder();
        sb.append(i);
        sb.append(i);
        return sb.toString();
    }

Here is how you would use my timing class:

    public static void simpleTimingTest() throws Exception {
        Timing t = new Timing();

        /*
        The timing function will run the tests in chunks.
        For each chunk, the same input will be used.

        Input will be gathered via the passed IntFunction. The timing method will
        pass the current index (going from 0 to amountRunsPerChunk) to it and will expect
        any return of the defined type.
        */

        IntFunction<string> inputProvider = i -> String.valueOf(i);

        /*
        The add method expects two functions: the above mentioned input provider,
        as well as a function which accepts the output from the input provider as input
        and applies it to the function which will be timed.
        */

        t.add((String s) -> function1(s), inputProvider, "function1 ");
        t.add((String s) -> function2(s), inputProvider, "function2 ");

        t.time(true); // true: force test (otherwise, time might throw an exception
                      // if it suspects that there isn't enough memory)
        t.output(s -> System.out.println(s), Timing.Sort.ASC);
    }

You can also do more complex things with it:

    public static void predefinedInputTimingTest() throws Exception {
        Timing t = new Timing();
        /*
        The input doesn't have to be generated using the passed index, you could
        also use predefined input to time your functions:
        */

        String[] input = new String[]{"input1", "another input", "more input"};
        IntFunction</string><string> inputProvider = i -> input[i % input.length];
        t.add((String s) -> function1(s), inputProvider, "function1 ");
        t.add((String s) -> function2(s), inputProvider, "function2 ");

        /*
        You can decide what should be reported when timing finished:
        */

        t.setReport(EnumSet.of(Timing.Report.NAME, Timing.Report.MEAN));
        t.setAmountChunks(1_500);
        t.setAmountRunsPerChunk(2_500);
        t.time(true, s -> System.out.println(s)); // pass String -> String function to report debug information
        t.output(s -> System.out.println(s), Timing.Sort.ASC);
    }
Continue

Refactoring Simple Boolean Checks in if-Statements

How to refactor simple boolean checks in if statements and avoid bad practices.

This is the first post out of a number of posts dealing with refactoring. This particular post is aimed at beginners, but further posts will contain somewhat more advanced concepts.

The concepts presented here can be used in a lot of programming languages, but the article is written with Java, PHP, and JavaScript in mind.

For one-liners, the general formating will look like this:
some expression => better expression doing the same thing

Check if a Value is True or False

if (A == true) => if (A)
if (A == false) => if (!A)

This is something I see a lot of beginners do. It’s not the end of the world, but it does lead to harder to read code, possible bugs, and expresses a lack of deeper understanding.

Empty if-Statement

if(A) {
} else {
    // do the thing
}

This can be written a lot cleaner by negating the condition:

if(!A) {
    // do the thing
}

Check Multiple Values, Some of which are the Same

if ((A && B) || (A && C) || (A && D)) => if (A && (B || C || D))

This is possible because AND and OR are distributive.

Simplify Complex if Condition

If you are not that well versed with boolean logic, you should read up on negation and boolean algebra in general (especially de Morgan and distributivity).

Just a couple of examples of how complex if conditions can be simplified using boolean logic:

  • !(!A || !B || !C) => A && B && C
  • A && (A || B)) => A
  • (A || B) && (!A || C) && (B || C) => (A || B) && (!A || C)

Bin Packing Algorithm (Java)

In this post I will present example Java code for solving the Bin Packing Problem. I will not go into what exactly Bin Packing is, as there are enough websites that do a good job describing it. As always, wikipedia is a good start to get a general overview: Wikipedia Bin Packing Problem.

Bin Packing: Brute Force Solution

To check all possible solutions for the bin packaging problem (brute force), a recursive approach can be used: Iterate over all bins, try to put the current item in the bin and – if it fits – call the same method with the next item.

    /**
     * bruteforce solution to bin packing problem.
     *
     * @param in list of items to be packed
     * @param currentPosition position in input list
     */

    private void bruteforce(List<Integer> in, int currentPosition) {
        if (currentPosition >= in.size()) { // reached last item, done with this iteration
            int filledBins = getFilledBinsCount();
            if (filledBins < currentBestSolution) { // is this solution better than the current best?
                currentBestSolution = filledBins; // then save it
                currentBestBins = deepCopy(bins);
            }
            return;
        }
        // iterate over bins
        Integer currentItem = in.get(currentPosition);
        for (Bin bin : bins) {
            if (bin.put(currentItem)) {
                bruteforce(in, currentPosition + 1);
                bin.remove(currentItem);
            } // else: item did not fit in bin, ignore
        }
    }

Bin Packing: First Fit Decreasing Algorithm

The Bin Packing Problem can also be solved by an algorithm, called first fit decreasing. Implementing the first fit decreasing algorithm is quite simple. Just sort your input (descending), and then iterate over it, packing each item into the first bin it fits into.

    /**
     * first fit decreasing algorithm for bin packing problem
     */

    public int firstFitDecreasing() {
        Collections.sort(in, Collections.reverseOrder()); // sort input by size (big to small)
        bins.add(new Bin(binSize)); // add first bin
        for (Integer currentItem : in) {
            // iterate over bins and try to put the item into the first one it fits into
            boolean putItem = false; // did we put the item in a bin?
            int currentBin = 0;
            while (!putItem) {
                if (currentBin == bins.size()) {
                    // item did not fit in last bin. put it in a new bin
                    Bin newBin = new Bin(binSize);
                    newBin.put(currentItem);
                    bins.add(newBin);
                    putItem = true;
                } else if (bins.get(currentBin).put(currentItem)) {
                    // item fit in bin
                    putItem = true;
                } else {
                    // try next bin
                    currentBin++;
                }
            }
        }
        return bins.size();
    }

Download Source Code for Bin Packing Problem

Java Bin Packing Source Code [3.9 kB]