CVE-2021-3277 – Nagios XI <= 5.7.5 Remote Code Execution

Nagios XI <= 5.7.5 allows authenticated admins to upload arbitrary files due to improper validation of the rename functionality in custom-includes component.
With the custom includes components we can upload various file types such as .css, .js, .png, and more.
After uploading an image file, we can rename the file, the renaming code is pretty straightforward:

function rename_file()
{
    $error = false;
    $id = grab_request_var('id', '');
    $name = grab_request_var('name', '');
    $newname = stripcslashes(trim($name));
    if (empty($id) || empty($name)) { $error = true; }

    if (!$error) {
        $images = get_array_option('custom_includes_files_images');
        $i = $images[$id];

        // Rename the file and send back json
        $x = rename($i['dir'].'/'.$i['name'], $i['dir'].'/'.$newname);
        if ($x === false) {
            $error = true;
        } else {
            // Rename the database entry
            $images[$id]['name'] = $newname;
            set_array_option('custom_includes_files_images', $images);
        }  
    }

    if ($error) {
        echo json_encode(array('error' => 1, 'msg' => _('Could not rename file. Check file permissions.')));
    } else {
        echo json_encode(array('error' => 0, 'msg' => _('Renamed successfully')));
    }
}

As you can see, it takes the id of the old image, the name of the new image, and then renaming it.
There is no file name is validation at all, which allows the attacker not only to directory traversal but also to rename the file with any extension we want.
Which as a result, the attacker can upload arbitrary files.