src/java.base/share/classes/sun/security/ssl/CertificateStatus.java
changeset 50768 68fa3d4026ea
child 53064 103ed9569fc8
equal deleted inserted replaced
50767:356eaea05bf0 50768:68fa3d4026ea
       
     1 /*
       
     2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package sun.security.ssl;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.nio.ByteBuffer;
       
    30 import java.text.MessageFormat;
       
    31 import java.util.List;
       
    32 import java.util.ArrayList;
       
    33 import java.util.Locale;
       
    34 import javax.net.ssl.SSLHandshakeException;
       
    35 import java.security.cert.X509Certificate;
       
    36 import sun.security.provider.certpath.OCSPResponse;
       
    37 import sun.security.ssl.SSLHandshake.HandshakeMessage;
       
    38 import static sun.security.ssl.CertStatusExtension.*;
       
    39 import static sun.security.ssl.CertificateMessage.*;
       
    40 
       
    41 /**
       
    42  * Consumers and producers for the CertificateStatus handshake message.
       
    43  * This message takes one of two related but slightly different forms,
       
    44  * depending on the type of stapling selected by the server.  The message
       
    45  * data will be of the form(s):
       
    46  *
       
    47  *  [status_request, RFC 6066]
       
    48  *
       
    49  *  struct {
       
    50  *      CertificateStatusType status_type;
       
    51  *      select (status_type) {
       
    52  *          case ocsp: OCSPResponse;
       
    53  *      } response;
       
    54  *  } CertificateStatus;
       
    55  *
       
    56  *  opaque OCSPResponse<1..2^24-1>;
       
    57  *
       
    58  *  [status_request_v2, RFC 6961]
       
    59  *
       
    60  *  struct {
       
    61  *      CertificateStatusType status_type;
       
    62  *      select (status_type) {
       
    63  *        case ocsp: OCSPResponse;
       
    64  *        case ocsp_multi: OCSPResponseList;
       
    65  *      } response;
       
    66  *  } CertificateStatus;
       
    67  *
       
    68  *  opaque OCSPResponse<0..2^24-1>;
       
    69  *
       
    70  *  struct {
       
    71  *      OCSPResponse ocsp_response_list<1..2^24-1>;
       
    72  *  } OCSPResponseList;
       
    73  */
       
    74 final class CertificateStatus {
       
    75     static final SSLConsumer handshakeConsumer =
       
    76             new CertificateStatusConsumer();
       
    77     static final HandshakeProducer handshakeProducer =
       
    78             new CertificateStatusProducer();
       
    79     static final HandshakeAbsence handshakeAbsence =
       
    80             new CertificateStatusAbsence();
       
    81 
       
    82     /**
       
    83      * The CertificateStatus handshake message.
       
    84      */
       
    85     static final class CertificateStatusMessage extends HandshakeMessage {
       
    86 
       
    87         final CertStatusRequestType statusType;
       
    88         int encodedResponsesLen = 0;
       
    89         int messageLength = -1;
       
    90         final List<byte[]> encodedResponses = new ArrayList<>();
       
    91 
       
    92         CertificateStatusMessage(HandshakeContext handshakeContext) {
       
    93             super(handshakeContext);
       
    94 
       
    95             ServerHandshakeContext shc =
       
    96                     (ServerHandshakeContext)handshakeContext;
       
    97 
       
    98             // Get the Certificates from the SSLContextImpl amd the Stapling
       
    99             // parameters
       
   100             StatusResponseManager.StaplingParameters stapleParams =
       
   101                     shc.stapleParams;
       
   102             if (stapleParams == null) {
       
   103                 throw new IllegalArgumentException(
       
   104                         "Unexpected null stapling parameters");
       
   105             }
       
   106 
       
   107             X509Certificate[] certChain =
       
   108                 (X509Certificate[])shc.handshakeSession.getLocalCertificates();
       
   109             if (certChain == null) {
       
   110                 throw new IllegalArgumentException(
       
   111                         "Unexpected null certificate chain");
       
   112             }
       
   113 
       
   114             // Walk the certificate list and add the correct encoded responses
       
   115             // to the encoded responses list
       
   116             statusType = stapleParams.statReqType;
       
   117             if (statusType == CertStatusRequestType.OCSP) {
       
   118                 // Just worry about the first cert in the chain
       
   119                 byte[] resp = stapleParams.responseMap.get(certChain[0]);
       
   120                 if (resp == null) {
       
   121                     // A not-found return status means we should include
       
   122                     // a zero-length response in CertificateStatus.
       
   123                     // This is highly unlikely to happen in practice.
       
   124                     resp = new byte[0];
       
   125                 }
       
   126                 encodedResponses.add(resp);
       
   127                 encodedResponsesLen += resp.length + 3;
       
   128             } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
       
   129                 for (X509Certificate cert : certChain) {
       
   130                     byte[] resp = stapleParams.responseMap.get(cert);
       
   131                     if (resp == null) {
       
   132                         resp = new byte[0];
       
   133                     }
       
   134                     encodedResponses.add(resp);
       
   135                     encodedResponsesLen += resp.length + 3;
       
   136                 }
       
   137             } else {
       
   138                 throw new IllegalArgumentException(
       
   139                         "Unsupported StatusResponseType: " + statusType);
       
   140             }
       
   141 
       
   142             messageLength = messageLength();
       
   143         }
       
   144 
       
   145         CertificateStatusMessage(HandshakeContext handshakeContext,
       
   146                 ByteBuffer m) throws IOException {
       
   147             super(handshakeContext);
       
   148 
       
   149             statusType = CertStatusRequestType.valueOf((byte)Record.getInt8(m));
       
   150             if (statusType == CertStatusRequestType.OCSP) {
       
   151                 byte[] respDER = Record.getBytes24(m);
       
   152                 // Convert the incoming bytes to a OCSPResponse strucutre
       
   153                 if (respDER.length > 0) {
       
   154                     encodedResponses.add(respDER);
       
   155                     encodedResponsesLen = 3 + respDER.length;
       
   156                 } else {
       
   157                     handshakeContext.conContext.fatal(Alert.HANDSHAKE_FAILURE,
       
   158                             "Zero-length OCSP Response");
       
   159                 }
       
   160             } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
       
   161                 int respListLen = Record.getInt24(m);
       
   162                 encodedResponsesLen = respListLen;
       
   163 
       
   164                 // Add each OCSP reponse into the array list in the order
       
   165                 // we receive them off the wire.  A zero-length array is
       
   166                 // allowed for ocsp_multi, and means that a response for
       
   167                 // a given certificate is not available.
       
   168                 while (respListLen > 0) {
       
   169                     byte[] respDER = Record.getBytes24(m);
       
   170                     encodedResponses.add(respDER);
       
   171                     respListLen -= (respDER.length + 3);
       
   172                 }
       
   173 
       
   174                 if (respListLen != 0) {
       
   175                     handshakeContext.conContext.fatal(Alert.INTERNAL_ERROR,
       
   176                             "Bad OCSP response list length");
       
   177                 }
       
   178             } else {
       
   179                 handshakeContext.conContext.fatal(Alert.HANDSHAKE_FAILURE,
       
   180                         "Unsupported StatusResponseType: " + statusType);
       
   181             }
       
   182             messageLength = messageLength();
       
   183         }
       
   184 
       
   185         @Override
       
   186         public SSLHandshake handshakeType() {
       
   187             return SSLHandshake.CERTIFICATE_STATUS;
       
   188         }
       
   189 
       
   190         @Override
       
   191         public int messageLength() {
       
   192             int len = 1;
       
   193 
       
   194             if (messageLength == -1) {
       
   195                 if (statusType == CertStatusRequestType.OCSP) {
       
   196                     len += encodedResponsesLen;
       
   197                 } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
       
   198                     len += 3 + encodedResponsesLen;
       
   199                 }
       
   200                 messageLength = len;
       
   201             }
       
   202 
       
   203             return messageLength;
       
   204         }
       
   205 
       
   206         @Override
       
   207         public void send(HandshakeOutStream s) throws IOException {
       
   208             s.putInt8(statusType.id);
       
   209             if (statusType == CertStatusRequestType.OCSP) {
       
   210                 s.putBytes24(encodedResponses.get(0));
       
   211             } else if (statusType == CertStatusRequestType.OCSP_MULTI) {
       
   212                 s.putInt24(encodedResponsesLen);
       
   213                 for (byte[] respBytes : encodedResponses) {
       
   214                     if (respBytes != null) {
       
   215                         s.putBytes24(respBytes);
       
   216                     } else {
       
   217                         s.putBytes24(null);
       
   218                     }
       
   219                 }
       
   220             } else {
       
   221                 // It is highly unlikely that we will fall into this section
       
   222                 // of the code.
       
   223                 throw new SSLHandshakeException("Unsupported status_type: " +
       
   224                         statusType.id);
       
   225             }
       
   226         }
       
   227 
       
   228         @Override
       
   229         public String toString() {
       
   230             StringBuilder sb = new StringBuilder();
       
   231 
       
   232             // Stringify the encoded OCSP response list
       
   233             for (byte[] respDER : encodedResponses) {
       
   234                 if (respDER.length > 0) {
       
   235                     try {
       
   236                         OCSPResponse oResp = new OCSPResponse(respDER);
       
   237                         sb.append(oResp.toString()).append("\n");
       
   238                     } catch (IOException ioe) {
       
   239                         sb.append("OCSP Response Exception: ").append(ioe)
       
   240                                 .append("\n");
       
   241                     }
       
   242                 } else {
       
   243                     sb.append("<Zero-length entry>\n");
       
   244                 }
       
   245             }
       
   246 
       
   247             MessageFormat messageFormat = new MessageFormat(
       
   248                 "\"CertificateStatus\": '{'\n" +
       
   249                 "  \"type\"                : \"{0}\",\n" +
       
   250                 "  \"responses \"          : [\n" + "{1}\n" + "  ]\n" +
       
   251                 "'}'",
       
   252                 Locale.ENGLISH);
       
   253             Object[] messageFields = {
       
   254                 statusType.name,
       
   255                 Utilities.indent(Utilities.indent(sb.toString()))
       
   256             };
       
   257 
       
   258             return messageFormat.format(messageFields);
       
   259         }
       
   260     }
       
   261 
       
   262     /**
       
   263      * The CertificateStatus handshake message consumer.
       
   264      */
       
   265     private static final class CertificateStatusConsumer
       
   266             implements SSLConsumer {
       
   267         // Prevent instantiation of this class.
       
   268         private CertificateStatusConsumer() {
       
   269             // blank
       
   270         }
       
   271 
       
   272         @Override
       
   273         public void consume(ConnectionContext context,
       
   274                 ByteBuffer message) throws IOException {
       
   275             ClientHandshakeContext chc = (ClientHandshakeContext)context;
       
   276             CertificateStatusMessage cst =
       
   277                     new CertificateStatusMessage(chc, message);
       
   278 
       
   279             // Log the message
       
   280             if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
       
   281                 SSLLogger.fine(
       
   282                         "Consuming server CertificateStatus handshake message",
       
   283                         cst);
       
   284             }
       
   285 
       
   286             // Pin the received responses to the SSLSessionImpl.  It will
       
   287             // be retrieved by the X509TrustManagerImpl during the certficicate
       
   288             // checking phase.
       
   289             chc.handshakeSession.setStatusResponses(cst.encodedResponses);
       
   290 
       
   291             // Now perform the check
       
   292             T12CertificateConsumer.checkServerCerts(chc, chc.deferredCerts);
       
   293         }
       
   294     }
       
   295 
       
   296     /**
       
   297      * The CertificateStatus handshake message consumer.
       
   298      */
       
   299     private static final class CertificateStatusProducer
       
   300             implements HandshakeProducer {
       
   301         // Prevent instantiation of this class.
       
   302         private CertificateStatusProducer() {
       
   303             // blank
       
   304         }
       
   305 
       
   306         @Override
       
   307         public byte[] produce(ConnectionContext context,
       
   308                 HandshakeMessage message) throws IOException {
       
   309             // Only the server-side should be a producer of this message
       
   310             ServerHandshakeContext shc = (ServerHandshakeContext)context;
       
   311 
       
   312             // If stapling is not active, immediately return without producing
       
   313             // a message or any further processing.
       
   314             if (!shc.staplingActive) {
       
   315                 return null;
       
   316             }
       
   317 
       
   318             // Create the CertificateStatus message from info in the
       
   319             CertificateStatusMessage csm = new CertificateStatusMessage(shc);
       
   320             if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
       
   321                 SSLLogger.fine(
       
   322                     "Produced server CertificateStatus handshake message", csm);
       
   323             }
       
   324 
       
   325             // Output the handshake message.
       
   326             csm.write(shc.handshakeOutput);
       
   327             shc.handshakeOutput.flush();
       
   328 
       
   329             // The handshake message has been delivered.
       
   330             return null;
       
   331         }
       
   332     }
       
   333 
       
   334     private static final class CertificateStatusAbsence
       
   335             implements HandshakeAbsence {
       
   336         // Prevent instantiation of this class
       
   337         private CertificateStatusAbsence() {
       
   338             // blank
       
   339         }
       
   340 
       
   341         @Override
       
   342         public void absent(ConnectionContext context,
       
   343                 HandshakeMessage message) throws IOException {
       
   344             ClientHandshakeContext chc = (ClientHandshakeContext)context;
       
   345 
       
   346             // Processing should only continue if stapling is active
       
   347             if (chc.staplingActive) {
       
   348                 // Because OCSP stapling is active, it means two things
       
   349                 // if we're here: 1) The server hello asserted the
       
   350                 // status_request[_v2] extension.  2) The CertificateStatus
       
   351                 // message was not sent.  This means that cert path checking
       
   352                 // was deferred, but must happen immediately.
       
   353                 if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
       
   354                     SSLLogger.fine("Server did not send CertificateStatus, " +
       
   355                             "checking cert chain without status info.");
       
   356                 }
       
   357                 T12CertificateConsumer.checkServerCerts(chc, chc.deferredCerts);
       
   358             }
       
   359         }
       
   360     }
       
   361 }
       
   362