From aeee2f910634ff0a496d679d53a116d5457dc60c Mon Sep 17 00:00:00 2001 From: Gautham <41098605+ahgamut@users.noreply.github.com> Date: Mon, 11 Jul 2022 20:47:58 +0530 Subject: [PATCH] Add depth limit for JSON (#476) --- 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 \