Exemplo n.º 1
0
        //[Test]
        public void AppFromTokenTest()
        {
            using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_ALL_ACCESS))
            {
                var sb   = new StringBuilder(1024, 1024);
                var sbSz = (uint)sb.Capacity;
                ResetSb();
                Assert.That(GetApplicationUserModelIdFromToken(hTok, ref sbSz, sb), Is.EqualTo((Win32Error)0));
                WriteSb("AppUserModelId");

                ResetSb();
                Assert.That(GetPackageFamilyNameFromToken(hTok, ref sbSz, sb), Is.EqualTo((Win32Error)0));
                WriteSb("PkgFamilyName");

                ResetSb();
                Assert.That(GetPackageFullNameFromToken(hTok, ref sbSz, sb), Is.EqualTo((Win32Error)0));
                WriteSb("PkgFullName");

                void ResetSb()
                {
                    sb.Clear(); sbSz = (uint)sb.Capacity;
                }

                void WriteSb(string prefix) => TestContext.WriteLine($"{prefix}:{sb}");
            }
        }
Exemplo n.º 2
0
            /// <summary>Extracts the user account SID associated with a security token.</summary>
            /// <param name="hToken">The security token handle.</param>
            /// <returns>A <see cref="SafePSID"/> instance of the user account SID associated with a security token.</returns>
            public static SafePSID FromToken(HTOKEN hToken)
            {
                var hTok = new SafeHTOKEN((IntPtr)hToken, false);

                using var pUserToken = hTok.GetInfo(TOKEN_INFORMATION_CLASS.TokenUser);
                return(new SafePSID(pUserToken.ToStructure <TOKEN_USER>().User.Sid));
            }
Exemplo n.º 3
0
 public static void EnablePrivilege(this Process process, SystemPrivilege privilege)
 {
     using (var hObj = SafeHTOKEN.FromProcess(process, TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_QUERY))
     {
         hObj.AdjustPrivilege(privilege, PrivilegeAttributes.SE_PRIVILEGE_ENABLED);
     }
 }
Exemplo n.º 4
0
 public static SafeAUTHZ_CLIENT_CONTEXT_HANDLE GetTokenAuthContext(SafeAUTHZ_RESOURCE_MANAGER_HANDLE hRM)
 {
     using SafeHTOKEN hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_QUERY);
     Assert.That(AuthzInitializeContextFromToken(0, hTok, hRM, IntPtr.Zero, new LUID(), IntPtr.Zero, out SafeAUTHZ_CLIENT_CONTEXT_HANDLE hCtx), ResultIs.Successful);
     Assert.That(!hCtx.IsInvalid);
     return(hCtx);
 }
Exemplo n.º 5
0
 /// <summary>Gets the privileges for this process.</summary>
 /// <param name="process">The process.</param>
 /// <returns>
 /// An enumeration of <see cref="PrivilegeAndAttributes"/> instances that include the process privileges and their associated attributes (enabled,
 /// disabled, removed, etc.).
 /// </returns>
 public static IEnumerable <PrivilegeAndAttributes> GetPrivileges(this Process process)
 {
     using (var hObj = SafeHTOKEN.FromProcess(process, TokenAccess.TOKEN_QUERY | TokenAccess.TOKEN_DUPLICATE))
     {
         return(hObj.GetPrivileges().Select(la => new PrivilegeAndAttributes(la.Luid.GetPrivilege(process.MachineName), la.Attributes)));
     }
 }
Exemplo n.º 6
0
 public void DuplicateTokenExTest()
 {
     using (var tok = SafeHTOKEN.FromThread(GetCurrentThread()))
     {
         Assert.That(tok.IsInvalid, Is.False);
     }
 }
Exemplo n.º 7
0
        private static int Main(string[] args)
        {
            try
            {
                //
                // obtain current process token
                //
                using var hToken = SafeHTOKEN.FromProcess(Process.GetCurrentProcess(), TokenAccess.TOKEN_QUERY);

                // obtain user identified by current process' access token
                //
                // Vanara Note: since the SID value of SID_AND_ATTRIBUTES is allocated in memory, you need to get the memory allocation and then
                // pull the SID value before destroying the memory
                //
                using var ptgUser = hToken.GetInfo(TOKEN_INFORMATION_CLASS.TokenUser);

                //
                // obtain the textual representaion of the Sid
                //
                var szTextualSid = GetTextualSid(ptgUser.ToStructure <TOKEN_USER>().User.Sid);

                // display the TextualSid representation
                Console.WriteLine($"Process Sid: {szTextualSid}");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(1);
            }
        }
