copyfile(): Fix potentially dangerous time of check-time of use bug.

Coverity reports a potenatially TOCTOU bug, CWE-367, in copyfile().
Turns out we tried to fall back to copy when readlink() failed, in
the case when the user requested to copy symlinks.

It's better to fail hard if stat() reports symlink and readlink()
right after fails to read the symlink ...

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
This commit is contained in:
Joachim Nilsson committed 2015-06-22 22:39:59 +02:00
1 parent 35b43c5c56
commit e4c5a0e77e
1 file changed
+19 -8
+19 -8
View File
@@ -53,13 +53,14 @@ static int adjust_target(char *src, char **dst);
* Returns: * Returns:
* The number of bytes copied, zero may be error (check errno!), but it * The number of bytes copied, zero may be error (check errno!), but it
* may also indicate that @src was empty. If @src is a directory errno * may also indicate that @src was empty. If @src is a directory errno
* will be set to %EISDIR since copyfile() is not recursive. * will be set to %EISDIR since copyfile() is not recursive. If @src
*/ */
ssize_t copyfile(char *src, char *dst, int len, int sym) ssize_t copyfile(char *src, char *dst, int len, int sym)
{ {
char *buffer; char *buffer;
int in, out, isdir = 0, saved_errno = 0; int in, out, isdir = 0, saved_errno = 0;
ssize_t num, size = 0; ssize_t num, size = 0;
struct stat sb;
errno = 0; errno = 0;
@@ -75,20 +76,30 @@ ssize_t copyfile(char *src, char *dst, int len, int sym)
/* Check if target is a directory, then append src filename. */ /* Check if target is a directory, then append src filename. */
isdir = adjust_target(src, &dst); isdir = adjust_target(src, &dst);
if (sym) { /* Check if the source file is a symlink ... */
size = readlink(src, buffer, BUFSIZ); if (stat(src, &sb)) {
if (size > 0) { size = -1;
if (size >= (ssize_t) BUFSIZ) {
saved_errno = ENOBUFS;
goto exit; goto exit;
} }
/* ... only try readlink() if symlink and @sym is set. */
if (sym && (sb.st_mode & S_IFMT) == S_IFLNK) {
size = readlink(src, buffer, BUFSIZ);
if (size > 0) {
if (size >= (ssize_t)BUFSIZ) {
saved_errno = ENOBUFS;
size = -1;
} else {
buffer[size] = 0; buffer[size] = 0;
size = !symlink(buffer, dst); size = !symlink(buffer, dst);
goto exit;
} }
} }
/* Don't fall back to copy, that is a potentially
* dangerous race condition, see CWE-367. */
goto exit;
}
/* 0: copy entire file */ /* 0: copy entire file */
if (len == 0) if (len == 0)
len = INT_MAX; /* XXX: 2047 MiB should sufficient ... */ len = INT_MAX; /* XXX: 2047 MiB should sufficient ... */
@@ -369,7 +380,7 @@ int main(void)
/** /**
* Local Variables: * Local Variables:
* compile-command: "gcc -g -I../include -o unittest -DUNITTEST copyfile.c && ./unittest" * compile-command: "gcc -g -I../include -o copy -DUNITTEST copyfile.c fisdir.c fexist.c fmode.c && ./copy"
* version-control: t * version-control: t
* indent-tabs-mode: t * indent-tabs-mode: t
* c-file-style: "linux" * c-file-style: "linux"