Esempio n. 1
0
        public static IEnumerable <INHERITED_FROM> GetInheritanceSource(string objectName, ResourceType objectType,
                                                                        SECURITY_INFORMATION securityInfo, bool container, IntPtr pAcl, ref GENERIC_MAPPING pGenericMapping)
        {
            var objSize  = Marshal.SizeOf(typeof(INHERITED_FROM));
            var aceCount = GetAceCount(pAcl);

            using (var pInherit = new SafeCoTaskMemHandle(objSize * (int)aceCount))
            {
                var hr = 0;
                try
                {
                    hr = AdvApi32.GetInheritanceSource(objectName, objectType, securityInfo, container, null, 0, pAcl, IntPtr.Zero, ref pGenericMapping, (IntPtr)pInherit);
                    if (hr != 0)
                    {
                        throw new System.ComponentModel.Win32Exception(hr);
                    }
                    return(pInherit.ToIEnum <INHERITED_FROM>((int)aceCount));
                }
                finally
                {
                    if (hr != 0)
                    {
                        FreeInheritedFromArray((IntPtr)pInherit, (ushort)aceCount, IntPtr.Zero);
                    }
                }
            }
        }
Esempio n. 2
0
        public bool Delete()
        {
            IntPtr manager = AdvApi32.OpenSCManager(null, null, AdvApi32.SC_MANAGER_ACCESS_MASK.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                return(false);
            }


            IntPtr service = AdvApi32.OpenService(manager, _id, AdvApi32.SERVICE_ACCESS_MASK.SERVICE_ALL_ACCESS);

            if (service == IntPtr.Zero)
            {
                return(true);
            }


            AdvApi32.SERVICE_STATUS status = new AdvApi32.SERVICE_STATUS();
            AdvApi32.ControlService(service, AdvApi32.SERVICE_CONTROL.SERVICE_CONTROL_STOP, ref status);
            AdvApi32.DeleteService(service);
            AdvApi32.CloseServiceHandle(service);
            AdvApi32.CloseServiceHandle(manager);

            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// Enables or disables the privilege with given key for this process
        /// </summary>
        /// <param name="key">The privilege key</param>
        /// <param name="enable">Whether to enable or disable the privilege</param>
        public void SetPrivilege(String key, Boolean enable)
        {
            AdvApi32.Luid luid = new AdvApi32.Luid();
            if (!AdvApi32.LookupPrivilegeValue(null, key, ref luid))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not perform lookup of privilege value");
            }

            IntPtr handle = IntPtr.Zero;

            if (!AdvApi32.OpenProcessToken(Handle.DangerousGetHandle(), TokenAccessLevels.AdjustPrivileges, ref handle))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open process token");
            }

            using (SafeAccessTokenHandle tokenHandle = new SafeAccessTokenHandle(handle))
            {
                AdvApi32.TokenPrivileges privileges = new AdvApi32.TokenPrivileges();
                privileges.PrivilegeCount = 1;
                privileges.Luid           = luid;
                privileges.State          = enable ? PrivilegeState.Enabled : PrivilegeState.Removed;

                if (!AdvApi32.AdjustTokenPrivileges(tokenHandle.DangerousGetHandle(), false, ref privileges, 0,
                                                    IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not adjust token privileges");
                }
            }
        }
Esempio n. 4
0
 public void OpenCloseSCManager()
 {
     using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
     {
         AssertHandleIsValid(scm);
     }
 }
Esempio n. 5
0
            public static IEnumerable <EVENT_TRACE_PROPERTIES> QueryAllTraces()
            {
                const int len      = 64;
                var       props    = new List <SafeHGlobalHandle>(len);
                var       loadProp = EVENT_TRACE_PROPERTIES.Create();

                for (var i = 0; i < len; i++)
                {
                    props.Add(SafeHGlobalHandle.CreateFromStructure(loadProp));
                }
                try
                {
                    var pprops = props.Select(p => (IntPtr)p).ToArray();
                    AdvApi32.QueryAllTraces(pprops, len, out var count).ThrowIfFailed();
                    for (var i = 0; i < count; i++)
                    {
                        yield return(props[i].ToStructure <EVENT_TRACE_PROPERTIES>());
                    }
                }
                finally
                {
                    for (var i = 0; i < props.Count; i++)
                    {
                        props[i].Dispose();
                    }
                }
            }
