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: 's avatarChristian Brauner <christian.brauner@ubuntu.com>
parent 4484e6f8
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
#include <dirent.h> #include <dirent.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <grp.h>
#include <libgen.h> #include <libgen.h>
#include <stddef.h> #include <stddef.h>
#include <stdio.h> #include <stdio.h>
...@@ -2053,3 +2054,32 @@ int lxc_safe_long(const char *numstr, long int *converted) ...@@ -2053,3 +2054,32 @@ int lxc_safe_long(const char *numstr, long int *converted)
*converted = sli; *converted = sli;
return 0; 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;
}
...@@ -327,4 +327,8 @@ int lxc_safe_uint(const char *numstr, unsigned int *converted); ...@@ -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_int(const char *numstr, int *converted);
int lxc_safe_long(const char *numstr, long 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 */ #endif /* __LXC_UTILS_H */
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment