Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modulo Bias #7

Open
stone14z opened this issue Jun 3, 2021 · 1 comment
Open

Modulo Bias #7

stone14z opened this issue Jun 3, 2021 · 1 comment

Comments

@stone14z
Copy link

stone14z commented Jun 3, 2021

pw_random_number(max_num) simply performs a modulo of a random integer against the number of elements in the character array. Since there is no check whether the maximum integer value is divisible by the number of elements in the character array, modulo bias is introduced. This would need to be fixed before the command is used to generate passwords for a high security environment.

@stone14z
Copy link
Author

stone14z commented Jun 3, 2021

The pw_random_number function can be re-written as follows to remove the modulo bias

/*

  • Generate a random number n, where 0 <= n < max_num, using

  • /dev/urandom if possible.

  • max_num is never greater than 127 for this application
    */
    int pw_random_number(max_num)
    int max_num;
    {
    unsigned char rand_num = 0xff;
    unsigned char mask = 0x7f;
    int i, fd = get_random_fd();
    int lose_counter = 0x1f;
    char *cp = (char *) &rand_num;

    if (max_num <= 0x3f) mask = 0x3f;
    if (max_num <= 0x1f) mask = 0x1f;

    if (fd >= 0) {
    while (rand_num >= (unsigned int)max_num) { // while loop removes modulo bias
    i = read(fd, cp, 1);
    rand_num &= mask;
    if ((i < 0) &&
    ((errno == EINTR) || (errno == EAGAIN)))
    continue;
    if (i <= 0) {
    if (!lose_counter--) break;
    continue;
    }
    }
    close(fd);
    return (rand_num);
    }

    /* We weren't able to use /dev/random, fail hard */

    fprintf(stderr, "No entropy available!\n");
    exit(1);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant