Пример #1
0
        public TokenProvider SetIntegrity(int integrityLevel)
        {
            string integritySid =
                "S-1-16-" + integrityLevel.ToString(System.Globalization.CultureInfo.InvariantCulture);
            IntPtr pIntegritySid;

            if (!ConvertStringSidToSid(integritySid, out pIntegritySid))
            {
                throw new Win32Exception();
            }

            TOKEN_MANDATORY_LABEL TIL = new TOKEN_MANDATORY_LABEL();

            TIL.Label.Attributes = 0x00000020 /* SE_GROUP_INTEGRITY */;
            TIL.Label.Sid        = pIntegritySid;

            var pTIL = Marshal.AllocHGlobal(Marshal.SizeOf <TOKEN_MANDATORY_LABEL>());

            Marshal.StructureToPtr(TIL, pTIL, false);

            if (!SetTokenInformation(Token.DangerousGetHandle(),
                                     TOKEN_INFORMATION_CLASS.TokenIntegrityLevel,
                                     pTIL,
                                     (uint)(Marshal.SizeOf <TOKEN_MANDATORY_LABEL>() + GetLengthSid(pIntegritySid))))
            {
                throw new Win32Exception();
            }

            return(this);
        }
        unsafe static public bool IsRunningElevated()
        {
            // Pre-vista, nothing ran elevated
            if (Environment.OSVersion.Version.Major < 6)
            {
                return(false);
            }

            IntPtr processToken = WindowsIdentity.GetCurrent().Token;

            uint returnLength;

            if (GetTokenInformation(
                    processToken,
                    25,                 // TokenIntegrityLevel,
                    IntPtr.Zero,        // TokenInformation
                    0,                  // tokenInformationLength
                    out returnLength) != 0)
            {
                return(false);
            }

            if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
            {
                return(false);
            }

            uint length = returnLength;

            byte[] tokenInformation = new byte[length];

            uint integLevel;

            fixed(byte *tokenInformationPtr = tokenInformation)
            {
                if (GetTokenInformation(
                        processToken,
                        25,                          // TokenIntegrityLevel,
                        (IntPtr)tokenInformationPtr, // TokenInformation
                        length,                      // tokenInformationLength
                        out returnLength) == 0)
                {
                    return(false);
                }

                TOKEN_MANDATORY_LABEL label = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure((IntPtr)tokenInformationPtr, typeof(TOKEN_MANDATORY_LABEL));
                IntPtr psid = label.Label.Sid;

                IntPtr subAuthCountPtr = GetSidSubAuthorityCount(psid);
                byte   subAuthCount    = Marshal.ReadByte(subAuthCountPtr);
                uint   subAuthIndex    = (uint)(subAuthCount - 1);
                IntPtr integLevelPtr   = GetSidSubAuthority(psid, subAuthIndex);

                integLevel = (uint)Marshal.ReadInt32(integLevelPtr);
            }

            return(integLevel >= SECURITY_MANDATORY_HIGH_RID);
        }
Пример #3
0
        public static bool SetInformationToken(IntPtr hproctoken, IntPtr pSid)
        {
            SID_AND_ATTRIBUTES sidAndAttributes = new SID_AND_ATTRIBUTES
            {
                Sid        = pSid,
                Attributes = SE_GROUP_INTEGRITY
            };

            TOKEN_MANDATORY_LABEL tokenMandatoryLevel = new TOKEN_MANDATORY_LABEL();

            tokenMandatoryLevel.Label = sidAndAttributes;
            Int32 tokenMandatoryLabelSize = Marshal.SizeOf(tokenMandatoryLevel);

            if (Natives.NtSetInformationToken(hproctoken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ref tokenMandatoryLevel, tokenMandatoryLabelSize) != 0)
            {
                return(false);
            }
            return(true);
        }
Пример #4
0
 public static extern Int32 NtSetInformationToken(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref TOKEN_MANDATORY_LABEL TokenInformation, int TokenInformationLength);
