Remove an authorized key from the specified user's authorized key file

    CLI Example:

    .. code-block:: bash

        salt '*' ssh.rm_auth_key <user> <key>
765931
def rm_auth_key(user,
                key,
                config='.ssh/authorized_keys',
                fingerprint_hash_type=None):
    '''
    
    '''
    current = auth_keys(user,
                        config=config,
                        fingerprint_hash_type=fingerprint_hash_type)
    linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$')
    if key in current:
        # Remove the key
        full = _get_config_file(user, config)

        # Return something sensible if the file doesn't exist
        if not os.path.isfile(full):
            return 'Authorized keys file {0} not present'.format(full)

        lines = []
        try:
            # Read every line in the file to find the right ssh key
            # and then write out the correct one. Open the file once
            with salt.utils.files.fopen(full, 'r') as _fh:
                for line in _fh:
                    # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                    line = salt.utils.stringutils.to_unicode(line.strip())
                    if line == '':
                        continue
                    line += '\n'

                    if line.startswith('#'):
                        # Commented Line
                        lines.append(line)
                        continue

                    # get "{options} key"
                    search = re.search(linere, line)
                    if not search:
                        # not an auth ssh key, perhaps a blank line
                        continue

                    comps = search.group(2).split()

                    if len(comps) < 2:
                        # Not a valid line
                        lines.append(line)
                        continue

                    pkey = comps[1]

                    # This is the key we are "deleting", so don't put
                    # it in the list of keys to be re-added back
                    if pkey == key:
                        continue

                    lines.append(line)

            # Let the context manager do the right thing here and then
            # re-open the file in write mode to save the changes out.
            with salt.utils.files.fopen(full, 'wb') as _fh:
                _fh.writelines(salt.utils.data.encode(lines))
        except (IOError, OSError) as exc:
            log.warning('Could not read/write key file: %s',
                        exc)
            return 'Key not removed'
        return 'Key removed'
    # TODO: Should this function return a simple boolean?
    return 'Key not present'
338330
def set_auth_key_from_file(user,
                           source,
                           config='.ssh/authorized_keys',
                           saltenv='base',
                           fingerprint_hash_type=None):
    '''
    
    '''
    # TODO: add support for pulling keys from other file sources as well
    lfile = __salt__['cp.cache_file'](source, saltenv)
    if not os.path.isfile(lfile):
        raise CommandExecutionError(
            'Failed to pull key file from salt file server'
        )

    s_keys = _validate_keys(lfile, fingerprint_hash_type)
    if not s_keys:
        err = (
            'No keys detected in {0}. Is file properly formatted?'.format(
                source
            )
        )
        log.error(err)
        __context__['ssh_auth.error'] = err
        return 'fail'
    else:
        rval = ''
        for key in s_keys:
            rval += set_auth_key(
                user,
                key,
                enc=s_keys[key]['enc'],
                comment=s_keys[key]['comment'],
                options=s_keys[key]['options'],
                config=config,
                cache_keys=list(s_keys.keys()),
                fingerprint_hash_type=fingerprint_hash_type
            )
        # Due to the ability for a single file to have multiple keys, it's
        # possible for a single call to this function to have both "replace"
        # and "new" as possible valid returns. I ordered the following as I
        # thought best.
        if 'fail' in rval:
            return 'fail'
        elif 'replace' in rval:
            return 'replace'
        elif 'new' in rval:
            return 'new'
        else:
            return 'no change'
538434
def remove(self, key):
        

        data = self._load_file()
        del data[key]
        self._save_file(data)
659739
def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub')
      cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m

      # get our cert unless the user provided a full cert for us.
      unless public_key =~ cert_regex
        public_key = File.expand_path(public_key)
        if File.exist?(public_key)
          public_key = File.read(public_key).to_s.strip
        else
          raise Shells::PfSenseCommon::PublicKeyNotFound
        end
        raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex
      end

      cfg = get_config_section 'system'
      user_id = nil
      user_name = options[:user].downcase
      cfg['user'].each_with_index do |user,index|
        if user['name'].downcase == user_name
          user_id = index

          authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip
          unless authkeys == '' || authkeys =~ cert_regex
            warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset."
            authkeys = ''
          end

          if authkeys == ''
            user['authorizedkeys'] = Base64.strict_encode64(public_key)
          else
            authkeys = authkeys.split("\n")
            unless authkeys.include?(public_key)
              authkeys << public_key unless authkeys.include?(public_key)
              user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n"))
            end
          end

          break
        end
      end


      raise Shells::PfSenseCommon::UserNotFound unless user_id

      set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}."

      apply_user_config user_id
    end
1345353
def remove_user(username):
    '''
    
    '''
    try:
        sendline('config terminal')
        user_line = 'no username {0}'.format(username)
        ret = sendline(user_line)
        sendline('end')
        sendline('copy running-config startup-config')
        return '\n'.join([user_line, ret])
    except TerminalException as e:
        log.error(e)
        return 'Failed to set password'
542072
def rm_token(opts, tok):
    '''
    
    '''
    t_path = os.path.join(opts['token_dir'], tok)
    try:
        os.remove(t_path)
        return {}
    except (IOError, OSError):
        log.warning('Could not remove token %s', tok)
