Top Description Inners Fields Constructors Methods
org.apache.sshd.common.session.helpers

public abstract Class AbstractSession

extends SessionHelper
Class Inheritance
Known Direct Subclasses
org.apache.sshd.server.session.AbstractServerSession, org.apache.sshd.client.session.AbstractClientSession
Annotations
@SuppressWarnings:checkstyle:MethodCount
Imports
java.io.IOException, .InterruptedIOException, java.net.ProtocolException, .SocketTimeoutException, java.nio.charset.StandardCharsets, java.security.GeneralSecurityException, java.time.Duration, .Instant, java.util.AbstractMap.SimpleImmutableEntry, .ArrayList, .Arrays, .Collection, .Collections, .Deque, .EnumMap, .LinkedHashSet, .List, .Map, .Objects, .Set, java.util.concurrent.ConcurrentHashMap, .ConcurrentLinkedDeque, .CopyOnWriteArraySet, .ScheduledExecutorService, .ScheduledFuture, .TimeUnit, .TimeoutException, java.util.concurrent.atomic.AtomicLong, .AtomicReference, java.util.function.LongConsumer, java.util.logging.Level, java.util.stream.Collectors, org.apache.sshd.common.Closeable, .Factory, .FactoryManager, .NamedFactory, .NamedResource, .RuntimeSshException, .Service, .SshConstants, .SshException, org.apache.sshd.common.channel.ChannelListener, org.apache.sshd.common.cipher.Cipher, .CipherInformation, org.apache.sshd.common.compression.Compression, .CompressionInformation, org.apache.sshd.common.digest.Digest, org.apache.sshd.common.forward.PortForwardingEventListener, org.apache.sshd.common.future.DefaultKeyExchangeFuture, .DefaultSshFuture, .GlobalRequestFuture, .KeyExchangeFuture, org.apache.sshd.common.global.GlobalRequestException, org.apache.sshd.common.io.IoSession, .IoWriteFuture, org.apache.sshd.common.kex.KexProposalOption, .KexState, .KeyExchange, .KeyExchangeFactory, org.apache.sshd.common.kex.extension.KexExtensionHandler, .KexExtensionHandler.AvailabilityPhase, .KexExtensionHandler.KexPhase, .KexExtensions, org.apache.sshd.common.mac.Mac, .MacInformation, org.apache.sshd.common.random.Random, org.apache.sshd.common.session.ReservedSessionMessagesHandler, .SessionDisconnectHandler, .SessionListener, .SessionWorkBuffer, org.apache.sshd.common.util.EventListenerUtils, .ExceptionUtils, .GenericUtils, .NumberUtils, .Readable, .ValidateUtils, org.apache.sshd.common.util.buffer.Buffer, .BufferUtils, .ByteArrayBuffer, org.apache.sshd.common.util.threads.ThreadUtils, org.apache.sshd.core.CoreModuleProperties

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 handleMessage(Buffer) method, which is dependent on the state and side of this session.

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 size

Author
Apache MINA SSHD Project

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static enum
protected static class
AbstractSession.MessageCodingSettings

Message encoding or decoding settings as determined at the end of a key exchange.

Field Summary

Modifier and TypeField and Description
protected final ChannelListener
protected final Collection<ChannelListener>
channelListeners

Channel events listener container

private byte[]
protected final Map<KexProposalOption, String>
protected String
protected final CurrentService
protected final Object
protected final SessionWorkBuffer
protected int
protected int
protected SshException
protected final Object
protected Boolean
private final Map<Buffer, LongConsumer>
protected int
protected final AtomicLong
protected long
protected int
protected final AtomicLong
protected final AtomicLong
protected Cipher
protected int
protected Compression
protected boolean
protected long
protected Mac
protected byte[]
protected int
protected final AtomicLong
protected AbstractSession.MessageCodingSettings
inSettings

Resulting message coding settings at the end of a key exchange for incoming messages.

