Exemplo n.º 1
0
    def __getattr__(self, attr):
        """ This method actually takes care of all the called method that are
        not resolved (i.e not existing methods). It actually will simulate
        the existance of any method    entered in the 'allowed' variable list.

        e.g. You just have to add 'uname' in list of allowed commands in
        the 'allowed' variable, and lshell will react as if you had
        added a do_uname in the ShellCmd class!
        """

        # in case the configuration file has been modified, reload it
        if self.conf['config_mtime'] != os.path.getmtime(self.conf['configfile']):
            self.conf = CheckConfig(self.args).returnconf()
            self.prompt = '%s:~$ ' % self.setprompt(self.conf)
            self.log = self.conf['logpath']

        if self.g_cmd in ['quit', 'exit', 'EOF']:
            self.log.error('Exited')
            if self.g_cmd == 'EOF':
                self.stdout.write('\n')
            sys.exit(0)
        if self.check_secure(self.g_line, self.conf['strict']) == 1: 
            return object.__getattribute__(self, attr)
        if self.check_path(self.g_line, strict = self.conf['strict']) == 1:
            return object.__getattribute__(self, attr)
        if self.g_cmd in self.conf['allowed']:
            self.g_arg = re.sub('^~$|^~/', '%s/' %self.conf['home_path'],      \
                                                                   self.g_arg)
            self.g_arg = re.sub(' ~/', ' %s/'  %self.conf['home_path'],        \
                                                                   self.g_arg)
            if type(self.conf['aliases']) == dict:
                self.g_line = get_aliases(self.g_line, self.conf['aliases'])
            self.log.info('CMD: "%s"' %self.g_line)
            if self.g_cmd == 'cd':
                self.cd()
            # builtin lpath function: list all allowed path
            elif self.g_cmd == 'lpath':
                self.lpath()
            # builtin lsudo function: list all allowed sudo commands
            elif self.g_cmd == 'lsudo':
                self.lsudo()
            # builtin history function: print command history
            elif self.g_cmd == 'history':
                self.history()
            # builtin export function
            elif self.g_cmd == 'export':
                self.export()
            # case 'cd' is in an alias e.g. {'toto':'cd /var/tmp'}
            elif self.g_line[0:2] == 'cd':
                self.g_cmd = self.g_line.split()[0]
                self.g_arg = ' '.join(self.g_line.split()[1:])
                self.cd()
            else:
                os.system(self.g_line)
        elif self.g_cmd not in ['', '?', 'help', None]: 
            self.log.warn('INFO: unknown syntax -> "%s"' %self.g_line)
            self.stderr.write('*** unknown syntax: %s\n' %self.g_cmd)
        self.g_cmd, self.g_arg, self.g_line = ['', '', ''] 
        return object.__getattribute__(self, attr)
