Expand the AuthorizedKeysFile expression. Defined in man sshd_config(5)
775366
def _expand_authorized_keys_path(path, user, home):
    '''
    
    '''
    converted_path = ''
    had_escape = False
    for char in path:
        if had_escape:
            had_escape = False
            if char == '%':
                converted_path += '%'
            elif char == 'u':
                converted_path += user
            elif char == 'h':
                converted_path += home
            else:
                error = 'AuthorizedKeysFile path: unknown token character "%{0}"'.format(char)
                raise CommandExecutionError(error)
            continue
        elif char == '%':
            had_escape = True
        else:
            converted_path += char
    if had_escape:
        error = "AuthorizedKeysFile path: Last character can't be escape character"
        raise CommandExecutionError(error)
    return converted_path
209734
def custom_expand(val, conf)
      val.gsub!(/\$\(([^()]+)\)/) do |var|
        key = $1
        if CONFIG.key? key
          custom_expand(conf[key], conf)
        else
          var
        end
      end
      val
    end
896970
def ssh_invite(ctx, code_length, user, **kwargs):
    
    for name, value in kwargs.items():
        setattr(ctx.obj, name, value)
    from . import cmd_ssh
    ctx.obj.code_length = code_length
    ctx.obj.ssh_user = user
    return go(cmd_ssh.invite, ctx.obj)
311883
def check_key_file(user,
                   source,
                   config='.ssh/authorized_keys',
                   saltenv='base',
                   fingerprint_hash_type=None):
    '''
    
    '''
    keyfile = __salt__['cp.cache_file'](source, saltenv)
    if not keyfile:
        return {}
    s_keys = _validate_keys(keyfile, 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 {}
    else:
        ret = {}
        for key in s_keys:
            ret[key] = check_key(
                user,
                key,
                s_keys[key]['enc'],
                s_keys[key]['comment'],
                s_keys[key]['options'],
                config=config,
                fingerprint_hash_type=fingerprint_hash_type)
        return ret
1143879
def keyscan(state, host, hostname, force=False):
    '''
    
    '''

    yield files.directory(
        state, host,
        '~/.ssh',
        mode=700,
    )

    hostname_present = host.fact.find_in_file(
        '~/.ssh/known_hosts',
        hostname,
    )

    keyscan_command = 'ssh-keyscan {0} >> ~/.ssh/known_hosts'.format(hostname)

    if not hostname_present:
        yield keyscan_command

    elif force:
        yield 'ssh-keygen -R {0}'.format(hostname)
        yield keyscan_command
782620
def convert_sshkey(cls, sshkey):
        
        params = {}
        if sshkey:
            params['keys'] = []
            for ssh in sshkey:
                if os.path.exists(os.path.expanduser(ssh)):
                    if 'ssh_key' in params:
                        cls.echo("Can't have more than one sshkey file.")
                        continue
                    with open(ssh) as fdesc:
                        sshkey_ = fdesc.read()
                    if sshkey_:
                        params['ssh_key'] = sshkey_
                else:
                    sshkey_id = Sshkey.usable_id(ssh)
                    if sshkey_id:
                        params['keys'].append(sshkey_id)
                    else:
                        cls.echo('This is not a ssh key %s' % ssh)

            if not params['keys']:
                params.pop('keys')

        return params
507066
def expand_header(header = {})
      header = DEFAULT_HEADER.merge(header)
      header['X-ITRP-Account'] = option(:account) if option(:account)
      header['AUTHORIZATION'] = 'Basic ' + ["#{option(:api_token)}:x"].pack('m*').gsub(/\s/, '')
      if option(:source)
        header['X-ITRP-Source'] = option(:source)
        header['HTTP_USER_AGENT'] = option(:source)
      end
      header
    end
52554
def copySshKeys(self, keyName):
        
        if keyName == 'core':
            return # No point.

        # Make sure that keys are there.
        self._waitForSSHKeys(keyName=keyName)

        # copy keys to core user so that the ssh calls will work
        # - normal mechanism failed unless public key was in the google-ssh format
        # - even so, the key wasn't copied correctly to the core account
        keyFile = '/home/%s/.ssh/authorized_keys' % keyName
        self.sshInstance('/usr/bin/sudo', '/usr/bin/cp', keyFile, '/home/core/.ssh', user=keyName)
        self.sshInstance('/usr/bin/sudo', '/usr/bin/chown', 'core',
                         '/home/core/.ssh/authorized_keys', user=keyName)
317349
def _RemoveAuthorizedKeys(self, user):
    
    pw_entry = self._GetUser(user)
    if not pw_entry:
      return

    home_dir = pw_entry.pw_dir
    authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
    if os.path.exists(authorized_keys_file):
      try:
        os.remove(authorized_keys_file)
      except OSError as e:
        message = 'Could not remove authorized keys for user %s. %s.'
        self.logger.warning(message, user, str(e))
376357
def key_file(self):
        """"""
        if self.auth_key:
            key_file_path = os.path.join(orchestration_mkdtemp(), 'key')
            with open(key_file_path, 'w') as fd:
                fd.write(self.auth_key)
            os.chmod(key_file_path, stat.S_IRUSR)
            return key_file_path
124437
def _get_config_file(user, config):
    '''
    
    '''
    uinfo = __salt__['user.info'](user)
    if not uinfo:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(user))
    home = uinfo['home']
    config = _expand_authorized_keys_path(config, user, home)
    if not os.path.isabs(config):
        config = os.path.join(home, config)
    return config
