Beispiel #1
0
def agent_auth(transport, username):
    """
    Attempt to authenticate to the given transport using any of the private
    keys available from an SSH agent or from a local private RSA key file (assumes no pass phrase).
    """
    try:
        ki = paramiko.RSAKey.from_private_key_file(rsa_private_key)
    except Exception as e:
        print('Failed loading' % (rsa_private_key, e))

    agent = paramiko.Agent()
    agent_keys = agent.get_keys() + (ki, )
    if len(agent_keys) == 0:
        return

    for key in agent_keys:
        My_Key = key.get_fingerprint()
        print('Trying ssh-agent key %s' % key.get_fingerprint()),
        try:
            transport.auth_publickey(username, key)
            print('... success!')
            return

        except paramiko.SSHException:
            print('... failed! SSH')
Beispiel #2
0
    def get_ssh_key(self):
        if self.auth is None or 'ssh_key' not in self.auth:
            return None

        key_path = self.auth['ssh_key']

        if key_path.startswith('@agent'):
            agent = paramiko.Agent()
            keys = agent.get_keys()

            key_no = int(
                key_path.replace('@agent', '').replace('.', '').replace(
                    '[', '').replace(']', '') or 0)

            return keys[key_no] if key_no < len(keys) else None

        password = self.auth.get('ssh_key_password')

        for pkey_class in (RSAKey, DSSKey, ECDSAKey, Ed25519Key):
            try:
                key = pkey_class.from_private_key_file(key_path, password)
            except SSHException as e:
                continue
            else:
                return key
        return key_path  # If cannot be treated as any key type, try pass filename to paramiko, maybe it will figure out
Beispiel #3
0
def pkey_connect(transport, user):
    for pkey in paramiko.Agent().get_keys():
        try:
            transport.auth_publickey(user, pkey)
            break
        except paramiko.SSHException:
            pass
Beispiel #4
0
 def authenticate(self, transport, username):
     """
     Attempt to authenticate to the given transport using any of the private
     keys available from an SSH agent or from a local private RSA key file (assumes no pass phrase).
     """
     agent = paramiko.Agent()
     agent_keys = agent.get_keys()
     rsa_private_key = join(self.riaps_Folder,
                            "keys/" + str(const.ctrlPrivateKey))
     agent_keys = self.addKeyToAgent(agent_keys, rsa_private_key)
     rsa_private_key = os.path.expanduser(
         os.path.join('~', '.ssh', str(const.ctrlPrivateKey)))
     agent_keys = self.addKeyToAgent(agent_keys, rsa_private_key)
     if len(agent_keys) == 0:
         self.logger.error('no suitable key found.')
         return
     for key in agent_keys:
         self.logger.info('trying user %s ssh-agent key %s' %
                          (username, key.get_fingerprint().hex()))
         try:
             transport.auth_publickey(username, key)
             self.logger.info('... success!')
             return
         except paramiko.SSHException as e:
             self.logger.info('... failed! - %s' % str(e))
Beispiel #5
0
 def do_authenticateWithAgent(self):
     """Authenticate with a SSH agent"""
     # Currently paramiko supports the openSSH key-agent and Komodo
     # adds putty/pageant support for windows
     try:
         agent = paramiko.Agent()
         agent_keys = agent.get_keys()
         if len(agent_keys) > 0:
             for key in agent_keys:
                 from binascii import hexlify
                 self.log.debug('Trying ssh-agent key %s',
                                hexlify(key.get_fingerprint()))
                 try:
                     self._connection.auth_publickey(self.username, key)
                     #self._connection.auth_publickey(self.username, key, event)
                 except paramiko.SSHException, e:
                     # the authentication failed (raised when no event passed in)
                     pass
                 if self._connection.is_authenticated():
                     self.log.debug('Agent authentication was successful!')
                     return 1
     except paramiko.BadAuthenticationType, e:
         # Likely if public-key authentication isn't allowed by the server
         self._lasterror = e.args[-1]
         self.log.error("SSH AGENT AUTH ERROR: %s", self._lasterror)
