Beispiel #1
0
        public static SafeRpcBindingHandle Create(string string_binding)
        {
            int status = Win32NativeMethods.RpcBindingFromStringBinding(string_binding, out SafeRpcBindingHandle binding);

            if (status != 0)
            {
                throw new SafeWin32Exception(status);
            }
            binding._cracked_binding = new CrackedBindingString(string_binding);
            return(binding);
        }
Beispiel #2
0
 private static ServiceLaunchProtectedType GetServiceLaunchProtectedType(SafeServiceHandle service)
 {
     using (var buf = new SafeStructureInOutBuffer <SERVICE_LAUNCH_PROTECTED_INFO>()) {
         if (!Win32NativeMethods.QueryServiceConfig2(service, SERVICE_CONFIG_LAUNCH_PROTECTED,
                                                     buf, buf.Length, out int needed))
         {
             return(ServiceLaunchProtectedType.None);
         }
         return(buf.Result.dwLaunchProtected);
     }
 }
Beispiel #3
0
 private static SERVICE_STATUS_PROCESS QueryStatus(SafeServiceHandle service)
 {
     using (var buffer = new SafeStructureInOutBuffer <SERVICE_STATUS_PROCESS>()) {
         if (!Win32NativeMethods.QueryServiceStatusEx(service, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO,
                                                      buffer, buffer.Length, out int length))
         {
             throw new SafeWin32Exception();
         }
         return(buffer.Result);
     }
 }
        protected override bool ReleaseHandle()
        {
            _values?.Dispose();
            if (!IsInvalid)
            {
                bool ret = Win32NativeMethods.DeleteProcThreadAttributeList(handle);
                return(base.ReleaseHandle() && ret);
            }

            return(false);
        }
Beispiel #5
0
        private static int GetServiceProcessId(SafeServiceHandle scm, string name)
        {
            using (SafeServiceHandle service = Win32NativeMethods.OpenService(scm, name, ServiceAccessRights.QueryStatus)) {
                if (service.IsInvalid)
                {
                    throw new SafeWin32Exception();
                }

                return(QueryStatus(service).dwProcessId);
            }
        }
Beispiel #6
0
 private static ServiceSidType GetServiceSidType(SafeServiceHandle service)
 {
     using (var buf = new SafeStructureInOutBuffer <SERVICE_SID_INFO>()) {
         if (!Win32NativeMethods.QueryServiceConfig2(service, SERVICE_CONFIG_SERVICE_SID_INFO,
                                                     buf, buf.Length, out int needed))
         {
             return(ServiceSidType.None);
         }
         return(buf.Result.dwServiceSidType);
     }
 }
        private static SecurityDescriptor GetServiceSecurityDescriptor(SafeServiceHandle handle,
                                                                       string type_name, SecurityInformation security_information)
        {
            byte[] sd = new byte[8192];
            if (!Win32NativeMethods.QueryServiceObjectSecurity(handle, security_information, sd, sd.Length, out _))
            {
                throw new SafeWin32Exception();
            }

            return(new SecurityDescriptor(sd, GetServiceNtType(type_name)));
        }
Beispiel #8
0
        private static IEnumerable <string> GetServiceRequiredPrivileges(SafeServiceHandle service)
        {
            using (var buf = new SafeHGlobalBuffer(8192)) {
                if (!Win32NativeMethods.QueryServiceConfig2(service, SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO,
                                                            buf, buf.Length, out int needed))
                {
                    return(new string[0]);
                }

                return(buf.Read <IntPtr>(0).GetMultiString());
            }
        }
Beispiel #9
0
        /// <summary>
        /// Get the information about a service.
        /// </summary>
        /// <param name="name">The name of the service.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The service information.</returns>
        public static NtResult <ServiceInformation> GetServiceInformation(string name, bool throw_on_error)
        {
            using (SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(null, null,
                                                                            ServiceControlManagerAccessRights.Connect)) {
                if (scm.IsInvalid)
                {
                    return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <ServiceInformation>(throw_on_error));
                }

                return(GetServiceSecurityInformation(scm, name, DEFAULT_SECURITY_INFORMATION, throw_on_error));
            }
        }
Beispiel #10
0
        private static ServiceInformation GetServiceSecurityInformation(SafeServiceHandle scm, string name)
        {
            using (SafeServiceHandle service = Win32NativeMethods.OpenService(scm, name, ServiceAccessRights.QueryConfig | ServiceAccessRights.ReadControl))
            {
                if (service.IsInvalid)
                {
                    throw new SafeWin32Exception();
                }

                return(new ServiceInformation(name, GetServiceSecurityDescriptor(service), GetTriggersForService(service)));
            }
        }
Beispiel #11
0
 private IntPtr RvaToVA(long rva)
 {
     if (MappedAsImage)
     {
         return(new IntPtr(GetBasePointer().ToInt64() + rva));
     }
     else
     {
         return(Win32NativeMethods.ImageRvaToVa(GetHeaderPointer(GetBasePointer()),
                                                GetBasePointer(), (int)rva, IntPtr.Zero));
     }
 }
Beispiel #12
0
        /// <summary>
        /// Get the PID of a running service.
        /// </summary>
        /// <param name="name">The name of the service.</param>
        /// <returns>Returns the PID of the running service, or 0 if not running.</returns>
        /// <exception cref="SafeWin32Exception">Thrown on error.</exception>
        public static int GetServiceProcessId(string name)
        {
            using (SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(null, null,
                                                                            ServiceControlManagerAccessRights.Connect)) {
                if (scm.IsInvalid)
                {
                    throw new SafeWin32Exception();
                }

                return(GetServiceProcessId(scm, name));
            }
        }
Beispiel #13
0
 /// <summary>
 /// Format a message.
 /// </summary>
 /// <param name="module">The module containing the message.</param>
 /// <param name="message_id">The ID of the message.</param>
 /// <returns>The message. Empty string on error.</returns>
 public static string FormatMessage(SafeLoadLibraryHandle module, uint message_id)
 {
     if (Win32NativeMethods.FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule
                                          | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
                                          module.DangerousGetHandle(), message_id, 0, out SafeLocalAllocBuffer buffer, 0, IntPtr.Zero) > 0)
     {
         using (buffer) {
             return(Marshal.PtrToStringUni(buffer.DangerousGetHandle()).Trim());
         }
     }
     return(string.Empty);
 }
Beispiel #14
0
 /// <summary>
 /// Open the AppContainer key.
 /// </summary>
 /// <param name="desired_access">The desired access for the key.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The opened key.</returns>
 public NtResult <NtKey> OpenKey(KeyAccessRights desired_access, bool throw_on_error)
 {
     using (var result = TokenUtils.CreateAppContainerToken(null, Sid, new Sid[0], throw_on_error)) {
         if (!result.IsSuccess)
         {
             return(result.Cast <NtKey>());
         }
         using (var imp = result.Result.Impersonate(SecurityImpersonationLevel.Impersonation)) {
             return(Win32NativeMethods.GetAppContainerRegistryLocation(desired_access, out SafeKernelObjectHandle key)
                    .CreateResult(throw_on_error, () => new NtKey(key, KeyDisposition.OpenedExistingKey, false)));
         }
     }
 }
Beispiel #15
0
 public override string ToString()
 {
     if (!IsInvalid && !IsClosed)
     {
         if (Win32NativeMethods.RpcBindingToStringBinding(handle, out SafeRpcStringHandle str) == 0)
         {
             using (str) {
                 return(str.ToString());
             }
         }
     }
     return(string.Empty);
 }
Beispiel #16
0
        public static SafeRpcBindingHandle Create(string objuuid, string protseq, string networkaddr, string endpoint, string options)
        {
            int status = Win32NativeMethods.RpcStringBindingCompose(objuuid, protseq,
                                                                    networkaddr, endpoint, options, out SafeRpcStringHandle binding);

            if (status != 0)
            {
                throw new SafeWin32Exception(status);
            }
            using (binding) {
                return(Create(binding.ToString()));
            }
        }
