From 8aa527684c837c18621b76f5ef440caa2f05d0b0 Mon Sep 17 00:00:00 2001 From: Andy Lutomirski Date: Sun, 19 Oct 2014 12:08:25 -0500 Subject: nsenter: A tool to use setns(2) This implements all of the namespace parts of nsenter, but UID and GID switching are missing, as are -r and -w (both because they're not strictly necessary and because the nsenter manpage has an insufficient description of how they work). --- toys/pending/nsenter.c | 104 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 toys/pending/nsenter.c diff --git a/toys/pending/nsenter.c b/toys/pending/nsenter.c new file mode 100644 index 00000000..33db873e --- /dev/null +++ b/toys/pending/nsenter.c @@ -0,0 +1,104 @@ +/* nsenter.c - Enter existing namespaces + * + * Copyright 2014 andy Lutomirski + +USE_NSENTER(NEWTOY(nsenter, "<1F(no-fork)t#(target)i:(ipc);m:(mount);n:(net);p:(pid);u:(uts);U:(user);", TOYFLAG_USR|TOYFLAG_BIN)) + +config NSENTER + bool "nsenter" + default n + help + usage: nsenter [-t pid] [-F] [-i] [-m] [-n] [-p] [-u] [-U] COMMAND... + + Run COMMAND in a different set of namespaces. + + -T PID to take namespaces from + -F don't fork, even if -p is set + + The namespaces to switch are: + + -i SysV IPC (message queues, semaphores, shared memory) + -m Mount/unmount tree + -n Network address, sockets, routing, iptables + -p Process IDs and init (will fork unless -F is used) + -u Host and domain names + -U UIDs, GIDs, capabilities + + Each of those options takes an optional argument giving the path of + the namespace file (usually in /proc). This optional argument is + mandatory unless -t is used. +*/ + +#define FOR_nsenter +#define _GNU_SOURCE +#include "toys.h" +#include +#include +#include + +#define NUM_NSTYPES 6 + +struct nstype { + int type; + const char *name; +}; + +struct nstype nstypes[NUM_NSTYPES] = { + {CLONE_NEWUSER, "user"}, /* must be first to allow non-root operation */ + {CLONE_NEWUTS, "uts"}, + {CLONE_NEWPID, "pid"}, + {CLONE_NEWNET, "net"}, + {CLONE_NEWNS, "mnt"}, + {CLONE_NEWIPC, "ipc"}, +}; + +GLOBALS( + char *nsnames[6]; + long targetpid; +) + +static void enter_by_name(int idx) +{ + int fd, rc; + char buf[64]; + char *filename = TT.nsnames[idx]; + + if (!(toys.optflags & (1<