985509
def key_create(options)
      ssh_key = key_generation(options)
      ssh_private_key_file = options[:private_key]
      ssh_public_key_file = "#{ssh_private_key_file}.pub"

      # TODO: - add to .fenton/config file
      File.write(ssh_private_key_file, ssh_key.private_key)
      File.chmod(0o600, ssh_private_key_file)
      File.write(ssh_public_key_file, ssh_key.ssh_public_key)
      File.chmod(0o600, ssh_public_key_file)

      [true, 'Key': ['creation failed']]
    end
767771
public static SshPublicKeyFile parse(byte[] formattedkey)
			throws IOException {
		try {
			try {
				return new OpenSSHPublicKeyFile(formattedkey);
			} catch (IOException ex) {
				try {
					return new SECSHPublicKeyFile(formattedkey);
				} catch (IOException ex2) {
					throw new IOException(
							"Unable to parse key, format could not be identified");
				}
			}
		} catch (OutOfMemoryError ex1) {
			throw new IOException(
					"An error occurred parsing a public key file! Is the file corrupt?");
		}
	}
1124379
def _load_hardware_key(keyfile):
    
    key = keyfile.read()
    if len(key) not in [24, 32]:
        raise esptool.FatalError("Key file contains wrong length (%d bytes), 24 or 32 expected." % len(key))
    if len(key) == 24:
        key = key + key[8:16]
        print("Using 192-bit key (extended)")
    else:
        print("Using 256-bit key")

    assert len(key) == 32
    return key
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
1164475
def Expandkey(key, clen):
		
		import sha
		from string import join
		from array import array

		blocks = (clen + 19) / 20
		xkey = []
		seed = key
		for i in xrange(blocks):
			seed = sha.new(key + seed).digest()
			xkey.append(seed)
		j = join(xkey, '')
		return array('L', j)
999141
def rm_auth_key_from_file(user,
                          source,
                          config='.ssh/authorized_keys',
                          saltenv='base',
                          fingerprint_hash_type=None):
    '''
    
    '''
    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 += rm_auth_key(
                user,
                key,
                config=config,
                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 'Key not removed' in rval:
            return 'Key not removed'
        elif 'Key removed' in rval:
            return 'Key removed'
        else:
            return 'Key not present'