From a2f4183b1a74c84c9477c56a0cc759a7098323cd Mon Sep 17 00:00:00 2001 From: Rahul Rampure Date: Thu, 13 Jun 2024 00:01:53 +0530 Subject: [PATCH] MB-62221: Fix buffer overflow (#29) - The `faiss::VectorIOWriter.data` is a vector of type `uint8_t`. However, the code attempts to copy this vector to a malloc'd array of type `unsigned char`. This results in platform-dependent code since `uint8_t` is platform-agnostic, whereas `unsigned char` is not defined consistently across different platforms in the C standard. - This issue becomes apparent when using `std::copy`, where the effective signature is `std::copy(uint8_t*, uint8_t*, unsigned char*)`. - According to the C++ STL template for `copy`, both the StartPointer and DestinationPointer are incremented by 1. The behavior of this pointer arithmetic depends on the type of pointer passed. Since `uint8_t*` is platform-agnostic and `unsigned char*` is platform-dependent, a buffer overflow could occur, leading to undefined behavior for `std::copy()` as per the C++ standard. - Also fixes a mismatched header file where the signature of `faiss_read_index_buf` was not matching the one defined in the source cpp file. --- c_api/index_io_c_ex.cpp | 4 ++-- c_api/index_io_c_ex.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/c_api/index_io_c_ex.cpp b/c_api/index_io_c_ex.cpp index ef2110dbe6..adcbe77b32 100644 --- a/c_api/index_io_c_ex.cpp +++ b/c_api/index_io_c_ex.cpp @@ -17,11 +17,11 @@ using faiss::Index; using faiss::IndexBinary; -int faiss_write_index_buf(const FaissIndex* idx, size_t* size, unsigned char** buf) { +int faiss_write_index_buf(const FaissIndex* idx, size_t* size, uint8_t** buf) { try { faiss::VectorIOWriter writer; faiss::write_index(reinterpret_cast(idx), &writer); - unsigned char* tempBuf = (unsigned char*)malloc((writer.data.size()) * sizeof(uint8_t)); + uint8_t* tempBuf = (uint8_t*)malloc((writer.data.size()) * sizeof(uint8_t)); std::copy(writer.data.begin(), writer.data.end(), tempBuf); *buf = tempBuf; *size = writer.data.size(); diff --git a/c_api/index_io_c_ex.h b/c_api/index_io_c_ex.h index 7c85409b8c..31f0339477 100644 --- a/c_api/index_io_c_ex.h +++ b/c_api/index_io_c_ex.h @@ -31,11 +31,11 @@ extern "C" { /** Write index to buffer */ -int faiss_write_index_buf(const FaissIndex* idx, size_t* buf_size, unsigned char** buf); +int faiss_write_index_buf(const FaissIndex* idx, size_t* buf_size, uint8_t** buf); /** Read index from buffer */ -int faiss_read_index_buf(const unsigned char* buf, size_t limit, int io_flags, +int faiss_read_index_buf(const uint8_t* buf, size_t limit, int io_flags, FaissIndex** p_out); #ifdef __cplusplus