Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 89 additions & 70 deletions src/Renci.SshNet/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1045,17 +1045,41 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout)
/// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
internal void SendMessage(Message message)
{
if (!_socket.IsConnected())
while (true)
{
throw new SshConnectionException("Client not connected.");
}
if (!_socket.IsConnected())
{
throw new SshConnectionException("Client not connected.");
}

if (!_keyExchangeCompletedWaitHandle.IsSet && message is not IKeyExchangedAllowed)
{
// Wait for key exchange to be completed
WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
if (!_keyExchangeCompletedWaitHandle.IsSet && message is not IKeyExchangedAllowed)
{
// Wait for key exchange to be completed
WaitOnHandle(_keyExchangeCompletedWaitHandle.WaitHandle);
}

// take a write lock to ensure the outbound packet sequence number is incremented
// atomically, and only after the packet has actually been sent
lock (_socketWriteLock)
{
if (!_keyExchangeCompletedWaitHandle.IsSet && message is not IKeyExchangedAllowed)
{
// A key re-exchange started between the check above and acquiring the
// write lock. Our SSH_MSG_KEXINIT may already have been sent, in which
// case sending this message now would violate RFC 4253 section 7.1 and
// cause the server to drop the connection. Go back to waiting for the
// key exchange to complete.
continue;
}

SendMessageWithinWriteLock(message);
return;
}
}
}

private void SendMessageWithinWriteLock(Message message)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
_logger.LogTrace("[{SessionId}] Sending message {MessageName}({MessageNumber}) to server: '{Message}'.", SessionIdHex, message.MessageName, message.MessageNumber, message.ToString());
Expand All @@ -1074,82 +1098,77 @@ internal void SendMessage(Message message)
macLength = _clientMac.HashSize / 8;
}

