Address overflows pointed out by Coverity
Subsystems (2)
cover Address overflows pointed out by Coverity
This patch series is part of my effort to bring Git for Windows' Coverity reports down to zero; Previous patch series have been merged in 347fe8a91b5 (Merge branch 'js/coverity-fixes', 2026-07-16), 0b75ef5168c (Merge branch 'js/coverity-fixes-null-safety', 2026-07-19), fcc8c931b53 (Merge branch 'js/coverity-unchecked-returns-fix', 2026-08-24) and 8bc9c7fcfd8 (Merge branch 'js/coverity-fixes', 2026-10-03).
Johannes Schindelin (5):
archive-tar: guard get_path_prefix against zero-length input
http: use size_t for byte position in fwrite_sha1_file
wrapper: reject insanely large byte counts when reading/writing
git-compat-util: add signed_mult_overflows and mult_overflows
macros
date: avoid overflow in approxidate relative-time multiplication
archive-tar.c | 2 ++ date.c | 26 +++++++++++++++++++++-- git-compat-util.h | 54 +++++++++++++++++++++++++++++++++++++++++++++++ http.c | 2 +- wrapper.c | 10 +++++++++ 5 files changed, 91 insertions(+), 3 deletions(-)
base-commit: 6de20f6092dcf9bdb1c8efe03db4b70c82b423dd
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2253%2Fdscho%2Fcoverity-fixes-overflow-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2253/dscho/coverity-fixes-overflow-v1
Pull-Request: https://github.com/gitgitgadget/git/pull/2253
Signature · 1 line
gitgitgadget
PATCH 1/5 archive-tar: guard get_path_prefix against zero-length input
From: Johannes Schindelin <[email protected]>
The get_path_prefix() function uses a do ... while() loop that unconditionally decrements the size_t index variable before checking the loop condition. When that variable is 0 on entry, the decrement wraps to SIZE_MAX, and path[SIZE_MAX] is an out-of-bounds read.
The current caller (write_tar_entry()) only invokes this function when pathlen > sizeof(header.name) i.e. when pathlen is at least 100. Therefore, the bug is unreachable in practice.
However, the function's interface accepts arbitrary pathlen and maxlen values, and a future caller or a maxlen of 0 could trigger the wrap, so let's add a check for that.
Pointed out by Coverity.
--- archive-tar.c | 2 ++ 1 file changed, 2 insertions(+)
archive-tar.c +2 -0
@@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen) i--;if (i > maxlen) i = maxlen; +if (!i) +return 0 ;do { i--; }while (i >0 && path[i] !='/' );
Signature · 1 line
gitgitgadget
PATCH 2/5 http: use `size_t` for byte position in fwrite_sha1_file
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
The fwrite_sha1_file() function tracks the number of bytes written via an int variable, but the total size to write is of type size_t. When the HTTP response body exceeds INT_MAX (~2GB), this causes an overflow and a heap under-read, then writes that data to the local object file.
The hash check afterward would reject the corrupt object (so no bad data enters the object store), but the under-read itself could leak adjacent heap contents to the temporary file. In practice this is unlikely because curl delivers data in small chunks (typically 16KB per callback invocation), so in practice, the total size is far below INT_MAX in a single call. However, the function interface accepts arbitrary sizes, and the accumulation across the loop means that the int variable grows across calls within a single invocation, not across callbacks.
Change the type from int to size_t to match the type of the total size. This is a hardening fix: the attack surface (a malicious HTTP server triggering a >2GB single-callback delivery) is theoretical under normal curl configurations, but the type mismatch is a genuine defect.
Pointed out by Coverity.
--- http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
http.c +1 -1
@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;
Signature · 1 line
gitgitgadget
Re: [PATCH 2/5] http: use `size_t` for byte position in fwrite_sha1_file
http.c static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, · line 2853
Quoted 12 lines · Johannes Schindelin via GitGitGadget
http.c +1
-1@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;
Right. This is how we access the variable:
do {
ssize_t retval = xwrite(freq->localfile,
(char *) ptr + posn, size - posn);
if (retval < 0)
return posn / eltsize;
posn += retval;
} while (posn < size);So it's clear that it doesn't have to be signed either, as we only ever add positive values to it.
Patrick
Re: [PATCH 2/5] http: use `size_t` for byte position in fwrite_sha1_file
Quoted 24 lines · Patrick Steinhardt
http.c static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, · line 2853
Quoted 12 lines · Johannes Schindelin via GitGitGadget
http.c +1
-1@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;Right. This is how we access the variable:
do { ssize_t retval = xwrite(freq->localfile, (char *) ptr + posn, size - posn); if (retval < 0) return posn / eltsize; posn += retval; } while (posn < size);
Quoted 2 lines
So it's clear that it doesn't have to be signed either, as we only ever add positive values to it.
I agree that changing the type of posn from int to size_t is the right move.
But I wondered what happens when (size - posn) is larger than half the range of the ssize_t type early in the loop. After all, the proposed commit log message worries about the case where HTTP response body exceeds 2GB.
Shouldn't the loop clamp the bytecount passed to xwrite() below whatever would fit in ssize_t when successful? It may end up making two calls of xwrite, writing 1.5GB each, to write out 3GB payload, but that would be better than attempting to write 3GB, succeed, and be fooled by ssize_t that is narrower by size_t by at least one bit that we got a negative return from xwrite() and return an error from here, when in reality we have written them all?
... goes and looks ...
Ah, nevermind. The big comment in git-compat-util.h before MAX_IO_SIZE clarifies all of the above. In short, xwrite() takes care of clamping, so its callers including this code do not have to worry about it.
Re: [PATCH 2/5] http: use `size_t` for byte position in fwrite_sha1_file
Hi,
Quoted 2 lines · Junio C Hamano
I agree that changing the type of posn from int to
size_tis the right move.
It is a position in a file that is being read as binary data[1], so off_t would be the best choice I think.
That is still signed, but it can't overflow, because opening large files requires O_LARGEFILE, which is available only if large file support is enabled, which conveniently makes sure that off_t is 64 bit.
Simon
[1] to make a distinction from the use case for fpos_t
Re: [PATCH 2/5] http: use `size_t` for byte position in fwrite_sha1_file
Quoted 5 lines · Simon Richter
Quoted 2 lines
I agree that changing the type of posn from int to
size_tis the right move.It is a position in a file that is being read as binary data[1], so
off_twould be the best choice I think.
Hmm, interesting. The function writes out eltsize * nmemb (both are of type size_t) bytes, so the total could theoretically exceed the range that fits size_t.
But the thing is that posn is used this way
ssize_t retval = xwrite(freq->localfile, (char *) ptr + posn, size - posn);
to offset into a contiguous in-core region that starts at ptr. I am not sure if (ptr + posn) is still valid for posn that is too large to fit in size_t, though.
To put it differently, we are writing out what is in the contiguous in-core region and posn runs up to the allocation size of that region, which should be measured in size_t, no?
Re: [PATCH 2/5] http: use `size_t` for byte position in fwrite_sha1_file
In reply to Simon RichterQuoted 5 lines · Simon Richter
Quoted 2 lines
I agree that changing the type of posn from int to
size_tis the right move.It is a position in a file that is being read as binary data[1], so
off_twould be the best choice I think.
Interesting.
The function writes out eltsize * nmemb bytes (both of type size_t), which means the product could theoretically exceed the range of size_t. However, posn is used in xwrite() to offset into a contiguous in-core buffer starting at ptr:
ssize_t retval = xwrite(freq->localfile,
(char *) ptr + posn,
size - posn);Because we are indexing into an allocated in-core region, any valid offset must fit within size_t. If posn were to exceed the bounds of size_t, the pointer arithmetic ptr + posn would already be invalid. As posn only runs up to the allocation size of the region, it indeed should be measured in size_t, no?
PATCH 3/5 wrapper: reject insanely large byte counts when reading/writing
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Both the read_in_full() as well as the write_in_full() function accumulate the bytes transferred count in a variable of type ssize_t, but accept a size_t count parameter. When count exceeds SSIZE_MAX, that total count overflows after processing SSIZE_MAX bytes, producing a negative return value that callers interpret as an error (or worse, a small positive value after further wrapping).
In practice, git never passes such large counts because file sizes and buffer allocations are bounded well below SSIZE_MAX on all target platforms. The POSIX specification for read() and write() also limits single operations to SSIZE_MAX bytes, and git's xread()/xwrite() wrappers further clamp to MAX_IO_SIZE. But the accumulation in the *_in_full() wrappers means that even with per-call clamping, total can exceed SSIZE_MAX when count does.
Reject a total count that exceeds the range of ssize_t upfront with EINVAL rather than silently producing wrong return values, matching the POSIX convention for invalid arguments.
Pointed out by Coverity.
--- git-compat-util.h | 4 ++++ wrapper.c | 10 ++++++++++ 2 files changed, 14 insertions(+)
git-compat-util.h +4 -0
@@ -740,6 +740,10 @@ static inline uint64_t u64_add(uint64_t a, uint64_t b)*/ #define DEFAULT_IO_BUFFER_SIZE (128 * 1024) +#ifndef SSIZE_MAX +# define SSIZE_MAX ((ssize_t)(((size_t)-1) >> 1)) +#endif +#ifdef HAVE_ALLOCA_H # include <alloca.h> # define xalloca (size) (alloca(size))
wrapper.c +10 -0
@@ -288,6 +288,11 @@ ssize_t read_in_full(int fd, void *buf, size_t count)char *p = buf;ssize_t total =0 ; +if (count >SSIZE_MAX ) { + errno =EINVAL ; +return -1 ; + } +while (count >0 ) {ssize_t loaded =xread (fd, p, count);if (loaded <0 )
@@ -307,6 +312,11 @@ ssize_t write_in_full(int fd, const void *buf, size_t count)const char *p = buf;ssize_t total =0 ; +if (count >SSIZE_MAX ) { + errno =EINVAL ; +return -1 ; + } +while (count >0 ) {ssize_t written =xwrite (fd, p, count);if (written <0 )
Signature · 1 line
gitgitgadget
Re: [PATCH 3/5] wrapper: reject insanely large byte counts when reading/writing
Hi Johannes
Quoted 9 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Both the
read_in_full()as well as thewrite_in_full()function accumulate the bytes transferred count in a variable of typessize_t, but accept asize_tcount parameter. When count exceedsSSIZE_MAX, that total count overflows after processingSSIZE_MAXbytes, producing a negative return value that callers interpret as an error (or worse, a small positive value after further wrapping).
Quoted 3 lines
In practice, git never passes such large counts because file sizes and buffer allocations are bounded well below
SSIZE_MAXon all target platforms.
Are we sure about that? In the past we've had bug fixes such as c14e5a1a50 (transport-helper: use xread instead of read, 2019-01-03)
on platforms where ssize_t is narrower that size_t (POSIX does not require them to be the same width). I've cc'd Randall to see if ssize_t is still narrower than size_t on the NonStop platforms git supports.
Thanks
Phillip
Quoted 62 lines
The POSIX specification for
read()andwrite()also limits single operations toSSIZE_MAXbytes, and git'sxread()/xwrite()wrappers further clamp toMAX_IO_SIZE. But the accumulation in the*_in_full()wrappers means that even with per-call clamping, total can exceedSSIZE_MAXwhen count does.Reject a total count that exceeds the range of
ssize_tupfront withEINVALrather than silently producing wrong return values, matching the POSIX convention for invalid arguments.Pointed out by Coverity.
Assisted-by Claude Opus 4.6Signed-off-by Johannes Schindelin <[email protected]>--- git-compat-util.h | 4 ++++ wrapper.c | 10 ++++++++++ 2 files changed, 14 insertions(+)git-compat-util.h +4
-0@@ -740,6 +740,10 @@ static inline uint64_t u64_add(uint64_t a, uint64_t b)*/ #define DEFAULT_IO_BUFFER_SIZE (128 * 1024) +#ifndef SSIZE_MAX +# define SSIZE_MAX ((ssize_t)(((size_t)-1) >> 1)) +#endif +#ifdef HAVE_ALLOCA_H # include <alloca.h> # define xalloca (size) (alloca(size))wrapper.c +10
-0@@ -288,6 +288,11 @@ ssize_t read_in_full(int fd, void *buf, size_t count)char *p = buf;ssize_t total =0 ; +if (count >SSIZE_MAX ) { + errno =EINVAL ; +return -1 ; + } +while (count >0 ) {ssize_t loaded =xread (fd, p, count);if (loaded <0 )@@ -307,6 +312,11 @@ ssize_t write_in_full(int fd, const void *buf, size_t count)const char *p = buf;ssize_t total =0 ; +if (count >SSIZE_MAX ) { + errno =EINVAL ; +return -1 ; + } +while (count >0 ) {ssize_t written =xwrite (fd, p, count);if (written <0 )
Re: [PATCH 3/5] wrapper: reject insanely large byte counts when reading/writing
Hi Phillip,
Quoted 14 lines · Phillip Wood
Quoted 9 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Both the
read_in_full()as well as thewrite_in_full()function accumulate the bytes transferred count in a variable of typessize_t, but accept asize_tcount parameter. When count exceedsSSIZE_MAX, that total count overflows after processingSSIZE_MAXbytes, producing a negative return value that callers interpret as an error (or worse, a small positive value after further wrapping).Quoted 3 lines
In practice, git never passes such large counts because file sizes and buffer allocations are bounded well below
SSIZE_MAXon all target platforms.
Quoted 5 lines
Are we sure about that? In the past we've had bug fixes such as
c14e5a1a50(transport-helper: use xread instead of read, 2019-01-03)
on platforms wheressize_tis narrower thatsize_t(POSIX does not require them to be the same width). I've cc'd Randall to see ifssize_tis still narrower thansize_ton the NonStop platforms git supports.
True. Even if there should be no current caller like this, there could easily be future callers like this.
So I changed this patch in the following ways:
- write_in_full() pointlessly returns the exact same count that the caller already passed upon success, modulo truncation to ssize_t. This is not useful, and I simply changed the signature to return 0 upon success.
- read_in_full(): many callers are really only interested whether this read was successful or not. Those callers now call a new function, read_in_full_or_error(), which returns 0 on success, -1 on error. The callers that did want the byte count returned but pass too large a size now no longer result in a bogus, negative return value, but instead error out. This might not be the _most_ desirable outcome, but it is better than before, and those callers would have to be vetted individually for better solutions (for which, as you can judge by the time it took me to get v2 out the door, I simply lack the bandwidth).
Ciao,
Johannes
PATCH 4/5 git-compat-util: add `signed_mult_overflows` and `mult_overflows` macros
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
unsigned_mult_overflows() does not cover signed arithmetic, but types such as time_t can be signed or unsigned. Add signed and type-generic guards so callers can check multiplication overflow in either case.
Overflow depends on the product type selected by C's usual arithmetic conversions. Products equal to the signed minimum are representable and must not be rejected.
--- git-compat-util.h | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+)
git-compat-util.h +50 -0
@@ -85,9 +85,27 @@ struct strbuf;#define bitsizeof (x) (CHAR_BIT * sizeof(x)) +#if GIT_GNUC_PREREQ (3 ,1 ) +#define is_unsigned_type (a) ((__typeof__(a))-1 >= 0) +#elif __STDC_VERSION__ >=201112L +#define is_unsigned_type (a) _Generic((a), \ + unsigned char: 1, \ + unsigned short: 1, \ + unsigned int: 1, \ + unsigned long: 1, \ + unsigned long long: 1, \ + _Bool: 1, \ + char: (CHAR_MIN == 0), \ + default: 0) +#endif +#define maximum_signed_value_of_type (a) \ (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a))) +/* Account for the extra negative value on two's-complement targets. */ +#define minimum_signed_value_of_type (a) \ + (-maximum_signed_value_of_type(a) - (INTMAX_MIN < -INTMAX_MAX)) +#define maximum_unsigned_value_of_type (a) \ (UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
@@ -111,6 +129,38 @@ struct strbuf;#define unsigned_mult_overflows (a, b) \ ((a) && (b) > maximum_unsigned_value_of_type(a) / (a)) +/* +* Returns true if the multiplication of "a" and "b" will +* overflow or underflow a signed type. The types of "a" and "b" +* must match and must be signed. Note that this macro evaluates +* both "a" and "b" twice! +*/ +#define signed_mult_overflows (a, b) \ + (((a) > 0 && (b) > 0 && (a) > maximum_signed_value_of_type(a) / (b)) || \ + ((a) < 0 && (b) < 0 && (a) < maximum_signed_value_of_type(a) / (b)) || \ + ((a) > 0 && (b) < 0 && (b) < minimum_signed_value_of_type(a) / (a)) || \ + ((a) < 0 && (b) > 0 && (a) < minimum_signed_value_of_type(b) / (b))) + +/* +* Returns true if the product of "a" and "b", after the usual arithmetic +* conversions, cannot be represented in the multiplication expression's +* type. The operands must be integers and may be evaluated more than once. +*/ +#if GIT_GNUC_PREREQ (3 ,1 ) +#define mult_overflows (a, b) \ + (is_unsigned_type((a) * (b)) \ + ? unsigned_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b)) \ + : signed_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b))) +#else +/* +* This implementation needs GNU `typeof` to convert both operands to the +* multiplication's type. Skip the check without that extension. +*/ +#define mult_overflows (a, b) 0 +#endif +/* * Returns true if the left shift of "a" by "shift" bits will * overflow. The type of "a" must be unsigned.
Signature · 1 line
gitgitgadget
Re: [PATCH 4/5] git-compat-util: add `signed_mult_overflows` and `mult_overflows` macros
Hi Johannes
Quoted 5 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
unsigned_mult_overflows()does not cover signed arithmetic, but types such astime_tcan be signed or unsigned. Add signed and type-generic guards so callers can check multiplication overflow in either case.
It would have been nice to mention that the type-generic macro is gcc only so we cannot rely on this for safety checks.
git-compat-util.h struct strbuf; · line 107
Quoted 6 lines
#define maximum_signed_value_of_type(a) \ (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))git-compat-util.h +3
-0+/* Account for the extra negative value on two's-complement targets. */ +#define minimum_signed_value_of_type (a) \ + (-maximum_signed_value_of_type(a) - (INTMAX_MIN < -INTMAX_MAX))
Do we support any platforms that do not use two's complement arithmetic? C23 makes it mandatory so presumably there are not may contemporary platforms out there that do not use it.
Quoted 5 lines
+/*
+ * Returns true if the multiplication of "a" and "b" will
+ * overflow or underflow a signed type. The types of "a" and "b"
+ * must match and must be signed. Note that this macro evaluates
+ * both "a" and "b" twice!
At least twice I think
Quoted 2 lines
+ */
+#definesigned_mult_overflows(a, b)\
As the macro relies on both operands being the same width, can we use BUILD_ASSERT_OR_ZERO() to ensure sizeof(a) == sizeof(b) here?
git-compat-util.h struct strbuf; · line 142
Quoted 4 lines
git-compat-util.h +4
-0+ (((a) >0 && (b) >0 && (a) >maximum_signed_value_of_type (a) / (b)) || \ + ((a) <0 && (b) <0 && (a) <maximum_signed_value_of_type (a) / (b)) || \ + ((a) >0 && (b) <0 && (b) <minimum_signed_value_of_type (a) / (a)) || \ + ((a) <0 && (b) >0 && (a) <minimum_signed_value_of_type (b) / (b)))
Thanks
Phillip
Quoted 24 lines
git-compat-util.h +21
-0+ +/* +* Returns true if the product of "a" and "b", after the usual arithmetic +* conversions, cannot be represented in the multiplication expression's +* type. The operands must be integers and may be evaluated more than once. +*/ +#if GIT_GNUC_PREREQ (3 ,1 ) +#define mult_overflows (a, b) \ + (is_unsigned_type((a) * (b)) \ + ? unsigned_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b)) \ + : signed_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b))) +#else +/* +* This implementation needs GNU `typeof` to convert both operands to the +* multiplication's type. Skip the check without that extension. +*/ +#define mult_overflows (a, b) 0 +#endif +/* * Returns true if the left shift of "a" by "shift" bits will * overflow. The type of "a" must be unsigned.
Re: [PATCH 4/5] git-compat-util: add `signed_mult_overflows` and `mult_overflows` macros
Hi Phillip,
Quoted 9 lines · Phillip Wood
Quoted 5 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
unsigned_mult_overflows()does not cover signed arithmetic, but types such astime_tcan be signed or unsigned. Add signed and type-generic guards so callers can check multiplication overflow in either case.It would have been nice to mention that the type-generic macro is gcc only so we cannot rely on this for safety checks.
True. And that is really not satifying at all.
Quoted 9 lines
git-compat-util.h struct strbuf; · line 107
Quoted 5 lines
#define
maximum_signed_value_of_type(a)\
(INTMAX_MAX>> (bitsizeof(intmax_t)- bitsizeof(a)))
+/* Account for the extra negative value on two's-complement targets. */git-compat-util.h +2
-0+#define minimum_signed_value_of_type (a) \ + (-maximum_signed_value_of_type(a) - (INTMAX_MIN < -INTMAX_MAX))Do we support any platforms that do not use two's complement arithmetic? C23 makes it mandatory so presumably there are not may contemporary platforms out there that do not use it.
Honestly, I had not even thought about that. I just assumed that it was the C standard, not something C23 introduced. Sorry about that.
Quoted 6 lines
Quoted 5 lines
+/*
+ * Returns true if the multiplication of "a" and "b" will
+ * overflow or underflow a signed type. The types of "a" and "b"
+ * must match and must be signed. Note that this macro evaluates
+ * both "a" and "b" twice!
Quoted 15 lines
At least twice I think
Quoted 2 lines
+ */
+#definesigned_mult_overflows(a, b)\As the macro relies on both operands being the same width, can we use
BUILD_ASSERT_OR_ZERO()to ensure sizeof(a) == sizeof(b) here?Quoted 7 lines
+ (((a) > 0 && (b) > 0 && (a) >
maximum_signed_value_of_type(a)/ (b)) ||
\
+ ((a) < 0 && (b) < 0 && (a) <maximum_signed_value_of_type(a)/ (b)) ||
\
+ ((a) > 0 && (b) < 0 && (b) <minimum_signed_value_of_type(a)/ (a)) ||
\
+ ((a) < 0 && (b) > 0 && (a) <minimum_signed_value_of_type(b)/ (b)))
Thank you for reviewing to thoroughly, and essentially proving that this is a doomed approach.
I dropped these macros from v2.
Ciao,
Johannes
Quoted 31 lines
Thanks
Phillip
Quoted 24 lines
git-compat-util.h +21
-0+ +/* +* Returns true if the product of "a" and "b", after the usual arithmetic +* conversions, cannot be represented in the multiplication expression's +* type. The operands must be integers and may be evaluated more than once. +*/ +#if GIT_GNUC_PREREQ (3 ,1 ) +#define mult_overflows (a, b) \ + (is_unsigned_type((a) * (b)) \ + ? unsigned_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b)) \ + : signed_mult_overflows((__typeof__((a) * (b)))(a), \ + (__typeof__((a) * (b)))(b))) +#else +/* +* This implementation needs GNU `typeof` to convert both operands to the +* multiplication's type. Skip the check without that extension. +*/ +#define mult_overflows (a, b) 0 +#endif +/* * Returns true if the left shift of "a" by "shift" bits will * overflow. The type of "a" must be unsigned.
PATCH 5/5 date: avoid overflow in approxidate relative-time multiplication
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
The approxidate_alpha() function multiplies a time unit length (e.g., 604800 for weeks) by a user-supplied number to compute a time offset in seconds. Both operands are int, and the product is passed to update_tm() as time_t. For inputs like "99999 weeks ago", the int multiplication overflows (604800 * 99999 is roughly 60 billion, far beyond INT_MAX), producing a wrapped value that results in a wrong date.
Use the checked time_t multiplication so oversized products do not overflow or wrap around.
On platforms where time_t is unsigned (and where the pre-processor allows us to determine this fact), reject counts that are too large and report a parse error. Narrowing them first could otherwise produce negative or truncated values that become bogus offsets. Leave signed time_t count parsing unchanged.
Pointed out by Coverity.
--- date.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-)
date.c +24 -2
@@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +time_t length = tl->length, num_t = *num; +time_t seconds; +#ifndef is_unsigned_type + seconds = length * num_t; +#else +time_t max_val =is_unsigned_type (length) + ?maximum_unsigned_value_of_type (length) + :maximum_signed_value_of_type (length); + seconds =mult_overflows (length, num_t) + ? max_val : length * num_t; +#endif +update_tm (tm, now, seconds); *num =0 ; *touched =1 ;return end;
@@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +#ifdef is_unsigned_type +if (is_unsigned_type ((time_t )0 ) && + (number >INT_MAX || + number >maximum_unsigned_value_of_type ((time_t )0 ))) +return NULL ; +#endif *num = number; + }return end; }
@@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); +if (!date) { + *error_ret =1 ; +return 0 ; + } touched =1 ;continue ; }
Signature · 1 line
gitgitgadget
Re: [PATCH 5/5] date: avoid overflow in approxidate relative-time multiplication
"Johannes Schindelin via GitGitGadget" <[email protected]>
Quoted 5 lines · writes:
On platforms where
time_tis unsigned (and where the pre-processor allows us to determine this fact), reject counts that are too large and report a parse error. Narrowing them first could otherwise produce negative or truncated values that become bogus offsets. Leave signedtime_tcount parsing unchanged.
Does this mean that "git log -p" in a project that were made on reasonably sized platforms and then cloned to my box may cause the history traversal to stop with an error when a commit has author or committer timestamp that would not fit the time_t on my box?
It would have been horrible regression than showing the entire history with patches with bogus timestamp if it were the case.
But I do not think that is what happens. approxidate_careful() is only used to parse input by local user (e.g., "git commit --date="...", "git log @{...}"), and the changes in this patch would not affect behaviours of other uses of timestamps, so we are safe.
Quoted 57 lines
Signed-off-by Johannes Schindelin <[email protected]>--- date.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-)date.c +24
-2@@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +time_t length = tl->length, num_t = *num; +time_t seconds; +#ifndef is_unsigned_type + seconds = length * num_t; +#else +time_t max_val =is_unsigned_type (length) + ?maximum_unsigned_value_of_type (length) + :maximum_signed_value_of_type (length); + seconds =mult_overflows (length, num_t) + ? max_val : length * num_t; +#endif +update_tm (tm, now, seconds); *num =0 ; *touched =1 ;return end;@@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +#ifdef is_unsigned_type +if (is_unsigned_type ((time_t )0 ) && + (number >INT_MAX || + number >maximum_unsigned_value_of_type ((time_t )0 ))) +return NULL ; +#endif *num = number; + }return end; }@@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); +if (!date) { + *error_ret =1 ; +return 0 ; + } touched =1 ;continue ; }
Re: [PATCH 5/5] date: avoid overflow in approxidate relative-time multiplication
In reply to Johannes Schindelin via GitGitGadgetHi Johannes
Quoted 9 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
The
approxidate_alpha()function multiplies a time unit length (e.g., 604800 for weeks) by a user-supplied number to compute a time offset in seconds. Both operands areint, and the product is passed toupdate_tm()astime_t. For inputs like "99999 weeks ago", the int multiplication overflows (604800 * 99999 is roughly 60 billion, far beyondINT_MAX), producing a wrapped value that results in a wrong date.
Signed integer overflow is undefined so we don't necessarily get a wrapped value - the whole program is invalid.
It looks like "length" is always positive, can the user supplied number ever be negative?
Quoted 2 lines
Use the checked
time_tmultiplication so oversized products do not overflow or wrap around.
This is only true when compiling with gcc or clang though because mult_overflows() always returns 0 on other compilers, so we're still exposed to undefined behavior when compiling with a different compiler on platforms where time_t is signed. I wonder if it would be better to perform the multiplication on a known type and then check that the result can be losslessly converted to time_t
intmax_t length tl->length, num_t = *num, result; if (signed_mult_overflows(length, num_t)) // error result = length * num_t; if ((intmax_t)((time_t)result) != result || (result < 0 && (time_t)result > 0)) // error
that would avoid overflow on all platforms, regardless of the compiler and regardless of the type of time_t. Having mult_overflows() only implemented for gcc seems like a footgun waiting to happen when we're typically checking for overflow to avoid some form of bad behavior.
Quoted 5 lines
On platforms where
time_tis unsigned (and where the pre-processor allows us to determine this fact), reject counts that are too large and report a parse error. Narrowing them first could otherwise produce negative or truncated values that become bogus offsets. Leave signedtime_tcount parsing unchanged.
I'm a bit confused what this is trying to do - why can't we check this when time_t is signed?
if ((timestamp_t)((int)number) != number) return NULL return *val = value;
Ensures "value" fits in "val" without truncation, we could also add a check that value is positive when time_t is unsigned if we wanted.
Thanks
Phillip
Quoted 60 lines
Pointed out by Coverity.
Assisted-by Claude Opus 4.6 and GPT-6.1 SolSigned-off-by Johannes Schindelin <[email protected]>--- date.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-)date.c +24
-2@@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +time_t length = tl->length, num_t = *num; +time_t seconds; +#ifndef is_unsigned_type + seconds = length * num_t; +#else +time_t max_val =is_unsigned_type (length) + ?maximum_unsigned_value_of_type (length) + :maximum_signed_value_of_type (length); + seconds =mult_overflows (length, num_t) + ? max_val : length * num_t; +#endif +update_tm (tm, now, seconds); *num =0 ; *touched =1 ;return end;@@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +#ifdef is_unsigned_type +if (is_unsigned_type ((time_t )0 ) && + (number >INT_MAX || + number >maximum_unsigned_value_of_type ((time_t )0 ))) +return NULL ; +#endif *num = number; + }return end; }@@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); +if (!date) { + *error_ret =1 ; +return 0 ; + } touched =1 ;continue ; }
Re: [PATCH 5/5] date: avoid overflow in approxidate relative-time multiplication
Hi Phillip,
Quoted 11 lines · Phillip Wood
Quoted 9 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
The
approxidate_alpha()function multiplies a time unit length (e.g., 604800 for weeks) by a user-supplied number to compute a time offset in seconds. Both operands areint, and the product is passed toupdate_tm()astime_t. For inputs like "99999 weeks ago", the int multiplication overflows (604800 * 99999 is roughly 60 billion, far beyondINT_MAX), producing a wrapped value that results in a wrong date.
Quoted 5 lines
Signed integer overflow is undefined so we don't necessarily get a wrapped value - the whole program is invalid.
It looks like "length" is always positive, can the user supplied number ever be negative?
Indeed, length cannot be negative. My entire approach was overzealous. I've simply replaced the logic with much easier-to-review manual overflow checks.
Quoted 19 lines
Quoted 2 lines
Use the checked
time_tmultiplication so oversized products do not overflow or wrap around.This is only true when compiling with gcc or clang though because
mult_overflows()always returns 0 on other compilers, so we're still exposed to undefined behavior when compiling with a different compiler on platforms wheretime_tis signed. I wonder if it would be better to perform the multiplication on a known type and then check that the result can be losslessly converted totime_tintmax_t length tl->length, num_t = *num, result; if (signed_mult_overflows(length, num_t)) // error result = length * num_t; if ((intmax_t)((time_t)result) != result || (result < 0 && (time_t)result > 0)) // error
Quoted 4 lines
that would avoid overflow on all platforms, regardless of the compiler and regardless of the type of
time_t. Havingmult_overflows()only implemented for gcc seems like a footgun waiting to happen when we're typically checking for overflow to avoid some form of bad behavior.
Yes, this GCC-only logic wasn't very smart of me.
Quoted 9 lines
Quoted 5 lines
On platforms where
time_tis unsigned (and where the pre-processor allows us to determine this fact), reject counts that are too large and report a parse error. Narrowing them first could otherwise produce negative or truncated values that become bogus offsets. Leave signedtime_tcount parsing unchanged.I'm a bit confused what this is trying to do - why can't we check this when
time_tis signed?
Quoted 7 lines
if ((timestamp_t)((int)number) != number) return NULL return *val = value;Ensures "value" fits in "val" without truncation, we could also add a check that value is positive when
time_tis unsigned if we wanted.
I simply did if (number > INT_MAX) return NULL.
Thank you for your thorough review!
Johannes
Quoted 70 lines
Thanks
Phillip
Quoted 63 lines
Pointed out by Coverity.
Assisted-by Claude Opus 4.6 and GPT-6.1 SolSigned-off-by Johannes Schindelin <[email protected]>--- date.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-)date.c +12
-1@@ -1298,7 +1298,18 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +time_t length = tl->length, num_t = *num; +time_t seconds; +#ifndef is_unsigned_type + seconds = length * num_t; +#else +time_t max_val =is_unsigned_type (length) + ?maximum_unsigned_value_of_type (length) + :maximum_signed_value_of_type (length); + seconds =mult_overflows (length, num_t) + ? max_val : length * num_t; +#endif +update_tm (tm, now, seconds); *num =0 ; *touched =1 ;return end;date.c +0
-0@@ -1368,8 +1379,15 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
date.c +12
-1-if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +#ifdef is_unsigned_type +if (is_unsigned_type ((time_t )0 ) && + (number >INT_MAX || + number >maximum_unsigned_value_of_type ((time_t )0 ))) +return NULL ; +#endif *num = number; + }return end; }@@ -1398,6 +1416,10 @@ static timestamp_t approxidate_str(const char *date,if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); +if (!date) { + *error_ret =1 ; +return 0 ; + } touched =1 ;continue ; }
Quoted 6 lines
This patch series is part of my effort to bring Git for Windows' Coverity reports down to zero; Previous patch series have been merged in
347fe8a91b5(Merge branch 'js/coverity-fixes', 2026-07-16),0b75ef5168c(Merge branch 'js/coverity-fixes-null-safety', 2026-07-19),fcc8c931b53(Merge branch 'js/coverity-unchecked-returns-fix', 2026-08-24) and8bc9c7fcfd8(Merge branch 'js/coverity-fixes', 2026-10-03).
Nice! Can Coverty run as part of GitHub CI? If so, once we have it down to zero, we can enable it to stop issues from creeping back in over time.
Harald
"Johannes Schindelin via GitGitGadget" <[email protected]>
Quoted 6 lines · writes:
This patch series is part of my effort to bring Git for Windows' Coverity reports down to zero; Previous patch series have been merged in
347fe8a91b5(Merge branch 'js/coverity-fixes', 2026-07-16),0b75ef5168c(Merge branch 'js/coverity-fixes-null-safety', 2026-07-19),fcc8c931b53(Merge branch 'js/coverity-unchecked-returns-fix', 2026-08-24) and8bc9c7fcfd8(Merge branch 'js/coverity-fixes', 2026-10-03).
It has been quite a while since we saw any activity on this thread.
The review discussion on patch [2/5] seems settled and I do not think the step needs any more work, but the review comments on patches [3/5], [4/5], and [5/5] are still awaiting a response from the author. The topic has been in the "Waiting for response" state since around Oct 17 (more than 20 days), and without any further activity, I will let it expire from my tree before long.
Thanks.
v2 cover Address overflows pointed out by Coverity
In reply to Johannes Schindelin via GitGitGadgetThis patch series is part of my effort to bring Git for Windows' Coverity reports down to zero; Previous patch series have been merged in 347fe8a91b5 (Merge branch 'js/coverity-fixes', 2026-07-16), 0b75ef5168c (Merge branch 'js/coverity-fixes-null-safety', 2026-07-19), fcc8c931b53 (Merge branch 'js/coverity-unchecked-returns-fix', 2026-08-24) and 8bc9c7fcfd8 (Merge branch 'js/coverity-fixes', 2026-10-03).
Changes since v1:
* Most callers of read_in_full() and all callers of write_in_full() are now no longer restricted by the range of ssize_t.
* The signed_mult_overflows() and mult_overflows() macros have been dropped.
* Since the approxidate() function only deals with non-negative values, the complicated overflow check could been simplified.
* Rebased to master, to avoid merge conflicts.
Johannes Schindelin (5):
archive-tar: guard get_path_prefix against zero-length input
http: use size_t for byte position in fwrite_sha1_file
wrapper: avoid byte-count overflow in write_in_full()
wrapper: add read_in_full_or_error()
date: avoid overflow in approxidate relative-time multiplication
Makefile | 1 + archive-tar.c | 2 + builtin/blame.c | 2 +- combine-diff.c | 6 +- date.c | 26 +++++++-- dir.c | 2 +- grep.c | 2 +- http.c | 2 +- imap-send.c | 2 +- notes-merge.c | 13 +---- refs/packed-backend.c | 4 +- strbuf.c | 10 +++- t/meson.build | 1 + t/t0006-date.sh | 13 +++++ t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 99 +++++++++++++++++++++++++++++++++ wrapper.c | 56 ++++++++++++++----- wrapper.h | 14 ++++- 18 files changed, 207 insertions(+), 50 deletions(-) create mode 100644 t/unit-tests/u-wrapper.c
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2253%2Fdscho%2Fcoverity-fixes-overflow-v2
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2253/dscho/coverity-fixes-overflow-v2
Pull-Request: https://github.com/gitgitgadget/git/pull/2253
Range-diff vs v1:
1: dcd319476a = 1: bb8225547f archive-tar: guard get_path_prefix against zero-length input 2: 70a909de18 ! 2: 38cc1dec53 http: use `size_t` for byte position in fwrite_sha1_file
@@ Commit message
Pointed out by Coverity.
- Assisted-by: Claude Opus 4.6
+ Helped-by: Patrick Steinhardt <[email protected]>
+ Helped-by: Junio C Hamano <[email protected]>
+ Assisted-by: Claude Opus 4.6 and GPT-6.1 Sol
## http.c ##
3: b1ed701935 < -: ---------- wrapper: reject insanely large byte counts when reading/writing
4: 3dcc3d9757 < -: ---------- git-compat-util: add `signed_mult_overflows` and `mult_overflows` macros
-: ---------- > 3: b24520c50d wrapper: avoid byte-count overflow in write_in_full()
-: ---------- > 4: ca30ed613d wrapper: add read_in_full_or_error()
5: a4e602b9e7 ! 5: 6057734709 date: avoid overflow in approxidate relative-time multiplication
@@ Metadata
## Commit message ##
date: avoid overflow in approxidate relative-time multiplication
- The `approxidate_alpha()` function multiplies a time unit length (e.g.,
- 604800 for weeks) by a user-supplied number to compute a time offset in
- seconds. Both operands are `int`, and the product is passed to
- `update_tm()` as `time_t`. For inputs like "99999 weeks ago", the int
- multiplication overflows (604800 * 99999 is roughly 60 billion, far
- beyond `INT_MAX`), producing a wrapped value that results in a wrong
- date.
+ Parsing relative dates can overflow `int` when multiplying a value by a
+ unit length, before converting the result to `time_t`. Signed overflow
+ is undefined behavior, therefore checking the converted value is too
+ late.
- Use the checked `time_t` multiplication so oversized products do not
- overflow or wrap around.
-
- On platforms where `time_t` is unsigned (and where the pre-processor
- allows us to determine this fact), reject counts that are too large and
- report a parse error. Narrowing them first could otherwise produce
- negative or truncated values that become bogus offsets. Leave signed
- `time_t` count parsing unchanged.
+ Reject quantities above `INT_MAX` before narrowing to `int` on all
+ platforms. The inputs are non-negative, meaning that checking unsigned
+ arithmetic is sufficient. The product must also fit the native `time_t`
+ range. Report arithmetic or conversion failures as parse errors rather
+ than saturating the offset.
Pointed out by Coverity.
- Assisted-by: Claude Opus 4.6 and GPT-6.1 Sol
+ Helped-by: Phillip Wood <[email protected]>
+ Assisted-by: Claude Opus 4.6 and GPT-6.1
Signed-off-by: Johannes Schindelin <[email protected]>
## date.c ##
@@ date.c: static const char *approxidate_alpha(const char *date, struct tm *tm, st
size_t len = strlen(tl->type);
if (match_string(date, tl->type) >= len-1) {
- update_tm(tm, now, tl->length * *num);
-+ time_t length = tl->length, num_t = *num;
-+ time_t seconds;
-+#ifndef is_unsigned_type
++ uintmax_t length = tl->length, num_t = *num, seconds;
++
++ if (unsigned_mult_overflows(length, num_t))
++ return NULL;
+ seconds = length * num_t;
-+#else
-+ time_t max_val = is_unsigned_type(length)
-+ ? maximum_unsigned_value_of_type(length)
-+ : maximum_signed_value_of_type(length);
-+ seconds = mult_overflows(length, num_t)
-+ ? max_val : length * num_t;
-+#endif
-+ update_tm(tm, now, seconds);
++ if (date_overflows(seconds))
++ return NULL;
++ update_tm(tm, now, (time_t)seconds);
*num = 0;
*touched = 1;
return end;
@@ date.c: static const char *approxidate_digit(const char *date, struct tm *tm, in
/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
- if (date[0] != '0' || end - date <= 2)
+ if (date[0] != '0' || end - date <= 2) {
-+#ifdef is_unsigned_type
-+ if (is_unsigned_type((time_t)0) &&
-+ (number > INT_MAX ||
-+ number > maximum_unsigned_value_of_type((time_t)0)))
++ if (number > INT_MAX)
+ return NULL;
-+#endif
*num = number;
+ }
return end;
}
@@ date.c: static timestamp_t approxidate_str(const char *date,
- if (isdigit(c)) {
+ if (!c)
+ break;
+ date++;
+- if (isdigit(c)) {
++ if (isalpha(c))
++ date = approxidate_alpha(date-1, &tm, &now,
++ &number, &touched);
++ else if (isdigit(c)) {
pending_number(&tm, &number);
date = approxidate_digit(date-1, &tm, &number, time_sec);
-+ if (!date) {
-+ *error_ret = 1;
-+ return 0;
-+ }
touched = 1;
- continue;
+- continue;
}
+- if (isalpha(c))
+- date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
++ if (!date) {
++ *error_ret = 1;
++ return 0;
++ }
+ }
+ pending_number(&tm, &number);
+ if (!touched)
+
+ ## t/t0006-date.sh ##
+@@ t/t0006-date.sh: check_approxidate 3.weeks.ago '2009-08-09 19:20:00'
+ check_approxidate 3.months.ago '2009-05-30 19:20:00'
+ check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00'
+
++test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' '
++ echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect &&
++ test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual &&
++ test_cmp expect actual
++'
++
++test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' '
++ git reflog expire --dry-run --all --expire="1 day 1 second ago" &&
++ test_must_fail git reflog expire --dry-run --all \
++ --expire="1 day 18446744073709551615 seconds ago" 2>err &&
++ test_grep "invalid timestamp" err
++'
++
+ check_approxidate '6am yesterday' '2009-08-29 06:00:00'
+ check_approxidate '6pm yesterday' '2009-08-29 18:00:00'
+ check_approxidate '3:00' '2009-08-30 03:00:00'Signature · 1 line
gitgitgadget
PATCH v2 1/5 archive-tar: guard get_path_prefix against zero-length input
From: Johannes Schindelin <[email protected]>
The get_path_prefix() function uses a do ... while() loop that unconditionally decrements the size_t index variable before checking the loop condition. When that variable is 0 on entry, the decrement wraps to SIZE_MAX, and path[SIZE_MAX] is an out-of-bounds read.
The current caller (write_tar_entry()) only invokes this function when pathlen > sizeof(header.name) i.e. when pathlen is at least 100. Therefore, the bug is unreachable in practice.
However, the function's interface accepts arbitrary pathlen and maxlen values, and a future caller or a maxlen of 0 could trigger the wrap, so let's add a check for that.
Pointed out by Coverity.
--- archive-tar.c | 2 ++ 1 file changed, 2 insertions(+)
archive-tar.c +2 -0
@@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen) i--;if (i > maxlen) i = maxlen; +if (!i) +return 0 ;do { i--; }while (i >0 && path[i] !='/' );
Signature · 1 line
gitgitgadget
Re: [PATCH v2 1/5] archive-tar: guard get_path_prefix against zero-length input
Quoted 10 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
The
get_path_prefix()function uses ado ... while()loop that unconditionally decrements thesize_tindex variable before checking the loop condition. When that variable is 0 on entry, the decrement wraps toSIZE_MAX, andpath[SIZE_MAX]is an out-of-bounds read.The current caller (
write_tar_entry()) only invokes this function whenpathlen > sizeof(header.name)i.e. whenpathlenis at least 100. Therefore, the bug is unreachable in practice.
There is an off-by-one here. Because header.name is 100 bytes in struct ustar_header, pathlen > sizeof(header.name) means pathlen is at least 101.
It indeed is unreachable in practice ;-)
archive-tar.c static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen) · line 217
Quoted 13 lines
archive-tar.c +2
-0@@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen) i--;if (i > maxlen) i = maxlen; +if (!i) +return 0 ;do { i--; }while (i >0 && path[i] !='/' );
Guarding against 'i == 0' after capping to 'maxlen' protects against both zero 'pathlen' and zero 'maxlen' before entering the 'do ... while' decrement, while leaving 'pathlen == 1' (e.g., "/") and all longer paths unchanged.
Looks good to me. Thanks.
PATCH v2 2/5 http: use `size_t` for byte position in fwrite_sha1_file
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
The fwrite_sha1_file() function tracks the number of bytes written via an int variable, but the total size to write is of type size_t. When the HTTP response body exceeds INT_MAX (~2GB), this causes an overflow and a heap under-read, then writes that data to the local object file.
The hash check afterward would reject the corrupt object (so no bad data enters the object store), but the under-read itself could leak adjacent heap contents to the temporary file. In practice this is unlikely because curl delivers data in small chunks (typically 16KB per callback invocation), so in practice, the total size is far below INT_MAX in a single call. However, the function interface accepts arbitrary sizes, and the accumulation across the loop means that the int variable grows across calls within a single invocation, not across callbacks.
Change the type from int to size_t to match the type of the total size. This is a hardening fix: the attack surface (a malicious HTTP server triggering a >2GB single-callback delivery) is theoretical under normal curl configurations, but the type mismatch is a genuine defect.
Pointed out by Coverity.
--- http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
http.c +1 -1
@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;
Signature · 1 line
gitgitgadget
Re: [PATCH v2 2/5] http: use `size_t` for byte position in fwrite_sha1_file
Quoted 7 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
The
fwrite_sha1_file()function tracks the number of bytes written via anintvariable, but the total size to write is of typesize_t. When the HTTP response body exceedsINT_MAX(~2GB), this causes an overflow and a heap under-read, then writes that data to the local object file.
Quoted 8 lines
The hash check afterward would reject the corrupt object (so no bad data enters the object store), but the under-read itself could leak adjacent heap contents to the temporary file. In practice this is unlikely because curl delivers data in small chunks (typically 16KB per callback invocation), so in practice, the total size is far below
INT_MAXin a single call. However, the function interface accepts arbitrary sizes, and the accumulation across the loop means that theintvariable grows across calls within a single invocation, not across callbacks.
The second paragraph also repeats "In practice ... so in practice".
I had to read the two paragraphs a few times to convince myself that they are not delivering contradictory messages. In fwrite_sha1_file(), 'posn' is a local variable reset to 0 on every invocation, so a multi-gigabyte HTTP response body delivered in normal chunks will never overflow 'posn'. Only a single invocation whose eltsize * nmemb is larger than INT_MAX would overflow it, as the second paragraph notes.
Perhaps shorten the thing (while removing the repetition) along the lines of something like...
The fwrite_sha1_file() function tracks the number of bytes written during a single invocation in an int variable ('posn'), even though the buffer length size = eltsize * nmemb has type size_t. If a caller or callback ever passed more than INT_MAX bytes in a single call, 'posn' could overflow and wrap negative, causing (char *)ptr + posn to under-read the buffer. While curl delivers data in small chunks in practice, matching the variable type to 'size' avoids the defect.
perhaps?
http.c static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, · line 2853
Quoted 12 lines
http.c +1
-1@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;
And of course, this single line change itself is good.
xwrite() clamps per-call I/O to MAX_IO_SIZE, and posn/eltsize division avoids signed-to-unsigned promotion on the value this function returns.
Looking good.
Re: [PATCH v2 2/5] http: use `size_t` for byte position in fwrite_sha1_file
Hi Junio,
Quoted 39 lines · Junio C Hamano
Quoted 7 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
The
fwrite_sha1_file()function tracks the number of bytes written via anintvariable, but the total size to write is of typesize_t. When the HTTP response body exceedsINT_MAX(~2GB), this causes an overflow and a heap under-read, then writes that data to the local object file.Quoted 8 lines
The hash check afterward would reject the corrupt object (so no bad data enters the object store), but the under-read itself could leak adjacent heap contents to the temporary file. In practice this is unlikely because curl delivers data in small chunks (typically 16KB per callback invocation), so in practice, the total size is far below
INT_MAXin a single call. However, the function interface accepts arbitrary sizes, and the accumulation across the loop means that theintvariable grows across calls within a single invocation, not across callbacks.The second paragraph also repeats "In practice ... so in practice".
I had to read the two paragraphs a few times to convince myself that they are not delivering contradictory messages. In
fwrite_sha1_file(), 'posn' is a local variable reset to 0 on every invocation, so a multi-gigabyte HTTP response body delivered in normal chunks will never overflow 'posn'. Only a single invocation whose eltsize * nmemb is larger thanINT_MAXwould overflow it, as the second paragraph notes.Perhaps shorten the thing (while removing the repetition) along the lines of something like...
The
fwrite_sha1_file()function tracks the number of bytes written during a single invocation in an int variable ('posn'), even though the buffer length size = eltsize * nmemb has typesize_t. If a caller or callback ever passed more thanINT_MAXbytes in a single call, 'posn' could overflow and wrap negative, causing (char *)ptr + posn to under-read the buffer. While curl delivers data in small chunks in practice, matching the variable type to 'size' avoids the defect.
Quoted 1 line
perhaps?
I'll use that.
Thanks!
Johannes
Quoted 22 lines
http.c static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, · line 2853
Quoted 13 lines
http.c +1
-1@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;And of course, this single line change itself is good.
xwrite()clamps per-call I/O toMAX_IO_SIZE, and posn/eltsize division avoids signed-to-unsigned promotion on the value this function returns.Looking good.
PATCH v2 3/5 wrapper: avoid byte-count overflow in write_in_full()
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Accumulating the output count in write_in_full() can overflow because it counts via a ssize_t variable which can overflow for valid size_t sizes passed as input.
Since this function either completes the requested count or fails, callers already know how many bytes were written on success. Let's just return status instead, so the total transfer size need not fit in ssize_t.
Pointed out by Coverity.
--- Makefile | 1 + imap-send.c | 2 +- notes-merge.c | 13 ++-------- t/meson.build | 1 + t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 42 +++++++++++++++++++++++++++++++++ wrapper.c | 6 ++--- wrapper.h | 7 ++++-- 8 files changed, 55 insertions(+), 19 deletions(-) create mode 100644 t/unit-tests/u-wrapper.c
Makefile +1 -0
@@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization CLAR_TEST_SUITES += u-utf8-width +CLAR_TEST_SUITES += u-wrapper CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
imap-send.c +1 -1
@@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len) n =SSL_write (sock->ssl, buf, len); else#endif - n =write_in_full (sock->fd[1 ], buf, len); + n =write_in_full (sock->fd[1 ], buf, len) <0 ?-1 : len;if (n != len) {socket_perror ("write" , sock, n);close (sock->fd[0 ]);
notes-merge.c +2 -11
@@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj, fd =xopen (path,O_WRONLY |O_EXCL |O_CREAT ,0666 ); -while (size >0 ) { -ssize_t ret =write_in_full (fd, buf, size); -if (ret <0 ) { -/* Ignore epipe */ -if (errno ==EPIPE ) -break ; -die_errno ("notes-merge" ); - } - size -= ret; - buf += ret; - } +if (write_in_full (fd, buf, size) <0 && errno !=EPIPE ) +die_errno ("notes-merge" );close (fd);free (path);
t/meson.build +1 -0
@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-wrapper.c', ] clar_sources = [
t/unit-tests/u-reftable-stack.c +1 -1
@@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)cl_assert (fd >0 ); n =write_in_full (fd, out,strlen (out)); -cl_assert_equal_i (n,strlen (out)); +cl_assert_equal_i (n,0 ); err =close (fd);cl_assert (err >=0 );
t/unit-tests/u-wrapper.c new file +42 -0
42 lines not on this page · raw message
wrapper.c +2 -4
@@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)return total; } -ssize_t write_in_full (int fd,const void *buf,size_t count) +int write_in_full (int fd,const void *buf,size_t count) {const char *p = buf; -ssize_t total =0 ;while (count >0 ) {ssize_t written =xwrite (fd, p, count);
@@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t count) } count -= written; p += written; - total += written; } -return total; +return 0 ; }ssize_t xwritev (int fd,struct iovec *iov,int iovcnt)
wrapper.h +5 -2
@@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int mode);int git_mkstemp_mode (char *pattern,int mode);ssize_t read_in_full (int fd,void *buf,size_t count); -ssize_t write_in_full (int fd,const void *buf,size_t count); + +/* Return 0 on a complete write, or -1 with errno set on failure. */ +int write_in_full (int fd,const void *buf,size_t count); +ssize_t pread_in_full (int fd,void *buf,size_t count,off_t offset);/*
@@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);*/ ssize_t writev_in_full (int fd,struct iovec *iov,int iovcnt); -static inline ssize_t write_str_in_full (int fd,const char *str) +static inline int write_str_in_full (int fd,const char *str) {return write_in_full (fd, str,strlen (str)); }
Signature · 1 line
gitgitgadget
Re: [PATCH v2 3/5] wrapper: avoid byte-count overflow in write_in_full()
Hi Johannes
Quoted 10 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Accumulating the output count in
write_in_full()can overflow because it counts via assize_tvariable which can overflow for validsize_tsizes passed as input.Since this function either completes the requested count or fails, callers already know how many bytes were written on success. Let's just return status instead, so the total transfer size need not fit in
ssize_t.
This makes perfect sense and the changes in this patch all look good. Looking at how the callers of write_in_full() use the return value, there are a few we might want to tweak.
In config.c write_section() and write_pair() both return the result of write_in_full(). All of the callers of those functions are only interested in whether the return value was negative, so there is no problem with the change in behavior, but we might want to change the return value to an int to match the new prototype of write_in_full().
In entry.c:write_entry() and parallel-checkout.c:write_pc_item_to_fd() we're still using a ssize_t to store the return value even though it is now an int.
In odb/streaming.c:odb_stream_blob_to_fd() we're also storing the return value in a ssize_t. Unlike the cases above we can simply avoid storing the value at all.
One final note - in refs.c:transaction_hook_feed_stdin(), sequencer.c:pipe_from_strbuf() and transport.c:pre_push_hook_feed_stdin() we're storing the result in an int and then checking if it is negative, so this patch actually fixes potential bugs in those callers.
Thanks
Phillip
Quoted 192 lines
Pointed out by Coverity.
Helped-by Phillip Wood <[email protected]>Assisted-by GPT-6.1Signed-off-by Johannes Schindelin <[email protected]>--- Makefile | 1 + imap-send.c | 2 +- notes-merge.c | 13 ++-------- t/meson.build | 1 + t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 42 +++++++++++++++++++++++++++++++++ wrapper.c | 6 ++--- wrapper.h | 7 ++++-- 8 files changed, 55 insertions(+), 19 deletions(-)create mode 100644
t/unit-tests/u-wrapper.cMakefile +1
-0@@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization CLAR_TEST_SUITES += u-utf8-width +CLAR_TEST_SUITES += u-wrapper CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.oimap-send.c +1
-1@@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len) n =SSL_write (sock->ssl, buf, len); else#endif - n =write_in_full (sock->fd[1 ], buf, len); + n =write_in_full (sock->fd[1 ], buf, len) <0 ?-1 : len;if (n != len) {socket_perror ("write" , sock, n);close (sock->fd[0 ]);notes-merge.c +2
-11@@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj, fd =xopen (path,O_WRONLY |O_EXCL |O_CREAT ,0666 ); -while (size >0 ) { -ssize_t ret =write_in_full (fd, buf, size); -if (ret <0 ) { -/* Ignore epipe */ -if (errno ==EPIPE ) -break ; -die_errno ("notes-merge" ); - } - size -= ret; - buf += ret; - } +if (write_in_full (fd, buf, size) <0 && errno !=EPIPE ) +die_errno ("notes-merge" );close (fd);free (path);t/meson.build +1
-0@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-wrapper.c', ] clar_sources = [t/unit-tests/u-reftable-stack.c +1
-1@@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)cl_assert (fd >0 ); n =write_in_full (fd, out,strlen (out)); -cl_assert_equal_i (n,strlen (out)); +cl_assert_equal_i (n,0 ); err =close (fd);cl_assert (err >=0 );t/unit-tests/u-wrapper.c new file +42
-0@@ -0,0 +1,42 @@ +#include "unit-test.h" +#include "tempfile.h" + +static struct tempfile *file; +static char data[128 *1024 ], actual[sizeof (data)]; + +void test_wrapper__initialize (void ) +{ + file =mks_tempfile ("wrapper-test-XXXXXX" ); +cl_assert (file !=NULL ); +for (size_t i =0 ; i <sizeof (data); i++) + data[i] = i %127 ; +memset (actual,0 ,sizeof (actual)); +} + +void test_wrapper__cleanup (void ) +{ +delete_tempfile (&file); +} + +void test_wrapper__write_in_full (void ) +{ +int fd =get_tempfile_fd (file); + +cl_assert_equal_i (write_in_full (fd, data,sizeof (data)),0 ); +cl_assert (lseek (fd,0 ,SEEK_SET ) ==0 ); +cl_assert (read_in_full (fd, actual,sizeof (actual)) == + (ssize_t )sizeof (actual)); +cl_assert (!memcmp (data, actual,sizeof (data))); +} + +void test_wrapper__write_in_full_empty (void ) +{ +cl_assert_equal_i (write_in_full (-1 ,NULL ,0 ),0 ); +} + +void test_wrapper__write_in_full_error (void ) +{ + errno =0 ; +cl_assert_equal_i (write_in_full (-1 , data,1 ),-1 ); +cl_assert_equal_i (errno,EBADF ); +}wrapper.c +2
-4@@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)return total; } -ssize_t write_in_full (int fd,const void *buf,size_t count) +int write_in_full (int fd,const void *buf,size_t count) {const char *p = buf; -ssize_t total =0 ;while (count >0 ) {ssize_t written =xwrite (fd, p, count);@@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t count) } count -= written; p += written; - total += written; } -return total; +return 0 ; }ssize_t xwritev (int fd,struct iovec *iov,int iovcnt)wrapper.h +5
-2@@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int mode);int git_mkstemp_mode (char *pattern,int mode);ssize_t read_in_full (int fd,void *buf,size_t count); -ssize_t write_in_full (int fd,const void *buf,size_t count); + +/* Return 0 on a complete write, or -1 with errno set on failure. */ +int write_in_full (int fd,const void *buf,size_t count); +ssize_t pread_in_full (int fd,void *buf,size_t count,off_t offset);/* @@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);*/ ssize_t writev_in_full (int fd,struct iovec *iov,int iovcnt); -static inline ssize_t write_str_in_full (int fd,const char *str) +static inline int write_str_in_full (int fd,const char *str) {return write_in_full (fd, str,strlen (str)); }
Re: [PATCH v2 3/5] wrapper: avoid byte-count overflow in write_in_full()
Hi Phillip,
Quoted 25 lines · Phillip Wood
Quoted 10 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Accumulating the output count in
write_in_full()can overflow because it counts via assize_tvariable which can overflow for validsize_tsizes passed as input.Since this function either completes the requested count or fails, callers already know how many bytes were written on success. Let's just return status instead, so the total transfer size need not fit in
ssize_t.This makes perfect sense and the changes in this patch all look good. Looking at how the callers of
write_in_full()use the return value, there are a few we might want to tweak.In
config.cwrite_section()andwrite_pair()both return the result ofwrite_in_full(). All of the callers of those functions are only interested in whether the return value was negative, so there is no problem with the change in behavior, but we might want to change the return value to an int to match the new prototype ofwrite_in_full().In entry.c:write_entry() and parallel-checkout.c:write_pc_item_to_fd() we're still using a
ssize_tto store the return value even though it is now an int.
Quoted 8 lines
In odb/streaming.c:odb_stream_blob_to_fd() we're also storing the return value in a
ssize_t. Unlike the cases above we can simply avoid storing the value at all.One final note - in refs.c:transaction_hook_feed_stdin(), sequencer.c:pipe_from_strbuf() and transport.c:pre_push_hook_feed_stdin() we're storing the result in an int and then checking if it is negative, so this patch actually fixes potential bugs in those callers.
Great call-out! I adjusted the callers accordingly.
Thank you,
Johannes
Quoted 203 lines
Thanks
Phillip
Quoted 195 lines
Pointed out by Coverity.
Helped-by Phillip Wood <[email protected]>Assisted-by GPT-6.1Signed-off-by Johannes Schindelin <[email protected]>--- Makefile | 1 + imap-send.c | 2 +- notes-merge.c | 13 ++-------- t/meson.build | 1 + t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 42 +++++++++++++++++++++++++++++++++ wrapper.c | 6 ++--- wrapper.h | 7 ++++-- 8 files changed, 55 insertions(+), 19 deletions(-)create mode 100644
t/unit-tests/u-wrapper.cMakefile +1
-0@@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization CLAR_TEST_SUITES += u-utf8-width +CLAR_TEST_SUITES += u-wrapper CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.oimap-send.c +1
-1@@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len) n =SSL_write (sock->ssl, buf, len); else#endif - n =write_in_full (sock->fd[1 ], buf, len); + n =write_in_full (sock->fd[1 ], buf, len) <0 ?-1 : len;if (n != len) {socket_perror ("write" , sock, n);close(sock->fd[0]);notes-merge.c +2
-10@@ -319,17 +319,8 @@ static void write_buf_to_worktree(const structobject_id *obj, fd =xopen (path,O_WRONLY |O_EXCL |O_CREAT ,0666 ); - while (size > 0) { -ssize_t ret =write_in_full (fd, buf, size); -if (ret <0 ) { -/* Ignore epipe */ -if (errno ==EPIPE ) -break ; -die_errno ("notes-merge" ); - } - size -= ret; - buf += ret; - } +if (write_in_full (fd, buf, size) <0 && errno !=EPIPE ) +die_errno ("notes-merge" );close (fd);free (path);t/meson.build +1
-0@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-wrapper.c',]
clar_sources= [t/unit-tests/u-reftable-stack.c +1
-1@@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)cl_assert (fd >0 ); n =write_in_full (fd, out,strlen (out)); -cl_assert_equal_i (n,strlen (out)); +cl_assert_equal_i (n,0 ); err =close (fd);cl_assert (err >=0 ); diff --git a/t/unit-tests/u-wrapper.c b/t/unit-tests/u-wrapper.cnew file mode 100644
index 0000000000..713ac0df92t/unit-tests/u-wrapper.c new file +42
-0@@ -0,0 +1,42 @@ +#include "unit-test.h" +#include "tempfile.h" + +static struct tempfile *file; +static char data[128 *1024 ], actual[sizeof (data)]; + +void test_wrapper__initialize (void ) +{ + file =mks_tempfile ("wrapper-test-XXXXXX" ); +cl_assert (file !=NULL ); +for (size_t i =0 ; i <sizeof (data); i++) + data[i] = i %127 ; +memset (actual,0 ,sizeof (actual)); +} + +void test_wrapper__cleanup (void ) +{ +delete_tempfile (&file); +} + +void test_wrapper__write_in_full (void ) +{ +int fd =get_tempfile_fd (file); + +cl_assert_equal_i (write_in_full (fd, data,sizeof (data)),0 ); +cl_assert (lseek (fd,0 ,SEEK_SET ) ==0 ); +cl_assert (read_in_full (fd, actual,sizeof (actual)) == + (ssize_t )sizeof (actual)); +cl_assert (!memcmp (data, actual,sizeof (data))); +} + +void test_wrapper__write_in_full_empty (void ) +{ +cl_assert_equal_i (write_in_full (-1 ,NULL ,0 ),0 ); +} + +void test_wrapper__write_in_full_error (void ) +{ + errno =0 ; +cl_assert_equal_i (write_in_full (-1 , data,1 ),-1 ); +cl_assert_equal_i (errno,EBADF ); +}wrapper.c +2
-3@@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)return total; } -ssize_t write_in_full (int fd,const void *buf,size_t count) +int write_in_full (int fd,const void *buf,size_t count) {const char *p = buf; -ssize_t total =0 ;while (count >0 ) {ssize_t written =xwrite (fd, p, count);@@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t count) } count -= written; p += written; - total += written; } - return total; +return 0 ; }ssize_t xwritev (int fd,struct iovec *iov,int iovcnt)wrapper.h +4
-1@@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int mode);int git_mkstemp_mode (char *pattern,int mode);ssize_t read_in_full (int fd,void *buf,size_t count); -ssize_t write_in_full (int fd,const void *buf,size_t count); + +/* Return 0 on a complete write, or -1 with errno set on failure. */ +int write_in_full (int fd,const void *buf,size_t count); +ssize_t pread_in_full (int fd,void *buf,size_t count,off_t offset);/*
wrapper.h +1
-1@@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count,off_t offset); */ ssize_t writev_in_full (int fd,struct iovec *iov,int iovcnt); -static inline ssize_t write_str_in_full (int fd,const char *str) +static inline int write_str_in_full (int fd,const char *str) {return write_in_full (fd, str,strlen (str));}
PATCH v2 4/5 wrapper: add read_in_full_or_error()
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Callers of the read_in_full() function want to read all requested bytes, or get an error. However, limiting the return value type to ssize_t is insufficient, as file sizes can easily exceed that type's range.
For those callers that do not require the return value to report the number of read bytes, add a new function, read_in_full_or_error(), that returns a Boolean to indicate success or faiure.
Callers that do need to know that byte count can still call read_in_full(), but will now error out early if the requested byte count exceeds what ssize_t can represent.
Pointed out by Coverity.
--- builtin/blame.c | 2 +- combine-diff.c | 6 +---- dir.c | 2 +- grep.c | 2 +- refs/packed-backend.c | 4 +-- strbuf.c | 10 ++++--- t/unit-tests/u-wrapper.c | 57 ++++++++++++++++++++++++++++++++++++++++ wrapper.c | 50 ++++++++++++++++++++++++++++------- wrapper.h | 7 +++++ 9 files changed, 116 insertions(+), 24 deletions(-)
builtin/blame.c +1 -1
@@ -1006,7 +1006,7 @@ static void parse_default_ignore_revs_file(struct blame_scoreboard *sb, } size =xsize_t (st.st_size); buf =xmalloc (size); -if (read_in_full (fd, buf, size) == (ssize_t )size) +if (!read_in_full_or_error (fd, buf, size))oidset_parse_buffer_carefully (&sb->ignore_list, buf, size, sb->repo->hash_algo, peel_to_commit_oid, sb);
combine-diff.c +1 -5
@@ -1073,7 +1073,6 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,free_filespec (df); }else if (0 <= (fd =open (elem->path,O_RDONLY ))) {size_t len =xsize_t (st.st_size); -ssize_t done;int is_file, i; elem->mode =canon_mode (st.st_mode);
@@ -1089,11 +1088,8 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent, result_size = len; result =xmallocz (len); - done =read_in_full (fd, result, len); -if (done <0 ) +if (read_in_full_or_error (fd, result, len) <0 )die_errno ("read error '%s'" , elem->path); -else if (done < len) -die ("early EOF '%s'" , elem->path);/* If not a fake symlink, apply filters, e.g. autocrlf */ if (is_file) {
dir.c +1 -1
@@ -1190,7 +1190,7 @@ static int add_patterns(const char *fname, const char *base, int baselen,return 0 ; } buf =xmallocz (size); -if (read_in_full (fd, buf, size) != size) { +if (read_in_full_or_error (fd, buf, size) <0 ) {free (buf);close (fd);return -1 ;
grep.c +1 -1
@@ -1964,7 +1964,7 @@ static int grep_source_load_file(struct grep_source *gs)if (i <0 ) goto err_ret; data =xmallocz (size); -if (st.st_size !=read_in_full (i, data, size)) { +if (read_in_full_or_error (i, data, size) <0 ) {error_errno (_ ("'%s': short read" ), filename);close (i);free (data);
refs/packed-backend.c +1 -3
@@ -543,7 +543,6 @@ static int refname_contains_nul(struct strbuf *refname)static int allocate_snapshot_buffer (struct snapshot *snapshot,int fd,struct stat *st) { -ssize_t bytes_read;size_t size; size =xsize_t (st->st_size);
@@ -552,8 +551,7 @@ static int allocate_snapshot_buffer(struct snapshot *snapshot, int fd, struct stif (mmap_strategy ==MMAP_NONE || size <=SMALL_FILE_SIZE ) { snapshot->buf =xmalloc (size); - bytes_read =read_in_full (fd, snapshot->buf, size); -if (bytes_read <0 || bytes_read != size) +if (read_in_full_or_error (fd, snapshot->buf, size) <0 )die_errno ("couldn't read %s" , snapshot->refs->path); snapshot->mmapped =0 ; }else {
strbuf.c +7 -3
@@ -537,8 +537,12 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)strbuf_grow (sb, hint ? hint :8192 );for (;;) { -ssize_t want = sb->alloc - sb->len -1 ; -ssize_t got =read_in_full (fd, sb->buf + sb->len, want); +size_t want = sb->alloc - sb->len -1 ; +ssize_t got; + +if ((uintmax_t )want >maximum_signed_value_of_type (ssize_t)) + want =maximum_signed_value_of_type (ssize_t); + got =read_in_full (fd, sb->buf + sb->len, want);if (got <0 ) {if (oldalloc ==0 )
@@ -548,7 +552,7 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)return -1 ; } sb->len += got; -if (got < want) +if ((size_t )got < want)break ;strbuf_grow (sb,8192 ); }
t/unit-tests/u-wrapper.c +57 -0
60 lines not on this page · raw message
wrapper.c +40 -10
63 lines not on this page · raw message
wrapper.h +7 -0
@@ -44,8 +44,15 @@ char *git_mkdtemp(char *pattern);int git_mkstemps_mode (char *pattern,int suffix_len,int mode);int git_mkstemp_mode (char *pattern,int mode); +/* +* Return the number of bytes read, possibly short at EOF, or -1 on error. +* The requested count must be representable in ssize_t. +*/ ssize_t read_in_full (int fd,void *buf,size_t count); +/* Return 0 on a complete read, or -1 with errno set (EIO on premature EOF). */ +int read_in_full_or_error (int fd,void *buf,size_t count); +/* Return 0 on a complete write, or -1 with errno set on failure. */ int write_in_full (int fd,const void *buf,size_t count);
Signature · 1 line
gitgitgadget
Re: [PATCH v2 4/5] wrapper: add read_in_full_or_error()
Quoted 1 line · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Thanks. In this step, I only saw a few minor nits.
Quoted 8 lines
Callers of the
read_in_full()function want to read all requested bytes, or get an error. However, limiting the return value type tossize_tis insufficient, as file sizes can easily exceed that type's range.For those callers that do not require the return value to report the number of read bytes, add a new function,
read_in_full_or_error(), that returns a Boolean to indicate success or faiure.
It returns an int to indicate success or failure. It is moral parallel to returning a Boolean, but the polarity is reversed (0 is success, a negative is failure, following our usual convention).
Quoted 3 lines
Callers that do need to know that byte count can still call
read_in_full(), but will now error out early if the requested byte count exceeds whatssize_tcan represent.
"error out early" -> "abort to signal a programming error".
read_in_full() aborts with BUG() when the requested byte count exceeds ssize_t max, instead of erroring out. We declare that our API contract is that count passed to read_in_full() must fit in ssize_t, so that any positive return value from the function reliably means a successful read, and in such a world, passing overly large count is a programming error (i.e., the caller must be written to check) and aborting with BUG() is perfetly fine. Let's document that design decision here in the log message.
Looking at the whole working tree after applying this series, all remaining callers of read_in_full() are small or explicitly bounded (setup.c, object-file.c, http-backend.c, pkt-line.c, odb/streaming.c).
Except that worktree.c:should_prune_worktree() passes size_t len that is computed as xsize_t(st.st_size) for a .git gitdir file. While gitdir files are tiny in practice, converting it to read_in_full_or_error() would be consistent with the other st.st_size conversions.
Quoted 20 lines
wrapper.c +9
-7+/* +* Read until count bytes have been read or EOF. On success, store the number +* read in out if non-NULL. Return false on an I/O error, with errno set. +*/ +static bool read_in_full_1 (int fd,void *buf,size_t count,size_t *out) {char *p = buf; -ssize_t total =0 ; +size_t remaining = count; -while (count >0 ) { -ssize_t loaded =xread (fd, p, count); +while (remaining) { +ssize_t loaded =xread (fd, p, remaining);if (loaded <0 ) -return -1 ; -if (loaded ==0 ) -return total; - count -= loaded; +return false;
wrapper.c ssize_t xpread(int fd, void *buf, size_t len, off_t offset) · line 306
Quoted 10 lines
wrapper.c +5
-2+if (!loaded) +break ; + remaining -= loaded; p += loaded; - total += loaded; } -return total; +if (out) + *out = count - remaining;
All two callers of this file-scope static helper passes &total, so this reporting of the total count can and should be done unconditionally.
Quoted 2 lines
(quoted diff) +2
-0+ return true; +}
PATCH v2 5/5 date: avoid overflow in approxidate relative-time multiplication
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Parsing relative dates can overflow int when multiplying a value by a unit length, before converting the result to time_t. Signed overflow is undefined behavior, therefore checking the converted value is too late.
Reject quantities above INT_MAX before narrowing to int on all platforms. The inputs are non-negative, meaning that checking unsigned arithmetic is sufficient. The product must also fit the native time_t range. Report arithmetic or conversion failures as parse errors rather than saturating the offset.
Pointed out by Coverity.
--- date.c | 26 ++++++++++++++++++++------ t/t0006-date.sh | 13 +++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-)
date.c +20 -6
@@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +uintmax_t length = tl->length, num_t = *num, seconds; + +if (unsigned_mult_overflows (length, num_t)) +return NULL ; + seconds = length * num_t; +if (date_overflows (seconds)) +return NULL ; +update_tm (tm, now, (time_t )seconds); *num =0 ; *touched =1 ;return end;
@@ -1377,8 +1384,11 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +if (number >INT_MAX ) +return NULL ; *num = number; + }return end; }
@@ -1404,14 +1414,18 @@ static timestamp_t approxidate_str(const char *date,if (!c)break ; date++; -if (isdigit (c)) { +if (isalpha (c)) + date =approxidate_alpha (date-1 , &tm, &now, + &number, &touched); +else if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); touched =1 ; -continue ; } -if (isalpha (c)) - date =approxidate_alpha (date-1 , &tm, &now, &number, &touched); +if (!date) { + *error_ret =1 ; +return 0 ; + } }pending_number (&tm, &number);if (!touched)
t/t0006-date.sh +13 -0
@@ -211,6 +211,19 @@ check_approxidate 3.weeks.ago '2009-08-09 19:20:00' check_approxidate 3.months.ago '2009-05-30 19:20:00' check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00' +test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' ' + echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect && + test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual && + test_cmp expect actual +' + +test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' ' + git reflog expire --dry-run --all --expire="1 day 1 second ago" && + test_must_fail git reflog expire --dry-run --all \ + --expire="1 day 18446744073709551615 seconds ago" 2>err && + test_grep "invalid timestamp" err +' + check_approxidate '6am yesterday' '2009-08-29 06:00:00' check_approxidate '6pm yesterday' '2009-08-29 18:00:00' check_approxidate '3:00' '2009-08-30 03:00:00'
Signature · 1 line
gitgitgadget
Re: [PATCH v2 5/5] date: avoid overflow in approxidate relative-time multiplication
Hi Johannes
Quoted 7 lines · Johannes Schindelin via GitGitGadget
From: Johannes Schindelin <[email protected]>
Parsing relative dates can overflow
intwhen multiplying a value by a unit length, before converting the result totime_t. Signed overflow is undefined behavior, therefore checking the converted value is too late.
Quoted 5 lines
Reject quantities above
INT_MAXbefore narrowing tointon all platforms. The inputs are non-negative, meaning that checking unsigned arithmetic is sufficient. The product must also fit the nativetime_trange. Report arithmetic or conversion failures as parse errors rather than saturating the offset.
This looks good and is much simpler than the previous version.
Thanks
Phillip
Quoted 90 lines
Pointed out by Coverity.
Helped-by Phillip Wood <[email protected]>Assisted-by Claude Opus 4.6 and GPT-6.1Signed-off-by Johannes Schindelin <[email protected]>--- date.c | 26 ++++++++++++++++++++------ t/t0006-date.sh | 13 +++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-)date.c +20
-6@@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +uintmax_t length = tl->length, num_t = *num, seconds; + +if (unsigned_mult_overflows (length, num_t)) +return NULL ; + seconds = length * num_t; +if (date_overflows (seconds)) +return NULL ; +update_tm (tm, now, (time_t )seconds); *num =0 ; *touched =1 ;return end;@@ -1377,8 +1384,11 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +if (number >INT_MAX ) +return NULL ; *num = number; + }return end; }@@ -1404,14 +1414,18 @@ static timestamp_t approxidate_str(const char *date,if (!c)break ; date++; -if (isdigit (c)) { +if (isalpha (c)) + date =approxidate_alpha (date-1 , &tm, &now, + &number, &touched); +else if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); touched =1 ; -continue ; } -if (isalpha (c)) - date =approxidate_alpha (date-1 , &tm, &now, &number, &touched); +if (!date) { + *error_ret =1 ; +return 0 ; + } }pending_number (&tm, &number);if (!touched)t/t0006-date.sh +13
-0@@ -211,6 +211,19 @@ check_approxidate 3.weeks.ago '2009-08-09 19:20:00' check_approxidate 3.months.ago '2009-05-30 19:20:00' check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00' +test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' ' + echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect && + test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual && + test_cmp expect actual +' + +test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' ' + git reflog expire --dry-run --all --expire="1 day 1 second ago" && + test_must_fail git reflog expire --dry-run --all \ + --expire="1 day 18446744073709551615 seconds ago" 2>err && + test_grep "invalid timestamp" err +' + check_approxidate '6am yesterday' '2009-08-29 06:00:00' check_approxidate '6pm yesterday' '2009-08-29 18:00:00' check_approxidate '3:00' '2009-08-30 03:00:00'
Quoted 9 lines · Johannes Schindelin via GitGitGadget
Changes since v1:
* Most callers of
read_in_full()and all callers ofwrite_in_full()are now no longer restricted by the range ofssize_t.
* Thesigned_mult_overflows()andmult_overflows()macros have been dropped.
* Since theapproxidate()function only deals with non-negative values, the complicated overflow check could been simplified.
* Rebased to master, to avoid merge conflicts.
The overall direction in v2 is a clear improvement over v1. Dropping the ad-hoc overflow macros and separating read_in_full_or_error() from read_in_full() keeps the APIs much cleaner and easier to verify.
Small nit on the wording above: "Most callers of read_in_full()" overstates the conversions slightly (five callers were switched to read_in_full_or_error() and strbuf_read() now clamps 'want', while the remaining callers already operate on small fixed sizes, apart from worktree.c:should_prune_worktree() which could also be converted).
Also "could been simplified" is missing "have".
But the cover letter will not be part of permanent record, so who cares ;-) As long as patches are good, we are all happy.
Thanks for working on this.
v3 cover Address overflows pointed out by Coverity
In reply to Johannes Schindelin via GitGitGadgetThis patch series is part of my effort to bring Git for Windows' Coverity reports down to zero; Previous patch series have been merged in 347fe8a91b5 (Merge branch 'js/coverity-fixes', 2026-07-16), 0b75ef5168c (Merge branch 'js/coverity-fixes-null-safety', 2026-07-19), fcc8c931b53 (Merge branch 'js/coverity-unchecked-returns-fix', 2026-08-24) and 8bc9c7fcfd8 (Merge branch 'js/coverity-fixes', 2026-10-03).
Changes since v2:
* Fixed a grammar error and an overstatement in the "Changes since v1" section :-)
* Accepted Junio's rewritten explanation in 2/5's commit message.
* Clarified the design decision to abort on programing errors in 4/5's commit message.
* Adjusted a few straggler ssize_t variables that can now safely be int or even be dropped.
Changes since v1:
* Five callers of read_in_full() and all callers of write_in_full() are now no longer restricted by the range of ssize_t.
* The signed_mult_overflows() and mult_overflows() macros have been dropped.
* Since the approxidate() function only deals with non-negative values, the complicated overflow check could have been simplified.
* Rebased to master, to avoid merge conflicts.
Johannes Schindelin (5):
archive-tar: guard get_path_prefix against zero-length input
http: use size_t for byte position in fwrite_sha1_file
wrapper: avoid byte-count overflow in write_in_full()
wrapper: add read_in_full_or_error()
date: avoid overflow in approxidate relative-time multiplication
Makefile | 1 + archive-tar.c | 2 + builtin/blame.c | 2 +- combine-diff.c | 6 +- config.c | 14 ++--- date.c | 26 +++++++-- dir.c | 2 +- entry.c | 2 +- grep.c | 2 +- http.c | 2 +- imap-send.c | 2 +- notes-merge.c | 13 +---- odb/streaming.c | 6 +- parallel-checkout.c | 2 +- refs/packed-backend.c | 4 +- strbuf.c | 10 +++- t/meson.build | 1 + t/t0006-date.sh | 13 +++++ t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 99 +++++++++++++++++++++++++++++++++ wrapper.c | 56 ++++++++++++++----- wrapper.h | 14 ++++- 22 files changed, 218 insertions(+), 63 deletions(-) create mode 100644 t/unit-tests/u-wrapper.c
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2253%2Fdscho%2Fcoverity-fixes-overflow-v3
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2253/dscho/coverity-fixes-overflow-v3
Pull-Request: https://github.com/gitgitgadget/git/pull/2253
Range-diff vs v2:
1: bb8225547f = 1: bb8225547f archive-tar: guard get_path_prefix against zero-length input 2: 38cc1dec53 ! 2: aa2d3961b2 http: use `size_t` for byte position in fwrite_sha1_file
@@ Metadata
## Commit message ##
http: use size_t for byte position in fwrite_sha1_file
- The fwrite_sha1_file() function tracks the number of bytes written via
- an int variable, but the total size to write is of type size_t. When
- the HTTP response body exceeds INT_MAX (~2GB), this causes an overflow
- and a heap under-read, then writes that data to the local object file.
-
- The hash check afterward would reject the corrupt object (so no bad data
- enters the object store), but the under-read itself could leak adjacent
- heap contents to the temporary file. In practice this is unlikely
- because curl delivers data in small chunks (typically 16KB per callback
- invocation), so in practice, the total size is far below INT_MAX in a
- single call. However, the function interface accepts arbitrary sizes,
- and the accumulation across the loop means that the int variable grows
- across calls within a single invocation, not across callbacks.
-
- Change the type from int to size_t to match the type of the total
- size. This is a hardening fix: the attack surface (a malicious HTTP
- server triggering a >2GB single-callback delivery) is theoretical under
- normal curl configurations, but the type mismatch is a genuine defect.
+ The fwrite_sha1_file() function tracks the number of bytes written
+ during a single invocation in an int variable (posn), even though
+ the buffer length size = eltsize * nmemb has type size_t. If a
+ caller or callback ever passed more than INT_MAX bytes in a single
+ call, posn could overflow and wrap negative, causing `(char *)ptr +
+ posn` to under-read the buffer. While curl delivers data in small
+ chunks in practice, matching the variable type to size avoids the
+ defect.
Pointed out by Coverity.
+ Assisted-by: GPT-6 Luna
3: b24520c50d ! 3: f38c7e7133 wrapper: avoid byte-count overflow in write_in_full()
@@ Makefile: CLAR_TEST_SUITES += u-strvec
CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
+ ## config.c ##
+@@ config.c: static struct strbuf store_create_section(const char *key,
+ return sb;
+ }
+
+-static ssize_t write_section(int fd, const char *key,
+- const struct config_store_data *store)
++static int write_section(int fd, const char *key,
++ const struct config_store_data *store)
+ {
+ struct strbuf sb = store_create_section(key, store);
+- ssize_t ret;
++ int ret;
+
+ ret = write_in_full(fd, sb.buf, sb.len);
+ strbuf_release(&sb);
+@@ config.c: static ssize_t write_section(int fd, const char *key,
+ return ret;
+ }
+
+-static ssize_t write_pair(int fd, const char *key, const char *value,
+- const char *comment,
+- const struct config_store_data *store)
++static int write_pair(int fd, const char *key, const char *value,
++ const char *comment,
++ const struct config_store_data *store)
+ {
+ int i;
+- ssize_t ret;
++ int ret;
+ const char *quote = "";
+ struct strbuf sb = STRBUF_INIT;
+
+
+ ## entry.c ##
+@@ entry.c: static int write_entry(struct cache_entry *ce, char *path, struct conv_attrs *ca
+ char *new_blob;
+ struct strbuf buf = STRBUF_INIT;
+ size_t size;
+- ssize_t wrote;
++ int wrote;
+ size_t newsize = 0;
+ struct stat st;
+ const struct submodule *sub;
+
## imap-send.c ##
@@ imap-send.c: static int socket_write(struct imap_socket *sock, const char *buf, int len)
n = SSL_write(sock->ssl, buf, len);
@@ notes-merge.c: static void write_buf_to_worktree(const struct object_id *obj,
close(fd);
free(path);
+ ## odb/streaming.c ##
+@@ odb/streaming.c: int odb_stream_blob_to_fd(struct object_database *odb,
+ goto close_and_exit;
+ for (;;) {
+ char buf[1024 * 16];
+- ssize_t wrote, holeto;
++ ssize_t holeto;
+ ssize_t readlen = odb_stream_read(st, buf, sizeof(buf));
+
+ if (readlen < 0)
+@@ odb/streaming.c: int odb_stream_blob_to_fd(struct object_database *odb,
+ goto close_and_exit;
+ else
+ kept = 0;
+- wrote = write_in_full(fd, buf, readlen);
+-
+- if (wrote < 0)
++ if (write_in_full(fd, buf, readlen) < 0)
+ goto close_and_exit;
+ }
+ if (kept && (lseek(fd, kept - 1, SEEK_CUR) == (off_t) -1 ||
+
+ ## parallel-checkout.c ##
+@@ parallel-checkout.c: static int write_pc_item_to_fd(struct parallel_checkout_item *pc_item, int fd,
+ struct strbuf buf = STRBUF_INIT;
+ char *blob;
+ size_t size;
+- ssize_t wrote;
++ int wrote;
+
+ /* Sanity check */
+ ASSERT(is_eligible_for_parallel_checkout(pc_item->ce, &pc_item->ca));
+
## t/meson.build ##
@@ t/meson.build: clar_test_suites = [
'unit-tests/u-trailer.c',
4: ca30ed613d ! 4: d45982f1cc wrapper: add read_in_full_or_error()
@@ Commit message
that returns a Boolean to indicate success or faiure.
Callers that do need to know that byte count can still call
- read_in_full(), but will now error out early if the requested byte
- count exceeds what ssize_t can represent.
+ read_in_full(), but will now abort to signal a programming error when
+ the requested byte count exceeds what ssize_t can represent.
Pointed out by Coverity.
- Assisted-by: GPT-6.1
+ Assisted-by: GPT-6.1 and GPT-6 Luna
## builtin/blame.c ##
5: 6057734709 = 5: 23ec6cf8f0 date: avoid overflow in approxidate relative-time multiplication
Signature · 1 line
gitgitgadget
PATCH v3 1/5 archive-tar: guard get_path_prefix against zero-length input
From: Johannes Schindelin <[email protected]>
The get_path_prefix() function uses a do ... while() loop that unconditionally decrements the size_t index variable before checking the loop condition. When that variable is 0 on entry, the decrement wraps to SIZE_MAX, and path[SIZE_MAX] is an out-of-bounds read.
The current caller (write_tar_entry()) only invokes this function when pathlen > sizeof(header.name) i.e. when pathlen is at least 100. Therefore, the bug is unreachable in practice.
However, the function's interface accepts arbitrary pathlen and maxlen values, and a future caller or a maxlen of 0 could trigger the wrap, so let's add a check for that.
Pointed out by Coverity.
--- archive-tar.c | 2 ++ 1 file changed, 2 insertions(+)
archive-tar.c +2 -0
@@ -210,6 +210,8 @@ static size_t get_path_prefix(const char *path, size_t pathlen, size_t maxlen) i--;if (i > maxlen) i = maxlen; +if (!i) +return 0 ;do { i--; }while (i >0 && path[i] !='/' );
Signature · 1 line
gitgitgadget
PATCH v3 2/5 http: use `size_t` for byte position in fwrite_sha1_file
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
The fwrite_sha1_file() function tracks the number of bytes written during a single invocation in an int variable (posn), even though the buffer length size = eltsize * nmemb has type size_t. If a caller or callback ever passed more than INT_MAX bytes in a single call, posn could overflow and wrap negative, causing (char *)ptr + posn to under-read the buffer. While curl delivers data in small chunks in practice, matching the variable type to size avoids the defect.
Pointed out by Coverity.
--- http.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
http.c +1 -1
@@ -2848,7 +2848,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb, {unsigned char expn[4096 ];size_t size = eltsize * nmemb; -int posn =0 ; +size_t posn =0 ;struct http_object_request *freq = data;struct active_request_slot *slot = freq->slot;
Signature · 1 line
gitgitgadget
PATCH v3 3/5 wrapper: avoid byte-count overflow in write_in_full()
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Accumulating the output count in write_in_full() can overflow because it counts via a ssize_t variable which can overflow for valid size_t sizes passed as input.
Since this function either completes the requested count or fails, callers already know how many bytes were written on success. Let's just return status instead, so the total transfer size need not fit in ssize_t.
Pointed out by Coverity.
--- Makefile | 1 + config.c | 14 +++++------ entry.c | 2 +- imap-send.c | 2 +- notes-merge.c | 13 ++-------- odb/streaming.c | 6 ++--- parallel-checkout.c | 2 +- t/meson.build | 1 + t/unit-tests/u-reftable-stack.c | 2 +- t/unit-tests/u-wrapper.c | 42 +++++++++++++++++++++++++++++++++ wrapper.c | 6 ++--- wrapper.h | 7 ++++-- 12 files changed, 66 insertions(+), 32 deletions(-) create mode 100644 t/unit-tests/u-wrapper.c
Makefile +1 -0
@@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization CLAR_TEST_SUITES += u-utf8-width +CLAR_TEST_SUITES += u-wrapper CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
config.c +7 -7
@@ -2768,11 +2768,11 @@ static struct strbuf store_create_section(const char *key,return sb; } -static ssize_t write_section (int fd,const char *key, -const struct config_store_data *store) +static int write_section (int fd,const char *key, +const struct config_store_data *store) {struct strbuf sb =store_create_section (key, store); -ssize_t ret; +int ret; ret =write_in_full (fd, sb.buf, sb.len);strbuf_release (&sb);
@@ -2780,12 +2780,12 @@ static ssize_t write_section(int fd, const char *key,return ret; } -static ssize_t write_pair (int fd,const char *key,const char *value, -const char *comment, -const struct config_store_data *store) +static int write_pair (int fd,const char *key,const char *value, +const char *comment, +const struct config_store_data *store) {int i; -ssize_t ret; +int ret;const char *quote ="" ;struct strbuf sb =STRBUF_INIT ;
entry.c +1 -1
@@ -290,7 +290,7 @@ static int write_entry(struct cache_entry *ce, char *path, struct conv_attrs *cachar *new_blob;struct strbuf buf =STRBUF_INIT ;size_t size; -ssize_t wrote; +int wrote;size_t newsize =0 ;struct stat st;const struct submodule *sub;
imap-send.c +1 -1
@@ -392,7 +392,7 @@ static int socket_write(struct imap_socket *sock, const char *buf, int len) n =SSL_write (sock->ssl, buf, len); else#endif - n =write_in_full (sock->fd[1 ], buf, len); + n =write_in_full (sock->fd[1 ], buf, len) <0 ?-1 : len;if (n != len) {socket_perror ("write" , sock, n);close (sock->fd[0 ]);
notes-merge.c +2 -11
@@ -319,17 +319,8 @@ static void write_buf_to_worktree(const struct object_id *obj, fd =xopen (path,O_WRONLY |O_EXCL |O_CREAT ,0666 ); -while (size >0 ) { -ssize_t ret =write_in_full (fd, buf, size); -if (ret <0 ) { -/* Ignore epipe */ -if (errno ==EPIPE ) -break ; -die_errno ("notes-merge" ); - } - size -= ret; - buf += ret; - } +if (write_in_full (fd, buf, size) <0 && errno !=EPIPE ) +die_errno ("notes-merge" );close (fd);free (path);
odb/streaming.c +2 -4
@@ -247,7 +247,7 @@ int odb_stream_blob_to_fd(struct object_database *odb, goto close_and_exit;for (;;) {char buf[1024 *16 ]; -ssize_t wrote, holeto; +ssize_t holeto;ssize_t readlen =odb_stream_read (st, buf,sizeof (buf));if (readlen <0 )
@@ -268,9 +268,7 @@ int odb_stream_blob_to_fd(struct object_database *odb, goto close_and_exit; else kept =0 ; - wrote =write_in_full (fd, buf, readlen); - -if (wrote <0 ) +if (write_in_full (fd, buf, readlen) <0 ) goto close_and_exit; } if (kept && (lseek(fd, kept - 1, SEEK_CUR) == (off_t) -1 ||
parallel-checkout.c +1 -1
@@ -274,7 +274,7 @@ static int write_pc_item_to_fd(struct parallel_checkout_item *pc_item, int fd,struct strbuf buf =STRBUF_INIT ;char *blob;size_t size; -ssize_t wrote; +int wrote;/* Sanity check */ ASSERT (is_eligible_for_parallel_checkout (pc_item->ce, &pc_item->ca));
t/meson.build +1 -0
@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-wrapper.c', ] clar_sources = [
t/unit-tests/u-reftable-stack.c +1 -1
@@ -86,7 +86,7 @@ void test_reftable_stack__read_file(void)cl_assert (fd >0 ); n =write_in_full (fd, out,strlen (out)); -cl_assert_equal_i (n,strlen (out)); +cl_assert_equal_i (n,0 ); err =close (fd);cl_assert (err >=0 );
t/unit-tests/u-wrapper.c new file +42 -0
42 lines not on this page · raw message
wrapper.c +2 -4
@@ -302,10 +302,9 @@ ssize_t read_in_full(int fd, void *buf, size_t count)return total; } -ssize_t write_in_full (int fd,const void *buf,size_t count) +int write_in_full (int fd,const void *buf,size_t count) {const char *p = buf; -ssize_t total =0 ;while (count >0 ) {ssize_t written =xwrite (fd, p, count);
@@ -317,10 +316,9 @@ ssize_t write_in_full(int fd, const void *buf, size_t count) } count -= written; p += written; - total += written; } -return total; +return 0 ; }ssize_t xwritev (int fd,struct iovec *iov,int iovcnt)
wrapper.h +5 -2
@@ -45,7 +45,10 @@ int git_mkstemps_mode(char *pattern, int suffix_len, int mode);int git_mkstemp_mode (char *pattern,int mode);ssize_t read_in_full (int fd,void *buf,size_t count); -ssize_t write_in_full (int fd,const void *buf,size_t count); + +/* Return 0 on a complete write, or -1 with errno set on failure. */ +int write_in_full (int fd,const void *buf,size_t count); +ssize_t pread_in_full (int fd,void *buf,size_t count,off_t offset);/*
@@ -57,7 +60,7 @@ ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset);*/ ssize_t writev_in_full (int fd,struct iovec *iov,int iovcnt); -static inline ssize_t write_str_in_full (int fd,const char *str) +static inline int write_str_in_full (int fd,const char *str) {return write_in_full (fd, str,strlen (str)); }
Signature · 1 line
gitgitgadget
PATCH v3 4/5 wrapper: add read_in_full_or_error()
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Callers of the read_in_full() function want to read all requested bytes, or get an error. However, limiting the return value type to ssize_t is insufficient, as file sizes can easily exceed that type's range.
For those callers that do not require the return value to report the number of read bytes, add a new function, read_in_full_or_error(), that returns a Boolean to indicate success or faiure.
Callers that do need to know that byte count can still call read_in_full(), but will now abort to signal a programming error when the requested byte count exceeds what ssize_t can represent.
Pointed out by Coverity.
--- builtin/blame.c | 2 +- combine-diff.c | 6 +---- dir.c | 2 +- grep.c | 2 +- refs/packed-backend.c | 4 +-- strbuf.c | 10 ++++--- t/unit-tests/u-wrapper.c | 57 ++++++++++++++++++++++++++++++++++++++++ wrapper.c | 50 ++++++++++++++++++++++++++++------- wrapper.h | 7 +++++ 9 files changed, 116 insertions(+), 24 deletions(-)
builtin/blame.c +1 -1
@@ -1006,7 +1006,7 @@ static void parse_default_ignore_revs_file(struct blame_scoreboard *sb, } size =xsize_t (st.st_size); buf =xmalloc (size); -if (read_in_full (fd, buf, size) == (ssize_t )size) +if (!read_in_full_or_error (fd, buf, size))oidset_parse_buffer_carefully (&sb->ignore_list, buf, size, sb->repo->hash_algo, peel_to_commit_oid, sb);
combine-diff.c +1 -5
@@ -1073,7 +1073,6 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent,free_filespec (df); }else if (0 <= (fd =open (elem->path,O_RDONLY ))) {size_t len =xsize_t (st.st_size); -ssize_t done;int is_file, i; elem->mode =canon_mode (st.st_mode);
@@ -1089,11 +1088,8 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent, result_size = len; result =xmallocz (len); - done =read_in_full (fd, result, len); -if (done <0 ) +if (read_in_full_or_error (fd, result, len) <0 )die_errno ("read error '%s'" , elem->path); -else if (done < len) -die ("early EOF '%s'" , elem->path);/* If not a fake symlink, apply filters, e.g. autocrlf */ if (is_file) {
dir.c +1 -1
@@ -1190,7 +1190,7 @@ static int add_patterns(const char *fname, const char *base, int baselen,return 0 ; } buf =xmallocz (size); -if (read_in_full (fd, buf, size) != size) { +if (read_in_full_or_error (fd, buf, size) <0 ) {free (buf);close (fd);return -1 ;
grep.c +1 -1
@@ -1964,7 +1964,7 @@ static int grep_source_load_file(struct grep_source *gs)if (i <0 ) goto err_ret; data =xmallocz (size); -if (st.st_size !=read_in_full (i, data, size)) { +if (read_in_full_or_error (i, data, size) <0 ) {error_errno (_ ("'%s': short read" ), filename);close (i);free (data);
refs/packed-backend.c +1 -3
@@ -543,7 +543,6 @@ static int refname_contains_nul(struct strbuf *refname)static int allocate_snapshot_buffer (struct snapshot *snapshot,int fd,struct stat *st) { -ssize_t bytes_read;size_t size; size =xsize_t (st->st_size);
@@ -552,8 +551,7 @@ static int allocate_snapshot_buffer(struct snapshot *snapshot, int fd, struct stif (mmap_strategy ==MMAP_NONE || size <=SMALL_FILE_SIZE ) { snapshot->buf =xmalloc (size); - bytes_read =read_in_full (fd, snapshot->buf, size); -if (bytes_read <0 || bytes_read != size) +if (read_in_full_or_error (fd, snapshot->buf, size) <0 )die_errno ("couldn't read %s" , snapshot->refs->path); snapshot->mmapped =0 ; }else {
strbuf.c +7 -3
@@ -537,8 +537,12 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)strbuf_grow (sb, hint ? hint :8192 );for (;;) { -ssize_t want = sb->alloc - sb->len -1 ; -ssize_t got =read_in_full (fd, sb->buf + sb->len, want); +size_t want = sb->alloc - sb->len -1 ; +ssize_t got; + +if ((uintmax_t )want >maximum_signed_value_of_type (ssize_t)) + want =maximum_signed_value_of_type (ssize_t); + got =read_in_full (fd, sb->buf + sb->len, want);if (got <0 ) {if (oldalloc ==0 )
@@ -548,7 +552,7 @@ ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)return -1 ; } sb->len += got; -if (got < want) +if ((size_t )got < want)break ;strbuf_grow (sb,8192 ); }
t/unit-tests/u-wrapper.c +57 -0
60 lines not on this page · raw message
wrapper.c +40 -10
63 lines not on this page · raw message
wrapper.h +7 -0
@@ -44,8 +44,15 @@ char *git_mkdtemp(char *pattern);int git_mkstemps_mode (char *pattern,int suffix_len,int mode);int git_mkstemp_mode (char *pattern,int mode); +/* +* Return the number of bytes read, possibly short at EOF, or -1 on error. +* The requested count must be representable in ssize_t. +*/ ssize_t read_in_full (int fd,void *buf,size_t count); +/* Return 0 on a complete read, or -1 with errno set (EIO on premature EOF). */ +int read_in_full_or_error (int fd,void *buf,size_t count); +/* Return 0 on a complete write, or -1 with errno set on failure. */ int write_in_full (int fd,const void *buf,size_t count);
Signature · 1 line
gitgitgadget
PATCH v3 5/5 date: avoid overflow in approxidate relative-time multiplication
In reply to Johannes Schindelin via GitGitGadgetFrom: Johannes Schindelin <[email protected]>
Parsing relative dates can overflow int when multiplying a value by a unit length, before converting the result to time_t. Signed overflow is undefined behavior, therefore checking the converted value is too late.
Reject quantities above INT_MAX before narrowing to int on all platforms. The inputs are non-negative, meaning that checking unsigned arithmetic is sufficient. The product must also fit the native time_t range. Report arithmetic or conversion failures as parse errors rather than saturating the offset.
Pointed out by Coverity.
--- date.c | 26 ++++++++++++++++++++------ t/t0006-date.sh | 13 +++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-)
date.c +20 -6
@@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +uintmax_t length = tl->length, num_t = *num, seconds; + +if (unsigned_mult_overflows (length, num_t)) +return NULL ; + seconds = length * num_t; +if (date_overflows (seconds)) +return NULL ; +update_tm (tm, now, (time_t )seconds); *num =0 ; *touched =1 ;return end;
@@ -1377,8 +1384,11 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num, }/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ -if (date[0 ] !='0' || end - date <=2 ) +if (date[0 ] !='0' || end - date <=2 ) { +if (number >INT_MAX ) +return NULL ; *num = number; + }return end; }
@@ -1404,14 +1414,18 @@ static timestamp_t approxidate_str(const char *date,if (!c)break ; date++; -if (isdigit (c)) { +if (isalpha (c)) + date =approxidate_alpha (date-1 , &tm, &now, + &number, &touched); +else if (isdigit (c)) {pending_number (&tm, &number); date =approxidate_digit (date-1 , &tm, &number, time_sec); touched =1 ; -continue ; } -if (isalpha (c)) - date =approxidate_alpha (date-1 , &tm, &now, &number, &touched); +if (!date) { + *error_ret =1 ; +return 0 ; + } }pending_number (&tm, &number);if (!touched)
t/t0006-date.sh +13 -0
@@ -211,6 +211,19 @@ check_approxidate 3.weeks.ago '2009-08-09 19:20:00' check_approxidate 3.months.ago '2009-05-30 19:20:00' check_approxidate 2.years.3.months.ago '2007-05-30 19:20:00' +test_expect_success HAVE_64BIT_TIME 'parse a large number of weeks' ' + echo "Jan 1 2099 4000 weeks ago -> 1651778400" >expect && + test-tool date timestamp "Jan 1 2099 4000 weeks ago" >actual && + test_cmp expect actual +' + +test_expect_success TIME_IS_64BIT 'reject a quantity that does not fit in int' ' + git reflog expire --dry-run --all --expire="1 day 1 second ago" && + test_must_fail git reflog expire --dry-run --all \ + --expire="1 day 18446744073709551615 seconds ago" 2>err && + test_grep "invalid timestamp" err +' + check_approxidate '6am yesterday' '2009-08-29 06:00:00' check_approxidate '6pm yesterday' '2009-08-29 18:00:00' check_approxidate '3:00' '2009-08-30 03:00:00'
Signature · 1 line
gitgitgadget
Re: [PATCH v3 5/5] date: avoid overflow in approxidate relative-time multiplication
Quoted 10 lines · Johannes Schindelin via GitGitGadget
date.c +1
-1@@ -1307,7 +1307,14 @@ static const char *approxidate_alpha(const char *date, struct tm *tm, struct tmwhile (tl->type) {size_t len =strlen (tl->type);if (match_string (date, tl->type) >= len-1 ) { -update_tm (tm, now, tl->length * *num); +uintmax_t length = tl->length, num_t = *num, seconds;
date.c static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm · line 1320
Quoted 10 lines
date.c +7
-0+ +if (unsigned_mult_overflows (length, num_t)) +return NULL ; + seconds = length * num_t; +if (date_overflows (seconds)) +return NULL ; +update_tm (tm, now, (time_t )seconds); *num =0 ; *touched =1 ;return end;
This looks pedanticly paranoid ;-)
Doesn't a similar issue exist, however, immediately after this tl->type loop, where we handle weekday names?
for (i = 0; i < 7; i++) {
int match = match_string(date, weekday_names[i]);
if (match >= 3) {
int diff, n = *num -1;
*num = 0;
diff = tm->tm_wday - i;
if (diff <= 0)
n++;
diff += 7*n;
update_tm(tm, now, diff * 24 * 60 * 60);
*touched = 1;
return end;
}
}Like "40000 Mondays" gives *num == 40000, diff becomes 280000, multiplied by 86000 would exceed 24 billion, overflowing 32-bit signed int. I guess you can use the same uintmax_t overflow check used in the previous block?
Thanks.