namespace-util: add helper for allocating an empty userns fd

This commit is contained in:
Lennart Poettering
2023-03-14 17:22:18 +01:00
parent 5783b4a954
commit e02fb2099c
2 changed files with 22 additions and 0 deletions

View File

@@ -262,6 +262,25 @@ int detach_mount_namespace_harder(uid_t target_uid, gid_t target_gid) {
return detach_mount_namespace();
}
int userns_acquire_empty(void) {
_cleanup_(sigkill_waitp) pid_t pid = 0;
_cleanup_close_ int userns_fd = -EBADF;
int r;
r = safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS, &pid);
if (r < 0)
return r;
if (r == 0)
/* Child. We do nothing here, just freeze until somebody kills us. */
freeze();
r = namespace_open(pid, NULL, NULL, NULL, &userns_fd, NULL);
if (r < 0)
return log_error_errno(r, "Failed to open userns fd: %m");
return TAKE_FD(userns_fd);
}
int userns_acquire(const char *uid_map, const char *gid_map) {
char path[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t) + 1];
_cleanup_(sigkill_waitp) pid_t pid = 0;

View File

@@ -51,8 +51,11 @@ static inline bool userns_shift_range_valid(uid_t shift, uid_t range) {
return true;
}
int userns_acquire_empty(void);
int userns_acquire(const char *uid_map, const char *gid_map);
int netns_acquire(void);
int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type);
int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range);