Browse Source

Call math.randomseed() without arguments to seed from system entropy.

Reminder: the math.random() PRNG is NOT SUITABLE FOR CRYPTOGRAPHIC USE.
Mike Pall 1 month ago
parent
commit
04dca7911e
4 changed files with 13 additions and 3 deletions
  1. 5 1
      doc/extensions.html
  2. 2 1
      src/Makefile.dep
  3. 5 1
      src/lib_math.c
  4. 1 0
      src/lj_errmsg.h

+ 5 - 1
doc/extensions.html

@@ -265,7 +265,7 @@ and let the GC do its work.
 LuaJIT uses a Tausworthe PRNG with period 2^223 to implement
 <tt>math.random()</tt> and <tt>math.randomseed()</tt>. The quality of
 the PRNG results is much superior compared to the standard Lua
-implementation, which uses the platform-specific ANSI rand().
+implementation, which uses the platform-specific ANSI <tt>rand()</tt>.
 </p>
 <p>
 The PRNG generates the same sequences from the same seeds on all
@@ -276,6 +276,10 @@ It's correctly scaled up and rounded for <tt>math.random(n&nbsp;[,m])</tt> to
 preserve uniformity.
 </p>
 <p>
+Call <tt>math.randomseed()</tt> without any arguments to seed it from
+system entropy.
+</p>
+<p>
 Important: Neither this nor any other PRNG based on the simplistic
 <tt>math.random()</tt> API is suitable for cryptographic use.
 </p>

+ 2 - 1
src/Makefile.dep

@@ -32,7 +32,8 @@ lib_jit.o: lib_jit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
  lj_target.h lj_target_*.h lj_trace.h lj_dispatch.h lj_traceerr.h \
  lj_vm.h lj_vmevent.h lj_lib.h luajit.h lj_libdef.h
 lib_math.o: lib_math.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
- lj_def.h lj_arch.h lj_lib.h lj_vm.h lj_prng.h lj_libdef.h
+ lj_def.h lj_arch.h lj_err.h lj_errmsg.h lj_lib.h lj_vm.h lj_prng.h \
+ lj_libdef.h
 lib_os.o: lib_os.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
  lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_lib.h \
  lj_libdef.h

+ 5 - 1
src/lib_math.c

@@ -13,6 +13,7 @@
 #include "lualib.h"
 
 #include "lj_obj.h"
+#include "lj_err.h"
 #include "lj_lib.h"
 #include "lj_vm.h"
 #include "lj_prng.h"
@@ -183,7 +184,10 @@ LJLIB_PUSH(top-2)  /* Upvalue holds userdata with PRNGState. */
 LJLIB_CF(math_randomseed)
 {
   PRNGState *rs = (PRNGState *)(uddata(udataV(lj_lib_upvalue(L, 1))));
-  random_seed(rs, lj_lib_checknum(L, 1));
+  if (L->base != L->top)
+    random_seed(rs, lj_lib_checknum(L, 1));
+  else if (!lj_prng_seed_secure(rs))
+    lj_err_caller(L, LJ_ERR_PRNGSD);
   return 0;
 }
 

+ 1 - 0
src/lj_errmsg.h

@@ -79,6 +79,7 @@ ERRDEF(SETFENV,	LUA_QL("setfenv") " cannot change environment of given object")
 ERRDEF(CORUN,	"cannot resume running coroutine")
 ERRDEF(CODEAD,	"cannot resume dead coroutine")
 ERRDEF(COSUSP,	"cannot resume non-suspended coroutine")
+ERRDEF(PRNGSD,	"PRNG seeding failed")
 ERRDEF(TABINS,	"wrong number of arguments to " LUA_QL("insert"))
 ERRDEF(TABCAT,	"invalid value (%s) at index %d in table for " LUA_QL("concat"))
 ERRDEF(TABSORT,	"invalid order function for sorting")