Path: blob/master/src/java.base/share/classes/sun/security/ssl/HandshakeContext.java
41159 views
/*1* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.ssl;2627import java.io.IOException;28import java.nio.BufferOverflowException;29import java.nio.BufferUnderflowException;30import java.nio.ByteBuffer;31import java.security.AlgorithmConstraints;32import java.security.CryptoPrimitive;33import java.util.AbstractMap.SimpleImmutableEntry;34import java.util.ArrayList;35import java.util.Collections;36import java.util.EnumMap;37import java.util.EnumSet;38import java.util.HashMap;39import java.util.LinkedHashMap;40import java.util.LinkedList;41import java.util.List;42import java.util.Map;43import java.util.Queue;44import javax.crypto.SecretKey;45import javax.net.ssl.SNIServerName;46import javax.net.ssl.SSLHandshakeException;47import javax.security.auth.x500.X500Principal;48import sun.security.ssl.NamedGroup.NamedGroupSpec;49import static sun.security.ssl.NamedGroup.NamedGroupSpec.*;50import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;5152abstract class HandshakeContext implements ConnectionContext {53// System properties5455// By default, disable the unsafe legacy session renegotiation.56static final boolean allowUnsafeRenegotiation =57Utilities.getBooleanProperty(58"sun.security.ssl.allowUnsafeRenegotiation", false);5960// For maximum interoperability and backward compatibility, RFC 574661// allows server (or client) to accept ClientHello (or ServerHello)62// message without the secure renegotiation_info extension or SCSV.63//64// For maximum security, RFC 5746 also allows server (or client) to65// reject such message with a fatal "handshake_failure" alert.66//67// By default, allow such legacy hello messages.68static final boolean allowLegacyHelloMessages =69Utilities.getBooleanProperty(70"sun.security.ssl.allowLegacyHelloMessages", true);7172// registered handshake message actors73LinkedHashMap<Byte, SSLConsumer> handshakeConsumers;74final HashMap<Byte, HandshakeProducer> handshakeProducers;7576// context77final SSLContextImpl sslContext;78final TransportContext conContext;79final SSLConfiguration sslConfig;8081// consolidated parameters82final List<ProtocolVersion> activeProtocols;83final List<CipherSuite> activeCipherSuites;84final AlgorithmConstraints algorithmConstraints;85final ProtocolVersion maximumActiveProtocol;8687// output stream88final HandshakeOutStream handshakeOutput;8990// handshake transcript hash91final HandshakeHash handshakeHash;9293// negotiated security parameters94SSLSessionImpl handshakeSession;95boolean handshakeFinished;96// boolean isInvalidated;9798boolean kickstartMessageDelivered;99100// Resumption101boolean isResumption;102SSLSessionImpl resumingSession;103// Session is using stateless resumption104boolean statelessResumption;105106final Queue<Map.Entry<Byte, ByteBuffer>> delegatedActions;107volatile boolean taskDelegated;108volatile Exception delegatedThrown;109110ProtocolVersion negotiatedProtocol;111CipherSuite negotiatedCipherSuite;112final List<SSLPossession> handshakePossessions;113final List<SSLCredentials> handshakeCredentials;114SSLKeyDerivation handshakeKeyDerivation;115SSLKeyExchange handshakeKeyExchange;116SecretKey baseReadSecret;117SecretKey baseWriteSecret;118119// protocol version being established120int clientHelloVersion;121String applicationProtocol;122123RandomCookie clientHelloRandom;124RandomCookie serverHelloRandom;125byte[] certRequestContext;126127////////////////////128// Extensions129130// the extensions used in the handshake131final Map<SSLExtension, SSLExtension.SSLExtensionSpec>132handshakeExtensions;133134// MaxFragmentLength135int maxFragmentLength;136137// SignatureScheme138List<SignatureScheme> localSupportedSignAlgs;139List<SignatureScheme> peerRequestedSignatureSchemes;140List<SignatureScheme> peerRequestedCertSignSchemes;141142// Known authorities143X500Principal[] peerSupportedAuthorities = null;144145// SupportedGroups146List<NamedGroup> clientRequestedNamedGroups;147148// HelloRetryRequest149NamedGroup serverSelectedNamedGroup;150151// if server name indicator is negotiated152//153// May need a public API for the indication in the future.154List<SNIServerName> requestedServerNames;155SNIServerName negotiatedServerName;156157// OCSP Stapling info158boolean staplingActive = false;159160protected HandshakeContext(SSLContextImpl sslContext,161TransportContext conContext) throws IOException {162this.sslContext = sslContext;163this.conContext = conContext;164this.sslConfig = (SSLConfiguration)conContext.sslConfig.clone();165166this.algorithmConstraints = new SSLAlgorithmConstraints(167sslConfig.userSpecifiedAlgorithmConstraints);168this.activeProtocols = getActiveProtocols(sslConfig.enabledProtocols,169sslConfig.enabledCipherSuites, algorithmConstraints);170if (activeProtocols.isEmpty()) {171throw new SSLHandshakeException(172"No appropriate protocol (protocol is disabled or " +173"cipher suites are inappropriate)");174}175176ProtocolVersion maximumVersion = ProtocolVersion.NONE;177for (ProtocolVersion pv : this.activeProtocols) {178if (maximumVersion == ProtocolVersion.NONE ||179pv.compare(maximumVersion) > 0) {180maximumVersion = pv;181}182}183this.maximumActiveProtocol = maximumVersion;184this.activeCipherSuites = getActiveCipherSuites(this.activeProtocols,185sslConfig.enabledCipherSuites, algorithmConstraints);186if (activeCipherSuites.isEmpty()) {187throw new SSLHandshakeException("No appropriate cipher suite");188}189190this.handshakeConsumers = new LinkedHashMap<>();191this.handshakeProducers = new HashMap<>();192this.handshakeHash = conContext.inputRecord.handshakeHash;193this.handshakeOutput = new HandshakeOutStream(conContext.outputRecord);194195this.handshakeFinished = false;196this.kickstartMessageDelivered = false;197198this.delegatedActions = new LinkedList<>();199this.handshakeExtensions = new HashMap<>();200this.handshakePossessions = new LinkedList<>();201this.handshakeCredentials = new LinkedList<>();202this.requestedServerNames = null;203this.negotiatedServerName = null;204this.negotiatedCipherSuite = conContext.cipherSuite;205initialize();206}207208/**209* Constructor for PostHandshakeContext210*/211protected HandshakeContext(TransportContext conContext) {212this.sslContext = conContext.sslContext;213this.conContext = conContext;214this.sslConfig = conContext.sslConfig;215216this.negotiatedProtocol = conContext.protocolVersion;217this.negotiatedCipherSuite = conContext.cipherSuite;218this.handshakeOutput = new HandshakeOutStream(conContext.outputRecord);219this.delegatedActions = new LinkedList<>();220221this.handshakeConsumers = new LinkedHashMap<>();222this.handshakeProducers = null;223this.handshakeHash = null;224this.activeProtocols = null;225this.activeCipherSuites = null;226this.algorithmConstraints = null;227this.maximumActiveProtocol = null;228this.handshakeExtensions = Collections.emptyMap(); // Not in TLS13229this.handshakePossessions = null;230this.handshakeCredentials = null;231}232233// Initialize the non-final class variables.234private void initialize() {235ProtocolVersion inputHelloVersion;236ProtocolVersion outputHelloVersion;237if (conContext.isNegotiated) {238inputHelloVersion = conContext.protocolVersion;239outputHelloVersion = conContext.protocolVersion;240} else {241if (activeProtocols.contains(ProtocolVersion.SSL20Hello)) {242inputHelloVersion = ProtocolVersion.SSL20Hello;243244// Per TLS 1.3 protocol, implementation MUST NOT send an SSL245// version 2.0 compatible CLIENT-HELLO.246if (maximumActiveProtocol.useTLS13PlusSpec()) {247outputHelloVersion = maximumActiveProtocol;248} else {249outputHelloVersion = ProtocolVersion.SSL20Hello;250}251} else {252inputHelloVersion = maximumActiveProtocol;253outputHelloVersion = maximumActiveProtocol;254}255}256257conContext.inputRecord.setHelloVersion(inputHelloVersion);258conContext.outputRecord.setHelloVersion(outputHelloVersion);259260if (!conContext.isNegotiated) {261conContext.protocolVersion = maximumActiveProtocol;262}263conContext.outputRecord.setVersion(conContext.protocolVersion);264}265266private static List<ProtocolVersion> getActiveProtocols(267List<ProtocolVersion> enabledProtocols,268List<CipherSuite> enabledCipherSuites,269AlgorithmConstraints algorithmConstraints) {270boolean enabledSSL20Hello = false;271ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);272for (ProtocolVersion protocol : enabledProtocols) {273if (!enabledSSL20Hello && protocol == ProtocolVersion.SSL20Hello) {274enabledSSL20Hello = true;275continue;276}277278if (!algorithmConstraints.permits(279EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),280protocol.name, null)) {281// Ignore disabled protocol.282continue;283}284285boolean found = false;286Map<NamedGroupSpec, Boolean> cachedStatus =287new EnumMap<>(NamedGroupSpec.class);288for (CipherSuite suite : enabledCipherSuites) {289if (suite.isAvailable() && suite.supports(protocol)) {290if (isActivatable(suite,291algorithmConstraints, cachedStatus)) {292protocols.add(protocol);293found = true;294break;295}296} else if (SSLLogger.isOn && SSLLogger.isOn("verbose")) {297SSLLogger.fine(298"Ignore unsupported cipher suite: " + suite +299" for " + protocol.name);300}301}302303if (!found && (SSLLogger.isOn) && SSLLogger.isOn("handshake")) {304SSLLogger.fine(305"No available cipher suite for " + protocol.name);306}307}308309if (!protocols.isEmpty()) {310if (enabledSSL20Hello) {311protocols.add(ProtocolVersion.SSL20Hello);312}313Collections.sort(protocols);314}315316return Collections.unmodifiableList(protocols);317}318319private static List<CipherSuite> getActiveCipherSuites(320List<ProtocolVersion> enabledProtocols,321List<CipherSuite> enabledCipherSuites,322AlgorithmConstraints algorithmConstraints) {323324List<CipherSuite> suites = new LinkedList<>();325if (enabledProtocols != null && !enabledProtocols.isEmpty()) {326Map<NamedGroupSpec, Boolean> cachedStatus =327new EnumMap<>(NamedGroupSpec.class);328for (CipherSuite suite : enabledCipherSuites) {329if (!suite.isAvailable()) {330continue;331}332333boolean isSupported = false;334for (ProtocolVersion protocol : enabledProtocols) {335if (!suite.supports(protocol)) {336continue;337}338if (isActivatable(suite,339algorithmConstraints, cachedStatus)) {340suites.add(suite);341isSupported = true;342break;343}344}345346if (!isSupported &&347SSLLogger.isOn && SSLLogger.isOn("verbose")) {348SSLLogger.finest(349"Ignore unsupported cipher suite: " + suite);350}351}352}353354return Collections.unmodifiableList(suites);355}356357/**358* Parse the handshake record and return the contentType359*/360static byte getHandshakeType(TransportContext conContext,361Plaintext plaintext) throws IOException {362// struct {363// HandshakeType msg_type; /* handshake type */364// uint24 length; /* bytes in message */365// select (HandshakeType) {366// ...367// } body;368// } Handshake;369370if (plaintext.contentType != ContentType.HANDSHAKE.id) {371throw conContext.fatal(Alert.INTERNAL_ERROR,372"Unexpected operation for record: " + plaintext.contentType);373}374375if (plaintext.fragment == null || plaintext.fragment.remaining() < 4) {376throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,377"Invalid handshake message: insufficient data");378}379380byte handshakeType = (byte)Record.getInt8(plaintext.fragment);381int handshakeLen = Record.getInt24(plaintext.fragment);382if (handshakeLen != plaintext.fragment.remaining()) {383throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,384"Invalid handshake message: insufficient handshake body");385}386387return handshakeType;388}389390void dispatch(byte handshakeType, Plaintext plaintext) throws IOException {391if (conContext.transport.useDelegatedTask()) {392boolean hasDelegated = !delegatedActions.isEmpty();393if (hasDelegated ||394(handshakeType != SSLHandshake.FINISHED.id &&395handshakeType != SSLHandshake.KEY_UPDATE.id &&396handshakeType != SSLHandshake.NEW_SESSION_TICKET.id)) {397if (!hasDelegated) {398taskDelegated = false;399delegatedThrown = null;400}401402// Clone the fragment for delegated actions.403//404// The plaintext may share the application buffers. It is405// fine to use shared buffers if no delegated actions.406// However, for delegated actions, the shared buffers may be407// polluted in application layer before the delegated actions408// executed.409ByteBuffer fragment = ByteBuffer.wrap(410new byte[plaintext.fragment.remaining()]);411fragment.put(plaintext.fragment);412fragment = fragment.rewind();413414delegatedActions.add(new SimpleImmutableEntry<>(415handshakeType,416fragment417));418419// For TLS 1.2 and previous versions, the ChangeCipherSpec420// message is always delivered before the Finished handshake421// message. ChangeCipherSpec is not a handshake message,422// and cannot be wrapped in one TLS record. The processing423// of Finished handshake message is unlikely to be delegated.424//425// However, for TLS 1.3 there is no non-handshake messages426// delivered immediately before Finished message. Then, the427// 'hasDelegated' could be true, and the Finished message is428// handled in a delegated action.429//430// The HandshakeStatus.FINISHED for the final handshake flight431// could be used to determine if the handshake has completed.432// Per the HandshakeStatus.FINISHED specification, it is only433// generated by call to SSLEngine.wrap()/unwrap(). It is434// unlikely to change the spec, so we cannot use delegated435// action and SSLEngine.getHandshakeStatus() to indicate the436// FINISHED handshake status.437//438// To workaround this special user case, the follow-on call to439// SSLEngine.wrap() method will return HandshakeStatus.FINISHED440// status if needed.441//442// As the final handshake flight is always delivered from the443// client side, so we only need to take care of the server444// dispatching processes.445//446// See also the note on447// TransportContext.needHandshakeFinishedStatus.448if (hasDelegated &&449!conContext.sslConfig.isClientMode &&450handshakeType == SSLHandshake.FINISHED.id) {451conContext.hasDelegatedFinished = true;452}453} else {454dispatch(handshakeType, plaintext.fragment);455}456} else {457dispatch(handshakeType, plaintext.fragment);458}459}460461void dispatch(byte handshakeType,462ByteBuffer fragment) throws IOException {463SSLConsumer consumer;464if (handshakeType == SSLHandshake.HELLO_REQUEST.id) {465// For TLS 1.2 and prior versions, the HelloRequest message MAY466// be sent by the server at any time.467consumer = SSLHandshake.HELLO_REQUEST;468} else {469consumer = handshakeConsumers.get(handshakeType);470}471472if (consumer == null) {473throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,474"Unexpected handshake message: " +475SSLHandshake.nameOf(handshakeType));476}477478try {479consumer.consume(this, fragment);480} catch (UnsupportedOperationException unsoe) {481throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,482"Unsupported handshake message: " +483SSLHandshake.nameOf(handshakeType), unsoe);484} catch (BufferUnderflowException | BufferOverflowException be) {485throw conContext.fatal(Alert.DECODE_ERROR,486"Illegal handshake message: " +487SSLHandshake.nameOf(handshakeType), be);488}489490// update handshake hash after handshake message consumption.491handshakeHash.consume();492}493494abstract void kickstart() throws IOException;495496/**497* Check if the given cipher suite is enabled and available within498* the current active cipher suites.499*500* Does not check if the required server certificates are available.501*/502boolean isNegotiable(CipherSuite cs) {503return isNegotiable(activeCipherSuites, cs);504}505506/**507* Check if the given cipher suite is enabled and available within508* the proposed cipher suite list.509*510* Does not check if the required server certificates are available.511*/512static final boolean isNegotiable(513List<CipherSuite> proposed, CipherSuite cs) {514return proposed.contains(cs) && cs.isNegotiable();515}516517/**518* Check if the given cipher suite is enabled and available within519* the proposed cipher suite list and specific protocol version.520*521* Does not check if the required server certificates are available.522*/523static final boolean isNegotiable(List<CipherSuite> proposed,524ProtocolVersion protocolVersion, CipherSuite cs) {525return proposed.contains(cs) &&526cs.isNegotiable() && cs.supports(protocolVersion);527}528529/**530* Check if the given protocol version is enabled and available.531*/532boolean isNegotiable(ProtocolVersion protocolVersion) {533return activeProtocols.contains(protocolVersion);534}535536/**537* Set the active protocol version and propagate it to the SSLSocket538* and our handshake streams. Called from ClientHandshaker539* and ServerHandshaker with the negotiated protocol version.540*/541void setVersion(ProtocolVersion protocolVersion) {542this.conContext.protocolVersion = protocolVersion;543}544545private static boolean isActivatable(CipherSuite suite,546AlgorithmConstraints algorithmConstraints,547Map<NamedGroupSpec, Boolean> cachedStatus) {548549if (algorithmConstraints.permits(550EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) {551if (suite.keyExchange == null) {552// TLS 1.3, no definition of key exchange in cipher suite.553return true;554}555556// Is at least one of the group types available?557boolean groupAvailable, retval = false;558NamedGroupSpec[] groupTypes = suite.keyExchange.groupTypes;559for (NamedGroupSpec groupType : groupTypes) {560if (groupType != NAMED_GROUP_NONE) {561Boolean checkedStatus = cachedStatus.get(groupType);562if (checkedStatus == null) {563groupAvailable = SupportedGroups.isActivatable(564algorithmConstraints, groupType);565cachedStatus.put(groupType, groupAvailable);566567if (!groupAvailable &&568SSLLogger.isOn && SSLLogger.isOn("verbose")) {569SSLLogger.fine(570"No activated named group in " + groupType);571}572} else {573groupAvailable = checkedStatus;574}575576retval |= groupAvailable;577} else {578retval = true;579}580}581582if (!retval && SSLLogger.isOn && SSLLogger.isOn("verbose")) {583SSLLogger.fine("No active named group(s), ignore " + suite);584}585586return retval;587588} else if (SSLLogger.isOn && SSLLogger.isOn("verbose")) {589SSLLogger.fine("Ignore disabled cipher suite: " + suite);590}591592return false;593}594595List<SNIServerName> getRequestedServerNames() {596if (requestedServerNames == null) {597return Collections.emptyList();598}599return requestedServerNames;600}601}602603604605