protected KeyExchange
protected final AtomicReference<DefaultKeyExchangeFuture>
protected final KeyExchangeMessageHandler
kexHandler

The KeyExchangeMessageHandler instance also serves as lock protecting kexState changes from DONE to INIT or RUN, and from KEYS to DONE.

protected DefaultKeyExchangeFuture
protected final AtomicReference<KexState>
kexState

Holds the current key exchange state.

protected final AtomicReference<Instant>
protected final AtomicLong
protected long
protected Duration
protected long
protected final Map<KexProposalOption, String>
protected final AtomicLong
protected final AtomicLong
protected Cipher
protected int
protected Compression
protected Mac
protected int
protected final AtomicLong
protected AbstractSession.MessageCodingSettings
outSettings

Resulting message coding settings at the end of a key exchange for outgoing messages.

private final Deque<GlobalRequestFuture>
pendingGlobalRequests

Used to wait for results of global requests sent with want-reply = true.

protected final Random
random

The pseudo random generator

protected final Object
protected long
seqi

Input packet sequence number.

protected long
seqo

Output packet sequence number.

private byte[]
protected final Map<KexProposalOption, String>
protected String
public static final String
SESSION

Name of the property where this session is stored in the attributes of the underlying MINA session.

protected byte[]
protected final SessionListener
protected final Collection<SessionListener>
sessionListeners

Session listeners container

protected boolean
strictKex

"Strict KEX" is a mitigation for the "Terrapin attack".

protected final PortForwardingEventListener
protected final Collection<PortForwardingEventListener>
tunnelListeners

Port forwarding events listener container

protected SessionWorkBuffer
protected final Map<KexProposalOption, String>
protected final Map<KexProposalOption, String>
protected final Map<KexProposalOption, String>
Inherited from org.apache.sshd.common.session.helpers.SessionHelper:
authStartidleStartinitialKexProposal

Constructor Summary

AccessConstructor and Description
protected
AbstractSession(boolean
true if this is a server session, false if client one
serverSession
,
FactoryManager
the factory manager
factoryManager
,
IoSession
the underlying I/O session
ioSession
)

Create a new session.

Method Summary

Modifier and TypeMethod and Description
public void
public void
public void
protected void
aeadOutgoingBuffer(Buffer buf, int offset, int len)

protected void
appendOutgoingMac(Buffer buf, int offset, int len)

public static void
attachSession(IoSession ioSession, AbstractSession
The SSH session to attach
session
)

Attach an SSH AbstractSession to the I/O session

public static int

Returns:

