NetBSD-Bugs archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

bin/56775: sort -o foo foo can sometines remove foo



>Number:         56775
>Category:       bin
>Synopsis:       sort -o foo foo can sometines remove foo
>Confidential:   no
>Severity:       serious
>Priority:       medium
>Responsible:    bin-bug-people
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Thu Mar 31 19:10:00 +0000 2022
>Originator:     RVP
>Release:        NetBSD/amd64 9.99.96
>Organization:
>Environment:
NetBSD x202e.localdomain 9.99.96 NetBSD 9.99.96 (MYKERNEL) #0: Thu Mar 31 09:03:09 UTC 2022  bld@x202e.localdomain:/usr/obj/usr/src/sys/arch/amd64/compile/MYKERNEL amd64
>Description:
Under certain circumstances, `sort -o foo foo' can end up deleting `foo':

$ sudo sysctl -w security.models.extensions.hardlink_check_uid=1
$ sudo sysctl -w security.models.extensions.hardlink_check_gid=1
$ cd /tmp               # cd to a world-writable dir.
$ >foo
$ ls -l foo             # note that group is `wheel' as per BSD
                        # semantics for /tmp
-rw-------  1 rvp  wheel  0 Mar 31 08:32 foo
$ sort -o foo foo
sort: cannot link foo: output left in foopSQspp: Permission denied
$ ls -l foo
ls: foo: No such file or directory
$ 

Input file is destroyed if user doesn't belong to group `wheel'--even
though files can be created and renamed by anyone in /tmp.

This results in this error message (caused by running lorder) while
building the kernel:

[...]
    compile  kern/umodti3.o
    compile  kern/xlat_mbr_fstype.o
building standard kern library
sort: cannot link /tmp/_reference_.psA3FN: output left in /tmp/_reference_.psA3FNlDcAku: Permission denied
sort: cannot link /tmp/_symbol_.Gy4pSK: output left in /tmp/_symbol_.Gy4pSKrHWftZ: Permission denied
nbjoin: /tmp/_reference_.psA3FN: No such file or directory
     create  vers.c
[...]

>How-To-Repeat:
As above.
>Fix:
Use rename(2):

diff -urN usr.bin/sort.orig/sort.c usr.bin/sort/sort.c
--- usr.bin/sort.orig/sort.c	2017-01-10 21:13:45.000000000 +0000
+++ usr.bin/sort/sort.c	2022-03-31 09:17:25.991550462 +0000
@@ -329,7 +329,7 @@
 		errno = 0;
 		if (access(outpath, W_OK))
 			err(2, "%s", outpath);
-		(void)snprintf(toutpath, sizeof(toutpath), "%sXXXXXX",
+		(void)snprintf(toutpath, sizeof(toutpath), "%s.XXXXXX",
 		    outpath);
 		if ((outfd = mkstemp(toutpath)) == -1)
 			err(2, "Cannot create temporary file `%s'", toutpath);
@@ -368,11 +368,8 @@
 			    outpath, outfile);
 		}
 
-		(void)unlink(outpath);
-		if (link(outfile, outpath))
-			err(2, "cannot link %s: output left in %s",
-			    outpath, outfile);
-		(void)unlink(outfile);
+		if (rename(outfile, outpath) == -1)
+			err(2, "rename failed: %s->%s", outfile, outpath);
 		toutpath[0] = 0;
 	}
 	exit(0);



Home | Main Index | Thread Index | Old Index