Python paramiko.PasswordRequiredException() Examples

The following are 17 code examples of paramiko.PasswordRequiredException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko , or try the search function .
Example #1
Source File: test_handler.py    From adminset with GNU General Public License v2.0 8 votes vote down vote up
def test_get_pkey_obj_with_encrypted_key(self):
        fname = 'test_ed25519_password.key'
        password = 'abc123'
        cls = paramiko.Ed25519Key
        key = read_file(make_tests_data_path(fname))

        pkey = IndexHandler.get_pkey_obj(key, password, fname)
        self.assertIsInstance(pkey, cls)

        with self.assertRaises(InvalidValueError) as ctx:
            pkey = IndexHandler.get_pkey_obj(key, 'wrongpass', fname)
        self.assertIn('Wrong password', str(ctx.exception))

        with self.assertRaises(InvalidValueError) as ctx:
            pkey = IndexHandler.get_pkey_obj('x'+key, '', fname)
        self.assertIn('Invalid private key', str(ctx.exception))

        with self.assertRaises(paramiko.PasswordRequiredException):
            pkey = IndexHandler.get_pkey_obj(key, '', fname) 
Example #2
Source File: handler.py    From webssh with MIT License 6 votes vote down vote up
def get_specific_pkey(self, name, offset, password):
        self.iostr.seek(offset)
        logging.debug('Reset offset to {}.'.format(offset))

        logging.debug('Try parsing it as {} type key'.format(name))
        pkeycls = getattr(paramiko, name+'Key')
        pkey = None

        try:
            pkey = pkeycls.from_private_key(self.iostr, password=password)
        except paramiko.PasswordRequiredException:
            raise InvalidValueError('Need a passphrase to decrypt the key.')
        except (paramiko.SSHException, ValueError) as exc:
            self.last_exception = exc
            logging.debug(str(exc))

        return pkey 
Example #3
Source File: RoHoneypot.py    From networking with GNU General Public License v3.0 6 votes vote down vote up
def check_auth_password(self, username, password):
		logger.info("-=-=- %s -=-=-\nUser: %s\nPassword: %s\n" % (self.client_address[0], username, password))
		
		print " IP: %s\n User: %s\n Pass: %s\n" % (self.client_address[0], username, password)
			
		if DENY_ALL == True:
			return paramiko.AUTH_FAILED
		f = open("blocked.dat","r")
		data = str(f.readlines()).find(self.client_address[0])
		if data > 1:
			if ran:
				new_key()
			return paramiko.PasswordRequiredException
		else:
			f = open("blocked.dat","a")
			deepscan(self.client_address[0],f)
		paramiko.OPEN_FAILED_CONNECT_FAILED
		if (username == "root") and (password in PASSWORDS):
			return paramiko.AUTH_SUCCESSFUL
		return paramiko.AUTH_FAILED 
Example #4
Source File: sftp.py    From statik with MIT License 6 votes vote down vote up
def try_load_private_key_interactive(filename, password=None,
        error_context=None):
    """Wraps the try_load_private_key method such that it can request a password
    from the user via stdin if necessary."""
    try:
        return try_load_private_key(
            filename,
            password=password,
            error_context=error_context,
        )
    except paramiko.PasswordRequiredException:
        print("The SSH key %s requires a password")
        password = getpass.getpass("Please enter the password for this key:")
        return try_load_private_key(
            filename,
            password=password,
            error_context=error_context,
        ) 
