2

Is there any documentation on what RNG algorithm PowerShell's Get-Random cmdlet officially uses in PowerShell 5.1?

I did some investigating (via decompiling), and it seems Get-Random is just a wrapper for the native .NET Random class. I can confirm this by getting the same values on PowerShell 2.0 (Windows 7) vs C# (targeting .NET 4.5.2). However, Powershell 5.1 (Windows 10) seems to output different numbers.

PowerShell 2.0:

Get-Random -SetSeed 0 -Minimum 0 -Maximum 2147483647
# Produces 1559595546

PowerShell 5.1:

Get-Random -SetSeed 0 -Minimum 0 -Maximum 2147483647
# Produces: 1866861594

C#:

new Random(0).Next(0, 2147483647);
# Produces 1559595546

I did read that after PowerShell 2.0, Get-Random is supposed to support 64-bit numbers, but I set the minimum and maximum above to the 32-bit range for proper testing. Even different seeds, or altering the ranges to something like [0, 100] still yields different results on PowerShell 5.1.

My end goal is basically trying to reproduce random numbers produced in PowerShell 5.1 in either C++ or C# for sake of performance. I already have the C# Random class translated to C++.

5
  • 2
    The .NET Random class isn't even the same across all platforms. You should not be trying to duplicate behavior in a component that itself does not have a documented algorithm it promises to use. If you want code in PowerShell and C# to both generate random numbers identically, you need to implement the generator in both languages yourself. Jul 17, 2017 at 2:18
  • I would if I could. ;) I'm actually working on cracking ransomware (this case, a particular strain of PowerWare/PoshCoder), so I'm not the author of the original. Do you have documentation about it not being consistent? I've not ran into .NET Random being different across platforms before in my experience - that could definitely be the root of my issue here. Jul 17, 2017 at 2:22
  • 1
    "Do you have documentation about it not being consistent?" -- The documentation for the Random class mentions several times that the implementation is changeable across .NET versions. For example: "However, note that Random objects in processes running under different versions of the .NET Framework may return different series of random numbers even if they're instantiated with identical seed values.". Jul 17, 2017 at 4:21
  • That's not the problem here though Peter. Powershell 5.0 has it's own implementation and isn't calling Random.Next. Instead it is using NextBytes which it then converts to an integer. Jul 17, 2017 at 6:16
  • @Alexander: "That's not the problem here though" -- it's not the only problem, I'll grant. But it sure is one of the problems. Jul 17, 2017 at 6:44

2 Answers 2

3

You can view Power Shell's Get Random implementation on GitHub.

Comments in the source code show it is using its own generator which have comments indicating it has some deviations from the .net / CRL implementation.

In particular, it has its own PolymorphicRandomNumberGenerator class that provides a "re-implementation" of methods using the NextBytes() primitive based on the CLR implementation:

    /// <summary>
    /// Provides an adapter API for random numbers that may be either cryptographically random, or
    /// generated with the regular pseudo-random number generator. Re-implementations of
    /// methods using the NextBytes() primitive based on the CLR implementation:
    ///     http://referencesource.microsoft.com/#mscorlib/system/random.cs
    /// </summary>
internal class PolymorphicRandomNumberGenerator

For example:

/// <summary>
/// Generates a non-negative random integer.
/// </summary>
/// <returns>A non-negative random integer.</returns>
internal int Next()
{
    int result;

    // The CLR implementation just fudges
    // Int32.MaxValue down to (Int32.MaxValue - 1). This implementation
    // errs on the side of correctness.
    do
    {
        result = InternalSample();
    }
    while (result == Int32.MaxValue);

    if (result < 0)
    {
        result += Int32.MaxValue;
    }

    return result;
}

The powershell implementation, while using the same underlying System.Random, will use different methods to generate the random values depending on the input. With your issue the power shell implementation does this:

 var rnd = new Random(0);
 int result;
 byte[] data = new byte[sizeof(int)];

 rnd.NextBytes(data);
 result = BitConverter.ToInt32(data, 0);
 console.log("result = {0}", result);
 // result = 1866861594

Where which does not match the output of:

var rresult = new Random(0).Next(0, int.MaxValue);
console.log("result = {0}", result);
// result = 1559595546
5
  • Their words /// <summary> Provides an adapter API for random numbers that may be either cryptographically random, or generated with the regular pseudo-random number generator. Re-implementations of methods using the NextBytes() primitive based on the CLR implementation: internal class PolymorphicRandomNumberGenerator Jul 17, 2017 at 4:39
  • It may or may not. GetBytes can return _cryptographicGenerator.GetBytes(buffer) or _pseudoGenerator.NextBytes(buffer); Jul 17, 2017 at 4:44
  • You where absolutely, but you are not getting that they are different implementations even if they both use the same Random class. And depending on the arguments you pass to the PolymorphicRandomNumberGenerator implementation it will generator the random value in a different manner that results in a different output. I have updated my answer to show how the implementation is getting a different result. Jul 17, 2017 at 5:07
  • 1
    Sorry, you're right. I did not notice the .NET Random isn't using GetBytes() for its Next() implementation. Still, the PowerShell implementation does depend on the .NET implementation, and so changes to the .NET implementation will affect the PS results. It is not sufficient to duplicate the implementation in PS. One also needs to duplicate the underlying .NET implementation (and that's true even in the crypto case, since in neither case does the PS implementation actually generate random #'s itself). But yes, no .NET implementation will return the same values as PS. Jul 17, 2017 at 6:44
  • Thanks! I stumbled on that page before I realized the difference between versions (I originally thought it was all PS since I test on my Win10 system), but missed the NextBytes() call and thought it was just using Next(). I can only assume victim's systems use the _pseudoGenerator, and hopefully not the _cryptographicGenerator... shame it isn't consistent on which is used in documentation. Jul 17, 2017 at 13:54
