Пример #1
0
    def test_is_missing_host_key(self):
        client = paramiko.SSHClient()
        file1 = make_tests_data_path('known_hosts_example')
        file2 = make_tests_data_path('known_hosts_example2')
        client.load_host_keys(file1)
        client.load_system_host_keys(file2)

        autoadd = AutoAddPolicy()
        for f in [file1, file2]:
            entry = paramiko.hostkeys.HostKeys(f)._entries[0]
            hostname = entry.hostnames[0]
            key = entry.key
            self.assertIsNone(
                autoadd.is_missing_host_key(client, hostname, key))

        for f in [file1, file2]:
            entry = paramiko.hostkeys.HostKeys(f)._entries[0]
            hostname = entry.hostnames[0]
            key = entry.key
            key.get_name = lambda: 'unknown'
            self.assertTrue(autoadd.is_missing_host_key(client, hostname, key))
        del key.get_name

        for f in [file1, file2]:
            entry = paramiko.hostkeys.HostKeys(f)._entries[0]
            hostname = entry.hostnames[0][1:]
            key = entry.key
            self.assertTrue(autoadd.is_missing_host_key(client, hostname, key))

        file3 = make_tests_data_path('known_hosts_example3')
        entry = paramiko.hostkeys.HostKeys(file3)._entries[0]
        hostname = entry.hostnames[0]
        key = entry.key
        with self.assertRaises(paramiko.BadHostKeyException):
            autoadd.is_missing_host_key(client, hostname, key)