Exemplo n.º 8
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 an exception if it is called on systems prior to Windows Vista.
        /// </summary>
        /// <returns>Returns the integrity level of the current process.</returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception with the last error code.
        /// </exception>
        /// <exception cref="System.ArgumentNullException"><paramref name="p"/> must be a valid <see cref="Process"/>.</exception>
        public static ProcessIntegrityLevel GetIntegrityLevel(this Process p)
        {
            if (p == null)
            {
                throw new ArgumentNullException(nameof(p));
            }

            // Open the access token of the current process with TOKEN_QUERY.
            var hObject = SafeHTOKEN.FromProcess(p, TokenAccess.TOKEN_QUERY | TokenAccess.TOKEN_DUPLICATE);

            // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object.
            var tokenIL = hObject.GetInfo <TOKEN_MANDATORY_LABEL>(TOKEN_INFORMATION_CLASS.TokenIntegrityLevel);

            // 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.
            switch (GetSidSubAuthority(tokenIL.Label.Sid, 0))
            {
            case 0:
                return(ProcessIntegrityLevel.Untrusted);

            case 0x1000:
                return(ProcessIntegrityLevel.Low);

            case var iVal when iVal >= 0x2000 && iVal < 0x3000:
                return(ProcessIntegrityLevel.Medium);

            case var iVal when iVal >= 0x4000:
                return(ProcessIntegrityLevel.System);

            case var iVal when iVal >= 0x3000:
                return(ProcessIntegrityLevel.High);

            default:
                return(ProcessIntegrityLevel.Undefined);
            }
        }
Exemplo n.º 9
0
        public void DuplicateTokenTest()
        {
            var pval = SafeHTOKEN.FromProcess(System.Diagnostics.Process.GetCurrentProcess());

            Assert.That(pval.IsInvalid, Is.False);
            Assert.That(DuplicateToken(pval, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, out var dtok));
            Assert.That(dtok.IsInvalid, Is.False);
        }
Exemplo n.º 10
0
 public static bool HasPrivileges(this SafeHTOKEN hObj, bool requireAll, params SystemPrivilege[] privs)
 {
     if (!PrivilegeCheck(hObj, new PRIVILEGE_SET((PrivilegeSetControl)(requireAll ? 1 : 0), privs.Select(p => new LUID_AND_ATTRIBUTES(p.GetLUID(), PrivilegeAttributes.SE_PRIVILEGE_ENABLED)).ToArray()), out bool ret))
     {
         Win32Error.ThrowLastError();
     }
     return(ret);
 }
Exemplo n.º 11
0
        public void AuditComputeEffectivePolicyByTokenTest()
        {
            using var identity = WindowsIdentity.GetCurrent();

            using var hTok = new SafeHTOKEN(identity.Token);

            Assert.That(AuditComputeEffectivePolicyByToken(hTok, new[] { regAudit }), Is.Not.Empty);
        }
Exemplo n.º 12
0
 /// <summary>Adjusts the specified privileges on a security token to have the supplied attributes.</summary>
 /// <param name="hObj">The security token object.</param>
 /// <param name="privileges">The privileges to change.</param>
 /// <returns>The privious privileges.</returns>
 public static TOKEN_PRIVILEGES AdjustPrivileges(this SafeHTOKEN hObj, params PrivilegeAndAttributes[] privileges)
 {
     if (privileges == null || privileges.Length == 0)
     {
         throw new ArgumentNullException(nameof(privileges));
     }
     return(AdjustPrivileges(hObj, new TOKEN_PRIVILEGES(privileges.Select(pa => new LUID_AND_ATTRIBUTES(pa.Privilege.GetLUID(), pa.Attributes)).ToArray())));
 }
Exemplo n.º 13
0
 public ElevPriv(string[] privs, HPROCESS hProc = default, TokenAccess access = TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_QUERY)
 {
     if (hProc.IsNull)
     {
         hProc = GetCurrentProcess();
     }
     tok = SafeHTOKEN.FromProcess(hProc, access);
     ElevatePrivileges(privs);
 }