Пример #5
0
        public static PROCESS_INFORMATION StartElevatedProcess(string binary, [Optional] int elevatedPID)
        {
            IntPtr hProcess = IntPtr.Zero;

            if (elevatedPID > 0)
            {
                hProcess = OpenProcess(0x00001000, false, elevatedPID);
            }
            else
            {
                SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO();

                shellInfo.cbSize = Marshal.SizeOf(shellInfo);
                shellInfo.fMask  = 0x40;
                shellInfo.lpFile = "wusa.exe";
                shellInfo.nShow  = 0x0;

                ShellExecuteEx(ref shellInfo);

                hProcess = shellInfo.hProcess;
            }

            IntPtr hToken = IntPtr.Zero;

            OpenProcessToken(hProcess, 0x02000000, ref hToken);

            IntPtr hNewToken = IntPtr.Zero;
            SECURITY_ATTRIBUTES secAttribs = new SECURITY_ATTRIBUTES();

            DuplicateTokenEx(hToken, 0xf01ff, ref secAttribs, 2, 1, ref hNewToken);

            SID_IDENTIFIER_AUTHORITY sia = new SID_IDENTIFIER_AUTHORITY();

            sia.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 };

            IntPtr pSID = IntPtr.Zero;

            AllocateAndInitializeSid(ref sia, 1, 0x2000, 0, 0, 0, 0, 0, 0, 0, ref pSID);

            SID_AND_ATTRIBUTES saa = new SID_AND_ATTRIBUTES();

            saa.Sid        = pSID;
            saa.Attributes = 0x20;

            TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL();

            tml.Label = saa;
            int tmlSize = Marshal.SizeOf(tml);

            NtSetInformationToken(hNewToken, 25, ref tml, tmlSize);

            IntPtr luaToken = IntPtr.Zero;

            NtFilterToken(hNewToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref luaToken);

            hNewToken  = IntPtr.Zero;
            secAttribs = new SECURITY_ATTRIBUTES();

            DuplicateTokenEx(luaToken, 0xc, ref secAttribs, 2, 2, ref hNewToken);

            ImpersonateLoggedOnUser(hNewToken);

            STARTUPINFO         sInfo = new STARTUPINFO();
            PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();

            CreateProcessWithLogonW("xxx", "xxx", "xxx", LogonFlags.LogonNetCredentialsOnly, binary, "", CreationFlags.CreateSuspended, 0, @"C:\Windows\System32", ref sInfo, out pInfo);

            if (elevatedPID == 0)
            {
                TerminateProcess(hProcess, 1);
            }

            return(pInfo);
        }
Пример #6
0
 internal static extern bool SetTokenInformation(SafeTokenHandle hToken, TOKEN_INFORMATION_CLASS informationClass,
                                                 TOKEN_MANDATORY_LABEL tokenInformation,
                                                 int tokenInformationLength);