Example #5
Source File: test_sftp.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def init(hostname, username, keyfile, passwd):
        global sftp, tc

        t = paramiko.Transport(hostname)
        tc = t
        try:
            key = paramiko.RSAKey.from_private_key_file(keyfile, passwd)
        except paramiko.PasswordRequiredException:
            sys.stderr.write('\n\nparamiko.RSAKey.from_private_key_file REQUIRES PASSWORD.\n')
            sys.stderr.write('You have two options:\n')
            sys.stderr.write('* Use the "-K" option to point to a different (non-password-protected)\n')
            sys.stderr.write('  private key file.\n')
            sys.stderr.write('* Use the "-P" option to provide the password needed to unlock this private\n')
            sys.stderr.write('  key.\n')
            sys.stderr.write('\n')
            sys.exit(1)
        try:
            t.connect(username=username, pkey=key)
        except paramiko.SSHException:
            t.close()
            sys.stderr.write('\n\nparamiko.Transport.connect FAILED.\n')
            sys.stderr.write('There are several possible reasons why it might fail so quickly:\n\n')
            sys.stderr.write('* The host to connect to (%s) is not a valid SSH server.\n' % hostname)
            sys.stderr.write('  (Use the "-H" option to change the host.)\n')
            sys.stderr.write('* The username to auth as (%s) is invalid.\n' % username)
            sys.stderr.write('  (Use the "-U" option to change the username.)\n')
            sys.stderr.write('* The private key given (%s) is not accepted by the server.\n' % keyfile)
            sys.stderr.write('  (Use the "-K" option to provide a different key file.)\n')
            sys.stderr.write('\n')
            sys.exit(1)
        sftp = paramiko.SFTP.from_transport(t) 
Example #6
Source File: demo.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def manual_auth(username, hostname):
    default_auth = 'p'
    auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
    if len(auth) == 0:
        auth = default_auth

    if auth == 'r':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: ')
            key = paramiko.RSAKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    elif auth == 'd':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: ')
            key = paramiko.DSSKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    else:
        pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)


# setup logging 
Example #7
Source File: main.py    From autoops with Apache License 2.0 5 votes vote down vote up
def get_specific_pkey(self, pkeycls, privatekey, password):
        logging.info('Trying {}'.format(pkeycls.__name__))
        try:
            pkey = pkeycls.from_private_key(io.StringIO(privatekey),
                                            password=password)
        except paramiko.PasswordRequiredException:
            raise ValueError('Need password to decrypt the private key.')
        except paramiko.SSHException:
            pass
        else:
            return pkey 
Example #8
Source File: handler.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def get_specific_pkey(cls, pkeycls, privatekey, password):
        logging.info('Trying {}'.format(pkeycls.__name__))
        try:
            pkey = pkeycls.from_private_key(io.StringIO(privatekey),
                                            password=password)
        except paramiko.PasswordRequiredException:
            raise
        except paramiko.SSHException:
            pass
        else:
            return pkey 
Example #9
Source File: test_handler.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_get_specific_pkey_with_encrypted_key(self):
        fname = 'test_rsa_password.key'
        cls = paramiko.RSAKey
        password = 'television'

        key = read_file(make_tests_data_path(fname))
        pkey = IndexHandler.get_specific_pkey(cls, key, password)
        self.assertIsInstance(pkey, cls)

        pkey = IndexHandler.get_specific_pkey(cls, 'x'+key, None)
        self.assertIsNone(pkey)

        with self.assertRaises(paramiko.PasswordRequiredException):
            pkey = IndexHandler.get_specific_pkey(cls, key, None) 
Example #10
Source File: connection.py    From conn with GNU General Public License v2.0 5 votes vote down vote up
def manual_auth(username, hostname):
    try:
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: ')
            key = paramiko.RSAKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    except IOError:
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: ')
            key = paramiko.DSSKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    #except paramiko.AuthenticationException as e:
    except:
        pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
        try:
            t.auth_password(username, pw)
        except (paramiko.AuthenticationException, KeyboardInterrupt) as error:
            print 'Permission denied, Authentication Error' 
Example #11
Source File: main.py    From chain with Apache License 2.0 5 votes vote down vote up
def get_specific_pkey(self, pkeycls, privatekey, password):
        logging.info('Trying {}'.format(pkeycls.__name__))
        try:
            pkey = pkeycls.from_private_key(io.StringIO(privatekey),
                                            password=password)
        except paramiko.PasswordRequiredException:
            raise ValueError('Need password to decrypt the private key.')
        except paramiko.SSHException:
            pass
        else:
            return pkey 
Example #12
Source File: auth.py    From margaritashotgun with MIT License 5 votes vote down vote up
def load_key(self, key_path, password):
        """
        Creates paramiko rsa key

        :type key_path: str
        :param key_path: path to rsa key
        :type password: str
        :param password: password to try if rsa key is encrypted
        """

        try:
            return paramiko.RSAKey.from_private_key_file(key_path)
        except PasswordRequiredException as ex:
            return paramiko.RSAKey.from_private_key_file(key_path,
                                                         password=password) 
