Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx random variables

Good morning programmers, I'm trying to create random variables on nginx, (I have OpenResty nginx+lua). Here is an example of a static variable:

set $teste 123;

So is it possible to turn this static variable random?

like image 976
xorhax5 Avatar asked Sep 05 '25 02:09

xorhax5


1 Answers

You need to provide random seed, otherwise you'll get the same values each time the server is restarted.

There I use resty.random.bytes (that internally uses RAND_pseudo_bytes or RAND_bytes from OpenSSL) to provide cryptographically strong pseudo-random seed on nginx worker start.

UPD: You should use resty_random.bytes(n, true) for really cryptographically strong pseudo-random value. If the second argument is true, RAND_bytes will be used instead of RAND_pseudo_byte. But in this case you'll have to deal with possible exhaustion of the entropy pool. That is, resty_random.bytes(n, true) could return nil if there is no enough randomness to ensure an unpredictable byte sequence.

http {

    init_worker_by_lua_block {
        local resty_random = require('resty.random')
        -- use random byte (0..255 int) as a seed
        local seed = string.byte(resty_random.bytes(1))
        math.randomseed(seed)
    }

    server {
        listen 8888;

        location = / {
            set_by_lua_block $random {
                return math.random(1, 100)
            }

            echo "random number: $random";

        }
    }
}
like image 54
Dmitry Meyer Avatar answered Sep 08 '25 12:09

Dmitry Meyer