Esempio n. 6
0
        /// <summary>
        /// Logs in, getting a windows identity representing the account you want
        /// to impersonate if successful.
        /// </summary>
        /// <param name="userName">The user to login as.</param>
        /// <param name="domainName">The domain of the user.</param>
        /// <param name="password">The user's password.</param>
        /// <returns>True, if login was successful.</returns>
        public bool Login(string userName, string domainName, string password)
        {
            if (CurrentIdentity != null)
            {
                CurrentIdentity.Dispose();
                CurrentIdentity = null;
            }

            try
            {
                Logout();

                bool loggedOn = AdvApi32.LogonUser(userName, domainName, password, LogonType, LogonProvider, ref _accessToken);

                if (loggedOn)
                {
                    CurrentIdentity = new WindowsIdentity(_accessToken);
                    return(true);
                }

                Logout();

                return(false);
            }
            catch
            {
                // could handle exceptions more gracefully.
                throw;
            }
        }
Esempio n. 7
0
        internal override unsafe NCryptKeyOrCryptProviderSafeHandle OpenExisting(string keyName, out KeySpec keySpec)
        {
            keySpec = KeySpec.NONE;
            const int DOES_NOT_EXIST = unchecked ((int)0x80090016);
            NCryptKeyOrCryptProviderSafeHandle provider;

            if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, 0u))
            {
                var result = Marshal.GetLastWin32Error();
                if (result == DOES_NOT_EXIST)
                {
                    return(null);
                }
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            const uint PP_KEYSPEC    = 0x27;
            uint *     keySpecBuffer = stackalloc uint[1];
            var        dataLength    = (uint)Marshal.SizeOf(typeof(uint));

            if (!AdvApi32.CryptGetProvParam(provider, PP_KEYSPEC, keySpecBuffer, ref dataLength, 0u))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            keySpec = (KeySpec)(*keySpecBuffer);
            return(provider);
        }