Пример #7
0
        public PROCESS_INFORMATION StartElevatedProcess(string binary, [Optional] int elevatedPID)
        {
            IntPtr hProcess = IntPtr.Zero;

            if (elevatedPID > 0)
            {
                hProcess = OpenProcess(0x00001000, false, elevatedPID);
            }
            else
            {
                SHELLEXECUTEINFO shellInfo = new SHELLEXECUTEINFO();

                shellInfo.cbSize = Marshal.SizeOf(shellInfo);
                shellInfo.fMask  = 0x40;
                shellInfo.lpFile = "wusa.exe";
                shellInfo.nShow  = 0x0;

                if (!ShellExecuteEx(ref shellInfo))
                {
                    throw new SystemException("[x] Failed to create process");
                }

                hProcess = shellInfo.hProcess;
            }

            if (hProcess == IntPtr.Zero)
            {
                throw new SystemException("[x] Failed to process handle");
            }

            IntPtr hToken = IntPtr.Zero;

            if (!OpenProcessToken(hProcess, 0x02000000, ref hToken))
            {
                throw new SystemException("[x] Failed to open process token");
            }

            IntPtr hNewToken = IntPtr.Zero;
            SECURITY_ATTRIBUTES secAttribs = new SECURITY_ATTRIBUTES();

            if (!DuplicateTokenEx(hToken, 0xf01ff, ref secAttribs, 2, 1, ref hNewToken))
            {
                throw new SystemException("[x] Failed to duplicate process token");
            }

            SID_IDENTIFIER_AUTHORITY sia = new SID_IDENTIFIER_AUTHORITY();

            sia.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 };

            IntPtr pSID = IntPtr.Zero;

            if (!AllocateAndInitializeSid(ref sia, 1, 0x2000, 0, 0, 0, 0, 0, 0, 0, ref pSID))
            {
                throw new SystemException("[x] Failed to initialize SID");
            }

            SID_AND_ATTRIBUTES saa = new SID_AND_ATTRIBUTES();

            saa.Sid        = pSID;
            saa.Attributes = 0x20;

            TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL();

            tml.Label = saa;
            int tmlSize = Marshal.SizeOf(tml);

            if (NtSetInformationToken(hNewToken, 25, ref tml, tmlSize) != 0)
            {
                throw new SystemException("[x] Failed to modify token");
            }

            IntPtr luaToken = IntPtr.Zero;

            if (NtFilterToken(hNewToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref luaToken) != 0)
            {
                throw new SystemException("[x] Failed to create restricted token");
            }

            hNewToken  = IntPtr.Zero;
            secAttribs = new SECURITY_ATTRIBUTES();

            if (!DuplicateTokenEx(luaToken, 0xc, ref secAttribs, 2, 2, ref hNewToken))
            {
                throw new SystemException("[x] Failed to duplicate restricted token");
            }

            if (!ImpersonateLoggedOnUser(hNewToken))
            {
                throw new SystemException("[x] Failed to impersonate context");
            }

            STARTUPINFO         sInfo = new STARTUPINFO();
            PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();

            CreateProcessWithLogonW("xxx", "xxx", "xxx", LogonFlags.LOGON_NETCREDENTIALS_ONLY, binary, "",
                                    CreationFlags.CREATE_SUSPENDED, 0, @"C:\\Windows\\System32", ref sInfo, out pInfo);

            if (elevatedPID == 0)
            {
                if (!TerminateProcess(hProcess, 1))
                {
                    Console.WriteLine("Warning, failed to terminate wusa.exe");
                }
            }

            return(pInfo);
        }
Пример #8
0
 public static extern int NtSetInformationToken(IntPtr TokenHandle, int TokenInformationClass, ref TOKEN_MANDATORY_LABEL TokenInformation, int TokenInformationLength);
