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