Esempio n. 8
0
 public static ACCESS_ALLOWED_ACE GetAce(IntPtr pAcl, int aceIndex)
 {
     if (AdvApi32.GetAce(pAcl, aceIndex, out IntPtr acePtr))
     {
         return((ACCESS_ALLOWED_ACE)Marshal.PtrToStructure(acePtr, typeof(ACCESS_ALLOWED_ACE)));
     }
     throw new System.ComponentModel.Win32Exception();
 }
        /// <summary>
        ///   Checks whether the primary access token of the process belongs to a user account that is a member of the local Administrator group, even if it currently is not elevated.
        /// </summary>
        /// <returns>
        ///   True if the primary access token of the process belongs to a user account that is a member of the Administrators group; false otherwise.
        /// </returns>
        public static bool IsUserInAdminGroup()
        {
            // Default token's received aren't impersonation tokens, we are looking for an impersonation token.
            bool isImpersonationToken = false;

            // Open the access token of the current process.
            SafeTokenHandle processToken;

            if (!AdvApi32.OpenProcessToken(Process.GetCurrentProcess().Handle, (uint)(TokenAccessLevels.Query | TokenAccessLevels.Duplicate), out processToken))
            {
                MarshalHelper.ThrowLastWin32ErrorException();
            }

            // Starting from Vista linked tokens are supported which need to be checked.
            if (EnvironmentHelper.VistaOrHigher)
            {
                // Determine token type: limited, elevated, or default.
                int marshalSize         = sizeof(AdvApi32.TokenElevationType);
                var elevationTypeHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory(marshalSize);
                if (!AdvApi32.GetTokenInformation(processToken, AdvApi32.TokenInformationClass.TokenElevationType, elevationTypeHandle.DangerousGetHandle(), marshalSize, out marshalSize))
                {
                    MarshalHelper.ThrowLastWin32ErrorException();
                }
                var tokenType = (AdvApi32.TokenElevationType)Marshal.ReadInt32(elevationTypeHandle.DangerousGetHandle());

                // If limited, get the linked elevated token for further check.
                if (tokenType == AdvApi32.TokenElevationType.TokenElevationTypeLimited)
                {
                    // Get the linked token.
                    marshalSize = IntPtr.Size;
                    var linkedTokenHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory(marshalSize);
                    if (!AdvApi32.GetTokenInformation(processToken, AdvApi32.TokenInformationClass.TokenLinkedToken, linkedTokenHandle.DangerousGetHandle(), marshalSize, out marshalSize))
                    {
                        MarshalHelper.ThrowLastWin32ErrorException();
                    }
                    processToken         = new SafeTokenHandle(Marshal.ReadIntPtr(linkedTokenHandle.DangerousGetHandle()));
                    isImpersonationToken = true;                     // Linked tokens are already impersonation tokens.
                }
            }

            // We need an impersonation token in order to check whether it contains admin SID.
            if (!isImpersonationToken)
            {
                SafeTokenHandle impersonatedToken;
                if (!AdvApi32.DuplicateToken(processToken, AdvApi32.SecurityImpersonationLevel.SecurityIdentification, out impersonatedToken))
                {
                    MarshalHelper.ThrowLastWin32ErrorException();
                }
                processToken = impersonatedToken;
            }

            // Check if the token to be checked contains admin SID.
            var identity  = new WindowsIdentity(processToken.DangerousGetHandle());
            var principal = new WindowsPrincipal(identity);

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Esempio n. 10
0
        internal override NCryptKeyOrCryptProviderSafeHandle CreateKey(string keyName, int keySize, Algorithm algorithm, bool overwrite, KeyUsage keyUsage, out KeySpec keySpec)
        {
            const int ALREADY_EXISTS = unchecked ((int)0x8009000f);

            if (algorithm != Algorithm.RSA)
            {
                throw new ArgumentException("CAPI does not support algorithms other than RSA.", nameof(algorithm));
            }
            NCryptKeyOrCryptProviderSafeHandle provider;

            if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_NEWKEYSET))
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == ALREADY_EXISTS && overwrite)
                {
                    if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_DELETEKEYSET))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                    if (!AdvApi32.CryptAcquireContext(out provider, keyName, _providerName, ProviderType.PROV_RSA_AES, CryptAcquireContextFlags.CRYPT_NEWKEYSET))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            var flags        = CryptGenKeyFlags.CRYPT_EXPORTABLE;
            var keySizeFlags = ((uint)keySize & 0xFFFFU) << 16;
            var genKeyFlags  = ((ushort)flags) | keySizeFlags;
            CryptKeySafeHandle key;
            KeySpec            algorithmKeySpec;

            switch (keyUsage)
            {
            case KeyUsage.KeyExchange:
                algorithmKeySpec = KeySpec.AT_KEYEXCHANGE;
                break;

            case KeyUsage.Signature:
                algorithmKeySpec = KeySpec.AT_SIGNATURE;
                break;

            default:
                throw new ArgumentException(nameof(keyUsage));
            }
            if (!AdvApi32.CryptGenKey(provider, algorithmKeySpec, genKeyFlags, out key))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            key.Close();
            keySpec = algorithmKeySpec;
            return(provider);
        }
