| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/10/26 21:06 | flow | patch-triage |
3mArgs:null Results: {
"EnableConfigs": [
"USER_NS"
],
"FocusSymbols": [
"cap_setfcap_level",
"cred_setfcap_reaches",
"cred_may_setfcap_userns",
"cap_convert_nscap",
"cap_ptrace_access_check",
"cap_ptrace_traceme",
"create_user_ns",
"proc_uid_map_write"
],
"KMSANReasoning": "The patch series tightens capability checks related to CAP_SETFCAP in nested user namespaces, ptrace access checks, and file capability conversions on idmapped/non-idmapped mounts.\n\nAnalysis of memory initialization and safety:\n1. Struct user_namespace changes: Replaced the 'parent_could_setfcap' boolean field with 'setfcap_level' integer. Struct user_namespace is allocated with kmem_cache_zalloc (fully zeroed) and explicitly initialized in create_user_ns() as well as statically initialized to 0 for init_user_ns. Furthermore, struct user_namespace is internal kernel state and never copied to user space.\n2. Local variables and control flow: In all newly introduced helper functions (map_has_id, map_root_level, setfcap_top, cap_root_level, cap_setfcap_level, cred_setfcap_reaches, cred_may_setfcap_userns, cap_covers_setfcap), all local variables and function parameters are fully initialized before use.\n3. User copying / info-leaks: No data structures, buffers, or padding bytes are exposed or copied to userspace.\n4. Existing buffers / bounds checks: uid_gid_map structures processed in map_has_id and map_root_level are cleared via memset prior to extent population in map_write().\n\nAny potential issues arising from this patch would involve logical authorization bugs, permission checks, or potential pointer dereferences, which fall under logic testing or standard KASAN bug detectors rather than uninitialized memory detection. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false,
"Reasoning": "The patch refactors and extends how CAP_SETFCAP is tracked and checked across nested user namespaces. Instead of a single boolean `parent_could_setfcap`, it introduces hierarchical level tracking (`setfcap_level`) and enforces capability bounds across `setns` (`userns_install`), ptrace access (`cap_ptrace_access_check`, `cap_ptrace_traceme`), idmap validation (`verify_root_map`, `map_root_level`, `map_has_id`), and xattr capability conversion (`cap_convert_nscap`). All of these modifications are in core user namespace and security capability subsystems and are reachable through standard syscalls (clone/unshare, ptrace, setns, setxattr, and /proc/pid/uid_map writes). Fuzzing is warranted to verify that nested namespace relationships, mapping checks, and capability boundaries do not introduce privilege bypasses, out-of-bounds access, or assertion failures.",
"WorthFuzzing": true
} |
| 1/1 | 2026/10/26 21:06 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 543756ccee5549bf199f9931395f781384962df6\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Mon Oct 26 21:06:57 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/include/linux/capability.h b/include/linux/capability.h\nindex 622137f66f0928..e4199b03668bdc 100644\n--- a/include/linux/capability.h\n+++ b/include/linux/capability.h\n@@ -34,6 +34,7 @@ struct cpu_vfs_cap_data {\n #define _USER_CAP_HEADER_SIZE (sizeof(struct __user_cap_header_struct))\n #define _KERNEL_CAP_T_SIZE (sizeof(kernel_cap_t))\n \n+struct cred;\n struct file;\n struct inode;\n struct dentry;\n@@ -222,4 +223,9 @@ int get_vfs_caps_from_disk(const struct mnt_idmap *idmap,\n int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n \t\t const void **ivalue, size_t size);\n \n+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns);\n+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n+\t\t\t int level);\n+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns);\n+\n #endif /* !_LINUX_CAPABILITY_H */\ndiff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h\nindex 91232053775d8d..f3753b6b6d29f7 100644\n--- a/include/linux/user_namespace.h\n+++ b/include/linux/user_namespace.h\n@@ -86,9 +86,10 @@ struct user_namespace {\n \tkgid_t\t\t\tgroup;\n \tstruct ns_common\tns;\n \tunsigned long\t\tflags;\n-\t/* parent_could_setfcap: true if the creator if this ns had CAP_SETFCAP\n-\t * in its effective capability set at the child ns creation time. */\n-\tbool\t\t\tparent_could_setfcap;\n+\t/* setfcap_level: CAP_SETFCAP held in this ns counts here and in the\n+\t * ancestors up to the one at this -\u003elevel, see cap_setfcap_level().\n+\t */\n+\tint\t\t\tsetfcap_level;\n \n #ifdef CONFIG_KEYS\n \t/* List of joinable keyrings in this namespace. Modification access of\ndiff --git a/kernel/user_namespace.c b/kernel/user_namespace.c\nindex 50c374ed4687be..db078dd6406aa8 100644\n--- a/kernel/user_namespace.c\n+++ b/kernel/user_namespace.c\n@@ -125,7 +125,7 @@ int create_user_ns(struct cred *new)\n \tif (!ns)\n \t\tgoto fail_dec;\n \n-\tns-\u003eparent_could_setfcap = cap_raised(new-\u003ecap_effective, CAP_SETFCAP);\n+\tns-\u003esetfcap_level = cap_setfcap_level(new, parent_ns);\n \n \tret = ns_common_init(ns);\n \tif (ret)\n@@ -881,15 +881,55 @@ VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map)\n }\n EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort);\n \n+static bool map_has_id(struct uid_gid_map *map, u32 id)\n+{\n+\tstruct uid_gid_extent *extent;\n+\tint idx;\n+\n+\tfor (idx = 0; idx \u003c map-\u003enr_extents; idx++) {\n+\t\tif (map-\u003enr_extents \u003c= UID_GID_MAP_MAX_BASE_EXTENTS)\n+\t\t\textent = \u0026map-\u003eextent[idx];\n+\t\telse\n+\t\t\textent = \u0026map-\u003eforward[idx];\n+\t\tif (id \u003e= extent-\u003elower_first \u0026\u0026\n+\t\t id - extent-\u003elower_first \u003c extent-\u003ecount)\n+\t\t\treturn true;\n+\t}\n+\n+\treturn false;\n+}\n+\n+/*\n+ * The lowest -\u003elevel among @parent and its ancestors whose root user @new_map\n+ * maps, whatever uid that root user has in @parent; INT_MAX if there is none.\n+ */\n+static int map_root_level(struct user_namespace *parent,\n+\t\t\t struct uid_gid_map *new_map)\n+{\n+\tstruct user_namespace *p;\n+\tint level = INT_MAX;\n+\tuid_t id;\n+\n+\tfor (p = parent; p; p = p-\u003eparent) {\n+\t\tid = from_kuid(parent, make_kuid(p, 0));\n+\t\tif (id != (uid_t)-1 \u0026\u0026 map_has_id(new_map, id))\n+\t\t\tlevel = p-\u003elevel;\n+\t}\n+\n+\treturn level;\n+}\n+\n /**\n * verify_root_map() - check the uid 0 mapping\n * @file: idmapping file\n * @map_ns: user namespace of the target process\n * @new_map: requested idmap\n *\n- * If a process requests mapping parent uid 0 into the new ns, verify that the\n- * process writing the map had the CAP_SETFCAP capability as the target process\n- * will be able to write fscaps that are valid in ancestor user namespaces.\n+ * If a process requests mapping the root user of the parent ns, or of one of\n+ * its ancestors, into the new ns, verify that the process that opened the map\n+ * file and the process writing the map had the CAP_SETFCAP capability as the\n+ * target process will be able to write fscaps that are valid in ancestor user\n+ * namespaces.\n *\n * Return: true if the mapping is allowed, false if not.\n */\n@@ -897,42 +937,43 @@ static bool verify_root_map(const struct file *file,\n \t\t\t struct user_namespace *map_ns,\n \t\t\t struct uid_gid_map *new_map)\n {\n-\tint idx;\n \tconst struct user_namespace *file_ns = file-\u003ef_cred-\u003euser_ns;\n-\tstruct uid_gid_extent *extent0 = NULL;\n-\n-\tfor (idx = 0; idx \u003c new_map-\u003enr_extents; idx++) {\n-\t\tif (new_map-\u003enr_extents \u003c= UID_GID_MAP_MAX_BASE_EXTENTS)\n-\t\t\textent0 = \u0026new_map-\u003eextent[idx];\n-\t\telse\n-\t\t\textent0 = \u0026new_map-\u003eforward[idx];\n-\t\tif (extent0-\u003elower_first == 0)\n-\t\t\tbreak;\n+\tint level;\n \n-\t\textent0 = NULL;\n-\t}\n-\n-\tif (!extent0)\n+\tlevel = map_root_level(map_ns-\u003eparent, new_map);\n+\tif (level == INT_MAX)\n \t\treturn true;\n \n \tif (map_ns == file_ns) {\n \t\t/* The process unshared its ns and is writing to its own\n \t\t * /proc/self/uid_map. User already has full capabilites in\n-\t\t * the new namespace. Verify that the parent had CAP_SETFCAP\n-\t\t * when it unshared.\n+\t\t * the new namespace. Verify that it still has CAP_SETFCAP\n+\t\t * there, and that the parent had it when it unshared, as far up\n+\t\t * as those root users go.\n \t\t * */\n-\t\tif (!file_ns-\u003eparent_could_setfcap)\n+\t\tif (!file_ns_capable(file, map_ns, CAP_SETFCAP) ||\n+\t\t file_ns-\u003esetfcap_level \u003e level)\n \t\t\treturn false;\n \t} else {\n \t\t/* Process p1 is writing to uid_map of p2, who is in a child\n \t\t * user namespace to p1's. Verify that the opener of the map\n \t\t * file has CAP_SETFCAP against the parent of the new map\n-\t\t * namespace */\n-\t\tif (!file_ns_capable(file, map_ns-\u003eparent, CAP_SETFCAP))\n+\t\t * namespace, and as far up as those root users go.\n+\t\t */\n+\t\tif (!file_ns_capable(file, map_ns-\u003eparent, CAP_SETFCAP) ||\n+\t\t !cred_setfcap_reaches(file-\u003ef_cred, map_ns-\u003eparent, level))\n \t\t\treturn false;\n \t}\n \n-\treturn true;\n+\t/* The file may have been handed to someone else since it was opened,\n+\t * so the same goes for the process that is doing the write.\n+\t */\n+\tif (map_ns == current_user_ns())\n+\t\treturn ns_capable(map_ns, CAP_SETFCAP) \u0026\u0026\n+\t\t map_ns-\u003esetfcap_level \u003c= level;\n+\n+\treturn ns_capable(map_ns-\u003eparent, CAP_SETFCAP) \u0026\u0026\n+\t cred_setfcap_reaches(current_cred(), map_ns-\u003eparent, level);\n }\n \n /*\n@@ -1390,6 +1431,12 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)\n \tif (!ns_capable(user_ns, CAP_SYS_ADMIN))\n \t\treturn -EPERM;\n \n+\t/* Tasks in the namespace may have CAP_SETFCAP that counts outside of\n+\t * it, so only let in tasks whose own counts as far.\n+\t */\n+\tif (!cred_may_setfcap_userns(current_cred(), user_ns))\n+\t\treturn -EPERM;\n+\n \tcred = nsset_cred(nsset);\n \tif (!cred)\n \t\treturn -EINVAL;\ndiff --git a/security/commoncap.c b/security/commoncap.c\nindex d47ab30223435b..91ed4a5f4b2503 100644\n--- a/security/commoncap.c\n+++ b/security/commoncap.c\n@@ -131,6 +131,114 @@ int cap_capable(const struct cred *cred, struct user_namespace *target_ns,\n \treturn ret;\n }\n \n+/**\n+ * cap_setfcap_level - Determine how far up CAP_SETFCAP of a cred reaches\n+ * @cred: The credentials to use\n+ * @ns: The user namespace to look from\n+ *\n+ * File capabilities belong to the kuid of a namespace's root user, and the\n+ * same kuid can be the root user of ancestors of that namespace. Every task\n+ * gets CAP_SETFCAP when it enters a user namespace, so having it there says\n+ * nothing about those ancestors. user_ns-\u003esetfcap_level does: it is taken\n+ * from the creator when the namespace is created.\n+ *\n+ * Return: the -\u003elevel of the topmost namespace, from @ns upwards, for which\n+ * CAP_SETFCAP of @cred counts; @ns-\u003elevel + 1 if it doesn't even count over\n+ * @ns, which includes an @ns that isn't @cred's namespace or a descendant.\n+ */\n+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)\n+{\n+\tif (cap_capable(cred, ns, CAP_SETFCAP, CAP_OPT_NOAUDIT) != 0)\n+\t\treturn ns-\u003elevel + 1;\n+\n+\tif (cap_raised(cred-\u003ecap_effective, CAP_SETFCAP))\n+\t\treturn cred-\u003euser_ns-\u003esetfcap_level;\n+\n+\t/* All we have is that we own a child of our namespace. */\n+\treturn cred-\u003euser_ns-\u003elevel + 1;\n+}\n+\n+/**\n+ * cred_setfcap_reaches - Check how far up CAP_SETFCAP of a cred reaches\n+ * @cred: The credentials to use\n+ * @ns: The user namespace to look from\n+ * @level: The -\u003elevel of the ancestor of @ns it has to count in\n+ *\n+ * Return: true if CAP_SETFCAP of @cred counts in @ns and in its ancestors\n+ * up to the one at @level.\n+ */\n+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n+\t\t\t int level)\n+{\n+\treturn cap_setfcap_level(cred, ns) \u003c= level;\n+}\n+\n+/*\n+ * The topmost ancestor of @ns whose root user tasks in @ns can write file\n+ * capabilities for: within @ns-\u003esetfcap_level, and mapped into @ns, or into\n+ * its parent while @ns has no uid_map yet. NULL if there is none. An\n+ * idmapped mount can store other root users, but that is up to whoever sets\n+ * up the mount.\n+ */\n+static struct user_namespace *setfcap_top(struct user_namespace *ns)\n+{\n+\tstruct user_namespace *seen, *p, *top = NULL;\n+\n+\tif (ns-\u003esetfcap_level \u003e= ns-\u003elevel)\n+\t\treturn NULL;\n+\n+\tseen = READ_ONCE(ns-\u003euid_map.nr_extents) ? ns : ns-\u003eparent;\n+\tfor (p = ns-\u003eparent; p; p = p-\u003eparent) {\n+\t\tif (p-\u003elevel \u003c ns-\u003esetfcap_level)\n+\t\t\tbreak;\n+\t\tif (kuid_has_mapping(seen, make_kuid(p, 0)))\n+\t\t\ttop = p;\n+\t}\n+\n+\treturn top;\n+}\n+\n+/**\n+ * cred_may_setfcap_userns - Check whether a cred covers what a userns can do\n+ * @cred: The credentials to use\n+ * @ns: The user namespace\n+ *\n+ * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see\n+ * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as\n+ * tasks in @ns can make use of theirs.\n+ *\n+ * Return: true if it does.\n+ */\n+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns)\n+{\n+\tstruct user_namespace *top = setfcap_top(ns);\n+\n+\treturn !top || cred_setfcap_reaches(cred, ns-\u003eparent, top-\u003elevel);\n+}\n+\n+/**\n+ * cap_root_level - Find the topmost namespace in which a kuid is the root user\n+ * @kuid: The kuid to look for\n+ * @ns: The user namespace to start from\n+ *\n+ * Return: the lowest -\u003elevel among @ns and its ancestors in which @kuid is\n+ * uid 0, which is how far up file capabilities with that root user are\n+ * honoured; INT_MAX if there is no such namespace.\n+ */\n+static int cap_root_level(kuid_t kuid, struct user_namespace *ns)\n+{\n+\tint level = INT_MAX;\n+\n+\tfor (;; ns = ns-\u003eparent) {\n+\t\tif (from_kuid(ns, kuid) == 0)\n+\t\t\tlevel = ns-\u003elevel;\n+\t\tif (ns == \u0026init_user_ns)\n+\t\t\tbreak;\n+\t}\n+\n+\treturn level;\n+}\n+\n /**\n * cap_settime - Determine whether the current process may set the system clock\n * @ts: The time to set\n@@ -146,14 +254,41 @@ int cap_settime(const struct timespec64 *ts, const struct timezone *tz)\n \treturn 0;\n }\n \n+/*\n+ * Tasks in a user namespace have CAP_SETFCAP that can count in ancestors of\n+ * the namespace, see cap_setfcap_level(). That is a privilege outside of the\n+ * namespace, so capabilities over the namespace are not enough to take\n+ * control of such a task.\n+ */\n+static bool cap_covers_setfcap(const struct cred *cred,\n+\t\t\t const struct cred *child_cred)\n+{\n+\tstruct user_namespace *ns = child_cred-\u003euser_ns, *top;\n+\n+\t/* setns() only lets in tasks whose CAP_SETFCAP reaches as far. */\n+\tif (cred-\u003euser_ns == ns)\n+\t\treturn true;\n+\n+\ttop = setfcap_top(ns);\n+\tif (!top)\n+\t\treturn true;\n+\n+\t/* CAP_SYS_PTRACE up there gives control of tasks with CAP_SETFCAP. */\n+\treturn cred_setfcap_reaches(cred, ns-\u003eparent, top-\u003elevel) ||\n+\t !cap_capable(cred, top, CAP_SYS_PTRACE, CAP_OPT_NOAUDIT);\n+}\n+\n /**\n * cap_ptrace_access_check - Determine whether the current process may access\n *\t\t\t another\n * @child: The process to be accessed\n * @mode: The mode of attachment.\n *\n- * If we are in the same or an ancestor user_ns and have all the target\n- * task's capabilities, then ptrace access is allowed.\n+ * For PTRACE_MODE_ATTACH, if the target task may make use of CAP_SETFCAP in\n+ * an ancestor of its user_ns that our CAP_SETFCAP or CAP_SYS_PTRACE doesn't\n+ * reach, then ptrace access is denied.\n+ * Otherwise, if we are in the same or an ancestor user_ns and have all the\n+ * target task's capabilities, then ptrace access is allowed.\n * If we have the ptrace capability to the target user_ns, then ptrace\n * access is allowed.\n * Else denied.\n@@ -174,11 +309,15 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)\n \t\tcaller_caps = \u0026cred-\u003ecap_effective;\n \telse\n \t\tcaller_caps = \u0026cred-\u003ecap_permitted;\n+\tif ((mode \u0026 PTRACE_MODE_ATTACH) \u0026\u0026\n+\t !cap_covers_setfcap(cred, child_cred))\n+\t\tgoto deny;\n \tif (cred-\u003euser_ns == child_cred-\u003euser_ns \u0026\u0026\n \t cap_issubset(child_cred-\u003ecap_permitted, *caller_caps))\n \t\tgoto out;\n \tif (ns_capable(child_cred-\u003euser_ns, CAP_SYS_PTRACE))\n \t\tgoto out;\n+deny:\n \tret = -EPERM;\n out:\n \trcu_read_unlock();\n@@ -189,8 +328,11 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)\n * cap_ptrace_traceme - Determine whether another process may trace the current\n * @parent: The task proposed to be the tracer\n *\n- * If parent is in the same or an ancestor user_ns and has all current's\n- * capabilities, then ptrace access is allowed.\n+ * If current may make use of CAP_SETFCAP in an ancestor of its user_ns that\n+ * parent's CAP_SETFCAP or CAP_SYS_PTRACE doesn't reach, then ptrace access\n+ * is denied.\n+ * Otherwise, if parent is in the same or an ancestor user_ns and has all\n+ * current's capabilities, then ptrace access is allowed.\n * If parent has the ptrace capability to current's user_ns, then ptrace\n * access is allowed.\n * Else denied.\n@@ -206,11 +348,14 @@ int cap_ptrace_traceme(struct task_struct *parent)\n \trcu_read_lock();\n \tcred = __task_cred(parent);\n \tchild_cred = current_cred();\n+\tif (!cap_covers_setfcap(cred, child_cred))\n+\t\tgoto deny;\n \tif (cred-\u003euser_ns == child_cred-\u003euser_ns \u0026\u0026\n \t cap_issubset(child_cred-\u003ecap_permitted, cred-\u003ecap_permitted))\n \t\tgoto out;\n \tif (has_ns_capability(parent, child_cred-\u003euser_ns, CAP_SYS_PTRACE))\n \t\tgoto out;\n+deny:\n \tret = -EPERM;\n out:\n \trcu_read_unlock();\n@@ -586,19 +731,46 @@ int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n \t\treturn -EINVAL;\n \tif (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))\n \t\treturn -EPERM;\n-\tif (size == XATTR_CAPS_SZ_2 \u0026\u0026 (idmap == \u0026nop_mnt_idmap))\n-\t\tif (ns_capable(inode-\u003ei_sb-\u003es_user_ns, CAP_SETFCAP))\n+\t/*\n+\t * A v2 xattr belongs to the root user of the filesystem's namespace,\n+\t * which may be the root user of ancestors of our namespace as well.\n+\t * There may be none, then nobody could ever run the file with these\n+\t * capabilities. Only write it unconverted if that root user is\n+\t * within reach, the checks below handle everything else.\n+\t */\n+\tif (size == XATTR_CAPS_SZ_2 \u0026\u0026 idmap == \u0026nop_mnt_idmap \u0026\u0026\n+\t ns_capable(fs_ns, CAP_SETFCAP)) {\n+\t\tkuid_t fsroot = make_kuid(fs_ns, 0);\n+\n+\t\tif (!uid_valid(fsroot))\n+\t\t\treturn -EINVAL;\n+\t\tif (cap_root_level(fsroot, task_ns) \u003e= task_ns-\u003esetfcap_level)\n \t\t\t/* user is privileged, just write the v2 */\n \t\t\treturn size;\n+\t}\n \n \tvfsrootid = rootid_from_xattr(*ivalue, size, task_ns);\n \tif (!vfsuid_valid(vfsrootid))\n \t\treturn -EINVAL;\n \n+\t/*\n+\t * The root user may be the root user of ancestors of our namespace as\n+\t * well. CAP_SETFCAP that we got for entering it doesn't cover those.\n+\t * On an idmapped mount the root user is vfsrootid as seen through\n+\t * this mount and rootid as seen through every other mount of the\n+\t * filesystem, so both have to stay within reach.\n+\t */\n+\tif (cap_root_level(vfsuid_into_kuid(vfsrootid), task_ns) \u003c\n+\t task_ns-\u003esetfcap_level)\n+\t\treturn -EPERM;\n+\n \trootid = from_vfsuid(idmap, fs_ns, vfsrootid);\n \tif (!uid_valid(rootid))\n \t\treturn -EINVAL;\n \n+\tif (cap_root_level(rootid, task_ns) \u003c task_ns-\u003esetfcap_level)\n+\t\treturn -EPERM;\n+\n \tnsrootid = from_kuid(fs_ns, rootid);\n \tif (nsrootid == -1)\n \t\treturn -EINVAL;\ndiff --git a/tools/testing/selftests/namespaces/Makefile b/tools/testing/selftests/namespaces/Makefile\nindex 9b22d12708e1aa..0455b6544869d1 100644\n--- a/tools/testing/selftests/namespaces/Makefile\n+++ b/tools/testing/selftests/namespaces/Makefile\n@@ -14,7 +14,8 @@ TEST_GEN_PROGS := nsid_test \\\n \t\t stress_test \\\n \t\t listns_pagination_bug \\\n \t\t regression_pidfd_setns_test \\\n-\t\t uid_map_range_test\n+\t\t uid_map_range_test \\\n+\t\t setfcap_test\n \n include ../lib.mk\n \ndiff --git a/tools/testing/selftests/namespaces/config b/tools/testing/selftests/namespaces/config\nindex d09836260262f4..dfbabc35cd8a12 100644\n--- a/tools/testing/selftests/namespaces/config\n+++ b/tools/testing/selftests/namespaces/config\n@@ -5,3 +5,6 @@ CONFIG_USER_NS=y\n CONFIG_PID_NS=y\n CONFIG_NET_NS=y\n CONFIG_CGROUPS=y\n+CONFIG_TMPFS=y\n+CONFIG_TMPFS_XATTR=y\n+CONFIG_KEYS=y\ndiff --git a/tools/testing/selftests/namespaces/setfcap_test.c b/tools/testing/selftests/namespaces/setfcap_test.c\nnew file mode 100644\nindex 00000000000000..0a82b239b36856\n--- /dev/null\n+++ b/tools/testing/selftests/namespaces/setfcap_test.c\n@@ -0,0 +1,1362 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Who may map the root user of an ancestor user namespace, write file\n+ * capabilities that are honoured in an ancestor, join a namespace whose\n+ * tasks may do so, or take control of such a task.\n+ *\n+ * \"R\" is a task with uid 0 and all capabilities in the initial namespace,\n+ * \"X\" one with uid 0 that gave up CAP_SETFCAP and CAP_SYS_PTRACE in its\n+ * permitted, effective and bounding sets, and \"U\" is uid 1000.\n+ *\n+ * Every test runs in a private mount namespace with a tmpfs on /tmp.\n+ */\n+#define _GNU_SOURCE\n+#include \u003cendian.h\u003e\n+#include \u003cerrno.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003csched.h\u003e\n+#include \u003csignal.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \u003csys/mount.h\u003e\n+#include \u003csys/prctl.h\u003e\n+#include \u003csys/ptrace.h\u003e\n+#include \u003csys/stat.h\u003e\n+#include \u003csys/syscall.h\u003e\n+#include \u003csys/wait.h\u003e\n+#include \u003csys/xattr.h\u003e\n+#include \u003clinux/capability.h\u003e\n+#include \u003clinux/keyctl.h\u003e\n+#include \u003clinux/mount.h\u003e\n+\n+#include \"kselftest_harness.h\"\n+\n+#ifndef __NR_pidfd_open\n+#define __NR_pidfd_open 434\n+#endif\n+#ifndef __NR_pidfd_getfd\n+#define __NR_pidfd_getfd 438\n+#endif\n+#ifndef __NR_open_tree\n+#define __NR_open_tree 428\n+#endif\n+#ifndef __NR_move_mount\n+#define __NR_move_mount 429\n+#endif\n+#ifndef __NR_mount_setattr\n+#define __NR_mount_setattr 442\n+#endif\n+\n+/* Exit codes of a copy of this program run with SETFCAP_TEST_CAPS set. */\n+#define CAPS_HAS_SYS_ADMIN\t42\n+#define CAPS_NO_SYS_ADMIN\t43\n+\n+/* A step that wasn't the one under test went wrong. */\n+#define SETUP_ERROR\t\t(-1000)\n+\n+static int capget_v3(struct __user_cap_data_struct d[2])\n+{\n+\tstruct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };\n+\n+\treturn syscall(SYS_capget, \u0026h, d);\n+}\n+\n+__attribute__((constructor)) static void report_caps(void)\n+{\n+\tstruct __user_cap_data_struct d[2];\n+\n+\tif (!getenv(\"SETFCAP_TEST_CAPS\"))\n+\t\treturn;\n+\tif (capget_v3(d))\n+\t\t_exit(1);\n+\t_exit(d[0].effective \u0026 (1u \u003c\u003c CAP_SYS_ADMIN) ?\n+\t CAPS_HAS_SYS_ADMIN : CAPS_NO_SYS_ADMIN);\n+}\n+\n+/* X: uid 0 without CAP_SETFCAP and CAP_SYS_PTRACE */\n+static void restrict_root(void)\n+{\n+\tstruct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };\n+\tstruct __user_cap_data_struct d[2];\n+\tunsigned int drop = (1u \u003c\u003c CAP_SETFCAP) | (1u \u003c\u003c CAP_SYS_PTRACE);\n+\n+\tif (prctl(PR_CAPBSET_DROP, CAP_SETFCAP) ||\n+\t prctl(PR_CAPBSET_DROP, CAP_SYS_PTRACE) || capget_v3(d))\n+\t\t_exit(99);\n+\td[0].effective \u0026= ~drop;\n+\td[0].permitted \u0026= ~drop;\n+\tif (syscall(SYS_capset, \u0026h, d))\n+\t\t_exit(99);\n+}\n+\n+/* Give up CAP_SETFCAP only in the permitted and effective set. */\n+static void drop_setfcap_keep_bset(void)\n+{\n+\tstruct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };\n+\tstruct __user_cap_data_struct d[2];\n+\n+\tif (capget_v3(d))\n+\t\t_exit(99);\n+\td[0].effective \u0026= ~(1u \u003c\u003c CAP_SETFCAP);\n+\td[0].permitted \u0026= ~(1u \u003c\u003c CAP_SETFCAP);\n+\tif (syscall(SYS_capset, \u0026h, d))\n+\t\t_exit(99);\n+}\n+\n+static void become_user(void)\n+{\n+\tif (setresgid(1000, 1000, 1000) || setresuid(1000, 1000, 1000))\n+\t\t_exit(99);\n+\tprctl(PR_SET_DUMPABLE, 1);\n+}\n+\n+static long wr(int fd, const char *s)\n+{\n+\tlong r = write(fd, s, strlen(s));\n+\n+\treturn r \u003c 0 ? -errno : 0;\n+}\n+\n+static long write_file(int pid, const char *name, const char *s)\n+{\n+\tchar path[64];\n+\tlong r;\n+\tint fd;\n+\n+\tif (pid)\n+\t\tsnprintf(path, sizeof(path), \"/proc/%d/%s\", pid, name);\n+\telse\n+\t\tsnprintf(path, sizeof(path), \"/proc/self/%s\", name);\n+\tfd = open(path, O_WRONLY);\n+\tif (fd \u003c 0)\n+\t\treturn -errno;\n+\tr = wr(fd, s);\n+\tclose(fd);\n+\treturn r;\n+}\n+\n+static long write_map(int pid, const char *map)\n+{\n+\treturn write_file(pid, \"uid_map\", map);\n+}\n+\n+/* both maps, as the setup for a test rather than its subject */\n+static long map_both(int pid, const char *map)\n+{\n+\tif (write_map(pid, map) || write_file(pid, \"setgroups\", \"deny\") ||\n+\t write_file(pid, \"gid_map\", map))\n+\t\treturn SETUP_ERROR;\n+\treturn 0;\n+}\n+\n+/* what an unprivileged user does after unshare(CLONE_NEWUSER) */\n+static long map_user(void)\n+{\n+\treturn map_both(0, \"0 1000 1\\n\");\n+}\n+\n+static long join(int pid)\n+{\n+\tchar path[64];\n+\tint fd, r;\n+\n+\tsnprintf(path, sizeof(path), \"/proc/%d/ns/user\", pid);\n+\tfd = open(path, O_RDONLY);\n+\tif (fd \u003c 0)\n+\t\treturn SETUP_ERROR;\n+\tr = setns(fd, CLONE_NEWUSER);\n+\tclose(fd);\n+\treturn r ? -errno : 0;\n+}\n+\n+/* security.capability with CAP_SYS_ADMIN in permitted and effective; v2 if rootid \u003c 0 */\n+static long set_fcap(const char *path, int rootid)\n+{\n+\tstruct vfs_ns_cap_data d;\n+\tint v3 = rootid \u003e= 0;\n+\n+\tmemset(\u0026d, 0, sizeof(d));\n+\td.magic_etc = htole32((v3 ? VFS_CAP_REVISION_3 : VFS_CAP_REVISION_2) |\n+\t\t\t VFS_CAP_FLAGS_EFFECTIVE);\n+\td.data[0].permitted = htole32(1u \u003c\u003c CAP_SYS_ADMIN);\n+\td.rootid = htole32(rootid);\n+\tif (setxattr(path, \"security.capability\", \u0026d,\n+\t\t v3 ? XATTR_CAPS_SZ_3 : XATTR_CAPS_SZ_2, 0))\n+\t\treturn -errno;\n+\treturn 0;\n+}\n+\n+/* a copy of this program, owned by uid */\n+static int new_file(const char *path, int uid)\n+{\n+\tchar buf[65536];\n+\tint in, out;\n+\tssize_t n;\n+\n+\tunlink(path);\n+\tin = open(\"/proc/self/exe\", O_RDONLY);\n+\tout = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0755);\n+\tif (in \u003c 0 || out \u003c 0)\n+\t\treturn -1;\n+\twhile ((n = read(in, buf, sizeof(buf))) \u003e 0)\n+\t\tif (write(out, buf, n) != n)\n+\t\t\treturn -1;\n+\tif (fchown(out, uid, uid) || fchmod(out, 0755))\n+\t\treturn -1;\n+\tclose(in);\n+\tclose(out);\n+\treturn 0;\n+}\n+\n+/* Does U get CAP_SYS_ADMIN from the file capabilities of path? */\n+static int user_gets_sys_admin(const char *path)\n+{\n+\tint pid, st;\n+\n+\tpid = fork();\n+\tif (!pid) {\n+\t\tbecome_user();\n+\t\tsetenv(\"SETFCAP_TEST_CAPS\", \"1\", 1);\n+\t\texecl(path, path, NULL);\n+\t\t_exit(1);\n+\t}\n+\twaitpid(pid, \u0026st, 0);\n+\treturn WIFEXITED(st) \u0026\u0026 WEXITSTATUS(st) == CAPS_HAS_SYS_ADMIN;\n+}\n+\n+/* run fn in a child and return what it returns */\n+static long in_child(long (*fn)(void *), void *arg)\n+{\n+\tint p[2], pid;\n+\tlong r = SETUP_ERROR;\n+\n+\tif (pipe(p))\n+\t\treturn SETUP_ERROR;\n+\tpid = fork();\n+\tif (!pid) {\n+\t\tr = fn(arg);\n+\t\tif (write(p[1], \u0026r, sizeof(r)) != sizeof(r))\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tclose(p[1]);\n+\tif (read(p[0], \u0026r, sizeof(r)) != sizeof(r))\n+\t\tr = SETUP_ERROR;\n+\tclose(p[0]);\n+\twaitpid(pid, NULL, 0);\n+\treturn r;\n+}\n+\n+/* A task that unshares a user namespace and waits. */\n+struct holder {\n+\tint pid, go;\n+};\n+\n+enum holder_kind {\n+\tHOLDER_ROOT,\t\t/* R */\n+\tHOLDER_RESTRICTED,\t/* X */\n+\tHOLDER_USER,\t\t/* U, maps \"0 1000 1\" itself */\n+};\n+\n+static struct holder spawn_holder(enum holder_kind kind, int map_fd_at)\n+{\n+\tstruct holder h = { -1, -1 };\n+\tint ready[2], go[2];\n+\tchar c;\n+\n+\tif (pipe(ready) || pipe(go))\n+\t\treturn h;\n+\th.pid = fork();\n+\tif (!h.pid) {\n+\t\tclose(ready[0]);\n+\t\tclose(go[1]);\n+\t\tif (kind == HOLDER_RESTRICTED)\n+\t\t\trestrict_root();\n+\t\tif (kind == HOLDER_USER)\n+\t\t\tbecome_user();\n+\t\tif (unshare(CLONE_NEWUSER))\n+\t\t\t_exit(1);\n+\t\tif (kind == HOLDER_USER \u0026\u0026 map_user())\n+\t\t\t_exit(1);\n+\t\tif (map_fd_at)\n+\t\t\tdup2(open(\"/proc/self/uid_map\", O_WRONLY), map_fd_at);\n+\t\tif (write(ready[1], \"r\", 1) != 1)\n+\t\t\t_exit(1);\n+\t\tif (read(go[0], \u0026c, 1) \u003c 0)\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tclose(ready[1]);\n+\tclose(go[0]);\n+\tif (read(ready[0], \u0026c, 1) != 1)\n+\t\th.pid = -1;\n+\tclose(ready[0]);\n+\th.go = go[1];\n+\treturn h;\n+}\n+\n+/* ... whose maps are written from the parent namespace by the caller */\n+static struct holder spawn_mapped(enum holder_kind kind, const char *map)\n+{\n+\tstruct holder h = spawn_holder(kind, 0);\n+\n+\tif (h.pid \u003e 0 \u0026\u0026 map_both(h.pid, map))\n+\t\th.pid = -1;\n+\treturn h;\n+}\n+\n+static void reap_holder(struct holder h)\n+{\n+\tif (h.pid \u003c= 0)\n+\t\treturn;\n+\tclose(h.go);\n+\tkill(h.pid, SIGKILL);\n+\twaitpid(h.pid, NULL, 0);\n+}\n+\n+#define PID(a) (((struct holder *)(a))-\u003epid)\n+\n+static long attach_only(int pid)\n+{\n+\tif (ptrace(PTRACE_ATTACH, pid, 0, 0))\n+\t\treturn -errno;\n+\twaitpid(pid, NULL, 0);\n+\tptrace(PTRACE_DETACH, pid, 0, 0);\n+\treturn 0;\n+}\n+\n+/* /tmp idmapped with the user namespace of pid, at /mnt */\n+static int idmap_tmp(int pid)\n+{\n+\tstruct mount_attr attr = { .attr_set = MOUNT_ATTR_IDMAP };\n+\tchar path[64];\n+\tint tfd, nsfd;\n+\n+\tmkdir(\"/mnt\", 0755);\n+\tsnprintf(path, sizeof(path), \"/proc/%d/ns/user\", pid);\n+\tnsfd = open(path, O_RDONLY);\n+\ttfd = syscall(__NR_open_tree, AT_FDCWD, \"/tmp\",\n+\t\t OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);\n+\tif (nsfd \u003c 0 || tfd \u003c 0)\n+\t\treturn -1;\n+\tattr.userns_fd = nsfd;\n+\tif (syscall(__NR_mount_setattr, tfd, \"\", AT_EMPTY_PATH, \u0026attr,\n+\t\t sizeof(attr)))\n+\t\treturn -1;\n+\tif (syscall(__NR_move_mount, tfd, \"\", AT_FDCWD, \"/mnt\",\n+\t\t MOVE_MOUNT_F_EMPTY_PATH))\n+\t\treturn -1;\n+\tclose(tfd);\n+\tclose(nsfd);\n+\treturn 0;\n+}\n+\n+/* Each test: private mounts, a tmpfs on /tmp with copies of this program */\n+static void prepare(struct __test_metadata *_metadata)\n+{\n+\tASSERT_EQ(unshare(CLONE_NEWNS), 0);\n+\tASSERT_EQ(mount(NULL, \"/\", NULL, MS_REC | MS_PRIVATE, NULL), 0);\n+\tASSERT_EQ(mount(\"tmpfs\", \"/tmp\", \"tmpfs\", 0, \"mode=1777\"), 0);\n+\tASSERT_EQ(new_file(\"/tmp/x\", 0), 0);\n+\tASSERT_EQ(new_file(\"/tmp/u\", 1000), 0);\n+\tmkdir(\"/mnt\", 0755);\n+}\n+\n+FIXTURE(setfcap) {};\n+\n+FIXTURE_SETUP(setfcap)\n+{\n+\tif (geteuid())\n+\t\tSKIP(return, \"needs root\");\n+\tprepare(_metadata);\n+}\n+\n+FIXTURE_TEARDOWN(setfcap) {}\n+\n+/* ---------------------------------------------------------------------- */\n+/* Mapping uid 0 of the parent, or the root user of an ancestor at any uid */\n+\n+static long x_maps_from_parent(void *a)\n+{\n+\trestrict_root();\n+\treturn write_map(PID(a), \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_from_parent_without_setfcap)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_maps_from_parent, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+static long x_maps_own(void *a)\n+{\n+\trestrict_root();\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_own_without_setfcap)\n+{\n+\tEXPECT_EQ(in_child(x_maps_own, NULL), -EPERM);\n+}\n+\n+static long x_joins_and_maps(void *a)\n+{\n+\tlong r;\n+\n+\trestrict_root();\n+\tr = join(PID(a));\n+\tif (r)\n+\t\treturn r;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+/* X can't get into R's namespace to map uid 0 from inside */\n+TEST_F(setfcap, map_after_setns)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins_and_maps, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+static long x_writes_fd(void *a)\n+{\n+\trestrict_root();\n+\treturn wr(*(int *)a, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_through_borrowed_fd)\n+{\n+\tstruct holder h;\n+\tchar path[64];\n+\tint fd;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tsnprintf(path, sizeof(path), \"/proc/%d/uid_map\", h.pid);\n+\tfd = open(path, O_WRONLY);\n+\tASSERT_GE(fd, 0);\n+\tEXPECT_EQ(in_child(x_writes_fd, \u0026fd), -EPERM);\n+\tclose(fd);\n+\treap_holder(h);\n+}\n+\n+static long x_steals_fd(void *a)\n+{\n+\tint pfd, fd;\n+\n+\trestrict_root();\n+\tpfd = syscall(__NR_pidfd_open, PID(a), 0);\n+\tif (pfd \u003c 0)\n+\t\treturn SETUP_ERROR;\n+\tfd = syscall(__NR_pidfd_getfd, pfd, 100, 0);\n+\tif (fd \u003c 0)\n+\t\treturn -errno;\n+\treturn wr(fd, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_through_pidfd_getfd)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 100);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_steals_fd, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+/* the same one level down, among tasks of an unprivileged user */\n+static long u_nested(void *a)\n+{\n+\tstruct holder h;\n+\tlong r;\n+\n+\tbecome_user();\n+\tif (unshare(CLONE_NEWUSER) || map_user())\n+\t\treturn SETUP_ERROR;\n+\t/* R-like: full set in the user's namespace */\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tif (h.pid \u003c= 0)\n+\t\treturn SETUP_ERROR;\n+\tr = in_child(x_joins_and_maps, \u0026h);\n+\treap_holder(h);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, map_after_setns_nested_unprivileged)\n+{\n+\tEXPECT_EQ(in_child(u_nested, NULL), -EPERM);\n+}\n+\n+static long x_joins_unshares_maps(void *a)\n+{\n+\tlong r;\n+\n+\trestrict_root();\n+\tr = join(PID(a));\n+\tif (r)\n+\t\treturn r;\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_after_setns_and_unshare)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins_unshares_maps, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+/* the writer opened the map, then went into an unrelated namespace */\n+static long r_opens_then_leaves(void *a)\n+{\n+\tchar path[64];\n+\tint fd;\n+\n+\tsnprintf(path, sizeof(path), \"/proc/%d/uid_map\", PID(a));\n+\tfd = open(path, O_WRONLY);\n+\tif (fd \u003c 0)\n+\t\treturn SETUP_ERROR;\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\treturn wr(fd, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_writer_left_for_other_ns)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_opens_then_leaves, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+/*\n+ * R maps host uid 0 as uid 1000 of X's namespace. X maps \"0 1000 1\" one\n+ * level down: host uid 0 is uid 0 there without any extent at uid 0.\n+ */\n+static long x_nonzero_root(void *a)\n+{\n+\tint s1[2], s2[2], res[2], pid;\n+\tlong r = SETUP_ERROR;\n+\tchar c;\n+\n+\tif (pipe(s1) || pipe(s2) || pipe(res))\n+\t\treturn SETUP_ERROR;\n+\tpid = fork();\n+\tif (!pid) {\n+\t\trestrict_root();\n+\t\tif (unshare(CLONE_NEWUSER) || write(s1[1], \"u\", 1) != 1 ||\n+\t\t read(s2[0], \u0026c, 1) != 1)\n+\t\t\t_exit(1);\n+\t\tif (unshare(CLONE_NEWUSER))\n+\t\t\tr = SETUP_ERROR;\n+\t\telse\n+\t\t\tr = write_map(0, \"0 1000 1\\n\");\n+\t\tif (write(res[1], \u0026r, sizeof(r)) != sizeof(r))\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tif (read(s1[0], \u0026c, 1) != 1 || map_both(pid, \"1000 0 1\\n\") ||\n+\t write(s2[1], \"g\", 1) != 1 || read(res[0], \u0026r, sizeof(r)) != sizeof(r))\n+\t\tr = SETUP_ERROR;\n+\twaitpid(pid, NULL, 0);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, map_ancestor_root_at_nonzero_uid)\n+{\n+\tEXPECT_EQ(in_child(x_nonzero_root, NULL), -EPERM);\n+}\n+\n+/*\n+ * R's namespace has no map yet. R opens its uid_map and hands the fd to a\n+ * task of the same namespace that gave up CAP_SETFCAP (but kept it in the\n+ * bounding set, so it would get it back from execve() as uid 0).\n+ */\n+static long dropped_writes_inherited_fd(void *a)\n+{\n+\tint fd, pid, st;\n+\tlong r = SETUP_ERROR;\n+\tint p[2];\n+\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\tfd = open(\"/proc/self/uid_map\", O_WRONLY);\n+\tif (fd \u003c 0 || pipe(p))\n+\t\treturn SETUP_ERROR;\n+\tpid = fork();\n+\tif (!pid) {\n+\t\tdrop_setfcap_keep_bset();\n+\t\tr = wr(fd, \"0 0 1\\n\");\n+\t\tif (write(p[1], \u0026r, sizeof(r)) != sizeof(r))\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tif (read(p[0], \u0026r, sizeof(r)) != sizeof(r))\n+\t\tr = SETUP_ERROR;\n+\twaitpid(pid, \u0026st, 0);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, map_in_ns_writer_without_setfcap)\n+{\n+\tEXPECT_EQ(in_child(dropped_writes_inherited_fd, NULL), -EPERM);\n+}\n+\n+/* ... and the same task opening its own map */\n+static long dropped_opens_and_writes(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\tdrop_setfcap_keep_bset();\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_in_ns_opener_without_setfcap)\n+{\n+\tEXPECT_EQ(in_child(dropped_opens_and_writes, NULL), -EPERM);\n+}\n+\n+/* What has to keep working. */\n+\n+static long r_maps_own(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_own)\n+{\n+\tEXPECT_EQ(in_child(r_maps_own, NULL), 0);\n+}\n+\n+static long r_maps_from_parent(void *a)\n+{\n+\treturn write_map(PID(a), \"0 0 1000\\n\");\n+}\n+\n+TEST_F(setfcap, map_from_parent)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_maps_from_parent, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+static long child_maps(void *a)\n+{\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+static long r_child_maps(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\treturn in_child(child_maps, NULL);\n+}\n+\n+TEST_F(setfcap, map_by_child_of_creator)\n+{\n+\tEXPECT_EQ(in_child(r_child_maps, NULL), 0);\n+}\n+\n+static long r_joins_and_maps(void *a)\n+{\n+\tlong r = join(PID(a));\n+\n+\tif (r)\n+\t\treturn r;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_after_setns_with_setfcap)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_joins_and_maps, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+static long r_joins_writes_fd(void *a)\n+{\n+\tvoid **v = a;\n+\tlong r = join(PID(v[0]));\n+\n+\tif (r)\n+\t\treturn r;\n+\treturn wr(*(int *)v[1], \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_opened_in_parent_written_inside)\n+{\n+\tstruct holder h;\n+\tchar path[64];\n+\tvoid *v[2];\n+\tint fd;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tsnprintf(path, sizeof(path), \"/proc/%d/uid_map\", h.pid);\n+\tfd = open(path, O_WRONLY);\n+\tASSERT_GE(fd, 0);\n+\tv[0] = \u0026h;\n+\tv[1] = \u0026fd;\n+\tEXPECT_EQ(in_child(r_joins_writes_fd, v), 0);\n+\tclose(fd);\n+\treap_holder(h);\n+}\n+\n+static long u_nested_maps_own(void *a)\n+{\n+\tbecome_user();\n+\tif (unshare(CLONE_NEWUSER) || map_user())\n+\t\treturn SETUP_ERROR;\n+\treturn in_child(r_maps_own, NULL);\n+}\n+\n+TEST_F(setfcap, map_unprivileged_nested)\n+{\n+\tEXPECT_EQ(in_child(u_nested_maps_own, NULL), 0);\n+}\n+\n+static long u_nested_maps_child(void *a)\n+{\n+\tstruct holder h;\n+\tlong r;\n+\n+\tbecome_user();\n+\tif (unshare(CLONE_NEWUSER) || map_user())\n+\t\treturn SETUP_ERROR;\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tif (h.pid \u003c= 0)\n+\t\treturn SETUP_ERROR;\n+\tr = write_map(h.pid, \"0 0 1\\n\");\n+\treap_holder(h);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, map_unprivileged_nested_from_parent)\n+{\n+\tEXPECT_EQ(in_child(u_nested_maps_child, NULL), 0);\n+}\n+\n+static long session_to_parent(void *a)\n+{\n+\tif (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) \u003c 0 ||\n+\t syscall(SYS_keyctl, KEYCTL_SESSION_TO_PARENT) \u003c 0)\n+\t\treturn SETUP_ERROR;\n+\treturn 0;\n+}\n+\n+/* a cred replaced by key_change_session_keyring() keeps what it had */\n+static long r_new_session_keyring_maps(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\tif (in_child(session_to_parent, NULL))\n+\t\treturn SETUP_ERROR;\n+\treturn write_map(0, \"0 0 1\\n\");\n+}\n+\n+TEST_F(setfcap, map_after_session_to_parent)\n+{\n+\tEXPECT_EQ(in_child(r_new_session_keyring_maps, NULL), 0);\n+}\n+\n+/* ---------------------------------------------------------------------- */\n+/* File capabilities that are honoured in an ancestor */\n+\n+static long x_joins_sets_fcap(void *a)\n+{\n+\tlong r;\n+\n+\trestrict_root();\n+\tr = join(PID(a));\n+\tif (r)\n+\t\treturn r;\n+\treturn set_fcap(\"/tmp/x\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_after_setns)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins_sets_fcap, \u0026h), -EPERM);\n+\treap_holder(h);\n+\tEXPECT_FALSE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+static long x_joins_sets_fcap_rootid5(void *a)\n+{\n+\tlong r;\n+\n+\trestrict_root();\n+\tr = join(PID(a));\n+\tif (r)\n+\t\treturn r;\n+\treturn set_fcap(\"/tmp/x\", 5);\n+}\n+\n+/* a v3 xattr can name the root user by any uid it has in the namespace */\n+TEST_F(setfcap, fcap_after_setns_v3_rootid)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"5 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins_sets_fcap_rootid5, \u0026h), -EPERM);\n+\treap_holder(h);\n+\tEXPECT_FALSE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+/* X unshares and R maps \"0 0 1\" for it from the parent */\n+static long x_unshares_r_maps(void *a)\n+{\n+\tint version = *(int *)a;\n+\tint s1[2], s2[2], res[2], pid;\n+\tlong r = SETUP_ERROR;\n+\tchar c;\n+\n+\tif (pipe(s1) || pipe(s2) || pipe(res))\n+\t\treturn SETUP_ERROR;\n+\tpid = fork();\n+\tif (!pid) {\n+\t\trestrict_root();\n+\t\tif (unshare(CLONE_NEWUSER) || write(s1[1], \"u\", 1) != 1 ||\n+\t\t read(s2[0], \u0026c, 1) != 1)\n+\t\t\t_exit(1);\n+\t\tif (version == 2) {\n+\t\t\t/* a v2 xattr on a tmpfs of its own */\n+\t\t\tif (unshare(CLONE_NEWNS) ||\n+\t\t\t mount(NULL, \"/\", NULL, MS_REC | MS_PRIVATE, NULL) ||\n+\t\t\t mount(\"tmpfs\", \"/mnt\", \"tmpfs\", 0, NULL) ||\n+\t\t\t new_file(\"/mnt/f\", 0))\n+\t\t\t\tr = SETUP_ERROR;\n+\t\t\telse\n+\t\t\t\tr = set_fcap(\"/mnt/f\", -1);\n+\t\t} else {\n+\t\t\tr = set_fcap(\"/tmp/x\", -1);\n+\t\t}\n+\t\tif (write(res[1], \u0026r, sizeof(r)) != sizeof(r))\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tif (read(s1[0], \u0026c, 1) != 1 || map_both(pid, \"0 0 1\\n\") ||\n+\t write(s2[1], \"g\", 1) != 1 || read(res[0], \u0026r, sizeof(r)) != sizeof(r))\n+\t\tr = SETUP_ERROR;\n+\twaitpid(pid, NULL, 0);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, fcap_creator_without_setfcap_parent_mapped)\n+{\n+\tint version = 3;\n+\n+\tEXPECT_EQ(in_child(x_unshares_r_maps, \u0026version), -EPERM);\n+\tEXPECT_FALSE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+/* the v2 fast path of cap_convert_nscap() */\n+TEST_F(setfcap, fcap_v2_creator_without_setfcap_parent_mapped)\n+{\n+\tint version = 2;\n+\n+\tEXPECT_EQ(in_child(x_unshares_r_maps, \u0026version), -EPERM);\n+}\n+\n+/* R maps \"5 0 1\", gives up CAP_SETFCAP, unshares again */\n+static long r_drops_then_nests(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER) || map_both(0, \"5 0 1\\n\"))\n+\t\treturn SETUP_ERROR;\n+\trestrict_root();\n+\tif (set_fcap(\"/tmp/x\", 5) != -EPERM)\n+\t\treturn SETUP_ERROR;\n+\tif (unshare(CLONE_NEWUSER))\n+\t\treturn SETUP_ERROR;\n+\tif (write_map(0, \"5 5 1\\n\"))\n+\t\treturn -EPERM;\n+\twrite_file(0, \"setgroups\", \"deny\");\n+\twrite_file(0, \"gid_map\", \"5 5 1\\n\");\n+\treturn set_fcap(\"/tmp/x\", 5);\n+}\n+\n+TEST_F(setfcap, fcap_after_dropping_setfcap_and_nesting)\n+{\n+\tEXPECT_EQ(in_child(r_drops_then_nests, NULL), -EPERM);\n+\tEXPECT_FALSE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+/* X unshares, R maps \"0 0 1\" for it, and another R joins it */\n+static long joiner_takes_ns_reach(void *a)\n+{\n+\tstruct holder h;\n+\tlong r;\n+\n+\th = spawn_mapped(HOLDER_RESTRICTED, \"0 0 1\\n\");\n+\tif (h.pid \u003c= 0)\n+\t\treturn SETUP_ERROR;\n+\tr = join(h.pid);\n+\tif (!r)\n+\t\tr = set_fcap(\"/tmp/x\", -1);\n+\treap_holder(h);\n+\treturn r;\n+}\n+\n+TEST_F(setfcap, fcap_joiner_takes_namespace_reach)\n+{\n+\tEXPECT_EQ(in_child(joiner_takes_ns_reach, NULL), -EPERM);\n+\tEXPECT_FALSE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+/*\n+ * A v2 xattr on a filesystem whose namespace has no uid 0 has no root user\n+ * and is honoured nowhere: refuse it rather than storing it unconverted.\n+ */\n+static long r_v2_without_uid0(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER) || map_both(0, \"1000 0 1\\n\"))\n+\t\treturn SETUP_ERROR;\n+\t/* host uid 0, our uid, is uid 1000 here */\n+\tif (unshare(CLONE_NEWNS) ||\n+\t mount(NULL, \"/\", NULL, MS_REC | MS_PRIVATE, NULL) ||\n+\t mount(\"tmpfs\", \"/mnt\", \"tmpfs\", 0, NULL) || new_file(\"/mnt/f\", 1000))\n+\t\treturn SETUP_ERROR;\n+\treturn set_fcap(\"/mnt/f\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_v2_without_uid0_in_fs_ns)\n+{\n+\tEXPECT_EQ(in_child(r_v2_without_uid0, NULL), -EINVAL);\n+}\n+\n+/* ... and from the parent namespace, where the writer does have a root user */\n+static long r_v2_without_uid0_from_parent(void *a)\n+{\n+\tstruct holder *h = a;\n+\tchar path[64];\n+\n+\tsnprintf(path, sizeof(path), \"/proc/%d/root/mnt/f\", h-\u003epid);\n+\treturn set_fcap(path, -1);\n+}\n+\n+TEST_F(setfcap, fcap_v2_without_uid0_from_parent)\n+{\n+\tint ready[2], go[2], mapped[2], pid;\n+\tstruct holder h;\n+\tchar c;\n+\n+\tASSERT_EQ(pipe(ready), 0);\n+\tASSERT_EQ(pipe(go), 0);\n+\tASSERT_EQ(pipe(mapped), 0);\n+\tpid = fork();\n+\tASSERT_GE(pid, 0);\n+\tif (!pid) {\n+\t\t/* host uid 0 is uid 1000 in here, nobody is uid 0 */\n+\t\tif (unshare(CLONE_NEWUSER) || write(ready[1], \"u\", 1) != 1 ||\n+\t\t read(mapped[0], \u0026c, 1) != 1 || unshare(CLONE_NEWNS) ||\n+\t\t mount(NULL, \"/\", NULL, MS_REC | MS_PRIVATE, NULL) ||\n+\t\t mount(\"tmpfs\", \"/mnt\", \"tmpfs\", 0, NULL) ||\n+\t\t new_file(\"/mnt/f\", 1000) || write(ready[1], \"m\", 1) != 1)\n+\t\t\t_exit(1);\n+\t\tif (read(go[0], \u0026c, 1) \u003c 0)\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\th.pid = pid;\n+\th.go = go[1];\n+\tASSERT_EQ(read(ready[0], \u0026c, 1), 1);\n+\tASSERT_EQ(map_both(pid, \"1000 0 1\\n\"), 0);\n+\tASSERT_EQ(write(mapped[1], \"g\", 1), 1);\n+\tASSERT_EQ(read(ready[0], \u0026c, 1), 1);\n+\tEXPECT_EQ(in_child(r_v2_without_uid0_from_parent, \u0026h), -EINVAL);\n+\treap_holder(h);\n+}\n+\n+/* What has to keep working. */\n+\n+static long r_maps_sets_fcap(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER) || map_both(0, \"0 0 1\\n\"))\n+\t\treturn SETUP_ERROR;\n+\treturn set_fcap(\"/tmp/x\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_own_ns)\n+{\n+\tEXPECT_EQ(in_child(r_maps_sets_fcap, NULL), 0);\n+\tEXPECT_TRUE(user_gets_sys_admin(\"/tmp/x\"));\n+}\n+\n+static long r_joins_sets_fcap(void *a)\n+{\n+\tlong r = join(PID(a));\n+\n+\tif (r)\n+\t\treturn r;\n+\treturn set_fcap(\"/tmp/x\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_after_setns_with_setfcap)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_joins_sets_fcap, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+static long u_sets_fcap(void *a)\n+{\n+\tbecome_user();\n+\tif (unshare(CLONE_NEWUSER) || map_user())\n+\t\treturn SETUP_ERROR;\n+\treturn set_fcap(\"/tmp/u\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_unprivileged)\n+{\n+\tEXPECT_EQ(in_child(u_sets_fcap, NULL), 0);\n+}\n+\n+static long u_nested_sets_fcap_inner(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER) || map_both(0, \"0 0 1\\n\"))\n+\t\treturn SETUP_ERROR;\n+\treturn set_fcap(\"/tmp/u\", -1);\n+}\n+\n+static long u_nested_sets_fcap(void *a)\n+{\n+\tbecome_user();\n+\tif (unshare(CLONE_NEWUSER) || map_user())\n+\t\treturn SETUP_ERROR;\n+\treturn in_child(u_nested_sets_fcap_inner, NULL);\n+}\n+\n+TEST_F(setfcap, fcap_unprivileged_nested)\n+{\n+\tEXPECT_EQ(in_child(u_nested_sets_fcap, NULL), 0);\n+}\n+\n+static long u_joins_own_sets_fcap(void *a)\n+{\n+\tlong r;\n+\n+\tbecome_user();\n+\tr = join(PID(a));\n+\tif (r)\n+\t\treturn r;\n+\treturn set_fcap(\"/tmp/u\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_unprivileged_after_setns)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_USER, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(u_joins_own_sets_fcap, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+static long r_v2_own_fs(void *a)\n+{\n+\tif (unshare(CLONE_NEWUSER) || map_both(0, \"0 0 1\\n\"))\n+\t\treturn SETUP_ERROR;\n+\tif (unshare(CLONE_NEWNS) ||\n+\t mount(NULL, \"/\", NULL, MS_REC | MS_PRIVATE, NULL) ||\n+\t mount(\"tmpfs\", \"/mnt\", \"tmpfs\", 0, NULL) || new_file(\"/mnt/f\", 0))\n+\t\treturn SETUP_ERROR;\n+\treturn set_fcap(\"/mnt/f\", -1);\n+}\n+\n+TEST_F(setfcap, fcap_v2_own_ns)\n+{\n+\tEXPECT_EQ(in_child(r_v2_own_fs, NULL), 0);\n+}\n+\n+/* ---------------------------------------------------------------------- */\n+/* Idmapped mounts: the root user is both the one seen through the mount */\n+/* and the one stored. Mounts that make a container's root host uid 0 are */\n+/* up to whoever sets them up. */\n+\n+struct idmap_case {\n+\tconst char *ns_map, *idmap_map;\n+\tint file_uid, restricted;\n+};\n+\n+/* returns 1 to skip: no idmapped mounts on tmpfs */\n+static int idmap_case(const struct idmap_case *c, long *r)\n+{\n+\tstruct holder ns, im;\n+\tint pid, p[2], st;\n+\n+\tns = spawn_mapped(HOLDER_ROOT, c-\u003ens_map);\n+\tif (ns.pid \u003c= 0)\n+\t\treturn -1;\n+\tim = c-\u003eidmap_map ? spawn_mapped(HOLDER_ROOT, c-\u003eidmap_map) : ns;\n+\tif (im.pid \u003c= 0 || new_file(\"/tmp/x\", c-\u003efile_uid))\n+\t\treturn -1;\n+\tif (idmap_tmp(im.pid)) {\n+\t\treap_holder(ns);\n+\t\tif (c-\u003eidmap_map)\n+\t\t\treap_holder(im);\n+\t\treturn 1;\n+\t}\n+\tif (pipe(p))\n+\t\treturn -1;\n+\t/* join from a child of the namespace's holder's sibling: pass the pid */\n+\tpid = fork();\n+\tif (!pid) {\n+\t\tlong res;\n+\n+\t\tif (c-\u003erestricted)\n+\t\t\trestrict_root();\n+\t\tres = join(ns.pid);\n+\t\tif (!res)\n+\t\t\tres = set_fcap(\"/mnt/x\", 0);\n+\t\tif (write(p[1], \u0026res, sizeof(res)) != sizeof(res))\n+\t\t\t_exit(1);\n+\t\t_exit(0);\n+\t}\n+\tif (read(p[0], r, sizeof(*r)) != sizeof(*r))\n+\t\t*r = SETUP_ERROR;\n+\twaitpid(pid, \u0026st, 0);\n+\tumount2(\"/mnt\", MNT_DETACH);\n+\treap_holder(ns);\n+\tif (c-\u003eidmap_map)\n+\t\treap_holder(im);\n+\treturn 0;\n+}\n+\n+FIXTURE(idmap) {};\n+\n+FIXTURE_VARIANT(idmap) {\n+\tstruct idmap_case c;\n+\tlong expect;\n+};\n+\n+/* X can't join a namespace that maps host uid 0 to get at the mount */\n+FIXTURE_VARIANT_ADD(idmap, reverse_mapping) {\n+\t.c = { \"0 0 1\\n\", \"100000 0 1\\n\", 100000, 1 },\n+\t.expect = -EPERM,\n+};\n+\n+/* R in its container writes through the container's own idmapped rootfs */\n+FIXTURE_VARIANT_ADD(idmap, container_root) {\n+\t.c = { \"0 100000 1000\\n\", NULL, 0, 0 },\n+\t.expect = 0,\n+};\n+\n+/* left to the admin: the container doesn't map host uid 0 */\n+FIXTURE_VARIANT_ADD(idmap, container_without_host_root) {\n+\t.c = { \"0 100000 1000\\n\", NULL, 0, 1 },\n+\t.expect = 0,\n+};\n+\n+FIXTURE_VARIANT_ADD(idmap, unrelated_idmap) {\n+\t.c = { \"0 100000 1000\\n\", \"200000 100000 1\\n\", 200000, 1 },\n+\t.expect = 0,\n+};\n+\n+FIXTURE_SETUP(idmap)\n+{\n+\tif (geteuid())\n+\t\tSKIP(return, \"needs root\");\n+\tprepare(_metadata);\n+}\n+\n+FIXTURE_TEARDOWN(idmap) {}\n+\n+TEST_F(idmap, fcap)\n+{\n+\tlong r;\n+\tint ret;\n+\n+\tret = idmap_case(\u0026variant-\u003ec, \u0026r);\n+\tASSERT_GE(ret, 0);\n+\tif (ret == 1)\n+\t\tSKIP(return, \"no idmapped mounts on tmpfs\");\n+\tEXPECT_EQ(r, variant-\u003eexpect);\n+}\n+\n+/* ---------------------------------------------------------------------- */\n+/* setns() */\n+\n+static long x_joins(void *a)\n+{\n+\trestrict_root();\n+\treturn join(PID(a));\n+}\n+\n+static long r_joins(void *a)\n+{\n+\treturn join(PID(a));\n+}\n+\n+TEST_F(setfcap, setns_ns_mapping_host_root)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, setns_ns_without_map_yet)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+/* a container that doesn't map host uid 0 */\n+TEST_F(setfcap, setns_container)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 100000 1000\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_joins, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, setns_unprivileged_ns)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_USER, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_joins, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+/* ---------------------------------------------------------------------- */\n+/* ptrace */\n+\n+static long x_attaches(void *a)\n+{\n+\trestrict_root();\n+\treturn attach_only(PID(a));\n+}\n+\n+static long r_attaches(void *a)\n+{\n+\treturn attach_only(PID(a));\n+}\n+\n+TEST_F(setfcap, ptrace_into_ns_without_map_yet)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_attaches, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, ptrace_into_ns_mapping_host_root)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 0 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_attaches, \u0026h), -EPERM);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, ptrace_into_container)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 100000 1000\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_attaches, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, ptrace_ns_mapping_only_user)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_mapped(HOLDER_ROOT, \"0 1000 1\\n\");\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_attaches, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, ptrace_between_restricted)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_RESTRICTED, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_attaches, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+TEST_F(setfcap, ptrace_with_setfcap)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(r_attaches, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+static long x_reads_environ(void *a)\n+{\n+\tchar path[64];\n+\tint fd;\n+\n+\trestrict_root();\n+\tsnprintf(path, sizeof(path), \"/proc/%d/environ\", PID(a));\n+\tfd = open(path, O_RDONLY);\n+\tif (fd \u003c 0)\n+\t\treturn -errno;\n+\tclose(fd);\n+\treturn 0;\n+}\n+\n+/* PTRACE_MODE_READ is unchanged */\n+TEST_F(setfcap, ptrace_read_mode_unchanged)\n+{\n+\tstruct holder h;\n+\n+\th = spawn_holder(HOLDER_ROOT, 0);\n+\tASSERT_GT(h.pid, 0);\n+\tEXPECT_EQ(in_child(x_reads_environ, \u0026h), 0);\n+\treap_holder(h);\n+}\n+\n+TEST_HARNESS_MAIN\n"
} |
| 2/1 | 2026/10/26 21:06 | agent | patch-evaluator |
1mModel:core Args: null Results: {
"EnableConfigs": [
"USER_NS"
],
"FocusSymbols": [
"cap_setfcap_level",
"cred_setfcap_reaches",
"cred_may_setfcap_userns",
"cap_convert_nscap",
"cap_ptrace_access_check",
"cap_ptrace_traceme",
"create_user_ns",
"proc_uid_map_write"
],
"Reasoning": "The patch refactors and extends how CAP_SETFCAP is tracked and checked across nested user namespaces. Instead of a single boolean `parent_could_setfcap`, it introduces hierarchical level tracking (`setfcap_level`) and enforces capability bounds across `setns` (`userns_install`), ptrace access (`cap_ptrace_access_check`, `cap_ptrace_traceme`), idmap validation (`verify_root_map`, `map_root_level`, `map_has_id`), and xattr capability conversion (`cap_convert_nscap`). All of these modifications are in core user namespace and security capability subsystems and are reachable through standard syscalls (clone/unshare, ptrace, setns, setxattr, and /proc/pid/uid_map writes). Fuzzing is warranted to verify that nested namespace relationships, mapping checks, and capability boundaries do not introduce privilege bypasses, out-of-bounds access, or assertion failures.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 543756ccee5549bf199f9931395f781384962df6
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Oct 26 21:06:57 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/capability.h b/include/linux/capability.h
index 622137f66f0928..e4199b03668bdc 100644
--- a/include/linux/capability.h
+++ b/include/linux/capability.h
@@ -34,6 +34,7 @@ struct cpu_vfs_cap_data {
#define _USER_CAP_HEADER_SIZE (sizeof(struct __user_cap_header_struct))
#define _KERNEL_CAP_T_SIZE (sizeof(kernel_cap_t))
+struct cred;
struct file;
struct inode;
struct dentry;
@@ -222,4 +223,9 @@ int get_vfs_caps_from_disk(const struct mnt_idmap *idmap,
int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,
const void **ivalue, size_t size);
+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns);
+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,
+ int level);
+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns);
+
#endif /* !_LINUX_CAPABILITY_H */
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d8d..f3753b6b6d29f7 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -86,9 +86,10 @@ struct user_namespace {
kgid_t group;
struct ns_common ns;
unsigned long flags;
- /* parent_could_setfcap: true if the creator if this ns had CAP_SETFCAP
- * in its effective capability set at the child ns creation time. */
- bool parent_could_setfcap;
+ /* setfcap_level: CAP_SETFCAP held in this ns counts here and in the
+ * ancestors up to the one at this ->level, see cap_setfcap_level().
+ */
+ int setfcap_level;
#ifdef CONFIG_KEYS
/* List of joinable keyrings in this namespace. Modification access of
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index 50c374ed4687be..db078dd6406aa8 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -125,7 +125,7 @@ int create_user_ns(struct cred *new)
if (!ns)
goto fail_dec;
- ns->parent_could_setfcap = cap_raised(new->cap_effective, CAP_SETFCAP);
+ ns->setfcap_level = cap_setfcap_level(new, parent_ns);
ret = ns_common_init(ns);
if (ret)
@@ -881,15 +881,55 @@ VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map)
}
EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort);
+static bool map_has_id(struct uid_gid_map *map, u32 id)
+{
+ struct uid_gid_extent *extent;
+ int idx;
+
+ for (idx = 0; idx < map->nr_extents; idx++) {
+ if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ extent = &map->extent[idx];
+ else
+ extent = &map->forward[idx];
+ if (id >= extent->lower_first &&
+ id - extent->lower_first < extent->count)
+ return true;
+ }
+
+ return false;
+}
+
+/*
+ * The lowest ->level among @parent and its ancestors whose root user @new_map
+ * maps, whatever uid that root user has in @parent; INT_MAX if there is none.
+ */
+static int map_root_level(struct user_namespace *parent,
+ struct uid_gid_map *new_map)
+{
+ struct user_namespace *p;
+ int level = INT_MAX;
+ uid_t id;
+
+ for (p = parent; p; p = p->parent) {
+ id = from_kuid(parent, make_kuid(p, 0));
+ if (id != (uid_t)-1 && map_has_id(new_map, id))
+ level = p->level;
+ }
+
+ return level;
+}
+
/**
* verify_root_map() - check the uid 0 mapping
* @file: idmapping file
* @map_ns: user namespace of the target process
* @new_map: requested idmap
*
- * If a process requests mapping parent uid 0 into the new ns, verify that the
- * process writing the map had the CAP_SETFCAP capability as the target process
- * will be able to write fscaps that are valid in ancestor user namespaces.
+ * If a process requests mapping the root user of the parent ns, or of one of
+ * its ancestors, into the new ns, verify that the process that opened the map
+ * file and the process writing the map had the CAP_SETFCAP capability as the
+ * target process will be able to write fscaps that are valid in ancestor user
+ * namespaces.
*
* Return: true if the mapping is allowed, false if not.
*/
@@ -897,42 +937,43 @@ static bool verify_root_map(const struct file *file,
struct user_namespace *map_ns,
struct uid_gid_map *new_map)
{
- int idx;
const struct user_namespace *file_ns = file->f_cred->user_ns;
- struct uid_gid_extent *extent0 = NULL;
-
- for (idx = 0; idx < new_map->nr_extents; idx++) {
- if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
- extent0 = &new_map->extent[idx];
- else
- extent0 = &new_map->forward[idx];
- if (extent0->lower_first == 0)
- break;
+ int level;
- extent0 = NULL;
- }
-
- if (!extent0)
+ level = map_root_level(map_ns->parent, new_map);
+ if (level == INT_MAX)
return true;
if (map_ns == file_ns) {
/* The process unshared its ns and is writing to its own
* /proc/self/uid_map. User already has full capabilites in
- * the new namespace. Verify that the parent had CAP_SETFCAP
- * when it unshared.
+ * the new namespace. Verify that it still has CAP_SETFCAP
+ * there, and that the parent had it when it unshared, as far up
+ * as those root users go.
* */
- if (!file_ns->parent_could_setfcap)
+ if (!file_ns_capable(file, map_ns, CAP_SETFCAP) ||
+ file_ns->setfcap_level > level)
return false;
} else {
/* Process p1 is writing to uid_map of p2, who is in a child
* user namespace to p1's. Verify that the opener of the map
* file has CAP_SETFCAP against the parent of the new map
- * namespace */
- if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP))
+ * namespace, and as far up as those root users go.
+ */
+ if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP) ||
+ !cred_setfcap_reaches(file->f_cred, map_ns->parent, level))
return false;
}
- return true;
+ /* The file may have been handed to someone else since it was opened,
+ * so the same goes for the process that is doing the write.
+ */
+ if (map_ns == current_user_ns())
+ return ns_capable(map_ns, CAP_SETFCAP) &&
+ map_ns->setfcap_level <= level;
+
+ return ns_capable(map_ns->parent, CAP_SETFCAP) &&
+ cred_setfcap_reaches(current_cred(), map_ns->parent, level);
}
/*
@@ -1390,6 +1431,12 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
+ /* Tasks in the namespace may have CAP_SETFCAP that counts outside of
+ * it, so only let in tasks whose own counts as far.
+ */
+ if (!cred_may_setfcap_userns(current_cred(), user_ns))
+ return -EPERM;
+
cred = nsset_cred(nsset);
if (!cred)
return -EINVAL;
diff --git a/security/commoncap.c b/security/commoncap.c
index d47ab30223435b..91ed4a5f4b2503 100644
--- a/security/commoncap.c
+++ b/security/commoncap.c
@@ -131,6 +131,114 @@ int cap_capable(const struct cred *cred, struct user_namespace *target_ns,
return ret;
}
+/**
+ * cap_setfcap_level - Determine how far up CAP_SETFCAP of a cred reaches
+ * @cred: The credentials to use
+ * @ns: The user namespace to look from
+ *
+ * File capabilities belong to the kuid of a namespace's root user, and the
+ * same kuid can be the root user of ancestors of that namespace. Every task
+ * gets CAP_SETFCAP when it enters a user namespace, so having it there says
+ * nothing about those ancestors. user_ns->setfcap_level does: it is taken
+ * from the creator when the namespace is created.
+ *
+ * Return: the ->level of the topmost namespace, from @ns upwards, for which
+ * CAP_SETFCAP of @cred counts; @ns->level + 1 if it doesn't even count over
+ * @ns, which includes an @ns that isn't @cred's namespace or a descendant.
+ */
+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)
+{
+ if (cap_capable(cred, ns, CAP_SETFCAP, CAP_OPT_NOAUDIT) != 0)
+ return ns->level + 1;
+
+ if (cap_raised(cred->cap_effective, CAP_SETFCAP))
+ return cred->user_ns->setfcap_level;
+
+ /* All we have is that we own a child of our namespace. */
+ return cred->user_ns->level + 1;
+}
+
+/**
+ * cred_setfcap_reaches - Check how far up CAP_SETFCAP of a cred reaches
+ * @cred: The credentials to use
+ * @ns: The user namespace to look from
+ * @level: The ->level of the ancestor of @ns it has to count in
+ *
+ * Return: true if CAP_SETFCAP of @cred counts in @ns and in its ancestors
+ * up to the one at @level.
+ */
+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,
+ int level)
+{
+ return cap_setfcap_level(cred, ns) <= level;
+}
+
+/*
+ * The topmost ancestor of @ns whose root user tasks in @ns can write file
+ * capabilities for: within @ns->setfcap_level, and mapped into @ns, or into
+ * its parent while @ns has no uid_map yet. NULL if there is none. An
+ * idmapped mount can store other root users, but that is up to whoever sets
+ * up the mount.
+ */
+static struct user_namespace *setfcap_top(struct user_namespace *ns)
+{
+ struct user_namespace *seen, *p, *top = NULL;
+
+ if (ns->setfcap_level >= ns->level)
+ return NULL;
+
+ seen = READ_ONCE(ns->uid_map.nr_extents) ? ns : ns->parent;
+ for (p = ns->parent; p; p = p->parent) {
+ if (p->level < ns->setfcap_level)
+ break;
+ if (kuid_has_mapping(seen, make_kuid(p, 0)))
+ top = p;
+ }
+
+ return top;
+}
+
+/**
+ * cred_may_setfcap_userns - Check whether a cred covers what a userns can do
+ * @cred: The credentials to use
+ * @ns: The user namespace
+ *
+ * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see
+ * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as
+ * tasks in @ns can make use of theirs.
+ *
+ * Return: true if it does.
+ */
+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns)
+{
+ struct user_namespace *top = setfcap_top(ns);
+
+ return !top || cred_setfcap_reaches(cred, ns->parent, top->level);
+}
+
+/**
+ * cap_root_level - Find the topmost namespace in which a kuid is the root user
+ * @kuid: The kuid to look for
+ * @ns: The user namespace to start from
+ *
+ * Return: the lowest ->level among @ns and its ancestors in which @kuid is
+ * uid 0, which is how far up file capabilities with that root user are
+ * honoured; INT_MAX if there is no such namespace.
+ */
+static int cap_root_level(kuid_t kuid, struct user_namespace *ns)
+{
+ int level = INT_MAX;
+
+ for (;; ns = ns->parent) {
+ if (from_kuid(ns, kuid) == 0)
+ level = ns->level;
+ if (ns == &init_user_ns)
+ break;
+ }
+
+ return level;
+}
+
/**
* cap_settime - Determine whether the current process may set the system clock
* @ts: The time to set
@@ -146,14 +254,41 @@ int cap_settime(const struct timespec64 *ts, const struct timezone *tz)
return 0;
}
+/*
+ * Tasks in a user namespace have CAP_SETFCAP that can count in ancestors of
+ * the namespace, see cap_setfcap_level(). That is a privilege outside of the
+ * namespace, so capabilities over the namespace are not enough to take
+ * control of such a task.
+ */
+static bool cap_covers_setfcap(const struct cred *cred,
+ const struct cred *child_cred)
+{
+ struct user_namespace *ns = child_cred->user_ns, *top;
+
+ /* setns() only lets in tasks whose CAP_SETFCAP reaches as far. */
+ if (cred->user_ns == ns)
+ return true;
+
+ top = setfcap_top(ns);
+ if (!top)
+ return true;
+
+ /* CAP_SYS_PTRACE up there gives control of tasks with CAP_SETFCAP. */
+ return cred_setfcap_reaches(cred, ns->parent, top->level) ||
+ !cap_capable(cred, top, CAP_SYS_PTRACE, CAP_OPT_NOAUDIT);
+}
+
/**
* cap_ptrace_access_check - Determine whether the current process may access
* another
* @child: The process to be accessed
* @mode: The mode of attachment.
*
- * If we are in the same or an ancestor user_ns and have all the target
- * task's capabilities, then ptrace access is allowed.
+ * For PTRACE_MODE_ATTACH, if the target task may make use of CAP_SETFCAP in
+ * an ancestor of its user_ns that our CAP_SETFCAP or CAP_SYS_PTRACE doesn't
+ * reach, then ptrace access is denied.
+ * Otherwise, if we are in the same or an ancestor user_ns and have all the
+ * target task's capabilities, then ptrace access is allowed.
* If we have the ptrace capability to the target user_ns, then ptrace
* access is allowed.
* Else denied.
@@ -174,11 +309,15 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
caller_caps = &cred->cap_effective;
else
caller_caps = &cred->cap_permitted;
+ if ((mode & PTRACE_MODE_ATTACH) &&
+ !cap_covers_setfcap(cred, child_cred))
+ goto deny;
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, *caller_caps))
goto out;
if (ns_capable(child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
+deny:
ret = -EPERM;
out:
rcu_read_unlock();
@@ -189,8 +328,11 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
* cap_ptrace_traceme - Determine whether another process may trace the current
* @parent: The task proposed to be the tracer
*
- * If parent is in the same or an ancestor user_ns and has all current's
- * capabilities, then ptrace access is allowed.
+ * If current may make use of CAP_SETFCAP in an ancestor of its user_ns that
+ * parent's CAP_SETFCAP or CAP_SYS_PTRACE doesn't reach, then ptrace access
+ * is denied.
+ * Otherwise, if parent is in the same or an ancestor user_ns and has all
+ * current's capabilities, then ptrace access is allowed.
* If parent has the ptrace capability to current's user_ns, then ptrace
* access is allowed.
* Else denied.
@@ -206,11 +348,14 @@ int cap_ptrace_traceme(struct task_struct *parent)
rcu_read_lock();
cred = __task_cred(parent);
child_cred = current_cred();
+ if (!cap_covers_setfcap(cred, child_cred))
+ goto deny;
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
goto out;
if (has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
+deny:
ret = -EPERM;
out:
rcu_read_unlock();
@@ -586,19 +731,46 @@ int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,
return -EINVAL;
if (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))
return -EPERM;
- if (size == XATTR_CAPS_SZ_2 && (idmap == &nop_mnt_idmap))
- if (ns_capable(inode->i_sb->s_user_ns, CAP_SETFCAP))
+ /*
+ * A v2 xattr belongs to the root user of the filesystem's namespace,
+ * which may be the root user of ancestors of our namespace as well.
+ * There may be none, then nobody could ever run the file with these
+ * capabilities. Only write it unconverted if that root user is
+ * within reach, the checks below handle everything else.
+ */
+ if (size == XATTR_CAPS_SZ_2 && idmap == &nop_mnt_idmap &&
+ ns_capable(fs_ns, CAP_SETFCAP)) {
+ kuid_t fsroot = make_kuid(fs_ns, 0);
+
+ if (!uid_valid(fsroot))
+ return -EINVAL;
+ if (cap_root_level(fsroot, task_ns) >= task_ns->setfcap_level)
/* user is privileged, just write the v2 */
return size;
+ }
vfsrootid = rootid_from_xattr(*ivalue, size, task_ns);
if (!vfsuid_valid(vfsrootid))
return -EINVAL;
+ /*
+ * The root user may be the root user of ancestors of our namespace as
+ * well. CAP_SETFCAP that we got for entering it doesn't cover those.
+ * On an idmapped mount the root user is vfsrootid as seen through
+ * this mount and rootid as seen through every other mount of the
+ * filesystem, so both have to stay within reach.
+ */
+ if (cap_root_level(vfsuid_into_kuid(vfsrootid), task_ns) <
+ task_ns->setfcap_level)
+ return -EPERM;
+
rootid = from_vfsuid(idmap, fs_ns, vfsrootid);
if (!uid_valid(rootid))
return -EINVAL;
+ if (cap_root_level(rootid, task_ns) < task_ns->setfcap_level)
+ return -EPERM;
+
nsrootid = from_kuid(fs_ns, rootid);
if (nsrootid == -1)
return -EINVAL;
diff --git a/tools/testing/selftests/namespaces/Makefile b/tools/testing/selftests/namespaces/Makefile
index 9b22d12708e1aa..0455b6544869d1 100644
--- a/tools/testing/selftests/namespaces/Makefile
+++ b/tools/testing/selftests/namespaces/Makefile
@@ -14,7 +14,8 @@ TEST_GEN_PROGS := nsid_test \
stress_test \
listns_pagination_bug \
regression_pidfd_setns_test \
- uid_map_range_test
+ uid_map_range_test \
+ setfcap_test
include ../lib.mk
diff --git a/tools/testing/selftests/namespaces/config b/tools/testing/selftests/namespaces/config
index d09836260262f4..dfbabc35cd8a12 100644
--- a/tools/testing/selftests/namespaces/config
+++ b/tools/testing/selftests/namespaces/config
@@ -5,3 +5,6 @@ CONFIG_USER_NS=y
CONFIG_PID_NS=y
CONFIG_NET_NS=y
CONFIG_CGROUPS=y
+CONFIG_TMPFS=y
+CONFIG_TMPFS_XATTR=y
+CONFIG_KEYS=y
diff --git a/tools/testing/selftests/namespaces/setfcap_test.c b/tools/testing/selftests/namespaces/setfcap_test.c
new file mode 100644
index 00000000000000..0a82b239b36856
--- /dev/null
+++ b/tools/testing/selftests/namespaces/setfcap_test.c
@@ -0,0 +1,1362 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Who may map the root user of an ancestor user namespace, write file
+ * capabilities that are honoured in an ancestor, join a namespace whose
+ * tasks may do so, or take control of such a task.
+ *
+ * "R" is a task with uid 0 and all capabilities in the initial namespace,
+ * "X" one with uid 0 that gave up CAP_SETFCAP and CAP_SYS_PTRACE in its
+ * permitted, effective and bounding sets, and "U" is uid 1000.
+ *
+ * Every test runs in a private mount namespace with a tmpfs on /tmp.
+ */
+#define _GNU_SOURCE
+#include <endian.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/wait.h>
+#include <sys/xattr.h>
+#include <linux/capability.h>
+#include <linux/keyctl.h>
+#include <linux/mount.h>
+
+#include "kselftest_harness.h"
+
+#ifndef __NR_pidfd_open
+#define __NR_pidfd_open 434
+#endif
+#ifndef __NR_pidfd_getfd
+#define __NR_pidfd_getfd 438
+#endif
+#ifndef __NR_open_tree
+#define __NR_open_tree 428
+#endif
+#ifndef __NR_move_mount
+#define __NR_move_mount 429
+#endif
+#ifndef __NR_mount_setattr
+#define __NR_mount_setattr 442
+#endif
+
+/* Exit codes of a copy of this program run with SETFCAP_TEST_CAPS set. */
+#define CAPS_HAS_SYS_ADMIN 42
+#define CAPS_NO_SYS_ADMIN 43
+
+/* A step that wasn't the one under test went wrong. */
+#define SETUP_ERROR (-1000)
+
+static int capget_v3(struct __user_cap_data_struct d[2])
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+
+ return syscall(SYS_capget, &h, d);
+}
+
+__attribute__((constructor)) static void report_caps(void)
+{
+ struct __user_cap_data_struct d[2];
+
+ if (!getenv("SETFCAP_TEST_CAPS"))
+ return;
+ if (capget_v3(d))
+ _exit(1);
+ _exit(d[0].effective & (1u << CAP_SYS_ADMIN) ?
+ CAPS_HAS_SYS_ADMIN : CAPS_NO_SYS_ADMIN);
+}
+
+/* X: uid 0 without CAP_SETFCAP and CAP_SYS_PTRACE */
+static void restrict_root(void)
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+ struct __user_cap_data_struct d[2];
+ unsigned int drop = (1u << CAP_SETFCAP) | (1u << CAP_SYS_PTRACE);
+
+ if (prctl(PR_CAPBSET_DROP, CAP_SETFCAP) ||
+ prctl(PR_CAPBSET_DROP, CAP_SYS_PTRACE) || capget_v3(d))
+ _exit(99);
+ d[0].effective &= ~drop;
+ d[0].permitted &= ~drop;
+ if (syscall(SYS_capset, &h, d))
+ _exit(99);
+}
+
+/* Give up CAP_SETFCAP only in the permitted and effective set. */
+static void drop_setfcap_keep_bset(void)
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+ struct __user_cap_data_struct d[2];
+
+ if (capget_v3(d))
+ _exit(99);
+ d[0].effective &= ~(1u << CAP_SETFCAP);
+ d[0].permitted &= ~(1u << CAP_SETFCAP);
+ if (syscall(SYS_capset, &h, d))
+ _exit(99);
+}
+
+static void become_user(void)
+{
+ if (setresgid(1000, 1000, 1000) || setresuid(1000, 1000, 1000))
+ _exit(99);
+ prctl(PR_SET_DUMPABLE, 1);
+}
+
+static long wr(int fd, const char *s)
+{
+ long r = write(fd, s, strlen(s));
+
+ return r < 0 ? -errno : 0;
+}
+
+static long write_file(int pid, const char *name, const char *s)
+{
+ char path[64];
+ long r;
+ int fd;
+
+ if (pid)
+ snprintf(path, sizeof(path), "/proc/%d/%s", pid, name);
+ else
+ snprintf(path, sizeof(path), "/proc/self/%s", name);
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return -errno;
+ r = wr(fd, s);
+ close(fd);
+ return r;
+}
+
+static long write_map(int pid, const char *map)
+{
+ return write_file(pid, "uid_map", map);
+}
+
+/* both maps, as the setup for a test rather than its subject */
+static long map_both(int pid, const char *map)
+{
+ if (write_map(pid, map) || write_file(pid, "setgroups", "deny") ||
+ write_file(pid, "gid_map", map))
+ return SETUP_ERROR;
+ return 0;
+}
+
+/* what an unprivileged user does after unshare(CLONE_NEWUSER) */
+static long map_user(void)
+{
+ return map_both(0, "0 1000 1\n");
+}
+
+static long join(int pid)
+{
+ char path[64];
+ int fd, r;
+
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return SETUP_ERROR;
+ r = setns(fd, CLONE_NEWUSER);
+ close(fd);
+ return r ? -errno : 0;
+}
+
+/* security.capability with CAP_SYS_ADMIN in permitted and effective; v2 if rootid < 0 */
+static long set_fcap(const char *path, int rootid)
+{
+ struct vfs_ns_cap_data d;
+ int v3 = rootid >= 0;
+
+ memset(&d, 0, sizeof(d));
+ d.magic_etc = htole32((v3 ? VFS_CAP_REVISION_3 : VFS_CAP_REVISION_2) |
+ VFS_CAP_FLAGS_EFFECTIVE);
+ d.data[0].permitted = htole32(1u << CAP_SYS_ADMIN);
+ d.rootid = htole32(rootid);
+ if (setxattr(path, "security.capability", &d,
+ v3 ? XATTR_CAPS_SZ_3 : XATTR_CAPS_SZ_2, 0))
+ return -errno;
+ return 0;
+}
+
+/* a copy of this program, owned by uid */
+static int new_file(const char *path, int uid)
+{
+ char buf[65536];
+ int in, out;
+ ssize_t n;
+
+ unlink(path);
+ in = open("/proc/self/exe", O_RDONLY);
+ out = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
+ if (in < 0 || out < 0)
+ return -1;
+ while ((n = read(in, buf, sizeof(buf))) > 0)
+ if (write(out, buf, n) != n)
+ return -1;
+ if (fchown(out, uid, uid) || fchmod(out, 0755))
+ return -1;
+ close(in);
+ close(out);
+ return 0;
+}
+
+/* Does U get CAP_SYS_ADMIN from the file capabilities of path? */
+static int user_gets_sys_admin(const char *path)
+{
+ int pid, st;
+
+ pid = fork();
+ if (!pid) {
+ become_user();
+ setenv("SETFCAP_TEST_CAPS", "1", 1);
+ execl(path, path, NULL);
+ _exit(1);
+ }
+ waitpid(pid, &st, 0);
+ return WIFEXITED(st) && WEXITSTATUS(st) == CAPS_HAS_SYS_ADMIN;
+}
+
+/* run fn in a child and return what it returns */
+static long in_child(long (*fn)(void *), void *arg)
+{
+ int p[2], pid;
+ long r = SETUP_ERROR;
+
+ if (pipe(p))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ r = fn(arg);
+ if (write(p[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ close(p[1]);
+ if (read(p[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ close(p[0]);
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+/* A task that unshares a user namespace and waits. */
+struct holder {
+ int pid, go;
+};
+
+enum holder_kind {
+ HOLDER_ROOT, /* R */
+ HOLDER_RESTRICTED, /* X */
+ HOLDER_USER, /* U, maps "0 1000 1" itself */
+};
+
+static struct holder spawn_holder(enum holder_kind kind, int map_fd_at)
+{
+ struct holder h = { -1, -1 };
+ int ready[2], go[2];
+ char c;
+
+ if (pipe(ready) || pipe(go))
+ return h;
+ h.pid = fork();
+ if (!h.pid) {
+ close(ready[0]);
+ close(go[1]);
+ if (kind == HOLDER_RESTRICTED)
+ restrict_root();
+ if (kind == HOLDER_USER)
+ become_user();
+ if (unshare(CLONE_NEWUSER))
+ _exit(1);
+ if (kind == HOLDER_USER && map_user())
+ _exit(1);
+ if (map_fd_at)
+ dup2(open("/proc/self/uid_map", O_WRONLY), map_fd_at);
+ if (write(ready[1], "r", 1) != 1)
+ _exit(1);
+ if (read(go[0], &c, 1) < 0)
+ _exit(1);
+ _exit(0);
+ }
+ close(ready[1]);
+ close(go[0]);
+ if (read(ready[0], &c, 1) != 1)
+ h.pid = -1;
+ close(ready[0]);
+ h.go = go[1];
+ return h;
+}
+
+/* ... whose maps are written from the parent namespace by the caller */
+static struct holder spawn_mapped(enum holder_kind kind, const char *map)
+{
+ struct holder h = spawn_holder(kind, 0);
+
+ if (h.pid > 0 && map_both(h.pid, map))
+ h.pid = -1;
+ return h;
+}
+
+static void reap_holder(struct holder h)
+{
+ if (h.pid <= 0)
+ return;
+ close(h.go);
+ kill(h.pid, SIGKILL);
+ waitpid(h.pid, NULL, 0);
+}
+
+#define PID(a) (((struct holder *)(a))->pid)
+
+static long attach_only(int pid)
+{
+ if (ptrace(PTRACE_ATTACH, pid, 0, 0))
+ return -errno;
+ waitpid(pid, NULL, 0);
+ ptrace(PTRACE_DETACH, pid, 0, 0);
+ return 0;
+}
+
+/* /tmp idmapped with the user namespace of pid, at /mnt */
+static int idmap_tmp(int pid)
+{
+ struct mount_attr attr = { .attr_set = MOUNT_ATTR_IDMAP };
+ char path[64];
+ int tfd, nsfd;
+
+ mkdir("/mnt", 0755);
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
+ nsfd = open(path, O_RDONLY);
+ tfd = syscall(__NR_open_tree, AT_FDCWD, "/tmp",
+ OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
+ if (nsfd < 0 || tfd < 0)
+ return -1;
+ attr.userns_fd = nsfd;
+ if (syscall(__NR_mount_setattr, tfd, "", AT_EMPTY_PATH, &attr,
+ sizeof(attr)))
+ return -1;
+ if (syscall(__NR_move_mount, tfd, "", AT_FDCWD, "/mnt",
+ MOVE_MOUNT_F_EMPTY_PATH))
+ return -1;
+ close(tfd);
+ close(nsfd);
+ return 0;
+}
+
+/* Each test: private mounts, a tmpfs on /tmp with copies of this program */
+static void prepare(struct __test_metadata *_metadata)
+{
+ ASSERT_EQ(unshare(CLONE_NEWNS), 0);
+ ASSERT_EQ(mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
+ ASSERT_EQ(mount("tmpfs", "/tmp", "tmpfs", 0, "mode=1777"), 0);
+ ASSERT_EQ(new_file("/tmp/x", 0), 0);
+ ASSERT_EQ(new_file("/tmp/u", 1000), 0);
+ mkdir("/mnt", 0755);
+}
+
+FIXTURE(setfcap) {};
+
+FIXTURE_SETUP(setfcap)
+{
+ if (geteuid())
+ SKIP(return, "needs root");
+ prepare(_metadata);
+}
+
+FIXTURE_TEARDOWN(setfcap) {}
+
+/* ---------------------------------------------------------------------- */
+/* Mapping uid 0 of the parent, or the root user of an ancestor at any uid */
+
+static long x_maps_from_parent(void *a)
+{
+ restrict_root();
+ return write_map(PID(a), "0 0 1\n");
+}
+
+TEST_F(setfcap, map_from_parent_without_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_maps_from_parent, &h), -EPERM);
+ reap_holder(h);
+}
+
+static long x_maps_own(void *a)
+{
+ restrict_root();
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_own_without_setfcap)
+{
+ EXPECT_EQ(in_child(x_maps_own, NULL), -EPERM);
+}
+
+static long x_joins_and_maps(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return write_map(0, "0 0 1\n");
+}
+
+/* X can't get into R's namespace to map uid 0 from inside */
+TEST_F(setfcap, map_after_setns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_and_maps, &h), -EPERM);
+ reap_holder(h);
+}
+
+static long x_writes_fd(void *a)
+{
+ restrict_root();
+ return wr(*(int *)a, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_through_borrowed_fd)
+{
+ struct holder h;
+ char path[64];
+ int fd;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", h.pid);
+ fd = open(path, O_WRONLY);
+ ASSERT_GE(fd, 0);
+ EXPECT_EQ(in_child(x_writes_fd, &fd), -EPERM);
+ close(fd);
+ reap_holder(h);
+}
+
+static long x_steals_fd(void *a)
+{
+ int pfd, fd;
+
+ restrict_root();
+ pfd = syscall(__NR_pidfd_open, PID(a), 0);
+ if (pfd < 0)
+ return SETUP_ERROR;
+ fd = syscall(__NR_pidfd_getfd, pfd, 100, 0);
+ if (fd < 0)
+ return -errno;
+ return wr(fd, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_through_pidfd_getfd)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 100);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_steals_fd, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* the same one level down, among tasks of an unprivileged user */
+static long u_nested(void *a)
+{
+ struct holder h;
+ long r;
+
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ /* R-like: full set in the user's namespace */
+ h = spawn_holder(HOLDER_ROOT, 0);
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = in_child(x_joins_and_maps, &h);
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, map_after_setns_nested_unprivileged)
+{
+ EXPECT_EQ(in_child(u_nested, NULL), -EPERM);
+}
+
+static long x_joins_unshares_maps(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_setns_and_unshare)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_unshares_maps, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* the writer opened the map, then went into an unrelated namespace */
+static long r_opens_then_leaves(void *a)
+{
+ char path[64];
+ int fd;
+
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", PID(a));
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return wr(fd, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_writer_left_for_other_ns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_opens_then_leaves, &h), -EPERM);
+ reap_holder(h);
+}
+
+/*
+ * R maps host uid 0 as uid 1000 of X's namespace. X maps "0 1000 1" one
+ * level down: host uid 0 is uid 0 there without any extent at uid 0.
+ */
+static long x_nonzero_root(void *a)
+{
+ int s1[2], s2[2], res[2], pid;
+ long r = SETUP_ERROR;
+ char c;
+
+ if (pipe(s1) || pipe(s2) || pipe(res))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ restrict_root();
+ if (unshare(CLONE_NEWUSER) || write(s1[1], "u", 1) != 1 ||
+ read(s2[0], &c, 1) != 1)
+ _exit(1);
+ if (unshare(CLONE_NEWUSER))
+ r = SETUP_ERROR;
+ else
+ r = write_map(0, "0 1000 1\n");
+ if (write(res[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(s1[0], &c, 1) != 1 || map_both(pid, "1000 0 1\n") ||
+ write(s2[1], "g", 1) != 1 || read(res[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+TEST_F(setfcap, map_ancestor_root_at_nonzero_uid)
+{
+ EXPECT_EQ(in_child(x_nonzero_root, NULL), -EPERM);
+}
+
+/*
+ * R's namespace has no map yet. R opens its uid_map and hands the fd to a
+ * task of the same namespace that gave up CAP_SETFCAP (but kept it in the
+ * bounding set, so it would get it back from execve() as uid 0).
+ */
+static long dropped_writes_inherited_fd(void *a)
+{
+ int fd, pid, st;
+ long r = SETUP_ERROR;
+ int p[2];
+
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ fd = open("/proc/self/uid_map", O_WRONLY);
+ if (fd < 0 || pipe(p))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ drop_setfcap_keep_bset();
+ r = wr(fd, "0 0 1\n");
+ if (write(p[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(p[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, &st, 0);
+ return r;
+}
+
+TEST_F(setfcap, map_in_ns_writer_without_setfcap)
+{
+ EXPECT_EQ(in_child(dropped_writes_inherited_fd, NULL), -EPERM);
+}
+
+/* ... and the same task opening its own map */
+static long dropped_opens_and_writes(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ drop_setfcap_keep_bset();
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_in_ns_opener_without_setfcap)
+{
+ EXPECT_EQ(in_child(dropped_opens_and_writes, NULL), -EPERM);
+}
+
+/* What has to keep working. */
+
+static long r_maps_own(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_own)
+{
+ EXPECT_EQ(in_child(r_maps_own, NULL), 0);
+}
+
+static long r_maps_from_parent(void *a)
+{
+ return write_map(PID(a), "0 0 1000\n");
+}
+
+TEST_F(setfcap, map_from_parent)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_maps_from_parent, &h), 0);
+ reap_holder(h);
+}
+
+static long child_maps(void *a)
+{
+ return write_map(0, "0 0 1\n");
+}
+
+static long r_child_maps(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return in_child(child_maps, NULL);
+}
+
+TEST_F(setfcap, map_by_child_of_creator)
+{
+ EXPECT_EQ(in_child(r_child_maps, NULL), 0);
+}
+
+static long r_joins_and_maps(void *a)
+{
+ long r = join(PID(a));
+
+ if (r)
+ return r;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_setns_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins_and_maps, &h), 0);
+ reap_holder(h);
+}
+
+static long r_joins_writes_fd(void *a)
+{
+ void **v = a;
+ long r = join(PID(v[0]));
+
+ if (r)
+ return r;
+ return wr(*(int *)v[1], "0 0 1\n");
+}
+
+TEST_F(setfcap, map_opened_in_parent_written_inside)
+{
+ struct holder h;
+ char path[64];
+ void *v[2];
+ int fd;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", h.pid);
+ fd = open(path, O_WRONLY);
+ ASSERT_GE(fd, 0);
+ v[0] = &h;
+ v[1] = &fd;
+ EXPECT_EQ(in_child(r_joins_writes_fd, v), 0);
+ close(fd);
+ reap_holder(h);
+}
+
+static long u_nested_maps_own(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return in_child(r_maps_own, NULL);
+}
+
+TEST_F(setfcap, map_unprivileged_nested)
+{
+ EXPECT_EQ(in_child(u_nested_maps_own, NULL), 0);
+}
+
+static long u_nested_maps_child(void *a)
+{
+ struct holder h;
+ long r;
+
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ h = spawn_holder(HOLDER_ROOT, 0);
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = write_map(h.pid, "0 0 1\n");
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, map_unprivileged_nested_from_parent)
+{
+ EXPECT_EQ(in_child(u_nested_maps_child, NULL), 0);
+}
+
+static long session_to_parent(void *a)
+{
+ if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) < 0 ||
+ syscall(SYS_keyctl, KEYCTL_SESSION_TO_PARENT) < 0)
+ return SETUP_ERROR;
+ return 0;
+}
+
+/* a cred replaced by key_change_session_keyring() keeps what it had */
+static long r_new_session_keyring_maps(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ if (in_child(session_to_parent, NULL))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_session_to_parent)
+{
+ EXPECT_EQ(in_child(r_new_session_keyring_maps, NULL), 0);
+}
+
+/* ---------------------------------------------------------------------- */
+/* File capabilities that are honoured in an ancestor */
+
+static long x_joins_sets_fcap(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_after_setns)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_sets_fcap, &h), -EPERM);
+ reap_holder(h);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+static long x_joins_sets_fcap_rootid5(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", 5);
+}
+
+/* a v3 xattr can name the root user by any uid it has in the namespace */
+TEST_F(setfcap, fcap_after_setns_v3_rootid)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "5 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_sets_fcap_rootid5, &h), -EPERM);
+ reap_holder(h);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* X unshares and R maps "0 0 1" for it from the parent */
+static long x_unshares_r_maps(void *a)
+{
+ int version = *(int *)a;
+ int s1[2], s2[2], res[2], pid;
+ long r = SETUP_ERROR;
+ char c;
+
+ if (pipe(s1) || pipe(s2) || pipe(res))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ restrict_root();
+ if (unshare(CLONE_NEWUSER) || write(s1[1], "u", 1) != 1 ||
+ read(s2[0], &c, 1) != 1)
+ _exit(1);
+ if (version == 2) {
+ /* a v2 xattr on a tmpfs of its own */
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) ||
+ new_file("/mnt/f", 0))
+ r = SETUP_ERROR;
+ else
+ r = set_fcap("/mnt/f", -1);
+ } else {
+ r = set_fcap("/tmp/x", -1);
+ }
+ if (write(res[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(s1[0], &c, 1) != 1 || map_both(pid, "0 0 1\n") ||
+ write(s2[1], "g", 1) != 1 || read(res[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+TEST_F(setfcap, fcap_creator_without_setfcap_parent_mapped)
+{
+ int version = 3;
+
+ EXPECT_EQ(in_child(x_unshares_r_maps, &version), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* the v2 fast path of cap_convert_nscap() */
+TEST_F(setfcap, fcap_v2_creator_without_setfcap_parent_mapped)
+{
+ int version = 2;
+
+ EXPECT_EQ(in_child(x_unshares_r_maps, &version), -EPERM);
+}
+
+/* R maps "5 0 1", gives up CAP_SETFCAP, unshares again */
+static long r_drops_then_nests(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "5 0 1\n"))
+ return SETUP_ERROR;
+ restrict_root();
+ if (set_fcap("/tmp/x", 5) != -EPERM)
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ if (write_map(0, "5 5 1\n"))
+ return -EPERM;
+ write_file(0, "setgroups", "deny");
+ write_file(0, "gid_map", "5 5 1\n");
+ return set_fcap("/tmp/x", 5);
+}
+
+TEST_F(setfcap, fcap_after_dropping_setfcap_and_nesting)
+{
+ EXPECT_EQ(in_child(r_drops_then_nests, NULL), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* X unshares, R maps "0 0 1" for it, and another R joins it */
+static long joiner_takes_ns_reach(void *a)
+{
+ struct holder h;
+ long r;
+
+ h = spawn_mapped(HOLDER_RESTRICTED, "0 0 1\n");
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = join(h.pid);
+ if (!r)
+ r = set_fcap("/tmp/x", -1);
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, fcap_joiner_takes_namespace_reach)
+{
+ EXPECT_EQ(in_child(joiner_takes_ns_reach, NULL), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/*
+ * A v2 xattr on a filesystem whose namespace has no uid 0 has no root user
+ * and is honoured nowhere: refuse it rather than storing it unconverted.
+ */
+static long r_v2_without_uid0(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "1000 0 1\n"))
+ return SETUP_ERROR;
+ /* host uid 0, our uid, is uid 1000 here */
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) || new_file("/mnt/f", 1000))
+ return SETUP_ERROR;
+ return set_fcap("/mnt/f", -1);
+}
+
+TEST_F(setfcap, fcap_v2_without_uid0_in_fs_ns)
+{
+ EXPECT_EQ(in_child(r_v2_without_uid0, NULL), -EINVAL);
+}
+
+/* ... and from the parent namespace, where the writer does have a root user */
+static long r_v2_without_uid0_from_parent(void *a)
+{
+ struct holder *h = a;
+ char path[64];
+
+ snprintf(path, sizeof(path), "/proc/%d/root/mnt/f", h->pid);
+ return set_fcap(path, -1);
+}
+
+TEST_F(setfcap, fcap_v2_without_uid0_from_parent)
+{
+ int ready[2], go[2], mapped[2], pid;
+ struct holder h;
+ char c;
+
+ ASSERT_EQ(pipe(ready), 0);
+ ASSERT_EQ(pipe(go), 0);
+ ASSERT_EQ(pipe(mapped), 0);
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (!pid) {
+ /* host uid 0 is uid 1000 in here, nobody is uid 0 */
+ if (unshare(CLONE_NEWUSER) || write(ready[1], "u", 1) != 1 ||
+ read(mapped[0], &c, 1) != 1 || unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) ||
+ new_file("/mnt/f", 1000) || write(ready[1], "m", 1) != 1)
+ _exit(1);
+ if (read(go[0], &c, 1) < 0)
+ _exit(1);
+ _exit(0);
+ }
+ h.pid = pid;
+ h.go = go[1];
+ ASSERT_EQ(read(ready[0], &c, 1), 1);
+ ASSERT_EQ(map_both(pid, "1000 0 1\n"), 0);
+ ASSERT_EQ(write(mapped[1], "g", 1), 1);
+ ASSERT_EQ(read(ready[0], &c, 1), 1);
+ EXPECT_EQ(in_child(r_v2_without_uid0_from_parent, &h), -EINVAL);
+ reap_holder(h);
+}
+
+/* What has to keep working. */
+
+static long r_maps_sets_fcap(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_own_ns)
+{
+ EXPECT_EQ(in_child(r_maps_sets_fcap, NULL), 0);
+ EXPECT_TRUE(user_gets_sys_admin("/tmp/x"));
+}
+
+static long r_joins_sets_fcap(void *a)
+{
+ long r = join(PID(a));
+
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_after_setns_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins_sets_fcap, &h), 0);
+ reap_holder(h);
+}
+
+static long u_sets_fcap(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return set_fcap("/tmp/u", -1);
+}
+
+TEST_F(setfcap, fcap_unprivileged)
+{
+ EXPECT_EQ(in_child(u_sets_fcap, NULL), 0);
+}
+
+static long u_nested_sets_fcap_inner(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ return set_fcap("/tmp/u", -1);
+}
+
+static long u_nested_sets_fcap(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return in_child(u_nested_sets_fcap_inner, NULL);
+}
+
+TEST_F(setfcap, fcap_unprivileged_nested)
+{
+ EXPECT_EQ(in_child(u_nested_sets_fcap, NULL), 0);
+}
+
+static long u_joins_own_sets_fcap(void *a)
+{
+ long r;
+
+ become_user();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/u", -1);
+}
+
+TEST_F(setfcap, fcap_unprivileged_after_setns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_USER, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(u_joins_own_sets_fcap, &h), 0);
+ reap_holder(h);
+}
+
+static long r_v2_own_fs(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) || new_file("/mnt/f", 0))
+ return SETUP_ERROR;
+ return set_fcap("/mnt/f", -1);
+}
+
+TEST_F(setfcap, fcap_v2_own_ns)
+{
+ EXPECT_EQ(in_child(r_v2_own_fs, NULL), 0);
+}
+
+/* ---------------------------------------------------------------------- */
+/* Idmapped mounts: the root user is both the one seen through the mount */
+/* and the one stored. Mounts that make a container's root host uid 0 are */
+/* up to whoever sets them up. */
+
+struct idmap_case {
+ const char *ns_map, *idmap_map;
+ int file_uid, restricted;
+};
+
+/* returns 1 to skip: no idmapped mounts on tmpfs */
+static int idmap_case(const struct idmap_case *c, long *r)
+{
+ struct holder ns, im;
+ int pid, p[2], st;
+
+ ns = spawn_mapped(HOLDER_ROOT, c->ns_map);
+ if (ns.pid <= 0)
+ return -1;
+ im = c->idmap_map ? spawn_mapped(HOLDER_ROOT, c->idmap_map) : ns;
+ if (im.pid <= 0 || new_file("/tmp/x", c->file_uid))
+ return -1;
+ if (idmap_tmp(im.pid)) {
+ reap_holder(ns);
+ if (c->idmap_map)
+ reap_holder(im);
+ return 1;
+ }
+ if (pipe(p))
+ return -1;
+ /* join from a child of the namespace's holder's sibling: pass the pid */
+ pid = fork();
+ if (!pid) {
+ long res;
+
+ if (c->restricted)
+ restrict_root();
+ res = join(ns.pid);
+ if (!res)
+ res = set_fcap("/mnt/x", 0);
+ if (write(p[1], &res, sizeof(res)) != sizeof(res))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(p[0], r, sizeof(*r)) != sizeof(*r))
+ *r = SETUP_ERROR;
+ waitpid(pid, &st, 0);
+ umount2("/mnt", MNT_DETACH);
+ reap_holder(ns);
+ if (c->idmap_map)
+ reap_holder(im);
+ return 0;
+}
+
+FIXTURE(idmap) {};
+
+FIXTURE_VARIANT(idmap) {
+ struct idmap_case c;
+ long expect;
+};
+
+/* X can't join a namespace that maps host uid 0 to get at the mount */
+FIXTURE_VARIANT_ADD(idmap, reverse_mapping) {
+ .c = { "0 0 1\n", "100000 0 1\n", 100000, 1 },
+ .expect = -EPERM,
+};
+
+/* R in its container writes through the container's own idmapped rootfs */
+FIXTURE_VARIANT_ADD(idmap, container_root) {
+ .c = { "0 100000 1000\n", NULL, 0, 0 },
+ .expect = 0,
+};
+
+/* left to the admin: the container doesn't map host uid 0 */
+FIXTURE_VARIANT_ADD(idmap, container_without_host_root) {
+ .c = { "0 100000 1000\n", NULL, 0, 1 },
+ .expect = 0,
+};
+
+FIXTURE_VARIANT_ADD(idmap, unrelated_idmap) {
+ .c = { "0 100000 1000\n", "200000 100000 1\n", 200000, 1 },
+ .expect = 0,
+};
+
+FIXTURE_SETUP(idmap)
+{
+ if (geteuid())
+ SKIP(return, "needs root");
+ prepare(_metadata);
+}
+
+FIXTURE_TEARDOWN(idmap) {}
+
+TEST_F(idmap, fcap)
+{
+ long r;
+ int ret;
+
+ ret = idmap_case(&variant->c, &r);
+ ASSERT_GE(ret, 0);
+ if (ret == 1)
+ SKIP(return, "no idmapped mounts on tmpfs");
+ EXPECT_EQ(r, variant->expect);
+}
+
+/* ---------------------------------------------------------------------- */
+/* setns() */
+
+static long x_joins(void *a)
+{
+ restrict_root();
+ return join(PID(a));
+}
+
+static long r_joins(void *a)
+{
+ return join(PID(a));
+}
+
+TEST_F(setfcap, setns_ns_mapping_host_root)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, setns_ns_without_map_yet)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* a container that doesn't map host uid 0 */
+TEST_F(setfcap, setns_container)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 100000 1000\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, setns_unprivileged_ns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_USER, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins, &h), 0);
+ reap_holder(h);
+}
+
+/* ---------------------------------------------------------------------- */
+/* ptrace */
+
+static long x_attaches(void *a)
+{
+ restrict_root();
+ return attach_only(PID(a));
+}
+
+static long r_attaches(void *a)
+{
+ return attach_only(PID(a));
+}
+
+TEST_F(setfcap, ptrace_into_ns_without_map_yet)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_into_ns_mapping_host_root)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_into_container)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 100000 1000\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_ns_mapping_only_user)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 1000 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_between_restricted)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_RESTRICTED, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_attaches, &h), 0);
+ reap_holder(h);
+}
+
+static long x_reads_environ(void *a)
+{
+ char path[64];
+ int fd;
+
+ restrict_root();
+ snprintf(path, sizeof(path), "/proc/%d/environ", PID(a));
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+ close(fd);
+ return 0;
+}
+
+/* PTRACE_MODE_READ is unchanged */
+TEST_F(setfcap, ptrace_read_mode_unchanged)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_reads_environ, &h), 0);
+ reap_holder(h);
+}
+
+TEST_HARNESS_MAIN
|
| 3/2 | 2026/10/26 21:06 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 23451 output: 21 thoughts: 683 Thoughts: **Analyzing the Patch for Fuzzing Potential** Okay, let's break down this patch. My initial impression is that it's touching some sensitive areas, specifically around user namespaces and security capabilities. It looks like we're dealing with modifications to the capability handling within user namespaces, which immediately flags it as something that warrants closer inspection from a fuzzing perspective. First, I see the core files being modified: `capability.h`, `user_namespace.h`, `user_namespace.c`, and the security code in `commoncap.c`. It looks like the patch is introducing a "setfcap_level" concept, which is new and, by default, will mean we need to understand how it impacts capability propagation and enforcement. The fact that `cred_setfcap_reaches` and `cred_may_setfcap_userns` are being added also tells me it’s deeply intertwined with credential management and access control. We have new functions like `cap_setfcap_level` and `cap_root_level` in `commoncap.c`, along with modifications to existing functions like `cap_ptrace_access_check`, which makes me think there's been some kind of logic change to the way we handle ptrace in conjunction with the new capabilities. And, the `setfcap_test` in the selftests directory means the developers are aware that this change needs testing. Now, from a fuzzing perspective, the crucial question is reachability. Based on my understanding of the core triage philosophy, this code definitely seems reachable. This touches user namespaces, which are fully accessible from both privileged and unprivileged userspace. The modifications, including the xattr security capability conversion, ptrace checks, and the underlying user/group ID mapping, are all exposed through standard syscalls like `setns`, `unshare`, `clone`, `setxattr`, and `ptrace` and `/proc/*/uid_map`. This checks the box for being accessible in standard virtualized environments like GCE or QEMU. In my experience, these are the types of changes that frequently lead to interesting bugs. Given that this patch affects core subsystems like user namespaces, security credentials, VFS, and potentially the scheduler through ptrace, the "Definitely Worth Fuzzing" flag should be raised immediately. The changes in `kernel/user_namespace.c` regarding the namespace creation and installation are a critical point. The addition of the new checks like `cred_may_setfcap_userns` warrants close scrutiny. I am particularly interested in the `create_user_ns` function, as that will be ground zero for how this change impacts namespaces. I need to get a handle on the interaction between `cap_setfcap_level` and the existing capability mechanisms. The `map_has_id`, `map_root_level`, and `verify_root_map` functions within `kernel/user_namespace.c` seem like the area where this new level is being integrated. My next step is to examine the code in detail, verifying config options and symbols. I will use `grepper` or `read-file` to check the context, particularly focusing on the `setfcap_test` selftest. I need to understand the test cases because that will highlight how the developers are expecting this new functionality to work and where it is intended to be used, and consequently, where it might fail. |
| 4/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "cap_setfcap_level"
}Results: {
"Output": "include/linux/capability.h=223=int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n--\ninclude/linux/capability.h-225-\ninclude/linux/capability.h:226:int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns);\ninclude/linux/capability.h-227-bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n--\ninclude/linux/user_namespace.h=79=struct user_namespace {\n--\ninclude/linux/user_namespace.h-89-\t/* setfcap_level: CAP_SETFCAP held in this ns counts here and in the\ninclude/linux/user_namespace.h:90:\t * ancestors up to the one at this -\u003elevel, see cap_setfcap_level().\ninclude/linux/user_namespace.h-91-\t */\n--\nkernel/user_namespace.c=84=int create_user_ns(struct cred *new)\n--\nkernel/user_namespace.c-127-\nkernel/user_namespace.c:128:\tns-\u003esetfcap_level = cap_setfcap_level(new, parent_ns);\nkernel/user_namespace.c-129-\n--\nsecurity/commoncap.c=124=int cap_capable(const struct cred *cred, struct user_namespace *target_ns,\n--\nsecurity/commoncap.c-134-/**\nsecurity/commoncap.c:135: * cap_setfcap_level - Determine how far up CAP_SETFCAP of a cred reaches\nsecurity/commoncap.c-136- * @cred: The credentials to use\n--\nsecurity/commoncap.c-148- */\nsecurity/commoncap.c:149:int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)\nsecurity/commoncap.c-150-{\n--\nsecurity/commoncap.c=170=bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n--\nsecurity/commoncap.c-172-{\nsecurity/commoncap.c:173:\treturn cap_setfcap_level(cred, ns) \u003c= level;\nsecurity/commoncap.c-174-}\n--\nsecurity/commoncap.c=183=static struct user_namespace *setfcap_top(struct user_namespace *ns)\n--\nsecurity/commoncap.c-206- * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see\nsecurity/commoncap.c:207: * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as\nsecurity/commoncap.c-208- * tasks in @ns can make use of theirs.\n--\nsecurity/commoncap.c=250=int cap_settime(const struct timespec64 *ts, const struct timezone *tz)\n--\nsecurity/commoncap.c-258- * Tasks in a user namespace have CAP_SETFCAP that can count in ancestors of\nsecurity/commoncap.c:259: * the namespace, see cap_setfcap_level(). That is a privilege outside of the\nsecurity/commoncap.c-260- * namespace, so capabilities over the namespace are not enough to take\n"
} |
| 5/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25723 output: 29 thoughts: 67 Thoughts: Here's my thought process, as requested: **Navigating the Kernel Configuration Landscape** Okay, let's get down to brass tacks. I need to figure out the dependencies for `kernel/user_namespace.c`. First instinct? Check the Kconfig. I'm pretty sure it's governed by a config symbol... is it `CONFIG_USER_NS`? That feels right, but let's not assume. To confirm that, I should double check. Where does that module get built? I should check `kernel/Makefile`, that might be sufficient. But to be sure, it’s worth a look at the `security/` directory, especially the `Makefile` there, or potentially even something like `security/commoncap.c`, just in case there's some indirect dependency lurking. It's always good to be thorough when tracking down these config options, you never know where they'll hide! |
| 6/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "user_namespace\\.o",
"PathPrefixes": [
"kernel/Makefile"
]
}Results: {
"Output": "kernel/Makefile=91=obj-$(CONFIG_UTS_NS) += utsname.o\nkernel/Makefile:92:obj-$(CONFIG_USER_NS) += user_namespace.o\nkernel/Makefile-93-obj-$(CONFIG_PID_NS) += pid_namespace.o\n"
} |
| 7/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26096 output: 29 thoughts: 32 Thoughts: Here's my take on those thoughts: **Peering into User Namespaces** Okay, so `CONFIG_USER_NS` is flipped on, which means the `user_namespace.o` module is getting built. My immediate instinct is to dig into the dependencies. Let's head over to `init/Kconfig` – that's usually where the configuration dependencies are laid out. I need to understand what other kernel features or configurations are gating this thing. Are there any prerequisites or conflicts I should be aware of? I'm thinking I'll be looking for `depends on` statements or potentially some `select` statements that might be implicating other parts of the kernel. A quick scan will give me the bigger picture. Understanding these dependencies is crucial, especially when working with user namespaces, as they can interact in interesting ways with other security features. |
| 8/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "config USER_NS",
"PathPrefixes": [
"init/Kconfig"
]
}Results: {
"Output": "init/Kconfig=1443=config IPC_NS\n--\ninit/Kconfig-1450-\ninit/Kconfig:1451:config USER_NS\ninit/Kconfig-1452-\tbool \"User namespace\"\n--\ninit/Kconfig-1464-\ninit/Kconfig:1465:config USER_NS_MAP_KUNIT_TEST\ninit/Kconfig-1466-\ttristate \"KUint test for user namespace map insertion\" if !KUNIT_ALL_TESTS\n"
} |
| 9/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26477 output: 33 thoughts: 17 Thoughts: Okay, let's dive into this. Here's my thought process on the matter: **Analyzing `init/Kconfig` Line 1451** Alright, I'm going to take a look at the `init/Kconfig` file, specifically around line 1451. I'm assuming there's something interesting or pertinent there, and based on the context, I expect to find some configuration option or a relevant dependency definition. I'll be looking for keywords or patterns that relate to initialization procedures or kernel boot-time parameters, especially if we're dealing with something related to drivers, hardware detection, or core system features. My goal is to quickly grasp the intention of that particular section and how it fits into the larger picture of the kernel's configuration options. Let's see what's there. |
| 10/2 | 2026/10/26 21:07 | tool | read-file |
0mArgs:{
"File": "init/Kconfig",
"FirstLine": 1448,
"LineCount": 20
}Results: {
"Contents": "1448:\t\t In this namespace tasks work with IPC ids which correspond to\n1449:\t\t different IPC objects in different namespaces.\n1450:\t\n1451:\tconfig USER_NS\n1452:\t\tbool \"User namespace\"\n1453:\t\tdefault n\n1454:\t\thelp\n1455:\t\t This allows containers, i.e. vservers, to use user namespaces\n1456:\t\t to provide different user info for different servers.\n1457:\t\n1458:\t\t When user namespaces are enabled in the kernel it is\n1459:\t\t recommended that the MEMCG option also be enabled and that\n1460:\t\t user-space use the memory control groups to limit the amount\n1461:\t\t of memory a memory unprivileged users can use.\n1462:\t\n1463:\t\t If unsure, say N.\n1464:\t\n1465:\tconfig USER_NS_MAP_KUNIT_TEST\n1466:\t\ttristate \"KUint test for user namespace map insertion\" if !KUNIT_ALL_TESTS\n1467:\t\tdepends on USER_NS \u0026\u0026 KUNIT\n"
} |
| 11/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27009 output: 26 thoughts: 35 Thoughts: Okay, let's dive into this. Here's how I'd approach this task, as if these were my internal thoughts: **Analyzing Potential Security Vulnerabilities within the Build Process** Right, my initial concern is about the integrity of the build process and potential security implications. Let me see... I need to start with the core files involved. First, I’ll check `security/Makefile` and quickly assess its structure. I need to understand how the security-related components are compiled. Specifically, I'm going to look for how `security/commoncap.c` is handled. The question I need to answer is: Is this file *always* included in the build, or is its compilation conditional? Is it guarded by any configuration options, compile-time flags, or other preprocessor directives? Knowing that will greatly inform how I proceed. If it's always built, it's a constant factor. If it's conditional, then what are the conditions? That's what I have to uncover. |
| 12/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "commoncap",
"PathPrefixes": [
"security/Makefile"
]
}Results: {
"Output": "security/Makefile=6=obj-$(CONFIG_KEYS)\t\t\t+= keys/\n--\nsecurity/Makefile-8-# always enable default capabilities\nsecurity/Makefile:9:obj-y\t\t\t\t\t+= commoncap.o\nsecurity/Makefile-10-obj-$(CONFIG_SECURITY) \t\t\t+= lsm_syscalls.o\n"
} |
| 13/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27367 output: 21 thoughts: 119 Thoughts: **Investigating Capability Conversion in the Kernel** Okay, so `security/commoncap.c` is baked in, `obj-y`, always there. But I know `kernel/user_namespace.c` relies on `CONFIG_USER_NS`, which means there's some interaction there. My immediate thought is, are there *other* configuration options in play that I need to be aware of? I've got to check for any dependencies on related configs. Let's see if the `cap_convert_nscap` function or anything that calls it has conditionals attached to it. Right, in `security/commoncap.c`, I remember `cap_convert_nscap` is crucial for dealing with file capabilities and extended attributes, specifically those related to the `security.capability` xattr. Now I want to determine where `cap_convert_nscap` is actually *used* in the codebase. |
| 14/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "cap_convert_nscap"
}Results: {
"Output": "fs/xattr.c=327=vfs_setxattr(const struct mnt_idmap *idmap, struct dentry *dentry,\n--\nfs/xattr.c-335-\tif (size \u0026\u0026 strcmp(name, XATTR_NAME_CAPS) == 0) {\nfs/xattr.c:336:\t\terror = cap_convert_nscap(idmap, dentry, \u0026value, size);\nfs/xattr.c-337-\t\tif (error \u003c 0)\n--\ninclude/linux/capability.h=219=int get_vfs_caps_from_disk(const struct mnt_idmap *idmap,\n--\ninclude/linux/capability.h-222-\ninclude/linux/capability.h:223:int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\ninclude/linux/capability.h-224-\t\t const void **ivalue, size_t size);\n--\nsecurity/commoncap.c=690=static bool validheader(size_t size, const struct vfs_cap_data *cap)\n--\nsecurity/commoncap.c-695-/**\nsecurity/commoncap.c:696: * cap_convert_nscap - check vfs caps\nsecurity/commoncap.c-697- *\n--\nsecurity/commoncap.c-713- */\nsecurity/commoncap.c:714:int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\nsecurity/commoncap.c-715-\t\t const void **ivalue, size_t size)\n--\nsecurity/commoncap.c=1197=int cap_inode_setxattr(struct dentry *dentry, const char *name,\n--\nsecurity/commoncap.c-1208-\t * For XATTR_NAME_CAPS the check will be done in\nsecurity/commoncap.c:1209:\t * cap_convert_nscap(), called by setxattr()\nsecurity/commoncap.c-1210-\t */\n--\ntools/testing/selftests/namespaces/setfcap_test.c=874=TEST_F(setfcap, fcap_creator_without_setfcap_parent_mapped)\n--\ntools/testing/selftests/namespaces/setfcap_test.c-881-\ntools/testing/selftests/namespaces/setfcap_test.c:882:/* the v2 fast path of cap_convert_nscap() */\ntools/testing/selftests/namespaces/setfcap_test.c-883-TEST_F(setfcap, fcap_v2_creator_without_setfcap_parent_mapped)\n"
} |
| 15/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28401 output: 33 thoughts: 569 Thoughts: **Analyzing Capability Changes in the Kernel** Okay, so `vfs_setxattr` calls `cap_convert_nscap` which is where this all hinges. My immediate focus is on the functions touched by this patch and how they interact. Let's break it down: First, `cap_setfcap_level`. It's non-static, exposed in `linux/capability.h`, and crucially, it's used in `create_user_ns` and `cred_setfcap_reaches`. That's important. It seems to determine or set a "level" related to file capabilities within a user namespace. The call in `create_user_ns` is initializing it for a *new* user namespace. Next, `cred_setfcap_reaches`. Also non-static and in `capability.h`. This one checks if a credential "reaches" a given level, which suggests some sort of capability hierarchy or delegation is at play. It's called from `verify_root_map`, `cred_may_setfcap_userns` and `cap_covers_setfcap`. Now, `cred_may_setfcap_userns`. Non-static again, `capability.h`, and this one dictates who is allowed to *set* the fcap capabilities for a user namespace via the `setns` system call. The `userns_install` function seems pivotal here. Then, there are the ptrace-related functions, `cap_ptrace_access_check` and `cap_ptrace_traceme`. They're directly modified to call `cap_covers_setfcap`. This implies a link between fcap levels and ptrace access control. The most important, of course, is `cap_convert_nscap`. This is where `vfs_setxattr` directs us and it's being modified to call `cap_root_level`. This suggests some sort of conversion or adaptation related to namespace capabilities and where `cap_root_level` seems to determine the root level. Finally, looking at `kernel/user_namespace.c`, we see `verify_root_map`, which is called when mapping uids or gids via `/proc/<pid>/uid_map`. Also, `userns_install` is called when setting the user namespace with `setns`. And `create_user_ns` which is called by `unshare(CLONE_NEWUSER)` or `clone(CLONE_NEWUSER)`. I'm going to look deeper into `verify_root_map` to see exactly what its implications are, especially given its role in mapping uids and gids within the user namespace. I need to understand how the ability to set capabilities influences this mapping. The interactions between these functions must be very specific. |
| 16/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "verify_root_map",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c=906=static int map_root_level(struct user_namespace *parent,\n--\nkernel/user_namespace.c-922-/**\nkernel/user_namespace.c:923: * verify_root_map() - check the uid 0 mapping\nkernel/user_namespace.c-924- * @file: idmapping file\n--\nkernel/user_namespace.c-935- */\nkernel/user_namespace.c:936:static bool verify_root_map(const struct file *file,\nkernel/user_namespace.c-937-\t\t\t struct user_namespace *map_ns,\n--\nkernel/user_namespace.c=1242=static bool new_idmap_permitted(const struct file *file,\n--\nkernel/user_namespace.c-1247-\nkernel/user_namespace.c:1248:\tif (cap_setid == CAP_SETUID \u0026\u0026 !verify_root_map(file, ns, new_map))\nkernel/user_namespace.c-1249-\t\treturn false;\n"
} |
| 17/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29887 output: 31 thoughts: 406 Thoughts: **Analyzing Potential Focus Symbols for User Namespace Security** Okay, so I'm diving into this `new_idmap_permitted` check, and it looks like the caller is `map_write`, which handles writing to `/proc/[pid]/uid_map` and `/proc/[pid]/gid_map`. That's the entry point, the critical handler. Now, I need to figure out the right symbols to focus on, following the FocusSymbols guidelines from Section 4. I need to avoid the obvious, ubiquitous stuff and zero in on the specific feature logic or entrypoints. No memory allocators, page faults, or core sync primitives. I want to look for functions that *specifically* implement this security logic or are direct entrypoints for the user namespace feature. And if a function is static, I'll need to figure out its non-static caller. Alright, let's start by looking at some candidate symbols and whether they are static or non-static. Let's see what we have in `security/commoncap.c`: `cap_setfcap_level`, `cred_setfcap_reaches`, `cred_may_setfcap_userns`, `cap_ptrace_access_check`, `cap_ptrace_traceme`, and `cap_convert_nscap`. Good, they're all non-static. Now, looking at `kernel/user_namespace.c`, I find `create_user_ns` is non-static as well. But, hang on, there's `verify_root_map` which is static, and is called by `new_idmap_permitted`, which is also static, which is called by `map_write`, which is also static. Okay, let's see, what is the `file_operations` for `uid_map`? I should go back to `kernel/user_namespace.c` around `map_write` and confirm the file operations for `/proc/[pid]/uid_map`. |
| 18/2 | 2026/10/26 21:07 | tool | grepper |
0mArgs:{
"Expression": "map_write",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c=983=static int map_parse_u32(char **pos, u32 *res)\n--\nkernel/user_namespace.c-998-\nkernel/user_namespace.c:999:static ssize_t map_write(struct file *file, const char __user *buf,\nkernel/user_namespace.c-1000-\t\t\t size_t count, loff_t *ppos,\n--\nkernel/user_namespace.c-1189-\nkernel/user_namespace.c:1190:ssize_t proc_uid_map_write(struct file *file, const char __user *buf,\nkernel/user_namespace.c-1191-\t\t\t size_t size, loff_t *ppos)\n--\nkernel/user_namespace.c-1202-\nkernel/user_namespace.c:1203:\treturn map_write(file, buf, size, ppos, CAP_SETUID,\nkernel/user_namespace.c-1204-\t\t\t \u0026ns-\u003euid_map, \u0026ns-\u003eparent-\u003euid_map);\n--\nkernel/user_namespace.c-1206-\nkernel/user_namespace.c:1207:ssize_t proc_gid_map_write(struct file *file, const char __user *buf,\nkernel/user_namespace.c-1208-\t\t\t size_t size, loff_t *ppos)\n--\nkernel/user_namespace.c-1219-\nkernel/user_namespace.c:1220:\treturn map_write(file, buf, size, ppos, CAP_SETGID,\nkernel/user_namespace.c-1221-\t\t\t \u0026ns-\u003egid_map, \u0026ns-\u003eparent-\u003egid_map);\n--\nkernel/user_namespace.c-1223-\nkernel/user_namespace.c:1224:ssize_t proc_projid_map_write(struct file *file, const char __user *buf,\nkernel/user_namespace.c-1225-\t\t\t size_t size, loff_t *ppos)\n--\nkernel/user_namespace.c-1237-\t/* Anyone can set any valid project id no capability needed */\nkernel/user_namespace.c:1238:\treturn map_write(file, buf, size, ppos, -1,\nkernel/user_namespace.c-1239-\t\t\t \u0026ns-\u003eprojid_map, \u0026ns-\u003eparent-\u003eprojid_map);\n"
} |
| 19/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31378 output: 34 thoughts: 773 Thoughts: **Focusing on Key Symbols for Capability Handling** Okay, so I'm diving into this patch related to user namespaces and capabilities. My initial thought is to identify the critical functions to focus on. `proc_uid_map_write` pops out because it's public and involved with `/proc/[pid]/uid_map` – that's a key entry point. But is it the best? Wait, hold on, is `create_user_ns` called *everywhere*? No, only when you `clone` or `unshare` with `CLONE_NEWUSER`. So, it's not like a basic memory allocation function. That makes it more interesting for targeted analysis. And `create_user_ns` calls `ns->setfcap_level`, so that's good. Let's see: `proc_uid_map_write` isn't directly modified here, but it calls `verify_root_map`, which *is* static within `kernel/user_namespace.c` and that is called from a chain: `new_idmap_permitted` -> `map_write` -> `proc_uid_map_write`. Alright, the patch adds several new non-static functions in `security/commoncap.c`: `cap_setfcap_level`, `cred_setfcap_reaches`, and `cred_may_setfcap_userns`. That's a clear signal. Plus, it modifies existing ones in the same file: `cap_convert_nscap`, `cap_ptrace_access_check`, and `cap_ptrace_traceme`. And, of course, `create_user_ns` and `proc_uid_map_write` are relevant but are in `kernel/user_namespace.c`. Okay, the guidelines for FocusSymbols are clear: I need to pick functions that *specifically* implement the logic being added or altered, or direct API entrypoints for the feature. And I need to avoid lifecycle wrappers. So, `create_user_ns` and `proc_uid_map_write` are decent because they are the entrypoints to the functions' logic, while also not being used ubiquitously. Now, let me read the code in `security/commoncap.c`, specifically lines 130 to 220, to make sure there are no subtle issues or assertions or loops that I need to be aware of. |
| 20/2 | 2026/10/26 21:07 | tool | read-file |
0mArgs:{
"File": "security/commoncap.c",
"FirstLine": 145,
"LineCount": 80
}Results: {
"Contents": " 145:\t * Return: the -\u003elevel of the topmost namespace, from @ns upwards, for which\n 146:\t * CAP_SETFCAP of @cred counts; @ns-\u003elevel + 1 if it doesn't even count over\n 147:\t * @ns, which includes an @ns that isn't @cred's namespace or a descendant.\n 148:\t */\n 149:\tint cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)\n 150:\t{\n 151:\t\tif (cap_capable(cred, ns, CAP_SETFCAP, CAP_OPT_NOAUDIT) != 0)\n 152:\t\t\treturn ns-\u003elevel + 1;\n 153:\t\n 154:\t\tif (cap_raised(cred-\u003ecap_effective, CAP_SETFCAP))\n 155:\t\t\treturn cred-\u003euser_ns-\u003esetfcap_level;\n 156:\t\n 157:\t\t/* All we have is that we own a child of our namespace. */\n 158:\t\treturn cred-\u003euser_ns-\u003elevel + 1;\n 159:\t}\n 160:\t\n 161:\t/**\n 162:\t * cred_setfcap_reaches - Check how far up CAP_SETFCAP of a cred reaches\n 163:\t * @cred: The credentials to use\n 164:\t * @ns: The user namespace to look from\n 165:\t * @level: The -\u003elevel of the ancestor of @ns it has to count in\n 166:\t *\n 167:\t * Return: true if CAP_SETFCAP of @cred counts in @ns and in its ancestors\n 168:\t * up to the one at @level.\n 169:\t */\n 170:\tbool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n 171:\t\t\t\t int level)\n 172:\t{\n 173:\t\treturn cap_setfcap_level(cred, ns) \u003c= level;\n 174:\t}\n 175:\t\n 176:\t/*\n 177:\t * The topmost ancestor of @ns whose root user tasks in @ns can write file\n 178:\t * capabilities for: within @ns-\u003esetfcap_level, and mapped into @ns, or into\n 179:\t * its parent while @ns has no uid_map yet. NULL if there is none. An\n 180:\t * idmapped mount can store other root users, but that is up to whoever sets\n 181:\t * up the mount.\n 182:\t */\n 183:\tstatic struct user_namespace *setfcap_top(struct user_namespace *ns)\n 184:\t{\n 185:\t\tstruct user_namespace *seen, *p, *top = NULL;\n 186:\t\n 187:\t\tif (ns-\u003esetfcap_level \u003e= ns-\u003elevel)\n 188:\t\t\treturn NULL;\n 189:\t\n 190:\t\tseen = READ_ONCE(ns-\u003euid_map.nr_extents) ? ns : ns-\u003eparent;\n 191:\t\tfor (p = ns-\u003eparent; p; p = p-\u003eparent) {\n 192:\t\t\tif (p-\u003elevel \u003c ns-\u003esetfcap_level)\n 193:\t\t\t\tbreak;\n 194:\t\t\tif (kuid_has_mapping(seen, make_kuid(p, 0)))\n 195:\t\t\t\ttop = p;\n 196:\t\t}\n 197:\t\n 198:\t\treturn top;\n 199:\t}\n 200:\t\n 201:\t/**\n 202:\t * cred_may_setfcap_userns - Check whether a cred covers what a userns can do\n 203:\t * @cred: The credentials to use\n 204:\t * @ns: The user namespace\n 205:\t *\n 206:\t * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see\n 207:\t * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as\n 208:\t * tasks in @ns can make use of theirs.\n 209:\t *\n 210:\t * Return: true if it does.\n 211:\t */\n 212:\tbool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns)\n 213:\t{\n 214:\t\tstruct user_namespace *top = setfcap_top(ns);\n 215:\t\n 216:\t\treturn !top || cred_setfcap_reaches(cred, ns-\u003eparent, top-\u003elevel);\n 217:\t}\n 218:\t\n 219:\t/**\n 220:\t * cap_root_level - Find the topmost namespace in which a kuid is the root user\n 221:\t * @kuid: The kuid to look for\n 222:\t * @ns: The user namespace to start from\n 223:\t *\n 224:\t * Return: the lowest -\u003elevel among @ns and its ancestors in which @kuid is\n"
} |
| 21/2 | 2026/10/26 21:07 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34061 output: 28 thoughts: 1028 Thoughts: **Fuzzing Target Identification: User Namespace Capability Interactions** Okay, here's what's running through my head. I've been looking at how user namespaces and capabilities interact in this kernel code, and it's screaming "fuzz me!" First, I see the core functions involved in capability and user namespace management: `cap_root_level`, `cap_covers_setfcap`, `map_has_id`, `map_root_level`, `verify_root_map`, `userns_install`, `cap_setfcap_level`, `cred_setfcap_reaches`, `setfcap_top`, `cred_may_setfcap_userns`, `cap_ptrace_access_check`, `cap_ptrace_traceme`, and `cap_convert_nscap`. These are all fundamental pieces. They touch how privilege checks and security boundaries work when you're dealing with user namespaces and capabilities. We're talking core stuff here, and it's reachable through standard system calls: `ptrace`, `setns`, `unshare`, `clone`, `setxattr`, and writes to `/proc/pid/uid_map`. Any one of these can trigger these privilege checks. Specifically, I'm noting that `!cap_capable(...)` means "capability is granted", which seems counterintuitive and warrants a second look to ensure the intended logic is correct. Given how integrated this code is with namespace, security, and capability components, it's a prime target for fuzzing. The goal of this kind of fuzzing should be to uncover any possible privilege escalation or unexpected behavior. Now, let's look at the prerequisites. `CONFIG_USER_NS` is essential – we need user namespaces enabled. I've checked and confirmed `kernel/user_namespace.c` is only built with that config option. Capabilities, thankfully, are always built into the Linux kernel; `security/commoncap.c` is `obj-y`. No specific config needed for capability code, that's good! I'll check that `cap_convert_nscap` does not require any additional options. I'll check `fs/xattr.c` to see if there are any build flags associated to capability related code. |
| 22/2 | 2026/10/26 21:08 | tool | grepper |
0mArgs:{
"Expression": "xattr\\.o",
"PathPrefixes": [
"fs/Makefile"
]
}Results: {
"Output": "fs/Makefile=10=obj-y :=\topen.o read_write.o file_table.o super.o \\\n--\nfs/Makefile-13-\t\tattr.o bad_inode.o file.o filesystems.o namespace.o \\\nfs/Makefile:14:\t\tseq_file.o xattr.o libfs.o fs-writeback.o \\\nfs/Makefile-15-\t\tpnode.o splice.o sync.o utimes.o d_path.o \\\n"
} |
| 23/2 | 2026/10/26 21:08 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35734 output: 19 thoughts: 517 Thoughts: **Analyzing User Namespace Dependencies and Functionality** Okay, so `xattr.o` is always built, that's not the issue. I need to figure out the dependencies related to this patch and user namespaces, specifically, what configurations are necessary. Let's start with `CONFIG_USER_NS`. I need to confirm there aren't any other hidden configurations required. The selftests config list gives me a good starting point: `CONFIG_USER_NS=y`, `CONFIG_PID_NS=y`, `CONFIG_NET_NS=y`, `CONFIG_CGROUPS=y`, `CONFIG_TMPFS=y`, `CONFIG_TMPFS_XATTR=y`, and `CONFIG_KEYS=y`. Now, for the core kernel code. I can see `kernel/user_namespace.c` is correctly guarded by `CONFIG_USER_NS`, which is expected. I’ll quickly scan through `user_namespace.c` and `commoncap.c`, looking for relevant `#ifdef` directives. In `include/linux/user_namespace.h` I noticed line 95 has `#ifdef CONFIG_KEYS`, but that's already in place, so that's not a new dependency. So, `CONFIG_USER_NS` looks like the fundamental configuration. Now, let's nail down the essential *functions*. I need to identify the core functions modified or added by the patch that are *specific* to this functionality, not widely used elsewhere. I'm focusing on those: * `cap_setfcap_level` * `cred_setfcap_reaches` * `cred_may_setfcap_userns` * `cap_convert_nscap` * `cap_ptrace_access_check` * `cap_ptrace_traceme` * `proc_uid_map_write` – This one is interesting; it's an entry point for `uid_map` writes, specifically where `verify_root_map`, `map_root_level`, and `map_has_id` get exercised. Wait, I just had a thought. What about `create_user_ns`? That function is key to the *creation* of user namespaces. Let's look at that. Okay, in `kernel/user_namespace.c`, I see `int create_user_ns(struct cred *new)`. The crucial question: is it non-static? Yes, it is! `int create_user_ns(struct cred *new)`. That's important. It's called by `copy_creds` (in `kernel/cred.c`) when `CLONE_NEWUSER` is set in clone/unshare. That's *very* specific to user namespace creation, so that’s definitely a core entry point to analyze. Now let me check if `create_user_ns` is exported or used elsewhere in a meaningful way. |
| 24/2 | 2026/10/26 21:08 | tool | grepper |
0mArgs:{
"Expression": "create_user_ns"
}Results: {
"Output": "include/linux/security.h=541=void security_task_to_inode(struct task_struct *p, struct inode *inode);\ninclude/linux/security.h:542:int security_create_user_ns(const struct cred *cred);\ninclude/linux/security.h-543-int security_ipc_permission(struct kern_ipc_perm *ipcp, short flag);\n--\ninclude/linux/security.h=1426=static inline void security_task_to_inode(struct task_struct *p, struct inode *inode)\n--\ninclude/linux/security.h-1428-\ninclude/linux/security.h:1429:static inline int security_create_user_ns(const struct cred *cred)\ninclude/linux/security.h-1430-{\n--\ninclude/linux/user_namespace.h=180=static inline struct user_namespace *get_user_ns(struct user_namespace *ns)\n--\ninclude/linux/user_namespace.h-186-\ninclude/linux/user_namespace.h:187:extern int create_user_ns(struct cred *new);\ninclude/linux/user_namespace.h-188-extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);\n--\ninclude/linux/user_namespace.h=220=static inline struct user_namespace *get_user_ns(struct user_namespace *ns)\n--\ninclude/linux/user_namespace.h-224-\ninclude/linux/user_namespace.h:225:static inline int create_user_ns(struct cred *new)\ninclude/linux/user_namespace.h-226-{\n--\nkernel/cred.c=263=int copy_creds(struct task_struct *p, u64 clone_flags)\n--\nkernel/cred.c-290-\tif (clone_flags \u0026 CLONE_NEWUSER) {\nkernel/cred.c:291:\t\tret = create_user_ns(new);\nkernel/cred.c-292-\t\tif (ret \u003c 0)\n--\nkernel/user_namespace.c=64=static unsigned long enforced_nproc_rlimit(void)\n--\nkernel/user_namespace.c-83- */\nkernel/user_namespace.c:84:int create_user_ns(struct cred *new)\nkernel/user_namespace.c-85-{\n--\nkernel/user_namespace.c-118-\nkernel/user_namespace.c:119:\tret = security_create_user_ns(new);\nkernel/user_namespace.c-120-\tif (ret \u003c 0)\n--\nkernel/user_namespace.c=175=int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)\n--\nkernel/user_namespace.c-184-\tif (cred) {\nkernel/user_namespace.c:185:\t\terr = create_user_ns(cred);\nkernel/user_namespace.c-186-\t\tif (err)\n--\nsecurity/security.c=3342=void security_task_to_inode(struct task_struct *p, struct inode *inode)\n--\nsecurity/security.c-3347-/**\nsecurity/security.c:3348: * security_create_user_ns() - Check if creating a new userns is allowed\nsecurity/security.c-3349- * @cred: prepared creds\n--\nsecurity/security.c-3354- */\nsecurity/security.c:3355:int security_create_user_ns(const struct cred *cred)\nsecurity/security.c-3356-{\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c=9=static int wait_for_pid(pid_t pid)\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-31- */\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c:32:static int create_user_ns(void)\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-33-{\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c=49=static void test_userns_create_bpf(void)\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-55-\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c:56:\tASSERT_OK(create_user_ns(), \"priv new user ns\");\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-57-\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-59-\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c:60:\tASSERT_EQ(create_user_ns(), EPERM, \"unpriv new user ns\");\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-61-\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c=66=static void test_unpriv_userns_create_no_bpf(void)\n--\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-72-\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c:73:\tASSERT_OK(create_user_ns(), \"no-bpf unpriv new user ns\");\ntools/testing/selftests/bpf/prog_tests/deny_namespace.c-74-\n"
} |
| 25/2 | 2026/10/26 21:08 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38338 output: 32 thoughts: 89 Thoughts: Okay, here's my understanding, tailored for an expert audience like yourself: **User Namespace Creation and Capabilities** Right, so `create_user_ns`... that's the key function called *exclusively* when we're actually creating a new user namespace, either through a `clone` or `unshare` system call with the `CLONE_NEWUSER` flag. It's not some general-purpose lifecycle function we'd see everywhere. My immediate thought is that it's a very specific entry point. It seems to directly engage with the `cap_setfcap_level(new, parent_ns)` call. So, we're setting the capabilities level, which implies we're managing some kind of inherited capability context from the parent namespace. And it looks like it initializes `ns->setfcap_level` as a part of this process. It seems this initialization is key, and sets up how capabilities are handled within the new namespace. Okay, that all makes sense, but what about `userns_install`? I need to get a clear picture of this to truly grasp the whole process. I'll need to go and check out how that one fits into the mix. I need to understand if it's involved in this phase or a subsequent one. |
| 26/2 | 2026/10/26 21:08 | tool | grepper |
0mArgs:{
"Expression": "userns_install",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c=1408=static void userns_put(struct ns_common *ns)\n--\nkernel/user_namespace.c-1412-\nkernel/user_namespace.c:1413:static int userns_install(struct nsset *nsset, struct ns_common *ns)\nkernel/user_namespace.c-1414-{\n--\nkernel/user_namespace.c=1476=const struct proc_ns_operations userns_operations = {\n--\nkernel/user_namespace.c-1479-\t.put\t\t= userns_put,\nkernel/user_namespace.c:1480:\t.install\t= userns_install,\nkernel/user_namespace.c-1481-\t.owner\t\t= userns_owner,\n"
} |
| 27/2 | 2026/10/26 21:08 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 38940 output: 325 thoughts: 945 Thoughts: **Analysis of Kernel Capability Scoping Patch** Okay, let's break this down. My initial observation is that `userns_install` is a good starting point because it's static and referenced via `userns_operations.install`. The fact that `cred_may_setfcap_userns` is directly called by it is a key factor. That gives us a really solid focus. I've reviewed the list of focus symbols: `cap_setfcap_level`, `cred_setfcap_reaches`, `cred_may_setfcap_userns`, `cap_convert_nscap`, `cap_ptrace_access_check`, `cap_ptrace_traceme`, `create_user_ns`, and `proc_uid_map_write`. Now, let's see which ones are worth further scrutiny. None of these look like they're called *everywhere*. `cap_setfcap_level` is tied to user namespace creation or credential checks. `cred_setfcap_reaches` is triggered during `uid_map` writes, ptrace access checks, and `userns_install`. `cred_may_setfcap_userns` is specifically for `setns` operations. `cap_convert_nscap` is just about `setxattr`. `cap_ptrace_access_check` is focused on attach/access checks for `ptrace`, and `cap_ptrace_traceme` is just for `PTRACE_TRACEME`. `create_user_ns` is only when creating a new user namespace. `proc_uid_map_write` is specific to writing to `/proc/<pid>/uid_map`. All of these appear to be very specific entrypoints. So, the key configuration flag is `CONFIG_USER_NS`, which makes sense because `setns` and `CLONE_NEWUSER` depend on it. `security/commoncap.c`, capabilities, and ptrace are standard, and extended attributes are also standard. `USER_NS` is clearly the gate. Essentially, the patch fundamentally changes how `CAP_SETFCAP` is handled in nested user namespaces. It's no longer a simple boolean; it's an integer level, `setfcap_level`. This impacts `create_user_ns`, `/proc/<pid>/uid_map` validation, `setns`, the ptrace checks, and the file capability setting. The core logic is touched by standard syscalls like `clone`, `unshare`, `/proc/[pid]/uid_map` writes, `setns`, `setxattr`, and `ptrace`. Given all of this, fuzzing is absolutely critical. We need to vigorously test for any logic errors, privilege escalation opportunities, or violations in how nested user namespaces and capability checks interact. This is all very clear. I think it's time to set the results. |
| 28/2 | 2026/10/26 21:08 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"USER_NS"
],
"FocusSymbols": [
"cap_setfcap_level",
"cred_setfcap_reaches",
"cred_may_setfcap_userns",
"cap_convert_nscap",
"cap_ptrace_access_check",
"cap_ptrace_traceme",
"create_user_ns",
"proc_uid_map_write"
],
"Reasoning": "The patch refactors and extends how CAP_SETFCAP is tracked and checked across nested user namespaces. Instead of a single boolean `parent_could_setfcap`, it introduces hierarchical level tracking (`setfcap_level`) and enforces capability bounds across `setns` (`userns_install`), ptrace access (`cap_ptrace_access_check`, `cap_ptrace_traceme`), idmap validation (`verify_root_map`, `map_root_level`, `map_has_id`), and xattr capability conversion (`cap_convert_nscap`). All of these modifications are in core user namespace and security capability subsystems and are reachable through standard syscalls (clone/unshare, ptrace, setns, setxattr, and /proc/pid/uid_map writes). Fuzzing is warranted to verify that nested namespace relationships, mapping checks, and capability boundaries do not introduce privilege bypasses, out-of-bounds access, or assertion failures.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"USER_NS"
],
"FocusSymbols": [
"cap_setfcap_level",
"cred_setfcap_reaches",
"cred_may_setfcap_userns",
"cap_convert_nscap",
"cap_ptrace_access_check",
"cap_ptrace_traceme",
"create_user_ns",
"proc_uid_map_write"
],
"Reasoning": "The patch refactors and extends how CAP_SETFCAP is tracked and checked across nested user namespaces. Instead of a single boolean `parent_could_setfcap`, it introduces hierarchical level tracking (`setfcap_level`) and enforces capability bounds across `setns` (`userns_install`), ptrace access (`cap_ptrace_access_check`, `cap_ptrace_traceme`), idmap validation (`verify_root_map`, `map_root_level`, `map_has_id`), and xattr capability conversion (`cap_convert_nscap`). All of these modifications are in core user namespace and security capability subsystems and are reachable through standard syscalls (clone/unshare, ptrace, setns, setxattr, and /proc/pid/uid_map writes). Fuzzing is warranted to verify that nested namespace relationships, mapping checks, and capability boundaries do not introduce privilege bypasses, out-of-bounds access, or assertion failures.",
"WorthFuzzing": true
} |
| 29/1 | 2026/10/26 21:08 | action | If |
1mArgs:{
"WorthFuzzing": true
}Results: null |
| 30/2 | 2026/10/26 21:08 | agent | kmsan-evaluator |
1mModel:core Args: null Results: {
"KMSANReasoning": "The patch series tightens capability checks related to CAP_SETFCAP in nested user namespaces, ptrace access checks, and file capability conversions on idmapped/non-idmapped mounts.\n\nAnalysis of memory initialization and safety:\n1. Struct user_namespace changes: Replaced the 'parent_could_setfcap' boolean field with 'setfcap_level' integer. Struct user_namespace is allocated with kmem_cache_zalloc (fully zeroed) and explicitly initialized in create_user_ns() as well as statically initialized to 0 for init_user_ns. Furthermore, struct user_namespace is internal kernel state and never copied to user space.\n2. Local variables and control flow: In all newly introduced helper functions (map_has_id, map_root_level, setfcap_top, cap_root_level, cap_setfcap_level, cred_setfcap_reaches, cred_may_setfcap_userns, cap_covers_setfcap), all local variables and function parameters are fully initialized before use.\n3. User copying / info-leaks: No data structures, buffers, or padding bytes are exposed or copied to userspace.\n4. Existing buffers / bounds checks: uid_gid_map structures processed in map_has_id and map_root_level are cleared via memset prior to extent population in map_write().\n\nAny potential issues arising from this patch would involve logical authorization bugs, permission checks, or potential pointer dereferences, which fall under logic testing or standard KASAN bug detectors rather than uninitialized memory detection. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 543756ccee5549bf199f9931395f781384962df6
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Oct 26 21:06:57 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/capability.h b/include/linux/capability.h
index 622137f66f0928..e4199b03668bdc 100644
--- a/include/linux/capability.h
+++ b/include/linux/capability.h
@@ -34,6 +34,7 @@ struct cpu_vfs_cap_data {
#define _USER_CAP_HEADER_SIZE (sizeof(struct __user_cap_header_struct))
#define _KERNEL_CAP_T_SIZE (sizeof(kernel_cap_t))
+struct cred;
struct file;
struct inode;
struct dentry;
@@ -222,4 +223,9 @@ int get_vfs_caps_from_disk(const struct mnt_idmap *idmap,
int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,
const void **ivalue, size_t size);
+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns);
+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,
+ int level);
+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns);
+
#endif /* !_LINUX_CAPABILITY_H */
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d8d..f3753b6b6d29f7 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -86,9 +86,10 @@ struct user_namespace {
kgid_t group;
struct ns_common ns;
unsigned long flags;
- /* parent_could_setfcap: true if the creator if this ns had CAP_SETFCAP
- * in its effective capability set at the child ns creation time. */
- bool parent_could_setfcap;
+ /* setfcap_level: CAP_SETFCAP held in this ns counts here and in the
+ * ancestors up to the one at this ->level, see cap_setfcap_level().
+ */
+ int setfcap_level;
#ifdef CONFIG_KEYS
/* List of joinable keyrings in this namespace. Modification access of
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index 50c374ed4687be..db078dd6406aa8 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -125,7 +125,7 @@ int create_user_ns(struct cred *new)
if (!ns)
goto fail_dec;
- ns->parent_could_setfcap = cap_raised(new->cap_effective, CAP_SETFCAP);
+ ns->setfcap_level = cap_setfcap_level(new, parent_ns);
ret = ns_common_init(ns);
if (ret)
@@ -881,15 +881,55 @@ VISIBLE_IF_KUNIT int uid_gid_map_sort(struct uid_gid_map *map)
}
EXPORT_SYMBOL_IF_KUNIT(uid_gid_map_sort);
+static bool map_has_id(struct uid_gid_map *map, u32 id)
+{
+ struct uid_gid_extent *extent;
+ int idx;
+
+ for (idx = 0; idx < map->nr_extents; idx++) {
+ if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
+ extent = &map->extent[idx];
+ else
+ extent = &map->forward[idx];
+ if (id >= extent->lower_first &&
+ id - extent->lower_first < extent->count)
+ return true;
+ }
+
+ return false;
+}
+
+/*
+ * The lowest ->level among @parent and its ancestors whose root user @new_map
+ * maps, whatever uid that root user has in @parent; INT_MAX if there is none.
+ */
+static int map_root_level(struct user_namespace *parent,
+ struct uid_gid_map *new_map)
+{
+ struct user_namespace *p;
+ int level = INT_MAX;
+ uid_t id;
+
+ for (p = parent; p; p = p->parent) {
+ id = from_kuid(parent, make_kuid(p, 0));
+ if (id != (uid_t)-1 && map_has_id(new_map, id))
+ level = p->level;
+ }
+
+ return level;
+}
+
/**
* verify_root_map() - check the uid 0 mapping
* @file: idmapping file
* @map_ns: user namespace of the target process
* @new_map: requested idmap
*
- * If a process requests mapping parent uid 0 into the new ns, verify that the
- * process writing the map had the CAP_SETFCAP capability as the target process
- * will be able to write fscaps that are valid in ancestor user namespaces.
+ * If a process requests mapping the root user of the parent ns, or of one of
+ * its ancestors, into the new ns, verify that the process that opened the map
+ * file and the process writing the map had the CAP_SETFCAP capability as the
+ * target process will be able to write fscaps that are valid in ancestor user
+ * namespaces.
*
* Return: true if the mapping is allowed, false if not.
*/
@@ -897,42 +937,43 @@ static bool verify_root_map(const struct file *file,
struct user_namespace *map_ns,
struct uid_gid_map *new_map)
{
- int idx;
const struct user_namespace *file_ns = file->f_cred->user_ns;
- struct uid_gid_extent *extent0 = NULL;
-
- for (idx = 0; idx < new_map->nr_extents; idx++) {
- if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
- extent0 = &new_map->extent[idx];
- else
- extent0 = &new_map->forward[idx];
- if (extent0->lower_first == 0)
- break;
+ int level;
- extent0 = NULL;
- }
-
- if (!extent0)
+ level = map_root_level(map_ns->parent, new_map);
+ if (level == INT_MAX)
return true;
if (map_ns == file_ns) {
/* The process unshared its ns and is writing to its own
* /proc/self/uid_map. User already has full capabilites in
- * the new namespace. Verify that the parent had CAP_SETFCAP
- * when it unshared.
+ * the new namespace. Verify that it still has CAP_SETFCAP
+ * there, and that the parent had it when it unshared, as far up
+ * as those root users go.
* */
- if (!file_ns->parent_could_setfcap)
+ if (!file_ns_capable(file, map_ns, CAP_SETFCAP) ||
+ file_ns->setfcap_level > level)
return false;
} else {
/* Process p1 is writing to uid_map of p2, who is in a child
* user namespace to p1's. Verify that the opener of the map
* file has CAP_SETFCAP against the parent of the new map
- * namespace */
- if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP))
+ * namespace, and as far up as those root users go.
+ */
+ if (!file_ns_capable(file, map_ns->parent, CAP_SETFCAP) ||
+ !cred_setfcap_reaches(file->f_cred, map_ns->parent, level))
return false;
}
- return true;
+ /* The file may have been handed to someone else since it was opened,
+ * so the same goes for the process that is doing the write.
+ */
+ if (map_ns == current_user_ns())
+ return ns_capable(map_ns, CAP_SETFCAP) &&
+ map_ns->setfcap_level <= level;
+
+ return ns_capable(map_ns->parent, CAP_SETFCAP) &&
+ cred_setfcap_reaches(current_cred(), map_ns->parent, level);
}
/*
@@ -1390,6 +1431,12 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
+ /* Tasks in the namespace may have CAP_SETFCAP that counts outside of
+ * it, so only let in tasks whose own counts as far.
+ */
+ if (!cred_may_setfcap_userns(current_cred(), user_ns))
+ return -EPERM;
+
cred = nsset_cred(nsset);
if (!cred)
return -EINVAL;
diff --git a/security/commoncap.c b/security/commoncap.c
index d47ab30223435b..91ed4a5f4b2503 100644
--- a/security/commoncap.c
+++ b/security/commoncap.c
@@ -131,6 +131,114 @@ int cap_capable(const struct cred *cred, struct user_namespace *target_ns,
return ret;
}
+/**
+ * cap_setfcap_level - Determine how far up CAP_SETFCAP of a cred reaches
+ * @cred: The credentials to use
+ * @ns: The user namespace to look from
+ *
+ * File capabilities belong to the kuid of a namespace's root user, and the
+ * same kuid can be the root user of ancestors of that namespace. Every task
+ * gets CAP_SETFCAP when it enters a user namespace, so having it there says
+ * nothing about those ancestors. user_ns->setfcap_level does: it is taken
+ * from the creator when the namespace is created.
+ *
+ * Return: the ->level of the topmost namespace, from @ns upwards, for which
+ * CAP_SETFCAP of @cred counts; @ns->level + 1 if it doesn't even count over
+ * @ns, which includes an @ns that isn't @cred's namespace or a descendant.
+ */
+int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)
+{
+ if (cap_capable(cred, ns, CAP_SETFCAP, CAP_OPT_NOAUDIT) != 0)
+ return ns->level + 1;
+
+ if (cap_raised(cred->cap_effective, CAP_SETFCAP))
+ return cred->user_ns->setfcap_level;
+
+ /* All we have is that we own a child of our namespace. */
+ return cred->user_ns->level + 1;
+}
+
+/**
+ * cred_setfcap_reaches - Check how far up CAP_SETFCAP of a cred reaches
+ * @cred: The credentials to use
+ * @ns: The user namespace to look from
+ * @level: The ->level of the ancestor of @ns it has to count in
+ *
+ * Return: true if CAP_SETFCAP of @cred counts in @ns and in its ancestors
+ * up to the one at @level.
+ */
+bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,
+ int level)
+{
+ return cap_setfcap_level(cred, ns) <= level;
+}
+
+/*
+ * The topmost ancestor of @ns whose root user tasks in @ns can write file
+ * capabilities for: within @ns->setfcap_level, and mapped into @ns, or into
+ * its parent while @ns has no uid_map yet. NULL if there is none. An
+ * idmapped mount can store other root users, but that is up to whoever sets
+ * up the mount.
+ */
+static struct user_namespace *setfcap_top(struct user_namespace *ns)
+{
+ struct user_namespace *seen, *p, *top = NULL;
+
+ if (ns->setfcap_level >= ns->level)
+ return NULL;
+
+ seen = READ_ONCE(ns->uid_map.nr_extents) ? ns : ns->parent;
+ for (p = ns->parent; p; p = p->parent) {
+ if (p->level < ns->setfcap_level)
+ break;
+ if (kuid_has_mapping(seen, make_kuid(p, 0)))
+ top = p;
+ }
+
+ return top;
+}
+
+/**
+ * cred_may_setfcap_userns - Check whether a cred covers what a userns can do
+ * @cred: The credentials to use
+ * @ns: The user namespace
+ *
+ * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see
+ * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as
+ * tasks in @ns can make use of theirs.
+ *
+ * Return: true if it does.
+ */
+bool cred_may_setfcap_userns(const struct cred *cred, struct user_namespace *ns)
+{
+ struct user_namespace *top = setfcap_top(ns);
+
+ return !top || cred_setfcap_reaches(cred, ns->parent, top->level);
+}
+
+/**
+ * cap_root_level - Find the topmost namespace in which a kuid is the root user
+ * @kuid: The kuid to look for
+ * @ns: The user namespace to start from
+ *
+ * Return: the lowest ->level among @ns and its ancestors in which @kuid is
+ * uid 0, which is how far up file capabilities with that root user are
+ * honoured; INT_MAX if there is no such namespace.
+ */
+static int cap_root_level(kuid_t kuid, struct user_namespace *ns)
+{
+ int level = INT_MAX;
+
+ for (;; ns = ns->parent) {
+ if (from_kuid(ns, kuid) == 0)
+ level = ns->level;
+ if (ns == &init_user_ns)
+ break;
+ }
+
+ return level;
+}
+
/**
* cap_settime - Determine whether the current process may set the system clock
* @ts: The time to set
@@ -146,14 +254,41 @@ int cap_settime(const struct timespec64 *ts, const struct timezone *tz)
return 0;
}
+/*
+ * Tasks in a user namespace have CAP_SETFCAP that can count in ancestors of
+ * the namespace, see cap_setfcap_level(). That is a privilege outside of the
+ * namespace, so capabilities over the namespace are not enough to take
+ * control of such a task.
+ */
+static bool cap_covers_setfcap(const struct cred *cred,
+ const struct cred *child_cred)
+{
+ struct user_namespace *ns = child_cred->user_ns, *top;
+
+ /* setns() only lets in tasks whose CAP_SETFCAP reaches as far. */
+ if (cred->user_ns == ns)
+ return true;
+
+ top = setfcap_top(ns);
+ if (!top)
+ return true;
+
+ /* CAP_SYS_PTRACE up there gives control of tasks with CAP_SETFCAP. */
+ return cred_setfcap_reaches(cred, ns->parent, top->level) ||
+ !cap_capable(cred, top, CAP_SYS_PTRACE, CAP_OPT_NOAUDIT);
+}
+
/**
* cap_ptrace_access_check - Determine whether the current process may access
* another
* @child: The process to be accessed
* @mode: The mode of attachment.
*
- * If we are in the same or an ancestor user_ns and have all the target
- * task's capabilities, then ptrace access is allowed.
+ * For PTRACE_MODE_ATTACH, if the target task may make use of CAP_SETFCAP in
+ * an ancestor of its user_ns that our CAP_SETFCAP or CAP_SYS_PTRACE doesn't
+ * reach, then ptrace access is denied.
+ * Otherwise, if we are in the same or an ancestor user_ns and have all the
+ * target task's capabilities, then ptrace access is allowed.
* If we have the ptrace capability to the target user_ns, then ptrace
* access is allowed.
* Else denied.
@@ -174,11 +309,15 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
caller_caps = &cred->cap_effective;
else
caller_caps = &cred->cap_permitted;
+ if ((mode & PTRACE_MODE_ATTACH) &&
+ !cap_covers_setfcap(cred, child_cred))
+ goto deny;
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, *caller_caps))
goto out;
if (ns_capable(child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
+deny:
ret = -EPERM;
out:
rcu_read_unlock();
@@ -189,8 +328,11 @@ int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
* cap_ptrace_traceme - Determine whether another process may trace the current
* @parent: The task proposed to be the tracer
*
- * If parent is in the same or an ancestor user_ns and has all current's
- * capabilities, then ptrace access is allowed.
+ * If current may make use of CAP_SETFCAP in an ancestor of its user_ns that
+ * parent's CAP_SETFCAP or CAP_SYS_PTRACE doesn't reach, then ptrace access
+ * is denied.
+ * Otherwise, if parent is in the same or an ancestor user_ns and has all
+ * current's capabilities, then ptrace access is allowed.
* If parent has the ptrace capability to current's user_ns, then ptrace
* access is allowed.
* Else denied.
@@ -206,11 +348,14 @@ int cap_ptrace_traceme(struct task_struct *parent)
rcu_read_lock();
cred = __task_cred(parent);
child_cred = current_cred();
+ if (!cap_covers_setfcap(cred, child_cred))
+ goto deny;
if (cred->user_ns == child_cred->user_ns &&
cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
goto out;
if (has_ns_capability(parent, child_cred->user_ns, CAP_SYS_PTRACE))
goto out;
+deny:
ret = -EPERM;
out:
rcu_read_unlock();
@@ -586,19 +731,46 @@ int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,
return -EINVAL;
if (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))
return -EPERM;
- if (size == XATTR_CAPS_SZ_2 && (idmap == &nop_mnt_idmap))
- if (ns_capable(inode->i_sb->s_user_ns, CAP_SETFCAP))
+ /*
+ * A v2 xattr belongs to the root user of the filesystem's namespace,
+ * which may be the root user of ancestors of our namespace as well.
+ * There may be none, then nobody could ever run the file with these
+ * capabilities. Only write it unconverted if that root user is
+ * within reach, the checks below handle everything else.
+ */
+ if (size == XATTR_CAPS_SZ_2 && idmap == &nop_mnt_idmap &&
+ ns_capable(fs_ns, CAP_SETFCAP)) {
+ kuid_t fsroot = make_kuid(fs_ns, 0);
+
+ if (!uid_valid(fsroot))
+ return -EINVAL;
+ if (cap_root_level(fsroot, task_ns) >= task_ns->setfcap_level)
/* user is privileged, just write the v2 */
return size;
+ }
vfsrootid = rootid_from_xattr(*ivalue, size, task_ns);
if (!vfsuid_valid(vfsrootid))
return -EINVAL;
+ /*
+ * The root user may be the root user of ancestors of our namespace as
+ * well. CAP_SETFCAP that we got for entering it doesn't cover those.
+ * On an idmapped mount the root user is vfsrootid as seen through
+ * this mount and rootid as seen through every other mount of the
+ * filesystem, so both have to stay within reach.
+ */
+ if (cap_root_level(vfsuid_into_kuid(vfsrootid), task_ns) <
+ task_ns->setfcap_level)
+ return -EPERM;
+
rootid = from_vfsuid(idmap, fs_ns, vfsrootid);
if (!uid_valid(rootid))
return -EINVAL;
+ if (cap_root_level(rootid, task_ns) < task_ns->setfcap_level)
+ return -EPERM;
+
nsrootid = from_kuid(fs_ns, rootid);
if (nsrootid == -1)
return -EINVAL;
diff --git a/tools/testing/selftests/namespaces/Makefile b/tools/testing/selftests/namespaces/Makefile
index 9b22d12708e1aa..0455b6544869d1 100644
--- a/tools/testing/selftests/namespaces/Makefile
+++ b/tools/testing/selftests/namespaces/Makefile
@@ -14,7 +14,8 @@ TEST_GEN_PROGS := nsid_test \
stress_test \
listns_pagination_bug \
regression_pidfd_setns_test \
- uid_map_range_test
+ uid_map_range_test \
+ setfcap_test
include ../lib.mk
diff --git a/tools/testing/selftests/namespaces/config b/tools/testing/selftests/namespaces/config
index d09836260262f4..dfbabc35cd8a12 100644
--- a/tools/testing/selftests/namespaces/config
+++ b/tools/testing/selftests/namespaces/config
@@ -5,3 +5,6 @@ CONFIG_USER_NS=y
CONFIG_PID_NS=y
CONFIG_NET_NS=y
CONFIG_CGROUPS=y
+CONFIG_TMPFS=y
+CONFIG_TMPFS_XATTR=y
+CONFIG_KEYS=y
diff --git a/tools/testing/selftests/namespaces/setfcap_test.c b/tools/testing/selftests/namespaces/setfcap_test.c
new file mode 100644
index 00000000000000..0a82b239b36856
--- /dev/null
+++ b/tools/testing/selftests/namespaces/setfcap_test.c
@@ -0,0 +1,1362 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Who may map the root user of an ancestor user namespace, write file
+ * capabilities that are honoured in an ancestor, join a namespace whose
+ * tasks may do so, or take control of such a task.
+ *
+ * "R" is a task with uid 0 and all capabilities in the initial namespace,
+ * "X" one with uid 0 that gave up CAP_SETFCAP and CAP_SYS_PTRACE in its
+ * permitted, effective and bounding sets, and "U" is uid 1000.
+ *
+ * Every test runs in a private mount namespace with a tmpfs on /tmp.
+ */
+#define _GNU_SOURCE
+#include <endian.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/wait.h>
+#include <sys/xattr.h>
+#include <linux/capability.h>
+#include <linux/keyctl.h>
+#include <linux/mount.h>
+
+#include "kselftest_harness.h"
+
+#ifndef __NR_pidfd_open
+#define __NR_pidfd_open 434
+#endif
+#ifndef __NR_pidfd_getfd
+#define __NR_pidfd_getfd 438
+#endif
+#ifndef __NR_open_tree
+#define __NR_open_tree 428
+#endif
+#ifndef __NR_move_mount
+#define __NR_move_mount 429
+#endif
+#ifndef __NR_mount_setattr
+#define __NR_mount_setattr 442
+#endif
+
+/* Exit codes of a copy of this program run with SETFCAP_TEST_CAPS set. */
+#define CAPS_HAS_SYS_ADMIN 42
+#define CAPS_NO_SYS_ADMIN 43
+
+/* A step that wasn't the one under test went wrong. */
+#define SETUP_ERROR (-1000)
+
+static int capget_v3(struct __user_cap_data_struct d[2])
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+
+ return syscall(SYS_capget, &h, d);
+}
+
+__attribute__((constructor)) static void report_caps(void)
+{
+ struct __user_cap_data_struct d[2];
+
+ if (!getenv("SETFCAP_TEST_CAPS"))
+ return;
+ if (capget_v3(d))
+ _exit(1);
+ _exit(d[0].effective & (1u << CAP_SYS_ADMIN) ?
+ CAPS_HAS_SYS_ADMIN : CAPS_NO_SYS_ADMIN);
+}
+
+/* X: uid 0 without CAP_SETFCAP and CAP_SYS_PTRACE */
+static void restrict_root(void)
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+ struct __user_cap_data_struct d[2];
+ unsigned int drop = (1u << CAP_SETFCAP) | (1u << CAP_SYS_PTRACE);
+
+ if (prctl(PR_CAPBSET_DROP, CAP_SETFCAP) ||
+ prctl(PR_CAPBSET_DROP, CAP_SYS_PTRACE) || capget_v3(d))
+ _exit(99);
+ d[0].effective &= ~drop;
+ d[0].permitted &= ~drop;
+ if (syscall(SYS_capset, &h, d))
+ _exit(99);
+}
+
+/* Give up CAP_SETFCAP only in the permitted and effective set. */
+static void drop_setfcap_keep_bset(void)
+{
+ struct __user_cap_header_struct h = { _LINUX_CAPABILITY_VERSION_3, 0 };
+ struct __user_cap_data_struct d[2];
+
+ if (capget_v3(d))
+ _exit(99);
+ d[0].effective &= ~(1u << CAP_SETFCAP);
+ d[0].permitted &= ~(1u << CAP_SETFCAP);
+ if (syscall(SYS_capset, &h, d))
+ _exit(99);
+}
+
+static void become_user(void)
+{
+ if (setresgid(1000, 1000, 1000) || setresuid(1000, 1000, 1000))
+ _exit(99);
+ prctl(PR_SET_DUMPABLE, 1);
+}
+
+static long wr(int fd, const char *s)
+{
+ long r = write(fd, s, strlen(s));
+
+ return r < 0 ? -errno : 0;
+}
+
+static long write_file(int pid, const char *name, const char *s)
+{
+ char path[64];
+ long r;
+ int fd;
+
+ if (pid)
+ snprintf(path, sizeof(path), "/proc/%d/%s", pid, name);
+ else
+ snprintf(path, sizeof(path), "/proc/self/%s", name);
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return -errno;
+ r = wr(fd, s);
+ close(fd);
+ return r;
+}
+
+static long write_map(int pid, const char *map)
+{
+ return write_file(pid, "uid_map", map);
+}
+
+/* both maps, as the setup for a test rather than its subject */
+static long map_both(int pid, const char *map)
+{
+ if (write_map(pid, map) || write_file(pid, "setgroups", "deny") ||
+ write_file(pid, "gid_map", map))
+ return SETUP_ERROR;
+ return 0;
+}
+
+/* what an unprivileged user does after unshare(CLONE_NEWUSER) */
+static long map_user(void)
+{
+ return map_both(0, "0 1000 1\n");
+}
+
+static long join(int pid)
+{
+ char path[64];
+ int fd, r;
+
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return SETUP_ERROR;
+ r = setns(fd, CLONE_NEWUSER);
+ close(fd);
+ return r ? -errno : 0;
+}
+
+/* security.capability with CAP_SYS_ADMIN in permitted and effective; v2 if rootid < 0 */
+static long set_fcap(const char *path, int rootid)
+{
+ struct vfs_ns_cap_data d;
+ int v3 = rootid >= 0;
+
+ memset(&d, 0, sizeof(d));
+ d.magic_etc = htole32((v3 ? VFS_CAP_REVISION_3 : VFS_CAP_REVISION_2) |
+ VFS_CAP_FLAGS_EFFECTIVE);
+ d.data[0].permitted = htole32(1u << CAP_SYS_ADMIN);
+ d.rootid = htole32(rootid);
+ if (setxattr(path, "security.capability", &d,
+ v3 ? XATTR_CAPS_SZ_3 : XATTR_CAPS_SZ_2, 0))
+ return -errno;
+ return 0;
+}
+
+/* a copy of this program, owned by uid */
+static int new_file(const char *path, int uid)
+{
+ char buf[65536];
+ int in, out;
+ ssize_t n;
+
+ unlink(path);
+ in = open("/proc/self/exe", O_RDONLY);
+ out = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
+ if (in < 0 || out < 0)
+ return -1;
+ while ((n = read(in, buf, sizeof(buf))) > 0)
+ if (write(out, buf, n) != n)
+ return -1;
+ if (fchown(out, uid, uid) || fchmod(out, 0755))
+ return -1;
+ close(in);
+ close(out);
+ return 0;
+}
+
+/* Does U get CAP_SYS_ADMIN from the file capabilities of path? */
+static int user_gets_sys_admin(const char *path)
+{
+ int pid, st;
+
+ pid = fork();
+ if (!pid) {
+ become_user();
+ setenv("SETFCAP_TEST_CAPS", "1", 1);
+ execl(path, path, NULL);
+ _exit(1);
+ }
+ waitpid(pid, &st, 0);
+ return WIFEXITED(st) && WEXITSTATUS(st) == CAPS_HAS_SYS_ADMIN;
+}
+
+/* run fn in a child and return what it returns */
+static long in_child(long (*fn)(void *), void *arg)
+{
+ int p[2], pid;
+ long r = SETUP_ERROR;
+
+ if (pipe(p))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ r = fn(arg);
+ if (write(p[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ close(p[1]);
+ if (read(p[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ close(p[0]);
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+/* A task that unshares a user namespace and waits. */
+struct holder {
+ int pid, go;
+};
+
+enum holder_kind {
+ HOLDER_ROOT, /* R */
+ HOLDER_RESTRICTED, /* X */
+ HOLDER_USER, /* U, maps "0 1000 1" itself */
+};
+
+static struct holder spawn_holder(enum holder_kind kind, int map_fd_at)
+{
+ struct holder h = { -1, -1 };
+ int ready[2], go[2];
+ char c;
+
+ if (pipe(ready) || pipe(go))
+ return h;
+ h.pid = fork();
+ if (!h.pid) {
+ close(ready[0]);
+ close(go[1]);
+ if (kind == HOLDER_RESTRICTED)
+ restrict_root();
+ if (kind == HOLDER_USER)
+ become_user();
+ if (unshare(CLONE_NEWUSER))
+ _exit(1);
+ if (kind == HOLDER_USER && map_user())
+ _exit(1);
+ if (map_fd_at)
+ dup2(open("/proc/self/uid_map", O_WRONLY), map_fd_at);
+ if (write(ready[1], "r", 1) != 1)
+ _exit(1);
+ if (read(go[0], &c, 1) < 0)
+ _exit(1);
+ _exit(0);
+ }
+ close(ready[1]);
+ close(go[0]);
+ if (read(ready[0], &c, 1) != 1)
+ h.pid = -1;
+ close(ready[0]);
+ h.go = go[1];
+ return h;
+}
+
+/* ... whose maps are written from the parent namespace by the caller */
+static struct holder spawn_mapped(enum holder_kind kind, const char *map)
+{
+ struct holder h = spawn_holder(kind, 0);
+
+ if (h.pid > 0 && map_both(h.pid, map))
+ h.pid = -1;
+ return h;
+}
+
+static void reap_holder(struct holder h)
+{
+ if (h.pid <= 0)
+ return;
+ close(h.go);
+ kill(h.pid, SIGKILL);
+ waitpid(h.pid, NULL, 0);
+}
+
+#define PID(a) (((struct holder *)(a))->pid)
+
+static long attach_only(int pid)
+{
+ if (ptrace(PTRACE_ATTACH, pid, 0, 0))
+ return -errno;
+ waitpid(pid, NULL, 0);
+ ptrace(PTRACE_DETACH, pid, 0, 0);
+ return 0;
+}
+
+/* /tmp idmapped with the user namespace of pid, at /mnt */
+static int idmap_tmp(int pid)
+{
+ struct mount_attr attr = { .attr_set = MOUNT_ATTR_IDMAP };
+ char path[64];
+ int tfd, nsfd;
+
+ mkdir("/mnt", 0755);
+ snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
+ nsfd = open(path, O_RDONLY);
+ tfd = syscall(__NR_open_tree, AT_FDCWD, "/tmp",
+ OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
+ if (nsfd < 0 || tfd < 0)
+ return -1;
+ attr.userns_fd = nsfd;
+ if (syscall(__NR_mount_setattr, tfd, "", AT_EMPTY_PATH, &attr,
+ sizeof(attr)))
+ return -1;
+ if (syscall(__NR_move_mount, tfd, "", AT_FDCWD, "/mnt",
+ MOVE_MOUNT_F_EMPTY_PATH))
+ return -1;
+ close(tfd);
+ close(nsfd);
+ return 0;
+}
+
+/* Each test: private mounts, a tmpfs on /tmp with copies of this program */
+static void prepare(struct __test_metadata *_metadata)
+{
+ ASSERT_EQ(unshare(CLONE_NEWNS), 0);
+ ASSERT_EQ(mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
+ ASSERT_EQ(mount("tmpfs", "/tmp", "tmpfs", 0, "mode=1777"), 0);
+ ASSERT_EQ(new_file("/tmp/x", 0), 0);
+ ASSERT_EQ(new_file("/tmp/u", 1000), 0);
+ mkdir("/mnt", 0755);
+}
+
+FIXTURE(setfcap) {};
+
+FIXTURE_SETUP(setfcap)
+{
+ if (geteuid())
+ SKIP(return, "needs root");
+ prepare(_metadata);
+}
+
+FIXTURE_TEARDOWN(setfcap) {}
+
+/* ---------------------------------------------------------------------- */
+/* Mapping uid 0 of the parent, or the root user of an ancestor at any uid */
+
+static long x_maps_from_parent(void *a)
+{
+ restrict_root();
+ return write_map(PID(a), "0 0 1\n");
+}
+
+TEST_F(setfcap, map_from_parent_without_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_maps_from_parent, &h), -EPERM);
+ reap_holder(h);
+}
+
+static long x_maps_own(void *a)
+{
+ restrict_root();
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_own_without_setfcap)
+{
+ EXPECT_EQ(in_child(x_maps_own, NULL), -EPERM);
+}
+
+static long x_joins_and_maps(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return write_map(0, "0 0 1\n");
+}
+
+/* X can't get into R's namespace to map uid 0 from inside */
+TEST_F(setfcap, map_after_setns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_and_maps, &h), -EPERM);
+ reap_holder(h);
+}
+
+static long x_writes_fd(void *a)
+{
+ restrict_root();
+ return wr(*(int *)a, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_through_borrowed_fd)
+{
+ struct holder h;
+ char path[64];
+ int fd;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", h.pid);
+ fd = open(path, O_WRONLY);
+ ASSERT_GE(fd, 0);
+ EXPECT_EQ(in_child(x_writes_fd, &fd), -EPERM);
+ close(fd);
+ reap_holder(h);
+}
+
+static long x_steals_fd(void *a)
+{
+ int pfd, fd;
+
+ restrict_root();
+ pfd = syscall(__NR_pidfd_open, PID(a), 0);
+ if (pfd < 0)
+ return SETUP_ERROR;
+ fd = syscall(__NR_pidfd_getfd, pfd, 100, 0);
+ if (fd < 0)
+ return -errno;
+ return wr(fd, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_through_pidfd_getfd)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 100);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_steals_fd, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* the same one level down, among tasks of an unprivileged user */
+static long u_nested(void *a)
+{
+ struct holder h;
+ long r;
+
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ /* R-like: full set in the user's namespace */
+ h = spawn_holder(HOLDER_ROOT, 0);
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = in_child(x_joins_and_maps, &h);
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, map_after_setns_nested_unprivileged)
+{
+ EXPECT_EQ(in_child(u_nested, NULL), -EPERM);
+}
+
+static long x_joins_unshares_maps(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_setns_and_unshare)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_unshares_maps, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* the writer opened the map, then went into an unrelated namespace */
+static long r_opens_then_leaves(void *a)
+{
+ char path[64];
+ int fd;
+
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", PID(a));
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return wr(fd, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_writer_left_for_other_ns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_opens_then_leaves, &h), -EPERM);
+ reap_holder(h);
+}
+
+/*
+ * R maps host uid 0 as uid 1000 of X's namespace. X maps "0 1000 1" one
+ * level down: host uid 0 is uid 0 there without any extent at uid 0.
+ */
+static long x_nonzero_root(void *a)
+{
+ int s1[2], s2[2], res[2], pid;
+ long r = SETUP_ERROR;
+ char c;
+
+ if (pipe(s1) || pipe(s2) || pipe(res))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ restrict_root();
+ if (unshare(CLONE_NEWUSER) || write(s1[1], "u", 1) != 1 ||
+ read(s2[0], &c, 1) != 1)
+ _exit(1);
+ if (unshare(CLONE_NEWUSER))
+ r = SETUP_ERROR;
+ else
+ r = write_map(0, "0 1000 1\n");
+ if (write(res[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(s1[0], &c, 1) != 1 || map_both(pid, "1000 0 1\n") ||
+ write(s2[1], "g", 1) != 1 || read(res[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+TEST_F(setfcap, map_ancestor_root_at_nonzero_uid)
+{
+ EXPECT_EQ(in_child(x_nonzero_root, NULL), -EPERM);
+}
+
+/*
+ * R's namespace has no map yet. R opens its uid_map and hands the fd to a
+ * task of the same namespace that gave up CAP_SETFCAP (but kept it in the
+ * bounding set, so it would get it back from execve() as uid 0).
+ */
+static long dropped_writes_inherited_fd(void *a)
+{
+ int fd, pid, st;
+ long r = SETUP_ERROR;
+ int p[2];
+
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ fd = open("/proc/self/uid_map", O_WRONLY);
+ if (fd < 0 || pipe(p))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ drop_setfcap_keep_bset();
+ r = wr(fd, "0 0 1\n");
+ if (write(p[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(p[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, &st, 0);
+ return r;
+}
+
+TEST_F(setfcap, map_in_ns_writer_without_setfcap)
+{
+ EXPECT_EQ(in_child(dropped_writes_inherited_fd, NULL), -EPERM);
+}
+
+/* ... and the same task opening its own map */
+static long dropped_opens_and_writes(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ drop_setfcap_keep_bset();
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_in_ns_opener_without_setfcap)
+{
+ EXPECT_EQ(in_child(dropped_opens_and_writes, NULL), -EPERM);
+}
+
+/* What has to keep working. */
+
+static long r_maps_own(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_own)
+{
+ EXPECT_EQ(in_child(r_maps_own, NULL), 0);
+}
+
+static long r_maps_from_parent(void *a)
+{
+ return write_map(PID(a), "0 0 1000\n");
+}
+
+TEST_F(setfcap, map_from_parent)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_maps_from_parent, &h), 0);
+ reap_holder(h);
+}
+
+static long child_maps(void *a)
+{
+ return write_map(0, "0 0 1\n");
+}
+
+static long r_child_maps(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ return in_child(child_maps, NULL);
+}
+
+TEST_F(setfcap, map_by_child_of_creator)
+{
+ EXPECT_EQ(in_child(r_child_maps, NULL), 0);
+}
+
+static long r_joins_and_maps(void *a)
+{
+ long r = join(PID(a));
+
+ if (r)
+ return r;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_setns_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins_and_maps, &h), 0);
+ reap_holder(h);
+}
+
+static long r_joins_writes_fd(void *a)
+{
+ void **v = a;
+ long r = join(PID(v[0]));
+
+ if (r)
+ return r;
+ return wr(*(int *)v[1], "0 0 1\n");
+}
+
+TEST_F(setfcap, map_opened_in_parent_written_inside)
+{
+ struct holder h;
+ char path[64];
+ void *v[2];
+ int fd;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ snprintf(path, sizeof(path), "/proc/%d/uid_map", h.pid);
+ fd = open(path, O_WRONLY);
+ ASSERT_GE(fd, 0);
+ v[0] = &h;
+ v[1] = &fd;
+ EXPECT_EQ(in_child(r_joins_writes_fd, v), 0);
+ close(fd);
+ reap_holder(h);
+}
+
+static long u_nested_maps_own(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return in_child(r_maps_own, NULL);
+}
+
+TEST_F(setfcap, map_unprivileged_nested)
+{
+ EXPECT_EQ(in_child(u_nested_maps_own, NULL), 0);
+}
+
+static long u_nested_maps_child(void *a)
+{
+ struct holder h;
+ long r;
+
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ h = spawn_holder(HOLDER_ROOT, 0);
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = write_map(h.pid, "0 0 1\n");
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, map_unprivileged_nested_from_parent)
+{
+ EXPECT_EQ(in_child(u_nested_maps_child, NULL), 0);
+}
+
+static long session_to_parent(void *a)
+{
+ if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) < 0 ||
+ syscall(SYS_keyctl, KEYCTL_SESSION_TO_PARENT) < 0)
+ return SETUP_ERROR;
+ return 0;
+}
+
+/* a cred replaced by key_change_session_keyring() keeps what it had */
+static long r_new_session_keyring_maps(void *a)
+{
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ if (in_child(session_to_parent, NULL))
+ return SETUP_ERROR;
+ return write_map(0, "0 0 1\n");
+}
+
+TEST_F(setfcap, map_after_session_to_parent)
+{
+ EXPECT_EQ(in_child(r_new_session_keyring_maps, NULL), 0);
+}
+
+/* ---------------------------------------------------------------------- */
+/* File capabilities that are honoured in an ancestor */
+
+static long x_joins_sets_fcap(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_after_setns)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_sets_fcap, &h), -EPERM);
+ reap_holder(h);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+static long x_joins_sets_fcap_rootid5(void *a)
+{
+ long r;
+
+ restrict_root();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", 5);
+}
+
+/* a v3 xattr can name the root user by any uid it has in the namespace */
+TEST_F(setfcap, fcap_after_setns_v3_rootid)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "5 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins_sets_fcap_rootid5, &h), -EPERM);
+ reap_holder(h);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* X unshares and R maps "0 0 1" for it from the parent */
+static long x_unshares_r_maps(void *a)
+{
+ int version = *(int *)a;
+ int s1[2], s2[2], res[2], pid;
+ long r = SETUP_ERROR;
+ char c;
+
+ if (pipe(s1) || pipe(s2) || pipe(res))
+ return SETUP_ERROR;
+ pid = fork();
+ if (!pid) {
+ restrict_root();
+ if (unshare(CLONE_NEWUSER) || write(s1[1], "u", 1) != 1 ||
+ read(s2[0], &c, 1) != 1)
+ _exit(1);
+ if (version == 2) {
+ /* a v2 xattr on a tmpfs of its own */
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) ||
+ new_file("/mnt/f", 0))
+ r = SETUP_ERROR;
+ else
+ r = set_fcap("/mnt/f", -1);
+ } else {
+ r = set_fcap("/tmp/x", -1);
+ }
+ if (write(res[1], &r, sizeof(r)) != sizeof(r))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(s1[0], &c, 1) != 1 || map_both(pid, "0 0 1\n") ||
+ write(s2[1], "g", 1) != 1 || read(res[0], &r, sizeof(r)) != sizeof(r))
+ r = SETUP_ERROR;
+ waitpid(pid, NULL, 0);
+ return r;
+}
+
+TEST_F(setfcap, fcap_creator_without_setfcap_parent_mapped)
+{
+ int version = 3;
+
+ EXPECT_EQ(in_child(x_unshares_r_maps, &version), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* the v2 fast path of cap_convert_nscap() */
+TEST_F(setfcap, fcap_v2_creator_without_setfcap_parent_mapped)
+{
+ int version = 2;
+
+ EXPECT_EQ(in_child(x_unshares_r_maps, &version), -EPERM);
+}
+
+/* R maps "5 0 1", gives up CAP_SETFCAP, unshares again */
+static long r_drops_then_nests(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "5 0 1\n"))
+ return SETUP_ERROR;
+ restrict_root();
+ if (set_fcap("/tmp/x", 5) != -EPERM)
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWUSER))
+ return SETUP_ERROR;
+ if (write_map(0, "5 5 1\n"))
+ return -EPERM;
+ write_file(0, "setgroups", "deny");
+ write_file(0, "gid_map", "5 5 1\n");
+ return set_fcap("/tmp/x", 5);
+}
+
+TEST_F(setfcap, fcap_after_dropping_setfcap_and_nesting)
+{
+ EXPECT_EQ(in_child(r_drops_then_nests, NULL), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/* X unshares, R maps "0 0 1" for it, and another R joins it */
+static long joiner_takes_ns_reach(void *a)
+{
+ struct holder h;
+ long r;
+
+ h = spawn_mapped(HOLDER_RESTRICTED, "0 0 1\n");
+ if (h.pid <= 0)
+ return SETUP_ERROR;
+ r = join(h.pid);
+ if (!r)
+ r = set_fcap("/tmp/x", -1);
+ reap_holder(h);
+ return r;
+}
+
+TEST_F(setfcap, fcap_joiner_takes_namespace_reach)
+{
+ EXPECT_EQ(in_child(joiner_takes_ns_reach, NULL), -EPERM);
+ EXPECT_FALSE(user_gets_sys_admin("/tmp/x"));
+}
+
+/*
+ * A v2 xattr on a filesystem whose namespace has no uid 0 has no root user
+ * and is honoured nowhere: refuse it rather than storing it unconverted.
+ */
+static long r_v2_without_uid0(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "1000 0 1\n"))
+ return SETUP_ERROR;
+ /* host uid 0, our uid, is uid 1000 here */
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) || new_file("/mnt/f", 1000))
+ return SETUP_ERROR;
+ return set_fcap("/mnt/f", -1);
+}
+
+TEST_F(setfcap, fcap_v2_without_uid0_in_fs_ns)
+{
+ EXPECT_EQ(in_child(r_v2_without_uid0, NULL), -EINVAL);
+}
+
+/* ... and from the parent namespace, where the writer does have a root user */
+static long r_v2_without_uid0_from_parent(void *a)
+{
+ struct holder *h = a;
+ char path[64];
+
+ snprintf(path, sizeof(path), "/proc/%d/root/mnt/f", h->pid);
+ return set_fcap(path, -1);
+}
+
+TEST_F(setfcap, fcap_v2_without_uid0_from_parent)
+{
+ int ready[2], go[2], mapped[2], pid;
+ struct holder h;
+ char c;
+
+ ASSERT_EQ(pipe(ready), 0);
+ ASSERT_EQ(pipe(go), 0);
+ ASSERT_EQ(pipe(mapped), 0);
+ pid = fork();
+ ASSERT_GE(pid, 0);
+ if (!pid) {
+ /* host uid 0 is uid 1000 in here, nobody is uid 0 */
+ if (unshare(CLONE_NEWUSER) || write(ready[1], "u", 1) != 1 ||
+ read(mapped[0], &c, 1) != 1 || unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) ||
+ new_file("/mnt/f", 1000) || write(ready[1], "m", 1) != 1)
+ _exit(1);
+ if (read(go[0], &c, 1) < 0)
+ _exit(1);
+ _exit(0);
+ }
+ h.pid = pid;
+ h.go = go[1];
+ ASSERT_EQ(read(ready[0], &c, 1), 1);
+ ASSERT_EQ(map_both(pid, "1000 0 1\n"), 0);
+ ASSERT_EQ(write(mapped[1], "g", 1), 1);
+ ASSERT_EQ(read(ready[0], &c, 1), 1);
+ EXPECT_EQ(in_child(r_v2_without_uid0_from_parent, &h), -EINVAL);
+ reap_holder(h);
+}
+
+/* What has to keep working. */
+
+static long r_maps_sets_fcap(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_own_ns)
+{
+ EXPECT_EQ(in_child(r_maps_sets_fcap, NULL), 0);
+ EXPECT_TRUE(user_gets_sys_admin("/tmp/x"));
+}
+
+static long r_joins_sets_fcap(void *a)
+{
+ long r = join(PID(a));
+
+ if (r)
+ return r;
+ return set_fcap("/tmp/x", -1);
+}
+
+TEST_F(setfcap, fcap_after_setns_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins_sets_fcap, &h), 0);
+ reap_holder(h);
+}
+
+static long u_sets_fcap(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return set_fcap("/tmp/u", -1);
+}
+
+TEST_F(setfcap, fcap_unprivileged)
+{
+ EXPECT_EQ(in_child(u_sets_fcap, NULL), 0);
+}
+
+static long u_nested_sets_fcap_inner(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ return set_fcap("/tmp/u", -1);
+}
+
+static long u_nested_sets_fcap(void *a)
+{
+ become_user();
+ if (unshare(CLONE_NEWUSER) || map_user())
+ return SETUP_ERROR;
+ return in_child(u_nested_sets_fcap_inner, NULL);
+}
+
+TEST_F(setfcap, fcap_unprivileged_nested)
+{
+ EXPECT_EQ(in_child(u_nested_sets_fcap, NULL), 0);
+}
+
+static long u_joins_own_sets_fcap(void *a)
+{
+ long r;
+
+ become_user();
+ r = join(PID(a));
+ if (r)
+ return r;
+ return set_fcap("/tmp/u", -1);
+}
+
+TEST_F(setfcap, fcap_unprivileged_after_setns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_USER, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(u_joins_own_sets_fcap, &h), 0);
+ reap_holder(h);
+}
+
+static long r_v2_own_fs(void *a)
+{
+ if (unshare(CLONE_NEWUSER) || map_both(0, "0 0 1\n"))
+ return SETUP_ERROR;
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) ||
+ mount("tmpfs", "/mnt", "tmpfs", 0, NULL) || new_file("/mnt/f", 0))
+ return SETUP_ERROR;
+ return set_fcap("/mnt/f", -1);
+}
+
+TEST_F(setfcap, fcap_v2_own_ns)
+{
+ EXPECT_EQ(in_child(r_v2_own_fs, NULL), 0);
+}
+
+/* ---------------------------------------------------------------------- */
+/* Idmapped mounts: the root user is both the one seen through the mount */
+/* and the one stored. Mounts that make a container's root host uid 0 are */
+/* up to whoever sets them up. */
+
+struct idmap_case {
+ const char *ns_map, *idmap_map;
+ int file_uid, restricted;
+};
+
+/* returns 1 to skip: no idmapped mounts on tmpfs */
+static int idmap_case(const struct idmap_case *c, long *r)
+{
+ struct holder ns, im;
+ int pid, p[2], st;
+
+ ns = spawn_mapped(HOLDER_ROOT, c->ns_map);
+ if (ns.pid <= 0)
+ return -1;
+ im = c->idmap_map ? spawn_mapped(HOLDER_ROOT, c->idmap_map) : ns;
+ if (im.pid <= 0 || new_file("/tmp/x", c->file_uid))
+ return -1;
+ if (idmap_tmp(im.pid)) {
+ reap_holder(ns);
+ if (c->idmap_map)
+ reap_holder(im);
+ return 1;
+ }
+ if (pipe(p))
+ return -1;
+ /* join from a child of the namespace's holder's sibling: pass the pid */
+ pid = fork();
+ if (!pid) {
+ long res;
+
+ if (c->restricted)
+ restrict_root();
+ res = join(ns.pid);
+ if (!res)
+ res = set_fcap("/mnt/x", 0);
+ if (write(p[1], &res, sizeof(res)) != sizeof(res))
+ _exit(1);
+ _exit(0);
+ }
+ if (read(p[0], r, sizeof(*r)) != sizeof(*r))
+ *r = SETUP_ERROR;
+ waitpid(pid, &st, 0);
+ umount2("/mnt", MNT_DETACH);
+ reap_holder(ns);
+ if (c->idmap_map)
+ reap_holder(im);
+ return 0;
+}
+
+FIXTURE(idmap) {};
+
+FIXTURE_VARIANT(idmap) {
+ struct idmap_case c;
+ long expect;
+};
+
+/* X can't join a namespace that maps host uid 0 to get at the mount */
+FIXTURE_VARIANT_ADD(idmap, reverse_mapping) {
+ .c = { "0 0 1\n", "100000 0 1\n", 100000, 1 },
+ .expect = -EPERM,
+};
+
+/* R in its container writes through the container's own idmapped rootfs */
+FIXTURE_VARIANT_ADD(idmap, container_root) {
+ .c = { "0 100000 1000\n", NULL, 0, 0 },
+ .expect = 0,
+};
+
+/* left to the admin: the container doesn't map host uid 0 */
+FIXTURE_VARIANT_ADD(idmap, container_without_host_root) {
+ .c = { "0 100000 1000\n", NULL, 0, 1 },
+ .expect = 0,
+};
+
+FIXTURE_VARIANT_ADD(idmap, unrelated_idmap) {
+ .c = { "0 100000 1000\n", "200000 100000 1\n", 200000, 1 },
+ .expect = 0,
+};
+
+FIXTURE_SETUP(idmap)
+{
+ if (geteuid())
+ SKIP(return, "needs root");
+ prepare(_metadata);
+}
+
+FIXTURE_TEARDOWN(idmap) {}
+
+TEST_F(idmap, fcap)
+{
+ long r;
+ int ret;
+
+ ret = idmap_case(&variant->c, &r);
+ ASSERT_GE(ret, 0);
+ if (ret == 1)
+ SKIP(return, "no idmapped mounts on tmpfs");
+ EXPECT_EQ(r, variant->expect);
+}
+
+/* ---------------------------------------------------------------------- */
+/* setns() */
+
+static long x_joins(void *a)
+{
+ restrict_root();
+ return join(PID(a));
+}
+
+static long r_joins(void *a)
+{
+ return join(PID(a));
+}
+
+TEST_F(setfcap, setns_ns_mapping_host_root)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, setns_ns_without_map_yet)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), -EPERM);
+ reap_holder(h);
+}
+
+/* a container that doesn't map host uid 0 */
+TEST_F(setfcap, setns_container)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 100000 1000\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_joins, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, setns_unprivileged_ns)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_USER, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_joins, &h), 0);
+ reap_holder(h);
+}
+
+/* ---------------------------------------------------------------------- */
+/* ptrace */
+
+static long x_attaches(void *a)
+{
+ restrict_root();
+ return attach_only(PID(a));
+}
+
+static long r_attaches(void *a)
+{
+ return attach_only(PID(a));
+}
+
+TEST_F(setfcap, ptrace_into_ns_without_map_yet)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_into_ns_mapping_host_root)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 0 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), -EPERM);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_into_container)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 100000 1000\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_ns_mapping_only_user)
+{
+ struct holder h;
+
+ h = spawn_mapped(HOLDER_ROOT, "0 1000 1\n");
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_between_restricted)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_RESTRICTED, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_attaches, &h), 0);
+ reap_holder(h);
+}
+
+TEST_F(setfcap, ptrace_with_setfcap)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(r_attaches, &h), 0);
+ reap_holder(h);
+}
+
+static long x_reads_environ(void *a)
+{
+ char path[64];
+ int fd;
+
+ restrict_root();
+ snprintf(path, sizeof(path), "/proc/%d/environ", PID(a));
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -errno;
+ close(fd);
+ return 0;
+}
+
+/* PTRACE_MODE_READ is unchanged */
+TEST_F(setfcap, ptrace_read_mode_unchanged)
+{
+ struct holder h;
+
+ h = spawn_holder(HOLDER_ROOT, 0);
+ ASSERT_GT(h.pid, 0);
+ EXPECT_EQ(in_child(x_reads_environ, &h), 0);
+ reap_holder(h);
+}
+
+TEST_HARNESS_MAIN
|
| 31/3 | 2026/10/26 21:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 22663 output: 33 thoughts: 1130 Thoughts: **KMSAN Fuzzing Session Evaluation**
Okay, let's assess whether this patch series warrants a dedicated KMSAN fuzzing session. My initial thought is to perform a thorough review, looking at the code changes to determine if there are potential uninitialized memory issues.
First, I need to get a handle on what's been changed. The patch touches these files: `include/linux/capability.h`, `include/linux/user_namespace.h`, `kernel/user_namespace.c`, `security/commoncap.c`, and some selftests. Seems like it's capability and user namespace related.
Let's break down the modifications:
* `include/linux/capability.h`: I see new prototypes for functions like `cap_setfcap_level`, `cred_setfcap_reaches`, and `cred_may_setfcap_userns`, along with a forward declaration of `struct cred`. So, new capability-related functions are being added.
* `include/linux/user_namespace.h`: The `struct user_namespace` now stores an `int setfcap_level` instead of `bool parent_could_setfcap`. Looks like we're moving from a boolean to an integer level to track capability settings.
* `kernel/user_namespace.c`: Here's where the core logic resides. The `create_user_ns` function uses `cap_setfcap_level` now. There are also new functions: `map_has_id`, `map_root_level`, and updates to `verify_root_map` and `userns_install`. `map_has_id` seems to iterate extents, `map_root_level` looks like it's about traversing user namespaces, and `verify_root_map` now uses capability checks. A new check is also added to `userns_install` using `cred_may_setfcap_userns`.
* `security/commoncap.c`: This file now implements the functions declared in `include/linux/capability.h`, such as `cap_setfcap_level`, `cred_setfcap_reaches`, `setfcap_top`, `cred_may_setfcap_userns`, `cap_root_level`, and `cap_covers_setfcap`. There are updates to `cap_ptrace_access_check`, `cap_ptrace_traceme`, and `cap_convert_nscap` that use these new capability checks.
Now, the critical part: uninitialized memory. I need to scrutinize these changes for potential vulnerabilities. My mental checklist includes:
* Are any new buffers or structs allocated on the stack or heap without initialization?
* Are there any uses of `copy_to_user`, `put_user`, netlink skb, ioctl output, or socket options where uninitialized memory could be exposed?
* Are any structs with padding exposed to userspace?
* Are there any instances where an uninitialized variable is read?
I'll be specifically focusing on functions like `cap_setfcap_level`, `map_root_level`, `map_has_id`, `verify_root_map`, and `cap_convert_nscap`, as they're the new or modified core functions.
Let's dive into the code, line by line. Let me start with `kernel/user_namespace.c`. I will start by looking at this code block:
```c
static bool map_has_id(struct uid_gid_map *map, u32 id)
{
struct uid_gid_extent *extent;
int idx;
for (idx = 0; idx < map->nr_extents; idx++) {
if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
extent = &map->extent[idx];
else
extent = &map->forward[idx];
if (id >= extent->lower_first &&
id - extent->lower_first < extent->count)
return true;
}
return false;
}
```
Okay, does `map` have valid initialized extents up to `nr_extents`? I need to track where `verify_root_map` is called to figure out how `map` gets set up. Let's search for calls to `verify_root_map` in `kernel/user_namespace.c`.
|
| 32/3 | 2026/10/26 21:08 | tool | grepper |
0mArgs:{
"Expression": "verify_root_map",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c=906=static int map_root_level(struct user_namespace *parent,\n--\nkernel/user_namespace.c-922-/**\nkernel/user_namespace.c:923: * verify_root_map() - check the uid 0 mapping\nkernel/user_namespace.c-924- * @file: idmapping file\n--\nkernel/user_namespace.c-935- */\nkernel/user_namespace.c:936:static bool verify_root_map(const struct file *file,\nkernel/user_namespace.c-937-\t\t\t struct user_namespace *map_ns,\n--\nkernel/user_namespace.c=1242=static bool new_idmap_permitted(const struct file *file,\n--\nkernel/user_namespace.c-1247-\nkernel/user_namespace.c:1248:\tif (cap_setid == CAP_SETUID \u0026\u0026 !verify_root_map(file, ns, new_map))\nkernel/user_namespace.c-1249-\t\treturn false;\n"
} |
| 33/3 | 2026/10/26 21:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25091 output: 36 thoughts: 24 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Diving into `new_idmap_permitted` and Its Usage** Alright, time to dig into the details. My initial thought is to zero in on `new_idmap_permitted`. I want to understand its purpose within the `kernel/user_namespace.c` context. My instinct is that this function likely has a crucial role in managing the creation of new user namespaces, specifically around the granting or denying of permissions related to ID mapping. I need to understand the precise criteria it uses. Is it based on capabilities, security labels, some form of configuration, or maybe a combination of factors? Beyond its direct function, I'm particularly interested in tracing its callers. Understanding *where* this function is invoked is critical. Are these calls coming from core namespace creation routines? Are they associated with specific system calls or user actions? By identifying the calling contexts, I can build a solid picture of the security boundaries and decision points `new_idmap_permitted` helps to enforce. I'm thinking of tracing its calls through `audit`, `security`, and `capabilities` files, or even the main files to understand the calling method of the function. |
| 34/3 | 2026/10/26 21:08 | tool | read-file |
0mArgs:{
"File": "kernel/user_namespace.c",
"FirstLine": 1230,
"LineCount": 50
}Results: {
"Contents": "1230:\t\n1231:\t\tif (!ns-\u003eparent)\n1232:\t\t\treturn -EPERM;\n1233:\t\n1234:\t\tif ((seq_ns != ns) \u0026\u0026 (seq_ns != ns-\u003eparent))\n1235:\t\t\treturn -EPERM;\n1236:\t\n1237:\t\t/* Anyone can set any valid project id no capability needed */\n1238:\t\treturn map_write(file, buf, size, ppos, -1,\n1239:\t\t\t\t \u0026ns-\u003eprojid_map, \u0026ns-\u003eparent-\u003eprojid_map);\n1240:\t}\n1241:\t\n1242:\tstatic bool new_idmap_permitted(const struct file *file,\n1243:\t\t\t\t\tstruct user_namespace *ns, int cap_setid,\n1244:\t\t\t\t\tstruct uid_gid_map *new_map)\n1245:\t{\n1246:\t\tconst struct cred *cred = file-\u003ef_cred;\n1247:\t\n1248:\t\tif (cap_setid == CAP_SETUID \u0026\u0026 !verify_root_map(file, ns, new_map))\n1249:\t\t\treturn false;\n1250:\t\n1251:\t\t/* Don't allow mappings that would allow anything that wouldn't\n1252:\t\t * be allowed without the establishment of unprivileged mappings.\n1253:\t\t */\n1254:\t\tif ((new_map-\u003enr_extents == 1) \u0026\u0026 (new_map-\u003eextent[0].count == 1) \u0026\u0026\n1255:\t\t uid_eq(ns-\u003eowner, cred-\u003eeuid)) {\n1256:\t\t\tu32 id = new_map-\u003eextent[0].lower_first;\n1257:\t\t\tif (cap_setid == CAP_SETUID) {\n1258:\t\t\t\tkuid_t uid = make_kuid(ns-\u003eparent, id);\n1259:\t\t\t\tif (uid_eq(uid, cred-\u003eeuid))\n1260:\t\t\t\t\treturn true;\n1261:\t\t\t} else if (cap_setid == CAP_SETGID) {\n1262:\t\t\t\tkgid_t gid = make_kgid(ns-\u003eparent, id);\n1263:\t\t\t\tif (!(ns-\u003eflags \u0026 USERNS_SETGROUPS_ALLOWED) \u0026\u0026\n1264:\t\t\t\t gid_eq(gid, cred-\u003eegid))\n1265:\t\t\t\t\treturn true;\n1266:\t\t\t}\n1267:\t\t}\n1268:\t\n1269:\t\t/* Allow anyone to set a mapping that doesn't require privilege */\n1270:\t\tif (!cap_valid(cap_setid))\n1271:\t\t\treturn true;\n1272:\t\n1273:\t\t/* Allow the specified ids if we have the appropriate capability\n1274:\t\t * (CAP_SETUID or CAP_SETGID) over the parent user namespace.\n1275:\t\t * And the opener of the id file also has the appropriate capability.\n1276:\t\t */\n1277:\t\tif (ns_capable(ns-\u003eparent, cap_setid) \u0026\u0026\n1278:\t\t file_ns_capable(file, ns-\u003eparent, cap_setid))\n1279:\t\t\treturn true;\n"
} |
| 35/3 | 2026/10/26 21:08 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26246 output: 34 thoughts: 22 Thoughts: Okay, here's my summary, tailored for an expert audience, as if I'm thinking these things myself: **Tracing the Initialization of `new_map`** Right, let's get down to brass tacks. I need to be absolutely certain of the state of the `new_map` variable *before* we even consider the implications of `new_idmap_permitted`. Context is king, as always, and a crucial piece of this puzzle lies in understanding how `new_map` is initialized. I can't just blindly assume; I need to meticulously verify its starting configuration. Is it empty? Does it get pre-populated with anything, and if so, what? Any initial assignments are going to fundamentally influence everything that follows. I need to know where we're coming from before figuring out where we're going, otherwise, this whole examination might be flawed. Let's delve in and find that first declaration and assignment. |
| 36/3 | 2026/10/26 21:09 | tool | grepper |
0mArgs:{
"Expression": "new_idmap_permitted",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c=28=static DEFINE_MUTEX(userns_state_mutex);\nkernel/user_namespace.c-29-\nkernel/user_namespace.c:30:static bool new_idmap_permitted(const struct file *file,\nkernel/user_namespace.c-31-\t\t\t\tstruct user_namespace *ns, int cap_setid,\n--\nkernel/user_namespace.c=999=static ssize_t map_write(struct file *file, const char __user *buf,\n--\nkernel/user_namespace.c-1125-\t/* Validate the user is allowed to use user id's mapped to. */\nkernel/user_namespace.c:1126:\tif (!new_idmap_permitted(file, map_ns, cap_setid, \u0026new_map))\nkernel/user_namespace.c-1127-\t\tgoto out;\n--\nkernel/user_namespace.c=1224=ssize_t proc_projid_map_write(struct file *file, const char __user *buf,\n--\nkernel/user_namespace.c-1241-\nkernel/user_namespace.c:1242:static bool new_idmap_permitted(const struct file *file,\nkernel/user_namespace.c-1243-\t\t\t\tstruct user_namespace *ns, int cap_setid,\n"
} |
| 37/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26844 output: 36 thoughts: 26 Thoughts: Here's a summary of my thought process, as requested: **Navigating User Namespace Code** Okay, so I need to dive into the `kernel/user_namespace.c` file. Specifically, I need to get my bearings around lines 1000 through 1127. Let's see what we find there. I'm assuming we're dealing with either user namespace creation, manipulation, or perhaps some sort of security context management within that area of the kernel. Given the line range, it's likely a specific function or a block of related functions. Time to start reading the code and see what sticks out. I'll be looking for function calls, data structures, and comments that provide context. My immediate focus will be to grasp the flow of execution and how this particular section interacts with the broader user namespace framework. |
| 38/3 | 2026/10/26 21:09 | tool | read-file |
0mArgs:{
"File": "kernel/user_namespace.c",
"FirstLine": 1000,
"LineCount": 50
}Results: {
"Contents": "1000:\t\t\t\t size_t count, loff_t *ppos,\n1001:\t\t\t\t int cap_setid,\n1002:\t\t\t\t struct uid_gid_map *map,\n1003:\t\t\t\t struct uid_gid_map *parent_map)\n1004:\t{\n1005:\t\tstruct seq_file *seq = file-\u003eprivate_data;\n1006:\t\tstruct user_namespace *map_ns = seq-\u003eprivate;\n1007:\t\tstruct uid_gid_map new_map;\n1008:\t\tunsigned idx;\n1009:\t\tstruct uid_gid_extent extent;\n1010:\t\tchar *kbuf, *pos, *next_line;\n1011:\t\tssize_t ret;\n1012:\t\n1013:\t\t/* Only allow \u003c page size writes at the beginning of the file */\n1014:\t\tif ((*ppos != 0) || (count \u003e= PAGE_SIZE))\n1015:\t\t\treturn -EINVAL;\n1016:\t\n1017:\t\t/* Slurp in the user data */\n1018:\t\tkbuf = memdup_user_nul(buf, count);\n1019:\t\tif (IS_ERR(kbuf))\n1020:\t\t\treturn PTR_ERR(kbuf);\n1021:\t\n1022:\t\t/*\n1023:\t\t * The userns_state_mutex serializes all writes to any given map.\n1024:\t\t *\n1025:\t\t * Any map is only ever written once.\n1026:\t\t *\n1027:\t\t * An id map fits within 1 cache line on most architectures.\n1028:\t\t *\n1029:\t\t * On read nothing needs to be done unless you are on an\n1030:\t\t * architecture with a crazy cache coherency model like alpha.\n1031:\t\t *\n1032:\t\t * There is a one time data dependency between reading the\n1033:\t\t * count of the extents and the values of the extents. The\n1034:\t\t * desired behavior is to see the values of the extents that\n1035:\t\t * were written before the count of the extents.\n1036:\t\t *\n1037:\t\t * To achieve this smp_wmb() is used on guarantee the write\n1038:\t\t * order and smp_rmb() is guaranteed that we don't have crazy\n1039:\t\t * architectures returning stale data.\n1040:\t\t */\n1041:\t\tmutex_lock(\u0026userns_state_mutex);\n1042:\t\n1043:\t\tmemset(\u0026new_map, 0, sizeof(struct uid_gid_map));\n1044:\t\n1045:\t\tret = -EPERM;\n1046:\t\t/* Only allow one successful write to the map */\n1047:\t\tif (map-\u003enr_extents != 0)\n1048:\t\t\tgoto out;\n1049:\t\n"
} |
| 39/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27851 output: 34 thoughts: 89 Thoughts: Okay, here's my breakdown of what's going on, thinking through this code: **Analyzing the ID Map and Capability Conversion** Alright, so I see `new_map` is being initialized with `memset` before being fed into `new_idmap_permitted`. That makes sense; we want a clean slate, ensuring everything is zeroed out before we start populating it. Now, the critical question is what happens to that `new_map` in the context of capabilities. I need to understand how these IDs interact with capability management. The next thing I'm doing is turning my attention to `cap_convert_nscap` in `security/commoncap.c`. Let's dig into lines 720-780, that's where I expect to find the meat of how this translation occurs. This section should illuminate the connection between the ID map being passed and how capabilities are handled across namespaces. I'll be looking for the logic that maps or adjusts capabilities based on the UID/GID mapping in `new_map`. Specifically, how does it handle transitions in the security context? I'm anticipating that this is where any ID mapping-related privilege checks or transformations will occur. |
| 40/3 | 2026/10/26 21:09 | tool | read-file |
0mArgs:{
"File": "security/commoncap.c",
"FirstLine": 720,
"LineCount": 80
}Results: {
"Contents": " 720:\t\t__u32 magic, nsmagic;\n 721:\t\tstruct inode *inode = d_backing_inode(dentry);\n 722:\t\tstruct user_namespace *task_ns = current_user_ns(),\n 723:\t\t\t*fs_ns = inode-\u003ei_sb-\u003es_user_ns;\n 724:\t\tkuid_t rootid;\n 725:\t\tvfsuid_t vfsrootid;\n 726:\t\tsize_t newsize;\n 727:\t\n 728:\t\tif (!*ivalue)\n 729:\t\t\treturn -EINVAL;\n 730:\t\tif (!validheader(size, cap))\n 731:\t\t\treturn -EINVAL;\n 732:\t\tif (!capable_wrt_inode_uidgid(idmap, inode, CAP_SETFCAP))\n 733:\t\t\treturn -EPERM;\n 734:\t\t/*\n 735:\t\t * A v2 xattr belongs to the root user of the filesystem's namespace,\n 736:\t\t * which may be the root user of ancestors of our namespace as well.\n 737:\t\t * There may be none, then nobody could ever run the file with these\n 738:\t\t * capabilities. Only write it unconverted if that root user is\n 739:\t\t * within reach, the checks below handle everything else.\n 740:\t\t */\n 741:\t\tif (size == XATTR_CAPS_SZ_2 \u0026\u0026 idmap == \u0026nop_mnt_idmap \u0026\u0026\n 742:\t\t ns_capable(fs_ns, CAP_SETFCAP)) {\n 743:\t\t\tkuid_t fsroot = make_kuid(fs_ns, 0);\n 744:\t\n 745:\t\t\tif (!uid_valid(fsroot))\n 746:\t\t\t\treturn -EINVAL;\n 747:\t\t\tif (cap_root_level(fsroot, task_ns) \u003e= task_ns-\u003esetfcap_level)\n 748:\t\t\t\t/* user is privileged, just write the v2 */\n 749:\t\t\t\treturn size;\n 750:\t\t}\n 751:\t\n 752:\t\tvfsrootid = rootid_from_xattr(*ivalue, size, task_ns);\n 753:\t\tif (!vfsuid_valid(vfsrootid))\n 754:\t\t\treturn -EINVAL;\n 755:\t\n 756:\t\t/*\n 757:\t\t * The root user may be the root user of ancestors of our namespace as\n 758:\t\t * well. CAP_SETFCAP that we got for entering it doesn't cover those.\n 759:\t\t * On an idmapped mount the root user is vfsrootid as seen through\n 760:\t\t * this mount and rootid as seen through every other mount of the\n 761:\t\t * filesystem, so both have to stay within reach.\n 762:\t\t */\n 763:\t\tif (cap_root_level(vfsuid_into_kuid(vfsrootid), task_ns) \u003c\n 764:\t\t task_ns-\u003esetfcap_level)\n 765:\t\t\treturn -EPERM;\n 766:\t\n 767:\t\trootid = from_vfsuid(idmap, fs_ns, vfsrootid);\n 768:\t\tif (!uid_valid(rootid))\n 769:\t\t\treturn -EINVAL;\n 770:\t\n 771:\t\tif (cap_root_level(rootid, task_ns) \u003c task_ns-\u003esetfcap_level)\n 772:\t\t\treturn -EPERM;\n 773:\t\n 774:\t\tnsrootid = from_kuid(fs_ns, rootid);\n 775:\t\tif (nsrootid == -1)\n 776:\t\t\treturn -EINVAL;\n 777:\t\n 778:\t\tnewsize = sizeof(struct vfs_ns_cap_data);\n 779:\t\tnscap = kmalloc(newsize, GFP_ATOMIC);\n 780:\t\tif (!nscap)\n 781:\t\t\treturn -ENOMEM;\n 782:\t\tnscap-\u003erootid = cpu_to_le32(nsrootid);\n 783:\t\tnsmagic = VFS_CAP_REVISION_3;\n 784:\t\tmagic = le32_to_cpu(cap-\u003emagic_etc);\n 785:\t\tif (magic \u0026 VFS_CAP_FLAGS_EFFECTIVE)\n 786:\t\t\tnsmagic |= VFS_CAP_FLAGS_EFFECTIVE;\n 787:\t\tnscap-\u003emagic_etc = cpu_to_le32(nsmagic);\n 788:\t\tmemcpy(\u0026nscap-\u003edata, \u0026cap-\u003edata, sizeof(__le32) * 2 * VFS_CAP_U32);\n 789:\t\n 790:\t\t*ivalue = nscap;\n 791:\t\treturn newsize;\n 792:\t}\n 793:\t\n 794:\t/*\n 795:\t * Calculate the new process capability sets from the capability sets attached\n 796:\t * to a file.\n 797:\t */\n 798:\tstatic inline int bprm_caps_from_vfs_caps(struct cpu_vfs_cap_data *caps,\n 799:\t\t\t\t\t\t struct linux_binprm *bprm,\n"
} |
| 41/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29625 output: 34 thoughts: 22 Thoughts: Okay, let's dive into this. Here's my thought process on tackling this snippet: **Diving into `security/commoncap.c:700-725`** Alright, the objective is to review lines 700 through 725 within `security/commoncap.c`. My initial assumption is that this section likely deals with a shared capability implementation, possibly common routines utilized across different security contexts. Given the file name and general context, I'm expecting to find either utility functions related to capability manipulation, maybe some access control checks, or perhaps even logging or error handling relevant to capability usage. I'll need to focus on understanding the logical flow within this code block. I'll want to quickly identify the key variables or data structures being operated on. I'll be looking for calls to any internal functions, external libraries, or system calls, as those will be indicators of what operations are being performed. I need to rapidly ascertain whether this code could introduce any vulnerabilities or potential for unexpected behavior, or if there's any area that could be improved upon from a performance or security standpoint, in particular with respect to possible race conditions, use of uninitialized variables, or insecure string handling. Then, I can start to form an opinion on whether there might be any potential for this section to cause problems in a broader context or if it looks sound. |
| 42/3 | 2026/10/26 21:09 | tool | read-file |
0mArgs:{
"File": "security/commoncap.c",
"FirstLine": 700,
"LineCount": 25
}Results: {
"Contents": " 700:\t * @ivalue:\tvfs caps value which may be modified by this function\n 701:\t * @size:\tsize of @ivalue\n 702:\t *\n 703:\t * User requested a write of security.capability. If needed, update the\n 704:\t * xattr to change from v2 to v3, or to fixup the v3 rootid.\n 705:\t *\n 706:\t * If the inode has been found through an idmapped mount the idmap of\n 707:\t * the vfsmount must be passed through @idmap. This function will then\n 708:\t * take care to map the inode according to @idmap before checking\n 709:\t * permissions. On non-idmapped mounts or if permission checking is to be\n 710:\t * performed on the raw inode simply pass @nop_mnt_idmap.\n 711:\t *\n 712:\t * Return: On success, return the new size; on error, return \u003c 0.\n 713:\t */\n 714:\tint cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n 715:\t\t\t const void **ivalue, size_t size)\n 716:\t{\n 717:\t\tstruct vfs_ns_cap_data *nscap;\n 718:\t\tuid_t nsrootid;\n 719:\t\tconst struct vfs_cap_data *cap = *ivalue;\n 720:\t\t__u32 magic, nsmagic;\n 721:\t\tstruct inode *inode = d_backing_inode(dentry);\n 722:\t\tstruct user_namespace *task_ns = current_user_ns(),\n 723:\t\t\t*fs_ns = inode-\u003ei_sb-\u003es_user_ns;\n 724:\t\tkuid_t rootid;\n"
} |
| 43/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 30462 output: 32 thoughts: 1033 Thoughts: **Analyzing Capability Conversion and Privilege Levels** Okay, let's break this down. My initial observation is that the core memory allocation within `cap_convert_nscap` using `kmalloc` was already present. The patch primarily introduces specific conditional checks, particularly focusing on `XATTR_CAPS_SZ_2` and the `cap_root_level`. My focus is on understanding the new checks, their implications, and their intended behavior. I want to dive into what these new conditions are doing. Essentially, it appears that for v2 extended attributes (`XATTR_CAPS_SZ_2`), the code is now checking if the filesystem's root user is within reach of the task's user namespace for `CAP_SETFCAP`. The first check is, if the filesystem root user has `CAP_SETFCAP` in the namespace, the code takes one path. The second path involves converting the root ID using `rootid_from_xattr` and checking its validity, including the use of `cap_root_level`. It also checks the same for the root ID of the mounted file-system. It returns errors if the `cap_root_level` is not sufficient, namely, if it's not within the setfcap level of the task's namespace. I'm interpreting this as a set of guardrails to prevent privilege escalation or unintended capability inheritance during extended attribute management, particularly for v2 capabilities. Specifically, `cap_root_level` is a key player here. It's crucial to ensure that the user attempting to set capabilities actually has the appropriate permissions across user namespace boundaries. Now, my curiosity is piqued by the `cap_setfcap_level` function. I see that it examines the credentials and user namespace to determine a "level" for setting capabilities. I'm wondering if this "level" is properly initialized in the context of `cap_convert_nscap`. I need to figure out how `cred->user_ns->setfcap_level` is set, since I see it referenced in `cap_setfcap_level`. I'm going to track down the initialization of `init_user_ns` and how `setfcap_level` is set. |
| 44/3 | 2026/10/26 21:09 | tool | grepper |
0mArgs:{
"Expression": "struct user_namespace init_user_ns",
"PathPrefixes": [
"kernel/"
]
}Results: {
"Output": "kernel/user.c=30=EXPORT_SYMBOL_GPL(init_binfmt_misc);\n--\nkernel/user.c-36- */\nkernel/user.c:37:struct user_namespace init_user_ns = {\nkernel/user.c-38-\t.ns = NS_COMMON_INIT(init_user_ns),\n"
} |
| 45/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32097 output: 32 thoughts: 17 Thoughts: Okay, let's dive into this. Here's my thought process summarized, assuming I'm already pretty familiar with kernel internals: **Investigating `kernel/user.c`** Alright, I need to get into the details of something, and I immediately think, based on context, that the relevant code will be in `kernel/user.c`. From experience, I know that's where a lot of the user-space interaction stuff is handled. I'm going to jump straight to line 37, because that line number is very specific. That could be for any number of reasons. I could have a vague recollection of what I'm looking for, an error message points me there, a recent change, etc. Whatever the reason, line 37 is the critical place to focus my attention. It is a good starting point to further understand the code around it. |
| 46/3 | 2026/10/26 21:09 | tool | read-file |
0mArgs:{
"File": "kernel/user.c",
"FirstLine": 35,
"LineCount": 40
}Results: {
"Contents": " 35:\t * and 1 for... ?\n 36:\t */\n 37:\tstruct user_namespace init_user_ns = {\n 38:\t\t.ns = NS_COMMON_INIT(init_user_ns),\n 39:\t\t.uid_map = {\n 40:\t\t\t{\n 41:\t\t\t\t.extent[0] = {\n 42:\t\t\t\t\t.first = 0,\n 43:\t\t\t\t\t.lower_first = 0,\n 44:\t\t\t\t\t.count = 4294967295U,\n 45:\t\t\t\t},\n 46:\t\t\t\t.nr_extents = 1,\n 47:\t\t\t},\n 48:\t\t},\n 49:\t\t.gid_map = {\n 50:\t\t\t{\n 51:\t\t\t\t.extent[0] = {\n 52:\t\t\t\t\t.first = 0,\n 53:\t\t\t\t\t.lower_first = 0,\n 54:\t\t\t\t\t.count = 4294967295U,\n 55:\t\t\t\t},\n 56:\t\t\t\t.nr_extents = 1,\n 57:\t\t\t},\n 58:\t\t},\n 59:\t\t.projid_map = {\n 60:\t\t\t{\n 61:\t\t\t\t.extent[0] = {\n 62:\t\t\t\t\t.first = 0,\n 63:\t\t\t\t\t.lower_first = 0,\n 64:\t\t\t\t\t.count = 4294967295U,\n 65:\t\t\t\t},\n 66:\t\t\t\t.nr_extents = 1,\n 67:\t\t\t},\n 68:\t\t},\n 69:\t\t.owner = GLOBAL_ROOT_UID,\n 70:\t\t.group = GLOBAL_ROOT_GID,\n 71:\t\t.flags = USERNS_INIT_FLAGS,\n 72:\t#ifdef CONFIG_KEYS\n 73:\t\t.keyring_name_list = LIST_HEAD_INIT(init_user_ns.keyring_name_list),\n 74:\t\t.keyring_sem = __RWSEM_INITIALIZER(init_user_ns.keyring_sem),\n"
} |
| 47/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 32872 output: 34 thoughts: 132 Thoughts: **My Initial Thoughts on Namespace Initialization** Okay, so I'm looking at how user namespaces are initialized. My initial impression is that the `init_user_ns` structure is statically allocated, which means it's residing in the BSS or data segment, and any fields that aren't explicitly assigned will default to zero. That's a key observation. Specifically, the level is implicitly set to zero, and the `setfcap_level` is also implicitly zero. I need to keep those default values in mind as I delve deeper. Now, shifting my focus to `create_user_ns`, it looks like a new namespace is allocated using `kmem_cache_zalloc` (or something similar). This ensures that any newly allocated structure also starts with all its fields zeroed out. This is good to know, and I need to verify how `create_user_ns` handles these allocations and initializations, so let me do that now. |
| 48/3 | 2026/10/26 21:09 | tool | grepper |
0mArgs:{
"Expression": "user_ns_cachep",
"PathPrefixes": [
"kernel/user_namespace.c"
]
}Results: {
"Output": "kernel/user_namespace.c-26-\nkernel/user_namespace.c:27:static struct kmem_cache *user_ns_cachep __ro_after_init;\nkernel/user_namespace.c-28-static DEFINE_MUTEX(userns_state_mutex);\n--\nkernel/user_namespace.c=84=int create_user_ns(struct cred *new)\n--\nkernel/user_namespace.c-123-\tret = -ENOMEM;\nkernel/user_namespace.c:124:\tns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);\nkernel/user_namespace.c-125-\tif (!ns)\n--\nkernel/user_namespace.c-167-fail_free:\nkernel/user_namespace.c:168:\tkmem_cache_free(user_ns_cachep, ns);\nkernel/user_namespace.c-169-fail_dec:\n--\nkernel/user_namespace.c=1485=static __init int user_namespaces_init(void)\nkernel/user_namespace.c-1486-{\nkernel/user_namespace.c:1487:\tuser_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC | SLAB_ACCOUNT);\nkernel/user_namespace.c-1488-\tns_tree_add(\u0026init_user_ns);\n"
} |
| 49/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33601 output: 34 thoughts: 955 Thoughts: **Analyzing User Namespace Initialization and Security Checks** Okay, let's break this down. My initial observation is that `kmem_cache_zalloc` is being used to zero-allocate `ns`. Good, that's a solid start for clean initialization. The critical `ns->setfcap_level` is explicitly initialized afterward with `cap_setfcap_level`, so that's handled. Now, I'm checking for all creation/initialization points of the `struct user_namespace`. Looks like it's done solely through `init_user_ns` and `create_user_ns`. Standard practice, nothing unexpected there. Diving into `setfcap_top`, I need to verify its behavior. The code initializes `top` to `NULL`. The loop looks reasonable, and `kuid_has_mapping` is used with `seen` and `make_kuid(p, 0)`. So far, so good, no obvious issues. Next, I'm looking at `cap_root_level`. The `level` variable is initialized to `INT_MAX`, and the loop safely breaks when `ns == &init_user_ns` because `init_user_ns.parent` is `NULL`. This prevents dereferencing `NULL` and avoids a potential vulnerability. It's a clean implementation. Moving on to `map_root_level`, `level` is initialized to `INT_MAX`, again ensuring a safe initial state. The loop iterates through the parent namespaces, and the check for `id != (uid_t)-1 && map_has_id(new_map, id)` is pretty robust. Finally, I'm checking `verify_root_map`. The `level` variable is being initialized from `map_root_level`. No direct initialization here, but it inherits the safety of the function it calls. Now, I need to check how `cap_ptrace_access_check` and `cap_ptrace_traceme` handles security checks. The code checks for `PTRACE_MODE_ATTACH` and uses `cap_covers_setfcap`. Looks like `ret` is initialized to 0. It's properly defined. |
| 50/3 | 2026/10/26 21:09 | tool | read-file |
0mArgs:{
"File": "security/commoncap.c",
"FirstLine": 290,
"LineCount": 45
}Results: {
"Contents": " 290:\t * Otherwise, if we are in the same or an ancestor user_ns and have all the\n 291:\t * target task's capabilities, then ptrace access is allowed.\n 292:\t * If we have the ptrace capability to the target user_ns, then ptrace\n 293:\t * access is allowed.\n 294:\t * Else denied.\n 295:\t *\n 296:\t * Determine whether a process may access another, returning 0 if permission\n 297:\t * granted, -ve if denied.\n 298:\t */\n 299:\tint cap_ptrace_access_check(struct task_struct *child, unsigned int mode)\n 300:\t{\n 301:\t\tint ret = 0;\n 302:\t\tconst struct cred *cred, *child_cred;\n 303:\t\tconst kernel_cap_t *caller_caps;\n 304:\t\n 305:\t\trcu_read_lock();\n 306:\t\tcred = current_cred();\n 307:\t\tchild_cred = __task_cred(child);\n 308:\t\tif (mode \u0026 PTRACE_MODE_FSCREDS)\n 309:\t\t\tcaller_caps = \u0026cred-\u003ecap_effective;\n 310:\t\telse\n 311:\t\t\tcaller_caps = \u0026cred-\u003ecap_permitted;\n 312:\t\tif ((mode \u0026 PTRACE_MODE_ATTACH) \u0026\u0026\n 313:\t\t !cap_covers_setfcap(cred, child_cred))\n 314:\t\t\tgoto deny;\n 315:\t\tif (cred-\u003euser_ns == child_cred-\u003euser_ns \u0026\u0026\n 316:\t\t cap_issubset(child_cred-\u003ecap_permitted, *caller_caps))\n 317:\t\t\tgoto out;\n 318:\t\tif (ns_capable(child_cred-\u003euser_ns, CAP_SYS_PTRACE))\n 319:\t\t\tgoto out;\n 320:\tdeny:\n 321:\t\tret = -EPERM;\n 322:\tout:\n 323:\t\trcu_read_unlock();\n 324:\t\treturn ret;\n 325:\t}\n 326:\t\n 327:\t/**\n 328:\t * cap_ptrace_traceme - Determine whether another process may trace the current\n 329:\t * @parent: The task proposed to be the tracer\n 330:\t *\n 331:\t * If current may make use of CAP_SETFCAP in an ancestor of its user_ns that\n 332:\t * parent's CAP_SETFCAP or CAP_SYS_PTRACE doesn't reach, then ptrace access\n 333:\t * is denied.\n 334:\t * Otherwise, if parent is in the same or an ancestor user_ns and has all\n"
} |
| 51/3 | 2026/10/26 21:09 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35803 output: 34 thoughts: 44 Thoughts: Okay, here's my take on those thoughts, framed as an expert's self-reflection: **Deep Dive into `cap_ptrace_access_check` and `cap_ptrace_traceme`** Alright, so the core of this seems to be about tracing permissions. My initial observation is that in `cap_ptrace_access_check`, there's a quick denial path at the `deny:` label where `ret` gets slammed to `-EPERM` and immediately returned. That's a classic access control "fail fast" pattern. It tells me that the default is to *deny* trace access, which is the expected secure behavior. Now, the natural next step is to figure out the conditions that trigger this denial. What are we *checking* against? The code snippet seems truncated. That "deny:" block sets a return value, so, where and how is the return value used? How does the kernel decide to enter the deny block? What criteria need to be met to actually allow the trace request to proceed? I need more context to understand the *why* behind that `-EPERM`. What capabilities are being checked? Is there a particular security module involved? Since it involves tracing, I'm immediately thinking about `cap_ptrace_traceme`. That's the obvious link, and it's where I'd start to understand the *allowed* side of the equation. I know that `ptrace` is a powerful and potentially dangerous system call, so it's a critical area for kernel security. I will need to understand what that function does to see how we could get access. I'll need to know whether any of the capabilities listed in the function would give a process permission to circumvent the restrictions set in the `cap_ptrace_access_check`. |
| 52/3 | 2026/10/26 21:10 | tool | read-file |
0mArgs:{
"File": "security/commoncap.c",
"FirstLine": 335,
"LineCount": 40
}Results: {
"Contents": " 335:\t * current's capabilities, then ptrace access is allowed.\n 336:\t * If parent has the ptrace capability to current's user_ns, then ptrace\n 337:\t * access is allowed.\n 338:\t * Else denied.\n 339:\t *\n 340:\t * Determine whether the nominated task is permitted to trace the current\n 341:\t * process, returning 0 if permission is granted, -ve if denied.\n 342:\t */\n 343:\tint cap_ptrace_traceme(struct task_struct *parent)\n 344:\t{\n 345:\t\tint ret = 0;\n 346:\t\tconst struct cred *cred, *child_cred;\n 347:\t\n 348:\t\trcu_read_lock();\n 349:\t\tcred = __task_cred(parent);\n 350:\t\tchild_cred = current_cred();\n 351:\t\tif (!cap_covers_setfcap(cred, child_cred))\n 352:\t\t\tgoto deny;\n 353:\t\tif (cred-\u003euser_ns == child_cred-\u003euser_ns \u0026\u0026\n 354:\t\t cap_issubset(child_cred-\u003ecap_permitted, cred-\u003ecap_permitted))\n 355:\t\t\tgoto out;\n 356:\t\tif (has_ns_capability(parent, child_cred-\u003euser_ns, CAP_SYS_PTRACE))\n 357:\t\t\tgoto out;\n 358:\tdeny:\n 359:\t\tret = -EPERM;\n 360:\tout:\n 361:\t\trcu_read_unlock();\n 362:\t\treturn ret;\n 363:\t}\n 364:\t\n 365:\t/**\n 366:\t * cap_capget - Retrieve a task's capability sets\n 367:\t * @target: The task from which to retrieve the capability sets\n 368:\t * @effective: The place to record the effective set\n 369:\t * @inheritable: The place to record the inheritable set\n 370:\t * @permitted: The place to record the permitted set\n 371:\t *\n 372:\t * This function retrieves the capabilities of the nominated task and returns\n 373:\t * them to the caller.\n 374:\t */\n"
} |
| 53/3 | 2026/10/26 21:10 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36878 output: 19 thoughts: 458 Thoughts: **Analyzing the Security Implications of a Kernel Patch** Okay, so I'm looking at this patch and immediately see that `-EPERM` is being returned. That's a red flag, but a necessary one to ensure security. First, I need to understand *why* this is happening. The code's denying access, but is it doing so safely? Let's dig into `cap_convert_nscap` again. The critical question here is whether any uninitialized data could be copied during this process. Looking at the code: ```c newsize = sizeof(struct vfs_ns_cap_data); nscap = kmalloc(newsize, GFP_ATOMIC); if (!nscap) return -ENOMEM; nscap->rootid = cpu_to_le32(nsrootid); nsmagic = VFS_CAP_REVISION_3; magic = le32_to_cpu(cap->magic_etc); if (magic & VFS_CAP_FLAGS_EFFECTIVE) nsmagic |= VFS_CAP_FLAGS_EFFECTIVE; nscap->magic_etc = cpu_to_le32(nsmagic); memcpy(&nscap->data, &cap->data, sizeof(__le32) * 2 * VFS_CAP_U32); *ivalue = nscap; return newsize; ``` This part seems stable; it's preexisting and unchanged. It allocates the `vfs_ns_cap_data` structure and copies data. No immediate vulnerabilities jump out at me here. Everything is explicitly initialized before it's passed back, so that looks fine. Now, let's switch gears and check the `struct user_namespace`. This patch changed `bool parent_could_setfcap;` to `int setfcap_level;` within that structure. The crux of this is whether this structure or any of its members are exposed to user space. It *shouldn't* be directly copied, right? It's an internal kernel structure. Okay, it's not. But... is *any* of its data exposed? Aha! `user_namespace` info *is* exposed via procfs: things like `/proc/<pid>/uid_map`, `/proc/<pid>/gid_map`, and `/proc/<pid>/projid_map`. However, `setfcap_level` is *not* listed there. The next step is a thorough check. I'll need to verify that `parent_could_setfcap` (the old name) or `setfcap_level` (the new name) is *not* exposed in *any* procfs entry or anywhere else user-space can reach. If it *is* exposed, then this patch has a potential security vulnerability. Otherwise, it looks sound. |
| 54/3 | 2026/10/26 21:10 | tool | grepper |
0mArgs:{
"Expression": "setfcap_level"
}Results: {
"Output": "include/linux/capability.h=223=int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n--\ninclude/linux/capability.h-225-\ninclude/linux/capability.h:226:int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns);\ninclude/linux/capability.h-227-bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n--\ninclude/linux/user_namespace.h=79=struct user_namespace {\n--\ninclude/linux/user_namespace.h-88-\tunsigned long\t\tflags;\ninclude/linux/user_namespace.h:89:\t/* setfcap_level: CAP_SETFCAP held in this ns counts here and in the\ninclude/linux/user_namespace.h:90:\t * ancestors up to the one at this -\u003elevel, see cap_setfcap_level().\ninclude/linux/user_namespace.h-91-\t */\ninclude/linux/user_namespace.h:92:\tint\t\t\tsetfcap_level;\ninclude/linux/user_namespace.h-93-\n--\nkernel/user_namespace.c=84=int create_user_ns(struct cred *new)\n--\nkernel/user_namespace.c-127-\nkernel/user_namespace.c:128:\tns-\u003esetfcap_level = cap_setfcap_level(new, parent_ns);\nkernel/user_namespace.c-129-\n--\nkernel/user_namespace.c=936=static bool verify_root_map(const struct file *file,\n--\nkernel/user_namespace.c-954-\t\tif (!file_ns_capable(file, map_ns, CAP_SETFCAP) ||\nkernel/user_namespace.c:955:\t\t file_ns-\u003esetfcap_level \u003e level)\nkernel/user_namespace.c-956-\t\t\treturn false;\n--\nkernel/user_namespace.c-972-\t\treturn ns_capable(map_ns, CAP_SETFCAP) \u0026\u0026\nkernel/user_namespace.c:973:\t\t map_ns-\u003esetfcap_level \u003c= level;\nkernel/user_namespace.c-974-\n--\nsecurity/commoncap.c=124=int cap_capable(const struct cred *cred, struct user_namespace *target_ns,\n--\nsecurity/commoncap.c-134-/**\nsecurity/commoncap.c:135: * cap_setfcap_level - Determine how far up CAP_SETFCAP of a cred reaches\nsecurity/commoncap.c-136- * @cred: The credentials to use\n--\nsecurity/commoncap.c-141- * gets CAP_SETFCAP when it enters a user namespace, so having it there says\nsecurity/commoncap.c:142: * nothing about those ancestors. user_ns-\u003esetfcap_level does: it is taken\nsecurity/commoncap.c-143- * from the creator when the namespace is created.\n--\nsecurity/commoncap.c-148- */\nsecurity/commoncap.c:149:int cap_setfcap_level(const struct cred *cred, struct user_namespace *ns)\nsecurity/commoncap.c-150-{\n--\nsecurity/commoncap.c-154-\tif (cap_raised(cred-\u003ecap_effective, CAP_SETFCAP))\nsecurity/commoncap.c:155:\t\treturn cred-\u003euser_ns-\u003esetfcap_level;\nsecurity/commoncap.c-156-\n--\nsecurity/commoncap.c=170=bool cred_setfcap_reaches(const struct cred *cred, struct user_namespace *ns,\n--\nsecurity/commoncap.c-172-{\nsecurity/commoncap.c:173:\treturn cap_setfcap_level(cred, ns) \u003c= level;\nsecurity/commoncap.c-174-}\n--\nsecurity/commoncap.c-177- * The topmost ancestor of @ns whose root user tasks in @ns can write file\nsecurity/commoncap.c:178: * capabilities for: within @ns-\u003esetfcap_level, and mapped into @ns, or into\nsecurity/commoncap.c-179- * its parent while @ns has no uid_map yet. NULL if there is none. An\n--\nsecurity/commoncap.c=183=static struct user_namespace *setfcap_top(struct user_namespace *ns)\n--\nsecurity/commoncap.c-186-\nsecurity/commoncap.c:187:\tif (ns-\u003esetfcap_level \u003e= ns-\u003elevel)\nsecurity/commoncap.c-188-\t\treturn NULL;\n--\nsecurity/commoncap.c-191-\tfor (p = ns-\u003eparent; p; p = p-\u003eparent) {\nsecurity/commoncap.c:192:\t\tif (p-\u003elevel \u003c ns-\u003esetfcap_level)\nsecurity/commoncap.c-193-\t\t\tbreak;\n--\nsecurity/commoncap.c-206- * Tasks in @ns can have CAP_SETFCAP that counts in ancestors of @ns, see\nsecurity/commoncap.c:207: * cap_setfcap_level(). Check that CAP_SETFCAP of @cred reaches as far up as\nsecurity/commoncap.c-208- * tasks in @ns can make use of theirs.\n--\nsecurity/commoncap.c=250=int cap_settime(const struct timespec64 *ts, const struct timezone *tz)\n--\nsecurity/commoncap.c-258- * Tasks in a user namespace have CAP_SETFCAP that can count in ancestors of\nsecurity/commoncap.c:259: * the namespace, see cap_setfcap_level(). That is a privilege outside of the\nsecurity/commoncap.c-260- * namespace, so capabilities over the namespace are not enough to take\n--\nsecurity/commoncap.c=714=int cap_convert_nscap(const struct mnt_idmap *idmap, struct dentry *dentry,\n--\nsecurity/commoncap.c-746-\t\t\treturn -EINVAL;\nsecurity/commoncap.c:747:\t\tif (cap_root_level(fsroot, task_ns) \u003e= task_ns-\u003esetfcap_level)\nsecurity/commoncap.c-748-\t\t\t/* user is privileged, just write the v2 */\n--\nsecurity/commoncap.c-763-\tif (cap_root_level(vfsuid_into_kuid(vfsrootid), task_ns) \u003c\nsecurity/commoncap.c:764:\t task_ns-\u003esetfcap_level)\nsecurity/commoncap.c-765-\t\treturn -EPERM;\n--\nsecurity/commoncap.c-770-\nsecurity/commoncap.c:771:\tif (cap_root_level(rootid, task_ns) \u003c task_ns-\u003esetfcap_level)\nsecurity/commoncap.c-772-\t\treturn -EPERM;\n"
} |
| 55/3 | 2026/10/26 21:10 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39747 output: 378 thoughts: 1143 Thoughts: **KMSAN Assessment: No Need for Dedicated Testing** Alright, let's break this down. My primary concern here is determining if this patch necessitates a dedicated KMSAN fuzzing session. The focus is on `setfcap_level`, an internal component of these capability checks. First, I've got to rule out potential risks. I've considered scenarios involving data transfer to userspace, conditional logic with potentially uninitialized variables, complex data structure allocation, and any bounds checks or logic that could expose uninitialized memory. From my analysis, it's clear: 1. There are no modifications to structures that are sent to user space. `struct user_namespace` is updated but not copied to userspace. 2. `setfcap_level` is always initialized through `create_user_ns()` and `init_user_ns` and no local variables in relevant functions are left uninitialized. 3. No new data structure allocations are introduced; `user_namespace` is zero-allocated and initialized, as before. 4. No new bounds checks or length modifications are introduced that could result in reading uninitialized memory. Next, I need to keep in mind the documentation on KMSAN's role: "KMSAN should not be run when a bug can be caught by KASAN, LOCKDEP, or other standard bug detectors." Given that this patch focuses on improving user namespace capabilities, it's a security enhancement and should not introduce memory risks. I've double-checked the tests in `tools/testing/selftests/namespaces/setfcap_test.c` (userspace test) to verify they aren't relevant to KMSAN. The key is that the code changes should not introduce any of the following: uninitialized stack/heap variables, uninitialized struct fields, or buffer lengths or bounds that could read uninitialized memory. My specific checks confirm: * `create_user_ns` zeroes the `user_namespace` struct, including `setfcap_level`. * `map_has_id` initializes the extents with `memset`. * Functions such as `map_root_level`, `setfcap_top`, and `cap_root_level` explicitly check initialization. I've carefully considered the documentation regarding `NeedsKMSAN`. Based on this thorough review, I'm confident in setting `NeedsKMSAN` to `false` and documenting the KMSAN reasoning. The changes are not introducing any risks of uninitialized memory usage or info-leaks. |
| 56/3 | 2026/10/26 21:10 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series tightens capability checks related to CAP_SETFCAP in nested user namespaces, ptrace access checks, and file capability conversions on idmapped/non-idmapped mounts.\n\nAnalysis of memory initialization and safety:\n1. Struct user_namespace changes: Replaced the 'parent_could_setfcap' boolean field with 'setfcap_level' integer. Struct user_namespace is allocated with kmem_cache_zalloc (fully zeroed) and explicitly initialized in create_user_ns() as well as statically initialized to 0 for init_user_ns. Furthermore, struct user_namespace is internal kernel state and never copied to user space.\n2. Local variables and control flow: In all newly introduced helper functions (map_has_id, map_root_level, setfcap_top, cap_root_level, cap_setfcap_level, cred_setfcap_reaches, cred_may_setfcap_userns, cap_covers_setfcap), all local variables and function parameters are fully initialized before use.\n3. User copying / info-leaks: No data structures, buffers, or padding bytes are exposed or copied to userspace.\n4. Existing buffers / bounds checks: uid_gid_map structures processed in map_has_id and map_root_level are cleared via memset prior to extent population in map_write().\n\nAny potential issues arising from this patch would involve logical authorization bugs, permission checks, or potential pointer dereferences, which fall under logic testing or standard KASAN bug detectors rather than uninitialized memory detection. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series tightens capability checks related to CAP_SETFCAP in nested user namespaces, ptrace access checks, and file capability conversions on idmapped/non-idmapped mounts.\n\nAnalysis of memory initialization and safety:\n1. Struct user_namespace changes: Replaced the 'parent_could_setfcap' boolean field with 'setfcap_level' integer. Struct user_namespace is allocated with kmem_cache_zalloc (fully zeroed) and explicitly initialized in create_user_ns() as well as statically initialized to 0 for init_user_ns. Furthermore, struct user_namespace is internal kernel state and never copied to user space.\n2. Local variables and control flow: In all newly introduced helper functions (map_has_id, map_root_level, setfcap_top, cap_root_level, cap_setfcap_level, cred_setfcap_reaches, cred_may_setfcap_userns, cap_covers_setfcap), all local variables and function parameters are fully initialized before use.\n3. User copying / info-leaks: No data structures, buffers, or padding bytes are exposed or copied to userspace.\n4. Existing buffers / bounds checks: uid_gid_map structures processed in map_has_id and map_root_level are cleared via memset prior to extent population in map_write().\n\nAny potential issues arising from this patch would involve logical authorization bugs, permission checks, or potential pointer dereferences, which fall under logic testing or standard KASAN bug detectors rather than uninitialized memory detection. Therefore, a dedicated KMSAN fuzzing session is not warranted.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|