Skip to content

Commit 0ceac0d

Browse files
pks-tethomson
authored andcommitted
mbedtls: fix potential size overflow when reading or writing data
The mbedtls library uses a callback mechanism to allow downstream users to plug in their own receive and send functions. We implement `bio_read` and `bio_write` functions, which simply wrap the `git_stream_read` and `git_stream_write` functions, respectively. The problem arises due to the return value of the callback functions: mbedtls expects us to return an `int` containing the actual number of bytes that were read or written. But this is in fact completely misdesigned, as callers are allowed to pass in a buffer with length `SIZE_MAX`. We thus may be unable to represent the number of bytes written via the return value. Fix this by only ever reading or writing at most `INT_MAX` bytes.
1 parent 75918ab commit 0ceac0d

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/streams/mbedtls.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,13 +169,13 @@ int git_mbedtls_stream_global_init(void)
169169
static int bio_read(void *b, unsigned char *buf, size_t len)
170170
{
171171
git_stream *io = (git_stream *) b;
172-
return (int) git_stream_read(io, buf, len);
172+
return (int) git_stream_read(io, buf, min(len, INT_MAX));
173173
}
174174

175175
static int bio_write(void *b, const unsigned char *buf, size_t len)
176176
{
177177
git_stream *io = (git_stream *) b;
178-
return (int) git_stream_write(io, (const char *)buf, len, 0);
178+
return (int) git_stream_write(io, (const char *)buf, min(len, INT_MAX), 0);
179179
}
180180

181181
static int ssl_set_error(mbedtls_ssl_context *ssl, int error)
@@ -308,6 +308,13 @@ static ssize_t mbedtls_stream_write(git_stream *stream, const char *data, size_t
308308

309309
GIT_UNUSED(flags);
310310

311+
/*
312+
* `mbedtls_ssl_write` can only represent INT_MAX bytes
313+
* written via its return value. We thus need to clamp
314+
* the maximum number of bytes written.
315+
*/
316+
len = min(len, INT_MAX);
317+
311318
if ((written = mbedtls_ssl_write(st->ssl, (const unsigned char *)data, len)) <= 0)
312319
return ssl_set_error(st->ssl, written);
313320

0 commit comments

Comments
 (0)