示例#1
0
 public static void AssertSuccess(NtStatus status)
 {
     if(status != NtStatus.Success)
     {
         Win32ErrorCode code = NativeMethods.RtlNtStatusToDosError(status);
         throw new Win32Exception((int) code);
     }
 }
示例#2
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, NtStatus result, params string[] parameters)
        {
            var extraParameters = parameters != null && parameters.Length > 0 ? ", " + string.Join(", ", parameters) : string.Empty;

#if TRACE
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}('{1}', {2}{3}) -> {4}",
                method, fileName, ToTrace(info), extraParameters, result));
#endif

            return result;
        }
示例#3
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info,
                                  FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
                                  NtStatus result)
        {
#if TRACE
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}('{1}', {2}, [{3}], [{4}], [{5}], [{6}], [{7}]) -> {8}",
                method, fileName, ToTrace(info), access, share, mode, options, attributes, result));
#endif

            return result;
        }
示例#4
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info,
            FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
            NtStatus result)
        {
#if TRACE
            logger.Debug(
                DokanFormat(
                    $"{method}('{fileName}', {info}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}"));
#endif

            return result;
        }
示例#5
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, NtStatus result,
            params object[] parameters)
        {
#if TRACE
            var extraParameters = parameters != null && parameters.Length > 0
                ? ", " + string.Join(", ", parameters.Select(x => string.Format(DefaultFormatProvider, "{0}", x)))
                : string.Empty;

            logger.Debug(DokanFormat($"{method}('{fileName}', {info}{extraParameters}) -> {result}"));
#endif

            return result;
        }
示例#6
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, NtStatus result)
        {
            logger?.Trace($"{System.Threading.Thread.CurrentThread.ManagedThreadId:D2} / {drive.DisplayRoot} {method}({fileName}, {info.ToTrace()}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}".ToString(CultureInfo.CurrentCulture));

            return(result);
        }
 /// <summary>
 /// Checks if the NtStatus value is a success
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>True if a success</returns>
 public static bool IsSuccess(this NtStatus status)
 {
     return((int)status >= 0);
 }
        /// <summary>
        /// SmbdEndpoint constructor will load RDMA providers and initialize default connection values.
        /// </summary>
        /// <param name="inboundEntries">maximum number of outstanding Receive requests.</param>
        /// <param name="outboundEntries">maximum number of outstanding Send, SendAndInvalidate
        /// , Bind, Invalidate, Read, and Write requests.
        /// </param>
        /// <param name="inboundSegment">inbound segments limit</param>
        /// <param name="outboundSegment">outbound segments limit</param>
        /// <param name="inboundReadLimit">maximum inbound read limit for the local Network 
        /// Direct adapter. This value can be zero if you do not support
        /// </param>
        /// <param name="outboundReadLimit"></param>
        /// <param name="inboundDataSize">Max Size of RDMA inbound data</param>
        /// <param name="logEvent">Delegate to log SMBD event</param>
        public SmbdConnectionEndpoint(
            uint inboundEntries,
            uint outboundEntries,
            uint inboundSegment,
            uint outboundSegment,
            uint inboundReadLimit,
            uint outboundReadLimit,
            uint inboundDataSize,
            SmbdLogEvent logEvent = null
            )
        {
            this.logEndpointEvent = logEvent;

            LogEvent("Loading the providers of registered network drivers.");
            initializeStatus = (NtStatus)RdmaProvider.LoadRdmaProviders(out rdmaProvidersList);

            this.inboundEntries = inboundEntries;
            this.outboundEntries = outboundEntries;
            this.inboundSegment = inboundSegment;
            this.outboundSegment = outboundSegment;
            this.inboundReadLimit = inboundReadLimit;
            this.outboundReadLimit = outboundReadLimit;
            this.completionQueueDepth = (inboundEntries + outboundEntries);
            this.inboundDataSize = inboundDataSize;

            isConnected = false;
            memoryWindowList = new List<SmbdMemoryWindow>();
            receiveRequestList = new List<SmbdRequest>();

            locker = new Object();

            otherRequestResult = new SyncFilterQueue<SmbdRequestResult>();
            receiveRequestResult = new SyncFilterQueue<SmbdRequestResult>();

            disconnectSemaphore = new Semaphore(0, 1);
            //threadStopSemaphore = new Semaphore(0, THREAD_COUNT);

            // one more for Semaphore Release when disconnection
            rdmaNotificationSemaphore = new Semaphore(0, (int)completionQueueDepth + 1);
            requestCount = 0;

            ReceivePostedCount = 0;

            #region output provider information
            if (initializeStatus != NtStatus.STATUS_SUCCESS)
            {
                LogEvent(string.Format("Load provider with error code: {0}", (NtStatus)initializeStatus));
                return;
            }
            if (rdmaProvidersList == null)
            {
                LogEvent("The returned providers list is NULL");
                return;
            }

            LogEvent(string.Format("{0} providers of registered network drivers have been load,", rdmaProvidersList.Length));
            int providerIndex = 0;
            foreach (RdmaProviderInfo info in rdmaProvidersList)
            {
                if (info != null)
                {
                    LogEvent(string.Format("Load provider {1}: {0}", info.Path, ++providerIndex));
                }
            }
            LogEvent("Loading providers is completed");
            #endregion
        }
