피드 구독

This article was originally published on the Red Hat Customer Portal. The information may no longer be current.

At least historically, misuse of functions like strcpystrcat, and sprintf was a common source of buffer overflow vulnerabilities. Therefore, in 1997, the Single UNIX Specification, Version 2, included a new interface for string construction that provided an explicit length of the output string: snprintf. This function can be used for string construction with explicit length checking.

Originally, it could be used in the following way:

    /* buff is a pointer to a buffer of blen characters. */
    /* Note well: This example is now incorrect. */
    char *cp = buff;
    if ((n = snprintf(cp, blen, "AF=%d ", sau->soa.sa_family)) < 0) {
        Warn1("sockaddr_info(): buffer too short ("F_Zu")", blen);
        *buff = '';
        return buff;
    }
    cp += n,  blen -= n;

This example is based on socat, but this coding pattern is still fairly common. The socat case is likely harmless as far as potential security impact is concerned.

The code in the above example avoids writing too much data to the buff pointer because early snprintf implementations returned -1 if the output string was truncated, based on this requirement from the Single UNIX Specification, Version 2:

Upon successful completion, these functions return the number of bytes transmitted excluding the terminating null in the case of sprintf() or snprintf() or a negative value if an output error was encountered.

However, the example code is insecure when compiled on current systems.

The specification quoted above is still ambiguous with regard to truncation, something that would be addressed during the standardization of the next version of C, ISO C99. As a result of that, in 2002, version 3 of the Single UNIX Specification was published, aligning the snprintf behavior with ISO C99:

Upon successful completion, the snprintf() function shall return the number of bytes that would be written to s had n been sufficiently large excluding the terminating null byte.

There is a remaining discrepancy between ISO C99 and POSIX regarding the EOVERFLOW return value, but we will ignore that. As far as the history can be retraced now, the GNU C Library adopted the ISO C99 behavior some time in 1998.

After this specification change, truncated output does not result in an error return value any more. Even worse, the result value exceeds the passed buffer length, making the pointer and length adjustment in the example invalid:

    cp += n,  blen -= n;

If the cp pointer and the blen argument are used in subsequent snprintf calls (which is often the case when the result from snprintf is used in pointer arithmetic), the buffer overflow vulnerability that snprintf was supposed to deal with resurfaces: cp points outside of the original buffer, and blen wraps around (after the conversion in size_t), resulting in a value that does not stop snprintf from writing to the invalid pointer.

Covering this error condition is somewhat difficult:

    char *cp = buff;
    n = snprintf(cp, blen, "AF=%d ", sau->soa.sa_family)
    if (n < 0) {
        Warn1("sockaddr_info(): snprintf failed: %s", strerror(errno));
        *buff = '';
        return buff;
    } else if (n >= blen) {
        Warn1("sockaddr_info(): buffer too short ("F_Zu")", blen);
        *buff = '';
        return buff;
    }
    cp += n,  blen -= n;

As a more convenient substitute, it is possible to ignore the return value from snprintf altogether, and acquire the number of written characters using strlen:

    char *cp = buff;
    assert(blen >= 1);
    *buff = 0;
    snprintf(cp, blen, "AF=%d ", sau->soa.sa_family)
    blen -= strlen(cp);
    cp += strlen(cp);

This code assumes that the snprintf implementation does not write an unterminated string to the destination buffer on error, which is quite reasonable as far as such assumptions go.  The value of strlen(cp) will always be less than the value of blen, so a subsequent snprintf will have room to write the null terminator.

Enhancing -D_FORTIFY_SOURCE=2 to cover the original example code reliably is difficult because GCC cannot track the size information through the pointer arithmetic following the snprintf call, so it is not available to subsequent snprintf calls. Another option would be to have snprintf abort in fortify mode when the buffer length passed in is INT_MAX or larger. Adding logic to GCC to deal with this snprintf oddity specifically is a bit dubious, considering that this only deals with misuse of a single library function.

Curiously, snprintf is not the only function that suffered from an interface change as the result of standardization. Another example is strerror_r, the thread-safe variant of strerror. Even today, it exists in two variants in the GNU C library, one that returns a pointer value (used with -D_GNU_SOURCE) and one that returns an int (the standardized version).

One can only hope that with increased openness of standardization processes and more participation from the free software community in the creation of mostly proprietary standard documents, future recurrences of this kind of problem can be avoided, for example by standardizing interfaces with conflicting implementations under completely new names.


저자 소개

UI_Icon-Red_Hat-Close-A-Black-RGB

채널별 검색

automation icon

오토메이션

기술, 팀, 인프라를 위한 IT 자동화 최신 동향

AI icon

인공지능

고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트

open hybrid cloud icon

오픈 하이브리드 클라우드

하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요

security icon

보안

환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보

edge icon

엣지 컴퓨팅

엣지에서의 운영을 단순화하는 플랫폼 업데이트

Infrastructure icon

인프라

세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보

application development icon

애플리케이션

복잡한 애플리케이션에 대한 솔루션 더 보기

Original series icon

오리지널 쇼

엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리