Python: Securing untrusted scripts/subprocess with chroot and chjail?

前端 未结 2 662
旧巷少年郎
旧巷少年郎 2021-02-13 21:34

I\'m writing a web server based on Python which should be able to execute \"plugins\" so that functionality can be easily extended.

For this I considered the approach to

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 22:09

    Perhaps something like this?

    # main.py
    subprocess.call(["python", "pluginhandler.py", "plugin", env])
    

    Then,

    # pluginhandler.py
    os.chroot(chrootpath)
    os.setgid(gid) # Important! Set GID first! See comments for details.
    os.setuid(uid)
    os.execle(programpath, arg1, arg2, ..., env)
    # or another subprocess call 
    subprocess.call["python", "plugin", env])
    

    EDIT: Wanted to use fork() but I didn't really understand what it did. Looked it up. New code!

    # main.py
    import os,sys
    somevar = someimportantdata
    pid = os.fork()
    if pid:
        # this is the parent process... do whatever needs to be done as the parent
    else:
        # we are the child process... lets do that plugin thing!
        os.setgid(gid) # Important! Set GID first! See comments for details.
        os.setuid(uid)
        os.chroot(chrootpath)
        import untrustworthyplugin
        untrustworthyplugin.run(somevar)
        sys.exit(0)
    

    This was useful and I pretty much just stole that code, so kudos to that guy for a decent example.

提交回复
热议问题