Skip to content

Commit

Permalink
[backport:1.0] json: limit recursion depth (#19252)
Browse files Browse the repository at this point in the history
* json: limit recursion depth

* do not run this check for JS backend

(cherry picked from commit c17baae)
  • Loading branch information
narimiran committed Dec 14, 2021
1 parent f577229 commit a57b1d7
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ type
of JArray:
elems*: seq[JsonNode]

const DepthLimit = 1000

proc newJString*(s: string): JsonNode =
## Creates a new `JString JsonNode`.
result = JsonNode(kind: JString, str: s)
Expand Down Expand Up @@ -785,7 +787,7 @@ iterator mpairs*(node: var JsonNode): tuple[key: string, val: var JsonNode] =
for key, val in mpairs(node.fields):
yield (key, val)

proc parseJson(p: var JsonParser): JsonNode =
proc parseJson(p: var JsonParser, depth=0): JsonNode =
## Parses JSON from a JSON Parser `p`.
case p.tok
of tkString:
Expand All @@ -809,6 +811,8 @@ proc parseJson(p: var JsonParser): JsonNode =
result = newJNull()
discard getTok(p)
of tkCurlyLe:
if depth > DepthLimit:
raiseParseErr(p, "}")
result = newJObject()
discard getTok(p)
while p.tok != tkCurlyRi:
Expand All @@ -817,16 +821,18 @@ proc parseJson(p: var JsonParser): JsonNode =
var key = p.a
discard getTok(p)
eat(p, tkColon)
var val = parseJson(p)
var val = parseJson(p, depth+1)
result[key] = val
if p.tok != tkComma: break
discard getTok(p)
eat(p, tkCurlyRi)
of tkBracketLe:
if depth > DepthLimit:
raiseParseErr(p, "]")
result = newJArray()
discard getTok(p)
while p.tok != tkBracketRi:
result.add(parseJson(p))
result.add(parseJson(p, depth+1))
if p.tok != tkComma: break
discard getTok(p)
eat(p, tkBracketRi)
Expand Down

0 comments on commit a57b1d7

Please sign in to comment.