| 1 |
# Copyright (C) 2003-2009 Robey Pointer <[email protected]> |
| 2 |
# |
| 3 |
# This file is part of paramiko. |
| 4 |
# |
| 5 |
# Paramiko is free software; you can redistribute it and/or modify it under the |
| 6 |
# terms of the GNU Lesser General Public License as published by the Free |
| 7 |
# Software Foundation; either version 2.1 of the License, or (at your option) |
| 8 |
# any later version. |
| 9 |
# |
| 10 |
# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY |
| 11 |
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR |
| 12 |
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more |
| 13 |
# details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU Lesser General Public License |
| 16 |
# along with Paramiko; if not, write to the Free Software Foundation, Inc., |
| 17 |
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 18 |
|
| 19 |
""" |
| 20 |
Some unit tests for the ssh2 protocol in Transport. |
| 21 |
""" |
| 22 |
|
| 23 |
import itertools |
| 24 |
import random |
| 25 |
import select |
| 26 |
import socket |
| 27 |
import threading |
| 28 |
import time |
| 29 |
import unittest |
| 30 |
from binascii import hexlify |
| 31 |
from unittest.mock import Mock |
| 32 |
|
| 33 |
from pytest import mark, raises |
| 34 |
|
| 35 |
from paramiko import ( |
| 36 |
OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED, |
| 37 |
AuthHandler, |
| 38 |
ChannelException, |
| 39 |
IncompatiblePeer, |
| 40 |
MessageOrderError, |
| 41 |
Packetizer, |
| 42 |
RSAKey, |
| 43 |
SecurityOptions, |
| 44 |
ServiceRequestingTransport, |
| 45 |
SSHException, |
| 46 |
Transport, |
| 47 |
) |
| 48 |
from paramiko.auth_handler import AuthOnlyHandler |
| 49 |
from paramiko.common import ( |
| 50 |
DEFAULT_MAX_PACKET_SIZE, |
| 51 |
DEFAULT_WINDOW_SIZE, |
| 52 |
MAX_WINDOW_SIZE, |
| 53 |
MIN_PACKET_SIZE, |
| 54 |
MIN_WINDOW_SIZE, |
| 55 |
MSG_CHANNEL_OPEN, |
| 56 |
MSG_DEBUG, |
| 57 |
MSG_IGNORE, |
| 58 |
MSG_KEXINIT, |
| 59 |
MSG_UNIMPLEMENTED, |
| 60 |
MSG_USERAUTH_SUCCESS, |
| 61 |
byte_chr, |
| 62 |
cMSG_CHANNEL_WINDOW_ADJUST, |
| 63 |
cMSG_UNIMPLEMENTED, |
| 64 |
) |
| 65 |
from paramiko.message import Message |
| 66 |
|
| 67 |
from ._loop import LoopSocket |
| 68 |
from ._util import ( |
| 69 |
TestServer as NullServer, |
| 70 |
) |
| 71 |
from ._util import ( |
| 72 |
_support, |
| 73 |
needs_builtin, |
| 74 |
server, |
| 75 |
slow, |
| 76 |
) |
| 77 |
|
| 78 |
LONG_BANNER = """\ |
| 79 |
Welcome to the super-fun-land BBS, where our MOTD is the primary thing we |
| 80 |
provide. All rights reserved. Offer void in Tennessee. Stunt drivers were |
| 81 |
used. Do not attempt at home. Some restrictions apply. |
| 82 |
|
| 83 |
Happy birthday to Commie the cat! |
| 84 |
|
| 85 |
Note: An SSH banner may eventually appear. |
| 86 |
|
| 87 |
Maybe. |
| 88 |
""" |
| 89 |
|
| 90 |
# Faux 'packet type' we do not implement and are unlikely ever to (but which is |
| 91 |
# technically "within spec" re RFC 4251 |
| 92 |
MSG_FUGGEDABOUTIT = 253 |
| 93 |
|
| 94 |
|
| 95 |
class TransportTest(unittest.TestCase): |
| 96 |
# TODO: this can get nuked once ServiceRequestingTransport becomes the |
| 97 |
# only Transport, as it has this baked in. |
| 98 |
_auth_handler_class = AuthHandler |
| 99 |
|
| 100 |
def setUp(self): |
| 101 |
self.socks = LoopSocket() |
| 102 |
self.sockc = LoopSocket() |
| 103 |
self.sockc.link(self.socks) |
| 104 |
self.tc = Transport(self.sockc) |
| 105 |
self.ts = Transport(self.socks) |
| 106 |
|
| 107 |
def tearDown(self): |
| 108 |
self.tc.close() |
| 109 |
self.ts.close() |
| 110 |
self.socks.close() |
| 111 |
self.sockc.close() |
| 112 |
|
| 113 |
# TODO: unify with newer contextmanager |
| 114 |
def setup_test_server( |
| 115 |
self, client_options=None, server_options=None, connect_kwargs=None |
| 116 |
): |
| 117 |
host_key = RSAKey.from_private_key_file(_support("rsa.key")) |
| 118 |
public_host_key = RSAKey(data=host_key.asbytes()) |
| 119 |
self.ts.add_server_key(host_key) |
| 120 |
|
| 121 |
if client_options is not None: |
| 122 |
client_options(self.tc.get_security_options()) |
| 123 |
if server_options is not None: |
| 124 |
server_options(self.ts.get_security_options()) |
| 125 |
|
| 126 |
event = threading.Event() |
| 127 |
self.server = NullServer() |
| 128 |
self.assertTrue(not event.is_set()) |
| 129 |
self.ts.start_server(event, self.server) |
| 130 |
if connect_kwargs is None: |
| 131 |
connect_kwargs = dict( |
| 132 |
hostkey=public_host_key, |
| 133 |
username="slowdive", |
| 134 |
password="pygmalion", |
| 135 |
) |
| 136 |
self.tc.connect(**connect_kwargs) |
| 137 |
event.wait(1.0) |
| 138 |
self.assertTrue(event.is_set()) |
| 139 |
self.assertTrue(self.ts.is_active()) |
| 140 |
|
| 141 |
def test_security_options(self): |
| 142 |
o = self.tc.get_security_options() |
| 143 |
self.assertEqual(type(o), SecurityOptions) |
| 144 |
self.assertTrue(("aes256-cbc", "aes192-cbc") != o.ciphers) |
| 145 |
o.ciphers = ("aes256-cbc", "aes192-cbc") |
| 146 |
self.assertEqual(("aes256-cbc", "aes192-cbc"), o.ciphers) |
| 147 |
try: |
| 148 |
o.ciphers = ("aes256-cbc", "made-up-cipher") |
| 149 |
self.assertTrue(False) |
| 150 |
except ValueError: |
| 151 |
pass |
| 152 |
try: |
| 153 |
o.ciphers = 23 |
| 154 |
self.assertTrue(False) |
| 155 |
except TypeError: |
| 156 |
pass |
| 157 |
|
| 158 |
def testb_security_options_reset(self): |
| 159 |
o = self.tc.get_security_options() |
| 160 |
# should not throw any exceptions |
| 161 |
o.ciphers = o.ciphers |
| 162 |
o.digests = o.digests |
| 163 |
o.key_types = o.key_types |
| 164 |
o.kex = o.kex |
| 165 |
o.compression = o.compression |
| 166 |
|
| 167 |
def test_compute_key(self): |
| 168 |
self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 # noqa |
| 169 |
self.tc.H = b"\x0c\x83\x07\xcd\xe6\x85\x6f\xf3\x0b\xa9\x36\x84\xeb\x0f\x04\xc2\x52\x0e\x9e\xd3" # noqa |
| 170 |
self.tc.session_id = self.tc.H |
| 171 |
key = self.tc._compute_key("C", 32) |
| 172 |
self.assertEqual( |
| 173 |
b"207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995", # noqa |
| 174 |
hexlify(key).upper(), |
| 175 |
) |
| 176 |
|
| 177 |
def test_simple(self): |
| 178 |
""" |
| 179 |
verify that we can establish an ssh link with ourselves across the |
| 180 |
loopback sockets. this is hardly "simple" but it's simpler than the |
| 181 |
later tests. :) |
| 182 |
""" |
| 183 |
host_key = RSAKey.from_private_key_file(_support("rsa.key")) |
| 184 |
public_host_key = RSAKey(data=host_key.asbytes()) |
| 185 |
self.ts.add_server_key(host_key) |
| 186 |
event = threading.Event() |
| 187 |
server = NullServer() |
| 188 |
self.assertTrue(not event.is_set()) |
| 189 |
self.assertEqual(None, self.tc.get_username()) |
| 190 |
self.assertEqual(None, self.ts.get_username()) |
| 191 |
self.assertEqual(False, self.tc.is_authenticated()) |
| 192 |
self.assertEqual(False, self.ts.is_authenticated()) |
| 193 |
self.ts.start_server(event, server) |
| 194 |
self.tc.connect( |
| 195 |
hostkey=public_host_key, username="slowdive", password="pygmalion" |
| 196 |
) |
| 197 |
event.wait(1.0) |
| 198 |
self.assertTrue(event.is_set()) |
| 199 |
self.assertTrue(self.ts.is_active()) |
| 200 |
self.assertEqual("slowdive", self.tc.get_username()) |
| 201 |
self.assertEqual("slowdive", self.ts.get_username()) |
| 202 |
self.assertEqual(True, self.tc.is_authenticated()) |
| 203 |
self.assertEqual(True, self.ts.is_authenticated()) |
| 204 |
|
| 205 |
def test_long_banner(self): |
| 206 |
""" |
| 207 |
verify that a long banner doesn't mess up the handshake. |
| 208 |
""" |
| 209 |
host_key = RSAKey.from_private_key_file(_support("rsa.key")) |
| 210 |
public_host_key = RSAKey(data=host_key.asbytes()) |
| 211 |
self.ts.add_server_key(host_key) |
| 212 |
event = threading.Event() |
| 213 |
server = NullServer() |
| 214 |
self.assertTrue(not event.is_set()) |
| 215 |
self.socks.send(LONG_BANNER) |
| 216 |
self.ts.start_server(event, server) |
| 217 |
self.tc.connect( |
| 218 |
hostkey=public_host_key, username="slowdive", password="pygmalion" |
| 219 |
) |
| 220 |
event.wait(1.0) |
| 221 |
self.assertTrue(event.is_set()) |
| 222 |
self.assertTrue(self.ts.is_active()) |
| 223 |
|
| 224 |
def test_special(self): |
| 225 |
""" |
| 226 |
verify that the client can demand odd handshake settings, and can |
| 227 |
renegotiate keys in mid-stream. |
| 228 |
""" |
| 229 |
|
| 230 |
def force_algorithms(options): |
| 231 |
options.ciphers = ("aes256-cbc",) |
| 232 |
options.digests = ("hmac-md5-96",) |
| 233 |
|
| 234 |
self.setup_test_server(client_options=force_algorithms) |
| 235 |
self.assertEqual("aes256-cbc", self.tc.local_cipher) |
| 236 |
self.assertEqual("aes256-cbc", self.tc.remote_cipher) |
| 237 |
self.assertEqual(12, self.tc.packetizer.get_mac_size_out()) |
| 238 |
self.assertEqual(12, self.tc.packetizer.get_mac_size_in()) |
| 239 |
|
| 240 |
self.tc.send_ignore(1024) |
| 241 |
self.tc.renegotiate_keys() |
| 242 |
self.ts.send_ignore(1024) |
| 243 |
|
| 244 |
@slow |
| 245 |
def test_keepalive(self): |
| 246 |
""" |
| 247 |
verify that the keepalive will be sent. |
| 248 |
""" |
| 249 |
self.setup_test_server() |
| 250 |
self.assertEqual(None, getattr(self.server, "_global_request", None)) |
| 251 |
self.tc.set_keepalive(1) |
| 252 |
time.sleep(2) |
| 253 |
self.assertEqual("[email protected]", self.server._global_request) |
| 254 |
|
| 255 |
def test_exec_command(self): |
| 256 |
""" |
| 257 |
verify that exec_command() does something reasonable. |
| 258 |
""" |
| 259 |
self.setup_test_server() |
| 260 |
|
| 261 |
chan = self.tc.open_session() |
| 262 |
schan = self.ts.accept(1.0) |
| 263 |
try: |
| 264 |
chan.exec_command( |
| 265 |
b"command contains \xfc and is not a valid UTF-8 string" |
| 266 |
) |
| 267 |
self.assertTrue(False) |
| 268 |
except SSHException: |
| 269 |
pass |
| 270 |
|
| 271 |
chan = self.tc.open_session() |
| 272 |
chan.exec_command("yes") |
| 273 |
schan = self.ts.accept(1.0) |
| 274 |
schan.send("Hello there.\n") |
| 275 |
schan.send_stderr("This is on stderr.\n") |
| 276 |
schan.close() |
| 277 |
|
| 278 |
f = chan.makefile() |
| 279 |
self.assertEqual("Hello there.\n", f.readline()) |
| 280 |
self.assertEqual("", f.readline()) |
| 281 |
f = chan.makefile_stderr() |
| 282 |
self.assertEqual("This is on stderr.\n", f.readline()) |
| 283 |
self.assertEqual("", f.readline()) |
| 284 |
|
| 285 |
# now try it with combined stdout/stderr |
| 286 |
chan = self.tc.open_session() |
| 287 |
chan.exec_command("yes") |
| 288 |
schan = self.ts.accept(1.0) |
| 289 |
schan.send("Hello there.\n") |
| 290 |
schan.send_stderr("This is on stderr.\n") |
| 291 |
schan.close() |
| 292 |
|
| 293 |
chan.set_combine_stderr(True) |
| 294 |
f = chan.makefile() |
| 295 |
self.assertEqual("Hello there.\n", f.readline()) |
| 296 |
self.assertEqual("This is on stderr.\n", f.readline()) |
| 297 |
self.assertEqual("", f.readline()) |
| 298 |
|
| 299 |
def test_channel_can_be_used_as_context_manager(self): |
| 300 |
""" |
| 301 |
verify that exec_command() does something reasonable. |
| 302 |
""" |
| 303 |
self.setup_test_server() |
| 304 |
|
| 305 |
with self.tc.open_session() as chan: |
| 306 |
with self.ts.accept(1.0) as schan: |
| 307 |
chan.exec_command("yes") |
| 308 |
schan.send("Hello there.\n") |
| 309 |
schan.close() |
| 310 |
|
| 311 |
f = chan.makefile() |
| 312 |
self.assertEqual("Hello there.\n", f.readline()) |
| 313 |
self.assertEqual("", f.readline()) |
| 314 |
|
| 315 |
def test_invoke_shell(self): |
| 316 |
""" |
| 317 |
verify that invoke_shell() does something reasonable. |
| 318 |
""" |
| 319 |
self.setup_test_server() |
| 320 |
chan = self.tc.open_session() |
| 321 |
chan.invoke_shell() |
| 322 |
schan = self.ts.accept(1.0) |
| 323 |
chan.send("communist j. cat\n") |
| 324 |
f = schan.makefile() |
| 325 |
self.assertEqual("communist j. cat\n", f.readline()) |
| 326 |
chan.close() |
| 327 |
self.assertEqual("", f.readline()) |
| 328 |
|
| 329 |
def test_channel_exception(self): |
| 330 |
""" |
| 331 |
verify that ChannelException is thrown for a bad open-channel request. |
| 332 |
""" |
| 333 |
self.setup_test_server() |
| 334 |
try: |
| 335 |
self.tc.open_channel("bogus") |
| 336 |
self.fail("expected exception") |
| 337 |
except ChannelException as e: |
| 338 |
self.assertTrue(e.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) |
| 339 |
|
| 340 |
def test_exit_status(self): |
| 341 |
""" |
| 342 |
verify that get_exit_status() works. |
| 343 |
""" |
| 344 |
self.setup_test_server() |
| 345 |
|
| 346 |
chan = self.tc.open_session() |
| 347 |
schan = self.ts.accept(1.0) |
| 348 |
chan.exec_command("yes") |
| 349 |
schan.send("Hello there.\n") |
| 350 |
self.assertTrue(not chan.exit_status_ready()) |
| 351 |
# trigger an EOF |
| 352 |
schan.shutdown_read() |
| 353 |
schan.shutdown_write() |
| 354 |
schan.send_exit_status(23) |
| 355 |
schan.close() |
| 356 |
|
| 357 |
f = chan.makefile() |
| 358 |
self.assertEqual("Hello there.\n", f.readline()) |
| 359 |
self.assertEqual("", f.readline()) |
| 360 |
count = 0 |
| 361 |
while not chan.exit_status_ready(): |
| 362 |
time.sleep(0.1) |
| 363 |
count += 1 |
| 364 |
if count > 50: |
| 365 |
raise Exception("timeout") |
| 366 |
self.assertEqual(23, chan.recv_exit_status()) |
| 367 |
chan.close() |
| 368 |
|
| 369 |
def test_select(self): |
| 370 |
""" |
| 371 |
verify that select() on a channel works. |
| 372 |
""" |
| 373 |
self.setup_test_server() |
| 374 |
chan = self.tc.open_session() |
| 375 |
chan.invoke_shell() |
| 376 |
schan = self.ts.accept(1.0) |
| 377 |
|
| 378 |
# nothing should be ready |
| 379 |
r, w, e = select.select([chan], [], [], 0.1) |
| 380 |
self.assertEqual([], r) |
| 381 |
self.assertEqual([], w) |
| 382 |
self.assertEqual([], e) |
| 383 |
|
| 384 |
schan.send("hello\n") |
| 385 |
|
| 386 |
# something should be ready now (give it 1 second to appear) |
| 387 |
for i in range(10): |
| 388 |
r, w, e = select.select([chan], [], [], 0.1) |
| 389 |
if chan in r: |
| 390 |
break |
| 391 |
time.sleep(0.1) |
| 392 |
self.assertEqual([chan], r) |
| 393 |
self.assertEqual([], w) |
| 394 |
self.assertEqual([], e) |
| 395 |
|
| 396 |
self.assertEqual(b"hello\n", chan.recv(6)) |
| 397 |
|
| 398 |
# and, should be dead again now |
| 399 |
r, w, e = select.select([chan], [], [], 0.1) |
| 400 |
self.assertEqual([], r) |
| 401 |
self.assertEqual([], w) |
| 402 |
self.assertEqual([], e) |
| 403 |
|
| 404 |
schan.close() |
| 405 |
|
| 406 |
# detect eof? |
| 407 |
for i in range(10): |
| 408 |
r, w, e = select.select([chan], [], [], 0.1) |
| 409 |
if chan in r: |
| 410 |
break |
| 411 |
time.sleep(0.1) |
| 412 |
self.assertEqual([chan], r) |
| 413 |
self.assertEqual([], w) |
| 414 |
self.assertEqual([], e) |
| 415 |
self.assertEqual(b"", chan.recv(16)) |
| 416 |
|
| 417 |
# make sure the pipe is still open for now... |
| 418 |
p = chan._pipe |
| 419 |
self.assertEqual(False, p._closed) |
| 420 |
chan.close() |
| 421 |
# ...and now is closed. |
| 422 |
self.assertEqual(True, p._closed) |
| 423 |
|
| 424 |
def test_renegotiate(self): |
| 425 |
""" |
| 426 |
verify that a transport can correctly renegotiate mid-stream. |
| 427 |
""" |
| 428 |
self.setup_test_server() |
| 429 |
self.tc.packetizer.REKEY_BYTES = 16384 |
| 430 |
chan = self.tc.open_session() |
| 431 |
chan.exec_command("yes") |
| 432 |
schan = self.ts.accept(1.0) |
| 433 |
|
| 434 |
self.assertEqual(self.tc.H, self.tc.session_id) |
| 435 |
for i in range(20): |
| 436 |
chan.send("x" * 1024) |
| 437 |
chan.close() |
| 438 |
|
| 439 |
# allow a few seconds for the rekeying to complete |
| 440 |
for i in range(50): |
| 441 |
if self.tc.H != self.tc.session_id: |
| 442 |
break |
| 443 |
time.sleep(0.1) |
| 444 |
self.assertNotEqual(self.tc.H, self.tc.session_id) |
| 445 |
|
| 446 |
schan.close() |
| 447 |
|
| 448 |
def test_compression(self): |
| 449 |
""" |
| 450 |
verify that zlib compression is basically working. |
| 451 |
""" |
| 452 |
|
| 453 |
def force_compression(o): |
| 454 |
o.compression = ("zlib",) |
| 455 |
|
| 456 |
self.setup_test_server(force_compression, force_compression) |
| 457 |
chan = self.tc.open_session() |
| 458 |
chan.exec_command("yes") |
| 459 |
schan = self.ts.accept(1.0) |
| 460 |
|
| 461 |
bytes = self.tc.packetizer._Packetizer__sent_bytes |
| 462 |
chan.send("x" * 1024) |
| 463 |
bytes2 = self.tc.packetizer._Packetizer__sent_bytes |
| 464 |
block_size = self.tc._cipher_info[self.tc.local_cipher]["block-size"] |
| 465 |
mac_size = self.tc._mac_info[self.tc.local_mac]["size"] |
| 466 |
# tests show this is actually compressed to *52 bytes*! including |
| 467 |
# packet overhead! nice!! :) |
| 468 |
self.assertTrue(bytes2 - bytes < 1024) |
| 469 |
self.assertEqual(16 + block_size + mac_size, bytes2 - bytes) |
| 470 |
|
| 471 |
chan.close() |
| 472 |
schan.close() |
| 473 |
|
| 474 |
def test_x11(self): |
| 475 |
""" |
| 476 |
verify that an x11 port can be requested and opened. |
| 477 |
""" |
| 478 |
self.setup_test_server() |
| 479 |
chan = self.tc.open_session() |
| 480 |
chan.exec_command("yes") |
| 481 |
schan = self.ts.accept(1.0) |
| 482 |
|
| 483 |
requested = [] |
| 484 |
|
| 485 |
def handler(c, addr_port): |
| 486 |
addr, port = addr_port |
| 487 |
requested.append((addr, port)) |
| 488 |
self.tc._queue_incoming_channel(c) |
| 489 |
|
| 490 |
self.assertEqual( |
| 491 |
None, getattr(self.server, "_x11_screen_number", None) |
| 492 |
) |
| 493 |
cookie = chan.request_x11(0, single_connection=True, handler=handler) |
| 494 |
self.assertEqual(0, self.server._x11_screen_number) |
| 495 |
self.assertEqual("MIT-MAGIC-COOKIE-1", self.server._x11_auth_protocol) |
| 496 |
self.assertEqual(cookie, self.server._x11_auth_cookie) |
| 497 |
self.assertEqual(True, self.server._x11_single_connection) |
| 498 |
|
| 499 |
x11_server = self.ts.open_x11_channel(("localhost", 6093)) |
| 500 |
x11_client = self.tc.accept() |
| 501 |
self.assertEqual("localhost", requested[0][0]) |
| 502 |
self.assertEqual(6093, requested[0][1]) |
| 503 |
|
| 504 |
x11_server.send("hello") |
| 505 |
self.assertEqual(b"hello", x11_client.recv(5)) |
| 506 |
|
| 507 |
x11_server.close() |
| 508 |
x11_client.close() |
| 509 |
chan.close() |
| 510 |
schan.close() |
| 511 |
|
| 512 |
def test_reverse_port_forwarding(self): |
| 513 |
""" |
| 514 |
verify that a client can ask the server to open a reverse port for |
| 515 |
forwarding. |
| 516 |
""" |
| 517 |
self.setup_test_server() |
| 518 |
chan = self.tc.open_session() |
| 519 |
chan.exec_command("yes") |
| 520 |
self.ts.accept(1.0) |
| 521 |
|
| 522 |
requested = [] |
| 523 |
|
| 524 |
def handler(c, origin_addr_port, server_addr_port): |
| 525 |
requested.append(origin_addr_port) |
| 526 |
requested.append(server_addr_port) |
| 527 |
self.tc._queue_incoming_channel(c) |
| 528 |
|
| 529 |
port = self.tc.request_port_forward("127.0.0.1", 0, handler) |
| 530 |
self.assertEqual(port, self.server._listen.getsockname()[1]) |
| 531 |
|
| 532 |
cs = socket.socket() |
| 533 |
cs.connect(("127.0.0.1", port)) |
| 534 |
ss, _ = self.server._listen.accept() |
| 535 |
sch = self.ts.open_forwarded_tcpip_channel( |
| 536 |
ss.getsockname(), ss.getpeername() |
| 537 |
) |
| 538 |
cch = self.tc.accept() |
| 539 |
|
| 540 |
sch.send("hello") |
| 541 |
self.assertEqual(b"hello", cch.recv(5)) |
| 542 |
sch.close() |
| 543 |
cch.close() |
| 544 |
ss.close() |
| 545 |
cs.close() |
| 546 |
|
| 547 |
# now cancel it. |
| 548 |
self.tc.cancel_port_forward("127.0.0.1", port) |
| 549 |
self.assertTrue(self.server._listen is None) |
| 550 |
|
| 551 |
def test_port_forwarding(self): |
| 552 |
""" |
| 553 |
verify that a client can forward new connections from a locally- |
| 554 |
forwarded port. |
| 555 |
""" |
| 556 |
self.setup_test_server() |
| 557 |
chan = self.tc.open_session() |
| 558 |
chan.exec_command("yes") |
| 559 |
self.ts.accept(1.0) |
| 560 |
|
| 561 |
# open a port on the "server" that the client will ask to forward to. |
| 562 |
greeting_server = socket.socket() |
| 563 |
greeting_server.bind(("127.0.0.1", 0)) |
| 564 |
greeting_server.listen(1) |
| 565 |
greeting_port = greeting_server.getsockname()[1] |
| 566 |
|
| 567 |
cs = self.tc.open_channel( |
| 568 |
"direct-tcpip", ("127.0.0.1", greeting_port), ("", 9000) |
| 569 |
) |
| 570 |
sch = self.ts.accept(1.0) |
| 571 |
cch = socket.socket() |
| 572 |
cch.connect(self.server._tcpip_dest) |
| 573 |
|
| 574 |
ss, _ = greeting_server.accept() |
| 575 |
ss.send(b"Hello!\n") |
| 576 |
ss.close() |
| 577 |
sch.send(cch.recv(8192)) |
| 578 |
sch.close() |
| 579 |
|
| 580 |
self.assertEqual(b"Hello!\n", cs.recv(7)) |
| 581 |
cs.close() |
| 582 |
|
| 583 |
def test_stderr_select(self): |
| 584 |
""" |
| 585 |
verify that select() on a channel works even if only stderr is |
| 586 |
receiving data. |
| 587 |
""" |
| 588 |
self.setup_test_server() |
| 589 |
chan = self.tc.open_session() |
| 590 |
chan.invoke_shell() |
| 591 |
schan = self.ts.accept(1.0) |
| 592 |
|
| 593 |
# nothing should be ready |
| 594 |
r, w, e = select.select([chan], [], [], 0.1) |
| 595 |
self.assertEqual([], r) |
| 596 |
self.assertEqual([], w) |
| 597 |
self.assertEqual([], e) |
| 598 |
|
| 599 |
schan.send_stderr("hello\n") |
| 600 |
|
| 601 |
# something should be ready now (give it 1 second to appear) |
| 602 |
for i in range(10): |
| 603 |
r, w, e = select.select([chan], [], [], 0.1) |
| 604 |
if chan in r: |
| 605 |
break |
| 606 |
time.sleep(0.1) |
| 607 |
self.assertEqual([chan], r) |
| 608 |
self.assertEqual([], w) |
| 609 |
self.assertEqual([], e) |
| 610 |
|
| 611 |
self.assertEqual(b"hello\n", chan.recv_stderr(6)) |
| 612 |
|
| 613 |
# and, should be dead again now |
| 614 |
r, w, e = select.select([chan], [], [], 0.1) |
| 615 |
self.assertEqual([], r) |
| 616 |
self.assertEqual([], w) |
| 617 |
self.assertEqual([], e) |
| 618 |
|
| 619 |
schan.close() |
| 620 |
chan.close() |
| 621 |
|
| 622 |
def test_send_ready(self): |
| 623 |
""" |
| 624 |
verify that send_ready() indicates when a send would not block. |
| 625 |
""" |
| 626 |
self.setup_test_server() |
| 627 |
chan = self.tc.open_session() |
| 628 |
chan.invoke_shell() |
| 629 |
schan = self.ts.accept(1.0) |
| 630 |
|
| 631 |
self.assertEqual(chan.send_ready(), True) |
| 632 |
total = 0 |
| 633 |
K = "*" * 1024 |
| 634 |
limit = 1 + (64 * 2**15) |
| 635 |
while total < limit: |
| 636 |
chan.send(K) |
| 637 |
total += len(K) |
| 638 |
if not chan.send_ready(): |
| 639 |
break |
| 640 |
self.assertTrue(total < limit) |
| 641 |
|
| 642 |
schan.close() |
| 643 |
chan.close() |
| 644 |
self.assertEqual(chan.send_ready(), True) |
| 645 |
|
| 646 |
def test_rekey_deadlock(self): |
| 647 |
""" |
| 648 |
Regression test for deadlock when in-transit messages are received |
| 649 |
after MSG_KEXINIT is sent |
| 650 |
|
| 651 |
Note: When this test fails, it may leak threads. |
| 652 |
""" |
| 653 |
|
| 654 |
# Test for an obscure deadlocking bug that can occur if we receive |
| 655 |
# certain messages while initiating a key exchange. |
| 656 |
# |
| 657 |
# The deadlock occurs as follows: |
| 658 |
# |
| 659 |
# In the main thread: |
| 660 |
# 1. The user's program calls Channel.send(), which sends |
| 661 |
# MSG_CHANNEL_DATA to the remote host. |
| 662 |
# 2. Packetizer discovers that REKEY_BYTES has been exceeded, and |
| 663 |
# sets the __need_rekey flag. |
| 664 |
# |
| 665 |
# In the Transport thread: |
| 666 |
# 3. Packetizer notices that the __need_rekey flag is set, and raises |
| 667 |
# NeedRekeyException. |
| 668 |
# 4. In response to NeedRekeyException, the transport thread sends |
| 669 |
# MSG_KEXINIT to the remote host. |
| 670 |
# |
| 671 |
# On the remote host (using any SSH implementation): |
| 672 |
# 5. The MSG_CHANNEL_DATA is received, and MSG_CHANNEL_WINDOW_ADJUST |
| 673 |
# is sent. |
| 674 |
# 6. The MSG_KEXINIT is received, and a corresponding MSG_KEXINIT is |
| 675 |
# sent. |
| 676 |
# |
| 677 |
# In the main thread: |
| 678 |
# 7. The user's program calls Channel.send(). |
| 679 |
# 8. Channel.send acquires Channel.lock, then calls |
| 680 |
# Transport._send_user_message(). |
| 681 |
# 9. Transport._send_user_message waits for Transport.clear_to_send |
| 682 |
# to be set (i.e., it waits for re-keying to complete). |
| 683 |
# Channel.lock is still held. |
| 684 |
# |
| 685 |
# In the Transport thread: |
| 686 |
# 10. MSG_CHANNEL_WINDOW_ADJUST is received; Channel._window_adjust |
| 687 |
# is called to handle it. |
| 688 |
# 11. Channel._window_adjust tries to acquire Channel.lock, but it |
| 689 |
# blocks because the lock is already held by the main thread. |
| 690 |
# |
| 691 |
# The result is that the Transport thread never processes the remote |
| 692 |
# host's MSG_KEXINIT packet, because it becomes deadlocked while |
| 693 |
# handling the preceding MSG_CHANNEL_WINDOW_ADJUST message. |
| 694 |
|
| 695 |
# We set up two separate threads for sending and receiving packets, |
| 696 |
# while the main thread acts as a watchdog timer. If the timer |
| 697 |
# expires, a deadlock is assumed. |
| 698 |
|
| 699 |
class SendThread(threading.Thread): |
| 700 |
def __init__(self, chan, iterations, done_event): |
| 701 |
threading.Thread.__init__( |
| 702 |
self, None, None, self.__class__.__name__ |
| 703 |
) |
| 704 |
self.daemon = True |
| 705 |
self.chan = chan |
| 706 |
self.iterations = iterations |
| 707 |
self.done_event = done_event |
| 708 |
self.watchdog_event = threading.Event() |
| 709 |
self.last = None |
| 710 |
|
| 711 |
def run(self): |
| 712 |
try: |
| 713 |
for i in range(1, 1 + self.iterations): |
| 714 |
if self.done_event.is_set(): |
| 715 |
break |
| 716 |
self.watchdog_event.set() |
| 717 |
# print i, "SEND" |
| 718 |
self.chan.send("x" * 2048) |
| 719 |
finally: |
| 720 |
self.done_event.set() |
| 721 |
self.watchdog_event.set() |
| 722 |
|
| 723 |
class ReceiveThread(threading.Thread): |
| 724 |
def __init__(self, chan, done_event): |
| 725 |
threading.Thread.__init__( |
| 726 |
self, None, None, self.__class__.__name__ |
| 727 |
) |
| 728 |
self.daemon = True |
| 729 |
self.chan = chan |
| 730 |
self.done_event = done_event |
| 731 |
self.watchdog_event = threading.Event() |
| 732 |
|
| 733 |
def run(self): |
| 734 |
try: |
| 735 |
while not self.done_event.is_set(): |
| 736 |
if self.chan.recv_ready(): |
| 737 |
chan.recv(65536) |
| 738 |
self.watchdog_event.set() |
| 739 |
else: |
| 740 |
if random.randint(0, 1): |
| 741 |
time.sleep(random.randint(0, 500) / 1000.0) |
| 742 |
finally: |
| 743 |
self.done_event.set() |
| 744 |
self.watchdog_event.set() |
| 745 |
|
| 746 |
self.setup_test_server() |
| 747 |
self.ts.packetizer.REKEY_BYTES = 2048 |
| 748 |
|
| 749 |
chan = self.tc.open_session() |
| 750 |
chan.exec_command("yes") |
| 751 |
schan = self.ts.accept(1.0) |
| 752 |
|
| 753 |
# Monkey patch the client's Transport._handler_table so that the client |
| 754 |
# sends MSG_CHANNEL_WINDOW_ADJUST whenever it receives an initial |
| 755 |
# MSG_KEXINIT. This is used to simulate the effect of network latency |
| 756 |
# on a real MSG_CHANNEL_WINDOW_ADJUST message. |
| 757 |
self.tc._handler_table = ( |
| 758 |
self.tc._handler_table.copy() |
| 759 |
) # copy per-class dictionary |
| 760 |
_negotiate_keys = self.tc._handler_table[MSG_KEXINIT] |
| 761 |
|
| 762 |
def _negotiate_keys_wrapper(self, m): |
| 763 |
if self.local_kex_init is None: # Remote side sent KEXINIT |
| 764 |
# Simulate in-transit MSG_CHANNEL_WINDOW_ADJUST by sending it |
| 765 |
# before responding to the incoming MSG_KEXINIT. |
| 766 |
m2 = Message() |
| 767 |
m2.add_byte(cMSG_CHANNEL_WINDOW_ADJUST) |
| 768 |
m2.add_int(chan.remote_chanid) |
| 769 |
m2.add_int(1) # bytes to add |
| 770 |
self._send_message(m2) |
| 771 |
return _negotiate_keys(self, m) |
| 772 |
|
| 773 |
self.tc._handler_table[MSG_KEXINIT] = _negotiate_keys_wrapper |
| 774 |
|
| 775 |
# Parameters for the test |
| 776 |
iterations = 500 # The deadlock does not happen every time, but it |
| 777 |
# should after many iterations. |
| 778 |
timeout = 5 |
| 779 |
|
| 780 |
# This event is set when the test is completed |
| 781 |
done_event = threading.Event() |
| 782 |
|
| 783 |
# Start the sending thread |
| 784 |
st = SendThread(schan, iterations, done_event) |
| 785 |
st.start() |
| 786 |
|
| 787 |
# Start the receiving thread |
| 788 |
rt = ReceiveThread(chan, done_event) |
| 789 |
rt.start() |
| 790 |
|
| 791 |
# Act as a watchdog timer, checking |
| 792 |
deadlocked = False |
| 793 |
while not deadlocked and not done_event.is_set(): |
| 794 |
for event in (st.watchdog_event, rt.watchdog_event): |
| 795 |
event.wait(timeout) |
| 796 |
if done_event.is_set(): |
| 797 |
break |
| 798 |
if not event.is_set(): |
| 799 |
deadlocked = True |
| 800 |
break |
| 801 |
event.clear() |
| 802 |
|
| 803 |
# Tell the threads to stop (if they haven't already stopped). Note |
| 804 |
# that if one or more threads are deadlocked, they might hang around |
| 805 |
# forever (until the process exits). |
| 806 |
done_event.set() |
| 807 |
|
| 808 |
# Assertion: We must not have detected a timeout. |
| 809 |
self.assertFalse(deadlocked) |
| 810 |
|
| 811 |
# Close the channels |
| 812 |
schan.close() |
| 813 |
chan.close() |
| 814 |
|
| 815 |
def test_sanitze_packet_size(self): |
| 816 |
""" |
| 817 |
verify that we conform to the rfc of packet and window sizes. |
| 818 |
""" |
| 819 |
for val, correct in [ |
| 820 |
(4095, MIN_PACKET_SIZE), |
| 821 |
(None, DEFAULT_MAX_PACKET_SIZE), |
| 822 |
(2**32, MAX_WINDOW_SIZE), |
| 823 |
]: |
| 824 |
self.assertEqual(self.tc._sanitize_packet_size(val), correct) |
| 825 |
|
| 826 |
def test_sanitze_window_size(self): |
| 827 |
""" |
| 828 |
verify that we conform to the rfc of packet and window sizes. |
| 829 |
""" |
| 830 |
for val, correct in [ |
| 831 |
(32767, MIN_WINDOW_SIZE), |
| 832 |
(None, DEFAULT_WINDOW_SIZE), |
| 833 |
(2**32, MAX_WINDOW_SIZE), |
| 834 |
]: |
| 835 |
self.assertEqual(self.tc._sanitize_window_size(val), correct) |
| 836 |
|
| 837 |
@slow |
| 838 |
def test_handshake_timeout(self): |
| 839 |
""" |
| 840 |
verify that we can get a handshake timeout. |
| 841 |
""" |
| 842 |
|
| 843 |
# Tweak client Transport instance's Packetizer instance so |
| 844 |
# its read_message() sleeps a bit. This helps prevent race conditions |
| 845 |
# where the client Transport's timeout timer thread doesn't even have |
| 846 |
# time to get scheduled before the main client thread finishes |
| 847 |
# handshaking with the server. |
| 848 |
# (Doing this on the server's transport *sounds* more 'correct' but |
| 849 |
# actually doesn't work nearly as well for whatever reason.) |
| 850 |
class SlowPacketizer(Packetizer): |
| 851 |
def read_message(self): |
| 852 |
time.sleep(1) |
| 853 |
return super().read_message() |
| 854 |
|
| 855 |
# NOTE: prettttty sure since the replaced .packetizer Packetizer is now |
| 856 |
# no longer doing anything with its copy of the socket...everything'll |
| 857 |
# be fine. Even tho it's a bit squicky. |
| 858 |
self.tc.packetizer = SlowPacketizer(self.tc.sock) |
| 859 |
# Continue with regular test red tape. |
| 860 |
host_key = RSAKey.from_private_key_file(_support("rsa.key")) |
| 861 |
public_host_key = RSAKey(data=host_key.asbytes()) |
| 862 |
self.ts.add_server_key(host_key) |
| 863 |
event = threading.Event() |
| 864 |
server = NullServer() |
| 865 |
self.assertTrue(not event.is_set()) |
| 866 |
self.tc.handshake_timeout = 0.000000000001 |
| 867 |
self.ts.start_server(event, server) |
| 868 |
self.assertRaises( |
| 869 |
EOFError, |
| 870 |
self.tc.connect, |
| 871 |
hostkey=public_host_key, |
| 872 |
username="slowdive", |
| 873 |
password="pygmalion", |
| 874 |
) |
| 875 |
|
| 876 |
def test_select_after_close(self): |
| 877 |
""" |
| 878 |
verify that select works when a channel is already closed. |
| 879 |
""" |
| 880 |
self.setup_test_server() |
| 881 |
chan = self.tc.open_session() |
| 882 |
chan.invoke_shell() |
| 883 |
schan = self.ts.accept(1.0) |
| 884 |
schan.close() |
| 885 |
|
| 886 |
# give client a moment to receive close notification |
| 887 |
time.sleep(0.1) |
| 888 |
|
| 889 |
r, w, e = select.select([chan], [], [], 0.1) |
| 890 |
self.assertEqual([chan], r) |
| 891 |
self.assertEqual([], w) |
| 892 |
self.assertEqual([], e) |
| 893 |
|
| 894 |
def test_channel_send_misc(self): |
| 895 |
""" |
| 896 |
verify behaviours sending various instances to a channel |
| 897 |
""" |
| 898 |
self.setup_test_server() |
| 899 |
text = "\xa7 slice me nicely" |
| 900 |
with self.tc.open_session() as chan: |
| 901 |
schan = self.ts.accept(1.0) |
| 902 |
if schan is None: |
| 903 |
self.fail("Test server transport failed to accept") |
| 904 |
sfile = schan.makefile() |
| 905 |
|
| 906 |
# TypeError raised on non string or buffer type |
| 907 |
self.assertRaises(TypeError, chan.send, object()) |
| 908 |
self.assertRaises(TypeError, chan.sendall, object()) |
| 909 |
|
| 910 |
# sendall() accepts a unicode instance |
| 911 |
chan.sendall(text) |
| 912 |
expected = text.encode("utf-8") |
| 913 |
self.assertEqual(sfile.read(len(expected)), expected) |
| 914 |
|
| 915 |
@needs_builtin("buffer") |
| 916 |
def test_channel_send_buffer(self): |
| 917 |
""" |
| 918 |
verify sending buffer instances to a channel |
| 919 |
""" |
| 920 |
self.setup_test_server() |
| 921 |
data = 3 * b"some test data\n whole" |
| 922 |
with self.tc.open_session() as chan: |
| 923 |
schan = self.ts.accept(1.0) |
| 924 |
if schan is None: |
| 925 |
self.fail("Test server transport failed to accept") |
| 926 |
sfile = schan.makefile() |
| 927 |
|
| 928 |
# send() accepts buffer instances |
| 929 |
sent = 0 |
| 930 |
while sent < len(data): |
| 931 |
sent += chan.send(buffer(data, sent, 8)) # noqa |
| 932 |
self.assertEqual(sfile.read(len(data)), data) |
| 933 |
|
| 934 |
# sendall() accepts a buffer instance |
| 935 |
chan.sendall(buffer(data)) # noqa |
| 936 |
self.assertEqual(sfile.read(len(data)), data) |
| 937 |
|
| 938 |
@needs_builtin("memoryview") |
| 939 |
def test_channel_send_memoryview(self): |
| 940 |
""" |
| 941 |
verify sending memoryview instances to a channel |
| 942 |
""" |
| 943 |
self.setup_test_server() |
| 944 |
data = 3 * b"some test data\n whole" |
| 945 |
with self.tc.open_session() as chan: |
| 946 |
schan = self.ts.accept(1.0) |
| 947 |
if schan is None: |
| 948 |
self.fail("Test server transport failed to accept") |
| 949 |
sfile = schan.makefile() |
| 950 |
|
| 951 |
# send() accepts memoryview slices |
| 952 |
sent = 0 |
| 953 |
view = memoryview(data) |
| 954 |
while sent < len(view): |
| 955 |
sent += chan.send(view[sent : sent + 8]) |
| 956 |
self.assertEqual(sfile.read(len(data)), data) |
| 957 |
|
| 958 |
# sendall() accepts a memoryview instance |
| 959 |
chan.sendall(memoryview(data)) |
| 960 |
self.assertEqual(sfile.read(len(data)), data) |
| 961 |
|
| 962 |
def test_server_rejects_open_channel_without_auth(self): |
| 963 |
try: |
| 964 |
self.setup_test_server(connect_kwargs={}) |
| 965 |
self.tc.open_session() |
| 966 |
except ChannelException as e: |
| 967 |
assert e.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED |
| 968 |
else: |
| 969 |
assert False, "Did not raise ChannelException!" |
| 970 |
|
| 971 |
def test_server_rejects_arbitrary_global_request_without_auth(self): |
| 972 |
self.setup_test_server(connect_kwargs={}) |
| 973 |
# NOTE: this dummy global request kind would normally pass muster |
| 974 |
# from the test server. |
| 975 |
self.tc.global_request("acceptable") |
| 976 |
# Global requests never raise exceptions, even on failure (not sure why |
| 977 |
# this was the original design...ugh.) Best we can do to tell failure |
| 978 |
# happened is that the client transport's global_response was set back |
| 979 |
# to None; if it had succeeded, it would be the response Message. |
| 980 |
err = "Unauthed global response incorrectly succeeded!" |
| 981 |
assert self.tc.global_response is None, err |
| 982 |
|
| 983 |
def test_server_rejects_port_forward_without_auth(self): |
| 984 |
# NOTE: at protocol level port forward requests are treated same as a |
| 985 |
# regular global request, but Paramiko server implements a special-case |
| 986 |
# method for it, so it gets its own test. (plus, THAT actually raises |
| 987 |
# an exception on the client side, unlike the general case...) |
| 988 |
self.setup_test_server(connect_kwargs={}) |
| 989 |
try: |
| 990 |
self.tc.request_port_forward("localhost", 1234) |
| 991 |
except SSHException as e: |
| 992 |
assert "forwarding request denied" in str(e) |
| 993 |
else: |
| 994 |
assert False, "Did not raise SSHException!" |
| 995 |
|
| 996 |
def _send_unimplemented(self, server_is_sender): |
| 997 |
self.setup_test_server() |
| 998 |
sender, recipient = self.tc, self.ts |
| 999 |
if server_is_sender: |
| 1000 |
sender, recipient = self.ts, self.tc |
| 1001 |
recipient._send_message = Mock() |
| 1002 |
msg = Message() |
| 1003 |
msg.add_byte(cMSG_UNIMPLEMENTED) |
| 1004 |
sender._send_message(msg) |
| 1005 |
# TODO: I hate this but I literally don't see a good way to know when |
| 1006 |
# the recipient has received the sender's message (there are no |
| 1007 |
# existing threading events in play that work for this), esp in this |
| 1008 |
# case where we don't WANT a response (as otherwise we could |
| 1009 |
# potentially try blocking on the sender's receipt of a reply...maybe). |
| 1010 |
time.sleep(0.1) |
| 1011 |
assert not recipient._send_message.called |
| 1012 |
|
| 1013 |
def test_server_does_not_respond_to_MSG_UNIMPLEMENTED(self): |
| 1014 |
self._send_unimplemented(server_is_sender=False) |
| 1015 |
|
| 1016 |
def test_client_does_not_respond_to_MSG_UNIMPLEMENTED(self): |
| 1017 |
self._send_unimplemented(server_is_sender=True) |
| 1018 |
|
| 1019 |
def _send_client_message(self, message_type): |
| 1020 |
self.setup_test_server(connect_kwargs={}) |
| 1021 |
self.ts._send_message = Mock() |
| 1022 |
# NOTE: this isn't 100% realistic (most of these message types would |
| 1023 |
# have actual other fields in 'em) but it suffices to test the level of |
| 1024 |
# message dispatch we're interested in here. |
| 1025 |
msg = Message() |
| 1026 |
# TODO: really not liking the whole cMSG_XXX vs MSG_XXX duality right |
| 1027 |
# now, esp since the former is almost always just byte_chr(the |
| 1028 |
# latter)...but since that's the case... |
| 1029 |
msg.add_byte(byte_chr(message_type)) |
| 1030 |
self.tc._send_message(msg) |
| 1031 |
# No good way to actually wait for server action (see above tests re: |
| 1032 |
# MSG_UNIMPLEMENTED). Grump. |
| 1033 |
time.sleep(0.1) |
| 1034 |
|
| 1035 |
def _expect_unimplemented(self): |
| 1036 |
# Ensure MSG_UNIMPLEMENTED was sent (implies it hit end of loop instead |
| 1037 |
# of truly handling the given message). |
| 1038 |
# NOTE: When bug present, this will actually be the first thing that |
| 1039 |
# fails (since in many cases actual message handling doesn't involve |
| 1040 |
# sending a message back right away). |
| 1041 |
assert self.ts._send_message.call_count == 1 |
| 1042 |
reply = self.ts._send_message.call_args[0][0] |
| 1043 |
reply.rewind() # Because it's pre-send, not post-receive |
| 1044 |
assert reply.get_byte() == cMSG_UNIMPLEMENTED |
| 1045 |
|
| 1046 |
def test_server_transports_reject_client_message_types(self): |
| 1047 |
# TODO: handle Transport's own tables too, not just its inner auth |
| 1048 |
# handler's table. See TODOs in auth_handler.py |
| 1049 |
some_handler = self._auth_handler_class(self.tc) |
| 1050 |
for message_type in some_handler._client_handler_table: |
| 1051 |
self._send_client_message(message_type) |
| 1052 |
self._expect_unimplemented() |
| 1053 |
# Reset for rest of loop |
| 1054 |
self.tearDown() |
| 1055 |
self.setUp() |
| 1056 |
|
| 1057 |
def test_server_rejects_client_MSG_USERAUTH_SUCCESS(self): |
| 1058 |
self._send_client_message(MSG_USERAUTH_SUCCESS) |
| 1059 |
# Sanity checks |
| 1060 |
assert not self.ts.authenticated |
| 1061 |
assert not self.ts.auth_handler.authenticated |
| 1062 |
# Real fix's behavior |
| 1063 |
self._expect_unimplemented() |
| 1064 |
|
| 1065 |
def test_can_override_packetizer_used(self): |
| 1066 |
class MyPacketizer(Packetizer): |
| 1067 |
pass |
| 1068 |
|
| 1069 |
# control case |
| 1070 |
assert Transport(sock=LoopSocket()).packetizer.__class__ is Packetizer |
| 1071 |
# overridden case |
| 1072 |
tweaked = Transport(sock=LoopSocket(), packetizer_class=MyPacketizer) |
| 1073 |
assert tweaked.packetizer.__class__ is MyPacketizer |
| 1074 |
|
| 1075 |
|
| 1076 |
# TODO: for now this is purely a regression test. It needs actual tests of the |
| 1077 |
# intentional new behavior too! |
| 1078 |
class ServiceRequestingTransportTest(TransportTest): |
| 1079 |
_auth_handler_class = AuthOnlyHandler |
| 1080 |
|
| 1081 |
def setUp(self): |
| 1082 |
# Copypasta (Transport init is load-bearing) |
| 1083 |
self.socks = LoopSocket() |
| 1084 |
self.sockc = LoopSocket() |
| 1085 |
self.sockc.link(self.socks) |
| 1086 |
# New class who dis |
| 1087 |
self.tc = ServiceRequestingTransport(self.sockc) |
| 1088 |
self.ts = ServiceRequestingTransport(self.socks) |
| 1089 |
|
| 1090 |
|
| 1091 |
class AlgorithmDisablingTests(unittest.TestCase): |
| 1092 |
def test_preferred_lists_default_to_private_attribute_contents(self): |
| 1093 |
t = Transport(sock=Mock()) |
| 1094 |
assert t.preferred_ciphers == t._preferred_ciphers |
| 1095 |
assert t.preferred_macs == t._preferred_macs |
| 1096 |
assert t.preferred_keys == tuple( |
| 1097 |
t._preferred_keys |
| 1098 |
+ tuple( |
| 1099 |
"{}[email protected]".format(x) for x in t._preferred_keys |
| 1100 |
) |
| 1101 |
) |
| 1102 |
assert t.preferred_kex == t._preferred_kex |
| 1103 |
|
| 1104 |
def test_preferred_lists_filter_disabled_algorithms(self): |
| 1105 |
t = Transport( |
| 1106 |
sock=Mock(), |
| 1107 |
disabled_algorithms={ |
| 1108 |
"ciphers": ["aes128-cbc"], |
| 1109 |
"macs": ["hmac-md5"], |
| 1110 |
"keys": ["rsa-sha2-512"], |
| 1111 |
"kex": ["diffie-hellman-group14-sha256"], |
| 1112 |
}, |
| 1113 |
) |
| 1114 |
assert "aes128-cbc" in t._preferred_ciphers |
| 1115 |
assert "aes128-cbc" not in t.preferred_ciphers |
| 1116 |
assert "hmac-md5" in t._preferred_macs |
| 1117 |
assert "hmac-md5" not in t.preferred_macs |
| 1118 |
assert "rsa-sha2-512" in t._preferred_keys |
| 1119 |
assert "rsa-sha2-512" not in t.preferred_keys |
| 1120 |
# Filtering also accounts for cert forms |
| 1121 |
assert "[email protected]" not in t.preferred_keys |
| 1122 |
assert "diffie-hellman-group14-sha256" in t._preferred_kex |
| 1123 |
assert "diffie-hellman-group14-sha256" not in t.preferred_kex |
| 1124 |
|
| 1125 |
def test_implementation_refers_to_public_algo_lists(self): |
| 1126 |
t = Transport( |
| 1127 |
sock=Mock(), |
| 1128 |
disabled_algorithms={ |
| 1129 |
"ciphers": ["aes128-cbc"], |
| 1130 |
"macs": ["hmac-md5"], |
| 1131 |
"keys": ["rsa-sha2-256"], |
| 1132 |
"kex": ["diffie-hellman-group14-sha256"], |
| 1133 |
"compression": ["zlib"], |
| 1134 |
}, |
| 1135 |
) |
| 1136 |
# Enable compression cuz otherwise disabling one option for it makes no |
| 1137 |
# sense... |
| 1138 |
t.use_compression(True) |
| 1139 |
# Effectively a random spot check, but kex init touches most/all of the |
| 1140 |
# algorithm lists so it's a good spot. |
| 1141 |
t._send_message = Mock() |
| 1142 |
t._send_kex_init() |
| 1143 |
# Cribbed from Transport._parse_kex_init, which didn't feel worth |
| 1144 |
# refactoring given all the vars involved :( |
| 1145 |
m = t._send_message.call_args[0][0] |
| 1146 |
m.rewind() |
| 1147 |
m.get_byte() # the msg type |
| 1148 |
m.get_bytes(16) # cookie, discarded |
| 1149 |
kexen = m.get_list() |
| 1150 |
server_keys = m.get_list() |
| 1151 |
ciphers = m.get_list() |
| 1152 |
m.get_list() |
| 1153 |
macs = m.get_list() |
| 1154 |
m.get_list() |
| 1155 |
compressions = m.get_list() |
| 1156 |
# OK, now we can actually check that our disabled algos were not |
| 1157 |
# included (as this message includes the full lists) |
| 1158 |
assert "aes128-cbc" not in ciphers |
| 1159 |
assert "hmac-md5" not in macs |
| 1160 |
assert "rsa-sha2-256" not in server_keys |
| 1161 |
assert "diffie-hellman-group14-sha256" not in kexen |
| 1162 |
assert "zlib" not in compressions |
| 1163 |
|
| 1164 |
|
| 1165 |
class TestSHA2SignatureKeyExchange(unittest.TestCase): |
| 1166 |
# NOTE: these all rely on the default server() hostkey being RSA |
| 1167 |
# NOTE: these rely on both sides being properly implemented re: agreed-upon |
| 1168 |
# hostkey during kex being what's actually used. Truly proving that eg |
| 1169 |
# SHA512 was used, is quite difficult w/o super gross hacks. However, there |
| 1170 |
# are new tests in test_pkey.py which use known signature blobs to prove |
| 1171 |
# the SHA2 family was in fact used! |
| 1172 |
|
| 1173 |
def test_kex_with_sha2_512(self): |
| 1174 |
# It's the default! |
| 1175 |
with server() as (tc, _): |
| 1176 |
assert tc.host_key_type == "rsa-sha2-512" |
| 1177 |
|
| 1178 |
def test_kex_with_sha2_256(self): |
| 1179 |
# No 512 -> you get 256 |
| 1180 |
with server( |
| 1181 |
init=dict(disabled_algorithms=dict(keys=["rsa-sha2-512"])) |
| 1182 |
) as (tc, _): |
| 1183 |
assert tc.host_key_type == "rsa-sha2-256" |
| 1184 |
|
| 1185 |
def _incompatible_peers(self, client_init, server_init): |
| 1186 |
with server( |
| 1187 |
client_init=client_init, server_init=server_init, catch_error=True |
| 1188 |
) as (tc, ts, err): |
| 1189 |
# If neither side blew up then that's bad! |
| 1190 |
assert err is not None |
| 1191 |
# If client side blew up first, it'll be straightforward |
| 1192 |
if isinstance(err, IncompatiblePeer): |
| 1193 |
pass |
| 1194 |
# If server side blew up first, client sees EOF & we need to check |
| 1195 |
# the server transport for its saved error (otherwise it can only |
| 1196 |
# appear in log output) |
| 1197 |
elif isinstance(err, EOFError): |
| 1198 |
assert ts.saved_exception is not None |
| 1199 |
assert isinstance(ts.saved_exception, IncompatiblePeer) |
| 1200 |
# If it was something else, welp |
| 1201 |
else: |
| 1202 |
raise err |
| 1203 |
|
| 1204 |
def test_explicit_client_hostkey_not_limited(self): |
| 1205 |
# Be very explicit about the hostkey on BOTH ends, |
| 1206 |
# and ensure it still ends up choosing sha2-512. |
| 1207 |
# (This is a regression test vs previous implementation which overwrote |
| 1208 |
# the entire preferred-hostkeys structure when given an explicit key as |
| 1209 |
# a client.) |
| 1210 |
hostkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 1211 |
connect = dict( |
| 1212 |
hostkey=hostkey, username="slowdive", password="pygmalion" |
| 1213 |
) |
| 1214 |
with server(hostkey=hostkey, connect=connect) as (tc, _): |
| 1215 |
assert tc.host_key_type == "rsa-sha2-512" |
| 1216 |
|
| 1217 |
|
| 1218 |
class TestExtInfo(unittest.TestCase): |
| 1219 |
def test_ext_info_handshake_exposed_in_client_kexinit(self): |
| 1220 |
with server() as (tc, _): |
| 1221 |
# NOTE: this is latest KEXINIT /sent by us/ (Transport retains it) |
| 1222 |
kex = tc._get_latest_kex_init() |
| 1223 |
# flag in KexAlgorithms list |
| 1224 |
assert "ext-info-c" in kex["kex_algo_list"] |
| 1225 |
# data stored on Transport after hearing back from a compatible |
| 1226 |
# server (such as ourselves in server mode) |
| 1227 |
assert tc.server_extensions == { |
| 1228 |
"server-sig-algs": b"ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256" # noqa |
| 1229 |
} |
| 1230 |
|
| 1231 |
def test_client_uses_server_sig_algs_for_pubkey_auth(self): |
| 1232 |
privkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 1233 |
with server( |
| 1234 |
pubkeys=[privkey], |
| 1235 |
connect=dict(pkey=privkey), |
| 1236 |
server_init=dict( |
| 1237 |
disabled_algorithms=dict(pubkeys=["rsa-sha2-512"]) |
| 1238 |
), |
| 1239 |
) as (tc, _): |
| 1240 |
assert tc.is_authenticated() |
| 1241 |
# Client settled on 256 despite itself not having 512 disabled (and |
| 1242 |
# otherwise, 512 would have been earlier in the preferred list) |
| 1243 |
assert tc._agreed_pubkey_algorithm == "rsa-sha2-256" |
| 1244 |
|
| 1245 |
|
| 1246 |
class BadSeqPacketizer(Packetizer): |
| 1247 |
def read_message(self): |
| 1248 |
cmd, msg = super().read_message() |
| 1249 |
# Only mess w/ seqno if kexinit. |
| 1250 |
if cmd is MSG_KEXINIT: |
| 1251 |
# NOTE: this is /only/ the copy of the seqno which gets |
| 1252 |
# transmitted up from Packetizer; it's not modifying |
| 1253 |
# Packetizer's own internal seqno. For these tests, |
| 1254 |
# modifying the latter isn't required, and is also harder |
| 1255 |
# to do w/o triggering MAC mismatches. |
| 1256 |
msg.seqno = 17 # arbitrary nonzero int |
| 1257 |
return cmd, msg |
| 1258 |
|
| 1259 |
|
| 1260 |
class TestStrictKex: |
| 1261 |
def test_kex_algos_includes_kex_strict_c(self): |
| 1262 |
with server() as (tc, _): |
| 1263 |
kex = tc._get_latest_kex_init() |
| 1264 |
assert "[email protected]" in kex["kex_algo_list"] |
| 1265 |
|
| 1266 |
@mark.parametrize( |
| 1267 |
"server_active,client_active", |
| 1268 |
itertools.product([True, False], repeat=2), |
| 1269 |
) |
| 1270 |
def test_mode_agreement(self, server_active, client_active): |
| 1271 |
with server( |
| 1272 |
server_init=dict(strict_kex=server_active), |
| 1273 |
client_init=dict(strict_kex=client_active), |
| 1274 |
) as (tc, ts): |
| 1275 |
if server_active and client_active: |
| 1276 |
assert tc.agreed_on_strict_kex is True |
| 1277 |
assert ts.agreed_on_strict_kex is True |
| 1278 |
else: |
| 1279 |
assert tc.agreed_on_strict_kex is False |
| 1280 |
assert ts.agreed_on_strict_kex is False |
| 1281 |
|
| 1282 |
def test_mode_advertised_by_default(self): |
| 1283 |
# NOTE: no explicit strict_kex overrides... |
| 1284 |
with server() as (tc, ts): |
| 1285 |
assert all( |
| 1286 |
( |
| 1287 |
tc.advertise_strict_kex, |
| 1288 |
tc.agreed_on_strict_kex, |
| 1289 |
ts.advertise_strict_kex, |
| 1290 |
ts.agreed_on_strict_kex, |
| 1291 |
) |
| 1292 |
) |
| 1293 |
|
| 1294 |
@mark.parametrize( |
| 1295 |
"ptype", |
| 1296 |
( |
| 1297 |
# "normal" but definitely out-of-order message |
| 1298 |
MSG_CHANNEL_OPEN, |
| 1299 |
# Normally ignored, but not in this case |
| 1300 |
MSG_IGNORE, |
| 1301 |
# Normally triggers debug parsing, but not in this case |
| 1302 |
MSG_DEBUG, |
| 1303 |
# Normally ignored, but...you get the idea |
| 1304 |
MSG_UNIMPLEMENTED, |
| 1305 |
# Not real, so would normally trigger us /sending/ |
| 1306 |
# MSG_UNIMPLEMENTED, but... |
| 1307 |
MSG_FUGGEDABOUTIT, |
| 1308 |
), |
| 1309 |
) |
| 1310 |
def test_MessageOrderError_non_kex_messages_in_initial_kex(self, ptype): |
| 1311 |
class AttackTransport(Transport): |
| 1312 |
# Easiest apparent spot on server side which is: |
| 1313 |
# - late enough for both ends to have handshook on strict mode |
| 1314 |
# - early enough to be in the window of opportunity for Terrapin |
| 1315 |
# attack; essentially during actual kex, when the engine is |
| 1316 |
# waiting for things like MSG_KEXECDH_REPLY (for eg curve25519). |
| 1317 |
def _negotiate_keys(self, m): |
| 1318 |
self.clear_to_send_lock.acquire() |
| 1319 |
try: |
| 1320 |
self.clear_to_send.clear() |
| 1321 |
finally: |
| 1322 |
self.clear_to_send_lock.release() |
| 1323 |
if self.local_kex_init is None: |
| 1324 |
# remote side wants to renegotiate |
| 1325 |
self._send_kex_init() |
| 1326 |
self._parse_kex_init(m) |
| 1327 |
# Here, we would normally kick over to kex_engine, but instead |
| 1328 |
# we want the server to send the OOO message. |
| 1329 |
m = Message() |
| 1330 |
m.add_byte(byte_chr(ptype)) |
| 1331 |
# rest of packet unnecessary... |
| 1332 |
self._send_message(m) |
| 1333 |
|
| 1334 |
with raises(MessageOrderError): |
| 1335 |
with server(server_transport_factory=AttackTransport) as (tc, _): |
| 1336 |
pass # above should run and except during connect() |
| 1337 |
|
| 1338 |
def test_SSHException_raised_on_out_of_order_messages_when_not_strict( |
| 1339 |
self, |
| 1340 |
): |
| 1341 |
# This is kind of dumb (either situation is still fatal!) but whatever, |
| 1342 |
# may as well be strict with our new strict flag... |
| 1343 |
with raises(SSHException) as info: # would be true either way, but |
| 1344 |
with server( |
| 1345 |
client_init=dict(strict_kex=False), |
| 1346 |
) as (tc, _): |
| 1347 |
tc._expect_packet(MSG_KEXINIT) |
| 1348 |
tc.open_session() |
| 1349 |
assert info.type is SSHException # NOT MessageOrderError! |
| 1350 |
|
| 1351 |
def test_error_not_raised_when_kexinit_not_seq_0_but_unstrict(self): |
| 1352 |
with server( |
| 1353 |
client_init=dict( |
| 1354 |
# Disable strict kex |
| 1355 |
strict_kex=False, |
| 1356 |
# Give our clientside a packetizer that sets all kexinit |
| 1357 |
# Message objects to have .seqno==17, which would trigger the |
| 1358 |
# new logic if we'd forgotten to wrap it in strict-kex check |
| 1359 |
packetizer_class=BadSeqPacketizer, |
| 1360 |
), |
| 1361 |
): |
| 1362 |
pass # kexinit happens at connect... |
| 1363 |
|
| 1364 |
def test_MessageOrderError_raised_when_kexinit_not_seq_0_and_strict(self): |
| 1365 |
with raises(MessageOrderError): |
| 1366 |
with server( |
| 1367 |
# Give our clientside a packetizer that sets all kexinit |
| 1368 |
# Message objects to have .seqno==17, which should trigger the |
| 1369 |
# new logic (given we are NOT disabling strict-mode) |
| 1370 |
client_init=dict(packetizer_class=BadSeqPacketizer), |
| 1371 |
): |
| 1372 |
pass # kexinit happens at connect... |
| 1373 |
|
| 1374 |
def test_sequence_numbers_reset_on_newkeys_when_strict(self): |
| 1375 |
with server(defer=True) as (tc, ts): |
| 1376 |
# When in strict mode, these should all be zero or close to it |
| 1377 |
# (post-kexinit, pre-auth). |
| 1378 |
# Server->client will be 1 (EXT_INFO got sent after NEWKEYS) |
| 1379 |
assert tc.packetizer._Packetizer__sequence_number_in == 1 |
| 1380 |
assert ts.packetizer._Packetizer__sequence_number_out == 1 |
| 1381 |
# Client->server will be 0 |
| 1382 |
assert tc.packetizer._Packetizer__sequence_number_out == 0 |
| 1383 |
assert ts.packetizer._Packetizer__sequence_number_in == 0 |
| 1384 |
|
| 1385 |
def test_sequence_numbers_not_reset_on_newkeys_when_not_strict(self): |
| 1386 |
with server(defer=True, client_init=dict(strict_kex=False)) as ( |
| 1387 |
tc, |
| 1388 |
ts, |
| 1389 |
): |
| 1390 |
# When not in strict mode, these will all be ~3-4 or so |
| 1391 |
# (post-kexinit, pre-auth). Not encoding exact values as it will |
| 1392 |
# change anytime we mess with the test harness... |
| 1393 |
assert tc.packetizer._Packetizer__sequence_number_in != 0 |
| 1394 |
assert tc.packetizer._Packetizer__sequence_number_out != 0 |
| 1395 |
assert ts.packetizer._Packetizer__sequence_number_in != 0 |
| 1396 |
assert ts.packetizer._Packetizer__sequence_number_out != 0 |
| 1397 |
|
| 1398 |
def test_sequence_number_rollover_detected(self): |
| 1399 |
class RolloverTransport(Transport): |
| 1400 |
def __init__(self, *args, **kwargs): |
| 1401 |
super().__init__(*args, **kwargs) |
| 1402 |
# Induce an about-to-rollover seqno, such that it rolls over |
| 1403 |
# during initial kex. (Sequence numbers are uint32, so we need |
| 1404 |
# the largest possible 32bit integer such that incrementing it |
| 1405 |
# will roll over to 0.) |
| 1406 |
last_seq = 2**32 - 1 |
| 1407 |
setattr( |
| 1408 |
self.packetizer, |
| 1409 |
"_Packetizer__sequence_number_in", |
| 1410 |
last_seq, |
| 1411 |
) |
| 1412 |
setattr( |
| 1413 |
self.packetizer, |
| 1414 |
"_Packetizer__sequence_number_out", |
| 1415 |
last_seq, |
| 1416 |
) |
| 1417 |
|
| 1418 |
with raises( |
| 1419 |
SSHException, |
| 1420 |
match=r"Sequence number rolled over during initial kex!", |
| 1421 |
): |
| 1422 |
with server( |
| 1423 |
client_init=dict( |
| 1424 |
# Disable strict kex - this should happen always |
| 1425 |
strict_kex=False, |
| 1426 |
), |
| 1427 |
# Transport which tickles its packetizer seqno's |
| 1428 |
transport_factory=RolloverTransport, |
| 1429 |
): |
| 1430 |
pass # kexinit happens at connect... |