Пример #9
0
        /// <summary>
        /// The function gets the integrity level of the current process. Integrity
        /// level is only available on Windows Vista and newer operating systems, thus
        /// GetProcessIntegrityLevel throws a C++ exception if it is called on systems
        /// prior to Windows Vista.
        /// </summary>
        /// <returns>
        /// Returns the integrity level of the current process. It is usually one of
        /// these values:
        ///
        ///    SECURITY_MANDATORY_UNTRUSTED_RID - means untrusted level. It is used
        ///    by processes started by the Anonymous group. Blocks most write access.
        ///    (SID: S-1-16-0x0)
        ///
        ///    SECURITY_MANDATORY_LOW_RID - means low integrity level. It is used by
        ///    Protected Mode Internet Explorer. Blocks write acess to most objects
        ///    (such as files and registry keys) on the system. (SID: S-1-16-0x1000)
        ///
        ///    SECURITY_MANDATORY_MEDIUM_RID - means medium integrity level. It is
        ///    used by normal applications being launched while UAC is enabled.
        ///    (SID: S-1-16-0x2000)
        ///
        ///    SECURITY_MANDATORY_HIGH_RID - means high integrity level. It is used
        ///    by administrative applications launched through elevation when UAC is
        ///    enabled, or normal applications if UAC is disabled and the user is an
        ///    administrator. (SID: S-1-16-0x3000)
        ///
        ///    SECURITY_MANDATORY_SYSTEM_RID - means system integrity level. It is
        ///    used by services and other system-level applications (such as Wininit,
        ///    Winlogon, Smss, etc.)  (SID: S-1-16-0x4000)
        ///
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception
        /// with the last error code.
        /// </exception>
        public static int GetProcessIntegrityLevel()
        {
            int             IL        = -1;
            SafeTokenHandle hToken    = null;
            int             cbTokenIL = 0;
            IntPtr          pTokenIL  = IntPtr.Zero;

            try
            {
                // Open the access token of the current process with TOKEN_QUERY.
                if (!NativeMethod.OpenProcessToken(Process.GetCurrentProcess().Handle,
                                                   NativeMethod.TOKEN_QUERY, out hToken))
                {
                    throw new Win32Exception();
                }

                // Then we must query the size of the integrity level information
                // associated with the token. Note that we expect GetTokenInformation
                // to return false with the ERROR_INSUFFICIENT_BUFFER error code
                // because we've given it a null buffer. On exit cbTokenIL will tell
                // the size of the group information.
                if (!NativeMethod.GetTokenInformation(hToken,
                                                      TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0,
                                                      out cbTokenIL))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error != NativeMethod.ERROR_INSUFFICIENT_BUFFER)
                    {
                        // When the process is run on operating systems prior to
                        // Windows Vista, GetTokenInformation returns false with the
                        // ERROR_INVALID_PARAMETER error code because
                        // TokenIntegrityLevel is not supported on those OS's.
                        throw new Win32Exception(error);
                    }
                }

                // Now we allocate a buffer for the integrity level information.
                pTokenIL = Marshal.AllocHGlobal(cbTokenIL);
                if (pTokenIL == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // Now we ask for the integrity level information again. This may fail
                // if an administrator has added this account to an additional group
                // between our first call to GetTokenInformation and this one.
                if (!NativeMethod.GetTokenInformation(hToken,
                                                      TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenIL, cbTokenIL,
                                                      out cbTokenIL))
                {
                    throw new Win32Exception();
                }

                // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object.
                TOKEN_MANDATORY_LABEL tokenIL = (TOKEN_MANDATORY_LABEL)
                                                Marshal.PtrToStructure(pTokenIL, typeof(TOKEN_MANDATORY_LABEL));

                // Integrity Level SIDs are in the form of S-1-16-0xXXXX. (e.g.
                // S-1-16-0x1000 stands for low integrity level SID). There is one
                // and only one subauthority.
                IntPtr pIL = NativeMethod.GetSidSubAuthority(tokenIL.Label.Sid, 0);
                IL = Marshal.ReadInt32(pIL);
            }
            finally
            {
                // Centralized cleanup for all allocated resources.
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (pTokenIL != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pTokenIL);
                    pTokenIL  = IntPtr.Zero;
                    cbTokenIL = 0;
                }
            }

            return(IL);
        }