Example #13
Source File: ssh_forward.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __try_connect(self, *args, **kwargs):
		raise_error = kwargs.pop('raise_error', False)
		try:
			self.client.connect(self.server[0], self.server[1], username=self.username, allow_agent=False, timeout=12.0, *args, **kwargs)
		except paramiko.PasswordRequiredException:
			raise
		except paramiko.AuthenticationException as error:
			if raise_error:
				raise error
			return False
		self.__connected = True
		return True 
Example #14
Source File: sftp.py    From statik with MIT License 4 votes vote down vote up
def try_load_private_key(filename, password=None, error_context=None):
    """Attempts to load a private key from the given file. Tries different types
    of keys (RSA, DSS, ECDSA, Ed25519)."""
    try:
        logger.debug("Attempting to load private key file as RSA key")
        return paramiko.rsakey.RSAKey.from_private_key_file(filename,
            password=password)
    except paramiko.PasswordRequiredException as e:
        raise e
    except Exception as e:
        logger.debug("Cannot load as RSA key: %s" % e)

    try:
        logger.debug("Attempting to load private key file as DSS key")
        return paramiko.dsskey.DSSKey.from_private_key_file(filename,
            password=password)
    except paramiko.PasswordRequiredException as e:
        raise e
    except Exception as e:
        logger.debug("Cannot load as DSS key: %s" % e)

    try:
        logger.debug("Attempting to load private key file as ECDSA key")
        return paramiko.ecdsakey.ECDSAKey.from_private_key_file(filename,
            password=password)
    except paramiko.PasswordRequiredException as e:
        raise e
    except Exception as e:
        logger.debug("Cannot load as ECDSA key: %s" % e)

    try:
        logger.debug("Attempting to load private key file as Ed25519 key")
        return paramiko.ed25519key.Ed25519Key.from_private_key_file(filename,
            password=password)
    except paramiko.PasswordRequiredException as e:
        raise e
    except Exception as e:
        logger.debug("Cannot load as Ed25519 key: %s" % e)

    raise ProjectConfigurationError(
        message="Failed to load private key for SFTP deployment: %s" % filename,
        context=error_context,
    ) 
Example #15
Source File: application.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _create_ssh_forwarder(self, server, username, password, window=None):
		"""
		Create and set the
		:py:attr:`~.KingPhisherClientApplication._ssh_forwarder` attribute.

		:param tuple server: The server information as a host and port tuple.
		:param str username: The username to authenticate to the SSH server with.
		:param str password: The password to authenticate to the SSH server with.
		:param window: The GTK window to use as the parent for error dialogs.
		:type window: :py:class:`Gtk.Window`
		:rtype: int
		:return: The local port that is forwarded to the remote server or None if the connection failed.
		"""
		window = window or self.get_active_window()
		title_ssh_error = 'Failed To Connect To The SSH Service'
		server_remote_port = self.config['server_remote_port']

		try:
			self._ssh_forwarder = ssh_forward.SSHTCPForwarder(
				server,
				username,
				password,
				('127.0.0.1', server_remote_port),
				private_key=self.config.get('ssh_preferred_key'),
				missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self)
			)
			self._ssh_forwarder.start()
		except ssh_forward.KingPhisherSSHKeyError as error:
			gui_utilities.show_dialog_error('SSH Key Configuration Error', window, error.message)
		except errors.KingPhisherAbortError as error:
			self.logger.info("ssh connection aborted ({0})".format(error.message))
		except paramiko.PasswordRequiredException:
			gui_utilities.show_dialog_error(title_ssh_error, window, 'The specified SSH key requires a password.')
		except paramiko.AuthenticationException:
			self.logger.warning('failed to authenticate to the remote ssh server')
			gui_utilities.show_dialog_error(title_ssh_error, window, 'The server responded that the credentials are invalid.')
		except paramiko.SSHException as error:
			self.logger.warning("failed with ssh exception '{0}'".format(error.args[0]))
		except socket.error as error:
			gui_utilities.show_dialog_exc_socket_error(error, window, title=title_ssh_error)
		except Exception as error:
			self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
			gui_utilities.show_dialog_error(title_ssh_error, window, "An {0}.{1} error occurred.".format(error.__class__.__module__, error.__class__.__name__))
		else:
			return self._ssh_forwarder.local_server
		self.emit('server-disconnected')
		return 