Exemplo n.º 2
0
    def check_scp_sftp(self):
        """ This method checks if the user is trying to SCP a file onto the    \
        server. If this is the case, it checks if the user is allowed to use   \
        SCP or not, and    acts as requested. : )
        """
        if self.conf.has_key('ssh'):
            if os.environ.has_key('SSH_CLIENT')                                \
                                        and not os.environ.has_key('SSH_TTY'):

                # check if sftp is requested and allowed
                if 'sftp-server' in self.conf['ssh']:
                    if self.conf['sftp'] is 1:
                        self.log.error('SFTP connect')
                        os.system(self.conf['ssh'])
                        self.log.error('SFTP disconnect')
                        sys.exit(0)
                    else:
                        self.log.error('*** forbidden SFTP connection')
                        sys.exit(0)

                # initialise cli session
                from lshell.shellcmd import ShellCmd
                cli = ShellCmd(self.conf, None, None, None, None,              \
                                                            self.conf['ssh'])
                if cli.check_path(self.conf['ssh'], None, ssh=1) == 1:
                    self.ssh_warn('path over SSH', self.conf['ssh'])

                # check if scp is requested and allowed
                if self.conf['ssh'].startswith('scp '):
                    if self.conf['scp'] is 1 or 'scp' in self.conf['overssh']: 
                        if ' -f ' in self.conf['ssh']:
                            # case scp download is allowed
                            if self.conf['scp_download']:
                                self.log.error('SCP: GET "%s"' \
                                                            % self.conf['ssh'])
                            # case scp download is forbidden
                            else:
                                self.log.error('SCP: download forbidden: "%s"' \
                                                            % self.conf['ssh'])
                                sys.exit(0)
                        elif ' -t ' in self.conf['ssh']:
                            # case scp upload is allowed
                            if self.conf['scp_upload']:
                                if self.conf.has_key('scpforce'):
                                    cmdsplit = self.conf['ssh'].split(' ')
                                    scppath = os.path.realpath(cmdsplit[-1])
                                    forcedpath = os.path.realpath(self.conf
                                                                   ['scpforce'])
                                    if scppath != forcedpath:
                                        self.log.error('SCP: forced SCP '      \
                                                       + 'directory: %s'       \
                                                                    %scppath)
                                        cmdsplit.pop(-1)
                                        cmdsplit.append(forcedpath)
                                        self.conf['ssh'] = string.join(cmdsplit)
                                self.log.error('SCP: PUT "%s"'                 \
                                                        %self.conf['ssh'])
                            # case scp upload is forbidden
                            else:
                                self.log.error('SCP: upload forbidden: "%s"'   \
                                                            % self.conf['ssh']) 
                                sys.exit(0)
                        os.system(self.conf['ssh'])
                        self.log.error('SCP disconnect')
                        sys.exit(0)
                    else:
                        self.ssh_warn('SCP connection', self.conf['ssh'], 'scp')

                # check if command is in allowed overssh commands
                elif self.conf['ssh']:
                    # replace aliases
                    self.conf['ssh'] = get_aliases(self.conf['ssh'],           \
                                                         self.conf['aliases'])
                    # if command is not "secure", exit
                    if cli.check_secure(self.conf['ssh'], strict=1, ssh=1):
                        self.ssh_warn('char/command over SSH', self.conf['ssh'])
                    # else
                    self.log.error('Over SSH: "%s"' %self.conf['ssh'])
                    # if command is "help"
                    if self.conf['ssh'] == "help":
                        cli.do_help(None)
                    else:
                        os.system(self.conf['ssh'])
                    self.log.error('Exited')
                    sys.exit(0)

                # else warn and log
                else:
                    self.ssh_warn('command over SSH', self.conf['ssh'])

            else :
                # case of shell escapes
                self.ssh_warn('shell escape', self.conf['ssh'])
Exemplo n.º 3
0
    def __getattr__(self, attr):
        """ This method actually takes care of all the called method that are
        not resolved (i.e not existing methods). It actually will simulate
        the existance of any method    entered in the 'allowed' variable list.

        e.g. You just have to add 'uname' in list of allowed commands in
        the 'allowed' variable, and lshell will react as if you had
        added a do_uname in the ShellCmd class!
        """

        # expand environment variables in command line
        self.g_cmd  = os.path.expandvars(self.g_cmd)
        self.g_line = os.path.expandvars(self.g_line)
        self.g_arg  = os.path.expandvars(self.g_arg)

        # in case the configuration file has been modified, reload it
        if self.conf['config_mtime'] != os.path.getmtime(self.conf['configfile']):
            from lshell.checkconfig import CheckConfig
            self.conf = CheckConfig(['--config', \
                                     self.conf['configfile']]).returnconf()
            self.prompt = '%s:~$ ' % self.setprompt(self.conf)
            self.log = self.conf['logpath']

        if self.g_cmd in ['quit', 'exit', 'EOF']:
            self.log.error('Exited')
            if self.g_cmd == 'EOF':
                self.stdout.write('\n')
            sys.exit(0)
        if self.check_secure(self.g_line, self.conf['strict']) == 1:
            # see http://tldp.org/LDP/abs/html/exitcodes.html
            self.retcode = 126
            return object.__getattribute__(self, attr)
        if self.check_path(self.g_line, strict = self.conf['strict']) == 1:
            # see http://tldp.org/LDP/abs/html/exitcodes.html
            self.retcode = 126
            return object.__getattribute__(self, attr)
        if self.g_cmd in self.conf['allowed']:
            if self.conf['timer'] > 0:
                self.mytimer(0)
            self.g_arg = re.sub('^~$|^~/', '%s/' %self.conf['home_path'],      \
                                                                   self.g_arg)
            self.g_arg = re.sub(' ~/', ' %s/'  %self.conf['home_path'],        \
                                                                   self.g_arg)
            # replace previous command exit code
            # in case multiple commands (using separators), only replace first command
            # regex replaces all occureces of $?, before ;,&,|
            if re.search('[;&\|]', self.g_line):
              p = re.compile("(\s|^)(\$\?)([\s|$]?[;&|].*)")
            else:
              p = re.compile("(\s|^)(\$\?)(\s|$)")
            self.g_line = p.sub(r' %s \3' % self.retcode, self.g_line)

            if type(self.conf['aliases']) == dict:
                self.g_line = get_aliases(self.g_line, self.conf['aliases'])

            self.log.info('CMD: "%s"' %self.g_line)

            if self.g_cmd == 'cd':
              if re.search('[;&\|]', self.g_line):
                # ignore internal cd function in case more than one command
                self.retcode = exec_cmd(self.g_line)
              else:
                # builtin cd function
                self.retcode = self.cd()
            # builtin lpath function: list all allowed path
            elif self.g_cmd == 'lpath':
                self.retcode = self.lpath()
            # builtin lsudo function: list all allowed sudo commands
            elif self.g_cmd == 'lsudo':
                self.retcode = self.lsudo()
            # builtin history function: print command history
            elif self.g_cmd == 'history':
                self.retcode = self.history()
            # builtin export function
            elif self.g_cmd == 'export':
                self.retcode = self.export()
            # case 'cd' is in an alias e.g. {'toto':'cd /var/tmp'}
            elif self.g_line[0:2] == 'cd':
                self.g_cmd = self.g_line.split()[0]
                self.g_arg = ' '.join(self.g_line.split()[1:])
                self.retcode = self.cd()
            else:
                self.retcode = exec_cmd(self.g_line)

        elif self.g_cmd not in ['', '?', 'help', None]: 
            self.log.warn('INFO: unknown syntax -> "%s"' %self.g_line)
            self.stderr.write('*** unknown syntax: %s\n' %self.g_cmd)
        self.g_cmd, self.g_arg, self.g_line = ['', '', '']
        if self.conf['timer'] > 0:
            self.mytimer(self.conf['timer'])
        return object.__getattribute__(self, attr)