Пример #10
0
        public string ShowProcessIntegrityLevel(int ID)
        {
            Process proc     = Process.GetProcessById(ID);
            IntPtr  hProcess = proc.Handle;
            IntPtr  hToken;

            OpenProcessToken(hProcess, TokenAccessLevels.MaximumAllowed, out hToken);
            string IL = ND_MESSAGE;

            try
            {
                uint dwLengthNeeded;
                if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out dwLengthNeeded))
                {
                    uint dwError = (uint)Marshal.GetLastWin32Error();
                }

                IntPtr pTIL = Marshal.AllocHGlobal((int)dwLengthNeeded);
                try
                {
                    if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel,
                                             pTIL, dwLengthNeeded, out dwLengthNeeded))
                    {
                        return(IL);
                    }

                    TOKEN_MANDATORY_LABEL TIL = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(pTIL,
                                                                                              typeof(TOKEN_MANDATORY_LABEL));

                    IntPtr SubAuthorityCount = GetSidSubAuthorityCount(TIL.Label.Sid);

                    IntPtr IntegrityLevelPtr = GetSidSubAuthority(TIL.Label.Sid,
                                                                  Marshal.ReadByte(SubAuthorityCount) - 1);

                    int dwIntegrityLevel = Marshal.ReadInt32(IntegrityLevelPtr);

                    if (dwIntegrityLevel >= SECURITY_MANDATORY_UNTRUSTED_RID &&
                        dwIntegrityLevel < SECURITY_MANDATORY_LOW_RID)
                    {
                        IL = "Ненадежный";
                    }

                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_LOW_RID &&
                             dwIntegrityLevel < SECURITY_MANDATORY_MEDIUM_RID)
                    {
                        IL = "Низкий";
                    }

                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID &&
                             dwIntegrityLevel < SECURITY_MANDATORY_MEDIUM_PLUS_RID)
                    {
                        IL = "Средний";
                    }

                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_PLUS_RID &&
                             dwIntegrityLevel < SECURITY_MANDATORY_HIGH_RID)
                    {
                        IL = "Средний+";
                    }
                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID &&
                             dwIntegrityLevel < SECURITY_MANDATORY_SYSTEM_RID)
                    {
                        IL = "Высокий";
                    }
                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_SYSTEM_RID &&
                             dwIntegrityLevel < SECURITY_MANDATORY_PROTECTED_PROCESS_RID)
                    {
                        IL = "Системный";
                    }
                    else if (dwIntegrityLevel >= SECURITY_MANDATORY_PROTECTED_PROCESS_RID)
                    {
                        IL = "Защищенный";
                    }
                }
                catch (Exception err)
                {
                    #region Запись в файл "Exeptions_LOG.txt" исключений, возникающих в ходе работы программы
                    string error_message = "Имя: " + proc.ProcessName + Environment.NewLine +
                                           "Исключение: " + err.Message.ToString() + Environment.NewLine + Environment.NewLine;

                    StreamWriter file = new StreamWriter("Исключение.txt", true);
                    file.WriteLine(error_message);
                    file.Close();
                    #endregion

                    Marshal.FreeHGlobal(pTIL);
                    return(IL);
                }
            }
            catch (Exception err)
            {
                #region Запись в файл "Exeptions_LOG.txt" исключений, возникающих в ходе работы программы
                string error_message = "Имя: " + proc.ProcessName + Environment.NewLine +
                                       "Исключение: " + err.Message.ToString() + Environment.NewLine + Environment.NewLine;

                StreamWriter file = new StreamWriter("Исключение.txt", true);
                file.WriteLine(error_message);
                file.Close();
                #endregion

                CloseHandle(hToken);
                return(IL);
            }
            return(IL);
        }
Пример #11
0
 internal static extern bool SetTokenInformation(SafeTokenHandle hToken, TOKEN_INFORMATION_CLASS informationClass,
                                                 TOKEN_MANDATORY_LABEL tokenInformation,
                                                 int tokenInformationLength);