Пример #2
0
    def test_app_auth_with_valid_pubkey_by_multipart_form(self):
        url = self.get_url('/')
        client = self.get_http_client()
        response = yield client.fetch(url)
        self.assertEqual(response.code, 200)

        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        files = [('privatekey', 'user_rsa_key', privatekey)]
        content_type, body = encode_multipart_formdata(self.body_dict.items(),
                                                       files)
        headers = {
            'Content-Type': content_type,
            'content-length': str(len(body))
        }
        response = yield client.fetch(url,
                                      method='POST',
                                      headers=headers,
                                      body=body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close()
Пример #3
0
    def test_missing_host_key(self):
        client = paramiko.SSHClient()
        file1 = make_tests_data_path('known_hosts_example')
        file2 = make_tests_data_path('known_hosts_example2')
        filename = make_tests_data_path('known_hosts')
        copyfile(file1, filename)
        client.load_host_keys(filename)
        n1 = len(client._host_keys)

        autoadd = AutoAddPolicy()
        entry = paramiko.hostkeys.HostKeys(file2)._entries[0]
        hostname = entry.hostnames[0]
        key = entry.key
        autoadd.missing_host_key(client, hostname, key)
        self.assertEqual(len(client._host_keys), n1 + 1)
        self.assertEqual(paramiko.hostkeys.HostKeys(filename),
                         client._host_keys)
        os.unlink(filename)
Пример #4
0
 def test_app_with_user_pkey2fa_with_empty_passcode(self):
     url = self.get_url('/')
     privatekey = read_file(make_tests_data_path('user_rsa_key'))
     self.body_dict.update(username='******',
                           password='******',
                           privatekey=privatekey,
                           totp='')
     response = yield self.async_post(url, self.body_dict)
     data = json.loads(to_str(response.body))
     self.assert_status_in('Need a verification code', data)
    def test_get_host_keys_settings(self):
        options.hostfile = ''
        options.syshostfile = ''
        dic = get_host_keys_settings(options)

        filename = os.path.join(base_dir, 'known_hosts')
        self.assertEqual(dic['host_keys'], load_host_keys(filename))
        self.assertEqual(dic['host_keys_filename'], filename)
        self.assertEqual(
            dic['system_host_keys'],
            load_host_keys(os.path.expanduser('~/.ssh/known_hosts')))

        options.hostfile = make_tests_data_path('known_hosts_example')
        options.syshostfile = make_tests_data_path('known_hosts_example2')
        dic2 = get_host_keys_settings(options)
        self.assertEqual(dic2['host_keys'], load_host_keys(options.hostfile))
        self.assertEqual(dic2['host_keys_filename'], options.hostfile)
        self.assertEqual(dic2['system_host_keys'],
                         load_host_keys(options.syshostfile))
Пример #6
0
 def test_app_with_user_pass2fa_with_wrong_pkey_correct_passwords(self):
     url = self.get_url('/')
     privatekey = read_file(make_tests_data_path('user_rsa_key'))
     self.body_dict.update(username='******',
                           password='******',
                           privatekey=privatekey,
                           totp='passcode')
     response = yield self.async_post(url, self.body_dict)
     data = json.loads(to_str(response.body))
     self.assert_status_none(data)
Пример #7
0
    def test_get_specific_pkey_with_plain_key(self):

        fname = 'test_rsa.key'
        cls = paramiko.RSAKey
        key = read_file(make_tests_data_path(fname))
        pkey = IndexHandler.get_specific_pkey(cls, key, None)
        self.assertIsInstance(pkey, cls)
        pkey = IndexHandler.get_specific_pkey(cls, key, 'iginored')
        self.assertIsInstance(pkey, cls)
        pkey = IndexHandler.get_specific_pkey(cls, 'x' + key, None)
        self.assertIsNone(pkey)
Пример #8
0
class TestAppWithRejectPolicy(OtherTestBase):

    policy = 'reject'
    hostfile = make_tests_data_path('known_hosts_example')

    @tornado.testing.gen_test
    def test_app_with_hostname_not_in_hostkeys(self):
        response = yield self.async_post('/', urlencode(self.body), self.headers) # noqa
        data = json.loads(to_str(response.body))
        message = 'Connection to {}:{} is not allowed.'.format(self.body['hostname'], self.sshserver_port) # noqa
        self.assertEqual(message, data['status'])
Пример #9
0
 def test_get_pkey_obj_with_plain_key(self):
     fname = 'test_ed25519.key'
     cls = paramiko.Ed25519Key
     key = read_file(make_tests_data_path(fname))
     pkey = IndexHandler.get_pkey_obj(key, None, fname)
     self.assertIsInstance(pkey, cls)
     pkey = IndexHandler.get_pkey_obj(key, 'iginored', fname)
     self.assertIsInstance(pkey, cls)
     with self.assertRaises(InvalidException) as exc:
         pkey = IndexHandler.get_pkey_obj('x' + key, None, fname)
         self.assertIn('Invalid private key', str(exc))
Пример #10
0
    def test_load_host_keys(self):
        path = '/path-not-exists'
        host_keys = load_host_keys(path)
        self.assertFalse(host_keys)

        path = '/tmp'
        host_keys = load_host_keys(path)
        self.assertFalse(host_keys)

        path = make_tests_data_path('known_hosts_example')
        host_keys = load_host_keys(path)
        self.assertEqual(host_keys, paramiko.hostkeys.HostKeys(path))
Пример #11
0
 def test_get_pkey_obj_with_encrypted_key(self):
     fname = 'test_ed25519_password.key'
     password = '******'
     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(InvalidException) as exc:
         pkey = IndexHandler.get_pkey_obj(key, 'wrongpass', fname)
         self.assertIn('Wrong password', str(exc))
     with self.assertRaises(InvalidException) as exc:
         pkey = IndexHandler.get_pkey_obj('x' + key, password, fname)
         self.assertIn('Invalid private key', str(exc))
Пример #12
0
    def test_get_specific_pkey_with_encrypted_key(self):
        fname = 'test_rsa_password.key'
        cls = paramiko.RSAKey
        password = '******'

        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)
Пример #13
0
class TestAppWithBadHostKey(OtherTestBase):

    policy = random.choice(['warning', 'autoadd', 'reject'])
    hostfile = make_tests_data_path('test_known_hosts')

    def setUp(self):
        self.sshserver_port = 2222
        super(TestAppWithBadHostKey, self).setUp()

    @tornado.testing.gen_test
    def test_app_with_bad_host_key(self):
        response = yield self.async_post('/', urlencode(self.body), self.headers) # noqa
        data = json.loads(to_str(response.body))
        self.assertEqual('Bad host key.', data['status'])
Пример #14
0
    def test_app_auth_with_valid_pubkey_by_urlencoded_form(self):
        url = self.get_url('/')
        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        self.body_dict.update(privatekey=privatekey)
        response = yield self.async_post(url, self.body_dict)
        data = json.loads(to_str(response.body))
        self.assert_status_none(data)

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close()
Пример #15
0
    def test_get_specific_pkey_with_encrypted_key(self):
        fname = 'test_rsa_password.key'
        cls = paramiko.RSAKey
        password = '******'

        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(InvalidValueError) as ctx:
            pkey = IndexHandler.get_specific_pkey(cls, key, None)
        self.assertIn('Need a password', str(ctx.exception))
