8184744: Replace finalizer in crypto classes with Cleaner
authorrriggs
Mon, 07 Aug 2017 14:14:03 -0400
changeset 46097 22316369c9b0
parent 46096 62c77b334012
child 46098 46f8a2a8ccfb
8184744: Replace finalizer in crypto classes with Cleaner Reviewed-by: mchung
jdk/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java
jdk/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java
jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java
jdk/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java
jdk/src/java.base/share/classes/sun/security/provider/KeyProtector.java
jdk/test/com/sun/crypto/provider/Cipher/DES/DESKeyCleanupTest.java
jdk/test/com/sun/crypto/provider/Cipher/PBE/PBEKeyCleanupTest.java
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Mon Aug 07 09:37:16 2017 +0100
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/DESKey.java	Mon Aug 07 14:14:03 2017 -0400
@@ -31,6 +31,8 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.DESKeySpec;
 
+import jdk.internal.ref.CleanerFactory;
+
 /**
  * This class represents a DES key.
  *
@@ -74,6 +76,11 @@
         this.key = new byte[DESKeySpec.DES_KEY_LEN];
         System.arraycopy(key, offset, this.key, 0, DESKeySpec.DES_KEY_LEN);
         DESKeyGenerator.setParityBit(this.key, 0);
+
+        // Use the cleaner to zero the key when no longer referenced
+        final byte[] k = this.key;
+        CleanerFactory.cleaner().register(this,
+                () -> java.util.Arrays.fill(k, (byte)0x00));
     }
 
     public byte[] getEncoded() {
@@ -144,20 +151,4 @@
                         getFormat(),
                         getEncoded());
     }
-
-    /**
-     * Ensures that the bytes of this key are
-     * set to zero when there are no more references to it.
-     */
-    @SuppressWarnings("deprecation")
-    protected void finalize() throws Throwable {
-        try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
-            }
-        } finally {
-            super.finalize();
-        }
-    }
 }
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Mon Aug 07 09:37:16 2017 +0100
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/DESedeKey.java	Mon Aug 07 14:14:03 2017 -0400
@@ -31,6 +31,8 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.DESedeKeySpec;
 
+import jdk.internal.ref.CleanerFactory;
+
 /**
  * This class represents a DES-EDE key.
  *
@@ -76,6 +78,11 @@
         DESKeyGenerator.setParityBit(this.key, 0);
         DESKeyGenerator.setParityBit(this.key, 8);
         DESKeyGenerator.setParityBit(this.key, 16);
+
+        // Use the cleaner to zero the key when no longer referenced
+        final byte[] k = this.key;
+        CleanerFactory.cleaner().register(this,
+                () -> java.util.Arrays.fill(k, (byte)0x00));
     }
 
     public byte[] getEncoded() {
@@ -145,20 +152,4 @@
                         getFormat(),
                         getEncoded());
     }
-
-    /**
-     * Ensures that the bytes of this key are
-     * set to zero when there are no more references to it.
-     */
-    @SuppressWarnings("deprecation")
-    protected void finalize() throws Throwable {
-        try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
-            }
-        } finally {
-            super.finalize();
-        }
-    }
 }
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Mon Aug 07 09:37:16 2017 +0100
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKey.java	Mon Aug 07 14:14:03 2017 -0400
@@ -32,6 +32,8 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.PBEKeySpec;
 
+import jdk.internal.ref.CleanerFactory;
+
 /**
  * This class represents a PBE key.
  *
@@ -49,7 +51,7 @@
     /**
      * Creates a PBE key from a given PBE key specification.
      *
-     * @param key the given PBE key specification
+     * @param keytype the given PBE key specification
      */
     PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
         char[] passwd = keySpec.getPassword();
@@ -70,6 +72,11 @@
             this.key[i] = (byte) (passwd[i] & 0x7f);
         java.util.Arrays.fill(passwd, ' ');
         type = keytype;
