Copilot commented on code in PR #3858:
URL: https://github.com/apache/avro/pull/3858#discussion_r3566956409


##########
lang/c/src/encoding_binary.c:
##########
@@ -180,15 +201,35 @@ size_bytes(avro_writer_t writer, const char *bytes, const 
int64_t len)
 static int read_string(avro_reader_t reader, char **s, int64_t *len)
 {
        int64_t  str_len = 0;
+       int64_t  available;
        int rval;
        check_prefix(rval, read_long(reader, &str_len),
                     "Cannot read string length: ");
        if (str_len < 0) {
                avro_set_error("Invalid string length: %" PRId64, str_len);
                return EINVAL;
        }
+       /* Reject a declared length that exceeds the data actually available
+        * before allocating for it, to guard against an out-of-memory attack
+        * from a malicious or truncated input. Only enforced when the reader
+        * can report the amount remaining. */
+       available = avro_reader_bytes_available(reader);
+       if (available >= 0 && str_len > available) {
+               avro_set_error("String length %" PRId64
+                              " exceeds %" PRId64 " bytes available",
+                              str_len, available);
+               return EINVAL;
+       }
+       /* Bound the length so the +1 (NUL terminator) cannot overflow the
+        * size_t allocation size, which could otherwise undersize the buffer
+        * and lead to an out-of-bounds read/write. */
+       if ((uint64_t) str_len > (uint64_t) (SIZE_MAX - 1)) {
+               avro_set_error("String length %" PRId64
+                              " exceeds the maximum allocatable size", 
str_len);
+               return EINVAL;
+       }
        *len = str_len + 1;
-       *s = (char *) avro_malloc(*len);
+       *s = (char *) avro_malloc((size_t) str_len + 1);
        if (!*s) {

Review Comment:
   `*len = str_len + 1;` can overflow when `str_len == INT64_MAX` (malformed 
input), which is undefined behavior in C and can corrupt the returned length. 
The preceding `SIZE_MAX - 1` check doesn’t prevent this on 64-bit platforms 
where `SIZE_MAX` > `INT64_MAX`. Add an explicit `INT64_MAX - 1` bound (or 
compute the +1 in an unsigned type) before assigning `*len`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to