Пример #16
0
    def test_check_policy_setting(self):
        host_keys_filename = make_tests_data_path('host_keys_test.db')
        host_keys_settings = dict(
            host_keys=paramiko.hostkeys.HostKeys(),
            system_host_keys=paramiko.hostkeys.HostKeys(),
            host_keys_filename=host_keys_filename)

        with self.assertRaises(ValueError):
            check_policy_setting(RejectPolicy, host_keys_settings)

        try:
            os.unlink(host_keys_filename)
        except OSError:
            pass
        check_policy_setting(AutoAddPolicy, host_keys_settings)
        self.assertEqual(os.path.exists(host_keys_filename), True)
Пример #17
0
class TestAppWithRejectPolicy(OtherTestBase):

    policy = 'reject'
    hostfile = make_tests_data_path('known_hosts_example')

    @tornado.testing.gen_test
    def test_app_with_hostname_not_in_hostkeys(self):
        url = self.get_url('/')
        client = self.get_http_client()
        body = urlencode(dict(self.body, username='******'))
        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['id'])
        self.assertIsNone(data['encoding'])
        message = 'Connection to {}:{} is not allowed.'.format(self.body['hostname'], self.sshserver_port) # noqa
        self.assertEqual(message, data['status'])
Пример #18
0
class TestAppWithBadHostKey(OtherTestBase):

    policy = random.choice(['warning', 'autoadd', 'reject'])
    hostfile = make_tests_data_path('test_known_hosts')

    def setUp(self):
        self.sshserver_port = 2222
        super(TestAppWithBadHostKey, self).setUp()

    @tornado.testing.gen_test
    def test_app_with_bad_host_key(self):
        url = self.get_url('/')
        client = self.get_http_client()
        body = urlencode(dict(self.body, username='******'))
        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['id'])
        self.assertIsNone(data['encoding'])
        self.assertEqual('Bad host key.', data['status'])
Пример #19
0
    def test_app_auth_with_valid_pubkey_by_urlencoded_form(self):
        url = self.get_url('/')
        client = self.get_http_client()
        response = yield client.fetch(url)
        self.assertEqual(response.code, 200)

        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        self.body_dict.update(privatekey=privatekey)
        body = urlencode(self.body_dict)
        response = yield client.fetch(url, method='POST', body=body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close()
    def test_get_ssl_context(self):
        options.certfile = ''
        options.keyfile = ''
        ssl_ctx = get_ssl_context(options)
        self.assertIsNone(ssl_ctx)

        options.certfile = 'provided'
        options.keyfile = ''
        with self.assertRaises(ValueError) as ctx:
            ssl_ctx = get_ssl_context(options)
        self.assertEqual('keyfile is not provided', str(ctx.exception))

        options.certfile = ''
        options.keyfile = 'provided'
        with self.assertRaises(ValueError) as ctx:
            ssl_ctx = get_ssl_context(options)
        self.assertEqual('certfile is not provided', str(ctx.exception))

        options.certfile = 'FileDoesNotExist'
        options.keyfile = make_tests_data_path('cert.key')
        with self.assertRaises(ValueError) as ctx:
            ssl_ctx = get_ssl_context(options)
        self.assertIn('does not exist', str(ctx.exception))

        options.certfile = make_tests_data_path('cert.key')
        options.keyfile = 'FileDoesNotExist'
        with self.assertRaises(ValueError) as ctx:
            ssl_ctx = get_ssl_context(options)
        self.assertIn('does not exist', str(ctx.exception))

        options.certfile = make_tests_data_path('cert.key')
        options.keyfile = make_tests_data_path('cert.key')
        with self.assertRaises(ssl.SSLError) as ctx:
            ssl_ctx = get_ssl_context(options)

        options.certfile = make_tests_data_path('cert.crt')
        options.keyfile = make_tests_data_path('cert.key')
        ssl_ctx = get_ssl_context(options)
        self.assertIsNotNone(ssl_ctx)
Пример #21
0
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.

import random
import socket
# import sys
import threading
# import traceback
import paramiko

from binascii import hexlify
from paramiko.py3compat import u, decodebytes
from tests.utils import make_tests_data_path


# setup logging
paramiko.util.log_to_file(make_tests_data_path('sshserver.log'))

host_key = paramiko.RSAKey(filename=make_tests_data_path('test_rsa.key'))
# host_key = paramiko.DSSKey(filename='test_dss.key')

print('Read key: ' + u(hexlify(host_key.get_fingerprint())))

banner = u'\r\n\u6b22\u8fce\r\n'
event_timeout = 5


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
Пример #22
0
 def get_pk_obj(self, fname, password=None):
     key = read_file(make_tests_data_path(fname))
     return PrivateKey(key, password=password, filename=fname)