Issue #428 resolved

RFE: implement a "drop privileges" feature for CherryPy's embedded HTTP server

Anonymous created an issue

Would it be possible to add a feature whereby CherryPy (when using the embedded HTTP server) changes uid and gid to values specified in the configuration, after binding its listening socket? This would allow it to serve on privileged ports (e.g. 80) while running as an unprivileged user.

Reported by danc86@gmail.com

Comments (7)

  1. Anonymous

    I don't think it should be part of CP itself but it would be really interesting to port this recipe to the main documentation website.

  2. Robert Brewer

    Here's a lean and mean version:

    def drop_privileges(new_user='nobody', new_group='nogroup'):
        """Drop privileges. UNIX only."""
        # Special thanks to Gavin Baker: http://antonym.org/node/100.
        
        import os, pwd, grp
        
        def names():
            return pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0]
        name, group = names()
        cherrypy.log('Started as %r/%r' % (name, group), "PRIV")
        
        if os.getuid() != 0:
            # We're not root so, like, whatever dude.
            cherrypy.log("Already running as %r" % name, "PRIV")
            return
        
        # Try setting the new uid/gid (from new_user/new_group).
        try:
            os.setgid(grp.getgrnam(new_group)[2])
        except OSError, e:
            cherrypy.log('Could not set effective group id: %r' % e, "PRIV")
        
        try:
            os.setuid(pwd.getpwnam(new_user)[2])
        except OSError, e:
            cherrypy.log('Could not set effective user id: %r' % e, "PRIV")
        
        # Ensure a very convervative umask
        old_umask = os.umask(077)
        cherrypy.log('Old umask: %o, new umask: 077' % old_umask, "PRIV")
        cherrypy.log('Running as %r/%r' % names(), "PRIV")
    
  3. Robert Brewer

    I've attached a patch which puts this feature into the Engine. You would still use it via on_start_engine_list, most likely, although it's callable whenever. Thoughts?

  4. Anonymous

    If you feel this patch won't have sneaky security issue then I don't mind it being included. If there are potentials security problems I am not sure we should take that risk.

  5. Log in to comment