Esempio n. 11
0
        public static bool HasPrivileges(this AdvApi32.SafeTokenHandle hObj, bool requireAll, params SystemPrivilege[] privs)
        {
            bool ret;

            if (!AdvApi32.PrivilegeCheck(hObj, new AdvApi32.PRIVILEGE_SET((AdvApi32.PrivilegeSetControl)(requireAll ? 1 : 0), privs.Select(p => new AdvApi32.LUID_AND_ATTRIBUTES(p.GetLUID(), AdvApi32.PrivilegeAttributes.SE_PRIVILEGE_ENABLED)).ToArray()), out ret))
            {
                throw new Win32Exception();
            }
            return(ret);
        }
Esempio n. 12
0
        /// <summary>Initiates a shutdown and optional restart of the specified computer.</summary>
        /// <param name="machineName">
        /// String that specifies the network name of the computer to shut down. If NULL or an empty string, the function shuts down the local computer.
        /// </param>
        /// <param name="message">String that specifies a message to display in the shutdown dialog box. This parameter can be NULL if no message is required.</param>
        /// <param name="timeout">
        /// Time that the shutdown dialog box should be displayed, in seconds. While this dialog box is displayed, shutdown can be stopped by the
        /// AbortSystemShutdown function.
        /// </param>
        /// <param name="forceAppsClosed">
        /// If this parameter is TRUE, applications with unsaved changes are to be forcibly closed. If this parameter is FALSE, the system displays a dialog box
        /// instructing the user to close the applications.
        /// </param>
        /// <param name="rebootAfterShutdown">
        /// If this parameter is TRUE, the computer is to restart immediately after shutting down. If this parameter is FALSE, the system flushes all caches to
        /// disk and clears the screen.
        /// </param>
        /// <param name="reason">Reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes.</param>
        /// <returns>0 on failure, non-zero for success</returns>
        public static bool InitiateShutdown(string machineName = null, string message = null, TimeSpan?timeout = null, bool forceAppsClosed = false, bool rebootAfterShutdown = false, AdvApi32.SystemShutDownReason reason = AdvApi32.SystemShutDownReason.SHTDN_REASON_UNKNOWN)
        {
            var graceSecs = (uint)timeout.GetValueOrDefault().TotalSeconds;

            if (Environment.OSVersion.Version.Major <= 5 && graceSecs > AdvApi32.MAX_SHUTDOWN_TIMEOUT)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), $"Timeout can be no longer than {AdvApi32.MAX_SHUTDOWN_TIMEOUT} seconds on Windows XP and earlier systems.");
            }
            using (string.IsNullOrEmpty(machineName) ? new PrivilegedCodeBlock(SystemPrivilege.Shutdown) : new PrivilegedCodeBlock(SystemPrivilege.RemoteShutdown))
                return(AdvApi32.InitiateSystemShutdownEx(machineName, message, graceSecs, forceAppsClosed, rebootAfterShutdown, reason));
        }
Esempio n. 13
0
        public static void PSID()
        {
            AdvApi32.PSID pSid;
            string        dn;

            AdvApi32.SID_NAME_USE snu;
            AdvApi32.LookupAccountName(null, "SYSTEM", out pSid, out dn, out snu);
            var newSid = AdvApi32.PSID.Init(AdvApi32.SECURITY_NT_AUTHORITY, 0x12);             // S-1-5-18

            AddTestResult(null, "Lookup SYSTEM == Built SYSTEM", pSid == newSid);
        }