Beispiel #6
0
def main():

  bastionAddr = (BASTION_IP, SSH_PORT)
  destAddr = (DESTINATION_IP, SSH_PORT)

  bastionHost = paramiko.SSHClient()
  bastionHost.set_missing_host_key_policy(paramiko.AutoAddPolicy())

  agent = paramiko.Agent()
  agent_keys = agent.get_keys()

  # Assumes you only have one key loaded on your SSH agent, easy to configure with Jenkins
  # but you would need to test each key if you had more than one
  bastionHost.connect(BASTION_IP, username=SSH_USERNAME, pkey=agent_keys[0])
  bastionTransport = bastionHost.get_transport()
  bastionChannel = bastionTransport.open_channel("direct-tcpip", destAddr, bastionAddr)

  destHost = paramiko.SSHClient()
  destHost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  destHost.connect(DESTINATION_IP, username=SSH_USERNAME, pkey=agent_keys[0], sock=bastionChannel)

  stdin, stdout, stderr = destHost.exec_command('ls -ltr /usr/bin')

  print(stderr.read())
  print(stdout.read())

  destHost.close()
  bastionHost.close()
Beispiel #7
0
def agent_auth(transport, username):
    """

    Attempt to authenticate to the given transport using any of the private

    keys available from an SSH agent.

    """

    agent = paramiko.Agent()

    agent_keys = agent.get_keys()

    if len(agent_keys) == 0:
        return

    for key in agent_keys:

        print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))

        try:

            transport.auth_publickey(username, key)

            print('... success!')

            return

        except paramiko.SSHException:

            print('... nope.')
Beispiel #8
0
    def __init__(self,
                 server,
                 username,
                 password,
                 remote_server,
                 local_port=0,
                 private_key=None,
                 missing_host_key_policy=None):
        """
		:param tuple server: The SSH server to connect to.
		:param str username: The username to authenticate with.
		:param str password: The password to authenticate with.
		:param tuple remote_server: The remote server to connect to through the specified SSH server.
		:param int local_port: The local port to forward, if not set a random one will be used.
		:param str private_key: An RSA key to prefer for authentication.
		:param missing_host_key_policy: The policy to use for missing host keys.
		"""
        super(SSHTCPForwarder, self).__init__()
        self.logger = logging.getLogger('KingPhisher.' +
                                        self.__class__.__name__)
        self.server = (server[0], int(server[1]))
        self.remote_server = (remote_server[0], int(remote_server[1]))
        client = paramiko.SSHClient()
        if missing_host_key_policy is None:
            missing_host_key_policy = paramiko.AutoAddPolicy()
        elif isinstance(missing_host_key_policy, paramiko.RejectPolicy):
            self.logger.info(
                'reject policy in place, loading system host keys')
            client.load_system_host_keys()
        client.set_missing_host_key_policy(missing_host_key_policy)
        self.client = client
        self.username = username
        self.__connected = False

        # an issue seems to exist in paramiko when multiple keys are present through the ssh-agent
        agent_keys = paramiko.Agent().get_keys()

        if not self.__connected and private_key:
            private_key = self.__resolve_private_key(private_key, agent_keys)
            if private_key:
                self.logger.debug(
                    'attempting ssh authentication with user specified key')
                self.__try_connect(look_for_keys=False, pkey=private_key)
            else:
                self.logger.warning(
                    'failed to identify the user specified key for ssh authentication'
                )

        if not self.__connected and len(agent_keys) == 1:
            self.__try_connect(look_for_keys=False, pkey=agent_keys[0])

        if not self.__connected:
            self.__try_connect(password=password,
                               look_for_keys=True,
                               raise_error=True)

        transport = self.client.get_transport()
        self._forward_server = ForwardServer(self.remote_server, transport,
                                             ('127.0.0.1', local_port),
                                             ForwardHandler)
 def __send_key(self, original_pwd):
     # This is very specific to the Raspberry PI, where SSH using a password for root is not possible.
     # Therefore we try to log using the 'pi' account to add our public key and copy it to the root account
     a = paramiko.Agent()
     ks = a.get_keys()
     k = ks[0].get_base64()
     for pwd in {'default_password', original_pwd}:
         if pwd is not None:
             print(
                 "Trying to add the tester public key to /root/.ssh/authorized_keys using \'"
                 + pwd + "\'")
             try:
                 tmp_dut = SshTarget(self.host,
                                     name='tmp_dut',
                                     port=self.port,
                                     user='******',
                                     password=pwd)
                 print(type(tmp_dut))
                 tmp_dut.write('sudo mkdir -p /root/.ssh')
                 tmp_dut.write('echo ' + 'ssh-rsa ' + str(k) +
                               '> ~/.ssh/authorized_keys2')
                 tmp_dut.write(
                     'sudo tee -a /root/.ssh/authorized_keys < ~/.ssh/authorized_keys2'
                 )
             except paramiko.ssh_exception.SSHException:
                 pass
