简体   繁体   English

如何在Linux中通过C / C ++创建文件作为另一个用户?

[英]How to create file as another user via C/C++ in Linux?

Linux C/C++ has open or fopen API, but created file are belong to process uid. Linux下C / C ++具有openfopen API,但创造是属于处理UID文件。

If we want to change owner/group of this file, we can use chown or fchown API after file created. 如果我们想要更改此文件的所有者/组,我们可以在创建文件后使用chownfchown API。

But, is there one API for creating file as another user, not two API ? 但是,是否有一个API用于创建另一个用户的文件,而不是两个API?

There is no Unix api dedicated for that, but you can change the current user to other user before create the file, such as: 没有专用的Unix api,但您可以在创建文件之前将当前用户更改为其他用户,例如:

  1. Make sure you have permission. 确保你有权限。 The current effective user must be "root" OR set user or group ID on executable file. 当前有效用户必须是“root”或在可执行文件上设置用户或组ID。

  2. Call setgid and setuid to other user. setgidsetuid调用给其他用户。

  3. Create the file. 创建文件。

  4. Call setuid and setgid to old user if required. 如果需要,请将setuidsetgid调用给旧用户。

Because the user is process-wide, if your program is multi-threaded, you may need to fork a child process doing the steps I listed before. 因为用户是进程范围的,所以如果你的程序是多线程的,你可能需要分叉子进程执行我之前列出的步骤。

But if you want non-root user (such as nobody) to run your program, you can give the permission to your executable file: 但是,如果您希望非root用户(例如nobody)运行您的程序,您可以授予您的可执行文件的权限:

sudo chown root:root ./your_app && sudo chmod gu+s ./you_app

Now you can call setuid(0) and setgid(0) to acquire root permission. 现在,您可以调用setuid(0)setgid(0)来获取root权限。

It's not possible in Linux. 这在Linux中是不可能的。

Allowing this could cause some subtle security bugs (remote code execution, destroying files of other users, etc.) and therefore is not allowed. 允许这可能会导致一些微妙的安全漏洞(远程代码执行,破坏其他用户的文件等),因此是不允许的。

Instead, please just run the process under sudo . 相反,请在sudo下运行该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM