Class OpenSSLSocketImpl
- All Implemented Interfaces:
Closeable,AutoCloseable,NativeCrypto.SSLHandshakeCallbacks
- Direct Known Subclasses:
OpenSSLSocketImplWrapper
public class OpenSSLSocketImpl extends SSLSocket implements NativeCrypto.SSLHandshakeCallbacks
Extensions to SSLSocket include:
- handshake timeout
- session tickets
- Server Name Indication
-
Constructor Summary
Constructors Modifier Constructor Description protectedOpenSSLSocketImpl(String host, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)protectedOpenSSLSocketImpl(String host, int port, SSLParametersImpl sslParameters)protectedOpenSSLSocketImpl(InetAddress address, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)protectedOpenSSLSocketImpl(InetAddress address, int port, SSLParametersImpl sslParameters)protectedOpenSSLSocketImpl(Socket socket, String host, int port, boolean autoClose, SSLParametersImpl sslParameters)Create an SSL socket that wraps another socket.protectedOpenSSLSocketImpl(SSLParametersImpl sslParameters)protectedOpenSSLSocketImpl(SSLParametersImpl sslParameters, String[] enabledProtocols, String[] enabledCipherSuites) -
Method Summary
Modifier and Type Method Description voidaddHandshakeCompletedListener(HandshakeCompletedListener listener)Registers the specified listener to receive notification on completion of a handshake on this connection.voidclientCertificateRequested(byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals)Called on an SSL client when the server requests (or requires a certificate).voidclose()Closes the socket.protected voidfinalize()Invoked when the garbage collector has detected that this instance is no longer reachable.byte[]getAlpnSelectedProtocol()Returns the protocol agreed upon by client and server, ornullif no protocol was agreed upon.byte[]getChannelId()Gets the TLS Channel ID for this server socket.String[]getEnabledCipherSuites()Returns the names of the enabled cipher suites.String[]getEnabledProtocols()Returns the names of the enabled protocols.booleangetEnableSessionCreation()Returns whether new SSL sessions may be created by this socket or if existing sessions must be reused.FileDescriptorgetFileDescriptor$()InputStreamgetInputStream()Returns an input stream to read data from this socket.booleangetNeedClientAuth()Returns true if the server socket should require client authentication.byte[]getNpnSelectedProtocol()Returns the protocol agreed upon by client and server, or null if no protocol was agreed upon.OutputStreamgetOutputStream()Returns an output stream to write data into this socket.SSLSessiongetSession()Returns theSSLSessionfor this connection.intgetSoTimeout()Returns this socket'sreceive timeout.intgetSoWriteTimeout()Note write timeouts are not part of the javax.net.ssl.SSLSocket APIString[]getSupportedCipherSuites()Returns the names of the supported cipher suites.String[]getSupportedProtocols()Returns the names of the supported protocols.booleangetUseClientMode()Returns true if this connection will act in client mode when handshaking.booleangetWantClientAuth()Returns true if the server should request client authentication.voidhandshakeCompleted()Called when SSL handshake is completed.voidremoveHandshakeCompletedListener(HandshakeCompletedListener listener)Removes the specified handshake completion listener.voidsendUrgentData(int data)Sends the given single byte data which is represented by the lowest octet ofvalueas "TCP urgent data".voidsetAlpnProtocols(byte[] alpnProtocols)Sets the list of protocols this peer is interested in.voidsetChannelIdEnabled(boolean enabled)Enables/disables TLS Channel ID for this server socket.voidsetChannelIdPrivateKey(PrivateKey privateKey)Sets thePrivateKeyto be used for TLS Channel ID by this client socket.voidsetEnabledCipherSuites(String[] suites)Sets the names of the cipher suites to be enabled.voidsetEnabledProtocols(String[] protocols)Sets the names of the protocols to be enabled.voidsetEnableSessionCreation(boolean flag)Sets whether new SSL sessions may be created by this socket or if existing sessions must be reused.voidsetHandshakeTimeout(int handshakeTimeoutMilliseconds)Set the handshake timeout on this socket.voidsetHostname(String hostname)This method enables Server Name IndicationvoidsetNeedClientAuth(boolean need)Sets whether the server should require client authentication.voidsetNpnProtocols(byte[] npnProtocols)Sets the list of protocols this peer is interested in.voidsetOOBInline(boolean on)Sets this socket'sSocketOptions.SO_OOBINLINEoption.voidsetSoTimeout(int readTimeoutMilliseconds)Sets this socket'sread timeoutin milliseconds.voidsetSoWriteTimeout(int writeTimeoutMilliseconds)Note write timeouts are not part of the javax.net.ssl.SSLSocket APIvoidsetUseClientMode(boolean mode)Sets whether this connection should act in client mode when handshaking.voidsetUseSessionTickets(boolean useSessionTickets)This method enables session ticket support.voidsetWantClientAuth(boolean want)Sets whether the server should request client authentication.voidstartHandshake()Starts a TLS/SSL handshake on this connection using some native methods from the OpenSSL library.voidverifyCertificateChain(byte[][] bytes, String authMethod)Verify that we trust the certificate chain is trusted.Methods inherited from class javax.net.ssl.SSLSocket
getSSLParameters, setSSLParameters, shutdownInput, shutdownOutputMethods inherited from class java.net.Socket
bind, connect, connect, getChannel, getInetAddress, getKeepAlive, getLocalAddress, getLocalPort, getLocalSocketAddress, getOOBInline, getPort, getReceiveBufferSize, getRemoteSocketAddress, getReuseAddress, getSendBufferSize, getSoLinger, getTcpNoDelay, getTrafficClass, isBound, isClosed, isConnected, isInputShutdown, isOutputShutdown, setKeepAlive, setPerformancePreferences, setReceiveBufferSize, setReuseAddress, setSendBufferSize, setSocketImplFactory, setSoLinger, setTcpNoDelay, setTrafficClass, toString
-
Constructor Details
-
OpenSSLSocketImpl
- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(SSLParametersImpl sslParameters, String[] enabledProtocols, String[] enabledCipherSuites) throws IOException- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(String host, int port, SSLParametersImpl sslParameters) throws IOException- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(InetAddress address, int port, SSLParametersImpl sslParameters) throws IOException- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(String host, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(InetAddress address, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException- Throws:
IOException
-
OpenSSLSocketImpl
protected OpenSSLSocketImpl(Socket socket, String host, int port, boolean autoClose, SSLParametersImpl sslParameters) throws IOExceptionCreate an SSL socket that wraps another socket. Invoked by OpenSSLSocketImplWrapper constructor.- Throws:
IOException
-
-
Method Details
-
startHandshake
Starts a TLS/SSL handshake on this connection using some native methods from the OpenSSL library. It can negotiate new encryption keys, change cipher suites, or initiate a new session. The certificate chain is verified if the correspondent property in java.Security is set. All listeners are notified at the end of the TLS/SSL handshake.- Specified by:
startHandshakein classSSLSocket- Throws:
IOException- if an error occurs.
-
clientCertificateRequested
public void clientCertificateRequested(byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws CertificateEncodingException, SSLExceptionDescription copied from interface:NativeCrypto.SSLHandshakeCallbacksCalled on an SSL client when the server requests (or requires a certificate). The client can respond by using SSL_use_certificate and SSL_use_PrivateKey to set a certificate if has an appropriate one available, similar to how the server provides its certificate.- Specified by:
clientCertificateRequestedin interfaceNativeCrypto.SSLHandshakeCallbacks- Parameters:
keyTypeBytes- key types supported by the server, convertible to strings with #keyTypeasn1DerEncodedPrincipals- CAs known to the server- Throws:
CertificateEncodingExceptionSSLException
-
handshakeCompleted
public void handshakeCompleted()Description copied from interface:NativeCrypto.SSLHandshakeCallbacksCalled when SSL handshake is completed. Note that this can be after SSL_do_handshake returns when handshake cutthrough is enabled.- Specified by:
handshakeCompletedin interfaceNativeCrypto.SSLHandshakeCallbacks
-
verifyCertificateChain
Description copied from interface:NativeCrypto.SSLHandshakeCallbacksVerify that we trust the certificate chain is trusted.- Specified by:
verifyCertificateChainin interfaceNativeCrypto.SSLHandshakeCallbacks- Parameters:
bytes- A chain of ASN.1 DER encoded certificatesauthMethod- auth algorithm name- Throws:
CertificateException- if the certificate is untrusted
-
getInputStream
Description copied from class:SocketReturns an input stream to read data from this socket.- Overrides:
getInputStreamin classSocket- Returns:
- the byte-oriented input stream.
- Throws:
IOException- if an error occurs while creating the input stream or the socket is in an invalid state.
-
getOutputStream
Description copied from class:SocketReturns an output stream to write data into this socket.- Overrides:
getOutputStreamin classSocket- Returns:
- the byte-oriented output stream.
- Throws:
IOException- if an error occurs while creating the output stream or the socket is in an invalid state.
-
getSession
Description copied from class:SSLSocketReturns theSSLSessionfor this connection. If necessary, a handshake will be initiated, in which case this method will block until the handshake has been established. If the handshake fails, an invalid session object will be returned.- Specified by:
getSessionin classSSLSocket- Returns:
- the session object.
-
addHandshakeCompletedListener
Description copied from class:SSLSocketRegisters the specified listener to receive notification on completion of a handshake on this connection.- Specified by:
addHandshakeCompletedListenerin classSSLSocket- Parameters:
listener- the listener to register.
-
removeHandshakeCompletedListener
Description copied from class:SSLSocketRemoves the specified handshake completion listener.- Specified by:
removeHandshakeCompletedListenerin classSSLSocket- Parameters:
listener- the listener to remove.
-
getEnableSessionCreation
public boolean getEnableSessionCreation()Description copied from class:SSLSocketReturns whether new SSL sessions may be created by this socket or if existing sessions must be reused.- Specified by:
getEnableSessionCreationin classSSLSocket- Returns:
trueif new sessions may be created, otherwisefalse.
-
setEnableSessionCreation
public void setEnableSessionCreation(boolean flag)Description copied from class:SSLSocketSets whether new SSL sessions may be created by this socket or if existing sessions must be reused. Ifflagis false and there are no sessions to resume, handshaking will fail.- Specified by:
setEnableSessionCreationin classSSLSocket- Parameters:
flag-trueif new sessions may be created.
-
getSupportedCipherSuites
Description copied from class:SSLSocketReturns the names of the supported cipher suites.- Specified by:
getSupportedCipherSuitesin classSSLSocket
-
getEnabledCipherSuites
Description copied from class:SSLSocketReturns the names of the enabled cipher suites.- Specified by:
getEnabledCipherSuitesin classSSLSocket
-
setEnabledCipherSuites
Description copied from class:SSLSocketSets the names of the cipher suites to be enabled. Only cipher suites returned bySSLSocket.getSupportedCipherSuites()are allowed.- Specified by:
setEnabledCipherSuitesin classSSLSocket- Parameters:
suites- the names of the to be enabled cipher suites.
-
getSupportedProtocols
Description copied from class:SSLSocketReturns the names of the supported protocols.- Specified by:
getSupportedProtocolsin classSSLSocket
-
getEnabledProtocols
Description copied from class:SSLSocketReturns the names of the enabled protocols.- Specified by:
getEnabledProtocolsin classSSLSocket
-
setEnabledProtocols
Description copied from class:SSLSocketSets the names of the protocols to be enabled. Only protocols returned bySSLSocket.getSupportedProtocols()are allowed.- Specified by:
setEnabledProtocolsin classSSLSocket- Parameters:
protocols- the names of the to be enabled protocols.
-
setUseSessionTickets
public void setUseSessionTickets(boolean useSessionTickets)This method enables session ticket support.- Parameters:
useSessionTickets- True to enable session tickets
-
setHostname
This method enables Server Name Indication- Parameters:
hostname- the desired SNI hostname, or null to disable
-
setChannelIdEnabled
public void setChannelIdEnabled(boolean enabled)Enables/disables TLS Channel ID for this server socket.This method needs to be invoked before the handshake starts.
- Throws:
IllegalStateException- if this is a client socket or if the handshake has already started.
-
getChannelId
Gets the TLS Channel ID for this server socket. Channel ID is only available once the handshake completes.- Returns:
- channel ID or
nullif not available. - Throws:
IllegalStateException- if this is a client socket or if the handshake has not yet completed.SSLException- if channel ID is available but could not be obtained.
-
setChannelIdPrivateKey
Sets thePrivateKeyto be used for TLS Channel ID by this client socket.This method needs to be invoked before the handshake starts.
- Parameters:
privateKey- private key (enables TLS Channel ID) ornullfor no key (disables TLS Channel ID). The private key must be an Elliptic Curve (EC) key based on the NIST P-256 curve (aka SECG secp256r1 or ANSI X9.62 prime256v1).- Throws:
IllegalStateException- if this is a server socket or if the handshake has already started.
-
getUseClientMode
public boolean getUseClientMode()Description copied from class:SSLSocketReturns true if this connection will act in client mode when handshaking.- Specified by:
getUseClientModein classSSLSocket
-
setUseClientMode
public void setUseClientMode(boolean mode)Description copied from class:SSLSocketSets whether this connection should act in client mode when handshaking.- Specified by:
setUseClientModein classSSLSocket- Parameters:
mode-trueif this connection should act in client mode,falseif not.
-
getWantClientAuth
public boolean getWantClientAuth()Description copied from class:SSLSocketReturns true if the server should request client authentication. This does not apply to sockets inclient mode.- Specified by:
getWantClientAuthin classSSLSocket
-
getNeedClientAuth
public boolean getNeedClientAuth()Description copied from class:SSLSocketReturns true if the server socket should require client authentication. This does not apply to sockets inclient mode.- Specified by:
getNeedClientAuthin classSSLSocket
-
setNeedClientAuth
public void setNeedClientAuth(boolean need)Description copied from class:SSLSocketSets whether the server should require client authentication. This does not apply to sockets inclient mode. Client authentication is one of the following:- authentication required
- authentication requested
- no authentication needed
SSLSocket.setWantClientAuth(boolean).- Specified by:
setNeedClientAuthin classSSLSocket
-
setWantClientAuth
public void setWantClientAuth(boolean want)Description copied from class:SSLSocketSets whether the server should request client authentication. UnlikeSSLSocket.setNeedClientAuth(boolean)this won't stop the negotiation if the client doesn't authenticate. This does not apply to sockets inclient mode.The client authentication is one of:- authentication required
- authentication requested
- no authentication needed
SSLSocket.setNeedClientAuth(boolean).- Specified by:
setWantClientAuthin classSSLSocket
-
sendUrgentData
Description copied from class:SocketSends the given single byte data which is represented by the lowest octet ofvalueas "TCP urgent data".- Overrides:
sendUrgentDatain classSocket- Parameters:
data- the byte of urgent data to be sent.- Throws:
IOException- if an error occurs while sending urgent data.
-
setOOBInline
Description copied from class:SocketSets this socket'sSocketOptions.SO_OOBINLINEoption.- Overrides:
setOOBInlinein classSocket- Throws:
SocketException
-
setSoTimeout
Description copied from class:SocketSets this socket'sread timeoutin milliseconds. Use 0 for no timeout. To take effect, this option must be set before the blocking method was called.- Overrides:
setSoTimeoutin classSocket- Throws:
SocketException
-
getSoTimeout
Description copied from class:SocketReturns this socket'sreceive timeout.- Overrides:
getSoTimeoutin classSocket- Throws:
SocketException
-
setSoWriteTimeout
Note write timeouts are not part of the javax.net.ssl.SSLSocket API- Throws:
SocketException
-
getSoWriteTimeout
Note write timeouts are not part of the javax.net.ssl.SSLSocket API- Throws:
SocketException
-
setHandshakeTimeout
Set the handshake timeout on this socket. This timeout is specified in milliseconds and will be used only during the handshake process.- Throws:
SocketException
-
close
Description copied from class:SocketCloses the socket. It is not possible to reconnect or rebind to this socket thereafter which means a new socket instance has to be created.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Overrides:
closein classSocket- Throws:
IOException- if an error occurs while closing the socket.
-
finalize
Description copied from class:ObjectInvoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.Note that objects that override
finalizeare significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.If you must use finalizers, consider at least providing your own
ReferenceQueueand having your own thread process that queue.Unlike constructors, finalizers are not automatically chained. You are responsible for calling
super.finalize()yourself.Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.
-
getFileDescriptor$
- Overrides:
getFileDescriptor$in classSocket
-
getNpnSelectedProtocol
public byte[] getNpnSelectedProtocol()Returns the protocol agreed upon by client and server, or null if no protocol was agreed upon. -
getAlpnSelectedProtocol
public byte[] getAlpnSelectedProtocol()Returns the protocol agreed upon by client and server, ornullif no protocol was agreed upon. -
setNpnProtocols
public void setNpnProtocols(byte[] npnProtocols)Sets the list of protocols this peer is interested in. If null no protocols will be used.- Parameters:
npnProtocols- a non-empty array of protocol names. From SSL_select_next_proto, "vector of 8-bit, length prefixed byte strings. The length byte itself is not included in the length. A byte string of length 0 is invalid. No byte string may be truncated.".
-
setAlpnProtocols
public void setAlpnProtocols(byte[] alpnProtocols)Sets the list of protocols this peer is interested in. If the list isnull, no protocols will be used.- Parameters:
alpnProtocols- a non-empty array of protocol names. From SSL_select_next_proto, "vector of 8-bit, length prefixed byte strings. The length byte itself is not included in the length. A byte string of length 0 is invalid. No byte string may be truncated.".
-