Esempio n. 14
0
        /// <summary>
        /// Initiates a shutdown and restart of the specified computer, and restarts any applications that have been registered for restart.
        /// </summary>
        /// <param name="machineName">The name of the computer to be shut down. If the value of this parameter is NULL, the local computer is shut down.</param>
        /// <param name="message">The message to be displayed in the interactive shutdown dialog box.</param>
        /// <param name="gracePeriod">The number of seconds to wait before shutting down the computer. If the value of this parameter is zero, the computer is shut down immediately. This value is limited to MAX_SHUTDOWN_TIMEOUT.
        /// <para>If the value of this parameter is greater than zero, and the dwShutdownFlags parameter specifies the flag SHUTDOWN_GRACE_OVERRIDE, the function fails and returns the error code ERROR_BAD_ARGUMENTS.</para></param>
        /// <param name="flags">One or more bit flags that specify options for the shutdown.</param>
        /// <param name="reason">The reason for initiating the shutdown. This parameter must be one of the system shutdown reason codes. If this parameter is zero, the default is an undefined shutdown that is logged as "No title for this reason could be found". By default, it is also an unplanned shutdown. Depending on how the system is configured, an unplanned shutdown triggers the creation of a file that contains the system state information, which can delay shutdown. Therefore, do not use zero for this parameter.</param>
        public static void InitiateShutdown(string machineName, string message, TimeSpan gracePeriod, ShutdownFlags flags, SystemShutDownReason reason = SystemShutDownReason.SHTDN_REASON_UNKNOWN)
        {
            var graceSecs = (uint)gracePeriod.TotalSeconds;

            if (graceSecs > MAX_SHUTDOWN_TIMEOUT)
            {
                throw new ArgumentOutOfRangeException(nameof(gracePeriod), $"Grace period can be no longer than {MAX_SHUTDOWN_TIMEOUT} seconds.");
            }
            using (string.IsNullOrEmpty(machineName) ? new PrivilegedCodeBlock(SystemPrivilege.Shutdown) : new PrivilegedCodeBlock(SystemPrivilege.RemoteShutdown))
                AdvApi32.InitiateShutdown(machineName, message, graceSecs, flags, reason);
        }
Esempio n. 15
0
        public static void Exit(ShutdownFlags Flags = ShutdownFlags.Shutdown, int Reason = 0)
        {
            var    tp = new TokPriv1Luid(1, 0, AdvApi32.SE_PRIVILEGE_ENABLED);
            IntPtr hproc = Kernel32.CurrentProcess, htok = IntPtr.Zero;

            AdvApi32.OpenProcessToken(hproc, AdvApi32.TOKEN_ADJUST_PRIVILEGES | AdvApi32.TOKEN_QUERY, ref htok);
            AdvApi32.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref tp.Luid);
            AdvApi32.AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

            User32.ExitWindows(Flags, 0);
        }
Esempio n. 16
0
        public static IEnumerable <INHERITED_FROM> GetInheritanceSource(string objectName, System.Security.AccessControl.ResourceType objectType,
                                                                        SECURITY_INFORMATION securityInfo, bool container, IntPtr pAcl, ref GENERIC_MAPPING pGenericMapping)
        {
            var objSize  = Marshal.SizeOf(typeof(INHERITED_FROM));
            var aceCount = GetAceCount(pAcl);

            using (var pInherit = new SafeInheritedFromArray((ushort)aceCount))
            {
                AdvApi32.GetInheritanceSource(objectName, (SE_OBJECT_TYPE)objectType, securityInfo, container, null, 0, pAcl, IntPtr.Zero, ref pGenericMapping, pInherit).ThrowIfFailed();
                return(pInherit.Results);
            }
        }
