Linux: changing file ownership without a copy?

2019-05-29 02:51发布

I have a REST server whose purpose is to organize files generated by various users. To keep things simple, both the server and the users have access to a shared network filesystem.

The workflow is as follows: the user generates the file in a temp folder. He then notifies the server who then puts the file in a place of its own and stores some metadata in a database. The server should then own the files and take care of their deletion as needed.

My problem is the following: since the files can be quite big, I'd like to avoid a costly copy and instead simply move the files from the temp folder to their final destination. However, moving the files prevents the server from changing their ownership (see here for example).

Is there a way around this, without 1) copying the file, and 2)running the server as root?

EDIT: a couple precisions:

  • The file to be moved can be a directory with a hierarchy of files
  • It would be nice to have the server own the files in the final location to restrict access to other users.

2条回答
狗以群分
2楼-- · 2019-05-29 03:13

You should use a user group for all users and the server. Make the temp directory owned by that group and set it group-writable and sgid.

chown :groupname /path/to/temp
chmod g+s /path/to/temp
chmod 770 /path/to/temp

Then the server can adopt ownership of the file easily. Of course this means users can write other users' files, but I guess this is not a concern because they stay there a very short time?

查看更多
SAY GOODBYE
3楼-- · 2019-05-29 03:22

If you create a separate user just to handle the chown, you can give that user the CAP_CHOWN capability, and you can have a single executable owned by that user that has the setuid bit set on it (so it executes as that user).

For security, this executable should do as little as possible, with as many checks as possible.

It should do the chown for the server user after the server user does the move. It should exist in a directory that is not writable by other users; it can do checks to insure that it is happy with all the attributes of the files it is asked to chown (current owner, location, etc.), it can have the server user hard-coded (so nobody else can use it), etc.

This will probably have to be a small C program, since most systems don't let you use setuid with scripts. You can find several small example programs on the web that do chown -- one is here

查看更多
登录 后发表回答