Beispiel #17
0
        /// <summary>
        /// Create process with a token from a user logon.
        /// </summary>
        /// <param name="credentials">The user's credentials.</param>
        /// <param name="logon_flags">Logon flags.</param>
        /// <param name="config">The process configuration.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The created win32 process.</returns>
        public static NtResult <Win32Process> CreateProcessWithLogon(UserCredentials credentials,
                                                                     CreateProcessLogonFlags logon_flags, Win32ProcessConfig config, bool throw_on_error)
        {
            STARTUPINFO         start_info = config.ToStartupInfo();
            PROCESS_INFORMATION proc_info  = new PROCESS_INFORMATION();

            using (var password = credentials.GetPassword()) {
                return(Win32NativeMethods.CreateProcessWithLogonW(credentials.UserName, credentials.Domain,
                                                                  password, logon_flags, config.ApplicationName, config.CommandLine, config.CreationFlags,
                                                                  config.Environment, config.CurrentDirectory, ref start_info,
                                                                  out proc_info).CreateWin32Result(throw_on_error, () => new Win32Process(proc_info, config.TerminateOnDispose)));
            }
        }
Beispiel #18
0
        /// <summary>
        /// Get the security descriptor of the SCM.
        /// </summary>
        /// <param name="security_information">Parts of the security descriptor to return.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The SCM security descriptor.</returns>
        public static NtResult <SecurityDescriptor> GetScmSecurityDescriptor(SecurityInformation security_information, bool throw_on_error)
        {
            var desired_access = NtSecurity.QuerySecurityAccessMask(security_information).ToSpecificAccess <ServiceControlManagerAccessRights>();

            using (SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(null, null,
                                                                            ServiceControlManagerAccessRights.Connect | desired_access)) {
                if (scm.IsInvalid)
                {
                    return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <SecurityDescriptor>(throw_on_error));
                }
                return(GetServiceSecurityDescriptor(scm, "scm", security_information, throw_on_error));
            }
        }
Beispiel #19
0
        /// <summary>
        /// Get the information about a service.
        /// </summary>
        /// <param name="name">The name of the service.</param>
        /// <returns>The servicec information.</returns>
        public static ServiceInformation GetServiceInformation(string name)
        {
            using (SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(null, null,
                                                                            ServiceControlManagerAccessRights.Connect | ServiceControlManagerAccessRights.ReadControl))
            {
                if (scm.IsInvalid)
                {
                    throw new SafeWin32Exception();
                }

                return(GetServiceSecurityInformation(scm, name));
            }
        }
 public static NtResult <NtToken> CreateAppContainerToken(NtToken token, Sid appcontainer_sid,
                                                          IEnumerable <Sid> capabilities, bool throw_on_error)
 {
     using (var resources = new DisposableList())
     {
         SECURITY_CAPABILITIES caps = Win32Utils.CreateSecuityCapabilities(appcontainer_sid, capabilities ?? new Sid[0], resources);
         if (!Win32NativeMethods.CreateAppContainerToken(token.GetHandle(), ref caps, out SafeKernelObjectHandle new_token))
         {
             return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <NtToken>(throw_on_error));
         }
         return(NtToken.FromHandle(new_token).CreateResult());
     }
 }
Beispiel #21
0
        private static SecurityDescriptor GetServiceSecurityDescriptor(SafeServiceHandle handle, string type_name)
        {
            byte[] sd = new byte[8192];
            if (!Win32NativeMethods.QueryServiceObjectSecurity(handle, SecurityInformation.Dacl
                                                               | SecurityInformation.Owner
                                                               | SecurityInformation.Label
                                                               | SecurityInformation.Group, sd, sd.Length, out int required))
            {
                throw new SafeWin32Exception();
            }

            return(new SecurityDescriptor(sd, GetServiceNtType(type_name)));
        }
        internal ExecutableManifest(SafeLoadLibraryHandle hModule, string fullpath, IntPtr hName)
        {
            FullPath = fullpath;

            IntPtr hResHandle = Win32NativeMethods.FindResource(hModule, hName, new IntPtr((int)ResType.MANIFEST));

            if (hResHandle == IntPtr.Zero)
            {
                throw new ArgumentException("Can't find manifest resource");
            }

            IntPtr hResource = Win32NativeMethods.LoadResource(hModule, hResHandle);
            IntPtr buf       = Win32NativeMethods.LockResource(hResource);
            int    size      = Win32NativeMethods.SizeofResource(hModule, hResHandle);

            if (size <= 0)
            {
                throw new ArgumentException("Invalid manifest size");
            }
            byte[] manifest = new byte[size];

            Marshal.Copy(buf, manifest, 0, size);
            MemoryStream stm = new MemoryStream(manifest);

            try
            {
                XmlDocument doc = LoadDocument(stm);

                UiAccess       = GetUiAccess(doc);
                AutoElevate    = GetAutoElevate(doc);
                ExecutionLevel = GetExecutionLevel(doc);
                LongPathAware  = GetLongPathAware(doc);

                XmlWriterSettings settings = new XmlWriterSettings
                {
                    Indent              = true,
                    OmitXmlDeclaration  = true,
                    NewLineOnAttributes = true
                };
                StringWriter string_writer = new StringWriter();
                XmlWriter    writer        = XmlWriter.Create(string_writer, settings);
                doc.Save(writer);
                ManifestXml = string_writer.ToString();
            }
            catch (XmlException)
            {
                ParseError  = true;
                ManifestXml = Encoding.UTF8.GetString(stm.ToArray());
            }
        }
