-
Notifications
You must be signed in to change notification settings - Fork 11
/
rdg_scanner_cve-2020-0609.py
executable file
·357 lines (277 loc) · 12.3 KB
/
rdg_scanner_cve-2020-0609.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
#!/usr/bin/env python3
#
# This scanner can do 2 things:
# 1. Simple check to see if the server is RD Gatway via webpage
# 2. vuln check (using the great work from https://github.com/MalwareTech/RDGScanner)
#
# Some scan framework code taken from https://raw.githubusercontent.com/trustedsec/cve-2019-19781/master/cve-2019-19781_scanner.py
#
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # disable warnings
import argparse
from netaddr import IPNetwork
import multiprocessing
import time
import subprocess
import re
from OpenSSL import SSL
from OpenSSL._util import (lib as _lib)
import sys
import os
import socket
import struct
import select
############################# kind of config ################################################
# set how many processes can run concurrently. gives missing file descriptor errors on my system if higher than ~1050 so 500 is a good value
max_processes = 500
# max_processes * new_process_wait = "seconds a process has before it gets killed". should be >= 5, more is better for reliable results on slow networks
new_process_wait = 0.04
# if server doesn't respond before timeout, we assume it's patched
# setting the timeout too low can result in false negatives
# the original scanner of malwaretech uses 3
timeout_secs = 3
# timeout to wait for all processes to be finished
timeout_end = timeout_secs + 2
###############################################################################################
# PyOpenSSL doesn't expose the DTLS method to python, so we have to patch it
DTLSv1_METHOD = 7
SSL.Context._methods[DTLSv1_METHOD] = getattr(_lib, "DTLSv1_client_method")
def asn_to_ip(asn):
# use ASN listings to enumerate whois information for scanning.
cidr_list = []
command = 'whois -h whois.radb.net -- \'-i origin %s\' | grep -Eo "([0-9.]+){4}/[0-9]+" | head' % (asn)
asn_convert = subprocess.Popen([command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr_read = asn_convert.stderr.read().decode('utf-8')
asn_convert = asn_convert.stdout.read().decode('utf-8').splitlines()
# if we don't have whois installed
if "whois: not found" in stderr_read:
print("[-] In order for ASN looks to work you must have whois installed. Type apt-get install whois as an example on Debian/Ubuntu.")
sys.exit()
# iterate through cidr ranges and append them to list to be scanned
for cidr in asn_convert:
cidr_list.append(cidr)
return cidr_list
# we need to do this hack job due to sanitization of urls in the latest version of urllib3
# special thanks to rxwx for the fix
def submit_url(url):
with requests.Session() as s:
r = requests.Request(method='GET', url=url)
prep = r.prepare()
prep.url = url
try:
return s.send(prep, verify=False, timeout=5)
except:
# send fails hard on openssl errors like sslv3 only but that shouldn't be in w2012+ anyway
pass
# vuln check
def check_server_vuln(target, targetport, verbose):
print("Scanning: %s " % target, end="\r") # Cleaning up output a little
vulnerable, cert = vuln_scan_server(target, targetport, timeout_secs)
if vulnerable:
print("[\033[91m!\033[0m]Server is vulnerable: {0:s} cert: {1:s} ".format(target, cert), end="\n")
found = target + "\t" + cert
vulnServers.append(found)
# write to log and flush to have the results if something crashes
logfile.write(found + "\n")
logfile.flush()
else:
print("Server is patched: {0:s} cert: {1:s} ".format(target, cert), end="\n")
# checking if webpage is an RD gateway
def check_server_webcheck(target, targetport, verbose):
try:
url = ("https://%s:%s/RDWeb" % (target,targetport))
print("Webcheck on: %s " % url, end="\n") # Cleaning up output a little
req = submit_url(url)
# only non-empty pages
if req:
cont = str(req.content)
if (
('RemoteApp and Desktop Connection') in cont or
('RD Web Access') in cont or
('Remote Desktop Services') in cont or
('RemoteApp') in cont or
('RD' in cont and 'Gateway' in cont ) or
('Remote Desktop' in cont and 'Gateway' in cont )
):
print("[\033[91m!\033[0m] This is a RD Gateway: %s " % (target))
vulnServers.append(target)
# write to log and flush to have the results if something crashes
logfile.write(target + "\n")
logfile.flush()
return 1
# if we run into something other than RD Gateway
else:
if verbose == True: print("[-] Server %s does not appear to be a RD Gateway server." % (target))
pass
# handle exception errors due to timeouts
except requests.ReadTimeout:
if verbose == True: print("[-] ReadTimeout: Server %s timed out and didn't respond on port: %s." % (target, targetport))
pass
except requests.ConnectTimeout:
if verbose == True: print("[-] ConnectTimeout: Server %s did not respond to a web request or the port (%s) is not open." % (target, targetport))
pass
except requests.ConnectionError:
if verbose == True: print("[-] ConnectionError: Server %s did not respond to a web request or the port (%s) is not open." % (target,targetport))
pass
# all other exceptions:
except requests.exceptions.RequestException as e:
print(e)
def start_scan_process(ip, port, verbose):
global counter
if webcheck ==True:
process = multiprocessing.Process(target=check_server_webcheck, args=(ip,port, verbose))
else:
process = multiprocessing.Process(target=check_server_vuln, args=(ip,port, verbose))
process.start()
# keep list of all running processes
all_processes.append(process)
# wait a bit to not create processes too fast
time.sleep(new_process_wait)
counter = counter + 1
# kill the oldest process hard if more than max_processes are running, because every process uses 13 file descriptors for SSL libs
# that's not clean programming, reason is this error in pythons OpenSSL https://github.com/pyca/pyopenssl/issues/168
# which prevents setting a timeout on the dtls handshake so it takes forever if the destination isn't responding
if verbose: print("num of processes running: " + str(len(all_processes)))
if len(all_processes) > max_processes:
oldest_proc = all_processes.pop(0)
# goodbye cruel world
oldest_proc.terminate()
def parse_target_args(target, port, verbose):
# cidr lookups for ASN lookups
if re.match ("as\d\d\d", target, re.IGNORECASE) :
CIDR_Blocks = asn_to_ip(target)
for ip_block in CIDR_Blocks:
for ip in IPNetwork(ip_block):
start_scan_process(ip,port,verbose)
# if we are iterating through IP addresses to scan CIDR notations
elif "/" in target:
for ip in IPNetwork(target):
start_scan_process(str(ip),port,verbose)
# if we are just using 1 IP address
else:
start_scan_process(target,port, verbose)
# vuln check from https://github.com/MalwareTech/RDGScanner)
def build_connect_packet(fragment_id, num_fragments, data):
packet_type = 5
packet_len = len(data) + 6
fragment_id = fragment_id
num_fragments = num_fragments
fragment_len = len(data)
data = data
packet = struct.pack('<HHHHH', packet_type, packet_len, fragment_id,
num_fragments, fragment_len)
packet += data
return packet
def certificate_callback(sock, cert, err_num, depth, ok):
server_name = cert.get_subject().commonName
if verbose: print('Got certificate for server: %s' % server_name)
cert_of_sock[sock] = server_name or "NOCERTIFICATE"
return True
def vuln_scan_server(ip, port, timeout):
vulnerable = True
print('Checking {}:{}'.format(ip, port))
ctx = SSL.Context(DTLSv1_METHOD)
ctx.set_verify_depth(2)
ctx.set_verify(SSL.VERIFY_PEER, certificate_callback)
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
sock.connect((ip, int(port)))
# this will hang indifinetly on hosts without open UDP 3391 because it doesn't only "send" but also waits for a reply, didn't find a better way to solve this than terminating the process
sock.send(build_connect_packet(0, 65, b"A"))
read_fds, _, _ = select.select([sock], [], [], timeout)
if read_fds:
data = sock.recv(1024)
if len(data) == 16:
error_code = struct.unpack('<L', data[12:])[0]
if error_code == 0x8000ffff:
vulnerable = False
cert = cert_of_sock[sock]
return vulnerable, cert
print("""
____ ____ ____ _
| _ \| _ \ / ___| __ _| |_ _____ ____ _ _ _
| |_) | | | | | | _ / _` | __/ _ \ \ /\ / / _` | | | |
| _ <| |_| | | |_| | (_| | || __/\ V V / (_| | |_| |
|_| \_\____/ \____|\__,_|\__\___| \_/\_/ \__,_|\__, |
|___/
RD-Gateway-Scanner
The scanner can use:
* IPs
* CIDR notations, for example: 192.168.1.0/24
* Hostnames
* Routing AS, e.g. as1234
* Plaintext files containing anything of the above, one entry per line, passed as file:netlist.txt
```
Example: python3 rdg_scanner_cve-2020-0609.py 192.168.1.1/24 # vuln scan for cve-2020-0609 on UDP 3391
Example2 python3 rdg_scanner_cve-2020-0609.py 192.168.1.1/24 --webcheck # check webpage for RD gateway
Example3: python3 rdg_scanner_cve-2020-0609.py 192.168.1.1
Example4: python3 rdg_scanner_cve-2020-0609.py fakewebsiteaddress.com
Example5: python3 rdg_scanner_cve-2020-0609.py as15169
Example6: python3 rdg_scanner_cve-2020-0609.py file:hostfile.txt
usage: rdg_scanner_cve-2020-0609.py [-h] [--port PORT] [--webcheck]
[--verbose]
target
""")
# for sharing global variables in multiprocessing
manager = multiprocessing.Manager()
vulnServers = manager.list()
# collect certificates of each socket
cert_of_sock = {}
# process queue to kill oldest, FIFO
all_processes = []
# counter of scanned IPs
counter = 0
# parse our commands
parser = argparse.ArgumentParser()
parser.add_argument("target", help="server to check (defaults https)")
parser.add_argument("--port", "-p", help="the target port (normally on 443 or 3391)")
parser.add_argument("--webcheck", "-w", action='store_true', help="Find RD gateways by their webpage (not all have UDP 3391 open on the firewall)")
parser.add_argument("--verbose", "-v", action='store_true', help="print out verbose information")
args = parser.parse_args()
t = time.strftime('%Y%m%dT%H%M%S')
# if we specify the webcheck flag
if args.webcheck:
webcheck = True
log = "scan_webcheck_rdg_" + t + ".log"
else:
webcheck = False
log = "scan_vulncheck_cve-2020-0609_" + t + ".log"
# if we specify a verbose flag
if args.verbose:
verbose = True
else: verbose = False
if args.port:
targetport = args.port
else:
if webcheck:
targetport = 443
else:
targetport = 3391
print("Writting results to logfile: " + log)
with open(log, 'a') as logfile:
# specify file option to import host:port
if "file:" in (args.target):
print("[*] Importing in list of hosts from filename: %s" % (args.target))
with open(args.target.split(':')[1], 'r') as file:
hosts= file.read().splitlines()
for target_line in hosts:
parse_target_args(target_line,targetport, verbose)
else:
parse_target_args(args.target, targetport, verbose)
time.sleep(5)
print("wait " + str(timeout_end) + " more seconds so all processes are hopefully finnished...")
time.sleep(timeout_end)
# do a report on servers
print("Finished testing. Below is a list system(s) identified:")
print("-" * 45)
for server in vulnServers:
print(server)
print("-" * 45)
# do a report on servers
if webcheck:
print("Tested %s servers: Found %s to be RD Gateway." % (counter, len(vulnServers)))
else:
print("Tested %s servers: Found %s to vulnerable to CVE-2020-0609." % (counter, len(vulnServers)))
print("Results written to logfile: " + log)
# not nice but see comments above ...
os._exit(os.EX_OK)