+
+        // Use the cleaner to zero the key when no longer referenced
+        final byte[] k = this.key;
+        CleanerFactory.cleaner().register(this,
+                () -> java.util.Arrays.fill(k, (byte)0x00));
     }
 
     public byte[] getEncoded() {
@@ -140,20 +147,4 @@
                         getFormat(),
                         getEncoded());
     }
-
-    /**
-     * Ensures that the password bytes of this key are
-     * set to zero when there are no more references to it.
-     */
-    @SuppressWarnings("deprecation")
-    protected void finalize() throws Throwable {
-        try {
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
-            }
-        } finally {
-            super.finalize();
-        }
-    }
 }
--- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Mon Aug 07 09:37:16 2017 +0100
+++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java	Mon Aug 07 14:14:03 2017 -0400
@@ -40,6 +40,8 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.PBEKeySpec;
 
+import jdk.internal.ref.CleanerFactory;
+
 /**
  * This class represents a PBE key derived using PBKDF2 defined
  * in PKCS#5 v2.0. meaning that
@@ -76,7 +78,8 @@
     /**
      * Creates a PBE key from a given PBE key specification.
      *
-     * @param key the given PBE key specification
+     * @param keySpec the given PBE key specification
+     * @param prfAlgo the given PBE key algorithm
      */
     PBKDF2KeyImpl(PBEKeySpec keySpec, String prfAlgo)
         throws InvalidKeySpecException {
@@ -120,6 +123,15 @@
             throw ike;
         }
         this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength);
+
+        // Use the cleaner to zero the key when no longer referenced
+        final byte[] k = this.key;
+        final char[] p = this.passwd;
+        CleanerFactory.cleaner().register(this,
+                () -> {
+                    java.util.Arrays.fill(k, (byte)0x00);
+                    java.util.Arrays.fill(p, '0');
+                });
     }
 
     private static byte[] deriveKey(final Mac prf, final byte[] password,
@@ -262,24 +274,4 @@
             return new KeyRep(KeyRep.Type.SECRET, getAlgorithm(),
                               getFormat(), getEncoded());
     }
-
-    /**
-     * Ensures that the password bytes of this key are
-     * erased when there are no more references to it.
-     */
-    @SuppressWarnings("deprecation")
-    protected void finalize() throws Throwable {
-        try {
-            if (this.passwd != null) {
-                java.util.Arrays.fill(this.passwd, '0');
-                this.passwd = null;
-            }
-            if (this.key != null) {
-                java.util.Arrays.fill(this.key, (byte)0x00);
-                this.key = null;
-            }
-        } finally {
-            super.finalize();
-        }
-    }
 }
--- a/jdk/src/java.base/share/classes/sun/security/provider/KeyProtector.java	Mon Aug 07 09:37:16 2017 +0100
+++ b/jdk/src/java.base/share/classes/sun/security/provider/KeyProtector.java	Mon Aug 07 14:14:03 2017 -0400
@@ -35,6 +35,7 @@
 import java.security.UnrecoverableKeyException;
 import java.util.*;
 
+import jdk.internal.ref.CleanerFactory;
 import sun.security.pkcs.PKCS8Key;
 import sun.security.pkcs.EncryptedPrivateKeyInfo;
 import sun.security.x509.AlgorithmId;
@@ -141,18 +142,10 @@
             passwdBytes[j++] = (byte)(password[i] >> 8);
             passwdBytes[j++] = (byte)password[i];
         }
