Created
October 30, 2016 16:55
-
-
Save shaardie/ea08884060e03585a655ec01c13ae197 to your computer and use it in GitHub Desktop.
Run external python function "run" mostly secure
This file contains hidden or 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
#!/usr/bin/env python3 | |
import os | |
import sys | |
import pwd | |
import grp | |
from importlib.machinery import SourceFileLoader | |
def secure(directory, user='nobody', group='nogroup'): | |
uid = os.getuid() | |
# Not root user, so unable to drop | |
if uid != 0: | |
return False | |
# Get the uid/gid from the name | |
current_uid = pwd.getpwnam(user)[2] | |
current_gid = grp.getgrnam(group)[2] | |
# Change root to another directory | |
os.chdir(directory) | |
os.chroot(".") | |
# New uid and gid | |
os.setgid(current_gid) | |
os.setuid(current_uid) | |
# Change umask | |
os.umask(0o077) | |
return True | |
def main(path): | |
fullpath = os.path.abspath(path) | |
directory = os.path.dirname(fullpath) | |
filename = os.path.basename(fullpath) | |
if not secure(directory): | |
print("unable to secure") | |
return False | |
try: | |
SourceFileLoader("", filename).load_module().run() | |
except Exception as e: | |
print(e) | |
return True | |
if __name__ == "__main__": | |
sys.exit(main(sys.argv[1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment