-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmn1.py
1491 lines (1132 loc) · 49 KB
/
mn1.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) 2014-2015 Sam Maloney.
# License: LGPL
import llog
import asyncio
from enum import Enum
import struct
import logging
import os
from Crypto.Cipher import AES
from hashlib import sha1
import hmac
import packet as mnetpacket
import kex
import kexdhgroup14sha1
import rsakey
import sshtype
from sshexception import SshException
from mutil import hex_dump
MAX_PACKET_LENGTH = 35000
log = logging.getLogger(__name__)
server_key = None
client_key = None
cleartext_transport_enabled = False
def enable_cleartext_transport():
global cleartext_transport_enabled
cleartext_transport_enabled = True
class Status(Enum):
new = 0
ready = 10
closed = 20
disconnected = 30
class ChannelStatus(Enum):
opening = -1
closing = -2
implicit_data_sent = -3
class SshProtocol(asyncio.Protocol):
def __init__(self, loop):
self.loop = loop
self.address = None # (host, port)
self.transport = None
self._next_channel_id = 0
self.channel_queues = {}
self.channel_handler = None
self.connection_handler = None
self.server_mode = None
self.binaryMode = False
self.inboundEnabled = True
self.status = Status.new
self.server_key = server_key
self.client_key = client_key
self.k = None
self.h = None
self.session_id = None
self.inCipher = None
self.outCipher = None
self.inHmacKey = None
self.outHmacKey = None
self.inHmacSize = 0
self.outHmacSize = 0
self.waitingForNewKeys = False
self.waiter = None
self.ready_waiters = []
self.buf = bytearray()
self.cbuf = self.buf
self.packet = None
self.bpLength = None
self.inPacketId = 0
self.outPacketId = 0
self.remote_banner = None
self.local_kex_init_message = None
self.remote_kex_init_message = None
self._channel_map = {} # {local_cid, remote_cid}
self._reverse_channel_map = {} # {remote_cid, local_cid}
self._implicit_channels_enabled = False
def connection_handler(self, value):
self.connection_handler = value
def channel_handler(self, value):
self.channel_handler = value
def get_transport(self):
return self.transport
def close(self):
if self.transport:
self.transport.close()
self.status = Status.closed
def closed(self):
return self.status is Status.closed
@asyncio.coroutine
def open_channel(self, channel_type, block=False):
"Returns the channel queue for the new channel."
if self.status is Status.new:
if not block:
raise SshException("Connection is not ready yet.")
waiter = asyncio.futures.Future(loop=self.loop)
self.ready_waiters.append(waiter)
yield from waiter
if self.status is not Status.ready:
# Ignore if it is closed or disconnected.
if log.isEnabledFor(logging.INFO):
log.info("open_channel(..) called on a closed connection.")
return None, None
if self._implicit_channels_enabled:
local_cid = self._open_implicit_channel(channel_type)
else:
local_cid = self._open_channel(channel_type)
queue = self._create_channel_queue()
self.channel_queues[local_cid] = queue
if self._implicit_channels_enabled:
yield from self.channel_handler.channel_opened(\
self, None, local_cid, queue)
elif block:
r = yield from queue.get()
if not r:
# Could be None for disconnect or False for rejected.
return local_cid, r
assert r == True, "r=[{}]!".format(r)
return local_cid, queue
def _open_implicit_channel(self, channel_type):
local_cid = self._allocate_channel_id()
if log.isEnabledFor(logging.INFO):
log.info("Opening implicit channel [{}] (address=[{}])."\
.format(local_cid, self.address))
msg = mnetpacket.SshChannelOpenMessage()
msg.channel_type = channel_type
msg.sender_channel = local_cid
msg.initial_window_size = 65535
msg.maximum_packet_size = 65535
self._channel_map[local_cid] = msg
return local_cid
def _open_channel(self, channel_type):
local_cid = self._allocate_channel_id()
if log.isEnabledFor(logging.INFO):
log.info("Opening channel [{}] (address=[{}])."\
.format(local_cid, self.address))
msg = mnetpacket.SshChannelOpenMessage()
msg.channel_type = channel_type
msg.sender_channel = local_cid
msg.initial_window_size = 65535
msg.maximum_packet_size = 65535
msg.encode()
self.write_packet(msg)
self._channel_map[local_cid] = ChannelStatus.opening
return local_cid
def _write_implicit_channel_data(self, local_cid, remote_cid, msg,\
data=None):
msg.recipient_channel = local_cid
edmsg = mnetpacket.SshChannelImplicitWrapper()
if remote_cid is ChannelStatus.implicit_data_sent:
if data:
self.write_data((edmsg.encode(), msg.encode(), data))
else:
self.write_data((edmsg.encode(), msg.encode()))
else:
assert type(remote_cid) is mnetpacket.SshChannelOpenMessage,\
type(remote_cid)
self._channel_map[local_cid] =\
ChannelStatus.implicit_data_sent
# Chain data message to end of open msg that was stored.
if data:
self.write_data(\
(remote_cid.encode(), edmsg.encode(), msg.encode(), data))
else:
self.write_data(\
(remote_cid.encode(), edmsg.encode(), msg.encode()))
def send_channel_request(self, local_cid, request_type, want_reply=False,\
payload=None):
remote_cid = self._channel_map.get(local_cid)
msg = mnetpacket.SshChannelRequest()
msg.request_type = request_type
msg.want_reply = want_reply
msg.payload = payload
if self._implicit_channels_enabled:
if type(remote_cid) is not int:
self._write_implicit_channel_data(local_cid, remote_cid, msg)
return
msg.recipient_channel = remote_cid
self.write_channel_data(local_cid, msg.encode())
@asyncio.coroutine
def close_channel(self, local_cid):
if log.isEnabledFor(logging.INFO):
log.info("Closing channel {} (address=[{}])."\
.format(local_cid, self.address))
if self.status is not Status.ready:
# Ignore this call if we are closed or disconnected.
if log.isEnabledFor(logging.DEBUG):
log.debug("close_channel({}) called on closing connection."\
.format(local_cid))
assert self.status is not Status.new
return False
remote_cid = self._channel_map.get(local_cid)
if remote_cid is None:
if log.isEnabledFor(logging.INFO):
log.info("close_channel(..) called on unmapped channel [{}]."\
.format(local_cid))
return False
if remote_cid is ChannelStatus.closing:
if log.isEnabledFor(logging.INFO):
log.info("close_channel(..) called on already closing channel."\
.format(remote_cid))
return False
if remote_cid is ChannelStatus.opening:
if log.isEnabledFor(logging.INFO):
log.info("close_channel(..) called on still opening channel."\
.format(remote_cid))
return False
#FIXME: Something like this should go here to signal to waiters on the queue
# that the channel is closed right away. However, the following causes problems
# later on where code wasn't expecting such to happen.
# queue = self.channel_queues.get(local_cid, None)
# if queue:
# yield from queue.put(None)
# else:
# log.warning("No channel queue for local_cid=[{}]."\
# .format(local_cid))
if type(remote_cid) is mnetpacket.SshChannelOpenMessage:
del self._channel_map[local_cid]
else:
msg = mnetpacket.SshChannelCloseMessage()
if remote_cid is ChannelStatus.implicit_data_sent:
remote_cid = local_cid
msg.implicit_channel = True
msg.recipient_channel = remote_cid
msg.encode()
self.write_packet(msg)
self._channel_map[local_cid] = ChannelStatus.closing
yield from self.channel_handler.channel_closed(self, local_cid)
def _create_channel_queue(self):
return asyncio.Queue()
def _allocate_channel_id(self):
nid = self._next_channel_id
self._next_channel_id += 1
return nid
@asyncio.coroutine
def verify_server_key(self, key_data, sig):
if self.server_key:
if self.server_key.asbytes() != key_data:
raise SshException("Key provided by server differs from that"\
" which we were expecting (address=[{}])."\
.format(self.address))
else:
self.server_key = rsakey.RsaKey(key_data)
if not self.server_key.verify_ssh_sig(self.h, sig):
raise SshException("Signature verification failed (address=[{}])."\
.format(self.address))
log.info("Signature validated correctly!")
r = yield from self.connection_handler.peer_authenticated(self)
return r
def set_K_H(self, k, h):
self.k = k
self.h = h
if self.session_id == None:
self.session_id = h
def set_inbound_enabled(self, val):
self.inboundEnabled = val
@property
def local_banner(self):
if cleartext_transport_enabled:
return "SSH-2.0-mNet_0.0.1+cleartext"
else:
return "SSH-2.0-mNet_0.0.1"
def init_outbound_encryption(self):
log.info("Initializing outbound encryption.")
# use: AES.MODE_CBC: bs: 16, ks: 32. hmac-sha1=20 key size.
if not self.server_mode:
iiv = self.generateKey(b'A', 16)
ekey = self.generateKey(b'C', 32)
ikey = self.generateKey(b'E', 20)
else:
iiv = self.generateKey(b'B', 16)
ekey = self.generateKey(b'D', 32)
ikey = self.generateKey(b'F', 20)
if log.isEnabledFor(logging.DEBUG):
log.debug("ekey=[{}], iiv=[{}].".format(ekey, iiv))
self.outCipher = AES.new(ekey, AES.MODE_CBC, iiv)
self.outHmacKey = ikey
self.outHmacSize = 20
def init_inbound_encryption(self):
log.info("Initializing inbound encryption.")
# use: AES.MODE_CBC: bs: 16, ks: 32. hmac-sha1=20 key size.
if not self.server_mode:
iiv = self.generateKey(b'B', 16)
ekey = self.generateKey(b'D', 32)
ikey = self.generateKey(b'F', 20)
else:
iiv = self.generateKey(b'A', 16)
ekey = self.generateKey(b'C', 32)
ikey = self.generateKey(b'E', 20)
if log.isEnabledFor(logging.DEBUG):
log.debug("ekey=[{}], iiv=[{}].".format(ekey, iiv))
self.inCipher = AES.new(ekey, AES.MODE_CBC, iiv)
self.inHmacKey = ikey
self.inHmacSize = 20
def generateKey(self, extra, needed_bytes):
assert isinstance(extra, bytes) and len(extra) == 1
buf = bytearray()
buf += sshtype.encodeMpint(self.k)
buf += self.h
buf += extra
buf += self.session_id
r = sha1(buf).digest()
while len(r) < needed_bytes:
buf.clear()
buf += sshtype.encodeMpint(self.k)
buf += self.h
buf += r
r += sha1(buf).digest()
return r[:needed_bytes]
def connection_made(self, transport):
self.transport = transport
self.address = peer_name = transport.get_extra_info("peername")
log.info("P: Connection made with [{}].".format(peer_name))
self.connection_handler.connection_made(self)
asyncio.async(self._process_ssh_protocol(), loop=self.loop)
@asyncio.coroutine
def _process_ssh_protocol(self):
try:
r = yield from connectTaskCommon(self, self.server_mode)
if not r:
return r
if "-mNet_" in self.remote_banner:
self._implicit_channels_enabled = True
if cleartext_transport_enabled\
and self.remote_banner.endswith("+cleartext"):
r = yield from connectTaskInsecure(self, self.server_mode)
else:
r = yield from connectTaskSecure(self, self.server_mode)
if not r:
return r
except Exception as e:
if log.isEnabledFor(logging.DEBUG):
log.exception("Exception performing connect task"\
" (closing connection):")
self.close()
raise
else:
log.warning("Error performing connect task: {}"\
.format(e))
self.close()
return
# Connected and fully authenticated at this point.
self.status = Status.ready
for waiter in self.ready_waiters:
waiter.set_result(False)
self.ready_waiters.clear()
yield from self.connection_handler.connection_ready(self)
while True:
packet = yield from self.read_packet(False)
if not packet:
return
yield from self._process_ssh_packet(packet)
def _fix_implicit_msg(self, msg):
"Returns remote_cid."
assert self._implicit_channels_enabled
remote_cid = msg.recipient_channel
msg.recipient_channel =\
self._reverse_channel_map[remote_cid]
if msg.recipient_channel is None:
log.info("Received data for closed implicit channel;"\
" ignoring.")
return None
return remote_cid
@asyncio.coroutine
def _process_ssh_packet(self, packet, offset=0):
t = mnetpacket.SshPacket.parse_type(packet, offset)
if log.isEnabledFor(logging.INFO):
log.info("Received packet, type=[{}].".format(t))
if t == mnetpacket.SSH_MSG_CHANNEL_OPEN:
msg = mnetpacket.SshChannelOpenMessage(packet)
if log.isEnabledFor(logging.INFO):
log.info("P: Received CHANNEL_OPEN: channel_type=[{}],"\
" sender_channel=[{}]."\
.format(msg.channel_type, msg.sender_channel))
if self._implicit_channels_enabled:
if msg.data_packet is None:
raise SshException()
if self._reverse_channel_map.get(msg.sender_channel):
log.warning("Remote end sent a CHANNEL_OPEN request with an already open remote id; ignoring.")
return
r = yield from\
self.channel_handler.request_open_channel(self, msg)
if r:
local_cid = self._accept_channel_open(msg)
if log.isEnabledFor(logging.INFO):
log.info("Channel [{}] opened (address=[{}])."\
.format(local_cid, self.address))
queue = self._create_channel_queue()
self.channel_queues[local_cid] = queue
yield from self.channel_handler.channel_opened(\
self, msg.channel_type, local_cid, queue)
if self._implicit_channels_enabled:
yield from self._process_ssh_packet(msg.data_packet)
elif not self._implicit_channels_enabled:
self._open_channel_reject(msg)
elif t == mnetpacket.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
if self._implicit_channels_enabled:
raise SshException()
msg = mnetpacket.SshChannelOpenConfirmationMessage(packet)
log.info("P: Received CHANNEL_OPEN_CONFIRMATION:"\
" sender_channel=[{}], recipient_channel=[{}]."\
.format(msg.sender_channel, msg.recipient_channel))
rcid = self._channel_map.get(msg.recipient_channel)
if rcid == None:
log.warning("Received a CHANNEL_OPEN_CONFIRMATION for a local channel that was not started; ignoring.")
return
if rcid == ChannelStatus.closing:
log.warning("Received a CHANNEL_OPEN_CONFIRMATION for a local channel that was closed; ignoring.")
return
if rcid != ChannelStatus.opening:
log.warning("Received a CHANNEL_OPEN_CONFIRMATION for a local channel that was already open; ignoring.")
return
lcid = self._reverse_channel_map\
.setdefault(msg.sender_channel, msg.recipient_channel)
if lcid is not msg.recipient_channel:
log.warning("Received a CHANNEL_OPEN_CONFIRMATION for a remote channel that is already open; ignoring.")
return
self._channel_map[msg.recipient_channel] = msg.sender_channel
if log.isEnabledFor(logging.INFO):
log.info("Channel [{}] opened (address=[{}])."\
.format(msg.recipient_channel, self.address))
# First 'packet' is a True, signaling the channel is open to
# those yielding from the queue.
queue = self.channel_queues[msg.recipient_channel]
yield from queue.put(True)
yield from self.channel_handler\
.channel_opened(self, None, msg.recipient_channel, queue)
elif t == mnetpacket.SSH_MSG_CHANNEL_OPEN_FAILURE:
msg = mnetpacket.SshChannelOpenFailureMessage(packet)
log.info("P: Received CHANNEL_OPEN_FAILURE recipient_channel=[{}].".format(msg.recipient_channel))
queue = self.channel_queues[msg.recipient_channel]
yield from queue.put(False)
if (yield from self._close_channel(msg.recipient_channel, True)):
yield from\
self.channel_handler.channel_open_failed(self, msg)
elif t == mnetpacket.SSH_MSG_CHANNEL_IMPLICIT_WRAPPER:
msg = mnetpacket.SshChannelImplicitWrapper(packet, offset)
offset += mnetpacket.SshChannelImplicitWrapper.data_offset
yield from self._process_ssh_packet(packet, offset)
elif t == mnetpacket.SSH_MSG_CHANNEL_EXTENDED_DATA:
raise SshException("Unimplemented.")
elif t == mnetpacket.SSH_MSG_CHANNEL_DATA:
msg = mnetpacket.SshChannelDataMessage(packet, offset)
if offset:
remote_cid = self._fix_implicit_msg(msg)
else:
remote_cid = self._channel_map[msg.recipient_channel]
log.info("P: Received CHANNEL_DATA recipient_channel=[{}]."\
.format(msg.recipient_channel))
if remote_cid is None:
raise SshException(\
"Received data for unmapped channel.")
r = yield from self.channel_handler.channel_data(\
self, msg.recipient_channel, msg.data)
if not r:
log.info(\
"Adding protocol (address={}) channel [{}] data"\
" to queue (remote_cid=[{}])."\
.format(self.address, msg.recipient_channel, remote_cid))
yield from self.channel_queues[msg.recipient_channel]\
.put(msg.data)
elif t == mnetpacket.SSH_MSG_CHANNEL_CLOSE:
msg = mnetpacket.SshChannelCloseMessage(packet)
if log.isEnabledFor(logging.INFO):
log.info("P: Received CHANNEL_CLOSE (recipient_channel=[{}],"\
" implicit_channel=[{}])."\
.format(msg.recipient_channel, msg.implicit_channel))
local_cid = msg.recipient_channel
if self._implicit_channels_enabled:
if msg.implicit_channel:
local_cid = self._reverse_channel_map[local_cid]
if log.isEnabledFor(logging.INFO):
log.info("implicit_channel, local_cid=[{}]."\
.format(local_cid))
else:
if msg.implicit_channel:
raise SshException()
if (yield from self._close_channel(local_cid)):
yield from self.channel_handler.channel_closed(\
self, local_cid)
elif t == mnetpacket.SSH_MSG_CHANNEL_REQUEST:
msg = mnetpacket.SshChannelRequest(packet, offset)
if offset:
self._fix_implicit_msg(msg)
if log.isEnabledFor(logging.INFO):
log.info("Received SSH_MSG_CHANNEL_REQUEST:"\
" recipient_channel=[{}], request_type=[{}],"\
" want_reply=[{}]."\
.format(msg.recipient_channel, msg.request_type,\
msg.want_reply))
yield from self.channel_handler.channel_request(self, msg)
else:
log.warning("Unhandled packet of type [{}].".format(t))
def _accept_channel_open(self, req_msg):
local_cid = self._allocate_channel_id()
if log.isEnabledFor(logging.INFO):
log.info("Accepting channel open request: {}, {}."\
.format(local_cid, req_msg.sender_channel))
self._channel_map[local_cid] = req_msg.sender_channel
self._reverse_channel_map[req_msg.sender_channel] = local_cid
if self._implicit_channels_enabled:
return local_cid
cm = mnetpacket.SshChannelOpenConfirmationMessage()
cm.recipient_channel = req_msg.sender_channel
cm.sender_channel = local_cid
cm.initial_window_size = 65535
cm.maximum_packet_size = 65535
cm.encode()
self.write_packet(cm)
return local_cid
def _open_channel_reject(self, req_msg):
log.info("Rejecting channel open request.")
fm = mnetpacket.SshChannelOpenFailureMessage()
fm.recipient_channel = req_msg.sender_channel
fm.reason_code = 0
fm.description = "invalid"
fm.language_tag = "en"
fm.encode()
self.write_packet(fm)
@asyncio.coroutine
def _close_channel(self, local_cid, rejected=False):
remote_cid = self._channel_map.pop(local_cid, None)
if remote_cid is None:
return False
# This means we didn't open it yet so other end can't close it.
assert type(remote_cid) is not mnetpacket.SshChannelOpenMessage
if not rejected and remote_cid is not ChannelStatus.closing:
if remote_cid is ChannelStatus.opening:
log.warning(\
"_close_channel called while channel is still opening.")
return False
msg = mnetpacket.SshChannelCloseMessage()
if remote_cid is ChannelStatus.implicit_data_sent:
remote_cid = local_cid
msg.implicit_channel = True
else:
self._reverse_channel_map.pop(remote_cid, None)
msg.recipient_channel = remote_cid
msg.encode()
self.write_packet(msg)
queue = self.channel_queues.pop(local_cid, None)
if queue:
yield from queue.put(None)
if log.isEnabledFor(logging.INFO):
log.info("Channel [{}] closed (address=[{}])."\
.format(local_cid, self.address))
return True
def data_received(self, data):
try:
self._data_received(data)
except Exception:
log.exception("_data_received() threw:")
def error_received(self, exc):
log.info("X: Error received: {}".format(exc))
self.connection_handler.error_received(self, exc)
def connection_lost(self, exc):
log.info("X: Connection lost to [{}].".format(self.address))
self.status = Status.closed
self._channel_map.clear()
self._close_queues()
if self.waiter != None:
self.waiter.set_result(False)
self.waiter = None
for waiter in self.ready_waiters:
waiter.set_result(False)
self.ready_waiters.clear()
self.connection_handler.connection_lost(self, exc)
def _close_queues(self):
for queue in self.channel_queues.values():
#yield from queue.put(None)
queue.put_nowait(None)
def _data_received(self, data):
if log.isEnabledFor(logging.DEBUG):
log.debug("data_received(..): start.")
log.debug("X: Received: [\n{}].".format(hex_dump(data)))
if self.binaryMode:
self.buf += data
if not self.packet and self.inboundEnabled:
self.process_buffer()
log.debug("data_received(..): end (binaryMode).")
return
# Handle handshake packet, detect end.
end = data.find(b"\r\n")
if end != -1:
self.buf += data[0:end]
self.packet = self.buf
self.buf = data[end+2:]
self.binaryMode = True
if self.waiter != None:
self.waiter.set_result(False)
self.waiter = None
# The following would overwrite packet if it were a complete
# packet in the buf.
# if len(self.buf) > 0:
# self.process_buffer()
else:
self.buf += data
log.debug("data_received(..): end.")
@asyncio.coroutine
def do_wait(self):
if self.waiter is not None:
errmsg = "waiter already set!"
log.fatal(errmsg)
raise Exception(errmsg)
self.waiter = asyncio.futures.Future(loop=self.loop)
try:
yield from self.waiter
finally:
self.waiter = None
@asyncio.coroutine
def read_packet(self, require_connected=True):
if self.status is Status.disconnected:
return None
if require_connected and self.status is Status.closed:
errstr = "ProtocolHandler closed, refusing read_packet(..)!"
log.debug(errstr)
raise SshException(errstr)
if self.packet != None:
packet = self.packet
self.packet = None
if packet[0] == 0x01:
yield from\
self._peer_disconnected(\
mnetpacket.SshDisconnectMessage(packet))
return None
log.info("P: Returning next packet.")
#asyncio.call_soon(self.process_buffer())
# For now, call process_buffer in this event.
if len(self.buf) > 0:
self.process_buffer()
return packet
if self.status is Status.closed or self.status is Status.disconnected:
return None
log.info("P: Waiting for packet.")
yield from self.do_wait()
if self.status is Status.closed or self.status is Status.disconnected:
return None
assert self.packet != None
packet = self.packet
self.packet = None
log.info("P: Notified of packet.")
if packet[0] == 0x01:
yield from\
self._peer_disconnected(\
mnetpacket.SshDisconnectMessage(packet))
return None
# For now, call process_buffer in this event.
if len(self.buf) > 0:
self.process_buffer()
return packet
def _peer_disconnected(self, msg):
if log.isEnabledFor(logging.INFO):
log.info("Remote end (address=[{}]) send Disconnect message"\
" (reason_code={}, description=[{}])."\
.format(self.address, msg.reason_code, msg.description))
self.status = Status.disconnected
yield from self.connection_handler.peer_disconnected(self, msg)
def write_packet(self, packet):
if log.isEnabledFor(logging.INFO):
log.info("Writing packet_type=[{}] ({} bytes) to address=[{}]."\
.format(packet.packet_type, len(packet.buf), self.address))
if log.isEnabledFor(logging.DEBUG):
log.debug("data=[\n{}].".format(hex_dump(packet.buf)))
self.write_data([packet.buf])
def write_channel_data(self, local_cid, data):
log.info("Writing to channel {} with {} bytes of data (address={}).".format(local_cid, len(data), self.address))
remote_cid = self._channel_map.get(local_cid)
if remote_cid is None:
return False
msg = mnetpacket.SshChannelDataMessage()
if self._implicit_channels_enabled:
if type(remote_cid) is not int:
self._write_implicit_channel_data(\
local_cid, remote_cid, msg, data)
return True
msg.recipient_channel = remote_cid
self.write_data((msg.encode(), data))
return True
def write_data(self, datas):
if self.status in [Status.closed, Status.disconnected]:
log.info("ProtocolHandler closed, ignoring write_data(..) call.")
return
mod_size = None
if self.outCipher == None:
mod_size = 8 # RFC says 8 minimum.
else:
mod_size = 16 # bs of current cipher is 16.
length = 0
for data in datas:
length += len(data)
if log.isEnabledFor(logging.INFO):
log.info("Writing {} bytes of data to connection (address=[{}])."\
.format(length, self.address))
extra = (length + 5) % mod_size;
if extra != 0:
padding = mod_size - extra
if padding < 4:
padding += mod_size #Minimum padding is 4.
else:
padding = mod_size; #Minimum padding is 4.
if self.outCipher == None:
self.transport.write(struct.pack(">L", 1 + length + padding))
self.transport.write(struct.pack("B", padding & 0xff))
for data in datas:
self.transport.write(data)
for i in range(0, padding):
self.transport.write(struct.pack("B", 0))
else:
buf = bytearray()
buf += struct.pack(">L", 1 + length + padding)
buf += struct.pack("B", padding & 0xff)
for data in datas:
buf += data
buf += os.urandom(padding)
if log.isEnabledFor(logging.DEBUG):
log.debug("len(buf)=[{}], padding=[{}].".format(len(buf), padding))
if self.outHmacSize != 0:
tmac = hmac.new(self.outHmacKey, digestmod=sha1)
tmac.update(struct.pack(">L", self.outPacketId))
tmac.update(buf)
out = self.outCipher.encrypt(bytes(buf))
self.transport.write(out)
self.transport.write(tmac.digest())
self.outPacketId = (self.outPacketId + 1) & 0xFFFFFFFF
def process_buffer(self):
try:
self._process_buffer()
except Exception:
log.exception("_process_buffer() threw:")
self.close()
return
def _process_buffer(self):
if log.isEnabledFor(logging.DEBUG):
log.debug("P: process_buffer(): called (binaryMode={}), buf=[\n{}].".format(self.binaryMode, hex_dump(self.buf)))
assert self.binaryMode
r = self._process_encrypted_buffer()
if not r:
return
# cbuf is clear text buf.
while True:
if self.bpLength is None:
assert not self.inCipher
if len(self.cbuf) < 4:
return
if log.isEnabledFor(logging.DEBUG):
log.debug("t=[{}].".format(self.cbuf[:4]))
packet_length = struct.unpack(">L", self.cbuf[:4])[0]
if log.isEnabledFor(logging.DEBUG):
log.debug("packet_length=[{}].".format(packet_length))
if packet_length > MAX_PACKET_LENGTH:
errmsg = "Illegal packet_length [{}] received."\
.format(packet_length)
log.warning(errmsg)
raise SshException(errmsg)
self.bpLength = packet_length + 4 # Add size of packet_length as we leave it in buf.
else:
if len(self.cbuf) < self.bpLength or len(self.buf) < self.inHmacSize:
return;
if log.isEnabledFor(logging.DEBUG):
log.debug("PACKET READ (bpLength={}, inHmacSize={}, len(self.cbuf)={}, len(self.buf)={})".format(self.bpLength, self.inHmacSize, len(self.cbuf), len(self.buf)))
padding_length = struct.unpack("B", self.cbuf[4:5])[0]
log.debug("padding_length=[{}].".format(padding_length))