Exemplo n.º 4
0
    def check_scp_sftp(self):
        """ This method checks if the user is trying to SCP a file onto the    \
        server. If this is the case, it checks if the user is allowed to use   \
        SCP or not, and    acts as requested. : )
        """
        if self.conf.has_key('ssh'):
            if os.environ.has_key('SSH_CLIENT')                                \
                                        and not os.environ.has_key('SSH_TTY'):

                # check if sftp is requested and allowed
                if 'sftp-server' in self.conf['ssh']:
                    if self.conf['sftp'] is 1:
                        self.log.error('SFTP connect')
                        os.system(self.conf['ssh'])
                        self.log.error('SFTP disconnect')
                        sys.exit(0)
                    else:
                        self.log.error('*** forbidden SFTP connection')
                        sys.exit(0)

                # initialise cli session
                from lshell.shellcmd import ShellCmd
                cli = ShellCmd(self.conf, None, None, None, None,              \
                                                            self.conf['ssh'])
                if cli.check_path(self.conf['ssh'], None, ssh=1) == 1:
                    self.ssh_warn('path over SSH', self.conf['ssh'])

                # check if scp is requested and allowed
                if self.conf['ssh'].startswith('scp '):
                    if self.conf['scp'] is 1 or 'scp' in self.conf['overssh']:
                        if ' -f ' in self.conf['ssh']:
                            # case scp download is allowed
                            if self.conf['scp_download']:
                                self.log.error('SCP: GET "%s"' \
                                                            % self.conf['ssh'])
                            # case scp download is forbidden
                            else:
                                self.log.error('SCP: download forbidden: "%s"' \
                                                            % self.conf['ssh'])
                                sys.exit(0)
                        elif ' -t ' in self.conf['ssh']:
                            # case scp upload is allowed
                            if self.conf['scp_upload']:
                                if self.conf.has_key('scpforce'):
                                    cmdsplit = self.conf['ssh'].split(' ')
                                    scppath = os.path.realpath(cmdsplit[-1])
                                    forcedpath = os.path.realpath(
                                        self.conf['scpforce'])
                                    if scppath != forcedpath:
                                        self.log.error('SCP: forced SCP '      \
                                                       + 'directory: %s'       \
                                                                    %scppath)
                                        cmdsplit.pop(-1)
                                        cmdsplit.append(forcedpath)
                                        self.conf['ssh'] = string.join(
                                            cmdsplit)
                                self.log.error('SCP: PUT "%s"'                 \
                                                        %self.conf['ssh'])
                            # case scp upload is forbidden
                            else:
                                self.log.error('SCP: upload forbidden: "%s"'   \
                                                            % self.conf['ssh'])
                                sys.exit(0)
                        os.system(self.conf['ssh'])
                        self.log.error('SCP disconnect')
                        sys.exit(0)
                    else:
                        self.ssh_warn('SCP connection', self.conf['ssh'],
                                      'scp')

                # check if command is in allowed overssh commands
                elif self.conf['ssh']:
                    # replace aliases
                    self.conf['ssh'] = get_aliases(self.conf['ssh'],           \
                                                         self.conf['aliases'])
                    # if command is not "secure", exit
                    if cli.check_secure(self.conf['ssh'], strict=1, ssh=1):
                        self.ssh_warn('char/command over SSH',
                                      self.conf['ssh'])
                    # else
                    self.log.error('Over SSH: "%s"' % self.conf['ssh'])
                    # if command is "help"
                    if self.conf['ssh'] == "help":
                        cli.do_help(None)
                    else:
                        os.system(self.conf['ssh'])
                    self.log.error('Exited')
                    sys.exit(0)

                # else warn and log
                else:
                    self.ssh_warn('command over SSH', self.conf['ssh'])

            else:
                # case of shell escapes
                self.ssh_warn('shell escape', self.conf['ssh'])
