-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_transport.py
2678 lines (2200 loc) · 92 KB
/
test_transport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for ssh/transport.py and the classes therein.
"""
from __future__ import absolute_import, division
import binascii
import re
import string
import struct
import types
from hashlib import md5, sha1, sha256, sha384, sha512
from twisted import __version__ as twisted_version
from twisted.trial import unittest
from twisted.internet import defer
from twisted.protocols import loopback
from twisted.python import randbytes
from twisted.python.randbytes import insecureRandom
from twisted.python.compat import iterbytes, _bytesChr as chr
from twisted.conch.ssh import address, service, _kex
from twisted.conch.error import ConchError
from twisted.test import proto_helpers
from twisted.python.reflect import requireModule
pyasn1 = requireModule("pyasn1")
cryptography = requireModule("cryptography")
if pyasn1 is not None and cryptography is not None:
dependencySkip = None
from twisted.conch.ssh import common, transport, keys, factory
from twisted.conch.test import keydata
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import dh, ec
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives import serialization
else:
if pyasn1 is None:
dependencySkip = "Cannot run without PyASN1"
elif cryptography is None:
dependencySkip = "can't run without cryptography"
class transport: # fictional modules to make classes work
class SSHTransportBase: pass
class SSHServerTransport: pass
class SSHClientTransport: pass
class factory:
class SSHFactory:
pass
class common:
@classmethod
def NS(self, arg): return b''
def _MPpow(x, y, z):
"""
Return the MP version of C{(x ** y) % z}.
"""
return common.MP(pow(x, y, z))
class MockTransportBase(transport.SSHTransportBase):
"""
A base class for the client and server protocols. Stores the messages
it receives instead of ignoring them.
@ivar errors: a list of tuples: (reasonCode, description)
@ivar unimplementeds: a list of integers: sequence number
@ivar debugs: a list of tuples: (alwaysDisplay, message, lang)
@ivar ignoreds: a list of strings: ignored data
"""
def connectionMade(self):
"""
Set up instance variables.
"""
transport.SSHTransportBase.connectionMade(self)
self.errors = []
self.unimplementeds = []
self.debugs = []
self.ignoreds = []
self.gotUnsupportedVersion = None
def _unsupportedVersionReceived(self, remoteVersion):
"""
Intercept unsupported version call.
@type remoteVersion: L{str}
"""
self.gotUnsupportedVersion = remoteVersion
return transport.SSHTransportBase._unsupportedVersionReceived(
self, remoteVersion)
def receiveError(self, reasonCode, description):
"""
Store any errors received.
@type reasonCode: L{int}
@type description: L{str}
"""
self.errors.append((reasonCode, description))
def receiveUnimplemented(self, seqnum):
"""
Store any unimplemented packet messages.
@type seqnum: L{int}
"""
self.unimplementeds.append(seqnum)
def receiveDebug(self, alwaysDisplay, message, lang):
"""
Store any debug messages.
@type alwaysDisplay: L{bool}
@type message: L{str}
@type lang: L{str}
"""
self.debugs.append((alwaysDisplay, message, lang))
def ssh_IGNORE(self, packet):
"""
Store any ignored data.
@type packet: L{str}
"""
self.ignoreds.append(packet)
class MockCipher(object):
"""
A mocked-up version of twisted.conch.ssh.transport.SSHCiphers.
"""
outCipType = b'test'
encBlockSize = 6
inCipType = b'test'
decBlockSize = 6
inMACType = b'test'
outMACType = b'test'
verifyDigestSize = 1
usedEncrypt = False
usedDecrypt = False
outMAC = (None, b'', b'', 1)
inMAC = (None, b'', b'', 1)
keys = ()
def encrypt(self, x):
"""
Called to encrypt the packet. Simply record that encryption was used
and return the data unchanged.
"""
self.usedEncrypt = True
if (len(x) % self.encBlockSize) != 0:
raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
(len(x), self.encBlockSize, len(x) % self.encBlockSize))
return x
def decrypt(self, x):
"""
Called to decrypt the packet. Simply record that decryption was used
and return the data unchanged.
"""
self.usedDecrypt = True
if (len(x) % self.encBlockSize) != 0:
raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
(len(x), self.decBlockSize, len(x) % self.decBlockSize))
return x
def makeMAC(self, outgoingPacketSequence, payload):
"""
Make a Message Authentication Code by sending the character value of
the outgoing packet.
"""
return chr(outgoingPacketSequence)
def verify(self, incomingPacketSequence, packet, macData):
"""
Verify the Message Authentication Code by checking that the packet
sequence number is the same.
"""
return chr(incomingPacketSequence) == macData
def setKeys(self, ivOut, keyOut, ivIn, keyIn, macIn, macOut):
"""
Record the keys.
"""
self.keys = (ivOut, keyOut, ivIn, keyIn, macIn, macOut)
class MockCompression:
"""
A mocked-up compression, based on the zlib interface. Instead of
compressing, it reverses the data and adds a 0x66 byte to the end.
"""
def compress(self, payload):
return payload[::-1] # reversed
def decompress(self, payload):
return payload[:-1][::-1]
def flush(self, kind):
return b'\x66'
class MockService(service.SSHService):
"""
A mocked-up service, based on twisted.conch.ssh.service.SSHService.
@ivar started: True if this service has been started.
@ivar stopped: True if this service has been stopped.
"""
name = b"MockService"
started = False
stopped = False
protocolMessages = {0xff: "MSG_TEST", 71: "MSG_fiction"}
def logPrefix(self):
return "MockService"
def serviceStarted(self):
"""
Record that the service was started.
"""
self.started = True
def serviceStopped(self):
"""
Record that the service was stopped.
"""
self.stopped = True
def ssh_TEST(self, packet):
"""
A message that this service responds to.
"""
self.transport.sendPacket(0xff, packet)
class MockFactory(factory.SSHFactory):
"""
A mocked-up factory based on twisted.conch.ssh.factory.SSHFactory.
"""
services = {
b'ssh-userauth': MockService}
def getPublicKeys(self):
"""
Return the public keys that authenticate this server.
"""
return {
b'ssh-rsa': keys.Key.fromString(keydata.publicRSA_openssh),
b'ssh-dsa': keys.Key.fromString(keydata.publicDSA_openssh)}
def getPrivateKeys(self):
"""
Return the private keys that authenticate this server.
"""
return {
b'ssh-rsa': keys.Key.fromString(keydata.privateRSA_openssh),
b'ssh-dsa': keys.Key.fromString(keydata.privateDSA_openssh)}
def getPrimes(self):
"""
Diffie-Hellman primes that can be used for key exchange algorithms
that use group exchange to establish a prime / generator group.
@return: The primes and generators.
@rtype: L{dict} mapping the key size to a C{list} of
C{(generator, prime)} tuple.
"""
# In these tests, we hardwire the prime values to those
# defined by the diffie-hellman-group14-sha1 key exchange
# algorithm, to avoid requiring a moduli file when running
# tests.
# See OpenSSHFactory.getPrimes.
group14 = _kex.getDHGeneratorAndPrime(b'diffie-hellman-group14-sha1')
return {
2048: (group14,),
4096: ((5, 7),)}
class MockOldFactoryPublicKeys(MockFactory):
"""
The old SSHFactory returned mappings from key names to strings from
getPublicKeys(). We return those here for testing.
"""
def getPublicKeys(self):
"""
We used to map key types to public key blobs as strings.
"""
keys = MockFactory.getPublicKeys(self)
for name, key in keys.items()[:]:
keys[name] = key.blob()
return keys
class MockOldFactoryPrivateKeys(MockFactory):
"""
The old SSHFactory returned mappings from key names to cryptography key
objects from getPrivateKeys(). We return those here for testing.
"""
def getPrivateKeys(self):
"""
We used to map key types to cryptography key objects.
"""
keys = MockFactory.getPrivateKeys(self)
for name, key in keys.items()[:]:
keys[name] = key.keyObject
return keys
def generatePredictableKey(transport):
p = transport.p
g = transport.g
bits = p.bit_length()
x = sum(0x9 << x for x
in range(0, bits-3, 4))
# The cryptography module doesn't let us create a secret key directly from
# an "x" value; we need to compute the public value ourselves.
y = pow(g, x, p)
try:
transport.dhSecretKey = dh.DHPrivateNumbers(
x,
dh.DHPublicNumbers(
y,
dh.DHParameterNumbers(p, g)
)
).private_key(default_backend())
except ValueError:
print("\np=%s\ng=%s\nx=%s\n" % (p, g, x))
raise
transport.dhSecretKeyPublicMP = common.MP(
transport.dhSecretKey
.public_key()
.public_numbers()
.y
)
class TransportTestCase(unittest.TestCase):
"""
Base class for transport test cases.
"""
klass = None
if dependencySkip:
skip = dependencySkip
def setUp(self):
self.transport = proto_helpers.StringTransport()
self.proto = self.klass()
self.packets = []
def secureRandom(len):
"""
Return a consistent entropy value
"""
return b'\x99' * len
self.patch(randbytes, 'secureRandom', secureRandom)
self.proto._startEphemeralDH = types.MethodType(
generatePredictableKey, self.proto)
def stubSendPacket(messageType, payload):
self.packets.append((messageType, payload))
self.proto.makeConnection(self.transport)
# we just let the kex packet go into the transport
self.proto.sendPacket = stubSendPacket
def finishKeyExchange(self, proto):
"""
Deliver enough additional messages to C{proto} so that the key exchange
which is started in L{SSHTransportBase.connectionMade} completes and
non-key exchange messages can be sent and received.
"""
proto.dataReceived(b"SSH-2.0-BogoClient-1.2i\r\n")
proto.dispatchMessage(
transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
proto._keySetup(b"foo", b"bar")
# SSHTransportBase can't handle MSG_NEWKEYS, or it would be the right
# thing to deliver next. _newKeys won't work either, because
# sendKexInit (probably) hasn't been called. sendKexInit is
# responsible for setting up certain state _newKeys relies on. So,
# just change the key exchange state to what it would be when key
# exchange is finished.
proto._keyExchangeState = proto._KEY_EXCHANGE_NONE
def simulateKeyExchange(self, sharedSecret, exchangeHash):
"""
Finish a key exchange by calling C{_keySetup} with the given arguments.
Also do extra whitebox stuff to satisfy that method's assumption that
some kind of key exchange has actually taken place.
"""
self.proto._keyExchangeState = self.proto._KEY_EXCHANGE_REQUESTED
self.proto._blockedByKeyExchange = []
self.proto._keySetup(sharedSecret, exchangeHash)
class DHGroupExchangeSHA1Mixin:
"""
Mixin for diffie-hellman-group-exchange-sha1 tests.
"""
kexAlgorithm = b'diffie-hellman-group-exchange-sha1'
hashProcessor = sha1
class DHGroupExchangeSHA256Mixin:
"""
Mixin for diffie-hellman-group-exchange-sha256 tests.
"""
kexAlgorithm = b'diffie-hellman-group-exchange-sha256'
hashProcessor = sha256
class ECDHMixin:
"""
Mixin for elliptic curve diffie-hellman tests.
"""
kexAlgorithm = b'ecdh-sha2-nistp256'
hashProcessor = sha256
class BaseSSHTransportBaseCase:
"""
Base case for TransportBase tests.
"""
klass = MockTransportBase
class BaseSSHTransportTests(BaseSSHTransportBaseCase, TransportTestCase):
"""
Test TransportBase. It implements the non-server/client specific
parts of the SSH transport protocol.
"""
if dependencySkip:
skip = dependencySkip
_A_KEXINIT_MESSAGE = (
b"\xAA" * 16 +
common.NS(b'diffie-hellman-group14-sha1') +
common.NS(b'ssh-rsa') +
common.NS(b'aes256-ctr') +
common.NS(b'aes256-ctr') +
common.NS(b'hmac-sha1') +
common.NS(b'hmac-sha1') +
common.NS(b'none') +
common.NS(b'none') +
common.NS(b'') +
common.NS(b'') +
b'\x00' + b'\x00\x00\x00\x00')
def test_sendVersion(self):
"""
Test that the first thing sent over the connection is the version
string. The 'softwareversion' part must consist of printable
US-ASCII characters, with the exception of whitespace characters and
the minus sign.
RFC 4253, section 4.2.
"""
# the other setup was done in the setup method
version = self.transport.value().split(b'\r\n', 1)[0]
self.assertEqual(version,
b"SSH-2.0-Twisted_" + twisted_version.encode('ascii'))
softwareVersion = version.decode('ascii')[len('SSH-2.0-'):]
# This is an inefficient regex, but it's simple to build.
softwareVersionRegex = (
r'^(' +
'|'.join(
re.escape(c) for c in string.printable
if c != '-' and not c.isspace()) +
r')*$')
self.assertRegex(softwareVersion, softwareVersionRegex)
def test_sendPacketPlain(self):
"""
Test that plain (unencrypted, uncompressed) packets are sent
correctly. The format is::
uint32 length (including type and padding length)
byte padding length
byte type
bytes[length-padding length-2] data
bytes[padding length] padding
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
self.transport.clear()
message = ord('A')
payload = b'BCDEFG'
proto.sendPacket(message, payload)
value = self.transport.value()
self.assertEqual(value, b'\x00\x00\x00\x0c\x04ABCDEFG\x99\x99\x99\x99')
def test_sendPacketEncrypted(self):
"""
Test that packets sent while encryption is enabled are sent
correctly. The whole packet should be encrypted.
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
proto.currentEncryptions = testCipher = MockCipher()
message = ord('A')
payload = b'BC'
self.transport.clear()
proto.sendPacket(message, payload)
self.assertTrue(testCipher.usedEncrypt)
value = self.transport.value()
self.assertEqual(
value,
# Four byte length prefix
b'\x00\x00\x00\x08'
# One byte padding length
b'\x04'
# The actual application data
b'ABC'
# "Random" padding - see the secureRandom monkeypatch in setUp
b'\x99\x99\x99\x99'
# The MAC
b'\x02')
def test_sendPacketCompressed(self):
"""
Test that packets sent while compression is enabled are sent
correctly. The packet type and data should be encrypted.
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
proto.outgoingCompression = MockCompression()
self.transport.clear()
proto.sendPacket(ord('A'), b'B')
value = self.transport.value()
self.assertEqual(
value,
b'\x00\x00\x00\x0c\x08BA\x66\x99\x99\x99\x99\x99\x99\x99\x99')
def test_sendPacketBoth(self):
"""
Test that packets sent while compression and encryption are
enabled are sent correctly. The packet type and data should be
compressed and then the whole packet should be encrypted.
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
proto.currentEncryptions = testCipher = MockCipher()
proto.outgoingCompression = MockCompression()
message = ord('A')
payload = b'BC'
self.transport.clear()
proto.sendPacket(message, payload)
self.assertTrue(testCipher.usedEncrypt)
value = self.transport.value()
self.assertEqual(
value,
# Four byte length prefix
b'\x00\x00\x00\x0e'
# One byte padding length
b'\x09'
# Compressed application data
b'CBA\x66'
# "Random" padding - see the secureRandom monkeypatch in setUp
b'\x99\x99\x99\x99\x99\x99\x99\x99\x99'
# The MAC
b'\x02')
def test_getPacketPlain(self):
"""
Test that packets are retrieved correctly out of the buffer when
no encryption is enabled.
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
self.transport.clear()
proto.sendPacket(ord('A'), b'BC')
proto.buf = self.transport.value() + b'extra'
self.assertEqual(proto.getPacket(), b'ABC')
self.assertEqual(proto.buf, b'extra')
def test_getPacketEncrypted(self):
"""
Test that encrypted packets are retrieved correctly.
See test_sendPacketEncrypted.
"""
proto = MockTransportBase()
proto.sendKexInit = lambda: None # don't send packets
proto.makeConnection(self.transport)
self.transport.clear()
proto.currentEncryptions = testCipher = MockCipher()
proto.sendPacket(ord('A'), b'BCD')
value = self.transport.value()
proto.buf = value[:MockCipher.decBlockSize]
self.assertIsNone(proto.getPacket())
self.assertTrue(testCipher.usedDecrypt)
self.assertEqual(proto.first, b'\x00\x00\x00\x0e\x09A')
proto.buf += value[MockCipher.decBlockSize:]
self.assertEqual(proto.getPacket(), b'ABCD')
self.assertEqual(proto.buf, b'')
def test_getPacketCompressed(self):
"""
Test that compressed packets are retrieved correctly. See
test_sendPacketCompressed.
"""
proto = MockTransportBase()
proto.makeConnection(self.transport)
self.finishKeyExchange(proto)
self.transport.clear()
proto.outgoingCompression = MockCompression()
proto.incomingCompression = proto.outgoingCompression
proto.sendPacket(ord('A'), b'BCD')
proto.buf = self.transport.value()
self.assertEqual(proto.getPacket(), b'ABCD')
def test_getPacketBoth(self):
"""
Test that compressed and encrypted packets are retrieved correctly.
See test_sendPacketBoth.
"""
proto = MockTransportBase()
proto.sendKexInit = lambda: None
proto.makeConnection(self.transport)
self.transport.clear()
proto.currentEncryptions = MockCipher()
proto.outgoingCompression = MockCompression()
proto.incomingCompression = proto.outgoingCompression
proto.sendPacket(ord('A'), b'BCDEFG')
proto.buf = self.transport.value()
self.assertEqual(proto.getPacket(), b'ABCDEFG')
def test_ciphersAreValid(self):
"""
Test that all the supportedCiphers are valid.
"""
ciphers = transport.SSHCiphers(b'A', b'B', b'C', b'D')
iv = key = b'\x00' * 16
for cipName in self.proto.supportedCiphers:
self.assertTrue(ciphers._getCipher(cipName, iv, key))
def test_sendKexInit(self):
"""
Test that the KEXINIT (key exchange initiation) message is sent
correctly. Payload::
bytes[16] cookie
string key exchange algorithms
string public key algorithms
string outgoing ciphers
string incoming ciphers
string outgoing MACs
string incoming MACs
string outgoing compressions
string incoming compressions
bool first packet follows
uint32 0
"""
value = self.transport.value().split(b'\r\n', 1)[1]
self.proto.buf = value
packet = self.proto.getPacket()
self.assertEqual(packet[0:1], chr(transport.MSG_KEXINIT))
self.assertEqual(packet[1:17], b'\x99' * 16)
(keyExchanges, pubkeys, ciphers1, ciphers2, macs1, macs2,
compressions1, compressions2, languages1, languages2,
buf) = common.getNS(packet[17:], 10)
self.assertEqual(
keyExchanges, b','.join(self.proto.supportedKeyExchanges))
self.assertEqual(pubkeys, b','.join(self.proto.supportedPublicKeys))
self.assertEqual(ciphers1, b','.join(self.proto.supportedCiphers))
self.assertEqual(ciphers2, b','.join(self.proto.supportedCiphers))
self.assertEqual(macs1, b','.join(self.proto.supportedMACs))
self.assertEqual(macs2, b','.join(self.proto.supportedMACs))
self.assertEqual(compressions1,
b','.join(self.proto.supportedCompressions))
self.assertEqual(compressions2,
b','.join(self.proto.supportedCompressions))
self.assertEqual(languages1, b','.join(self.proto.supportedLanguages))
self.assertEqual(languages2, b','.join(self.proto.supportedLanguages))
self.assertEqual(buf, b'\x00' * 5)
def test_receiveKEXINITReply(self):
"""
Immediately after connecting, the transport expects a KEXINIT message
and does not reply to it.
"""
self.transport.clear()
self.proto.dispatchMessage(
transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
self.assertEqual(self.packets, [])
def test_sendKEXINITReply(self):
"""
When a KEXINIT message is received which is not a reply to an earlier
KEXINIT message which was sent, a KEXINIT reply is sent.
"""
self.finishKeyExchange(self.proto)
del self.packets[:]
self.proto.dispatchMessage(
transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
self.assertEqual(len(self.packets), 1)
self.assertEqual(self.packets[0][0], transport.MSG_KEXINIT)
def test_sendKexInitTwiceFails(self):
"""
A new key exchange cannot be started while a key exchange is already in
progress. If an attempt is made to send a I{KEXINIT} message using
L{SSHTransportBase.sendKexInit} while a key exchange is in progress
causes that method to raise a L{RuntimeError}.
"""
self.assertRaises(RuntimeError, self.proto.sendKexInit)
def test_sendKexInitBlocksOthers(self):
"""
After L{SSHTransportBase.sendKexInit} has been called, messages types
other than the following are queued and not sent until after I{NEWKEYS}
is sent by L{SSHTransportBase._keySetup}.
RFC 4253, section 7.1.
"""
# sendKexInit is called by connectionMade, which is called in setUp.
# So we're in the state already.
disallowedMessageTypes = [
transport.MSG_SERVICE_REQUEST,
transport.MSG_KEXINIT,
]
# Drop all the bytes sent by setUp, they're not relevant to this test.
self.transport.clear()
# Get rid of the sendPacket monkey patch, we are testing the behavior
# of sendPacket.
del self.proto.sendPacket
for messageType in disallowedMessageTypes:
self.proto.sendPacket(messageType, b'foo')
self.assertEqual(self.transport.value(), b"")
self.finishKeyExchange(self.proto)
# Make the bytes written to the transport cleartext so it's easier to
# make an assertion about them.
self.proto.nextEncryptions = MockCipher()
# Pseudo-deliver the peer's NEWKEYS message, which should flush the
# messages which were queued above.
self.proto._newKeys()
self.assertEqual(self.transport.value().count(b"foo"), 2)
def test_sendDebug(self):
"""
Test that debug messages are sent correctly. Payload::
bool always display
string debug message
string language
"""
self.proto.sendDebug(b"test", True, b'en')
self.assertEqual(
self.packets,
[(transport.MSG_DEBUG,
b"\x01\x00\x00\x00\x04test\x00\x00\x00\x02en")])
def test_receiveDebug(self):
"""
Test that debug messages are received correctly. See test_sendDebug.
"""
self.proto.dispatchMessage(
transport.MSG_DEBUG,
b'\x01\x00\x00\x00\x04test\x00\x00\x00\x02en')
self.proto.dispatchMessage(
transport.MSG_DEBUG,
b'\x00\x00\x00\x00\x06silent\x00\x00\x00\x02en')
self.assertEqual(
self.proto.debugs,
[(True, b'test', b'en'), (False, b'silent', b'en')])
def test_sendIgnore(self):
"""
Test that ignored messages are sent correctly. Payload::
string ignored data
"""
self.proto.sendIgnore(b"test")
self.assertEqual(
self.packets, [(transport.MSG_IGNORE,
b'\x00\x00\x00\x04test')])
def test_receiveIgnore(self):
"""
Test that ignored messages are received correctly. See
test_sendIgnore.
"""
self.proto.dispatchMessage(transport.MSG_IGNORE, b'test')
self.assertEqual(self.proto.ignoreds, [b'test'])
def test_sendUnimplemented(self):
"""
Test that unimplemented messages are sent correctly. Payload::
uint32 sequence number
"""
self.proto.sendUnimplemented()
self.assertEqual(
self.packets, [(transport.MSG_UNIMPLEMENTED,
b'\x00\x00\x00\x00')])
def test_receiveUnimplemented(self):
"""
Test that unimplemented messages are received correctly. See
test_sendUnimplemented.
"""
self.proto.dispatchMessage(transport.MSG_UNIMPLEMENTED,
b'\x00\x00\x00\xff')
self.assertEqual(self.proto.unimplementeds, [255])
def test_sendDisconnect(self):
"""
Test that disconnection messages are sent correctly. Payload::
uint32 reason code
string reason description
string language
"""
disconnected = [False]
def stubLoseConnection():
disconnected[0] = True
self.transport.loseConnection = stubLoseConnection
self.proto.sendDisconnect(0xff, b"test")
self.assertEqual(
self.packets,
[(transport.MSG_DISCONNECT,
b"\x00\x00\x00\xff\x00\x00\x00\x04test\x00\x00\x00\x00")])
self.assertTrue(disconnected[0])
def test_receiveDisconnect(self):
"""
Test that disconnection messages are received correctly. See
test_sendDisconnect.
"""
disconnected = [False]
def stubLoseConnection():
disconnected[0] = True
self.transport.loseConnection = stubLoseConnection
self.proto.dispatchMessage(transport.MSG_DISCONNECT,
b'\x00\x00\x00\xff\x00\x00\x00\x04test')
self.assertEqual(self.proto.errors, [(255, b'test')])
self.assertTrue(disconnected[0])
def test_dataReceived(self):
"""
Test that dataReceived parses packets and dispatches them to
ssh_* methods.
"""
kexInit = [False]
def stubKEXINIT(packet):
kexInit[0] = True
self.proto.ssh_KEXINIT = stubKEXINIT
self.proto.dataReceived(self.transport.value())
self.assertTrue(self.proto.gotVersion)
self.assertEqual(self.proto.ourVersionString,
self.proto.otherVersionString)
self.assertTrue(kexInit[0])
def test_service(self):
"""
Test that the transport can set the running service and dispatches
packets to the service's packetReceived method.
"""
service = MockService()
self.proto.setService(service)
self.assertEqual(self.proto.service, service)
self.assertTrue(service.started)
self.proto.dispatchMessage(0xff, b"test")
self.assertEqual(self.packets, [(0xff, b"test")])
service2 = MockService()
self.proto.setService(service2)
self.assertTrue(service2.started)
self.assertTrue(service.stopped)
self.proto.connectionLost(None)
self.assertTrue(service2.stopped)
def test_avatar(self):
"""
Test that the transport notifies the avatar of disconnections.
"""
disconnected = [False]
def logout():
disconnected[0] = True
self.proto.logoutFunction = logout
self.proto.avatar = True
self.proto.connectionLost(None)
self.assertTrue(disconnected[0])
def test_isEncrypted(self):
"""
Test that the transport accurately reflects its encrypted status.
"""
self.assertFalse(self.proto.isEncrypted('in'))
self.assertFalse(self.proto.isEncrypted('out'))
self.assertFalse(self.proto.isEncrypted('both'))
self.proto.currentEncryptions = MockCipher()
self.assertTrue(self.proto.isEncrypted('in'))
self.assertTrue(self.proto.isEncrypted('out'))
self.assertTrue(self.proto.isEncrypted('both'))
self.proto.currentEncryptions = transport.SSHCiphers(b'none', b'none',
b'none', b'none')
self.assertFalse(self.proto.isEncrypted('in'))
self.assertFalse(self.proto.isEncrypted('out'))
self.assertFalse(self.proto.isEncrypted('both'))
self.assertRaises(TypeError, self.proto.isEncrypted, 'bad')
def test_isVerified(self):
"""
Test that the transport accurately reflects its verified status.
"""
self.assertFalse(self.proto.isVerified('in'))
self.assertFalse(self.proto.isVerified('out'))
self.assertFalse(self.proto.isVerified('both'))
self.proto.currentEncryptions = MockCipher()
self.assertTrue(self.proto.isVerified('in'))
self.assertTrue(self.proto.isVerified('out'))