From 9bf47f75e221584c9dbfaf36b9df3fead497dbd0 Mon Sep 17 00:00:00 2001
From: Brad Jorsch <bjorsch@wikimedia.org>
Date: Fri, 12 Jan 2018 13:27:45 -0500
Subject: [PATCH] SECURITY: Reduce precision on os.clock() to mitigate timing
 attacks

Bug: T184156
Change-Id: I3defbb9aefd018d9cfe4a1389ec57afcc417825a
---
 library.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/library.c b/library.c
index 32b807e..76168af 100644
--- a/library.c
+++ b/library.c
@@ -11,6 +11,7 @@
 #include <lua.h>
 #include <lauxlib.h>
 #include <lualib.h>
+#include <math.h>
 
 #include "php.h"
 #include "php_luasandbox.h"
@@ -450,14 +451,21 @@ static int luasandbox_base_xpcall (lua_State *L)
  */
 static int luasandbox_os_clock(lua_State * L)
 {
+	double clock;
+
 #ifdef LUASANDBOX_NO_CLOCK
-	lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
+	clock = ((double)clock())/(double)CLOCKS_PER_SEC;
 #else
 	struct timespec ts;
 	php_luasandbox_obj * sandbox = luasandbox_get_php_obj(L);
 	luasandbox_timer_get_usage(&sandbox->timer, &ts);
-	lua_pushnumber(L, ts.tv_sec + 1e-9 * ts.tv_nsec);
+	clock = ts.tv_sec + 1e-9 * ts.tv_nsec;
 #endif
+
+	// Reduce precision to 20μs to mitigate timing attacks
+	clock = round(clock * 50000) / 50000;
+
+	lua_pushnumber(L, (lua_Number)clock);
 	return 1;
 }
 
-- 
2.15.1