Exemplo n.º 5
0
def cmd():
    eos_cmd = utils.get_aliases().get('eos', None)
    if eos_cmd:
        return sh.Command(eos_cmd)
Exemplo n.º 6
0
    def __getattr__(self, attr):
        """ This method actually takes care of all the called method that are
        not resolved (i.e not existing methods). It actually will simulate
        the existance of any method    entered in the 'allowed' variable list.

        e.g. You just have to add 'uname' in list of allowed commands in
        the 'allowed' variable, and lshell will react as if you had
        added a do_uname in the ShellCmd class!
        """

        # expand environment variables in command line
        self.g_cmd = os.path.expandvars(self.g_cmd)
        self.g_line = os.path.expandvars(self.g_line)
        self.g_arg = os.path.expandvars(self.g_arg)

        # in case the configuration file has been modified, reload it
        if self.conf["config_mtime"] != os.path.getmtime(self.conf["configfile"]):
            from lshell.checkconfig import CheckConfig

            self.conf = CheckConfig(["--config", self.conf["configfile"]]).returnconf()
            self.prompt = "%s:~$ " % self.setprompt(self.conf)
            self.log = self.conf["logpath"]

        if self.g_cmd in ["quit", "exit", "EOF"]:
            self.log.error("Exited")
            if self.g_cmd == "EOF":
                self.stdout.write("\n")
            sys.exit(0)
        if self.check_secure(self.g_line, self.conf["strict"]) == 1:
            return object.__getattribute__(self, attr)
        if self.check_path(self.g_line, strict=self.conf["strict"]) == 1:
            return object.__getattribute__(self, attr)
        if self.g_cmd in self.conf["allowed"]:
            if self.conf["timer"] > 0:
                self.mytimer(0)
            self.g_arg = re.sub("^~$|^~/", "%s/" % self.conf["home_path"], self.g_arg)
            self.g_arg = re.sub(" ~/", " %s/" % self.conf["home_path"], self.g_arg)
            # replace previous command exit code
            # in case multiple commands (using separators), only replace first command
            # regex replaces all occureces of $?, before ;,&,|
            if re.search("[;&\|]", self.g_line):
                p = re.compile("(\s|^)(\$\?)([\s|$]?[;&|].*)")
            else:
                p = re.compile("(\s|^)(\$\?)(\s|$)")
            self.g_line = p.sub(r" %s \3" % self.retcode, self.g_line)

            if type(self.conf["aliases"]) == dict:
                self.g_line = get_aliases(self.g_line, self.conf["aliases"])

            self.log.info('CMD: "%s"' % self.g_line)

            if self.g_cmd == "cd":
                if re.search("[;&\|]", self.g_line):
                    # ignore internal cd function in case more than one command
                    self.retcode = exec_cmd(self.g_line)
                else:
                    # builtin cd function
                    self.retcode = self.cd()
            # builtin lpath function: list all allowed path
            elif self.g_cmd == "lpath":
                self.retcode = self.lpath()
            # builtin lsudo function: list all allowed sudo commands
            elif self.g_cmd == "lsudo":
                self.retcode = self.lsudo()
            # builtin history function: print command history
            elif self.g_cmd == "history":
                self.retcode = self.history()
            # builtin export function
            elif self.g_cmd == "export":
                self.retcode = self.export()
            # case 'cd' is in an alias e.g. {'toto':'cd /var/tmp'}
            elif self.g_line[0:2] == "cd":
                self.g_cmd = self.g_line.split()[0]
                self.g_arg = " ".join(self.g_line.split()[1:])
                self.retcode = self.cd()
            else:
                self.retcode = exec_cmd(self.g_line)

        elif self.g_cmd not in ["", "?", "help", None]:
            self.log.warn('INFO: unknown syntax -> "%s"' % self.g_line)
            self.stderr.write("*** unknown syntax: %s\n" % self.g_cmd)
        self.g_cmd, self.g_arg, self.g_line = ["", "", ""]
        if self.conf["timer"] > 0:
            self.mytimer(self.conf["timer"])
        return object.__getattribute__(self, attr)
