Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/net/ssl/SSLEngine.java
38918 views
/*1* Copyright (c) 2003, 2020, 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 javax.net.ssl;2627import java.nio.ByteBuffer;28import java.nio.ReadOnlyBufferException;29import java.util.List;30import java.util.function.BiFunction;313233/**34* A class which enables secure communications using protocols such as35* the Secure Sockets Layer (SSL) or36* <A HREF="http://www.ietf.org/rfc/rfc2246.txt"> IETF RFC 2246 "Transport37* Layer Security" (TLS) </A> protocols, but is transport independent.38* <P>39* The secure communications modes include: <UL>40*41* <LI> <em>Integrity Protection</em>. SSL/TLS protects against42* modification of messages by an active wiretapper.43*44* <LI> <em>Authentication</em>. In most modes, SSL/TLS provides45* peer authentication. Servers are usually authenticated, and46* clients may be authenticated as requested by servers.47*48* <LI> <em>Confidentiality (Privacy Protection)</em>. In most49* modes, SSL/TLS encrypts data being sent between client and50* server. This protects the confidentiality of data, so that51* passive wiretappers won't see sensitive data such as financial52* information or personal information of many kinds.53*54* </UL>55*56* These kinds of protection are specified by a "cipher suite", which57* is a combination of cryptographic algorithms used by a given SSL58* connection. During the negotiation process, the two endpoints must59* agree on a cipher suite that is available in both environments. If60* there is no such suite in common, no SSL connection can be61* established, and no data can be exchanged.62* <P>63* The cipher suite used is established by a negotiation process called64* "handshaking". The goal of this process is to create or rejoin a65* "session", which may protect many connections over time. After66* handshaking has completed, you can access session attributes by67* using the {@link #getSession()} method.68* <P>69* The <code>SSLSocket</code> class provides much of the same security70* functionality, but all of the inbound and outbound data is71* automatically transported using the underlying {@link72* java.net.Socket Socket}, which by design uses a blocking model.73* While this is appropriate for many applications, this model does not74* provide the scalability required by large servers.75* <P>76* The primary distinction of an <code>SSLEngine</code> is that it77* operates on inbound and outbound byte streams, independent of the78* transport mechanism. It is the responsibility of the79* <code>SSLEngine</code> user to arrange for reliable I/O transport to80* the peer. By separating the SSL/TLS abstraction from the I/O81* transport mechanism, the <code>SSLEngine</code> can be used for a82* wide variety of I/O types, such as {@link83* java.nio.channels.spi.AbstractSelectableChannel#configureBlocking(boolean)84* non-blocking I/O (polling)}, {@link java.nio.channels.Selector85* selectable non-blocking I/O}, {@link java.net.Socket Socket} and the86* traditional Input/OutputStreams, local {@link java.nio.ByteBuffer87* ByteBuffers} or byte arrays, <A88* HREF="http://www.jcp.org/en/jsr/detail?id=203"> future asynchronous89* I/O models </A>, and so on.90* <P>91* At a high level, the <code>SSLEngine</code> appears thus:92*93* <pre>94* app data95*96* | ^97* | | |98* v | |99* +----+-----|-----+----+100* | | |101* | SSL|Engine |102* wrap() | | | unwrap()103* | OUTBOUND | INBOUND |104* | | |105* +----+-----|-----+----+106* | | ^107* | | |108* v |109*110* net data111* </pre>112* Application data (also known as plaintext or cleartext) is data which113* is produced or consumed by an application. Its counterpart is114* network data, which consists of either handshaking and/or ciphertext115* (encrypted) data, and destined to be transported via an I/O116* mechanism. Inbound data is data which has been received from the117* peer, and outbound data is destined for the peer.118* <P>119* (In the context of an <code>SSLEngine</code>, the term "handshake120* data" is taken to mean any data exchanged to establish and control a121* secure connection. Handshake data includes the SSL/TLS messages122* "alert", "change_cipher_spec," and "handshake.")123* <P>124* There are five distinct phases to an <code>SSLEngine</code>.125*126* <OL>127* <li> Creation - The <code>SSLEngine</code> has been created and128* initialized, but has not yet been used. During this phase, an129* application may set any <code>SSLEngine</code>-specific settings130* (enabled cipher suites, whether the <code>SSLEngine</code> should131* handshake in client or server mode, and so on). Once132* handshaking has begun, though, any new settings (except133* client/server mode, see below) will be used for134* the next handshake.135*136* <li> Initial Handshake - The initial handshake is a procedure by137* which the two peers exchange communication parameters until an138* SSLSession is established. Application data can not be sent during139* this phase.140*141* <li> Application Data - Once the communication parameters have142* been established and the handshake is complete, application data143* may flow through the <code>SSLEngine</code>. Outbound144* application messages are encrypted and integrity protected,145* and inbound messages reverse the process.146*147* <li> Rehandshaking - Either side may request a renegotiation of148* the session at any time during the Application Data phase. New149* handshaking data can be intermixed among the application data.150* Before starting the rehandshake phase, the application may151* reset the SSL/TLS communication parameters such as the list of152* enabled ciphersuites and whether to use client authentication,153* but can not change between client/server modes. As before, once154* handshaking has begun, any new <code>SSLEngine</code>155* configuration settings will not be used until the next156* handshake.157*158* <li> Closure - When the connection is no longer needed, the159* application should close the <code>SSLEngine</code> and should160* send/receive any remaining messages to the peer before161* closing the underlying transport mechanism. Once an engine is162* closed, it is not reusable: a new <code>SSLEngine</code> must163* be created.164* </OL>165* An <code>SSLEngine</code> is created by calling {@link166* SSLContext#createSSLEngine()} from an initialized167* <code>SSLContext</code>. Any configuration168* parameters should be set before making the first call to169* <code>wrap()</code>, <code>unwrap()</code>, or170* <code>beginHandshake()</code>. These methods all trigger the171* initial handshake.172* <P>173* Data moves through the engine by calling {@link #wrap(ByteBuffer,174* ByteBuffer) wrap()} or {@link #unwrap(ByteBuffer, ByteBuffer)175* unwrap()} on outbound or inbound data, respectively. Depending on176* the state of the <code>SSLEngine</code>, a <code>wrap()</code> call177* may consume application data from the source buffer and may produce178* network data in the destination buffer. The outbound data179* may contain application and/or handshake data. A call to180* <code>unwrap()</code> will examine the source buffer and may181* advance the handshake if the data is handshaking information, or182* may place application data in the destination buffer if the data183* is application. The state of the underlying SSL/TLS algorithm184* will determine when data is consumed and produced.185* <P>186* Calls to <code>wrap()</code> and <code>unwrap()</code> return an187* <code>SSLEngineResult</code> which indicates the status of the188* operation, and (optionally) how to interact with the engine to make189* progress.190* <P>191* The <code>SSLEngine</code> produces/consumes complete SSL/TLS192* packets only, and does not store application data internally between193* calls to <code>wrap()/unwrap()</code>. Thus input and output194* <code>ByteBuffer</code>s must be sized appropriately to hold the195* maximum record that can be produced. Calls to {@link196* SSLSession#getPacketBufferSize()} and {@link197* SSLSession#getApplicationBufferSize()} should be used to determine198* the appropriate buffer sizes. The size of the outbound application199* data buffer generally does not matter. If buffer conditions do not200* allow for the proper consumption/production of data, the application201* must determine (via {@link SSLEngineResult}) and correct the202* problem, and then try the call again.203* <P>204* For example, <code>unwrap()</code> will return a {@link205* SSLEngineResult.Status#BUFFER_OVERFLOW} result if the engine206* determines that there is not enough destination buffer space available.207* Applications should call {@link SSLSession#getApplicationBufferSize()}208* and compare that value with the space available in the destination buffer,209* enlarging the buffer if necessary. Similarly, if <code>unwrap()</code>210* were to return a {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}, the211* application should call {@link SSLSession#getPacketBufferSize()} to ensure212* that the source buffer has enough room to hold a record (enlarging if213* necessary), and then obtain more inbound data.214*215* <pre>{@code216* SSLEngineResult r = engine.unwrap(src, dst);217* switch (r.getStatus()) {218* BUFFER_OVERFLOW:219* // Could attempt to drain the dst buffer of any already obtained220* // data, but we'll just increase it to the size needed.221* int appSize = engine.getSession().getApplicationBufferSize();222* ByteBuffer b = ByteBuffer.allocate(appSize + dst.position());223* dst.flip();224* b.put(dst);225* dst = b;226* // retry the operation.227* break;228* BUFFER_UNDERFLOW:229* int netSize = engine.getSession().getPacketBufferSize();230* // Resize buffer if needed.231* if (netSize > dst.capacity()) {232* ByteBuffer b = ByteBuffer.allocate(netSize);233* src.flip();234* b.put(src);235* src = b;236* }237* // Obtain more inbound network data for src,238* // then retry the operation.239* break;240* // other cases: CLOSED, OK.241* }242* }</pre>243*244* <P>245* Unlike <code>SSLSocket</code>, all methods of SSLEngine are246* non-blocking. <code>SSLEngine</code> implementations may247* require the results of tasks that may take an extended period of248* time to complete, or may even block. For example, a TrustManager249* may need to connect to a remote certificate validation service,250* or a KeyManager might need to prompt a user to determine which251* certificate to use as part of client authentication. Additionally,252* creating cryptographic signatures and verifying them can be slow,253* seemingly blocking.254* <P>255* For any operation which may potentially block, the256* <code>SSLEngine</code> will create a {@link java.lang.Runnable}257* delegated task. When <code>SSLEngineResult</code> indicates that a258* delegated task result is needed, the application must call {@link259* #getDelegatedTask()} to obtain an outstanding delegated task and260* call its {@link java.lang.Runnable#run() run()} method (possibly using261* a different thread depending on the compute strategy). The262* application should continue obtaining delegated tasks until no more263* exist, and try the original operation again.264* <P>265* At the end of a communication session, applications should properly266* close the SSL/TLS link. The SSL/TLS protocols have closure handshake267* messages, and these messages should be communicated to the peer268* before releasing the <code>SSLEngine</code> and closing the269* underlying transport mechanism. A close can be initiated by one of:270* an SSLException, an inbound closure handshake message, or one of the271* close methods. In all cases, closure handshake messages are272* generated by the engine, and <code>wrap()</code> should be repeatedly273* called until the resulting <code>SSLEngineResult</code>'s status274* returns "CLOSED", or {@link #isOutboundDone()} returns true. All275* data obtained from the <code>wrap()</code> method should be sent to the276* peer.277* <P>278* {@link #closeOutbound()} is used to signal the engine that the279* application will not be sending any more data.280* <P>281* A peer will signal its intent to close by sending its own closure282* handshake message. After this message has been received and283* processed by the local <code>SSLEngine</code>'s <code>unwrap()</code>284* call, the application can detect the close by calling285* <code>unwrap()</code> and looking for a <code>SSLEngineResult</code>286* with status "CLOSED", or if {@link #isInboundDone()} returns true.287* If for some reason the peer closes the communication link without288* sending the proper SSL/TLS closure message, the application can289* detect the end-of-stream and can signal the engine via {@link290* #closeInbound()} that there will no more inbound messages to291* process. Some applications might choose to require orderly shutdown292* messages from a peer, in which case they can check that the closure293* was generated by a handshake message and not by an end-of-stream294* condition.295* <P>296* There are two groups of cipher suites which you will need to know297* about when managing cipher suites:298*299* <UL>300* <LI> <em>Supported</em> cipher suites: all the suites which are301* supported by the SSL implementation. This list is reported302* using {@link #getSupportedCipherSuites()}.303*304* <LI> <em>Enabled</em> cipher suites, which may be fewer than305* the full set of supported suites. This group is set using the306* {@link #setEnabledCipherSuites(String [])} method, and307* queried using the {@link #getEnabledCipherSuites()} method.308* Initially, a default set of cipher suites will be enabled on a309* new engine that represents the minimum suggested310* configuration.311* </UL>312*313* Implementation defaults require that only cipher suites which314* authenticate servers and provide confidentiality be enabled by315* default. Only if both sides explicitly agree to unauthenticated316* and/or non-private (unencrypted) communications will such a317* cipher suite be selected.318* <P>319* Each SSL/TLS connection must have one client and one server, thus320* each endpoint must decide which role to assume. This choice determines321* who begins the handshaking process as well as which type of messages322* should be sent by each party. The method {@link323* #setUseClientMode(boolean)} configures the mode. Once the initial324* handshaking has started, an <code>SSLEngine</code> can not switch325* between client and server modes, even when performing renegotiations.326* <P>327* Applications might choose to process delegated tasks in different328* threads. When an <code>SSLEngine</code>329* is created, the current {@link java.security.AccessControlContext}330* is saved. All future delegated tasks will be processed using this331* context: that is, all access control decisions will be made using the332* context captured at engine creation.333*334* <HR>335*336* <B>Concurrency Notes</B>:337* There are two concurrency issues to be aware of:338*339* <OL>340* <li>The <code>wrap()</code> and <code>unwrap()</code> methods341* may execute concurrently of each other.342*343* <li> The SSL/TLS protocols employ ordered packets.344* Applications must take care to ensure that generated packets345* are delivered in sequence. If packets arrive346* out-of-order, unexpected or fatal results may occur.347* <P>348* For example:349*350* <pre>351* synchronized (outboundLock) {352* sslEngine.wrap(src, dst);353* outboundQueue.put(dst);354* }355* </pre>356*357* As a corollary, two threads must not attempt to call the same method358* (either <code>wrap()</code> or <code>unwrap()</code>) concurrently,359* because there is no way to guarantee the eventual packet ordering.360* </OL>361*362* @see SSLContext363* @see SSLSocket364* @see SSLServerSocket365* @see SSLSession366* @see java.net.Socket367*368* @since 1.5369* @author Brad R. Wetmore370*/371372public abstract class SSLEngine {373374private String peerHost = null;375private int peerPort = -1;376377/**378* Constructor for an <code>SSLEngine</code> providing no hints379* for an internal session reuse strategy.380*381* @see SSLContext#createSSLEngine()382* @see SSLSessionContext383*/384protected SSLEngine() {385}386387/**388* Constructor for an <code>SSLEngine</code>.389* <P>390* <code>SSLEngine</code> implementations may use the391* <code>peerHost</code> and <code>peerPort</code> parameters as hints392* for their internal session reuse strategy.393* <P>394* Some cipher suites (such as Kerberos) require remote hostname395* information. Implementations of this class should use this396* constructor to use Kerberos.397* <P>398* The parameters are not authenticated by the399* <code>SSLEngine</code>.400*401* @param peerHost the name of the peer host402* @param peerPort the port number of the peer403* @see SSLContext#createSSLEngine(String, int)404* @see SSLSessionContext405*/406protected SSLEngine(String peerHost, int peerPort) {407this.peerHost = peerHost;408this.peerPort = peerPort;409}410411/**412* Returns the host name of the peer.413* <P>414* Note that the value is not authenticated, and should not be415* relied upon.416*417* @return the host name of the peer, or null if nothing is418* available.419*/420public String getPeerHost() {421return peerHost;422}423424/**425* Returns the port number of the peer.426* <P>427* Note that the value is not authenticated, and should not be428* relied upon.429*430* @return the port number of the peer, or -1 if nothing is431* available.432*/433public int getPeerPort() {434return peerPort;435}436437/**438* Attempts to encode a buffer of plaintext application data into439* SSL/TLS network data.440* <P>441* An invocation of this method behaves in exactly the same manner442* as the invocation:443* <blockquote><pre>444* {@link #wrap(ByteBuffer [], int, int, ByteBuffer)445* engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);}446* </pre></blockquote>447*448* @param src449* a <code>ByteBuffer</code> containing outbound application data450* @param dst451* a <code>ByteBuffer</code> to hold outbound network data452* @return an <code>SSLEngineResult</code> describing the result453* of this operation.454* @throws SSLException455* A problem was encountered while processing the456* data that caused the <code>SSLEngine</code> to abort.457* See the class description for more information on458* engine closure.459* @throws ReadOnlyBufferException460* if the <code>dst</code> buffer is read-only.461* @throws IllegalArgumentException462* if either <code>src</code> or <code>dst</code>463* is null.464* @throws IllegalStateException if the client/server mode465* has not yet been set.466* @see #wrap(ByteBuffer [], int, int, ByteBuffer)467*/468public SSLEngineResult wrap(ByteBuffer src,469ByteBuffer dst) throws SSLException {470return wrap(new ByteBuffer [] { src }, 0, 1, dst);471}472473/**474* Attempts to encode plaintext bytes from a sequence of data475* buffers into SSL/TLS network data.476* <P>477* An invocation of this method behaves in exactly the same manner478* as the invocation:479* <blockquote><pre>480* {@link #wrap(ByteBuffer [], int, int, ByteBuffer)481* engine.wrap(srcs, 0, srcs.length, dst);}482* </pre></blockquote>483*484* @param srcs485* an array of <code>ByteBuffers</code> containing the486* outbound application data487* @param dst488* a <code>ByteBuffer</code> to hold outbound network data489* @return an <code>SSLEngineResult</code> describing the result490* of this operation.491* @throws SSLException492* A problem was encountered while processing the493* data that caused the <code>SSLEngine</code> to abort.494* See the class description for more information on495* engine closure.496* @throws ReadOnlyBufferException497* if the <code>dst</code> buffer is read-only.498* @throws IllegalArgumentException499* if either <code>srcs</code> or <code>dst</code>500* is null, or if any element in <code>srcs</code> is null.501* @throws IllegalStateException if the client/server mode502* has not yet been set.503* @see #wrap(ByteBuffer [], int, int, ByteBuffer)504*/505public SSLEngineResult wrap(ByteBuffer [] srcs,506ByteBuffer dst) throws SSLException {507if (srcs == null) {508throw new IllegalArgumentException("src == null");509}510return wrap(srcs, 0, srcs.length, dst);511}512513514/**515* Attempts to encode plaintext bytes from a subsequence of data516* buffers into SSL/TLS network data. This <i>"gathering"</i>517* operation encodes, in a single invocation, a sequence of bytes518* from one or more of a given sequence of buffers. Gathering519* wraps are often useful when implementing network protocols or520* file formats that, for example, group data into segments521* consisting of one or more fixed-length headers followed by a522* variable-length body. See523* {@link java.nio.channels.GatheringByteChannel} for more524* information on gathering, and {@link525* java.nio.channels.GatheringByteChannel#write(ByteBuffer[],526* int, int)} for more information on the subsequence527* behavior.528* <P>529* Depending on the state of the SSLEngine, this method may produce530* network data without consuming any application data (for example,531* it may generate handshake data.)532* <P>533* The application is responsible for reliably transporting the534* network data to the peer, and for ensuring that data created by535* multiple calls to wrap() is transported in the same order in which536* it was generated. The application must properly synchronize537* multiple calls to this method.538* <P>539* If this <code>SSLEngine</code> has not yet started its initial540* handshake, this method will automatically start the handshake.541* <P>542* This method will attempt to produce SSL/TLS records, and will543* consume as much source data as possible, but will never consume544* more than the sum of the bytes remaining in each buffer. Each545* <code>ByteBuffer</code>'s position is updated to reflect the546* amount of data consumed or produced. The limits remain the547* same.548* <P>549* The underlying memory used by the <code>srcs</code> and550* <code>dst ByteBuffer</code>s must not be the same.551* <P>552* See the class description for more information on engine closure.553*554* @param srcs555* an array of <code>ByteBuffers</code> containing the556* outbound application data557* @param offset558* The offset within the buffer array of the first buffer from559* which bytes are to be retrieved; it must be non-negative560* and no larger than <code>srcs.length</code>561* @param length562* The maximum number of buffers to be accessed; it must be563* non-negative and no larger than564* <code>srcs.length</code> - <code>offset</code>565* @param dst566* a <code>ByteBuffer</code> to hold outbound network data567* @return an <code>SSLEngineResult</code> describing the result568* of this operation.569* @throws SSLException570* A problem was encountered while processing the571* data that caused the <code>SSLEngine</code> to abort.572* See the class description for more information on573* engine closure.574* @throws IndexOutOfBoundsException575* if the preconditions on the <code>offset</code> and576* <code>length</code> parameters do not hold.577* @throws ReadOnlyBufferException578* if the <code>dst</code> buffer is read-only.579* @throws IllegalArgumentException580* if either <code>srcs</code> or <code>dst</code>581* is null, or if any element in the <code>srcs</code>582* subsequence specified is null.583* @throws IllegalStateException if the client/server mode584* has not yet been set.585* @see java.nio.channels.GatheringByteChannel586* @see java.nio.channels.GatheringByteChannel#write(587* ByteBuffer[], int, int)588*/589public abstract SSLEngineResult wrap(ByteBuffer [] srcs, int offset,590int length, ByteBuffer dst) throws SSLException;591592/**593* Attempts to decode SSL/TLS network data into a plaintext594* application data buffer.595* <P>596* An invocation of this method behaves in exactly the same manner597* as the invocation:598* <blockquote><pre>599* {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)600* engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);}601* </pre></blockquote>602*603* @param src604* a <code>ByteBuffer</code> containing inbound network data.605* @param dst606* a <code>ByteBuffer</code> to hold inbound application data.607* @return an <code>SSLEngineResult</code> describing the result608* of this operation.609* @throws SSLException610* A problem was encountered while processing the611* data that caused the <code>SSLEngine</code> to abort.612* See the class description for more information on613* engine closure.614* @throws ReadOnlyBufferException615* if the <code>dst</code> buffer is read-only.616* @throws IllegalArgumentException617* if either <code>src</code> or <code>dst</code>618* is null.619* @throws IllegalStateException if the client/server mode620* has not yet been set.621* @see #unwrap(ByteBuffer, ByteBuffer [], int, int)622*/623public SSLEngineResult unwrap(ByteBuffer src,624ByteBuffer dst) throws SSLException {625return unwrap(src, new ByteBuffer [] { dst }, 0, 1);626}627628/**629* Attempts to decode SSL/TLS network data into a sequence of plaintext630* application data buffers.631* <P>632* An invocation of this method behaves in exactly the same manner633* as the invocation:634* <blockquote><pre>635* {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)636* engine.unwrap(src, dsts, 0, dsts.length);}637* </pre></blockquote>638*639* @param src640* a <code>ByteBuffer</code> containing inbound network data.641* @param dsts642* an array of <code>ByteBuffer</code>s to hold inbound643* application data.644* @return an <code>SSLEngineResult</code> describing the result645* of this operation.646* @throws SSLException647* A problem was encountered while processing the648* data that caused the <code>SSLEngine</code> to abort.649* See the class description for more information on650* engine closure.651* @throws ReadOnlyBufferException652* if any of the <code>dst</code> buffers are read-only.653* @throws IllegalArgumentException654* if either <code>src</code> or <code>dsts</code>655* is null, or if any element in <code>dsts</code> is null.656* @throws IllegalStateException if the client/server mode657* has not yet been set.658* @see #unwrap(ByteBuffer, ByteBuffer [], int, int)659*/660public SSLEngineResult unwrap(ByteBuffer src,661ByteBuffer [] dsts) throws SSLException {662if (dsts == null) {663throw new IllegalArgumentException("dsts == null");664}665return unwrap(src, dsts, 0, dsts.length);666}667668/**669* Attempts to decode SSL/TLS network data into a subsequence of670* plaintext application data buffers. This <i>"scattering"</i>671* operation decodes, in a single invocation, a sequence of bytes672* into one or more of a given sequence of buffers. Scattering673* unwraps are often useful when implementing network protocols or674* file formats that, for example, group data into segments675* consisting of one or more fixed-length headers followed by a676* variable-length body. See677* {@link java.nio.channels.ScatteringByteChannel} for more678* information on scattering, and {@link679* java.nio.channels.ScatteringByteChannel#read(ByteBuffer[],680* int, int)} for more information on the subsequence681* behavior.682* <P>683* Depending on the state of the SSLEngine, this method may consume684* network data without producing any application data (for example,685* it may consume handshake data.)686* <P>687* The application is responsible for reliably obtaining the network688* data from the peer, and for invoking unwrap() on the data in the689* order it was received. The application must properly synchronize690* multiple calls to this method.691* <P>692* If this <code>SSLEngine</code> has not yet started its initial693* handshake, this method will automatically start the handshake.694* <P>695* This method will attempt to consume one complete SSL/TLS network696* packet, but will never consume more than the sum of the bytes697* remaining in the buffers. Each <code>ByteBuffer</code>'s698* position is updated to reflect the amount of data consumed or699* produced. The limits remain the same.700* <P>701* The underlying memory used by the <code>src</code> and702* <code>dsts ByteBuffer</code>s must not be the same.703* <P>704* The inbound network buffer may be modified as a result of this705* call: therefore if the network data packet is required for some706* secondary purpose, the data should be duplicated before calling this707* method. Note: the network data will not be useful to a second708* SSLEngine, as each SSLEngine contains unique random state which709* influences the SSL/TLS messages.710* <P>711* See the class description for more information on engine closure.712*713* @param src714* a <code>ByteBuffer</code> containing inbound network data.715* @param dsts716* an array of <code>ByteBuffer</code>s to hold inbound717* application data.718* @param offset719* The offset within the buffer array of the first buffer from720* which bytes are to be transferred; it must be non-negative721* and no larger than <code>dsts.length</code>.722* @param length723* The maximum number of buffers to be accessed; it must be724* non-negative and no larger than725* <code>dsts.length</code> - <code>offset</code>.726* @return an <code>SSLEngineResult</code> describing the result727* of this operation.728* @throws SSLException729* A problem was encountered while processing the730* data that caused the <code>SSLEngine</code> to abort.731* See the class description for more information on732* engine closure.733* @throws IndexOutOfBoundsException734* If the preconditions on the <code>offset</code> and735* <code>length</code> parameters do not hold.736* @throws ReadOnlyBufferException737* if any of the <code>dst</code> buffers are read-only.738* @throws IllegalArgumentException739* if either <code>src</code> or <code>dsts</code>740* is null, or if any element in the <code>dsts</code>741* subsequence specified is null.742* @throws IllegalStateException if the client/server mode743* has not yet been set.744* @see java.nio.channels.ScatteringByteChannel745* @see java.nio.channels.ScatteringByteChannel#read(746* ByteBuffer[], int, int)747*/748public abstract SSLEngineResult unwrap(ByteBuffer src,749ByteBuffer [] dsts, int offset, int length) throws SSLException;750751752/**753* Returns a delegated <code>Runnable</code> task for754* this <code>SSLEngine</code>.755* <P>756* <code>SSLEngine</code> operations may require the results of757* operations that block, or may take an extended period of time to758* complete. This method is used to obtain an outstanding {@link759* java.lang.Runnable} operation (task). Each task must be assigned760* a thread (possibly the current) to perform the {@link761* java.lang.Runnable#run() run} operation. Once the762* <code>run</code> method returns, the <code>Runnable</code> object763* is no longer needed and may be discarded.764* <P>765* Delegated tasks run in the <code>AccessControlContext</code>766* in place when this object was created.767* <P>768* A call to this method will return each outstanding task769* exactly once.770* <P>771* Multiple delegated tasks can be run in parallel.772*773* @return a delegated <code>Runnable</code> task, or null774* if none are available.775*/776public abstract Runnable getDelegatedTask();777778779/**780* Signals that no more inbound network data will be sent781* to this <code>SSLEngine</code>.782* <P>783* If the application initiated the closing process by calling784* {@link #closeOutbound()}, under some circumstances it is not785* required that the initiator wait for the peer's corresponding786* close message. (See section 7.2.1 of the TLS specification (<A787* HREF="http://www.ietf.org/rfc/rfc2246.txt">RFC 2246</A>) for more788* information on waiting for closure alerts.) In such cases, this789* method need not be called.790* <P>791* But if the application did not initiate the closure process, or792* if the circumstances above do not apply, this method should be793* called whenever the end of the SSL/TLS data stream is reached.794* This ensures closure of the inbound side, and checks that the795* peer followed the SSL/TLS close procedure properly, thus796* detecting possible truncation attacks.797* <P>798* This method is idempotent: if the inbound side has already799* been closed, this method does not do anything.800* <P>801* {@link #wrap(ByteBuffer, ByteBuffer) wrap()} should be802* called to flush any remaining handshake data.803*804* @throws SSLException805* if this engine has not received the proper SSL/TLS close806* notification message from the peer.807*808* @see #isInboundDone()809* @see #isOutboundDone()810*/811public abstract void closeInbound() throws SSLException;812813814/**815* Returns whether {@link #unwrap(ByteBuffer, ByteBuffer)} will816* accept any more inbound data messages.817*818* @return true if the <code>SSLEngine</code> will not819* consume anymore network data (and by implication,820* will not produce any more application data.)821* @see #closeInbound()822*/823public abstract boolean isInboundDone();824825826/**827* Signals that no more outbound application data will be sent828* on this <code>SSLEngine</code>.829* <P>830* This method is idempotent: if the outbound side has already831* been closed, this method does not do anything.832* <P>833* {@link #wrap(ByteBuffer, ByteBuffer)} should be834* called to flush any remaining handshake data.835*836* @see #isOutboundDone()837*/838public abstract void closeOutbound();839840841/**842* Returns whether {@link #wrap(ByteBuffer, ByteBuffer)} will843* produce any more outbound data messages.844* <P>845* Note that during the closure phase, a <code>SSLEngine</code> may846* generate handshake closure data that must be sent to the peer.847* <code>wrap()</code> must be called to generate this data. When848* this method returns true, no more outbound data will be created.849*850* @return true if the <code>SSLEngine</code> will not produce851* any more network data852*853* @see #closeOutbound()854* @see #closeInbound()855*/856public abstract boolean isOutboundDone();857858859/**860* Returns the names of the cipher suites which could be enabled for use861* on this engine. Normally, only a subset of these will actually862* be enabled by default, since this list may include cipher suites which863* do not meet quality of service requirements for those defaults. Such864* cipher suites might be useful in specialized applications.865*866* @return an array of cipher suite names867* @see #getEnabledCipherSuites()868* @see #setEnabledCipherSuites(String [])869*/870public abstract String [] getSupportedCipherSuites();871872873/**874* Returns the names of the SSL cipher suites which are currently875* enabled for use on this engine. When an SSLEngine is first876* created, all enabled cipher suites support a minimum quality of877* service. Thus, in some environments this value might be empty.878* <P>879* Even if a suite has been enabled, it might never be used. (For880* example, the peer does not support it, the requisite881* certificates/private keys for the suite are not available, or an882* anonymous suite is enabled but authentication is required.)883*884* @return an array of cipher suite names885* @see #getSupportedCipherSuites()886* @see #setEnabledCipherSuites(String [])887*/888public abstract String [] getEnabledCipherSuites();889890891/**892* Sets the cipher suites enabled for use on this engine.893* <P>894* Each cipher suite in the <code>suites</code> parameter must have895* been listed by getSupportedCipherSuites(), or the method will896* fail. Following a successful call to this method, only suites897* listed in the <code>suites</code> parameter are enabled for use.898* <P>899* See {@link #getEnabledCipherSuites()} for more information900* on why a specific cipher suite may never be used on a engine.901*902* @param suites Names of all the cipher suites to enable903* @throws IllegalArgumentException when one or more of the ciphers904* named by the parameter is not supported, or when the905* parameter is null.906* @see #getSupportedCipherSuites()907* @see #getEnabledCipherSuites()908*/909public abstract void setEnabledCipherSuites(String suites []);910911912/**913* Returns the names of the protocols which could be enabled for use914* with this <code>SSLEngine</code>.915*916* @return an array of protocols supported917*/918public abstract String [] getSupportedProtocols();919920921/**922* Returns the names of the protocol versions which are currently923* enabled for use with this <code>SSLEngine</code>.924*925* @return an array of protocols926* @see #setEnabledProtocols(String [])927*/928public abstract String [] getEnabledProtocols();929930931/**932* Set the protocol versions enabled for use on this engine.933* <P>934* The protocols must have been listed by getSupportedProtocols()935* as being supported. Following a successful call to this method,936* only protocols listed in the <code>protocols</code> parameter937* are enabled for use.938*939* @param protocols Names of all the protocols to enable.940* @throws IllegalArgumentException when one or more of941* the protocols named by the parameter is not supported or942* when the protocols parameter is null.943* @see #getEnabledProtocols()944*/945public abstract void setEnabledProtocols(String protocols[]);946947948/**949* Returns the <code>SSLSession</code> in use in this950* <code>SSLEngine</code>.951* <P>952* These can be long lived, and frequently correspond to an entire953* login session for some user. The session specifies a particular954* cipher suite which is being actively used by all connections in955* that session, as well as the identities of the session's client956* and server.957* <P>958* Unlike {@link SSLSocket#getSession()}959* this method does not block until handshaking is complete.960* <P>961* Until the initial handshake has completed, this method returns962* a session object which reports an invalid cipher suite of963* "SSL_NULL_WITH_NULL_NULL".964*965* @return the <code>SSLSession</code> for this <code>SSLEngine</code>966* @see SSLSession967*/968public abstract SSLSession getSession();969970971/**972* Returns the {@code SSLSession} being constructed during a SSL/TLS973* handshake.974* <p>975* TLS protocols may negotiate parameters that are needed when using976* an instance of this class, but before the {@code SSLSession} has977* been completely initialized and made available via {@code getSession}.978* For example, the list of valid signature algorithms may restrict979* the type of certificates that can used during TrustManager980* decisions, or the maximum TLS fragment packet sizes can be981* resized to better support the network environment.982* <p>983* This method provides early access to the {@code SSLSession} being984* constructed. Depending on how far the handshake has progressed,985* some data may not yet be available for use. For example, if a986* remote server will be sending a Certificate chain, but that chain987* has yet not been processed, the {@code getPeerCertificates}988* method of {@code SSLSession} will throw a989* SSLPeerUnverifiedException. Once that chain has been processed,990* {@code getPeerCertificates} will return the proper value.991*992* @see SSLSocket993* @see SSLSession994* @see ExtendedSSLSession995* @see X509ExtendedKeyManager996* @see X509ExtendedTrustManager997*998* @return null if this instance is not currently handshaking, or999* if the current handshake has not progressed far enough to1000* create a basic SSLSession. Otherwise, this method returns the1001* {@code SSLSession} currently being negotiated.1002* @throws UnsupportedOperationException if the underlying provider1003* does not implement the operation.1004*1005* @since 1.71006*/1007public SSLSession getHandshakeSession() {1008throw new UnsupportedOperationException();1009}101010111012/**1013* Initiates handshaking (initial or renegotiation) on this SSLEngine.1014* <P>1015* This method is not needed for the initial handshake, as the1016* <code>wrap()</code> and <code>unwrap()</code> methods will1017* implicitly call this method if handshaking has not already begun.1018* <P>1019* Note that the peer may also request a session renegotiation with1020* this <code>SSLEngine</code> by sending the appropriate1021* session renegotiate handshake message.1022* <P>1023* Unlike the {@link SSLSocket#startHandshake()1024* SSLSocket#startHandshake()} method, this method does not block1025* until handshaking is completed.1026* <P>1027* To force a complete SSL/TLS session renegotiation, the current1028* session should be invalidated prior to calling this method.1029* <P>1030* Some protocols may not support multiple handshakes on an existing1031* engine and may throw an <code>SSLException</code>.1032*1033* @throws SSLException1034* if a problem was encountered while signaling the1035* <code>SSLEngine</code> to begin a new handshake.1036* See the class description for more information on1037* engine closure.1038* @throws IllegalStateException if the client/server mode1039* has not yet been set.1040* @see SSLSession#invalidate()1041*/1042public abstract void beginHandshake() throws SSLException;104310441045/**1046* Returns the current handshake status for this <code>SSLEngine</code>.1047*1048* @return the current <code>SSLEngineResult.HandshakeStatus</code>.1049*/1050public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();105110521053/**1054* Configures the engine to use client (or server) mode when1055* handshaking.1056* <P>1057* This method must be called before any handshaking occurs.1058* Once handshaking has begun, the mode can not be reset for the1059* life of this engine.1060* <P>1061* Servers normally authenticate themselves, and clients1062* are not required to do so.1063*1064* @param mode true if the engine should start its handshaking1065* in "client" mode1066* @throws IllegalArgumentException if a mode change is attempted1067* after the initial handshake has begun.1068* @see #getUseClientMode()1069*/1070public abstract void setUseClientMode(boolean mode);107110721073/**1074* Returns true if the engine is set to use client mode when1075* handshaking.1076*1077* @return true if the engine should do handshaking1078* in "client" mode1079* @see #setUseClientMode(boolean)1080*/1081public abstract boolean getUseClientMode();108210831084/**1085* Configures the engine to <i>require</i> client authentication. This1086* option is only useful for engines in the server mode.1087* <P>1088* An engine's client authentication setting is one of the following:1089* <ul>1090* <li> client authentication required1091* <li> client authentication requested1092* <li> no client authentication desired1093* </ul>1094* <P>1095* Unlike {@link #setWantClientAuth(boolean)}, if this option is set and1096* the client chooses not to provide authentication information1097* about itself, <i>the negotiations will stop and the engine will1098* begin its closure procedure</i>.1099* <P>1100* Calling this method overrides any previous setting made by1101* this method or {@link #setWantClientAuth(boolean)}.1102*1103* @param need set to true if client authentication is required,1104* or false if no client authentication is desired.1105* @see #getNeedClientAuth()1106* @see #setWantClientAuth(boolean)1107* @see #getWantClientAuth()1108* @see #setUseClientMode(boolean)1109*/1110public abstract void setNeedClientAuth(boolean need);111111121113/**1114* Returns true if the engine will <i>require</i> client authentication.1115* This option is only useful to engines in the server mode.1116*1117* @return true if client authentication is required,1118* or false if no client authentication is desired.1119* @see #setNeedClientAuth(boolean)1120* @see #setWantClientAuth(boolean)1121* @see #getWantClientAuth()1122* @see #setUseClientMode(boolean)1123*/1124public abstract boolean getNeedClientAuth();112511261127/**1128* Configures the engine to <i>request</i> client authentication.1129* This option is only useful for engines in the server mode.1130* <P>1131* An engine's client authentication setting is one of the following:1132* <ul>1133* <li> client authentication required1134* <li> client authentication requested1135* <li> no client authentication desired1136* </ul>1137* <P>1138* Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and1139* the client chooses not to provide authentication information1140* about itself, <i>the negotiations will continue</i>.1141* <P>1142* Calling this method overrides any previous setting made by1143* this method or {@link #setNeedClientAuth(boolean)}.1144*1145* @param want set to true if client authentication is requested,1146* or false if no client authentication is desired.1147* @see #getWantClientAuth()1148* @see #setNeedClientAuth(boolean)1149* @see #getNeedClientAuth()1150* @see #setUseClientMode(boolean)1151*/1152public abstract void setWantClientAuth(boolean want);115311541155/**1156* Returns true if the engine will <i>request</i> client authentication.1157* This option is only useful for engines in the server mode.1158*1159* @return true if client authentication is requested,1160* or false if no client authentication is desired.1161* @see #setNeedClientAuth(boolean)1162* @see #getNeedClientAuth()1163* @see #setWantClientAuth(boolean)1164* @see #setUseClientMode(boolean)1165*/1166public abstract boolean getWantClientAuth();116711681169/**1170* Controls whether new SSL sessions may be established by this engine.1171* If session creations are not allowed, and there are no1172* existing sessions to resume, there will be no successful1173* handshaking.1174*1175* @param flag true indicates that sessions may be created; this1176* is the default. false indicates that an existing session1177* must be resumed1178* @see #getEnableSessionCreation()1179*/1180public abstract void setEnableSessionCreation(boolean flag);118111821183/**1184* Returns true if new SSL sessions may be established by this engine.1185*1186* @return true indicates that sessions may be created; this1187* is the default. false indicates that an existing session1188* must be resumed1189* @see #setEnableSessionCreation(boolean)1190*/1191public abstract boolean getEnableSessionCreation();11921193/**1194* Returns the SSLParameters in effect for this SSLEngine.1195* The ciphersuites and protocols of the returned SSLParameters1196* are always non-null.1197*1198* @return the SSLParameters in effect for this SSLEngine.1199* @since 1.61200*/1201public SSLParameters getSSLParameters() {1202SSLParameters params = new SSLParameters();1203params.setCipherSuites(getEnabledCipherSuites());1204params.setProtocols(getEnabledProtocols());1205if (getNeedClientAuth()) {1206params.setNeedClientAuth(true);1207} else if (getWantClientAuth()) {1208params.setWantClientAuth(true);1209}1210return params;1211}12121213/**1214* Applies SSLParameters to this engine.1215*1216* <p>This means:1217* <ul>1218* <li>If {@code params.getCipherSuites()} is non-null,1219* {@code setEnabledCipherSuites()} is called with that value.</li>1220* <li>If {@code params.getProtocols()} is non-null,1221* {@code setEnabledProtocols()} is called with that value.</li>1222* <li>If {@code params.getNeedClientAuth()} or1223* {@code params.getWantClientAuth()} return {@code true},1224* {@code setNeedClientAuth(true)} and1225* {@code setWantClientAuth(true)} are called, respectively;1226* otherwise {@code setWantClientAuth(false)} is called.</li>1227* <li>If {@code params.getServerNames()} is non-null, the engine will1228* configure its server names with that value.</li>1229* <li>If {@code params.getSNIMatchers()} is non-null, the engine will1230* configure its SNI matchers with that value.</li>1231* </ul>1232*1233* @param params the parameters1234* @throws IllegalArgumentException if the setEnabledCipherSuites() or1235* the setEnabledProtocols() call fails1236* @since 1.61237*/1238public void setSSLParameters(SSLParameters params) {1239String[] s;1240s = params.getCipherSuites();1241if (s != null) {1242setEnabledCipherSuites(s);1243}1244s = params.getProtocols();1245if (s != null) {1246setEnabledProtocols(s);1247}1248if (params.getNeedClientAuth()) {1249setNeedClientAuth(true);1250} else if (params.getWantClientAuth()) {1251setWantClientAuth(true);1252} else {1253setWantClientAuth(false);1254}1255}12561257/**1258* Returns the most recent application protocol value negotiated for this1259* connection.1260* <p>1261* If supported by the underlying SSL/TLS/DTLS implementation,1262* application name negotiation mechanisms such as <a1263* href="http://www.ietf.org/rfc/rfc7301.txt"> RFC 7301 </a>, the1264* Application-Layer Protocol Negotiation (ALPN), can negotiate1265* application-level values between peers.1266*1267* @implSpec1268* The implementation in this class throws1269* {@code UnsupportedOperationException} and performs no other action.1270*1271* @return null if it has not yet been determined if application1272* protocols might be used for this connection, an empty1273* {@code String} if application protocols values will not1274* be used, or a non-empty application protocol {@code String}1275* if a value was successfully negotiated.1276* @throws UnsupportedOperationException if the underlying provider1277* does not implement the operation.1278* @since 81279*/1280public String getApplicationProtocol() {1281throw new UnsupportedOperationException();1282}12831284/**1285* Returns the application protocol value negotiated on a SSL/TLS1286* handshake currently in progress.1287* <p>1288* Like {@link #getHandshakeSession()},1289* a connection may be in the middle of a handshake. The1290* application protocol may or may not yet be available.1291*1292* @implSpec1293* The implementation in this class throws1294* {@code UnsupportedOperationException} and performs no other action.1295*1296* @return null if it has not yet been determined if application1297* protocols might be used for this handshake, an empty1298* {@code String} if application protocols values will not1299* be used, or a non-empty application protocol {@code String}1300* if a value was successfully negotiated.1301* @throws UnsupportedOperationException if the underlying provider1302* does not implement the operation.1303* @since 81304*/1305public String getHandshakeApplicationProtocol() {1306throw new UnsupportedOperationException();1307}13081309/**1310* Registers a callback function that selects an application protocol1311* value for a SSL/TLS/DTLS handshake.1312* The function overrides any values supplied using1313* {@link SSLParameters#setApplicationProtocols1314* SSLParameters.setApplicationProtocols} and it supports the following1315* type parameters:1316* <blockquote>1317* <dl>1318* <dt> {@code SSLEngine}1319* <dd> The function's first argument allows the current {@code SSLEngine}1320* to be inspected, including the handshake session and configuration1321* settings.1322* <dt> {@code List<String>}1323* <dd> The function's second argument lists the application protocol names1324* advertised by the TLS peer.1325* <dt> {@code String}1326* <dd> The function's result is an application protocol name, or null to1327* indicate that none of the advertised names are acceptable.1328* If the return value is an empty {@code String} then application1329* protocol indications will not be used.1330* If the return value is null (no value chosen) or is a value that1331* was not advertised by the peer, the underlying protocol will1332* determine what action to take. (For example, ALPN will send a1333* "no_application_protocol" alert and terminate the connection.)1334* </dl>1335* </blockquote>1336*1337* For example, the following call registers a callback function that1338* examines the TLS handshake parameters and selects an application protocol1339* name:1340* <pre>{@code1341* serverEngine.setHandshakeApplicationProtocolSelector(1342* (serverEngine, clientProtocols) -> {1343* SSLSession session = serverEngine.getHandshakeSession();1344* return chooseApplicationProtocol(1345* serverEngine,1346* clientProtocols,1347* session.getProtocol(),1348* session.getCipherSuite());1349* });1350* }</pre>1351*1352* @apiNote1353* This method should be called by TLS server applications before the TLS1354* handshake begins. Also, this {@code SSLEngine} should be configured with1355* parameters that are compatible with the application protocol selected by1356* the callback function. For example, enabling a poor choice of cipher1357* suites could result in no suitable application protocol.1358* See {@link SSLParameters}.1359*1360* @implSpec1361* The implementation in this class throws1362* {@code UnsupportedOperationException} and performs no other action.1363*1364* @param selector the callback function, or null to disable the callback1365* functionality.1366* @throws UnsupportedOperationException if the underlying provider1367* does not implement the operation.1368* @since 81369*/1370public void setHandshakeApplicationProtocolSelector(1371BiFunction<SSLEngine, List<String>, String> selector) {1372throw new UnsupportedOperationException();1373}13741375/**1376* Retrieves the callback function that selects an application protocol1377* value during a SSL/TLS/DTLS handshake.1378* See {@link #setHandshakeApplicationProtocolSelector1379* setHandshakeApplicationProtocolSelector}1380* for the function's type parameters.1381*1382* @implSpec1383* The implementation in this class throws1384* {@code UnsupportedOperationException} and performs no other action.1385*1386* @return the callback function, or null if none has been set.1387* @throws UnsupportedOperationException if the underlying provider1388* does not implement the operation.1389* @since 81390*/1391public BiFunction<SSLEngine, List<String>, String>1392getHandshakeApplicationProtocolSelector() {1393throw new UnsupportedOperationException();1394}1395}139613971398