Пример #1
0
    def getCurrentPrivilegesDescription(self):
        """
        Return a text describing current privileges.

        On Unix it informs if the process has root capabilities.
        """
        if self.impersonate_local_account:
            return _(u'root capabilities enabled.')
        else:
            return _(u'root capabilities disabled.')
Пример #2
0
    def home_segments(self):
        '''See `ILocalFilesystem`.'''

        if not self._avatar:
            return self._pathSplitRecursive(str(os.path.expanduser('~')))

        if self._avatar.root_folder_path is None:
            return self._pathSplitRecursive(self._avatar.home_folder_path)

        home_lower = self._avatar.home_folder_path.lower()
        root_lower = self._avatar.root_folder_path.rstrip('/\\').lower()
        # Check that we have a valid home folder.
        if not home_lower.startswith(root_lower):
            raise CompatError(
                20019,
                _(
                    'User home folder "%s" is not withing the root folder '
                    '"%s".' % (
                        self._avatar.home_folder_path,
                        self._avatar.root_folder_path),
                    ),
                )

        path = self._avatar.home_folder_path[len(root_lower):]
        return self._pathSplitRecursive(path)
Пример #3
0
def _change_effective_privileges(username=None, euid=None, egid=None):
    """
    Change current process effective user and group.
    """
    if username:
        username_encoded = username.encode('utf-8')
        try:
            pwnam = pwd.getpwnam(username_encoded)
        except KeyError:
            raise ChangeUserException(_(u'User does not exists.'))
        euid = pwnam.pw_uid
        egid = pwnam.pw_gid
    else:
        assert euid is not None
        pwnam = pwd.getpwuid(euid)
        username_encoded = pwnam.pw_name

    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return

    try:
        if uid != 0:
            # We set root euid first to get full permissions.
            os.seteuid(0)
            os.setegid(0)

        # Make sure to set user euid as the last action. Otherwise we will no
        # longer have permissions to change egid.
        os.initgroups(username_encoded, egid)
        os.setegid(egid)
        os.seteuid(euid)
    except OSError:
        raise ChangeUserException(u'Could not switch user.')
Пример #4
0
 def raiseFailedToSetOwner(self, owner, path, message=u''):
     """
     Helper for raising the exception from a single place.
     """
     raise CompatError(
         1016,
         _(u'Failed to set owner to "%s" for "%s". %s' % (
             owner, path, message)),
         )
Пример #5
0
 def raiseFailedToAddGroup(self, group, path, message=u''):
     """
     Helper for raising the exception from a single place.
     """
     raise CompatError(
         1017,
         _(u'Failed to add group "%s" for "%s". %s' % (
             group, path, message)),
         )
Пример #6
0
def _get_euid_and_egid(username_encoded):
    """
    Return a tuple of (euid, egid) for username.
    """
    try:
        pwnam = pwd.getpwnam(username_encoded)
    except KeyError:
        raise ChangeUserException(_(u'User does not exists.'))

    return (pwnam.pw_uid, pwnam.pw_gid)
Пример #7
0
 def getHomeFolder(self, username, token=None):
     '''Get home folder for local (or NIS) user.'''
     try:
         username_encoded = username.encode('utf-8')
         home_folder = pwd.getpwnam(
             username_encoded).pw_dir.decode('utf-8')
         return home_folder.rstrip('/')
     except KeyError:
         self.raiseFailedToGetHomeFolder(
             username, _(u'Username not found.'))
Пример #8
0
def install_nt_service(service_class, options):
    """Install an NT service."""
    try:
        module_path = sys.modules[service_class.__module__].__file__
    except AttributeError:
        # maybe py2exe went by.
        from sys import executable

        module_path = executable
    module_file = os.path.splitext(os.path.abspath(module_path))[0]
    service_class._svc_reg_class_ = "%s.%s" % (module_file, service_class.__name__)

    try:
        win32serviceutil.InstallService(
            service_class._svc_reg_class_,
            service_class._svc_name_,
            service_class._svc_display_name_,
            startType=win32service.SERVICE_AUTO_START,
        )
        print(
            _(
                'Service "%s" successfully installed.\n'
                'Please use "sc" command or Windows Services to manage '
                "this service." % (service_class._svc_name_)
            )
        )
    except pywintypes.error as error:
        if error[0] == 5:
            print(
                _(
                    "You do not have permissions to install this service.\n"
                    "Please install the service as an administrator."
                )
            )
        else:
            print(
                _(
                    "Failed to install the service %s:%s.\n"
                    "%s:%d %s"
                    % (service_class._svc_name_, service_class._svc_display_name_, error[1], error[0], error[2])
                )
            )
Пример #9
0
 def __init__(self, username=None, euid=0, egid=0):
     '''Initialize the context manager.'''
     if username is not None:
         try:
             pwnam = pwd.getpwnam(username.encode('utf-8'))
         except KeyError:
             raise ChangeUserException(_(u'User does not exists.'))
         euid = pwnam.pw_uid
         egid = pwnam.pw_gid
     self.euid = euid
     self.egid = egid
     self.initial_euid = os.geteuid()
     self.initial_egid = os.getegid()
Пример #10
0
 def _writePID(self):
     """
     Write process ID in pid file.
     """
     pid_path = os.path.abspath(self.options.pid)
     pid_segments = local_filesystem.getSegmentsFromRealPath(pid_path)
     try:
         pid_file = local_filesystem.openFileForWriting(pid_segments)
         pid_file.write('%d' % os.getpid())
         pid_file.close()
     except (OSError, IOError):
         raise CompatError(
             1008,
             _(u'Could not write PID file at %s.' % (pid_path)),
             )
Пример #11
0
    def _impersonateUser(self):
        """
        Returns an impersonation context for current user.
        """
        if not self._avatar:
            return NoOpContext()

        try:
            return self._avatar.getImpersonationContext()
        except ChangeUserException:
            raise CompatError(
                1006,
                _(u'Could not switch process to local account "%s".' % (
                    self._avatar.name)),
                )