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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
| | #! /usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Copyright Red Hat
# Author: David Gibson <david@gibson.dropbear.id.au>
"""
Test A Simple Socket Transport
unshare.py - Create and run commands in Linux namespaces
"""
import contextlib
import os
import subprocess
import tempfile
from typing import Any, Callable, Iterator
import exeter
from . import cmdsite
# FIXME: Can this be made more portable?
UNIX_PATH_MAX = 108
NSTOOL_BIN = './nstool'
class Unshare(cmdsite.CmdSite):
"""A bundle of Linux namespaces managed by nstool"""
sockpath: str
parent: cmdsite.CmdSite
_pid: int
def __init__(self, name: str, sockpath: str,
parent: cmdsite.CmdSite = cmdsite.BUILD_HOST,
parent_priv: bool = False) -> None:
if len(sockpath) > UNIX_PATH_MAX:
raise ValueError(
f'Unix domain socket path "{sockpath}" is too long'
)
super().__init__(name)
self.sockpath = sockpath
self.parent = parent
self.parent_priv = parent_priv
self.parent.fg(NSTOOL_BIN, 'info', '-wp', self.sockpath, timeout=1)
# PID of the nstool hold process as seen by another site which can
# see the nstool socket (important when using PID namespaces)
def relative_pid(self, relative_to: cmdsite.CmdSite) -> int | None:
cmd = [NSTOOL_BIN, 'info', '-p', self.sockpath]
relpid = int(relative_to.output(*cmd))
if not relpid:
return None
return relpid
def popen(self, *cmd: str, privilege: bool = False,
**kwargs: Any) -> subprocess.Popen[bytes]:
hostcmd = [NSTOOL_BIN, 'exec']
if privilege:
hostcmd.append('--keep-caps')
hostcmd += [self.sockpath, '--']
hostcmd += list(cmd)
return self.parent.popen(*hostcmd, privilege=self.parent_priv,
**kwargs)
@contextlib.contextmanager
def unshare(name: str, *opts: str,
parent: cmdsite.CmdSite = cmdsite.BUILD_HOST,
privilege: bool = False) -> Iterator[Unshare]:
# Create path for temporary nstool Unix socket
with tempfile.TemporaryDirectory() as tmpd:
sockpath = os.path.join(tmpd, name)
cmd = ['unshare'] + list(opts)
cmd += ['--', NSTOOL_BIN, 'hold', sockpath]
with parent.bg(*cmd, privilege=privilege) as holder:
try:
yield Unshare(name, sockpath, parent=parent,
parent_priv=privilege)
finally:
try:
parent.fg(NSTOOL_BIN, 'stop', sockpath)
finally:
try:
holder.run(timeout=0.1)
holder.kill()
finally:
try:
os.remove(sockpath)
except FileNotFoundError:
pass
def _userns_setup() -> Iterator[cmdsite.CmdSite]:
with unshare('usernetns', '-Ucn') as site:
yield site
def _nested_setup() -> Iterator[cmdsite.CmdSite]:
with unshare('userns', '-Uc') as userns:
with unshare('netns', '-n', parent=userns, privilege=True) as netns:
yield netns
def _pidns_setup() -> Iterator[cmdsite.CmdSite]:
with unshare('pidns', '-Upfn') as site:
yield site
def connect_site() -> Iterator[Unshare]:
with tempfile.TemporaryDirectory() as tmpd:
sockpath = os.path.join(tmpd, 'nons')
holdcmd = [NSTOOL_BIN, 'hold', sockpath]
with subprocess.Popen(holdcmd) as holder:
try:
yield Unshare("fakens", sockpath)
finally:
holder.kill()
os.remove(sockpath)
def selftests() -> None:
@exeter.test
def test_userns() -> None:
cmd = ['capsh', '--has-p=CAP_SETUID']
status = cmdsite.BUILD_HOST.fg(*cmd, check=False)
assert status.returncode != 0
with unshare('userns', '-Ucn') as ns:
ns.fg(*cmd, privilege=True)
@exeter.test
def test_relative_pid() -> None:
with unshare('pidns', '-Upfn') as site:
# The holder is init (pid 1) within its own pidns
exeter.assert_eq(site.relative_pid(site), 1)
def sockdir_cleanup(setup: Callable[[], Iterator[cmdsite.CmdSite]]) \
-> None:
cm = contextlib.contextmanager(setup)
def mess(sockpaths: list[str]) -> None:
with cm() as site:
while isinstance(site, Unshare):
sockpaths.append(site.sockpath)
site = site.parent
sockpaths: list[str] = []
mess(sockpaths)
assert sockpaths
for path in sockpaths:
assert not os.path.exists(os.path.dirname(path))
# General tests for all the nstool examples
for setup in [_userns_setup, _nested_setup, _pidns_setup]:
# Common cmdsite.CmdSite & NetSite tests
cmdsite.CmdSite.test(setup)
exeter.register(f'{setup.__qualname__}|sockdir_cleanup',
sockdir_cleanup, setup)
cmdsite.CmdSite.test(connect_site)
|