From 909687ddf0cfbcc3bbc4679f2c67af80bcb954d0 Mon Sep 17 00:00:00 2001 From: "Matthew L. Curry" Date: Sun, 11 Oct 2020 05:02:24 -0600 Subject: [PATCH] Userland/cp: Disallow copying directories into themselves This patch causes cp to investigate whether a directory is being copied into a subdirectory of itself. It uses realpath(3) to ensure that links do not confound detection. --- Userland/cp.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Userland/cp.cpp b/Userland/cp.cpp index 8f0b6286b0..a19a883834 100644 --- a/Userland/cp.cpp +++ b/Userland/cp.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -174,6 +175,16 @@ bool copy_directory(String src_path, String dst_path) perror("cp: mkdir"); return false; } + + String src_rp = Core::File::real_path_for(src_path); + String dst_rp = Core::File::real_path_for(dst_path); + + if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp)) { + fprintf(stderr, "cp: Cannot copy %s into itself (%s)\n", + src_path.characters(), dst_path.characters()); + return false; + } + Core::DirIterator di(src_path, Core::DirIterator::SkipDots); if (di.has_error()) { fprintf(stderr, "cp: DirIterator: %s\n", di.error_string());