Copy the output of fixed-output derivations before registering them

It is possible to exfiltrate a file descriptor out of the build sandbox
of FODs, and use it to modify the store path after it has been
registered.
To avoid that issue, don't register the output of the build, but a copy
of it (that will be free of any leaked file descriptor).
This commit is contained in:
Théophane Hufschmitt 2024-02-13 08:28:02 +01:00
parent a55c6a0f47
commit c3878f510e
3 changed files with 18 additions and 0 deletions

View file

@ -2543,6 +2543,12 @@ SingleDrvOutputs LocalDerivationGoal::registerOutputs()
[&](const DerivationOutput::CAFixed & dof) { [&](const DerivationOutput::CAFixed & dof) {
auto & wanted = dof.ca.hash; auto & wanted = dof.ca.hash;
// Replace the output by a fresh copy of itself to make sure
// that there's no stale file descriptor pointing to it
Path tmpOutput = actualPath + ".tmp";
renameFile(actualPath, tmpOutput);
copyFile(tmpOutput, actualPath, true);
auto newInfo0 = newInfoFromCA(DerivationOutput::CAFloating { auto newInfo0 = newInfoFromCA(DerivationOutput::CAFloating {
.method = dof.ca.method, .method = dof.ca.method,
.hashAlgo = wanted.algo, .hashAlgo = wanted.algo,

View file

@ -617,6 +617,11 @@ void copy(const fs::directory_entry & from, const fs::path & to, bool andDelete)
} }
} }
void copyFile(const Path & oldPath, const Path & newPath, bool andDelete)
{
return copy(fs::directory_entry(fs::path(oldPath)), fs::path(newPath), andDelete);
}
void renameFile(const Path & oldName, const Path & newName) void renameFile(const Path & oldName, const Path & newName)
{ {
fs::rename(oldName, newName); fs::rename(oldName, newName);

View file

@ -186,6 +186,13 @@ void renameFile(const Path & src, const Path & dst);
*/ */
void moveFile(const Path & src, const Path & dst); void moveFile(const Path & src, const Path & dst);
/**
* Recursively copy the content of `oldPath` to `newPath`. If `andDelete` is
* `true`, then also remove `oldPath` (making this equivalent to `moveFile`, but
* with the guaranty that the destination will be fresh, with no stale inode
* or file descriptor pointing to it).
*/
void copyFile(const Path & oldPath, const Path & newPath, bool andDelete);
/** /**
* Automatic cleanup of resources. * Automatic cleanup of resources.