Skip to content

Instantly share code, notes, and snippets.

@shaardie
Created October 30, 2016 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaardie/ea08884060e03585a655ec01c13ae197 to your computer and use it in GitHub Desktop.
Save shaardie/ea08884060e03585a655ec01c13ae197 to your computer and use it in GitHub Desktop.
Run external python function "run" mostly secure
#!/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