Skip to content

Commit

Permalink
Check offset bounds in BinaryDict::NewFromFile method
Browse files Browse the repository at this point in the history
  • Loading branch information
Peng Wu committed Mar 1, 2021
1 parent 30e27f2 commit e1b8c79
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/BinaryDict.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ void BinaryDict::SerializeToFile(FILE* fp) const {
}

BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
size_t offsetBound, savedOffset;
savedOffset = ftell(fp);
fseek(fp, 0L, SEEK_END);
offsetBound = ftell(fp) - savedOffset;
fseek(fp, savedOffset, SEEK_SET);

BinaryDictPtr dict(new BinaryDict(LexiconPtr(new Lexicon)));

// Number of items
Expand Down Expand Up @@ -113,7 +119,7 @@ BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
// Key offset
size_t keyOffset;
unitsRead = fread(&keyOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
if (unitsRead != 1 || keyOffset >= offsetBound) {
throw InvalidFormat("Invalid OpenCC binary dictionary (keyOffset)");
}
std::string key = dict->keyBuffer.c_str() + keyOffset;
Expand All @@ -122,7 +128,7 @@ BinaryDictPtr BinaryDict::NewFromFile(FILE* fp) {
for (size_t j = 0; j < numValues; j++) {
size_t valueOffset;
unitsRead = fread(&valueOffset, sizeof(size_t), 1, fp);
if (unitsRead != 1) {
if (unitsRead != 1 || valueOffset >= offsetBound) {
throw InvalidFormat("Invalid OpenCC binary dictionary (valueOffset)");
}
const char* value = dict->valueBuffer.c_str() + valueOffset;
Expand Down

0 comments on commit e1b8c79

Please # to comment.