Resurrecting a PhantomReference
Jan 20, 2015In this post, you'll learn about Java necromancy: how to resurrect objects back from the dead. We will abuse a recently fixed security bug in the JDK to trick the garbage collector to get ahold of an object to which no living object should have a connection.
In essence, the garbage collector collects all unreachable objects; objects to which there are no references anymore. But there are multiple levels of reachability, types of references and phases in an object's dying process. Before we start resurrecting phantoms, let's briefly explore some background and the history of resurrection in Java.
Weakness
A WeakReference is a pointer to an object that does not prevent it from being garbage collected. When the garbage collector determines that an object is weakly reachable (only reachable through WeakReferences), it also clears those references, severing their last link to the world of the living. To notify the owner of the reference it then adds the WeakReference to its ReferenceQueue; its queue of death records. For example WeakHashMap, which uses WeakReferences internally, polls its queue to expunge stale entries from its hash table.
Surprisingly, even after a WeakReference has been enqueued, the object it pointed to may still be revived: in the same dying phase as the enqueuing, the object is marked for finalization. That means its finalize() method will be called. That usually temporarily but possibly permanently revives the object, because the body of the finalize method has access to this. This is a well known documented flaw, and one of the reasons you should avoid finalization whenever you can.
In short, the purpose of finalization is to signal that an object is dying, but ironically that same signal resurrects it from its weak death.
Phantoms
An object is another step closer to death when it becomes phantom reachable. That means it's not strongly, softly or weakly reachable, any finalization has already happened, but there's still a PhantomReference to it. Just like for WeakReferences, if the garbage collector determines that an object is phantom reachable, it adds it to the PhantomReference's ReferenceQueue. For example direct ByteBuffers rely on the queuing of phantom references to free native memory. This is supposed to mean that the object will stay dead: it should never become reachable again by Java code.
Side note: One difference with an enqueued weak reference is that it is not cleared: the PhantomReference still has a reference to the object after enqueuing, but there's no honest way to get it out: PhantomReference.get() always returns null. You could use reflection to access the Reference.referent field, but if we go that way we can throw all guarantees out the window. It's cheating, like changing the matrix, and not allowed by the JVM if a security manager is enabled.
Resurrection theory
- So, where can an honest necromancer get ahold of a dead object around here?
Remember, we could resurrect a dying weakly reachable object only because we got help from our omniscient friend the garbage collector. He's not constrained by reachability when calling finalize() to signal a presumed impending death. We can't use that same trick here, but there's a similar signal from the garbage collector that we can abuse: the ReferenceQueue,
to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected (from its javadoc).
Loose translation: it's magically given references of our choice from our helpful friend after stuff becomes hard to reach.
- Thank you mr Garbage Collector, you just performed resurrection by appending the appropriately reachable reference.
- GC: No, I only append the phantom, not the actual referred dead object.
And here comes the twist...
- Ow, I don't care about the referred object, that's just a decoy. It's the phantom itself we're resurrecting.
- Nice try, but I'm not that easily tricked: I'd garbage collect any unreachable phantom before I'd consider adding it to its queue. Dead phantoms stay dead.
- Well, it's not quite dead yet, it's still dying. It's not unreachable; it's phantom reachable. A phantom reachable phantom!
*GC mind blown*
So this allows you to trick the garbage collector into resurrection a PhantomReference. The phantom is allowed to bring its friends: it can have ordinary, strong, references to any other object that will then be resurrected along with it.
Taking a step back, our goal was to get ahold of an object after some victim PhantomReference declared it dead. We do that by resurrecting another associated PhantomReference that in turn also is only phantom reachable. That's a complicated dance of three phantoms; the diagram below makes this choreography a bit easier to follow.
Resurrection in practice
Let's look at a concrete resurrection in action of a DirectByteBuffer. A DirectByteBuffer directly accesses native memory which is freed when its Cleaner (a special kind of PhantomReference) would be enqueued. That gives us a use-after-free vulnerability.
When the garbage collector realizes that the objects in gray here are only phantom reachable he calls the Cleaner and enqueues them in their queue; adding the reference in green. That makes the ResurrectedReference and thereby the DirectByteBuffer strongly reachable again. If we then access the buffer, we're accessing freed memory...
Here's the code for that:
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
/**
* Acts like a reference that's weaker than a phantom reference, but
* allows you to revive the referent after it becomes phantom reachable.
*/
public class Necromancer<T> {
/** The queue which gets the ResurrectedReference enqueued */
private final ReferenceQueue<Object> q = new ReferenceQueue<>();
/** Making ResurrectedReference phantom reachable (instead of unreachable) */
private final PhantomReference<ResurrectedReference<T>> pr;
public Necromancer(T o) {
ResurrectedReference<T> toBeResurrected = new ResurrectedReference<>(o, q);
pr = new PhantomReference<>(toBeResurrected, new ReferenceQueue<>());
}
public T waitForDeathAndResurrect() {
ResurrectedReference<T> ref;
do {
System.gc();
ref = (ResurrectedReference<T>) q.poll();
} while (ref == null);
return ref.o;
}
static class ResurrectedReference<T> extends PhantomReference<Object> {
/** Strong reference to object to resurrect along with this */
private final T o;
public ResurrectedReference(T o, ReferenceQueue<Object> q) {
super(new Object() /* decoy */, q);
this.o = o;
}
}
}ByteBuffer getResurrectedByteBuffer(int size) {
Necromancer<ByteBuffer> necromancer =
new Necromancer<>(ByteBuffer.allocateDirect(size));
return necromancer.waitForDeathAndResurrect();
}Vulnerability info
Timeline: Alexey Makhmutov sent this as a puzzle a la "try to break this PhantomReference" in June 2014. I reported it to Oracle after solving it and realizing it was a security vulnerability. Oracle, released a Critical Patch Update for this today (2015-01-20).
Thanks Alexey, and sorry for ruining your puzzle with this report.
Exploitability: Here's a proof-of-concept crash. Given the nature of the bug, it can likely be exploited to execute arbitrary code.
This is CVE-2015-0395
.Conclusion
Finalization is resurrection because it hands you back the dead object to finalize it. PhantomReferences and their queue prevent that by giving you a different object instead, an indirect reference. But they forget to check if that reference also doesn't happen to be in the middle of its own death scene.
What does this mean for Java users and developer? Nothing at all. If you're not running hostile Java code on your machine and relying on the Java sandbox for protection, you have nothing to worry about. If you do, e.g. if you're running Java applets or running a multi-tenant application server, then you should install the latest Java update; as you should always be doing already anyways. There probably are a bunch of worse vulnerabilities in the same update, as usual.
Follow-up: how it was fixed (twice)
This section was added in 2026-11, with help from Claude. Based on my records, openjdk bug reports, and digging through git history, painting a full picture of the aftermath of the discovery of this vulnerability.
It took two attempts to fix this vulnerability, and years before the underlying PhantomReference resurrection was gone completely.
First attempt: cleaners as an even weaker kind of reference
To understand the fixes, you need to know what the garbage collector does with a phantom reference whose referent is about to die: it doesn't clear the reference. Instead it keeps the referent alive (marks it, and everything reachable from it, as live) until the reference has been processed. That's exactly where the necromancy comes from: keeping our ResurrectedReference alive like that is what gets it added to its own queue.
The fix in the January 2015 update (8047125: (ref) More phantom object references, in 8u31) taught the JVM to recognize sun.misc.Cleaner as its own type of reference, and to handle cleaners in a separate step, after all ordinary PhantomReferences. So cleaners became an even weaker type of reference than phantom references. In the attack above, by the time the cleaner of the DirectByteBuffer is looked at, the garbage collector has already kept the ResurrectedReference (and with it the buffer) alive on behalf of our ordinary PhantomReference. The buffer then no longer looks dead, so its cleaner doesn't run and its memory isn't freed.
Ordinary PhantomReferences could still be resurrected, but that no longer freed any memory from under us.
Why that wasn't enough
That fix relies on the outer reference of the necromancer being an ordinary PhantomReference. If the outer reference is a Cleaner too, then both cleaners are handled in the same step: the garbage collector decides that both their referents are dead before it keeps either of them alive. The buffer's cleaner runs and frees the memory, and our ResurrectedReference, kept alive through the other cleaner, is still added to its queue. We're back to a use-after-free.
sun.misc.Cleaner is an internal class that untrusted code isn't allowed to use directly. But it doesn't need to: some code that it is allowed to use creates cleaners for it. javafx.beans.property.adapter.JavaBeanObjectProperty uses a Cleaner with the property itself as referent, and a property holds strong references to its listeners. So creating such a property and adding a listener that holds on to our ResurrectedReference makes the ResurrectedReference reachable only through a cleaner:
JavaBeanObjectProperty<?> property =
JavaBeanObjectPropertyBuilder.create().bean(bean).name("foo").build();
property.addListener(new MyListener(toBeResurrected));With that replacing the PhantomReference in the Necromancer, the DirectByteBuffer could be resurrected again on a fully patched JDK. I reported that two days after the first fix was released.
Second fix: clear instead of keeping alive
The second fix (8071931: Return of the phantom menace, in 8u45, released in April 2015) is a one-word change in the garbage collector: for cleaners, the referent is now cleared instead of kept alive. Clearing the referent means nothing behind it gets marked as live, so whatever was only reachable through a cleaner stays dead, and can no longer end up in a queue. It was only applied to cleaners, because the Java 8 specification said that phantom references are not automatically cleared, so ordinary PhantomReferences were left unchanged.
Clearing phantom references for everyone
The more fundamental solution was to change that specification: JDK-8071507: (ref) Clear phantom reference as soft and weak references do. Since Java 9, all phantom references are cleared when they are enqueued, just like weak references, so that the referent can't be reached anymore. That made cleaners' separate step unnecessary, and it was removed again (JDK-8143847). This change was eventually also backported to Java 8, in 8u352 (October 2022). That is the first Java 8 version where the original Necromancer can no longer resurrect anything; up to 8u345 it still works.
Timeline
| Date | Event |
|---|---|
| 2014-06-11 | Alexey's challenge to try to break a PhantomReference is shared in a small group |
| 2014-06-13 | I solved the challenge by abusing what I then realize is a security bug. I reported the vulnerability to Oracle |
| 2014-09-26 | First fix committed: 8047125, processing cleaners separately, after phantom references |
| 2015-01-20 | First fix released in the January 2015 Critical Patch Update (8u31); assigned CVE-2015-0395; this post published |
| 2015-01-22 | I reported that the fix was incomplete, using a cleaner from JavaBeanObjectProperty |
| 2015-01-23 | JDK-8071507 opened: clear phantom references, like soft and weak references |
| 2015-02-09 | Second fix committed: 8071931: Return of the phantom menace, clearing the referent of cleaners |
| 2015-04 | Second fix released in the April 2015 Critical Patch Update (8u45); assigned CVE-2015-0460 |
| 2015-12-28 | JDK-8071507 fixed for Java 9: all phantom references are now cleared |
| 2016-01-12 | Separate handling of cleaners removed again (JDK-8143847), no longer needed now that all phantom references are cleared |
| 2016-02-02 | sun.misc.Cleaner moved to jdk.internal.ref for Java 9 (JDK-8148117) |
| 2017-09-21 | Java 9 released, the first release where plain phantom references can no longer be resurrected |
| 2022-08-11 | JDK-8071507 backported to Java 8: commit 0869fc0153bd |
| 2022-10-18 | Backport released in 8u352 (Oracle 8u351, October 2022 Critical Patch Update); the Necromancer stops working on Java 8 |