summaryrefslogtreecommitdiffhomepage
path: root/test/test_go_isolation.py
blob: ba3390eafd3cf18e9df20e6c73e4526f5ecfc49a (plain) (blame)
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import grp
import os
import pwd

import pytest
from unit.applications.lang.go import ApplicationGo
from unit.option import option
from unit.utils import getns

prerequisites = {'modules': {'go': 'any'}, 'features': {'isolation': True}}

client = ApplicationGo()


def unpriv_creds():
    nobody_uid = pwd.getpwnam('nobody').pw_uid

    try:
        nogroup_gid = grp.getgrnam('nogroup').gr_gid
        nogroup = 'nogroup'
    except KeyError:
        nogroup_gid = grp.getgrnam('nobody').gr_gid
        nogroup = 'nobody'

    return (nobody_uid, nogroup_gid, nogroup)


def test_isolation_values():
    client.load('ns_inspect')

    obj = client.getjson()['body']

    for ns, ns_value in option.available['features']['isolation'].items():
        if ns.upper() in obj['NS']:
            assert obj['NS'][ns.upper()] == ns_value, f'{ns} match'


def test_isolation_unpriv_user(require):
    require(
        {
            'privileged_user': False,
            'features': {'isolation': ['unprivileged_userns_clone']},
        }
    )

    client.load('ns_inspect')
    obj = client.getjson()['body']

    assert obj['UID'] == os.geteuid(), 'uid match'
    assert obj['GID'] == os.getegid(), 'gid match'

    client.load('ns_inspect', isolation={'namespaces': {'credential': True}})

    obj = client.getjson()['body']

    nobody_uid, nogroup_gid, nogroup = unpriv_creds()

    # unprivileged unit map itself to nobody in the container by default
    assert obj['UID'] == nobody_uid, 'uid of nobody'
    assert obj['GID'] == nogroup_gid, f'gid of {nogroup}'

    client.load(
        'ns_inspect',
        user='root',
        isolation={'namespaces': {'credential': True}},
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid match user=root'
    assert obj['GID'] == 0, 'gid match user=root'

    client.load(
        'ns_inspect',
        user='root',
        group=nogroup,
        isolation={'namespaces': {'credential': True}},
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid match user=root group=nogroup'
    assert obj['GID'] == nogroup_gid, 'gid match user=root group=nogroup'

    client.load(
        'ns_inspect',
        user='root',
        group='root',
        isolation={
            'namespaces': {'credential': True},
            'uidmap': [{'container': 0, 'host': os.geteuid(), 'size': 1}],
            'gidmap': [{'container': 0, 'host': os.getegid(), 'size': 1}],
        },
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid match uidmap'
    assert obj['GID'] == 0, 'gid match gidmap'


def test_isolation_priv_user(require):
    require({'privileged_user': True})

    client.load('ns_inspect')

    nobody_uid, nogroup_gid, nogroup = unpriv_creds()

    obj = client.getjson()['body']

    assert obj['UID'] == nobody_uid, 'uid match'
    assert obj['GID'] == nogroup_gid, 'gid match'

    client.load('ns_inspect', isolation={'namespaces': {'credential': True}})

    obj = client.getjson()['body']

    # privileged unit map app creds in the container by default
    assert obj['UID'] == nobody_uid, 'uid nobody'
    assert obj['GID'] == nogroup_gid, 'gid nobody'

    client.load(
        'ns_inspect',
        user='root',
        isolation={'namespaces': {'credential': True}},
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid nobody user=root'
    assert obj['GID'] == 0, 'gid nobody user=root'

    client.load(
        'ns_inspect',
        user='root',
        group=nogroup,
        isolation={'namespaces': {'credential': True}},
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid match user=root group=nogroup'
    assert obj['GID'] == nogroup_gid, 'gid match user=root group=nogroup'

    client.load(
        'ns_inspect',
        user='root',
        group='root',
        isolation={
            'namespaces': {'credential': True},
            'uidmap': [{'container': 0, 'host': 0, 'size': 1}],
            'gidmap': [{'container': 0, 'host': 0, 'size': 1}],
        },
    )

    obj = client.getjson()['body']

    assert obj['UID'] == 0, 'uid match uidmap user=root'
    assert obj['GID'] == 0, 'gid match gidmap user=root'

    # map 65535 uids
    client.load(
        'ns_inspect',
        user='nobody',
        isolation={
            'namespaces': {'credential': True},
            'uidmap': [{'container': 0, 'host': 0, 'size': nobody_uid + 1}],
        },
    )

    obj = client.getjson()['body']

    assert obj['UID'] == nobody_uid, 'uid match uidmap user=nobody'
    assert obj['GID'] == nogroup_gid, 'gid match uidmap user=nobody'


def test_isolation_mnt(require):
    require(
        {
            'features': {'isolation': ['unprivileged_userns_clone', 'mnt']},
        }
    )

    client.load(
        'ns_inspect',
        isolation={'namespaces': {'mount': True, 'credential': True}},
    )

    obj = client.getjson()['body']

    # all but user and mnt
    allns = list(option.available['features']['isolation'].keys())
    allns.remove('user')
    allns.remove('mnt')

    for ns in allns:
        if ns.upper() in obj['NS']:
            assert (
                obj['NS'][ns.upper()]
                == option.available['features']['isolation'][ns]
            ), f'{ns} match'

    assert obj['NS']['MNT'] != getns('mnt'), 'mnt set'
    assert obj['NS']['USER'] != getns('user'), 'user set'


def test_isolation_pid(is_su, require):
    require({'features': {'isolation': ['pid']}})

    if not is_su:
        require(
            {
                'features': {
                    'isolation': [
                        'unprivileged_userns_clone',
                        'user',
                        'mnt',
                    ]
                }
            }
        )

    isolation = {'namespaces': {'pid': True}}

    if not is_su:
        isolation['namespaces']['mount'] = True
        isolation['namespaces']['credential'] = True

    client.load('ns_inspect', isolation=isolation)

    obj = client.getjson()['body']

    assert obj['PID'] == 2, 'pid of container is 2'


def test_isolation_namespace_false():
    client.load('ns_inspect')
    allns = list(option.available['features']['isolation'].keys())

    remove_list = ['unprivileged_userns_clone', 'ipc', 'cgroup']
    allns = [ns for ns in allns if ns not in remove_list]

    namespaces = {}
    for ns in allns:
        if ns == 'user':
            namespaces['credential'] = False
        elif ns == 'mnt':
            namespaces['mount'] = False
        elif ns == 'net':
            namespaces['network'] = False
        elif ns == 'uts':
            namespaces['uname'] = False
        else:
            namespaces[ns] = False

    client.load('ns_inspect', isolation={'namespaces': namespaces})

    obj = client.getjson()['body']

    for ns in allns:
        if ns.upper() in obj['NS']:
            assert (
                obj['NS'][ns.upper()]
                == option.available['features']['isolation'][ns]
            ), f'{ns} match'


def test_go_isolation_rootfs_container(is_su, require, temp_dir):
    if not is_su:
        require(
            {
                'features': {
                    'isolation': [
                        'unprivileged_userns_clone',
                        'user',
                        'mnt',
                        'pid',
                    ]
                }
            }
        )

    isolation = {'rootfs': temp_dir}

    if not is_su:
        isolation['namespaces'] = {
            'mount': True,
            'credential': True,
            'pid': True,
        }

    client.load('ns_inspect', isolation=isolation)

    obj = client.getjson(url='/?file=/go/app')['body']

    assert obj['FileExists'], 'app relative to rootfs'

    obj = client.getjson(url='/?file=/bin/sh')['body']
    assert not obj['FileExists'], 'file should not exists'


def test_go_isolation_rootfs_container_priv(require, temp_dir):
    require({'privileged_user': True, 'features': {'isolation': ['mnt']}})

    isolation = {
        'namespaces': {'mount': True},
        'rootfs': temp_dir,
    }

    client.load('ns_inspect', isolation=isolation)

    obj = client.getjson(url='/?file=/go/app')['body']

    assert obj['FileExists'], 'app relative to rootfs'

    obj = client.getjson(url='/?file=/bin/sh')['body']
    assert not obj['FileExists'], 'file should not exists'


def test_go_isolation_rootfs_automount_tmpfs(is_su, require, temp_dir):
    try:
        open("/proc/self/mountinfo")
    except:
        pytest.skip('The system lacks /proc/self/mountinfo file')

    if not is_su:
        require(
            {
                'features': {
                    'isolation': [
                        'unprivileged_userns_clone',
                        'user',
                        'mnt',
                        'pid',
                    ]
                }
            }
        )

    isolation = {'rootfs': temp_dir}

    if not is_su:
        isolation['namespaces'] = {
            'mount': True,
            'credential': True,
            'pid': True,
        }

    isolation['automount'] = {'tmpfs': False}

    client.load('ns_inspect', isolation=isolation)

    obj = client.getjson(url='/?mounts=true')['body']

    assert (
        "/ /tmp" not in obj['Mounts'] and "tmpfs" not in obj['Mounts']
    ), 'app has no /tmp mounted'

    isolation['automount'] = {'tmpfs': True}

    client.load('ns_inspect', isolation=isolation)

    obj = client.getjson(url='/?mounts=true')['body']

    assert (
        "/ /tmp" in obj['Mounts'] and "tmpfs" in obj['Mounts']
    ), 'app has /tmp mounted on /'