From b02150f87072c3231afb6d4d9b98240425bd65f1 Mon Sep 17 00:00:00 2001 From: ahgamut <41098605+ahgamut@users.noreply.github.com> Date: Mon, 11 Jul 2022 19:39:05 +0530 Subject: [PATCH] add depth limit for JSON - json depth limit set as 1024 - STACK_FRAME_UNLIMITED for ljson.c - every call of Parse checks if the limit will be crossed alternative: check stack at the start of Parse everytime, and adjust when necessary. --- tool/net/ljson.c | 11 ++++++++++- tool/net/net.mk | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tool/net/ljson.c b/tool/net/ljson.c index c65849589..c00d6ab94 100644 --- a/tool/net/ljson.c +++ b/tool/net/ljson.c @@ -27,6 +27,8 @@ #include "third_party/lua/ltests.h" #include "third_party/lua/lua.h" +#define MAX_JSON_DEPTH 1024 + struct Rc { int t; const char *p; @@ -39,6 +41,10 @@ static struct Rc Parse(struct lua_State *L, const char *p, const char *e) { const char *a; luaL_Buffer b; int A, B, C, D, c, d, i, u; + if (lua_gettop(L) >= MAX_JSON_DEPTH) { + luaL_error(L, "maximum depth exceeded\n"); + return (struct Rc){-1, p}; + } for (a = p, d = +1; p < e;) { switch ((c = *p++ & 255)) { default: @@ -316,6 +322,9 @@ static struct Rc Parse(struct lua_State *L, const char *p, const char *e) { */ int DecodeJson(struct lua_State *L, const char *p, size_t n) { if (n == -1) n = p ? strlen(p) : 0; - lua_checkstack(L, 128); + if(!lua_checkstack(L, MAX_JSON_DEPTH + MAX_JSON_DEPTH/2)) { + luaL_error(L, "unable to set stack depth of %d\n", MAX_JSON_DEPTH + MAX_JSON_DEPTH/2); + return -1; + } return Parse(L, p, p + n).t; } diff --git a/tool/net/net.mk b/tool/net/net.mk index c6288fcc8..7cd230e30 100644 --- a/tool/net/net.mk +++ b/tool/net/net.mk @@ -210,6 +210,9 @@ o/$(MODE)/tool/net/demo/virtualbean.html.zip.o: \ -Predbean.justine.lol \ -B +o/$(MODE)/tool/net/ljson.o: \ + -DSTACK_FRAME_UNLIMITED + o/$(MODE)/tool/net/redbean-demo.com.dbg: \ $(TOOL_NET_DEPS) \ o/$(MODE)/tool/net/redbean.o \