172471
def _replace_auth_key(
        user,
        key,
        enc='ssh-rsa',
        comment='',
        options=None,
        config='.ssh/authorized_keys'):
    '''
    
    '''

    auth_line = _format_auth_line(key, enc, comment, options or [])

    lines = []
    full = _get_config_file(user, config)

    try:
        # open the file for both reading AND writing
        with salt.utils.files.fopen(full, 'r') as _fh:
            for line in _fh:
                # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                line = salt.utils.stringutils.to_unicode(line.strip())
                if line == '':
                    continue
                line += '\n'

                if line.startswith('#'):
                    # Commented Line
                    lines.append(line)
                    continue
                comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line)
                if comps and len(comps[0]) > 3 and comps[0][3] == key:
                    # Found our key, replace it
                    lines.append(auth_line)
                else:
                    lines.append(line)
            _fh.close()
            # Re-open the file writable after properly closing it
            with salt.utils.files.fopen(full, 'wb') as _fh:
                # Write out any changes
                _fh.writelines(salt.utils.data.encode(lines))
    except (IOError, OSError) as exc:
        raise CommandExecutionError(
            'Problem reading or writing to key file: {0}'.format(exc)
        )
772961
def _RemoveUsers(self, remove_users):
    
    for username in remove_users:
      self.utils.RemoveUser(username)
      self.user_ssh_keys.pop(username, None)
    self.invalid_users -= set(remove_users)
938938
def delete_(*keyname):
    '''
    
    '''
    mdata = _check_mdata_delete()
    valid_keynames = list_()
    ret = {}

    for k in keyname:
        if mdata and k in valid_keynames:
            cmd = '{0} {1}'.format(mdata, k)
            ret[k] = __salt__['cmd.run_all'](cmd, ignore_retcode=True)['retcode'] == 0
        else:
            ret[k] = True

    return ret
492701
def keypair_delete(name, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.keypair_delete(name)
1085755
def remove_permission(self, file_id, permission_id):
        
        url = '{0}/{1}/permissions/{2}'.format(
            DRIVE_FILES_API_V2_URL,
            file_id,
            permission_id
        )

        self.request('delete', url)
1083888
def delete_key(self,
                    match=None,
                    match_dict=None,
                    preserve_minions=None,
                    revoke_auth=False):
        '''
        
        '''
        if match is not None:
            matches = self.name_match(match)
        elif match_dict is not None and isinstance(match_dict, dict):
            matches = match_dict
        else:
            matches = {}
        for status, keys in six.iteritems(matches):
            for key in keys:
                try:
                    if revoke_auth:
                        if self.opts.get('rotate_aes_key') is False:
                            print('Immediate auth revocation specified but AES key rotation not allowed. '
                                     'Minion will not be disconnected until the master AES key is rotated.')
                        else:
                            try:
                                client = salt.client.get_local_client(mopts=self.opts)
                                client.cmd_async(key, 'saltutil.revoke_auth')
                            except salt.exceptions.SaltClientError:
                                print('Cannot contact Salt master. '
                                      'Connection for {0} will remain up until '
                                      'master AES key is rotated or auth is revoked '
                                      'with \'saltutil.revoke_auth\'.'.format(key))
                    os.remove(os.path.join(self.opts['pki_dir'], status, key))
                    eload = {'result': True,
                             'act': 'delete',
                             'id': key}
                    self.event.fire_event(eload,
                                          salt.utils.event.tagify(prefix='key'))
                except (OSError, IOError):
                    pass
        if self.opts.get('preserve_minions') is True:
            self.check_minion_cache(preserve_minions=matches.get('minions', []))
        else:
            self.check_minion_cache()
        if self.opts.get('rotate_aes_key'):
            salt.crypt.dropfile(self.opts['cachedir'], self.opts['user'])
        return (
            self.name_match(match) if match is not None
            else self.dict_match(matches)
        )
848762
def destroy
      authentication = current_user.authentications.find_by(id: params[:id])
      authentication.destroy

      redirect_to authentications_path
    end
354888
def read_authorized_keys(username=None):
    
    authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.format(username)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(username, rnd_chars)
    authorized_keys = list()
    copy_result = execute_command(
        shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), authorized_keys_path, tmp_authorized_keys_path))))
    result_message = copy_result[0][1].decode('UTF-8')
    if 'you must have a tty to run sudo' in result_message:  # pragma: no cover
        raise OSError("/etc/sudoers is blocked sudo. Remove entry: 'Defaults    requiretty'.")
    elif 'No such file or directory' not in result_message:
        execute_command(shlex.split(str('{0} chmod 755 {1}'.format(sudo_check(), tmp_authorized_keys_path))))
        with open(tmp_authorized_keys_path) as keys_file:
            for key in keys_file:
                authorized_keys.append(PublicKey(raw=key))
        execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
    return authorized_keys
244203
def unset(ctx, key):
    ''''''
    file = ctx.obj['FILE']
    quote = ctx.obj['QUOTE']
    success, key = unset_key(file, key, quote)
    if success:
        click.echo("Successfully removed %s" % key)
    else:
        exit(1)
718649
async def remove_ssh_key(self, user, key):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        key = base64.b64decode(bytes(key.strip().split()[1].encode('ascii')))
        key = hashlib.md5(key).hexdigest()
        key = ':'.join(a + b for a, b in zip(key[::2], key[1::2]))
        await key_facade.DeleteKeys([key], user)
102486
def remove_file(self, file_name, *args, **kwargs):
		
		client = self.dav_client()
		remote_path = self.join_path(self.session_path(), file_name)
		if client.is_dir(remote_path) is True:
			raise ValueError('Unable to remove non-file entry')
		client.clean(remote_path)