示例#9
0
        /// <summary>
        /// Convert security descriptor to a byte array
        /// </summary>
        /// <returns>The binary security descriptor</returns>
        public byte[] ToByteArray()
        {
            SafeStructureInOutBuffer <SecurityDescriptorStructure> sd_buffer = null;
            SafeHGlobalBuffer   dacl_buffer  = null;
            SafeHGlobalBuffer   sacl_buffer  = null;
            SafeSidBufferHandle owner_buffer = null;
            SafeSidBufferHandle group_buffer = null;

            try
            {
                sd_buffer = new SafeStructureInOutBuffer <SecurityDescriptorStructure>();
                NtRtl.RtlCreateSecurityDescriptor(sd_buffer, Revision).ToNtException();
                SecurityDescriptorControl control = Control & SecurityDescriptorControl.ValidControlSetMask;
                NtRtl.RtlSetControlSecurityDescriptor(sd_buffer, control, control).ToNtException();
                if (Dacl != null)
                {
                    if (!Dacl.NullAcl)
                    {
                        dacl_buffer = new SafeHGlobalBuffer(Dacl.ToByteArray());
                    }
                    else
                    {
                        dacl_buffer = new SafeHGlobalBuffer(IntPtr.Zero, 0, false);
                    }

                    NtRtl.RtlSetDaclSecurityDescriptor(sd_buffer, true, dacl_buffer.DangerousGetHandle(), Dacl.Defaulted).ToNtException();
                }
                if (Sacl != null)
                {
                    if (!Sacl.NullAcl)
                    {
                        sacl_buffer = new SafeHGlobalBuffer(Sacl.ToByteArray());
                    }
                    else
                    {
                        sacl_buffer = new SafeHGlobalBuffer(IntPtr.Zero, 0, false);
                    }

                    NtRtl.RtlSetSaclSecurityDescriptor(sd_buffer, true, sacl_buffer.DangerousGetHandle(), Sacl.Defaulted).ToNtException();
                }
                if (Owner != null)
                {
                    owner_buffer = Owner.Sid.ToSafeBuffer();
                    NtRtl.RtlSetOwnerSecurityDescriptor(sd_buffer, owner_buffer.DangerousGetHandle(), Owner.Defaulted);
                }
                if (Group != null)
                {
                    group_buffer = Group.Sid.ToSafeBuffer();
                    NtRtl.RtlSetGroupSecurityDescriptor(sd_buffer, group_buffer.DangerousGetHandle(), Group.Defaulted);
                }

                int      total_length = 0;
                NtStatus status       = NtRtl.RtlAbsoluteToSelfRelativeSD(sd_buffer, new SafeHGlobalBuffer(IntPtr.Zero, 0, false), ref total_length);
                if (status != NtStatus.STATUS_BUFFER_TOO_SMALL)
                {
                    status.ToNtException();
                }

                using (SafeHGlobalBuffer relative_sd = new SafeHGlobalBuffer(total_length))
                {
                    NtRtl.RtlAbsoluteToSelfRelativeSD(sd_buffer, relative_sd, ref total_length).ToNtException();
                    return(relative_sd.ToArray());
                }
            }
            finally
            {
                sd_buffer?.Close();
                dacl_buffer?.Close();
                sacl_buffer?.Close();
                owner_buffer?.Close();
                group_buffer?.Close();
            }
        }
示例#10
0
 /// <summary>
 /// Determines whether the NT status value indicates success.
 /// </summary>
 /// <param name="status">The NT status value.</param>
 public static bool IsSuccess(NtStatus status)
 {
     return status >= NtStatus.Success && status < NtStatus.Informational;
 }
        internal CreateUserProcessResult(NtStatus status, ProcessCreateInfoData create_info, ProcessCreateState create_state)
        {
            ImageFile = null;
            if (create_state == ProcessCreateState.FailOnSectionCreate)
            {
                ImageFile = new NtFile(new SafeKernelObjectHandle(create_info.FileHandle, true));
            }
            else if (create_state == ProcessCreateState.FailExeName)
            {
                IFEOKeyHandle = RegistryKey.FromHandle(new SafeRegistryHandle(create_info.IFEOKey, true));
            }
            Status = status;
            CreateInfo = create_info;
            CreateState = create_state;

            Process = null;
            Thread = null;
            SectionHandle = null;
            ImageInfo = new SectionImageInformation();
            ClientId = new ClientId();
        }
示例#12
0
 public static extern NtStatus NtTerminateThread(SafeKernelObjectHandle ThreadHandle, NtStatus status);
