From: Christian Brauner Date: Mon, 2 Jan 2017 14:12:10 +0000 (+0100) Subject: utils: add uid, gid, group convenience wrappers X-Git-Tag: lxc-2.1.0~214^2~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=dbaf55a35377e1aa497ffc22de528e76c237b0fd;p=thirdparty%2Flxc.git 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 --- diff --git a/src/lxc/utils.c b/src/lxc/utils.c index 2a0f05a55..0227c3267 100644 --- a/src/lxc/utils.c +++ b/src/lxc/utils.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -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; +} diff --git a/src/lxc/utils.h b/src/lxc/utils.h index b7dcd5d92..2b56905cb 100644 --- a/src/lxc/utils.h +++ b/src/lxc/utils.h @@ -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 */