The required padding length
calculatePadLength
(int
The packet payload size
len
,
int
The cipher block size
blockSize
,
boolean
Whether using "encrypt-then-MAC" mode
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 key

protected KeyExchangeFuture

Returns:

A KeyExchangeFuture to wait for the initiated exchange or null if no need to re-key or an exchange is already in progress
checkRekey
()

Checks if a re-keying is required and if so initiates it

protected Map.Entry<String, String>

Returns:

null if option is equal, otherwise a key/value pair where key=client option value and value=the server-side one
comparePreferredKexProposalOption
(KexProposalOption
The option to check
option
)

Compares the specified KexProposalOption option value for client vs. server

public Buffer
createBuffer(byte
The SSH command to initialize the buffer with
cmd
,
int
Estimated number of bytes the buffer will hold, 0 if unknown.
len
)

Implements org.apache.sshd.common.session.Session.createBuffer.

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

Returns:

the number of block after which re-keying occur at the latest
determineRekeyBlockLimit
(int
block size of the input cipher
inCipherBlockSize
,
int
block size of the output cipher
outCipherBlockSize
)

Compute the number of blocks after which we should re-key again.

protected void
protected boolean
protected void
protected Map<KexProposalOption, String>
protected IoWriteFuture
protected Buffer

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.
encode
(Buffer
the buffer to encode
buffer
)

Encode a buffer into the SSH protocol

Note

This method must be called inside a synchronized block using encodeLock.

protected void
encryptOutgoingBuffer(Buffer buf, int offset, int len)

protected void
failStrictKex(int cmd)

public ChannelListener
public CipherInformation
getCipherInformation(boolean
If true then the cipher for the incoming data, otherwise for the outgoing data
incoming
)

Implements org.apache.sshd.common.session.SessionContext.getCipherInformation.

Retrieves current cipher information - Note: may change if key re-exchange executed

protected byte[]
public Map<KexProposalOption, String>
public String
getClientVersion()

Implements org.apache.sshd.common.session.SessionContext.getClientVersion.

Retrieve the client version for this session.

public CompressionInformation
getCompressionInformation(boolean
If true then the compression for the incoming data, otherwise for the outgoing data
incoming
)

Implements org.apache.sshd.common.session.SessionContext.getCompressionInformation.

Retrieves current compression information - Note: may change if key re-exchange executed

protected Closeable
public KeyExchange
public Map<KexProposalOption, String>
public KexState
public MacInformation
getMacInformation(boolean
If true then the MAC for the incoming data, otherwise for the outgoing data
incoming
)

Implements org.apache.sshd.common.session.SessionContext.getMacInformation.

Retrieves current MAC information - Note: may change if key re-exchange executed

public String
getNegotiatedKexParameter(KexProposalOption
The request KexProposalOption value - ignored if null
paramType
)

Implements org.apache.sshd.common.session.SessionContext.getNegotiatedKexParameter.

Retrieve one of the negotiated values during the KEX stage

public PortForwardingEventListener
protected byte[]
public Map<KexProposalOption, String>
public String
getServerVersion()

Implements org.apache.sshd.common.session.SessionContext.getServerVersion.

Retrieve the server version for this session.

public <T extends Service> T
getService(Class<T>
The service class
clazz
)

Implements org.apache.sshd.common.session.Session.getService.

Get the service of the specified type.

protected List<Service>
public static AbstractSession

Returns:

The SSH session attached to the I/O session
getSession
(IoSession ioSession)

Retrieve the SSH session from the I/O session.

public static AbstractSession

Returns:

the session attached to the I/O session or null
getSession
(IoSession ioSession, boolean
If true, a null value may be returned if no session is attached
allowNull
)

Retrieve the session SSH from the I/O session.

public byte[]
public SessionListener
protected boolean
handleFirstKexPacketFollows(int cmd, Buffer buffer, boolean followFlag)

protected void
handleKexExtension(int cmd, Buffer buffer)

protected void
protected void
handleKexMessage(int cmd, Buffer buffer)

protected void
handleMessage(Buffer
The Buffer containing the packet - it may be re-used to generate the response once request has been decoded
buffer
)

Abstract method for processing incoming decoded packets.

protected void
handleNewCompression(int cmd, Buffer buffer)

protected void
handleNewKeys(int cmd, Buffer buffer)

protected void
protected void
handleServiceAccept(String serviceName, Buffer buffer)

protected void
protected boolean
handleServiceRequest(String serviceName, Buffer buffer)

protected CurrentService

Returns:

a new CurrentService instance for the session
initializeCurrentService
()

Creates a new CurrentService instance managing this session's current SSH service.

protected KeyExchangeMessageHandler

Returns:

a new KeyExchangeMessageHandler instance for the session
initializeKeyExchangeMessageHandler
()

Creates a new KeyExchangeMessageHandler instance managing packet sending for this session.

protected boolean
protected boolean
protected boolean
protected boolean
protected boolean
public void
messageReceived(Readable
the new buffer received
buffer
)

Main input point for the MINA framework.

protected Map<KexProposalOption, String>

Returns:

The negotiated options Map
negotiate
()

Compute the negotiated proposals by merging the client and server proposal.

protected IoWriteFuture

Returns:

An IoWriteFuture that can be used to wait for packet write completion - null if the registered ReservedSessionMessagesHandler decided to handle the command internally
notImplemented
(int
The un-implemented command value
cmd
,
Buffer
The Buffer that contains the command

Note

the buffer's read position is just beyond the command.

buffer
)

Send a SSH_MSG_UNIMPLEMENTED packet.

protected void
protected void
preClose()

Overrides org.apache.sshd.common.util.closeable.AbstractCloseable.preClose.

preClose is guaranteed to be called before doCloseGracefully or doCloseImmediately.

public Buffer
prepareBuffer(byte
The SSH command to initialize the buffer with
cmd
,
Buffer
The Buffer instance to initialize
buffer
)

Implements org.apache.sshd.common.session.Session.prepareBuffer.

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 in inSettings and outSettings.

protected Buffer
preProcessEncodeBuffer(int
The command stored in the buffer
cmd
,
Buffer
The original Buffer - assumed to be properly formatted and be of at least the required minimum length.
buffer
)

Overrides org.apache.sshd.common.session.helpers.SessionHelper.preProcessEncodeBuffer.

Invoked by the session before encoding the buffer in order to make sure that it is at least of size SSH_PACKET_HEADER_LEN.

protected abstract boolean

Returns:

true if the identification has been fully read or false if more data is needed
readIdentification
(Buffer
The Buffer containing the remote identification
buffer
)

Read the other side identification.

protected byte[]

Returns:

the packet data
receiveKexInit
(Buffer
the Buffer containing the key exchange init packet
buffer
,
Map<KexProposalOption, String>
the remote proposal to fill
proposal
)

Receive the remote key exchange init message.

protected byte[]
protected abstract void
receiveKexInit(Map<KexProposalOption, String> proposal, byte[] seed)

public KeyExchangeFuture
protected void
refreshConfiguration()

Refresh whatever internal configuration is not final

public void
public void
public void
protected boolean

Returns:

true if the option contained the value (and it was removed); false otherwise
removeValue
(Map<KexProposalOption, String>
Map holding the Kex proposal
options
,
KexProposalOption option, String
value to remove
toRemove
)

Given a KEX proposal and a KexProposalOption, removes all occurrences of a value from a comma-separated value list.

public Buffer
request(String
the request name - used mainly for logging and debugging
request
,
Buffer
the buffer containing the global request
buffer
,
long
maximum time in milliseconds to wait for the request to finish - must be positive
maxWaitMillis
)

Implements org.apache.sshd.common.session.Session.request.

Send a global request and wait for the response, if the request is sent with want-reply = true.

public GlobalRequestFuture
request(Buffer
the Buffer containing the global request, with the want-reply flag set as appropriate
buffer
,
String
the request name
request
,
GlobalRequestFuture.ReplyHandler
ReplyHandler for handling the reply; may be null
replyHandler
)

Implements org.apache.sshd.common.session.Session.request.

Send a global request and handle the reply asynchronously.

protected void
requestFailure(Buffer
The Buffer containing the message data
buffer
)

Indicates the reception of a SSH_MSG_REQUEST_FAILURE message

protected KeyExchangeFuture

Returns:

A KeyExchangeFuture to wait for the initiated exchange or null if an exchange is already in progress
requestNewKeysExchange
()

Initiates a new keys exchange if one not already in progress

protected void
requestSuccess(Buffer
The Buffer containing the message data
buffer
)

Indicates the reception of a SSH_MSG_REQUEST_SUCCESS message

protected int
protected Buffer
protected String
protected byte[]

Returns:

the sent packet data which must be kept for later use when deriving the session keys
sendKexInit
(Map<KexProposalOption, String>
our proposal for key exchange negotiation
proposal
)

Send the key exchange initialization packet.

protected byte[]
protected IoWriteFuture

Returns:

An IoWriteFuture that can be used to wait and check the result of sending the packet
sendNewKeys
()

Send a message to put new keys into use.

protected void
setClientKexData(byte[] data)

protected void
setInputEncoding()

Installs the current prepared inSettings so that they are effective and will be applied to any future incoming packet.

protected abstract void
setKexSeed(byte...
The result of the KEXINIT handshake - required for correct session key establishment
seed
)

protected Map<KexProposalOption, String>
protected void
setOutputEncoding()

Installs the current prepared outSettings 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
protected <
The Buffer type being validated
B extends Buffer
>
B

Returns:

The validated target instance - default same as input
validateTargetBuffer
(int
The most likely command this buffer refers to (not guaranteed to be correct)
cmd
,
B
The buffer to be examined
buffer
)

Makes sure that the buffer used for output is not null or one of the session's internal ones used for decoding and uncompressing

private boolean
wantReply(Buffer buffer)

public IoWriteFuture
writePacket(Buffer
the buffer to encode and send
buffer
)

Implements org.apache.sshd.common.session.Session.writePacket.

Encode and send the given buffer.

public IoWriteFuture
writePacket(Buffer
the buffer to encode and spend
buffer
,
long
the timeout
timeout
,
TimeUnit
the time unit of the timeout parameter
unit
)

Implements org.apache.sshd.common.session.Session.writePacket.

Encode and send the given buffer with the specified timeout.

Inherited from org.apache.sshd.common.session.helpers.SessionHelper:
attributeKeyscalculateNextIgnorePacketCountcheckAuthenticationTimeoutcheckForTimeoutscheckIdleTimeoutclearAttributescomputeAttributeIfAbsentcreateProposaldisconnectdoInvokeDebugMessageHandlerdoInvokeIgnoreMessageHandlerdoReadIdentificationexceptionCaughtgetAttributegetAttributesCountgetAuthTimeoutgetAuthTimeoutStartgetBoundLocalPortForwardsgetBoundRemotePortForwardgetChannelStreamWriterResolvergetConnectionServicegetFactoryManagergetForwardergetIdleTimeoutgetIdleTimeoutStartgetIoSessiongetKexProposalgetLocalForwardsBindingsgetParentPropertyResolvergetPropertiesgetRemoteForwardsBindingsgetReservedSessionMessagesHandlergetSessionDisconnectHandlergetStartedLocalPortForwardsgetStartedRemotePortForwardsgetTimeoutStatusgetUnknownChannelReferenceHandlergetUsernamehandleDebughandleDisconnecthandleDisconnecthandleIgnorehandleUnimplementedinvokeSessionSignallerisAuthenticatedisLocalPortForwardingStartedForPortisRemotePortForwardingStartedForPortisServerSessionmergeProposalsremoveAttributeresetAuthTimeoutresetIdleTimeoutresizeKeyresolveAvailableSignaturesProposalresolveAvailableSignaturesProposalresolveChannelStreamWriterResolverresolveIdentificationStringresolvePeerAddressresolveReservedSessionMessagesHandlerresolveUnknownChannelReferenceHandlersendDebugMessagesendIdentificationsendIgnoreMessagesendNotImplementedsetAttributesetAuthenticatedsetChannelStreamWriterResolversetReservedSessionMessagesHandlersetSessionDisconnectHandlersetUnknownChannelReferenceHandlersetUsernamesignalDisconnectsignalDisconnectsignalExceptionCaughtsignalExceptionCaughtsignalNegotiationEndsignalNegotiationEndsignalNegotiationOptionsCreatedsignalNegotiationOptionsCreatedsignalNegotiationStartsignalNegotiationStartsignalPeerIdentificationReceivedsignalPeerIdentificationReceivedsignalReadPeerIdentificationLinesignalReadPeerIdentificationLinesignalSendIdentificationsignalSendIdentificationsignalSessionClosedsignalSessionClosedsignalSessionCreatedsignalSessionCreatedsignalSessionEstablishedsignalSessionEstablishedsignalSessionEventsignalSessionEventtoString