Now, it is possible to do this at the kernel level.
This is actually a design flaw of the Linux kernel, that credential changes occur only on disks but not in memory. To put it specifically, when credentials (UID, GID, or supplementary group list) are changed, all existing processes will continue to use their previous credentials and enjoy access to previously granted data. And there is not a single API function to propagate credential change throughout the system (i.e., all processes). As a result of this defect, no user-level programs can do what you want. You have to end your current process and create a new process.
Nevertheless, at kernel level, it is possible to do this. I have just tried to make one and it works on simple programs. (https://github.com/xuancong84/supgroup)
However, in general it is not a good idea to do so because in general a program can have lots of external interactions, e.g., opened file handles, child processes/threads running on other CPU cores, bound pipes, opened devices, etc. Thus, changing the UID/GID while running can lead to many undefined behavior among which some can cause error (e.g., broken pipe, aborted I/O communication), some can turn out hazardous (e.g., system crash). I have tested that this program works on simple programs (such as nc -l 8080
), but on a much bigger complex program running many threads on many CPU cores and GPU CUDA cores, having heavy network activity and disk I/O activity, I am not sure what will happen.
foo
; should any of those be allowed to IDbar
? This is probably one of the main reasons why it is not done. – Zygophyte