Example #16
Source File: sshtunnel.py    From sshtunnel with MIT License 4 votes vote down vote up
def read_private_key_file(pkey_file,
                              pkey_password=None,
                              key_type=None,
                              logger=None):
        """
        Get SSH Public key from a private key file, given an optional password

        Arguments:
            pkey_file (str):
                File containing a private key (RSA, DSS or ECDSA)
        Keyword Arguments:
            pkey_password (Optional[str]):
                Password to decrypt the private key
            logger (Optional[logging.Logger])
        Return:
            paramiko.Pkey
        """
        ssh_pkey = None
        for pkey_class in (key_type,) if key_type else (
            paramiko.RSAKey,
            paramiko.DSSKey,
            paramiko.ECDSAKey,
            paramiko.Ed25519Key
        ):
            try:
                ssh_pkey = pkey_class.from_private_key_file(
                    pkey_file,
                    password=pkey_password
                )
                if logger:
                    logger.debug('Private key file ({0}, {1}) successfully '
                                 'loaded'.format(pkey_file, pkey_class))
                break
            except paramiko.PasswordRequiredException:
                if logger:
                    logger.error('Password is required for key {0}'
                                 .format(pkey_file))
                break
            except paramiko.SSHException:
                if logger:
                    logger.debug('Private key file ({0}) could not be loaded '
                                 'as type {1} or bad password'
                                 .format(pkey_file, pkey_class))
        return ssh_pkey 
Example #17
Source File: ssh_forward.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __resolve_private_key(self, private_key, agent_keys):
		private_key = private_key.strip()
		pkey_type = private_key.split(':', 1)[0].lower()
		if pkey_type in ('file', 'key'):
			if pkey_type == 'file':
				file_path = os.path.expandvars(private_key[5:])
				if not os.access(file_path, os.R_OK):
					self.logger.warning("the user specified ssh key file '{0}' can not be opened".format(file_path))
					raise KingPhisherSSHKeyError('The SSH key file can not be opened.')
				self.logger.debug('loading the user specified ssh key file: ' + file_path)
				file_h = open(file_path, 'r')
				first_line = file_h.readline()
				file_h.seek(0, os.SEEK_SET)
			else:
				self.logger.debug('loading the user specified ssh key string from memory')
				key_str = private_key[4:]
				file_h = io.StringIO(key_str)
				first_line = key_str.split('\n', 1)[0]

			if 'BEGIN DSA PRIVATE KEY' in first_line:
				KeyKlass = paramiko.DSSKey
			elif 'BEGIN RSA PRIVATE KEY' in first_line:
				KeyKlass = paramiko.RSAKey
			else:
				file_h.close()
				self.logger.warning('the user specified ssh key does not appear to be a valid dsa or rsa private key')
				raise KingPhisherSSHKeyError('The SSH key file is not a DSA or RSA private key.')
			try:
				private_key = KeyKlass.from_private_key(file_h)
			except paramiko.PasswordRequiredException:
				self.logger.warning('the user specified ssh key is encrypted and requires a password')
				raise
			finally:
				file_h.close()
			return private_key
		# if the key has whitespace, discard anything after the first occurrence
		private_key = private_key.split(' ', 1)[0]

		# if it's not one of the above, treat it like it's a fingerprint
		if pkey_type == 'sha256':
			# OpenSSH 6.8 started to use sha256 & base64 for keys
			algorithm = pkey_type
			private_key = private_key[7:] + '='
			decode = binascii.a2b_base64
		else:
			algorithm = 'md5'
			private_key = private_key.replace(':', '')
			decode = binascii.a2b_hex
		try:
			private_key = decode(private_key)
		except binascii.Error as error:
			self.logger.warning("the user specified ssh key could not be decoded (type: {0}, error: {1!r})".format(pkey_type, error))
			raise KingPhisherSSHKeyError('The preferred SSH key could not be decoded.')
		private_key = tuple(key for key in agent_keys if hashlib.new(algorithm, key.blob).digest() == private_key)
		if not private_key:
			self.logger.warning('the user specified ssh key could not be loaded from the ssh agent')
			raise KingPhisherSSHKeyError('The preferred SSH key could not be loaded from the SSH agent.')
		return private_key[0]