Subject: Re: bug#39236: [musl] coreutils cp mishandles error return from lchmod

From: Rich Felker <[email-masked]>
Date: Wed, 22 Jan 2020 17:05:15 -0500

On Wed, Jan 22, 2020 at 01:55:57PM -0800, Paul Eggert wrote:
> On 1/22/20 7:08 AM, Florian Weimer wrote:
> >I think you misread what I wrote: lchmod*always*  returns ENOSYS.  Even
> >if the file is not a symbolic link.  Likewise, fchmodat with
> >AT_SYMLINK_NOFOLLOW *always* returns ENOTSUP.
> 
> That's too bad, because coreutils (and many other applications, I
> expect) assume that lchmod (and fchmodat with AT_SYMLINK_NOFOLLOW)
> to act like chmod except not follow symlinks, in order to make it
> less likely that the application will run afoul of a symlink race
> and chmod the wrong file. Isn't that how the Linux fstatat call
> behaves? And if so, why does glibc fstatat refuse to support this
> behavior?

I think you're confusing fchmodat with fstatat. The Linux fchmodat
syscall lacks a flags argument and thus doesn't suffice to implement
fchmodat. The fstatat syscall does work.

> To work around this bug, I suppose coreutils etc. should do
> something like the following:
> 
> 1. Never use lchmod since the porting nightmare is bad enough without it.
> 
> 2. On non-glibc systems (or glibc systems where the bug is fixed),
> use fchmodat with AT_SYMLINK_NOFOLLOW.
> 
> 3. On glibc systems with the bug, use openat with
> AT_SYMLINK_NOFOLLOW and O_PATH, and then fchmod the resulting file
> descriptor.
> 
> Does this sound right? Or is there some O_PATH gotcha that I haven't
> thought about?

I think fchmod historically did not work on O_PATH file descriptors,
which is why musl is using chmod on the procfs magic symlink. However,
fchmodat might work too with an empty pathname; I'm not sure.

I think these fixes are better encapsulated as a replacement for
missing/broken fchmodat, rather than putting the logic in individual
utilities or coreutils-specific library code.

Also, note that if you want to skip checking stat to make sure you
didn't open a symlink with O_PATH, that depends on confirming
Florian's claim that the kernel documents it will not follow the
symlink.

> Come to think of it, perhaps the best thing would be to change
> Gnulib's lchmod and fchmodat modules so that they do what
> applications expect, even on buggy glibc systems. (Which would be
> ironic, since Gnulib's main goal is to put wrappers around other
> libraries so that they look more like glibc.)

I think we're approaching a consensus that glibc should fix this too,
so then it would just be gnulib matching the fix.

Rich