Пример #12
0
        /// <summary>
        /// Sets the integrity level of the given access token.
        /// </summary>
        /// <param name="token">handle to the access token</param>
        /// <param name="mlrid">mandatory integrity level</param>
        private static void SetTokenMandatoryLabel(IntPtr token, MandatoryLabel mlrid)
        {
            SID_IDENTIFIER_AUTHORITY mlauth = new SID_IDENTIFIER_AUTHORITY() {
                Value = MANDATORY_LABEL_AUTHORITY
            };
            TOKEN_MANDATORY_LABEL tml = new TOKEN_MANDATORY_LABEL();
            IntPtr mlauthptr;
            IntPtr sidptr;
            IntPtr tmlptr;
            int tmlsz;
            int errno = 0;

            mlauthptr = Marshal.AllocHGlobal(Marshal.SizeOf(mlauth));
            Marshal.StructureToPtr(mlauth, mlauthptr, false);

            if (!Security.AllocateAndInitializeSid(mlauthptr, 1, (int)mlrid, 0, 0, 0, 0, 0, 0, 0, out sidptr)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(mlauthptr);
                throw new IOException("Failed to allocate new SID. (" + errno + ")");
            }

            Marshal.FreeHGlobal(mlauthptr);

            tml.Label.Sid = sidptr;
            tml.Label.Attributes = SE_GROUP_INTEGRITY;

            tmlsz = Marshal.SizeOf(tml);
            tmlptr = Marshal.AllocHGlobal(tmlsz);
            Marshal.StructureToPtr(tml, tmlptr, false);

            if (!Security.SetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, tmlptr, tmlsz)) {
                errno = Marshal.GetLastWin32Error();
                Marshal.FreeHGlobal(sidptr);
                Marshal.FreeHGlobal(tmlptr);
                throw new IOException("Failed to set token mandatory label. (" + errno + ")");
            }

            Marshal.FreeHGlobal(sidptr);
            Marshal.FreeHGlobal(tmlptr);
        }
        /// <summary>
        /// Extracts Token information from a thread's memory by wrapping GetTokenInformation(). Returns token information specified by the tokenInformationClass param
        /// </summary>
        /// <param name="hToken"></param>
        /// <param name="tokenInformationClass"></param>
        /// <returns>String containing the requested token information</returns>
        static string QueryToken(IntPtr hToken, TOKEN_INFORMATION_CLASS tokenInformationClass)
        {
            int tokenInformationLength = 0;

            // First need to get the length of TokenInformation - won't return true
            bool result = GetTokenInformation(hToken, tokenInformationClass, IntPtr.Zero, tokenInformationLength, out tokenInformationLength);
            // Buffer for the struct
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInformationLength);

            // Make call to GetTokenInformation() and get particular Struct
            switch (tokenInformationClass)
            {
            case TOKEN_INFORMATION_CLASS.TokenUser:

                // Store the requested token information in the buffer
                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    // Marshal the buffer to TOKEN_USER Struct
                    TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_USER));

                    // Extract SID from the TOKEN_USER struct
                    IntPtr pSID = IntPtr.Zero;
                    ConvertSidToStringSid(tokenUser.User.Sid, out pSID);
                    string SID = Marshal.PtrToStringAuto(pSID);

                    return(SID);
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenPrivileges:

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_PRIVILEGES tokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES));

                    StringBuilder stringBuilder = new StringBuilder();

                    for (int i = 0; i < tokenPrivileges.PrivilegeCount; i++)
                    {
                        // Bitwise AND comparison to check that each token privilege attribute for SE_PRIVILEGE_ENABLED
                        if (((LUID_ATTRIBUTES)tokenPrivileges.Privileges[i].Attributes & LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED) == LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED)
                        {
                            // Append the privilege to the stringBuilder
                            stringBuilder.Append($", {tokenPrivileges.Privileges[i].Luid.LowPart.ToString()}");
                        }
                    }

                    return(stringBuilder.ToString().Remove(0, 2));
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenIntegrityLevel:

                // Mandatory Level SIDs for QueryToken()
                // https://support.microsoft.com/en-au/help/243330/well-known-security-identifiers-in-windows-operating-systems#allsids
                Dictionary <string, string> tokenIntegritySIDs = new Dictionary <string, string>
                {
                    { "S-1-16-0", "Untrusted Mandatory Level" },
                    { "S-1-16-4096", "Low Mandatory Level" },
                    { "S-1-16-8192", "Medium Mandatory Level" },
                    { "S-1-16-8448", "Medium Plus Mandatory Level" },
                    { "S-1-16-12288", "High Mandatory Level" },
                    { "S-1-16-16384", "System Mandatory Level" },
                    { "S-1-16-20480", "Protected Process Mandatory Level" },
                    { "S-1-16-28672", "Secure Process Mandatory Level" }
                };

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_MANDATORY_LABEL tokenMandatoryLabel = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_MANDATORY_LABEL));

                    // Extract SID string from TOKEN_MANDATORY_LABEL
                    IntPtr pSID = IntPtr.Zero;
                    ConvertSidToStringSid(tokenMandatoryLabel.label.Sid, out pSID);
                    string SID = Marshal.PtrToStringAuto(pSID);

                    if (tokenIntegritySIDs.ContainsKey(SID))
                    {
                        return(tokenIntegritySIDs[SID]);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenOrigin:

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_ORIGIN tokenOrigin = (TOKEN_ORIGIN)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_ORIGIN));
                    string       logonId     = tokenOrigin.OriginatingLogonSession.LowPart.ToString();
                    return(logonId);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
