This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug tree-optimization/78913] Probably misleading error reported by -Wformat-length


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78913

--- Comment #4 from Martin Sebor <msebor at gcc dot gnu.org> ---
I'm not sure I do understand exactly what you mean.  The warning in this
specific case is a false positive.  There is no easy way for GCC to avoid it
without compromising the checker's efficacy in general.  (There is, however, an
easy way to avoid the warning by changing the code.)

Let me explain the rationale for the warning (in the general case).  Unintended
truncation by snprintf has been linked to a number of vulnerabilities (see [1]
and [2]).  To avoid truncation, the snprintf destination buffer must be big
enough to hold the longest output of the function for the given format string
and the possible values of the arguments of the directives within it.

Ignoring the strcpy call for the moment, in the test case in comment #0, the
buffer is big enough for input strings at most 508 bytes long, but the "design"
allows the input to be as long as 511 bytes.  If a.path were 509 or more bytes
long the result would be truncated, missing some or all of the characters in
the "/_\n" suffix.  If the constructed path were to be used to create a
sensitive file in a privileged directory, the missing suffix could result in
the file being created in a directory accessible by unprivileged users.  (This
is the prototypical example of why -Wformat-length warns for snprintf and not
just sprintf.)  If a.path can never be longer than 508 characters then there
are a couple of ways to express that constraint:

1) use the %.508s directive instead of %s, or
2) verify the snprintf return value is less than 512.

As I explained, due to the limitation of the implementation, the length of the
string created by the strcpy call is not available to the checker and so it or
similar solutions (such as guarding the snprintf call by 'if (srrlen(a.path) <
508)) don't suppress the warning and will likely require extensive changes to
implement.

Of the two alternatives, (2) is the expected/recommended way to avoid both the
truncation and the warning.  (3) is a possible enhancement that could also be
used to suppress the warning (along with changing the code).

Does one of these alternatives resolve your concern?

[1] CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path
Traversal')
[2] The Art of Software Security Assessment: Identifying and Preventing
Software Vulnerabilities, chapter 8, Truncation

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]