1 /*
2  * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package javax.net.ssl;
27 
28 import java.nio.ByteBuffer;
29 import java.nio.ReadOnlyBufferException;
30 import java.util.List;
31 import java.util.function.BiFunction;
32 
33 
34 /**
35  * A class which enables secure communications using protocols such as
36  * the Secure Sockets Layer (SSL) or
37  * <A HREF="http://www.ietf.org/rfc/rfc2246.txt"> IETF RFC 2246 "Transport
38  * Layer Security" (TLS) </A> protocols, but is transport independent.
39  * <P>
40  * The secure communications modes include: <UL>
41  *
42  *      <LI> <em>Integrity Protection</em>.  SSL/TLS/DTLS protects against
43  *      modification of messages by an active wiretapper.
44  *
45  *      <LI> <em>Authentication</em>.  In most modes, SSL/TLS/DTLS provides
46  *      peer authentication.  Servers are usually authenticated, and
47  *      clients may be authenticated as requested by servers.
48  *
49  *      <LI> <em>Confidentiality (Privacy Protection)</em>.  In most
50  *      modes, SSL/TLS/DTLS encrypts data being sent between client and
51  *      server.  This protects the confidentiality of data, so that
52  *      passive wiretappers won't see sensitive data such as financial
53  *      information or personal information of many kinds.
54  *
55  *      </UL>
56  *
57  * These kinds of protection are specified by a "cipher suite", which
58  * is a combination of cryptographic algorithms used by a given SSL
59  * connection.  During the negotiation process, the two endpoints must
60  * agree on a cipher suite that is available in both environments.  If
61  * there is no such suite in common, no SSL connection can be
62  * established, and no data can be exchanged.
63  * <P>
64  * The cipher suite used is established by a negotiation process called
65  * "handshaking".  The goal of this process is to create or rejoin a
66  * "session", which may protect many connections over time.  After
67  * handshaking has completed, you can access session attributes by
68  * using the {@link #getSession()} method.
69  * <P>
70  * The {@code SSLSocket} class provides much of the same security
71  * functionality, but all of the inbound and outbound data is
72  * automatically transported using the underlying {@link
73  * java.net.Socket Socket}, which by design uses a blocking model.
74  * While this is appropriate for many applications, this model does not
75  * provide the scalability required by large servers.
76  * <P>
77  * The primary distinction of an {@code SSLEngine} is that it
78  * operates on inbound and outbound byte streams, independent of the
79  * transport mechanism.  It is the responsibility of the
80  * {@code SSLEngine} user to arrange for reliable I/O transport to
81  * the peer.  By separating the SSL/TLS/DTLS abstraction from the I/O
82  * transport mechanism, the {@code SSLEngine} can be used for a
83  * wide variety of I/O types, such as {@link
84  * java.nio.channels.spi.AbstractSelectableChannel#configureBlocking(boolean)
85  * non-blocking I/O (polling)}, {@link java.nio.channels.Selector
86  * selectable non-blocking I/O}, {@link java.net.Socket Socket} and the
87  * traditional Input/OutputStreams, local {@link java.nio.ByteBuffer
88  * ByteBuffers} or byte arrays, <A
89  * HREF="http://www.jcp.org/en/jsr/detail?id=203"> future asynchronous
90  * I/O models </A>, and so on.
91  * <P>
92  * At a high level, the {@code SSLEngine} appears thus:
93  *
94  * <pre>
95  *                   app data
96  *
97  *                |           ^
98  *                |     |     |
99  *                v     |     |
100  *           +----+-----|-----+----+
101  *           |          |          |
102  *           |       SSL|Engine    |
103  *   wrap()  |          |          |  unwrap()
104  *           | OUTBOUND | INBOUND  |
105  *           |          |          |
106  *           +----+-----|-----+----+
107  *                |     |     ^
108  *                |     |     |
109  *                v           |
110  *
111  *                   net data
112  * </pre>
113  * Application data (also known as plaintext or cleartext) is data which
114  * is produced or consumed by an application.  Its counterpart is
115  * network data, which consists of either handshaking and/or ciphertext
116  * (encrypted) data, and destined to be transported via an I/O
117  * mechanism.  Inbound data is data which has been received from the
118  * peer, and outbound data is destined for the peer.
119  * <P>
120  * (In the context of an {@code SSLEngine}, the term "handshake
121  * data" is taken to mean any data exchanged to establish and control a
122  * secure connection.  Handshake data includes the SSL/TLS/DTLS messages
123  * "alert", "change_cipher_spec," and "handshake.")
124  * <P>
125  * There are five distinct phases to an {@code SSLEngine}.
126  *
127  * <OL>
128  *     <li> Creation - The {@code SSLEngine} has been created and
129  *     initialized, but has not yet been used.  During this phase, an
130  *     application may set any {@code SSLEngine}-specific settings
131  *     (enabled cipher suites, whether the {@code SSLEngine} should
132  *     handshake in client or server mode, and so on).  Once
133  *     handshaking has begun, though, any new settings (except
134  *     client/server mode, see below) will be used for
135  *     the next handshake.
136  *
137  *     <li> Initial Handshake - The initial handshake is a procedure by
138  *     which the two peers exchange communication parameters until an
139  *     SSLSession is established.  Application data can not be sent during
140  *     this phase.
141  *
142  *     <li> Application Data - Once the communication parameters have
143  *     been established and the handshake is complete, application data
144  *     may flow through the {@code SSLEngine}.  Outbound
145  *     application messages are encrypted and integrity protected,
146  *     and inbound messages reverse the process.
147  *
148  *     <li> Rehandshaking - Either side may request a renegotiation of
149  *     the session at any time during the Application Data phase.  New
150  *     handshaking data can be intermixed among the application data.
151  *     Before starting the rehandshake phase, the application may
152  *     reset the SSL/TLS/DTLS communication parameters such as the list of
153  *     enabled ciphersuites and whether to use client authentication,
154  *     but can not change between client/server modes.  As before, once
155  *     handshaking has begun, any new {@code SSLEngine}
156  *     configuration settings will not be used until the next
157  *     handshake.
158  *
159  *     <li> Closure - When the connection is no longer needed, the client
160  *     and the server applications should each close both sides of their
161  *     respective connections.  For {@code SSLEngine} objects, an
162  *     application should call {@link SSLEngine#closeOutbound()} and
163  *     send any remaining messages to the peer.  Likewise, an application
164  *     should receive any remaining messages from the peer before calling
165  *     {@link SSLEngine#closeInbound()}.  The underlying transport mechanism
166  *     can then be closed after both sides of the {@code SSLEngine} have
167  *     been closed.  If the connection is not closed in an orderly manner
168  *     (for example {@link SSLEngine#closeInbound()} is called before the
169  *     peer's write closure notification has been received), exceptions
170  *     will be raised to indicate that an error has occurred.  Once an
171  *     engine is closed, it is not reusable: a new {@code SSLEngine}
172  *     must be created.
173  * </OL>
174  * An {@code SSLEngine} is created by calling {@link
175  * SSLContext#createSSLEngine()} from an initialized
176  * {@code SSLContext}.  Any configuration
177  * parameters should be set before making the first call to
178  * {@code wrap()}, {@code unwrap()}, or
179  * {@code beginHandshake()}.  These methods all trigger the
180  * initial handshake.
181  * <P>
182  * Data moves through the engine by calling {@link #wrap(ByteBuffer,
183  * ByteBuffer) wrap()} or {@link #unwrap(ByteBuffer, ByteBuffer)
184  * unwrap()} on outbound or inbound data, respectively.  Depending on
185  * the state of the {@code SSLEngine}, a {@code wrap()} call
186  * may consume application data from the source buffer and may produce
187  * network data in the destination buffer.  The outbound data
188  * may contain application and/or handshake data.  A call to
189  * {@code unwrap()} will examine the source buffer and may
190  * advance the handshake if the data is handshaking information, or
191  * may place application data in the destination buffer if the data
192  * is application.  The state of the underlying SSL/TLS/DTLS algorithm
193  * will determine when data is consumed and produced.
194  * <P>
195  * Calls to {@code wrap()} and {@code unwrap()} return an
196  * {@code SSLEngineResult} which indicates the status of the
197  * operation, and (optionally) how to interact with the engine to make
198  * progress.
199  * <P>
200  * The {@code SSLEngine} produces/consumes complete SSL/TLS/DTLS
201  * packets only, and does not store application data internally between
202  * calls to {@code wrap()/unwrap()}.  Thus input and output
203  * {@code ByteBuffer}s must be sized appropriately to hold the
204  * maximum record that can be produced.  Calls to {@link
205  * SSLSession#getPacketBufferSize()} and {@link
206  * SSLSession#getApplicationBufferSize()} should be used to determine
207  * the appropriate buffer sizes.  The size of the outbound application
208  * data buffer generally does not matter.  If buffer conditions do not
209  * allow for the proper consumption/production of data, the application
210  * must determine (via {@link SSLEngineResult}) and correct the
211  * problem, and then try the call again.
212  * <P>
213  * For example, {@code unwrap()} will return a {@link
214  * SSLEngineResult.Status#BUFFER_OVERFLOW} result if the engine
215  * determines that there is not enough destination buffer space available.
216  * Applications should call {@link SSLSession#getApplicationBufferSize()}
217  * and compare that value with the space available in the destination buffer,
218  * enlarging the buffer if necessary.  Similarly, if {@code unwrap()}
219  * were to return a {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}, the
220  * application should call {@link SSLSession#getPacketBufferSize()} to ensure
221  * that the source buffer has enough room to hold a record (enlarging if
222  * necessary), and then obtain more inbound data.
223  *
224  * <pre>{@code
225  *   SSLEngineResult r = engine.unwrap(src, dst);
226  *   switch (r.getStatus()) {
227  *   BUFFER_OVERFLOW:
228  *       // Could attempt to drain the dst buffer of any already obtained
229  *       // data, but we'll just increase it to the size needed.
230  *       int appSize = engine.getSession().getApplicationBufferSize();
231  *       ByteBuffer b = ByteBuffer.allocate(appSize + dst.position());
232  *       dst.flip();
233  *       b.put(dst);
234  *       dst = b;
235  *       // retry the operation.
236  *       break;
237  *   BUFFER_UNDERFLOW:
238  *       int netSize = engine.getSession().getPacketBufferSize();
239  *       // Resize buffer if needed.
240  *       if (netSize > src.capacity()) {
241  *           ByteBuffer b = ByteBuffer.allocate(netSize);
242  *           src.flip();
243  *           b.put(src);
244  *           src = b;
245  *       }
246  *       // Obtain more inbound network data for src,
247  *       // then retry the operation.
248  *       break;
249  *   // other cases: CLOSED, OK.
250  *   }
251  * }</pre>
252  *
253  * <P>
254  * Unlike {@code SSLSocket}, all methods of SSLEngine are
255  * non-blocking.  {@code SSLEngine} implementations may
256  * require the results of tasks that may take an extended period of
257  * time to complete, or may even block.  For example, a TrustManager
258  * may need to connect to a remote certificate validation service,
259  * or a KeyManager might need to prompt a user to determine which
260  * certificate to use as part of client authentication.  Additionally,
261  * creating cryptographic signatures and verifying them can be slow,
262  * seemingly blocking.
263  * <P>
264  * For any operation which may potentially block, the
265  * {@code SSLEngine} will create a {@link java.lang.Runnable}
266  * delegated task.  When {@code SSLEngineResult} indicates that a
267  * delegated task result is needed, the application must call {@link
268  * #getDelegatedTask()} to obtain an outstanding delegated task and
269  * call its {@link java.lang.Runnable#run() run()} method (possibly using
270  * a different thread depending on the compute strategy).  The
271  * application should continue obtaining delegated tasks until no more
272  * exist, and try the original operation again.
273  * <P>
274  * At the end of a communication session, applications should properly
275  * close the SSL/TLS/DTLS link.  The SSL/TLS/DTLS protocols have closure
276  * handshake messages, and these messages should be communicated to the
277  * peer before releasing the {@code SSLEngine} and closing the
278  * underlying transport mechanism.  A close can be initiated by one of:
279  * an SSLException, an inbound closure handshake message, or one of the
280  * close methods.  In all cases, closure handshake messages are
281  * generated by the engine, and {@code wrap()} should be repeatedly
282  * called until the resulting {@code SSLEngineResult}'s status
283  * returns "CLOSED", or {@link #isOutboundDone()} returns true.  All
284  * data obtained from the {@code wrap()} method should be sent to the
285  * peer.
286  * <P>
287  * {@link #closeOutbound()} is used to signal the engine that the
288  * application will not be sending any more data.
289  * <P>
290  * A peer will signal its intent to close by sending its own closure
291  * handshake message.  After this message has been received and
292  * processed by the local {@code SSLEngine}'s {@code unwrap()}
293  * call, the application can detect the close by calling
294  * {@code unwrap()} and looking for a {@code SSLEngineResult}
295  * with status "CLOSED", or if {@link #isInboundDone()} returns true.
296  * If for some reason the peer closes the communication link without
297  * sending the proper SSL/TLS/DTLS closure message, the application can
298  * detect the end-of-stream and can signal the engine via {@link
299  * #closeInbound()} that there will no more inbound messages to
300  * process.  Some applications might choose to require orderly shutdown
301  * messages from a peer, in which case they can check that the closure
302  * was generated by a handshake message and not by an end-of-stream
303  * condition.
304  * <P>
305  * There are two groups of cipher suites which you will need to know
306  * about when managing cipher suites:
307  *
308  * <UL>
309  *      <LI> <em>Supported</em> cipher suites:  all the suites which are
310  *      supported by the SSL implementation.  This list is reported
311  *      using {@link #getSupportedCipherSuites()}.
312  *
313  *      <LI> <em>Enabled</em> cipher suites, which may be fewer than
314  *      the full set of supported suites.  This group is set using the
315  *      {@link #setEnabledCipherSuites(String [])} method, and
316  *      queried using the {@link #getEnabledCipherSuites()} method.
317  *      Initially, a default set of cipher suites will be enabled on a
318  *      new engine that represents the minimum suggested
319  *      configuration.
320  * </UL>
321  *
322  * Implementation defaults require that only cipher suites which
323  * authenticate servers and provide confidentiality be enabled by
324  * default.  Only if both sides explicitly agree to unauthenticated
325  * and/or non-private (unencrypted) communications will such a
326  * cipher suite be selected.
327  * <P>
328  * Each SSL/TLS/DTLS connection must have one client and one server, thus
329  * each endpoint must decide which role to assume.  This choice determines
330  * who begins the handshaking process as well as which type of messages
331  * should be sent by each party.  The method {@link
332  * #setUseClientMode(boolean)} configures the mode.  Note that the
333  * default mode for a new {@code SSLEngine} is provider-specific.
334  * Applications should set the mode explicitly before invoking other
335  * methods of the {@code SSLEngine}.  Once the initial handshaking has
336  * started, an {@code SSLEngine} can not switch between client and server
337  * modes, even when performing renegotiations.
338  * <P>
339  * Applications might choose to process delegated tasks in different
340  * threads.  When an {@code SSLEngine}
341  * is created, the current {@link java.security.AccessControlContext}
342  * is saved.  All future delegated tasks will be processed using this
343  * context:  that is, all access control decisions will be made using the
344  * context captured at engine creation.
345  *
346  * <HR>
347  *
348  * <B>Concurrency Notes</B>:
349  * There are two concurrency issues to be aware of:
350  *
351  * <OL>
352  *      <li>The {@code wrap()} and {@code unwrap()} methods
353  *      may execute concurrently of each other.
354  *
355  *      <li> The SSL/TLS/DTLS protocols employ ordered packets.
356  *      Applications must take care to ensure that generated packets
357  *      are delivered in sequence.  If packets arrive
358  *      out-of-order, unexpected or fatal results may occur.
359  * <P>
360  *      For example:
361  *
362  *      <pre>
363  *              synchronized (outboundLock) {
364  *                  sslEngine.wrap(src, dst);
365  *                  outboundQueue.put(dst);
366  *              }
367  *      </pre>
368  *
369  *      As a corollary, two threads must not attempt to call the same method
370  *      (either {@code wrap()} or {@code unwrap()}) concurrently,
371  *      because there is no way to guarantee the eventual packet ordering.
372  * </OL>
373  *
374  * @see SSLContext
375  * @see SSLSocket
376  * @see SSLServerSocket
377  * @see SSLSession
378  * @see java.net.Socket
379  *
380  * @since 1.5
381  * @author Brad R. Wetmore
382  */
383 
384 public abstract class SSLEngine {
385 
386     private String peerHost = null;
387     private int peerPort = -1;
388 
389     /**
390      * Constructor for an {@code SSLEngine} providing no hints
391      * for an internal session reuse strategy.
392      *
393      * @see     SSLContext#createSSLEngine()
394      * @see     SSLSessionContext
395      */
SSLEngine()396     protected SSLEngine() {
397     }
398 
399     /**
400      * Constructor for an {@code SSLEngine}.
401      * <P>
402      * {@code SSLEngine} implementations may use the
403      * {@code peerHost} and {@code peerPort} parameters as hints
404      * for their internal session reuse strategy.
405      * <P>
406      * Some cipher suites (such as Kerberos) require remote hostname
407      * information. Implementations of this class should use this
408      * constructor to use Kerberos.
409      * <P>
410      * The parameters are not authenticated by the
411      * {@code SSLEngine}.
412      *
413      * @param   peerHost the name of the peer host
414      * @param   peerPort the port number of the peer
415      * @see     SSLContext#createSSLEngine(String, int)
416      * @see     SSLSessionContext
417      */
SSLEngine(String peerHost, int peerPort)418     protected SSLEngine(String peerHost, int peerPort) {
419         this.peerHost = peerHost;
420         this.peerPort = peerPort;
421     }
422 
423     /**
424      * Returns the host name of the peer.
425      * <P>
426      * Note that the value is not authenticated, and should not be
427      * relied upon.
428      *
429      * @return  the host name of the peer, or null if nothing is
430      *          available.
431      */
getPeerHost()432     public String getPeerHost() {
433         return peerHost;
434     }
435 
436     /**
437      * Returns the port number of the peer.
438      * <P>
439      * Note that the value is not authenticated, and should not be
440      * relied upon.
441      *
442      * @return  the port number of the peer, or -1 if nothing is
443      *          available.
444      */
getPeerPort()445     public int getPeerPort() {
446         return peerPort;
447     }
448 
449     /**
450      * Attempts to encode a buffer of plaintext application data into
451      * SSL/TLS/DTLS network data.
452      * <P>
453      * An invocation of this method behaves in exactly the same manner
454      * as the invocation:
455      * <blockquote><pre>
456      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
457      *     engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);}
458      * </pre></blockquote>
459      *
460      * @param   src
461      *          a {@code ByteBuffer} containing outbound application data
462      * @param   dst
463      *          a {@code ByteBuffer} to hold outbound network data
464      * @return  an {@code SSLEngineResult} describing the result
465      *          of this operation.
466      * @throws  SSLException
467      *          A problem was encountered while processing the
468      *          data that caused the {@code SSLEngine} to abort.
469      *          See the class description for more information on
470      *          engine closure.
471      * @throws  ReadOnlyBufferException
472      *          if the {@code dst} buffer is read-only.
473      * @throws  IllegalArgumentException
474      *          if either {@code src} or {@code dst}
475      *          is null.
476      * @throws  IllegalStateException if the client/server mode
477      *          has not yet been set.
478      * @see     #wrap(ByteBuffer [], int, int, ByteBuffer)
479      */
wrap(ByteBuffer src, ByteBuffer dst)480     public SSLEngineResult wrap(ByteBuffer src,
481             ByteBuffer dst) throws SSLException {
482         return wrap(new ByteBuffer [] { src }, 0, 1, dst);
483     }
484 
485     /**
486      * Attempts to encode plaintext bytes from a sequence of data
487      * buffers into SSL/TLS/DTLS network data.
488      * <P>
489      * An invocation of this method behaves in exactly the same manner
490      * as the invocation:
491      * <blockquote><pre>
492      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
493      *     engine.wrap(srcs, 0, srcs.length, dst);}
494      * </pre></blockquote>
495      *
496      * @param   srcs
497      *          an array of {@code ByteBuffers} containing the
498      *          outbound application data
499      * @param   dst
500      *          a {@code ByteBuffer} to hold outbound network data
501      * @return  an {@code SSLEngineResult} describing the result
502      *          of this operation.
503      * @throws  SSLException
504      *          A problem was encountered while processing the
505      *          data that caused the {@code SSLEngine} to abort.
506      *          See the class description for more information on
507      *          engine closure.
508      * @throws  ReadOnlyBufferException
509      *          if the {@code dst} buffer is read-only.
510      * @throws  IllegalArgumentException
511      *          if either {@code srcs} or {@code dst}
512      *          is null, or if any element in {@code srcs} is null.
513      * @throws  IllegalStateException if the client/server mode
514      *          has not yet been set.
515      * @see     #wrap(ByteBuffer [], int, int, ByteBuffer)
516      */
wrap(ByteBuffer [] srcs, ByteBuffer dst)517     public SSLEngineResult wrap(ByteBuffer [] srcs,
518             ByteBuffer dst) throws SSLException {
519         if (srcs == null) {
520             throw new IllegalArgumentException("src == null");
521         }
522         return wrap(srcs, 0, srcs.length, dst);
523     }
524 
525 
526     /**
527      * Attempts to encode plaintext bytes from a subsequence of data
528      * buffers into SSL/TLS/DTLS network data.  This <i>"gathering"</i>
529      * operation encodes, in a single invocation, a sequence of bytes
530      * from one or more of a given sequence of buffers.  Gathering
531      * wraps are often useful when implementing network protocols or
532      * file formats that, for example, group data into segments
533      * consisting of one or more fixed-length headers followed by a
534      * variable-length body.  See
535      * {@link java.nio.channels.GatheringByteChannel} for more
536      * information on gathering, and {@link
537      * java.nio.channels.GatheringByteChannel#write(ByteBuffer[],
538      * int, int)} for more information on the subsequence
539      * behavior.
540      * <P>
541      * Depending on the state of the SSLEngine, this method may produce
542      * network data without consuming any application data (for example,
543      * it may generate handshake data.)
544      * <P>
545      * The application is responsible for reliably transporting the
546      * network data to the peer, and for ensuring that data created by
547      * multiple calls to wrap() is transported in the same order in which
548      * it was generated.  The application must properly synchronize
549      * multiple calls to this method.
550      * <P>
551      * If this {@code SSLEngine} has not yet started its initial
552      * handshake, this method will automatically start the handshake.
553      * <P>
554      * This method will attempt to produce SSL/TLS/DTLS records, and will
555      * consume as much source data as possible, but will never consume
556      * more than the sum of the bytes remaining in each buffer.  Each
557      * {@code ByteBuffer}'s position is updated to reflect the
558      * amount of data consumed or produced.  The limits remain the
559      * same.
560      * <P>
561      * The underlying memory used by the {@code srcs} and
562      * {@code dst ByteBuffer}s must not be the same.
563      * <P>
564      * See the class description for more information on engine closure.
565      *
566      * @param   srcs
567      *          an array of {@code ByteBuffers} containing the
568      *          outbound application data
569      * @param   offset
570      *          The offset within the buffer array of the first buffer from
571      *          which bytes are to be retrieved; it must be non-negative
572      *          and no larger than {@code srcs.length}
573      * @param   length
574      *          The maximum number of buffers to be accessed; it must be
575      *          non-negative and no larger than
576      *          {@code srcs.length}&nbsp;-&nbsp;{@code offset}
577      * @param   dst
578      *          a {@code ByteBuffer} to hold outbound network data
579      * @return  an {@code SSLEngineResult} describing the result
580      *          of this operation.
581      * @throws  SSLException
582      *          A problem was encountered while processing the
583      *          data that caused the {@code SSLEngine} to abort.
584      *          See the class description for more information on
585      *          engine closure.
586      * @throws  IndexOutOfBoundsException
587      *          if the preconditions on the {@code offset} and
588      *          {@code length} parameters do not hold.
589      * @throws  ReadOnlyBufferException
590      *          if the {@code dst} buffer is read-only.
591      * @throws  IllegalArgumentException
592      *          if either {@code srcs} or {@code dst}
593      *          is null, or if any element in the {@code srcs}
594      *          subsequence specified is null.
595      * @throws  IllegalStateException if the client/server mode
596      *          has not yet been set.
597      * @see     java.nio.channels.GatheringByteChannel
598      * @see     java.nio.channels.GatheringByteChannel#write(
599      *              ByteBuffer[], int, int)
600      */
wrap(ByteBuffer [] srcs, int offset, int length, ByteBuffer dst)601     public abstract SSLEngineResult wrap(ByteBuffer [] srcs, int offset,
602             int length, ByteBuffer dst) throws SSLException;
603 
604     /**
605      * Attempts to decode SSL/TLS/DTLS network data into a plaintext
606      * application data buffer.
607      * <P>
608      * An invocation of this method behaves in exactly the same manner
609      * as the invocation:
610      * <blockquote><pre>
611      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
612      *     engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);}
613      * </pre></blockquote>
614      *
615      * @param   src
616      *          a {@code ByteBuffer} containing inbound network data.
617      * @param   dst
618      *          a {@code ByteBuffer} to hold inbound application data.
619      * @return  an {@code SSLEngineResult} describing the result
620      *          of this operation.
621      * @throws  SSLException
622      *          A problem was encountered while processing the
623      *          data that caused the {@code SSLEngine} to abort.
624      *          See the class description for more information on
625      *          engine closure.
626      * @throws  ReadOnlyBufferException
627      *          if the {@code dst} buffer is read-only.
628      * @throws  IllegalArgumentException
629      *          if either {@code src} or {@code dst}
630      *          is null.
631      * @throws  IllegalStateException if the client/server mode
632      *          has not yet been set.
633      * @see     #unwrap(ByteBuffer, ByteBuffer [], int, int)
634      */
unwrap(ByteBuffer src, ByteBuffer dst)635     public SSLEngineResult unwrap(ByteBuffer src,
636             ByteBuffer dst) throws SSLException {
637         return unwrap(src, new ByteBuffer [] { dst }, 0, 1);
638     }
639 
640     /**
641      * Attempts to decode SSL/TLS/DTLS network data into a sequence of plaintext
642      * application data buffers.
643      * <P>
644      * An invocation of this method behaves in exactly the same manner
645      * as the invocation:
646      * <blockquote><pre>
647      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
648      *     engine.unwrap(src, dsts, 0, dsts.length);}
649      * </pre></blockquote>
650      *
651      * @param   src
652      *          a {@code ByteBuffer} containing inbound network data.
653      * @param   dsts
654      *          an array of {@code ByteBuffer}s to hold inbound
655      *          application data.
656      * @return  an {@code SSLEngineResult} describing the result
657      *          of this operation.
658      * @throws  SSLException
659      *          A problem was encountered while processing the
660      *          data that caused the {@code SSLEngine} to abort.
661      *          See the class description for more information on
662      *          engine closure.
663      * @throws  ReadOnlyBufferException
664      *          if any of the {@code dst} buffers are read-only.
665      * @throws  IllegalArgumentException
666      *          if either {@code src} or {@code dsts}
667      *          is null, or if any element in {@code dsts} is null.
668      * @throws  IllegalStateException if the client/server mode
669      *          has not yet been set.
670      * @see     #unwrap(ByteBuffer, ByteBuffer [], int, int)
671      */
unwrap(ByteBuffer src, ByteBuffer [] dsts)672     public SSLEngineResult unwrap(ByteBuffer src,
673             ByteBuffer [] dsts) throws SSLException {
674         if (dsts == null) {
675             throw new IllegalArgumentException("dsts == null");
676         }
677         return unwrap(src, dsts, 0, dsts.length);
678     }
679 
680     /**
681      * Attempts to decode SSL/TLS/DTLS network data into a subsequence of
682      * plaintext application data buffers.  This <i>"scattering"</i>
683      * operation decodes, in a single invocation, a sequence of bytes
684      * into one or more of a given sequence of buffers.  Scattering
685      * unwraps are often useful when implementing network protocols or
686      * file formats that, for example, group data into segments
687      * consisting of one or more fixed-length headers followed by a
688      * variable-length body.  See
689      * {@link java.nio.channels.ScatteringByteChannel} for more
690      * information on scattering, and {@link
691      * java.nio.channels.ScatteringByteChannel#read(ByteBuffer[],
692      * int, int)} for more information on the subsequence
693      * behavior.
694      * <P>
695      * Depending on the state of the SSLEngine, this method may consume
696      * network data without producing any application data (for example,
697      * it may consume handshake data.)
698      * <P>
699      * The application is responsible for reliably obtaining the network
700      * data from the peer, and for invoking unwrap() on the data in the
701      * order it was received.  The application must properly synchronize
702      * multiple calls to this method.
703      * <P>
704      * If this {@code SSLEngine} has not yet started its initial
705      * handshake, this method will automatically start the handshake.
706      * <P>
707      * This method will attempt to consume one complete SSL/TLS/DTLS network
708      * packet, but will never consume more than the sum of the bytes
709      * remaining in the buffers.  Each {@code ByteBuffer}'s
710      * position is updated to reflect the amount of data consumed or
711      * produced.  The limits remain the same.
712      * <P>
713      * The underlying memory used by the {@code src} and
714      * {@code dsts ByteBuffer}s must not be the same.
715      * <P>
716      * The inbound network buffer may be modified as a result of this
717      * call:  therefore if the network data packet is required for some
718      * secondary purpose, the data should be duplicated before calling this
719      * method.  Note:  the network data will not be useful to a second
720      * SSLEngine, as each SSLEngine contains unique random state which
721      * influences the SSL/TLS/DTLS messages.
722      * <P>
723      * See the class description for more information on engine closure.
724      *
725      * @param   src
726      *          a {@code ByteBuffer} containing inbound network data.
727      * @param   dsts
728      *          an array of {@code ByteBuffer}s to hold inbound
729      *          application data.
730      * @param   offset
731      *          The offset within the buffer array of the first buffer from
732      *          which bytes are to be transferred; it must be non-negative
733      *          and no larger than {@code dsts.length}.
734      * @param   length
735      *          The maximum number of buffers to be accessed; it must be
736      *          non-negative and no larger than
737      *          {@code dsts.length}&nbsp;-&nbsp;{@code offset}.
738      * @return  an {@code SSLEngineResult} describing the result
739      *          of this operation.
740      * @throws  SSLException
741      *          A problem was encountered while processing the
742      *          data that caused the {@code SSLEngine} to abort.
743      *          See the class description for more information on
744      *          engine closure.
745      * @throws  IndexOutOfBoundsException
746      *          If the preconditions on the {@code offset} and
747      *          {@code length} parameters do not hold.
748      * @throws  ReadOnlyBufferException
749      *          if any of the {@code dst} buffers are read-only.
750      * @throws  IllegalArgumentException
751      *          if either {@code src} or {@code dsts}
752      *          is null, or if any element in the {@code dsts}
753      *          subsequence specified is null.
754      * @throws  IllegalStateException if the client/server mode
755      *          has not yet been set.
756      * @see     java.nio.channels.ScatteringByteChannel
757      * @see     java.nio.channels.ScatteringByteChannel#read(
758      *              ByteBuffer[], int, int)
759      */
unwrap(ByteBuffer src, ByteBuffer [] dsts, int offset, int length)760     public abstract SSLEngineResult unwrap(ByteBuffer src,
761             ByteBuffer [] dsts, int offset, int length) throws SSLException;
762 
763 
764     /**
765      * Returns a delegated {@code Runnable} task for
766      * this {@code SSLEngine}.
767      * <P>
768      * {@code SSLEngine} operations may require the results of
769      * operations that block, or may take an extended period of time to
770      * complete.  This method is used to obtain an outstanding {@link
771      * java.lang.Runnable} operation (task).  Each task must be assigned
772      * a thread (possibly the current) to perform the {@link
773      * java.lang.Runnable#run() run} operation.  Once the
774      * {@code run} method returns, the {@code Runnable} object
775      * is no longer needed and may be discarded.
776      * <P>
777      * Delegated tasks run in the {@code AccessControlContext}
778      * in place when this object was created.
779      * <P>
780      * A call to this method will return each outstanding task
781      * exactly once.
782      * <P>
783      * Multiple delegated tasks can be run in parallel.
784      *
785      * @return  a delegated {@code Runnable} task, or null
786      *          if none are available.
787      */
getDelegatedTask()788     public abstract Runnable getDelegatedTask();
789 
790 
791     /**
792      * Signals that no more inbound network data will be sent
793      * to this {@code SSLEngine}.
794      * <P>
795      * If the application initiated the closing process by calling
796      * {@link #closeOutbound()}, under some circumstances it is not
797      * required that the initiator wait for the peer's corresponding
798      * close message.  (See section 7.2.1 of the TLS specification (<A
799      * HREF="http://www.ietf.org/rfc/rfc2246.txt">RFC 2246</A>) for more
800      * information on waiting for closure alerts.)  In such cases, this
801      * method need not be called.
802      * <P>
803      * But if the application did not initiate the closure process, or
804      * if the circumstances above do not apply, this method should be
805      * called whenever the end of the SSL/TLS/DTLS data stream is reached.
806      * This ensures closure of the inbound side, and checks that the
807      * peer followed the SSL/TLS/DTLS close procedure properly, thus
808      * detecting possible truncation attacks.
809      * <P>
810      * This method is idempotent:  if the inbound side has already
811      * been closed, this method does not do anything.
812      * <P>
813      * {@link #wrap(ByteBuffer, ByteBuffer) wrap()} should be
814      * called to flush any remaining handshake data.
815      *
816      * @throws  SSLException
817      *          if this engine has not received the proper SSL/TLS/DTLS close
818      *          notification message from the peer.
819      *
820      * @see     #isInboundDone()
821      * @see     #isOutboundDone()
822      */
closeInbound()823     public abstract void closeInbound() throws SSLException;
824 
825 
826     /**
827      * Returns whether {@link #unwrap(ByteBuffer, ByteBuffer)} will
828      * accept any more inbound data messages.
829      *
830      * @return  true if the {@code SSLEngine} will not
831      *          consume anymore network data (and by implication,
832      *          will not produce any more application data.)
833      * @see     #closeInbound()
834      */
isInboundDone()835     public abstract boolean isInboundDone();
836 
837 
838     /**
839      * Signals that no more outbound application data will be sent
840      * on this {@code SSLEngine}.
841      * <P>
842      * This method is idempotent:  if the outbound side has already
843      * been closed, this method does not do anything.
844      * <P>
845      * {@link #wrap(ByteBuffer, ByteBuffer)} should be
846      * called to flush any remaining handshake data.
847      *
848      * @see     #isOutboundDone()
849      */
closeOutbound()850     public abstract void closeOutbound();
851 
852 
853     /**
854      * Returns whether {@link #wrap(ByteBuffer, ByteBuffer)} will
855      * produce any more outbound data messages.
856      * <P>
857      * Note that during the closure phase, a {@code SSLEngine} may
858      * generate handshake closure data that must be sent to the peer.
859      * {@code wrap()} must be called to generate this data.  When
860      * this method returns true, no more outbound data will be created.
861      *
862      * @return  true if the {@code SSLEngine} will not produce
863      *          any more network data
864      *
865      * @see     #closeOutbound()
866      * @see     #closeInbound()
867      */
isOutboundDone()868     public abstract boolean isOutboundDone();
869 
870 
871     /**
872      * Returns the names of the cipher suites which could be enabled for use
873      * on this engine.  Normally, only a subset of these will actually
874      * be enabled by default, since this list may include cipher suites which
875      * do not meet quality of service requirements for those defaults.  Such
876      * cipher suites might be useful in specialized applications.
877      * <P>
878      * The returned array includes cipher suites from the list of standard
879      * cipher suite names in the <a href=
880      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
881      * JSSE Cipher Suite Names</a> section of the Java Cryptography
882      * Architecture Standard Algorithm Name Documentation, and may also
883      * include other cipher suites that the provider supports.
884      *
885      * @return  an array of cipher suite names
886      * @see     #getEnabledCipherSuites()
887      * @see     #setEnabledCipherSuites(String [])
888      */
getSupportedCipherSuites()889     public abstract String [] getSupportedCipherSuites();
890 
891 
892     /**
893      * Returns the names of the SSL cipher suites which are currently
894      * enabled for use on this engine.  When an SSLEngine is first
895      * created, all enabled cipher suites support a minimum quality of
896      * service.  Thus, in some environments this value might be empty.
897      * <P>
898      * Note that even if a suite is enabled, it may never be used. This
899      * can occur if the peer does not support it, or its use is restricted,
900      * or the requisite certificates (and private keys) for the suite are
901      * not available, or an anonymous suite is enabled but authentication
902      * is required.
903      * <P>
904      * The returned array includes cipher suites from the list of standard
905      * cipher suite names in the <a href=
906      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
907      * JSSE Cipher Suite Names</a> section of the Java Cryptography
908      * Architecture Standard Algorithm Name Documentation, and may also
909      * include other cipher suites that the provider supports.
910      *
911      * @return  an array of cipher suite names
912      * @see     #getSupportedCipherSuites()
913      * @see     #setEnabledCipherSuites(String [])
914      */
getEnabledCipherSuites()915     public abstract String [] getEnabledCipherSuites();
916 
917 
918     /**
919      * Sets the cipher suites enabled for use on this engine.
920      * <P>
921      * Each cipher suite in the {@code suites} parameter must have
922      * been listed by getSupportedCipherSuites(), or the method will
923      * fail.  Following a successful call to this method, only suites
924      * listed in the {@code suites} parameter are enabled for use.
925      * <P>
926      * Note that the standard list of cipher suite names may be found in the
927      * <a href=
928      * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names">
929      * JSSE Cipher Suite Names</a> section of the Java Cryptography
930      * Architecture Standard Algorithm Name Documentation.  Providers
931      * may support cipher suite names not found in this list or might not
932      * use the recommended name for a certain cipher suite.
933      * <P>
934      * See {@link #getEnabledCipherSuites()} for more information
935      * on why a specific cipher suite may never be used on a engine.
936      *
937      * @param   suites Names of all the cipher suites to enable
938      * @throws  IllegalArgumentException when one or more of the ciphers
939      *          named by the parameter is not supported, or when the
940      *          parameter is null.
941      * @see     #getSupportedCipherSuites()
942      * @see     #getEnabledCipherSuites()
943      */
setEnabledCipherSuites(String suites [])944     public abstract void setEnabledCipherSuites(String suites []);
945 
946 
947     /**
948      * Returns the names of the protocols which could be enabled for use
949      * with this {@code SSLEngine}.
950      *
951      * @return  an array of protocols supported
952      */
getSupportedProtocols()953     public abstract String [] getSupportedProtocols();
954 
955 
956     /**
957      * Returns the names of the protocol versions which are currently
958      * enabled for use with this {@code SSLEngine}.
959      * <P>
960      * Note that even if a protocol is enabled, it may never be used.
961      * This can occur if the peer does not support the protocol, or its
962      * use is restricted, or there are no enabled cipher suites supported
963      * by the protocol.
964      *
965      * @return  an array of protocols
966      * @see     #setEnabledProtocols(String [])
967      */
getEnabledProtocols()968     public abstract String [] getEnabledProtocols();
969 
970 
971     /**
972      * Set the protocol versions enabled for use on this engine.
973      * <P>
974      * The protocols must have been listed by getSupportedProtocols()
975      * as being supported.  Following a successful call to this method,
976      * only protocols listed in the {@code protocols} parameter
977      * are enabled for use.
978      *
979      * @param   protocols Names of all the protocols to enable.
980      * @throws  IllegalArgumentException when one or more of
981      *          the protocols named by the parameter is not supported or
982      *          when the protocols parameter is null.
983      * @see     #getEnabledProtocols()
984      */
setEnabledProtocols(String protocols[])985     public abstract void setEnabledProtocols(String protocols[]);
986 
987 
988     /**
989      * Returns the {@code SSLSession} in use in this
990      * {@code SSLEngine}.
991      * <P>
992      * These can be long lived, and frequently correspond to an entire
993      * login session for some user.  The session specifies a particular
994      * cipher suite which is being actively used by all connections in
995      * that session, as well as the identities of the session's client
996      * and server.
997      * <P>
998      * Unlike {@link SSLSocket#getSession()}
999      * this method does not block until handshaking is complete.
1000      * <P>
1001      * Until the initial handshake has completed, this method returns
1002      * a session object which reports an invalid cipher suite of
1003      * "SSL_NULL_WITH_NULL_NULL".
1004      *
1005      * @return  the {@code SSLSession} for this {@code SSLEngine}
1006      * @see     SSLSession
1007      */
getSession()1008     public abstract SSLSession getSession();
1009 
1010 
1011     /**
1012      * Returns the {@code SSLSession} being constructed during a SSL/TLS/DTLS
1013      * handshake.
1014      * <p>
1015      * TLS/DTLS protocols may negotiate parameters that are needed when using
1016      * an instance of this class, but before the {@code SSLSession} has
1017      * been completely initialized and made available via {@code getSession}.
1018      * For example, the list of valid signature algorithms may restrict
1019      * the type of certificates that can be used during TrustManager
1020      * decisions, or the maximum TLS/DTLS fragment packet sizes can be
1021      * resized to better support the network environment.
1022      * <p>
1023      * This method provides early access to the {@code SSLSession} being
1024      * constructed.  Depending on how far the handshake has progressed,
1025      * some data may not yet be available for use.  For example, if a
1026      * remote server will be sending a Certificate chain, but that chain
1027      * has yet not been processed, the {@code getPeerCertificates}
1028      * method of {@code SSLSession} will throw a
1029      * SSLPeerUnverifiedException.  Once that chain has been processed,
1030      * {@code getPeerCertificates} will return the proper value.
1031      *
1032      * @see SSLSocket
1033      * @see SSLSession
1034      * @see ExtendedSSLSession
1035      * @see X509ExtendedKeyManager
1036      * @see X509ExtendedTrustManager
1037      *
1038      * @return null if this instance is not currently handshaking, or
1039      *         if the current handshake has not progressed far enough to
1040      *         create a basic SSLSession.  Otherwise, this method returns the
1041      *         {@code SSLSession} currently being negotiated.
1042      * @throws UnsupportedOperationException if the underlying provider
1043      *         does not implement the operation.
1044      *
1045      * @since 1.7
1046      */
getHandshakeSession()1047     public SSLSession getHandshakeSession() {
1048         throw new UnsupportedOperationException();
1049     }
1050 
1051 
1052     /**
1053      * Initiates handshaking (initial or renegotiation) on this SSLEngine.
1054      * <P>
1055      * This method is not needed for the initial handshake, as the
1056      * {@code wrap()} and {@code unwrap()} methods will
1057      * implicitly call this method if handshaking has not already begun.
1058      * <P>
1059      * Note that the peer may also request a session renegotiation with
1060      * this {@code SSLEngine} by sending the appropriate
1061      * session renegotiate handshake message.
1062      * <P>
1063      * Unlike the {@link SSLSocket#startHandshake()
1064      * SSLSocket#startHandshake()} method, this method does not block
1065      * until handshaking is completed.
1066      * <P>
1067      * To force a complete SSL/TLS/DTLS session renegotiation, the current
1068      * session should be invalidated prior to calling this method.
1069      * <P>
1070      * Some protocols may not support multiple handshakes on an existing
1071      * engine and may throw an {@code SSLException}.
1072      *
1073      * @throws  SSLException
1074      *          if a problem was encountered while signaling the
1075      *          {@code SSLEngine} to begin a new handshake.
1076      *          See the class description for more information on
1077      *          engine closure.
1078      * @throws  IllegalStateException if the client/server mode
1079      *          has not yet been set.
1080      * @see     SSLSession#invalidate()
1081      */
beginHandshake()1082     public abstract void beginHandshake() throws SSLException;
1083 
1084 
1085     /**
1086      * Returns the current handshake status for this {@code SSLEngine}.
1087      *
1088      * @return  the current {@code SSLEngineResult.HandshakeStatus}.
1089      */
getHandshakeStatus()1090     public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();
1091 
1092 
1093     /**
1094      * Configures the engine to use client (or server) mode when
1095      * handshaking.
1096      * <P>
1097      * This method must be called before any handshaking occurs.
1098      * Once handshaking has begun, the mode can not be reset for the
1099      * life of this engine.
1100      * <P>
1101      * Servers normally authenticate themselves, and clients
1102      * are not required to do so.
1103      *
1104      * @implNote
1105      * The JDK SunJSSE provider implementation default for this mode is false.
1106      *
1107      * @param   mode true if the engine should start its handshaking
1108      *          in "client" mode
1109      * @throws  IllegalArgumentException if a mode change is attempted
1110      *          after the initial handshake has begun.
1111      * @see     #getUseClientMode()
1112      */
setUseClientMode(boolean mode)1113     public abstract void setUseClientMode(boolean mode);
1114 
1115 
1116     /**
1117      * Returns true if the engine is set to use client mode when
1118      * handshaking.
1119      *
1120      * @implNote
1121      * The JDK SunJSSE provider implementation returns false unless
1122      * {@link setUseClientMode(boolean)} is used to change the mode to true.
1123      *
1124      * @return  true if the engine should do handshaking
1125      *          in "client" mode
1126      * @see     #setUseClientMode(boolean)
1127      */
getUseClientMode()1128     public abstract boolean getUseClientMode();
1129 
1130 
1131     /**
1132      * Configures the engine to <i>require</i> client authentication.  This
1133      * option is only useful for engines in the server mode.
1134      * <P>
1135      * An engine's client authentication setting is one of the following:
1136      * <ul>
1137      * <li> client authentication required
1138      * <li> client authentication requested
1139      * <li> no client authentication desired
1140      * </ul>
1141      * <P>
1142      * Unlike {@link #setWantClientAuth(boolean)}, if this option is set and
1143      * the client chooses not to provide authentication information
1144      * about itself, <i>the negotiations will stop and the engine will
1145      * begin its closure procedure</i>.
1146      * <P>
1147      * Calling this method overrides any previous setting made by
1148      * this method or {@link #setWantClientAuth(boolean)}.
1149      *
1150      * @param   need set to true if client authentication is required,
1151      *          or false if no client authentication is desired.
1152      * @see     #getNeedClientAuth()
1153      * @see     #setWantClientAuth(boolean)
1154      * @see     #getWantClientAuth()
1155      * @see     #setUseClientMode(boolean)
1156      */
setNeedClientAuth(boolean need)1157     public abstract void setNeedClientAuth(boolean need);
1158 
1159 
1160     /**
1161      * Returns true if the engine will <i>require</i> client authentication.
1162      * This option is only useful to engines in the server mode.
1163      *
1164      * @return  true if client authentication is required,
1165      *          or false if no client authentication is desired.
1166      * @see     #setNeedClientAuth(boolean)
1167      * @see     #setWantClientAuth(boolean)
1168      * @see     #getWantClientAuth()
1169      * @see     #setUseClientMode(boolean)
1170      */
getNeedClientAuth()1171     public abstract boolean getNeedClientAuth();
1172 
1173 
1174     /**
1175      * Configures the engine to <i>request</i> client authentication.
1176      * This option is only useful for engines in the server mode.
1177      * <P>
1178      * An engine's client authentication setting is one of the following:
1179      * <ul>
1180      * <li> client authentication required
1181      * <li> client authentication requested
1182      * <li> no client authentication desired
1183      * </ul>
1184      * <P>
1185      * Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and
1186      * the client chooses not to provide authentication information
1187      * about itself, <i>the negotiations will continue</i>.
1188      * <P>
1189      * Calling this method overrides any previous setting made by
1190      * this method or {@link #setNeedClientAuth(boolean)}.
1191      *
1192      * @param   want set to true if client authentication is requested,
1193      *          or false if no client authentication is desired.
1194      * @see     #getWantClientAuth()
1195      * @see     #setNeedClientAuth(boolean)
1196      * @see     #getNeedClientAuth()
1197      * @see     #setUseClientMode(boolean)
1198      */
setWantClientAuth(boolean want)1199     public abstract void setWantClientAuth(boolean want);
1200 
1201 
1202     /**
1203      * Returns true if the engine will <i>request</i> client authentication.
1204      * This option is only useful for engines in the server mode.
1205      *
1206      * @return  true if client authentication is requested,
1207      *          or false if no client authentication is desired.
1208      * @see     #setNeedClientAuth(boolean)
1209      * @see     #getNeedClientAuth()
1210      * @see     #setWantClientAuth(boolean)
1211      * @see     #setUseClientMode(boolean)
1212      */
getWantClientAuth()1213     public abstract boolean getWantClientAuth();
1214 
1215 
1216     /**
1217      * Controls whether new SSL sessions may be established by this engine.
1218      * If session creations are not allowed, and there are no
1219      * existing sessions to resume, there will be no successful
1220      * handshaking.
1221      *
1222      * @param   flag true indicates that sessions may be created; this
1223      *          is the default.  false indicates that an existing session
1224      *          must be resumed
1225      * @see     #getEnableSessionCreation()
1226      */
setEnableSessionCreation(boolean flag)1227     public abstract void setEnableSessionCreation(boolean flag);
1228 
1229 
1230     /**
1231      * Returns true if new SSL sessions may be established by this engine.
1232      *
1233      * @return  true indicates that sessions may be created; this
1234      *          is the default.  false indicates that an existing session
1235      *          must be resumed
1236      * @see     #setEnableSessionCreation(boolean)
1237      */
getEnableSessionCreation()1238     public abstract boolean getEnableSessionCreation();
1239 
1240     /**
1241      * Returns the SSLParameters in effect for this SSLEngine.
1242      * The ciphersuites and protocols of the returned SSLParameters
1243      * are always non-null.
1244      *
1245      * @return the SSLParameters in effect for this SSLEngine.
1246      * @since 1.6
1247      */
getSSLParameters()1248     public SSLParameters getSSLParameters() {
1249         SSLParameters params = new SSLParameters();
1250         params.setCipherSuites(getEnabledCipherSuites());
1251         params.setProtocols(getEnabledProtocols());
1252         if (getNeedClientAuth()) {
1253             params.setNeedClientAuth(true);
1254         } else if (getWantClientAuth()) {
1255             params.setWantClientAuth(true);
1256         }
1257         return params;
1258     }
1259 
1260     /**
1261      * Applies SSLParameters to this engine.
1262      *
1263      * <p>This means:
1264      * <ul>
1265      * <li>If {@code params.getCipherSuites()} is non-null,
1266      *   {@code setEnabledCipherSuites()} is called with that value.</li>
1267      * <li>If {@code params.getProtocols()} is non-null,
1268      *   {@code setEnabledProtocols()} is called with that value.</li>
1269      * <li>If {@code params.getNeedClientAuth()} or
1270      *   {@code params.getWantClientAuth()} return {@code true},
1271      *   {@code setNeedClientAuth(true)} and
1272      *   {@code setWantClientAuth(true)} are called, respectively;
1273      *   otherwise {@code setWantClientAuth(false)} is called.</li>
1274      * <li>If {@code params.getServerNames()} is non-null, the engine will
1275      *   configure its server names with that value.</li>
1276      * <li>If {@code params.getSNIMatchers()} is non-null, the engine will
1277      *   configure its SNI matchers with that value.</li>
1278      * </ul>
1279      *
1280      * @param params the parameters
1281      * @throws IllegalArgumentException if the setEnabledCipherSuites() or
1282      *    the setEnabledProtocols() call fails
1283      * @since 1.6
1284      */
setSSLParameters(SSLParameters params)1285     public void setSSLParameters(SSLParameters params) {
1286         String[] s;
1287         s = params.getCipherSuites();
1288         if (s != null) {
1289             setEnabledCipherSuites(s);
1290         }
1291         s = params.getProtocols();
1292         if (s != null) {
1293             setEnabledProtocols(s);
1294         }
1295         if (params.getNeedClientAuth()) {
1296             setNeedClientAuth(true);
1297         } else if (params.getWantClientAuth()) {
1298             setWantClientAuth(true);
1299         } else {
1300             setWantClientAuth(false);
1301         }
1302     }
1303 
1304     /**
1305      * Returns the most recent application protocol value negotiated for this
1306      * connection.
1307      * <p>
1308      * If supported by the underlying SSL/TLS/DTLS implementation,
1309      * application name negotiation mechanisms such as <a
1310      * href="http://www.ietf.org/rfc/rfc7301.txt"> RFC 7301 </a>, the
1311      * Application-Layer Protocol Negotiation (ALPN), can negotiate
1312      * application-level values between peers.
1313      *
1314      * @implSpec
1315      * The implementation in this class throws
1316      * {@code UnsupportedOperationException} and performs no other action.
1317      *
1318      * @return null if it has not yet been determined if application
1319      *         protocols might be used for this connection, an empty
1320      *         {@code String} if application protocols values will not
1321      *         be used, or a non-empty application protocol {@code String}
1322      *         if a value was successfully negotiated.
1323      * @throws UnsupportedOperationException if the underlying provider
1324      *         does not implement the operation.
1325      * @since 9
1326      */
getApplicationProtocol()1327     public String getApplicationProtocol() {
1328         throw new UnsupportedOperationException();
1329     }
1330 
1331     /**
1332      * Returns the application protocol value negotiated on a SSL/TLS
1333      * handshake currently in progress.
1334      * <p>
1335      * Like {@link #getHandshakeSession()},
1336      * a connection may be in the middle of a handshake. The
1337      * application protocol may or may not yet be available.
1338      *
1339      * @implSpec
1340      * The implementation in this class throws
1341      * {@code UnsupportedOperationException} and performs no other action.
1342      *
1343      * @return null if it has not yet been determined if application
1344      *         protocols might be used for this handshake, an empty
1345      *         {@code String} if application protocols values will not
1346      *         be used, or a non-empty application protocol {@code String}
1347      *         if a value was successfully negotiated.
1348      * @throws UnsupportedOperationException if the underlying provider
1349      *         does not implement the operation.
1350      * @since 9
1351      */
getHandshakeApplicationProtocol()1352     public String getHandshakeApplicationProtocol() {
1353         throw new UnsupportedOperationException();
1354     }
1355 
1356     /**
1357      * Registers a callback function that selects an application protocol
1358      * value for a SSL/TLS/DTLS handshake.
1359      * The function overrides any values supplied using
1360      * {@link SSLParameters#setApplicationProtocols
1361      * SSLParameters.setApplicationProtocols} and it supports the following
1362      * type parameters:
1363      * <blockquote>
1364      * <dl>
1365      * <dt> {@code SSLEngine}
1366      * <dd> The function's first argument allows the current {@code SSLEngine}
1367      *      to be inspected, including the handshake session and configuration
1368      *      settings.
1369      * <dt> {@code List<String>}
1370      * <dd> The function's second argument lists the application protocol names
1371      *      advertised by the TLS peer.
1372      * <dt> {@code String}
1373      * <dd> The function's result is an application protocol name, or null to
1374      *      indicate that none of the advertised names are acceptable.
1375      *      If the return value is an empty {@code String} then application
1376      *      protocol indications will not be used.
1377      *      If the return value is null (no value chosen) or is a value that
1378      *      was not advertised by the peer, the underlying protocol will
1379      *      determine what action to take. (For example, ALPN will send a
1380      *      "no_application_protocol" alert and terminate the connection.)
1381      * </dl>
1382      * </blockquote>
1383      *
1384      * For example, the following call registers a callback function that
1385      * examines the TLS handshake parameters and selects an application protocol
1386      * name:
1387      * <pre>{@code
1388      *     serverEngine.setHandshakeApplicationProtocolSelector(
1389      *         (serverEngine, clientProtocols) -> {
1390      *             SSLSession session = serverEngine.getHandshakeSession();
1391      *             return chooseApplicationProtocol(
1392      *                 serverEngine,
1393      *                 clientProtocols,
1394      *                 session.getProtocol(),
1395      *                 session.getCipherSuite());
1396      *         });
1397      * }</pre>
1398      *
1399      * @apiNote
1400      * This method should be called by TLS server applications before the TLS
1401      * handshake begins. Also, this {@code SSLEngine} should be configured with
1402      * parameters that are compatible with the application protocol selected by
1403      * the callback function. For example, enabling a poor choice of cipher
1404      * suites could result in no suitable application protocol.
1405      * See {@link SSLParameters}.
1406      *
1407      * @implSpec
1408      * The implementation in this class throws
1409      * {@code UnsupportedOperationException} and performs no other action.
1410      *
1411      * @param selector the callback function, or null to disable the callback
1412      *         functionality.
1413      * @throws UnsupportedOperationException if the underlying provider
1414      *         does not implement the operation.
1415      * @since 9
1416      */
setHandshakeApplicationProtocolSelector( BiFunction<SSLEngine, List<String>, String> selector)1417     public void setHandshakeApplicationProtocolSelector(
1418             BiFunction<SSLEngine, List<String>, String> selector) {
1419         throw new UnsupportedOperationException();
1420     }
1421 
1422     /**
1423      * Retrieves the callback function that selects an application protocol
1424      * value during a SSL/TLS/DTLS handshake.
1425      * See {@link #setHandshakeApplicationProtocolSelector
1426      * setHandshakeApplicationProtocolSelector}
1427      * for the function's type parameters.
1428      *
1429      * @implSpec
1430      * The implementation in this class throws
1431      * {@code UnsupportedOperationException} and performs no other action.
1432      *
1433      * @return the callback function, or null if none has been set.
1434      * @throws UnsupportedOperationException if the underlying provider
1435      *         does not implement the operation.
1436      * @since 9
1437      */
1438     public BiFunction<SSLEngine, List<String>, String>
getHandshakeApplicationProtocolSelector()1439             getHandshakeApplicationProtocolSelector() {
1440         throw new UnsupportedOperationException();
1441     }
1442 }
1443