Home › Blog › Account Takeover via a Sandwich Attack on System.Random

Account Takeover via a Sandwich Attack on System.Random

04.11
Account Takeover via a Sandwich Attack on System.Random

During a penetration test of a web application, we identified a vulnerability that allowed us to take over any user account by exploiting the password reset mechanism. The attack relied on a technique known as a sandwich attack and the use of System.Random, a non-cryptographically secure pseudo-random number generator in C#.

Using an unsuitable random number generator to produce secrets is a well-known security weakness. However, this case demonstrates that the consequences are far from theoretical: a seemingly random temporary password can become predictable, potentially leading to account takeover.

In this article, we explain the root cause of the vulnerability, how we exploited it in practice, and the conditions that made the attack possible.

Context: A Vulnerable Password Reset Mechanism

How the Password Reset Process Works

In the application we assessed, the password reset process involved the following steps:

  1. The user clicks on “Forgotten password” and enters their username.
  2. The application sends an eight-character temporary password to the user’s email address.
  3. The user logs in using this temporary password.
  4. The application then prompts the user to set a new password.

The vulnerability lay not in the delivery of the password by email, but in how the temporary password was generated.

Generating Temporary Passwords with System.Random

The password generation function could be represented by the following C# code:

public string genPass()
{
    var charset = new List<string> {
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
        "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
    };
    var random = new Random();
    var password = string.Empty;
    int ind;

    for (var i = 0; i < 8; i++)
    {
        ind = random.Next(0, charset.length);
        password += charset[ind];
    }

    return password;
}

The function uses a character set containing 36 characters: lowercase letters from a to z and digits from 0 to 9. For each of the eight characters in the password, System.Random generates an index used to select a character from this set.

At first glance, the resulting passwords appear random. However, their security depends entirely on how predictable the underlying random number generator is.

Why Does System.Random Make These Passwords Predictable?

A Pseudo-Random Number Generator Not Designed for Cryptography

The System.Random class generates sequences of pseudo-random values. It can be initialised using an explicit value, known as a seed, or without an argument using the Random() constructor.

A given seed always produces the same sequence of values. Therefore, if an attacker manages to recover the seed used, they can reproduce the generated sequence and, in this case, the corresponding temporary password.

Microsoft’s documentation explicitly states that System.Random should not be used to generate values requiring cryptographic security, such as passwords. Instead, it recommends using System.Security.Cryptography.RandomNumberGenerator.

A Seed Derived from Environment.TickCount in .NET Framework 4.8.1

The next step was to understand how Random() was initialised when no explicit seed was provided.

The constructor documentation indicates that the default seed depends on the system clock, without fully explaining how it is calculated. Several sources covering older versions of .NET Framework suggested that Environment.TickCount was used.

To verify this behaviour in .NET Framework 4.8.1, we decompiled mscorlib.dll using dnSpy and found the following implementation:

public Random() : this(Environment.TickCount) { }

public Random(int Seed)
{
    int num = (Seed == int.MinValue)
        ? int.MaxValue
        : Math.Abs(Seed);
    // ...
}

The Environment.TickCount property represents the number of milliseconds elapsed since the system was started, expressed as a signed 32-bit integer (Int32).

Two characteristics are particularly important for understanding the attack: the seed changes predictably over time, and the number of possible values is limited.

Reducing the Search Space to 2³¹ Possible Seeds

A signed 32-bit integer can theoretically represent 2³² distinct bit patterns. However, the implementation we observed takes the absolute value of negative seeds, with special handling for int.MinValue.

As a result, the effective range of internal seed values is limited to a maximum of 2³¹ possibilities, or approximately 2.15 billion seeds.

This search space is small enough to make an exhaustive local search feasible. More importantly, the relationship with Environment.TickCount provides an additional advantage: we do not need to test every possible seed to predict a victim’s password.

Exploitation: How the Sandwich Attack Works

Three Password Reset Requests to Narrow Down the Victim’s Password

In this scenario, a sandwich attack involves triggering three consecutive password resets within the shortest possible time:

  1. First reset request for our own account: we receive a first temporary password, which we know.
  2. Reset request for the victim’s account: a temporary password is generated and sent to the victim. We do not have access to their email inbox.
  3. Second reset request for our own account: we receive a second temporary password, which we also know.

The victim’s unknown password is effectively sandwiched between two passwords that we can observe.

Recovering the Seeds of the Two Known Passwords

Once the three requests have been completed, the exploitation continues locally.

We use brute force to identify the seed that reproduces the first temporary password, then repeat the process for the second password. We refer to these values as seed1 and seed2.

Because the three passwords were generated consecutively, their seeds are linked to the progression of Environment.TickCount.

As long as the passwords are generated within a continuous interval in which the seed changes without discontinuity, the victim’s seed must lie between the two recovered seeds.

In an interval where the seed values increase, this can be expressed as:

seed1 < seed_victim < seed2

When applying the absolute value during a negative TickCount interval reverses the direction of progression, the same principle applies, but the order of the two boundaries is reversed.

Transitions between positive and negative values, as well as counter wraparound, must therefore be taken into account.

Generating Candidate Passwords

The next step is to iterate through the seeds between the two recovered boundaries and generate the corresponding password for each one, using the same pseudo-random algorithm and character ordering.

