Paper - 1999 USENIX Annual Technical Conference, June 6-11, 1999, Monterey, California, USA
strlcpy and strlcat - consistent, safe, string copy and concatenation.
Todd C. Miller
Theo de Raadt
As the prevalence of buffer overflow attacks has increased, more and more programmers are using size or length-bounded string functions such as strncpy() and strncat(). While this is certainly an encouraging trend, the standard C string functions generally used were not really designed for the task. This paper describes an alternate, intuitive, and consistent API designed with safe string copies in mind.
There are several problems encountered when strncpy() and strncat() are used as safe versions of strcpy() and strcat(). Both functions deal with NUL-termination and the length parameter in different and non-intuitive ways that confuse even experienced programmers. They also provide no easy way to detect when truncation occurs. Finally, strncpy() zero-fills the remainder of the destination string, incurring a performance penalty. Of all these issues, the confusion caused by the length parameters and the related issue of NUL-termination are most important. When we audited the OpenBSD source tree for potential security holes we found rampant misuse of strncpy() and strncat(). While not all of these resulted in exploitable security holes, they made it clear that the rules for using strncpy() and strncat() in safe string operations are widely misunderstood. The proposed replacement functions, strlcpy() and strlcat(), address these problems by presenting an API designed for safe string copies (see Figure 1 for function prototypes). Both functions guarantee NUL-termination, take as a length parameter the size of the string in bytes, and provide an easy way to detect truncation. Neither function zero-fills unused bytes in the destination.
In the middle of 1996, the authors, along with other members of the OpenBSD project, undertook an audit of the OpenBSD source tree looking for security problems, starting with an emphasis on buffer overflows. Buffer overflows  had recently gotten a lot of attention in forums such as BugTraq  and were being widely exploited. We found a large number of overflows due to unbounded string copies using sprintf(), strcpy() and strcat(), as well as loops that manipulated strings without an explicate length check in the loop invariant. Additionally, we also found many instances where the programmer had tried to do safe string manipulation with strncpy() and strncat() but failed to grasp the subtleties of the API.
Thus, when auditing code, we found that not only was it necessary to check for unsafe usage of functions like strcpy() and strcat(), we also had to check for incorrect usage of strncpy() and strncat(). Checking for correct usage is not always obvious, especially in the case of ``static'' variables or buffers allocated via calloc(), which are effectively pre-terminated. We came to the conclusion that a foolproof alternative to strncpy() and strncat() was needed, primarily to simplify the job of the programmer, but also to make code auditing easier.
Figure 1: ANSI C prototypes for strlcpy() and strlcat()
The most common misconception is that strncpy() NUL-terminates the destination string. This is only true, however, if length of the source string is less than the size parameter. This can be problematic when copying user input that may be of arbitrary length into a fixed size buffer. The safest way to use strncpy() in this situation is to pass it one less than the size of the destination string, and then terminate the string by hand. That way you are guaranteed to always have a NUL-terminated destination string. Strictly speaking, it is not necessary to hand-terminate the string if it is a ``static'' variable or if it was allocated via calloc() since such strings are zeroed out when allocated. However, relying on this feature is generally confusing to those persons who must later maintain the code.
There is also an implicit assumption that converting code from strcpy() and strcat() to strncpy() and strncat() causes negligible performance degradation. With this is true of strncat(), the same cannot be said for strncpy() since it zero-fills the remaining bytes not used to store the string being copied. This can lead to a measurable performance hit when the size of the destination string is much greater than the length of the source string. The exact penalty for using strncpy() due to this behavior varies by CPU architecture and implementation.
The most common mistake made with strncat() is to use an incorrect size parameter. While strncat() does guarantee to NUL-terminate the destination, you must not count the space for the NUL in the size parameter. Most importantly, this is not the size of the destination string itself, rather it is the amount of space available. As this is almost always a value that must be computed, as opposed to a known constant, it is often computed incorrectly.
How do strlcpy() and strlcat() help things?
The strlcpy() and strlcat() functions provide a consistent, unambiguous
API to help the programmer write more bullet-proof code. First and
foremost, both strlcpy() and strlcat() guarantee to NUL-terminate the
destination string for all strings where the given size is non-zero.
Secondly, both functions take the full size of the destination string
as a size parameter. In most cases this value is easily computed at
compile time using the
The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that is simply the length of the source; for strlcat() that means the length of the destination (before concatenation) plus the length of the source. To check for truncation, the programmer need only verify that the return value is less than the size parameter. Thus, if truncation has occurred, the number of bytes needed to store the entire string is now known and the programmer may allocate more space and re-copy the strings if he or she wishes. The return value has similar semantics to the return value of snprintf() as implemented in BSD and as specified by the upcoming C9X specification  (note that not all snprintf() implementations currently comply with C9X). If no truncation occurred, the programmer now has the length of the resulting string. This is useful since it is common practice to build a string with strncpy() and strncat() and then to find the length of the result using strlen(). With strlcpy() and strlcat() the final strlen() is no longer necessary.
Example 1a is a code fragment with a potential buffer overflow (the HOME environment variable is controlled by the user and can be of arbitrary length).
Example 1a: Code fragment using strcpy() and strcat()
Example 1b is the same fragment converted to safely use strncpy() and strncat() (note that we have to terminate the destination by hand).
Example 1b: Converted to strncpy() and strncat()
Example 1c is a trivial conversion to the strlcpy()/strlcat() API. It has the advantage of being as simple as Example 1a, but it does not take advantage of the new API's return value.
Example 1c: Trivial conversion to strlcpy()/strlcat()
Since Example 1c is so easy to read and comprehend, it is simple to add additional checks to it. In Example 1d, we check the return value to make sure there was enough space for the source string. If there was not, we return an error. This is slightly more complicated but in addition to being more robust, it also avoids the final strlen() call.
Example 1d: Now with a check for truncation
Programmers are starting to avoid strncpy() due its poor performance when the target buffer is significantly larger than the length of the source string. For instance, the apache group  replaced calls to strncpy() with an internal function and noticed a performance improvement . Also, the ncurses  package recently removed an occurrence of strncpy(), resulting in a factor of four speedup of the tic utility. It is our hope that, in the future, more programmers will use the interface provided by strlcpy() rather than using a custom interface.
To get a feel for the worst-case scenario in comparing strncpy() and strlcpy(), we ran a test program that copies the string ``this is just a test'' 1000 times into a 1024 byte buffer. This is somewhat unfair to strncpy(), since by using a small string and a large buffer strncpy() has to fill most of the buffer with NUL characters. In practice, however, it is common to use a buffer that is much larger than the expected user input. For instance, pathname buffers are MAXPATHLEN long (1024 bytes), but most filenames are significantly shorter than that. The averages run times in Table 1 were generated on an HP9000/425t with a 25Mhz 68040 CPU running OpenBSD 2.5 and a DEC AXPPCI166 with a 166Mhz alpha CPU also running OpenBSD 2.5. In all cases, the same C versions of the functions were used and the times are the ``real time'' as reported by the time utility.
As can be seen in Table 1, the timings for strncpy() are far worse than those for strcpy() and strlcpy(). This is probably due not only to the cost of NUL padding but also because the CPU's data cache is effectively being flushed by the long stream of zeroes.
What strlcpy() and strlcat() are not
While strlcpy() and strlcat() are well-suited for dealing with
fixed-size buffers, they cannot replace strncpy() and strncat() in
all cases. There are still times where it is necessary to manipulate
buffers that are not true C strings (the strings in
Who uses strlcpy() and strlcat()?
The strlcpy() and strlcat() functions first appeared in OpenBSD 2.4. The functions have also recently been approved for inclusion in a future version of Solaris. Third-party packages are starting to pick up the API as well. For instance, the rsync  package now uses strlcpy() and provides its own version if the OS does not support it. It is our hope that other operating systems and applications will use strlcpy() and strlcat() in the future, and that it will receive standards acceptance at some time.
We plan to replace occurrences of strncpy() and strncat() with strlcpy() and strlcat() in OpenBSD where it is sensible to do so. While new code in OpenBSD is being written to use the new API, there is still a large amount of code that was converted to use strncpy() and strncat() during our original security audit. To this day, we continue to discover bugs due to incorrect usage of strncpy() and strncat() in existing code. Updating older code to use strlcpy() and strlcat() should serve to speed up some programs and uncover bugs in others.
The source code for strlcpy() and strlcat() is available free of charge and under a BSD-style license as part of the OpenBSD operating system. You may also download the code and its associated manual pages via anonymous ftp from ftp.openbsd.org in the directory /pub/OpenBSD/src/lib/libc/string. The source code for strlcpy() and strlcat() is in strlcpy.c and strlcat.c. The documentation (which uses the tmac.doc troff macros) may be found in strlcpy.3.
Todd C. Miller has been involved in the free software community since 1993 when he took over maintenance of the sudo package. He joined the OpenBSD project in 1996 as an active developer. Todd belatedly received a BS in Computer Science in 1997 from the University of Colorado, Boulder (after years of prodding). Todd has so far managed to avoid the corporate world and currently works as a Systems Administrator at the University of Colorado, Boulder blissfully ensconced in academia. He may be reached via email at <Todd.Miller@cs.colorado.edu>.
Theo de Raadt has been involved with free Unix operating systems since 1990. Early developments included porting Minix to the sun3/50 and amiga, and PDP-11 BSD 2.9 to a 68030 computer. As one of the founders of the NetBSD project, Theo worked on maintaining and improving many system components including the sparc port and a free YP implementation that is now in use by most free systems. In 1995 Theo created the OpenBSD project, which places focus on security, integrated cryptography, and code correctness. Theo works full time on advancing OpenBSD. He may be reached via email at <email@example.com>.
This paper was originally published in the
Proceedings of the 1999 USENIX Annual Technical Conference, June 6-11, 1999, Monterey, California, USA
Last changed: 1 Mar 2002 ml