Пример #14
0
        public string GetProcessIntegrityLevel()
        {
            int IL = -1;

            IntPtr hToken    = IntPtr.Zero;
            uint   cbTokenIL = 0;
            IntPtr pTokenIL  = IntPtr.Zero;
            string d         = "";

            try
            {
                if (!OpenProcessToken(ProcList[ProcNumber].Handle, TokenAccessLevels.Query, out hToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }


                if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out cbTokenIL))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error != ERROR_INSUFFICIENT_BUFFER)
                    {
                        throw new Win32Exception(error);
                    }
                }

                pTokenIL = Marshal.AllocHGlobal((int)cbTokenIL);
                if (pTokenIL == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                if (!GetTokenInformation(hToken,
                                         TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenIL, cbTokenIL,
                                         out cbTokenIL))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                TOKEN_MANDATORY_LABEL tokenIL = (TOKEN_MANDATORY_LABEL)
                                                Marshal.PtrToStructure(pTokenIL, typeof(TOKEN_MANDATORY_LABEL));

                IntPtr pIL = GetSidSubAuthority(tokenIL.Label.Sid, 0);
                IL = Marshal.ReadInt32(pIL);



                if (IL == SECURITY_MANDATORY_UNTRUSTED_RID)
                {
                    // Untrusted Integrity
                    d = "Untrusted Process";
                }
                else if (IL == SECURITY_MANDATORY_LOW_RID)
                {
                    // Low Integrity
                    d = "Low Process";
                }
                else if (IL == SECURITY_MANDATORY_MEDIUM_RID)
                {
                    // Medium Integrity
                    d = "Medium Process";
                }
                else if (IL == SECURITY_MANDATORY_HIGH_RID)
                {
                    // High Integrity
                    d = "High Integrity Process";
                }
                else if (IL == SECURITY_MANDATORY_SYSTEM_RID)
                {
                    // System Integrity
                    d = "System Integrity Process";
                }
                d += cbTokenIL.ToString();
            }
            finally
            {
                if (hToken != null)
                {
                    CloseHandle(hToken);
                    hToken = IntPtr.Zero;
                }
                if (pTokenIL != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pTokenIL);
                    pTokenIL  = IntPtr.Zero;
                    cbTokenIL = 0;
                }
            }

            return(d);
        }
Пример #15
0
 //integrity level процесса
 public static string GetIntegrityLevel(Process process)
 {
     try
     {
         IntPtr hProcess = process.Handle;
         IntPtr hToken;
         if (!OpenProcessToken(hProcess, TokenAccessLevels.MaximumAllowed, out hToken))
         {
             return("error");
         }
         try
         {
             uint dwLengthNeeded;
             if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out dwLengthNeeded))
             {
                 return("error");
             }
             uint dwError = (uint)Marshal.GetLastWin32Error();
             if (dwError == ERROR_INSUFFICIENT_BUFFER)
             {
                 IntPtr pTIL = Marshal.AllocHGlobal((int)dwLengthNeeded);
                 try
                 {
                     if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTIL, dwLengthNeeded, out dwLengthNeeded))
                     {
                         return("error");
                     }
                     //
                     TOKEN_MANDATORY_LABEL TIL = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(pTIL, typeof(TOKEN_MANDATORY_LABEL));
                     IntPtr SubAuthorityCount  = GetSidSubAuthorityCount(TIL.Label.Sid);
                     IntPtr IntegrityLevelPtr  = GetSidSubAuthority(TIL.Label.Sid, Marshal.ReadByte(SubAuthorityCount) - 1);
                     //
                     int dwIntegrityLevel = Marshal.ReadInt32(IntegrityLevelPtr);
                     if (dwIntegrityLevel < SECURITY_MANDATORY_LOW_RID)
                     {
                         return("untrusted");
                     }
                     else if (dwIntegrityLevel == SECURITY_MANDATORY_LOW_RID)
                     {
                         return("low");
                     }
                     else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID &&
                              dwIntegrityLevel < SECURITY_MANDATORY_HIGH_RID)
                     {
                         return("medium");
                     }
                     else if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID &&
                              dwIntegrityLevel < SECURITY_MANDATORY_SYSTEM_RID)
                     {
                         return("high");
                     }
                     else if (dwIntegrityLevel >= SECURITY_MANDATORY_SYSTEM_RID)
                     {
                         return("system");
                     }
                 }
                 finally { Marshal.FreeHGlobal(pTIL); }
             }
         }
         finally { CloseHandle(hToken); }
         return("");
     }
     catch { return("system"); }
 }
Пример #16
0
 public static extern bool SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, ref TOKEN_MANDATORY_LABEL TokenInformation, uint TokenInformationLength);