Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/ssl/HandshakeContext.java
38830 views
/*1* Copyright (c) 2018, 2019, 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.SupportedGroupsExtension.NamedGroup;49import sun.security.ssl.SupportedGroupsExtension.NamedGroupType;50import static sun.security.ssl.SupportedGroupsExtension.NamedGroupType.*;51import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;5253abstract class HandshakeContext implements ConnectionContext {54// System properties5556// By default, disable the unsafe legacy session renegotiation.57static final boolean allowUnsafeRenegotiation =58Utilities.getBooleanProperty(59"sun.security.ssl.allowUnsafeRenegotiation", false);6061// For maximum interoperability and backward compatibility, RFC 574662// allows server (or client) to accept ClientHello (or ServerHello)63// message without the secure renegotiation_info extension or SCSV.64//65// For maximum security, RFC 5746 also allows server (or client) to66// reject such message with a fatal "handshake_failure" alert.67//68// By default, allow such legacy hello messages.69static final boolean allowLegacyHelloMessages =70Utilities.getBooleanProperty(71"sun.security.ssl.allowLegacyHelloMessages", true);7273// registered handshake message actors74LinkedHashMap<Byte, SSLConsumer> handshakeConsumers;75final HashMap<Byte, HandshakeProducer> handshakeProducers;7677// context78final SSLContextImpl sslContext;79final TransportContext conContext;80final SSLConfiguration sslConfig;8182// consolidated parameters83final List<ProtocolVersion> activeProtocols;84final List<CipherSuite> activeCipherSuites;85final AlgorithmConstraints algorithmConstraints;86final ProtocolVersion maximumActiveProtocol;8788// output stream89final HandshakeOutStream handshakeOutput;9091// handshake transcript hash92final HandshakeHash handshakeHash;9394// negotiated security parameters95SSLSessionImpl handshakeSession;96boolean handshakeFinished;97// boolean isInvalidated;9899boolean kickstartMessageDelivered;100101// Resumption102boolean isResumption;103SSLSessionImpl resumingSession;104105final Queue<Map.Entry<Byte, ByteBuffer>> delegatedActions;106volatile boolean taskDelegated = false;107volatile Exception delegatedThrown = null;108109ProtocolVersion negotiatedProtocol;110CipherSuite negotiatedCipherSuite;111final List<SSLPossession> handshakePossessions;112final List<SSLCredentials> handshakeCredentials;113SSLKeyDerivation handshakeKeyDerivation;114SSLKeyExchange handshakeKeyExchange;115SecretKey baseReadSecret;116SecretKey baseWriteSecret;117118// protocol version being established119int clientHelloVersion;120String applicationProtocol;121122RandomCookie clientHelloRandom;123RandomCookie serverHelloRandom;124byte[] certRequestContext;125126////////////////////127// Extensions128129// the extensions used in the handshake130final Map<SSLExtension, SSLExtension.SSLExtensionSpec>131handshakeExtensions;132133// MaxFragmentLength134int maxFragmentLength;135136// SignatureScheme137List<SignatureScheme> localSupportedSignAlgs;138List<SignatureScheme> peerRequestedSignatureSchemes;139List<SignatureScheme> peerRequestedCertSignSchemes;140141// Known authorities142X500Principal[] peerSupportedAuthorities = null;143144// SupportedGroups145List<NamedGroup> clientRequestedNamedGroups;146147// HelloRetryRequest148NamedGroup serverSelectedNamedGroup;149150// if server name indicator is negotiated151//152// May need a public API for the indication in the future.153List<SNIServerName> requestedServerNames;154SNIServerName negotiatedServerName;155156// OCSP Stapling info157boolean staplingActive = false;158159protected HandshakeContext(SSLContextImpl sslContext,160TransportContext conContext) throws IOException {161this.sslContext = sslContext;162this.conContext = conContext;163this.sslConfig = (SSLConfiguration)conContext.sslConfig.clone();164165this.algorithmConstraints = new SSLAlgorithmConstraints(166sslConfig.userSpecifiedAlgorithmConstraints);167this.activeProtocols = getActiveProtocols(sslConfig.enabledProtocols,168sslConfig.enabledCipherSuites, algorithmConstraints);169if (activeProtocols.isEmpty()) {170throw new SSLHandshakeException(171"No appropriate protocol (protocol is disabled or " +172"cipher suites are inappropriate)");173}174175ProtocolVersion maximumVersion = ProtocolVersion.NONE;176for (ProtocolVersion pv : this.activeProtocols) {177if (maximumVersion == ProtocolVersion.NONE ||178pv.compare(maximumVersion) > 0) {179maximumVersion = pv;180}181}182this.maximumActiveProtocol = maximumVersion;183this.activeCipherSuites = getActiveCipherSuites(this.activeProtocols,184sslConfig.enabledCipherSuites, algorithmConstraints);185if (activeCipherSuites.isEmpty()) {186throw new SSLHandshakeException("No appropriate cipher suite");187}188189this.handshakeConsumers = new LinkedHashMap<>();190this.handshakeProducers = new HashMap<>();191this.handshakeHash = conContext.inputRecord.handshakeHash;192this.handshakeOutput = new HandshakeOutStream(conContext.outputRecord);193194this.handshakeFinished = false;195this.kickstartMessageDelivered = false;196197this.delegatedActions = new LinkedList<>();198this.handshakeExtensions = new HashMap<>();199this.handshakePossessions = new LinkedList<>();200this.handshakeCredentials = new LinkedList<>();201this.requestedServerNames = null;202this.negotiatedServerName = null;203this.negotiatedCipherSuite = conContext.cipherSuite;204initialize();205}206207/**208* Constructor for PostHandshakeContext209*/210protected HandshakeContext(TransportContext conContext) {211this.sslContext = conContext.sslContext;212this.conContext = conContext;213this.sslConfig = conContext.sslConfig;214215this.negotiatedProtocol = conContext.protocolVersion;216this.negotiatedCipherSuite = conContext.cipherSuite;217this.handshakeOutput = new HandshakeOutStream(conContext.outputRecord);218this.delegatedActions = new LinkedList<>();219220this.handshakeConsumers = new LinkedHashMap<>();221this.handshakeProducers = null;222this.handshakeHash = null;223this.activeProtocols = null;224this.activeCipherSuites = null;225this.algorithmConstraints = null;226this.maximumActiveProtocol = null;227this.handshakeExtensions = Collections.emptyMap(); // Not in TLS13228this.handshakePossessions = null;229this.handshakeCredentials = null;230}231232// Initialize the non-final class variables.233private void initialize() {234ProtocolVersion inputHelloVersion;235ProtocolVersion outputHelloVersion;236if (conContext.isNegotiated) {237inputHelloVersion = conContext.protocolVersion;238outputHelloVersion = conContext.protocolVersion;239} else {240if (activeProtocols.contains(ProtocolVersion.SSL20Hello)) {241inputHelloVersion = ProtocolVersion.SSL20Hello;242243// Per TLS 1.3 protocol, implementation MUST NOT send an SSL244// version 2.0 compatible CLIENT-HELLO.245if (maximumActiveProtocol.useTLS13PlusSpec()) {246outputHelloVersion = maximumActiveProtocol;247} else {248outputHelloVersion = ProtocolVersion.SSL20Hello;249}250} else {251inputHelloVersion = maximumActiveProtocol;252outputHelloVersion = maximumActiveProtocol;253}254}255256conContext.inputRecord.setHelloVersion(inputHelloVersion);257conContext.outputRecord.setHelloVersion(outputHelloVersion);258259if (!conContext.isNegotiated) {260conContext.protocolVersion = maximumActiveProtocol;261}262conContext.outputRecord.setVersion(conContext.protocolVersion);263}264265private static List<ProtocolVersion> getActiveProtocols(266List<ProtocolVersion> enabledProtocols,267List<CipherSuite> enabledCipherSuites,268AlgorithmConstraints algorithmConstraints) {269boolean enabledSSL20Hello = false;270ArrayList<ProtocolVersion> protocols = new ArrayList<>(4);271for (ProtocolVersion protocol : enabledProtocols) {272if (!enabledSSL20Hello && protocol == ProtocolVersion.SSL20Hello) {273enabledSSL20Hello = true;274continue;275}276277if (!algorithmConstraints.permits(278EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),279protocol.name, null)) {280// Ignore disabled protocol.281continue;282}283284boolean found = false;285Map<NamedGroupType, Boolean> cachedStatus =286new EnumMap<>(NamedGroupType.class);287for (CipherSuite suite : enabledCipherSuites) {288if (suite.isAvailable() && suite.supports(protocol)) {289if (isActivatable(suite,290algorithmConstraints, cachedStatus)) {291protocols.add(protocol);292found = true;293break;294}295} else if (SSLLogger.isOn && SSLLogger.isOn("verbose")) {296SSLLogger.fine(297"Ignore unsupported cipher suite: " + suite +298" for " + protocol);299}300}301302if (!found && (SSLLogger.isOn) && SSLLogger.isOn("handshake")) {303SSLLogger.fine(304"No available cipher suite for " + protocol);305}306}307308if (!protocols.isEmpty()) {309if (enabledSSL20Hello) {310protocols.add(ProtocolVersion.SSL20Hello);311}312Collections.sort(protocols);313}314315return Collections.unmodifiableList(protocols);316}317318private static List<CipherSuite> getActiveCipherSuites(319List<ProtocolVersion> enabledProtocols,320List<CipherSuite> enabledCipherSuites,321AlgorithmConstraints algorithmConstraints) {322323List<CipherSuite> suites = new LinkedList<>();324if (enabledProtocols != null && !enabledProtocols.isEmpty()) {325Map<NamedGroupType, Boolean> cachedStatus =326new EnumMap<>(NamedGroupType.class);327for (CipherSuite suite : enabledCipherSuites) {328if (!suite.isAvailable()) {329continue;330}331332boolean isSupported = false;333for (ProtocolVersion protocol : enabledProtocols) {334if (!suite.supports(protocol)) {335continue;336}337if (isActivatable(suite,338algorithmConstraints, cachedStatus)) {339suites.add(suite);340isSupported = true;341break;342}343}344345if (!isSupported &&346SSLLogger.isOn && SSLLogger.isOn("verbose")) {347SSLLogger.finest(348"Ignore unsupported cipher suite: " + suite);349}350}351}352353return Collections.unmodifiableList(suites);354}355356/**357* Parse the handshake record and return the contentType358*/359static byte getHandshakeType(TransportContext conContext,360Plaintext plaintext) throws IOException {361// struct {362// HandshakeType msg_type; /* handshake type */363// uint24 length; /* bytes in message */364// select (HandshakeType) {365// ...366// } body;367// } Handshake;368369if (plaintext.contentType != ContentType.HANDSHAKE.id) {370throw conContext.fatal(Alert.INTERNAL_ERROR,371"Unexpected operation for record: " + plaintext.contentType);372}373374if (plaintext.fragment == null || plaintext.fragment.remaining() < 4) {375throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,376"Invalid handshake message: insufficient data");377}378379byte handshakeType = (byte)Record.getInt8(plaintext.fragment);380int handshakeLen = Record.getInt24(plaintext.fragment);381if (handshakeLen != plaintext.fragment.remaining()) {382throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,383"Invalid handshake message: insufficient handshake body");384}385386return handshakeType;387}388389void dispatch(byte handshakeType, Plaintext plaintext) throws IOException {390if (conContext.transport.useDelegatedTask()) {391boolean hasDelegated = !delegatedActions.isEmpty();392if (hasDelegated ||393(handshakeType != SSLHandshake.FINISHED.id &&394handshakeType != SSLHandshake.KEY_UPDATE.id &&395handshakeType != SSLHandshake.NEW_SESSION_TICKET.id)) {396if (!hasDelegated) {397taskDelegated = false;398delegatedThrown = null;399}400401// Clone the fragment for delegated actions.402//403// The plaintext may share the application buffers. It is404// fine to use shared buffers if no delegated actions.405// However, for delegated actions, the shared buffers may be406// polluted in application layer before the delegated actions407// executed.408ByteBuffer fragment = ByteBuffer.wrap(409new byte[plaintext.fragment.remaining()]);410fragment.put(plaintext.fragment);411fragment = (ByteBuffer)fragment.rewind();412413delegatedActions.add(new SimpleImmutableEntry<>(414handshakeType,415fragment416));417} else {418dispatch(handshakeType, plaintext.fragment);419}420} else {421dispatch(handshakeType, plaintext.fragment);422}423}424425void dispatch(byte handshakeType,426ByteBuffer fragment) throws IOException {427SSLConsumer consumer;428if (handshakeType == SSLHandshake.HELLO_REQUEST.id) {429// For TLS 1.2 and prior versions, the HelloRequest message MAY430// be sent by the server at any time.431consumer = SSLHandshake.HELLO_REQUEST;432} else {433consumer = handshakeConsumers.get(handshakeType);434}435436if (consumer == null) {437throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,438"Unexpected handshake message: " +439SSLHandshake.nameOf(handshakeType));440}441442try {443consumer.consume(this, fragment);444} catch (UnsupportedOperationException unsoe) {445throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,446"Unsupported handshake message: " +447SSLHandshake.nameOf(handshakeType), unsoe);448} catch (BufferUnderflowException | BufferOverflowException be) {449throw conContext.fatal(Alert.DECODE_ERROR,450"Illegal handshake message: " +451SSLHandshake.nameOf(handshakeType), be);452}453454// update handshake hash after handshake message consumption.455handshakeHash.consume();456}457458abstract void kickstart() throws IOException;459460/**461* Check if the given cipher suite is enabled and available within462* the current active cipher suites.463*464* Does not check if the required server certificates are available.465*/466boolean isNegotiable(CipherSuite cs) {467return isNegotiable(activeCipherSuites, cs);468}469470/**471* Check if the given cipher suite is enabled and available within472* the proposed cipher suite list.473*474* Does not check if the required server certificates are available.475*/476static final boolean isNegotiable(477List<CipherSuite> proposed, CipherSuite cs) {478return proposed.contains(cs) && cs.isNegotiable();479}480481/**482* Check if the given cipher suite is enabled and available within483* the proposed cipher suite list and specific protocol version.484*485* Does not check if the required server certificates are available.486*/487static final boolean isNegotiable(List<CipherSuite> proposed,488ProtocolVersion protocolVersion, CipherSuite cs) {489return proposed.contains(cs) &&490cs.isNegotiable() && cs.supports(protocolVersion);491}492493/**494* Check if the given protocol version is enabled and available.495*/496boolean isNegotiable(ProtocolVersion protocolVersion) {497return activeProtocols.contains(protocolVersion);498}499500/**501* Set the active protocol version and propagate it to the SSLSocket502* and our handshake streams. Called from ClientHandshaker503* and ServerHandshaker with the negotiated protocol version.504*/505void setVersion(ProtocolVersion protocolVersion) {506this.conContext.protocolVersion = protocolVersion;507}508509private static boolean isActivatable(CipherSuite suite,510AlgorithmConstraints algorithmConstraints,511Map<NamedGroupType, Boolean> cachedStatus) {512513if (algorithmConstraints.permits(514EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) {515if (suite.keyExchange == null) {516// TLS 1.3, no definition of key exchange in cipher suite.517return true;518}519520boolean available;521NamedGroupType groupType = suite.keyExchange.groupType;522if (groupType != NAMED_GROUP_NONE) {523Boolean checkedStatus = cachedStatus.get(groupType);524if (checkedStatus == null) {525available = SupportedGroups.isActivatable(526algorithmConstraints, groupType);527cachedStatus.put(groupType, available);528529if (!available &&530SSLLogger.isOn && SSLLogger.isOn("verbose")) {531SSLLogger.fine("No activated named group");532}533} else {534available = checkedStatus;535}536537if (!available && SSLLogger.isOn && SSLLogger.isOn("verbose")) {538SSLLogger.fine(539"No active named group, ignore " + suite);540}541return available;542} else {543return true;544}545} else if (SSLLogger.isOn && SSLLogger.isOn("verbose")) {546SSLLogger.fine("Ignore disabled cipher suite: " + suite);547}548549return false;550}551552List<SNIServerName> getRequestedServerNames() {553if (requestedServerNames == null) {554return Collections.<SNIServerName>emptyList();555}556return requestedServerNames;557}558}559560561562