Esempio n. 17
0
        public override void Execute(object context, ActivityQueue queue, Trigger trigger)
        {
            // get the login information out of the credential store
            int    count;
            IntPtr pCredentials;
            var    ret = AdvApi32.CredEnumerate(null, 0, out count, out pCredentials);

            if (!ret)
            {
                throw new Win32Exception();
            }
            var credentials = new IntPtr[count];

            // convert pointer to array to array of pointers
            for (var n = 0; n < count; n++)
            {
                credentials[n] = Marshal.ReadIntPtr(pCredentials,
                                                    n * Marshal.SizeOf(typeof(IntPtr)));
            }

            var login = credentials
                        // convert each pointer to a structure
                        .Select(ptr => (WinCred.Credential)Marshal.PtrToStructure(ptr, typeof(WinCred.Credential)))
                        // select the structure with the matching credential name
                        .FirstOrDefault(cred => cred.targetName.StartsWith(_credential));

            // get the password
            var currentPass = Marshal.PtrToStringUni(login.credentialBlob, (int)login.credentialBlobSize / 2);
            var lastError   = Marshal.GetLastWin32Error();

            if (lastError != 0)
            {
                throw new Win32Exception(lastError);
            }

            // finally try to log in
            var hostArr = login.targetName.Substring(_credential.Length + 1).Split(':');
            var host    = hostArr[0];
            var port    = hostArr.Length > 1 ? int.Parse(hostArr[1]) : 143;
            var @params = new ImapParams
            {
                Host     = host,
                Username = login.userName,
                Password = currentPass,
                Port     = port,
                Validate = false,
                Ssl      = port == 993 || port == 995,
                Queue    = queue
            };

            // start a thread to check for e-mail
            ThreadPool.QueueUserWorkItem(MailPoller, @params);
        }
Esempio n. 18
0
        public static bool DeleteService(string serviceName)
        // Marks the specified service for deletion from
        // the service control manager database
        {
            Trace.WriteLine(
                "Deleting service: \'" + serviceName + "\'"
                );

            IntPtr scManagerHandle = AdvApi32.OpenSCManager(
                null,
                null,
                AdvApi32.SC_MANAGER_ALL_ACCESS
                );

            if (scManagerHandle == IntPtr.Zero)
            {
                Win32Error.Set("OpenSCManager");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
                return(false);
            }

            IntPtr serviceHandle = AdvApi32.OpenService(
                scManagerHandle,
                serviceName,
                AdvApi32.DELETE
                );

            if (serviceHandle == IntPtr.Zero)
            {
                Win32Error.Set("OpenService");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
                AdvApi32.CloseServiceHandle(scManagerHandle);
                return(false);
            }

            bool success = AdvApi32.DeleteService(serviceHandle);

            if (success)
            {
                Trace.WriteLine("Service deleted successfully");
            }
            else
            {
                Win32Error.Set("DeleteService");
                Trace.WriteLine(Win32Error.GetFullErrMsg());
            }

            AdvApi32.CloseServiceHandle(serviceHandle);
            AdvApi32.CloseServiceHandle(scManagerHandle);

            return(success);
        }
Esempio n. 19
0
        public void OpenCloseService()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                //opens task scheduler service
                using (var service = AdvApi32.OpenService(scm, "Schedule", ServiceAccessTypes.SERVICE_QUERY_STATUS))
                {
                    AssertHandleIsValid(service);
                }
            }
        }
Esempio n. 20
0
        public static void AdjustPrivileges(this AdvApi32.SafeTokenHandle hObj, SafeCoTaskMemHandle privileges)
        {
            if (privileges == null || privileges.IsInvalid)
            {
                return;
            }
            uint retLen = 0;

            if (!AdvApi32.AdjustTokenPrivileges(hObj, false, privileges, (uint)privileges.Size, SafeCoTaskMemHandle.Null, ref retLen))
            {
                throw new Win32Exception();
            }
        }
Esempio n. 21
0
        public static void AdjustPrivileges(this AdvApi32.SafeTokenHandle hObj, AdvApi32.PTOKEN_PRIVILEGES privileges)
        {
            if (privileges == null)
            {
                return;
            }
            uint retLen = 0;

            if (!AdvApi32.AdjustTokenPrivileges(hObj, false, privileges, (uint)privileges.SizeInBytes, null, ref retLen))
            {
                throw new Win32Exception();
            }
        }