示例#13
0
        private void unloadMenuItem_Click(object sender, EventArgs e)
        {
            if (!PhUtils.ShowConfirmMessage(
                    "Unload",
                    _pid != 4 ? "the selected module" : "the selected driver",
                    _pid != 4 ?
                    "Unloading a module may cause the process to crash." :
                    "Unloading a driver may cause system instability.",
                    true
                    ))
            {
                return;
            }

            if (_pid == 4)
            {
                try
                {
                    var    moduleItem  = (ModuleItem)listModules.SelectedItems[0].Tag;
                    string serviceName = null;

                    // Try to find the name of the service key for the driver by
                    // looping through the objects in the Driver directory and
                    // opening each one.
                    using (var dhandle = new DirectoryHandle("\\Driver", DirectoryAccess.Query))
                    {
                        foreach (var obj in dhandle.GetObjects())
                        {
                            try
                            {
                                using (var driverHandle = new DriverHandle("\\Driver\\" + obj.Name))
                                {
                                    if (driverHandle.GetBasicInformation().DriverStart == moduleItem.BaseAddress.ToIntPtr())
                                    {
                                        serviceName = driverHandle.GetServiceKeyName();
                                        break;
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }

                    // If we didn't find the service name, use the driver base name.
                    if (serviceName == null)
                    {
                        if (moduleItem.Name.EndsWith(".sys", StringComparison.OrdinalIgnoreCase))
                        {
                            serviceName = moduleItem.Name.Remove(moduleItem.Name.Length - 4, 4);
                        }
                        else
                        {
                            serviceName = moduleItem.Name;
                        }
                    }

                    RegistryKey servicesKey =
                        Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services", true);
                    bool        serviceKeyCreated;
                    RegistryKey serviceKey;

                    // Check if the service key exists so that we don't delete it
                    // later if it does.
                    if (Array.Exists <string>(servicesKey.GetSubKeyNames(),
                                              (keyName) => (string.Compare(keyName, serviceName, true) == 0)))
                    {
                        serviceKeyCreated = false;
                    }
                    else
                    {
                        serviceKeyCreated = true;
                        // Create the service key.
                        serviceKey = servicesKey.CreateSubKey(serviceName);

                        serviceKey.SetValue("ErrorControl", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("ImagePath", "\\??\\" + moduleItem.FileName, RegistryValueKind.ExpandString);
                        serviceKey.SetValue("Start", 1, RegistryValueKind.DWord);
                        serviceKey.SetValue("Type", 1, RegistryValueKind.DWord);
                        serviceKey.Close();
                        servicesKey.Flush();
                    }

                    try
                    {
                        Windows.UnloadDriver(serviceName);
                    }
                    finally
                    {
                        if (serviceKeyCreated)
                        {
                            servicesKey.DeleteSubKeyTree(serviceName);
                        }

                        servicesKey.Close();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to unload the driver. Make sure Process Hacker " +
                                    "is running with administrative privileges. Error:\n\n" +
                                    ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    using (ProcessHandle phandle = new ProcessHandle(_pid,
                                                                     Program.MinProcessQueryRights | ProcessAccess.VmOperation |
                                                                     ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.CreateThread))
                    {
                        IntPtr baseAddress = ((ModuleItem)listModules.SelectedItems[0].Tag).BaseAddress.ToIntPtr();

                        phandle.SetModuleReferenceCount(baseAddress, 1);

                        ThreadHandle thread;

                        if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista))
                        {
                            // Use RtlCreateUserThread to bypass session boundaries. Since
                            // LdrUnloadDll is a native function we don't need to notify CSR.
                            thread = phandle.CreateThread(
                                Loader.GetProcedure("ntdll.dll", "LdrUnloadDll"),
                                baseAddress
                                );
                        }
                        else
                        {
                            // On XP it seems we need to notify CSR...
                            thread = phandle.CreateThreadWin32(
                                Loader.GetProcedure("kernel32.dll", "FreeLibrary"),
                                baseAddress
                                );
                        }

                        thread.Wait(1000 * Win32.TimeMsTo100Ns);

                        NtStatus exitStatus = thread.GetExitStatus();

                        if (exitStatus == NtStatus.DllNotFound)
                        {
                            if (OSVersion.Architecture == OSArch.Amd64)
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file or a 32-bit module.");
                            }
                            else
                            {
                                PhUtils.ShowError("Unable to find the module to unload. This may be caused " +
                                                  "by an attempt to unload a mapped file.");
                            }
                        }
                        else
                        {
                            exitStatus.ThrowIf();
                        }

                        thread.Dispose();
                    }

                    listModules.SelectedItems.Clear();
                }
                catch (Exception ex)
                {
                    PhUtils.ShowException("Unable to unload the module", ex);
                }
            }
        }
示例#14
0
 internal NtResult(NtStatus status, T result)
 {
     Status  = status;
     _result = result;
 }
示例#15
0
 internal static extern int RtlNtStatusToDosError(NtStatus ntStatus);
示例#16
0
        public NtStatus CreateFile(string filename, FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, System.IO.FileAttributes attributes, IDokanFileInfo info)
        {
            var node = GetNodeFast(filename, info);

            if (node == null)
            {
                if (access == FileAccess.Delete)
                {
                    return(DokanResult.Success);                            //already gone
                }
                switch (mode)
                {
                case FileMode.CreateNew:
                case FileMode.Create:
                case FileMode.OpenOrCreate:
                    if (filename.Length == 0)
                    {
                        return(NtStatus.Success);
                    }
                    string Directory = filename;
                    if (!info.IsDirectory)     //Directory doesn't have a filename that we want to cut off
                    {
                        Directory = filename.Substring(0, filename.LastIndexOf('\\'));
                        if (Directory.Length == 0)
                        {
                            Directory = "\\";
                        }
                    }


                    var nodeDirectory = CreateOrFindDirectoryRecursive(Directory);

                    if (!(nodeDirectory is PboFsRealFolder) && nodeDirectory is PboFsFolder virtualFolder)
                    {
                        nodeDirectory = fileTree.MakeDirectoryWriteable(virtualFolder);
                    }

                    if (nodeDirectory is PboFsRealFolder folder)
                    {
                        if (info.IsDirectory)
                        {
                            info.Context = nodeDirectory;
                            //Nothing else to do as full path is already included in DirectoryPath
                        }
                        else
                        {
                            //Filename without folder path
                            var FileNameDirect = filename.Substring(filename.LastIndexOf('\\'));
                            var FileNameDirectNoLeadingSlash = filename.Substring(filename.LastIndexOf('\\') + 1);

                            FileStream newStream = null;
                            try
                            {
                                newStream = System.IO.File.Create(folder.path + FileNameDirect);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                return(DokanResult.AccessDenied);   //#TODO correct result for exception type
                            }

                            var rlFile = new PboFsRealFile(new System.IO.FileInfo(folder.path + FileNameDirect), folder, newStream);

                            folder.Children[FileNameDirectNoLeadingSlash.ToLower()] = rlFile;
                            fileTree.AddNode(rlFile);
                            info.Context = rlFile;
                        }

                        return(DokanResult.Success);
                    }

                    return(DokanResult.DiskFull);

                case FileMode.Open:
                case FileMode.Truncate:
                case FileMode.Append:
                    return(DokanResult.FileNotFound);
                }
            }

            info.Context = node;
            if (node is PboFsFolder && !info.IsDirectory)
            {
                info.IsDirectory = true;                                           //Dokan documentation says we need to do that.
            }
            if (mode == FileMode.CreateNew)
            {
                return(DokanResult.FileExists);
            }

            if (access == FileAccess.Delete)
            {
                NtStatus deleteResult = DokanResult.NotImplemented;
                if (node is PboFsRealFile)
                {
                    deleteResult = DeleteFile(filename, info);
                }
                else if (node is PboFsRealFolder)
                {
                    deleteResult = DeleteDirectory(filename, info);
                }

                return(deleteResult);
            }

            bool wantsWrite = (access &
                               (FileAccess.WriteData | FileAccess.AppendData | FileAccess.Delete | FileAccess.GenericWrite)
                               ) != 0;

            bool wantsRead = (access &
                              (FileAccess.ReadData | FileAccess.GenericRead | FileAccess.Execute | FileAccess.GenericExecute)
                              ) != 0;

            if (wantsWrite && !(node is IPboFsRealObject))
            {
                return(DokanResult.AccessDenied);
            }

            if (node is IPboFsFile file && (wantsRead || wantsWrite))
            {
                return(file.Open(wantsWrite, mode));
            }

            return(DokanResult.Success);
        }
示例#17
0
        protected NtStatus Trace(string method, string fileName, IDokanFileInfo info, NtStatus result,
                                 params object[] parameters)
        {
#if TRACE
            var extraParameters = parameters != null && parameters.Length > 0
                ? ", " + string.Join(", ", parameters.Select(x => string.Format(DefaultFormatProvider, "{0}", x)))
                : string.Empty;

            logger.Debug(DokanFormat($"{method}('{fileName}', {info}{extraParameters}) -> {result}"));
#endif

            return(result);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="status">Status result</param>
 public NtException(NtStatus status)
 {
     Status = status;
 }
 /// <summary>
 /// Checks if the NtStatus value is an error.
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>True if an error.</returns>
 public static bool IsError(this NtStatus status)
 {
     return(status.GetSeverity() == NtStatusSeverity.STATUS_SEVERITY_ERROR);
 }
 /// <summary>
 /// Add a queued status to the queue.
 /// </summary>
 /// <param name="key_context">The optional key context.</param>
 /// <param name="apc_context">The optional APC context.</param>
 /// <param name="status">Status code</param>
 /// <param name="information">The information context.</param>
 public void Set(IntPtr key_context, IntPtr apc_context, NtStatus status, IntPtr information)
 {
     NtSystemCalls.NtSetIoCompletion(Handle, key_context,
                                     apc_context, status, information).ToNtException();
 }
示例#21
0
        public void KphTerminateProcess(ProcessHandle processHandle, NtStatus exitStatus)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = processHandle;
            *(int*)(inData + 4) = (int)exitStatus;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphTerminateProcess), inData, 8, null, 0);
            }
            catch (WindowsException ex)
            {
                // STATUS_CANT_TERMINATE_SELF means we tried to terminate ourself. Kernel-mode can't do it, 
                // so we do it now.
                if (ex.Status == NtStatus.CantTerminateSelf)
                    Win32.TerminateProcess(new IntPtr(-1), (int)exitStatus);
                else
                    throw ex;
            }
        }
