| 1 | package userns |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "sync" |
| 8 | ) |
| 9 | |
| 10 | var inUserNS = sync.OnceValue(runningInUserNS) |
| 11 | |
| 12 | // runningInUserNS detects whether we are currently running in a user namespace. |
| 13 | // |
| 14 | // This code was migrated from [libcontainer/runc] and based on an implementation |
| 15 | // from [lcx/incus]. |
| 16 | // |
| 17 | // [libcontainer/runc]: https://github.com/opencontainers/runc/blob/3778ae603c706494fd1e2c2faf83b406e38d687d/libcontainer/userns/userns_linux.go#L12-L49 |
| 18 | // [lcx/incus]: https://github.com/lxc/incus/blob/e45085dd42f826b3c8c3228e9733c0b6f998eafe/shared/util.go#L678-L700 |
| 19 | func runningInUserNS() bool { |
| 20 | file, err := os.Open("/proc/self/uid_map") |
| 21 | if err != nil { |
| 22 | // This kernel-provided file only exists if user namespaces are supported. |
| 23 | return false |
| 24 | } |
| 25 | defer file.Close() |
| 26 | |
| 27 | buf := bufio.NewReader(file) |
| 28 | l, _, err := buf.ReadLine() |
| 29 | if err != nil { |
| 30 | return false |
| 31 | } |
| 32 | |
| 33 | return uidMapInUserNS(string(l)) |
| 34 | } |
| 35 | |
| 36 | func uidMapInUserNS(uidMap string) bool { |
| 37 | if uidMap == "" { |
| 38 | // File exist but empty (the initial state when userns is created, |
| 39 | // see user_namespaces(7)). |
| 40 | return true |
| 41 | } |
| 42 | |
| 43 | var a, b, c int64 |
| 44 | if _, err := fmt.Sscanf(uidMap, "%d %d %d", &a, &b, &c); err != nil { |
| 45 | // Assume we are in a regular, non user namespace. |
| 46 | return false |
| 47 | } |
| 48 | |
| 49 | // As per user_namespaces(7), /proc/self/uid_map of |
| 50 | // the initial user namespace shows 0 0 4294967295. |
| 51 | initNS := a == 0 && b == 0 && c == 4294967295 |
| 52 | return !initNS |
| 53 | } |