Ticket #600: setgroups.patch

File setgroups.patch, 2.5 KB (added by Jean-Paul Calderone, 16 years ago)
  • twisted/scripts/twistd.py

     
    33# See LICENSE for details.
    44
    55
    6 from twisted.python import log, syslog
    7 from twisted.python.util import switchUID
     6from twisted.python import log, syslog, util
    87from twisted.application import app, service
    98from twisted import copyright
    109import os, errno, signal, sys
     
    118117    os.close(null)
    119118
    120119def shedPrivileges(euid, uid, gid):
    121     switchUID(uid, gid, euid)
     120    util.switchUID(uid, gid, euid)
    122121    extra = euid and 'e' or ''
    123122    log.msg('set %suid/%sgid %s/%s' % (extra, extra, uid, gid))
    124123
     
    144143        launchWithName(process.processName)
    145144    setupEnvironment(config)
    146145    service.IService(application).privilegedStartService()
    147     shedPrivileges(config['euid'], process.uid, process.gid)
    148     app.startApplication(application, not config['no_save'])
     146    try:
     147        shedPrivileges(config['euid'], process.uid, process.gid)
     148    except util.CannotSetGroups, e:
     149        e.desiredGroups.sort()
     150        e.actualGroups.sort()
     151        log.msg("Tried to set groups to %r but failed (got %r instead)." % (
     152            e.desiredGroups, e.actualGroups))
     153        log.msg("Refusing to start application.")
     154        raise SystemExit()
     155    else:
     156        app.startApplication(application, not config['no_save'])
    149157
    150 
    151158def runApp(config):
    152159    checkPID(config['pidfile'])
    153160    passphrase = app.getPassphrase(config['encrypted'])
  • twisted/python/util.py

     
    562562    L2.sort()
    563563    return [e[2] for e in L2]
    564564
     565class CannotSetGroups(RuntimeError):
     566    """Raised when os.setgroups() fails with a permission error.
     567    """
     568    def __init__(self, actualGroups, desiredGroups):
     569        self.actualGroups = actualGroups
     570        self.desiredGroups = desiredGroups
     571
    565572try:
    566573    import pwd, grp
    567574    from os import setgroups, getgroups
     
    576583        except OSError, e:
    577584            if e.errno == errno.EPERM:
    578585                groups = getgroups()
    579                 for g in getgroups():
     586                for g in groups:
    580587                    if g not in l:
    581                         raise
     588                        raise CannotSetGroups(groups, l)
    582589            else:
    583590                raise
    584591