-
-
Notifications
You must be signed in to change notification settings - Fork 963
Implement OpenSSH strict key exchange extension #1366
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
5070ca9
Implement OpenSSH strict key exchange extension
scott-xu 5357fee
The pseudo-algorithm
scott-xu 95bc410
Merge branch 'develop' into strict-kex
scott-xu 15eb67d
Merge branch 'develop' into strict-kex
scott-xu 4f704a7
Merge branch 'develop' into strict-kex
scott-xu afc4bb2
Only send strict kex pseudo algorithm for the first kex.
scott-xu 6350350
Unit tests for strict kex
scott-xu 9097805
More unit tests
scott-xu c5da652
More unit tests
scott-xu d0b0a08
Correct file name
scott-xu 35f0b9c
Update SessionTest_ConnectingBase.cs
scott-xu f0cb434
More unit tests
scott-xu 38b5b9f
Delete SessionTest_Connecting_ServerSendsMaxIgnoreMessagesBeforeKexIn…
scott-xu 5b1421e
Add a comment about throwing exception when inbound sequence number i…
scott-xu 48787e9
Merge branch 'develop' of https://github.com/scott-xu/SSH.NET into st…
scott-xu 9cd2653
Delete SessionTest_Connecting_ServerSendsDebugMessageAfterKexInit_NoS…
scott-xu ebc555e
Fix build
scott-xu c64f058
Merge branch 'develop' into strict-kex
scott-xu a5fdc4f
Update test/Renci.SshNet.Tests/Classes/SessionTest_Connected.cs
Rob-Hague File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -154,6 +154,17 @@ public class Session : ISession | |
/// </summary> | ||
private bool _isDisconnecting; | ||
|
||
/// <summary> | ||
/// Indicates whether it is the init kex. | ||
/// </summary> | ||
private bool _isInitialKex; | ||
|
||
/// <summary> | ||
/// Indicates whether server supports strict key exchange. | ||
/// <see href="https://github.com/openssh/openssh-portable/blob/master/PROTOCOL"/> 1.10. | ||
/// </summary> | ||
private bool _isStrictKex; | ||
|
||
private IKeyExchange _keyExchange; | ||
|
||
private HashAlgorithm _serverMac; | ||
|
@@ -281,35 +292,11 @@ public bool IsConnected | |
/// </value> | ||
public byte[] SessionId { get; private set; } | ||
|
||
private Message _clientInitMessage; | ||
|
||
/// <summary> | ||
/// Gets the client init message. | ||
/// </summary> | ||
/// <value>The client init message.</value> | ||
public Message ClientInitMessage | ||
{ | ||
get | ||
{ | ||
_clientInitMessage ??= new KeyExchangeInitMessage | ||
{ | ||
KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(), | ||
ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(), | ||
EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(), | ||
EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(), | ||
MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), | ||
MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), | ||
CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), | ||
CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), | ||
LanguagesClientToServer = new[] { string.Empty }, | ||
LanguagesServerToClient = new[] { string.Empty }, | ||
FirstKexPacketFollows = false, | ||
Reserved = 0 | ||
}; | ||
|
||
return _clientInitMessage; | ||
} | ||
} | ||
public Message ClientInitMessage { get; private set; } | ||
|
||
/// <summary> | ||
/// Gets the server version string. | ||
|
@@ -617,6 +604,8 @@ public void Connect() | |
// Send our key exchange init. | ||
// We need to do this before starting the message listener to avoid the case where we receive the server | ||
// key exchange init and we continue the key exchange before having sent our own init. | ||
_isInitialKex = true; | ||
ClientInitMessage = BuildClientInitMessage(includeStrictKexPseudoAlgorithm: true); | ||
SendMessage(ClientInitMessage); | ||
|
||
// Mark the message listener threads as started | ||
|
@@ -741,6 +730,8 @@ public async Task ConnectAsync(CancellationToken cancellationToken) | |
// Send our key exchange init. | ||
// We need to do this before starting the message listener to avoid the case where we receive the server | ||
// key exchange init and we continue the key exchange before having sent our own init. | ||
_isInitialKex = true; | ||
ClientInitMessage = BuildClientInitMessage(includeStrictKexPseudoAlgorithm: true); | ||
SendMessage(ClientInitMessage); | ||
|
||
// Mark the message listener threads as started | ||
|
@@ -1107,13 +1098,20 @@ internal void SendMessage(Message message) | |
SendPacket(data, 0, data.Length); | ||
} | ||
|
||
// 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++; | ||
} | ||
} | ||
} | ||
|
||
|
@@ -1344,6 +1342,13 @@ private Message ReceiveMessage(Socket socket) | |
|
||
_inboundPacketSequence++; | ||
|
||
// The below code mirrors from https://github.com/openssh/openssh-portable/commit/1edb00c58f8a6875fad6a497aa2bacf37f9e6cd5 | ||
// It ensures the integrity of key exchange process. | ||
if (_inboundPacketSequence == uint.MaxValue && _isInitialKex) | ||
{ | ||
throw new SshConnectionException("Inbound packet sequence number is about to wrap during initial key exchange.", DisconnectReason.KeyExchangeFailed); | ||
} | ||
|
||
return LoadMessage(data, messagePayloadOffset, messagePayloadLength); | ||
} | ||
|
||
|
@@ -1455,8 +1460,20 @@ internal void OnKeyExchangeInitReceived(KeyExchangeInitMessage message) | |
|
||
_keyExchangeCompletedWaitHandle.Reset(); | ||
|
||
if (_isInitialKex && message.KeyExchangeAlgorithms.Contains("[email protected]")) | ||
scott-xu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
_isStrictKex = true; | ||
|
||
DiagnosticAbstraction.Log(string.Format("[{0}] Enabling strict key exchange extension.", ToHex(SessionId))); | ||
|
||
if (_inboundPacketSequence != 1) | ||
{ | ||
throw new SshConnectionException("KEXINIT was not the first packet during strict key exchange.", DisconnectReason.KeyExchangeFailed); | ||
} | ||
} | ||
|
||
// Disable messages that are not key exchange related | ||
_sshMessageFactory.DisableNonKeyExchangeMessages(); | ||
_sshMessageFactory.DisableNonKeyExchangeMessages(_isStrictKex); | ||
|
||
_keyExchange = _serviceFactory.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms, | ||
message.KeyExchangeAlgorithms); | ||
|
@@ -1533,6 +1550,17 @@ internal void OnNewKeysReceived(NewKeysMessage message) | |
// Enable activated messages that are not key exchange related | ||
_sshMessageFactory.EnableActivatedMessages(); | ||
|
||
if (_isInitialKex) | ||
{ | ||
_isInitialKex = false; | ||
ClientInitMessage = BuildClientInitMessage(includeStrictKexPseudoAlgorithm: false); | ||
} | ||
|
||
if (_isStrictKex) | ||
{ | ||
_inboundPacketSequence = 0; | ||
} | ||
|
||
NewKeysReceived?.Invoke(this, new MessageEventArgs<NewKeysMessage>(message)); | ||
|
||
// Signal that key exchange completed | ||
|
@@ -2067,7 +2095,28 @@ private void Reset() | |
private static SshConnectionException CreateConnectionAbortedByServerException() | ||
{ | ||
return new SshConnectionException("An established connection was aborted by the server.", | ||
DisconnectReason.ConnectionLost); | ||
DisconnectReason.ConnectionLost); | ||
} | ||
|
||
private KeyExchangeInitMessage BuildClientInitMessage(bool includeStrictKexPseudoAlgorithm) | ||
{ | ||
return new KeyExchangeInitMessage | ||
{ | ||
KeyExchangeAlgorithms = includeStrictKexPseudoAlgorithm ? | ||
ConnectionInfo.KeyExchangeAlgorithms.Keys.Concat(["[email protected]"]).ToArray() : | ||
ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(), | ||
ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(), | ||
EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(), | ||
EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(), | ||
MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), | ||
MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), | ||
CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), | ||
CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), | ||
LanguagesClientToServer = new[] { string.Empty }, | ||
LanguagesServerToClient = new[] { string.Empty }, | ||
FirstKexPacketFollows = false, | ||
Reserved = 0, | ||
}; | ||
} | ||
|
||
private bool _disposed; | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
using System; | ||
using System.Linq; | ||
using System.Threading; | ||
using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
using Moq; | ||
|
@@ -30,6 +31,31 @@ public void ClientVersionIsRenciSshNet() | |
Assert.AreEqual("SSH-2.0-Renci.SshNet.SshClient.0.0.1", Session.ClientVersion); | ||
} | ||
|
||
[TestMethod] | ||
public void IncludeStrictKexPseudoAlgorithmInInitKex() | ||
{ | ||
Assert.IsTrue(ServerBytesReceivedRegister.Count > 0); | ||
|
||
var kexInitMessage = new KeyExchangeInitMessage(); | ||
kexInitMessage.Load(ServerBytesReceivedRegister[0], 4 + 1 + 1, ServerBytesReceivedRegister[0].Length - 4 - 1 - 1); | ||
Assert.IsTrue(kexInitMessage.KeyExchangeAlgorithms.Contains("[email protected]")); | ||
} | ||
|
||
[TestMethod] | ||
public void ShouldNotIncludeStrictKexPseudoAlgorithmInSubsequentKex() | ||
{ | ||
ServerBytesReceivedRegister.Clear(); | ||
Session.SendMessage(Session.ClientInitMessage); | ||
|
||
Thread.Sleep(100); | ||
|
||
Assert.IsTrue(ServerBytesReceivedRegister.Count > 0); | ||
|
||
var kexInitMessage = new KeyExchangeInitMessage(); | ||
kexInitMessage.Load(ServerBytesReceivedRegister[0], 4 + 1 + 1, ServerBytesReceivedRegister[0].Length - 4 - 1 - 1); | ||
Assert.IsFalse(kexInitMessage.KeyExchangeAlgorithms.Contains("[email protected]")); | ||
} | ||
|
||
[TestMethod] | ||
public void ConnectionInfoShouldReturnConnectionInfoPassedThroughConstructor() | ||
{ | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.