python / python/cpython

docs: `secrets.token_bytes()` has imprecise security properties

Open
#101,996 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Documentation

I recently needed to generate some cryptographic key material. As far as I can tell, secrets.token_bytes() is the recommended way of doing this, and cpython's concrete implementation appears to be suitable for this purpose. However, the precise wording of the documentation for the API does not make this 100% clear.

The token subsection says:

The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.

And, under token_bytes() specifically:

Return a random byte string containing nbytes number of bytes. [...]

In my very pedantic reading of this, it does not make the sufficient guarantees for securely generating cryptographic key material. It does guarantee that generated tokens will be hard-to-guess, but that's a weaker guarantee than is sometimes necessary.

As an example, generating ECDSA signatures requires a uniform-random nonce value. If even a single bit of that nonce is biased one way or another, over a sufficient number of signatures, then an attacker can use that information to recover the private key (see https://eprint.iacr.org/2019/023.pdf )

As such, I think the documentation for these methods should be amended to explicitly state that the generated bytes are uniformly random, or to otherwise explicitly state that the direct output of secrets.token_bytes() may be suitable for generating cryptographic key material.

To be clear, I am not requesting any changes to the current implementation, merely that the docs accurately reflect what I assume to be the intended and current behaviour.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the documentation for the secrets module, especially the token subsection and the token_bytes() entry. Review the existing wording and the cited concern about uniform randomness and cryptographic key material; done means the documentation accurately states the relevant security properties without changing the implementation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cryptography, documentation, security
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.