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 sun.security.ssl;
28
29 import java.io.*;
30 import java.net.*;
31 import java.security.GeneralSecurityException;
32 import java.security.AccessController;
33 import java.security.AccessControlContext;
34 import java.security.PrivilegedAction;
35 import java.security.AlgorithmConstraints;
36 import java.util.*;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.locks.ReentrantLock;
39
40 import javax.crypto.BadPaddingException;
41 import javax.net.ssl.*;
42 import sun.misc.ManagedLocalsThread;
43
44 /**
45 * Implementation of an SSL socket. This is a normal connection type
46 * socket, implementing SSL over some lower level socket, such as TCP.
47 * Because it is layered over some lower level socket, it MUST override
48 * all default socket methods.
49 *
142 * v | |
143 * ERROR>------>----->CLOSED<--------<----+-- +
144 * |
145 * v
146 * APP_CLOSED
147 *
148 * ALSO, note that the purpose of handshaking (renegotiation is
149 * included) is to assign a different, and perhaps new, session to
150 * the connection. The SSLv3 spec is a bit confusing on that new
151 * protocol feature.
152 */
153 private static final int cs_START = 0;
154 private static final int cs_HANDSHAKE = 1;
155 private static final int cs_DATA = 2;
156 private static final int cs_RENEGOTIATE = 3;
157 private static final int cs_ERROR = 4;
158 private static final int cs_SENT_CLOSE = 5;
159 private static final int cs_CLOSED = 6;
160 private static final int cs_APP_CLOSED = 7;
161
162
163 /*
164 * Client authentication be off, requested, or required.
165 *
166 * Migrated to SSLEngineImpl:
167 * clauth_none/cl_auth_requested/clauth_required
168 */
169
170 /*
171 * Drives the protocol state machine.
172 */
173 private volatile int connectionState;
174
175 /*
176 * Flag indicating that the engine's handshaker has done the necessary
177 * steps so the engine may process a ChangeCipherSpec message.
178 */
179 private boolean receivedCCS;
180
181 /*
182 * Flag indicating if the next record we receive MUST be a Finished
183 * message. Temporarily set during the handshake to ensure that
184 * a change cipher spec message is followed by a finished message.
185 */
186 private boolean expectingFinished;
187
188 /*
189 * For improved diagnostics, we detail connection closure
190 * If the socket is closed (connectionState >= cs_ERROR),
191 * closeReason != null indicates if the socket was closed
192 * because of an error or because or normal shutdown.
193 */
194 private SSLException closeReason;
195
196 /*
197 * Per-connection private state that doesn't change when the
198 * session is changed.
199 */
200 private byte doClientAuth;
201 private boolean roleIsServer;
202 private boolean enableSessionCreation = true;
203 private String host;
204 private boolean autoClose = true;
205 private AccessControlContext acc;
206
207 // The cipher suites enabled for use on this connection.
208 private CipherSuiteList enabledCipherSuites;
209
210 // The endpoint identification protocol
211 private String identificationProtocol = null;
212
213 // The cryptographic algorithm constraints
214 private AlgorithmConstraints algorithmConstraints = null;
215
216 // The server name indication and matchers
217 List<SNIServerName> serverNames =
218 Collections.<SNIServerName>emptyList();
219 Collection<SNIMatcher> sniMatchers =
220 Collections.<SNIMatcher>emptyList();
267 * temporary reader to read the responses from the other side. As a
268 * side-effect, the writer's reader will have priority over any
269 * other reader. However, the writer's reader is not allowed to
270 * consume any application data. When handshakeLock is finally
271 * released, we either have a cs_DATA connection, or a
272 * cs_CLOSED/cs_ERROR socket.
273 *
274 * The writeLock is held while writing on a socket connection and
275 * also to protect the MAC and cipher for their direction. The
276 * writeLock is package private for Handshaker which holds it while
277 * writing the ChangeCipherSpec message.
278 *
279 * To avoid the problem of a thread trying to change operational
280 * modes on a socket while handshaking is going on, we synchronize
281 * on 'this'. If handshaking has not started yet, we tell the
282 * handshaker to change its mode. If handshaking has started,
283 * we simply store that request until the next pending session
284 * is created, at which time the new handshaker's state is set.
285 *
286 * The readLock is held during readRecord(), which is responsible
287 * for reading an InputRecord, decrypting it, and processing it.
288 * The readLock ensures that these three steps are done atomically
289 * and that once started, no other thread can block on InputRecord.read.
290 * This is necessary so that processing of close_notify alerts
291 * from the peer are handled properly.
292 */
293 final private Object handshakeLock = new Object();
294 final ReentrantLock writeLock = new ReentrantLock();
295 final private Object readLock = new Object();
296
297 private InputRecord inrec;
298
299 /*
300 * Crypto state that's reinitialized when the session changes.
301 */
302 private Authenticator readAuthenticator, writeAuthenticator;
303 private CipherBox readCipher, writeCipher;
304 // NOTE: compression state would be saved here
305
306 /*
307 * security parameters for secure renegotiation.
308 */
309 private boolean secureRenegotiation;
310 private byte[] clientVerifyData;
311 private byte[] serverVerifyData;
312
313 /*
314 * The authentication context holds all information used to establish
315 * who this end of the connection is (certificate chains, private keys,
316 * etc) and who is trusted (e.g. as CAs or websites).
317 */
318 private SSLContextImpl sslContext;
319
320
321 /*
322 * This connection is one of (potentially) many associated with
323 * any given session. The output of the handshake protocol is a
324 * new session ... although all the protocol description talks
325 * about changing the cipher spec (and it does change), in fact
326 * that's incidental since it's done by changing everything that
351 * and usually arrange integrity and privacy protection for those
352 * records. The guts of the SSL protocol are wrapped up in these
353 * streams, and in the handshaking that establishes the details of
354 * that integrity and privacy protection.
355 */
356 private AppInputStream input;
357 private AppOutputStream output;
358
359 /*
360 * The protocol versions enabled for use on this connection.
361 *
362 * Note: we support a pseudo protocol called SSLv2Hello which when
363 * set will result in an SSL v2 Hello being sent with SSL (version 3.0)
364 * or TLS (version 3.1, 3.2, etc.) version info.
365 */
366 private ProtocolList enabledProtocols;
367
368 /*
369 * The SSL version associated with this connection.
370 */
371 private ProtocolVersion protocolVersion = ProtocolVersion.DEFAULT;
372
373 /* Class and subclass dynamic debugging support */
374 private static final Debug debug = Debug.getInstance("ssl");
375
376 /*
377 * Is it the first application record to write?
378 */
379 private boolean isFirstAppOutputRecord = true;
380
381 /*
382 * If AppOutputStream needs to delay writes of small packets, we
383 * will use this to store the data until we actually do the write.
384 */
385 private ByteArrayOutputStream heldRecordBuffer = null;
386
387 /*
388 * Whether local cipher suites preference in server side should be
389 * honored during handshaking?
390 */
391 private boolean preferLocalCipherSuites = false;
392
393 //
394 // CONSTRUCTORS AND INITIALIZATION CODE
395 //
396
397 /**
398 * Constructs an SSL connection to a named host at a specified port,
399 * using the authentication context provided. This endpoint acts as
400 * the client, and may rejoin an existing SSL session if appropriate.
401 *
402 * @param context authentication context to use
403 * @param host name of the host with which to connect
404 * @param port number of the server's port
405 */
406 SSLSocketImpl(SSLContextImpl context, String host, int port)
407 throws IOException, UnknownHostException {
408 super();
409 this.host = host;
410 this.serverNames =
411 Utilities.addToSNIServerNameList(this.serverNames, this.host);
412 init(context, false);
474 * @param localAddr the local address the socket is bound to
475 * @param localPort the local port the socket is bound to
476 */
477 SSLSocketImpl(SSLContextImpl context, InetAddress host, int port,
478 InetAddress localAddr, int localPort)
479 throws IOException {
480 super();
481 init(context, false);
482 bind(new InetSocketAddress(localAddr, localPort));
483 SocketAddress socketAddress = new InetSocketAddress(host, port);
484 connect(socketAddress, 0);
485 }
486
487 /*
488 * Package-private constructor used ONLY by SSLServerSocket. The
489 * java.net package accepts the TCP connection after this call is
490 * made. This just initializes handshake state to use "server mode",
491 * giving control over the use of SSL client authentication.
492 */
493 SSLSocketImpl(SSLContextImpl context, boolean serverMode,
494 CipherSuiteList suites, byte clientAuth,
495 boolean sessionCreation, ProtocolList protocols,
496 String identificationProtocol,
497 AlgorithmConstraints algorithmConstraints,
498 Collection<SNIMatcher> sniMatchers,
499 boolean preferLocalCipherSuites) throws IOException {
500
501 super();
502 doClientAuth = clientAuth;
503 enableSessionCreation = sessionCreation;
504 this.identificationProtocol = identificationProtocol;
505 this.algorithmConstraints = algorithmConstraints;
506 this.sniMatchers = sniMatchers;
507 this.preferLocalCipherSuites = preferLocalCipherSuites;
508 init(context, serverMode);
509
510 /*
511 * Override what was picked out for us.
512 */
513 enabledCipherSuites = suites;
514 enabledProtocols = protocols;
577
578 init(context, true);
579 this.autoClose = autoClose;
580 doneConnect();
581 }
582
583 /**
584 * Initializes the client socket.
585 */
586 private void init(SSLContextImpl context, boolean isServer) {
587 sslContext = context;
588 sess = SSLSessionImpl.nullSession;
589 handshakeSession = null;
590
591 /*
592 * role is as specified, state is START until after
593 * the low level connection's established.
594 */
595 roleIsServer = isServer;
596 connectionState = cs_START;
597 receivedCCS = false;
598
599 /*
600 * default read and write side cipher and MAC support
601 *
602 * Note: compression support would go here too
603 */
604 readCipher = CipherBox.NULL;
605 readAuthenticator = MAC.NULL;
606 writeCipher = CipherBox.NULL;
607 writeAuthenticator = MAC.NULL;
608
609 // initial security parameters for secure renegotiation
610 secureRenegotiation = false;
611 clientVerifyData = new byte[0];
612 serverVerifyData = new byte[0];
613
614 enabledCipherSuites =
615 sslContext.getDefaultCipherSuiteList(roleIsServer);
616 enabledProtocols =
617 sslContext.getDefaultProtocolList(roleIsServer);
618
619 inrec = null;
620
621 // save the acc
622 acc = AccessController.getContext();
623
624 input = new AppInputStream(this);
625 output = new AppOutputStream(this);
626 }
627
628 /**
629 * Connects this socket to the server with a specified timeout
630 * value.
631 *
632 * This method is either called on an unconnected SSLSocketImpl by the
633 * application, or it is called in the constructor of a regular
634 * SSLSocketImpl. If we are layering on top on another socket, then
635 * this method should not be called, because we assume that the
636 * underlying socket is already connected by the time it is passed to
637 * us.
638 *
639 * @param endpoint the <code>SocketAddress</code>
640 * @param timeout the timeout value to be used, 0 is no timeout
655 }
656
657 super.connect(endpoint, timeout);
658 doneConnect();
659 }
660
661 /**
662 * Initialize the handshaker and socket streams.
663 *
664 * Called by connect, the layered constructor, and SSLServerSocket.
665 */
666 void doneConnect() throws IOException {
667 /*
668 * Save the input and output streams. May be done only after
669 * java.net actually connects using the socket "self", else
670 * we get some pretty bizarre failure modes.
671 */
672 sockInput = super.getInputStream();
673 sockOutput = super.getOutputStream();
674
675 /*
676 * Move to handshaking state, with pending session initialized
677 * to defaults and the appropriate kind of handshaker set up.
678 */
679 initHandshaker();
680 }
681
682 synchronized private int getConnectionState() {
683 return connectionState;
684 }
685
686 synchronized private void setConnectionState(int state) {
687 connectionState = state;
688 }
689
690 AccessControlContext getAcc() {
691 return acc;
692 }
693
694 //
695 // READING AND WRITING RECORDS
696 //
697
698 /*
699 * AppOutputStream calls may need to buffer multiple outbound
700 * application packets.
701 *
702 * All other writeRecord() calls will not buffer, so do not hold
703 * these records.
704 */
705 void writeRecord(OutputRecord r) throws IOException {
706 writeRecord(r, false);
707 }
708
709 /*
710 * Record Output. Application data can't be sent until the first
711 * handshake establishes a session.
712 *
713 * NOTE: we let empty records be written as a hook to force some
714 * TCP-level activity, notably handshaking, to occur.
715 */
716 void writeRecord(OutputRecord r, boolean holdRecord) throws IOException {
717 /*
718 * The loop is in case of HANDSHAKE --> ERROR transitions, etc
719 */
720 loop:
721 while (r.contentType() == Record.ct_application_data) {
722 /*
723 * Not all states support passing application data. We
724 * synchronize access to the connection state, so that
725 * synchronous handshakes can complete cleanly.
726 */
727 switch (getConnectionState()) {
728
729 /*
730 * We've deferred the initial handshaking till just now,
731 * when presumably a thread's decided it's OK to block for
732 * longish periods of time for I/O purposes (as well as
733 * configured the cipher suites it wants to use).
734 */
735 case cs_HANDSHAKE:
736 performInitialHandshake();
737 break;
738
739 case cs_DATA:
740 case cs_RENEGOTIATE:
741 break loop;
742
743 case cs_ERROR:
744 fatal(Alerts.alert_close_notify,
745 "error while writing to socket");
746 break; // dummy
747
748 case cs_SENT_CLOSE:
749 case cs_CLOSED:
750 case cs_APP_CLOSED:
751 // we should never get here (check in AppOutputStream)
752 // this is just a fallback
753 if (closeReason != null) {
754 throw closeReason;
755 } else {
756 throw new SocketException("Socket closed");
757 }
758
759 /*
760 * Else something's goofy in this state machine's use.
761 */
762 default:
763 throw new SSLProtocolException("State error, send app data");
764 }
765 }
766
767 //
768 // Don't bother to really write empty records. We went this
769 // far to drive the handshake machinery, for correctness; not
770 // writing empty records improves performance by cutting CPU
771 // time and network resource usage. However, some protocol
772 // implementations are fragile and don't like to see empty
773 // records, so this also increases robustness.
774 //
775 if (!r.isEmpty()) {
776
777 // If the record is a close notify alert, we need to honor
778 // socket option SO_LINGER. Note that we will try to send
779 // the close notify even if the SO_LINGER set to zero.
780 if (r.isAlert(Alerts.alert_close_notify) && getSoLinger() >= 0) {
781
782 // keep and clear the current thread interruption status.
783 boolean interrupted = Thread.interrupted();
784 try {
785 if (writeLock.tryLock(getSoLinger(), TimeUnit.SECONDS)) {
786 try {
787 writeRecordInternal(r, holdRecord);
788 } finally {
789 writeLock.unlock();
790 }
791 } else {
792 SSLException ssle = new SSLException(
793 "SO_LINGER timeout," +
794 " close_notify message cannot be sent.");
795
796
797 // For layered, non-autoclose sockets, we are not
798 // able to bring them into a usable state, so we
799 // treat it as fatal error.
800 if (isLayered() && !autoClose) {
801 // Note that the alert description is
802 // specified as -1, so no message will be send
803 // to peer anymore.
804 fatal((byte)(-1), ssle);
805 } else if ((debug != null) && Debug.isOn("ssl")) {
806 System.out.println(
807 Thread.currentThread().getName() +
816 // RFC4346 no longer requires that a session not be
817 // resumed if failure to properly close a connection.
818 //
819 // We choose to make the session unresumable if
820 // failed to send the close_notify message.
821 //
822 sess.invalidate();
823 }
824 } catch (InterruptedException ie) {
825 // keep interrupted status
826 interrupted = true;
827 }
828
829 // restore the interrupted status
830 if (interrupted) {
831 Thread.currentThread().interrupt();
832 }
833 } else {
834 writeLock.lock();
835 try {
836 writeRecordInternal(r, holdRecord);
837 } finally {
838 writeLock.unlock();
839 }
840 }
841 }
842 }
843
844 private void writeRecordInternal(OutputRecord r,
845 boolean holdRecord) throws IOException {
846
847 // r.compress(c);
848 r.encrypt(writeAuthenticator, writeCipher);
849
850 if (holdRecord) {
851 // If we were requested to delay the record due to possibility
852 // of Nagle's being active when finally got to writing, and
853 // it's actually not, we don't really need to delay it.
854 if (getTcpNoDelay()) {
855 holdRecord = false;
856 } else {
857 // We need to hold the record, so let's provide
858 // a per-socket place to do it.
859 if (heldRecordBuffer == null) {
860 // Likely only need 37 bytes.
861 heldRecordBuffer = new ByteArrayOutputStream(40);
862 }
863 }
864 }
865 r.write(sockOutput, holdRecord, heldRecordBuffer);
866
867 /*
868 * Check the sequence number state
869 *
870 * Note that in order to maintain the connection I/O
871 * properly, we check the sequence number after the last
872 * record writing process. As we request renegotiation
873 * or close the connection for wrapped sequence number
874 * when there is enough sequence number space left to
875 * handle a few more records, so the sequence number
876 * of the last record cannot be wrapped.
877 */
878 if (connectionState < cs_ERROR) {
879 checkSequenceNumber(writeAuthenticator, r.contentType());
880 }
881
882 // turn off the flag of the first application record
883 if (isFirstAppOutputRecord &&
884 r.contentType() == Record.ct_application_data) {
885 isFirstAppOutputRecord = false;
886 }
887 }
888
889 /*
890 * Need to split the payload except the following cases:
891 *
892 * 1. protocol version is TLS 1.1 or later;
893 * 2. bulk cipher does not use CBC mode, including null bulk cipher suites.
894 * 3. the payload is the first application record of a freshly
895 * negotiated TLS session.
896 * 4. the CBC protection is disabled;
897 *
898 * More details, please refer to AppOutputStream.write(byte[], int, int).
899 */
900 boolean needToSplitPayload() {
901 writeLock.lock();
902 try {
903 return (protocolVersion.v <= ProtocolVersion.TLS10.v) &&
904 writeCipher.isCBCMode() && !isFirstAppOutputRecord &&
905 Record.enableCBCProtection;
906 } finally {
907 writeLock.unlock();
908 }
909 }
910
911 /*
912 * Read an application data record. Alerts and handshake
913 * messages are handled directly.
914 */
915 void readDataRecord(InputRecord r) throws IOException {
916 if (getConnectionState() == cs_HANDSHAKE) {
917 performInitialHandshake();
918 }
919 readRecord(r, true);
920 }
921
922
923 /*
924 * Clear the pipeline of records from the peer, optionally returning
925 * application data. Caller is responsible for knowing that it's
926 * possible to do this kind of clearing, if they don't want app
927 * data -- e.g. since it's the initial SSL handshake.
928 *
929 * Don't synchronize (this) during a blocking read() since it
930 * protects data which is accessed on the write side as well.
931 */
932 private void readRecord(InputRecord r, boolean needAppData)
933 throws IOException {
934 int state;
935
936 // readLock protects reading and processing of an InputRecord.
937 // It keeps the reading from sockInput and processing of the record
938 // atomic so that no two threads can be blocked on the
939 // read from the same input stream at the same time.
940 // This is required for example when a reader thread is
941 // blocked on the read and another thread is trying to
942 // close the socket. For a non-autoclose, layered socket,
943 // the thread performing the close needs to read the close_notify.
944 //
945 // Use readLock instead of 'this' for locking because
946 // 'this' also protects data accessed during writing.
947 synchronized (readLock) {
948 /*
949 * Read and handle records ... return application data
950 * ONLY if it's needed.
951 */
952
953 while (((state = getConnectionState()) != cs_CLOSED) &&
954 (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
955 /*
956 * Read a record ... maybe emitting an alert if we get a
957 * comprehensible but unsupported "hello" message during
958 * format checking (e.g. V2).
959 */
960 try {
961 r.setAppDataValid(false);
962 r.read(sockInput, sockOutput);
963 } catch (SSLProtocolException e) {
964 try {
965 fatal(Alerts.alert_unexpected_message, e);
966 } catch (IOException x) {
967 // discard this exception
968 }
969 throw e;
970 } catch (EOFException eof) {
971 boolean handshaking = (getConnectionState() <= cs_HANDSHAKE);
972 boolean rethrow = requireCloseNotify || handshaking;
973 if ((debug != null) && Debug.isOn("ssl")) {
974 System.out.println(Thread.currentThread().getName() +
975 ", received EOFException: "
976 + (rethrow ? "error" : "ignored"));
977 }
978 if (rethrow) {
979 SSLException e;
980 if (handshaking) {
981 e = new SSLHandshakeException
982 ("Remote host closed connection during handshake");
983 } else {
984 e = new SSLProtocolException
985 ("Remote host closed connection incorrectly");
986 }
987 e.initCause(eof);
988 throw e;
989 } else {
990 // treat as if we had received a close_notify
991 closeInternal(false);
992 continue;
993 }
994 }
995
996
997 /*
998 * The basic SSLv3 record protection involves (optional)
999 * encryption for privacy, and an integrity check ensuring
1000 * data origin authentication. We do them both here, and
1001 * throw a fatal alert if the integrity check fails.
1002 */
1003 try {
1004 r.decrypt(readAuthenticator, readCipher);
1005 } catch (BadPaddingException e) {
1006 byte alertType = (r.contentType() == Record.ct_handshake)
1007 ? Alerts.alert_handshake_failure
1008 : Alerts.alert_bad_record_mac;
1009 fatal(alertType, e.getMessage(), e);
1010 }
1011
1012 // if (!r.decompress(c))
1013 // fatal(Alerts.alert_decompression_failure,
1014 // "decompression failure");
1015
1016 /*
1017 * Process the record.
1018 */
1019 synchronized (this) {
1020 switch (r.contentType()) {
1021 case Record.ct_handshake:
1022 /*
1023 * Handshake messages always go to a pending session
1024 * handshaker ... if there isn't one, create one. This
1025 * must work asynchronously, for renegotiation.
1026 *
1027 * NOTE that handshaking will either resume a session
1028 * which was in the cache (and which might have other
1029 * connections in it already), or else will start a new
1030 * session (new keys exchanged) with just this connection
1031 * in it.
1032 */
1033 initHandshaker();
1034 if (!handshaker.activated()) {
1035 // prior to handshaking, activate the handshake
1036 if (connectionState == cs_RENEGOTIATE) {
1037 // don't use SSLv2Hello when renegotiating
1038 handshaker.activate(protocolVersion);
1039 } else {
1040 handshaker.activate(null);
1041 }
1042 }
1043
1044 /*
1045 * process the handshake record ... may contain just
1046 * a partial handshake message or multiple messages.
1047 *
1048 * The handshaker state machine will ensure that it's
1049 * a finished message.
1050 */
1051 handshaker.process_record(r, expectingFinished);
1052 expectingFinished = false;
1053
1054 if (handshaker.invalidated) {
1055 handshaker = null;
1056 receivedCCS = false;
1057 // if state is cs_RENEGOTIATE, revert it to cs_DATA
1058 if (connectionState == cs_RENEGOTIATE) {
1059 connectionState = cs_DATA;
1060 }
1061 } else if (handshaker.isDone()) {
1062 // reset the parameters for secure renegotiation.
1063 secureRenegotiation =
1064 handshaker.isSecureRenegotiation();
1065 clientVerifyData = handshaker.getClientVerifyData();
1066 serverVerifyData = handshaker.getServerVerifyData();
1067
1068 sess = handshaker.getSession();
1069 handshakeSession = null;
1070 handshaker = null;
1071 connectionState = cs_DATA;
1072 receivedCCS = false;
1073
1074 //
1075 // Tell folk about handshake completion, but do
1076 // it in a separate thread.
1077 //
1078 if (handshakeListeners != null) {
1079 HandshakeCompletedEvent event =
1080 new HandshakeCompletedEvent(this, sess);
1081
1082 Thread t = new ManagedLocalsThread(
1083 new NotifyHandshake(
1084 handshakeListeners.entrySet(), event),
1085 "HandshakeCompletedNotify-Thread");
1086 t.start();
1087 }
1088 }
1089
1090 if (needAppData || connectionState != cs_DATA) {
1091 continue;
1092 }
1093 break;
1094
1095 case Record.ct_application_data:
1096 // Pass this right back up to the application.
1097 if (connectionState != cs_DATA
1098 && connectionState != cs_RENEGOTIATE
1099 && connectionState != cs_SENT_CLOSE) {
1100 throw new SSLProtocolException(
1101 "Data received in non-data state: " +
1102 connectionState);
1103 }
1104 if (expectingFinished) {
1105 throw new SSLProtocolException
1106 ("Expecting finished message, received data");
1107 }
1108 if (!needAppData) {
1109 throw new SSLException("Discarding app data");
1110 }
1111
1112 r.setAppDataValid(true);
1113 break;
1114
1115 case Record.ct_alert:
1116 recvAlert(r);
1117 continue;
1118
1119 case Record.ct_change_cipher_spec:
1120 if ((connectionState != cs_HANDSHAKE
1121 && connectionState != cs_RENEGOTIATE)
1122 || !handshaker.sessionKeysCalculated()
1123 || receivedCCS) {
1124 // For the CCS message arriving in the wrong state
1125 fatal(Alerts.alert_unexpected_message,
1126 "illegal change cipher spec msg, conn state = "
1127 + connectionState + ", handshake state = "
1128 + handshaker.state);
1129 } else if (r.available() != 1 || r.read() != 1) {
1130 // For structural/content issues with the CCS
1131 fatal(Alerts.alert_unexpected_message,
1132 "Malformed change cipher spec msg");
1133 }
1134
1135 // Once we've received CCS, update the flag.
1136 // If the remote endpoint sends it again in this handshake
1137 // we won't process it.
1138 receivedCCS = true;
1139
1140 //
1141 // The first message after a change_cipher_spec
1142 // record MUST be a "Finished" handshake record,
1143 // else it's a protocol violation. We force this
1144 // to be checked by a minor tweak to the state
1145 // machine.
1146 //
1147 changeReadCiphers();
1148 // next message MUST be a finished message
1149 expectingFinished = true;
1150 continue;
1151
1152 default:
1153 //
1154 // TLS requires that unrecognized records be ignored.
1155 //
1156 if (debug != null && Debug.isOn("ssl")) {
1157 System.out.println(Thread.currentThread().getName() +
1158 ", Received record type: "
1159 + r.contentType());
1160 }
1161 continue;
1162 } // switch
1163
1164 /*
1165 * Check the sequence number state
1166 *
1167 * Note that in order to maintain the connection I/O
1168 * properly, we check the sequence number after the last
1169 * record reading process. As we request renegotiation
1170 * or close the connection for wrapped sequence number
1171 * when there is enough sequence number space left to
1172 * handle a few more records, so the sequence number
1173 * of the last record cannot be wrapped.
1174 */
1175 if (connectionState < cs_ERROR) {
1176 checkSequenceNumber(readAuthenticator, r.contentType());
1177 }
1178
1179 return;
1180 } // synchronized (this)
1181 }
1182
1183 //
1184 // couldn't read, due to some kind of error
1185 //
1186 r.close();
1187 return;
1188 } // synchronized (readLock)
1189 }
1190
1191 /**
1192 * Check the sequence number state
1193 *
1194 * RFC 4346 states that, "Sequence numbers are of type uint64 and
1195 * may not exceed 2^64-1. Sequence numbers do not wrap. If a TLS
1196 * implementation would need to wrap a sequence number, it must
1197 * renegotiate instead."
1198 */
1199 private void checkSequenceNumber(Authenticator authenticator, byte type)
1200 throws IOException {
1201
1202 /*
1203 * Don't bother to check the sequence number for error or
1204 * closed connections, or NULL MAC.
1205 */
1206 if (connectionState >= cs_ERROR || authenticator == MAC.NULL) {
1207 return;
1208 }
1209
1210 /*
1211 * Conservatively, close the connection immediately when the
1212 * sequence number is close to overflow
1213 */
1214 if (authenticator.seqNumOverflow()) {
1215 /*
1216 * TLS protocols do not define a error alert for sequence
1217 * number overflow. We use handshake_failure error alert
1218 * for handshaking and bad_record_mac for other records.
1219 */
1220 if (debug != null && Debug.isOn("ssl")) {
1221 System.out.println(Thread.currentThread().getName() +
1222 ", sequence number extremely close to overflow " +
1223 "(2^64-1 packets). Closing connection.");
1224
1225 }
1226
1227 fatal(Alerts.alert_handshake_failure, "sequence number overflow");
1228 }
1229
1230 /*
1231 * Ask for renegotiation when need to renew sequence number.
1232 *
1233 * Don't bother to kickstart the renegotiation when the local is
1234 * asking for it.
1235 */
1236 if ((type != Record.ct_handshake) && authenticator.seqNumIsHuge()) {
1237 if (debug != null && Debug.isOn("ssl")) {
1238 System.out.println(Thread.currentThread().getName() +
1239 ", request renegotiation " +
1240 "to avoid sequence number overflow");
1241 }
1242
1243 startHandshake();
1244 }
1245 }
1246
1247 //
1248 // HANDSHAKE RELATED CODE
1249 //
1250
1251 /**
1252 * Return the AppInputStream. For use by Handshaker only.
1253 */
1254 AppInputStream getAppInputStream() {
1255 return input;
1256 }
1257
1258 /**
1259 * Return the AppOutputStream. For use by Handshaker only.
1260 */
1261 AppOutputStream getAppOutputStream() {
1262 return output;
1263 }
1264
1265 /**
1266 * Initialize the handshaker object. This means:
1306 // state is either cs_START or cs_DATA
1307 if (connectionState == cs_START) {
1308 connectionState = cs_HANDSHAKE;
1309 } else { // cs_DATA
1310 connectionState = cs_RENEGOTIATE;
1311 }
1312 if (roleIsServer) {
1313 handshaker = new ServerHandshaker(this, sslContext,
1314 enabledProtocols, doClientAuth,
1315 protocolVersion, connectionState == cs_HANDSHAKE,
1316 secureRenegotiation, clientVerifyData, serverVerifyData);
1317 handshaker.setSNIMatchers(sniMatchers);
1318 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
1319 } else {
1320 handshaker = new ClientHandshaker(this, sslContext,
1321 enabledProtocols,
1322 protocolVersion, connectionState == cs_HANDSHAKE,
1323 secureRenegotiation, clientVerifyData, serverVerifyData);
1324 handshaker.setSNIServerNames(serverNames);
1325 }
1326 handshaker.setEnabledCipherSuites(enabledCipherSuites);
1327 handshaker.setEnableSessionCreation(enableSessionCreation);
1328 }
1329
1330 /**
1331 * Synchronously perform the initial handshake.
1332 *
1333 * If the handshake is already in progress, this method blocks until it
1334 * is completed. If the initial handshake has already been completed,
1335 * it returns immediately.
1336 */
1337 private void performInitialHandshake() throws IOException {
1338 // use handshakeLock and the state check to make sure only
1339 // one thread performs the handshake
1340 synchronized (handshakeLock) {
1341 if (getConnectionState() == cs_HANDSHAKE) {
1342 kickstartHandshake();
1343
1344 /*
1345 * All initial handshaking goes through this
1346 * InputRecord until we have a valid SSL connection.
1347 * Once initial handshaking is finished, AppInputStream's
1348 * InputRecord can handle any future renegotiation.
1349 *
1350 * Keep this local so that it goes out of scope and is
1351 * eventually GC'd.
1352 */
1353 if (inrec == null) {
1354 inrec = new InputRecord();
1355
1356 /*
1357 * Grab the characteristics already assigned to
1358 * AppInputStream's InputRecord. Enable checking for
1359 * SSLv2 hellos on this first handshake.
1360 */
1361 inrec.setHandshakeHash(input.r.getHandshakeHash());
1362 inrec.setHelloVersion(input.r.getHelloVersion());
1363 inrec.enableFormatChecks();
1364 }
1365
1366 readRecord(inrec, false);
1367 inrec = null;
1368 }
1369 }
1370 }
1371
1372 /**
1373 * Starts an SSL handshake on this connection.
1374 */
1375 @Override
1376 public void startHandshake() throws IOException {
1377 // start an ssl handshake that could be resumed from timeout exception
1378 startHandshake(true);
1379 }
1380
1381 /**
1382 * Starts an ssl handshake on this connection.
1383 *
1384 * @param resumable indicates the handshake process is resumable from a
1385 * certain exception. If <code>resumable</code>, the socket will
1386 * be reserved for exceptions like timeout; otherwise, the socket
1387 * will be closed, no further communications could be done.
1388 */
1389 private void startHandshake(boolean resumable) throws IOException {
1390 checkWrite();
1465 // SSLSocketImpl.writeRecord() to send it.
1466 //
1467 if (!handshaker.activated()) {
1468 // prior to handshaking, activate the handshake
1469 if (connectionState == cs_RENEGOTIATE) {
1470 // don't use SSLv2Hello when renegotiating
1471 handshaker.activate(protocolVersion);
1472 } else {
1473 handshaker.activate(null);
1474 }
1475
1476 if (handshaker instanceof ClientHandshaker) {
1477 // send client hello
1478 handshaker.kickstart();
1479 } else {
1480 if (connectionState == cs_HANDSHAKE) {
1481 // initial handshake, no kickstart message to send
1482 } else {
1483 // we want to renegotiate, send hello request
1484 handshaker.kickstart();
1485 // hello request is not included in the handshake
1486 // hashes, reset them
1487 handshaker.handshakeHash.reset();
1488 }
1489 }
1490 }
1491 }
1492
1493 //
1494 // CLOSURE RELATED CALLS
1495 //
1496
1497 /**
1498 * Return whether the socket has been explicitly closed by the application.
1499 */
1500 @Override
1501 public boolean isClosed() {
1502 return connectionState == cs_APP_CLOSED;
1503 }
1504
1505 /**
1506 * Return whether we have reached end-of-file.
1507 *
1530 return true;
1531 }
1532 IOException e = new SSLException
1533 ("Connection has been shutdown: " + closeReason);
1534 e.initCause(closeReason);
1535 throw e;
1536
1537 }
1538 }
1539
1540 /**
1541 * Check if we can write data to this socket. If not, throw an IOException.
1542 */
1543 void checkWrite() throws IOException {
1544 if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
1545 // we are at EOF, write must throw Exception
1546 throw new SocketException("Connection closed by remote host");
1547 }
1548 }
1549
1550 protected void closeSocket() throws IOException {
1551
1552 if ((debug != null) && Debug.isOn("ssl")) {
1553 System.out.println(Thread.currentThread().getName() +
1554 ", called closeSocket()");
1555 }
1556
1557 super.close();
1558 }
1559
1560 private void closeSocket(boolean selfInitiated) throws IOException {
1561 if ((debug != null) && Debug.isOn("ssl")) {
1562 System.out.println(Thread.currentThread().getName() +
1563 ", called closeSocket(" + selfInitiated + ")");
1564 }
1565 if (!isLayered() || autoClose) {
1566 super.close();
1567 } else if (selfInitiated) {
1568 // layered && non-autoclose
1569 // read close_notify alert to clear input stream
1570 waitForClose(false);
1574 /*
1575 * Closing the connection is tricky ... we can't officially close the
1576 * connection until we know the other end is ready to go away too,
1577 * and if ever the connection gets aborted we must forget session
1578 * state (it becomes invalid).
1579 */
1580
1581 /**
1582 * Closes the SSL connection. SSL includes an application level
1583 * shutdown handshake; you should close SSL sockets explicitly
1584 * rather than leaving it for finalization, so that your remote
1585 * peer does not experience a protocol error.
1586 */
1587 @Override
1588 public void close() throws IOException {
1589 if ((debug != null) && Debug.isOn("ssl")) {
1590 System.out.println(Thread.currentThread().getName() +
1591 ", called close()");
1592 }
1593 closeInternal(true); // caller is initiating close
1594 setConnectionState(cs_APP_CLOSED);
1595 }
1596
1597 /**
1598 * Don't synchronize the whole method because waitForClose()
1599 * (which calls readRecord()) might be called.
1600 *
1601 * @param selfInitiated Indicates which party initiated the close.
1602 * If selfInitiated, this side is initiating a close; for layered and
1603 * non-autoclose socket, wait for close_notify response.
1604 * If !selfInitiated, peer sent close_notify; we reciprocate but
1605 * no need to wait for response.
1606 */
1607 private void closeInternal(boolean selfInitiated) throws IOException {
1608 if ((debug != null) && Debug.isOn("ssl")) {
1609 System.out.println(Thread.currentThread().getName() +
1610 ", called closeInternal(" + selfInitiated + ")");
1611 }
1612
1613 int state = getConnectionState();
1697 getConnectionState());
1698 }
1699 return;
1700 }
1701
1702 if (!closeSocketCalled) {
1703 closeSocketCalled = true;
1704 closeSocket(selfInitiated);
1705 }
1706
1707 break;
1708 }
1709 } finally {
1710 synchronized (this) {
1711 // Upon exit from this method, the state is always >= cs_CLOSED
1712 connectionState = (connectionState == cs_APP_CLOSED)
1713 ? cs_APP_CLOSED : cs_CLOSED;
1714 // notify any threads waiting for the closing to finish
1715 this.notifyAll();
1716 }
1717 if (closeSocketCalled) {
1718 // Dispose of ciphers since we've closed socket
1719 disposeCiphers();
1720 }
1721 if (cachedThrowable != null) {
1722 /*
1723 * Rethrow the error to the calling method
1724 * The Throwable caught can only be an Error or RuntimeException
1725 */
1726 if (cachedThrowable instanceof Error)
1727 throw (Error) cachedThrowable;
1728 if (cachedThrowable instanceof RuntimeException)
1729 throw (RuntimeException) cachedThrowable;
1730 }
1731 }
1732 }
1733
1734 /**
1735 * Reads a close_notify or a fatal alert from the input stream.
1736 * Keep reading records until we get a close_notify or until
1737 * the connection is otherwise closed. The close_notify or alert
1738 * might be read by another reader,
1739 * which will then process the close and set the connection state.
1740 */
1741 void waitForClose(boolean rethrow) throws IOException {
1742 if (debug != null && Debug.isOn("ssl")) {
1743 System.out.println(Thread.currentThread().getName() +
1744 ", waiting for close_notify or alert: state "
1745 + getConnectionState());
1746 }
1747
1748 try {
1749 int state;
1750
1751 while (((state = getConnectionState()) != cs_CLOSED) &&
1752 (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1753 // create the InputRecord if it isn't initialized.
1754 if (inrec == null) {
1755 inrec = new InputRecord();
1756 }
1757
1758 // Ask for app data and then throw it away
1759 try {
1760 readRecord(inrec, true);
1761 } catch (SocketTimeoutException e) {
1762 // if time out, ignore the exception and continue
1763 }
1764 }
1765 inrec = null;
1766 } catch (IOException e) {
1767 if (debug != null && Debug.isOn("ssl")) {
1768 System.out.println(Thread.currentThread().getName() +
1769 ", Exception while waiting for close " +e);
1770 }
1771 if (rethrow) {
1772 throw e; // pass exception up
1773 }
1774 }
1775 }
1776
1777 /**
1778 * Called by closeInternal() only. Be sure to consider the
1779 * synchronization locks carefully before calling it elsewhere.
1780 */
1781 private void disposeCiphers() {
1782 // See comment in changeReadCiphers()
1783 synchronized (readLock) {
1784 readCipher.dispose();
1785 }
1786 // See comment in changeReadCiphers()
1787 writeLock.lock();
1788 try {
1789 writeCipher.dispose();
1790 } finally {
1791 writeLock.unlock();
1792 }
1793 }
1794
1795 //
1796 // EXCEPTION AND ALERT HANDLING
1797 //
1798
1799 /**
1800 * Handle an exception. This method is called by top level exception
1801 * handlers (in read(), write()) to make sure we always shutdown the
1802 * connection correctly and do not pass runtime exception to the
1803 * application.
1804 */
1805 void handleException(Exception e) throws IOException {
1806 handleException(e, true);
1807 }
1808
1809 /**
1810 * Handle an exception. This method is called by top level exception
1811 * handlers (in read(), write(), startHandshake()) to make sure we
1812 * always shutdown the connection correctly and do not pass runtime
1813 * exception to the application.
1814 *
1836 if (e instanceof InterruptedIOException && resumable) {
1837 throw (IOException)e;
1838 }
1839
1840 // if we've already shutdown because of an error,
1841 // there is nothing to do except rethrow the exception
1842 if (closeReason != null) {
1843 if (e instanceof IOException) { // includes SSLException
1844 throw (IOException)e;
1845 } else {
1846 // this is odd, not an IOException.
1847 // normally, this should not happen
1848 // if closeReason has been already been set
1849 throw Alerts.getSSLException(Alerts.alert_internal_error, e,
1850 "Unexpected exception");
1851 }
1852 }
1853
1854 // need to perform error shutdown
1855 boolean isSSLException = (e instanceof SSLException);
1856 if ((isSSLException == false) && (e instanceof IOException)) {
1857 // IOException from the socket
1858 // this means the TCP connection is already dead
1859 // we call fatal just to set the error status
1860 try {
1861 fatal(Alerts.alert_unexpected_message, e);
1862 } catch (IOException ee) {
1863 // ignore (IOException wrapped in SSLException)
1864 }
1865 // rethrow original IOException
1866 throw (IOException)e;
1867 }
1868
1869 // must be SSLException or RuntimeException
1870 byte alertType;
1871 if (isSSLException) {
1872 if (e instanceof SSLHandshakeException) {
1873 alertType = Alerts.alert_handshake_failure;
1874 } else {
1875 alertType = Alerts.alert_unexpected_message;
1876 }
1886 void warning(byte description) {
1887 sendAlert(Alerts.alert_warning, description);
1888 }
1889
1890 synchronized void fatal(byte description, String diagnostic)
1891 throws IOException {
1892 fatal(description, diagnostic, null);
1893 }
1894
1895 synchronized void fatal(byte description, Throwable cause)
1896 throws IOException {
1897 fatal(description, null, cause);
1898 }
1899
1900 /*
1901 * Send a fatal alert, and throw an exception so that callers will
1902 * need to stand on their heads to accidentally continue processing.
1903 */
1904 synchronized void fatal(byte description, String diagnostic,
1905 Throwable cause) throws IOException {
1906 if ((input != null) && (input.r != null)) {
1907 input.r.close();
1908 }
1909 sess.invalidate();
1910 if (handshakeSession != null) {
1911 handshakeSession.invalidate();
1912 }
1913
1914 int oldState = connectionState;
1915 if (connectionState < cs_ERROR) {
1916 connectionState = cs_ERROR;
1917 }
1918
1919 /*
1920 * Has there been an error received yet? If not, remember it.
1921 * By RFC 2246, we don't bother waiting for a response.
1922 * Fatal errors require immediate shutdown.
1923 */
1924 if (closeReason == null) {
1925 /*
1926 * Try to clear the kernel buffer to avoid TCP connection resets.
1927 */
1928 if (oldState == cs_HANDSHAKE) {
1929 sockInput.skip(sockInput.available());
1930 }
1931
1932 // If the description equals -1, the alert won't be sent to peer.
1933 if (description != -1) {
1934 sendAlert(Alerts.alert_fatal, description);
1935 }
1936 if (cause instanceof SSLException) { // only true if != null
1937 closeReason = (SSLException)cause;
1938 } else {
1939 closeReason =
1940 Alerts.getSSLException(description, cause, diagnostic);
1941 }
1942 }
1943
1944 /*
1945 * Clean up our side.
1946 */
1947 closeSocket();
1948 // Another thread may have disposed the ciphers during closing
1949 if (connectionState < cs_CLOSED) {
1950 connectionState = (oldState == cs_APP_CLOSED) ? cs_APP_CLOSED
1951 : cs_CLOSED;
1952
1953 // We should lock readLock and writeLock if no deadlock risks.
1954 // See comment in changeReadCiphers()
1955 readCipher.dispose();
1956 writeCipher.dispose();
1957 }
1958
1959 throw closeReason;
1960 }
1961
1962
1963 /*
1964 * Process an incoming alert ... caller must already have synchronized
1965 * access to "this".
1966 */
1967 private void recvAlert(InputRecord r) throws IOException {
1968 byte level = (byte)r.read();
1969 byte description = (byte)r.read();
1970 if (description == -1) { // check for short message
1971 fatal(Alerts.alert_illegal_parameter, "Short alert message");
1972 }
1973
1974 if (debug != null && (Debug.isOn("record") ||
1975 Debug.isOn("handshake"))) {
1976 synchronized (System.out) {
1977 System.out.print(Thread.currentThread().getName());
1978 System.out.print(", RECV " + protocolVersion + " ALERT: ");
1979 if (level == Alerts.alert_fatal) {
1980 System.out.print("fatal, ");
1981 } else if (level == Alerts.alert_warning) {
1982 System.out.print("warning, ");
1983 } else {
1984 System.out.print("<level " + (0x0ff & level) + ">, ");
1985 }
1986 System.out.println(Alerts.alertDescription(description));
1987 }
1988 }
1989
2012 + Alerts.alertDescription(description);
2013 if (closeReason == null) {
2014 closeReason = Alerts.getSSLException(description, reason);
2015 }
2016 fatal(Alerts.alert_unexpected_message, reason);
2017 }
2018 }
2019
2020
2021 /*
2022 * Emit alerts. Caller must have synchronized with "this".
2023 */
2024 private void sendAlert(byte level, byte description) {
2025 // the connectionState cannot be cs_START
2026 if (connectionState >= cs_SENT_CLOSE) {
2027 return;
2028 }
2029
2030 // For initial handshaking, don't send alert message to peer if
2031 // handshaker has not started.
2032 if (connectionState == cs_HANDSHAKE &&
2033 (handshaker == null || !handshaker.started())) {
2034 return;
2035 }
2036
2037 OutputRecord r = new OutputRecord(Record.ct_alert);
2038 r.setVersion(protocolVersion);
2039
2040 boolean useDebug = debug != null && Debug.isOn("ssl");
2041 if (useDebug) {
2042 synchronized (System.out) {
2043 System.out.print(Thread.currentThread().getName());
2044 System.out.print(", SEND " + protocolVersion + " ALERT: ");
2045 if (level == Alerts.alert_fatal) {
2046 System.out.print("fatal, ");
2047 } else if (level == Alerts.alert_warning) {
2048 System.out.print("warning, ");
2049 } else {
2050 System.out.print("<level = " + (0x0ff & level) + ">, ");
2051 }
2052 System.out.println("description = "
2053 + Alerts.alertDescription(description));
2054 }
2055 }
2056
2057 r.write(level);
2058 r.write(description);
2059 try {
2060 writeRecord(r);
2061 } catch (IOException e) {
2062 if (useDebug) {
2063 System.out.println(Thread.currentThread().getName() +
2064 ", Exception sending alert: " + e);
2065 }
2066 }
2067 }
2068
2069 //
2070 // VARIOUS OTHER METHODS
2071 //
2072
2073 /*
2074 * When a connection finishes handshaking by enabling use of a newly
2075 * negotiated session, each end learns about it in two halves (read,
2076 * and write). When both read and write ciphers have changed, and the
2077 * last handshake message has been read, the connection has joined
2078 * (rejoined) the new session.
2079 *
2080 * NOTE: The SSLv3 spec is rather unclear on the concepts here.
2081 * Sessions don't change once they're established (including cipher
2082 * suite and master secret) but connections can join them (and leave
2083 * them). They're created by handshaking, though sometime handshaking
2084 * causes connections to join up with pre-established sessions.
2085 */
2086 private void changeReadCiphers() throws SSLException {
2087 if (connectionState != cs_HANDSHAKE
2088 && connectionState != cs_RENEGOTIATE) {
2089 throw new SSLProtocolException(
2090 "State error, change cipher specs");
2091 }
2092
2093 // ... create decompressor
2094
2095 CipherBox oldCipher = readCipher;
2096
2097 try {
2098 readCipher = handshaker.newReadCipher();
2099 readAuthenticator = handshaker.newReadAuthenticator();
2100 } catch (GeneralSecurityException e) {
2101 // "can't happen"
2102 throw new SSLException("Algorithm missing: ", e);
2103 }
2104
2105 /*
2106 * Dispose of any intermediate state in the underlying cipher.
2107 * For PKCS11 ciphers, this will release any attached sessions,
2108 * and thus make finalization faster.
2109 *
2110 * Since MAC's doFinal() is called for every SSL/TLS packet, it's
2111 * not necessary to do the same with MAC's.
2112 */
2113 oldCipher.dispose();
2114 }
2115
2116 // used by Handshaker
2117 void changeWriteCiphers() throws SSLException {
2118 if (connectionState != cs_HANDSHAKE
2119 && connectionState != cs_RENEGOTIATE) {
2120 throw new SSLProtocolException(
2121 "State error, change cipher specs");
2122 }
2123
2124 // ... create compressor
2125
2126 CipherBox oldCipher = writeCipher;
2127
2128 try {
2129 writeCipher = handshaker.newWriteCipher();
2130 writeAuthenticator = handshaker.newWriteAuthenticator();
2131 } catch (GeneralSecurityException e) {
2132 // "can't happen"
2133 throw new SSLException("Algorithm missing: ", e);
2134 }
2135
2136 // See comment above.
2137 oldCipher.dispose();
2138
2139 // reset the flag of the first application record
2140 isFirstAppOutputRecord = true;
2141 }
2142
2143 /*
2144 * Updates the SSL version associated with this connection.
2145 * Called from Handshaker once it has determined the negotiated version.
2146 */
2147 synchronized void setVersion(ProtocolVersion protocolVersion) {
2148 this.protocolVersion = protocolVersion;
2149 output.r.setVersion(protocolVersion);
2150 }
2151
2152 synchronized String getHost() {
2153 // Note that the host may be null or empty for localhost.
2154 if (host == null || host.length() == 0) {
2155 host = getInetAddress().getHostName();
2156 }
2157 return host;
2158 }
2159
2160 // ONLY used by HttpsClient to setup the URI specified hostname
2161 //
2162 // Please NOTE that this method MUST be called before calling to
2163 // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
2164 // may override SNIHostName in the customized server name indication.
2165 synchronized public void setHost(String host) {
2166 this.host = host;
2167 this.serverNames =
2168 Utilities.addToSNIServerNameList(this.serverNames, this.host);
2169 }
2228 startHandshake(false);
2229 } catch (IOException e) {
2230 // handshake failed. log and return a nullSession
2231 if (debug != null && Debug.isOn("handshake")) {
2232 System.out.println(Thread.currentThread().getName() +
2233 ", IOException in getSession(): " + e);
2234 }
2235 }
2236 }
2237 synchronized (this) {
2238 return sess;
2239 }
2240 }
2241
2242 @Override
2243 synchronized public SSLSession getHandshakeSession() {
2244 return handshakeSession;
2245 }
2246
2247 synchronized void setHandshakeSession(SSLSessionImpl session) {
2248 handshakeSession = session;
2249 }
2250
2251 /**
2252 * Controls whether new connections may cause creation of new SSL
2253 * sessions.
2254 *
2255 * As long as handshaking has not started, we can change
2256 * whether we enable session creations. Otherwise,
2257 * we will need to wait for the next handshake.
2258 */
2259 @Override
2260 synchronized public void setEnableSessionCreation(boolean flag) {
2261 enableSessionCreation = flag;
2262
2263 if ((handshaker != null) && !handshaker.activated()) {
2264 handshaker.setEnableSessionCreation(enableSessionCreation);
2265 }
2266 }
2267
2268 /**
2269 * Returns true if new connections may cause creation of new SSL
2270 * sessions.
2271 */
2272 @Override
2273 synchronized public boolean getEnableSessionCreation() {
2274 return enableSessionCreation;
2275 }
2276
2277
2278 /**
2279 * Sets the flag controlling whether a server mode socket
2280 * *REQUIRES* SSL client authentication.
2281 *
2282 * As long as handshaking has not started, we can change
2283 * whether client authentication is needed. Otherwise,
2284 * we will need to wait for the next handshake.
2285 */
2286 @Override
2287 synchronized public void setNeedClientAuth(boolean flag) {
2288 doClientAuth = (flag ?
2289 SSLEngineImpl.clauth_required : SSLEngineImpl.clauth_none);
2290
2291 if ((handshaker != null) &&
2292 (handshaker instanceof ServerHandshaker) &&
2293 !handshaker.activated()) {
2294 ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2295 }
2296 }
2297
2298 @Override
2299 synchronized public boolean getNeedClientAuth() {
2300 return (doClientAuth == SSLEngineImpl.clauth_required);
2301 }
2302
2303 /**
2304 * Sets the flag controlling whether a server mode socket
2305 * *REQUESTS* SSL client authentication.
2306 *
2307 * As long as handshaking has not started, we can change
2308 * whether client authentication is requested. Otherwise,
2309 * we will need to wait for the next handshake.
2310 */
2311 @Override
2312 synchronized public void setWantClientAuth(boolean flag) {
2313 doClientAuth = (flag ?
2314 SSLEngineImpl.clauth_requested : SSLEngineImpl.clauth_none);
2315
2316 if ((handshaker != null) &&
2317 (handshaker instanceof ServerHandshaker) &&
2318 !handshaker.activated()) {
2319 ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2320 }
2321 }
2322
2323 @Override
2324 synchronized public boolean getWantClientAuth() {
2325 return (doClientAuth == SSLEngineImpl.clauth_requested);
2326 }
2327
2328
2329 /**
2330 * Sets the flag controlling whether the socket is in SSL
2331 * client or server mode. Must be called before any SSL
2332 * traffic has started.
2333 */
2334 @Override
2335 @SuppressWarnings("fallthrough")
2336 synchronized public void setUseClientMode(boolean flag) {
2337 switch (connectionState) {
2338
2339 case cs_START:
2340 /*
2341 * If we need to change the socket mode and the enabled
2342 * protocols haven't specifically been set by the user,
2343 * change them to the corresponding default ones.
2344 */
2345 if (roleIsServer != (!flag) &&
2346 sslContext.isDefaultProtocolList(enabledProtocols)) {
2347 enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2348 }
2349 roleIsServer = !flag;
2350 break;
2351
2352 case cs_HANDSHAKE:
2353 /*
2354 * If we have a handshaker, but haven't started
2355 * SSL traffic, we can throw away our current
2356 * handshaker, and start from scratch. Don't
2357 * need to call doneConnect() again, we already
2358 * have the streams.
2359 */
2360 assert(handshaker != null);
2361 if (!handshaker.activated()) {
2362 /*
2363 * If we need to change the socket mode and the enabled
2364 * protocols haven't specifically been set by the user,
2365 * change them to the corresponding default ones.
2366 */
2367 if (roleIsServer != (!flag) &&
2368 sslContext.isDefaultProtocolList(enabledProtocols)) {
2369 enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2370 }
2371 roleIsServer = !flag;
2372 connectionState = cs_START;
2373 initHandshaker();
2374 break;
2375 }
2376
2377 // If handshake has started, that's an error. Fall through...
2378
2379 default:
2380 if (debug != null && Debug.isOn("ssl")) {
2381 System.out.println(Thread.currentThread().getName() +
2382 ", setUseClientMode() invoked in state = " +
2383 connectionState);
2384 }
2385 throw new IllegalArgumentException(
2386 "Cannot change mode after SSL traffic has started");
2387 }
2388 }
2389
2390 @Override
2518 throw new IllegalArgumentException("listener not registered");
2519 }
2520 if (handshakeListeners.isEmpty()) {
2521 handshakeListeners = null;
2522 }
2523 }
2524
2525 /**
2526 * Returns the SSLParameters in effect for this SSLSocket.
2527 */
2528 @Override
2529 synchronized public SSLParameters getSSLParameters() {
2530 SSLParameters params = super.getSSLParameters();
2531
2532 // the super implementation does not handle the following parameters
2533 params.setEndpointIdentificationAlgorithm(identificationProtocol);
2534 params.setAlgorithmConstraints(algorithmConstraints);
2535 params.setSNIMatchers(sniMatchers);
2536 params.setServerNames(serverNames);
2537 params.setUseCipherSuitesOrder(preferLocalCipherSuites);
2538
2539 return params;
2540 }
2541
2542 /**
2543 * Applies SSLParameters to this socket.
2544 */
2545 @Override
2546 synchronized public void setSSLParameters(SSLParameters params) {
2547 super.setSSLParameters(params);
2548
2549 // the super implementation does not handle the following parameters
2550 identificationProtocol = params.getEndpointIdentificationAlgorithm();
2551 algorithmConstraints = params.getAlgorithmConstraints();
2552 preferLocalCipherSuites = params.getUseCipherSuitesOrder();
2553
2554 List<SNIServerName> sniNames = params.getServerNames();
2555 if (sniNames != null) {
2556 serverNames = sniNames;
2557 }
2558
2559 Collection<SNIMatcher> matchers = params.getSNIMatchers();
2560 if (matchers != null) {
2561 sniMatchers = matchers;
2562 }
2563
2564 if ((handshaker != null) && !handshaker.started()) {
2565 handshaker.setIdentificationProtocol(identificationProtocol);
2566 handshaker.setAlgorithmConstraints(algorithmConstraints);
2567 if (roleIsServer) {
2568 handshaker.setSNIMatchers(sniMatchers);
2569 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
2570 } else {
2571 handshaker.setSNIServerNames(serverNames);
2572 }
2573 }
2574 }
2575
2576 //
2577 // We allocate a separate thread to deliver handshake completion
2578 // events. This ensures that the notifications don't block the
2579 // protocol state machine.
2580 //
2581 private static class NotifyHandshake implements Runnable {
2582
2583 private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2584 targets; // who gets notified
2585 private HandshakeCompletedEvent event; // the notification
2586
2594
2595 @Override
2596 public void run() {
2597 // Don't need to synchronize, as it only runs in one thread.
2598 for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
2599 entry : targets) {
2600
2601 final HandshakeCompletedListener l = entry.getKey();
2602 AccessControlContext acc = entry.getValue();
2603 AccessController.doPrivileged(new PrivilegedAction<Void>() {
2604 @Override
2605 public Void run() {
2606 l.handshakeCompleted(event);
2607 return null;
2608 }
2609 }, acc);
2610 }
2611 }
2612 }
2613
2614 /**
2615 * Returns a boolean indicating whether the ChangeCipherSpec message
2616 * has been received for this handshake.
2617 */
2618 boolean receivedChangeCipherSpec() {
2619 return receivedCCS;
2620 }
2621
2622 /**
2623 * Returns a printable representation of this end of the connection.
2624 */
2625 @Override
2626 public String toString() {
2627 StringBuilder retval = new StringBuilder(80);
2628
2629 retval.append(Integer.toHexString(hashCode()));
2630 retval.append("[");
2631 retval.append(sess.getCipherSuite());
2632 retval.append(": ");
2633
2634 retval.append(super.toString());
2635 retval.append("]");
2636
2637 return retval.toString();
2638 }
2639 }
|
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 sun.security.ssl;
28
29 import java.io.*;
30 import java.nio.*;
31 import java.net.*;
32 import java.security.GeneralSecurityException;
33 import java.security.AccessController;
34 import java.security.AccessControlContext;
35 import java.security.PrivilegedAction;
36 import java.security.AlgorithmConstraints;
37 import java.util.*;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.locks.ReentrantLock;
40
41 import javax.crypto.BadPaddingException;
42 import javax.net.ssl.*;
43 import sun.misc.ManagedLocalsThread;
44
45 /**
46 * Implementation of an SSL socket. This is a normal connection type
47 * socket, implementing SSL over some lower level socket, such as TCP.
48 * Because it is layered over some lower level socket, it MUST override
49 * all default socket methods.
50 *
143 * v | |
144 * ERROR>------>----->CLOSED<--------<----+-- +
145 * |
146 * v
147 * APP_CLOSED
148 *
149 * ALSO, note that the purpose of handshaking (renegotiation is
150 * included) is to assign a different, and perhaps new, session to
151 * the connection. The SSLv3 spec is a bit confusing on that new
152 * protocol feature.
153 */
154 private static final int cs_START = 0;
155 private static final int cs_HANDSHAKE = 1;
156 private static final int cs_DATA = 2;
157 private static final int cs_RENEGOTIATE = 3;
158 private static final int cs_ERROR = 4;
159 private static final int cs_SENT_CLOSE = 5;
160 private static final int cs_CLOSED = 6;
161 private static final int cs_APP_CLOSED = 7;
162
163 /*
164 * Drives the protocol state machine.
165 */
166 private volatile int connectionState;
167
168 /*
169 * Flag indicating if the next record we receive MUST be a Finished
170 * message. Temporarily set during the handshake to ensure that
171 * a change cipher spec message is followed by a finished message.
172 */
173 private boolean expectingFinished;
174
175 /*
176 * For improved diagnostics, we detail connection closure
177 * If the socket is closed (connectionState >= cs_ERROR),
178 * closeReason != null indicates if the socket was closed
179 * because of an error or because or normal shutdown.
180 */
181 private SSLException closeReason;
182
183 /*
184 * Per-connection private state that doesn't change when the
185 * session is changed.
186 */
187 private ClientAuthType doClientAuth =
188 ClientAuthType.CLIENT_AUTH_NONE;
189 private boolean roleIsServer;
190 private boolean enableSessionCreation = true;
191 private String host;
192 private boolean autoClose = true;
193 private AccessControlContext acc;
194
195 // The cipher suites enabled for use on this connection.
196 private CipherSuiteList enabledCipherSuites;
197
198 // The endpoint identification protocol
199 private String identificationProtocol = null;
200
201 // The cryptographic algorithm constraints
202 private AlgorithmConstraints algorithmConstraints = null;
203
204 // The server name indication and matchers
205 List<SNIServerName> serverNames =
206 Collections.<SNIServerName>emptyList();
207 Collection<SNIMatcher> sniMatchers =
208 Collections.<SNIMatcher>emptyList();
255 * temporary reader to read the responses from the other side. As a
256 * side-effect, the writer's reader will have priority over any
257 * other reader. However, the writer's reader is not allowed to
258 * consume any application data. When handshakeLock is finally
259 * released, we either have a cs_DATA connection, or a
260 * cs_CLOSED/cs_ERROR socket.
261 *
262 * The writeLock is held while writing on a socket connection and
263 * also to protect the MAC and cipher for their direction. The
264 * writeLock is package private for Handshaker which holds it while
265 * writing the ChangeCipherSpec message.
266 *
267 * To avoid the problem of a thread trying to change operational
268 * modes on a socket while handshaking is going on, we synchronize
269 * on 'this'. If handshaking has not started yet, we tell the
270 * handshaker to change its mode. If handshaking has started,
271 * we simply store that request until the next pending session
272 * is created, at which time the new handshaker's state is set.
273 *
274 * The readLock is held during readRecord(), which is responsible
275 * for reading an SSLInputRecord, decrypting it, and processing it.
276 * The readLock ensures that these three steps are done atomically
277 * and that once started, no other thread can block on SSLInputRecord.read.
278 * This is necessary so that processing of close_notify alerts
279 * from the peer are handled properly.
280 */
281 final private Object handshakeLock = new Object();
282 final ReentrantLock writeLock = new ReentrantLock();
283 final private Object readLock = new Object();
284
285 InputRecord inputRecord;
286 OutputRecord outputRecord;
287
288 /*
289 * security parameters for secure renegotiation.
290 */
291 private boolean secureRenegotiation;
292 private byte[] clientVerifyData;
293 private byte[] serverVerifyData;
294
295 /*
296 * The authentication context holds all information used to establish
297 * who this end of the connection is (certificate chains, private keys,
298 * etc) and who is trusted (e.g. as CAs or websites).
299 */
300 private SSLContextImpl sslContext;
301
302
303 /*
304 * This connection is one of (potentially) many associated with
305 * any given session. The output of the handshake protocol is a
306 * new session ... although all the protocol description talks
307 * about changing the cipher spec (and it does change), in fact
308 * that's incidental since it's done by changing everything that
333 * and usually arrange integrity and privacy protection for those
334 * records. The guts of the SSL protocol are wrapped up in these
335 * streams, and in the handshaking that establishes the details of
336 * that integrity and privacy protection.
337 */
338 private AppInputStream input;
339 private AppOutputStream output;
340
341 /*
342 * The protocol versions enabled for use on this connection.
343 *
344 * Note: we support a pseudo protocol called SSLv2Hello which when
345 * set will result in an SSL v2 Hello being sent with SSL (version 3.0)
346 * or TLS (version 3.1, 3.2, etc.) version info.
347 */
348 private ProtocolList enabledProtocols;
349
350 /*
351 * The SSL version associated with this connection.
352 */
353 private ProtocolVersion protocolVersion = ProtocolVersion.DEFAULT_TLS;
354
355 /* Class and subclass dynamic debugging support */
356 private static final Debug debug = Debug.getInstance("ssl");
357
358 /*
359 * Is it the first application record to write?
360 */
361 private boolean isFirstAppOutputRecord = true;
362
363 /*
364 * If AppOutputStream needs to delay writes of small packets, we
365 * will use this to store the data until we actually do the write.
366 */
367 private ByteArrayOutputStream heldRecordBuffer = null;
368
369 /*
370 * Whether local cipher suites preference in server side should be
371 * honored during handshaking?
372 */
373 private boolean preferLocalCipherSuites = false;
374
375 /*
376 * The maximum expected network packet size for SSL/TLS/DTLS records.
377 */
378 private int maximumPacketSize = 0;
379
380 //
381 // CONSTRUCTORS AND INITIALIZATION CODE
382 //
383
384 /**
385 * Constructs an SSL connection to a named host at a specified port,
386 * using the authentication context provided. This endpoint acts as
387 * the client, and may rejoin an existing SSL session if appropriate.
388 *
389 * @param context authentication context to use
390 * @param host name of the host with which to connect
391 * @param port number of the server's port
392 */
393 SSLSocketImpl(SSLContextImpl context, String host, int port)
394 throws IOException, UnknownHostException {
395 super();
396 this.host = host;
397 this.serverNames =
398 Utilities.addToSNIServerNameList(this.serverNames, this.host);
399 init(context, false);
461 * @param localAddr the local address the socket is bound to
462 * @param localPort the local port the socket is bound to
463 */
464 SSLSocketImpl(SSLContextImpl context, InetAddress host, int port,
465 InetAddress localAddr, int localPort)
466 throws IOException {
467 super();
468 init(context, false);
469 bind(new InetSocketAddress(localAddr, localPort));
470 SocketAddress socketAddress = new InetSocketAddress(host, port);
471 connect(socketAddress, 0);
472 }
473
474 /*
475 * Package-private constructor used ONLY by SSLServerSocket. The
476 * java.net package accepts the TCP connection after this call is
477 * made. This just initializes handshake state to use "server mode",
478 * giving control over the use of SSL client authentication.
479 */
480 SSLSocketImpl(SSLContextImpl context, boolean serverMode,
481 CipherSuiteList suites, ClientAuthType clientAuth,
482 boolean sessionCreation, ProtocolList protocols,
483 String identificationProtocol,
484 AlgorithmConstraints algorithmConstraints,
485 Collection<SNIMatcher> sniMatchers,
486 boolean preferLocalCipherSuites) throws IOException {
487
488 super();
489 doClientAuth = clientAuth;
490 enableSessionCreation = sessionCreation;
491 this.identificationProtocol = identificationProtocol;
492 this.algorithmConstraints = algorithmConstraints;
493 this.sniMatchers = sniMatchers;
494 this.preferLocalCipherSuites = preferLocalCipherSuites;
495 init(context, serverMode);
496
497 /*
498 * Override what was picked out for us.
499 */
500 enabledCipherSuites = suites;
501 enabledProtocols = protocols;
564
565 init(context, true);
566 this.autoClose = autoClose;
567 doneConnect();
568 }
569
570 /**
571 * Initializes the client socket.
572 */
573 private void init(SSLContextImpl context, boolean isServer) {
574 sslContext = context;
575 sess = SSLSessionImpl.nullSession;
576 handshakeSession = null;
577
578 /*
579 * role is as specified, state is START until after
580 * the low level connection's established.
581 */
582 roleIsServer = isServer;
583 connectionState = cs_START;
584
585 // initial security parameters for secure renegotiation
586 secureRenegotiation = false;
587 clientVerifyData = new byte[0];
588 serverVerifyData = new byte[0];
589
590 enabledCipherSuites =
591 sslContext.getDefaultCipherSuiteList(roleIsServer);
592 enabledProtocols =
593 sslContext.getDefaultProtocolList(roleIsServer);
594
595 inputRecord = new SSLSocketInputRecord();;
596 outputRecord = new SSLSocketOutputRecord();
597
598 maximumPacketSize = outputRecord.getMaxPacketSize();
599
600 // save the acc
601 acc = AccessController.getContext();
602
603 input = new AppInputStream(this);
604 output = new AppOutputStream(this);
605 }
606
607 /**
608 * Connects this socket to the server with a specified timeout
609 * value.
610 *
611 * This method is either called on an unconnected SSLSocketImpl by the
612 * application, or it is called in the constructor of a regular
613 * SSLSocketImpl. If we are layering on top on another socket, then
614 * this method should not be called, because we assume that the
615 * underlying socket is already connected by the time it is passed to
616 * us.
617 *
618 * @param endpoint the <code>SocketAddress</code>
619 * @param timeout the timeout value to be used, 0 is no timeout
634 }
635
636 super.connect(endpoint, timeout);
637 doneConnect();
638 }
639
640 /**
641 * Initialize the handshaker and socket streams.
642 *
643 * Called by connect, the layered constructor, and SSLServerSocket.
644 */
645 void doneConnect() throws IOException {
646 /*
647 * Save the input and output streams. May be done only after
648 * java.net actually connects using the socket "self", else
649 * we get some pretty bizarre failure modes.
650 */
651 sockInput = super.getInputStream();
652 sockOutput = super.getOutputStream();
653
654 inputRecord.setDeliverStream(sockOutput);
655 outputRecord.setDeliverStream(sockOutput);
656
657 /*
658 * Move to handshaking state, with pending session initialized
659 * to defaults and the appropriate kind of handshaker set up.
660 */
661 initHandshaker();
662 }
663
664 synchronized private int getConnectionState() {
665 return connectionState;
666 }
667
668 synchronized private void setConnectionState(int state) {
669 connectionState = state;
670 }
671
672 AccessControlContext getAcc() {
673 return acc;
674 }
675
676 //
677 // READING AND WRITING RECORDS
678 //
679
680 /*
681 * Application data record output.
682 *
683 * Application data can't be sent until the first handshake establishes
684 * a session.
685 */
686 void writeRecord(byte[] source, int offset, int length) throws IOException {
687 /*
688 * The loop is in case of HANDSHAKE --> ERROR transitions, etc
689 */
690 // Don't bother to check the emptiness of source applicatoin data
691 // before the security connection established.
692 for (boolean readyForApp = false; !readyForApp;) {
693 /*
694 * Not all states support passing application data. We
695 * synchronize access to the connection state, so that
696 * synchronous handshakes can complete cleanly.
697 */
698 switch (getConnectionState()) {
699
700 /*
701 * We've deferred the initial handshaking till just now,
702 * when presumably a thread's decided it's OK to block for
703 * longish periods of time for I/O purposes (as well as
704 * configured the cipher suites it wants to use).
705 */
706 case cs_HANDSHAKE:
707 performInitialHandshake();
708 break;
709
710 case cs_DATA:
711 case cs_RENEGOTIATE:
712 readyForApp = true;
713 break;
714
715 case cs_ERROR:
716 fatal(Alerts.alert_close_notify,
717 "error while writing to socket");
718 break; // dummy
719
720 case cs_SENT_CLOSE:
721 case cs_CLOSED:
722 case cs_APP_CLOSED:
723 // we should never get here (check in AppOutputStream)
724 // this is just a fallback
725 if (closeReason != null) {
726 throw closeReason;
727 } else {
728 throw new SocketException("Socket closed");
729 }
730
731 /*
732 * Else something's goofy in this state machine's use.
733 */
734 default:
735 throw new SSLProtocolException(
736 "State error, send app data");
737 }
738 }
739
740 //
741 // Don't bother to really write empty records. We went this
742 // far to drive the handshake machinery, for correctness; not
743 // writing empty records improves performance by cutting CPU
744 // time and network resource usage. However, some protocol
745 // implementations are fragile and don't like to see empty
746 // records, so this also increases robustness.
747 //
748 if (length > 0) {
749 writeLock.lock();
750 try {
751 outputRecord.deliver(source, offset, length);
752 } catch (SSLHandshakeException she) {
753 // may be record sequence number overflow
754 fatal(Alerts.alert_handshake_failure, she);
755 } catch (IOException e) {
756 fatal(Alerts.alert_unexpected_message, e);
757 } finally {
758 writeLock.unlock();
759 }
760 }
761
762 /*
763 * Check the sequence number state
764 *
765 * Note that in order to maintain the connection I/O
766 * properly, we check the sequence number after the last
767 * record writing process. As we request renegotiation
768 * or close the connection for wrapped sequence number
769 * when there is enough sequence number space left to
770 * handle a few more records, so the sequence number
771 * of the last record cannot be wrapped.
772 *
773 * Don't bother to kickstart the renegotiation when the
774 * local is asking for it.
775 */
776 if ((connectionState == cs_DATA) && outputRecord.seqNumIsHuge()) {
777 /*
778 * Ask for renegotiation when need to renew sequence number.
779 *
780 * Don't bother to kickstart the renegotiation when the local is
781 * asking for it.
782 */
783 if (debug != null && Debug.isOn("ssl")) {
784 System.out.println(Thread.currentThread().getName() +
785 ", request renegotiation " +
786 "to avoid sequence number overflow");
787 }
788
789 startHandshake();
790 }
791 }
792
793 /*
794 * Alert record output.
795 */
796 void writeAlert(byte level, byte description) throws IOException {
797
798 // If the record is a close notify alert, we need to honor
799 // socket option SO_LINGER. Note that we will try to send
800 // the close notify even if the SO_LINGER set to zero.
801 if ((description == Alerts.alert_close_notify) && getSoLinger() >= 0) {
802
803 // keep and clear the current thread interruption status.
804 boolean interrupted = Thread.interrupted();
805 try {
806 if (writeLock.tryLock(getSoLinger(), TimeUnit.SECONDS)) {
807 try {
808 outputRecord.encodeAlert(level, description);
809 } finally {
810 writeLock.unlock();
811 }
812 } else {
813 SSLException ssle = new SSLException(
814 "SO_LINGER timeout," +
815 " close_notify message cannot be sent.");
816
817
818 // For layered, non-autoclose sockets, we are not
819 // able to bring them into a usable state, so we
820 // treat it as fatal error.
821 if (isLayered() && !autoClose) {
822 // Note that the alert description is
823 // specified as -1, so no message will be send
824 // to peer anymore.
825 fatal((byte)(-1), ssle);
826 } else if ((debug != null) && Debug.isOn("ssl")) {
827 System.out.println(
828 Thread.currentThread().getName() +
837 // RFC4346 no longer requires that a session not be
838 // resumed if failure to properly close a connection.
839 //
840 // We choose to make the session unresumable if
841 // failed to send the close_notify message.
842 //
843 sess.invalidate();
844 }
845 } catch (InterruptedException ie) {
846 // keep interrupted status
847 interrupted = true;
848 }
849
850 // restore the interrupted status
851 if (interrupted) {
852 Thread.currentThread().interrupt();
853 }
854 } else {
855 writeLock.lock();
856 try {
857 outputRecord.encodeAlert(level, description);
858 } finally {
859 writeLock.unlock();
860 }
861 }
862
863 // Don't bother to check sequence number overlap here. If sequence
864 // number is huge, there should be enough sequence number space to
865 // request renegotiation in next application data read and write.
866 }
867
868
869 int bytesInCompletePacket() throws IOException {
870 if (getConnectionState() == cs_HANDSHAKE) {
871 performInitialHandshake();
872 }
873
874 synchronized (readLock) {
875 int state = getConnectionState();
876 if ((state == cs_CLOSED) ||
877 (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
878 return -1;
879 }
880
881 try {
882 return inputRecord.bytesInCompletePacket(sockInput);
883 } catch (EOFException eofe) {
884 boolean handshaking = (connectionState <= cs_HANDSHAKE);
885 boolean rethrow = requireCloseNotify || handshaking;
886 if ((debug != null) && Debug.isOn("ssl")) {
887 System.out.println(Thread.currentThread().getName() +
888 ", received EOFException: "
889 + (rethrow ? "error" : "ignored"));
890 }
891
892 if (!rethrow) {
893 // treat as if we had received a close_notify
894 closeInternal(false);
895 } else {
896 SSLException e;
897 if (handshaking) {
898 e = new SSLHandshakeException(
899 "Remote host terminated the handshake");
900 } else {
901 e = new SSLProtocolException(
902 "Remote host terminated the handshake");
903 }
904 e.initCause(eofe);
905 throw e;
906 }
907 }
908
909 return -1;
910 }
911 }
912
913 // the caller have synchronized readLock
914 void expectingFinishFlight() {
915 inputRecord.expectingFinishFlight();
916 }
917
918 /*
919 * Read an application data record.
920 *
921 * Alerts and handshake messages are internally handled directly.
922 */
923 int readRecord(ByteBuffer buffer) throws IOException {
924 if (getConnectionState() == cs_HANDSHAKE) {
925 performInitialHandshake();
926 }
927
928 return readRecord(buffer, true);
929 }
930
931 /*
932 * Read a record, no application data input required.
933 *
934 * Alerts and handshake messages are internally handled directly.
935 */
936 int readRecord(boolean needAppData) throws IOException {
937 return readRecord(null, needAppData);
938 }
939
940 /*
941 * Clear the pipeline of records from the peer, optionally returning
942 * application data. Caller is responsible for knowing that it's
943 * possible to do this kind of clearing, if they don't want app
944 * data -- e.g. since it's the initial SSL handshake.
945 *
946 * Don't synchronize (this) during a blocking read() since it
947 * protects data which is accessed on the write side as well.
948 */
949 private int readRecord(ByteBuffer buffer, boolean needAppData)
950 throws IOException {
951 int state;
952
953 // readLock protects reading and processing of an SSLInputRecord.
954 // It keeps the reading from sockInput and processing of the record
955 // atomic so that no two threads can be blocked on the
956 // read from the same input stream at the same time.
957 // This is required for example when a reader thread is
958 // blocked on the read and another thread is trying to
959 // close the socket. For a non-autoclose, layered socket,
960 // the thread performing the close needs to read the close_notify.
961 //
962 // Use readLock instead of 'this' for locking because
963 // 'this' also protects data accessed during writing.
964 synchronized (readLock) {
965 /*
966 * Read and handle records ... return application data
967 * ONLY if it's needed.
968 */
969 Plaintext plainText = null;
970 while (((state = getConnectionState()) != cs_CLOSED) &&
971 (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
972 // clean the buffer
973 if (buffer != null) {
974 buffer.clear();
975 }
976
977 /*
978 * Read a record ... maybe emitting an alert if we get a
979 * comprehensible but unsupported "hello" message during
980 * format checking (e.g. V2).
981 */
982 try {
983 plainText = inputRecord.decode(sockInput, buffer);
984 } catch (BadPaddingException bpe) {
985 byte alertType = (state != cs_DATA) ?
986 Alerts.alert_handshake_failure :
987 Alerts.alert_bad_record_mac;
988 fatal(alertType, bpe.getMessage(), bpe);
989 } catch (SSLProtocolException spe) {
990 try {
991 fatal(Alerts.alert_unexpected_message, spe);
992 } catch (IOException x) {
993 // discard this exception, throw the original exception
994 }
995 throw spe;
996 } catch (SSLHandshakeException she) {
997 // may be record sequence number overflow
998 fatal(Alerts.alert_handshake_failure, she);
999 } catch (EOFException eof) {
1000 boolean handshaking = (connectionState <= cs_HANDSHAKE);
1001 boolean rethrow = requireCloseNotify || handshaking;
1002 if ((debug != null) && Debug.isOn("ssl")) {
1003 System.out.println(Thread.currentThread().getName() +
1004 ", received EOFException: "
1005 + (rethrow ? "error" : "ignored"));
1006 }
1007 if (rethrow) {
1008 SSLException e;
1009 if (handshaking) {
1010 e = new SSLHandshakeException(
1011 "Remote host terminated the handshake");
1012 } else {
1013 e = new SSLProtocolException(
1014 "Remote host terminated the connection");
1015 }
1016 e.initCause(eof);
1017 throw e;
1018 } else {
1019 // treat as if we had received a close_notify
1020 closeInternal(false);
1021 continue;
1022 }
1023 }
1024
1025 // PlainText should never be null. Process input record.
1026 int volume = processInputRecord(plainText, needAppData);
1027
1028 if (plainText.contentType == Record.ct_application_data) {
1029 return volume;
1030 }
1031
1032 if (plainText.contentType == Record.ct_handshake) {
1033 if (!needAppData && connectionState == cs_DATA) {
1034 return volume;
1035 } // otherwise, need to read more for app data.
1036 }
1037
1038 // continue to read more net data
1039 } // while
1040
1041 //
1042 // couldn't read, due to some kind of error
1043 //
1044 return -1;
1045 } // readLock synchronization
1046 }
1047
1048 /*
1049 * Process the plainText input record.
1050 */
1051 private synchronized int processInputRecord(
1052 Plaintext plainText, boolean needAppData) throws IOException {
1053
1054 /*
1055 * Process the record.
1056 */
1057 int volume = 0; // no application data
1058 switch (plainText.contentType) {
1059 case Record.ct_handshake:
1060 /*
1061 * Handshake messages always go to a pending session
1062 * handshaker ... if there isn't one, create one. This
1063 * must work asynchronously, for renegotiation.
1064 *
1065 * NOTE that handshaking will either resume a session
1066 * which was in the cache (and which might have other
1067 * connections in it already), or else will start a new
1068 * session (new keys exchanged) with just this connection
1069 * in it.
1070 */
1071 initHandshaker();
1072 if (!handshaker.activated()) {
1073 // prior to handshaking, activate the handshake
1074 if (connectionState == cs_RENEGOTIATE) {
1075 // don't use SSLv2Hello when renegotiating
1076 handshaker.activate(protocolVersion);
1077 } else {
1078 handshaker.activate(null);
1079 }
1080 }
1081
1082 /*
1083 * process the handshake record ... may contain just
1084 * a partial handshake message or multiple messages.
1085 *
1086 * The handshaker state machine will ensure that it's
1087 * a finished message.
1088 */
1089 handshaker.processRecord(plainText.fragment, expectingFinished);
1090 expectingFinished = false;
1091
1092 if (handshaker.invalidated) {
1093 handshaker = null;
1094 inputRecord.setHandshakeHash(null);
1095 outputRecord.setHandshakeHash(null);
1096
1097 // if state is cs_RENEGOTIATE, revert it to cs_DATA
1098 if (connectionState == cs_RENEGOTIATE) {
1099 connectionState = cs_DATA;
1100 }
1101 } else if (handshaker.isDone()) {
1102 // reset the parameters for secure renegotiation.
1103 secureRenegotiation =
1104 handshaker.isSecureRenegotiation();
1105 clientVerifyData = handshaker.getClientVerifyData();
1106 serverVerifyData = handshaker.getServerVerifyData();
1107
1108 sess = handshaker.getSession();
1109 handshakeSession = null;
1110 handshaker = null;
1111 inputRecord.setHandshakeHash(null);
1112 outputRecord.setHandshakeHash(null);
1113 connectionState = cs_DATA;
1114
1115 //
1116 // Tell folk about handshake completion, but do
1117 // it in a separate thread.
1118 //
1119 if (handshakeListeners != null) {
1120 HandshakeCompletedEvent event =
1121 new HandshakeCompletedEvent(this, sess);
1122
1123 Thread thread = new ManagedLocalsThread(
1124 new NotifyHandshake(
1125 handshakeListeners.entrySet(), event),
1126 "HandshakeCompletedNotify-Thread");
1127 thread.start();
1128 }
1129 }
1130
1131 break;
1132
1133 case Record.ct_application_data:
1134 if (connectionState != cs_DATA
1135 && connectionState != cs_RENEGOTIATE
1136 && connectionState != cs_SENT_CLOSE) {
1137 throw new SSLProtocolException(
1138 "Data received in non-data state: " +
1139 connectionState);
1140 }
1141 if (expectingFinished) {
1142 throw new SSLProtocolException
1143 ("Expecting finished message, received data");
1144 }
1145 if (!needAppData) {
1146 throw new SSLException("Discarding app data");
1147 }
1148
1149 volume = plainText.fragment.remaining();
1150 break;
1151
1152 case Record.ct_alert:
1153 recvAlert(plainText.fragment);
1154 break;
1155
1156 case Record.ct_change_cipher_spec:
1157 if ((connectionState != cs_HANDSHAKE
1158 && connectionState != cs_RENEGOTIATE)) {
1159 // For the CCS message arriving in the wrong state
1160 fatal(Alerts.alert_unexpected_message,
1161 "illegal change cipher spec msg, conn state = "
1162 + connectionState);
1163 } else if (plainText.fragment.remaining() != 1
1164 || plainText.fragment.get() != 1) {
1165 // For structural/content issues with the CCS
1166 fatal(Alerts.alert_unexpected_message,
1167 "Malformed change cipher spec msg");
1168 }
1169
1170 //
1171 // The first message after a change_cipher_spec
1172 // record MUST be a "Finished" handshake record,
1173 // else it's a protocol violation. We force this
1174 // to be checked by a minor tweak to the state
1175 // machine.
1176 //
1177 handshaker.receiveChangeCipherSpec();
1178
1179 CipherBox readCipher;
1180 Authenticator readAuthenticator;
1181 try {
1182 readCipher = handshaker.newReadCipher();
1183 readAuthenticator = handshaker.newReadAuthenticator();
1184 } catch (GeneralSecurityException e) {
1185 // can't happen
1186 throw new SSLException("Algorithm missing: ", e);
1187 }
1188 inputRecord.changeReadCiphers(readAuthenticator, readCipher);
1189
1190 // next message MUST be a finished message
1191 expectingFinished = true;
1192
1193 break;
1194
1195 default:
1196 //
1197 // TLS requires that unrecognized records be ignored.
1198 //
1199 if (debug != null && Debug.isOn("ssl")) {
1200 System.out.println(Thread.currentThread().getName() +
1201 ", Received record type: " + plainText.contentType);
1202 }
1203 break;
1204 }
1205
1206 /*
1207 * Check the sequence number state
1208 *
1209 * Note that in order to maintain the connection I/O
1210 * properly, we check the sequence number after the last
1211 * record reading process. As we request renegotiation
1212 * or close the connection for wrapped sequence number
1213 * when there is enough sequence number space left to
1214 * handle a few more records, so the sequence number
1215 * of the last record cannot be wrapped.
1216 *
1217 * Don't bother to kickstart the renegotiation when the
1218 * local is asking for it.
1219 */
1220 if ((connectionState == cs_DATA) && inputRecord.seqNumIsHuge()) {
1221 /*
1222 * Ask for renegotiation when need to renew sequence number.
1223 *
1224 * Don't bother to kickstart the renegotiation when the local is
1225 * asking for it.
1226 */
1227 if (debug != null && Debug.isOn("ssl")) {
1228 System.out.println(Thread.currentThread().getName() +
1229 ", request renegotiation " +
1230 "to avoid sequence number overflow");
1231 }
1232
1233 startHandshake();
1234 }
1235
1236 return volume;
1237 }
1238
1239
1240 //
1241 // HANDSHAKE RELATED CODE
1242 //
1243
1244 /**
1245 * Return the AppInputStream. For use by Handshaker only.
1246 */
1247 AppInputStream getAppInputStream() {
1248 return input;
1249 }
1250
1251 /**
1252 * Return the AppOutputStream. For use by Handshaker only.
1253 */
1254 AppOutputStream getAppOutputStream() {
1255 return output;
1256 }
1257
1258 /**
1259 * Initialize the handshaker object. This means:
1299 // state is either cs_START or cs_DATA
1300 if (connectionState == cs_START) {
1301 connectionState = cs_HANDSHAKE;
1302 } else { // cs_DATA
1303 connectionState = cs_RENEGOTIATE;
1304 }
1305 if (roleIsServer) {
1306 handshaker = new ServerHandshaker(this, sslContext,
1307 enabledProtocols, doClientAuth,
1308 protocolVersion, connectionState == cs_HANDSHAKE,
1309 secureRenegotiation, clientVerifyData, serverVerifyData);
1310 handshaker.setSNIMatchers(sniMatchers);
1311 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
1312 } else {
1313 handshaker = new ClientHandshaker(this, sslContext,
1314 enabledProtocols,
1315 protocolVersion, connectionState == cs_HANDSHAKE,
1316 secureRenegotiation, clientVerifyData, serverVerifyData);
1317 handshaker.setSNIServerNames(serverNames);
1318 }
1319 handshaker.setMaximumPacketSize(maximumPacketSize);
1320 handshaker.setEnabledCipherSuites(enabledCipherSuites);
1321 handshaker.setEnableSessionCreation(enableSessionCreation);
1322 }
1323
1324 /**
1325 * Synchronously perform the initial handshake.
1326 *
1327 * If the handshake is already in progress, this method blocks until it
1328 * is completed. If the initial handshake has already been completed,
1329 * it returns immediately.
1330 */
1331 private void performInitialHandshake() throws IOException {
1332 // use handshakeLock and the state check to make sure only
1333 // one thread performs the handshake
1334 synchronized (handshakeLock) {
1335 if (getConnectionState() == cs_HANDSHAKE) {
1336 kickstartHandshake();
1337
1338 /*
1339 * All initial handshaking goes through this operation
1340 * until we have a valid SSL connection.
1341 *
1342 * Handle handshake messages only, need no application data.
1343 */
1344 readRecord(false);
1345 }
1346 }
1347 }
1348
1349 /**
1350 * Starts an SSL handshake on this connection.
1351 */
1352 @Override
1353 public void startHandshake() throws IOException {
1354 // start an ssl handshake that could be resumed from timeout exception
1355 startHandshake(true);
1356 }
1357
1358 /**
1359 * Starts an ssl handshake on this connection.
1360 *
1361 * @param resumable indicates the handshake process is resumable from a
1362 * certain exception. If <code>resumable</code>, the socket will
1363 * be reserved for exceptions like timeout; otherwise, the socket
1364 * will be closed, no further communications could be done.
1365 */
1366 private void startHandshake(boolean resumable) throws IOException {
1367 checkWrite();
1442 // SSLSocketImpl.writeRecord() to send it.
1443 //
1444 if (!handshaker.activated()) {
1445 // prior to handshaking, activate the handshake
1446 if (connectionState == cs_RENEGOTIATE) {
1447 // don't use SSLv2Hello when renegotiating
1448 handshaker.activate(protocolVersion);
1449 } else {
1450 handshaker.activate(null);
1451 }
1452
1453 if (handshaker instanceof ClientHandshaker) {
1454 // send client hello
1455 handshaker.kickstart();
1456 } else {
1457 if (connectionState == cs_HANDSHAKE) {
1458 // initial handshake, no kickstart message to send
1459 } else {
1460 // we want to renegotiate, send hello request
1461 handshaker.kickstart();
1462 }
1463 }
1464 }
1465 }
1466
1467 //
1468 // CLOSURE RELATED CALLS
1469 //
1470
1471 /**
1472 * Return whether the socket has been explicitly closed by the application.
1473 */
1474 @Override
1475 public boolean isClosed() {
1476 return connectionState == cs_APP_CLOSED;
1477 }
1478
1479 /**
1480 * Return whether we have reached end-of-file.
1481 *
1504 return true;
1505 }
1506 IOException e = new SSLException
1507 ("Connection has been shutdown: " + closeReason);
1508 e.initCause(closeReason);
1509 throw e;
1510
1511 }
1512 }
1513
1514 /**
1515 * Check if we can write data to this socket. If not, throw an IOException.
1516 */
1517 void checkWrite() throws IOException {
1518 if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
1519 // we are at EOF, write must throw Exception
1520 throw new SocketException("Connection closed by remote host");
1521 }
1522 }
1523
1524 private void closeSocket() throws IOException {
1525
1526 if ((debug != null) && Debug.isOn("ssl")) {
1527 System.out.println(Thread.currentThread().getName() +
1528 ", called closeSocket()");
1529 }
1530
1531 super.close();
1532 }
1533
1534 private void closeSocket(boolean selfInitiated) throws IOException {
1535 if ((debug != null) && Debug.isOn("ssl")) {
1536 System.out.println(Thread.currentThread().getName() +
1537 ", called closeSocket(" + selfInitiated + ")");
1538 }
1539 if (!isLayered() || autoClose) {
1540 super.close();
1541 } else if (selfInitiated) {
1542 // layered && non-autoclose
1543 // read close_notify alert to clear input stream
1544 waitForClose(false);
1548 /*
1549 * Closing the connection is tricky ... we can't officially close the
1550 * connection until we know the other end is ready to go away too,
1551 * and if ever the connection gets aborted we must forget session
1552 * state (it becomes invalid).
1553 */
1554
1555 /**
1556 * Closes the SSL connection. SSL includes an application level
1557 * shutdown handshake; you should close SSL sockets explicitly
1558 * rather than leaving it for finalization, so that your remote
1559 * peer does not experience a protocol error.
1560 */
1561 @Override
1562 public void close() throws IOException {
1563 if ((debug != null) && Debug.isOn("ssl")) {
1564 System.out.println(Thread.currentThread().getName() +
1565 ", called close()");
1566 }
1567 closeInternal(true); // caller is initiating close
1568
1569 // Clearup the resources.
1570 try {
1571 synchronized (readLock) {
1572 inputRecord.close();
1573 }
1574
1575 writeLock.lock();
1576 try {
1577 outputRecord.close();
1578 } finally {
1579 writeLock.unlock();
1580 }
1581 } catch (IOException ioe) {
1582 // ignore
1583 }
1584
1585 setConnectionState(cs_APP_CLOSED);
1586 }
1587
1588 /**
1589 * Don't synchronize the whole method because waitForClose()
1590 * (which calls readRecord()) might be called.
1591 *
1592 * @param selfInitiated Indicates which party initiated the close.
1593 * If selfInitiated, this side is initiating a close; for layered and
1594 * non-autoclose socket, wait for close_notify response.
1595 * If !selfInitiated, peer sent close_notify; we reciprocate but
1596 * no need to wait for response.
1597 */
1598 private void closeInternal(boolean selfInitiated) throws IOException {
1599 if ((debug != null) && Debug.isOn("ssl")) {
1600 System.out.println(Thread.currentThread().getName() +
1601 ", called closeInternal(" + selfInitiated + ")");
1602 }
1603
1604 int state = getConnectionState();
1688 getConnectionState());
1689 }
1690 return;
1691 }
1692
1693 if (!closeSocketCalled) {
1694 closeSocketCalled = true;
1695 closeSocket(selfInitiated);
1696 }
1697
1698 break;
1699 }
1700 } finally {
1701 synchronized (this) {
1702 // Upon exit from this method, the state is always >= cs_CLOSED
1703 connectionState = (connectionState == cs_APP_CLOSED)
1704 ? cs_APP_CLOSED : cs_CLOSED;
1705 // notify any threads waiting for the closing to finish
1706 this.notifyAll();
1707 }
1708
1709 if (cachedThrowable != null) {
1710 /*
1711 * Rethrow the error to the calling method
1712 * The Throwable caught can only be an Error or RuntimeException
1713 */
1714 if (cachedThrowable instanceof Error) {
1715 throw (Error)cachedThrowable;
1716 } else if (cachedThrowable instanceof RuntimeException) {
1717 throw (RuntimeException)cachedThrowable;
1718 } // Otherwise, unlikely
1719 }
1720 }
1721 }
1722
1723 /**
1724 * Reads a close_notify or a fatal alert from the input stream.
1725 * Keep reading records until we get a close_notify or until
1726 * the connection is otherwise closed. The close_notify or alert
1727 * might be read by another reader,
1728 * which will then process the close and set the connection state.
1729 */
1730 void waitForClose(boolean rethrow) throws IOException {
1731 if (debug != null && Debug.isOn("ssl")) {
1732 System.out.println(Thread.currentThread().getName() +
1733 ", waiting for close_notify or alert: state "
1734 + getConnectionState());
1735 }
1736
1737 try {
1738 int state;
1739
1740 while (((state = getConnectionState()) != cs_CLOSED) &&
1741 (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1742
1743 // Ask for app data and then throw it away
1744 try {
1745 readRecord(true);
1746 } catch (SocketTimeoutException e) {
1747 // if time out, ignore the exception and continue
1748 }
1749 }
1750 } catch (IOException e) {
1751 if (debug != null && Debug.isOn("ssl")) {
1752 System.out.println(Thread.currentThread().getName() +
1753 ", Exception while waiting for close " +e);
1754 }
1755 if (rethrow) {
1756 throw e; // pass exception up
1757 }
1758 }
1759 }
1760
1761 //
1762 // EXCEPTION AND ALERT HANDLING
1763 //
1764
1765 /**
1766 * Handle an exception. This method is called by top level exception
1767 * handlers (in read(), write()) to make sure we always shutdown the
1768 * connection correctly and do not pass runtime exception to the
1769 * application.
1770 */
1771 void handleException(Exception e) throws IOException {
1772 handleException(e, true);
1773 }
1774
1775 /**
1776 * Handle an exception. This method is called by top level exception
1777 * handlers (in read(), write(), startHandshake()) to make sure we
1778 * always shutdown the connection correctly and do not pass runtime
1779 * exception to the application.
1780 *
1802 if (e instanceof InterruptedIOException && resumable) {
1803 throw (IOException)e;
1804 }
1805
1806 // if we've already shutdown because of an error,
1807 // there is nothing to do except rethrow the exception
1808 if (closeReason != null) {
1809 if (e instanceof IOException) { // includes SSLException
1810 throw (IOException)e;
1811 } else {
1812 // this is odd, not an IOException.
1813 // normally, this should not happen
1814 // if closeReason has been already been set
1815 throw Alerts.getSSLException(Alerts.alert_internal_error, e,
1816 "Unexpected exception");
1817 }
1818 }
1819
1820 // need to perform error shutdown
1821 boolean isSSLException = (e instanceof SSLException);
1822 if ((!isSSLException) && (e instanceof IOException)) {
1823 // IOException from the socket
1824 // this means the TCP connection is already dead
1825 // we call fatal just to set the error status
1826 try {
1827 fatal(Alerts.alert_unexpected_message, e);
1828 } catch (IOException ee) {
1829 // ignore (IOException wrapped in SSLException)
1830 }
1831 // rethrow original IOException
1832 throw (IOException)e;
1833 }
1834
1835 // must be SSLException or RuntimeException
1836 byte alertType;
1837 if (isSSLException) {
1838 if (e instanceof SSLHandshakeException) {
1839 alertType = Alerts.alert_handshake_failure;
1840 } else {
1841 alertType = Alerts.alert_unexpected_message;
1842 }
1852 void warning(byte description) {
1853 sendAlert(Alerts.alert_warning, description);
1854 }
1855
1856 synchronized void fatal(byte description, String diagnostic)
1857 throws IOException {
1858 fatal(description, diagnostic, null);
1859 }
1860
1861 synchronized void fatal(byte description, Throwable cause)
1862 throws IOException {
1863 fatal(description, null, cause);
1864 }
1865
1866 /*
1867 * Send a fatal alert, and throw an exception so that callers will
1868 * need to stand on their heads to accidentally continue processing.
1869 */
1870 synchronized void fatal(byte description, String diagnostic,
1871 Throwable cause) throws IOException {
1872
1873 // Be care of deadlock. Please don't synchronize readLock.
1874 try {
1875 inputRecord.close();
1876 } catch (IOException ioe) {
1877 // ignore
1878 }
1879
1880 sess.invalidate();
1881 if (handshakeSession != null) {
1882 handshakeSession.invalidate();
1883 }
1884
1885 int oldState = connectionState;
1886 if (connectionState < cs_ERROR) {
1887 connectionState = cs_ERROR;
1888 }
1889
1890 /*
1891 * Has there been an error received yet? If not, remember it.
1892 * By RFC 2246, we don't bother waiting for a response.
1893 * Fatal errors require immediate shutdown.
1894 */
1895 if (closeReason == null) {
1896 /*
1897 * Try to clear the kernel buffer to avoid TCP connection resets.
1898 */
1899 if (oldState == cs_HANDSHAKE) {
1900 sockInput.skip(sockInput.available());
1901 }
1902
1903 // If the description equals -1, the alert won't be sent to peer.
1904 if (description != -1) {
1905 sendAlert(Alerts.alert_fatal, description);
1906 }
1907 if (cause instanceof SSLException) { // only true if != null
1908 closeReason = (SSLException)cause;
1909 } else {
1910 closeReason =
1911 Alerts.getSSLException(description, cause, diagnostic);
1912 }
1913 }
1914
1915 /*
1916 * Clean up our side.
1917 */
1918 closeSocket();
1919
1920 // Be care of deadlock. Please don't synchronize writeLock.
1921 try {
1922 outputRecord.close();
1923 } catch (IOException ioe) {
1924 // ignore
1925 }
1926
1927 throw closeReason;
1928 }
1929
1930
1931 /*
1932 * Process an incoming alert ... caller must already have synchronized
1933 * access to "this".
1934 */
1935 private void recvAlert(ByteBuffer fragment) throws IOException {
1936 byte level = fragment.get();
1937 byte description = fragment.get();
1938
1939 if (description == -1) { // check for short message
1940 fatal(Alerts.alert_illegal_parameter, "Short alert message");
1941 }
1942
1943 if (debug != null && (Debug.isOn("record") ||
1944 Debug.isOn("handshake"))) {
1945 synchronized (System.out) {
1946 System.out.print(Thread.currentThread().getName());
1947 System.out.print(", RECV " + protocolVersion + " ALERT: ");
1948 if (level == Alerts.alert_fatal) {
1949 System.out.print("fatal, ");
1950 } else if (level == Alerts.alert_warning) {
1951 System.out.print("warning, ");
1952 } else {
1953 System.out.print("<level " + (0x0ff & level) + ">, ");
1954 }
1955 System.out.println(Alerts.alertDescription(description));
1956 }
1957 }
1958
1981 + Alerts.alertDescription(description);
1982 if (closeReason == null) {
1983 closeReason = Alerts.getSSLException(description, reason);
1984 }
1985 fatal(Alerts.alert_unexpected_message, reason);
1986 }
1987 }
1988
1989
1990 /*
1991 * Emit alerts. Caller must have synchronized with "this".
1992 */
1993 private void sendAlert(byte level, byte description) {
1994 // the connectionState cannot be cs_START
1995 if (connectionState >= cs_SENT_CLOSE) {
1996 return;
1997 }
1998
1999 // For initial handshaking, don't send alert message to peer if
2000 // handshaker has not started.
2001 //
2002 // Shall we send an fatal alter to terminate the connection gracefully?
2003 if (connectionState <= cs_HANDSHAKE &&
2004 (handshaker == null || !handshaker.started() ||
2005 !handshaker.activated())) {
2006 return;
2007 }
2008
2009 boolean useDebug = debug != null && Debug.isOn("ssl");
2010 if (useDebug) {
2011 synchronized (System.out) {
2012 System.out.print(Thread.currentThread().getName());
2013 System.out.print(", SEND " + protocolVersion + " ALERT: ");
2014 if (level == Alerts.alert_fatal) {
2015 System.out.print("fatal, ");
2016 } else if (level == Alerts.alert_warning) {
2017 System.out.print("warning, ");
2018 } else {
2019 System.out.print("<level = " + (0x0ff & level) + ">, ");
2020 }
2021 System.out.println("description = "
2022 + Alerts.alertDescription(description));
2023 }
2024 }
2025
2026 try {
2027 writeAlert(level, description);
2028 } catch (IOException e) {
2029 if (useDebug) {
2030 System.out.println(Thread.currentThread().getName() +
2031 ", Exception sending alert: " + e);
2032 }
2033 }
2034 }
2035
2036 //
2037 // VARIOUS OTHER METHODS
2038 //
2039
2040 // used by Handshaker
2041 void changeWriteCiphers() throws IOException {
2042 Authenticator writeAuthenticator;
2043 CipherBox writeCipher;
2044 try {
2045 writeCipher = handshaker.newWriteCipher();
2046 writeAuthenticator = handshaker.newWriteAuthenticator();
2047 } catch (GeneralSecurityException e) {
2048 // "can't happen"
2049 throw new SSLException("Algorithm missing: ", e);
2050 }
2051 outputRecord.changeWriteCiphers(writeAuthenticator, writeCipher);
2052 }
2053
2054 /*
2055 * Updates the SSL version associated with this connection.
2056 * Called from Handshaker once it has determined the negotiated version.
2057 */
2058 synchronized void setVersion(ProtocolVersion protocolVersion) {
2059 this.protocolVersion = protocolVersion;
2060 outputRecord.setVersion(protocolVersion);
2061 }
2062
2063 synchronized String getHost() {
2064 // Note that the host may be null or empty for localhost.
2065 if (host == null || host.length() == 0) {
2066 host = getInetAddress().getHostName();
2067 }
2068 return host;
2069 }
2070
2071 // ONLY used by HttpsClient to setup the URI specified hostname
2072 //
2073 // Please NOTE that this method MUST be called before calling to
2074 // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
2075 // may override SNIHostName in the customized server name indication.
2076 synchronized public void setHost(String host) {
2077 this.host = host;
2078 this.serverNames =
2079 Utilities.addToSNIServerNameList(this.serverNames, this.host);
2080 }
2139 startHandshake(false);
2140 } catch (IOException e) {
2141 // handshake failed. log and return a nullSession
2142 if (debug != null && Debug.isOn("handshake")) {
2143 System.out.println(Thread.currentThread().getName() +
2144 ", IOException in getSession(): " + e);
2145 }
2146 }
2147 }
2148 synchronized (this) {
2149 return sess;
2150 }
2151 }
2152
2153 @Override
2154 synchronized public SSLSession getHandshakeSession() {
2155 return handshakeSession;
2156 }
2157
2158 synchronized void setHandshakeSession(SSLSessionImpl session) {
2159 // update the fragment size, which may be negotiated during handshaking
2160 inputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2161 outputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2162
2163 handshakeSession = session;
2164 }
2165
2166 /**
2167 * Controls whether new connections may cause creation of new SSL
2168 * sessions.
2169 *
2170 * As long as handshaking has not started, we can change
2171 * whether we enable session creations. Otherwise,
2172 * we will need to wait for the next handshake.
2173 */
2174 @Override
2175 synchronized public void setEnableSessionCreation(boolean flag) {
2176 enableSessionCreation = flag;
2177
2178 if ((handshaker != null) && !handshaker.activated()) {
2179 handshaker.setEnableSessionCreation(enableSessionCreation);
2180 }
2181 }
2182
2183 /**
2184 * Returns true if new connections may cause creation of new SSL
2185 * sessions.
2186 */
2187 @Override
2188 synchronized public boolean getEnableSessionCreation() {
2189 return enableSessionCreation;
2190 }
2191
2192
2193 /**
2194 * Sets the flag controlling whether a server mode socket
2195 * *REQUIRES* SSL client authentication.
2196 *
2197 * As long as handshaking has not started, we can change
2198 * whether client authentication is needed. Otherwise,
2199 * we will need to wait for the next handshake.
2200 */
2201 @Override
2202 synchronized public void setNeedClientAuth(boolean flag) {
2203 doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUIRED :
2204 ClientAuthType.CLIENT_AUTH_NONE);
2205
2206 if ((handshaker != null) &&
2207 (handshaker instanceof ServerHandshaker) &&
2208 !handshaker.activated()) {
2209 ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2210 }
2211 }
2212
2213 @Override
2214 synchronized public boolean getNeedClientAuth() {
2215 return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED);
2216 }
2217
2218 /**
2219 * Sets the flag controlling whether a server mode socket
2220 * *REQUESTS* SSL client authentication.
2221 *
2222 * As long as handshaking has not started, we can change
2223 * whether client authentication is requested. Otherwise,
2224 * we will need to wait for the next handshake.
2225 */
2226 @Override
2227 synchronized public void setWantClientAuth(boolean flag) {
2228 doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUESTED :
2229 ClientAuthType.CLIENT_AUTH_NONE);
2230
2231 if ((handshaker != null) &&
2232 (handshaker instanceof ServerHandshaker) &&
2233 !handshaker.activated()) {
2234 ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2235 }
2236 }
2237
2238 @Override
2239 synchronized public boolean getWantClientAuth() {
2240 return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED);
2241 }
2242
2243
2244 /**
2245 * Sets the flag controlling whether the socket is in SSL
2246 * client or server mode. Must be called before any SSL
2247 * traffic has started.
2248 */
2249 @Override
2250 @SuppressWarnings("fallthrough")
2251 synchronized public void setUseClientMode(boolean flag) {
2252 switch (connectionState) {
2253
2254 case cs_START:
2255 /*
2256 * If we need to change the socket mode and the enabled
2257 * protocols and cipher suites haven't specifically been
2258 * set by the user, change them to the corresponding
2259 * default ones.
2260 */
2261 if (roleIsServer != (!flag)) {
2262 if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2263 enabledProtocols =
2264 sslContext.getDefaultProtocolList(!flag);
2265 }
2266
2267 if (sslContext.isDefaultCipherSuiteList(enabledCipherSuites)) {
2268 enabledCipherSuites =
2269 sslContext.getDefaultCipherSuiteList(!flag);
2270 }
2271 }
2272
2273 roleIsServer = !flag;
2274 break;
2275
2276 case cs_HANDSHAKE:
2277 /*
2278 * If we have a handshaker, but haven't started
2279 * SSL traffic, we can throw away our current
2280 * handshaker, and start from scratch. Don't
2281 * need to call doneConnect() again, we already
2282 * have the streams.
2283 */
2284 assert(handshaker != null);
2285 if (!handshaker.activated()) {
2286 /*
2287 * If we need to change the socket mode and the enabled
2288 * protocols and cipher suites haven't specifically been
2289 * set by the user, change them to the corresponding
2290 * default ones.
2291 */
2292 if (roleIsServer != (!flag)) {
2293 if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2294 enabledProtocols =
2295 sslContext.getDefaultProtocolList(!flag);
2296 }
2297
2298 if (sslContext.isDefaultCipherSuiteList(
2299 enabledCipherSuites)) {
2300 enabledCipherSuites =
2301 sslContext.getDefaultCipherSuiteList(!flag);
2302 }
2303 }
2304
2305 roleIsServer = !flag;
2306 connectionState = cs_START;
2307 initHandshaker();
2308 break;
2309 }
2310
2311 // If handshake has started, that's an error. Fall through...
2312
2313 default:
2314 if (debug != null && Debug.isOn("ssl")) {
2315 System.out.println(Thread.currentThread().getName() +
2316 ", setUseClientMode() invoked in state = " +
2317 connectionState);
2318 }
2319 throw new IllegalArgumentException(
2320 "Cannot change mode after SSL traffic has started");
2321 }
2322 }
2323
2324 @Override
2452 throw new IllegalArgumentException("listener not registered");
2453 }
2454 if (handshakeListeners.isEmpty()) {
2455 handshakeListeners = null;
2456 }
2457 }
2458
2459 /**
2460 * Returns the SSLParameters in effect for this SSLSocket.
2461 */
2462 @Override
2463 synchronized public SSLParameters getSSLParameters() {
2464 SSLParameters params = super.getSSLParameters();
2465
2466 // the super implementation does not handle the following parameters
2467 params.setEndpointIdentificationAlgorithm(identificationProtocol);
2468 params.setAlgorithmConstraints(algorithmConstraints);
2469 params.setSNIMatchers(sniMatchers);
2470 params.setServerNames(serverNames);
2471 params.setUseCipherSuitesOrder(preferLocalCipherSuites);
2472 params.setMaximumPacketSize(maximumPacketSize);
2473
2474 // DTLS handshake retransmissions parameter does not apply here.
2475
2476 return params;
2477 }
2478
2479 /**
2480 * Applies SSLParameters to this socket.
2481 */
2482 @Override
2483 synchronized public void setSSLParameters(SSLParameters params) {
2484 super.setSSLParameters(params);
2485
2486 // the super implementation does not handle the following parameters
2487 identificationProtocol = params.getEndpointIdentificationAlgorithm();
2488 algorithmConstraints = params.getAlgorithmConstraints();
2489 preferLocalCipherSuites = params.getUseCipherSuitesOrder();
2490 maximumPacketSize = params.getMaximumPacketSize();
2491
2492 // DTLS handshake retransmissions parameter does not apply here.
2493
2494 if (maximumPacketSize != 0) {
2495 outputRecord.changePacketSize(maximumPacketSize);
2496 } else {
2497 // use the implicit maximum packet size.
2498 maximumPacketSize = outputRecord.getMaxPacketSize();
2499 }
2500
2501 List<SNIServerName> sniNames = params.getServerNames();
2502 if (sniNames != null) {
2503 serverNames = sniNames;
2504 }
2505
2506 Collection<SNIMatcher> matchers = params.getSNIMatchers();
2507 if (matchers != null) {
2508 sniMatchers = matchers;
2509 }
2510
2511 if ((handshaker != null) && !handshaker.started()) {
2512 handshaker.setIdentificationProtocol(identificationProtocol);
2513 handshaker.setAlgorithmConstraints(algorithmConstraints);
2514 handshaker.setMaximumPacketSize(maximumPacketSize);
2515 if (roleIsServer) {
2516 handshaker.setSNIMatchers(sniMatchers);
2517 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
2518 } else {
2519 handshaker.setSNIServerNames(serverNames);
2520 }
2521 }
2522 }
2523
2524 //
2525 // We allocate a separate thread to deliver handshake completion
2526 // events. This ensures that the notifications don't block the
2527 // protocol state machine.
2528 //
2529 private static class NotifyHandshake implements Runnable {
2530
2531 private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2532 targets; // who gets notified
2533 private HandshakeCompletedEvent event; // the notification
2534
2542
2543 @Override
2544 public void run() {
2545 // Don't need to synchronize, as it only runs in one thread.
2546 for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
2547 entry : targets) {
2548
2549 final HandshakeCompletedListener l = entry.getKey();
2550 AccessControlContext acc = entry.getValue();
2551 AccessController.doPrivileged(new PrivilegedAction<Void>() {
2552 @Override
2553 public Void run() {
2554 l.handshakeCompleted(event);
2555 return null;
2556 }
2557 }, acc);
2558 }
2559 }
2560 }
2561
2562 /**
2563 * Returns a printable representation of this end of the connection.
2564 */
2565 @Override
2566 public String toString() {
2567 StringBuilder retval = new StringBuilder(80);
2568
2569 retval.append(Integer.toHexString(hashCode()));
2570 retval.append("[");
2571 retval.append(sess.getCipherSuite());
2572 retval.append(": ");
2573
2574 retval.append(super.toString());
2575 retval.append("]");
2576
2577 return retval.toString();
2578 }
2579 }
|