Skip to content

Commit b199467

Browse files
authored
Fix key material extension during key exchange (#1689)
When the key exchange produces less key material than is needed for the cipher or hmac algorithms, there is an iterative procedure to produce more. For example, a SHA-1 key exchange algorithm produces 20 bytes of key material. A SHA-256 hmac uses a 32 byte key, so one iteration of the procedure produces another 20 bytes of key material for a total of 40 which is sufficient for the hmac key. The library works correctly in such cases of one iteration, but the logic is wrong if more than one iteration is needed. In #1660, the connection uses a SHA-1 kex algorithm with a SHA-512 hmac (64 byte key), requiring 3 iterations of the extension procedure and resulting in an error upon connection. This change fixes the logic to use the output of the previous iteration per the spec. closes #1660
1 parent 6cba1be commit b199467

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

src/Renci.SshNet/Security/KeyExchange.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Collections.Generic;
32
using System.Linq;
43
using System.Security.Cryptography;
54

@@ -530,9 +529,7 @@ protected void SendMessage(Message message)
530529
/// </returns>
531530
private byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash, byte[] key, int size)
532531
{
533-
var result = new List<byte>(key);
534-
535-
while (size > result.Count)
532+
while (key.Length < size)
536533
{
537534
var sessionKeyAdjustment = new SessionKeyAdjustment
538535
{
@@ -541,10 +538,10 @@ private byte[] GenerateSessionKey(byte[] sharedKey, byte[] exchangeHash, byte[]
541538
Key = key,
542539
};
543540

544-
result.AddRange(Hash(sessionKeyAdjustment.GetBytes()));
541+
key = key.Concat(Hash(sessionKeyAdjustment.GetBytes()));
545542
}
546543

547-
return result.ToArray();
544+
return key;
548545
}
549546

550547
/// <summary>

test/Renci.SshNet.IntegrationTests/HmacTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,22 @@ public void HmacSha2_512()
4040
DoTest(MessageAuthenticationCodeAlgorithm.HmacSha2_512);
4141
}
4242

43+
[TestMethod]
44+
public void HmacSha2_512_ShortKexOutput()
45+
{
46+
_remoteSshdConfig.ClearMessageAuthenticationCodeAlgorithms()
47+
.AddMessageAuthenticationCodeAlgorithm(MessageAuthenticationCodeAlgorithm.HmacSha2_512)
48+
.ClearKeyExchangeAlgorithms()
49+
.AddKeyExchangeAlgorithm(KeyExchangeAlgorithm.DiffieHellmanGroupExchangeSha1)
50+
.Update()
51+
.Restart();
52+
53+
using (var client = new SshClient(_connectionInfoFactory.Create()))
54+
{
55+
client.Connect();
56+
client.Disconnect();
57+
}
58+
}
4359

4460
[TestMethod]
4561
public void HmacSha1_Etm()

0 commit comments

Comments
 (0)