[systemd-devel] [PATCH 1/2] Add detect_userns to detect uid/gid shifts

Stéphane Graber stgraber at ubuntu.com
Thu Jan 8 11:27:35 PST 2015


This adds a new detect_userns function in virt.c which will check
whether systemd is running in the host user namespace (single map of all
available uids and gids) or is using a uid/gid map.

The check makes sure that uid_map and gid_map are both exactly equal to
the default host map (assuming 32bit uid_t) for a process running in the
host namespace.
---
 src/shared/virt.c | 22 ++++++++++++++++++++++
 src/shared/virt.h |  1 +
 2 files changed, 23 insertions(+)

diff --git a/src/shared/virt.c b/src/shared/virt.c
index f10baab..3d94e1f 100644
--- a/src/shared/virt.c
+++ b/src/shared/virt.c
@@ -363,3 +363,25 @@ int detect_virtualization(const char **id) {
 
         return VIRTUALIZATION_NONE;
 }
+
+/* Detect whether we run in a uid/gid shifted namespace */
+int detect_userns(void) {
+        int r;
+        static const char host_id_map[] = "         0          0 4294967295";
+        char *uid_map = NULL;
+        char *gid_map = NULL;
+
+        /* Check if we are uid-shifted */
+        r = read_one_line_file("/proc/self/uid_map", &uid_map);
+        if (r == 0 && !streq(uid_map, host_id_map))
+                return 1;
+
+        /* Check if we are gid-shifted */
+        r = read_one_line_file("/proc/self/gid_map", &gid_map);
+        if (r == 0 && !streq(gid_map, host_id_map))
+                return 1;
+
+        /* If both uid_map and gid_map don't exist or if they both match
+         * the full uid/gid range, then we're not inside a user namespace */
+        return 0;
+}
diff --git a/src/shared/virt.h b/src/shared/virt.h
index 7194ab2..e19c7e8 100644
--- a/src/shared/virt.h
+++ b/src/shared/virt.h
@@ -33,3 +33,4 @@ enum {
 };
 
 int detect_virtualization(const char **id);
+int detect_userns(void);
-- 
1.9.1



More information about the systemd-devel mailing list