示例#22
0
 /// <summary>
 /// Terminate the process
 /// </summary>
 /// <param name="exitcode">The exit code for the termination</param>
 public void Terminate(NtStatus exitcode)
 {
     NtSystemCalls.NtTerminateProcess(Handle, exitcode).ToNtException();
 }
示例#23
0
 /// <summary>
 /// Determines whether the NT status value indicates an error.
 /// </summary>
 /// <param name="status">The NT status value.</param>
 public static bool IsError(NtStatus status)
 {
     return status >= NtStatus.Error && status <= NtStatus.MaximumNtStatus;
 }
示例#24
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, NtStatus result, params string[] parameters)
        {
            var extraParameters = parameters != null && parameters.Length > 0 ? ", " + string.Join(", ", parameters) : string.Empty;

            logger?.Trace($"{System.Threading.Thread.CurrentThread.ManagedThreadId:D2} / {method}({fileName}, {ToTrace(info)}{extraParameters}) -> {result}");

            return result;
        }
        public TokenHandle LogonUser(
            string originName,
            SecurityLogonType logonType,
            IAuthenticationPackage package,
            TokenSource source,
            out object profileData,
            out Luid logonId,
            out NtStatus subStatus
            )
        {
            IntPtr profileBuffer;
            int profileBufferLength;
            IntPtr token;
            QuotaLimits quotas;

            AnsiString originNameStr = new AnsiString(originName);

            try
            {
                using (MemoryRegion logonData = package.GetAuthData())
                {
                    Win32.LsaLogonUser(
                        this,
                        ref originNameStr,
                        logonType,
                        this.LookupAuthenticationPackage(package.PackageName),
                        logonData,
                        logonData.Size,
                        IntPtr.Zero,
                        ref source,
                        out profileBuffer,
                        out profileBufferLength,
                        out logonId,
                        out token,
                        out quotas,
                        out subStatus
                        ).ThrowIf();

                    using (new LsaMemoryAlloc(profileBuffer, true))
                    {
                        profileData = package.GetProfileData(new MemoryRegion(profileBuffer, 0, profileBufferLength));
                    }

                    return new TokenHandle(token, true);
                }
            }
            finally
            {
                originNameStr.Dispose();
            }
        }
