libarchive: do not extract unsafe symlinks unless $EXTRACT_UNSAFE_SYMLINKS=1
[oweals/busybox.git] / libbb / copy_file.c
index 23bcf2e828f03bcbc0654e115ae8d18131802ee8..be90066311fbb34c48e8c0def9d206db9c262068 100644 (file)
@@ -296,11 +296,16 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
                if (!S_ISREG(source_stat.st_mode))
                        new_mode = 0666;
 
-               // POSIX way is a security problem versus (sym)link attacks
-               if (!ENABLE_FEATURE_NON_POSIX_CP) {
-                       dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
-               } else { /* safe way: */
+               if (ENABLE_FEATURE_NON_POSIX_CP || (flags & FILEUTILS_INTERACTIVE)) {
+                       /*
+                        * O_CREAT|O_EXCL: require that file did not exist before creation
+                        */
                        dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
+               } else { /* POSIX, and not "cp -i" */
+                       /*
+                        * O_CREAT|O_TRUNC: create, or truncate (security problem versus (sym)link attacks)
+                        */
+                       dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
                }
                if (dst_fd == -1) {
                        ovr = ask_and_unlink(dest, flags);
@@ -366,7 +371,10 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
                        int r = symlink(lpath, dest);
                        free(lpath);
                        if (r < 0) {
-                               bb_perror_msg("can't create symlink '%s'", dest);
+                               /* shared message */
+                               bb_perror_msg("can't create %slink '%s' to '%s'",
+                                       "sym", dest, lpath
+                               );
                                return -1;
                        }
                        if (flags & FILEUTILS_PRESERVE_STATUS)
@@ -375,7 +383,7 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
                }
                /* _Not_ jumping to preserve_mode_ugid_time:
                 * symlinks don't have those */
-               return 0;
+               goto verb_and_exit;
        }
        if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
         || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
@@ -410,6 +418,7 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
                        bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
        }
 
+ verb_and_exit:
        if (flags & FILEUTILS_VERBOSE) {
                printf("'%s' -> '%s'\n", source, dest);
        }