Beispiel #23
0
        /// <summary>
        /// Load a library into memory.
        /// </summary>
        /// <param name="name">The path to the library.</param>
        /// <param name="flags">Additonal flags to pass to LoadLibraryEx</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>Handle to the loaded library.</returns>
        public static NtResult <SafeLoadLibraryHandle> LoadLibrary(string name, LoadLibraryFlags flags, bool throw_on_error)
        {
            SafeLoadLibraryHandle ret = Win32NativeMethods.LoadLibraryEx(name, IntPtr.Zero, flags);

            if (ret.IsInvalid)
            {
                if (throw_on_error)
                {
                    throw new SafeWin32Exception();
                }
                return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <SafeLoadLibraryHandle>(false));
            }
            return(ret.CreateResult());
        }
Beispiel #24
0
        /// <summary>
        /// Derive a package sid from a name.
        /// </summary>
        /// <param name="name">The name of the package.</param>
        /// <returns>The derived Sid</returns>
        public static Sid DerivePackageSidFromName(string name)
        {
            int hr = Win32NativeMethods.DeriveAppContainerSidFromAppContainerName(name, out SafeSidBufferHandle sid);

            if (hr != 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            using (sid)
            {
                return(new Sid(sid));
            }
        }
Beispiel #25
0
        /// <summary>
        /// Derive a package sid from a name.
        /// </summary>
        /// <param name="name">The name of the package.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The derived Sid</returns>
        public static NtResult <Sid> DerivePackageSidFromName(string name, bool throw_on_error)
        {
            int hr = Win32NativeMethods.DeriveAppContainerSidFromAppContainerName(name, out SafeSidBufferHandle sid);

            if (hr == 0)
            {
                using (sid)
                {
                    return(new Sid(sid).CreateResult());
                }
            }

            return(((NtStatus)hr).CreateResultFromError <Sid>(throw_on_error));
        }
Beispiel #26
0
        /// <summary>
        /// Create a new service.
        /// </summary>
        /// <param name="name">The name of the service.</param>
        /// <param name="display_name">The display name for the service.</param>
        /// <param name="service_type">The service type.</param>
        /// <param name="start_type">The service start type.</param>
        /// <param name="error_control">Error control.</param>
        /// <param name="binary_path_name">Path to the service executable.</param>
        /// <param name="load_order_group">Load group order.</param>
        /// <param name="dependencies">List of service dependencies.</param>
        /// <param name="service_start_name">The username for the service.</param>
        /// <param name="password">Password for the username if needed.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The registered service information.</returns>
        public static NtResult <RunningService> CreateService(
            string name,
            string display_name,
            ServiceType service_type,
            ServiceStartType start_type,
            ServiceErrorControl error_control,
            string binary_path_name,
            string load_order_group,
            IEnumerable <string> dependencies,
            string service_start_name,
            SecureString password,
            bool throw_on_error)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException($"'{nameof(name)}' cannot be null or empty", nameof(name));
            }

            if (string.IsNullOrEmpty(binary_path_name))
            {
                throw new ArgumentException($"'{nameof(binary_path_name)}' cannot be null or empty", nameof(binary_path_name));
            }

            using (var scm = Win32NativeMethods.OpenSCManager(null, null,
                                                              ServiceControlManagerAccessRights.Connect | ServiceControlManagerAccessRights.CreateService)) {
                if (scm.IsInvalid)
                {
                    return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <RunningService>(throw_on_error));
                }

                IntPtr pwd = password != null?Marshal.SecureStringToBSTR(password) : IntPtr.Zero;

                try {
                    using (var service = Win32NativeMethods.CreateService(scm, name, display_name, ServiceAccessRights.MaximumAllowed,
                                                                          service_type, start_type, error_control, binary_path_name, load_order_group, null, dependencies.ToMultiString(),
                                                                          string.IsNullOrEmpty(service_start_name) ? null : service_start_name, pwd)) {
                        if (service.IsInvalid)
                        {
                            return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <RunningService>(throw_on_error));
                        }
                        return(new RunningService(name, display_name ?? string.Empty, QueryStatus(service)).CreateResult());
                    }
                } finally {
                    if (pwd != IntPtr.Zero)
                    {
                        Marshal.FreeBSTR(pwd);
                    }
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Set the SCM security descriptor.
        /// </summary>
        /// <param name="security_descriptor">The security descriptor to set.</param>
        /// <param name="security_information">The parts of the security descriptor to set.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The NT status code.</returns>
        public static NtStatus SetScmSecurityDescriptor(SecurityDescriptor security_descriptor,
                                                        SecurityInformation security_information, bool throw_on_error)
        {
            var desired_access = NtSecurity.SetSecurityAccessMask(security_information).ToSpecificAccess <ServiceControlManagerAccessRights>();

            using (SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(null, null,
                                                                            ServiceControlManagerAccessRights.Connect | desired_access)) {
                if (scm.IsInvalid)
                {
                    return(Win32Utils.GetLastWin32Error().ToNtException(throw_on_error));
                }
                return(SetServiceSecurityDescriptor(scm, security_information, security_descriptor, throw_on_error));
            }
        }
        /// <summary>
        /// Create process with a token from a user logon.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="domain">The user's domain.</param>
        /// <param name="password">The user's password.</param>
        /// <param name="logon_flags">Logon flags.</param>
        /// <param name="config">The process configuration.</param>
        /// <returns>The created win32 process.</returns>
        public static Win32Process CreateProcessWithLogin(string username, string domain, string password,
                                                          CreateProcessLogonFlags logon_flags, Win32ProcessConfig config)
        {
            STARTUPINFO         start_info = config.ToStartupInfo();
            PROCESS_INFORMATION proc_info  = new PROCESS_INFORMATION();

            if (!Win32NativeMethods.CreateProcessWithLogonW(username, domain, password, logon_flags,
                                                            config.ApplicationName, config.CommandLine, config.CreationFlags,
                                                            config.Environment, config.CurrentDirectory, ref start_info, out proc_info))
            {
                throw new SafeWin32Exception();
            }

            return(new Win32Process(proc_info, config.TerminateOnDispose));
        }
Beispiel #29
0
        /// <summary>
        /// Derive a package sid from a name.
        /// </summary>
        /// <param name="name">The name of the package.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The derived Sid</returns>
        public static NtResult <Sid> DerivePackageSidFromName(string name, bool throw_on_error)
        {
            int hr = Win32NativeMethods.DeriveAppContainerSidFromAppContainerName(name, out SafeSidBufferHandle sid);

            if (hr == 0)
            {
                using (sid) {
                    Sid result = new Sid(sid);
                    return(NtSecurity.CacheSidName(result, string.Empty, name,
                                                   SidNameSource.Package, SidNameUse.User).CreateResult());
                }
            }

            return(((NtStatus)hr).CreateResultFromError <Sid>(throw_on_error));
        }
Beispiel #30
0
        /// <summary>
        /// Get the default RPC server security descriptor.
        /// </summary>
        /// <returns>The default security descriptor.</returns>
        public static SecurityDescriptor GetDefaultSecurityDescriptor()
        {
            Win32Error result = Win32NativeMethods.I_RpcGetDefaultSD(out IntPtr sd);

            if (result != Win32Error.SUCCESS)
            {
                result.ToNtException();
            }

            try {
                return(new SecurityDescriptor(sd));
            } finally {
                Win32NativeMethods.I_RpcFree(sd);
            }
        }