Fortify reported a buffer overflow vulnerability in below code citing following reason -
In this case we are primarily concerned with the case "Depends upon properties of the data that are enforced outside of the immediate scope of the code.", because we cannot verify the safety of the operation performed by memcpy() in abc.cpp
void create_dir(const char *sys_tmp_dir, const char *base_name,
size_t base_name_len)
{
char *tmp_dir;
size_t sys_tmp_dir_len;
sys_tmp_dir_len = strlen(sys_tmp_dir);
tmp_dir = (char*) malloc(sys_tmp_dir_len + 1 + base_name_len + 1);
if(NULL == tmp_dir)
return;
memcpy(tmp_dir, sys_tmp_dir, sys_tmp_dir_len);
tmp_dir[sys_tmp_dir_len] = FN_LIBCHAR;
memcpy(tmp_dir + sys_tmp_dir_len + 1, base_name, base_name_len);
tmp_dir[sys_tmp_dir_len + base_name_len + 1] = '\0';
..........
..........
}
It appears to me a false positive since we are getting the size of data first, allocating that much amount of space, then calling memcpy with size to copy. But I am looking for good reasons to convince fellow developer to get rid of current implementation and rather use c++ strings. This issue has been assigned to him. He just sees this a false positive so doesn't want to change anything.
Edit I see quick, valid criticism of the current code. Hopefully, I'll be able to convince him now. Otherwise, I'll hold the baton. :)
base_name_lenbeing truthful. As it says, that's not being enforced in the scope of this code. Using something more sensible likestd::stringwould fix that.base_nameis not a null-terminated string, you could usememcpy(tmp_dir + sys_tmp_dir_len + 1, base_name, base_name_len + 1);somemcpy()null terminates the string. Ifbase_nameis not accurate or is not a null-terminated string, then your existing code is safer. I don't see a problem with buffer overflow if you check the result ofmalloc()— but if you don't think you can trust the strings being passed, then you should check them for nullness. You can't check them for validity otherwise in a reliable, portable way.std::stringone-liner making it exception-safe in the process, plus you know it'll shut up a false positive in your tool - what more reason do you need? If you want to use C,asprintf()if it suits your portability needs... concise code can hide fewer bugs and obfuscate less meaningful logic.base_name_len, Adriano Repetti's comment on trustingsys_tmp_dirand Matt's comment onmallocfailing, in just 20 minutes.