0

regerror returns the number of bytes that are needed to store the error message. Since the application I'm working with isn't going "deep" in the stack (i.e. no deeply nested function calls) I was thinking about using alloca (which the application is already using for other purposes) to acquire temporary storage for the error message on the stack (rather than the heap).

Is it safe to assume that the error message (length) will be bounded, so that I don't run into a stack overflow?

Does this open a security hole (by manipulating the used message catalog)?

size_t const length = regerror(status, regex, NULL, 0);
char * const buffer = alloca(length);
size_t const check_length = regerror(status, regex, buffer, length);
assert(check_length == length);
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
  • 1
    `alloca()` is no more or less dangerous than using a variable-length array (VLA). – Andrew Henle Jun 15 '16 at 15:15
  • 1
    Provided that you're not pushing the limits of your stack space already, it should be fine. As long as the allocating function doesn't return before everything is done with the buffer, and as long as the function you pass it to doesn't free or resize it, there wouldn't be a problem. – Dmitri Jun 15 '16 at 15:16
  • 2
    Micro-optimizing error handling and reporting code is not useful, nobody can read that fast. Just use the free store and you'll never have to be sorry. – Hans Passant Jun 15 '16 at 15:17
  • @Dmitri What I'm concerned with is whether the error message length could be (by an attacker) made extremely long, causing a stack overflow. – Daniel Jour Jun 15 '16 at 15:25
  • @HansPassant True, but using `malloc` is not that nice, because the application uses a garbage collected heap *and* is further processing that error message directly afterwards (storing a not NULL terminated copy of it). Currently there's a (large) fixed size buffer on the stack, I'd like to make that a bit more elegant. – Daniel Jour Jun 15 '16 at 15:27
  • 1
    @DanielJour If you're concerned with an attacker causing a stack overflow, use a fixed-length array of a known safe size and either don't allow longer error messages to be generated or use `malloc()`/`free()` for longer messages. – Andrew Henle Jun 15 '16 at 15:30
  • @Dmitri Yes, but if the first invocation of `regerror` returns a huge size, I'll `alloca` too much on the stack (causing the overflow). – Daniel Jour Jun 15 '16 at 15:31
  • Just check the length returned by the first call, and if it's ridiculously large use a smaller one and live with a truncated error message.. or fall back to a dynamically allocated buffer in that case.. – Dmitri Jun 15 '16 at 15:33
  • @AndrewHenle Yes, I guess that's what I'm doing then. In the expected case, the messages are quite short, so this'll probably keep the buffer stack allocated unless somebody is actively trying to do harm. – Daniel Jour Jun 15 '16 at 15:33

0 Answers0