def role_helper(self, new_roles, curr_roles):
        """ Helper to prepare adding and removing roles for patching

        :param new_roles: dictionary of new roles to add or remove
        :type new_roles: dict.
        :param curr_roles: list of current roles on the system
        :type curr_roles: list.
        """
        final_roles = curr_roles
        if 'add' in new_roles:
            for role in new_roles['add']:
                role = role.split(':', 1)
                if not self.duplicate_group(role[1], curr_roles):
                    final_roles.append({"LocalRole":role[0], "RemoteGroup":role[1]})
                else:
                    raise ResourceExists('Group DN "%s" already exists.' % role[1].split(':')[0])
        if 'remove' in new_roles:
            removed = False
            for role in new_roles['remove']:
                removed = False
                for item in reversed(final_roles):
                    if item['LocalRole'] == role:
                        del final_roles[final_roles.index(item)]
                        removed = True
                        break
                if not removed:
                    raise InvalidCommandLineError("Unable to find local role %s to delete" % role)

        return final_roles
Exemple #2
0
    def credentialsvalidation(self, username='', loginname='', password='', acct=None, \
                                                            check_password=False, options=None):
        """ sanity validation of credentials
        :param username: username to be added
        :type username: str.
        :param loginname: loginname to be added
        :type loginname: str.
        :param password: password to be added
        :type password: str.
        :param accounts: target federation account
        :type accounts: dict.
        :param check_password: flag to check password
        :type check_password: bool.
        """
        username_max_chars = 39  #60
        loginname_max_chars = 39  #60
        password_max_chars = 39  #PASSWORD MAX CHARS
        password_min_chars = 8  #PASSWORD MIN CHARS

        password_min_chars = next(iter(self.rdmc.app.select(\
            'AccountService.'))).dict['Oem'][self.rdmc.app.typepath.defs.oemhp]['MinPasswordLength']

        if username != '' and loginname != '':
            if len(username) > username_max_chars:
                raise InvalidCommandLineError('Username exceeds maximum length'\
                    '. Use at most %s characters.' % username_max_chars)

            if len(loginname) > loginname_max_chars:
                raise InvalidCommandLineError('Login name exceeds maximum '\
                    'length. Use at most %s characters.' % loginname_max_chars)

            try:
                if acct['UserName'] == username or acct['Oem'][self.rdmc.app.typepath.defs.oemhp]\
                                                                    ['LoginName'] == loginname:
                    raise ResourceExists(
                        'Username or login name is already in use.')
            except KeyError:
                pass

        if check_password:
            if password == '' or password == '/r':
                raise InvalidCommandLineError(
                    'An invalid password was entered.')
            else:
                if len(password) > password_max_chars:
                    raise InvalidCommandLineError('Password length is invalid.'\
                            ' Use at most %s characters.' % password_max_chars)
                if len(password) < password_min_chars:
                    raise InvalidCommandLineError('Password length is invalid.'\
                            ' Use at least %s characters.' % password_min_chars)
