[SERVER-32832] Arithmetic overflow in mongo::nsDBHash Created: 22/Jan/18  Updated: 27/Oct/23  Resolved: 21/Jun/18

Status: Closed
Project: Core Server
Component/s: Internal Code
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Billy Donahue Assignee: Backlog - Storage Execution Team
Resolution: Gone away Votes: 0
Labels: neweng
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Storage Execution
Operating System: ALL
Participants:

 Description   

After just a few characters, this function will overflow the signed int 'hash', which is undefined behavior. Conjecture: it might even be exploitable by an optimizer since the function is inline.

inline int nsDBHash(const std::string& ns) {                                                                                 
    int hash = 7; 
    for (size_t i = 0; i < ns.size(); i++) {                                                                                 
        if (ns[i] == '.')                                                                                                    
            break; 
        hash += 11 * ns[i];                                                                                                  
        hash *= 3;                                                                                                           
    }
    return hash;                                                                                                             
}                                                                                                                            

I suggest we switch to unsigned math for the bit wrangling and cast to int at the end.

https://github.com/mongodb/mongo/commit/bc2d722169d5d1b46adfc603e29730b029b5e933#diff-fad15cbf66c82ba4a36fd2cc2e1c0b00R584



 Comments   
Comment by Eric Milkie [ 21/Jun/18 ]

Code was removed in SERVER-32367

Comment by Eric Milkie [ 22/Jan/18 ]

I also recommend moving this function into namespace_string_test.cpp, since it is only consumed by functions in that source file.

Generated at Thu Feb 08 04:31:25 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.