forked from arthepsy/ssh-audit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh-audit.py
executable file
·2015 lines (1820 loc) · 65 KB
/
ssh-audit.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (C) 2016 Andris Raugulis ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from __future__ import print_function
import os, io, sys, socket, struct, random, errno, getopt, re, hashlib, base64
VERSION = 'v1.7.0'
if sys.version_info >= (3,): # pragma: nocover
StringIO, BytesIO = io.StringIO, io.BytesIO
text_type = str
binary_type = bytes
else: # pragma: nocover
import StringIO as _StringIO # pylint: disable=import-error
StringIO = BytesIO = _StringIO.StringIO
text_type = unicode # pylint: disable=undefined-variable
binary_type = str
try: # pragma: nocover
# pylint: disable=unused-import
from typing import List, Set, Sequence, Tuple, Iterable
from typing import Callable, Optional, Union, Any
except ImportError: # pragma: nocover
pass
try: # pragma: nocover
from colorama import init as colorama_init
colorama_init() # pragma: nocover
except ImportError: # pragma: nocover
pass
def usage(err=None):
# type: (Optional[str]) -> None
uout = Output()
p = os.path.basename(sys.argv[0])
uout.head('# {0} {1}, [email protected]\n'.format(p, VERSION))
if err is not None:
uout.fail('\n' + err)
uout.info('usage: {0} [-1246pbnvl] <host>\n'.format(p))
uout.info(' -h, --help print this help')
uout.info(' -1, --ssh1 force ssh version 1 only')
uout.info(' -2, --ssh2 force ssh version 2 only')
uout.info(' -4, --ipv4 enable IPv4 (order of precedence)')
uout.info(' -6, --ipv6 enable IPv6 (order of precedence)')
uout.info(' -p, --port=<port> port to connect')
uout.info(' -b, --batch batch output')
uout.info(' -n, --no-colors disable colors')
uout.info(' -v, --verbose verbose output')
uout.info(' -l, --level=<level> minimum output level (info|warn|fail)')
uout.sep()
sys.exit(1)
class AuditConf(object):
# pylint: disable=too-many-instance-attributes
def __init__(self, host=None, port=22):
# type: (Optional[str], int) -> None
self.host = host
self.port = port
self.ssh1 = True
self.ssh2 = True
self.batch = False
self.colors = True
self.verbose = False
self.minlevel = 'info'
self.ipvo = () # type: Sequence[int]
self.ipv4 = False
self.ipv6 = False
def __setattr__(self, name, value):
# type: (str, Union[str, int, bool, Sequence[int]]) -> None
valid = False
if name in ['ssh1', 'ssh2', 'batch', 'colors', 'verbose']:
valid, value = True, True if value else False
elif name in ['ipv4', 'ipv6']:
valid = False
value = True if value else False
ipv = 4 if name == 'ipv4' else 6
if value:
value = tuple(list(self.ipvo) + [ipv])
else:
if len(self.ipvo) == 0:
value = (6,) if ipv == 4 else (4,)
else:
value = tuple(filter(lambda x: x != ipv, self.ipvo))
self.__setattr__('ipvo', value)
elif name == 'ipvo':
if isinstance(value, (tuple, list)):
uniq_value = utils.unique_seq(value)
value = tuple(filter(lambda x: x in (4, 6), uniq_value))
valid = True
ipv_both = len(value) == 0
object.__setattr__(self, 'ipv4', ipv_both or 4 in value)
object.__setattr__(self, 'ipv6', ipv_both or 6 in value)
elif name == 'port':
valid, port = True, utils.parse_int(value)
if port < 1 or port > 65535:
raise ValueError('invalid port: {0}'.format(value))
value = port
elif name in ['minlevel']:
if value not in ('info', 'warn', 'fail'):
raise ValueError('invalid level: {0}'.format(value))
valid = True
elif name == 'host':
valid = True
if valid:
object.__setattr__(self, name, value)
@classmethod
def from_cmdline(cls, args, usage_cb):
# type: (List[str], Callable[..., None]) -> AuditConf
# pylint: disable=too-many-branches
aconf = cls()
try:
sopts = 'h1246p:bnvl:'
lopts = ['help', 'ssh1', 'ssh2', 'ipv4', 'ipv6', 'port',
'batch', 'no-colors', 'verbose', 'level=']
opts, args = getopt.getopt(args, sopts, lopts)
except getopt.GetoptError as err:
usage_cb(str(err))
aconf.ssh1, aconf.ssh2 = False, False
oport = None
for o, a in opts:
if o in ('-h', '--help'):
usage_cb()
elif o in ('-1', '--ssh1'):
aconf.ssh1 = True
elif o in ('-2', '--ssh2'):
aconf.ssh2 = True
elif o in ('-4', '--ipv4'):
aconf.ipv4 = True
elif o in ('-6', '--ipv6'):
aconf.ipv6 = True
elif o in ('-p', '--port'):
oport = a
elif o in ('-b', '--batch'):
aconf.batch = True
aconf.verbose = True
elif o in ('-n', '--no-colors'):
aconf.colors = False
elif o in ('-v', '--verbose'):
aconf.verbose = True
elif o in ('-l', '--level'):
if a not in ('info', 'warn', 'fail'):
usage_cb('level {0} is not valid'.format(a))
aconf.minlevel = a
if len(args) == 0:
usage_cb()
if oport is not None:
host = args[0]
port = utils.parse_int(oport)
else:
s = args[0].split(':')
host = s[0].strip()
if len(s) == 2:
oport, port = s[1], utils.parse_int(s[1])
else:
oport, port = '22', 22
if not host:
usage_cb('host is empty')
if port <= 0 or port > 65535:
usage_cb('port {0} is not valid'.format(oport))
aconf.host = host
aconf.port = port
if not (aconf.ssh1 or aconf.ssh2):
aconf.ssh1, aconf.ssh2 = True, True
return aconf
class Output(object):
LEVELS = ['info', 'warn', 'fail']
COLORS = {'head': 36, 'good': 32, 'warn': 33, 'fail': 31}
def __init__(self):
# type: () -> None
self.batch = False
self.colors = True
self.verbose = False
self.__minlevel = 0
@property
def minlevel(self):
# type: () -> str
if self.__minlevel < len(self.LEVELS):
return self.LEVELS[self.__minlevel]
return 'unknown'
@minlevel.setter
def minlevel(self, name):
# type: (str) -> None
self.__minlevel = self.getlevel(name)
def getlevel(self, name):
# type: (str) -> int
cname = 'info' if name == 'good' else name
if cname not in self.LEVELS:
return sys.maxsize
return self.LEVELS.index(cname)
def sep(self):
# type: () -> None
if not self.batch:
print()
@property
def colors_supported(self):
# type: () -> bool
return 'colorama' in sys.modules or os.name == 'posix'
@staticmethod
def _colorized(color):
# type: (str) -> Callable[[text_type], None]
return lambda x: print(u'{0}{1}\033[0m'.format(color, x))
def __getattr__(self, name):
# type: (str) -> Callable[[text_type], None]
if name == 'head' and self.batch:
return lambda x: None
if not self.getlevel(name) >= self.__minlevel:
return lambda x: None
if self.colors and self.colors_supported and name in self.COLORS:
color = '\033[0;{0}m'.format(self.COLORS[name])
return self._colorized(color)
else:
return lambda x: print(u'{0}'.format(x))
class OutputBuffer(list):
def __enter__(self):
# type: () -> OutputBuffer
# pylint: disable=attribute-defined-outside-init
self.__buf = StringIO()
self.__stdout = sys.stdout
sys.stdout = self.__buf
return self
def flush(self):
# type: () -> None
for line in self:
print(line)
def __exit__(self, *args):
# type: (*Any) -> None
self.extend(self.__buf.getvalue().splitlines())
sys.stdout = self.__stdout
class SSH2(object): # pylint: disable=too-few-public-methods
class KexParty(object):
def __init__(self, enc, mac, compression, languages):
# type: (List[text_type], List[text_type], List[text_type], List[text_type]) -> None
self.__enc = enc
self.__mac = mac
self.__compression = compression
self.__languages = languages
@property
def encryption(self):
# type: () -> List[text_type]
return self.__enc
@property
def mac(self):
# type: () -> List[text_type]
return self.__mac
@property
def compression(self):
# type: () -> List[text_type]
return self.__compression
@property
def languages(self):
# type: () -> List[text_type]
return self.__languages
class Kex(object):
def __init__(self, cookie, kex_algs, key_algs, cli, srv, follows, unused=0):
# type: (binary_type, List[text_type], List[text_type], SSH2.KexParty, SSH2.KexParty, bool, int) -> None
self.__cookie = cookie
self.__kex_algs = kex_algs
self.__key_algs = key_algs
self.__client = cli
self.__server = srv
self.__follows = follows
self.__unused = unused
@property
def cookie(self):
# type: () -> binary_type
return self.__cookie
@property
def kex_algorithms(self):
# type: () -> List[text_type]
return self.__kex_algs
@property
def key_algorithms(self):
# type: () -> List[text_type]
return self.__key_algs
# client_to_server
@property
def client(self):
# type: () -> SSH2.KexParty
return self.__client
# server_to_client
@property
def server(self):
# type: () -> SSH2.KexParty
return self.__server
@property
def follows(self):
# type: () -> bool
return self.__follows
@property
def unused(self):
# type: () -> int
return self.__unused
def write(self, wbuf):
# type: (WriteBuf) -> None
wbuf.write(self.cookie)
wbuf.write_list(self.kex_algorithms)
wbuf.write_list(self.key_algorithms)
wbuf.write_list(self.client.encryption)
wbuf.write_list(self.server.encryption)
wbuf.write_list(self.client.mac)
wbuf.write_list(self.server.mac)
wbuf.write_list(self.client.compression)
wbuf.write_list(self.server.compression)
wbuf.write_list(self.client.languages)
wbuf.write_list(self.server.languages)
wbuf.write_bool(self.follows)
wbuf.write_int(self.__unused)
@property
def payload(self):
# type: () -> binary_type
wbuf = WriteBuf()
self.write(wbuf)
return wbuf.write_flush()
@classmethod
def parse(cls, payload):
# type: (binary_type) -> SSH2.Kex
buf = ReadBuf(payload)
cookie = buf.read(16)
kex_algs = buf.read_list()
key_algs = buf.read_list()
cli_enc = buf.read_list()
srv_enc = buf.read_list()
cli_mac = buf.read_list()
srv_mac = buf.read_list()
cli_compression = buf.read_list()
srv_compression = buf.read_list()
cli_languages = buf.read_list()
srv_languages = buf.read_list()
follows = buf.read_bool()
unused = buf.read_int()
cli = SSH2.KexParty(cli_enc, cli_mac, cli_compression, cli_languages)
srv = SSH2.KexParty(srv_enc, srv_mac, srv_compression, srv_languages)
kex = cls(cookie, kex_algs, key_algs, cli, srv, follows, unused)
return kex
class SSH1(object):
class CRC32(object):
def __init__(self):
# type: () -> None
self._table = [0] * 256
for i in range(256):
crc = 0
n = i
for _ in range(8):
x = (crc ^ n) & 1
crc = (crc >> 1) ^ (x * 0xedb88320)
n = n >> 1
self._table[i] = crc
def calc(self, v):
# type: (binary_type) -> int
crc, l = 0, len(v)
for i in range(l):
n = ord(v[i:i + 1])
n = n ^ (crc & 0xff)
crc = (crc >> 8) ^ self._table[n]
return crc
_crc32 = None # type: Optional[SSH1.CRC32]
CIPHERS = ['none', 'idea', 'des', '3des', 'tss', 'rc4', 'blowfish']
AUTHS = [None, 'rhosts', 'rsa', 'password', 'rhosts_rsa', 'tis', 'kerberos']
@classmethod
def crc32(cls, v):
# type: (binary_type) -> int
if cls._crc32 is None:
cls._crc32 = cls.CRC32()
return cls._crc32.calc(v)
class KexDB(object): # pylint: disable=too-few-public-methods
# pylint: disable=bad-whitespace
FAIL_PLAINTEXT = 'no encryption/integrity'
FAIL_OPENSSH37_REMOVE = 'removed since OpenSSH 3.7'
FAIL_NA_BROKEN = 'not implemented in OpenSSH, broken algorithm'
FAIL_NA_UNSAFE = 'not implemented in OpenSSH (server), unsafe algorithm'
TEXT_CIPHER_IDEA = 'cipher used by commercial SSH'
ALGORITHMS = {
'key': {
'ssh-rsa1': [['1.2.2']],
},
'enc': {
'none': [['1.2.2'], [FAIL_PLAINTEXT]],
'idea': [[None], [], [], [TEXT_CIPHER_IDEA]],
'des': [['2.3.0C'], [FAIL_NA_UNSAFE]],
'3des': [['1.2.2']],
'tss': [[''], [FAIL_NA_BROKEN]],
'rc4': [[], [FAIL_NA_BROKEN]],
'blowfish': [['1.2.2']],
},
'aut': {
'rhosts': [['1.2.2', '3.6'], [FAIL_OPENSSH37_REMOVE]],
'rsa': [['1.2.2']],
'password': [['1.2.2']],
'rhosts_rsa': [['1.2.2']],
'tis': [['1.2.2']],
'kerberos': [['1.2.2', '3.6'], [FAIL_OPENSSH37_REMOVE]],
}
} # type: Dict[str, Dict[str, List[List[str]]]]
class PublicKeyMessage(object):
def __init__(self, cookie, skey, hkey, pflags, cmask, amask):
# type: (binary_type, Tuple[int, int, int], Tuple[int, int, int], int, int, int) -> None
assert len(skey) == 3
assert len(hkey) == 3
self.__cookie = cookie
self.__server_key = skey
self.__host_key = hkey
self.__protocol_flags = pflags
self.__supported_ciphers_mask = cmask
self.__supported_authentications_mask = amask
@property
def cookie(self):
# type: () -> binary_type
return self.__cookie
@property
def server_key_bits(self):
# type: () -> int
return self.__server_key[0]
@property
def server_key_public_exponent(self):
# type: () -> int
return self.__server_key[1]
@property
def server_key_public_modulus(self):
# type: () -> int
return self.__server_key[2]
@property
def host_key_bits(self):
# type: () -> int
return self.__host_key[0]
@property
def host_key_public_exponent(self):
# type: () -> int
return self.__host_key[1]
@property
def host_key_public_modulus(self):
# type: () -> int
return self.__host_key[2]
@property
def host_key_fingerprint_data(self):
# type: () -> binary_type
# pylint: disable=protected-access
mod = WriteBuf._create_mpint(self.host_key_public_modulus, False)
e = WriteBuf._create_mpint(self.host_key_public_exponent, False)
return mod + e
@property
def protocol_flags(self):
# type: () -> int
return self.__protocol_flags
@property
def supported_ciphers_mask(self):
# type: () -> int
return self.__supported_ciphers_mask
@property
def supported_ciphers(self):
# type: () -> List[text_type]
ciphers = []
for i in range(len(SSH1.CIPHERS)):
if self.__supported_ciphers_mask & (1 << i) != 0:
ciphers.append(utils.to_utext(SSH1.CIPHERS[i]))
return ciphers
@property
def supported_authentications_mask(self):
# type: () -> int
return self.__supported_authentications_mask
@property
def supported_authentications(self):
# type: () -> List[text_type]
auths = []
for i in range(1, len(SSH1.AUTHS)):
if self.__supported_authentications_mask & (1 << i) != 0:
auths.append(utils.to_utext(SSH1.AUTHS[i]))
return auths
def write(self, wbuf):
# type: (WriteBuf) -> None
wbuf.write(self.cookie)
wbuf.write_int(self.server_key_bits)
wbuf.write_mpint1(self.server_key_public_exponent)
wbuf.write_mpint1(self.server_key_public_modulus)
wbuf.write_int(self.host_key_bits)
wbuf.write_mpint1(self.host_key_public_exponent)
wbuf.write_mpint1(self.host_key_public_modulus)
wbuf.write_int(self.protocol_flags)
wbuf.write_int(self.supported_ciphers_mask)
wbuf.write_int(self.supported_authentications_mask)
@property
def payload(self):
# type: () -> binary_type
wbuf = WriteBuf()
self.write(wbuf)
return wbuf.write_flush()
@classmethod
def parse(cls, payload):
# type: (binary_type) -> SSH1.PublicKeyMessage
buf = ReadBuf(payload)
cookie = buf.read(8)
server_key_bits = buf.read_int()
server_key_exponent = buf.read_mpint1()
server_key_modulus = buf.read_mpint1()
skey = (server_key_bits, server_key_exponent, server_key_modulus)
host_key_bits = buf.read_int()
host_key_exponent = buf.read_mpint1()
host_key_modulus = buf.read_mpint1()
hkey = (host_key_bits, host_key_exponent, host_key_modulus)
pflags = buf.read_int()
cmask = buf.read_int()
amask = buf.read_int()
pkm = cls(cookie, skey, hkey, pflags, cmask, amask)
return pkm
class ReadBuf(object):
def __init__(self, data=None):
# type: (Optional[binary_type]) -> None
super(ReadBuf, self).__init__()
self._buf = BytesIO(data) if data else BytesIO()
self._len = len(data) if data else 0
@property
def unread_len(self):
# type: () -> int
return self._len - self._buf.tell()
def read(self, size):
# type: (int) -> binary_type
return self._buf.read(size)
def read_byte(self):
# type: () -> int
return struct.unpack('B', self.read(1))[0]
def read_bool(self):
# type: () -> bool
return self.read_byte() != 0
def read_int(self):
# type: () -> int
return struct.unpack('>I', self.read(4))[0]
def read_list(self):
# type: () -> List[text_type]
list_size = self.read_int()
return self.read(list_size).decode('utf-8', 'replace').split(',')
def read_string(self):
# type: () -> binary_type
n = self.read_int()
return self.read(n)
@classmethod
def _parse_mpint(cls, v, pad, sf):
# type: (binary_type, binary_type, str) -> int
r = 0
if len(v) % 4:
v = pad * (4 - (len(v) % 4)) + v
for i in range(0, len(v), 4):
r = (r << 32) | struct.unpack(sf, v[i:i + 4])[0]
return r
def read_mpint1(self):
# type: () -> int
# NOTE: Data Type Enc @ http://www.snailbook.com/docs/protocol-1.5.txt
bits = struct.unpack('>H', self.read(2))[0]
n = (bits + 7) // 8
return self._parse_mpint(self.read(n), b'\x00', '>I')
def read_mpint2(self):
# type: () -> int
# NOTE: Section 5 @ https://www.ietf.org/rfc/rfc4251.txt
v = self.read_string()
if len(v) == 0:
return 0
pad, sf = (b'\xff', '>i') if ord(v[0:1]) & 0x80 else (b'\x00', '>I')
return self._parse_mpint(v, pad, sf)
def read_line(self):
# type: () -> text_type
return self._buf.readline().rstrip().decode('utf-8', 'replace')
class WriteBuf(object):
def __init__(self, data=None):
# type: (Optional[binary_type]) -> None
super(WriteBuf, self).__init__()
self._wbuf = BytesIO(data) if data else BytesIO()
def write(self, data):
# type: (binary_type) -> WriteBuf
self._wbuf.write(data)
return self
def write_byte(self, v):
# type: (int) -> WriteBuf
return self.write(struct.pack('B', v))
def write_bool(self, v):
# type: (bool) -> WriteBuf
return self.write_byte(1 if v else 0)
def write_int(self, v):
# type: (int) -> WriteBuf
return self.write(struct.pack('>I', v))
def write_string(self, v):
# type: (Union[binary_type, text_type]) -> WriteBuf
if not isinstance(v, bytes):
v = bytes(bytearray(v, 'utf-8'))
self.write_int(len(v))
return self.write(v)
def write_list(self, v):
# type: (List[text_type]) -> WriteBuf
return self.write_string(u','.join(v))
@classmethod
def _bitlength(cls, n):
# type: (int) -> int
try:
return n.bit_length()
except AttributeError:
return len(bin(n)) - (2 if n > 0 else 3)
@classmethod
def _create_mpint(cls, n, signed=True, bits=None):
# type: (int, bool, Optional[int]) -> binary_type
if bits is None:
bits = cls._bitlength(n)
length = bits // 8 + (1 if n != 0 else 0)
ql = (length + 7) // 8
fmt, v2 = '>{0}Q'.format(ql), [0] * ql
for i in range(ql):
v2[ql - i - 1] = (n & 0xffffffffffffffff)
n >>= 64
data = bytes(struct.pack(fmt, *v2)[-length:])
if not signed:
data = data.lstrip(b'\x00')
elif data.startswith(b'\xff\x80'):
data = data[1:]
return data
def write_mpint1(self, n):
# type: (int) -> WriteBuf
# NOTE: Data Type Enc @ http://www.snailbook.com/docs/protocol-1.5.txt
bits = self._bitlength(n)
data = self._create_mpint(n, False, bits)
self.write(struct.pack('>H', bits))
return self.write(data)
def write_mpint2(self, n):
# type: (int) -> WriteBuf
# NOTE: Section 5 @ https://www.ietf.org/rfc/rfc4251.txt
data = self._create_mpint(n)
return self.write_string(data)
def write_line(self, v):
# type: (Union[binary_type, str]) -> WriteBuf
if not isinstance(v, bytes):
v = bytes(bytearray(v, 'utf-8'))
v += b'\r\n'
return self.write(v)
def write_flush(self):
# type: () -> binary_type
payload = self._wbuf.getvalue()
self._wbuf.truncate(0)
self._wbuf.seek(0)
return payload
class SSH(object): # pylint: disable=too-few-public-methods
class Protocol(object): # pylint: disable=too-few-public-methods
# pylint: disable=bad-whitespace
SMSG_PUBLIC_KEY = 2
MSG_KEXINIT = 20
MSG_NEWKEYS = 21
MSG_KEXDH_INIT = 30
MSG_KEXDH_REPLY = 32
class Product(object): # pylint: disable=too-few-public-methods
OpenSSH = 'OpenSSH'
DropbearSSH = 'Dropbear SSH'
LibSSH = 'libssh'
class Software(object):
def __init__(self, vendor, product, version, patch, os_version):
# type: (Optional[str], str, str, Optional[str], Optional[str]) -> None
self.__vendor = vendor
self.__product = product
self.__version = version
self.__patch = patch
self.__os = os_version
@property
def vendor(self):
# type: () -> Optional[str]
return self.__vendor
@property
def product(self):
# type: () -> str
return self.__product
@property
def version(self):
# type: () -> str
return self.__version
@property
def patch(self):
# type: () -> Optional[str]
return self.__patch
@property
def os(self):
# type: () -> Optional[str]
return self.__os
def compare_version(self, other):
# type: (Union[None, SSH.Software, text_type]) -> int
# pylint: disable=too-many-branches
if other is None:
return 1
if isinstance(other, SSH.Software):
other = '{0}{1}'.format(other.version, other.patch or '')
else:
other = str(other)
mx = re.match(r'^([\d\.]+\d+)(.*)$', other)
if mx:
oversion, opatch = mx.group(1), mx.group(2).strip()
else:
oversion, opatch = other, ''
if self.version < oversion:
return -1
elif self.version > oversion:
return 1
spatch = self.patch or ''
if self.product == SSH.Product.DropbearSSH:
if not re.match(r'^test\d.*$', opatch):
opatch = 'z{0}'.format(opatch)
if not re.match(r'^test\d.*$', spatch):
spatch = 'z{0}'.format(spatch)
elif self.product == SSH.Product.OpenSSH:
mx1 = re.match(r'^p\d(.*)', opatch)
mx2 = re.match(r'^p\d(.*)', spatch)
if not (mx1 and mx2):
if mx1:
opatch = mx1.group(1)
if mx2:
spatch = mx2.group(1)
if spatch < opatch:
return -1
elif spatch > opatch:
return 1
return 0
def between_versions(self, vfrom, vtill):
# type: (str, str) -> bool
if vfrom and self.compare_version(vfrom) < 0:
return False
if vtill and self.compare_version(vtill) > 0:
return False
return True
def display(self, full=True):
# type: (bool) -> str
r = '{0} '.format(self.vendor) if self.vendor else ''
r += self.product
if self.version:
r += ' {0}'.format(self.version)
if full:
patch = self.patch or ''
if self.product == SSH.Product.OpenSSH:
mx = re.match(r'^(p\d)(.*)$', patch)
if mx is not None:
r += mx.group(1)
patch = mx.group(2).strip()
if patch:
r += ' ({0})'.format(patch)
if self.os:
r += ' running on {0}'.format(self.os)
return r
def __str__(self):
# type: () -> str
return self.display()
def __repr__(self):
# type: () -> str
r = 'vendor={0}'.format(self.vendor) if self.vendor else ''
if self.product:
if self.vendor:
r += ', '
r += 'product={0}'.format(self.product)
if self.version:
r += ', version={0}'.format(self.version)
if self.patch:
r += ', patch={0}'.format(self.patch)
if self.os:
r += ', os={0}'.format(self.os)
return '<{0}({1})>'.format(self.__class__.__name__, r)
@staticmethod
def _fix_patch(patch):
# type: (str) -> Optional[str]
return re.sub(r'^[-_\.]+', '', patch) or None
@staticmethod
def _fix_date(d):
# type: (str) -> Optional[str]
if d is not None and len(d) == 8:
return '{0}-{1}-{2}'.format(d[:4], d[4:6], d[6:8])
else:
return None
@classmethod
def _extract_os_version(cls, c):
# type: (Optional[str]) -> str
if c is None:
return None
mx = re.match(r'^NetBSD(?:_Secure_Shell)?(?:[\s-]+(\d{8})(.*))?$', c)
if mx:
d = cls._fix_date(mx.group(1))
return 'NetBSD' if d is None else 'NetBSD ({0})'.format(d)
mx = re.match(r'^FreeBSD(?:\slocalisations)?[\s-]+(\d{8})(.*)$', c)
if not mx:
mx = re.match(r'^[^@]+@FreeBSD\.org[\s-]+(\d{8})(.*)$', c)
if mx:
d = cls._fix_date(mx.group(1))
return 'FreeBSD' if d is None else 'FreeBSD ({0})'.format(d)
w = ['RemotelyAnywhere', 'DesktopAuthority', 'RemoteSupportManager']
for win_soft in w:
mx = re.match(r'^in ' + win_soft + r' ([\d\.]+\d)$', c)
if mx:
ver = mx.group(1)
return 'Microsoft Windows ({0} {1})'.format(win_soft, ver)
generic = ['NetBSD', 'FreeBSD']
for g in generic:
if c.startswith(g) or c.endswith(g):
return g
return None
@classmethod
def parse(cls, banner):
# type: (SSH.Banner) -> SSH.Software
# pylint: disable=too-many-return-statements
software = str(banner.software)
mx = re.match(r'^dropbear_([\d\.]+\d+)(.*)', software)
if mx:
patch = cls._fix_patch(mx.group(2))
v, p = 'Matt Johnston', SSH.Product.DropbearSSH
v = None
return cls(v, p, mx.group(1), patch, None)
mx = re.match(r'^OpenSSH[_\.-]+([\d\.]+\d+)(.*)', software)
if mx:
patch = cls._fix_patch(mx.group(2))
v, p = 'OpenBSD', SSH.Product.OpenSSH
v = None
os_version = cls._extract_os_version(banner.comments)
return cls(v, p, mx.group(1), patch, os_version)
mx = re.match(r'^libssh-([\d\.]+\d+)(.*)', software)
if mx:
patch = cls._fix_patch(mx.group(2))
v, p = None, SSH.Product.LibSSH
os_version = cls._extract_os_version(banner.comments)
return cls(v, p, mx.group(1), patch, os_version)
mx = re.match(r'^RomSShell_([\d\.]+\d+)(.*)', software)
if mx:
patch = cls._fix_patch(mx.group(2))
v, p = 'Allegro Software', 'RomSShell'
return cls(v, p, mx.group(1), patch, None)
mx = re.match(r'^mpSSH_([\d\.]+\d+)', software)
if mx:
v, p = 'HP', 'iLO (Integrated Lights-Out) sshd'
return cls(v, p, mx.group(1), None, None)
mx = re.match(r'^Cisco-([\d\.]+\d+)', software)
if mx:
v, p = 'Cisco', 'IOS/PIX sshd'
return cls(v, p, mx.group(1), None, None)
return None
class Banner(object):
_RXP, _RXR = r'SSH-\d\.\s*?\d+', r'(-\s*([^\s]*)(?:\s+(.*))?)?'
RX_PROTOCOL = re.compile(re.sub(r'\\d(\+?)', r'(\\d\g<1>)', _RXP))
RX_BANNER = re.compile(r'^({0}(?:(?:-{0})*)){1}$'.format(_RXP, _RXR))
def __init__(self, protocol, software, comments, valid_ascii):
# type: (Tuple[int, int], str, str, bool) -> None
self.__protocol = protocol
self.__software = software
self.__comments = comments
self.__valid_ascii = valid_ascii
@property
def protocol(self):
# type: () -> Tuple[int, int]
return self.__protocol
@property
def software(self):
# type: () -> str
return self.__software
@property
def comments(self):
# type: () -> str
return self.__comments
@property
def valid_ascii(self):
# type: () -> bool
return self.__valid_ascii
def __str__(self):
# type: () -> str
r = 'SSH-{0}.{1}'.format(self.protocol[0], self.protocol[1])
if self.software is not None:
r += '-{0}'.format(self.software)
if self.comments:
r += ' {0}'.format(self.comments)
return r
def __repr__(self):
# type: () -> str
p = '{0}.{1}'.format(self.protocol[0], self.protocol[1])
r = 'protocol={0}'.format(p)
if self.software:
r += ', software={0}'.format(self.software)