Пример #1
0
def sftp_server():
    """
    Set up an in-memory SFTP server thread. Yields the client Transport/socket.

    The resulting client Transport (along with all the server components) will
    be the same object throughout the test session; the `sftp` fixture then
    creates new higher level client objects wrapped around the client
    Transport, as necessary.
    """
    # Sockets & transports
    socks = LoopSocket()
    sockc = LoopSocket()
    sockc.link(socks)
    tc = Transport(sockc)
    ts = Transport(socks)
    # Auth
    host_key = load_private_key_file(_support('test_rsa.key'))
    ts.add_server_key(host_key)
    # Server setup
    event = threading.Event()
    server = StubServer()
    ts.set_subsystem_handler('sftp', SFTPServer, StubSFTPServer)
    ts.start_server(event, server)
    # Wait (so client has time to connect? Not sure. Old.)
    event.wait(1.0)
    # Make & yield connection.
    tc.connect(username='******', password='******')
    yield tc
Пример #2
0
 def _run(self):
     self.socks, addr = self.sockl.accept()
     self.ts = paramiko.Transport(self.socks)
     host_key = paramiko.load_private_key_file('tests/test_rsa.key')
     self.ts.add_server_key(host_key)
     server = NullServer()
     self.ts.start_server(self.event, server)
Пример #3
0
 def start_server(self):
     host_key = load_private_key_file(_support('test_rsa.key'))
     self.public_host_key = RSAKey(data=host_key.asbytes())
     self.ts.add_server_key(host_key)
     self.event = threading.Event()
     self.server = NullServer()
     self.assertTrue(not self.event.is_set())
     self.ts.start_server(self.event, self.server)
Пример #4
0
def manual_auth(username, hostname):
    default_auth = 'p'
    auth = input('Auth by (p)assword or (k)ey file? [%s] ' % default_auth)
    if len(auth) == 0:
        auth = default_auth

    if auth == 'k':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('Private key file [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.load_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('Private key password: '******'Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)
Пример #5
0
 def _run(self):
     self.socks, addr = self.sockl.accept()
     self.ts = paramiko.Transport(self.socks, gss_kex=True)
     host_key = paramiko.load_private_key_file('tests/test_rsa.key')
     self.ts.add_server_key(host_key)
     self.ts.set_gss_host(self.realm.hostname)
     try:
         self.ts.load_server_moduli()
     except:
         print('(Failed to load moduli -- gex will be unsupported.)')
     server = NullServer()
     self.ts.start_server(self.event, server)
Пример #6
0
 def test_multipart_auth(self):
     """
     verify that multipart auth works.
     """
     self.start_server()
     self.tc.connect(hostkey=self.public_host_key)
     remain = self.tc.auth_password(username='******',
                                    password='******')
     self.assertEqual(['publickey'], remain)
     key = load_private_key_file(_support('test_dss.key'))
     remain = self.tc.auth_publickey(username='******', key=key)
     self.assertEqual([], remain)
     self.verify_finished()
Пример #7
0
    def _test_gsskex_and_auth(self, gss_host, rekey=False):
        """
        Verify that Paramiko can handle SSHv2 GSS-API / SSPI authenticated
        Diffie-Hellman Key Exchange and user authentication with the GSS-API
        context created during key exchange.
        """
        host_key = paramiko.load_private_key_file('tests/test_rsa.key')
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.get_host_keys().add('[%s]:%d' % (self.hostname, self.port),
                                    'ssh-rsa', public_host_key)
        self.tc.connect(self.hostname,
                        self.port,
                        username=self.username,
                        gss_auth=True,
                        gss_kex=True,
                        gss_host=gss_host)

        self.event.wait(1.0)
        self.assertTrue(self.event.is_set())
        self.assertTrue(self.ts.is_active())
        self.assertEqual(self.username, self.ts.get_username())
        self.assertTrue(self.ts.is_authenticated())
        self.assertTrue(self.tc.get_transport().gss_kex_used)

        stdin, stdout, stderr = self.tc.exec_command('yes')
        schan = self.ts.accept(1.0)
        if rekey:
            self.tc.get_transport().renegotiate_keys()

        schan.send('Hello there.\n')
        schan.send_stderr('This is on stderr.\n')
        schan.close()

        self.assertEqual('Hello there.\n', stdout.readline())
        self.assertEqual('', stdout.readline())
        self.assertEqual('This is on stderr.\n', stderr.readline())
        self.assertEqual('', stderr.readline())

        stdin.close()
        stdout.close()
        stderr.close()