Beispiel #10
0
    def _agent_auth(self, transport):
        """Attempt to authenticate to the given transport using any of the private
        keys available from an SSH agent ... or from a local private RSA key file
        (assumes no pass phrase).

        PFE: http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/
        """
        import paramiko

        agent = paramiko.Agent()

        private_key_file = self.attrs.get("ssh_private_key_file", None)
        if private_key_file:
            private_key_file = os.path.expanduser(private_key_file)
            LOGGER.info("Loading keys from local file %s", private_key_file)
            agent_keys = (paramiko.RSAKey.from_private_key_file(private_key_file),)
        else:
            LOGGER.info("Loading keys from SSH agent")
            agent_keys = agent.get_keys()
        if len(agent_keys) == 0:
            raise IOError("No available keys")

        for key in agent_keys:
            LOGGER.debug('Trying ssh key %s',
                         key.get_fingerprint().encode('hex'))
            try:
                transport.auth_publickey(self.destination.username, key)
                LOGGER.debug('... ssh key success!')
                return
            except paramiko.SSHException:
                continue

        # We found no valid key
        raise IOError("RSA key auth failed!")
Beispiel #11
0
    def __init__(self, host, user, password):
        try:
            self._transport = paramiko.Transport((host, 22))

            if password is not None:
                self._transport.connect(username=user, password=password)
            else:
                agent = paramiko.Agent()
                agent_keys = agent.get_keys()
                if len(agent_keys) == 0:
                    raise DataSourceError(
                        "Error performing passwordless login")

                success = False
                for key in agent_keys:
                    try:
                        self._transport.connect(username=user, pkey=key)
                        success = True
                        break
                    except paramiko.SSHException:
                        pass

                if not success:
                    raise DataSourceError(
                        "Error performing passwordless login")

            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        except Exception, e:
            raise DataSourceError(e.__str__())
Beispiel #12
0
    def agent_auth(cls, transport, username):
        """
        Attempt to authenticate to the given transport using any of the private
        keys available from an SSH agent.
        return True, if the transport is authenticated
        raises: AuthenticationException when network errro
        """

        agent = paramiko.Agent()
        agent_keys = agent.get_keys()
        if len(agent_keys) == 0:
            #print "Warning: No keys found loaded in ssh-agent. Forgot to use ssh-add ?"
            return

        for key in agent_keys:
            #print 'Trying ssh-agent key %s' % \
            #      paramiko.util.hexify(key.get_fingerprint()),
            try:
                transport.auth_publickey(username, key)
                if not transport.is_authenticated():
                    continue
                else:
                    break
            except paramiko.AuthenticationException, e:
                print "Used key from agent. Auth failed. Will skip it."
                pass
            except SSHException, ex:
                raise CommunicationException(0, "[agent_auth]:" + to_str(ex))