This produces a much smaller list of candidate passwords that can be tested against the target account, without ever accessing the email received by the victim.

For our tests, we reimplemented the pseudo-random number generation algorithm used by the application’s System.Random implementation in Python.

Results Obtained During the Penetration Test

Under our test conditions, recovering the two seeds and generating the list of candidate passwords took approximately four to five minutes.

The final list contained around 3,000 possible passwords, compared with a substantially larger search space if only the password length and permitted characters were known.

Such a number of candidates may still be exploitable even when certain rate-limiting mechanisms are in place. However, the actual effectiveness of the attack depends on the security controls implemented, including request throttling, account lockout and detection of repeated login attempts.

Limitations and Technical Considerations

System counter behaviour

Environment.TickCount is a signed 32-bit integer. After approximately 24.9 days of uptime, its value changes from Int32.MaxValue to Int32.MinValue, before continuing to increase towards zero over the following 24.9 days.

This behaviour does not necessarily prevent exploitation, but it requires careful handling of transitions between value ranges and the use of Math.Abs. Both boundaries must be interpreted within a consistent interval of the counter’s progression.

.NET version

Our findings relate to an application running .NET Framework 4.8.1. The initialisation behaviour of System.Random has changed in .NET Core and modern versions of .NET.

Our tests did not reproduce the same attack under equivalent conditions on these newer implementations. The results presented here should therefore not be generalised to all versions of .NET.

Use of an AI assistant

Claude also helped identify the vulnerability in the source code and assisted during the exploitation process.

Can the Attack Be Performed Without Access to the Source Code?

Why the Character Set Matters

During this assessment, we had access to the source code. We therefore knew both the characters used to generate the temporary passwords and their exact order within the charset character set.

This information made it easier to reproduce the passwords from the recovered seeds.

However, we wanted to determine whether the same attack would still be possible if the character set were unavailable, for example because it was defined in another code repository to which we had no access.

Our experiments showed that the character set and its ordering could be reconstructed using multiple temporary passwords generated by the application.

We refer to these observed passwords as samples.

Reconstructing charset from Password Samples

The approach involves comparing the sequence of indices generated for each candidate seed with the characters appearing in the collected samples.

Our experimental method followed these steps:

  1. Iterate through the 2³¹ possible seeds and generate the corresponding sequence of eight indices for each one.
  2. For each sample, map the generated indices to the characters observed at the corresponding positions.
  3. Reject a seed whenever an inconsistency is found: the same index cannot correspond to two different characters, and the same character cannot be assigned to two different indices.
  4. Retain the seeds that are compatible with each sample.
  5. Cross-reference the results across samples to reconstruct a consistent character set and identify the compatible seeds.

To reconstruct the entire character set, every character in charset must appear at least once across the collected samples.

Experimental Results and Practical Constraints

We tested this approach using 30 to 40 locally generated samples, each eight characters long.

The selected samples contained a high proportion of repeated characters (approximately five repeated characters out of eight). This helped eliminate inconsistent seeds early in the process and reduce memory consumption.

These results demonstrate that reconstructing the character set is feasible under the conditions of our experiment.

However, obtaining a comparable number of samples with the required characteristics from a remote application would take additional time.

We did not carry out further optimisation or additional experiments on this aspect of the attack.

Can This Attack Be Reproduced in Other Programming Languages?

We also briefly examined the implementations of random() functions in several programming languages.

Some rely on a 32-bit seed space. However, none of the implementations we tested independently combined the two characteristics required for this particular attack scenario: a limited seed space and time-based initialisation whose progression makes it possible to narrow down an unknown seed.

The presence of a non-cryptographically secure pseudo-random number generator is therefore not sufficient, on its own, to reproduce this sandwich attack.

The details of the generator’s initialisation and the application context are critical to determining whether the technique is applicable.

Remediation: Use a Cryptographically Secure Random Number Generator

The primary remediation is to avoid using general-purpose pseudo-random number generators to produce security-sensitive values, including temporary passwords, password reset tokens, session tokens, nonces, secrets and cryptographic keys.

Within the .NET ecosystem, Microsoft recommends the System.Security.Cryptography.RandomNumberGenerator class, which is designed to generate random values suitable for cryptographic purposes.

The key requirement is to ensure that the unpredictability of a secret relies on a cryptographically secure random number generator, rather than an internal state or seed that an attacker could reconstruct from elapsed time.

Conclusion

This vulnerability demonstrates how a seemingly minor implementation decision can compromise a critical security mechanism.

In the application we assessed, the use of System.Random to generate temporary passwords, combined with predictable seed initialisation in .NET Framework, enabled a sandwich attack that allowed us to predict another user’s password.

Beyond this specific case, the main lesson is clear: the security of a password or token depends not only on its length or apparent randomness, but also on the quality of the mechanism used to generate it.

References

Author: Souad SEBAA – Pentester @Vaadata

Partager l'article
Language

Stay connected!

Receive offensive security updates (selection of articles, events, training…)

Search

Tell us about your offensive security challenges and needs
Contact us to discuss your offensive security needs and get information about our services and processes. Our team will get back to you as soon as possible.
This site is registered on wpml.org as a development site. Switch to a production site key to remove this banner.