View Javadoc
1   /*
2    * Copyright (c) 1997, 2013, 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  
27  package javax.net.ssl;
28  
29  import java.io.IOException;
30  import java.net.*;
31  
32  /**
33   * This class extends <code>Socket</code>s and provides secure
34   * socket using protocols such as the "Secure
35   * Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols.
36   * <P>
37   * Such sockets are normal stream sockets, but they
38   * add a layer of security protections over the underlying network transport
39   * protocol, such as TCP.  Those protections include: <UL>
40   *
41   *      <LI> <em>Integrity Protection</em>.  SSL protects against
42   *      modification of messages by an active wiretapper.
43   *
44   *      <LI> <em>Authentication</em>.  In most modes, SSL provides
45   *      peer authentication.  Servers are usually authenticated,
46   *      and clients may be authenticated as requested by servers.
47   *
48   *      <LI> <em>Confidentiality (Privacy Protection)</em>.  In most
49   *      modes, SSL encrypts data being sent between client and server.
50   *      This protects the confidentiality of data, so that passive
51   *      wiretappers won't see sensitive data such as financial
52   *      information or personal information of many kinds.
53   *
54   *      </UL>
55   *
56   * <P>These kinds of protection are specified by a "cipher suite", which
57   * is a combination of cryptographic algorithms used by a given SSL connection.
58   * During the negotiation process, the two endpoints must agree on
59   * a ciphersuite that is available in both environments.
60   * If there is no such suite in common, no SSL connection can
61   * be established, and no data can be exchanged.
62   *
63   * <P> The cipher suite used is established by a negotiation process
64   * called "handshaking".  The goal of this
65   * process is to create or rejoin a "session", which may protect many
66   * connections over time.  After handshaking has completed, you can access
67   * session attributes by using the <em>getSession</em> method.
68   * The initial handshake on this connection can be initiated in
69   * one of three ways: <UL>
70   *
71   *      <LI> calling <code>startHandshake</code> which explicitly
72   *              begins handshakes, or
73   *      <LI> any attempt to read or write application data on
74   *              this socket causes an implicit handshake, or
75   *      <LI> a call to <code>getSession</code> tries to set up a session
76   *              if there is no currently valid session, and
77   *              an implicit handshake is done.
78   * </UL>
79   *
80   * <P>If handshaking fails for any reason, the <code>SSLSocket</code>
81   * is closed, and no further communications can be done.
82   *
83   * <P>There are two groups of cipher suites which you will need to know
84   * about when managing cipher suites: <UL>
85   *
86   *      <LI> <em>Supported</em> cipher suites:  all the suites which are
87   *      supported by the SSL implementation.  This list is reported
88   *      using <em>getSupportedCipherSuites</em>.
89   *
90   *      <LI> <em>Enabled</em> cipher suites, which may be fewer
91   *      than the full set of supported suites.  This group is
92   *      set using the <em>setEnabledCipherSuites</em> method, and
93   *      queried using the <em>getEnabledCipherSuites</em> method.
94   *      Initially, a default set of cipher suites will be enabled on
95   *      a new socket that represents the minimum suggested configuration.
96   *
97   *      </UL>
98   *
99   * <P> Implementation defaults require that only cipher
100  * suites which authenticate servers and provide confidentiality
101  * be enabled by default.
102  * Only if both sides explicitly agree to unauthenticated and/or
103  * non-private (unencrypted) communications will such a ciphersuite be
104  * selected.
105  *
106  * <P>When <code>SSLSocket</code>s are first created, no handshaking
107  * is done so that applications may first set their communication
108  * preferences:  what cipher suites to use, whether the socket should be
109  * in client or server mode, etc.
110  * However, security is always provided by the time that application data
111  * is sent over the connection.
112  *
113  * <P> You may register to receive event notification of handshake
114  * completion.  This involves
115  * the use of two additional classes.  <em>HandshakeCompletedEvent</em>
116  * objects are passed to <em>HandshakeCompletedListener</em> instances,
117  * which are registered by users of this API.
118  *
119  * <code>SSLSocket</code>s are created by <code>SSLSocketFactory</code>s,
120  * or by <code>accept</code>ing a connection from a
121  * <code>SSLServerSocket</code>.
122  *
123  * <P>A SSL socket must choose to operate in the client or server mode.
124  * This will determine who begins the handshaking process, as well
125  * as which messages should be sent by each party.  Each
126  * connection must have one client and one server, or handshaking
127  * will not progress properly.  Once the initial handshaking has started, a
128  * socket can not switch between client and server modes, even when
129  * performing renegotiations.
130  *
131  * @see java.net.Socket
132  * @see SSLServerSocket
133  * @see SSLSocketFactory
134  *
135  * @since 1.4
136  * @author David Brownell
137  */
138 public abstract class SSLSocket extends Socket
139 {
140     /**
141      * Used only by subclasses.
142      * Constructs an uninitialized, unconnected TCP socket.
143      */
144     protected SSLSocket()
145         { super(); }
146 
147 
148     /**
149      * Used only by subclasses.
150      * Constructs a TCP connection to a named host at a specified port.
151      * This acts as the SSL client.
152      * <p>
153      * If there is a security manager, its <code>checkConnect</code>
154      * method is called with the host address and <code>port</code>
155      * as its arguments. This could result in a SecurityException.
156      *
157      * @param host name of the host with which to connect, or
158      *        <code>null</code> for the loopback address.
159      * @param port number of the server's port
160      * @throws IOException if an I/O error occurs when creating the socket
161      * @throws SecurityException if a security manager exists and its
162      *         <code>checkConnect</code> method doesn't allow the operation.
163      * @throws UnknownHostException if the host is not known
164      * @throws IllegalArgumentException if the port parameter is outside the
165      *         specified range of valid port values, which is between 0 and
166      *         65535, inclusive.
167      * @see SecurityManager#checkConnect
168      */
169     protected SSLSocket(String host, int port)
170     throws IOException, UnknownHostException
171         { super(host, port); }
172 
173 
174     /**
175      * Used only by subclasses.
176      * Constructs a TCP connection to a server at a specified address
177      * and port.  This acts as the SSL client.
178      * <p>
179      * If there is a security manager, its <code>checkConnect</code>
180      * method is called with the host address and <code>port</code>
181      * as its arguments. This could result in a SecurityException.
182      *
183      * @param address the server's host
184      * @param port its port
185      * @throws IOException if an I/O error occurs when creating the socket
186      * @throws SecurityException if a security manager exists and its
187      *         <code>checkConnect</code> method doesn't allow the operation.
188      * @throws IllegalArgumentException if the port parameter is outside the
189      *         specified range of valid port values, which is between 0 and
190      *         65535, inclusive.
191      * @throws NullPointerException if <code>address</code> is null.
192      * @see SecurityManager#checkConnect
193      */
194     protected SSLSocket(InetAddress address, int port)
195     throws IOException
196         { super(address, port); }
197 
198 
199     /**
200      * Used only by subclasses.
201      * Constructs an SSL connection to a named host at a specified port,
202      * binding the client side of the connection a given address and port.
203      * This acts as the SSL client.
204      * <p>
205      * If there is a security manager, its <code>checkConnect</code>
206      * method is called with the host address and <code>port</code>
207      * as its arguments. This could result in a SecurityException.
208      *
209      * @param host name of the host with which to connect, or
210      *        <code>null</code> for the loopback address.
211      * @param port number of the server's port
212      * @param clientAddress the client's address the socket is bound to, or
213      *        <code>null</code> for the <code>anyLocal</code> address.
214      * @param clientPort the client's port the socket is bound to, or
215      *        <code>zero</code> for a system selected free port.
216      * @throws IOException if an I/O error occurs when creating the socket
217      * @throws SecurityException if a security manager exists and its
218      *         <code>checkConnect</code> method doesn't allow the operation.
219      * @throws UnknownHostException if the host is not known
220      * @throws IllegalArgumentException if the port parameter or clientPort
221      *         parameter is outside the specified range of valid port values,
222      *         which is between 0 and 65535, inclusive.
223      * @see SecurityManager#checkConnect
224      */
225     protected SSLSocket(String host, int port,
226         InetAddress clientAddress, int clientPort)
227     throws IOException, UnknownHostException
228         { super(host, port, clientAddress, clientPort); }
229 
230 
231     /**
232      * Used only by subclasses.
233      * Constructs an SSL connection to a server at a specified address
234      * and TCP port, binding the client side of the connection a given
235      * address and port.  This acts as the SSL client.
236      * <p>
237      * If there is a security manager, its <code>checkConnect</code>
238      * method is called with the host address and <code>port</code>
239      * as its arguments. This could result in a SecurityException.
240      *
241      * @param address the server's host
242      * @param port its port
243      * @param clientAddress the client's address the socket is bound to, or
244      *        <code>null</code> for the <code>anyLocal</code> address.
245      * @param clientPort the client's port the socket is bound to, or
246      *        <code>zero</code> for a system selected free port.
247      * @throws IOException if an I/O error occurs when creating the socket
248      * @throws SecurityException if a security manager exists and its
249      *         <code>checkConnect</code> method doesn't allow the operation.
250      * @throws IllegalArgumentException if the port parameter or clientPort
251      *         parameter is outside the specified range of valid port values,
252      *         which is between 0 and 65535, inclusive.
253      * @throws NullPointerException if <code>address</code> is null.
254      * @see SecurityManager#checkConnect
255      */
256     protected SSLSocket(InetAddress address, int port,
257         InetAddress clientAddress, int clientPort)
258     throws IOException
259         { super(address, port, clientAddress, clientPort); }
260 
261 
262     /**
263      * Returns the names of the cipher suites which could be enabled for use
264      * on this connection.  Normally, only a subset of these will actually
265      * be enabled by default, since this list may include cipher suites which
266      * do not meet quality of service requirements for those defaults.  Such
267      * cipher suites might be useful in specialized applications.
268      *
269      * @return an array of cipher suite names
270      * @see #getEnabledCipherSuites()
271      * @see #setEnabledCipherSuites(String [])
272      */
273     public abstract String [] getSupportedCipherSuites();
274 
275 
276     /**
277      * Returns the names of the SSL cipher suites which are currently
278      * enabled for use on this connection.  When an SSLSocket is first
279      * created, all enabled cipher suites support a minimum quality of
280      * service.  Thus, in some environments this value might be empty.
281      * <P>
282      * Even if a suite has been enabled, it might never be used.  (For
283      * example, the peer does not support it, the requisite certificates
284      * (and private keys) for the suite are not available, or an
285      * anonymous suite is enabled but authentication is required.
286      *
287      * @return an array of cipher suite names
288      * @see #getSupportedCipherSuites()
289      * @see #setEnabledCipherSuites(String [])
290      */
291     public abstract String [] getEnabledCipherSuites();
292 
293 
294     /**
295      * Sets the cipher suites enabled for use on this connection.
296      * <P>
297      * Each cipher suite in the <code>suites</code> parameter must have
298      * been listed by getSupportedCipherSuites(), or the method will
299      * fail.  Following a successful call to this method, only suites
300      * listed in the <code>suites</code> parameter are enabled for use.
301      * <P>
302      * See {@link #getEnabledCipherSuites()} for more information
303      * on why a specific ciphersuite may never be used on a connection.
304      *
305      * @param suites Names of all the cipher suites to enable
306      * @throws IllegalArgumentException when one or more of the ciphers
307      *          named by the parameter is not supported, or when the
308      *          parameter is null.
309      * @see #getSupportedCipherSuites()
310      * @see #getEnabledCipherSuites()
311      */
312     public abstract void setEnabledCipherSuites(String suites []);
313 
314 
315     /**
316      * Returns the names of the protocols which could be enabled for use
317      * on an SSL connection.
318      *
319      * @return an array of protocols supported
320      */
321     public abstract String [] getSupportedProtocols();
322 
323 
324     /**
325      * Returns the names of the protocol versions which are currently
326      * enabled for use on this connection.
327      * @see #setEnabledProtocols(String [])
328      * @return an array of protocols
329      */
330     public abstract String [] getEnabledProtocols();
331 
332 
333     /**
334      * Sets the protocol versions enabled for use on this connection.
335      * <P>
336      * The protocols must have been listed by
337      * <code>getSupportedProtocols()</code> as being supported.
338      * Following a successful call to this method, only protocols listed
339      * in the <code>protocols</code> parameter are enabled for use.
340      *
341      * @param protocols Names of all the protocols to enable.
342      * @throws IllegalArgumentException when one or more of
343      *            the protocols named by the parameter is not supported or
344      *            when the protocols parameter is null.
345      * @see #getEnabledProtocols()
346      */
347     public abstract void setEnabledProtocols(String protocols[]);
348 
349 
350     /**
351      * Returns the SSL Session in use by this connection.  These can
352      * be long lived, and frequently correspond to an entire login session
353      * for some user.  The session specifies a particular cipher suite
354      * which is being actively used by all connections in that session,
355      * as well as the identities of the session's client and server.
356      * <P>
357      * This method will initiate the initial handshake if
358      * necessary and then block until the handshake has been
359      * established.
360      * <P>
361      * If an error occurs during the initial handshake, this method
362      * returns an invalid session object which reports an invalid
363      * cipher suite of "SSL_NULL_WITH_NULL_NULL".
364      *
365      * @return the <code>SSLSession</code>
366      */
367     public abstract SSLSession getSession();
368 
369 
370     /**
371      * Returns the {@code SSLSession} being constructed during a SSL/TLS
372      * handshake.
373      * <p>
374      * TLS protocols may negotiate parameters that are needed when using
375      * an instance of this class, but before the {@code SSLSession} has
376      * been completely initialized and made available via {@code getSession}.
377      * For example, the list of valid signature algorithms may restrict
378      * the type of certificates that can used during TrustManager
379      * decisions, or the maximum TLS fragment packet sizes can be
380      * resized to better support the network environment.
381      * <p>
382      * This method provides early access to the {@code SSLSession} being
383      * constructed.  Depending on how far the handshake has progressed,
384      * some data may not yet be available for use.  For example, if a
385      * remote server will be sending a Certificate chain, but that chain
386      * has yet not been processed, the {@code getPeerCertificates}
387      * method of {@code SSLSession} will throw a
388      * SSLPeerUnverifiedException.  Once that chain has been processed,
389      * {@code getPeerCertificates} will return the proper value.
390      * <p>
391      * Unlike {@link #getSession()}, this method does not initiate the
392      * initial handshake and does not block until handshaking is
393      * complete.
394      *
395      * @see SSLEngine
396      * @see SSLSession
397      * @see ExtendedSSLSession
398      * @see X509ExtendedKeyManager
399      * @see X509ExtendedTrustManager
400      *
401      * @return null if this instance is not currently handshaking, or
402      *         if the current handshake has not progressed far enough to
403      *         create a basic SSLSession.  Otherwise, this method returns the
404      *         {@code SSLSession} currently being negotiated.
405      * @throws UnsupportedOperationException if the underlying provider
406      *         does not implement the operation.
407      *
408      * @since 1.7
409      */
410     public SSLSession getHandshakeSession() {
411         throw new UnsupportedOperationException();
412     }
413 
414 
415     /**
416      * Registers an event listener to receive notifications that an
417      * SSL handshake has completed on this connection.
418      *
419      * @param listener the HandShake Completed event listener
420      * @see #startHandshake()
421      * @see #removeHandshakeCompletedListener(HandshakeCompletedListener)
422      * @throws IllegalArgumentException if the argument is null.
423      */
424     public abstract void addHandshakeCompletedListener(
425         HandshakeCompletedListener listener);
426 
427 
428     /**
429      * Removes a previously registered handshake completion listener.
430      *
431      * @param listener the HandShake Completed event listener
432      * @throws IllegalArgumentException if the listener is not registered,
433      * or the argument is null.
434      * @see #addHandshakeCompletedListener(HandshakeCompletedListener)
435      */
436     public abstract void removeHandshakeCompletedListener(
437         HandshakeCompletedListener listener);
438 
439 
440     /**
441      * Starts an SSL handshake on this connection.  Common reasons include
442      * a need to use new encryption keys, to change cipher suites, or to
443      * initiate a new session.  To force complete reauthentication, the
444      * current session could be invalidated before starting this handshake.
445      *
446      * <P> If data has already been sent on the connection, it continues
447      * to flow during this handshake.  When the handshake completes, this
448      * will be signaled with an event.
449      *
450      * This method is synchronous for the initial handshake on a connection
451      * and returns when the negotiated handshake is complete. Some
452      * protocols may not support multiple handshakes on an existing socket
453      * and may throw an IOException.
454      *
455      * @throws IOException on a network level error
456      * @see #addHandshakeCompletedListener(HandshakeCompletedListener)
457      */
458     public abstract void startHandshake() throws IOException;
459 
460 
461     /**
462      * Configures the socket to use client (or server) mode when
463      * handshaking.
464      * <P>
465      * This method must be called before any handshaking occurs.
466      * Once handshaking has begun, the mode can not be reset for the
467      * life of this socket.
468      * <P>
469      * Servers normally authenticate themselves, and clients
470      * are not required to do so.
471      *
472      * @param mode true if the socket should start its handshaking
473      *          in "client" mode
474      * @throws IllegalArgumentException if a mode change is attempted
475      *          after the initial handshake has begun.
476      * @see #getUseClientMode()
477      */
478     public abstract void setUseClientMode(boolean mode);
479 
480 
481     /**
482      * Returns true if the socket is set to use client mode when
483      * handshaking.
484      *
485      * @return true if the socket should do handshaking
486      *          in "client" mode
487      * @see #setUseClientMode(boolean)
488      */
489     public abstract boolean getUseClientMode();
490 
491 
492     /**
493      * Configures the socket to <i>require</i> client authentication.  This
494      * option is only useful for sockets in the server mode.
495      * <P>
496      * A socket's client authentication setting is one of the following:
497      * <ul>
498      * <li> client authentication required
499      * <li> client authentication requested
500      * <li> no client authentication desired
501      * </ul>
502      * <P>
503      * Unlike {@link #setWantClientAuth(boolean)}, if this option is set and
504      * the client chooses not to provide authentication information
505      * about itself, <i>the negotiations will stop and the connection
506      * will be dropped</i>.
507      * <P>
508      * Calling this method overrides any previous setting made by
509      * this method or {@link #setWantClientAuth(boolean)}.
510      *
511      * @param   need set to true if client authentication is required,
512      *          or false if no client authentication is desired.
513      * @see #getNeedClientAuth()
514      * @see #setWantClientAuth(boolean)
515      * @see #getWantClientAuth()
516      * @see #setUseClientMode(boolean)
517      */
518     public abstract void setNeedClientAuth(boolean need);
519 
520 
521     /**
522      * Returns true if the socket will <i>require</i> client authentication.
523      * This option is only useful to sockets in the server mode.
524      *
525      * @return  true if client authentication is required,
526      *          or false if no client authentication is desired.
527      * @see #setNeedClientAuth(boolean)
528      * @see #setWantClientAuth(boolean)
529      * @see #getWantClientAuth()
530      * @see #setUseClientMode(boolean)
531      */
532     public abstract boolean getNeedClientAuth();
533 
534 
535     /**
536      * Configures the socket to <i>request</i> client authentication.
537      * This option is only useful for sockets in the server mode.
538      * <P>
539      * A socket's client authentication setting is one of the following:
540      * <ul>
541      * <li> client authentication required
542      * <li> client authentication requested
543      * <li> no client authentication desired
544      * </ul>
545      * <P>
546      * Unlike {@link #setNeedClientAuth(boolean)}, if this option is set and
547      * the client chooses not to provide authentication information
548      * about itself, <i>the negotiations will continue</i>.
549      * <P>
550      * Calling this method overrides any previous setting made by
551      * this method or {@link #setNeedClientAuth(boolean)}.
552      *
553      * @param   want set to true if client authentication is requested,
554      *          or false if no client authentication is desired.
555      * @see #getWantClientAuth()
556      * @see #setNeedClientAuth(boolean)
557      * @see #getNeedClientAuth()
558      * @see #setUseClientMode(boolean)
559      */
560     public abstract void setWantClientAuth(boolean want);
561 
562 
563     /**
564      * Returns true if the socket will <i>request</i> client authentication.
565      * This option is only useful for sockets in the server mode.
566      *
567      * @return  true if client authentication is requested,
568      *          or false if no client authentication is desired.
569      * @see #setNeedClientAuth(boolean)
570      * @see #getNeedClientAuth()
571      * @see #setWantClientAuth(boolean)
572      * @see #setUseClientMode(boolean)
573      */
574     public abstract boolean getWantClientAuth();
575 
576 
577     /**
578      * Controls whether new SSL sessions may be established by this socket.
579      * If session creations are not allowed, and there are no
580      * existing sessions to resume, there will be no successful
581      * handshaking.
582      *
583      * @param flag true indicates that sessions may be created; this
584      *          is the default.  false indicates that an existing session
585      *          must be resumed
586      * @see #getEnableSessionCreation()
587      */
588     public abstract void setEnableSessionCreation(boolean flag);
589 
590 
591     /**
592      * Returns true if new SSL sessions may be established by this socket.
593      *
594      * @return true indicates that sessions may be created; this
595      *          is the default.  false indicates that an existing session
596      *          must be resumed
597      * @see #setEnableSessionCreation(boolean)
598      */
599     public abstract boolean getEnableSessionCreation();
600 
601     /**
602      * Returns the SSLParameters in effect for this SSLSocket.
603      * The ciphersuites and protocols of the returned SSLParameters
604      * are always non-null.
605      *
606      * @return the SSLParameters in effect for this SSLSocket.
607      * @since 1.6
608      */
609     public SSLParameters getSSLParameters() {
610         SSLParameters params = new SSLParameters();
611         params.setCipherSuites(getEnabledCipherSuites());
612         params.setProtocols(getEnabledProtocols());
613         if (getNeedClientAuth()) {
614             params.setNeedClientAuth(true);
615         } else if (getWantClientAuth()) {
616             params.setWantClientAuth(true);
617         }
618         return params;
619     }
620 
621     /**
622      * Applies SSLParameters to this socket.
623      *
624      * <p>This means:
625      * <ul>
626      * <li>If {@code params.getCipherSuites()} is non-null,
627      *   {@code setEnabledCipherSuites()} is called with that value.</li>
628      * <li>If {@code params.getProtocols()} is non-null,
629      *   {@code setEnabledProtocols()} is called with that value.</li>
630      * <li>If {@code params.getNeedClientAuth()} or
631      *   {@code params.getWantClientAuth()} return {@code true},
632      *   {@code setNeedClientAuth(true)} and
633      *   {@code setWantClientAuth(true)} are called, respectively;
634      *   otherwise {@code setWantClientAuth(false)} is called.</li>
635      * <li>If {@code params.getServerNames()} is non-null, the socket will
636      *   configure its server names with that value.</li>
637      * <li>If {@code params.getSNIMatchers()} is non-null, the socket will
638      *   configure its SNI matchers with that value.</li>
639      * </ul>
640      *
641      * @param params the parameters
642      * @throws IllegalArgumentException if the setEnabledCipherSuites() or
643      *    the setEnabledProtocols() call fails
644      * @since 1.6
645      */
646     public void setSSLParameters(SSLParameters params) {
647         String[] s;
648         s = params.getCipherSuites();
649         if (s != null) {
650             setEnabledCipherSuites(s);
651         }
652         s = params.getProtocols();
653         if (s != null) {
654             setEnabledProtocols(s);
655         }
656         if (params.getNeedClientAuth()) {
657             setNeedClientAuth(true);
658         } else if (params.getWantClientAuth()) {
659             setWantClientAuth(true);
660         } else {
661             setWantClientAuth(false);
662         }
663     }
664 
665 }