示例#26
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, NtStatus result)
        {
            logger?.Trace($"{System.Threading.Thread.CurrentThread.ManagedThreadId:D2} / {method}({fileName}, {ToTrace(info)}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}");

            return result;
        }
 static extern NtStatus LsaLogonUser(SafeLsaHandle LsaHandle, LsaString OriginName, SecurityLogonType LogonType, uint AuthenticationPackage,
     SafeBuffer AuthenticationInformation,
     int AuthenticationInformationLength,
     IntPtr LocalGroups,
     TOKEN_SOURCE SourceContext,
     out IntPtr ProfileBuffer,
     out int ProfileBufferLength,
     out Luid LogonId,
     out SafeKernelObjectHandle Token,
     out QUOTA_LIMITS Quotas,
     out NtStatus SubStatus
 );
 /// <summary>
 /// Terminate the process
 /// </summary>
 /// <param name="exitcode">The exit code for the termination</param>
 public void Terminate(NtStatus exitcode)
 {
     Process?.Terminate(exitcode);
 }
 public static extern int RtlNtStatusToDosErrorNoTeb(NtStatus status);
示例#30
0
 public static extern int LsaNtStatusToWinError(
     [In] NtStatus Status
     );
示例#31
0
 public static extern NtStatus NtTerminateProcess(SafeKernelObjectHandle ProcessHandle, NtStatus ExitCode);
 public void CompleteCommand(int commandId, NtStatus completionStatus)
 {
     this.CompletionStatus = completionStatus;
     this.commandCompleted.Set();
 }
示例#33
0
        public static void AssertSuccess(NtStatus status)
        {
            Win32ErrorCode code = NativeMethods.RtlNtStatusToDosError(status);

            AssertSuccess(code);
        }
示例#34
0
 internal static extern Win32ErrorCode RtlNtStatusToDosError(NtStatus status);
 /// <summary>
 /// Convert an NtStatus to an exception if the status is an error
 /// </summary>
 /// <param name="status">The NtStatus</param>
 /// <returns>The original NtStatus if not an error</returns>
 /// <exception cref="NtException">Thrown if status is an error.</exception>
 public static NtStatus ToNtException(this NtStatus status)
 {
     return(status.ToNtException(true));
 }
示例#36
0
        public void KphDangerousTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = (int)exitStatus;

            _fileHandle.IoControl(CtlCode(Control.KphDangerousTerminateThread), inData, 8, null, 0);
        }
 /// <summary>
 /// Get the severity of the NTSTATUS.
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>The severity.</returns>
 public static NtStatusSeverity GetSeverity(this NtStatus status)
 {
     return((NtStatusSeverity)((uint)status >> 30));
 }
 internal static extern NtStatus LsaCallAuthenticationPackage(
     IntPtr LsaHandle,
     uint AuthenticationPackage,
     IntPtr ProtocolSubmitBuffer,
     int SubmitBufferLength,
     out IntPtr ProtocolReturnBuffer,
     out ulong ReturnBufferLength,
     out NtStatus ProtocolStatus
     );
 /// <summary>
 /// Get the facility of the NTSTATUS.
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>The facility.</returns>
 public static NtStatusFacility GetFacility(this NtStatus status)
 {
     return((NtStatusFacility)(((uint)status >> 16) & 0xFFF));
 }
