]> git.ipfire.org Git - thirdparty/lxc.git/commitdiff
utils: add uid, gid, group convenience wrappers
authorChristian Brauner <christian.brauner@ubuntu.com>
Mon, 2 Jan 2017 14:12:10 +0000 (15:12 +0100)
committerChristian Brauner <christian.brauner@ubuntu.com>
Sat, 7 Jan 2017 10:18:19 +0000 (11:18 +0100)
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>
src/lxc/utils.c
src/lxc/utils.h

index 2a0f05a55806c43778c444af0ed34e27682426ca..0227c3267554c704dfd598596143781bea487866 100644 (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;
+}
index b7dcd5d92d0951a0142c0cacf31fafe1124987ec..2b56905cb99e0beabdb076455649ea254c7dd923 100644 (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 */