Skip to content

Catching string overflows#339

Merged
jgfoster merged 42 commits intoOpen-Acidification:mainfrom
je-foster:strlcpy
Dec 11, 2022
Merged

Catching string overflows#339
jgfoster merged 42 commits intoOpen-Acidification:mainfrom
je-foster:strlcpy

Conversation

@je-foster
Copy link
Contributor

These changes aim to replace strcpy(), strncpy(), and dtostrf(), which can cause overflows.

  • strcpy() does not respect destination size at all, and easily overflows allocated memory.
  • strncpy() is much better, but it always fills the destination by padding the end with as many null characters as necessary. Worse, if it fills the destination then it does not null-terminate. So the next read from that memory will overflow if the correct read size isn't coded.
  • dtostrf() has no limit on the number of characters it prints, so if the float has a greater than expected magnitude, the destination will overflow.

A good replacement for the string copy functions would be strlcpy(), but it is not available in all C++ libraries. I can compile it and put it on the Arduino device, but when I upload my code to GitHub, the tests fail because its compiler doesn't recognize strlcpy().

For copying strings, I've added a "strscpy()" function to TC_util.cpp. If the destination is too small to fit the source plus a null terminator, then it will write a truncated, null-terminated string. It will also record in the day's log file that the string was truncated to avoid overflow. There's a similar strscpy_P() function for addresses in PROGMEM.

For printing floats, I've added a "floattostrf()" function to TC_util.cpp. It uses dtostrf() to print the float to a temporary buffer whose size is 10 bytes larger than the destination, and then it uses strscpy() to copy that buffer to the destination. Therefore there will be appropriate logging if the string is truncated. Eventually it might be better to replace "3552148" with "99999" instead of "35521", for example, but I think even truncation is preferable to the current (potential) behavior of overflowing the destination.

I hope this is a positive contribution; I'd be happy to hear feedback!

Copy link
Member

@jgfoster jgfoster left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry this took so long to review. I have just a few small questions...

@jgfoster jgfoster merged commit 6871716 into Open-Acidification:main Dec 11, 2022
@je-foster je-foster deleted the strlcpy branch December 12, 2022 15:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants