-
Notifications
You must be signed in to change notification settings - Fork 44
/
sshscan.py
executable file
·342 lines (251 loc) · 9.13 KB
/
sshscan.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
#!/usr/bin/env python3
import sys
import socket
import struct
from yaml import safe_load
from typing import List, Tuple
from secrets import token_bytes
from binascii import hexlify
from optparse import OptionParser, OptionGroup
def banner():
banner = """
_____ _____ _ _ _____
/ ___/ ___| | | / ___|
\ `--.\ `--.| |_| \ `--. ___ __ _ _ __
`--. \`--. | _ |`--. \/ __/ _` | '_ \\
/\__/ /\__/ | | | /\__/ | (_| (_| | | | |
\____/\____/\_| |_\____/ \___\__,_|_| |_|
evict
"""
return banner
def print_columns(cipherlist):
# adjust the amount of columns to display
cols = 2
while len(cipherlist) % cols != 0:
cipherlist.append("")
else:
split = [
cipherlist[i : i + int(len(cipherlist) / cols)]
for i in range(0, len(cipherlist), int(len(cipherlist) / cols))
]
for row in zip(*split):
print(" " + "".join(str.ljust(c, 37) for c in row))
print("\n")
def return_diff_list(detected, strong):
results = []
for item in detected:
if item not in strong:
results.append(item)
return results
def parse_results(version, kex, salg, enc, mac, cmpv):
version = version.decode("utf-8").rstrip()
kex = kex.decode("utf-8").split(",")
salg = salg.decode("utf-8").split(",")
enc = enc.decode("utf-8").split(",")
mac = mac.decode("utf-8").split(",")
cmpv = cmpv.decode("utf-8").split(",")
with open("config.yml") as fd:
config = safe_load(fd)
weak_ciphers = return_diff_list(enc, config["ciphers"])
weak_macs = return_diff_list(mac, config["macs"])
weak_kex = return_diff_list(kex, config["kex"])
weak_hka = return_diff_list(salg, config["hka"])
compression = True if "zlib@openssh.com" in cmpv else False
print(" [+] Detected the following ciphers: ")
print_columns(enc)
print(" [+] Detected the following KEX algorithms: ")
print_columns(kex)
print(" [+] Detected the following MACs: ")
print_columns(mac)
print(" [+] Detected the following HostKey algorithms: ")
print_columns(salg)
print(" [+] Target SSH version is: %s" % version)
print(" [+] Retrieving ciphers...")
if weak_ciphers:
print(" [+] Detected the following weak ciphers: ")
print_columns(weak_ciphers)
else:
print(" [+] No weak ciphers detected!")
if weak_kex:
print(" [+] Detected the following weak KEX algorithms: ")
print_columns(weak_kex)
else:
print(" [+] No weak KEX detected!")
if weak_macs:
print(" [+] Detected the following weak MACs: ")
print_columns(weak_macs)
else:
print(" [+] No weak MACs detected!")
if weak_hka:
print(" [+] Detected the following weak HostKey algorithms: ")
print_columns(weak_hka)
else:
print(" [+] No weak HostKey algorithms detected!")
if compression:
print(" [+] Compression has been enabled!")
def unpack_ssh_name_list(kex, n):
"""
Unpack the name-list from the packet
The comma separated list is preceded by an unsigned
integer which specifies the size of the list.
"""
size = struct.unpack("!I", kex[n : n + 4])[0] + 1
# jump to the name-list
n += 3
payload = struct.unpack(f"!{size}p", kex[n : n + size])[0]
# to the next integer
n += size
return payload, n
def unpack_msg_kex_init(kex):
# the MSG for KEXINIT looks as follows
# byte SSH_MSG_KEXINIT
# byte[16] cookie (random bytes)
# name-list kex_algorithms
# name-list server_host_key_algorithms
# name-list encryption_algorithms_client_to_server
# name-list encryption_algorithms_server_to_client
# name-list mac_algorithms_client_to_server
# name-list mac_algorithms_server_to_client
# name-list compression_algorithms_client_to_server
# name-list compression_algorithms_server_to_client
# name-list languages_client_to_server
# name-list languages_server_to_client
# boolean first_kex_packet_follows
# uint32 0 (reserved for future extension)
packet_size = struct.unpack("!I", kex[0:4])[0]
print(f"[*] KEX size: {packet_size}")
message = kex[5] # 20 == SSH_MSG_KEXINIT
if message != 20:
raise ValueError("did not receive SSH_MSG_KEXINIT")
cookie = struct.unpack("!16p", kex[6:22])[0]
print(f"[*] server cookie: {hexlify(cookie).decode('utf-8')}")
kex_size = struct.unpack("!I", kex[22:26])[0]
kex_size += 1
kex_algos = struct.unpack(f"!{kex_size}p", kex[25 : 25 + kex_size])[0]
n = 25 + kex_size
server_host_key_algo, n = unpack_ssh_name_list(kex, n)
enc_client_to_server, n = unpack_ssh_name_list(kex, n)
enc_server_to_client, n = unpack_ssh_name_list(kex, n)
mac_client_to_server, n = unpack_ssh_name_list(kex, n)
mac_server_to_client, n = unpack_ssh_name_list(kex, n)
cmp_client_to_server, n = unpack_ssh_name_list(kex, n)
cmp_server_to_client, n = unpack_ssh_name_list(kex, n)
return (
kex_algos,
server_host_key_algo,
enc_server_to_client,
mac_server_to_client,
cmp_server_to_client,
)
def pack_msg_kexinit_for_server(kex, salg, enc, mac, cmpv):
kex_fmt = f"!I{len(kex)}s"
sal_fmt = f"!I{len(salg)}s"
enc_fmt = f"!I{len(enc)}s"
mac_fmt = f"!I{len(mac)}s"
cmp_fmt = f"!I{len(cmpv)}s"
kex = struct.pack(kex_fmt, len(kex), kex)
sal = struct.pack(sal_fmt, len(salg), salg)
enc = struct.pack(enc_fmt, len(enc), enc)
mac = struct.pack(mac_fmt, len(mac), mac)
cmpv = struct.pack(cmp_fmt, len(cmpv), cmpv)
# languages are not used, therefore null
# 4 bytes are reserved
remain = b"\x00\x00\x00\x00"
packet = b"\x20"
packet += token_bytes(16)
packet += kex
packet += sal
# we are lazy and have the ctos and stoc options same.
# this should not be the case
packet += enc
packet += enc
packet += mac
packet += mac
packet += cmpv
packet += cmpv
packet += b"\x00"
packet += remain
packet += b"\x00" * 8
# + unsigned int + header
size = len(packet) + 4 + 2
# properly calculate the padding with length % 8
padding_len = size % 8
if padding_len < 4:
padding_len = 4
return _pack_packet(packet)
def retrieve_initial_kexinit(host: str, port: int) -> Tuple[List, List]:
s = return_socket_for_host(host, port)
version = s.recv(2048)
s.send(version)
kex_init = s.recv(4096)
s.close()
return kex_init, version
def return_socket_for_host(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
def _pack_packet(packet):
block_size = 8
# https://github.com/paramiko/paramiko/blob/master/paramiko/packet.py#L631
padding_len = 3 + block_size - ((len(packet) + 8) % block_size) + 1
if padding_len < block_size:
padding_len = block_size
header = struct.pack(">IB", len(packet) + padding_len, padding_len)
padding = b"\x00" * padding_len
packet = header + packet + padding
return packet
def main():
print(banner())
parser = OptionParser(usage="usage %prog [options]", version="%prog 2.0")
parameters = OptionGroup(parser, "Options")
parameters.add_option(
"-t",
"--target",
type="string",
help="Specify target as 'target' or 'target:port' (port 22 is default)",
dest="target",
)
parameters.add_option(
"-l",
"--target-list",
type="string",
help="File with targets: 'target' or 'target:port' seperated by a newline (port 22 is default)",
dest="targetlist",
)
parser.add_option_group(parameters)
options, arguments = parser.parse_args()
targets = []
target = options.target
targetlist = options.targetlist
if target:
targets.append(target)
else:
if targetlist:
with open(targetlist) as fd:
for item in fd.readlines():
targets.append(item.rstrip())
else:
print("[-] No target specified!")
sys.exit(0)
# we send first packets to make sure we match keys
for target in targets:
if ":" not in target:
target += ":22"
host, port = target.split(":")
port = int(port)
try:
kex_init, version = retrieve_initial_kexinit(host, port)
except socket.timeout:
print(" [-] Timeout while connecting to %s on port %i\n" % (host, port))
except socket.error as e:
if e.errno == 61:
print(" [-] %s\n" % (e.strerror))
else:
print(
" [-] Error while connecting to %s on port %i\n" % (host, port)
)
# parse the server KEXINIT message
kex, salg, enc, mac, cmpv = unpack_msg_kex_init(kex_init)
parse_results(version, kex, salg, enc, mac, cmpv)
if __name__ == "__main__":
main()