Unsafe Functions In C And Their Safer Replacements: Strings Part II
Tuesday, December 2nd, 2008Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
Last time, we advised you to use ditch the unsafe functions like strcpy and strcat, and use their safer replacements (strlcpy, strlcat) instead. However, there is a small problem with this that you might discover that your compiler (especially gcc) does not have these functions in their implementation of the c library (libc). Why is this so? Read this thread about the original patch that was submitted to add these functions to libc. Essentially, it was rejected on the basis that these functions hide problems instead of solving them and would actually lead to hard to detect bugs that creep in because of unsolicited truncation caused by these functions. A sample implementation of strlcpy looks like this:
#include <sys/types.h> #include <string.h> /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ size_t strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) == '\0') break; } } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ }
Now, there are supporters for both the sides. Solaris and BSD accepted these functions while GNU/Linux refuses to do so till date. The stand that I’d like to take here is that this is at least a step towards the right direction because a truncation bug is much better than an attacker taking over the control of your network just by pushing out a long string onto the stack. However, we could indeed augment the implementation above to communicate back to the caller somehow that truncation occurred. Whichever side you choose, be aware that these problems are very real and don’t just keep on using the older unsafe versions (Even in words of Ulrich Drepper, the opposer of strlcpy: “ The users of these functions[strcpy, strcat] should be severly punished”).
© Safer Code | Unsafe Functions In C And Their Safer Replacements: Strings Part II
|
Liked this post? Get FREE Updates Subscribe to RSS feed |