Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The C Standard function rand() makes no guarantees as to the quality of the random sequence produced. The numbers generated by some implementations of rand() have a comparatively short cycle, and the numbers can be predictable. Applications which that have strong pseudorandom number requirements should use a generator that is known to be sufficient for their needs.

...

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#include <stdlib.h>
 
void func(void) {
  enum { len = 12 };
  char id[len];  /*
                  * id will hold the ID, starting with
                  * the characters "ID" followed by a
                  * random integer.
                  */
  int r;
  int num;
  /* ... */
  r = rand();  /* Generate a random integer */
  num = snprintf(id, len, "ID%-d", r);  /* Generate the ID */
  /* ... */
}

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void func(void) {
  enum { len = 12 };
  char id[len];  /*
                  * id will hold the ID, starting with
                  * the characters "ID" followed by a
                  * random integer.
                  */
  int r;
  int num;
  /* ... */
  time_t now = time(NULL);
  if (now == (time_t)-1) {
    /* handleHandle error */
  }
  srandom(now);  /* Seed the PRNG with the current time */
  /* ... */
  r = random();  /* Generate a random integer */
  num = snprintf(id, len, "ID%-d", r);  /* Generate the ID */
  /* ... */
}

...

Although not specified by POSIX, arc4random() is an option on systems that support it. From the arc4random(3) manual page [OpenBSD]:

arc4random() fits into a middle ground not covered by other subsystems such as the strong, slow, and resource expensive random devices described in random(4) versus the fast but poor quality interfaces described in rand(3), random(3), and drand48(3).

To achieve the best random numbers possible, an implementation-specific function must be used. When unpredictability really matters and speed is not an issue, as in the creation of strong cryptographic keys, use a true entropy source, such as /dev/random, or a hardware device capable of generating random numbers. Note that the /dev/random device can block for a long time if there are not enough events going on to generate sufficient entropy.

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

CC2.MSC30

Fully implemented

Fortify SCA

5.0

 

 

LDRA tool suite

Include Page
LDRA_V
LDRA_V

 

 

PRQA QA-C
Include Page
PRQA_V
PRQA_V
Warncall -wc randFully implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...

 

...