micro / faisi /src /runner /drop_privileges.py
ppJustin's picture
Add files using upload-large-folder tool
c5f5de4 verified
Raw History Blame Contribute Delete
1.11 kB
"""Drop mount-namespace setup privileges before running a jailed Python role."""
import ctypes
import errno
import os
import sys
class Header(ctypes.Structure):
_fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)]
class Data(ctypes.Structure):
_fields_ = [(field, ctypes.c_uint32) for field in ("effective", "permitted", "inheritable")]
def main():
libc = ctypes.CDLL(None, use_errno=True)
# PR_SET_NO_NEW_PRIVS, PR_CAP_AMBIENT_CLEAR_ALL, PR_CAPBSET_DROP.
for option, arg in ((38, 1), (47, 4)):
if libc.prctl(option, arg, 0, 0, 0):
raise OSError(ctypes.get_errno(), "privilege setup")
for capability in range(64):
if libc.prctl(24, capability, 0, 0, 0):
if ctypes.get_errno() == errno.EINVAL:
break
raise OSError(ctypes.get_errno(), "capability bounding set")
if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()):
raise OSError(ctypes.get_errno(), "capability drop")
os.execv(sys.executable, [sys.executable, "-u", *sys.argv[1:]])
if __name__ == "__main__":
main()