summaryrefslogtreecommitdiff
path: root/netjail/netjail-privdrop.sh
blob: 816bdf8010104068d0f81f74a5e174ec6439c884 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/sh

# This file is in the public domain.
#
# Shell script for to setup one instance of a network namespace.
# Used by buildslaves to avoid port conflicts.
#
# First argument ($1) must be a unique number (unique amongst
# all users of the script) to be used in
# the name of the virtual network devices and the namespace itself.
#
# The remaining arguments are the command (and arguments to the
# command) to be run in the network namespace (i.e. 'make check').

# This script is executed by root and should *not* be in sudoers

set -eu
set -x

N=$1
shift 1

NAME=buildernet-$N

# Go to the root namespace to delete our network NS,
# as we can't do it from inside when we use 'ip netns' to enter it.
nsenter -m -t 1 -- ip netns del $NAME

# Configure our network inside the namespace
ip link set dev lo up
ip link set dev "tap-$N" up
dhclient --no-pid "tap-$N"

# Finally, run whatever the user's command was
ME=${SUDO_USER:?must run in sudo}

# Execute target program as the original user.
# We should already be in a PID namespace, but we still need to mount proc.
set +e
unshare --mount-proc -- sudo -u "$ME" -- "$@"
ret=$?
set -e

# Release the lease
dhclient --no-pid -r || false

# Exit with the target program's exit status
exit $ret