Exemple #3
0
    def addvalidation(self, username, key, feds):
        """ add validation function
        :param username: username to be added
        :type username: str.
        :param key: key to be added
        :type key: str.
        :param feds: list of federation accounts
        :type feds: list.
        """
        for fed in feds:
            if fed['Name'] == username:
                raise ResourceExists('Federation name is already in use.')

        if len(username) >= 32:
            raise InvalidCommandLineError('User name exceeds maximum length.')
        elif len(key) >= 32 or len(key) <= 7:
            raise InvalidCommandLineError('Password is invalid length.')
    def run(self, line):
        """ Main addfederation function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.addfederationvalidation(options)

        if len(args) == 2 and args[0] in ['add', 'changekey']:
            sys.stdout.write('Please input the federation key.\n')
            tempnewkey = getpass.getpass()

            if tempnewkey and tempnewkey != '\r':
                tempnewkey = tempnewkey
            else:
                raise InvalidCommandLineError(
                    "Empty or invalid key was entered.")
            args.extend([tempnewkey])

        elif not len(args) <= 3:
            raise InvalidCommandLineError("invalid number of parameters.")

        redfish = self._rdmc.app.current_client.monolith.is_redfish
        path = self.typepath.defs.federationpath
        results = self._rdmc.app.get_handler(path, service=True,
                                             silent=True).dict

        newresults = []

        if redfish:
            results = results['Members']
        else:
            results = results['links']['Member']

        for fed in results:
            fed = self._rdmc.app.get_handler(\
                                         fed[self.typepath.defs.hrefstring], \
                                         service=True, silent=True).dict

            newresults.append(fed)
            results = newresults

        if not results:
            raise NoContentsFoundForOperationError("")

        if not args:
            sys.stdout.write("iLO Federation Id list with Privileges:\n")

            for fed in sorted(results, key=lambda k: k['Name']):
                privstr = ""
                privs = fed['Privileges']

                for priv in privs:
                    privstr += priv + '=' + str(privs[priv]) + '\n'

                sys.stdout.write("\nName=%s:\n%s" % (fed['Name'], privstr))

        elif args[0].lower() == 'add':
            args.remove('add')

            if not len(args) == 2:
                raise InvalidCommandLineError("Invalid number of parameters.")

            body = {"Name": args[0], "Key": args[1], \
                    "Privileges": {"RemoteConsolePriv": options.remoteconsole, \
                    "iLOConfigPriv": options.iloconfig,\
                    "VirtualMediaPriv": options.virtualmedia,\
                    "UserConfigPriv": options.userconfig,\
                    "VirtualPowerAndResetPriv": options.virtualpr,\
                    "LoginPriv": options.loginpriv}}

            if self.typepath.flagiften:
                body["Privileges"].update({\
                    "HostBIOSConfigPriv": options.biosconfigpriv,\
                    "HostNICConfigPriv": options.nicconfigpriv,\
                    "HostStorageConfigPriv": options.hoststoragepriv,\
                    "SystemRecoveryConfigPriv": options.sysrecoveryconfigpriv})

            self.addvalidation(args[0], args[1], results)

            if path and body:
                resp = self._rdmc.app.post_handler(path, body, response=True)

            if resp and resp.dict:
                if 'resourcealreadyexist' in str(resp.dict).lower():
                    raise ResourceExists('')

        elif args[0].lower() == 'changekey':
            args.remove('changekey')

            try:
                name = args[0]
                newkey = args[1]
            except:
                raise InvalidCommandLineError('Invalid number of parameters.')

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            body = {'Key': newkey}

            if path and body:
                self._rdmc.app.patch_handler(path, body, service=True)
            else:
                raise NoContentsFoundForOperationError('Unable to find '\
                                            'the specified federation.')
        elif args[0].lower() == 'delete':
            args.remove('delete')

            try:
                name = str(args[0])
            except:
                raise InvalidCommandLineError("No Name entered to delete.")

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            if not path == self.typepath.defs.federationpath:
                self._rdmc.app.delete_handler(path)
            else:
                raise NoContentsFoundForOperationError(
                    'Unable to find the specified account.')
        else:
            raise InvalidCommandLineError('Invalid command.')

        return ReturnCodes.SUCCESS
Exemple #5
0
    def run(self, line):
        """ Main addfederation function
        :param line: string of arguments passed in
        :type line: str.
        """
        mod_fed = None
        body = dict()
        try:
            ident_subparser = False
            for cmnd in __subparsers__:
                if cmnd in line:
                    (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
                    ident_subparser = True
                    break
            if not ident_subparser:
                (options, args) = self.rdmc.rdmc_parse_arglist(self,
                                                               line,
                                                               default=True)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.addfederationvalidation(options)

        redfish = self.rdmc.app.monolith.is_redfish
        path = self.rdmc.app.typepath.defs.federationpath
        results = self.rdmc.app.get_handler(path, service=True,
                                            silent=False).dict

        newresults = []

        if redfish:
            results = results['Members']
        else:
            if 'Member' in results['links']:
                results = results['links']['Member']
            else:
                results = list()

        for fed in results:
            fed = self.rdmc.app.get_handler(fed[self.rdmc.app.typepath.defs.hrefstring], \
                                         service=True, silent=True).dict
            if hasattr(options, 'fedname') or hasattr(options, 'fedkey'):
                mod_fed = fed
                if redfish:
                    path = fed['@odata.id']
                else:
                    path = fed['links']['self']['href']
            newresults.append(fed)
            results = newresults

        fed = mod_fed
        if not results:
            raise NoContentsFoundForOperationError(
                "No iLO Federation accounts were found.")

        if options.command.lower() == 'add':
            privs = self.getprivs(options)
            path = self.rdmc.app.typepath.defs.federationpath

            body = {"Name": options.fedname, "Key": options.fedkey}
            if privs:
                body.update({"Privileges": privs})
            self.addvalidation(options.fedname, options.fedkey, results)

            if path and body:
                resp = self.rdmc.app.post_handler(path, body)

            if resp and resp.dict:
                if 'resourcealreadyexist' in str(resp.dict).lower():
                    raise ResourceExists('')

        elif options.command.lower() == 'changekey':

            try:
                name = options.fedname
                newkey = options.fedkey
            except:
                raise InvalidCommandLineError('Invalid number of parameters.')

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            body = {'Key': newkey}

            if path and body:
                self.rdmc.app.patch_handler(path, body, service=True)
            else:
                raise NoContentsFoundForOperationError('Unable to find '\
                                            'the specified federation.')
        elif options.command.lower() == 'modify':
            if not mod_fed:
                raise InvalidCommandLineError(
                    "Unable to find the specified federation.")

            name = options.fedname

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            if options.optprivs:
                body.update({'Privileges': {}})
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                        and 'SystemRecoveryConfigPriv' not in \
                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in federation must have The System "\
                                       "Recovery Config privilege to add the System Recovery "\
                                       "Config privilege.")
                privs = self.getprivs(options)
                body['Privileges'] = privs

            self.rdmc.app.patch_handler(path, body)

        elif options.command.lower() == 'delete':
            if not mod_fed:
                raise InvalidCommandLineError(
                    "Unable to find the specified Federation.")

            name = options.fedname

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            if not path == self.rdmc.app.typepath.defs.federationpath:
                self.rdmc.app.delete_handler(path)
            else:
                raise NoContentsFoundForOperationError(
                    'Unable to find the specified federation.')
        else:
            self.rdmc.ui.printer("iLO Federation Id list with Privileges:\n")
            if options.json:
                outdict = dict()
                for fed in sorted(results, key=lambda k: k['Name']):
                    outdict[fed['Name']] = fed['Privileges']
                self.rdmc.ui.print_out_json_ordered(
                    str(json.dumps(outdict, indent=2)))
            else:
                for fed in sorted(results, key=lambda k: k['Name']):
                    privstr = ""
                    privs = fed['Privileges']
                    for priv in privs:
                        privstr += priv + '=' + str(privs[priv]) + '\n'
                    self.rdmc.ui.printer("\nName=%s:\n%s" %
                                         (fed['Name'], privstr))

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main addfederation function

        :param line: string of arguments passed in
        :type line: str.
        """
        mod_fed = None
        valid_args = ['add', 'delete', 'modify', 'changekey']
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args) > 4:
            raise InvalidCommandLineError("Invalid number of parameters for "\
                                          "this command.")
        arg_cnt = 0
        for arg in args:
            if arg in valid_args:
                arg_cnt += 1
        if arg_cnt > 1:
            raise InvalidCommandLineError("Invalid command.")

        self.addfederationvalidation(options)

        redfish = self._rdmc.app.monolith.is_redfish
        path = self.typepath.defs.federationpath
        results = self._rdmc.app.get_handler(path, service=True,
                                             silent=True).dict

        newresults = []

        if redfish:
            results = results['Members']
        else:
            results = results['links']['Member']

        for fed in results:
            fed = self._rdmc.app.get_handler(fed[self.typepath.defs.hrefstring], \
                                         service=True, silent=True).dict
            if fed['Name'] in args or fed['Id'] in args:
                mod_fed = fed
                if redfish:
                    path = fed['@odata.id']
                else:
                    path = fed['links']['self']['href']
            newresults.append(fed)
            results = newresults

        fed = mod_fed
        if not results:
            raise NoContentsFoundForOperationError("")

        if not args:
            sys.stdout.write("iLO Federation Id list with Privileges:\n")

            for fed in sorted(results, key=lambda k: k['Name']):
                privstr = ""
                privs = fed['Privileges']

                for priv in privs:
                    privstr += priv + '=' + str(privs[priv]) + '\n'

                sys.stdout.write("\nName=%s:\n%s" % (fed['Name'], privstr))

        elif args[0].lower() == 'add':
            args.remove('add')
            if len(args) == 1:
                sys.stdout.write("Please input the federation key.\n")
                tempinput = getpass.getpass()

                args.extend([tempinput])

            privs = self.getprivs(options)
            path = self.typepath.defs.federationpath

            body = {"Name": args[0], "Key": args[1]}
            if privs:
                body.update({"Privileges": privs})
            self.addvalidation(args[0], args[1], results)

            if path and body:
                resp = self._rdmc.app.post_handler(path, body, response=True)

            if resp and resp.dict:
                if 'resourcealreadyexist' in str(resp.dict).lower():
                    raise ResourceExists('')

        elif args[0].lower() == 'changekey':
            args.remove('changekey')

            try:
                name = args[0]
                newkey = args[1]
            except:
                raise InvalidCommandLineError('Invalid number of parameters.')

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            body = {'Key': newkey}

            if path and body:
                self._rdmc.app.patch_handler(path, body, service=True)
            else:
                raise NoContentsFoundForOperationError('Unable to find '\
                                            'the specified federation.')
        elif args[0].lower() == 'modify':
            if not mod_fed:
                raise InvalidCommandLineError(
                    "Unable to find the specified federation.")
            body = {}
            args.remove('modify')

            if not len(args) == 1:
                raise InvalidCommandLineError("Invalid number of parameters.")

            if options.optprivs:
                body.update({'Privileges': {}})
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                        and 'SystemRecoveryConfigPriv' not in \
                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in federation must have The System "\
                                       "Recovery Config privilege to add the System Recovery "\
                                       "Config privilege.")
                privs = self.getprivs(options)
                body['Privileges'] = privs

            self._rdmc.app.patch_handler(path, body)

        elif args[0].lower() == 'delete':
            if not mod_fed:
                raise InvalidCommandLineError(
                    "Unable to find the specified Federation.")
            args.remove('delete')

            try:
                name = str(args[0])
            except:
                raise InvalidCommandLineError("No Name entered to delete.")

            for fed in results:
                if fed['Name'] == name:
                    if redfish:
                        path = fed['@odata.id']
                        break
                    else:
                        path = fed['links']['self']['href']
                        break

            if not path == self.typepath.defs.federationpath:
                self._rdmc.app.delete_handler(path)
            else:
                raise NoContentsFoundForOperationError(
                    'Unable to find the specified federation.')
        else:
            raise InvalidCommandLineError('Invalid command.')

        return ReturnCodes.SUCCESS