示例#40
0
 private protected void WriteAccessWarning(NtObject root, string path, NtStatus status)
 {
     WriteAccessWarning($@"{root.FullPath.TrimEnd('\\')}\{path}", status);
 }
        public void KphTerminateProcess(ProcessHandle processHandle, NtStatus exitStatus)
        {
            KphTerminateProcessInput input;

            input.ProcessHandle = processHandle;
            input.ExitStatus = exitStatus;
            _fileHandle.IoControl(IoCtlTerminateProcess, &input, sizeof(KphTerminateProcessInput), null, 0);
        }
 /// <summary>
 /// Get the status code of the NTSTATUS.
 /// </summary>
 /// <param name="status">The NtStatus value.</param>
 /// <returns>The static code.</returns>
 public static int GetStatusCode(this NtStatus status)
 {
     return((int)((uint)status & 0xFFFF));
 }
示例#43
0
        public void KphTerminateThread(ThreadHandle threadHandle, NtStatus exitStatus)
        {
            byte* inData = stackalloc byte[8];

            *(int*)inData = threadHandle;
            *(int*)(inData + 4) = (int)exitStatus;

            try
            {
                _fileHandle.IoControl(CtlCode(Control.KphTerminateThread), inData, 8, null, 0);
            }
            catch (WindowsException ex)
            {
                if (ex.Status == NtStatus.CantTerminateSelf)
                    Win32.TerminateThread(new IntPtr(-2), (int)exitStatus);
                else
                    throw ex;
            }
        }
 /// <summary>
 /// Is an NTSTATUS a customer code.
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>True if is a customer code.</returns>
 public static bool IsCustomerCode(this NtStatus status)
 {
     return((((uint)status >> 29) & 1) != 0);
 }
示例#45
0
 public static void ThrowLastError(NtStatus status)
 {
     throw new WindowsException(status);
 }
 /// <summary>
 /// Is an NTSTATUS reserved.
 /// </summary>
 /// <param name="status">The NtStatus value</param>
 /// <returns>True if reserved.</returns>
 public static bool IsReserved(this NtStatus status)
 {
     return((((uint)status >> 28) & 1) != 0);
 }
示例#47
0
 /// <summary>
 /// Determines whether the NT status value indicates information.
 /// </summary>
 /// <param name="status">The NT status value.</param>
 public static bool IsInformational(NtStatus status)
 {
     return status >= NtStatus.Informational && status < NtStatus.Warning;
 }
 /// <summary>
 /// Create an NT result object. If status is successful then call function otherwise use default value.
 /// </summary>
 /// <typeparam name="T">The result type.</typeparam>
 /// <param name="status">The associated status code.</param>
 /// <param name="throw_on_error">Throw an exception on error.</param>
 /// <param name="create_func">Function to call to create an instance of the result</param>
 /// <returns>The created result.</returns>
 internal static NtResult <T> CreateResult <T>(this NtStatus status, bool throw_on_error, Func <NtStatus, T> create_func)
 {
     return(CreateResult(status, throw_on_error, create_func, null));
 }
