Skip to content

nested ncr() calls can be very slow (potential denial of service) #62

Closed

Description

@invd

Issue description

I've recently discovered via fuzzing with libFuzzer that nested usage of the ncr() expression can result in unexpectedly long expression evaluation times.

The smallest representation of the problematic expression that I could find so far, as generated by libFuzzer:
ncr(ncr(2,7),1)
I measured around ~60s runtime at -O3 (with fuzzing instrumentation overhead) on a modern AMD Ryzen CPU.

This may be a low-severity security issue for projects that evaluate externally provided expression input.

Debug information:

The undefined behavior sanitizer also complains about the 'unsigned int' range, here are some variants:

tinyexpr.c:127:23: runtime error: nan is outside the range of representable values of type 'unsigned int'
tinyexpr.c:139:28: runtime error: -nan is outside the range of representable values of type 'unsigned int'
tinyexpr.c:139:28: runtime error: nan is outside the range of representable values of type 'unsigned int'
tinyexpr.c:139:52: runtime error: -nan is outside the range of representable values of type 'unsigned int'
tinyexpr.c:139:52: runtime error: nan is outside the range of representable values of type 'unsigned int'

Some gdb debug info for the above mentioned ncr(ncr(2,7),1) case where this happens:

Thread 1 "tinyexpr_fuzzer" hit Breakpoint 1, ncr
(n=nan(0x8000000000000), r=1) at tinyexpr.c:139
139	    unsigned long int un = (unsigned int)(n), ur = (unsigned int)(r), i;
(gdb) bt
#0  ncr (n=nan(0x8000000000000), r=1) at tinyexpr.c:139
#1  0x000000000055d8fe in te_eval (n=0x603000000100) at tinyexpr.c:532
#2  0x0000000000569940 in optimize (n=0x603000000100) at tinyexpr.c:580
#3  0x00000000005681b9 in te_compile (expression=0x7fffffffd780 "ncr(ncr(2,7),1)", variables=0x0, var_count=0, error=0x0) at tinyexpr.c:606
#4  0x0000000000569d6b in te_interp (expression=0x7fffffffd780 "ncr(ncr(2,7),1)", error=0x0) at tinyexpr.c:614
#5  0x000000000055366b in LLVMFuzzerTestOneInput (data=0x6020000000b0 "ncr(ncr(2,7),1)", size=15) at tinyexpr_fuzzer.c:29
(gdb) print r
$1 = 1
(gdb) print n
$2 = nan(0x8000000000000)
(gdb) print i
$3 = 105690555220240

Disclosure information

I have privately reported this issue to @codeplea. He asked me to document it via a public Github issue.

