Exploit databaseDownload repository ZIP
GH-a794980697aa5e77c313e4780ec4d286
ruppde/rdg_scanner_cve-2020-0609
Sources for CVE-2020-0609
13 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
ruppde/rdg_scanner_cve-2020-0609Revision 4732922935ee
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
rdg_scanner_cve-2020-0609.py
Python · 12,608 bytes#!/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)