summaryrefslogtreecommitdiff
path: root/examples/fakeroot.py
blob: 47db33020bb4b7516f248bc7a0a3470d67104e01 (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
#!/usr/bin/python3
# Copyright 2024 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: GPL-3

"""Vaguely emulate fakeroot using a user namespace that maps the current user
and group to root and the rest of the low range to a subuid range without
performing any chroot. This is similar to unshare --map-root-user --map-auto.
"""

import os
import sys

if __file__.split("/")[-2:-1] == ["examples"]:
    sys.path.insert(0, "/".join(__file__.split("/")[:-2]))

import linuxnamespaces


def main() -> None:
    uidmap = [
        linuxnamespaces.IDMapping(0, os.getuid(), 1),
        linuxnamespaces.IDAllocation.loadsubid("uid").allocatemap(65535, 1),
    ]
    gidmap = [
        linuxnamespaces.IDMapping(0, os.getgid(), 1),
        linuxnamespaces.IDAllocation.loadsubid("gid").allocatemap(65535, 1),
    ]
    linuxnamespaces.unshare_user_idmap(uidmap, gidmap)
    os.execlp(os.environ["SHELL"], os.environ["SHELL"])


if __name__ == "__main__":
    main()