Beispiel #13
0
    def __init__(self,
                 default_user,
                 auth_file='./.radssh_authfile',
                 include_agent=UNUSED_PARAMETER,
                 include_userkeys=UNUSED_PARAMETER,
                 default_password=None,
                 try_auth_none=True):
        if include_agent != UNUSED_PARAMETER:
            warnings.warn(FutureWarning(
                'AuthManager will no longer support include_agent starting with 2.0: passed value (%s) ignored'
                % include_agent),
                          stacklevel=2)
        if include_userkeys != UNUSED_PARAMETER:
            warnings.warn(FutureWarning(
                'AuthManager will no longer support include_userkeys starting with 2.0: passed value (%s) ignored'
                % include_userkeys),
                          stacklevel=2)
        self.keys = []
        self.passwords = []
        self.default_passwords = {}
        self.try_auth_none = try_auth_none
        self.logger = logging.getLogger('radssh.auth')
        self.import_lock = threading.Lock()
        if default_password:
            self.add_password(PlainText(default_password))
        self.deferred_keys = dict()
        if default_user:
            self.default_user = default_user
        else:
            self.default_user = os.environ.get('SSH_USER', os.environ['USER'])

        self.agent_connection = paramiko.Agent()

        if auth_file:
            self.read_auth_file(auth_file)
Beispiel #14
0
 def _get_rsa_key_from_ssh_agent(self):
     try:
         ssh_agent = paramiko.Agent()
         ssh_keys = ssh_agent.get_keys()
     except paramiko.ssh_exception.SSHException:
         print('Incompatible protocol')
     return ssh_keys
Beispiel #15
0
def list_keys():
    """List keys from SSH agent"""
    agent = paramiko.Agent()
    keys = agent.get_keys()
    for key in agent.get_keys():
        # paramiko doesn't expose key comments (yet?)
        keystr = "[{}] {}".format(key.get_name(), to_hex(key.get_fingerprint()))
        click.echo(keystr)
    agent.close()
Beispiel #16
0
def sign_via_agent(data, fingerprint=None):
    """Attempt to sign 'data' via ssh-agent.

    Args:
        data (str):
            The data to sign

    Kwargs:
        fingerprint (str, optional):
            The fingerprint of an SSH public key associated with the private key
            to be used for signing data.

    Returns:
        A dict containing the following keys:
            key_fingerprint:
                The SSH public key fingerprint associated with the private key
                used for signing 'data'.
            key_type: The SSH key type used for signing.
            signature: The data signature returned from ssh-agent.
    Raises:
        AgentKeyError: An error occured while signing.
    """

    agent = paramiko.Agent()
    keys = agent.get_keys()
    sign_key = None
    key_fp = None

    if not keys:
        raise AgentKeyError(AgentKeyError.E_NO_KEYS)

    if fingerprint is not None:
        for key in keys:
            key_fp = key.get_fingerprint()
            if fingerprint == key_fp:
                sign_key = key
                break
        if sign_key is None:
            raise AgentKeyError(AgentKeyError.E_MISSING_KEY,
                                fingerprint=to_hex(fingerprint))
    else:
        sign_key = keys[0]
        key_fp = sign_key.get_fingerprint()

    if PARAMIKO_VER >= (1, 14, 0):
        sig = sign_key.sign_ssh_data(data)
    else:
        sig = sign_key.sign_ssh_data(None, data)

    sig = paramiko.message.Message(sig)

    return {
        'key_fingerprint': key_fp,
        'key_type': sig.get_string(),
        'signature': sig.get_string()
    }
Beispiel #17
0
def check_keys_from_ssh_agent():
    """
    Check if private keys are available from an SSH agent.
    :return:
    """
    agent = paramiko.Agent()
    agent_keys = agent.get_keys()
    if len(agent_keys) == 0:
        return False
    return True
 def _test_local_agent(self):
     """
     try to connect to the local ssh-agent
     return True if local agent is running, False if not
     """
     agent = paramiko.Agent()
     if len(agent.get_keys()) == 0:
         return False
     else:
         return True
Beispiel #19
0
 def get_ssh_to_remote_by_key(ip, keyfile):
     warnings.warn('LEGACY,  for fuel-qa compatibility', DeprecationWarning)
     try:
         with open(keyfile) as f:
             keys = [paramiko.RSAKey.from_private_key(f)]
     except IOError:
         logger.warning('Loading of SSH key from file failed. Trying to use'
                        ' SSH agent ...')
         keys = paramiko.Agent().get_keys()
     return ssh_client.SSHClient(ip, auth=ssh_client.SSHAuth(keys=keys))
