Created
June 17, 2022 22:40
-
-
Save ConnorNelson/dc32aa8e31be082438d54605081ccde0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import socket | |
import subprocess | |
import signal | |
import ctypes | |
def sandbox(target, *, privileged=True): | |
CLONE_NEWNS = 0x00020000 # New mount namespace group | |
CLONE_NEWCGROUP = 0x02000000 # New cgroup namespace | |
CLONE_NEWUTS = 0x04000000 # New utsname namespace | |
CLONE_NEWIPC = 0x08000000 # New ipc namespace | |
CLONE_NEWUSER = 0x10000000 # New user namespace | |
CLONE_NEWPID = 0x20000000 # New pid namespace | |
CLONE_NEWNET = 0x40000000 # New network namespace | |
PR_SET_PDEATHSIG = 1 | |
euid = os.geteuid() | |
egid = os.getegid() | |
libc = ctypes.CDLL("libc.so.6") | |
unshare_result = libc.unshare( | |
CLONE_NEWUSER | | |
CLONE_NEWNS | | |
CLONE_NEWCGROUP | | |
CLONE_NEWUTS | | |
CLONE_NEWIPC | | |
CLONE_NEWPID | | |
CLONE_NEWNET | |
) | |
assert unshare_result == 0 | |
if os.fork(): | |
os.wait() | |
return | |
libc.prctl(PR_SET_PDEATHSIG, signal.SIGKILL) | |
proc_values = { | |
"/proc/self/setgroups": "deny", | |
"/proc/self/uid_map": f"0 {euid} 1", | |
"/proc/self/gid_map": f"0 {egid} 1", | |
} | |
for path, value in proc_values.items(): | |
with open(path, "w") as f: | |
f.write(value) | |
socket.sethostname("sandbox") | |
subprocess.run(["/sbin/ip", "link", "set", "dev", "lo", "up"]) | |
if not privileged: | |
unshare_result = libc.unshare( | |
CLONE_NEWUSER | |
) | |
assert unshare_result == 0 | |
proc_values = { | |
"/proc/self/setgroups": "deny", | |
"/proc/self/uid_map": f"{euid} 0 1", | |
"/proc/self/gid_map": f"{egid} 0 1", | |
} | |
for path, value in proc_values.items(): | |
with open(path, "w") as f: | |
f.write(value) | |
target() | |
exit() | |
def target(): | |
print(os.getpid()) | |
os.execve("/bin/sh", ["/bin/sh"], os.environ) | |
s = socket.create_server(("0.0.0.0", 80)) | |
input() | |
print(s) | |
sandbox(target, privileged=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment