1

I have a top-level console app targeting net5 with this code:

Work();
void Work()
{
    Work();
}

It will eventually throw a StackOverflowException and print to the console the last known stack size. Here are the results of a few runs:

32120
32113
32133
32127

I also see this variability of the stack size when I target .net framework 4.8.

I looked at ECMA-335 Standard: Common Language Infrastructure and found this sentence, regarding StackOverflowException: "The precise timing of this exception and the conditions under which it occurs are implementation-specific". Then I found out about ASLR (address space layout randomization), and thought that perhaps the CLI implementation uses a similar technique.

My question is, why does this variability exist and if ASLR is turned off, how could a potential attack work?

Mr Balanikas
  • 1,657
  • 15
  • 28
  • I always thought ASLR randomized the base address of stack/heaps/..., not their size, so ASLR shouldn't changed the maximum recursion depth of a program... But I'm not truly expert of the inner working of the .NET runtime – xanatos Dec 31 '20 at 14:27

1 Answers1

0

ASLR may limit the size of the stack if there is not enough space in that location for the stack to expand.

Do not assume anything about timing of StackOverflowException. Anytime you have a risk of hitting it due to deep recursion, you should use a custom Stack object on the heap and convert your code to the iterative form.

Charlieface
  • 52,284
  • 6
  • 19
  • 43