Пример #8
0
    def _test_connection(self, **kwargs):
        """
        (Most) kwargs get passed directly into SSHClient.connect().

        The exception is ... no exception yet
        """
        host_key = paramiko.load_private_key_file('tests/test_rsa.key')
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
        self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port),
                                    'ssh-rsa', public_host_key)
        self.tc.connect(hostname=self.addr,
                        port=self.port,
                        username=self.username,
                        gss_host=self.hostname,
                        gss_auth=True,
                        **kwargs)

        self.event.wait(1.0)
        self.assertTrue(self.event.is_set())
        self.assertTrue(self.ts.is_active())
        self.assertEqual(self.username, self.ts.get_username())
        self.assertTrue(self.ts.is_authenticated())

        stdin, stdout, stderr = self.tc.exec_command('yes')
        schan = self.ts.accept(1.0)

        schan.send('Hello there.\n')
        schan.send_stderr('This is on stderr.\n')
        schan.close()

        self.assertEqual('Hello there.\n', stdout.readline())
        self.assertEqual('', stdout.readline())
        self.assertEqual('This is on stderr.\n', stderr.readline())
        self.assertEqual('', stderr.readline())

        stdin.close()
        stdout.close()
        stderr.close()
Пример #9
0
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.

import socket
import sys
import threading
import traceback

import paramiko
from paramiko.py3compat import decodebytes

# setup logging
paramiko.util.log_to_file('demo_server.log')

host_key = paramiko.load_private_key_file('test_rsa.key')

print("Read key: " + host_key.get_fingerprint_sha256_b64())


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()
Пример #10
0
class NullServer(ServerInterface):
    paranoid_did_password = False
    paranoid_did_public_key = False
    paranoid_key = load_private_key_file(_support('test_dss.key'))

    def get_allowed_auths(self, username):
        if username == 'slowdive':
            return 'publickey,password'
        if username == 'paranoid':
            if not self.paranoid_did_password and not self.paranoid_did_public_key:
                return 'publickey,password'
            elif self.paranoid_did_password:
                return 'publickey'
            else:
                return 'password'
        if username == 'commie':
            return 'keyboard-interactive'
        if username == 'utf8':
            return 'password'
        if username == 'non-utf8':
            return 'password'
        return 'publickey'

    def check_auth_password(self, username, password):
        if (username == 'slowdive') and (password == 'pygmalion'):
            return AUTH_SUCCESSFUL
        if (username == 'paranoid') and (password == 'paranoid'):
            # 2-part auth (even openssh doesn't support this)
            self.paranoid_did_password = True
            if self.paranoid_did_public_key:
                return AUTH_SUCCESSFUL
            return AUTH_PARTIALLY_SUCCESSFUL
        if (username == 'utf8') and (password == _pwd):
            return AUTH_SUCCESSFUL
        if (username == 'non-utf8') and (password == '\xff'):
            return AUTH_SUCCESSFUL
        if username == 'bad-server':
            raise Exception("Ack!")
        if username == 'unresponsive-server':
            sleep(5)
            return AUTH_SUCCESSFUL
        return AUTH_FAILED

    def check_auth_publickey(self, username, key):
        if (username == 'paranoid') and (key == self.paranoid_key):
            # 2-part auth
            self.paranoid_did_public_key = True
            if self.paranoid_did_password:
                return AUTH_SUCCESSFUL
            return AUTH_PARTIALLY_SUCCESSFUL
        return AUTH_FAILED

    def check_auth_interactive(self, username, submethods):
        if username == 'commie':
            self.username = username
            return InteractiveQuery('password', 'Please enter a password.',
                                    ('Password', False))
        return AUTH_FAILED

    def check_auth_interactive_response(self, responses):
        if self.username == 'commie':
            if (len(responses) == 1) and (responses[0] == 'cat'):
                return AUTH_SUCCESSFUL
        return AUTH_FAILED