Esempio n. 22
0
        public static SafeCoTaskMemHandle AdjustPrivilege(this AdvApi32.SafeTokenHandle hObj, SystemPrivilege priv, AdvApi32.PrivilegeAttributes attr)
        {
            var newState  = new AdvApi32.PTOKEN_PRIVILEGES(priv.GetLUID(), attr);
            var prevState = AdvApi32.PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();
            var retLen    = (uint)prevState.Size;

            if (!AdvApi32.AdjustTokenPrivileges(hObj, false, newState, newState.SizeInBytes, prevState, ref retLen))
            {
                throw new Win32Exception();
            }
            prevState.Resize((int)retLen);
            return(prevState);
        }
Esempio n. 23
0
        public void StartStopService()
        {
            using (var scm = AdvApi32.OpenSCManager(null, null, ScManagerAccessTypes.SC_MANAGER_CONNECT))
            {
                AssertHandleIsValid(scm);

                var access = ServiceAccessTypes.SERVICE_START | ServiceAccessTypes.SERVICE_STOP | ServiceAccessTypes.SERVICE_QUERY_STATUS;

                //opens print spooler service
                using (var service = AdvApi32.OpenService(scm, "Spooler", access))
                {
                    AssertHandleIsValid(service);

                    //query service status
                    var status = AdvApi32.QueryServiceStatusEx <SERVICE_STATUS_PROCESS>(service, SC_STATUS_TYPE.SC_STATUS_PROCESS_INFO);

                    if (status.dwCurrentState == ServiceState.SERVICE_RUNNING)
                    {
                        var ret4 = AdvApi32.StopService(service, out var _);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_STOPPED);

                        var ret6 = AdvApi32.StartService(service);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                    else
                    {
                        var ret4 = AdvApi32.StartService(service);
                        if (!ret4)
                        {
                            Win32Error.ThrowLastError();
                        }

                        WaitForServiceStatus(service, ServiceState.SERVICE_RUNNING);

                        var ret6 = AdvApi32.StopService(service, out var _);
                        if (!ret6)
                        {
                            Win32Error.ThrowLastError();
                        }
                    }
                }
            }
        }
 protected override bool ReleaseHandle()
 {
     if (!_callerFree)
     {
         return(true);
     }
     if (IsNCryptKey)
     {
         return(NCrypt.NCryptFreeObject(handle) == SECURITY_STATUS.ERROR_SUCCESS);
     }
     else
     {
         return(AdvApi32.CryptReleaseContext(handle, 0u));
     }
 }
Esempio n. 25
0
        public static SafeSecurityDescriptor GetPrivateObjectSecurity(this PSECURITY_DESCRIPTOR pSD, SECURITY_INFORMATION si)
        {
            var pResSD = SafeSecurityDescriptor.Null;

            AdvApi32.GetPrivateObjectSecurity(pSD, si, pResSD, 0, out var ret);
            if (ret > 0)
            {
                pResSD = new SafeSecurityDescriptor((int)ret);
                if (!pResSD.IsInvalid && !AdvApi32.GetPrivateObjectSecurity(pSD, si, pResSD, ret, out ret))
                {
                    Win32Error.GetLastError().ThrowIfFailed();
                }
            }
            return(pResSD);
        }
Esempio n. 26
0
        public int LogonServiceAccount(ISecurityPrincipal o, string password)
        {
            var domain = this.discoveryServices.GetDomainNameNetBios(o.Sid);

            if (AdvApi32.LogonUser(o.SamAccountName, domain, password, AdvApi32.LogonUserType.LOGON32_LOGON_SERVICE, AdvApi32.LogonUserProvider.LOGON32_PROVIDER_DEFAULT, out AdvApi32.SafeHTOKEN token))
            {
                return(0);
            }

            int       result = Marshal.GetLastWin32Error();
            Exception ex     = new Win32Exception(result);

            this.logger.LogError(EventIDs.UIGenericError, ex, "Unable to validate credentials");

            return(result);
        }
        /// <summary>
        ///   Retrieves the multilingual string associated with the specified name. Returns null if the name/value pair does not exist in the registry.
        ///   The key must have been opened using
        /// </summary>
        /// <param name = "key">The registry key to load the string from.</param>
        /// <param name = "name">The name of the string to load.</param>
        /// <returns>The language-specific string, or null if the name/value pair does not exist in the registry.</returns>
        public static string LoadMuiStringValue(this RegistryKey key, string name)
        {
            const int initialBufferSize = 1024;
            var       output            = new StringBuilder(initialBufferSize);
            int       requiredSize;
            IntPtr    keyHandle = key.Handle.DangerousGetHandle();
            ErrorCode result    = (ErrorCode)AdvApi32.RegLoadMUIString(keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null);

            if (result == ErrorCode.MoreData)
            {
                output.EnsureCapacity(requiredSize);
                result = (ErrorCode)AdvApi32.RegLoadMUIString(keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null);
            }

            return(result == ErrorCode.Success ? output.ToString() : null);
        }
