/// <summary> /// Gets a list of the principal's token groups /// </summary> /// <returns>A list of security identifiers representing the groups present in the principal's security token</returns> public IEnumerable <SecurityIdentifier> GetTokenGroups() { uint sizeRequired = 0; if (!NativeMethods.AuthzGetInformationFromContext(this.authzContext, AuthzContextInformationClass.AuthzContextInfoGroupsSids, sizeRequired, out sizeRequired, IntPtr.Zero)) { Win32Exception e = new Win32Exception(Marshal.GetLastWin32Error()); if (e.NativeErrorCode != NativeMethods.InsufficientBuffer) { throw new AuthorizationContextException("AuthzGetInformationFromContext failed", e); } } SafeAllocHGlobalHandle structure = new SafeAllocHGlobalHandle(sizeRequired); IntPtr pstructure = structure.DangerousGetHandle(); if (!NativeMethods.AuthzGetInformationFromContext(this.authzContext, AuthzContextInformationClass.AuthzContextInfoGroupsSids, sizeRequired, out sizeRequired, pstructure)) { throw new AuthorizationContextException("AuthzGetInformationFromContext failed", new Win32Exception(Marshal.GetLastWin32Error())); } TokenGroups groups = Marshal.PtrToStructure <TokenGroups>(pstructure); IntPtr current = IntPtr.Add(pstructure, Marshal.OffsetOf <TokenGroups>(nameof(groups.Groups)).ToInt32()); for (int i = 0; i < groups.GroupCount; i++) { SidAndAttributes sidAndAttributes = (SidAndAttributes)Marshal.PtrToStructure(current, typeof(SidAndAttributes)); yield return(new SecurityIdentifier(sidAndAttributes.Sid)); current = IntPtr.Add(current, Marshal.SizeOf(typeof(SidAndAttributes))); } }
/// <summary> /// Return a list of Windows 8 app container configuration settings. /// </summary> private static List <SidAndAttributes> PINetworkIsolationGetAppContainerConfig() { IntPtr arrayValue = IntPtr.Zero; uint size = 0; List <SidAndAttributes> myCapabilities = new List <SidAndAttributes>(); GCHandle handlePdwCntPublicACs = GCHandle.Alloc(size, GCHandleType.Pinned); GCHandle handlePpACs = GCHandle.Alloc(arrayValue, GCHandleType.Pinned); uint retVal = NetworkIsolationGetAppContainerConfig(out size, out arrayValue); int structSize = Marshal.SizeOf(typeof(SidAndAttributes)); for (var i = 0; i < size; i++) { SidAndAttributes currentSidAndAttributes = (SidAndAttributes)Marshal.PtrToStructure(arrayValue, typeof(SidAndAttributes)); myCapabilities.Add(currentSidAndAttributes); arrayValue = new IntPtr((long)(arrayValue) + (long)(structSize)); } handlePdwCntPublicACs.Free(); handlePpACs.Free(); return(myCapabilities); }
/// <summary> /// Enable Windows 8 Mail loopback exemptions. /// </summary> public void EnableWindows8MailLoopback() { // Loop through and enable loopbacks for any Windows 8 Mail applications. for (int i = 0; i < Apps.Count; i++) { // Strings relevant to the Windows 8 Mail app. if (Apps[i].AppContainerName.Contains("microsoft.windowscommunicationsapps_") || Apps[i].AppContainerName.Contains("microsoft.winjs.")) { Apps[i].LoopbackEnabled = true; } } // Count the number of exemptions. int countEnabled = Apps.Where(_ => _.LoopbackEnabled == true).Count(); SidAndAttributes[] sidAndAttributesArray = new SidAndAttributes[countEnabled]; int count = 0; // Save our exemptions. for (int i = 0; i < Apps.Count; i++) { if (Apps[i].LoopbackEnabled) { sidAndAttributesArray[count].Attributes = 0; IntPtr ptr; ConvertStringSidToSid(Apps[i].StringSid, out ptr); sidAndAttributesArray[count].Sid = ptr; count++; } } NetworkIsolationSetAppContainerConfig((uint)countEnabled, sidAndAttributesArray); // Free our app container handles. NetworkIsolationFreeAppContainers(ACs); }
/// <summary> /// Get list of groups for the AuthZ context. /// </summary> /// <param name="group_type">The group type.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The list of groups.</returns> public NtResult <UserGroup[]> GetGroups(AuthZGroupSidType group_type, bool throw_on_error) { using (var buffer = QueryBuffer <TokenGroups>(SidTypeToInfoClass(group_type), throw_on_error)) { return(buffer.Map(groups => { TokenGroups result = groups.Result; SidAndAttributes[] sids = new SidAndAttributes[result.GroupCount]; groups.Data.ReadArray(0, sids, 0, result.GroupCount); return sids.Select(s => s.ToUserGroup()).ToArray(); } )); } }
public void CreateRestrictedToken_Process() { using (var token = Security.OpenProcessToken(AccessTokenRights.Duplicate | AccessTokenRights.Query)) { SidAndAttributes info = token.GetTokenUserSid(); info.Sid.IsValidSid().Should().BeTrue(); info.Attributes.Should().NotHaveFlag(SidAttributes.UseForDenyOnly); using (var restricted = token.CreateRestrictedToken(info.Sid)) { restricted.IsInvalid.Should().BeFalse(); info = restricted.GetTokenUserSid(); info.Attributes.Should().HaveFlag(SidAttributes.UseForDenyOnly); info.Sid.IsValidSid().Should().BeTrue(); restricted.GetTokenStatistics().TokenType.Should().Be(TokenType.Primary); } } }
/// <summary> /// Return a list of capabilities of a Windows 8 application. /// </summary> private static List <SidAndAttributes> GetCapabilites(InetFirewallAcCapabilities cap) { List <SidAndAttributes> myCapabilities = new List <SidAndAttributes>(); IntPtr arrayValue = cap.Capabilities; int structSize = Marshal.SizeOf(typeof(SidAndAttributes)); for (var i = 0; i < cap.Count; i++) { SidAndAttributes currentSidAndAttributes = (SidAndAttributes)Marshal.PtrToStructure(arrayValue, typeof(SidAndAttributes)); myCapabilities.Add(currentSidAndAttributes); arrayValue = new IntPtr((long)(arrayValue) + (long)(structSize)); } return(myCapabilities); }
public unsafe SidAndAttributes[] GetGroupsTokenInformation(TokenInformationClass tokenInformationClass) { if (tokenInformationClass != TokenInformationClass.TokenGroups && tokenInformationClass != TokenInformationClass.TokenRestrictedSids && tokenInformationClass != TokenInformationClass.TokenLogonSid && tokenInformationClass != TokenInformationClass.TokenCapabilities && tokenInformationClass != TokenInformationClass.TokenDeviceGroups && tokenInformationClass != TokenInformationClass.TokenRestrictedDeviceGroups) { throw new ArgumentException(string.Format("{0} is not a valid Group token information class", tokenInformationClass), "tokenInformationClass"); } int tokenSize; if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, IntPtr.Zero, 0, out tokenSize) && Marshal.GetLastWin32Error() != (int)SystemErrorCode.ErrorInsufficientBuffer) { ErrorHelper.ThrowCustomWin32Exception(); } IntPtr tokenInformationPtr = Marshal.AllocHGlobal(tokenSize); try { if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, tokenInformationPtr, tokenSize, out tokenSize)) { ErrorHelper.ThrowCustomWin32Exception(); } var groupStructure = (NativeTokenGroups)Marshal.PtrToStructure(tokenInformationPtr, typeof(NativeTokenGroups)); IntPtr offset = Marshal.OffsetOf(typeof(NativeTokenGroups), "Groups"); var groups = new SidAndAttributes[groupStructure.GroupCount]; long start = new IntPtr(tokenInformationPtr.ToInt64() + offset.ToInt64()).ToInt64(); for (int i = 0; i < groupStructure.GroupCount; i++) { var arrayElementPtr = new IntPtr(start + i * sizeof(NativeSidAndAttributes)); var group = (NativeSidAndAttributes)Marshal.PtrToStructure(arrayElementPtr, typeof(NativeSidAndAttributes)); groups[i] = new SidAndAttributes(group.Attributes, group.Sid); } return(groups); } finally { Marshal.FreeHGlobal(tokenInformationPtr); } }
private static SidAndAttributes[] GetLoopbackContainers() { uint errorCode = NetworkIsolationGetAppContainerConfig(out uint count, out IntPtr appContainerSids); if (errorCode != 0) { throw new ExternalException("Enum loopback containers failed", (int)errorCode); } SidAndAttributes[] sdiAndAttributes = new SidAndAttributes[count]; int structSize = Marshal.SizeOf(typeof(SidAndAttributes)); for (var i = 0; i < count; i++) { sdiAndAttributes[i] = (SidAndAttributes)Marshal.PtrToStructure(appContainerSids + i * structSize, typeof(SidAndAttributes)); } return(sdiAndAttributes); }
public void ApplyLoopbackExempt() { int count = loopbackSids.Count; List <SidAndAttributes> list = new List <SidAndAttributes>(); foreach (string sid in loopbackSids) { ConvertStringSidToSid(sid, out IntPtr pSid); SidAndAttributes sdiAndAttributes = new SidAndAttributes(); sdiAndAttributes.Sid = pSid; sdiAndAttributes.Attributes = 0; list.Add(sdiAndAttributes); } uint code = NetworkIsolationSetAppContainerConfig((uint)count, list.ToArray()); if (code != 0) { throw new ExternalException("Set config failed", (int)code); } }
private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources) { int count = GetAttributeCount(); if (count == 0) { return(SafeHGlobalBuffer.Null); } var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count)); if (ParentProcess != null) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle()); } if (MitigationOptions2 != ProcessMitigationOptions2.None) { MemoryStream stm = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stm); writer.Write((ulong)MitigationOptions); writer.Write((ulong)MitigationOptions2); attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray()); } else if (MitigationOptions != ProcessMitigationOptions.None) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions); } if (Win32kFilterFlags != Win32kFilterFlags.None) { Win32kFilterAttribute filter = new Win32kFilterAttribute(); filter.Flags = Win32kFilterFlags; filter.FilterLevel = Win32kFilterLevel; attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer())); } if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel); } if (InheritHandleList.Count > 0) { int total_size = IntPtr.Size * InheritHandleList.Count; var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size)); handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count); attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeHandleList, handle_list); } if (AppContainerSid != null) { SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES(); caps.AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle(); if (Capabilities.Count > 0) { SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count]; for (int i = 0; i < Capabilities.Count; ++i) { cap_sids[i] = new SidAndAttributes() { Sid = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(), Attributes = GroupAttributes.Enabled }; } SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count)); cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length); caps.Capabilities = cap_buffer.DangerousGetHandle(); caps.CapabilityCount = cap_sids.Length; } attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps); } if (LowPrivilegeAppContainer) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1); } return(attr_list); }
private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources) { int count = GetAttributeCount(); if (count == 0) { return(SafeHGlobalBuffer.Null); } var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count)); if (ParentProcess != null) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle()); } if (MitigationOptions2 != ProcessMitigationOptions2.None) { MemoryStream stm = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stm); writer.Write((ulong)MitigationOptions); writer.Write((ulong)MitigationOptions2); attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray()); } else if (MitigationOptions != ProcessMitigationOptions.None) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions); } if (Win32kFilterFlags != Win32kFilterFlags.None) { Win32kFilterAttribute filter = new Win32kFilterAttribute { Flags = Win32kFilterFlags, FilterLevel = Win32kFilterLevel }; attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer())); } if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0 && ProtectionLevel != ProtectionLevel.None) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel); } if (InheritHandleList.Count > 0) { int total_size = IntPtr.Size * InheritHandleList.Count; var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size)); handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count); attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributeHandleList, handle_list); } if (AppContainerSid != null) { SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES { AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle() }; if (Capabilities.Count > 0) { SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count]; for (int i = 0; i < Capabilities.Count; ++i) { cap_sids[i] = new SidAndAttributes() { Sid = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(), Attributes = GroupAttributes.Enabled }; } SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count)); cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length); caps.Capabilities = cap_buffer.DangerousGetHandle(); caps.CapabilityCount = cap_sids.Length; } attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps); } if (LowPrivilegeAppContainer) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1); } if (RestrictChildProcessCreation || OverrideChildProcessCreation) { int flags = RestrictChildProcessCreation ? 1 : 0; flags |= OverrideChildProcessCreation ? 2 : 0; attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeChildProcessPolicy, flags); } if (DesktopAppBreakaway != ProcessDesktopAppBreakawayFlags.None) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeDesktopAppPolicy, (int)DesktopAppBreakaway); } if (!string.IsNullOrWhiteSpace(PackageName)) { byte[] str_bytes = Encoding.Unicode.GetBytes(PackageName); var string_buffer = resources.AddResource(new SafeHGlobalBuffer(str_bytes)); attr_list.AddAttributeBuffer(Win32ProcessAttributes.ProcThreadAttributePackageName, string_buffer); } if (PseudoConsole != IntPtr.Zero) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributePseudoConsole, PseudoConsole); } if (!string.IsNullOrEmpty(BnoIsolationPrefix)) { var prefix = new BnoIsolationAttribute() { IsolationEnabled = 1, IsolationPrefix = BnoIsolationPrefix }; attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeBnoIsolation, prefix); } if (SafeOpenPromptOriginClaim != null) { var bytes = (byte[])SafeOpenPromptOriginClaim.Clone(); Array.Resize(ref bytes, 524); attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeSafeOpenPromptOriginClaim, bytes); } if (ExtendedFlags != ProcessExtendedFlags.None) { attr_list.AddAttribute(Win32ProcessAttributes.ProcThreadAttributeExtendedFlags, (int)ExtendedFlags); } return(attr_list); }
/// <summary> /// Copies the specified SID. /// </summary> /// <param name="saa">A SID_AND_ATTRIBUTES structure.</param> public Sid(SidAndAttributes saa) : this(saa.Sid, saa.Attributes) { }
private static extern uint NetworkIsolationSetAppContainerConfig(uint pdwCntACs, SidAndAttributes[] appContainerSids);
/// <summary> /// Enable Windows 8 Mail loopback exemptions. /// </summary> public void EnableWindows8MailLoopback() { // Loop through and enable loopbacks for any Windows 8 Mail applications. for (int i = 0; i < Apps.Count; i++) { // Strings relevant to the Windows 8 Mail app. if (Apps[i].AppContainerName.Contains("microsoft.windowscommunicationsapps_") || Apps[i].AppContainerName.Contains("microsoft.winjs.")) Apps[i].LoopbackEnabled = true; } // Count the number of exemptions. int countEnabled = Apps.Where(_ => _.LoopbackEnabled == true).Count(); SidAndAttributes[] sidAndAttributesArray = new SidAndAttributes[countEnabled]; int count = 0; // Save our exemptions. for (int i = 0; i < Apps.Count; i++) { if (Apps[i].LoopbackEnabled) { sidAndAttributesArray[count].Attributes = 0; IntPtr ptr; ConvertStringSidToSid(Apps[i].StringSid, out ptr); sidAndAttributesArray[count].Sid = ptr; count++; } } NetworkIsolationSetAppContainerConfig((uint)countEnabled, sidAndAttributesArray); // Free our app container handles. NetworkIsolationFreeAppContainers(ACs); }
internal static extern bool CreateRestrictedToken( IntPtr existingTokenHandle, CreateRestrictedTokenFlags createRestrictedTokenFlags, int disableSidCount, SidAndAttributes[] sidsToDisable, int deletePrivilegeCount, LuidAndAttributes[] privilegesToDelete, int restrictedSidCount, SidAndAttributes[] sidsToRestrict, out IntPtr newTokenHandle);