0

Here's my ported C++ code for the PowerShell 5.0 PRNG, if it's of any use to anyone else searching. Confirmed it produces the same numbers as PowerShell 5.1 on Windows 10.

It utilizes my Random class that is a ported version of the .NET RNG, which I separated a bit to make both inherit from a common interface (Random.h) and renamed to RandomDotNet: https://stackoverflow.com/a/39338606/1301139

Random.h

#include <limits>
#include <Windows.h>

#pragma once
class Random
{
public:
    virtual ~Random() {}
    virtual int Next() = 0;
    virtual int Next(int minValue, int maxValue) = 0;
    virtual int Next(int maxValue) = 0;
    virtual void NextBytes(BYTE *buffer, int bufferLen) {};
    virtual double NextDouble() = 0;
};

RandomPS5.h

#include <limits>
#include <Windows.h>
#include "Random.h"

#pragma once
class RandomPS5 : public Random
{
protected:
    double InternalSampleLargeRange();
    int InternalSample();
    int BytesToInt(BYTE *dword);

    Random *pseudoGenerator;

public:
    RandomPS5(int seed);
    ~RandomPS5();
    int Next();
    int Next(int minValue, int maxValue);
    int Next(int maxValue);
    double NextDouble();
    void NextBytes(BYTE *buffer, int bufferLen);
};

RandomPS5.cpp

#include "stdafx.h"
#include "RandomPS5.h"
#include "RandomDotNet.h"
#include <limits.h>
#include <math.h>
#include <stdexcept>
#include <string>

// Naive conversion of BitConverter.ToInt32
int RandomPS5::BytesToInt(BYTE *b) {
    int Int32 = 0;

    Int32 = (Int32 << 8) + b[3];
    Int32 = (Int32 << 8) + b[2];
    Int32 = (Int32 << 8) + b[1];
    Int32 = (Int32 << 8) + b[0];
    return Int32;
}

RandomPS5::RandomPS5(int seed) {
    pseudoGenerator = new RandomDotNet(seed);
}

RandomPS5::~RandomPS5(){
    delete pseudoGenerator;
}

double RandomPS5::NextDouble() {
    return Next() * (1.0 / 0x7FFFFFFF);
}

int RandomPS5::Next() {
    int result;

    do {
        result = InternalSample();
    } while (result == 0x7FFFFFFF);

    if (result < 0) {
        result += 0x7FFFFFFF;
    }

    return result;
}

int RandomPS5::Next(int maxValue) {
    if (maxValue<0) {
        throw std::invalid_argument("maxValue must be positive");
    }

    return Next(0, maxValue);
}

int RandomPS5::Next(int minValue, int maxValue) {
    if (minValue > maxValue)
    {
        throw std::invalid_argument("minValue is larger than maxValue");
    }

    long range = (long)maxValue - (long)minValue;
    if (range <= 0x7FFFFFFF)
    {
        return ((int)(NextDouble() * range) + minValue);
    }
    else
    {
        double largeSample = this->InternalSampleLargeRange() * (1.0 / (2 * 0x7FFFFFFF));
        int result = (int)((long)(largeSample * range) + minValue);

        return result;
    }
}

int RandomPS5::InternalSample() {

    BYTE *data = (BYTE*)malloc(sizeof(int));

    this->NextBytes(data, sizeof(int));
    int result = BytesToInt(data);

    free(data);

    return result;
}

double RandomPS5::InternalSampleLargeRange() {
    double result;

    do{
        result = this->InternalSample();
    } while (result == 0x7FFFFFFF);

    result += 0x7FFFFFFF;
    return result;
}

void RandomPS5::NextBytes(BYTE *buffer, int bufferLen) {
    this->pseudoGenerator->NextBytes(buffer, bufferLen);
}

Main.cpp

#include "RandomDotNet.h"
#include "RandomPS5.h"
#include <Windows.h>

// Length of charset string
#define CHARSETLEN 62

// Random charset
const char charset[CHARSETLEN + 1] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

// Function that processes a record like PowerShell does for -ObjectList
void processRecord(CHAR *string, int len, Random *r) {

    // Processed characters
    int processed = 0;

    int i, indexToReplace;
    CHAR temp;

    // Iterate the charset
    for (i = 0; i < CHARSETLEN; ++i) {

        if (processed < len) {
            string[processed] = charset[i];
        }
        else if (r->Next(processed + 1) < len) {
            string[r->Next(len)] = charset[i];
        }
        ++processed;

    }

    // Iterate selected items to return them in "random" order
    for (i = 0; i < len; ++i) {

        // Get random index
        indexToReplace = r->Next(i, len);

        if (i != indexToReplace) {

            // Swap
            temp = string[i];
            string[i] = string[indexToReplace];
            string[indexToReplace] = temp;

        }

    }

    // Terminate the string
    string[len] = '\0';

}
int main(int argc, char* argv[]){

    // Example usage with a given seed
    Random *r = new RandomPS5(1000);

    // Length of random string
    int len = 49;

    // Random string buffer
    CHAR *buffer = (CHAR*)malloc(len + 1);

    // ([char[]](Get-Random -Input $(48..57 + 65..90 + 97..122) -Count 49 -SetSeed 1000)) -Join ""
    processRecord(buffer, len, r);

    // Produces: y6FLfcKrpINqgP25GXS7Z0dVBmJOzntlQ3hjbHMAU1ExkewWY
    printf("Random string: %s", buffer);

    delete r;

    return 0;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.