Class AbstractSession
- java.lang.Object
-
- org.apache.sshd.common.util.logging.AbstractLoggingBean
-
- org.apache.sshd.common.util.closeable.IoBaseCloseable
-
- org.apache.sshd.common.util.closeable.AbstractCloseable
-
- org.apache.sshd.common.util.closeable.AbstractInnerCloseable
-
- org.apache.sshd.common.kex.AbstractKexFactoryManager
-
- org.apache.sshd.common.session.helpers.SessionHelper
-
- org.apache.sshd.common.session.helpers.AbstractSession
-
- All Implemented Interfaces:
Closeable
,AutoCloseable
,Channel
,AttributeRepository
,AttributeStore
,MutableUserHolder
,UsernameHolder
,ChannelListenerManager
,ChannelStreamWriterResolver
,ChannelStreamWriterResolverManager
,Closeable
,FactoryManagerHolder
,PortForwardingEventListenerManager
,PortForwardingInformationProvider
,KexExtensionHandlerManager
,KexFactoryManager
,PropertyResolver
,ReservedSessionMessagesManager
,Session
,SessionContext
,SessionDisconnectHandlerManager
,SessionHeartbeatController
,SessionListenerManager
,UnknownChannelReferenceHandlerManager
,SignatureFactoriesHolder
,SignatureFactoriesManager
,ConnectionEndpointsIndicator
- Direct Known Subclasses:
AbstractClientSession
,AbstractServerSession
public abstract class AbstractSession extends SessionHelper
The AbstractSession handles all the basic SSH protocol such as key exchange, authentication, encoding and decoding. Both server side and client side sessions should inherit from this abstract class. Some basic packet processing methods are defined but the actual call to these methods should be done from the
TODO: if there is any very big packet, decoderBuffer and uncompressBuffer will get quite big and they won't be resized down at any time. Though the packet size is really limited by the channel max packet sizehandleMessage(Buffer)
method, which is dependent on the state and side of this session.- Author:
- Apache MINA SSHD Project
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static class
AbstractSession.MessageCodingSettings
Message encoding or decoding settings as determined at the end of a key exchange.-
Nested classes/interfaces inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
AbstractCloseable.State
-
Nested classes/interfaces inherited from interface org.apache.sshd.common.AttributeRepository
AttributeRepository.AttributeKey<T extends Object>
-
Nested classes/interfaces inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
SessionHeartbeatController.HeartbeatType
-
-
Field Summary
-
Fields inherited from class org.apache.sshd.common.session.helpers.SessionHelper
authStart, idleStart, initialKexProposal
-
Fields inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
closeFuture, futureLock, state
-
Fields inherited from class org.apache.sshd.common.util.logging.AbstractLoggingBean
log
-
Fields inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolver
NONE
-
Fields inherited from interface org.apache.sshd.common.PropertyResolver
EMPTY
-
Fields inherited from interface org.apache.sshd.common.session.SessionContext
DEFAULT_SSH_VERSION_PREFIX, FALLBACK_SSH_VERSION_PREFIX, MAX_VERSION_LINE_LENGTH
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
AbstractSession(boolean serverSession, FactoryManager factoryManager, IoSession ioSession)
Create a new session.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description void
addChannelListener(ChannelListener listener)
Add a channel listenervoid
addPortForwardingEventListener(PortForwardingEventListener listener)
Add a port forwarding listenervoid
addSessionListener(SessionListener listener)
Add a session listener.protected void
aeadOutgoingBuffer(Buffer buf, int offset, int len)
protected void
appendOutgoingMac(Buffer buf, int offset, int len)
static void
attachSession(IoSession ioSession, AbstractSession session)
Attach an SSHAbstractSession
to the I/O sessionstatic int
calculatePadLength(int len, int blockSize, boolean etmMode)
protected abstract void
checkKeys()
Indicates the the key exchange is completed and the exchanged keys can now be verified - e.g., client can verify the server's keyprotected KeyExchangeFuture
checkRekey()
Checks if a re-keying is required and if so initiates itprotected Map.Entry<String,String>
comparePreferredKexProposalOption(KexProposalOption option)
Compares the specifiedKexProposalOption
option value for client vs.Buffer
createBuffer(byte cmd, int len)
Create a new buffer for the specified SSH packet and reserve the needed space (5 bytes) for the packet header.protected void
decode()
Decode the incoming buffer and handle packets as needed.protected long
determineRekeyBlockLimit(int inCipherBlockSize, int outCipherBlockSize)
Compute the number of blocks after which we should re-key again.protected void
doHandleMessage(Buffer buffer)
protected boolean
doInvokeUnimplementedMessageHandler(int cmd, Buffer buffer)
protected void
doKexNegotiation()
protected IoWriteFuture
doWritePacket(Buffer buffer)
protected Buffer
encode(Buffer buffer)
Encode a buffer into the SSH protocol.protected void
encryptOutgoingBuffer(Buffer buf, int offset, int len)
ChannelListener
getChannelListenerProxy()
CipherInformation
getCipherInformation(boolean incoming)
protected byte[]
getClientKexData()
Map<KexProposalOption,String>
getClientKexProposals()
String
getClientVersion()
CompressionInformation
getCompressionInformation(boolean incoming)
protected Closeable
getInnerCloseable()
KeyExchange
getKex()
Map<KexProposalOption,String>
getKexNegotiationResult()
KexState
getKexState()
MacInformation
getMacInformation(boolean incoming)
String
getNegotiatedKexParameter(KexProposalOption paramType)
PortForwardingEventListener
getPortForwardingEventListenerProxy()
protected byte[]
getServerKexData()
Map<KexProposalOption,String>
getServerKexProposals()
String
getServerVersion()
<T extends Service>
TgetService(Class<T> clazz)
Get the service of the specified type.protected List<Service>
getServices()
static AbstractSession
getSession(IoSession ioSession)
Retrieve the SSH session from the I/O session.static AbstractSession
getSession(IoSession ioSession, boolean allowNull)
Retrieve the session SSH from the I/O session.byte[]
getSessionId()
SessionListener
getSessionListenerProxy()
protected boolean
handleFirstKexPacketFollows(int cmd, Buffer buffer, boolean followFlag)
protected void
handleKexExtension(int cmd, Buffer buffer)
protected void
handleKexInit(Buffer buffer)
protected void
handleKexMessage(int cmd, Buffer buffer)
protected void
handleMessage(Buffer buffer)
Abstract method for processing incoming decoded packets.protected void
handleNewCompression(int cmd, Buffer buffer)
protected void
handleNewKeys(int cmd, Buffer buffer)
protected void
handleServiceAccept(String serviceName, Buffer buffer)
protected void
handleServiceAccept(Buffer buffer)
protected boolean
handleServiceRequest(String serviceName, Buffer buffer)
protected void
handleServiceRequest(Buffer buffer)
protected CurrentService
initializeCurrentService()
Creates a newCurrentService
instance managing this session's current SSH service.protected KeyExchangeMessageHandler
initializeKeyExchangeMessageHandler()
Creates a newKeyExchangeMessageHandler
instance managing packet sending for this session.protected boolean
isRekeyBlocksCountExceeded()
protected boolean
isRekeyDataSizeExceeded()
protected boolean
isRekeyPacketCountsExceeded()
protected boolean
isRekeyRequired()
protected boolean
isRekeyTimeIntervalExceeded()
void
messageReceived(Readable buffer)
Main input point for the MINA framework.protected Map<KexProposalOption,String>
negotiate()
Compute the negotiated proposals by merging the client and server proposal.protected IoWriteFuture
notImplemented(int cmd, Buffer buffer)
Send aSSH_MSG_UNIMPLEMENTED
packet.protected void
preClose()
Buffer
prepareBuffer(byte cmd, Buffer buffer)
Prepare a new "clean" buffer while reserving the needed space (5 bytes) for the packet header.protected void
prepareNewKeys()
Prepares the new ciphers, macs and compression algorithms according to the negotiated server and client proposals and stores them ininSettings
andoutSettings
.protected Buffer
preProcessEncodeBuffer(int cmd, Buffer buffer)
Invoked by the session before encoding the buffer in order to make sure that it is at least of sizeSSH_PACKET_HEADER_LEN
.protected abstract boolean
readIdentification(Buffer buffer)
Read the other side identification.protected abstract void
receiveKexInit(Map<KexProposalOption,String> proposal, byte[] seed)
protected byte[]
receiveKexInit(Buffer buffer)
protected byte[]
receiveKexInit(Buffer buffer, Map<KexProposalOption,String> proposal)
Receive the remote key exchange init message.KeyExchangeFuture
reExchangeKeys()
Initiate a new key exchange.protected void
refreshConfiguration()
Refresh whatever internal configuration is notfinal
void
removeChannelListener(ChannelListener listener)
Remove a channel listenervoid
removePortForwardingEventListener(PortForwardingEventListener listener)
Remove a port forwarding listenervoid
removeSessionListener(SessionListener listener)
Remove a session listener.Buffer
request(String request, Buffer buffer, long maxWaitMillis)
Send a global request and wait for the response, if the request is sent withwant-reply = true
.GlobalRequestFuture
request(Buffer buffer, String request, GlobalRequestFuture.ReplyHandler replyHandler)
Send a global request and handle the reply asynchronously.protected void
requestFailure(Buffer buffer)
Indicates the reception of aSSH_MSG_REQUEST_FAILURE
messageprotected KeyExchangeFuture
requestNewKeysExchange()
Initiates a new keys exchange if one not already in progressprotected void
requestSuccess(Buffer buffer)
Indicates the reception of aSSH_MSG_REQUEST_SUCCESS
messageprotected int
resolveIgnoreBufferDataLength()
protected Buffer
resolveOutputPacket(Buffer buffer)
protected String
resolveSessionKexProposal(String hostKeyTypes)
protected byte[]
sendKexInit()
protected byte[]
sendKexInit(Map<KexProposalOption,String> proposal)
Send the key exchange initialization packet.protected IoWriteFuture
sendNewKeys()
Send a message to put new keys into use.protected void
setClientKexData(byte[] data)
protected void
setInputEncoding()
Installs the current preparedinSettings
so that they are effective and will be applied to any future incoming packet.protected abstract void
setKexSeed(byte... seed)
protected Map<KexProposalOption,String>
setNegotiationResult(Map<KexProposalOption,String> guess)
protected void
setOutputEncoding()
Installs the current preparedoutSettings
so that they are effective and will be applied to any future outgoing packet.protected void
setServerKexData(byte[] data)
protected void
validateIncomingMac(byte[] data, int offset, int len)
protected void
validateKexState(int cmd, KexState expected)
protected boolean
validateServiceKexState(KexState state)
protected <B extends Buffer>
BvalidateTargetBuffer(int cmd, B buffer)
Makes sure that the buffer used for output is notnull
or one of the session's internal ones used for decoding and uncompressingIoWriteFuture
writePacket(Buffer buffer)
Encode and send the given buffer.IoWriteFuture
writePacket(Buffer buffer, long timeout, TimeUnit unit)
Encode and send the given buffer with the specified timeout.-
Methods inherited from class org.apache.sshd.common.session.helpers.SessionHelper
attributeKeys, calculateNextIgnorePacketCount, checkAuthenticationTimeout, checkForTimeouts, checkIdleTimeout, clearAttributes, computeAttributeIfAbsent, createProposal, disconnect, doInvokeDebugMessageHandler, doInvokeIgnoreMessageHandler, doReadIdentification, exceptionCaught, getAttribute, getAttributesCount, getAuthTimeout, getAuthTimeoutStart, getBoundLocalPortForwards, getBoundRemotePortForward, getChannelStreamWriterResolver, getConnectionService, getFactoryManager, getForwarder, getIdleTimeout, getIdleTimeoutStart, getIoSession, getKexProposal, getLocalForwardsBindings, getParentPropertyResolver, getProperties, getRemoteForwardsBindings, getReservedSessionMessagesHandler, getSessionDisconnectHandler, getStartedLocalPortForwards, getStartedRemotePortForwards, getTimeoutStatus, getUnknownChannelReferenceHandler, getUsername, handleDebug, handleDisconnect, handleDisconnect, handleIgnore, handleUnimplemented, invokeSessionSignaller, isAuthenticated, isLocalPortForwardingStartedForPort, isRemotePortForwardingStartedForPort, isServerSession, mergeProposals, removeAttribute, resetAuthTimeout, resetIdleTimeout, resizeKey, resolveAvailableSignaturesProposal, resolveAvailableSignaturesProposal, resolveChannelStreamWriterResolver, resolveIdentificationString, resolvePeerAddress, resolveReservedSessionMessagesHandler, resolveUnknownChannelReferenceHandler, sendDebugMessage, sendIdentification, sendIgnoreMessage, sendNotImplemented, setAttribute, setAuthenticated, setChannelStreamWriterResolver, setReservedSessionMessagesHandler, setSessionDisconnectHandler, setUnknownChannelReferenceHandler, setUsername, signalDisconnect, signalDisconnect, signalExceptionCaught, signalExceptionCaught, signalNegotiationEnd, signalNegotiationEnd, signalNegotiationOptionsCreated, signalNegotiationOptionsCreated, signalNegotiationStart, signalNegotiationStart, signalPeerIdentificationReceived, signalPeerIdentificationReceived, signalReadPeerIdentificationLine, signalReadPeerIdentificationLine, signalSendIdentification, signalSendIdentification, signalSessionClosed, signalSessionClosed, signalSessionCreated, signalSessionCreated, signalSessionEstablished, signalSessionEstablished, signalSessionEvent, signalSessionEvent, toString
-
Methods inherited from class org.apache.sshd.common.kex.AbstractKexFactoryManager
getCipherFactories, getCompressionFactories, getDelegate, getKexExtensionHandler, getKeyExchangeFactories, getMacFactories, getSignatureFactories, resolveEffectiveFactories, resolveEffectiveProvider, setCipherFactories, setCompressionFactories, setKexExtensionHandler, setKeyExchangeFactories, setMacFactories, setSignatureFactories
-
Methods inherited from class org.apache.sshd.common.util.closeable.AbstractInnerCloseable
doCloseGracefully, doCloseImmediately
-
Methods inherited from class org.apache.sshd.common.util.closeable.AbstractCloseable
addCloseFutureListener, builder, close, getFutureLock, isClosed, isClosing, removeCloseFutureListener
-
Methods inherited from class org.apache.sshd.common.util.logging.AbstractLoggingBean
debug, debug, debug, debug, debug, error, error, error, error, error, getSimplifiedLogger, info, info, warn, warn, warn, warn, warn, warn, warn, warn
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolverManager
resolveChannelStreamWriter
-
Methods inherited from interface org.apache.sshd.common.Closeable
addCloseFutureListener, close, close, isClosed, isClosing, isOpen, removeCloseFutureListener
-
Methods inherited from interface org.apache.sshd.common.kex.extension.KexExtensionHandlerManager
getKexExtensionHandler, setKexExtensionHandler
-
Methods inherited from interface org.apache.sshd.common.kex.KexFactoryManager
getCipherFactories, getCipherFactoriesNameList, getCipherFactoriesNames, getCompressionFactories, getCompressionFactoriesNameList, getCompressionFactoriesNames, getKeyExchangeFactories, getMacFactories, getMacFactoriesNameList, getMacFactoriesNames, setCipherFactories, setCipherFactoriesNameList, setCipherFactoriesNames, setCipherFactoriesNames, setCompressionFactories, setCompressionFactoriesNameList, setCompressionFactoriesNames, setCompressionFactoriesNames, setKeyExchangeFactories, setMacFactories, setMacFactoriesNameList, setMacFactoriesNames, setMacFactoriesNames
-
Methods inherited from interface org.apache.sshd.common.PropertyResolver
getBoolean, getBooleanProperty, getCharset, getInteger, getIntProperty, getLong, getLongProperty, getObject, getString, getStringProperty, isEmpty
-
Methods inherited from interface org.apache.sshd.common.session.Session
createBuffer, getLocalAddress, getRemoteAddress, request, request, resolveAttribute, startService, writePacket, writePacket
-
Methods inherited from interface org.apache.sshd.common.session.SessionHeartbeatController
disableSessionHeartbeat, getSessionHeartbeatInterval, getSessionHeartbeatType, setSessionHeartbeat, setSessionHeartbeat
-
Methods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesHolder
getSignatureFactories, getSignatureFactoriesNameList, getSignatureFactoriesNames
-
Methods inherited from interface org.apache.sshd.common.signature.SignatureFactoriesManager
setSignatureFactories, setSignatureFactoriesNameList, setSignatureFactoriesNames, setSignatureFactoriesNames
-
-
-
-
Field Detail
-
SESSION
public static final String SESSION
Name of the property where this session is stored in the attributes of the underlying MINA session. SeegetSession(IoSession, boolean)
andattachSession(IoSession, AbstractSession)
.- See Also:
- Constant Field Values
-
random
protected final Random random
The pseudo random generator
-
sessionListeners
protected final Collection<SessionListener> sessionListeners
Session listeners container
-
sessionListenerProxy
protected final SessionListener sessionListenerProxy
-
channelListeners
protected final Collection<ChannelListener> channelListeners
Channel events listener container
-
channelListenerProxy
protected final ChannelListener channelListenerProxy
-
tunnelListeners
protected final Collection<PortForwardingEventListener> tunnelListeners
Port forwarding events listener container
-
tunnelListenerProxy
protected final PortForwardingEventListener tunnelListenerProxy
-
sessionId
protected byte[] sessionId
-
serverVersion
protected String serverVersion
-
clientVersion
protected String clientVersion
-
serverProposal
protected final Map<KexProposalOption,String> serverProposal
-
unmodServerProposal
protected final Map<KexProposalOption,String> unmodServerProposal
-
clientProposal
protected final Map<KexProposalOption,String> clientProposal
-
unmodClientProposal
protected final Map<KexProposalOption,String> unmodClientProposal
-
negotiationResult
protected final Map<KexProposalOption,String> negotiationResult
-
unmodNegotiationResult
protected final Map<KexProposalOption,String> unmodNegotiationResult
-
kex
protected KeyExchange kex
-
firstKexPacketFollows
protected Boolean firstKexPacketFollows
-
initialKexDone
protected boolean initialKexDone
-
kexState
protected final AtomicReference<KexState> kexState
Holds the current key exchange state.
-
kexFutureHolder
protected final AtomicReference<DefaultKeyExchangeFuture> kexFutureHolder
-
kexInitializedFuture
protected DefaultKeyExchangeFuture kexInitializedFuture
-
outCipher
protected Cipher outCipher
-
inCipher
protected Cipher inCipher
-
outCipherSize
protected int outCipherSize
-
inCipherSize
protected int inCipherSize
-
outMac
protected Mac outMac
-
inMac
protected Mac inMac
-
outMacSize
protected int outMacSize
-
inMacSize
protected int inMacSize
-
inMacResult
protected byte[] inMacResult
-
outCompression
protected Compression outCompression
-
inCompression
protected Compression inCompression
-
seqi
protected long seqi
Input packet sequence number.
-
seqo
protected long seqo
Output packet sequence number.
-
uncompressBuffer
protected SessionWorkBuffer uncompressBuffer
-
decoderBuffer
protected final SessionWorkBuffer decoderBuffer
-
decoderState
protected int decoderState
-
decoderLength
protected int decoderLength
-
encodeLock
protected final Object encodeLock
-
decodeLock
protected final Object decodeLock
-
requestLock
protected final Object requestLock
-
kexHandler
protected final KeyExchangeMessageHandler kexHandler
TheKeyExchangeMessageHandler
instance also serves as lock protectingkexState
changes from DONE to INIT or RUN, and from KEYS to DONE.
-
inPacketsCount
protected final AtomicLong inPacketsCount
-
outPacketsCount
protected final AtomicLong outPacketsCount
-
inBytesCount
protected final AtomicLong inBytesCount
-
outBytesCount
protected final AtomicLong outBytesCount
-
inBlocksCount
protected final AtomicLong inBlocksCount
-
outBlocksCount
protected final AtomicLong outBlocksCount
-
lastKeyTimeValue
protected final AtomicReference<Instant> lastKeyTimeValue
-
maxRekyPackets
protected long maxRekyPackets
-
maxRekeyBytes
protected long maxRekeyBytes
-
maxRekeyInterval
protected Duration maxRekeyInterval
-
inSettings
protected AbstractSession.MessageCodingSettings inSettings
Resulting message coding settings at the end of a key exchange for incoming messages.- See Also:
prepareNewKeys()
,setInputEncoding()
-
outSettings
protected AbstractSession.MessageCodingSettings outSettings
Resulting message coding settings at the end of a key exchange for outgoing messages.- See Also:
prepareNewKeys()
,setOutputEncoding()
-
currentService
protected final CurrentService currentService
-
ignorePacketDataLength
protected int ignorePacketDataLength
-
ignorePacketsFrequency
protected long ignorePacketsFrequency
-
ignorePacketsVariance
protected int ignorePacketsVariance
-
maxRekeyBlocks
protected final AtomicLong maxRekeyBlocks
-
ignorePacketsCount
protected final AtomicLong ignorePacketsCount
-
-
Constructor Detail
-
AbstractSession
protected AbstractSession(boolean serverSession, FactoryManager factoryManager, IoSession ioSession)
Create a new session.- Parameters:
serverSession
-true
if this is a server session,false
if client onefactoryManager
- the factory managerioSession
- the underlying I/O session
-
-
Method Detail
-
initializeKeyExchangeMessageHandler
protected KeyExchangeMessageHandler initializeKeyExchangeMessageHandler()
Creates a newKeyExchangeMessageHandler
instance managing packet sending for this session.This initialization method is invoked once from the
AbstractSession
constructor. Do not rely on subclass fields being initialized.- Returns:
- a new
KeyExchangeMessageHandler
instance for the session
-
initializeCurrentService
protected CurrentService initializeCurrentService()
Creates a newCurrentService
instance managing this session's current SSH service.This initialization method is invoked once from the
AbstractSession
constructor. Do not rely on subclass fields being initialized.- Returns:
- a new
CurrentService
instance for the session
-
calculatePadLength
public static int calculatePadLength(int len, int blockSize, boolean etmMode)
- Parameters:
len
- The packet payload sizeblockSize
- The cipher block sizeetmMode
- Whether using "encrypt-then-MAC" mode- Returns:
- The required padding length
-
getServerVersion
public String getServerVersion()
-
getServerKexProposals
public Map<KexProposalOption,String> getServerKexProposals()
-
getClientVersion
public String getClientVersion()
-
getClientKexProposals
public Map<KexProposalOption,String> getClientKexProposals()
-
getKex
public KeyExchange getKex()
- Returns:
- The current
KeyExchange
in progress -null
if KEX not started or successfully completed
-
getKexState
public KexState getKexState()
-
getSessionId
public byte[] getSessionId()
-
getKexNegotiationResult
public Map<KexProposalOption,String> getKexNegotiationResult()
-
getNegotiatedKexParameter
public String getNegotiatedKexParameter(KexProposalOption paramType)
-
getCipherInformation
public CipherInformation getCipherInformation(boolean incoming)
-
getCompressionInformation
public CompressionInformation getCompressionInformation(boolean incoming)
-
getMacInformation
public MacInformation getMacInformation(boolean incoming)
-
messageReceived
public void messageReceived(Readable buffer) throws Exception
Main input point for the MINA framework.
This method will be called each time new data is received on the socket and will append it to the input buffer before calling the
decode()
method.- Parameters:
buffer
- the new buffer received- Throws:
Exception
- if an error occurs while decoding or handling the data
-
refreshConfiguration
protected void refreshConfiguration()
Refresh whatever internal configuration is notfinal
-
handleMessage
protected void handleMessage(Buffer buffer) throws Exception
Abstract method for processing incoming decoded packets. The given buffer will hold the decoded packet, starting from the command byte at the read position.- Parameters:
buffer
- TheBuffer
containing the packet - it may be re-used to generate the response once request has been decoded- Throws:
Exception
- if an exception occurs while handling this packet.- See Also:
doHandleMessage(Buffer)
-
handleFirstKexPacketFollows
protected boolean handleFirstKexPacketFollows(int cmd, Buffer buffer, boolean followFlag)
-
comparePreferredKexProposalOption
protected Map.Entry<String,String> comparePreferredKexProposalOption(KexProposalOption option)
Compares the specifiedKexProposalOption
option value for client vs. server- Parameters:
option
- The option to check- Returns:
null
if option is equal, otherwise a key/value pair where key=client option value and value=the server-side one
-
sendNewKeys
protected IoWriteFuture sendNewKeys() throws Exception
Send a message to put new keys into use.- Returns:
- An
IoWriteFuture
that can be used to wait and check the result of sending the packet - Throws:
Exception
- if an error occurs sending the message
-
handleKexMessage
protected void handleKexMessage(int cmd, Buffer buffer) throws Exception
- Throws:
Exception
-
handleKexExtension
protected void handleKexExtension(int cmd, Buffer buffer) throws Exception
- Throws:
Exception
-
handleNewCompression
protected void handleNewCompression(int cmd, Buffer buffer) throws Exception
- Throws:
Exception
-
handleServiceRequest
protected void handleServiceRequest(Buffer buffer) throws Exception
- Throws:
Exception
-
handleServiceRequest
protected boolean handleServiceRequest(String serviceName, Buffer buffer) throws Exception
- Throws:
Exception
-
validateServiceKexState
protected boolean validateServiceKexState(KexState state)
-
handleServiceAccept
protected void handleServiceAccept(Buffer buffer) throws Exception
- Throws:
Exception
-
handleServiceAccept
protected void handleServiceAccept(String serviceName, Buffer buffer) throws Exception
- Throws:
Exception
-
handleNewKeys
protected void handleNewKeys(int cmd, Buffer buffer) throws Exception
- Throws:
Exception
-
validateKexState
protected void validateKexState(int cmd, KexState expected)
-
getInnerCloseable
protected Closeable getInnerCloseable()
- Specified by:
getInnerCloseable
in classAbstractInnerCloseable
-
preClose
protected void preClose()
- Overrides:
preClose
in classAbstractCloseable
-
getService
public <T extends Service> T getService(Class<T> clazz)
Description copied from interface:Session
Get the service of the specified type. If the service is not of the specified class, an IllegalStateException will be thrown.- Type Parameters:
T
- The genericService
type- Parameters:
clazz
- The service class- Returns:
- The service instance
-
preProcessEncodeBuffer
protected Buffer preProcessEncodeBuffer(int cmd, Buffer buffer) throws IOException
Description copied from class:SessionHelper
Invoked by the session before encoding the buffer in order to make sure that it is at least of sizeSSH_PACKET_HEADER_LEN
. This is required in order to efficiently handle the encoding. If necessary, it re-allocates a new buffer and returns it instead.- Overrides:
preProcessEncodeBuffer
in classSessionHelper
- Parameters:
cmd
- The command stored in the bufferbuffer
- The originalBuffer
- assumed to be properly formatted and be of at least the required minimum length.- Returns:
- The adjusted
Buffer
. Note: users may use this method to totally alter the contents of the buffer being sent but it is highly discouraged as it may have unexpected results. - Throws:
IOException
- If failed to process the buffer
-
writePacket
public IoWriteFuture writePacket(Buffer buffer) throws IOException
Description copied from interface:Session
Encode and send the given buffer. The buffer has to have 5 bytes free at the beginning to allow the encoding to take place. Also, the write position of the buffer has to be set to the position of the last byte to write.- Parameters:
buffer
- the buffer to encode and send- Returns:
- An
IoWriteFuture
that can be used to check when the packet has actually been sent - Throws:
IOException
- if an error occurred when encoding sending the packet
-
writePacket
public IoWriteFuture writePacket(Buffer buffer, long timeout, TimeUnit unit) throws IOException
Description copied from interface:Session
Encode and send the given buffer with the specified timeout. If the buffer could not be written before the timeout elapses, the returnedIoWriteFuture
will be set with aTimeoutException
exception to indicate a timeout.- Parameters:
buffer
- the buffer to encode and spendtimeout
- the timeoutunit
- the time unit of the timeout parameter- Returns:
- a future that can be used to check when the packet has actually been sent
- Throws:
IOException
- if an error occurred when encoding or sending the packet
-
resolveOutputPacket
protected Buffer resolveOutputPacket(Buffer buffer) throws IOException
- Throws:
IOException
-
doWritePacket
protected IoWriteFuture doWritePacket(Buffer buffer) throws IOException
- Throws:
IOException
-
resolveIgnoreBufferDataLength
protected int resolveIgnoreBufferDataLength()
-
request
public Buffer request(String request, Buffer buffer, long maxWaitMillis) throws IOException
Description copied from interface:Session
Send a global request and wait for the response, if the request is sent withwant-reply = true
.- Parameters:
request
- the request name - used mainly for logging and debuggingbuffer
- the buffer containing the global requestmaxWaitMillis
- maximum time in milliseconds to wait for the request to finish - must be positive- Returns:
- the return buffer if the request was successful,
null
otherwise. - Throws:
IOException
- if an error occurred when encoding or sending the packetSocketTimeoutException
- If no response received within specified timeout
-
request
public GlobalRequestFuture request(Buffer buffer, String request, GlobalRequestFuture.ReplyHandler replyHandler) throws IOException
Description copied from interface:Session
Send a global request and handle the reply asynchronously. Ifwant-reply = true
, pass the receivedBuffer
to the givenGlobalRequestFuture.ReplyHandler
, which may execute in a different thread.- want-reply == true && replyHandler != null
- The returned future is fulfilled with
null
when the request was sent, or with an exception if the request could not be sent. ThereplyHandler
is invoked once the reply is received, with the SSH reply code and the data received. - want-reply == true && replyHandler == null
- The returned future is fulfilled with an exception if the request could not be sent, or a failure reply was received. If a success reply was received, the future is fulfilled with the received data buffer.
- want-reply == false
- The returned future is fulfilled with an empty
Buffer
when the request was sent, or with an exception if the request could not be sent. If a reply handler is given, it is invoked with that empty buffer. The handler is not invoked if sending the request failed.
- Parameters:
buffer
- theBuffer
containing the global request, with thewant-reply
flag set as appropriaterequest
- the request namereplyHandler
-GlobalRequestFuture.ReplyHandler
for handling the reply; may benull
- Throws:
IOException
- if an error occurred while encoding or sending the packet
-
doInvokeUnimplementedMessageHandler
protected boolean doInvokeUnimplementedMessageHandler(int cmd, Buffer buffer) throws Exception
- Overrides:
doInvokeUnimplementedMessageHandler
in classSessionHelper
- Parameters:
cmd
- The unimplemented commandbuffer
- The inputBuffer
- Returns:
- Result of invoking
handleUnimplementedMessage
- Throws:
Exception
- if failed to handle the message
-
createBuffer
public Buffer createBuffer(byte cmd, int len)
Description copied from interface:Session
Create a new buffer for the specified SSH packet and reserve the needed space (5 bytes) for the packet header.- Parameters:
cmd
- The SSH command to initialize the buffer withlen
- Estimated number of bytes the buffer will hold, 0 if unknown.- Returns:
- a new buffer ready for write
- See Also:
Session.prepareBuffer(byte, Buffer)
-
prepareBuffer
public Buffer prepareBuffer(byte cmd, Buffer buffer)
Description copied from interface:Session
Prepare a new "clean" buffer while reserving the needed space (5 bytes) for the packet header.- Parameters:
cmd
- The SSH command to initialize the buffer withbuffer
- TheBuffer
instance to initialize- Returns:
- The initialized buffer
-
validateTargetBuffer
protected <B extends Buffer> B validateTargetBuffer(int cmd, B buffer)
Makes sure that the buffer used for output is notnull
or one of the session's internal ones used for decoding and uncompressing- Type Parameters:
B
- TheBuffer
type being validated- Parameters:
cmd
- The most likely command this buffer refers to (not guaranteed to be correct)buffer
- The buffer to be examined- Returns:
- The validated target instance - default same as input
- Throws:
IllegalArgumentException
- if any of the conditions is violated
-
encode
protected Buffer encode(Buffer buffer) throws IOException
Encode a buffer into the SSH protocol. Note: This method must be called inside asynchronized
block usingencodeLock
.- Parameters:
buffer
- the buffer to encode- Returns:
- The encoded buffer - may be different than original if input buffer does not have enough room
for
SshConstants.SSH_PACKET_HEADER_LEN
, in which case a substitute buffer will be created and used. - Throws:
IOException
- if an exception occurs during the encoding process
-
aeadOutgoingBuffer
protected void aeadOutgoingBuffer(Buffer buf, int offset, int len) throws Exception
- Throws:
Exception
-
appendOutgoingMac
protected void appendOutgoingMac(Buffer buf, int offset, int len) throws Exception
- Throws:
Exception
-
encryptOutgoingBuffer
protected void encryptOutgoingBuffer(Buffer buf, int offset, int len) throws Exception
- Throws:
Exception
-
decode
protected void decode() throws Exception
Decode the incoming buffer and handle packets as needed.- Throws:
Exception
- If failed to decode
-
validateIncomingMac
protected void validateIncomingMac(byte[] data, int offset, int len) throws Exception
- Throws:
Exception
-
readIdentification
protected abstract boolean readIdentification(Buffer buffer) throws Exception
Read the other side identification. This method is specific to the client or server side, but both should callSessionHelper.doReadIdentification(Buffer, boolean)
and store the result in the needed property.
-
sendKexInit
protected byte[] sendKexInit(Map<KexProposalOption,String> proposal) throws Exception
Send the key exchange initialization packet. This packet contains random data along with our proposal.- Parameters:
proposal
- our proposal for key exchange negotiation- Returns:
- the sent packet data which must be kept for later use when deriving the session keys
- Throws:
Exception
- if an error occurred sending the packet
-
receiveKexInit
protected byte[] receiveKexInit(Buffer buffer, Map<KexProposalOption,String> proposal) throws Exception
Receive the remote key exchange init message. The packet data is returned for later use.
-
prepareNewKeys
protected void prepareNewKeys() throws Exception
Prepares the new ciphers, macs and compression algorithms according to the negotiated server and client proposals and stores them ininSettings
andoutSettings
. The new settings do not take effect yet; usesetInputEncoding()
orsetOutputEncoding()
for that.- Throws:
Exception
- if an error occurs
-
setOutputEncoding
protected void setOutputEncoding() throws Exception
Installs the current preparedoutSettings
so that they are effective and will be applied to any future outgoing packet. ClearsoutSettings
.- Throws:
Exception
- on errors
-
setInputEncoding
protected void setInputEncoding() throws Exception
Installs the current preparedinSettings
so that they are effective and will be applied to any future incoming packet. ClearsinSettings
.- Throws:
Exception
- on errors
-
determineRekeyBlockLimit
protected long determineRekeyBlockLimit(int inCipherBlockSize, int outCipherBlockSize)
Compute the number of blocks after which we should re-key again. See RFC 4344.- Parameters:
inCipherBlockSize
- block size of the input cipheroutCipherBlockSize
- block size of the output cipher- Returns:
- the number of block after which re-keying occur at the latest
- See Also:
- RFC 4344, section 3.2
-
notImplemented
protected IoWriteFuture notImplemented(int cmd, Buffer buffer) throws Exception
Send aSSH_MSG_UNIMPLEMENTED
packet. This packet should contain the sequence id of the unsupported packet: this number is assumed to be the last packet received.- Parameters:
cmd
- The un-implemented command valuebuffer
- TheBuffer
that contains the command. Note: the buffer's read position is just beyond the command.- Returns:
- An
IoWriteFuture
that can be used to wait for packet write completion -null
if the registeredReservedSessionMessagesHandler
decided to handle the command internally - Throws:
Exception
- if an error occurred while handling the packet.- See Also:
SessionHelper.sendNotImplemented(long)
-
negotiate
protected Map<KexProposalOption,String> negotiate() throws Exception
Compute the negotiated proposals by merging the client and server proposal. The negotiated proposal will also be stored in thenegotiationResult
property.
-
setNegotiationResult
protected Map<KexProposalOption,String> setNegotiationResult(Map<KexProposalOption,String> guess)
-
requestSuccess
protected void requestSuccess(Buffer buffer) throws Exception
Indicates the reception of aSSH_MSG_REQUEST_SUCCESS
message
-
requestFailure
protected void requestFailure(Buffer buffer) throws Exception
Indicates the reception of aSSH_MSG_REQUEST_FAILURE
message
-
addSessionListener
public void addSessionListener(SessionListener listener)
Description copied from interface:SessionListenerManager
Add a session listener.- Parameters:
listener
- TheSessionListener
to add - notnull
-
removeSessionListener
public void removeSessionListener(SessionListener listener)
Description copied from interface:SessionListenerManager
Remove a session listener.- Parameters:
listener
- TheSessionListener
to remove
-
getSessionListenerProxy
public SessionListener getSessionListenerProxy()
- Returns:
- A (never
null
proxySessionListener
that represents all the currently registered listeners. Any method invocation on the proxy is replicated to the currently registered listeners
-
addChannelListener
public void addChannelListener(ChannelListener listener)
Description copied from interface:ChannelListenerManager
Add a channel listener- Parameters:
listener
- TheChannelListener
to add - notnull
-
removeChannelListener
public void removeChannelListener(ChannelListener listener)
Description copied from interface:ChannelListenerManager
Remove a channel listener- Parameters:
listener
- TheChannelListener
to remove
-
getChannelListenerProxy
public ChannelListener getChannelListenerProxy()
- Returns:
- A (never
null
proxyChannelListener
that represents all the currently registered listeners. Any method invocation on the proxy is replicated to the currently registered listeners
-
getPortForwardingEventListenerProxy
public PortForwardingEventListener getPortForwardingEventListenerProxy()
- Returns:
- A proxy listener representing all the currently registered listener through this manager
-
addPortForwardingEventListener
public void addPortForwardingEventListener(PortForwardingEventListener listener)
Description copied from interface:PortForwardingEventListenerManager
Add a port forwarding listener- Parameters:
listener
- ThePortForwardingEventListener
to add - nevernull
-
removePortForwardingEventListener
public void removePortForwardingEventListener(PortForwardingEventListener listener)
Description copied from interface:PortForwardingEventListenerManager
Remove a port forwarding listener- Parameters:
listener
- ThePortForwardingEventListener
to remove - ignored ifnull
-
reExchangeKeys
public KeyExchangeFuture reExchangeKeys() throws IOException
Description copied from interface:Session
Initiate a new key exchange.- Returns:
- A
KeyExchangeFuture
for awaiting the completion of the exchange - Throws:
IOException
- If failed to request keys re-negotiation
-
checkRekey
protected KeyExchangeFuture checkRekey() throws Exception
Checks if a re-keying is required and if so initiates it- Returns:
- A
KeyExchangeFuture
to wait for the initiated exchange ornull
if no need to re-key or an exchange is already in progress - Throws:
Exception
- If failed load/generate the keys or send the request- See Also:
isRekeyRequired()
,requestNewKeysExchange()
-
requestNewKeysExchange
protected KeyExchangeFuture requestNewKeysExchange() throws Exception
Initiates a new keys exchange if one not already in progress- Returns:
- A
KeyExchangeFuture
to wait for the initiated exchange ornull
if an exchange is already in progress - Throws:
Exception
- If failed to load/generate the keys or send the request
-
isRekeyRequired
protected boolean isRekeyRequired()
-
isRekeyTimeIntervalExceeded
protected boolean isRekeyTimeIntervalExceeded()
-
isRekeyPacketCountsExceeded
protected boolean isRekeyPacketCountsExceeded()
-
isRekeyDataSizeExceeded
protected boolean isRekeyDataSizeExceeded()
-
isRekeyBlocksCountExceeded
protected boolean isRekeyBlocksCountExceeded()
-
resolveSessionKexProposal
protected String resolveSessionKexProposal(String hostKeyTypes) throws IOException
- Overrides:
resolveSessionKexProposal
in classSessionHelper
- Throws:
IOException
-
getClientKexData
protected byte[] getClientKexData()
-
setClientKexData
protected void setClientKexData(byte[] data)
-
getServerKexData
protected byte[] getServerKexData()
-
setServerKexData
protected void setServerKexData(byte[] data)
-
setKexSeed
protected abstract void setKexSeed(byte... seed)
- Parameters:
seed
- The result of the KEXINIT handshake - required for correct session key establishment
-
checkKeys
protected abstract void checkKeys() throws IOException
Indicates the the key exchange is completed and the exchanged keys can now be verified - e.g., client can verify the server's key- Throws:
IOException
- If validation failed
-
receiveKexInit
protected abstract void receiveKexInit(Map<KexProposalOption,String> proposal, byte[] seed) throws IOException
- Throws:
IOException
-
getSession
public static AbstractSession getSession(IoSession ioSession) throws MissingAttachedSessionException
Retrieve the SSH session from the I/O session. If the session has not been attached, an exception will be thrown- Parameters:
ioSession
- TheIoSession
- Returns:
- The SSH session attached to the I/O session
- Throws:
MissingAttachedSessionException
- if no attached SSH session- See Also:
getSession(IoSession, boolean)
-
attachSession
public static void attachSession(IoSession ioSession, AbstractSession session) throws MultipleAttachedSessionException
Attach an SSHAbstractSession
to the I/O session- Parameters:
ioSession
- TheIoSession
session
- The SSH session to attach- Throws:
MultipleAttachedSessionException
- If a previous session already attached
-
getSession
public static AbstractSession getSession(IoSession ioSession, boolean allowNull) throws MissingAttachedSessionException
Retrieve the session SSH from the I/O session. If the session has not been attached and allowNull isfalse
, an exception will be thrown, otherwise anull
will be returned.- Parameters:
ioSession
- TheIoSession
allowNull
- Iftrue
, anull
value may be returned if no session is attached- Returns:
- the session attached to the I/O session or
null
- Throws:
MissingAttachedSessionException
- if no attached session and allowNull=false
-
-