1 /* 2 * Copyright (c) 2003, 2021, 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 * case 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 * case 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 * The ApplicationProtocol {@code String} values returned by the methods 340 * in this class are in the network byte representation sent by the peer. 341 * The bytes could be directly compared, or converted to its Unicode 342 * {code String} format for comparison. 343 * 344 * <blockquote><pre> 345 * String networkString = sslEngine.getHandshakeApplicationProtocol(); 346 * byte[] bytes = networkString.getBytes(StandardCharsets.ISO_8859_1); 347 * 348 * // 349 * // Match using bytes: 350 * // 351 * // "http/1.1" (7-bit ASCII values same in UTF-8) 352 * // MEETEI MAYEK LETTERS "HUK UN I" (Unicode 0xabcd->0xabcf) 353 * // 354 * String HTTP1_1 = "http/1.1"; 355 * byte[] HTTP1_1_BYTES = HTTP1_1.getBytes(StandardCharsets.UTF_8); 356 * 357 * byte[] HUK_UN_I_BYTES = new byte[] { 358 * (byte) 0xab, (byte) 0xcd, 359 * (byte) 0xab, (byte) 0xce, 360 * (byte) 0xab, (byte) 0xcf}; 361 * 362 * if ((Arrays.compare(bytes, HTTP1_1_BYTES) == 0 ) 363 * || Arrays.compare(bytes, HUK_UN_I_BYTES) == 0) { 364 * ... 365 * } 366 * 367 * // 368 * // Alternatively match using string.equals() if we know the ALPN value 369 * // was encoded from a {@code String} using a certain character set, 370 * // for example {@code UTF-8}. The ALPN value must first be properly 371 * // decoded to a Unicode {@code String} before use. 372 * // 373 * String unicodeString = new String(bytes, StandardCharsets.UTF_8); 374 * if (unicodeString.equals(HTTP1_1) 375 * || unicodeString.equals("\u005cuabcd\u005cuabce\u005cuabcf")) { 376 * ... 377 * } 378 * </pre></blockquote> 379 * 380 * <P> 381 * Applications might choose to process delegated tasks in different 382 * threads. When an {@code SSLEngine} 383 * is created, the current {@link java.security.AccessControlContext} 384 * is saved. All future delegated tasks will be processed using this 385 * context: that is, all access control decisions will be made using the 386 * context captured at engine creation. 387 * 388 * <HR> 389 * 390 * <B>Concurrency Notes</B>: 391 * There are two concurrency issues to be aware of: 392 * 393 * <OL> 394 * <li>The {@code wrap()} and {@code unwrap()} methods 395 * may execute concurrently of each other. 396 * 397 * <li> The SSL/TLS/DTLS protocols employ ordered packets. 398 * Applications must take care to ensure that generated packets 399 * are delivered in sequence. If packets arrive 400 * out-of-order, unexpected or fatal results may occur. 401 * <P> 402 * For example: 403 * 404 * <pre> 405 * synchronized (outboundLock) { 406 * sslEngine.wrap(src, dst); 407 * outboundQueue.put(dst); 408 * } 409 * </pre> 410 * 411 * As a corollary, two threads must not attempt to call the same method 412 * (either {@code wrap()} or {@code unwrap()}) concurrently, 413 * because there is no way to guarantee the eventual packet ordering. 414 * </OL> 415 * 416 * @see SSLContext 417 * @see SSLSocket 418 * @see SSLServerSocket 419 * @see SSLSession 420 * @see java.net.Socket 421 * 422 * @since 1.5 423 * @author Brad R. Wetmore 424 */ 425 426 public abstract class SSLEngine { 427 428 private String peerHost = null; 429 private int peerPort = -1; 430 431 /** 432 * Constructor for an {@code SSLEngine} providing no hints 433 * for an internal session reuse strategy. 434 * 435 * @see SSLContext#createSSLEngine() 436 * @see SSLSessionContext 437 */ SSLEngine()438 protected SSLEngine() { 439 } 440 441 /** 442 * Constructor for an {@code SSLEngine}. 443 * <P> 444 * {@code SSLEngine} implementations may use the 445 * {@code peerHost} and {@code peerPort} parameters as hints 446 * for their internal session reuse strategy. 447 * <P> 448 * Some cipher suites (such as Kerberos) require remote hostname 449 * information. Implementations of this class should use this 450 * constructor to use Kerberos. 451 * <P> 452 * The parameters are not authenticated by the 453 * {@code SSLEngine}. 454 * 455 * @param peerHost the name of the peer host 456 * @param peerPort the port number of the peer 457 * @see SSLContext#createSSLEngine(String, int) 458 * @see SSLSessionContext 459 */ SSLEngine(String peerHost, int peerPort)460 protected SSLEngine(String peerHost, int peerPort) { 461 this.peerHost = peerHost; 462 this.peerPort = peerPort; 463 } 464 465 /** 466 * Returns the host name of the peer. 467 * <P> 468 * Note that the value is not authenticated, and should not be 469 * relied upon. 470 * 471 * @return the host name of the peer, or null if nothing is 472 * available. 473 */ getPeerHost()474 public String getPeerHost() { 475 return peerHost; 476 } 477 478 /** 479 * Returns the port number of the peer. 480 * <P> 481 * Note that the value is not authenticated, and should not be 482 * relied upon. 483 * 484 * @return the port number of the peer, or -1 if nothing is 485 * available. 486 */ getPeerPort()487 public int getPeerPort() { 488 return peerPort; 489 } 490 491 /** 492 * Attempts to encode a buffer of plaintext application data into 493 * SSL/TLS/DTLS network data. 494 * <P> 495 * An invocation of this method behaves in exactly the same manner 496 * as the invocation: 497 * <blockquote><pre> 498 * {@link #wrap(ByteBuffer [], int, int, ByteBuffer) 499 * engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);} 500 * </pre></blockquote> 501 * 502 * @param src 503 * a {@code ByteBuffer} containing outbound application data 504 * @param dst 505 * a {@code ByteBuffer} to hold outbound network data 506 * @return an {@code SSLEngineResult} describing the result 507 * of this operation. 508 * @throws SSLException 509 * A problem was encountered while processing the 510 * data that caused the {@code SSLEngine} to abort. 511 * See the class description for more information on 512 * engine closure. 513 * @throws ReadOnlyBufferException 514 * if the {@code dst} buffer is read-only. 515 * @throws IllegalArgumentException 516 * if either {@code src} or {@code dst} 517 * is null. 518 * @throws IllegalStateException if the client/server mode 519 * has not yet been set. 520 * @see #wrap(ByteBuffer [], int, int, ByteBuffer) 521 */ wrap(ByteBuffer src, ByteBuffer dst)522 public SSLEngineResult wrap(ByteBuffer src, 523 ByteBuffer dst) throws SSLException { 524 return wrap(new ByteBuffer [] { src }, 0, 1, dst); 525 } 526 527 /** 528 * Attempts to encode plaintext bytes from a sequence of data 529 * buffers into SSL/TLS/DTLS network data. 530 * <P> 531 * An invocation of this method behaves in exactly the same manner 532 * as the invocation: 533 * <blockquote><pre> 534 * {@link #wrap(ByteBuffer [], int, int, ByteBuffer) 535 * engine.wrap(srcs, 0, srcs.length, dst);} 536 * </pre></blockquote> 537 * 538 * @param srcs 539 * an array of {@code ByteBuffers} containing the 540 * outbound application data 541 * @param dst 542 * a {@code ByteBuffer} to hold outbound network data 543 * @return an {@code SSLEngineResult} describing the result 544 * of this operation. 545 * @throws SSLException 546 * A problem was encountered while processing the 547 * data that caused the {@code SSLEngine} to abort. 548 * See the class description for more information on 549 * engine closure. 550 * @throws ReadOnlyBufferException 551 * if the {@code dst} buffer is read-only. 552 * @throws IllegalArgumentException 553 * if either {@code srcs} or {@code dst} 554 * is null, or if any element in {@code srcs} is null. 555 * @throws IllegalStateException if the client/server mode 556 * has not yet been set. 557 * @see #wrap(ByteBuffer [], int, int, ByteBuffer) 558 */ wrap(ByteBuffer [] srcs, ByteBuffer dst)559 public SSLEngineResult wrap(ByteBuffer [] srcs, 560 ByteBuffer dst) throws SSLException { 561 if (srcs == null) { 562 throw new IllegalArgumentException("src == null"); 563 } 564 return wrap(srcs, 0, srcs.length, dst); 565 } 566 567 568 /** 569 * Attempts to encode plaintext bytes from a subsequence of data 570 * buffers into SSL/TLS/DTLS network data. This <i>"gathering"</i> 571 * operation encodes, in a single invocation, a sequence of bytes 572 * from one or more of a given sequence of buffers. Gathering 573 * wraps are often useful when implementing network protocols or 574 * file formats that, for example, group data into segments 575 * consisting of one or more fixed-length headers followed by a 576 * variable-length body. See 577 * {@link java.nio.channels.GatheringByteChannel} for more 578 * information on gathering, and {@link 579 * java.nio.channels.GatheringByteChannel#write(ByteBuffer[], 580 * int, int)} for more information on the subsequence 581 * behavior. 582 * <P> 583 * Depending on the state of the SSLEngine, this method may produce 584 * network data without consuming any application data (for example, 585 * it may generate handshake data.) 586 * <P> 587 * The application is responsible for reliably transporting the 588 * network data to the peer, and for ensuring that data created by 589 * multiple calls to wrap() is transported in the same order in which 590 * it was generated. The application must properly synchronize 591 * multiple calls to this method. 592 * <P> 593 * If this {@code SSLEngine} has not yet started its initial 594 * handshake, this method will automatically start the handshake. 595 * <P> 596 * This method will attempt to produce SSL/TLS/DTLS records, and will 597 * consume as much source data as possible, but will never consume 598 * more than the sum of the bytes remaining in each buffer. Each 599 * {@code ByteBuffer}'s position is updated to reflect the 600 * amount of data consumed or produced. The limits remain the 601 * same. 602 * <P> 603 * The underlying memory used by the {@code srcs} and 604 * {@code dst ByteBuffer}s must not be the same. 605 * <P> 606 * See the class description for more information on engine closure. 607 * 608 * @param srcs 609 * an array of {@code ByteBuffers} containing the 610 * outbound application data 611 * @param offset 612 * The offset within the buffer array of the first buffer from 613 * which bytes are to be retrieved; it must be non-negative 614 * and no larger than {@code srcs.length} 615 * @param length 616 * The maximum number of buffers to be accessed; it must be 617 * non-negative and no larger than 618 * {@code srcs.length} - {@code offset} 619 * @param dst 620 * a {@code ByteBuffer} to hold outbound network data 621 * @return an {@code SSLEngineResult} describing the result 622 * of this operation. 623 * @throws SSLException 624 * A problem was encountered while processing the 625 * data that caused the {@code SSLEngine} to abort. 626 * See the class description for more information on 627 * engine closure. 628 * @throws IndexOutOfBoundsException 629 * if the preconditions on the {@code offset} and 630 * {@code length} parameters do not hold. 631 * @throws ReadOnlyBufferException 632 * if the {@code dst} buffer is read-only. 633 * @throws IllegalArgumentException 634 * if either {@code srcs} or {@code dst} 635 * is null, or if any element in the {@code srcs} 636 * subsequence specified is null. 637 * @throws IllegalStateException if the client/server mode 638 * has not yet been set. 639 * @see java.nio.channels.GatheringByteChannel 640 * @see java.nio.channels.GatheringByteChannel#write( 641 * ByteBuffer[], int, int) 642 */ wrap(ByteBuffer [] srcs, int offset, int length, ByteBuffer dst)643 public abstract SSLEngineResult wrap(ByteBuffer [] srcs, int offset, 644 int length, ByteBuffer dst) throws SSLException; 645 646 /** 647 * Attempts to decode SSL/TLS/DTLS network data into a plaintext 648 * application data buffer. 649 * <P> 650 * An invocation of this method behaves in exactly the same manner 651 * as the invocation: 652 * <blockquote><pre> 653 * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int) 654 * engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);} 655 * </pre></blockquote> 656 * 657 * @param src 658 * a {@code ByteBuffer} containing inbound network data. 659 * @param dst 660 * a {@code ByteBuffer} to hold inbound application data. 661 * @return an {@code SSLEngineResult} describing the result 662 * of this operation. 663 * @throws SSLException 664 * A problem was encountered while processing the 665 * data that caused the {@code SSLEngine} to abort. 666 * See the class description for more information on 667 * engine closure. 668 * @throws ReadOnlyBufferException 669 * if the {@code dst} buffer is read-only. 670 * @throws IllegalArgumentException 671 * if either {@code src} or {@code dst} 672 * is null. 673 * @throws IllegalStateException if the client/server mode 674 * has not yet been set. 675 * @see #unwrap(ByteBuffer, ByteBuffer [], int, int) 676 */ unwrap(ByteBuffer src, ByteBuffer dst)677 public SSLEngineResult unwrap(ByteBuffer src, 678 ByteBuffer dst) throws SSLException { 679 return unwrap(src, new ByteBuffer [] { dst }, 0, 1); 680 } 681 682 /** 683 * Attempts to decode SSL/TLS/DTLS network data into a sequence of plaintext 684 * application data buffers. 685 * <P> 686 * An invocation of this method behaves in exactly the same manner 687 * as the invocation: 688 * <blockquote><pre> 689 * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int) 690 * engine.unwrap(src, dsts, 0, dsts.length);} 691 * </pre></blockquote> 692 * 693 * @param src 694 * a {@code ByteBuffer} containing inbound network data. 695 * @param dsts 696 * an array of {@code ByteBuffer}s to hold inbound 697 * application data. 698 * @return an {@code SSLEngineResult} describing the result 699 * of this operation. 700 * @throws SSLException 701 * A problem was encountered while processing the 702 * data that caused the {@code SSLEngine} to abort. 703 * See the class description for more information on 704 * engine closure. 705 * @throws ReadOnlyBufferException 706 * if any of the {@code dst} buffers are read-only. 707 * @throws IllegalArgumentException 708 * if either {@code src} or {@code dsts} 709 * is null, or if any element in {@code dsts} is null. 710 * @throws IllegalStateException if the client/server mode 711 * has not yet been set. 712 * @see #unwrap(ByteBuffer, ByteBuffer [], int, int) 713 */ unwrap(ByteBuffer src, ByteBuffer [] dsts)714 public SSLEngineResult unwrap(ByteBuffer src, 715 ByteBuffer [] dsts) throws SSLException { 716 if (dsts == null) { 717 throw new IllegalArgumentException("dsts == null"); 718 } 719 return unwrap(src, dsts, 0, dsts.length); 720 } 721 722 /** 723 * Attempts to decode SSL/TLS/DTLS network data into a subsequence of 724 * plaintext application data buffers. This <i>"scattering"</i> 725 * operation decodes, in a single invocation, a sequence of bytes 726 * into one or more of a given sequence of buffers. Scattering 727 * unwraps are often useful when implementing network protocols or 728 * file formats that, for example, group data into segments 729 * consisting of one or more fixed-length headers followed by a 730 * variable-length body. See 731 * {@link java.nio.channels.ScatteringByteChannel} for more 732 * information on scattering, and {@link 733 * java.nio.channels.ScatteringByteChannel#read(ByteBuffer[], 734 * int, int)} for more information on the subsequence 735 * behavior. 736 * <P> 737 * Depending on the state of the SSLEngine, this method may consume 738 * network data without producing any application data (for example, 739 * it may consume handshake data.) 740 * <P> 741 * The application is responsible for reliably obtaining the network 742 * data from the peer, and for invoking unwrap() on the data in the 743 * order it was received. The application must properly synchronize 744 * multiple calls to this method. 745 * <P> 746 * If this {@code SSLEngine} has not yet started its initial 747 * handshake, this method will automatically start the handshake. 748 * <P> 749 * This method will attempt to consume one complete SSL/TLS/DTLS network 750 * packet, but will never consume more than the sum of the bytes 751 * remaining in the buffers. Each {@code ByteBuffer}'s 752 * position is updated to reflect the amount of data consumed or 753 * produced. The limits remain the same. 754 * <P> 755 * The underlying memory used by the {@code src} and 756 * {@code dsts ByteBuffer}s must not be the same. 757 * <P> 758 * The inbound network buffer may be modified as a result of this 759 * call: therefore if the network data packet is required for some 760 * secondary purpose, the data should be duplicated before calling this 761 * method. Note: the network data will not be useful to a second 762 * SSLEngine, as each SSLEngine contains unique random state which 763 * influences the SSL/TLS/DTLS messages. 764 * <P> 765 * See the class description for more information on engine closure. 766 * 767 * @param src 768 * a {@code ByteBuffer} containing inbound network data. 769 * @param dsts 770 * an array of {@code ByteBuffer}s to hold inbound 771 * application data. 772 * @param offset 773 * The offset within the buffer array of the first buffer from 774 * which bytes are to be transferred; it must be non-negative 775 * and no larger than {@code dsts.length}. 776 * @param length 777 * The maximum number of buffers to be accessed; it must be 778 * non-negative and no larger than 779 * {@code dsts.length} - {@code offset}. 780 * @return an {@code SSLEngineResult} describing the result 781 * of this operation. 782 * @throws SSLException 783 * A problem was encountered while processing the 784 * data that caused the {@code SSLEngine} to abort. 785 * See the class description for more information on 786 * engine closure. 787 * @throws IndexOutOfBoundsException 788 * If the preconditions on the {@code offset} and 789 * {@code length} parameters do not hold. 790 * @throws ReadOnlyBufferException 791 * if any of the {@code dst} buffers are read-only. 792 * @throws IllegalArgumentException 793 * if either {@code src} or {@code dsts} 794 * is null, or if any element in the {@code dsts} 795 * subsequence specified is null. 796 * @throws IllegalStateException if the client/server mode 797 * has not yet been set. 798 * @see java.nio.channels.ScatteringByteChannel 799 * @see java.nio.channels.ScatteringByteChannel#read( 800 * ByteBuffer[], int, int) 801 */ unwrap(ByteBuffer src, ByteBuffer [] dsts, int offset, int length)802 public abstract SSLEngineResult unwrap(ByteBuffer src, 803 ByteBuffer [] dsts, int offset, int length) throws SSLException; 804 805 806 /** 807 * Returns a delegated {@code Runnable} task for 808 * this {@code SSLEngine}. 809 * <P> 810 * {@code SSLEngine} operations may require the results of 811 * operations that block, or may take an extended period of time to 812 * complete. This method is used to obtain an outstanding {@link 813 * java.lang.Runnable} operation (task). Each task must be assigned 814 * a thread (possibly the current) to perform the {@link 815 * java.lang.Runnable#run() run} operation. Once the 816 * {@code run} method returns, the {@code Runnable} object 817 * is no longer needed and may be discarded. 818 * <P> 819 * Delegated tasks run in the {@code AccessControlContext} 820 * in place when this object was created. 821 * <P> 822 * A call to this method will return each outstanding task 823 * exactly once. 824 * <P> 825 * Multiple delegated tasks can be run in parallel. 826 * 827 * @return a delegated {@code Runnable} task, or null 828 * if none are available. 829 */ getDelegatedTask()830 public abstract Runnable getDelegatedTask(); 831 832 833 /** 834 * Signals that no more inbound network data will be sent 835 * to this {@code SSLEngine}. 836 * <P> 837 * If the application initiated the closing process by calling 838 * {@link #closeOutbound()}, under some circumstances it is not 839 * required that the initiator wait for the peer's corresponding 840 * close message. (See section 7.2.1 of the TLS specification (<A 841 * HREF="http://www.ietf.org/rfc/rfc2246.txt">RFC 2246</A>) for more 842 * information on waiting for closure alerts.) In such cases, this 843 * method need not be called. 844 * <P> 845 * But if the application did not initiate the closure process, or 846 * if the circumstances above do not apply, this method should be 847 * called whenever the end of the SSL/TLS/DTLS data stream is reached. 848 * This ensures closure of the inbound side, and checks that the 849 * peer followed the SSL/TLS/DTLS close procedure properly, thus 850 * detecting possible truncation attacks. 851 * <P> 852 * This method is idempotent: if the inbound side has already 853 * been closed, this method does not do anything. 854 * <P> 855 * {@link #wrap(ByteBuffer, ByteBuffer) wrap()} should be 856 * called to flush any remaining handshake data. 857 * 858 * @throws SSLException 859 * if this engine has not received the proper SSL/TLS/DTLS close 860 * notification message from the peer. 861 * 862 * @see #isInboundDone() 863 * @see #isOutboundDone() 864 */ closeInbound()865 public abstract void closeInbound() throws SSLException; 866 867 868 /** 869 * Returns whether {@link #unwrap(ByteBuffer, ByteBuffer)} will 870 * accept any more inbound data messages. 871 * 872 * @return true if the {@code SSLEngine} will not 873 * consume anymore network data (and by implication, 874 * will not produce any more application data.) 875 * @see #closeInbound() 876 */ isInboundDone()877 public abstract boolean isInboundDone(); 878 879 880 /** 881 * Signals that no more outbound application data will be sent 882 * on this {@code SSLEngine}. 883 * <P> 884 * This method is idempotent: if the outbound side has already 885 * been closed, this method does not do anything. 886 * <P> 887 * {@link #wrap(ByteBuffer, ByteBuffer)} should be 888 * called to flush any remaining handshake data. 889 * 890 * @see #isOutboundDone() 891 */ closeOutbound()892 public abstract void closeOutbound(); 893 894 895 /** 896 * Returns whether {@link #wrap(ByteBuffer, ByteBuffer)} will 897 * produce any more outbound data messages. 898 * <P> 899 * Note that during the closure phase, a {@code SSLEngine} may 900 * generate handshake closure data that must be sent to the peer. 901 * {@code wrap()} must be called to generate this data. When 902 * this method returns true, no more outbound data will be created. 903 * 904 * @return true if the {@code SSLEngine} will not produce 905 * any more network data 906 * 907 * @see #closeOutbound() 908 * @see #closeInbound() 909 */ isOutboundDone()910 public abstract boolean isOutboundDone(); 911 912 913 /** 914 * Returns the names of the cipher suites which could be enabled for use 915 * on this engine. Normally, only a subset of these will actually 916 * be enabled by default, since this list may include cipher suites which 917 * do not meet quality of service requirements for those defaults. Such 918 * cipher suites might be useful in specialized applications. 919 * <P> 920 * The returned array includes cipher suites from the list of standard 921 * cipher suite names in the <a href= 922 * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names"> 923 * JSSE Cipher Suite Names</a> section of the Java Cryptography 924 * Architecture Standard Algorithm Name Documentation, and may also 925 * include other cipher suites that the provider supports. 926 * 927 * @return an array of cipher suite names 928 * @see #getEnabledCipherSuites() 929 * @see #setEnabledCipherSuites(String []) 930 */ getSupportedCipherSuites()931 public abstract String [] getSupportedCipherSuites(); 932 933 934 /** 935 * Returns the names of the SSL cipher suites which are currently 936 * enabled for use on this engine. When an SSLEngine is first 937 * created, all enabled cipher suites support a minimum quality of 938 * service. Thus, in some environments this value might be empty. 939 * <P> 940 * Note that even if a suite is enabled, it may never be used. This 941 * can occur if the peer does not support it, or its use is restricted, 942 * or the requisite certificates (and private keys) for the suite are 943 * not available, or an anonymous suite is enabled but authentication 944 * is required. 945 * <P> 946 * The returned array includes cipher suites from the list of standard 947 * cipher suite names in the <a href= 948 * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names"> 949 * JSSE Cipher Suite Names</a> section of the Java Cryptography 950 * Architecture Standard Algorithm Name Documentation, and may also 951 * include other cipher suites that the provider supports. 952 * 953 * @return an array of cipher suite names 954 * @see #getSupportedCipherSuites() 955 * @see #setEnabledCipherSuites(String []) 956 */ getEnabledCipherSuites()957 public abstract String [] getEnabledCipherSuites(); 958 959 960 /** 961 * Sets the cipher suites enabled for use on this engine. 962 * <P> 963 * Each cipher suite in the {@code suites} parameter must have 964 * been listed by getSupportedCipherSuites(), or the method will 965 * fail. Following a successful call to this method, only suites 966 * listed in the {@code suites} parameter are enabled for use. 967 * <P> 968 * Note that the standard list of cipher suite names may be found in the 969 * <a href= 970 * "{@docRoot}/../specs/security/standard-names.html#jsse-cipher-suite-names"> 971 * JSSE Cipher Suite Names</a> section of the Java Cryptography 972 * Architecture Standard Algorithm Name Documentation. Providers 973 * may support cipher suite names not found in this list or might not 974 * use the recommended name for a certain cipher suite. 975 * <P> 976 * See {@link #getEnabledCipherSuites()} for more information 977 * on why a specific cipher suite may never be used on a engine. 978 * 979 * @param suites Names of all the cipher suites to enable 980 * @throws IllegalArgumentException when one or more of the ciphers 981 * named by the parameter is not supported, or when the 982 * parameter is null. 983 * @see #getSupportedCipherSuites() 984 * @see #getEnabledCipherSuites() 985 */ setEnabledCipherSuites(String suites [])986 public abstract void setEnabledCipherSuites(String suites []); 987 988 989 /** 990 * Returns the names of the protocols which could be enabled for use 991 * with this {@code SSLEngine}. 992 * 993 * @return an array of protocols supported 994 */ getSupportedProtocols()995 public abstract String [] getSupportedProtocols(); 996 997 998 /** 999 * Returns the names of the protocol versions which are currently 1000 * enabled for use with this {@code SSLEngine}. 1001 * <P> 1002 * Note that even if a protocol is enabled, it may never be used. 1003 * This can occur if the peer does not support the protocol, or its 1004 * use is restricted, or there are no enabled cipher suites supported 1005 * by the protocol. 1006 * 1007 * @return an array of protocols 1008 * @see #setEnabledProtocols(String []) 1009 */ getEnabledProtocols()1010 public abstract String [] getEnabledProtocols(); 1011 1012 1013 /** 1014 * Set the protocol versions enabled for use on this engine. 1015 * <P> 1016 * The protocols must have been listed by getSupportedProtocols() 1017 * as being supported. Following a successful call to this method, 1018 * only protocols listed in the {@code protocols} parameter 1019 * are enabled for use. 1020 * 1021 * @param protocols Names of all the protocols to enable. 1022 * @throws IllegalArgumentException when one or more of 1023 * the protocols named by the parameter is not supported or 1024 * when the protocols parameter is null. 1025 * @see #getEnabledProtocols() 1026 */ setEnabledProtocols(String protocols[])1027 public abstract void setEnabledProtocols(String protocols[]); 1028 1029 1030 /** 1031 * Returns the {@code SSLSession} in use in this 1032 * {@code SSLEngine}. 1033 * <P> 1034 * These can be long lived, and frequently correspond to an entire 1035 * login session for some user. The session specifies a particular 1036 * cipher suite which is being actively used by all connections in 1037 * that session, as well as the identities of the session's client 1038 * and server. 1039 * <P> 1040 * Unlike {@link SSLSocket#getSession()} 1041 * this method does not block until handshaking is complete. 1042 * <P> 1043 * Until the initial handshake has completed, this method returns 1044 * a session object which reports an invalid cipher suite of 1045 * "SSL_NULL_WITH_NULL_NULL". 1046 * 1047 * @return the {@code SSLSession} for this {@code SSLEngine} 1048 * @see SSLSession 1049 */ getSession()1050 public abstract SSLSession getSession(); 1051 1052 1053 /** 1054 * Returns the {@code SSLSession} being constructed during a SSL/TLS/DTLS 1055 * handshake. 1056 * <p> 1057 * TLS/DTLS protocols may negotiate parameters that are needed when using 1058 * an instance of this class, but before the {@code SSLSession} has 1059 * been completely initialized and made available via {@code getSession}. 1060 * For example, the list of valid signature algorithms may restrict 1061 * the type of certificates that can be used during TrustManager 1062 * decisions, or the maximum TLS/DTLS fragment packet sizes can be 1063 * resized to better support the network environment. 1064 * <p> 1065 * This method provides early access to the {@code SSLSession} being 1066 * constructed. Depending on how far the handshake has progressed, 1067 * some data may not yet be available for use. For example, if a 1068 * remote server will be sending a Certificate chain, but that chain 1069 * has yet not been processed, the {@code getPeerCertificates} 1070 * method of {@code SSLSession} will throw a 1071 * SSLPeerUnverifiedException. Once that chain has been processed, 1072 * {@code getPeerCertificates} will return the proper value. 1073 * 1074 * @see SSLSocket 1075 * @see SSLSession 1076 * @see ExtendedSSLSession 1077 * @see X509ExtendedKeyManager 1078 * @see X509ExtendedTrustManager 1079 * 1080 * @return null if this instance is not currently handshaking, or 1081 * if the current handshake has not progressed far enough to 1082 * create a basic SSLSession. Otherwise, this method returns the 1083 * {@code SSLSession} currently being negotiated. 1084 * @throws UnsupportedOperationException if the underlying provider 1085 * does not implement the operation. 1086 * 1087 * @since 1.7 1088 */ getHandshakeSession()1089 public SSLSession getHandshakeSession() { 1090 throw new UnsupportedOperationException(); 1091 } 1092 1093 1094 /** 1095 * Initiates handshaking (initial or renegotiation) on this SSLEngine. 1096 * <P> 1097 * This method is not needed for the initial handshake, as the 1098 * {@code wrap()} and {@code unwrap()} methods will 1099 * implicitly call this method if handshaking has not already begun. 1100 * <P> 1101 * Note that the peer may also request a session renegotiation with 1102 * this {@code SSLEngine} by sending the appropriate 1103 * session renegotiate handshake message. 1104 * <P> 1105 * Unlike the {@link SSLSocket#startHandshake() 1106 * SSLSocket#startHandshake()} method, this method does not block 1107 * until handshaking is completed. 1108 * <P> 1109 * To force a complete SSL/TLS/DTLS session renegotiation, the current 1110 * session should be invalidated prior to calling this method. 1111 * <P> 1112 * Some protocols may not support multiple handshakes on an existing 1113 * engine and may throw an {@code SSLException}. 1114 * 1115 * @throws SSLException 1116 * if a problem was encountered while signaling the 1117 * {@code SSLEngine} to begin a new handshake. 1118 * See the class description for more information on 1119 * engine closure. 1120 * @throws IllegalStateException if the client/server mode 1121 * has not yet been set. 1122 * @see SSLSession#invalidate() 1123 */ beginHandshake()1124 public abstract void beginHandshake() throws SSLException; 1125 1126 1127 /** 1128 * Returns the current handshake status for this {@code SSLEngine}. 1129 * 1130 * @return the current {@code SSLEngineResult.HandshakeStatus}. 1131 */ getHandshakeStatus()1132 public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus(); 1133 1134 1135 /** 1136 * Configures the engine to use client (or server) mode when 1137 * handshaking. 1138 * <P> 1139 * This method must be called before any handshaking occurs. 1140 * Once handshaking has begun, the mode can not be reset for the 1141 * life of this engine. 1142 * <P> 1143 * Servers normally authenticate themselves, and clients 1144 * are not required to do so. 1145 * 1146 * @implNote 1147 * The JDK SunJSSE provider implementation default for this mode is false. 1148 * 1149 * @param mode true if the engine should start its handshaking 1150 * in "client" mode 1151 * @throws IllegalArgumentException if a mode change is attempted 1152 * after the initial handshake has begun. 1153 * @see #getUseClientMode() 1154 */ setUseClientMode(boolean mode)1155 public abstract void setUseClientMode(boolean mode); 1156 1157 1158 /** 1159 * Returns true if the engine is set to use client mode when 1160 * handshaking. 1161 * 1162 * @implNote 1163 * The JDK SunJSSE provider implementation returns false unless 1164 * {@link setUseClientMode(boolean)} is used to change the mode to true. 1165 * 1166 * @return true if the engine should do handshaking 1167 * in "client" mode 1168 * @see #setUseClientMode(boolean) 1169 */ getUseClientMode()1170 public abstract boolean getUseClientMode(); 1171 1172 1173 /** 1174 * Configures the engine to <i>require</i> client authentication. This 1175 * option is only useful for engines in the server mode. 1176 * <P> 1177 * An engine's client authentication setting is one of the following: 1178 * <ul> 1179 * <li> client authentication required 1180 * <li> client authentication requested 1181 * <li> no client authentication desired 1182 * </ul> 1183 * <P> 1184 * Unlike {@link #setWantClientAuth(boolean)}, if this option is set and 1185 * the client chooses not to provide authentication information 1186 * about itself, <i>the negotiations will stop and the engine will 1187 * begin its closure procedure</i>. 1188 * <P> 1189 * Calling this method overrides any previous setting made by 1190 * this method or {@link #setWantClientAuth(boolean)}. 1191 * 1192 * @param need set to true if client authentication is required, 1193 * or false if no client authentication is desired. 1194 * @see #getNeedClientAuth() 1195 * @see #setWantClientAuth(boolean) 1196 * @see #getWantClientAuth() 1197 * @see #setUseClientMode(boolean) 1198 */ setNeedClientAuth(boolean need)1199 public abstract void setNeedClientAuth(boolean need); 1200 1201 1202 /** 1203 * Returns true if the engine will <i>require</i> client authentication. 1204 * This option is only useful to engines in the server mode. 1205 * 1206 * @return true if client authentication is required, 1207 * or false if no client authentication is desired. 1208 * @see #setNeedClientAuth(boolean) 1209 * @see #setWantClientAuth(boolean) 1210 * @see #getWantClientAuth() 1211 * @see #setUseClientMode(boolean) 1212 */ getNeedClientAuth()1213 public abstract boolean getNeedClientAuth(); 1214 1215 1216 /** 1217 * Configures the engine to <i>request</i> client authentication. 1218 * This option is only useful for engines in the server mode. 1219 * <P> 1220 * An engine's client authentication setting is one of the following: 1221 * <ul> 1222 * <li> client authentication required 1223 * <li> client authentication requested 1224 * <li> no client authentication desired 1225 * </ul> 1226 * <P> 1227 * Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and 1228 * the client chooses not to provide authentication information 1229 * about itself, <i>the negotiations will continue</i>. 1230 * <P> 1231 * Calling this method overrides any previous setting made by 1232 * this method or {@link #setNeedClientAuth(boolean)}. 1233 * 1234 * @param want set to true if client authentication is requested, 1235 * or false if no client authentication is desired. 1236 * @see #getWantClientAuth() 1237 * @see #setNeedClientAuth(boolean) 1238 * @see #getNeedClientAuth() 1239 * @see #setUseClientMode(boolean) 1240 */ setWantClientAuth(boolean want)1241 public abstract void setWantClientAuth(boolean want); 1242 1243 1244 /** 1245 * Returns true if the engine will <i>request</i> client authentication. 1246 * This option is only useful for engines in the server mode. 1247 * 1248 * @return true if client authentication is requested, 1249 * or false if no client authentication is desired. 1250 * @see #setNeedClientAuth(boolean) 1251 * @see #getNeedClientAuth() 1252 * @see #setWantClientAuth(boolean) 1253 * @see #setUseClientMode(boolean) 1254 */ getWantClientAuth()1255 public abstract boolean getWantClientAuth(); 1256 1257 1258 /** 1259 * Controls whether new SSL sessions may be established by this engine. 1260 * If session creations are not allowed, and there are no 1261 * existing sessions to resume, there will be no successful 1262 * handshaking. 1263 * 1264 * @param flag true indicates that sessions may be created; this 1265 * is the default. false indicates that an existing session 1266 * must be resumed 1267 * @see #getEnableSessionCreation() 1268 */ setEnableSessionCreation(boolean flag)1269 public abstract void setEnableSessionCreation(boolean flag); 1270 1271 1272 /** 1273 * Returns true if new SSL sessions may be established by this engine. 1274 * 1275 * @return true indicates that sessions may be created; this 1276 * is the default. false indicates that an existing session 1277 * must be resumed 1278 * @see #setEnableSessionCreation(boolean) 1279 */ getEnableSessionCreation()1280 public abstract boolean getEnableSessionCreation(); 1281 1282 /** 1283 * Returns the SSLParameters in effect for this SSLEngine. 1284 * The ciphersuites and protocols of the returned SSLParameters 1285 * are always non-null. 1286 * 1287 * @return the SSLParameters in effect for this SSLEngine. 1288 * @since 1.6 1289 */ getSSLParameters()1290 public SSLParameters getSSLParameters() { 1291 SSLParameters params = new SSLParameters(); 1292 params.setCipherSuites(getEnabledCipherSuites()); 1293 params.setProtocols(getEnabledProtocols()); 1294 if (getNeedClientAuth()) { 1295 params.setNeedClientAuth(true); 1296 } else if (getWantClientAuth()) { 1297 params.setWantClientAuth(true); 1298 } 1299 return params; 1300 } 1301 1302 /** 1303 * Applies SSLParameters to this engine. 1304 * 1305 * <p>This means: 1306 * <ul> 1307 * <li>If {@code params.getCipherSuites()} is non-null, 1308 * {@code setEnabledCipherSuites()} is called with that value.</li> 1309 * <li>If {@code params.getProtocols()} is non-null, 1310 * {@code setEnabledProtocols()} is called with that value.</li> 1311 * <li>If {@code params.getNeedClientAuth()} or 1312 * {@code params.getWantClientAuth()} return {@code true}, 1313 * {@code setNeedClientAuth(true)} and 1314 * {@code setWantClientAuth(true)} are called, respectively; 1315 * otherwise {@code setWantClientAuth(false)} is called.</li> 1316 * <li>If {@code params.getServerNames()} is non-null, the engine will 1317 * configure its server names with that value.</li> 1318 * <li>If {@code params.getSNIMatchers()} is non-null, the engine will 1319 * configure its SNI matchers with that value.</li> 1320 * </ul> 1321 * 1322 * @param params the parameters 1323 * @throws IllegalArgumentException if the setEnabledCipherSuites() or 1324 * the setEnabledProtocols() call fails 1325 * @since 1.6 1326 */ setSSLParameters(SSLParameters params)1327 public void setSSLParameters(SSLParameters params) { 1328 String[] s; 1329 s = params.getCipherSuites(); 1330 if (s != null) { 1331 setEnabledCipherSuites(s); 1332 } 1333 s = params.getProtocols(); 1334 if (s != null) { 1335 setEnabledProtocols(s); 1336 } 1337 if (params.getNeedClientAuth()) { 1338 setNeedClientAuth(true); 1339 } else if (params.getWantClientAuth()) { 1340 setWantClientAuth(true); 1341 } else { 1342 setWantClientAuth(false); 1343 } 1344 } 1345 1346 /** 1347 * Returns the most recent application protocol value negotiated for this 1348 * connection. 1349 * <p> 1350 * If supported by the underlying SSL/TLS/DTLS implementation, 1351 * application name negotiation mechanisms such as <a 1352 * href="http://www.ietf.org/rfc/rfc7301.txt"> RFC 7301 </a>, the 1353 * Application-Layer Protocol Negotiation (ALPN), can negotiate 1354 * application-level values between peers. 1355 * 1356 * @implSpec 1357 * The implementation in this class throws 1358 * {@code UnsupportedOperationException} and performs no other action. 1359 * 1360 * @return null if it has not yet been determined if application 1361 * protocols might be used for this connection, an empty 1362 * {@code String} if application protocols values will not 1363 * be used, or a non-empty application protocol {@code String} 1364 * if a value was successfully negotiated. 1365 * @throws UnsupportedOperationException if the underlying provider 1366 * does not implement the operation. 1367 * @since 9 1368 */ getApplicationProtocol()1369 public String getApplicationProtocol() { 1370 throw new UnsupportedOperationException(); 1371 } 1372 1373 /** 1374 * Returns the application protocol value negotiated on a SSL/TLS 1375 * handshake currently in progress. 1376 * <p> 1377 * Like {@link #getHandshakeSession()}, 1378 * a connection may be in the middle of a handshake. The 1379 * application protocol may or may not yet be available. 1380 * 1381 * @implSpec 1382 * The implementation in this class throws 1383 * {@code UnsupportedOperationException} and performs no other action. 1384 * 1385 * @return null if it has not yet been determined if application 1386 * protocols might be used for this handshake, an empty 1387 * {@code String} if application protocols values will not 1388 * be used, or a non-empty application protocol {@code String} 1389 * if a value was successfully negotiated. 1390 * @throws UnsupportedOperationException if the underlying provider 1391 * does not implement the operation. 1392 * @since 9 1393 */ getHandshakeApplicationProtocol()1394 public String getHandshakeApplicationProtocol() { 1395 throw new UnsupportedOperationException(); 1396 } 1397 1398 /** 1399 * Registers a callback function that selects an application protocol 1400 * value for a SSL/TLS/DTLS handshake. 1401 * The function overrides any values supplied using 1402 * {@link SSLParameters#setApplicationProtocols 1403 * SSLParameters.setApplicationProtocols} and it supports the following 1404 * type parameters: 1405 * <blockquote> 1406 * <dl> 1407 * <dt> {@code SSLEngine} 1408 * <dd> The function's first argument allows the current {@code SSLEngine} 1409 * to be inspected, including the handshake session and configuration 1410 * settings. 1411 * <dt> {@code List<String>} 1412 * <dd> The function's second argument lists the application protocol names 1413 * advertised by the TLS peer. 1414 * <dt> {@code String} 1415 * <dd> The function's result is an application protocol name, or null to 1416 * indicate that none of the advertised names are acceptable. 1417 * If the return value is an empty {@code String} then application 1418 * protocol indications will not be used. 1419 * If the return value is null (no value chosen) or is a value that 1420 * was not advertised by the peer, the underlying protocol will 1421 * determine what action to take. (For example, ALPN will send a 1422 * "no_application_protocol" alert and terminate the connection.) 1423 * </dl> 1424 * </blockquote> 1425 * 1426 * For example, the following call registers a callback function that 1427 * examines the TLS handshake parameters and selects an application protocol 1428 * name: 1429 * <pre>{@code 1430 * serverEngine.setHandshakeApplicationProtocolSelector( 1431 * (serverEngine, clientProtocols) -> { 1432 * SSLSession session = serverEngine.getHandshakeSession(); 1433 * return chooseApplicationProtocol( 1434 * serverEngine, 1435 * clientProtocols, 1436 * session.getProtocol(), 1437 * session.getCipherSuite()); 1438 * }); 1439 * }</pre> 1440 * 1441 * @apiNote 1442 * This method should be called by TLS server applications before the TLS 1443 * handshake begins. Also, this {@code SSLEngine} should be configured with 1444 * parameters that are compatible with the application protocol selected by 1445 * the callback function. For example, enabling a poor choice of cipher 1446 * suites could result in no suitable application protocol. 1447 * See {@link SSLParameters}. 1448 * 1449 * @implSpec 1450 * The implementation in this class throws 1451 * {@code UnsupportedOperationException} and performs no other action. 1452 * 1453 * @param selector the callback function, or null to disable the callback 1454 * functionality. 1455 * @throws UnsupportedOperationException if the underlying provider 1456 * does not implement the operation. 1457 * @since 9 1458 */ setHandshakeApplicationProtocolSelector( BiFunction<SSLEngine, List<String>, String> selector)1459 public void setHandshakeApplicationProtocolSelector( 1460 BiFunction<SSLEngine, List<String>, String> selector) { 1461 throw new UnsupportedOperationException(); 1462 } 1463 1464 /** 1465 * Retrieves the callback function that selects an application protocol 1466 * value during a SSL/TLS/DTLS handshake. 1467 * See {@link #setHandshakeApplicationProtocolSelector 1468 * setHandshakeApplicationProtocolSelector} 1469 * for the function's type parameters. 1470 * 1471 * @implSpec 1472 * The implementation in this class throws 1473 * {@code UnsupportedOperationException} and performs no other action. 1474 * 1475 * @return the callback function, or null if none has been set. 1476 * @throws UnsupportedOperationException if the underlying provider 1477 * does not implement the operation. 1478 * @since 9 1479 */ 1480 public BiFunction<SSLEngine, List<String>, String> getHandshakeApplicationProtocolSelector()1481 getHandshakeApplicationProtocolSelector() { 1482 throw new UnsupportedOperationException(); 1483 } 1484 } 1485