Re: Buffer overflow in "lpr"

Todd Vierling (tv@POBOX.COM)
Wed, 09 Jul 1997 11:21:33 -0400

On Tue, 8 Jul 1997, Casper Dik wrote:

: >strncat wouldn't do what you wanted in this case. It would append at
: >most BUFSIZ characters, rather than at most BUFSIZE-strlen(buf)
: >characters. Also, you need to '\0' terminate the buf after this
: >because str*cat doesn't do that for you.

: strncat(a,b,n): append at most n characters from b to a; then add NUL byte.

: Yep, standards are that warped.

Try this on for size: strlcat(), a limited strcat() that limits on total
buffer size rather than source argument size. I found this idea somewhere
in a book long forgotten, but here's a diff for lib/libc/string/strncat.c
that implements it.

Usage:

char *strlcat(char *dst, const char *src, size_t n);

Concatenate src on the end of dst. At most n+1 bytes are written at dst (at
most n+1-strlen(dst) bytes being appended). If n<=strlen(dst), does
nothing. Returns dst.

*** strncat.c Wed Jul 9 10:46:00 1997
--- strlcat.c Wed Jul 9 10:51:42 1997
***************
*** 33,62 ****
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/

#if defined(LIBC_SCCS) && !defined(lint)
/*static char *sccsid = "from: @(#)strncat.c 5.6 (Berkeley) 1/26/91";*/
! static char *rcsid = "$Id: strncat.c,v 1.4 1995/06/15 00:08:07 jtc Exp $";
#endif /* LIBC_SCCS and not lint */

#include <string.h>

/*
! * Concatenate src on the end of dst. At most strlen(dst)+n+1 bytes
! * are written at dst (at most n+1 bytes being appended). Return dst.
*/
char *
! strncat(dst, src, n)
char *dst;
const char *src;
register size_t n;
{
! if (n != 0) {
! register char *d = dst;
register const char *s = src;

- while (*d != 0)
- d++;
do {
if ((*d = *s++) == 0)
break;
--- 33,67 ----
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
+ /* Adapted from strncat.c by Todd Vierling; Berkeley license above applies. */

#if defined(LIBC_SCCS) && !defined(lint)
/*static char *sccsid = "from: @(#)strncat.c 5.6 (Berkeley) 1/26/91";*/
! static char *rcsid = "$Id$";
#endif /* LIBC_SCCS and not lint */

#include <string.h>

/*
! * Concatenate src on the end of dst. At most n+1 bytes are written at dst
! * (at most n+1-strlen(dst) bytes being appended). If n<=strlen(dst),
! * does nothing. Returns dst.
*/
char *
! strlcat(dst, src, n)
char *dst;
const char *src;
register size_t n;
{
! register char *d = dst;
!
! while (*d != 0) {
! d++;
! n--;
! }
! if (n > 0) {
register const char *s = src;

do {
if ((*d = *s++) == 0)
break;

=====
== Todd Vierling (Personal tv@pobox.com; Business tv@iag.net) Foo-bar-baz! ==
== System administrator/technician, Internet Access Group, Orlando Florida ==
== Dialups in Orange, Volusia, Lake, Osceola counties - http://www.iag.net ==