Beispiel #20
0
    def __init__(self,
                 host,
                 port=22,
                 username=username,
                 password=None,
                 key=None,
                 passphrase=None,
                 timeout=TIMEOUT):
        self.username = username
        self.password = password
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        agent = paramiko.Agent()
        agent_keys = agent.get_keys()
        if 'http_proxy' in os.environ:
            if re.match(r'socks5', os.environ['http_proxy']):
                # For production use socks5 proxy
                proxy_host, proxy_port = (re.sub(
                    r'^socks5://', "", os.environ['http_proxy'])).split(':')
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_host,
                                      int(proxy_port), False)
                paramiko.client.socket.socket = socks.socksocket
                logging.info("Using Socks5 Proxy")

        conn = False

        if len(agent_keys) > 0:
            for mykey in agent_keys:
                try:
                    self.client.connect(host,
                                        port,
                                        username=username,
                                        password=password,
                                        pkey=mykey,
                                        timeout=timeout,
                                        allow_agent=False)
                    conn = True
                    break
                except:
                    pass

        if conn is False:
            if key is not None:
                key = paramiko.RSAKey.from_private_key(io.StringIO(key),
                                                       password=passphrase)

            logging.info("Making connection to host " + host)
            self.client.connect(host,
                                port,
                                username=username,
                                password=password,
                                pkey=key,
                                timeout=timeout,
                                allow_agent=False)
Beispiel #21
0
 def _get_key(self):
     try:
         import paramiko as ssh
     except ImportError:
         import ssh
     keys = ssh.Agent().get_keys()
     self._keys = filter(is_rsa, keys)
     if self._keys:
         self._agent_key = self._keys[0]
         self._keys = self._keys[1:]
         self.sign_algorithm, self.hash_algorithm = ('rsa', 'sha1')
Beispiel #22
0
def test_server_connection(server):
    agent = paramiko.Agent()
    keys = agent.get_keys()

    assert len(keys) == 1
    assert keys[0].get_name() == 'ssh-rsa'

    for key in keys:
        print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))

    agent.close()
Beispiel #23
0
 def get_keys(key=None, allow_agent=False, logger=None):
     agent_keys = []
     if allow_agent:
         agent = paramiko.Agent()
         agent_keys.extend(agent.get_keys())
         if logger:
             logger.debug('{0} keys loaded from agent'.format(
                 len(agent_keys)))
     if key:  # last one to try
         agent_keys.append(key)
     return agent_keys
Beispiel #24
0
    def __agent_auth(self, transport, username):
        agent = paramiko.Agent()
        agent_keys = agent.get_keys()
        if len(agent_keys) == 0:
            return

        for key in agent_keys:
            try:
                transport.auth_publickey(username, key)
                return
            except paramiko.SSHException:
                pass
Beispiel #25
0
 def open(self):
     self.ssh_agent = paramiko.Agent()
     keys = self.ssh_agent.get_keys()
     if len(keys) != 1:
         raise ShifterError("Failed to get a private key from ssh-agent")
     try:
         self.transport = paramiko.Transport((self.host, self.port))
         self.transport.connect(username=self.user, pkey=keys[0])
         self.sftp_client = paramiko.SFTPClient.from_transport(
             self.transport)
     except paramiko.SSHException as e:
         raise ShifterError(str(e))