Exemplo n.º 14
0
 public void AccessCheckByTypeAndAuditAlarmTest()
 {
     using (var pSD = AdvApi32Tests.GetSD(AdvApi32Tests.fn, siNoSacl))
         using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_IMPERSONATE | TokenAccess.TOKEN_DUPLICATE | TokenAccess.TOKEN_READ).Duplicate(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation))
         {
             var         gm         = GENERIC_MAPPING.GenericFileMapping;
             ACCESS_MASK accessMask = ACCESS_MASK.GENERIC_READ;
             MapGenericMask(ref accessMask, gm);
             var otl = new[] { new OBJECT_TYPE_LIST(ObjectTypeListLevel.ACCESS_OBJECT_GUID) };
             Assert.That(AccessCheckByTypeAndAuditAlarm(subSys, default, objType, null, pSD, pCurSid, accessMask, AUDIT_EVENT_TYPE.AuditEventObjectAccess,
Exemplo n.º 15
0
 public static void AdjustPrivileges(this SafeHTOKEN hObj, SafeAllocatedMemoryHandle privileges)
 {
     if (privileges == null || privileges.IsInvalid)
     {
         return;
     }
     if (!AdjustTokenPrivileges(hObj, false, privileges))
     {
         throw new Win32Exception();
     }
 }
Exemplo n.º 16
0
 /// <summary>Determines whether the specified process is elevated.</summary>
 /// <param name="process">The process. If this value is <c>null</c>, then the current process is used.</param>
 /// <returns><c>true</c> if the specified process is elevated; otherwise, <c>false</c>.</returns>
 public static bool IsElevated(Process process = null)
 {
     try
     {
         // Open the access token of the current process with TOKEN_QUERY.
         using (var hObject = SafeHTOKEN.FromProcess(process ?? Process.GetCurrentProcess(), TokenAccess.TOKEN_QUERY | TokenAccess.TOKEN_DUPLICATE))
             return(hObject.IsElevated);
     }
     catch { }
     return(false);
 }
Exemplo n.º 17
0
 public static void AdjustPrivileges(this SafeHTOKEN hObj, PTOKEN_PRIVILEGES privileges)
 {
     if (privileges == null)
     {
         return;
     }
     if (!AdjustTokenPrivileges(hObj, false, privileges))
     {
         throw new Win32Exception();
     }
 }
Exemplo n.º 18
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 an exception if it is called on systems prior to Windows Vista.
        /// </summary>
        /// <returns>Returns the integrity level of the current process.</returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception with the last error code.
        /// </exception>
        /// <exception cref="System.ArgumentNullException"><paramref name="p"/> must be a valid <see cref="Process"/>.</exception>
        public static MANDATORY_LEVEL GetIntegrityLevel(this Process p)
        {
            if (p == null)
            {
                throw new ArgumentNullException(nameof(p));
            }

            // Open the access token of the current process with TOKEN_QUERY.
            using var hObject = SafeHTOKEN.FromProcess(p, TokenAccess.TOKEN_QUERY | TokenAccess.TOKEN_DUPLICATE);
            return(((HTOKEN)hObject).GetIntegrityLevel());
        }
Exemplo n.º 19
0
 public void AppPolicyGetTest()
 {
     using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_ALL_ACCESS))
     {
         Assert.That(AppPolicyGetCreateFileAccess(hTok, out var fileAccess), Is.EqualTo((Win32Error)0));
         Assert.That(AppPolicyGetProcessTerminationMethod(hTok, out var termMeth), Is.EqualTo((Win32Error)0));
         Assert.That(AppPolicyGetShowDeveloperDiagnostic(hTok, out var diag), Is.EqualTo((Win32Error)0));
         Assert.That(AppPolicyGetThreadInitializationType(hTok, out var iType), Is.EqualTo((Win32Error)0));
         TestContext.WriteLine($"File:{fileAccess}; TermMeth:{termMeth}; DevDiag:{diag}; InitType:{iType}");
     }
 }
Exemplo n.º 20
0
        public static SafeCoTaskMemHandle AdjustPrivilege(this SafeHTOKEN hObj, SystemPrivilege priv, PrivilegeAttributes attr)
        {
            var newState  = new PTOKEN_PRIVILEGES(priv.GetLUID(), attr);
            var prevState = PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();

            if (!AdjustTokenPrivileges(hObj, false, newState, (uint)prevState.Size, prevState, out var retLen))
            {
                throw new Win32Exception();
            }
            prevState.Size = (int)retLen;
            return(prevState);
        }
Exemplo n.º 21
0
        public void CreateEnvironmentBlockTest_And_DestroyEnvironmentBlockTest()
        {
            using var hToken = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_IMPERSONATE | TokenAccess.TOKEN_DUPLICATE | TokenAccess.TOKEN_READ);
            Assert.That(hToken.IsInvalid, Is.False);

            Assert.That(CreateEnvironmentBlock(out string[] environmentBlock, hToken, false), ResultIs.Successful);
            Assert.That(environmentBlock, Is.Not.Empty);

            // Validate same environment variables count as .NET method
            // Assert.That(Environment.GetEnvironmentVariables().Count, Is.EqualTo(environmentBlock.Length));
            TestContext.Write(string.Join("\r\n", environmentBlock));
        }
