Provides direct Win32 calls to the security related functions
Beispiel #1
0
    IEnumerable <string> FetchSchedulerGroups()
    {
        var privileges = new LSA_UNICODE_STRING[1];

        privileges[0] = InitLsaString("SeBatchLogonRight");
        var ret      = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out LSA_HANDLE buffer, out ulong count);
        var accounts = new List <String>();

        if (ret == 0)
        {
            var LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
            var myLsaus = new LSA_ENUMERATION_INFORMATION();
            for (ulong i = 0; i < count; i++)
            {
                var itemAddr = new IntPtr(buffer.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));

                LsaInfo[i] =
                    (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                var SID = new SecurityIdentifier(LsaInfo[i].PSid);
                accounts.Add(ResolveAccountName(SID));
            }
        }

        return(accounts);
    }
Beispiel #2
0
    void TestReturnValue(uint ReturnValue)
    {
        if (ReturnValue == 0)
        {
            return;
        }

        if (ReturnValue == ERROR_PRIVILEGE_DOES_NOT_EXIST)
        {
            return;
        }
        if (ReturnValue == ERROR_NO_MORE_ITEMS)
        {
            return;
        }
        if (ReturnValue == STATUS_ACCESS_DENIED)
        {
            throw new UnauthorizedAccessException();
        }
        if (ReturnValue == STATUS_INSUFFICIENT_RESOURCES || ReturnValue == STATUS_NO_MEMORY)
        {
            return;
        }
        throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ReturnValue));
    }
Beispiel #3
0
    private IEnumerable <string> FetchSchedulerGroups()
    {
        var privileges = new LSA_UNICODE_STRING[1];

        privileges[0] = InitLsaString("SeBatchLogonRight");
        IntPtr buffer;
        int    count;
        uint   ret      = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count);
        var    accounts = new List <String>();

        if (ret == 0)
        {
            var LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
            for (int i = 0, elemOffs = (int)buffer; i < count; i++)
            {
                LsaInfo[i] =
                    (LSA_ENUMERATION_INFORMATION)
                    Marshal.PtrToStructure((IntPtr)elemOffs, typeof(LSA_ENUMERATION_INFORMATION));
                elemOffs += Marshal.SizeOf(typeof(LSA_ENUMERATION_INFORMATION));
                var SID = new SecurityIdentifier(LsaInfo[i].PSid);
                accounts.Add(ResolveAccountName(SID));
            }
        }

        return(accounts);
    }
Beispiel #4
0
 public void Dispose()
 {
     if (lsaHandle != IntPtr.Zero)
     {
         Win32Sec.LsaClose(lsaHandle);
         lsaHandle = IntPtr.Zero;
     }
     GC.SuppressFinalize(this);
 }
Beispiel #5
0
    public bool IsWindowsAuthorised(string privilege, string userName)
    {
        bool windowsAuthorised = false;

        userName = CleanUser(userName);
        var privileges = new LSA_UNICODE_STRING[1];

        privileges[0] = InitLsaString(privilege);
        IntPtr buffer;
        ulong  count;
        uint   ret      = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count);
        var    Accounts = new List <String>();

        if (ret == 0)
        {
            var LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
            LSA_ENUMERATION_INFORMATION myLsaus = new LSA_ENUMERATION_INFORMATION();
            for (ulong i = 0; i < count; i++)
            {
                IntPtr itemAddr = new IntPtr(buffer.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));

                LsaInfo[i] =
                    (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                var SID = new SecurityIdentifier(LsaInfo[i].PSid);
                Accounts.Add(ResolveAccountName(SID));
            }

            try
            {
                var wp = new WindowsPrincipal(new WindowsIdentity(userName));

                foreach (string account in Accounts)
                {
                    if (wp.IsInRole(account))
                    {
                        windowsAuthorised = true;
                    }
                }

                return(windowsAuthorised);
            }
            catch (Exception)
            {
                var localGroups = GetLocalUserGroupsForTaskSchedule(userName);

                var intersection = localGroups.Intersect(Accounts);

                return(intersection.Any());
            }
        }

        return(false);
    }
Beispiel #6
0
    public SecurityWrapper(string MachineName)
    {
        LSA_OBJECT_ATTRIBUTES lsaAttr;

        lsaAttr.RootDirectory            = IntPtr.Zero;
        lsaAttr.ObjectName               = IntPtr.Zero;
        lsaAttr.Attributes               = 0;
        lsaAttr.SecurityDescriptor       = IntPtr.Zero;
        lsaAttr.SecurityQualityOfService = IntPtr.Zero;
        lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
        lsaHandle      = IntPtr.Zero;
        LSA_UNICODE_STRING[] system = null;
        if (MachineName != null)
        {
            system    = new LSA_UNICODE_STRING[1];
            system[0] = InitLsaString(MachineName);
        }
        var ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr, (int)Access.POLICY_ALL_ACCESS, out lsaHandle);

        TestReturnValue(ret);
    }
Beispiel #7
0
    private List <string> GetAccountsWithPrivilege(string privilege)
    {
        var privileges = new LSA_UNICODE_STRING[1];

        privileges[0] = InitLsaString(privilege);
        var gotAccounts  = Win32Sec.LsaEnumerateAccountsWithUserRight(_lsaHandle, privileges, out LSA_HANDLE buffer, out ulong count) == 0;
        var accountNames = new List <string>();

        if (gotAccounts)
        {
            var LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
            var myLsaus = new LSA_ENUMERATION_INFORMATION();
            for (ulong i = 0; i < count; i++)
            {
                var itemAddr = new IntPtr(buffer.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                LsaInfo[i] = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                var sid = new SecurityIdentifier(LsaInfo[i].PSid);
                accountNames.Add(ResolveAccountName(sid));
            }
        }
        return(accountNames);
    }
Beispiel #8
0
    public bool IsWindowsAuthorised(string privilege, string userName)
    {
        var windowsAuthorised = false;

        var username   = CleanUser(userName);
        var privileges = new LSA_UNICODE_STRING[1];

        privileges[0] = InitLsaString(privilege);
        var ret      = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out LSA_HANDLE buffer, out ulong count);
        var Accounts = new List <String>();

        if (ret == 0)
        {
            var LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
            var myLsaus = new LSA_ENUMERATION_INFORMATION();
            for (ulong i = 0; i < count; i++)
            {
                var itemAddr = new IntPtr(buffer.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                LsaInfo[i] =
                    (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                var SID = new SecurityIdentifier(LsaInfo[i].PSid);
                Accounts.Add(ResolveAccountName(SID));
            }

            try
            {
                return(IsWindowsAuthorised(username, ref windowsAuthorised, Accounts));
            }
            catch (Exception)
            {
                var localGroups  = GetLocalUserGroupsForTaskSchedule(username);
                var intersection = localGroups.Intersect(Accounts);
                return(intersection.Any(s => !s.Equals(Environment.MachineName + "\\" + username, StringComparison.InvariantCultureIgnoreCase)));
            }
        }

        return(false);
    }
Beispiel #9
0
            /// <summary>
            /// Reads the user accounts which have the specific privilege
            /// </summary>
            /// <param name="Privilege">The name of the privilege for which the accounts with this right should be enumerated</param>
            public List <String> ReadPrivilege(string Privilege)
            {
                LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
                privileges[0] = InitLsaString(Privilege);
                IntPtr        buffer;
                int           count    = 0;
                uint          ret      = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count);
                List <String> Accounts = new List <String>();

                if (ret == 0)
                {
                    LSA_ENUMERATION_INFORMATION[] LsaInfo = new LSA_ENUMERATION_INFORMATION[count];
                    for (int i = 0, elemOffs = (int)buffer; i < count; i++)
                    {
                        LsaInfo[i] = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure((IntPtr)elemOffs, typeof(LSA_ENUMERATION_INFORMATION));
                        elemOffs  += Marshal.SizeOf(typeof(LSA_ENUMERATION_INFORMATION));
                        SecurityIdentifier SID = new SecurityIdentifier(LsaInfo[i].PSid);
                        Accounts.Add(SID.ToString());
                    }
                    return(Accounts);
                }
                TestReturnValue(ret);
                return(Accounts);
            }
        /************************************************************************************************/
        /*                                  Methods                                                     */
        /************************************************************************************************/
        #region Public methods
        public void StartTerminalSessionObservation(object hServ)
        {
            string msg;
            IntPtr pEvents = IntPtr.Zero;
            IntPtr hServer = (IntPtr)hServ;
            List <TerminalSessionInfo> oldSessions, newSessions;
            TerminalSessionInfo        tsi;
            WM_WTSSESSION_CHANGE_TYPE  changeType;

            // initial read actual sessions
            oldSessions       = ListSessions(false);
            newSessions       = new List <TerminalSessionInfo>(oldSessions.ToArray());
            tsObserverRunning = true;
            while (this.tsObserverRunning)
            {
                if (WTSWaitSystemEvent(hServer, (UInt32)WaitSystemEventFlags.AllEvents, out pEvents))
                {
                    WaitSystemEventFlags eventType = GetSystemEventType(pEvents);
                    switch (eventType)
                    {
                    case WaitSystemEventFlags.ConnectedWinstation:
                    case WaitSystemEventFlags.CreatedWinstation:
                    case WaitSystemEventFlags.LogonUser:
                        newSessions = ListSessions(false);
                        tsi         = GetChangedTerminalSession(oldSessions, newSessions, out changeType);
                        oldSessions.Clear();
                        oldSessions.AddRange(newSessions.ToArray());
                        if (tsi != null && tsi.SessionInfo.iSessionID != 0)
                        {
                            OnSessionChanged(new TerminalSessionChangedEventArgs(changeType, tsi.SessionInfo.iSessionID, tsi));
                        }
                        break;

                    case WaitSystemEventFlags.DeletedWinstation:
                    case WaitSystemEventFlags.DisconnectedWinstation:
                    case WaitSystemEventFlags.LogoffUser:
                    case WaitSystemEventFlags.WinstationStateChange:
                        newSessions = ListSessions(false);
                        tsi         = GetChangedTerminalSession(oldSessions, newSessions, out changeType);
                        oldSessions.Clear();
                        oldSessions.AddRange(newSessions.ToArray());
                        if (tsi != null && tsi.SessionInfo.iSessionID != 0)
                        {
                            OnSessionChanged(new TerminalSessionChangedEventArgs(changeType, tsi.SessionInfo.iSessionID, tsi));
                        }
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    uint winErrorCode = Win32Sec.GetLastError();
                    msg = new System.ComponentModel.Win32Exception((int)winErrorCode).Message;
                    WindowsEventLogHelper.WriteEventLog(msg, EventLogEntryType.Error);
                    WindowsEventLogHelper.WriteEventLog(RdpControl.SVC_NAME + " " + System.Reflection.MethodInfo.GetCurrentMethod().Name + " - methode failed: " + msg, EventLogEntryType.Error);
                }
                Thread.Sleep(100);
            }
            WTSCloseServer(hServer);
        }