[ntp:hackers] Please use strlcpy(), strlcat() in NTP distribution.

Dave Hart hart at ntp.org
Tue Apr 5 22:43:50 UTC 2011

I've converted nearly all of the strcpy() and strncpy() uses in NTP to use
strlcpy(), and strcat() and strncat() to strlcat().  The big win is the
strl... routines always null-terminate the resulting string, even when
truncating.  strncpy() zero-fills after the string to the end of the buffer,
which is needlessly expensive particularly with larger buffers.  strncat()
is difficult to use correctly, as it takes not the buffer size but the
remaining buffer after the existing string.  Most uses in NTP got this
wrong, refclock_jjy.c being the major exception.  strlcpy() and strlcat()
are documented in both ntp_stdlib.h and libntp/strl_obsd.c, but here's the
cheat sheet:

To avoid buffer overrun and ignore truncation, call them passing the
sizeof(buffer) or equivalent, and ignore the return value.  The return value
is the strlen() of the string that would have resulted, assuming sufficient
buffer.  The return value will be strictly less than the provided size if
the string fits, so to check for truncation:

if (strlcpy(buf, src, sizeof(buf)) >= sizeof(buf))
    /* handle truncation */

The remaining strcpy()/strcat() calls in lib/isc and sntp/libopts have all
been audited and have no overrun issues.  That leaves
ports/winnt/instsrv/instsrv.c and ntp_crypto.c as the only strcpy()/strcat()
consumers.  I'll take care of ntp_crypto.c separately.  I'm tempted to
remove instsrv, adapted from an ancient BIND windows port.  I never use it
or recommend its use.

http://www.gratisoft.us/todd/papers/strlcpy.html is from the mid-90s when
strlcpy() and strlcat() were introduced.

Dave Hart

More information about the hackers mailing list