unlink-directory.c revision 2c8041ef37c9bf07344bdf2a162c0ac96647bf8b
/* Copyright (c) 2002-2010 Dovecot authors, see the included COPYING file */
/*
There's a bit tricky race condition with recursive deletion.
Suppose this happens:
lstat(dir, ..) -> OK, it's a directory
// attacker deletes dir, replaces it with symlink to /
opendir(dir) -> it actually opens /
Most portable solution is to lstat() the dir, chdir() there, then check
assumes that the device has usable inodes, most should except for some NFS
implementations.
Filesystems may also reassign a deleted inode to another file
immediately after it's deleted. That in theory makes it possible to exploit
this race to delete the new directory. However, the new inode is quite
unlikely to be any important directory, and attacker is quite unlikely to
find out which directory even got the inode. Maybe with some setuid program
or daemon interaction something could come out of it though.
Another less portable solution is to fchdir(open(dir, O_NOFOLLOW)).
This should be completely safe.
The actual file deletion also has to be done relative to current
directory, to make sure that the whole directory structure isn't replaced
with another one while we're deleting it. Going back to parent directory
isn't too easy either - safest (and easiest) way again is to open() the
directory and fchdir() back there.
*/
#define _GNU_SOURCE /* for O_NOFOLLOW with Linux */
#include "lib.h"
#include "close-keep-errno.h"
#include "unlink-directory.h"
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
static int unlink_directory_r(const char *dir)
{
struct dirent *d;
#ifdef O_NOFOLLOW
if (dir_fd == -1)
return -1;
#else
return -1;
else {
/* be compatible with O_NOFOLLOW */
}
return -1;
}
if (dir_fd == -1)
return -1;
return -1;
}
/* directory was just replaced with something else. */
return -1;
}
#endif
return -1;
}
return -1;
}
errno = 0;
if (d->d_name[0] == '.' &&
/* skip . and .. */
continue;
}
break;
errno = 0;
if (unlink_directory_r(d->d_name) < 0) {
break;
errno = 0;
}
break;
/* standardize errno */
}
break;
}
errno = 0;
}
/* can't delete NFS files that are still
in use. let the caller decide if this error
is worth logging about */
break;
} else {
/* so it wasn't a directory */
i_error("unlink(%s/%s) failed: %m",
break;
}
}
}
return -1;
if (old_errno != 0) {
return -1;
}
return 0;
}
{
if (fd == -1)
return -1;
ret = 0;
i_fatal("unlink_directory(%s): "
"Can't fchdir() back to our original dir: %m", dir);
}
if (ret < 0) {
return -1;
}
if (unlink_dir) {
/* standardize errno */
}
return -1;
}
}
return 0;
}