// take a write lock to ensure the outbound packet sequence number is incremented
// atomically, and only after the packet has actually been sent
lock (_socketWriteLock)
{
var activeBufferLength = message.GetPacket(
ref _sendBuffer,
paddingMultiplier,
_clientCompression,
_clientEtm || _clientAead,
macLength);
var activeBufferLength = message.GetPacket(
ref _sendBuffer,
paddingMultiplier,
_clientCompression,
_clientEtm || _clientAead,
macLength);

// write outbound packet sequence to start of packet data
BinaryPrimitives.WriteUInt32BigEndian(_sendBuffer, _outboundPacketSequence);
// write outbound packet sequence to start of packet data
BinaryPrimitives.WriteUInt32BigEndian(_sendBuffer, _outboundPacketSequence);

if (_clientMac != null && !_clientEtm)
{
// non-ETM mac = MAC(key, sequence_number || unencrypted_packet)
if (_clientMac != null && !_clientEtm)
{
// non-ETM mac = MAC(key, sequence_number || unencrypted_packet)

var hashSuccess = _clientMac.TryComputeHash(
buffer: _sendBuffer,
offset: 0,
count: activeBufferLength - macLength,
destination: _sendBuffer.AsSpan(activeBufferLength - macLength),
bytesWritten: out var bytesWritten);
var hashSuccess = _clientMac.TryComputeHash(
buffer: _sendBuffer,
offset: 0,
count: activeBufferLength - macLength,
destination: _sendBuffer.AsSpan(activeBufferLength - macLength),
bytesWritten: out var bytesWritten);

Debug.Assert(hashSuccess && bytesWritten == macLength);
}
Debug.Assert(hashSuccess && bytesWritten == macLength);
}

if (_clientCipher != null)
{
_clientCipher.SetSequenceNumber(_outboundPacketSequence);
if (_clientCipher != null)
{
_clientCipher.SetSequenceNumber(_outboundPacketSequence);

// Not encrypting the sequence number (it is not part of the packet),
// nor the packet length for ETM.
var offset = _clientEtm ? 8 : 4;
// Not encrypting the sequence number (it is not part of the packet),
// nor the packet length for ETM.
var offset = _clientEtm ? 8 : 4;

var numberOfBytesEncrypted = _clientCipher.Encrypt(
input: _sendBuffer,
offset,
length: activeBufferLength - offset - macLength,
output: _sendBuffer,
outputOffset: offset);
var numberOfBytesEncrypted = _clientCipher.Encrypt(
input: _sendBuffer,
offset,
length: activeBufferLength - offset - macLength,
output: _sendBuffer,
outputOffset: offset);

Debug.Assert(numberOfBytesEncrypted == activeBufferLength - offset - macLength + (_clientAead ? macLength : 0));
}
Debug.Assert(numberOfBytesEncrypted == activeBufferLength - offset - macLength + (_clientAead ? macLength : 0));
}

if (_clientMac != null && _clientEtm)
{
// ETM mac = MAC(key, sequence_number || packet_length || encrypted_packet)
if (_clientMac != null && _clientEtm)
{
// ETM mac = MAC(key, sequence_number || packet_length || encrypted_packet)

var hashSuccess = _clientMac.TryComputeHash(
buffer: _sendBuffer,
offset: 0,
count: activeBufferLength - macLength,
destination: _sendBuffer.AsSpan(activeBufferLength - macLength),
bytesWritten: out var bytesWritten);
var hashSuccess = _clientMac.TryComputeHash(
buffer: _sendBuffer,
offset: 0,
count: activeBufferLength - macLength,
destination: _sendBuffer.AsSpan(activeBufferLength - macLength),
bytesWritten: out var bytesWritten);

Debug.Assert(hashSuccess && bytesWritten == macLength);
}
Debug.Assert(hashSuccess && bytesWritten == macLength);
}

SendPacket(_sendBuffer, 4, activeBufferLength - 4);
SendPacket(_sendBuffer, 4, activeBufferLength - 4);

if (_isStrictKex && message is NewKeysMessage)
{
_outboundPacketSequence = 0;
}
else
{
// increment the packet sequence number only after we're sure the packet has
// been sent; even though it's only used for the MAC, it needs to be incremented
// for each package sent.
//
// the server will use it to verify the data integrity, and as such the order in
// which messages are sent must follow the outbound packet sequence number
_outboundPacketSequence++;
}
if (_isStrictKex && message is NewKeysMessage)
{
_outboundPacketSequence = 0;
}
else
{
// increment the packet sequence number only after we're sure the packet has
// been sent; even though it's only used for the MAC, it needs to be incremented
// for each package sent.
//
// the server will use it to verify the data integrity, and as such the order in
// which messages are sent must follow the outbound packet sequence number
_outboundPacketSequence++;
}
}

Expand Down
1 change: 1 addition & 0 deletions test/Renci.SshNet.IntegrationTests/.dockerignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*
!server/*
!user/*
!proftpd/*
45 changes: 45 additions & 0 deletions test/Renci.SshNet.IntegrationTests/Logging/TextWriterLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#nullable enable

using Microsoft.Extensions.Logging;

namespace Renci.SshNet.IntegrationTests.Logging
{
internal class TextWriterLogger(TextWriter writer, string categoryName) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
{
return null;
}

public bool IsEnabled(LogLevel logLevel)
{
return true;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
StringBuilder sb = new StringBuilder();
sb.Append(logLevel);
sb.Append(": ");
sb.Append(categoryName);
sb.Append(": ");

string message = formatter(state, exception);
sb.Append(message);

if (exception != null)
{
sb.Append(": ");
sb.Append(exception);
}

string line = sb.ToString();

lock (writer)
{
writer.WriteLine(line);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#nullable enable

using Microsoft.Extensions.Logging;

namespace Renci.SshNet.IntegrationTests.Logging
{
internal class TextWriterLoggerProvider(TextWriter writer) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new TextWriterLogger(writer, categoryName);
}

public void Dispose()
{
}
}
}
Loading