示例#49
0
 /// <summary>
 /// Determines whether the NT status value indicates a warning.
 /// </summary>
 /// <param name="status">The NT status value.</param>
 public static bool IsWarning(NtStatus status)
 {
     return status >= NtStatus.Warning && status < NtStatus.Error;
 }
        private NtStatus ReadFile(IntPtr handle, IntPtr hEvent, IntPtr *apcRoutine, IntPtr *apcContext,
                                  ref Native.IO_STATUS_BLOCK ioStatus, byte *buffer, uint length, LARGE_INTEGER *byteOffset, IntPtr key,
                                  VirtualDwPack pack, long offset, long effOffset)
        {
            // File data read
            NtStatus result = NtStatus.Success;

            for (int i = 0; i < pack.Entries.Count; i++)
            {
                var entry      = pack.Entries[i];
                var dataOffset = (pack.Native.Data + entry.Native->DataOffset) - pack.Native.Ptr;
                if (effOffset < dataOffset || effOffset >= (dataOffset + entry.Native->CompressedSize))
                {
                    continue;
                }

                var fileDataOffset = effOffset - dataOffset;
                var readEndOffset  = fileDataOffset + length;
                if (readEndOffset > entry.Native->CompressedSize)
                {
                    continue;
                }

                // Make sure the file has been redirected
                // This is done as late as possible to improve startup times
                if (!entry.IsRedirected)
                {
                    mLogger.Info($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Data access Offset: 0x{effOffset:X8} Length: 0x{length:X8}");
                    result = mHooks.NtReadFileHook.OriginalFunction(handle, hEvent, apcRoutine, apcContext, ref ioStatus, buffer, length, byteOffset, key);
                }
                else
                {
                    mLogger.Info($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Data access Offset: 0x{effOffset:X8} Length: 0x{length:X8} redirected to {entry.RedirectedFilePath}");
                    result = NtStatus.Success;

                    if (fileDataOffset < 0)
                    {
                        mLogger.Error($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Offset is before start of data!!!");
                    }
                    else if (fileDataOffset > entry.RedirectedFileSize)
                    {
                        mLogger.Error($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Offset is after end of data!!!");
                    }

                    mLogger.Debug($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Reading 0x{length:X8} bytes from redirected file at offset 0x{fileDataOffset:X8}");

                    // Get cached file stream if the file was previously opened or open a new file
                    Stream redirectedStream;
                    if (mCachedFile == entry)
                    {
                        redirectedStream = mCachedFileStream;
                    }
                    else
                    {
                        mCachedFileStream?.Close();
                        mCachedFile       = entry;
                        mCachedFileStream = redirectedStream = entry.OpenRead();
                    }

                    // Read from redirected file into the buffer
                    try
                    {
                        redirectedStream.Seek(fileDataOffset, SeekOrigin.Begin);
                        var readBytes = redirectedStream.Read(new Span <byte>(( void * )buffer, ( int )length));
                        SetBytesRead(handle, ( int )offset, ( int )length, ref ioStatus);

                        if (readBytes != length)
                        {
                            mLogger.Error($"{pack.FileName} Hnd: {handle} {entry.Native->Path} File read length doesnt match requested read length!! Expected 0x{length:X8}, Actual 0x{readBytes:X8}");
                        }

                        mLogger.Debug($"{pack.FileName} Hnd: {handle} {entry.Native->Path} Wrote redirected file to buffer");
                    }
                    catch (Exception e)
                    {
                        mLogger.Debug($"{pack.FileName} Hnd: {handle} Index: {i} {entry.Native->Path} Unhandled exception thrown during reading {entry.RedirectedFilePath}: {e}");
                    }
                }

                // Return early, we're done here
                return(result);
            }

            mLogger.Error($"{pack.FileName} Hnd: {handle} Unhandled file data read request!! Offset: 0x{effOffset:X8} Length: 0x{length:X8}");
            return(mHooks.NtReadFileHook.OriginalFunction(handle, hEvent, apcRoutine, apcContext, ref ioStatus, buffer, length, byteOffset, key));
        }
        private void ReconnectResilientHandle(
            Smb2FunctionalClient client,
            Guid clientGuid,
            string fileName,
            FILEID fileId,
            NtStatus expectedReconnectStatus,
            string message)
        {
            uint treeId;
            ConnectToShare(
                client,
                clientGuid,
                out treeId);
            BaseTestSite.Log.Add(
                LogEntryKind.Debug,
                "Reconnect to resilient handle");

            Smb2CreateContextResponse[] createContextResponse;
            uint status = client.Create(
                treeId,
                fileName,
                CreateOptions_Values.NONE,
                out fileId,
                out createContextResponse,
                createContexts: new Smb2CreateContextRequest[]
                    {
                        new Smb2CreateDurableHandleReconnect()
                        {
                            Data = fileId
                        }
                    },
                checker: (header, response) =>
                {
                    // do nothing, skip the exception
                }
                );
            BaseTestSite.Assert.AreEqual<NtStatus>(
                expectedReconnectStatus,
                (NtStatus)status,
                message);
        }
        public void Smb2OverRdma_Read_SMB2_CHANNEL_RDMA_V1()
        {
            EstablishConnectionAndOpenFile(fileName);

            uint fileSize = smbdAdapter.Smb2MaxReadSize;

            byte[] fileContent = Smb2Utility.CreateRandomByteArray((int)fileSize);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Register memory and get buffer descriptor for SMB2 WRITE");
            SmbdBufferDescriptorV1 descp;
            NtStatus status = smbdAdapter.SmbdRegisterBuffer(
                fileSize,
                SmbdBufferReadWrite.RDMA_READ_PERMISSION_FOR_WRITE_FILE,
                out descp);

            BaseTestSite.Assert.AreEqual(
                NtStatus.STATUS_SUCCESS,
                status,
                "Register buffer should succeed.");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Write content to file over RDMA.");
            status = Smb2WriteOverRdma(fileName, fileContent, Channel_Values.CHANNEL_RDMA_V1_INVALIDATE, descp);
            BaseTestSite.Assert.AreEqual <NtStatus>(
                NtStatus.STATUS_SUCCESS,
                status,
                "SMB2 WRITE over RDMA should succeed.");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Register memory and get buffer descriptor for SMB2 READ.");
            status = smbdAdapter.SmbdRegisterBuffer(
                fileSize,
                SmbdBufferReadWrite.RDMA_WRITE_PERMISSION_FOR_READ_FILE,
                out descp);
            BaseTestSite.Assert.AreEqual(
                NtStatus.STATUS_SUCCESS,
                status,
                "Register buffer should succeed.");

            byte[] channelInfo = TypeMarshal.ToBytes <SmbdBufferDescriptorV1>(descp);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Read content from file over RDMA.");
            READ_Response readResponse;

            byte[] readData;
            status = (NtStatus)smbdAdapter.Smb2ReadOverRdmaChannel(
                0,
                (uint)fileSize,
                channelInfo,
                out readResponse,
                out readData,
                Channel_Values.CHANNEL_RDMA_V1);

            BaseTestSite.Assert.AreEqual <NtStatus>(
                NtStatus.STATUS_SUCCESS,
                status,
                "SMB2 READ over RDMA should succeed.");

            byte[] readContent = new byte[fileSize];
            smbdAdapter.SmbdReadRegisteredBuffer(readContent, descp);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify the read content same as the original one on server.");
            BaseTestSite.Assert.IsTrue(
                SmbdUtilities.CompareByteArray(fileContent, readContent),
                "Content read should be identical with original on server.");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Send SMB2 READ using same descriptor.");
            status = (NtStatus)smbdAdapter.Smb2ReadOverRdmaChannel(
                0,
                (uint)fileSize,
                channelInfo,
                out readResponse,
                out readData,
                Channel_Values.CHANNEL_RDMA_V1);

            BaseTestSite.Assert.AreEqual <NtStatus>(
                NtStatus.STATUS_SUCCESS,
                status,
                "SMB2 READ over RDMA should succeed.");

            smbdAdapter.SmbdReadRegisteredBuffer(readContent, descp);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify the read content same as the original one on server.");
            BaseTestSite.Assert.IsTrue(
                SmbdUtilities.CompareByteArray(fileContent, readContent),
                "Content read should be identical with original on server.");
        }
 /// <summary>
 /// Terminate the process
 /// </summary>
 /// <param name="exitcode">Exit code for termination</param>
 public void Terminate(NtStatus exitcode)
 {
     if (Process != null)
         Process.Terminate(exitcode);
 }
        public void BVT_Smb2OverRdma_Smb302_Read_SMB2_CHANNEL_RDMA_V1_INVALIDATE()
        {
            EstablishConnectionAndOpenFile(fileName, Smb302AboveDialects);

            uint fileSize = smbdAdapter.Smb2MaxReadSize;

            byte[] fileContent = Smb2Utility.CreateRandomByteArray((int)fileSize);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Register memory and get buffer descriptor for SMB2 WRITE");
            SmbdBufferDescriptorV1 descp;
            NtStatus status = smbdAdapter.SmbdRegisterBuffer(
                fileSize,
                SmbdBufferReadWrite.RDMA_READ_PERMISSION_FOR_WRITE_FILE,
                out descp);

            BaseTestSite.Assert.AreEqual(
                NtStatus.STATUS_SUCCESS,
                status,
                "Register buffer should succeed.");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Write content to file over RDMA.");
            status = Smb2WriteOverRdma(fileName, fileContent, Channel_Values.CHANNEL_RDMA_V1_INVALIDATE, descp);
            BaseTestSite.Assert.AreEqual <NtStatus>(
                NtStatus.STATUS_SUCCESS,
                status,
                "SMB2 WRITE over RDMA should succeed.");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Register memory and get buffer descriptor for SMB2 READ.");
            status = smbdAdapter.SmbdRegisterBuffer(
                fileSize,
                SmbdBufferReadWrite.RDMA_WRITE_PERMISSION_FOR_READ_FILE,
                out descp);
            BaseTestSite.Assert.AreEqual(
                NtStatus.STATUS_SUCCESS,
                status,
                "Register buffer should succeed.");
            byte[] channelInfo = TypeMarshal.ToBytes <SmbdBufferDescriptorV1>(descp);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Read content from file over RDMA.");
            READ_Response readResponse;

            byte[] readData;
            status = (NtStatus)smbdAdapter.Smb2ReadOverRdmaChannel(
                0,
                (uint)fileSize,
                channelInfo,
                out readResponse,
                out readData,
                Channel_Values.CHANNEL_RDMA_V1_INVALIDATE);

            BaseTestSite.Assert.AreEqual <NtStatus>(
                NtStatus.STATUS_SUCCESS,
                status,
                "SMB2 READ over RDMA should succeed.");

            byte[] readContent = new byte[fileSize];
            smbdAdapter.SmbdReadRegisteredBuffer(readContent, descp);

            BaseTestSite.Assert.IsTrue(
                SmbdUtilities.CompareByteArray(fileContent, readContent),
                "Content read should be identical with original on server.");

            try
            {
                status = (NtStatus)smbdAdapter.Smb2ReadOverRdmaChannel(
                    0,
                    (uint)fileSize,
                    channelInfo,
                    out readResponse,
                    out readData,
                    Channel_Values.CHANNEL_RDMA_V1_INVALIDATE);
            }
            catch
            {
                BaseTestSite.Log.Add(LogEntryKind.Debug, "Wait for connection to be terminated ");
                smbdAdapter.WaitRdmaDisconnect();
            }

            BaseTestSite.Assert.IsFalse(smbdAdapter.ClientConnection.Endpoint.IsConnected, "Connection should be terminated when accessing a memory window which is already invalidated.");
        }
 public static extern int RtlNtStatusToDosError(NtStatus status);        
示例#56
0
 /// <summary>
 /// Creates an exception from a NT status value.
 /// </summary>
 /// <param name="status">The NT status value.</param>
 public WindowsException(NtStatus status)
 {
     _status = status;
     _errorCode = status.ToDosError();
     _isNtStatus = true;
 }