[GH-ISSUE #851] snprintf may or may not terminate trunacated strings #461

Closed
opened 2026-10-14 03:09:06 +07:00 by bsakaguchi · 15 comments
Owner

Originally created by @jfoug on GitHub (Nov 11, 2014).
Original GitHub issue: https://github.com/openwall/john/issues/851

Not all platforms null terminate a string when snprintf is used, and the buffer is not large enough (i.e. the end string gets truncated.)

The safer way to do this is:

char buf[48];
snprintf(buf,sizeof(buf),"%s",some_long_string);
buf[sizeof(buf)-1] =0;

This will be a no-op if some_long_string fits into buf, or if the compiler properly truncates. But on an environment which writes the full string with no null (on truncated string), then adding that null byte is needed.

I just spotted this issue when trying to add a > 32 byte scrypt hash (ScryptKDF.pm does longer than 32 bytes, and we need to make changes to handle that). The issue was seen in the format.c valid failure, which uses snprintf to write out the failed hash string.

Originally created by @jfoug on GitHub (Nov 11, 2014). Original GitHub issue: https://github.com/openwall/john/issues/851 Not all platforms null terminate a string when snprintf is used, and the buffer is not large enough (i.e. the end string gets truncated.) The safer way to do this is: char buf[48]; snprintf(buf,sizeof(buf),"%s",some_long_string); buf[sizeof(buf)-1] =0; This will be a no-op if some_long_string fits into buf, or if the compiler properly truncates. But on an environment which writes the full string with no null (on truncated string), then adding that null byte is needed. I just spotted this issue when trying to add a > 32 byte scrypt hash (ScryptKDF.pm does longer than 32 bytes, and we need to make changes to handle that). The issue was seen in the format.c valid failure, which uses snprintf to write out the failed hash string.
bsakaguchi 2026-10-14 03:09:06 +07:00
Author
Owner

@frank-dittrich commented on GitHub (Nov 11, 2014):

Acording to https://stackoverflow.com/questions/1505986/sprintf-s-with-a-buffer-too-small, the C99 standard requires snprintf() to null terminate the string unless the length of the string is 0. Section 7.19.6.5: If n is zero, nothing is written... Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

Does this problem occur only on platforms which don't have snprintf, so tat we redefine it as sprintf_s?
Is there a better macro definition then just replacing snprintf with a function that does something else?

<!-- gh-comment-id:62553234 --> @frank-dittrich commented on GitHub (Nov 11, 2014): Acording to https://stackoverflow.com/questions/1505986/sprintf-s-with-a-buffer-too-small, `the C99 standard requires snprintf() to null terminate the string unless the length of the string is 0. Section 7.19.6.5: If n is zero, nothing is written... Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.` Does this problem occur only on platforms which don't have `snprintf`, so tat we redefine it as `sprintf_s`? Is there a better macro definition then just replacing snprintf with a function that does something else?
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

Does this problem occur only on platforms which don't have snprintf, so tat we redefine it as sprintf_s?
Is there a better macro definition then just replacing snprintf with a function that does something else?

Yeah I doubt that any platform that actually has snprintf() will do it wrong. If you use a macro pointing to sprintf_s(), you should add that extra buf[sizeof(buf)-1] =0; to that macro, that's all.

<!-- gh-comment-id:62558394 --> @magnumripper commented on GitHub (Nov 11, 2014): > Does this problem occur only on platforms which don't have snprintf, so tat we redefine it as sprintf_s? > Is there a better macro definition then just replacing snprintf with a function that does something else? Yeah I doubt that any platform that actually has snprintf() will do it wrong. If you use a macro pointing to sprintf_s(), you should add that extra `buf[sizeof(buf)-1] =0;` to that macro, that's all.
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

That would need to be a variadic macro though. Something like

#define snprintf(str, size, ...) { sprintf_s(str, size, __VA_ARGS__); str[(size) - 1] = 0; }
<!-- gh-comment-id:62559272 --> @magnumripper commented on GitHub (Nov 11, 2014): That would need to be a variadic macro though. Something like ``` #define snprintf(str, size, ...) { sprintf_s(str, size, __VA_ARGS__); str[(size) - 1] = 0; } ```
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

VC has snprintf (actually _snprintf). I was using printf_s but that ends up having different 'safe' behavior. If the string is too long, VC throws an ESHORT error and abends.

Since VC may be the only one that has this problem, the above would work, using _snprint, while keeping it safe.

#define snprintf(str, size, ...) { _snprintf(str, size, __VA_ARGS__); str[size - 1] = 0; }

I will take a look at that. I do not know if there are other environments that have this issue. This is a long standing legacy issue in VC (from early 90's, way before C99)

<!-- gh-comment-id:62561424 --> @jfoug commented on GitHub (Nov 11, 2014): VC has snprintf (actually _snprintf). I was using printf_s but that ends up having different 'safe' behavior. If the string is too long, VC throws an ESHORT error and abends. Since VC may be the only one that has this problem, the above would work, using _snprint, while keeping it safe. ``` #define snprintf(str, size, ...) { _snprintf(str, size, __VA_ARGS__); str[size - 1] = 0; } ``` I will take a look at that. I do not know if there are other environments that have this issue. This is a long standing legacy issue in VC (from early 90's, way before C99)
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

Note I added parens in str[(size) - 1], they might be crucial at times.

<!-- gh-comment-id:62561941 --> @magnumripper commented on GitHub (Nov 11, 2014): Note I added parens in `str[(size) - 1]`, they might be crucial at times.
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

I also wrapped in a do { } while(0) so that block logic does not get screwed up such as:

if (x)
snprintf(xxxx);

without the do..while(0) we would not snprintf, but would null terminate. Other block logic may actually make things not compile at all

if (x)
snprintf(xxxx);
else
foobar();

that would compile to this without the dowhile

if (x)
   {snprintf(xxx); xxx[size-1]=0;};
else
   foobar(x);

which will not compile and will leave you scratching your head why.

<!-- gh-comment-id:62562503 --> @jfoug commented on GitHub (Nov 11, 2014): I also wrapped in a `do { } while(0)` so that block logic does not get screwed up such as: if (x) snprintf(xxxx); without the do..while(0) we would not snprintf, but would null terminate. Other block logic may actually make things not compile at all if (x) snprintf(xxxx); else foobar(); that would compile to this without the dowhile ``` if (x) {snprintf(xxx); xxx[size-1]=0;}; else foobar(x); ``` which will not compile and will leave you scratching your head why.
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

Note that we have one such define in jumbo.h and also one in regex.h

<!-- gh-comment-id:62562852 --> @magnumripper commented on GitHub (Nov 11, 2014): Note that we have one such define in jumbo.h and also one in regex.h
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

Noted. Here is the end result.

#define snprintf(str, size, ...) do { _snprintf((str), (size), __VA_ARGS__); str[(size) - 1] = 0; } while(0)
<!-- gh-comment-id:62562978 --> @jfoug commented on GitHub (Nov 11, 2014): Noted. Here is the end result. ``` #define snprintf(str, size, ...) do { _snprintf((str), (size), __VA_ARGS__); str[(size) - 1] = 0; } while(0) ```
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

Not sure how to work around this now, since snprintf returns an int.

rar2john.c : gecos_len += snprintf(&gecos[gecos_len], PATH_BUFFER_SIZE - 1, "%s ", (char*)file_name);

_snprintf in vc also returns a - value on truncation. The += is a bug anyway. snprintf returns length that WOULD be if it could do the whole thing. Thus on truncation, your len will be off.

<!-- gh-comment-id:62563898 --> @jfoug commented on GitHub (Nov 11, 2014): Not sure how to work around this now, since snprintf returns an int. rar2john.c : gecos_len += snprintf(&gecos[gecos_len], PATH_BUFFER_SIZE - 1, "%s ", (char*)file_name); _snprintf in vc also returns a - value on truncation. The += is a bug anyway. snprintf returns length that WOULD be if it could do the whole thing. Thus on truncation, your len will be off.
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

What we'd really want in that rar2john case is a strncat() that takes the buffer size as an argument as opposed to max. added size. We could write such function with ease.

What the heck were they thinking when they designed strncat()?

<!-- gh-comment-id:62565140 --> @magnumripper commented on GitHub (Nov 11, 2014): What we'd really want in that rar2john case is a strncat() that takes the **buffer size** as an argument as opposed to max. **added** size. We could write such function with ease. What the heck were they thinking when they designed strncat()?
Author
Owner

@frank-dittrich commented on GitHub (Nov 11, 2014):

On 11/11/2014 04:29 PM, JimF wrote:

Noted. Here is the end result.

|#define snprintf(str, size, ...) do { _snprintf((str), (size), VA_ARGS); str[(size) - 1] = 0; } while(0)

Make that

#define snprintf(str, size, ...) do { int i; i = size; _snprintf((str), i, VA_ARGS); str[i - 1] = 0; } while(0)

Just in case someone calls ||snprintf| with something like size++ or ++size as the size parameter.

<!-- gh-comment-id:62571750 --> @frank-dittrich commented on GitHub (Nov 11, 2014): On 11/11/2014 04:29 PM, JimF wrote: > Noted. Here is the end result. > > |#define snprintf(str, size, ...) do { _snprintf((str), (size), __VA_ARGS__); str[(size) - 1] = 0; } while(0) Make that #define snprintf(str, size, ...) do { int i; i = size; _snprintf((str), i, __VA_ARGS__); str[i - 1] = 0; } while(0) Just in case someone calls ||snprintf| with something like size++ or ++size as the size parameter.
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

What if an i is one of VA_ARGS? If using that version you should probably use something like __i or whatever.

<!-- gh-comment-id:62572355 --> @magnumripper commented on GitHub (Nov 11, 2014): What if an `i` is one of VA_ARGS? If using that version you should probably use something like `__i` or whatever.
Author
Owner

@magnumripper commented on GitHub (Nov 11, 2014):

What if an i is one of VA_ARGS?

We'll be chasing our tails anyway we do it. The only really safe option is to actually make it a function instead of a macro.

<!-- gh-comment-id:62572842 --> @magnumripper commented on GitHub (Nov 11, 2014): > What if an i is one of VA_ARGS? We'll be chasing our tails anyway we do it. The only really safe option is to actually make it a function instead of a macro.
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

That is what I did.

int vc_fixed_snprintf(char *dst, int maxcnt, const char *Fmt, ...);

I think this will fix the problems with old VC snprintf (termination and return value for truncated strings)

I could find no way with a macro, since snprintf returns a value, and we have to allow snprintf to be used as an rparam. No way to do multiple commands (even using comma) that I could think of. A function is better anyway. It still takes a macro to use it, but it can be done with either:

#define snprintf(str,size,...) vc_fixed_snprintf(str,size,__VA_ARGS__)
or 
#define snprintf vc_fixed_snprintf

Either will give identical results, with a function that has the same interface.

<!-- gh-comment-id:62575991 --> @jfoug commented on GitHub (Nov 11, 2014): That is what I did. int vc_fixed_snprintf(char *dst, int maxcnt, const char *Fmt, ...); I think this will fix the problems with old VC snprintf (termination and return value for truncated strings) I could find no way with a macro, since snprintf returns a value, and we have to allow snprintf to be used as an rparam. No way to do multiple commands (even using comma) that I could think of. A function is better anyway. It still takes a macro to use it, but it can be done with either: ``` #define snprintf(str,size,...) vc_fixed_snprintf(str,size,__VA_ARGS__) or #define snprintf vc_fixed_snprintf ``` Either will give identical results, with a function that has the same interface.
Author
Owner

@jfoug commented on GitHub (Nov 11, 2014):

Fixed. I checked against gcc/cygwin, both length, the buffer done, and the null match now. I had to grow the buffer to get the right return value. I would not need to do that, but did, so that it keeps full C99 compliance.

This will be in jumbo.c

int vc_fixed_snprintf(char *Dest, size_t max_cnt, const char *Fmt, ...) {
    va_list varg;
    int len;

    va_start(varg, Fmt);
    len = _vsnprintf(Dest, max_cnt, Fmt, varg);
    if (len < 0) {
        int len_now = max_cnt;
        Dest[max_cnt-1] = 0;
        // len = -1 right now.  We want to figure out exactly WHAT len should be, to stay C99 compliant.
        while (len < 0) {
            char *cp;
            len_now *= 2;
            cp = (char*)mem_alloc(len_now);
            len = _vsnprintf(cp, len_now, Fmt, varg);
            MEM_FREE(cp);
        }
    }
    va_end(varg);
    return len;
}
<!-- gh-comment-id:62581607 --> @jfoug commented on GitHub (Nov 11, 2014): Fixed. I checked against gcc/cygwin, both length, the buffer done, and the null match now. I had to grow the buffer to get the right return value. I would not need to do that, but did, so that it keeps full C99 compliance. This will be in jumbo.c ``` int vc_fixed_snprintf(char *Dest, size_t max_cnt, const char *Fmt, ...) { va_list varg; int len; va_start(varg, Fmt); len = _vsnprintf(Dest, max_cnt, Fmt, varg); if (len < 0) { int len_now = max_cnt; Dest[max_cnt-1] = 0; // len = -1 right now. We want to figure out exactly WHAT len should be, to stay C99 compliant. while (len < 0) { char *cp; len_now *= 2; cp = (char*)mem_alloc(len_now); len = _vsnprintf(cp, len_now, Fmt, varg); MEM_FREE(cp); } } va_end(varg); return len; } ```
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
openwall/john#461
No description provided.