Activity

  1. codeplea commented on Jun 26, 2020

    @codeplea
    Owner

    Thanks for the issue.

    I don't think it's possible to add a timeout option (without bringing in external dependencies, which I won't do), so I'll probably address this in two ways:

    1. Add a compile-time option to disable the functions that use loops (fac, ncr, npr, possibly others).
    2. Document it in the readme.
  2. mortie commented on Oct 12, 2020

    @mortie
    Contributor

    Well, it would be possible to add a timeout, albeit not in a very nice way. You could make a tick function which calls time() and compares it to a start time, then bails if the elapsed time is greater than a timeout, then sprinkle in calls to tick() in strategic locations throughout the code. For example, you could call tick() at the top of te_eval and every nth iteration in the loop-based functions.

    The balance between performance and accuracy would be super hard to get right, but it would be a useful feature.

  3. juntuu commented on Jul 26, 2021

    @juntuu

    The cause seems to be ncr(NAN, 1), which goes into pathologically slowly advancing loop for some reason.

    Printing the values with %lu format just before the loop, I got:

    un = 0
    ur = 18446744073709551615
    

    Seeing, that the project is now using c99, isnan should be available, so checking the nan should be reasonable mitigation on this issue. I opened a PR #82 adding those.

  4. invd commented on Jun 18, 2024

    @invd
    Author

    @codeplea it would be great to see this bug finally fixed via @juntuu 's #82 after 4+ years.

    This will also help with @DavidKorczynski 's efforts for #114, since the GitHub fuzzing action jobs will otherwise spend a lot of time on timeouts.

    Basic reproducer based on example.c, can be used under the project's zlib license:

    #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    
    #include "tinyexpr.h"
    
    int main(int argc, char *argv[])
    {
        const char *c = "ncr(ncr(2,7),1)";
        double r = te_interp(c, 0);
        printf("the execution of this calculation should be slow");
        return 0;
    }

    For completeness, here is the fuzzer harness code I used to find the issue:

    #include <stdio.h>
    #include <stdint.h>
    #include <string.h>
    
    #include "tinyexpr.h"
    
    #define FUZZER_MAX_INPUT_LENGTH 512
    
    int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
      
        if(size > FUZZER_MAX_INPUT_LENGTH) {
          return 0;
        }
    
        char inputbuffer[FUZZER_MAX_INPUT_LENGTH + 1] = {0};
        memcpy(inputbuffer, data, size);
        // null-terminate
        inputbuffer[size] = 0;
        
        // call target
        double r = te_interp(inputbuffer, 0);
        
        return 0;
    }

    I also make this available under zlib license so it can be used in the project.

    Compared with the fuzzer harness proposed in #114, it has a restricted max length through fixed stack buffer usage (-> less heap allocations), and doesn't pre-define expression variables. Otherwise it's fairly similar.

  5. RAK2315 commented on Aug 1, 2026

    @RAK2315

    Independent confirmation of this, plus a smaller reproducer, from building a differential test harness against tinyexpr.

    The nesting is incidental. The title suggests composed ncr() calls are the problem, but ncr(ncr(2,7),1) is just a way to manufacture a NaN — any NaN-valued first argument does it, with no nesting at all:

    $ gcc -O2 -o probe probe.c tinyexpr.c -lm     # tinyexpr @ 4a7456e2
    
      ncr(0/0,1)         = inf   18.322 s
      ncr(sqrt(-1),1)    = inf   18.386 s
      npr(sqrt(-1),1)    = inf   18.352 s
      ncr(sqrt(-1),2)    = inf    0.014 s
      ncr(sqrt(-1),3)    = inf    0.000 s
      ncr(0,1)           = nan    0.000 s
    

    ncr(0/0,1) is ten characters and burns ~18 seconds of CPU.

    Why r == 1 specifically. With n NaN, the guards at tinyexpr.c:142-143 are all false (every comparison against NaN is), so un becomes 0 while ur stays 1. Then:

    if (ur > un / 2) ur = un - ur;     /* 0 - 1, unsigned -> ULONG_MAX */

    The loop bound becomes ULONG_MAX, and the overflow guard result > ULONG_MAX / (un - ur + i) is what actually terminates it. But with ur == ULONG_MAX the denominator is i + 1, so result grows only linearly (result == i + 1 at every step) and the guard does not trip until i is around 2^32 — roughly 4.3 billion iterations.

    For r >= 2 the product grows quadratically or faster and overflows almost immediately, which is why only r == 1 is pathological.

    ncr(0,1) correctly returns NaN via the n < r guard — it is specifically NaN that leaks through.

    Related to #133. Same root cause: NaN → unsigned int is UB. On x86-64, gcc lowers that conversion to cvttsd2si into a 64-bit register and uses the low 32 bits; NaN yields 0x8000000000000000, whose low half is zero. That is also why fac(sqrt(-1)) returns 1.0 rather than garbage — the loop bound becomes 0 and the loop never runs.

    A NaN check at the top of ncr and fac addresses both. I have no opinion on whether that should be #82's approach or #138's; just noting the two issues look like the same defect observed from different ends.

    Happy to supply the timing harness if useful.

  6. codeplea commented on Aug 5, 2026

    @codeplea
    Owner

    Fixed in 9108148, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions