Index | Thread | Search

From:
"Theo de Raadt" <deraadt@openbsd.org>
Subject:
Re: ksh(1), use arc4random_uniform(3) to calculate $RANDOM
To:
Biarder <mss091204.1@gmail.com>
Cc:
tech@openbsd.org
Date:
Fri, 22 May 2026 09:21:52 -0600

Download raw body.

Thread
  • Stuart Henderson:

    ksh(1), use arc4random_uniform(3) to calculate $RANDOM

  • Theo de Raadt:

    ksh(1), use arc4random_uniform(3) to calculate $RANDOM

  • Biarder <mss091204.1@gmail.com> wrote:
    
    > Currently, ksh(1) uses rand(3) and modular arithmetic to calculate
    > $RANDOM.  However, OpenBSD recommend using arc4random_uniform(3)
    > to calculate a uniform random integer because rand function is
    > predictable and also has modular bias when modulo operation is
    > performed.
    
    Your change is incorrect.  There are situations when ksh randomness
    must follow the rand() method.
    
    This is handled by not using arcrandom(), but by using the rand()
    which _is_ arc4random() behind the scenes unless srand_deterministic()
    is called.  And srand_deterministic() is called, in those circumstances,
    to satisfy that requirement.
    
    It is in the manual page.
    
         RANDOM     A random number generator.  Every time RANDOM is referenced,
                    it is assigned the next random number in the range 0-32767.
                    By default, arc4random(3) is used to produce values.  If the
                    variable RANDOM is assigned a value, the value is used as the
                    seed to srand_deterministic(3) and subsequent references of
                    RANDOM produce a predictable sequence.
    
    This work was done in 2004.  When making changes, please look at the history
    of the code you are touching.  In this case 'grep arc4random' would have found
    you this reference, the commit message, and this text above.  If you had
    done 'man rand', you would have learned the rest of it.
    
     
    
    
  • Stuart Henderson:

    ksh(1), use arc4random_uniform(3) to calculate $RANDOM

  • Theo de Raadt:

    ksh(1), use arc4random_uniform(3) to calculate $RANDOM