Exemplo n.º 22
0
        public void AdjustTokenPrivilegesTest()
        {
            using (var t = SafeHTOKEN.FromThread(SafeHTHREAD.Current, TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_QUERY))
            {
                Assert.That(LookupPrivilegeValue(null, "SeShutdownPrivilege", out var luid));
                var ptp = new PTOKEN_PRIVILEGES(luid, PrivilegeAttributes.SE_PRIVILEGE_ENABLED);
                var old = PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();
                Assert.That(AdjustTokenPrivileges(t, false, ptp, (uint)old.Size, old, out var rLen));

                Assert.That(AdjustTokenPrivileges(t, false, ptp));
            }
        }
Exemplo n.º 23
0
        /****************************************************************************++
         *
         * Description :
         *
         * This function creates a well known sid using User domain. CreateWellKnownSid requires
         * domain sid to be provided to generate such sids. This function first gets the domain sid
         * out of the user information in the token and then generate a well known sid.
         *
         * Arguments:
         *
         * hToken - [supplies] The token for which sid has to be generated
         * sidType - [supplies] The type of well known sid
         * pSid - [receives] The newly create sid
         * pdwSidSize - [Supplies/Receives] The size of the memory allocated for ppSid
         *
         * Returns:
         *
         * Errors returned by GetTokenInformation
         * Errors returned by CreateWellKnownSid
         * E_OUTOFMEMORY In case there is not enough memory
         * Errors returned by GetWindowsAccountDomainSid
         * --***************************************************************************/
        static SafePSID CreateWellKnownSidForAccount(HTOKEN hToken, WELL_KNOWN_SID_TYPE sidType)
        {
            var hTok = new SafeHTOKEN((IntPtr)hToken, false);

            using var pUserToken = hTok.GetInfo(TOKEN_INFORMATION_CLASS.TokenUser);

            //
            // Now get the domain sid from the TokenUser
            //
            Win32Error.ThrowLastErrorIfFalse(GetWindowsAccountDomainSid(pUserToken.ToStructure <TOKEN_USER>().User.Sid, out var pDomainSid));

            return(SafePSID.CreateWellKnown(sidType, pDomainSid));
        }
Exemplo n.º 24
0
        public static void AdjustPrivileges(this SafeHTOKEN hObj, PTOKEN_PRIVILEGES privileges)
        {
            if (privileges == null)
            {
                return;
            }
            uint retLen = 0;

            if (!AdjustTokenPrivileges(hObj, false, privileges, (uint)privileges.SizeInBytes, null, ref retLen))
            {
                throw new Win32Exception();
            }
        }
Exemplo n.º 25
0
        public static void AdjustPrivileges(this SafeHTOKEN hObj, SafeCoTaskMemHandle privileges)
        {
            if (privileges == null || privileges.IsInvalid)
            {
                return;
            }
            uint retLen = 0;

            if (!AdjustTokenPrivileges(hObj, false, privileges, (uint)privileges.Size, SafeCoTaskMemHandle.Null, ref retLen))
            {
                throw new Win32Exception();
            }
        }
Exemplo n.º 26
0
 public static SafeAUTHZ_CLIENT_CONTEXT_HANDLE GetTokenAuthContext(SafeAUTHZ_RESOURCE_MANAGER_HANDLE hRM)
 {
     using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_QUERY))
     {
         var b = AuthzInitializeContextFromToken(0, hTok, hRM, IntPtr.Zero, new LUID(), IntPtr.Zero, out var hCtx);
         if (!b)
         {
             TestContext.WriteLine($"AuthzAccessCheck:{Win32Error.GetLastError()}");
         }
         Assert.That(b);
         Assert.That(!hCtx.IsInvalid);
         return(hCtx);
     }
 }
