Skip to content

math/rand: Deterministic random by default is dangerous #11871

Closed
@shazow

Description

@shazow

Go's standard library is generally considered to have great security-focused defaults (like net/http validating certificates out of the box). In many cases, the default behaviour goes out of the way to prevent the programmer from employing bad practices (such as relying on map key ordering). I believe that the default behavior of math/rand can be improved to better represent these ideals.

There have already been incidents where people didn't realize that math/rand was deterministic by default (example), and even in security-related applications (example). Additionally, tutorials tend to forego mentioning this potentially-catastrophic default (example).

I want to acknowledge that the stdlib documentation mentions this behavior in the second paragraph.

Random numbers are generated by a Source. Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

Unfortunately, merely documenting dangerous default behaviour has not proven to be sufficient. Also worth pointing out that the math/rand docs don't mention crypto/rand (this should be fixed too).

To resolve this, I propose that the top-level math/rand functions be seeded by crypto/rand's Reader by default.

Context: PHP's mt_rand was recently torn down for generating only odd numbers when the max value given was too big (a reasonably easy mistake to make; HN thread). Some Twitter discussions started by @richo pointed out that default-deterministic random is a similarly easy mistake to make.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions