libnds icon indicating copy to clipboard operation
libnds copied to clipboard

Possible read out-of-bounds in `con_write`

Open trustytrojan opened this issue 5 months ago • 3 comments

https://github.com/devkitPro/libnds/blob/6194b32d8f94e2ebc8078e64bf213ffc13ba1985/source/arm9/console.c#L221-L223

I got a crash/exception on line 223 when calling std::ostream::write(char *, size_t) with buffers of unknown size (coming from libcurl during an HTTP request). By instead iterating the buffer myself and calling libc's putchar or libstdc++'s std::ostream::operator<<(char), there was no crash/exception.

I believe this might be due to the loop check on line 221 not checking for a possible early null-termination. A possible fix would be:

while (*tmp && i < len)

trustytrojan avatar Aug 01 '25 16:08 trustytrojan

con_write receives a sized buffer (it is the implementation of write(2) for libnds's console stdout), not a NULL terminated string.

By any chance are you using \x1b console escape codes?

fincs avatar Aug 01 '25 17:08 fincs

The HTTP response did have a lot of escape codes, yes, that could be the cause. For reference the URL is https://pretzels.onthewifi.com/spy, go to it in a browser and you'll see the escape codes are RGB/Truecolor sequences (ESC[38;2;{r};{g};{b}m) which I'm aware the default libnds console does not support, but the crash wasn't expected so I looked into it.

trustytrojan avatar Aug 01 '25 17:08 trustytrojan

One more thing to note: Beforehand I disabled stdout buffering completely with this line:

setvbuf(stdout, NULL, _IONBF, 0);

Without this line, a heap-overflow occurred, which I could recognize by seeing the contents of memory spill out into the console.

It would be nice if your implementation of the POSIX standard I/O streams did not buffer by default, especially on limited memory platforms like the NDS or GBA.

trustytrojan avatar Aug 01 '25 17:08 trustytrojan