Exemplo n.º 27
0
        public void AdjustTokenPrivilegesTest()
        {
            using (var t = SafeHTOKEN.FromThread(GetCurrentThread(), TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_QUERY))
            {
                Assert.That(LookupPrivilegeValue(null, "SeShutdownPrivilege", out var luid));
                var ptp  = new PTOKEN_PRIVILEGES(luid, PrivilegeAttributes.SE_PRIVILEGE_ENABLED);
                var old  = PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();
                var rLen = (uint)old.Size;
                Assert.That(AdjustTokenPrivileges(t, false, ptp, ptp.SizeInBytes, old, ref rLen));

                rLen = 0U;
                Assert.That(AdjustTokenPrivileges(t, false, ptp, ptp.SizeInBytes, SafeCoTaskMemHandle.Null, ref rLen));
            }
        }
Exemplo n.º 28
0
 public void AccessCheckByTypeResultListTest()
 {
     using (var pSD = AdvApi32Tests.GetSD(AdvApi32Tests.fn, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION))
         using (var hTok = SafeHTOKEN.FromProcess(GetCurrentProcess(), TokenAccess.TOKEN_IMPERSONATE | TokenAccess.TOKEN_DUPLICATE | TokenAccess.TOKEN_READ).Duplicate(SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation))
         {
             var         ps         = PRIVILEGE_SET.InitializeWithCapacity(100);
             var         psSz       = ps.SizeInBytes;
             var         gm         = GENERIC_MAPPING.GenericFileMapping;
             ACCESS_MASK accessMask = ACCESS_MASK.GENERIC_READ;
             MapGenericMask(ref accessMask, gm);
             var otl    = new[] { new OBJECT_TYPE_LIST(ObjectTypeListLevel.ACCESS_OBJECT_GUID) };
             var access = new uint[otl.Length];
             var status = new uint[otl.Length];
             Assert.That(AccessCheckByTypeResultList(pSD, default, hTok, accessMask, otl, (uint)otl.Length, gm, ps, ref psSz, access, status), ResultIs.Successful);
Exemplo n.º 29
0
        public static SafeCoTaskMemHandle AdjustPrivileges(this SafeHTOKEN hObj, params PrivilegeAndAttributes[] privileges)
        {
            if (privileges == null || privileges.Length == 0)
            {
                return(SafeCoTaskMemHandle.Null);
            }
            var newState  = new PTOKEN_PRIVILEGES(privileges.Select(pa => new LUID_AND_ATTRIBUTES(pa.Privilege.GetLUID(), pa.Attributes)).ToArray());
            var prevState = PTOKEN_PRIVILEGES.GetAllocatedAndEmptyInstance();

            if (!AdjustTokenPrivileges(hObj, false, newState, (uint)prevState.Size, prevState, out var retLen))
            {
                throw new Win32Exception();
            }
            prevState.Size = (int)retLen;
            return(prevState);
        }
Exemplo n.º 30
0
        /// <summary>
        /// The function gets the elevation information of the current process. It dictates whether the process is elevated or not. Token elevation is only
        /// available on Windows Vista and newer operating systems, thus IsProcessElevated throws a C++ exception if it is called on systems prior to Windows
        /// Vista. It is not appropriate to use this function to determine whether a process is run as administrator.
        /// </summary>
        /// <returns>Returns true if the process is elevated. Returns false if it is not.</returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception with the last error code.
        /// </exception>
        /// <exception cref="System.ArgumentNullException"><paramref name="p"/> must be a valid <see cref="Process"/>.</exception>
        /// <remarks>
        /// TOKEN_INFORMATION_CLASS provides TokenElevationType to check the elevation type (TokenElevationTypeDefault / TokenElevationTypeLimited /
        /// TokenElevationTypeFull) of the process. It is different from TokenElevation in that, when UAC is turned off, elevation type always returns
        /// TokenElevationTypeDefault even though the process is elevated (Integrity Level == High). In other words, it is not safe to say if the process is
        /// elevated based on elevation type. Instead, we should use TokenElevation.
        /// </remarks>
        public static bool IsElevated(this Process p)
        {
            if (p == null)
            {
                throw new ArgumentNullException(nameof(p));
            }

            try
            {
                // Open the access token of the current process with TOKEN_QUERY.
                using (var hObject = SafeHTOKEN.FromProcess(p, TokenAccess.TOKEN_QUERY | TokenAccess.TOKEN_DUPLICATE))
                    return(hObject.IsElevated);
            }
            catch { }
            return(false);
        }