2
0
mirror of git://github.com/lxc/lxc synced 2025-09-05 11:49:34 +00:00

utils: add uid, gid, group convenience wrappers

This commit adds lxc_switch_uid_gid() which allows to switch the uid and gid of
a process via setuid() and setgid() and lxc_setgroups() which allows to set
groups via setgroups(). The main advantage is that they nicely log the switches
they perform.

Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>
This commit is contained in:
Christian Brauner
2017-01-02 15:12:10 +01:00
parent 4484e6f80c
commit dbaf55a353
2 changed files with 34 additions and 0 deletions

View File

@@ -26,6 +26,7 @@
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <libgen.h>
#include <stddef.h>
#include <stdio.h>
@@ -2053,3 +2054,32 @@ int lxc_safe_long(const char *numstr, long int *converted)
*converted = sli;
return 0;
}
int lxc_switch_uid_gid(uid_t uid, gid_t gid)
{
if (setgid(gid) < 0) {
SYSERROR("Failed to switch to gid %d.", gid);
return -errno;
}
NOTICE("Switched to gid %d.", gid);
if (setuid(uid) < 0) {
SYSERROR("Failed to switch to uid %d.", uid);
return -errno;
}
NOTICE("Switched to uid %d.", uid);
return 0;
}
/* Simple covenience function which enables uniform logging. */
int lxc_setgroups(int size, gid_t list[])
{
if (setgroups(size, list) < 0) {
SYSERROR("Failed to setgroups().");
return -errno;
}
NOTICE("Dropped additional groups.");
return 0;
}

View File

@@ -327,4 +327,8 @@ int lxc_safe_uint(const char *numstr, unsigned int *converted);
int lxc_safe_int(const char *numstr, int *converted);
int lxc_safe_long(const char *numstr, long int *converted);
/* Switch to a new uid and gid. */
int lxc_switch_uid_gid(uid_t uid, gid_t gid);
int lxc_setgroups(int size, gid_t list[]);
#endif /* __LXC_UTILS_H */