From 7f2c35052183b400827d9949a68b41c90f90a32d Mon Sep 17 00:00:00 2001 From: Chris Rose Date: Thu, 17 May 2018 10:13:38 -0400 Subject: Blacken Paramiko on 2.4 --- tests/test_transport.py | 313 ++++++++++++++++++++++++++++-------------------- 1 file changed, 184 insertions(+), 129 deletions(-) (limited to 'tests/test_transport.py') diff --git a/tests/test_transport.py b/tests/test_transport.py index 9474acfc..e09c5e92 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -32,14 +32,26 @@ from hashlib import sha1 import unittest from paramiko import ( - Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey, SSHException, - ChannelException, Packetizer, Channel, + Transport, + SecurityOptions, + ServerInterface, + RSAKey, + DSSKey, + SSHException, + ChannelException, + Packetizer, + Channel, ) from paramiko import AUTH_FAILED, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED from paramiko.common import ( - MSG_KEXINIT, cMSG_CHANNEL_WINDOW_ADJUST, MIN_PACKET_SIZE, MIN_WINDOW_SIZE, - MAX_WINDOW_SIZE, DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, + MSG_KEXINIT, + cMSG_CHANNEL_WINDOW_ADJUST, + MIN_PACKET_SIZE, + MIN_WINDOW_SIZE, + MAX_WINDOW_SIZE, + DEFAULT_WINDOW_SIZE, + DEFAULT_MAX_PACKET_SIZE, ) from paramiko.py3compat import bytes from paramiko.message import Message @@ -61,28 +73,28 @@ Maybe. """ -class NullServer (ServerInterface): +class NullServer(ServerInterface): paranoid_did_password = False paranoid_did_public_key = False - paranoid_key = DSSKey.from_private_key_file(_support('test_dss.key')) + paranoid_key = DSSKey.from_private_key_file(_support("test_dss.key")) def get_allowed_auths(self, username): - if username == 'slowdive': - return 'publickey,password' - return 'publickey' + if username == "slowdive": + return "publickey,password" + return "publickey" def check_auth_password(self, username, password): - if (username == 'slowdive') and (password == 'pygmalion'): + if (username == "slowdive") and (password == "pygmalion"): return AUTH_SUCCESSFUL return AUTH_FAILED def check_channel_request(self, kind, chanid): - if kind == 'bogus': + if kind == "bogus": return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED return OPEN_SUCCEEDED def check_channel_exec_request(self, channel, command): - if command != b'yes': + if command != b"yes": return False return True @@ -95,9 +107,16 @@ class NullServer (ServerInterface): # tho that's only supposed to occur if the request cannot be served. # For now, leaving that the default unless test supplies specific # 'acceptable' request kind - return kind == 'acceptable' - - def check_channel_x11_request(self, channel, single_connection, auth_protocol, auth_cookie, screen_number): + return kind == "acceptable" + + def check_channel_x11_request( + self, + channel, + single_connection, + auth_protocol, + auth_cookie, + screen_number, + ): self._x11_single_connection = single_connection self._x11_auth_protocol = auth_protocol self._x11_auth_cookie = auth_cookie @@ -106,7 +125,7 @@ class NullServer (ServerInterface): def check_port_forward_request(self, addr, port): self._listen = socket.socket() - self._listen.bind(('127.0.0.1', 0)) + self._listen.bind(("127.0.0.1", 0)) self._listen.listen(1) return self._listen.getsockname()[1] @@ -120,6 +139,7 @@ class NullServer (ServerInterface): class TransportTest(unittest.TestCase): + def setUp(self): self.socks = LoopSocket() self.sockc = LoopSocket() @@ -134,9 +154,9 @@ class TransportTest(unittest.TestCase): self.sockc.close() def setup_test_server( - self, client_options=None, server_options=None, connect_kwargs=None, + self, client_options=None, server_options=None, connect_kwargs=None ): - host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) + host_key = RSAKey.from_private_key_file(_support("test_rsa.key")) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) @@ -152,8 +172,8 @@ class TransportTest(unittest.TestCase): if connect_kwargs is None: connect_kwargs = dict( hostkey=public_host_key, - username='slowdive', - password='pygmalion', + username="slowdive", + password="pygmalion", ) self.tc.connect(**connect_kwargs) event.wait(1.0) @@ -163,11 +183,11 @@ class TransportTest(unittest.TestCase): def test_1_security_options(self): o = self.tc.get_security_options() self.assertEqual(type(o), SecurityOptions) - self.assertTrue(('aes256-cbc', 'blowfish-cbc') != o.ciphers) - o.ciphers = ('aes256-cbc', 'blowfish-cbc') - self.assertEqual(('aes256-cbc', 'blowfish-cbc'), o.ciphers) + self.assertTrue(("aes256-cbc", "blowfish-cbc") != o.ciphers) + o.ciphers = ("aes256-cbc", "blowfish-cbc") + self.assertEqual(("aes256-cbc", "blowfish-cbc"), o.ciphers) try: - o.ciphers = ('aes256-cbc', 'made-up-cipher') + o.ciphers = ("aes256-cbc", "made-up-cipher") self.assertTrue(False) except ValueError: pass @@ -188,11 +208,13 @@ class TransportTest(unittest.TestCase): def test_2_compute_key(self): self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 - self.tc.H = b'\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3' + self.tc.H = b"\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3" self.tc.session_id = self.tc.H - key = self.tc._compute_key('C', 32) - self.assertEqual(b'207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995', - hexlify(key).upper()) + key = self.tc._compute_key("C", 32) + self.assertEqual( + b"207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995", + hexlify(key).upper(), + ) def test_3_simple(self): """ @@ -200,7 +222,7 @@ class TransportTest(unittest.TestCase): loopback sockets. this is hardly "simple" but it's simpler than the later tests. :) """ - host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) + host_key = RSAKey.from_private_key_file(_support("test_rsa.key")) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() @@ -211,13 +233,14 @@ class TransportTest(unittest.TestCase): self.assertEqual(False, self.tc.is_authenticated()) self.assertEqual(False, self.ts.is_authenticated()) self.ts.start_server(event, server) - self.tc.connect(hostkey=public_host_key, - username='slowdive', password='pygmalion') + self.tc.connect( + hostkey=public_host_key, username="slowdive", password="pygmalion" + ) event.wait(1.0) self.assertTrue(event.is_set()) self.assertTrue(self.ts.is_active()) - self.assertEqual('slowdive', self.tc.get_username()) - self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual("slowdive", self.tc.get_username()) + self.assertEqual("slowdive", self.ts.get_username()) self.assertEqual(True, self.tc.is_authenticated()) self.assertEqual(True, self.ts.is_authenticated()) @@ -225,7 +248,7 @@ class TransportTest(unittest.TestCase): """ verify that a long banner doesn't mess up the handshake. """ - host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) + host_key = RSAKey.from_private_key_file(_support("test_rsa.key")) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() @@ -233,8 +256,9 @@ class TransportTest(unittest.TestCase): self.assertTrue(not event.is_set()) self.socks.send(LONG_BANNER) self.ts.start_server(event, server) - self.tc.connect(hostkey=public_host_key, - username='slowdive', password='pygmalion') + self.tc.connect( + hostkey=public_host_key, username="slowdive", password="pygmalion" + ) event.wait(1.0) self.assertTrue(event.is_set()) self.assertTrue(self.ts.is_active()) @@ -244,12 +268,14 @@ class TransportTest(unittest.TestCase): verify that the client can demand odd handshake settings, and can renegotiate keys in mid-stream. """ + def force_algorithms(options): - options.ciphers = ('aes256-cbc',) - options.digests = ('hmac-md5-96',) + options.ciphers = ("aes256-cbc",) + options.digests = ("hmac-md5-96",) + self.setup_test_server(client_options=force_algorithms) - self.assertEqual('aes256-cbc', self.tc.local_cipher) - self.assertEqual('aes256-cbc', self.tc.remote_cipher) + self.assertEqual("aes256-cbc", self.tc.local_cipher) + self.assertEqual("aes256-cbc", self.tc.remote_cipher) self.assertEqual(12, self.tc.packetizer.get_mac_size_out()) self.assertEqual(12, self.tc.packetizer.get_mac_size_in()) @@ -263,10 +289,10 @@ class TransportTest(unittest.TestCase): verify that the keepalive will be sent. """ self.setup_test_server() - self.assertEqual(None, getattr(self.server, '_global_request', None)) + self.assertEqual(None, getattr(self.server, "_global_request", None)) self.tc.set_keepalive(1) time.sleep(2) - self.assertEqual('keepalive@lag.net', self.server._global_request) + self.assertEqual("keepalive@lag.net", self.server._global_request) def test_6_exec_command(self): """ @@ -277,39 +303,41 @@ class TransportTest(unittest.TestCase): chan = self.tc.open_session() schan = self.ts.accept(1.0) try: - chan.exec_command(b'command contains \xfc and is not a valid UTF-8 string') + chan.exec_command( + b"command contains \xfc and is not a valid UTF-8 string" + ) self.assertTrue(False) except SSHException: pass chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) - schan.send('Hello there.\n') - schan.send_stderr('This is on stderr.\n') + schan.send("Hello there.\n") + schan.send_stderr("This is on stderr.\n") schan.close() f = chan.makefile() - self.assertEqual('Hello there.\n', f.readline()) - self.assertEqual('', f.readline()) + self.assertEqual("Hello there.\n", f.readline()) + self.assertEqual("", f.readline()) f = chan.makefile_stderr() - self.assertEqual('This is on stderr.\n', f.readline()) - self.assertEqual('', f.readline()) + self.assertEqual("This is on stderr.\n", f.readline()) + self.assertEqual("", f.readline()) # now try it with combined stdout/stderr chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) - schan.send('Hello there.\n') - schan.send_stderr('This is on stderr.\n') + schan.send("Hello there.\n") + schan.send_stderr("This is on stderr.\n") schan.close() chan.set_combine_stderr(True) f = chan.makefile() - self.assertEqual('Hello there.\n', f.readline()) - self.assertEqual('This is on stderr.\n', f.readline()) - self.assertEqual('', f.readline()) - + self.assertEqual("Hello there.\n", f.readline()) + self.assertEqual("This is on stderr.\n", f.readline()) + self.assertEqual("", f.readline()) + def test_6a_channel_can_be_used_as_context_manager(self): """ verify that exec_command() does something reasonable. @@ -318,13 +346,13 @@ class TransportTest(unittest.TestCase): with self.tc.open_session() as chan: with self.ts.accept(1.0) as schan: - chan.exec_command('yes') - schan.send('Hello there.\n') + chan.exec_command("yes") + schan.send("Hello there.\n") schan.close() f = chan.makefile() - self.assertEqual('Hello there.\n', f.readline()) - self.assertEqual('', f.readline()) + self.assertEqual("Hello there.\n", f.readline()) + self.assertEqual("", f.readline()) def test_7_invoke_shell(self): """ @@ -334,11 +362,11 @@ class TransportTest(unittest.TestCase): chan = self.tc.open_session() chan.invoke_shell() schan = self.ts.accept(1.0) - chan.send('communist j. cat\n') + chan.send("communist j. cat\n") f = schan.makefile() - self.assertEqual('communist j. cat\n', f.readline()) + self.assertEqual("communist j. cat\n", f.readline()) chan.close() - self.assertEqual('', f.readline()) + self.assertEqual("", f.readline()) def test_8_channel_exception(self): """ @@ -346,8 +374,8 @@ class TransportTest(unittest.TestCase): """ self.setup_test_server() try: - chan = self.tc.open_channel('bogus') - self.fail('expected exception') + chan = self.tc.open_channel("bogus") + self.fail("expected exception") except ChannelException as e: self.assertTrue(e.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) @@ -359,8 +387,8 @@ class TransportTest(unittest.TestCase): chan = self.tc.open_session() schan = self.ts.accept(1.0) - chan.exec_command('yes') - schan.send('Hello there.\n') + chan.exec_command("yes") + schan.send("Hello there.\n") self.assertTrue(not chan.exit_status_ready()) # trigger an EOF schan.shutdown_read() @@ -369,8 +397,8 @@ class TransportTest(unittest.TestCase): schan.close() f = chan.makefile() - self.assertEqual('Hello there.\n', f.readline()) - self.assertEqual('', f.readline()) + self.assertEqual("Hello there.\n", f.readline()) + self.assertEqual("", f.readline()) count = 0 while not chan.exit_status_ready(): time.sleep(0.1) @@ -395,7 +423,7 @@ class TransportTest(unittest.TestCase): self.assertEqual([], w) self.assertEqual([], e) - schan.send('hello\n') + schan.send("hello\n") # something should be ready now (give it 1 second to appear) for i in range(10): @@ -407,7 +435,7 @@ class TransportTest(unittest.TestCase): self.assertEqual([], w) self.assertEqual([], e) - self.assertEqual(b'hello\n', chan.recv(6)) + self.assertEqual(b"hello\n", chan.recv(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) @@ -442,12 +470,12 @@ class TransportTest(unittest.TestCase): self.setup_test_server() self.tc.packetizer.REKEY_BYTES = 16384 chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) self.assertEqual(self.tc.H, self.tc.session_id) for i in range(20): - chan.send('x' * 1024) + chan.send("x" * 1024) chan.close() # allow a few seconds for the rekeying to complete @@ -463,18 +491,20 @@ class TransportTest(unittest.TestCase): """ verify that zlib compression is basically working. """ + def force_compression(o): - o.compression = ('zlib',) + o.compression = ("zlib",) + self.setup_test_server(force_compression, force_compression) chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) bytes = self.tc.packetizer._Packetizer__sent_bytes - chan.send('x' * 1024) + chan.send("x" * 1024) bytes2 = self.tc.packetizer._Packetizer__sent_bytes - block_size = self.tc._cipher_info[self.tc.local_cipher]['block-size'] - mac_size = self.tc._mac_info[self.tc.local_mac]['size'] + block_size = self.tc._cipher_info[self.tc.local_cipher]["block-size"] + mac_size = self.tc._mac_info[self.tc.local_mac]["size"] # tests show this is actually compressed to *52 bytes*! including packet overhead! nice!! :) self.assertTrue(bytes2 - bytes < 1024) self.assertEqual(16 + block_size + mac_size, bytes2 - bytes) @@ -488,29 +518,32 @@ class TransportTest(unittest.TestCase): """ self.setup_test_server() chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) requested = [] + def handler(c, addr_port): addr, port = addr_port requested.append((addr, port)) self.tc._queue_incoming_channel(c) - self.assertEqual(None, getattr(self.server, '_x11_screen_number', None)) + self.assertEqual( + None, getattr(self.server, "_x11_screen_number", None) + ) cookie = chan.request_x11(0, single_connection=True, handler=handler) self.assertEqual(0, self.server._x11_screen_number) - self.assertEqual('MIT-MAGIC-COOKIE-1', self.server._x11_auth_protocol) + self.assertEqual("MIT-MAGIC-COOKIE-1", self.server._x11_auth_protocol) self.assertEqual(cookie, self.server._x11_auth_cookie) self.assertEqual(True, self.server._x11_single_connection) - x11_server = self.ts.open_x11_channel(('localhost', 6093)) + x11_server = self.ts.open_x11_channel(("localhost", 6093)) x11_client = self.tc.accept() - self.assertEqual('localhost', requested[0][0]) + self.assertEqual("localhost", requested[0][0]) self.assertEqual(6093, requested[0][1]) - x11_server.send('hello') - self.assertEqual(b'hello', x11_client.recv(5)) + x11_server.send("hello") + self.assertEqual(b"hello", x11_client.recv(5)) x11_server.close() x11_client.close() @@ -524,33 +557,36 @@ class TransportTest(unittest.TestCase): """ self.setup_test_server() chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) requested = [] + def handler(c, origin_addr_port, server_addr_port): requested.append(origin_addr_port) requested.append(server_addr_port) self.tc._queue_incoming_channel(c) - port = self.tc.request_port_forward('127.0.0.1', 0, handler) + port = self.tc.request_port_forward("127.0.0.1", 0, handler) self.assertEqual(port, self.server._listen.getsockname()[1]) cs = socket.socket() - cs.connect(('127.0.0.1', port)) + cs.connect(("127.0.0.1", port)) ss, _ = self.server._listen.accept() - sch = self.ts.open_forwarded_tcpip_channel(ss.getsockname(), ss.getpeername()) + sch = self.ts.open_forwarded_tcpip_channel( + ss.getsockname(), ss.getpeername() + ) cch = self.tc.accept() - sch.send('hello') - self.assertEqual(b'hello', cch.recv(5)) + sch.send("hello") + self.assertEqual(b"hello", cch.recv(5)) sch.close() cch.close() ss.close() cs.close() # now cancel it. - self.tc.cancel_port_forward('127.0.0.1', port) + self.tc.cancel_port_forward("127.0.0.1", port) self.assertTrue(self.server._listen is None) def test_F_port_forwarding(self): @@ -560,27 +596,29 @@ class TransportTest(unittest.TestCase): """ self.setup_test_server() chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) # open a port on the "server" that the client will ask to forward to. greeting_server = socket.socket() - greeting_server.bind(('127.0.0.1', 0)) + greeting_server.bind(("127.0.0.1", 0)) greeting_server.listen(1) greeting_port = greeting_server.getsockname()[1] - cs = self.tc.open_channel('direct-tcpip', ('127.0.0.1', greeting_port), ('', 9000)) + cs = self.tc.open_channel( + "direct-tcpip", ("127.0.0.1", greeting_port), ("", 9000) + ) sch = self.ts.accept(1.0) cch = socket.socket() cch.connect(self.server._tcpip_dest) ss, _ = greeting_server.accept() - ss.send(b'Hello!\n') + ss.send(b"Hello!\n") ss.close() sch.send(cch.recv(8192)) sch.close() - self.assertEqual(b'Hello!\n', cs.recv(7)) + self.assertEqual(b"Hello!\n", cs.recv(7)) cs.close() def test_G_stderr_select(self): @@ -599,7 +637,7 @@ class TransportTest(unittest.TestCase): self.assertEqual([], w) self.assertEqual([], e) - schan.send_stderr('hello\n') + schan.send_stderr("hello\n") # something should be ready now (give it 1 second to appear) for i in range(10): @@ -611,7 +649,7 @@ class TransportTest(unittest.TestCase): self.assertEqual([], w) self.assertEqual([], e) - self.assertEqual(b'hello\n', chan.recv_stderr(6)) + self.assertEqual(b"hello\n", chan.recv_stderr(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) @@ -633,8 +671,8 @@ class TransportTest(unittest.TestCase): self.assertEqual(chan.send_ready(), True) total = 0 - K = '*' * 1024 - limit = 1+(64 * 2 ** 15) + K = "*" * 1024 + limit = 1 + (64 * 2 ** 15) while total < limit: chan.send(K) total += len(K) @@ -696,8 +734,11 @@ class TransportTest(unittest.TestCase): # expires, a deadlock is assumed. class SendThread(threading.Thread): + def __init__(self, chan, iterations, done_event): - threading.Thread.__init__(self, None, None, self.__class__.__name__) + threading.Thread.__init__( + self, None, None, self.__class__.__name__ + ) self.setDaemon(True) self.chan = chan self.iterations = iterations @@ -707,19 +748,22 @@ class TransportTest(unittest.TestCase): def run(self): try: - for i in range(1, 1+self.iterations): + for i in range(1, 1 + self.iterations): if self.done_event.is_set(): break self.watchdog_event.set() - #print i, "SEND" + # print i, "SEND" self.chan.send("x" * 2048) finally: self.done_event.set() self.watchdog_event.set() class ReceiveThread(threading.Thread): + def __init__(self, chan, done_event): - threading.Thread.__init__(self, None, None, self.__class__.__name__) + threading.Thread.__init__( + self, None, None, self.__class__.__name__ + ) self.setDaemon(True) self.chan = chan self.done_event = done_event @@ -742,7 +786,7 @@ class TransportTest(unittest.TestCase): self.ts.packetizer.REKEY_BYTES = 2048 chan = self.tc.open_session() - chan.exec_command('yes') + chan.exec_command("yes") schan = self.ts.accept(1.0) # Monkey patch the client's Transport._handler_table so that the client @@ -751,21 +795,23 @@ class TransportTest(unittest.TestCase): # on a real MSG_CHANNEL_WINDOW_ADJUST message. self.tc._handler_table = self.tc._handler_table.copy() # copy per-class dictionary _negotiate_keys = self.tc._handler_table[MSG_KEXINIT] + def _negotiate_keys_wrapper(self, m): - if self.local_kex_init is None: # Remote side sent KEXINIT + if self.local_kex_init is None: # Remote side sent KEXINIT # Simulate in-transit MSG_CHANNEL_WINDOW_ADJUST by sending it # before responding to the incoming MSG_KEXINIT. m2 = Message() m2.add_byte(cMSG_CHANNEL_WINDOW_ADJUST) m2.add_int(chan.remote_chanid) - m2.add_int(1) # bytes to add + m2.add_int(1) # bytes to add self._send_message(m2) return _negotiate_keys(self, m) + self.tc._handler_table[MSG_KEXINIT] = _negotiate_keys_wrapper # Parameters for the test - iterations = 500 # The deadlock does not happen every time, but it - # should after many iterations. + iterations = 500 # The deadlock does not happen every time, but it + # should after many iterations. timeout = 5 # This event is set when the test is completed @@ -807,18 +853,22 @@ class TransportTest(unittest.TestCase): """ verify that we conform to the rfc of packet and window sizes. """ - for val, correct in [(4095, MIN_PACKET_SIZE), - (None, DEFAULT_MAX_PACKET_SIZE), - (2**32, MAX_WINDOW_SIZE)]: + for val, correct in [ + (4095, MIN_PACKET_SIZE), + (None, DEFAULT_MAX_PACKET_SIZE), + (2 ** 32, MAX_WINDOW_SIZE), + ]: self.assertEqual(self.tc._sanitize_packet_size(val), correct) def test_K_sanitze_window_size(self): """ verify that we conform to the rfc of packet and window sizes. """ - for val, correct in [(32767, MIN_WINDOW_SIZE), - (None, DEFAULT_WINDOW_SIZE), - (2**32, MAX_WINDOW_SIZE)]: + for val, correct in [ + (32767, MIN_WINDOW_SIZE), + (None, DEFAULT_WINDOW_SIZE), + (2 ** 32, MAX_WINDOW_SIZE), + ]: self.assertEqual(self.tc._sanitize_window_size(val), correct) @slow @@ -834,15 +884,17 @@ class TransportTest(unittest.TestCase): # (Doing this on the server's transport *sounds* more 'correct' but # actually doesn't work nearly as well for whatever reason.) class SlowPacketizer(Packetizer): + def read_message(self): time.sleep(1) return super(SlowPacketizer, self).read_message() + # NOTE: prettttty sure since the replaced .packetizer Packetizer is now # no longer doing anything with its copy of the socket...everything'll # be fine. Even tho it's a bit squicky. self.tc.packetizer = SlowPacketizer(self.tc.sock) # Continue with regular test red tape. - host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) + host_key = RSAKey.from_private_key_file(_support("test_rsa.key")) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() @@ -850,10 +902,13 @@ class TransportTest(unittest.TestCase): self.assertTrue(not event.is_set()) self.tc.handshake_timeout = 0.000000000001 self.ts.start_server(event, server) - self.assertRaises(EOFError, self.tc.connect, - hostkey=public_host_key, - username='slowdive', - password='pygmalion') + self.assertRaises( + EOFError, + self.tc.connect, + hostkey=public_host_key, + username="slowdive", + password="pygmalion", + ) def test_M_select_after_close(self): """ @@ -894,13 +949,13 @@ class TransportTest(unittest.TestCase): expected = text.encode("utf-8") self.assertEqual(sfile.read(len(expected)), expected) - @needs_builtin('buffer') + @needs_builtin("buffer") def test_channel_send_buffer(self): """ verify sending buffer instances to a channel """ self.setup_test_server() - data = 3 * b'some test data\n whole' + data = 3 * b"some test data\n whole" with self.tc.open_session() as chan: schan = self.ts.accept(1.0) if schan is None: @@ -917,13 +972,13 @@ class TransportTest(unittest.TestCase): chan.sendall(buffer(data)) self.assertEqual(sfile.read(len(data)), data) - @needs_builtin('memoryview') + @needs_builtin("memoryview") def test_channel_send_memoryview(self): """ verify sending memoryview instances to a channel """ self.setup_test_server() - data = 3 * b'some test data\n whole' + data = 3 * b"some test data\n whole" with self.tc.open_session() as chan: schan = self.ts.accept(1.0) if schan is None: @@ -934,7 +989,7 @@ class TransportTest(unittest.TestCase): sent = 0 view = memoryview(data) while sent < len(view): - sent += chan.send(view[sent:sent+8]) + sent += chan.send(view[sent:sent + 8]) self.assertEqual(sfile.read(len(data)), data) # sendall() accepts a memoryview instance @@ -954,7 +1009,7 @@ class TransportTest(unittest.TestCase): self.setup_test_server(connect_kwargs={}) # NOTE: this dummy global request kind would normally pass muster # from the test server. - self.tc.global_request('acceptable') + self.tc.global_request("acceptable") # Global requests never raise exceptions, even on failure (not sure why # this was the original design...ugh.) Best we can do to tell failure # happened is that the client transport's global_response was set back @@ -969,7 +1024,7 @@ class TransportTest(unittest.TestCase): # an exception on the client side, unlike the general case...) self.setup_test_server(connect_kwargs={}) try: - self.tc.request_port_forward('localhost', 1234) + self.tc.request_port_forward("localhost", 1234) except SSHException as e: assert "forwarding request denied" in str(e) else: -- cgit v1.2.3 From c091e756084ce017d8d872ffeaf95422f79140f1 Mon Sep 17 00:00:00 2001 From: Jeff Forcier Date: Tue, 29 May 2018 15:18:24 -0700 Subject: Blacken under black 18.5b0 --- demos/demo.py | 85 +++++++++++----------- demos/demo_keygen.py | 130 +++++++++++++++++++++++----------- demos/demo_server.py | 88 ++++++++++++----------- demos/demo_sftp.py | 76 +++++++++++--------- demos/demo_simple.py | 50 ++++++++----- demos/forward.py | 176 ++++++++++++++++++++++++++++++++-------------- demos/interactive.py | 19 ++--- demos/rforward.py | 147 +++++++++++++++++++++++++++----------- paramiko/_winapi.py | 17 +++-- paramiko/agent.py | 9 +-- paramiko/auth_handler.py | 9 +-- paramiko/ber.py | 6 +- paramiko/client.py | 10 +-- paramiko/common.py | 22 ++---- paramiko/dsskey.py | 16 ++--- paramiko/ecdsakey.py | 2 +- paramiko/ed25519key.py | 4 +- paramiko/file.py | 18 ++--- paramiko/kex_ecdh_nist.py | 2 +- paramiko/kex_gex.py | 8 +-- paramiko/kex_group1.py | 4 +- paramiko/kex_group14.py | 4 +- paramiko/kex_gss.py | 16 ++--- paramiko/packet.py | 45 +++++------- paramiko/pkey.py | 6 +- paramiko/primes.py | 8 ++- paramiko/proxy.py | 2 +- paramiko/rsakey.py | 4 +- paramiko/sftp.py | 8 +-- paramiko/sftp_attr.py | 7 +- paramiko/sftp_file.py | 12 ++-- paramiko/ssh_exception.py | 4 +- paramiko/ssh_gss.py | 5 +- paramiko/transport.py | 24 +++---- paramiko/util.py | 11 +-- setup.cfg | 4 +- setup.py | 52 +++++++------- setup_helper.py | 48 ++++++++----- sites/docs/conf.py | 13 ++-- sites/shared_conf.py | 39 +++++----- sites/www/conf.py | 16 ++--- tasks.py | 2 +- tests/stub_sftp.py | 6 +- tests/test_client.py | 4 +- tests/test_file.py | 4 +- tests/test_kex.py | 108 +++++++++++++++++++--------- tests/test_message.py | 17 +++-- tests/test_pkey.py | 36 +++++++--- tests/test_sftp.py | 6 +- tests/test_sftp_big.py | 16 ++--- tests/test_ssh_gss.py | 4 +- tests/test_transport.py | 14 ++-- tests/test_util.py | 3 +- 53 files changed, 861 insertions(+), 585 deletions(-) (limited to 'tests/test_transport.py') diff --git a/demos/demo.py b/demos/demo.py index fff61784..c9b0a5f5 100755 --- a/demos/demo.py +++ b/demos/demo.py @@ -31,6 +31,7 @@ import traceback from paramiko.py3compat import input import paramiko + try: import interactive except ImportError: @@ -42,71 +43,73 @@ 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())) + print("Trying ssh-agent key %s" % hexlify(key.get_fingerprint())) try: transport.auth_publickey(username, key) - print('... success!') + print("... success!") return except paramiko.SSHException: - print('... nope.') + print("... nope.") def manual_auth(username, hostname): - default_auth = 'p' - auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth) + 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 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: ') + 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) + 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: ') + 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)) + pw = getpass.getpass("Password for %s@%s: " % (username, hostname)) t.auth_password(username, pw) # setup logging -paramiko.util.log_to_file('demo.log') +paramiko.util.log_to_file("demo.log") -username = '' +username = "" if len(sys.argv) > 1: hostname = sys.argv[1] - if hostname.find('@') >= 0: - username, hostname = hostname.split('@') + if hostname.find("@") >= 0: + username, hostname = hostname.split("@") else: - hostname = input('Hostname: ') + hostname = input("Hostname: ") if len(hostname) == 0: - print('*** Hostname required.') + print("*** Hostname required.") sys.exit(1) port = 22 -if hostname.find(':') >= 0: - hostname, portstr = hostname.split(':') +if hostname.find(":") >= 0: + hostname, portstr = hostname.split(":") port = int(portstr) # now connect @@ -114,7 +117,7 @@ try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception as e: - print('*** Connect failed: ' + str(e)) + print("*** Connect failed: " + str(e)) traceback.print_exc() sys.exit(1) @@ -123,34 +126,38 @@ try: try: t.start_client() except paramiko.SSHException: - print('*** SSH negotiation failed.') + print("*** SSH negotiation failed.") sys.exit(1) try: - keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) + keys = paramiko.util.load_host_keys( + os.path.expanduser("~/.ssh/known_hosts") + ) except IOError: try: - keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) + keys = paramiko.util.load_host_keys( + os.path.expanduser("~/ssh/known_hosts") + ) except IOError: - print('*** Unable to open host keys file') + print("*** Unable to open host keys file") keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: - print('*** WARNING: Unknown host key!') + print("*** WARNING: Unknown host key!") elif key.get_name() not in keys[hostname]: - print('*** WARNING: Unknown host key!') + print("*** WARNING: Unknown host key!") elif keys[hostname][key.get_name()] != key: - print('*** WARNING: Host key has changed!!!') + print("*** WARNING: Host key has changed!!!") sys.exit(1) else: - print('*** Host key OK.') + print("*** Host key OK.") # get username - if username == '': + if username == "": default_username = getpass.getuser() - username = input('Username [%s]: ' % default_username) + username = input("Username [%s]: " % default_username) if len(username) == 0: username = default_username @@ -158,25 +165,23 @@ try: if not t.is_authenticated(): manual_auth(username, hostname) if not t.is_authenticated(): - print('*** Authentication failed. :(') + print("*** Authentication failed. :(") t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() - print('*** Here we go!\n') + print("*** Here we go!\n") interactive.interactive_shell(chan) chan.close() t.close() except Exception as e: - print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) + print("*** Caught exception: " + str(e.__class__) + ": " + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1) - - diff --git a/demos/demo_keygen.py b/demos/demo_keygen.py index 860ee4e9..6a80272d 100755 --- a/demos/demo_keygen.py +++ b/demos/demo_keygen.py @@ -28,62 +28,97 @@ from paramiko import RSAKey from paramiko.ssh_exception import SSHException from paramiko.py3compat import u -usage=""" +usage = """ %prog [-v] [-b bits] -t type [-N new_passphrase] [-f output_keyfile]""" default_values = { "ktype": "dsa", "bits": 1024, "filename": "output", - "comment": "" + "comment": "", } -key_dispatch_table = { - 'dsa': DSSKey, - 'rsa': RSAKey, -} +key_dispatch_table = {"dsa": DSSKey, "rsa": RSAKey} + def progress(arg=None): if not arg: - sys.stdout.write('0%\x08\x08\x08 ') + sys.stdout.write("0%\x08\x08\x08 ") sys.stdout.flush() - elif arg[0] == 'p': - sys.stdout.write('25%\x08\x08\x08\x08 ') + elif arg[0] == "p": + sys.stdout.write("25%\x08\x08\x08\x08 ") sys.stdout.flush() - elif arg[0] == 'h': - sys.stdout.write('50%\x08\x08\x08\x08 ') + elif arg[0] == "h": + sys.stdout.write("50%\x08\x08\x08\x08 ") sys.stdout.flush() - elif arg[0] == 'x': - sys.stdout.write('75%\x08\x08\x08\x08 ') + elif arg[0] == "x": + sys.stdout.write("75%\x08\x08\x08\x08 ") sys.stdout.flush() -if __name__ == '__main__': - phrase=None - pfunc=None +if __name__ == "__main__": + + phrase = None + pfunc = None parser = OptionParser(usage=usage) - parser.add_option("-t", "--type", type="string", dest="ktype", + parser.add_option( + "-t", + "--type", + type="string", + dest="ktype", help="Specify type of key to create (dsa or rsa)", - metavar="ktype", default=default_values["ktype"]) - parser.add_option("-b", "--bits", type="int", dest="bits", - help="Number of bits in the key to create", metavar="bits", - default=default_values["bits"]) - parser.add_option("-N", "--new-passphrase", dest="newphrase", - help="Provide new passphrase", metavar="phrase") - parser.add_option("-P", "--old-passphrase", dest="oldphrase", - help="Provide old passphrase", metavar="phrase") - parser.add_option("-f", "--filename", type="string", dest="filename", - help="Filename of the key file", metavar="filename", - default=default_values["filename"]) - parser.add_option("-q", "--quiet", default=False, action="store_false", - help="Quiet") - parser.add_option("-v", "--verbose", default=False, action="store_true", - help="Verbose") - parser.add_option("-C", "--comment", type="string", dest="comment", - help="Provide a new comment", metavar="comment", - default=default_values["comment"]) + metavar="ktype", + default=default_values["ktype"], + ) + parser.add_option( + "-b", + "--bits", + type="int", + dest="bits", + help="Number of bits in the key to create", + metavar="bits", + default=default_values["bits"], + ) + parser.add_option( + "-N", + "--new-passphrase", + dest="newphrase", + help="Provide new passphrase", + metavar="phrase", + ) + parser.add_option( + "-P", + "--old-passphrase", + dest="oldphrase", + help="Provide old passphrase", + metavar="phrase", + ) + parser.add_option( + "-f", + "--filename", + type="string", + dest="filename", + help="Filename of the key file", + metavar="filename", + default=default_values["filename"], + ) + parser.add_option( + "-q", "--quiet", default=False, action="store_false", help="Quiet" + ) + parser.add_option( + "-v", "--verbose", default=False, action="store_true", help="Verbose" + ) + parser.add_option( + "-C", + "--comment", + type="string", + dest="comment", + help="Provide a new comment", + metavar="comment", + default=default_values["comment"], + ) (options, args) = parser.parse_args() @@ -95,18 +130,23 @@ if __name__ == '__main__': globals()[o] = getattr(options, o, default_values[o.lower()]) if options.newphrase: - phrase = getattr(options, 'newphrase') + phrase = getattr(options, "newphrase") if options.verbose: pfunc = progress - sys.stdout.write("Generating priv/pub %s %d bits key pair (%s/%s.pub)..." % (ktype, bits, filename, filename)) + sys.stdout.write( + "Generating priv/pub %s %d bits key pair (%s/%s.pub)..." + % (ktype, bits, filename, filename) + ) sys.stdout.flush() - if ktype == 'dsa' and bits > 1024: + if ktype == "dsa" and bits > 1024: raise SSHException("DSA Keys must be 1024 bits") if ktype not in key_dispatch_table: - raise SSHException("Unknown %s algorithm to generate keys pair" % ktype) + raise SSHException( + "Unknown %s algorithm to generate keys pair" % ktype + ) # generating private key prv = key_dispatch_table[ktype].generate(bits=bits, progress_func=pfunc) @@ -114,7 +154,7 @@ if __name__ == '__main__': # generating public key pub = key_dispatch_table[ktype](filename=filename, password=phrase) - with open("%s.pub" % filename, 'w') as f: + with open("%s.pub" % filename, "w") as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) if options.comment: f.write(" %s" % comment) @@ -123,4 +163,12 @@ if __name__ == '__main__': print("done.") hash = u(hexlify(pub.get_fingerprint())) - print("Fingerprint: %d %s %s.pub (%s)" % (bits, ":".join([ hash[i:2+i] for i in range(0, len(hash), 2)]), filename, ktype.upper())) + print( + "Fingerprint: %d %s %s.pub (%s)" + % ( + bits, + ":".join([hash[i : 2 + i] for i in range(0, len(hash), 2)]), + filename, + ktype.upper(), + ) + ) diff --git a/demos/demo_server.py b/demos/demo_server.py index 3a7ec854..313e5fb2 100644 --- a/demos/demo_server.py +++ b/demos/demo_server.py @@ -31,45 +31,47 @@ from paramiko.py3compat import b, u, decodebytes # setup logging -paramiko.util.log_to_file('demo_server.log') +paramiko.util.log_to_file("demo_server.log") -host_key = paramiko.RSAKey(filename='test_rsa.key') -#host_key = paramiko.DSSKey(filename='test_dss.key') +host_key = paramiko.RSAKey(filename="test_rsa.key") +# host_key = paramiko.DSSKey(filename='test_dss.key') -print('Read key: ' + u(hexlify(host_key.get_fingerprint()))) +print("Read key: " + u(hexlify(host_key.get_fingerprint()))) -class Server (paramiko.ServerInterface): +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=') + 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() def check_channel_request(self, kind, chanid): - if kind == 'session': + if kind == "session": return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def check_auth_password(self, username, password): - if (username == 'robey') and (password == 'foo'): + if (username == "robey") and (password == "foo"): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED def check_auth_publickey(self, username, key): - print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint()))) - if (username == 'robey') and (key == self.good_pub_key): + print("Auth attempt with key: " + u(hexlify(key.get_fingerprint()))) + if (username == "robey") and (key == self.good_pub_key): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED - - def check_auth_gssapi_with_mic(self, username, - gss_authenticated=paramiko.AUTH_FAILED, - cc_file=None): + + def check_auth_gssapi_with_mic( + self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None + ): """ .. note:: We are just checking in `AuthHandler` that the given user is a @@ -88,9 +90,9 @@ class Server (paramiko.ServerInterface): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED - def check_auth_gssapi_keyex(self, username, - gss_authenticated=paramiko.AUTH_FAILED, - cc_file=None): + def check_auth_gssapi_keyex( + self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None + ): if gss_authenticated == paramiko.AUTH_SUCCESSFUL: return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED @@ -99,14 +101,15 @@ class Server (paramiko.ServerInterface): return True def get_allowed_auths(self, username): - return 'gssapi-keyex,gssapi-with-mic,password,publickey' + return "gssapi-keyex,gssapi-with-mic,password,publickey" def check_channel_shell_request(self, channel): self.event.set() return True - def check_channel_pty_request(self, channel, term, width, height, pixelwidth, - pixelheight, modes): + def check_channel_pty_request( + self, channel, term, width, height, pixelwidth, pixelheight, modes + ): return True @@ -116,22 +119,22 @@ DoGSSAPIKeyExchange = True try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - sock.bind(('', 2200)) + sock.bind(("", 2200)) except Exception as e: - print('*** Bind failed: ' + str(e)) + print("*** Bind failed: " + str(e)) traceback.print_exc() sys.exit(1) try: sock.listen(100) - print('Listening for connection ...') + print("Listening for connection ...") client, addr = sock.accept() except Exception as e: - print('*** Listen/accept failed: ' + str(e)) + print("*** Listen/accept failed: " + str(e)) traceback.print_exc() sys.exit(1) -print('Got a connection!') +print("Got a connection!") try: t = paramiko.Transport(client, gss_kex=DoGSSAPIKeyExchange) @@ -139,43 +142,44 @@ try: try: t.load_server_moduli() except: - print('(Failed to load moduli -- gex will be unsupported.)') + print("(Failed to load moduli -- gex will be unsupported.)") raise t.add_server_key(host_key) server = Server() try: t.start_server(server=server) except paramiko.SSHException: - print('*** SSH negotiation failed.') + print("*** SSH negotiation failed.") sys.exit(1) # wait for auth chan = t.accept(20) if chan is None: - print('*** No channel.') + print("*** No channel.") sys.exit(1) - print('Authenticated!') + print("Authenticated!") server.event.wait(10) if not server.event.is_set(): - print('*** Client never asked for a shell.') + print("*** Client never asked for a shell.") sys.exit(1) - chan.send('\r\n\r\nWelcome to my dorky little BBS!\r\n\r\n') - chan.send('We are on fire all the time! Hooray! Candy corn for everyone!\r\n') - chan.send('Happy birthday to Robot Dave!\r\n\r\n') - chan.send('Username: ') - f = chan.makefile('rU') - username = f.readline().strip('\r\n') - chan.send('\r\nI don\'t like you, ' + username + '.\r\n') + chan.send("\r\n\r\nWelcome to my dorky little BBS!\r\n\r\n") + chan.send( + "We are on fire all the time! Hooray! Candy corn for everyone!\r\n" + ) + chan.send("Happy birthday to Robot Dave!\r\n\r\n") + chan.send("Username: ") + f = chan.makefile("rU") + username = f.readline().strip("\r\n") + chan.send("\r\nI don't like you, " + username + ".\r\n") chan.close() except Exception as e: - print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) + print("*** Caught exception: " + str(e.__class__) + ": " + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1) - diff --git a/demos/demo_sftp.py b/demos/demo_sftp.py index 2cb44701..7f6a002e 100644 --- a/demos/demo_sftp.py +++ b/demos/demo_sftp.py @@ -32,38 +32,38 @@ from paramiko.py3compat import input # setup logging -paramiko.util.log_to_file('demo_sftp.log') +paramiko.util.log_to_file("demo_sftp.log") # Paramiko client configuration -UseGSSAPI = True # enable GSS-API / SSPI authentication +UseGSSAPI = True # enable GSS-API / SSPI authentication DoGSSAPIKeyExchange = True Port = 22 # get hostname -username = '' +username = "" if len(sys.argv) > 1: hostname = sys.argv[1] - if hostname.find('@') >= 0: - username, hostname = hostname.split('@') + if hostname.find("@") >= 0: + username, hostname = hostname.split("@") else: - hostname = input('Hostname: ') + hostname = input("Hostname: ") if len(hostname) == 0: - print('*** Hostname required.') + print("*** Hostname required.") sys.exit(1) -if hostname.find(':') >= 0: - hostname, portstr = hostname.split(':') +if hostname.find(":") >= 0: + hostname, portstr = hostname.split(":") Port = int(portstr) # get username -if username == '': +if username == "": default_username = getpass.getuser() - username = input('Username [%s]: ' % default_username) + username = input("Username [%s]: " % default_username) if len(username) == 0: username = default_username if not UseGSSAPI: - password = getpass.getpass('Password for %s@%s: ' % (username, hostname)) + password = getpass.getpass("Password for %s@%s: " % (username, hostname)) else: password = None @@ -72,59 +72,69 @@ else: hostkeytype = None hostkey = None try: - host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) + host_keys = paramiko.util.load_host_keys( + os.path.expanduser("~/.ssh/known_hosts") + ) except IOError: try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ - host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) + host_keys = paramiko.util.load_host_keys( + os.path.expanduser("~/ssh/known_hosts") + ) except IOError: - print('*** Unable to open host keys file') + print("*** Unable to open host keys file") host_keys = {} if hostname in host_keys: hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] - print('Using host key of type %s' % hostkeytype) + print("Using host key of type %s" % hostkeytype) # now, connect and use paramiko Transport to negotiate SSH2 across the connection try: t = paramiko.Transport((hostname, Port)) - t.connect(hostkey, username, password, gss_host=socket.getfqdn(hostname), - gss_auth=UseGSSAPI, gss_kex=DoGSSAPIKeyExchange) + t.connect( + hostkey, + username, + password, + gss_host=socket.getfqdn(hostname), + gss_auth=UseGSSAPI, + gss_kex=DoGSSAPIKeyExchange, + ) sftp = paramiko.SFTPClient.from_transport(t) # dirlist on remote host - dirlist = sftp.listdir('.') + dirlist = sftp.listdir(".") print("Dirlist: %s" % dirlist) # copy this demo onto the server try: sftp.mkdir("demo_sftp_folder") except IOError: - print('(assuming demo_sftp_folder/ already exists)') - with sftp.open('demo_sftp_folder/README', 'w') as f: - f.write('This was created by demo_sftp.py.\n') - with open('demo_sftp.py', 'r') as f: + print("(assuming demo_sftp_folder/ already exists)") + with sftp.open("demo_sftp_folder/README", "w") as f: + f.write("This was created by demo_sftp.py.\n") + with open("demo_sftp.py", "r") as f: data = f.read() - sftp.open('demo_sftp_folder/demo_sftp.py', 'w').write(data) - print('created demo_sftp_folder/ on the server') - + sftp.open("demo_sftp_folder/demo_sftp.py", "w").write(data) + print("created demo_sftp_folder/ on the server") + # copy the README back here - with sftp.open('demo_sftp_folder/README', 'r') as f: + with sftp.open("demo_sftp_folder/README", "r") as f: data = f.read() - with open('README_demo_sftp', 'w') as f: + with open("README_demo_sftp", "w") as f: f.write(data) - print('copied README back here') - + print("copied README back here") + # BETTER: use the get() and put() methods - sftp.put('demo_sftp.py', 'demo_sftp_folder/demo_sftp.py') - sftp.get('demo_sftp_folder/README', 'README_demo_sftp') + sftp.put("demo_sftp.py", "demo_sftp_folder/demo_sftp.py") + sftp.get("demo_sftp_folder/README", "README_demo_sftp") t.close() except Exception as e: - print('*** Caught exception: %s: %s' % (e.__class__, e)) + print("*** Caught exception: %s: %s" % (e.__class__, e)) traceback.print_exc() try: t.close() diff --git a/demos/demo_simple.py b/demos/demo_simple.py index 9def57f8..5dd4f6c1 100644 --- a/demos/demo_simple.py +++ b/demos/demo_simple.py @@ -28,6 +28,7 @@ import traceback from paramiko.py3compat import input import paramiko + try: import interactive except ImportError: @@ -35,39 +36,43 @@ except ImportError: # setup logging -paramiko.util.log_to_file('demo_simple.log') +paramiko.util.log_to_file("demo_simple.log") # Paramiko client configuration -UseGSSAPI = paramiko.GSS_AUTH_AVAILABLE # enable "gssapi-with-mic" authentication, if supported by your python installation -DoGSSAPIKeyExchange = paramiko.GSS_AUTH_AVAILABLE # enable "gssapi-kex" key exchange, if supported by your python installation +UseGSSAPI = ( + paramiko.GSS_AUTH_AVAILABLE +) # enable "gssapi-with-mic" authentication, if supported by your python installation +DoGSSAPIKeyExchange = ( + paramiko.GSS_AUTH_AVAILABLE +) # enable "gssapi-kex" key exchange, if supported by your python installation # UseGSSAPI = False # DoGSSAPIKeyExchange = False port = 22 # get hostname -username = '' +username = "" if len(sys.argv) > 1: hostname = sys.argv[1] - if hostname.find('@') >= 0: - username, hostname = hostname.split('@') + if hostname.find("@") >= 0: + username, hostname = hostname.split("@") else: - hostname = input('Hostname: ') + hostname = input("Hostname: ") if len(hostname) == 0: - print('*** Hostname required.') + print("*** Hostname required.") sys.exit(1) -if hostname.find(':') >= 0: - hostname, portstr = hostname.split(':') +if hostname.find(":") >= 0: + hostname, portstr = hostname.split(":") port = int(portstr) # get username -if username == '': +if username == "": default_username = getpass.getuser() - username = input('Username [%s]: ' % default_username) + username = input("Username [%s]: " % default_username) if len(username) == 0: username = default_username if not UseGSSAPI and not DoGSSAPIKeyExchange: - password = getpass.getpass('Password for %s@%s: ' % (username, hostname)) + password = getpass.getpass("Password for %s@%s: " % (username, hostname)) # now, connect and use paramiko Client to negotiate SSH2 across the connection @@ -75,27 +80,34 @@ try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) - print('*** Connecting...') + print("*** Connecting...") if not UseGSSAPI and not DoGSSAPIKeyExchange: client.connect(hostname, port, username, password) else: try: - client.connect(hostname, port, username, gss_auth=UseGSSAPI, - gss_kex=DoGSSAPIKeyExchange) + client.connect( + hostname, + port, + username, + gss_auth=UseGSSAPI, + gss_kex=DoGSSAPIKeyExchange, + ) except Exception: # traceback.print_exc() - password = getpass.getpass('Password for %s@%s: ' % (username, hostname)) + password = getpass.getpass( + "Password for %s@%s: " % (username, hostname) + ) client.connect(hostname, port, username, password) chan = client.invoke_shell() print(repr(client.get_transport())) - print('*** Here we go!\n') + print("*** Here we go!\n") interactive.interactive_shell(chan) chan.close() client.close() except Exception as e: - print('*** Caught exception: %s: %s' % (e.__class__, e)) + print("*** Caught exception: %s: %s" % (e.__class__, e)) traceback.print_exc() try: client.close() diff --git a/demos/forward.py b/demos/forward.py index 96e1700d..98757911 100644 --- a/demos/forward.py +++ b/demos/forward.py @@ -30,6 +30,7 @@ import getpass import os import socket import select + try: import SocketServer except ImportError: @@ -46,30 +47,41 @@ DEFAULT_PORT = 4000 g_verbose = True -class ForwardServer (SocketServer.ThreadingTCPServer): +class ForwardServer(SocketServer.ThreadingTCPServer): daemon_threads = True allow_reuse_address = True - -class Handler (SocketServer.BaseRequestHandler): + +class Handler(SocketServer.BaseRequestHandler): def handle(self): try: - chan = self.ssh_transport.open_channel('direct-tcpip', - (self.chain_host, self.chain_port), - self.request.getpeername()) + chan = self.ssh_transport.open_channel( + "direct-tcpip", + (self.chain_host, self.chain_port), + self.request.getpeername(), + ) except Exception as e: - verbose('Incoming request to %s:%d failed: %s' % (self.chain_host, - self.chain_port, - repr(e))) + verbose( + "Incoming request to %s:%d failed: %s" + % (self.chain_host, self.chain_port, repr(e)) + ) return if chan is None: - verbose('Incoming request to %s:%d was rejected by the SSH server.' % - (self.chain_host, self.chain_port)) + verbose( + "Incoming request to %s:%d was rejected by the SSH server." + % (self.chain_host, self.chain_port) + ) return - verbose('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(), - chan.getpeername(), (self.chain_host, self.chain_port))) + verbose( + "Connected! Tunnel open %r -> %r -> %r" + % ( + self.request.getpeername(), + chan.getpeername(), + (self.chain_host, self.chain_port), + ) + ) while True: r, w, x = select.select([self.request, chan], [], []) if self.request in r: @@ -82,22 +94,23 @@ class Handler (SocketServer.BaseRequestHandler): if len(data) == 0: break self.request.send(data) - + peername = self.request.getpeername() chan.close() self.request.close() - verbose('Tunnel closed from %r' % (peername,)) + verbose("Tunnel closed from %r" % (peername,)) def forward_tunnel(local_port, remote_host, remote_port, transport): # this is a little convoluted, but lets me configure things for the Handler # object. (SocketServer doesn't give Handlers any way to access the outer # server normally.) - class SubHander (Handler): + class SubHander(Handler): chain_host = remote_host chain_port = remote_port ssh_transport = transport - ForwardServer(('', local_port), SubHander).serve_forever() + + ForwardServer(("", local_port), SubHander).serve_forever() def verbose(s): @@ -114,40 +127,88 @@ the SSH server. This is similar to the openssh -L option. def get_host_port(spec, default_port): "parse 'hostname:22' into a host and port, with the port optional" - args = (spec.split(':', 1) + [default_port])[:2] + args = (spec.split(":", 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1] def parse_options(): global g_verbose - - parser = OptionParser(usage='usage: %prog [options] [:]', - version='%prog 1.0', description=HELP) - parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True, - help='squelch all informational output') - parser.add_option('-p', '--local-port', action='store', type='int', dest='port', - default=DEFAULT_PORT, - help='local port to forward (default: %d)' % DEFAULT_PORT) - parser.add_option('-u', '--user', action='store', type='string', dest='user', - default=getpass.getuser(), - help='username for SSH authentication (default: %s)' % getpass.getuser()) - parser.add_option('-K', '--key', action='store', type='string', dest='keyfile', - default=None, - help='private key file to use for SSH authentication') - parser.add_option('', '--no-key', action='store_false', dest='look_for_keys', default=True, - help='don\'t look for or use a private key file') - parser.add_option('-P', '--password', action='store_true', dest='readpass', default=False, - help='read password (for key or password auth) from stdin') - parser.add_option('-r', '--remote', action='store', type='string', dest='remote', default=None, metavar='host:port', - help='remote host and port to forward to') + + parser = OptionParser( + usage="usage: %prog [options] [:]", + version="%prog 1.0", + description=HELP, + ) + parser.add_option( + "-q", + "--quiet", + action="store_false", + dest="verbose", + default=True, + help="squelch all informational output", + ) + parser.add_option( + "-p", + "--local-port", + action="store", + type="int", + dest="port", + default=DEFAULT_PORT, + help="local port to forward (default: %d)" % DEFAULT_PORT, + ) + parser.add_option( + "-u", + "--user", + action="store", + type="string", + dest="user", + default=getpass.getuser(), + help="username for SSH authentication (default: %s)" + % getpass.getuser(), + ) + parser.add_option( + "-K", + "--key", + action="store", + type="string", + dest="keyfile", + default=None, + help="private key file to use for SSH authentication", + ) + parser.add_option( + "", + "--no-key", + action="store_false", + dest="look_for_keys", + default=True, + help="don't look for or use a private key file", + ) + parser.add_option( + "-P", + "--password", + action="store_true", + dest="readpass", + default=False, + help="read password (for key or password auth) from stdin", + ) + parser.add_option( + "-r", + "--remote", + action="store", + type="string", + dest="remote", + default=None, + metavar="host:port", + help="remote host and port to forward to", + ) options, args = parser.parse_args() if len(args) != 1: - parser.error('Incorrect number of arguments.') + parser.error("Incorrect number of arguments.") if options.remote is None: - parser.error('Remote address required (-r).') - + parser.error("Remote address required (-r).") + g_verbose = options.verbose server_host, server_port = get_host_port(args[0], SSH_PORT) remote_host, remote_port = get_host_port(options.remote, SSH_PORT) @@ -156,31 +217,42 @@ def parse_options(): def main(): options, server, remote = parse_options() - + password = None if options.readpass: - password = getpass.getpass('Enter SSH password: ') - + password = getpass.getpass("Enter SSH password: ") + client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) - verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1])) + verbose("Connecting to ssh host %s:%d ..." % (server[0], server[1])) try: - client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, - look_for_keys=options.look_for_keys, password=password) + client.connect( + server[0], + server[1], + username=options.user, + key_filename=options.keyfile, + look_for_keys=options.look_for_keys, + password=password, + ) except Exception as e: - print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e)) + print("*** Failed to connect to %s:%d: %r" % (server[0], server[1], e)) sys.exit(1) - verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1])) + verbose( + "Now forwarding port %d to %s:%d ..." + % (options.port, remote[0], remote[1]) + ) try: - forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) + forward_tunnel( + options.port, remote[0], remote[1], client.get_transport() + ) except KeyboardInterrupt: - print('C-c: Port forwarding stopped.') + print("C-c: Port forwarding stopped.") sys.exit(0) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/demos/interactive.py b/demos/interactive.py index 7138cd6c..037787c4 100644 --- a/demos/interactive.py +++ b/demos/interactive.py @@ -25,6 +25,7 @@ from paramiko.py3compat import u try: import termios import tty + has_termios = True except ImportError: has_termios = False @@ -39,7 +40,7 @@ def interactive_shell(chan): def posix_shell(chan): import select - + oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) @@ -52,7 +53,7 @@ def posix_shell(chan): try: x = u(chan.recv(1024)) if len(x) == 0: - sys.stdout.write('\r\n*** EOF\r\n') + sys.stdout.write("\r\n*** EOF\r\n") break sys.stdout.write(x) sys.stdout.flush() @@ -67,26 +68,28 @@ def posix_shell(chan): finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) - + # thanks to Mike Looijmans for this code def windows_shell(chan): import threading - sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n") - + sys.stdout.write( + "Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n" + ) + def writeall(sock): while True: data = sock.recv(256) if not data: - sys.stdout.write('\r\n*** EOF ***\r\n\r\n') + sys.stdout.write("\r\n*** EOF ***\r\n\r\n") sys.stdout.flush() break sys.stdout.write(data) sys.stdout.flush() - + writer = threading.Thread(target=writeall, args=(chan,)) writer.start() - + try: while True: d = sys.stdin.read(1) diff --git a/demos/rforward.py b/demos/rforward.py index ae70670c..a2e8a776 100755 --- a/demos/rforward.py +++ b/demos/rforward.py @@ -47,11 +47,13 @@ def handler(chan, host, port): try: sock.connect((host, port)) except Exception as e: - verbose('Forwarding request to %s:%d failed: %r' % (host, port, e)) + verbose("Forwarding request to %s:%d failed: %r" % (host, port, e)) return - - verbose('Connected! Tunnel open %r -> %r -> %r' % (chan.origin_addr, - chan.getpeername(), (host, port))) + + verbose( + "Connected! Tunnel open %r -> %r -> %r" + % (chan.origin_addr, chan.getpeername(), (host, port)) + ) while True: r, w, x = select.select([sock, chan], [], []) if sock in r: @@ -66,16 +68,18 @@ def handler(chan, host, port): sock.send(data) chan.close() sock.close() - verbose('Tunnel closed from %r' % (chan.origin_addr,)) + verbose("Tunnel closed from %r" % (chan.origin_addr,)) def reverse_forward_tunnel(server_port, remote_host, remote_port, transport): - transport.request_port_forward('', server_port) + transport.request_port_forward("", server_port) while True: chan = transport.accept(1000) if chan is None: continue - thr = threading.Thread(target=handler, args=(chan, remote_host, remote_port)) + thr = threading.Thread( + target=handler, args=(chan, remote_host, remote_port) + ) thr.setDaemon(True) thr.start() @@ -95,40 +99,88 @@ network. This is similar to the openssh -R option. def get_host_port(spec, default_port): "parse 'hostname:22' into a host and port, with the port optional" - args = (spec.split(':', 1) + [default_port])[:2] + args = (spec.split(":", 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1] def parse_options(): global g_verbose - - parser = OptionParser(usage='usage: %prog [options] [:]', - version='%prog 1.0', description=HELP) - parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True, - help='squelch all informational output') - parser.add_option('-p', '--remote-port', action='store', type='int', dest='port', - default=DEFAULT_PORT, - help='port on server to forward (default: %d)' % DEFAULT_PORT) - parser.add_option('-u', '--user', action='store', type='string', dest='user', - default=getpass.getuser(), - help='username for SSH authentication (default: %s)' % getpass.getuser()) - parser.add_option('-K', '--key', action='store', type='string', dest='keyfile', - default=None, - help='private key file to use for SSH authentication') - parser.add_option('', '--no-key', action='store_false', dest='look_for_keys', default=True, - help='don\'t look for or use a private key file') - parser.add_option('-P', '--password', action='store_true', dest='readpass', default=False, - help='read password (for key or password auth) from stdin') - parser.add_option('-r', '--remote', action='store', type='string', dest='remote', default=None, metavar='host:port', - help='remote host and port to forward to') + + parser = OptionParser( + usage="usage: %prog [options] [:]", + version="%prog 1.0", + description=HELP, + ) + parser.add_option( + "-q", + "--quiet", + action="store_false", + dest="verbose", + default=True, + help="squelch all informational output", + ) + parser.add_option( + "-p", + "--remote-port", + action="store", + type="int", + dest="port", + default=DEFAULT_PORT, + help="port on server to forward (default: %d)" % DEFAULT_PORT, + ) + parser.add_option( + "-u", + "--user", + action="store", + type="string", + dest="user", + default=getpass.getuser(), + help="username for SSH authentication (default: %s)" + % getpass.getuser(), + ) + parser.add_option( + "-K", + "--key", + action="store", + type="string", + dest="keyfile", + default=None, + help="private key file to use for SSH authentication", + ) + parser.add_option( + "", + "--no-key", + action="store_false", + dest="look_for_keys", + default=True, + help="don't look for or use a private key file", + ) + parser.add_option( + "-P", + "--password", + action="store_true", + dest="readpass", + default=False, + help="read password (for key or password auth) from stdin", + ) + parser.add_option( + "-r", + "--remote", + action="store", + type="string", + dest="remote", + default=None, + metavar="host:port", + help="remote host and port to forward to", + ) options, args = parser.parse_args() if len(args) != 1: - parser.error('Incorrect number of arguments.') + parser.error("Incorrect number of arguments.") if options.remote is None: - parser.error('Remote address required (-r).') - + parser.error("Remote address required (-r).") + g_verbose = options.verbose server_host, server_port = get_host_port(args[0], SSH_PORT) remote_host, remote_port = get_host_port(options.remote, SSH_PORT) @@ -137,31 +189,42 @@ def parse_options(): def main(): options, server, remote = parse_options() - + password = None if options.readpass: - password = getpass.getpass('Enter SSH password: ') - + password = getpass.getpass("Enter SSH password: ") + client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) - verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1])) + verbose("Connecting to ssh host %s:%d ..." % (server[0], server[1])) try: - client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, - look_for_keys=options.look_for_keys, password=password) + client.connect( + server[0], + server[1], + username=options.user, + key_filename=options.keyfile, + look_for_keys=options.look_for_keys, + password=password, + ) except Exception as e: - print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e)) + print("*** Failed to connect to %s:%d: %r" % (server[0], server[1], e)) sys.exit(1) - verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1])) + verbose( + "Now forwarding remote port %d to %s:%d ..." + % (options.port, remote[0], remote[1]) + ) try: - reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) + reverse_forward_tunnel( + options.port, remote[0], remote[1], client.get_transport() + ) except KeyboardInterrupt: - print('C-c: Port forwarding stopped.') + print("C-c: Port forwarding stopped.") sys.exit(0) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/paramiko/_winapi.py b/paramiko/_winapi.py index c996ec46..ebcc678a 100644 --- a/paramiko/_winapi.py +++ b/paramiko/_winapi.py @@ -96,15 +96,15 @@ GlobalAlloc.argtypes = ctypes.wintypes.UINT, ctypes.c_size_t GlobalAlloc.restype = ctypes.wintypes.HANDLE GlobalLock = ctypes.windll.kernel32.GlobalLock -GlobalLock.argtypes = ctypes.wintypes.HGLOBAL, +GlobalLock.argtypes = (ctypes.wintypes.HGLOBAL,) GlobalLock.restype = ctypes.wintypes.LPVOID GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock -GlobalUnlock.argtypes = ctypes.wintypes.HGLOBAL, +GlobalUnlock.argtypes = (ctypes.wintypes.HGLOBAL,) GlobalUnlock.restype = ctypes.wintypes.BOOL GlobalSize = ctypes.windll.kernel32.GlobalSize -GlobalSize.argtypes = ctypes.wintypes.HGLOBAL, +GlobalSize.argtypes = (ctypes.wintypes.HGLOBAL,) GlobalSize.restype = ctypes.c_size_t CreateFileMapping = ctypes.windll.kernel32.CreateFileMappingW @@ -122,12 +122,12 @@ MapViewOfFile = ctypes.windll.kernel32.MapViewOfFile MapViewOfFile.restype = ctypes.wintypes.HANDLE UnmapViewOfFile = ctypes.windll.kernel32.UnmapViewOfFile -UnmapViewOfFile.argtypes = ctypes.wintypes.HANDLE, +UnmapViewOfFile.argtypes = (ctypes.wintypes.HANDLE,) RtlMoveMemory = ctypes.windll.kernel32.RtlMoveMemory RtlMoveMemory.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t) -ctypes.windll.kernel32.LocalFree.argtypes = ctypes.wintypes.HLOCAL, +ctypes.windll.kernel32.LocalFree.argtypes = (ctypes.wintypes.HLOCAL,) ##################### # jaraco.windows.mmap @@ -276,7 +276,8 @@ class TokenInformationClass: class TOKEN_USER(ctypes.Structure): num = 1 _fields_ = [ - ("SID", ctypes.c_void_p), ("ATTRIBUTES", ctypes.wintypes.DWORD) + ("SID", ctypes.c_void_p), + ("ATTRIBUTES", ctypes.wintypes.DWORD), ] @@ -336,7 +337,9 @@ class SECURITY_ATTRIBUTES(ctypes.Structure): ctypes.windll.advapi32.SetSecurityDescriptorOwner.argtypes = ( - ctypes.POINTER(SECURITY_DESCRIPTOR), ctypes.c_void_p, ctypes.wintypes.BOOL + ctypes.POINTER(SECURITY_DESCRIPTOR), + ctypes.c_void_p, + ctypes.wintypes.BOOL, ) ######################### diff --git a/paramiko/agent.py b/paramiko/agent.py index 00baf85c..62a271d5 100644 --- a/paramiko/agent.py +++ b/paramiko/agent.py @@ -116,12 +116,9 @@ class AgentProxyThread(threading.Thread): # The address should be an IP address as a string? or None self.__addr = addr self._agent.connect() - if ( - not isinstance(self._agent, int) - and ( - self._agent._conn is None - or not hasattr(self._agent._conn, "fileno") - ) + if not isinstance(self._agent, int) and ( + self._agent._conn is None + or not hasattr(self._agent._conn, "fileno") ): raise AuthenticationException("Unable to connect to SSH agent") self._communicate() diff --git a/paramiko/auth_handler.py b/paramiko/auth_handler.py index 416657e2..3f0456e5 100644 --- a/paramiko/auth_handler.py +++ b/paramiko/auth_handler.py @@ -464,9 +464,8 @@ Error Message: {} if service != "ssh-connection": self._disconnect_service_not_available() return - if ( - (self.auth_username is not None) - and (self.auth_username != username) + if (self.auth_username is not None) and ( + self.auth_username != username ): self._log( WARNING, @@ -514,7 +513,9 @@ Error Message: {} self._log(INFO, "Auth rejected: public key: {}".format(str(e))) key = None except Exception as e: - msg = "Auth rejected: unsupported or mangled public key ({}: {})" # noqa + msg = ( + "Auth rejected: unsupported or mangled public key ({}: {})" + ) # noqa self._log(INFO, msg.format(e.__class__.__name__, e)) key = None if key is None: diff --git a/paramiko/ber.py b/paramiko/ber.py index fb6ee71d..92d7121e 100644 --- a/paramiko/ber.py +++ b/paramiko/ber.py @@ -71,12 +71,14 @@ class BER(object): t = size & 0x7f if self.idx + t > len(self.content): return None - size = util.inflate_long(self.content[self.idx:self.idx + t], True) + size = util.inflate_long( + self.content[self.idx : self.idx + t], True + ) self.idx += t if self.idx + size > len(self.content): # can't fit return None - data = self.content[self.idx:self.idx + size] + data = self.content[self.idx : self.idx + size] self.idx += size # now switch on id if ident == 0x30: diff --git a/paramiko/client.py b/paramiko/client.py index 8690c86d..2538d582 100644 --- a/paramiko/client.py +++ b/paramiko/client.py @@ -562,7 +562,7 @@ class SSHClient(ClosingContextManager): cert_suffix = "-cert.pub" # Assume privkey, not cert, by default if filename.endswith(cert_suffix): - key_path = filename[:-len(cert_suffix)] + key_path = filename[: -len(cert_suffix)] cert_path = filename else: key_path = filename @@ -648,7 +648,7 @@ class SSHClient(ClosingContextManager): allowed_types = set( self._transport.auth_publickey(username, pkey) ) - two_factor = (allowed_types & two_factor_types) + two_factor = allowed_types & two_factor_types if not two_factor: return except SSHException as e: @@ -664,7 +664,7 @@ class SSHClient(ClosingContextManager): allowed_types = set( self._transport.auth_publickey(username, key) ) - two_factor = (allowed_types & two_factor_types) + two_factor = allowed_types & two_factor_types if not two_factor: return break @@ -684,7 +684,7 @@ class SSHClient(ClosingContextManager): allowed_types = set( self._transport.auth_publickey(username, key) ) - two_factor = (allowed_types & two_factor_types) + two_factor = allowed_types & two_factor_types if not two_factor: return break @@ -724,7 +724,7 @@ class SSHClient(ClosingContextManager): allowed_types = set( self._transport.auth_publickey(username, key) ) - two_factor = (allowed_types & two_factor_types) + two_factor = allowed_types & two_factor_types if not two_factor: return break diff --git a/paramiko/common.py b/paramiko/common.py index 7e9510b9..87d3dcf6 100644 --- a/paramiko/common.py +++ b/paramiko/common.py @@ -29,18 +29,14 @@ from paramiko.py3compat import byte_chr, PY2, bytes_types, text_type, long MSG_DEBUG, MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT, -) = range( - 1, 7 -) +) = range(1, 7) (MSG_KEXINIT, MSG_NEWKEYS) = range(20, 22) ( MSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE, MSG_USERAUTH_SUCCESS, MSG_USERAUTH_BANNER, -) = range( - 50, 54 -) +) = range(50, 54) MSG_USERAUTH_PK_OK = 60 (MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE) = range(60, 62) (MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN) = range(60, 62) @@ -49,9 +45,7 @@ MSG_USERAUTH_PK_OK = 60 MSG_USERAUTH_GSSAPI_ERROR, MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC, -) = range( - 63, 67 -) +) = range(63, 67) HIGHEST_USERAUTH_MESSAGE_ID = 79 (MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE) = range(80, 83) ( @@ -66,9 +60,7 @@ HIGHEST_USERAUTH_MESSAGE_ID = 79 MSG_CHANNEL_REQUEST, MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, -) = range( - 90, 101 -) +) = range(90, 101) cMSG_DISCONNECT = byte_chr(MSG_DISCONNECT) cMSG_IGNORE = byte_chr(MSG_IGNORE) @@ -165,9 +157,7 @@ AUTH_SUCCESSFUL, AUTH_PARTIALLY_SUCCESSFUL, AUTH_FAILED = range(3) OPEN_FAILED_CONNECT_FAILED, OPEN_FAILED_UNKNOWN_CHANNEL_TYPE, OPEN_FAILED_RESOURCE_SHORTAGE, -) = range( - 0, 5 -) +) = range(0, 5) CONNECTION_FAILED_CODE = { @@ -182,7 +172,7 @@ CONNECTION_FAILED_CODE = { DISCONNECT_SERVICE_NOT_AVAILABLE, DISCONNECT_AUTH_CANCELLED_BY_USER, DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, -) = 7, 13, 14 +) = (7, 13, 14) zero_byte = byte_chr(0) one_byte = byte_chr(1) diff --git a/paramiko/dsskey.py b/paramiko/dsskey.py index fc9e7b54..ec358ee2 100644 --- a/paramiko/dsskey.py +++ b/paramiko/dsskey.py @@ -113,9 +113,7 @@ class DSSKey(PKey): p=self.p, q=self.q, g=self.g ), ), - ).private_key( - backend=default_backend() - ) + ).private_key(backend=default_backend()) sig = key.sign(data, hashes.SHA1()) r, s = decode_dss_signature(sig) @@ -152,9 +150,7 @@ class DSSKey(PKey): parameter_numbers=dsa.DSAParameterNumbers( p=self.p, q=self.q, g=self.g ), - ).public_key( - backend=default_backend() - ) + ).public_key(backend=default_backend()) try: key.verify(signature, data, hashes.SHA1()) except InvalidSignature: @@ -171,9 +167,7 @@ class DSSKey(PKey): p=self.p, q=self.q, g=self.g ), ), - ).private_key( - backend=default_backend() - ) + ).private_key(backend=default_backend()) self._write_private_key_file( filename, @@ -191,9 +185,7 @@ class DSSKey(PKey): p=self.p, q=self.q, g=self.g ), ), - ).private_key( - backend=default_backend() - ) + ).private_key(backend=default_backend()) self._write_private_key( file_obj, diff --git a/paramiko/ecdsakey.py b/paramiko/ecdsakey.py index 4b7984ca..b73a969e 100644 --- a/paramiko/ecdsakey.py +++ b/paramiko/ecdsakey.py @@ -141,7 +141,7 @@ class ECDSAKey(PKey): # feels more correct to do it here?) suffix = "-cert-v01@openssh.com" if key_type.endswith(suffix): - key_type = key_type[:-len(suffix)] + key_type = key_type[: -len(suffix)] self.ecdsa_curve = self._ECDSA_CURVES.get_by_key_format_identifier( key_type ) diff --git a/paramiko/ed25519key.py b/paramiko/ed25519key.py index c8f6dd34..68ada224 100644 --- a/paramiko/ed25519key.py +++ b/paramiko/ed25519key.py @@ -145,8 +145,8 @@ class Ed25519Key(PKey): ignore_few_rounds=True, ) decryptor = Cipher( - cipher["class"](key[:cipher["key-size"]]), - cipher["mode"](key[cipher["key-size"]:]), + cipher["class"](key[: cipher["key-size"]]), + cipher["mode"](key[cipher["key-size"] :]), backend=default_backend(), ).decryptor() private_data = ( diff --git a/paramiko/file.py b/paramiko/file.py index 62686b53..9e9f6eb8 100644 --- a/paramiko/file.py +++ b/paramiko/file.py @@ -166,7 +166,7 @@ class BufferedFile(ClosingContextManager): The number of bytes read. """ data = self.read(len(buff)) - buff[:len(data)] = data + buff[: len(data)] = data return len(data) def read(self, size=None): @@ -283,12 +283,8 @@ class BufferedFile(ClosingContextManager): n = size - len(line) else: n = self._bufsize - if ( - linefeed_byte in line - or ( - self._flags & self.FLAG_UNIVERSAL_NEWLINE - and cr_byte in line - ) + if linefeed_byte in line or ( + self._flags & self.FLAG_UNIVERSAL_NEWLINE and cr_byte in line ): break try: @@ -415,9 +411,9 @@ class BufferedFile(ClosingContextManager): if last_newline_pos >= 0: wbuf = self._wbuffer.getvalue() last_newline_pos += len(wbuf) - len(data) - self._write_all(wbuf[:last_newline_pos + 1]) + self._write_all(wbuf[: last_newline_pos + 1]) self._wbuffer = BytesIO() - self._wbuffer.write(wbuf[last_newline_pos + 1:]) + self._wbuffer.write(wbuf[last_newline_pos + 1 :]) return # even if we're line buffering, if the buffer has grown past the # buffer size, force a flush. @@ -541,8 +537,8 @@ class BufferedFile(ClosingContextManager): return if self.newlines is None: self.newlines = newline - elif ( - self.newlines != newline and isinstance(self.newlines, bytes_types) + elif self.newlines != newline and isinstance( + self.newlines, bytes_types ): self.newlines = (self.newlines, newline) elif newline not in self.newlines: diff --git a/paramiko/kex_ecdh_nist.py b/paramiko/kex_ecdh_nist.py index ca32404f..1d87442a 100644 --- a/paramiko/kex_ecdh_nist.py +++ b/paramiko/kex_ecdh_nist.py @@ -15,7 +15,7 @@ _MSG_KEXECDH_INIT, _MSG_KEXECDH_REPLY = range(30, 32) c_MSG_KEXECDH_INIT, c_MSG_KEXECDH_REPLY = [byte_chr(c) for c in range(30, 32)] -class KexNistp256(): +class KexNistp256: name = "ecdh-sha2-nistp256" hash_algo = sha256 diff --git a/paramiko/kex_gex.py b/paramiko/kex_gex.py index 6b24c1ff..fb8f01fd 100644 --- a/paramiko/kex_gex.py +++ b/paramiko/kex_gex.py @@ -38,9 +38,7 @@ from paramiko.ssh_exception import SSHException _MSG_KEXDH_GEX_INIT, _MSG_KEXDH_GEX_REPLY, _MSG_KEXDH_GEX_REQUEST, -) = range( - 30, 35 -) +) = range(30, 35) ( c_MSG_KEXDH_GEX_REQUEST_OLD, @@ -48,9 +46,7 @@ from paramiko.ssh_exception import SSHException c_MSG_KEXDH_GEX_INIT, c_MSG_KEXDH_GEX_REPLY, c_MSG_KEXDH_GEX_REQUEST, -) = [ - byte_chr(c) for c in range(30, 35) -] +) = [byte_chr(c) for c in range(30, 35)] class KexGex(object): diff --git a/paramiko/kex_group1.py b/paramiko/kex_group1.py index 904835d7..66b7bb20 100644 --- a/paramiko/kex_group1.py +++ b/paramiko/kex_group1.py @@ -41,7 +41,9 @@ b0000000000000000 = zero_byte * 8 class KexGroup1(object): # draft-ietf-secsh-transport-09.txt, page 17 - P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF # noqa + P = ( + 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF # noqa + ) G = 2 name = "diffie-hellman-group1-sha1" diff --git a/paramiko/kex_group14.py b/paramiko/kex_group14.py index 0df302e3..29af2408 100644 --- a/paramiko/kex_group14.py +++ b/paramiko/kex_group14.py @@ -28,7 +28,9 @@ from hashlib import sha1 class KexGroup14(KexGroup1): # http://tools.ietf.org/html/rfc3526#section-3 - P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF # noqa + P = ( + 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF # noqa + ) G = 2 name = "diffie-hellman-group14-sha1" diff --git a/paramiko/kex_gss.py b/paramiko/kex_gss.py index 5eaaa5d5..1510ff9c 100644 --- a/paramiko/kex_gss.py +++ b/paramiko/kex_gss.py @@ -53,9 +53,7 @@ from paramiko.ssh_exception import SSHException MSG_KEXGSS_COMPLETE, MSG_KEXGSS_HOSTKEY, MSG_KEXGSS_ERROR, -) = range( - 30, 35 -) +) = range(30, 35) (MSG_KEXGSS_GROUPREQ, MSG_KEXGSS_GROUP) = range(40, 42) ( c_MSG_KEXGSS_INIT, @@ -63,9 +61,7 @@ from paramiko.ssh_exception import SSHException c_MSG_KEXGSS_COMPLETE, c_MSG_KEXGSS_HOSTKEY, c_MSG_KEXGSS_ERROR, -) = [ - byte_chr(c) for c in range(30, 35) -] +) = [byte_chr(c) for c in range(30, 35)] (c_MSG_KEXGSS_GROUPREQ, c_MSG_KEXGSS_GROUP) = [ byte_chr(c) for c in range(40, 42) ] @@ -77,7 +73,9 @@ class KexGSSGroup1(object): 4462 Section 2 `_ """ # draft-ietf-secsh-transport-09.txt, page 17 - P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF # noqa + P = ( + 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF # noqa + ) G = 2 b7fffffffffffffff = byte_chr(0x7f) + max_byte * 7 # noqa b0000000000000000 = zero_byte * 8 # noqa @@ -324,7 +322,9 @@ class KexGSSGroup14(KexGSSGroup1): in `RFC 4462 Section 2 `_ """ - P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF # noqa + P = ( + 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF # noqa + ) G = 2 NAME = "gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==" diff --git a/paramiko/packet.py b/paramiko/packet.py index 20b37ac4..d324fc35 100644 --- a/paramiko/packet.py +++ b/paramiko/packet.py @@ -365,7 +365,7 @@ class Packetizer(object): while linefeed_byte not in buf: buf += self._read_timeout(timeout) n = buf.index(linefeed_byte) - self.__remainder = buf[n + 1:] + self.__remainder = buf[n + 1 :] buf = buf[:n] if (len(buf) > 0) and (buf[-1] == cr_byte_value): buf = buf[:-1] @@ -400,14 +400,12 @@ class Packetizer(object): out = packet # + mac if self.__block_engine_out is not None: - payload = struct.pack( - ">I", self.__sequence_number_out - ) + packet + payload = ( + struct.pack(">I", self.__sequence_number_out) + packet + ) out += compute_hmac( self.__mac_key_out, payload, self.__mac_engine_out - )[ - :self.__mac_size_out - ] + )[: self.__mac_size_out] self.__sequence_number_out = ( self.__sequence_number_out + 1 ) & xffffffff @@ -451,8 +449,8 @@ class Packetizer(object): if (packet_size - len(leftover)) % self.__block_size_in != 0: raise SSHException("Invalid packet blocking") buf = self.read_all(packet_size + self.__mac_size_in - len(leftover)) - packet = buf[:packet_size - len(leftover)] - post_packet = buf[packet_size - len(leftover):] + packet = buf[: packet_size - len(leftover)] + post_packet = buf[packet_size - len(leftover) :] if self.__block_engine_in is not None: packet = self.__block_engine_in.update(packet) if self.__dump_packets: @@ -460,19 +458,18 @@ class Packetizer(object): packet = leftover + packet if self.__mac_size_in > 0: - mac = post_packet[:self.__mac_size_in] - mac_payload = struct.pack( - ">II", self.__sequence_number_in, packet_size - ) + packet + mac = post_packet[: self.__mac_size_in] + mac_payload = ( + struct.pack(">II", self.__sequence_number_in, packet_size) + + packet + ) my_mac = compute_hmac( self.__mac_key_in, mac_payload, self.__mac_engine_in - )[ - :self.__mac_size_in - ] + )[: self.__mac_size_in] if not util.constant_time_bytes_eq(my_mac, mac): raise SSHException("Mismatched MAC") padding = byte_ord(packet[0]) - payload = packet[1:packet_size - padding] + payload = packet[1 : packet_size - padding] if self.__dump_packets: self._log( @@ -499,14 +496,10 @@ class Packetizer(object): self.__received_bytes_overflow += raw_packet_size self.__received_packets_overflow += 1 if ( - ( - self.__received_packets_overflow - >= self.REKEY_PACKETS_OVERFLOW_MAX - ) - or ( - self.__received_bytes_overflow - >= self.REKEY_BYTES_OVERFLOW_MAX - ) + self.__received_packets_overflow + >= self.REKEY_PACKETS_OVERFLOW_MAX + ) or ( + self.__received_bytes_overflow >= self.REKEY_BYTES_OVERFLOW_MAX ): raise SSHException( "Remote transport is ignoring rekey requests" @@ -592,7 +585,7 @@ class Packetizer(object): # cute trick i caught openssh doing: if we're not encrypting or # SDCTR mode (RFC4344), # don't waste random bytes for the padding - packet += (zero_byte * padding) + packet += zero_byte * padding else: packet += os.urandom(padding) return packet diff --git a/paramiko/pkey.py b/paramiko/pkey.py index a01d4fd8..fa014800 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -507,8 +507,10 @@ class PublicBlob(object): m = Message(key_blob) blob_type = m.get_text() if blob_type != key_type: - msg = "Invalid PublicBlob contents: key type={!r}, but blob type={!r}" # noqa - raise ValueError(msg.format(key_type, blob_type)) + deets = "key type={!r}, but blob type={!r}".format( + key_type, blob_type + ) + raise ValueError("Invalid PublicBlob contents: {}".format(deets)) # All good? All good. return cls(type_=key_type, blob=key_blob, comment=comment) diff --git a/paramiko/primes.py b/paramiko/primes.py index 7496abbd..8dff7683 100644 --- a/paramiko/primes.py +++ b/paramiko/primes.py @@ -62,7 +62,13 @@ class ModulusPack(object): def _parse_modulus(self, line): ( - timestamp, mod_type, tests, tries, size, generator, modulus + timestamp, + mod_type, + tests, + tries, + size, + generator, + modulus, ) = line.split() mod_type = int(mod_type) tests = int(tests) diff --git a/paramiko/proxy.py b/paramiko/proxy.py index d0ef8784..444c47b6 100644 --- a/paramiko/proxy.py +++ b/paramiko/proxy.py @@ -89,7 +89,7 @@ class ProxyCommand(ClosingContextManager): while len(buffer) < size: select_timeout = None if self.timeout is not None: - elapsed = (time.time() - start) + elapsed = time.time() - start if elapsed >= self.timeout: raise socket.timeout() select_timeout = self.timeout - elapsed diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index b0fce1f1..442bfe1f 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -66,9 +66,7 @@ class RSAKey(PKey): ) self.key = rsa.RSAPublicNumbers( e=msg.get_mpint(), n=msg.get_mpint() - ).public_key( - default_backend() - ) + ).public_key(default_backend()) @property def size(self): diff --git a/paramiko/sftp.py b/paramiko/sftp.py index ac32f6bd..6aa4ce44 100644 --- a/paramiko/sftp.py +++ b/paramiko/sftp.py @@ -47,9 +47,7 @@ from paramiko.py3compat import byte_chr, byte_ord CMD_RENAME, CMD_READLINK, CMD_SYMLINK, -) = range( - 1, 21 -) +) = range(1, 21) (CMD_STATUS, CMD_HANDLE, CMD_DATA, CMD_NAME, CMD_ATTRS) = range(101, 106) (CMD_EXTENDED, CMD_EXTENDED_REPLY) = range(200, 202) @@ -63,9 +61,7 @@ SFTP_OK = 0 SFTP_NO_CONNECTION, SFTP_CONNECTION_LOST, SFTP_OP_UNSUPPORTED, -) = range( - 1, 9 -) +) = range(1, 9) SFTP_DESC = [ "Success", diff --git a/paramiko/sftp_attr.py b/paramiko/sftp_attr.py index 8e483739..f16ac746 100644 --- a/paramiko/sftp_attr.py +++ b/paramiko/sftp_attr.py @@ -231,7 +231,12 @@ class SFTPAttributes(object): # it untouched for the time being, re: .format() upgrade, until someone # has time to doublecheck return "%s 1 %-8d %-8d %8d %-12s %s" % ( - ks, uid, gid, size, datestr, filename + ks, + uid, + gid, + size, + datestr, + filename, ) def asbytes(self): diff --git a/paramiko/sftp_file.py b/paramiko/sftp_file.py index 049e804d..0104d857 100644 --- a/paramiko/sftp_file.py +++ b/paramiko/sftp_file.py @@ -200,9 +200,8 @@ class SFTPFile(BufferedFile): data[:chunk], ) self._reqs.append(sftp_async_request) - if ( - not self.pipelined - or (len(self._reqs) > 100 and self.sftp.sock.recv_ready()) + if not self.pipelined or ( + len(self._reqs) > 100 and self.sftp.sock.recv_ready() ): while len(self._reqs): req = self._reqs.popleft() @@ -497,10 +496,9 @@ class SFTPFile(BufferedFile): read_chunks = [] for offset, size in chunks: # don't fetch data that's already in the prefetch buffer - if ( - self._data_in_prefetch_buffers(offset) - or self._data_in_prefetch_requests(offset, size) - ): + if self._data_in_prefetch_buffers( + offset + ) or self._data_in_prefetch_requests(offset, size): continue # break up anything larger than the max read size diff --git a/paramiko/ssh_exception.py b/paramiko/ssh_exception.py index c1276c69..12407d66 100644 --- a/paramiko/ssh_exception.py +++ b/paramiko/ssh_exception.py @@ -109,7 +109,9 @@ class BadHostKeyException(SSHException): """ def __init__(self, hostname, got_key, expected_key): - message = "Host key for server {} does not match: got {}, expected {}" # noqa + message = ( + "Host key for server {} does not match: got {}, expected {}" + ) # noqa message = message.format( hostname, got_key.get_base64(), expected_key.get_base64() ) diff --git a/paramiko/ssh_gss.py b/paramiko/ssh_gss.py index 14087042..eb8826e0 100644 --- a/paramiko/ssh_gss.py +++ b/paramiko/ssh_gss.py @@ -561,9 +561,8 @@ class _SSH_SSPI(_SSH_GSSAuth): :return: ``True`` if credentials are delegated, otherwise ``False`` """ - return ( - self._gss_flags & sspicon.ISC_REQ_DELEGATE - and (self._gss_srv_ctxt_status or self._gss_flags) + return self._gss_flags & sspicon.ISC_REQ_DELEGATE and ( + self._gss_srv_ctxt_status or self._gss_flags ) def save_client_creds(self, client_token): diff --git a/paramiko/transport.py b/paramiko/transport.py index ea303d37..4e6cb2c1 100644 --- a/paramiko/transport.py +++ b/paramiko/transport.py @@ -583,9 +583,8 @@ class Transport(threading.Thread, ClosingContextManager): if e is not None: raise e raise SSHException("Negotiation failed.") - if ( - event.is_set() - or (timeout is not None and time.time() >= max_time) + if event.is_set() or ( + timeout is not None and time.time() >= max_time ): break @@ -2389,7 +2388,8 @@ class Transport(threading.Thread, ClosingContextManager): len(agreed_local_compression) == 0 or len(agreed_remote_compression) == 0 ): - msg = "Incompatible ssh server (no acceptable compression) {!r} {!r} {!r}" # noqa + msg = "Incompatible ssh server (no acceptable compression)" + msg += " {!r} {!r} {!r}" raise SSHException( msg.format( agreed_local_compression, @@ -2441,12 +2441,8 @@ class Transport(threading.Thread, ClosingContextManager): engine, block_size, mac_engine, mac_size, mac_key ) compress_in = self._compression_info[self.remote_compression][1] - if ( - compress_in is not None - and ( - self.remote_compression != "zlib@openssh.com" - or self.authenticated - ) + if compress_in is not None and ( + self.remote_compression != "zlib@openssh.com" or self.authenticated ): self._log(DEBUG, "Switching on inbound compression ...") self.packetizer.set_inbound_compressor(compress_in()) @@ -2484,12 +2480,8 @@ class Transport(threading.Thread, ClosingContextManager): engine, block_size, mac_engine, mac_size, mac_key, sdctr ) compress_out = self._compression_info[self.local_compression][0] - if ( - compress_out is not None - and ( - self.local_compression != "zlib@openssh.com" - or self.authenticated - ) + if compress_out is not None and ( + self.local_compression != "zlib@openssh.com" or self.authenticated ): self._log(DEBUG, "Switching on outbound compression ...") self.packetizer.set_outbound_compressor(compress_out()) diff --git a/paramiko/util.py b/paramiko/util.py index c60c040c..399141ad 100644 --- a/paramiko/util.py +++ b/paramiko/util.py @@ -49,9 +49,9 @@ def inflate_long(s, always_positive=False): # noinspection PyAugmentAssignment s = filler * (4 - len(s) % 4) + s for i in range(0, len(s), 4): - out = (out << 32) + struct.unpack(">I", s[i:i + 4])[0] + out = (out << 32) + struct.unpack(">I", s[i : i + 4])[0] if negative: - out -= (long(1) << (8 * len(s))) + out -= long(1) << (8 * len(s)) return out @@ -81,7 +81,7 @@ def deflate_long(n, add_sign_padding=True): s = zero_byte else: s = max_byte - s = s[i[0]:] + s = s[i[0] :] if add_sign_padding: if (n == 0) and (byte_ord(s[0]) >= 0x80): s = zero_byte + s @@ -94,7 +94,7 @@ def format_binary(data, prefix=""): x = 0 out = [] while len(data) > x + 16: - out.append(format_binary_line(data[x:x + 16])) + out.append(format_binary_line(data[x : x + 16])) x += 16 if x < len(data): out.append(format_binary_line(data[x:])) @@ -251,7 +251,8 @@ def log_to_file(filename, level=DEBUG): l.setLevel(level) f = open(filename, "a") lh = logging.StreamHandler(f) - frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d %(name)s: %(message)s" # noqa + frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d" + frm += " %(name)s: %(message)s" lh.setFormatter(logging.Formatter(frm, "%Y%m%d-%H:%M:%S")) l.addHandler(lh) diff --git a/setup.cfg b/setup.cfg index 2d673ea4..bf86db42 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,7 +9,9 @@ omit = paramiko/_winapi.py [flake8] exclude = sites,.git,build,dist,demos,tests -ignore = E124,E125,E128,E261,E301,E302,E303,E402,E721,W503 +# NOTE: W503, E203 are concessions to black 18.0b5 and could be reinstated +# later if fixed on that end. +ignore = E124,E125,E128,E261,E301,E302,E303,E402,E721,W503,E203 max-line-length = 79 [tool:pytest] diff --git a/setup.py b/setup.py index 6e1f0e0e..a427ccc3 100644 --- a/setup.py +++ b/setup.py @@ -19,12 +19,12 @@ import sys from setuptools import setup -if sys.platform == 'darwin': +if sys.platform == "darwin": import setup_helper setup_helper.install_custom_make_tarball() -longdesc = ''' +longdesc = """ This is a library for making SSH2 connections (client or server). Emphasis is on using SSH2 as an alternative to SSL for making secure connections between python scripts. All major ciphers and hash methods @@ -35,14 +35,14 @@ Required packages: To install the development version, ``pip install -e git+https://github.com/paramiko/paramiko/#egg=paramiko``. -''' +""" # Version info -- read without importing _locals = {} -with open('paramiko/_version.py') as fp: +with open("paramiko/_version.py") as fp: exec(fp.read(), None, _locals) -version = _locals['__version__'] +version = _locals["__version__"] setup( name="paramiko", @@ -52,29 +52,29 @@ setup( author="Jeff Forcier", author_email="jeff@bitprophet.org", url="https://github.com/paramiko/paramiko/", - packages=['paramiko'], - license='LGPL', - platforms='Posix; MacOS X; Windows', + packages=["paramiko"], + license="LGPL", + platforms="Posix; MacOS X; Windows", classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: ' - 'GNU Library or Lesser General Public License (LGPL)', - 'Operating System :: OS Independent', - 'Topic :: Internet', - 'Topic :: Security :: Cryptography', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: " + "GNU Library or Lesser General Public License (LGPL)", + "Operating System :: OS Independent", + "Topic :: Internet", + "Topic :: Security :: Cryptography", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", ], install_requires=[ - 'bcrypt>=3.1.3', - 'cryptography>=1.5', - 'pynacl>=1.0.1', - 'pyasn1>=0.1.7', + "bcrypt>=3.1.3", + "cryptography>=1.5", + "pynacl>=1.0.1", + "pyasn1>=0.1.7", ], ) diff --git a/setup_helper.py b/setup_helper.py index c359a16c..d0a8700e 100644 --- a/setup_helper.py +++ b/setup_helper.py @@ -40,6 +40,7 @@ try: except ImportError: getgrnam = None + def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: @@ -52,6 +53,7 @@ def _get_gid(name): return result[2] return None + def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: @@ -64,8 +66,16 @@ def _get_uid(name): return result[2] return None -def make_tarball(base_name, base_dir, compress='gzip', verbose=0, dry_run=0, - owner=None, group=None): + +def make_tarball( + base_name, + base_dir, + compress="gzip", + verbose=0, + dry_run=0, + owner=None, + group=None, +): """Create a tar file from all the files under 'base_dir'. This file may be compressed. @@ -87,28 +97,26 @@ def make_tarball(base_name, base_dir, compress='gzip', verbose=0, dry_run=0, # "create a tree of hardlinks" step! (Would also be nice to # detect GNU tar to use its 'z' option and save a step.) - compress_ext = { - 'gzip': ".gz", - 'bzip2': '.bz2', - 'compress': ".Z", - } + compress_ext = {"gzip": ".gz", "bzip2": ".bz2", "compress": ".Z"} # flags for compression program, each element of list will be an argument - tarfile_compress_flag = {'gzip': 'gz', 'bzip2': 'bz2'} - compress_flags = {'compress': ["-f"]} + tarfile_compress_flag = {"gzip": "gz", "bzip2": "bz2"} + compress_flags = {"compress": ["-f"]} if compress is not None and compress not in compress_ext.keys(): - raise ValueError("bad value for 'compress': must be None, 'gzip'," - "'bzip2' or 'compress'") + raise ValueError( + "bad value for 'compress': must be None, 'gzip'," + "'bzip2' or 'compress'" + ) archive_name = base_name + ".tar" if compress and compress in tarfile_compress_flag: archive_name += compress_ext[compress] - mode = 'w:' + tarfile_compress_flag.get(compress, '') + mode = "w:" + tarfile_compress_flag.get(compress, "") mkpath(os.path.dirname(archive_name), dry_run=dry_run) - log.info('Creating tar file %s with mode %s' % (archive_name, mode)) + log.info("Creating tar file %s with mode %s" % (archive_name, mode)) uid = _get_uid(owner) gid = _get_gid(group) @@ -136,18 +144,20 @@ def make_tarball(base_name, base_dir, compress='gzip', verbose=0, dry_run=0, tar.close() if compress and compress not in tarfile_compress_flag: - spawn([compress] + compress_flags[compress] + [archive_name], - dry_run=dry_run) + spawn( + [compress] + compress_flags[compress] + [archive_name], + dry_run=dry_run, + ) return archive_name + compress_ext[compress] else: return archive_name _custom_formats = { - 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), - 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), - 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"), - 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"), + "gztar": (make_tarball, [("compress", "gzip")], "gzip'ed tar-file"), + "bztar": (make_tarball, [("compress", "bzip2")], "bzip2'ed tar-file"), + "ztar": (make_tarball, [("compress", "compress")], "compressed tar file"), + "tar": (make_tarball, [("compress", None)], "uncompressed tar file"), } # Hack in and insert ourselves into the distutils code base diff --git a/sites/docs/conf.py b/sites/docs/conf.py index 5674fed1..eb895804 100644 --- a/sites/docs/conf.py +++ b/sites/docs/conf.py @@ -1,16 +1,17 @@ # Obtain shared config values import os, sys -sys.path.append(os.path.abspath('..')) -sys.path.append(os.path.abspath('../..')) + +sys.path.append(os.path.abspath("..")) +sys.path.append(os.path.abspath("../..")) from shared_conf import * # Enable autodoc, intersphinx -extensions.extend(['sphinx.ext.autodoc']) +extensions.extend(["sphinx.ext.autodoc"]) # Autodoc settings -autodoc_default_flags = ['members', 'special-members'] +autodoc_default_flags = ["members", "special-members"] # Sister-site links to WWW -html_theme_options['extra_nav_links'] = { - "Main website": 'http://www.paramiko.org', +html_theme_options["extra_nav_links"] = { + "Main website": "http://www.paramiko.org" } diff --git a/sites/shared_conf.py b/sites/shared_conf.py index cf0d77ff..f4806cf1 100644 --- a/sites/shared_conf.py +++ b/sites/shared_conf.py @@ -5,36 +5,29 @@ import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] -extensions = ['alabaster', 'sphinx.ext.intersphinx'] +extensions = ["alabaster", "sphinx.ext.intersphinx"] # Paths relative to invoking conf.py - not this shared file -html_theme = 'alabaster' +html_theme = "alabaster" html_theme_options = { - 'description': "A Python implementation of SSHv2.", - 'github_user': 'paramiko', - 'github_repo': 'paramiko', - 'analytics_id': 'UA-18486793-2', - 'travis_button': True, + "description": "A Python implementation of SSHv2.", + "github_user": "paramiko", + "github_repo": "paramiko", + "analytics_id": "UA-18486793-2", + "travis_button": True, } html_sidebars = { - '**': [ - 'about.html', - 'navigation.html', - 'searchbox.html', - 'donate.html', - ] + "**": ["about.html", "navigation.html", "searchbox.html", "donate.html"] } # Everything intersphinx's to Python -intersphinx_mapping = { - 'python': ('https://docs.python.org/2.7/', None), -} +intersphinx_mapping = {"python": ("https://docs.python.org/2.7/", None)} # Regular settings -project = 'Paramiko' +project = "Paramiko" year = datetime.now().year -copyright = '{} Jeff Forcier'.format(year) -master_doc = 'index' -templates_path = ['_templates'] -exclude_trees = ['_build'] -source_suffix = '.rst' -default_role = 'obj' +copyright = "{} Jeff Forcier".format(year) +master_doc = "index" +templates_path = ["_templates"] +exclude_trees = ["_build"] +source_suffix = ".rst" +default_role = "obj" diff --git a/sites/www/conf.py b/sites/www/conf.py index c7ba0a86..00944871 100644 --- a/sites/www/conf.py +++ b/sites/www/conf.py @@ -3,22 +3,22 @@ import sys import os from os.path import abspath, join, dirname -sys.path.append(abspath(join(dirname(__file__), '..'))) +sys.path.append(abspath(join(dirname(__file__), ".."))) from shared_conf import * # Releases changelog extension -extensions.append('releases') +extensions.append("releases") releases_release_uri = "https://github.com/paramiko/paramiko/tree/%s" releases_issue_uri = "https://github.com/paramiko/paramiko/issues/%s" # Default is 'local' building, but reference the public docs site when building # under RTD. -target = join(dirname(__file__), '..', 'docs', '_build') -if os.environ.get('READTHEDOCS') == 'True': - target = 'http://docs.paramiko.org/en/latest/' -intersphinx_mapping['docs'] = (target, None) +target = join(dirname(__file__), "..", "docs", "_build") +if os.environ.get("READTHEDOCS") == "True": + target = "http://docs.paramiko.org/en/latest/" +intersphinx_mapping["docs"] = (target, None) # Sister-site links to API docs -html_theme_options['extra_nav_links'] = { - "API Docs": 'http://docs.paramiko.org', +html_theme_options["extra_nav_links"] = { + "API Docs": "http://docs.paramiko.org" } diff --git a/tasks.py b/tasks.py index d4cd414b..fb15728b 100644 --- a/tasks.py +++ b/tasks.py @@ -108,7 +108,7 @@ def release(ctx, sdist=True, wheel=True, sign=True, dry_run=False, index=None): copytree("sites/docs/_build", target) # Publish publish( - ctx, sdist=sdist, wheel=wheel, sign=sign, dry_run=dry_run, index=index, + ctx, sdist=sdist, wheel=wheel, sign=sign, dry_run=dry_run, index=index ) # Remind print( diff --git a/tests/stub_sftp.py b/tests/stub_sftp.py index 170304ab..ffae635d 100644 --- a/tests/stub_sftp.py +++ b/tests/stub_sftp.py @@ -207,7 +207,7 @@ class StubSFTPServer(SFTPServerInterface): else: # compute relative to path abspath = os.path.join(os.path.dirname(path), target_path) - if abspath[:len(self.ROOT)] != self.ROOT: + if abspath[: len(self.ROOT)] != self.ROOT: # this symlink isn't going to work anyway -- just break it immediately target_path = "" try: @@ -224,8 +224,8 @@ class StubSFTPServer(SFTPServerInterface): return SFTPServer.convert_errno(e.errno) # if it's absolute, remove the root if os.path.isabs(symlink): - if symlink[:len(self.ROOT)] == self.ROOT: - symlink = symlink[len(self.ROOT):] + if symlink[: len(self.ROOT)] == self.ROOT: + symlink = symlink[len(self.ROOT) :] if (len(symlink) == 0) or (symlink[0] != "/"): symlink = "/" + symlink else: diff --git a/tests/test_client.py b/tests/test_client.py index 4a1e9829..4943df29 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -264,7 +264,9 @@ class SSHClientTest(ClientTest): """ # This is dumb :( types_ = { - "rsa": "ssh-rsa", "dss": "ssh-dss", "ecdsa": "ecdsa-sha2-nistp256" + "rsa": "ssh-rsa", + "dss": "ssh-dss", + "ecdsa": "ecdsa-sha2-nistp256", } # Various combos of attempted & valid keys # TODO: try every possible combo using itertools functions diff --git a/tests/test_file.py b/tests/test_file.py index d2990118..deacd60a 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -42,7 +42,7 @@ class LoopbackFile(BufferedFile): self.offset = 0 def _read(self, size): - data = self.buffer.getvalue()[self.offset:self.offset + size] + data = self.buffer.getvalue()[self.offset : self.offset + size] self.offset += len(data) return data @@ -226,7 +226,7 @@ class BufferedFileTest(unittest.TestCase): with LoopbackFile("rb+") as f: view = memoryview(data) for offset in offsets: - f.write(view[offset:offset + 8]) + f.write(view[offset : offset + 8]) self.assertEqual(f.read(), data) diff --git a/tests/test_kex.py b/tests/test_kex.py index 41e2dea2..13d19d86 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -40,28 +40,26 @@ def dummy_urandom(n): def dummy_generate_key_pair(obj): - private_key_value = 94761803665136558137557783047955027733968423115106677159790289642479432803037 - public_key_numbers = "042bdab212fa8ba1b7c843301682a4db424d307246c7e1e6083c41d9ca7b098bf30b3d63e2ec6278488c135360456cc054b3444ecc45998c08894cbc1370f5f989" + private_key_value = ( + 94761803665136558137557783047955027733968423115106677159790289642479432803037 + ) + public_key_numbers = ( + "042bdab212fa8ba1b7c843301682a4db424d307246c7e1e6083c41d9ca7b098bf30b3d63e2ec6278488c135360456cc054b3444ecc45998c08894cbc1370f5f989" + ) public_key_numbers_obj = ec.EllipticCurvePublicNumbers.from_encoded_point( ec.SECP256R1(), unhexlify(public_key_numbers) ) obj.P = ec.EllipticCurvePrivateNumbers( private_value=private_key_value, public_numbers=public_key_numbers_obj - ).private_key( - default_backend() - ) + ).private_key(default_backend()) if obj.transport.server_mode: obj.Q_S = ec.EllipticCurvePublicNumbers.from_encoded_point( ec.SECP256R1(), unhexlify(public_key_numbers) - ).public_key( - default_backend() - ) + ).public_key(default_backend()) return obj.Q_C = ec.EllipticCurvePublicNumbers.from_encoded_point( ec.SECP256R1(), unhexlify(public_key_numbers) - ).public_key( - default_backend() - ) + ).public_key(default_backend()) class FakeKey(object): @@ -77,7 +75,9 @@ class FakeKey(object): class FakeModulusPack(object): - P = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF + P = ( + 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF + ) G = 2 def get_modulus(self, min, ask, max): @@ -118,7 +118,9 @@ class FakeTransport(object): class KexTest(unittest.TestCase): - K = 14730343317708716439807310032871972459448364195094179797249681733965528989482751523943515690110179031004049109375612685505881911274101441415545039654102474376472240501616988799699744135291070488314748284283496055223852115360852283821334858541043710301057312858051901453919067023103730011648890038847384890504 + K = ( + 14730343317708716439807310032871972459448364195094179797249681733965528989482751523943515690110179031004049109375612685505881911274101441415545039654102474376472240501616988799699744135291070488314748284283496055223852115360852283821334858541043710301057312858051901453919067023103730011648890038847384890504 + ) def setUp(self): self._original_urandom = os.urandom @@ -135,7 +137,9 @@ class KexTest(unittest.TestCase): transport.server_mode = False kex = KexGroup1(transport) kex.start_kex() - x = b"1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + x = ( + b"1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect @@ -168,7 +172,9 @@ class KexTest(unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) H = b"B16BF34DD10945EDE84E9C1EF24A14BFDC843389" - x = b"1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + x = ( + b"1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + ) self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -190,7 +196,9 @@ class KexTest(unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + x = ( + b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect @@ -224,7 +232,9 @@ class KexTest(unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + x = ( + b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect @@ -261,7 +271,9 @@ class KexTest(unittest.TestCase): msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) - x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + x = ( + b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect @@ -271,9 +283,13 @@ class KexTest(unittest.TestCase): msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + K = ( + 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + ) H = b"CE754197C21BF3452863B4F44D0B3951F12516EF" - x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + x = ( + b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + ) self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -296,7 +312,9 @@ class KexTest(unittest.TestCase): msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) - x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + x = ( + b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect @@ -306,9 +324,13 @@ class KexTest(unittest.TestCase): msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + K = ( + 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + ) H = b"B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B" - x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + x = ( + b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + ) self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -330,7 +352,9 @@ class KexTest(unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + x = ( + b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect @@ -364,7 +388,9 @@ class KexTest(unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + x = ( + b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect @@ -401,7 +427,9 @@ class KexTest(unittest.TestCase): msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) - x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + x = ( + b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect @@ -411,9 +439,13 @@ class KexTest(unittest.TestCase): msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + K = ( + 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + ) H = b"CCAC0497CF0ABA1DBF55E1A3995D17F4CC31824B0E8D95CDF8A06F169D050D80" - x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + x = ( + b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + ) self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -436,7 +468,9 @@ class KexTest(unittest.TestCase): msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) - x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + x = ( + b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" + ) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect @@ -446,16 +480,22 @@ class KexTest(unittest.TestCase): msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + K = ( + 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 + ) H = b"3DDD2AD840AD095E397BA4D0573972DC60F6461FD38A187CACA6615A5BC8ADBB" - x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + x = ( + b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" + ) self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_11_kex_nistp256_client(self): - K = 91610929826364598472338906427792435253694642563583721654249504912114314269754 + K = ( + 91610929826364598472338906427792435253694642563583721654249504912114314269754 + ) transport = FakeTransport() transport.server_mode = False kex = KexNistp256(transport) @@ -481,7 +521,9 @@ class KexTest(unittest.TestCase): self.assertTrue(transport._activated) def test_12_kex_nistp256_server(self): - K = 91610929826364598472338906427792435253694642563583721654249504912114314269754 + K = ( + 91610929826364598472338906427792435253694642563583721654249504912114314269754 + ) transport = FakeTransport() transport.server_mode = True kex = KexNistp256(transport) diff --git a/tests/test_message.py b/tests/test_message.py index e6b80f3b..c292f4e6 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -28,10 +28,19 @@ from paramiko.common import byte_chr, zero_byte class MessageTest(unittest.TestCase): - __a = b"\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01\x71\x00\x00\x00\x05\x68\x65\x6c\x6c\x6f\x00\x00\x03\xe8" + b"x" * 1000 - __b = b"\x01\x00\xf3\x00\x3f\x00\x00\x00\x10\x68\x75\x65\x79\x2c\x64\x65\x77\x65\x79\x2c\x6c\x6f\x75\x69\x65" - __c = b"\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7" - __d = b"\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x63\x61\x74\x00\x00\x00\x03\x61\x2c\x62" + __a = ( + b"\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01\x71\x00\x00\x00\x05\x68\x65\x6c\x6c\x6f\x00\x00\x03\xe8" + + b"x" * 1000 + ) + __b = ( + b"\x01\x00\xf3\x00\x3f\x00\x00\x00\x10\x68\x75\x65\x79\x2c\x64\x65\x77\x65\x79\x2c\x6c\x6f\x75\x69\x65" + ) + __c = ( + b"\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7" + ) + __d = ( + b"\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x63\x61\x74\x00\x00\x00\x03\x61\x2c\x62" + ) def test_1_encode(self): msg = Message() diff --git a/tests/test_pkey.py b/tests/test_pkey.py index 66bebc43..4bbfaba1 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -34,18 +34,30 @@ from .util import _support # from openssh's ssh-keygen -PUB_RSA = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEA049W6geFpmsljTwfvI1UmKWWJPNFI74+vNKTk4dmzkQY2yAMs6FhlvhlI8ysU4oj71ZsRYMecHbBbxdN79+JRFVYTKaLqjwGENeTd+yv4q+V2PvZv3fLnzApI3l7EJCqhWwJUHJ1jAkZzqDx0tyOL4uoZpww3nmE0kb3y21tH4c=" -PUB_DSS = "ssh-dss AAAAB3NzaC1kc3MAAACBAOeBpgNnfRzr/twmAQRu2XwWAp3CFtrVnug6s6fgwj/oLjYbVtjAy6pl/h0EKCWx2rf1IetyNsTxWrniA9I6HeDj65X1FyDkg6g8tvCnaNB8Xp/UUhuzHuGsMIipRxBxw9LF608EqZcj1E3ytktoW5B5OcjrkEoz3xG7C+rpIjYvAAAAFQDwz4UnmsGiSNu5iqjn3uTzwUpshwAAAIEAkxfFeY8P2wZpDjX0MimZl5wkoFQDL25cPzGBuB4OnB8NoUk/yjAHIIpEShw8V+LzouMK5CTJQo5+Ngw3qIch/WgRmMHy4kBq1SsXMjQCte1So6HBMvBPIW5SiMTmjCfZZiw4AYHK+B/JaOwaG9yRg2Ejg4Ok10+XFDxlqZo8Y+wAAACARmR7CCPjodxASvRbIyzaVpZoJ/Z6x7dAumV+ysrV1BVYd0lYukmnjO1kKBWApqpH1ve9XDQYN8zgxM4b16L21kpoWQnZtXrY3GZ4/it9kUgyB7+NwacIBlXa8cMDL7Q/69o0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=" -PUB_ECDSA_256 = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJSPZm3ZWkvk/Zx8WP+fZRZ5/NBBHnGQwR6uIC6XHGPDIHuWUzIjAwA0bzqkOUffEsbLe+uQgKl5kbc/L8KA/eo=" -PUB_ECDSA_384 = "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBBbGibQLW9AAZiGN2hEQxWYYoFaWKwN3PKSaDJSMqmIn1Z9sgRUuw8Y/w502OGvXL/wFk0i2z50l3pWZjD7gfMH7gX5TUiCzwrQkS+Hn1U2S9aF5WJp0NcIzYxXw2r4M2A==" -PUB_ECDSA_521 = "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACaOaFLZGuxa5AW16qj6VLypFbLrEWrt9AZUloCMefxO8bNLjK/O5g0rAVasar1TnyHE9qj4NwzANZASWjQNbc4MAG8vzqezFwLIn/kNyNTsXNfqEko9OgHZknlj2Z79dwTJcRAL4QLcT5aND0EHZLB2fAUDXiWIb2j4rg1mwPlBMiBXA==" +PUB_RSA = ( + "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEA049W6geFpmsljTwfvI1UmKWWJPNFI74+vNKTk4dmzkQY2yAMs6FhlvhlI8ysU4oj71ZsRYMecHbBbxdN79+JRFVYTKaLqjwGENeTd+yv4q+V2PvZv3fLnzApI3l7EJCqhWwJUHJ1jAkZzqDx0tyOL4uoZpww3nmE0kb3y21tH4c=" +) +PUB_DSS = ( + "ssh-dss AAAAB3NzaC1kc3MAAACBAOeBpgNnfRzr/twmAQRu2XwWAp3CFtrVnug6s6fgwj/oLjYbVtjAy6pl/h0EKCWx2rf1IetyNsTxWrniA9I6HeDj65X1FyDkg6g8tvCnaNB8Xp/UUhuzHuGsMIipRxBxw9LF608EqZcj1E3ytktoW5B5OcjrkEoz3xG7C+rpIjYvAAAAFQDwz4UnmsGiSNu5iqjn3uTzwUpshwAAAIEAkxfFeY8P2wZpDjX0MimZl5wkoFQDL25cPzGBuB4OnB8NoUk/yjAHIIpEShw8V+LzouMK5CTJQo5+Ngw3qIch/WgRmMHy4kBq1SsXMjQCte1So6HBMvBPIW5SiMTmjCfZZiw4AYHK+B/JaOwaG9yRg2Ejg4Ok10+XFDxlqZo8Y+wAAACARmR7CCPjodxASvRbIyzaVpZoJ/Z6x7dAumV+ysrV1BVYd0lYukmnjO1kKBWApqpH1ve9XDQYN8zgxM4b16L21kpoWQnZtXrY3GZ4/it9kUgyB7+NwacIBlXa8cMDL7Q/69o0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=" +) +PUB_ECDSA_256 = ( + "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJSPZm3ZWkvk/Zx8WP+fZRZ5/NBBHnGQwR6uIC6XHGPDIHuWUzIjAwA0bzqkOUffEsbLe+uQgKl5kbc/L8KA/eo=" +) +PUB_ECDSA_384 = ( + "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBBbGibQLW9AAZiGN2hEQxWYYoFaWKwN3PKSaDJSMqmIn1Z9sgRUuw8Y/w502OGvXL/wFk0i2z50l3pWZjD7gfMH7gX5TUiCzwrQkS+Hn1U2S9aF5WJp0NcIzYxXw2r4M2A==" +) +PUB_ECDSA_521 = ( + "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACaOaFLZGuxa5AW16qj6VLypFbLrEWrt9AZUloCMefxO8bNLjK/O5g0rAVasar1TnyHE9qj4NwzANZASWjQNbc4MAG8vzqezFwLIn/kNyNTsXNfqEko9OgHZknlj2Z79dwTJcRAL4QLcT5aND0EHZLB2fAUDXiWIb2j4rg1mwPlBMiBXA==" +) FINGER_RSA = "1024 60:73:38:44:cb:51:86:65:7f:de:da:a2:2b:5a:57:d5" FINGER_DSS = "1024 44:78:f0:b9:a2:3c:c5:18:20:09:ff:75:5b:c1:d2:6c" FINGER_ECDSA_256 = "256 25:19:eb:55:e6:a1:47:ff:4f:38:d2:75:6f:a5:d5:60" FINGER_ECDSA_384 = "384 c1:8d:a0:59:09:47:41:8e:a8:a6:07:01:29:23:b4:65" FINGER_ECDSA_521 = "521 44:58:22:52:12:33:16:0e:ce:0e:be:2c:7c:7e:cc:1e" -SIGNED_RSA = "20:d7:8a:31:21:cb:f7:92:12:f2:a4:89:37:f5:78:af:e6:16:b6:25:b9:97:3d:a2:cd:5f:ca:20:21:73:4c:ad:34:73:8f:20:77:28:e2:94:15:08:d8:91:40:7a:85:83:bf:18:37:95:dc:54:1a:9b:88:29:6c:73:ca:38:b4:04:f1:56:b9:f2:42:9d:52:1b:29:29:b4:4f:fd:c9:2d:af:47:d2:40:76:30:f3:63:45:0c:d9:1d:43:86:0f:1c:70:e2:93:12:34:f3:ac:c5:0a:2f:14:50:66:59:f1:88:ee:c1:4a:e9:d1:9c:4e:46:f0:0e:47:6f:38:74:f1:44:a8" +SIGNED_RSA = ( + "20:d7:8a:31:21:cb:f7:92:12:f2:a4:89:37:f5:78:af:e6:16:b6:25:b9:97:3d:a2:cd:5f:ca:20:21:73:4c:ad:34:73:8f:20:77:28:e2:94:15:08:d8:91:40:7a:85:83:bf:18:37:95:dc:54:1a:9b:88:29:6c:73:ca:38:b4:04:f1:56:b9:f2:42:9d:52:1b:29:29:b4:4f:fd:c9:2d:af:47:d2:40:76:30:f3:63:45:0c:d9:1d:43:86:0f:1c:70:e2:93:12:34:f3:ac:c5:0a:2f:14:50:66:59:f1:88:ee:c1:4a:e9:d1:9c:4e:46:f0:0e:47:6f:38:74:f1:44:a8" +) RSA_PRIVATE_OUT = """\ -----BEGIN RSA PRIVATE KEY----- @@ -109,8 +121,12 @@ L4QLcT5aND0EHZLB2fAUDXiWIb2j4rg1mwPlBMiBXA== x1234 = b"\x01\x02\x03\x04" -TEST_KEY_BYTESTR_2 = "\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01#\x00\x00\x00\x81\x00\xd3\x8fV\xea\x07\x85\xa6k%\x8d<\x1f\xbc\x8dT\x98\xa5\x96$\xf3E#\xbe>\xbc\xd2\x93\x93\x87f\xceD\x18\xdb \x0c\xb3\xa1a\x96\xf8e#\xcc\xacS\x8a#\xefVlE\x83\x1epv\xc1o\x17M\xef\xdf\x89DUXL\xa6\x8b\xaa<\x06\x10\xd7\x93w\xec\xaf\xe2\xaf\x95\xd8\xfb\xd9\xbfw\xcb\x9f0)#y{\x10\x90\xaa\x85l\tPru\x8c\t\x19\xce\xa0\xf1\xd2\xdc\x8e/\x8b\xa8f\x9c0\xdey\x84\xd2F\xf7\xcbmm\x1f\x87" -TEST_KEY_BYTESTR_3 = "\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01#\x00\x00\x00\x00ӏV\x07k%<\x1fT$E#>ғfD\x18 \x0cae#̬S#VlE\x1epvo\x17M߉DUXL<\x06\x10דw\u2bd5ٿw˟0)#y{\x10l\tPru\t\x19Π\u070e/f0yFmm\x1f" +TEST_KEY_BYTESTR_2 = ( + "\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01#\x00\x00\x00\x81\x00\xd3\x8fV\xea\x07\x85\xa6k%\x8d<\x1f\xbc\x8dT\x98\xa5\x96$\xf3E#\xbe>\xbc\xd2\x93\x93\x87f\xceD\x18\xdb \x0c\xb3\xa1a\x96\xf8e#\xcc\xacS\x8a#\xefVlE\x83\x1epv\xc1o\x17M\xef\xdf\x89DUXL\xa6\x8b\xaa<\x06\x10\xd7\x93w\xec\xaf\xe2\xaf\x95\xd8\xfb\xd9\xbfw\xcb\x9f0)#y{\x10\x90\xaa\x85l\tPru\x8c\t\x19\xce\xa0\xf1\xd2\xdc\x8e/\x8b\xa8f\x9c0\xdey\x84\xd2F\xf7\xcbmm\x1f\x87" +) +TEST_KEY_BYTESTR_3 = ( + "\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01#\x00\x00\x00\x00ӏV\x07k%<\x1fT$E#>ғfD\x18 \x0cae#̬S#VlE\x1epvo\x17M߉DUXL<\x06\x10דw\u2bd5ٿw˟0)#y{\x10l\tPru\t\x19Π\u070e/f0yFmm\x1f" +) class KeyTest(unittest.TestCase): @@ -134,7 +150,9 @@ class KeyTest(unittest.TestCase): def test_1_generate_key_bytes(self): key = util.generate_key_bytes(md5, x1234, "happy birthday", 30) - exp = b"\x61\xE1\xF2\x72\xF4\xC1\xC4\x56\x15\x86\xBD\x32\x24\x98\xC0\xE9\x24\x67\x27\x80\xF4\x7B\xB3\x7D\xDA\x7D\x54\x01\x9E\x64" + exp = ( + b"\x61\xE1\xF2\x72\xF4\xC1\xC4\x56\x15\x86\xBD\x32\x24\x98\xC0\xE9\x24\x67\x27\x80\xF4\x7B\xB3\x7D\xDA\x7D\x54\x01\x9E\x64" + ) self.assertEqual(exp, key) def test_2_load_rsa(self): diff --git a/tests/test_sftp.py b/tests/test_sftp.py index a03961d6..576b69b7 100644 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -424,8 +424,8 @@ class TestSFTP(object): assert sftp.stat(sftp.FOLDER + "/link.txt").st_size == 9 # the sftp server may be hiding extra path members from us, so the # length may be longer than we expect: - assert ( - sftp.lstat(sftp.FOLDER + "/link2.txt").st_size >= len(abs_path) + assert sftp.lstat(sftp.FOLDER + "/link2.txt").st_size >= len( + abs_path ) assert sftp.stat(sftp.FOLDER + "/link2.txt").st_size == 9 assert sftp.stat(sftp.FOLDER + "/original.txt").st_size == 9 @@ -786,7 +786,7 @@ class TestSFTP(object): with sftp.open("%s/write_memoryview" % sftp.FOLDER, "wb") as f: view = memoryview(data) for offset in range(0, len(data), 8): - f.write(view[offset:offset + 8]) + f.write(view[offset : offset + 8]) with sftp.open("%s/write_memoryview" % sftp.FOLDER, "rb") as f: assert f.read() == data diff --git a/tests/test_sftp_big.py b/tests/test_sftp_big.py index 7f74d5f6..97c0eb90 100644 --- a/tests/test_sftp_big.py +++ b/tests/test_sftp_big.py @@ -70,7 +70,7 @@ class TestBigSFTP(object): """ write a 1MB file with no buffering. """ - kblob = (1024 * b"x") + kblob = 1024 * b"x" start = time.time() try: with sftp.open("%s/hongry.txt" % sftp.FOLDER, "w") as f: @@ -133,7 +133,7 @@ class TestBigSFTP(object): chunk = size - n data = f.read(chunk) offset = n % 1024 - assert data == k2blob[offset:offset + chunk] + assert data == k2blob[offset : offset + chunk] n += chunk end = time.time() @@ -174,7 +174,7 @@ class TestBigSFTP(object): f.seek(offset) data = f.read(chunk) n_offset = offset % 1024 - assert data == k2blob[n_offset:n_offset + chunk] + assert data == k2blob[n_offset : n_offset + chunk] offset += chunk end = time.time() sys.stderr.write("%ds " % round(end - start)) @@ -215,7 +215,7 @@ class TestBigSFTP(object): for i in range(len(readv_list)): offset = readv_list[i][0] n_offset = offset % 1024 - assert next(ret) == k2blob[n_offset:n_offset + chunk] + assert next(ret) == k2blob[n_offset : n_offset + chunk] end = time.time() sys.stderr.write("%ds " % round(end - start)) finally: @@ -226,7 +226,7 @@ class TestBigSFTP(object): prefetch a 1MB file a bunch of times, discarding the file object without using it, to verify that paramiko doesn't get confused. """ - kblob = (1024 * b"x") + kblob = 1024 * b"x" try: with sftp.open("%s/hongry.txt" % sftp.FOLDER, "w") as f: f.set_pipelined(True) @@ -290,7 +290,7 @@ class TestBigSFTP(object): for data in f.readv(chunks): offset = base_offset % 1024 assert chunk_size == len(data) - assert k2blob[offset:offset + chunk_size] == data + assert k2blob[offset : offset + chunk_size] == data base_offset += chunk_size sys.stderr.write(" ") @@ -330,7 +330,7 @@ class TestBigSFTP(object): """ write a 1MB file, with no linefeeds, and a big buffer. """ - mblob = (1024 * 1024 * "x") + mblob = 1024 * 1024 * "x" try: with sftp.open( "%s/hongry.txt" % sftp.FOLDER, "w", 128 * 1024 @@ -349,7 +349,7 @@ class TestBigSFTP(object): """ t = sftp.sock.get_transport() t.packetizer.REKEY_BYTES = 512 * 1024 - k32blob = (32 * 1024 * "x") + k32blob = 32 * 1024 * "x" try: with sftp.open( "%s/hongry.txt" % sftp.FOLDER, "w", 128 * 1024 diff --git a/tests/test_ssh_gss.py b/tests/test_ssh_gss.py index 1e08b361..cee6ce89 100644 --- a/tests/test_ssh_gss.py +++ b/tests/test_ssh_gss.py @@ -152,7 +152,9 @@ class GSSAuthTest(unittest.TestCase): """ Failed gssapi-with-mic auth doesn't prevent subsequent key auth from succeeding """ - self.hostname = "this_host_does_not_exists_and_causes_a_GSSAPI-exception" + self.hostname = ( + "this_host_does_not_exists_and_causes_a_GSSAPI-exception" + ) self._test_connection( key_filename=[_support("test_rsa.key")], allow_agent=False, diff --git a/tests/test_transport.py b/tests/test_transport.py index e09c5e92..c05d6781 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -207,8 +207,12 @@ class TransportTest(unittest.TestCase): o.compression = o.compression def test_2_compute_key(self): - self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 - self.tc.H = b"\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3" + self.tc.K = ( + 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 + ) + self.tc.H = ( + b"\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3" + ) self.tc.session_id = self.tc.H key = self.tc._compute_key("C", 32) self.assertEqual( @@ -793,7 +797,9 @@ class TransportTest(unittest.TestCase): # sends MSG_CHANNEL_WINDOW_ADJUST whenever it receives an initial # MSG_KEXINIT. This is used to simulate the effect of network latency # on a real MSG_CHANNEL_WINDOW_ADJUST message. - self.tc._handler_table = self.tc._handler_table.copy() # copy per-class dictionary + self.tc._handler_table = ( + self.tc._handler_table.copy() + ) # copy per-class dictionary _negotiate_keys = self.tc._handler_table[MSG_KEXINIT] def _negotiate_keys_wrapper(self, m): @@ -989,7 +995,7 @@ class TransportTest(unittest.TestCase): sent = 0 view = memoryview(data) while sent < len(view): - sent += chan.send(view[sent:sent + 8]) + sent += chan.send(view[sent : sent + 8]) self.assertEqual(sfile.read(len(data)), data) # sendall() accepts a memoryview instance diff --git a/tests/test_util.py b/tests/test_util.py index 6431b9c1..23b2e86a 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -117,7 +117,8 @@ class UtilTest(unittest.TestCase): { "host": ["*"], "config": { - "identityfile": ["~/.ssh/id_rsa"], "user": "robey" + "identityfile": ["~/.ssh/id_rsa"], + "user": "robey", }, }, { -- cgit v1.2.3