Esempio n. 28
0
        private static SafeFileHandle OpenReparsePoint(string path, bool writeAccess)
        {
            using (Process currentProcess = Process.GetCurrentProcess())
            {
                IntPtr tokenHandle = IntPtr.Zero;
                try
                {
                    tokenHandle = AdvApi32.OpenProcessToken(currentProcess.Handle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query);

                    Luid luid       = AdvApi32.LookupPrivilegeValue(writeAccess ? PrivilegeName.Restore : PrivilegeName.Backup);
                    var  privileges = new TokenPrivileges
                    {
                        PrivilegeCount = 1,
                        Privileges     = new []
                        {
                            new Privilege()
                            {
                                Luid       = luid,
                                Attributes = Privilege.EnabledAttribute,
                            }
                        }
                    };

                    AdvApi32.AdjustTokenPrivileges(tokenHandle, privileges);
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        Kernel32.CloseHandle(tokenHandle);
                    }
                }
            }

            GenericAccessRights access = GenericAccessRights.Read;

            if (writeAccess)
            {
                access |= GenericAccessRights.Write;
            }

            SafeFileHandle handle = Kernel32.CreateFile(path, access, FileShare.None,
                                                        FileMode.Open, FileAttributes.Normal, FileFlags.OpenReparsePoint | FileFlags.BackupSemantics);

            return(handle);
        }
Esempio n. 29
0
        public static SafeCoTaskMemHandle AdjustPrivileges(this AdvApi32.SafeTokenHandle hObj, params ExtensionMethods.PrivilegeAndAttributes[] privileges)
        {
            if (privileges == null || privileges.Length == 0)
            {
                return(SafeCoTaskMemHandle.Null);
            }
            var newState  = new AdvApi32.PTOKEN_PRIVILEGES(privileges.Select(pa => new AdvApi32.LUID_AND_ATTRIBUTES(pa.Privilege.GetLUID(), pa.Attributes)).ToArray());
            var prevState = AdvApi32.PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();
            var retLen    = (uint)prevState.Size;

            if (!AdvApi32.AdjustTokenPrivileges(hObj, false, newState, newState.SizeInBytes, prevState, ref retLen))
            {
                throw new Win32Exception();
            }
            prevState.Resize((int)retLen);
            return(prevState);
        }
Esempio n. 30
0
        public static IntPtr GetPrivateObjectSecurity(IntPtr pSD, SECURITY_INFORMATION si)
        {
            var pResSD = IntPtr.Zero;

            AdvApi32.GetPrivateObjectSecurity(pSD, si, IntPtr.Zero, 0, out uint ret);
            if (ret > 0)
            {
                pResSD = Marshal.AllocHGlobal((int)ret);
                if (pResSD != IntPtr.Zero && !AdvApi32.GetPrivateObjectSecurity(pSD, si, pResSD, ret, out ret))
                {
                    Marshal.FreeHGlobal(pResSD);
                    pResSD = IntPtr.Zero;
                    Win32Error.GetLastError().ThrowIfFailed();
                }
            }
            return(pResSD);
        }