Beispiel #26
0
def requires_password():
    """Check ssh key password requirement

    Checks to see if a passphrase/password is needed by the private ssh key.
    If it is needed and the user has not yet entered the passphrase for this
    key, it will return True.  If the user has already successfully entered the
    passphrase previously (by way of checking to see if there's already a key
    in the ssh-agent process) OR the private ssh key is not secured with a
    passphrase, then it will return False.

    Note: The ardana-service does not remember credentials across restarts.
          (i.e. ssh-agent will be reset when ardana-service restarts)

    .. :quickref: SSH Agent; does ssh key require password?

    **Example Request**:

    .. sourcecode:: http

       GET /api/v2/sshagent/requires_password HTTP/1.1
       Content-Type: application/json

    **Example Response**:

    .. sourcecode:: http

       HTTP/1.1 200 OK

       {
           "requires_password": false
       }
    """

    if not instance:
        response = jsonify({"error_msg": "ssh-agent instance not running"})
        response.status_code = 400
        return response

    # If there's already a key in ssh-agent, assume there is no need to add
    # any keys because user already entered a passphrased key
    agent = paramiko.Agent()
    if len(agent.get_keys()):
        return jsonify({"requires_password": False})
    agent.close()

    try:
        paramiko.RSAKey.from_private_key_file(instance.key_path)
        return jsonify({"requires_password": False})
    except paramiko.ssh_exception.PasswordRequiredException:
        return jsonify({"requires_password": True})
    except FileNotFoundError:
        return jsonify({"requires_password": True})
Beispiel #27
0
    def _auth(self, transport, username):
        # TODO: known hosts
        # paramiko.RSAKey.from_private_key_file(key_path)

        agent = paramiko.Agent()
        agent_keys = agent.get_keys()

        for key in agent_keys:
            try:
                transport.auth_publickey(username, key)
                return
            except paramiko.SSHException:
                pass
Beispiel #28
0
    def __init__(self,
                 server,
                 username,
                 password,
                 local_port,
                 remote_server,
                 preferred_private_key=None):
        """
		:param tuple server: The server to connect to.
		:param str username: The username to authenticate with.
		:param str password: The password to authenticate with.
		:param int local_port: The local port to forward.
		:param tuple remote_server: The remote server to connect to through the SSH server.
		:param str preferred_private_key: An RSA key to prefer for authentication.
		"""
        super(SSHTCPForwarder, self).__init__()
        self.local_port = local_port
        self.server = server
        self.remote_server = remote_server
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client = client
        self.username = username
        self.__connected = False

        # an issue seems to exist in paramiko when multiple keys are present through the ssh-agent
        ssh_agent = paramiko.Agent()
        ssh_keys = ssh_agent.get_keys()
        if len(ssh_keys) == 1:
            self.__try_connect(look_for_keys=False,
                               allow_agent=False,
                               pkey=ssh_keys[0])

        if not self.__connected and preferred_private_key:
            preferred_private_key = preferred_private_key.strip()
            preferred_private_key = preferred_private_key.replace(':', '')
            preferred_private_key = preferred_private_key.lower()
            preferred_private_key = filter(
                lambda k: binascii.b2a_hex(k.get_fingerprint()).lower() ==
                preferred_private_key, ssh_keys)
            if len(preferred_private_key) == 1:
                self.__try_connect(look_for_keys=False,
                                   allow_agent=False,
                                   pkey=preferred_private_key[0])

        if not self.__connected:
            self.__try_connect(password=password,
                               allow_agent=False,
                               look_for_keys=True,
                               raise_error=True)
Beispiel #29
0
def get_ssh_keys():
    agent = paramiko.Agent()
    if len(agent.get_keys()) > 0:
      return agent.get_keys()
    try:
        return [paramiko.RSAKey.from_private_key_file(SSH_KEY)]
    except paramiko.PasswordRequiredException:
        passwd = getpass.getpass("Enter passphrase for %s: " % SSH_KEY)
        try:
            return [paramiko.RSAKey.from_private_key_file(filename=SSH_KEY,
                                                         password=passwd)]
        except paramiko.SSHException:
            print "Could not read private key; bad password?"
            raise SystemExit(1)
Beispiel #30
0
def agent_auth(transport,username):
    agent=paramiko.Agent()
    agent_keys=agent.get_keys()
    if len(agent_keys)==0:
        return
    #对key认证方式处理
    for key in agent_keys:
        print('Trying ssh-agent key %s'%hexlify(key.get_fingerpint()))
        try:
            transport.auth_publickey(username,key)
            print('....success!')
            return
        except paramiko.SSHException:
            print('...nope.')