8191808: Configurable read timeout for CRLs
authormullan
Thu, 09 May 2019 13:49:08 -0400
changeset 54796 3c16c876b094
parent 54795 fd08f5a976e6
child 54797 c90da1272d7f
8191808: Configurable read timeout for CRLs Reviewed-by: xuelei, coffeys
src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java
test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java
--- a/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java	Thu May 09 12:04:20 2019 -0500
+++ b/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java	Thu May 09 13:49:08 2019 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2019, 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
@@ -123,23 +123,40 @@
     // allowed when downloading CRLs
     private static final int DEFAULT_CRL_CONNECT_TIMEOUT = 15000;
 
+    // Default maximum read timeout in milliseconds (15 seconds)
+    // allowed when downloading CRLs
+    private static final int DEFAULT_CRL_READ_TIMEOUT = 15000;
+
     /**
      * Integer value indicating the connect timeout, in seconds, to be
      * used for the CRL download. A timeout of zero is interpreted as
      * an infinite timeout.
      */
-    private static final int CRL_CONNECT_TIMEOUT = initializeTimeout();
+    private static final int CRL_CONNECT_TIMEOUT =
+        initializeTimeout("com.sun.security.crl.timeout",
+                          DEFAULT_CRL_CONNECT_TIMEOUT);
 
     /**
-     * Initialize the timeout length by getting the CRL timeout
-     * system property. If the property has not been set, or if its
-     * value is negative, set the timeout length to the default.
+     * Integer value indicating the read timeout, in seconds, to be
+     * used for the CRL download. A timeout of zero is interpreted as
+     * an infinite timeout.
      */
-    private static int initializeTimeout() {
-        Integer tmp = java.security.AccessController.doPrivileged(
-                new GetIntegerAction("com.sun.security.crl.timeout"));
+    private static final int CRL_READ_TIMEOUT =
+        initializeTimeout("com.sun.security.crl.readtimeout",
+                          DEFAULT_CRL_READ_TIMEOUT);
+
+    /**
+     * Initialize the timeout length by getting the specified CRL timeout
+     * system property. If the property has not been set, or if its
+     * value is negative, set the timeout length to the specified default.
+     */
+    private static int initializeTimeout(String prop, int def) {
+        Integer tmp = GetIntegerAction.privilegedGetProperty(prop);
         if (tmp == null || tmp < 0) {
-            return DEFAULT_CRL_CONNECT_TIMEOUT;
+            return def;
+        }
+        if (debug != null) {
+            debug.println(prop + " set to " + tmp + " seconds");
         }
         // Convert to milliseconds, as the system property will be
         // specified in seconds
@@ -364,6 +381,7 @@
             }
             long oldLastModified = lastModified;
             connection.setConnectTimeout(CRL_CONNECT_TIMEOUT);
+            connection.setReadTimeout(CRL_READ_TIMEOUT);
             try (InputStream in = connection.getInputStream()) {
                 lastModified = connection.getLastModified();
                 if (oldLastModified != 0) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java	Thu May 09 13:49:08 2019 -0400
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2019, 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
+ * @bug 8191808
+ * @summary check that CRL download is interrupted if it takes too long
+ * @library /test/lib
+ * @run main/othervm -Dcom.sun.security.crl.readtimeout=1 CRLReadTimeout
+ */
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketTimeoutException;
+import java.security.KeyStore;
+import java.security.cert.CertificateFactory;
+import java.security.cert.CertPath;
+import java.security.cert.CertPathValidator;
+import java.security.cert.CertPathValidatorException;
+import java.security.cert.PKIXParameters;
+import java.security.cert.PKIXRevocationChecker;
+import static java.security.cert.PKIXRevocationChecker.Option.*;
+import java.security.cert.TrustAnchor;
+import java.security.cert.X509Certificate;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Set;
+import com.sun.net.httpserver.HttpServer;
+
+import jdk.test.lib.SecurityTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+public class CRLReadTimeout {
+
+    public static void main(String[] args) throws Exception {
+
+        String timeout = System.getProperty("com.sun.security.crl.readtimeout");
+        if (timeout == null) {
+            timeout = "15";
+        }
+        System.out.println("Testing timeout of " + timeout + " seconds");
+
+        CrlHttpServer crlServer = new CrlHttpServer(Integer.parseInt(timeout));
+        try {
+            crlServer.start();
+            testTimeout(crlServer.getPort());
+        } finally {
+            crlServer.stop();
+        }
+    }
+
+    private static void testTimeout(int port) throws Exception {
+
+        // create certificate chain with two certs, root and end-entity
+        keytool("-alias duke -dname CN=duke -genkey -keyalg RSA");
+        keytool("-alias root -dname CN=root -genkey -keyalg RSA");
+        keytool("-certreq -alias duke -file duke.req");
+        // set CRL URI to local server
+        keytool("-gencert -infile duke.req -alias root -rfc -outfile duke.cert "
+                + "-ext crl=uri:http://localhost:" + port + "/crl");
+        keytool("-importcert -file duke.cert -alias duke");
+
+        KeyStore ks = KeyStore.getInstance(new File("ks"),
+                                           "changeit".toCharArray());
+        X509Certificate cert = (X509Certificate)ks.getCertificate("duke");
+        X509Certificate root = (X509Certificate)ks.getCertificate("root");
+
+        // validate chain
+        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
+        PKIXRevocationChecker prc =
+            (PKIXRevocationChecker)cpv.getRevocationChecker();
+        prc.setOptions(EnumSet.of(PREFER_CRLS, NO_FALLBACK, SOFT_FAIL));
+        PKIXParameters params =
+            new PKIXParameters(Set.of(new TrustAnchor(root, null)));
+        params.addCertPathChecker(prc);
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+        CertPath cp = cf.generateCertPath(List.of(cert));
+        cpv.validate(cp, params);
+
+        // unwrap soft fail exceptions and check for SocketTimeoutException
+        boolean expected = false;
+        for (CertPathValidatorException softFail:prc.getSoftFailExceptions()) {
+            Throwable cause = softFail.getCause();
+            while (cause != null) {
+                if (cause instanceof SocketTimeoutException) {
+                    expected = true;
+                    break;
+                }
+                cause = cause.getCause();
+            }
+            if (expected) {
+                break;
+            }
+        }
+        if (!expected) {
+            throw new Exception("SocketTimeoutException not thrown");
+        }
+    }
+
+    private static OutputAnalyzer keytool(String cmd) throws Exception {
+        return SecurityTools.keytool("-storepass changeit "
+                + "-keystore ks " + cmd);
+    }
+
+    private static class CrlHttpServer {
+
+        private final HttpServer server;
+        private final int timeout;
+
+        public CrlHttpServer(int timeout) throws IOException {
+            server = HttpServer.create();
+            this.timeout = timeout;
+        }
+
+        public void start() throws IOException {
+            server.bind(new InetSocketAddress(0), 0);
+            server.createContext("/", t -> {
+                try (InputStream is = t.getRequestBody()) {
+                    is.readAllBytes();
+                }
+                try {
+                    // sleep for 2 seconds longer to force timeout
+                    Thread.sleep((timeout + 2)*1000);
+                } catch (InterruptedException ie) {
+                    throw new IOException(ie);
+                }
+            });
+            server.setExecutor(null);
+            server.start();
+        }
+
+        public void stop() {
+            server.stop(0);
+        }
+
+        int getPort() {
+            return server.getAddress().getPort();
+        }
+    }
+}