6 ms·
Wouldn't a "safe" api require size parameters on both the source and destination? We have historically had security bugs that over run on both sides, right? W
by TheCondor 13y ago
Wouldn't a "safe" api require size parameters on both the source and destination? We have historically had security bugs that over run on both sides, right? Why only address half the problem?
I like C, I use it, I use it in my work, but I simply cannot understand why we don't pay more attention to its huge problems to give compatibility with an ancient standard library.
- clarry 13y agoThat really depends. Error checking gets suddenly even more complicated if you also need some way to handle the case where the source string isn't a string. If you don't know what your source is, how can you pass its length to the function? On the other hand, if you know its length, then you should know that it is NUL-terminated (i.e. it is a string), or you should be able to NUL-terminate it. Perhaps there is some scenario where a helper function could also be used to force NUL-termination on a fixed-size source buffer (say, after fetching input with read()). But I cannot think of one that makes a lot of sense. For instance, having to forcibly NUL-terminate a bufferful of data from read() would imply data loss: you've read too much and now one byte was replaced with a zero. How would your safe function signal this error condition, and how would you react? In the end you'd have to fix the broken code so it leaves one space for the NUL. By contrast, strcat/cpy generally speaking do not catch broken-code errors (that is difficult anyway); they only implement some correct code. Also, reading past the end of the input buffer is much less likely to lead to an exploitable hole (unless you count DoS, but then how would your "safe" function react anyway?). EDIT: One of the goals in OBSD helper functions is simplicity. The rationale being that if doing the right thing is too complicated, the right thing won't be done (lazy programmers!). And, of course, all complications make human error more likely. This is why strlcat and strlcpy are not the solution to any and all string handling ever; sometimes you need something smarter, e.g. for performance. But these functions are great when they're good enough (which is plenty often, if you trust any of the code that actually uses these!).
- tedunangst 13y agoIf you never write a string past the end of a buffer, you will never read past the end. If your program starts in a correct state, write operations are where it can possibly transition to an incorrect state. The strlcpy function helps maintain the invariant that all strings in your program are actually strings, not unbounded nonsense, and so the source will be safe to use.