Exemplo n.º 7
0
    def __getattr__(self, attr):
        """ This method actually takes care of all the called method that are
        not resolved (i.e not existing methods). It actually will simulate
        the existance of any method    entered in the 'allowed' variable list.

        e.g. You just have to add 'uname' in list of allowed commands in
        the 'allowed' variable, and lshell will react as if you had
        added a do_uname in the ShellCmd class!
        """

        # in case the configuration file has been modified, reload it
        if self.conf['config_mtime'] != os.path.getmtime(
                self.conf['configfile']):
            from lshell.checkconfig import CheckConfig
            self.conf = CheckConfig(['--config', \
                                     self.conf['configfile']]).returnconf()
            self.prompt = '%s:~$ ' % self.setprompt(self.conf)
            self.log = self.conf['logpath']

        if self.g_cmd in ['quit', 'exit', 'EOF']:
            self.log.error('Exited')
            if self.g_cmd == 'EOF':
                self.stdout.write('\n')
            sys.exit(0)
        if self.check_secure(self.g_line, self.conf['strict']) == 1:
            return object.__getattribute__(self, attr)
        if self.check_path(self.g_line, strict=self.conf['strict']) == 1:
            return object.__getattribute__(self, attr)
        if self.g_cmd in self.conf['allowed']:
            self.g_arg = re.sub('^~$|^~/', '%s/' %self.conf['home_path'],      \
                                                                   self.g_arg)
            self.g_arg = re.sub(' ~/', ' %s/'  %self.conf['home_path'],        \
                                                                   self.g_arg)
            # replace previous command exit code
            self.g_line = re.sub('(\s|^)\$\?(\s|$)', ' %s ' % self.retcode,
                                 self.g_line)

            if type(self.conf['aliases']) == dict:
                self.g_line = get_aliases(self.g_line, self.conf['aliases'])
            self.log.info('CMD: "%s"' % self.g_line)
            if self.g_cmd == 'cd':
                self.retcode = self.cd()
            # builtin lpath function: list all allowed path
            elif self.g_cmd == 'lpath':
                self.retcode = self.lpath()
            # builtin lsudo function: list all allowed sudo commands
            elif self.g_cmd == 'lsudo':
                self.retcode = self.lsudo()
            # builtin history function: print command history
            elif self.g_cmd == 'history':
                self.retcode = self.history()
            # builtin export function
            elif self.g_cmd == 'export':
                self.retcode = self.export()
            # case 'cd' is in an alias e.g. {'toto':'cd /var/tmp'}
            elif self.g_line[0:2] == 'cd':
                self.g_cmd = self.g_line.split()[0]
                self.g_arg = ' '.join(self.g_line.split()[1:])
                self.retcode = self.cd()
            else:
                self.retcode = os.system('set -m; %s' % self.g_line)
        elif self.g_cmd not in ['', '?', 'help', None]:
            self.log.warn('INFO: unknown syntax -> "%s"' % self.g_line)
            self.stderr.write('*** unknown syntax: %s\n' % self.g_cmd)
        self.g_cmd, self.g_arg, self.g_line = ['', '', '']
        return object.__getattribute__(self, attr)
Exemplo n.º 8
0
Arquivo: eos.py Projeto: l1calo/CAF
def cmd():
    eos_cmd = utils.get_aliases().get("eos", None)
    if eos_cmd:
        return sh.Command(eos_cmd)