-    }
-
-    /**
-     * Ensures that the password bytes of this key protector are
-     * set to zero when there are no more references to it.
-     */
-    @SuppressWarnings("deprecation")
-    protected void finalize() {
-        if (passwdBytes != null) {
-            Arrays.fill(passwdBytes, (byte)0x00);
-            passwdBytes = null;
-        }
+        // Use the cleaner to zero the password when no longer referenced
+        final byte[] k = this.passwdBytes;
+        CleanerFactory.cleaner().register(this,
+                () -> java.util.Arrays.fill(k, (byte)0x00));
     }
 
     /*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/crypto/provider/Cipher/DES/DESKeyCleanupTest.java	Mon Aug 07 14:14:03 2017 -0400
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @modules java.base/com.sun.crypto.provider:+open
+ * @run main/othervm DESKeyCleanupTest
+ * @summary Verify that key storage is cleared
+ */
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+/**
+ * Test that the array holding the key bytes is cleared when it is
+ * no longer referenced by the key.
+ */
+
+public class DESKeyCleanupTest {
+
+    private final static String SunJCEProvider = "SunJCE";
+
+    public static void main(String[] args) throws Exception {
+        testCleanupSecret("DES");
+        testCleanupSecret("DESede");
+    }
+
+    static void testCleanupSecret(String algorithm) throws Exception {
+        KeyGenerator desGen = KeyGenerator.getInstance(algorithm, SunJCEProvider);
+        SecretKey key = desGen.generateKey();
+
+        // Break into the implementation to observe the key byte array.
+        Class<?> keyClass = key.getClass();
+        Field keyField = keyClass.getDeclaredField("key");
+        keyField.setAccessible(true);
+        byte[] array = (byte[])keyField.get(key);
+
+        byte[] zeros = new byte[array.length];
+        do {
+            // Wait for array to be cleared;  if not cleared test will timeout
+            System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));
+            key = null;
+            System.gc();        // attempt to reclaim the key
+        } while (Arrays.compare(zeros, array) != 0);
+        System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));
+
+        Reference.reachabilityFence(key); // Keep key alive
+        Reference.reachabilityFence(array); // Keep array alive
+    }
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBEKeyCleanupTest.java	Mon Aug 07 14:14:03 2017 -0400
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @modules java.base/com.sun.crypto.provider:+open
+ * @run main/othervm PBEKeyCleanupTest
+ * @summary Verify that key storage is cleared
+ */
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Random;
+
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+
+/**
+ * Test that the array holding the key bytes is cleared when it is
+ * no longer referenced by the key.
+ */
+public class PBEKeyCleanupTest {
+
+    private final static String SunJCEProvider = "SunJCE";
+
+    private static final String PASS_PHRASE = "some hidden string";
+    private static final int ITERATION_COUNT = 1000;
+    private static final int KEY_SIZE = 128;
+
+    public static void main(String[] args) throws Exception {
+        testPBESecret("PBEWithMD5AndDES");
+        testPBKSecret("PBKDF2WithHmacSHA1");
+    }
+
+    private static void testPBESecret(String algorithm) throws Exception {
+        char[] password = new char[] {'f', 'o', 'o'};
+        PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
+        SecretKeyFactory keyFac =
+                SecretKeyFactory.getInstance(algorithm, SunJCEProvider);
+
+        testCleanupSecret(algorithm, keyFac.generateSecret(pbeKeySpec));
+    }
+
+    private static void testPBKSecret(String algorithm) throws Exception {
+        byte[] salt = new byte[8];
+        new Random().nextBytes(salt);
+        char[] password = new char[] {'f', 'o', 'o'};
+        PBEKeySpec pbeKeySpec = new PBEKeySpec(PASS_PHRASE.toCharArray(), salt,
+                ITERATION_COUNT, KEY_SIZE);
+        SecretKeyFactory keyFac =
+                SecretKeyFactory.getInstance(algorithm, SunJCEProvider);
+
+        testCleanupSecret(algorithm, keyFac.generateSecret(pbeKeySpec));
+    }
+
+    static void testCleanupSecret(String algorithm, SecretKey key) throws Exception {
+
+        // Break into the implementation to observe the key byte array.
+        Class<?> keyClass = key.getClass();
+        Field keyField = keyClass.getDeclaredField("key");
+        keyField.setAccessible(true);
+        byte[] array = (byte[])keyField.get(key);
+
+        byte[] zeros = new byte[array.length];
+        do {
+            // Wait for array to be cleared;  if not cleared test will timeout
+            System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));
+            key = null;
+            System.gc();        // attempt to reclaim the key
+        } while (Arrays.compare(zeros, array) != 0);
+        System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));
+
+        Reference.reachabilityFence(key); // Keep key alive
+        Reference.reachabilityFence(array); // Keep array alive
+    }
+}
+
+
+