forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.py
1639 lines (1345 loc) · 58.3 KB
/
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
# -*- test-case-name: twisted.conch.test.test_transport -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
The lowest level SSH protocol. This handles the key negotiation, the
encryption and the compression. The transport layer is described in
RFC 4253.
Maintainer: Paul Swartz
"""
# base library imports
import struct
import zlib
import array
from hashlib import md5, sha1
import string
import hmac
# external library imports
from Crypto import Util
# twisted imports
from twisted.internet import protocol, defer
from twisted.conch import error
from twisted.python import log, randbytes
# sibling imports
from twisted.conch.ssh import address, keys
from twisted.conch.ssh.common import NS, getNS, MP, getMP, _MPpow, ffs
def _getRandomNumber(random, bits):
"""
Generate a random number in the range [0, 2 ** bits).
@param bits: The number of bits in the result.
@type bits: C{int}
@rtype: C{int} or C{long}
@return: The newly generated random number.
@raise ValueError: if C{bits} is not a multiple of 8.
"""
if bits % 8:
raise ValueError("bits (%d) must be a multiple of 8" % (bits,))
bytes = random(bits / 8)
result = Util.number.bytes_to_long(bytes)
return result
def _generateX(random, bits):
"""
Generate a new value for the private key x.
From RFC 2631, section 2.2::
X9.42 requires that the private key x be in the interval
[2, (q - 2)]. x should be randomly generated in this interval.
"""
while True:
x = _getRandomNumber(random, bits)
if 2 <= x <= (2 ** bits) - 2:
return x
class _MACParams(tuple):
"""
L{_MACParams} represents the parameters necessary to compute SSH MAC
(Message Authenticate Codes).
L{_MACParams} is a L{tuple} subclass to maintain compatibility with older
versions of the code. The elements of a L{_MACParams} are::
0. The digest object used for the MAC
1. The inner pad ("ipad") string
2. The outer pad ("opad") string
3. The size of the digest produced by the digest object
L{_MACParams} is also an object lesson in why tuples are a bad type for
public APIs.
@ivar key: The HMAC key which will be used.
"""
class SSHTransportBase(protocol.Protocol):
"""
Protocol supporting basic SSH functionality: sending/receiving packets
and message dispatch. To connect to or run a server, you must use
SSHClientTransport or SSHServerTransport.
@ivar protocolVersion: A string representing the version of the SSH
protocol we support. Currently defaults to '2.0'.
@ivar version: A string representing the version of the server or client.
Currently defaults to 'Twisted'.
@ivar comment: An optional string giving more information about the
server or client.
@ivar supportedCiphers: A list of strings representing the encryption
algorithms supported, in order from most-preferred to least.
@ivar supportedMACs: A list of strings representing the message
authentication codes (hashes) supported, in order from most-preferred
to least. Both this and supportedCiphers can include 'none' to use
no encryption or authentication, but that must be done manually,
@ivar supportedKeyExchanges: A list of strings representing the
key exchanges supported, in order from most-preferred to least.
@ivar supportedPublicKeys: A list of strings representing the
public key types supported, in order from most-preferred to least.
@ivar supportedCompressions: A list of strings representing compression
types supported, from most-preferred to least.
@ivar supportedLanguages: A list of strings representing languages
supported, from most-preferred to least.
@ivar supportedVersions: A container of strings representing supported ssh
protocol version numbers.
@ivar isClient: A boolean indicating whether this is a client or server.
@ivar gotVersion: A boolean indicating whether we have receieved the
version string from the other side.
@ivar buf: Data we've received but hasn't been parsed into a packet.
@ivar outgoingPacketSequence: the sequence number of the next packet we
will send.
@ivar incomingPacketSequence: the sequence number of the next packet we
are expecting from the other side.
@ivar outgoingCompression: an object supporting the .compress(str) and
.flush() methods, or None if there is no outgoing compression. Used to
compress outgoing data.
@ivar outgoingCompressionType: A string representing the outgoing
compression type.
@ivar incomingCompression: an object supporting the .decompress(str)
method, or None if there is no incoming compression. Used to
decompress incoming data.
@ivar incomingCompressionType: A string representing the incoming
compression type.
@ivar ourVersionString: the version string that we sent to the other side.
Used in the key exchange.
@ivar otherVersionString: the version string sent by the other side. Used
in the key exchange.
@ivar ourKexInitPayload: the MSG_KEXINIT payload we sent. Used in the key
exchange.
@ivar otherKexInitPayload: the MSG_KEXINIT payload we received. Used in
the key exchange
@ivar sessionID: a string that is unique to this SSH session. Created as
part of the key exchange, sessionID is used to generate the various
encryption and authentication keys.
@ivar service: an SSHService instance, or None. If it's set to an object,
it's the currently running service.
@ivar kexAlg: the agreed-upon key exchange algorithm.
@ivar keyAlg: the agreed-upon public key type for the key exchange.
@ivar currentEncryptions: an SSHCiphers instance. It represents the
current encryption and authentication options for the transport.
@ivar nextEncryptions: an SSHCiphers instance. Held here until the
MSG_NEWKEYS messages are exchanged, when nextEncryptions is
transitioned to currentEncryptions.
@ivar first: the first bytes of the next packet. In order to avoid
decrypting data twice, the first bytes are decrypted and stored until
the whole packet is available.
@ivar _keyExchangeState: The current protocol state with respect to key
exchange. This is either C{_KEY_EXCHANGE_NONE} if no key exchange is
in progress (and returns to this value after any key exchange
completqes), C{_KEY_EXCHANGE_REQUESTED} if this side of the connection
initiated a key exchange, and C{_KEY_EXCHANGE_PROGRESSING} if the other
side of the connection initiated a key exchange. C{_KEY_EXCHANGE_NONE}
is the initial value (however SSH connections begin with key exchange,
so it will quickly change to another state).
@ivar _blockedByKeyExchange: Whenever C{_keyExchangeState} is not
C{_KEY_EXCHANGE_NONE}, this is a C{list} of pending messages which were
passed to L{sendPacket} but could not be sent because it is not legal
to send them while a key exchange is in progress. When the key
exchange completes, another attempt is made to send these messages.
"""
protocolVersion = '2.0'
version = 'Twisted'
comment = ''
ourVersionString = ('SSH-' + protocolVersion + '-' + version + ' '
+ comment).strip()
supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc',
'aes128-ctr', 'aes128-cbc', 'cast128-ctr',
'cast128-cbc', 'blowfish-ctr', 'blowfish-cbc',
'3des-ctr', '3des-cbc'] # ,'none']
supportedMACs = ['hmac-sha1', 'hmac-md5'] # , 'none']
# both of the above support 'none', but for security are disabled by
# default. to enable them, subclass this class and add it, or do:
# SSHTransportBase.supportedCiphers.append('none')
supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1',
'diffie-hellman-group1-sha1']
supportedPublicKeys = ['ssh-rsa', 'ssh-dss']
supportedCompressions = ['none', 'zlib']
supportedLanguages = ()
supportedVersions = ('1.99', '2.0')
isClient = False
gotVersion = False
buf = ''
outgoingPacketSequence = 0
incomingPacketSequence = 0
outgoingCompression = None
incomingCompression = None
sessionID = None
service = None
# There is no key exchange activity in progress.
_KEY_EXCHANGE_NONE = '_KEY_EXCHANGE_NONE'
# Key exchange is in progress and we started it.
_KEY_EXCHANGE_REQUESTED = '_KEY_EXCHANGE_REQUESTED'
# Key exchange is in progress and both sides have sent KEXINIT messages.
_KEY_EXCHANGE_PROGRESSING = '_KEY_EXCHANGE_PROGRESSING'
# There is a fourth conceptual state not represented here: KEXINIT received
# but not sent. Since we always send a KEXINIT as soon as we get it, we
# can't ever be in that state.
# The current key exchange state.
_keyExchangeState = _KEY_EXCHANGE_NONE
_blockedByKeyExchange = None
def connectionLost(self, reason):
if self.service:
self.service.serviceStopped()
if hasattr(self, 'avatar'):
self.logoutFunction()
log.msg('connection lost')
def connectionMade(self):
"""
Called when the connection is made to the other side. We sent our
version and the MSG_KEXINIT packet.
"""
self.transport.write('%s\r\n' % (self.ourVersionString,))
self.currentEncryptions = SSHCiphers('none', 'none', 'none', 'none')
self.currentEncryptions.setKeys('', '', '', '', '', '')
self.sendKexInit()
def sendKexInit(self):
"""
Send a I{KEXINIT} message to initiate key exchange or to respond to a
key exchange initiated by the peer.
@raise RuntimeError: If a key exchange has already been started and it
is not appropriate to send a I{KEXINIT} message at this time.
@return: C{None}
"""
if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
raise RuntimeError(
"Cannot send KEXINIT while key exchange state is %r" % (
self._keyExchangeState,))
self.ourKexInitPayload = (chr(MSG_KEXINIT) +
randbytes.secureRandom(16) +
NS(','.join(self.supportedKeyExchanges)) +
NS(','.join(self.supportedPublicKeys)) +
NS(','.join(self.supportedCiphers)) +
NS(','.join(self.supportedCiphers)) +
NS(','.join(self.supportedMACs)) +
NS(','.join(self.supportedMACs)) +
NS(','.join(self.supportedCompressions)) +
NS(','.join(self.supportedCompressions)) +
NS(','.join(self.supportedLanguages)) +
NS(','.join(self.supportedLanguages)) +
'\000' + '\000\000\000\000')
self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
self._keyExchangeState = self._KEY_EXCHANGE_REQUESTED
self._blockedByKeyExchange = []
def _allowedKeyExchangeMessageType(self, messageType):
"""
Determine if the given message type may be sent while key exchange is
in progress.
@param messageType: The type of message
@type messageType: C{int}
@return: C{True} if the given type of message may be sent while key
exchange is in progress, C{False} if it may not.
@rtype: C{bool}
@see: U{http://tools.ietf.org/html/rfc4253#section-7.1}
"""
# Written somewhat peculularly to reflect the way the specification
# defines the allowed message types.
if 1 <= messageType <= 19:
return messageType not in (MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT)
if 20 <= messageType <= 29:
return messageType not in (MSG_KEXINIT,)
return 30 <= messageType <= 49
def sendPacket(self, messageType, payload):
"""
Sends a packet. If it's been set up, compress the data, encrypt it,
and authenticate it before sending. If key exchange is in progress and
the message is not part of key exchange, queue it to be sent later.
@param messageType: The type of the packet; generally one of the
MSG_* values.
@type messageType: C{int}
@param payload: The payload for the message.
@type payload: C{str}
"""
if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
if not self._allowedKeyExchangeMessageType(messageType):
self._blockedByKeyExchange.append((messageType, payload))
return
payload = chr(messageType) + payload
if self.outgoingCompression:
payload = (self.outgoingCompression.compress(payload)
+ self.outgoingCompression.flush(2))
bs = self.currentEncryptions.encBlockSize
# 4 for the packet length and 1 for the padding length
totalSize = 5 + len(payload)
lenPad = bs - (totalSize % bs)
if lenPad < 4:
lenPad = lenPad + bs
packet = (struct.pack('!LB',
totalSize + lenPad - 4, lenPad) +
payload + randbytes.secureRandom(lenPad))
encPacket = (
self.currentEncryptions.encrypt(packet) +
self.currentEncryptions.makeMAC(
self.outgoingPacketSequence, packet))
self.transport.write(encPacket)
self.outgoingPacketSequence += 1
def getPacket(self):
"""
Try to return a decrypted, authenticated, and decompressed packet
out of the buffer. If there is not enough data, return None.
@rtype: C{str}/C{None}
"""
bs = self.currentEncryptions.decBlockSize
ms = self.currentEncryptions.verifyDigestSize
if len(self.buf) < bs: return # not enough data
if not hasattr(self, 'first'):
first = self.currentEncryptions.decrypt(self.buf[:bs])
else:
first = self.first
del self.first
packetLen, paddingLen = struct.unpack('!LB', first[:5])
if packetLen > 1048576: # 1024 ** 2
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
'bad packet length %s' % packetLen)
return
if len(self.buf) < packetLen + 4 + ms:
self.first = first
return # not enough packet
if(packetLen + 4) % bs != 0:
self.sendDisconnect(
DISCONNECT_PROTOCOL_ERROR,
'bad packet mod (%i%%%i == %i)' % (packetLen + 4, bs,
(packetLen + 4) % bs))
return
encData, self.buf = self.buf[:4 + packetLen], self.buf[4 + packetLen:]
packet = first + self.currentEncryptions.decrypt(encData[bs:])
if len(packet) != 4 + packetLen:
self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
'bad decryption')
return
if ms:
macData, self.buf = self.buf[:ms], self.buf[ms:]
if not self.currentEncryptions.verify(self.incomingPacketSequence,
packet, macData):
self.sendDisconnect(DISCONNECT_MAC_ERROR, 'bad MAC')
return
payload = packet[5:-paddingLen]
if self.incomingCompression:
try:
payload = self.incomingCompression.decompress(payload)
except: # bare except, because who knows what kind of errors
# decompression can raise
log.err()
self.sendDisconnect(DISCONNECT_COMPRESSION_ERROR,
'compression error')
return
self.incomingPacketSequence += 1
return payload
def _unsupportedVersionReceived(self, remoteVersion):
"""
Called when an unsupported version of the ssh protocol is received from
the remote endpoint.
@param remoteVersion: remote ssh protocol version which is unsupported
by us.
@type remoteVersion: C{str}
"""
self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
'bad version ' + remoteVersion)
def dataReceived(self, data):
"""
First, check for the version string (SSH-2.0-*). After that has been
received, this method adds data to the buffer, and pulls out any
packets.
@type data: C{str}
"""
self.buf = self.buf + data
if not self.gotVersion:
if self.buf.find('\n', self.buf.find('SSH-')) == -1:
return
lines = self.buf.split('\n')
for p in lines:
if p.startswith('SSH-'):
self.gotVersion = True
self.otherVersionString = p.strip()
remoteVersion = p.split('-')[1]
if remoteVersion not in self.supportedVersions:
self._unsupportedVersionReceived(remoteVersion)
return
i = lines.index(p)
self.buf = '\n'.join(lines[i + 1:])
packet = self.getPacket()
while packet:
messageNum = ord(packet[0])
self.dispatchMessage(messageNum, packet[1:])
packet = self.getPacket()
def dispatchMessage(self, messageNum, payload):
"""
Send a received message to the appropriate method.
@type messageNum: C{int}
@type payload: c{str}
"""
if messageNum < 50 and messageNum in messages:
messageType = messages[messageNum][4:]
f = getattr(self, 'ssh_%s' % messageType, None)
if f is not None:
f(payload)
else:
log.msg("couldn't handle %s" % messageType)
log.msg(repr(payload))
self.sendUnimplemented()
elif self.service:
log.callWithLogger(self.service, self.service.packetReceived,
messageNum, payload)
else:
log.msg("couldn't handle %s" % messageNum)
log.msg(repr(payload))
self.sendUnimplemented()
def getPeer(self):
"""
Returns an L{SSHTransportAddress} corresponding to the other (peer)
side of this transport.
@return: L{SSHTransportAddress} for the peer
@rtype: L{SSHTransportAddress}
@since: 12.1
"""
return address.SSHTransportAddress(self.transport.getPeer())
def getHost(self):
"""
Returns an L{SSHTransportAddress} corresponding to the this side of
transport.
@return: L{SSHTransportAddress} for the peer
@rtype: L{SSHTransportAddress}
@since: 12.1
"""
return address.SSHTransportAddress(self.transport.getHost())
# Client-initiated rekeying looks like this:
#
# C> MSG_KEXINIT
# S> MSG_KEXINIT
# C> MSG_KEX_DH_GEX_REQUEST or MSG_KEXDH_INIT
# S> MSG_KEX_DH_GEX_GROUP or MSG_KEXDH_REPLY
# C> MSG_KEX_DH_GEX_INIT or --
# S> MSG_KEX_DH_GEX_REPLY or --
# C> MSG_NEWKEYS
# S> MSG_NEWKEYS
#
# Server-initiated rekeying is the same, only the first two messages are
# switched.
def ssh_KEXINIT(self, packet):
"""
Called when we receive a MSG_KEXINIT message. Payload::
bytes[16] cookie
string keyExchangeAlgorithms
string keyAlgorithms
string incomingEncryptions
string outgoingEncryptions
string incomingAuthentications
string outgoingAuthentications
string incomingCompressions
string outgoingCompressions
string incomingLanguages
string outgoingLanguages
bool firstPacketFollows
unit32 0 (reserved)
Starts setting up the key exchange, keys, encryptions, and
authentications. Extended by ssh_KEXINIT in SSHServerTransport and
SSHClientTransport.
"""
self.otherKexInitPayload = chr(MSG_KEXINIT) + packet
#cookie = packet[: 16] # taking this is useless
k = getNS(packet[16:], 10)
strings, rest = k[:-1], k[-1]
(kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS,
langSC) = [s.split(',') for s in strings]
# these are the server directions
outs = [encSC, macSC, compSC]
ins = [encCS, macSC, compCS]
if self.isClient:
outs, ins = ins, outs # switch directions
server = (self.supportedKeyExchanges, self.supportedPublicKeys,
self.supportedCiphers, self.supportedCiphers,
self.supportedMACs, self.supportedMACs,
self.supportedCompressions, self.supportedCompressions)
client = (kexAlgs, keyAlgs, outs[0], ins[0], outs[1], ins[1],
outs[2], ins[2])
if self.isClient:
server, client = client, server
self.kexAlg = ffs(client[0], server[0])
self.keyAlg = ffs(client[1], server[1])
self.nextEncryptions = SSHCiphers(
ffs(client[2], server[2]),
ffs(client[3], server[3]),
ffs(client[4], server[4]),
ffs(client[5], server[5]))
self.outgoingCompressionType = ffs(client[6], server[6])
self.incomingCompressionType = ffs(client[7], server[7])
if None in (self.kexAlg, self.keyAlg, self.outgoingCompressionType,
self.incomingCompressionType):
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
"couldn't match all kex parts")
return
if None in self.nextEncryptions.__dict__.values():
self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
"couldn't match all kex parts")
return
log.msg('kex alg, key alg: %s %s' % (self.kexAlg, self.keyAlg))
log.msg('outgoing: %s %s %s' % (self.nextEncryptions.outCipType,
self.nextEncryptions.outMACType,
self.outgoingCompressionType))
log.msg('incoming: %s %s %s' % (self.nextEncryptions.inCipType,
self.nextEncryptions.inMACType,
self.incomingCompressionType))
if self._keyExchangeState == self._KEY_EXCHANGE_REQUESTED:
self._keyExchangeState = self._KEY_EXCHANGE_PROGRESSING
else:
self.sendKexInit()
return kexAlgs, keyAlgs, rest # for SSHServerTransport to use
def ssh_DISCONNECT(self, packet):
"""
Called when we receive a MSG_DISCONNECT message. Payload::
long code
string description
This means that the other side has disconnected. Pass the message up
and disconnect ourselves.
"""
reasonCode = struct.unpack('>L', packet[: 4])[0]
description, foo = getNS(packet[4:])
self.receiveError(reasonCode, description)
self.transport.loseConnection()
def ssh_IGNORE(self, packet):
"""
Called when we receieve a MSG_IGNORE message. No payload.
This means nothing; we simply return.
"""
def ssh_UNIMPLEMENTED(self, packet):
"""
Called when we receieve a MSG_UNIMPLEMENTED message. Payload::
long packet
This means that the other side did not implement one of our packets.
"""
seqnum, = struct.unpack('>L', packet)
self.receiveUnimplemented(seqnum)
def ssh_DEBUG(self, packet):
"""
Called when we receieve a MSG_DEBUG message. Payload::
bool alwaysDisplay
string message
string language
This means the other side has passed along some debugging info.
"""
alwaysDisplay = bool(packet[0])
message, lang, foo = getNS(packet[1:], 2)
self.receiveDebug(alwaysDisplay, message, lang)
def setService(self, service):
"""
Set our service to service and start it running. If we were
running a service previously, stop it first.
@type service: C{SSHService}
"""
log.msg('starting service %s' % service.name)
if self.service:
self.service.serviceStopped()
self.service = service
service.transport = self
self.service.serviceStarted()
def sendDebug(self, message, alwaysDisplay=False, language=''):
"""
Send a debug message to the other side.
@param message: the message to send.
@type message: C{str}
@param alwaysDisplay: if True, tell the other side to always
display this message.
@type alwaysDisplay: C{bool}
@param language: optionally, the language the message is in.
@type language: C{str}
"""
self.sendPacket(MSG_DEBUG, chr(alwaysDisplay) + NS(message) +
NS(language))
def sendIgnore(self, message):
"""
Send a message that will be ignored by the other side. This is
useful to fool attacks based on guessing packet sizes in the
encrypted stream.
@param message: data to send with the message
@type message: C{str}
"""
self.sendPacket(MSG_IGNORE, NS(message))
def sendUnimplemented(self):
"""
Send a message to the other side that the last packet was not
understood.
"""
seqnum = self.incomingPacketSequence
self.sendPacket(MSG_UNIMPLEMENTED, struct.pack('!L', seqnum))
def sendDisconnect(self, reason, desc):
"""
Send a disconnect message to the other side and then disconnect.
@param reason: the reason for the disconnect. Should be one of the
DISCONNECT_* values.
@type reason: C{int}
@param desc: a descrption of the reason for the disconnection.
@type desc: C{str}
"""
self.sendPacket(
MSG_DISCONNECT, struct.pack('>L', reason) + NS(desc) + NS(''))
log.msg('Disconnecting with error, code %s\nreason: %s' % (reason,
desc))
self.transport.loseConnection()
def _getKey(self, c, sharedSecret, exchangeHash):
"""
Get one of the keys for authentication/encryption.
@type c: C{str}
@type sharedSecret: C{str}
@type exchangeHash: C{str}
"""
k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
k1 = k1.digest()
k2 = sha1(sharedSecret + exchangeHash + k1).digest()
return k1 + k2
def _keySetup(self, sharedSecret, exchangeHash):
"""
Set up the keys for the connection and sends MSG_NEWKEYS when
finished,
@param sharedSecret: a secret string agreed upon using a Diffie-
Hellman exchange, so it is only shared between
the server and the client.
@type sharedSecret: C{str}
@param exchangeHash: A hash of various data known by both sides.
@type exchangeHash: C{str}
"""
if not self.sessionID:
self.sessionID = exchangeHash
initIVCS = self._getKey('A', sharedSecret, exchangeHash)
initIVSC = self._getKey('B', sharedSecret, exchangeHash)
encKeyCS = self._getKey('C', sharedSecret, exchangeHash)
encKeySC = self._getKey('D', sharedSecret, exchangeHash)
integKeyCS = self._getKey('E', sharedSecret, exchangeHash)
integKeySC = self._getKey('F', sharedSecret, exchangeHash)
outs = [initIVSC, encKeySC, integKeySC]
ins = [initIVCS, encKeyCS, integKeyCS]
if self.isClient: # reverse for the client
log.msg('REVERSE')
outs, ins = ins, outs
self.nextEncryptions.setKeys(outs[0], outs[1], ins[0], ins[1],
outs[2], ins[2])
self.sendPacket(MSG_NEWKEYS, '')
def _newKeys(self):
"""
Called back by a subclass once a I{MSG_NEWKEYS} message has been
received. This indicates key exchange has completed and new encryption
and compression parameters should be adopted. Any messages which were
queued during key exchange will also be flushed.
"""
log.msg('NEW KEYS')
self.currentEncryptions = self.nextEncryptions
if self.outgoingCompressionType == 'zlib':
self.outgoingCompression = zlib.compressobj(6)
if self.incomingCompressionType == 'zlib':
self.incomingCompression = zlib.decompressobj()
self._keyExchangeState = self._KEY_EXCHANGE_NONE
messages = self._blockedByKeyExchange
self._blockedByKeyExchange = None
for (messageType, payload) in messages:
self.sendPacket(messageType, payload)
def isEncrypted(self, direction="out"):
"""
Return True if the connection is encrypted in the given direction.
Direction must be one of ["out", "in", "both"].
"""
if direction == "out":
return self.currentEncryptions.outCipType != 'none'
elif direction == "in":
return self.currentEncryptions.inCipType != 'none'
elif direction == "both":
return self.isEncrypted("in") and self.isEncrypted("out")
else:
raise TypeError('direction must be "out", "in", or "both"')
def isVerified(self, direction="out"):
"""
Return True if the connecction is verified/authenticated in the
given direction. Direction must be one of ["out", "in", "both"].
"""
if direction == "out":
return self.currentEncryptions.outMACType != 'none'
elif direction == "in":
return self.currentEncryptions.inMACType != 'none'
elif direction == "both":
return self.isVerified("in")and self.isVerified("out")
else:
raise TypeError('direction must be "out", "in", or "both"')
def loseConnection(self):
"""
Lose the connection to the other side, sending a
DISCONNECT_CONNECTION_LOST message.
"""
self.sendDisconnect(DISCONNECT_CONNECTION_LOST,
"user closed connection")
# client methods
def receiveError(self, reasonCode, description):
"""
Called when we receive a disconnect error message from the other
side.
@param reasonCode: the reason for the disconnect, one of the
DISCONNECT_ values.
@type reasonCode: C{int}
@param description: a human-readable description of the
disconnection.
@type description: C{str}
"""
log.msg('Got remote error, code %s\nreason: %s' % (reasonCode,
description))
def receiveUnimplemented(self, seqnum):
"""
Called when we receive an unimplemented packet message from the other
side.
@param seqnum: the sequence number that was not understood.
@type seqnum: C{int}
"""
log.msg('other side unimplemented packet #%s' % seqnum)
def receiveDebug(self, alwaysDisplay, message, lang):
"""
Called when we receive a debug message from the other side.
@param alwaysDisplay: if True, this message should always be
displayed.
@type alwaysDisplay: C{bool}
@param message: the debug message
@type message: C{str}
@param lang: optionally the language the message is in.
@type lang: C{str}
"""
if alwaysDisplay:
log.msg('Remote Debug Message: %s' % message)
class SSHServerTransport(SSHTransportBase):
"""
SSHServerTransport implements the server side of the SSH protocol.
@ivar isClient: since we are never the client, this is always False.
@ivar ignoreNextPacket: if True, ignore the next key exchange packet. This
is set when the client sends a guessed key exchange packet but with
an incorrect guess.
@ivar dhGexRequest: the KEX_DH_GEX_REQUEST(_OLD) that the client sent.
The key generation needs this to be stored.
@ivar g: the Diffie-Hellman group generator.
@ivar p: the Diffie-Hellman group prime.
"""
isClient = False
ignoreNextPacket = 0
def ssh_KEXINIT(self, packet):
"""
Called when we receive a MSG_KEXINIT message. For a description
of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
this method checks if a guessed key exchange packet was sent. If
it was sent, and it guessed incorrectly, the next key exchange
packet MUST be ignored.
"""
retval = SSHTransportBase.ssh_KEXINIT(self, packet)
if not retval: # disconnected
return
else:
kexAlgs, keyAlgs, rest = retval
if ord(rest[0]): # first_kex_packet_follows
if (kexAlgs[0] != self.supportedKeyExchanges[0] or
keyAlgs[0] != self.supportedPublicKeys[0]):
self.ignoreNextPacket = True # guess was wrong
def _ssh_KEXDH_INIT(self, packet):
"""
Called to handle the beginning of a diffie-hellman-group1-sha1 key
exchange.
Unlike other message types, this is not dispatched automatically. It
is called from C{ssh_KEX_DH_GEX_REQUEST_OLD} because an extra check is
required to determine if this is really a KEXDH_INIT message or if it
is a KEX_DH_GEX_REQUEST_OLD message.
The KEXDH_INIT (for diffie-hellman-group1-sha1 exchanges) payload::
integer e (the client's Diffie-Hellman public key)
We send the KEXDH_REPLY with our host key and signature.
"""
clientDHpublicKey, foo = getMP(packet)
y = _getRandomNumber(randbytes.secureRandom, 512)
serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
h = sha1()
h.update(NS(self.otherVersionString))
h.update(NS(self.ourVersionString))
h.update(NS(self.otherKexInitPayload))
h.update(NS(self.ourKexInitPayload))
h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
h.update(MP(clientDHpublicKey))
h.update(serverDHpublicKey)
h.update(sharedSecret)
exchangeHash = h.digest()
self.sendPacket(
MSG_KEXDH_REPLY,
NS(self.factory.publicKeys[self.keyAlg].blob()) +
serverDHpublicKey +
NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
self._keySetup(sharedSecret, exchangeHash)
def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
"""
This represents two different key exchange methods that share the same
integer value. If the message is determined to be a KEXDH_INIT,
C{_ssh_KEXDH_INIT} is called to handle it. Otherwise, for
KEX_DH_GEX_REQUEST_OLD (for diffie-hellman-group-exchange-sha1)
payload::
integer ideal (ideal size for the Diffie-Hellman prime)
We send the KEX_DH_GEX_GROUP message with the group that is
closest in size to ideal.
If we were told to ignore the next key exchange packet by ssh_KEXINIT,
drop it on the floor and return.
"""
if self.ignoreNextPacket:
self.ignoreNextPacket = 0
return
# KEXDH_INIT and KEX_DH_GEX_REQUEST_OLD have the same value, so use
# another cue to decide what kind of message the peer sent us.
if self.kexAlg == 'diffie-hellman-group1-sha1':
return self._ssh_KEXDH_INIT(packet)
elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
self.dhGexRequest = packet
ideal = struct.unpack('>L', packet)[0]
self.g, self.p = self.factory.getDHPrime(ideal)
self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
else:
raise error.ConchError('bad kexalg: %s' % self.kexAlg)
def ssh_KEX_DH_GEX_REQUEST(self, packet):
"""
Called when we receive a MSG_KEX_DH_GEX_REQUEST message. Payload::
integer minimum
integer ideal
integer maximum
The client is asking for a Diffie-Hellman group between minimum and
maximum size, and close to ideal if possible. We reply with a
MSG_KEX_DH_GEX_GROUP message.
If we were told to ignore the next key exchange packet by ssh_KEXINIT,
drop it on the floor and return.
"""
if self.ignoreNextPacket:
self.ignoreNextPacket = 0
return
self.dhGexRequest = packet
min, ideal, max = struct.unpack('>3L', packet)
self.g, self.p = self.factory.getDHPrime(ideal)
self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
def ssh_KEX_DH_GEX_INIT(self, packet):
"""