Search code examples
postgresqlsecuritycryptographyaccess-token

PostgreSQL /dev/urandom


Is there a PostgreSQL function that we can use to generate 160 bits of randomness with /dev/urandom?

We want to generate an access token.

According to the OAuth 2.0 Authorization Framework: 10.10. Credentials-Guessing Attacks:

The probability of an attacker guessing generated tokens (and other credentials not intended for handling by end-users) MUST be less than or equal to 2^(-128) and SHOULD be less than or equal to 2^(-160).


Solution

  • Like pozs said, you can use gen_random_bytes(int) from the pgcrypto contrib module.

    This function calls pg_strong_random from src/port/pg_strong_random.c and throws an error if the return code is false.

    The comment explains how pg_strong_random works:

     * Generate requested number of random bytes. The returned bytes are
     * cryptographically secure, suitable for use e.g. in authentication.
     *
     * We rely on system facilities for actually generating the numbers.
     * We support a number of sources:
     *
     * 1. OpenSSL's RAND_bytes()
     * 2. Windows' CryptGenRandom() function
     * 3. /dev/urandom
     *
     * The configure script will choose which one to use, and set
     * a USE_*_RANDOM flag accordingly.
     *
     * Returns true on success, and false if none of the sources
     * were available. NB: It is important to check the return value!
    

    You can look into include/pg_config.h in your PostgreSQL installation and see which source for random numbers is used.

    If you are on Linux, you'll probably use OpenSSL as source for randomness.

    The manual page for RAND_bytes claims:

    RAND_bytes() puts num cryptographically strong pseudo-random bytes into buf.

    I did not dig into OpenSSL source since that really hurts, but essentially, if you trust OpenSSL, you can also trust pgcrypto.