Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

/dev/urandom error (permission denied by webhost)

I am using function:

private function random($len) {
        if (@is_readable('/dev/urandom')) {
            $f=fopen('/dev/urandom', 'r');
            $urandom=fread($f, $len);
            fclose($f);
        }

        $return='';
        for ($i=0;$i<$len;++$i) {
            if (!isset($urandom)) {
                if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
                $rand=48+mt_rand()%64;
            } else $rand=48+ord($urandom[$i])%64;

            if ($rand>57)
                $rand+=7;
            if ($rand>90)
                $rand+=6;

            if ($rand==123) $rand=52;
            if ($rand==124) $rand=53;
            $return.=chr($rand);
        }
        return $return;
    }

I have some forms which trigger this function and I get the error:

int(2) string(200) "is_readable(): open_basedir restriction in effect. File(/dev/urandom) is not within the allowed path(s):

Is there a way to replace this function and not to use /dev/urandom ? Thank you very much.

like image 700
Bogdan Avatar asked Feb 14 '26 13:02

Bogdan


1 Answers

From the (previously accepted) answer:

Instead of urandom you can use "rand":

Nooooooooo!


Dealing with open_basedir is one of the things we handle gracefully in random_compat. Seriously consider importing that library then just using random_bytes() instead of reading from /dev/urandom.

Whatever you do, DON'T USE rand(). Even if you believe there's a use case for it, the security trade-offs are a lie.

Also, if you need a function to generate a random string (depends on PHP 7 or random_compat):

/**
 * Note: See https://paragonie.com/b/JvICXzh_jhLyt4y3 for an alternative implementation
 */
function random_string($length = 26, $alphabet = 'abcdefghijklmnopqrstuvwxyz234567')
{
    if ($length < 1) {
        throw new InvalidArgumentException('Length must be a positive integer');
    }
    $str = '';
    $alphamax = strlen($alphabet) - 1;
    if ($alphamax < 1) {
        throw new InvalidArgumentException('Invalid alphabet');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $alphabet[random_int(0, $alphamax)];
    }
    return $str;
}

Demo code: https://3v4l.org/DOjNE

like image 138
Scott Arciszewski Avatar answered Feb 17 '26 01:02

Scott Arciszewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!