Skip to content

Use after free, in bruteforce.h #626

@davidshoon

Description

@davidshoon

In the following function in hnswlib/bruteforce.h:

void removePoint(labeltype cur_external) {
    std::unique_lock<std::mutex> lock(index_lock);

    auto found = dict_external_to_internal.find(cur_external);
    if (found == dict_external_to_internal.end()) {
        return;
    }
    
    dict_external_to_internal.erase(found);

// found->second is used after it's been freed (above)
// and it's used by cur_c later on.
size_t cur_c = found->second;

    labeltype label = *((labeltype*)(data_ + size_per_element_ * (cur_element_count-1) + data_size_));
    dict_external_to_internal[label] = cur_c;
    memcpy(data_ + size_per_element_ * cur_c,
            data_ + size_per_element_ * (cur_element_count-1),
            data_size_+sizeof(labeltype));
    cur_element_count--;
}

It should be:

void removePoint(labeltype cur_external) {
    std::unique_lock<std::mutex> lock(index_lock);

    auto found = dict_external_to_internal.find(cur_external);
    if (found == dict_external_to_internal.end()) {
        return;
    }

// store a copy of found->second before freeing found...
size_t cur_c = found->second;
dict_external_to_internal.erase(found);

    labeltype label = *((labeltype*)(data_ + size_per_element_ * (cur_element_count-1) + data_size_));
    dict_external_to_internal[label] = cur_c;
    memcpy(data_ + size_per_element_ * cur_c,
            data_ + size_per_element_ * (cur_element_count-1),
            data_size_+sizeof(labeltype));
    cur_element_count--;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions