// // Wrapper around avdapi32.GetWindowsAccountDomainSid // internal static int GetWindowsAccountDomainSid( SecurityIdentifier sid, out SecurityIdentifier?resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength; byte[] resultSidBinary = new byte[sidLength]; if (FALSE != Interop.Advapi32.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength)) { resultSid = new SecurityIdentifier(resultSidBinary, 0); return(Interop.Errors.ERROR_SUCCESS); } else { resultSid = null; return(Marshal.GetLastPInvokeError()); } }
// // Wrapper around advapi32.CreateWellKnownSid // internal static int CreateWellKnownSid( WellKnownSidType sidType, SecurityIdentifier?domainSid, out byte[]?resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // uint length = (uint)SecurityIdentifier.MaxBinaryLength; resultSid = new byte[length]; if (FALSE != Interop.Advapi32.CreateWellKnownSid((int)sidType, domainSid?.BinaryForm, resultSid, ref length)) { return(Interop.Errors.ERROR_SUCCESS); } else { resultSid = null; return(Marshal.GetLastPInvokeError()); } }
private void CreateFromParts(ControlFlags flags, SecurityIdentifier?owner, SecurityIdentifier?group, RawAcl?systemAcl, RawAcl?discretionaryAcl) { SetFlags(flags); Owner = owner; Group = group; SystemAcl = systemAcl; DiscretionaryAcl = discretionaryAcl; ResourceManagerControl = 0; }
public bool IsAccountSid() { if (!_accountDomainSidInitialized) { _accountDomainSid = GetAccountDomainSid(); _accountDomainSidInitialized = true; } if (_accountDomainSid == null) { return(false); } return(true); }
/// <summary> /// Generic generate method. This method should be used carefully as some parameters are not required and /// some parameters mean different things for different security types /// </summary> private static SecurityIdentifier Generate(DateTime date, string symbol, SecurityType securityType, string market, decimal strike = 0, OptionRight optionRight = 0, OptionStyle optionStyle = 0, SecurityIdentifier?underlying = null, bool forceSymbolToUpper = true) { if ((ulong)securityType >= SecurityTypeWidth || securityType < 0) { throw new ArgumentOutOfRangeException(nameof(securityType), "securityType must be between 0 and 99"); } if ((int)optionRight > 1 || optionRight < 0) { throw new ArgumentOutOfRangeException(nameof(optionRight), "optionType must be either 0 or 1"); } // normalize input strings market = market.ToLowerInvariant(); symbol = forceSymbolToUpper ? symbol.LazyToUpper() : symbol; var marketIdentifier = QuantConnect.Market.Encode(market); if (!marketIdentifier.HasValue) { throw new ArgumentOutOfRangeException(nameof(market), "The specified market wasn't found in the markets lookup. " + $"Requested: {market}. You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)" ); } var days = (ulong)date.ToOADate() * DaysOffset; var marketCode = (ulong)marketIdentifier * MarketOffset; ulong strikeScale; var strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset; strikeScale *= StrikeScaleOffset; var style = (ulong)optionStyle * OptionStyleOffset; var putcall = (ulong)optionRight * PutCallOffset; var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType; return(new SecurityIdentifier(symbol, otherData, underlying ?? Empty)); }
private void ValidateRemotePipeUser() { if (!IsCurrentUserOnly) { return; } PipeSecurity accessControl = this.GetAccessControl(); IdentityReference?remoteOwnerSid = accessControl.GetOwner(typeof(SecurityIdentifier)); using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent()) { SecurityIdentifier?currentUserSid = currentIdentity.Owner; if (remoteOwnerSid != currentUserSid) { State = PipeState.Closed; throw new UnauthorizedAccessException(SR.UnauthorizedAccess_NotOwnedByCurrentUser); } } }
public int CompareTo(SecurityIdentifier?sid) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } if (this.IdentifierAuthority < sid.IdentifierAuthority) { return(-1); } if (this.IdentifierAuthority > sid.IdentifierAuthority) { return(1); } if (this.SubAuthorityCount < sid.SubAuthorityCount) { return(-1); } if (this.SubAuthorityCount > sid.SubAuthorityCount) { return(1); } for (int i = 0; i < this.SubAuthorityCount; i++) { int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i); if (diff != 0) { return(diff); } } return(0); }
private CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier?owner, SecurityIdentifier?group, RawAcl?systemAcl, RawAcl?discretionaryAcl) : this(isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl)) { }
// // Creates a security descriptor explicitly // public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier?owner, SecurityIdentifier?group, SystemAcl?systemAcl, DiscretionaryAcl?discretionaryAcl) { CreateFromParts(isContainer, isDS, flags, owner, group, systemAcl, discretionaryAcl); }
private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier?owner, SecurityIdentifier?group, SystemAcl?systemAcl, DiscretionaryAcl?discretionaryAcl) { if (systemAcl != null && systemAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsContainer != isContainer) { throw new ArgumentException( isContainer ? SR.AccessControl_MustSpecifyContainerAcl : SR.AccessControl_MustSpecifyLeafObjectAcl, nameof(discretionaryAcl)); } _isContainer = isContainer; if (systemAcl != null && systemAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(systemAcl)); } if (discretionaryAcl != null && discretionaryAcl.IsDS != isDS) { throw new ArgumentException( isDS ? SR.AccessControl_MustSpecifyDirectoryObjectAcl : SR.AccessControl_MustSpecifyNonDirectoryObjectAcl, nameof(discretionaryAcl)); } _isDS = isDS; _sacl = systemAcl; // // Replace null DACL with an allow-all for everyone DACL // // // to conform to native behavior, we will add allow everyone ace for DACL // discretionaryAcl ??= DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer); _dacl = discretionaryAcl; // // DACL is never null. So always set the flag bit on // ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent; // // Keep SACL and the flag bit in sync. // if (systemAcl == null) { unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); } } else { actualFlags |= (ControlFlags.SystemAclPresent); } _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl?.RawAcl, discretionaryAcl.RawAcl); }
// // Creates a security descriptor explicitly // public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier?owner, SecurityIdentifier?group, RawAcl?systemAcl, RawAcl?discretionaryAcl) : base() { CreateFromParts(flags, owner, group, systemAcl, discretionaryAcl); }
// // Constructs a well-known SID // The 'domainSid' parameter is optional and only used // by the well-known types that require it // NOTE: although there is a P/Invoke call involved in the implementation of this constructor, // there is no security risk involved, so no security demand is being made. // public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier?domainSid) { // // sidType must not be equal to LogonIdsSid // if (sidType == WellKnownSidType.LogonIdsSid) { throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType)); } // // sidType should not exceed the max defined value // if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.WinCapabilityRemovableStorageSid)) { throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType)); } // // for sidType between 38 to 50, the domainSid parameter must be specified // int error; if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid)) { if (domainSid == null) { throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType)); } // // verify that the domain sid is a valid windows domain sid // to do that we call GetAccountDomainSid and the return value should be the same as the domainSid // error = Win32.GetWindowsAccountDomainSid(domainSid, out SecurityIdentifier? resultDomainSid); if (error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) { throw new OutOfMemoryException(); } else if (error == Interop.Errors.ERROR_NON_ACCOUNT_SID) { // this means that the domain sid is not valid throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } else if (error != Interop.Errors.ERROR_SUCCESS) { Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {error}"); throw new Win32Exception(error); } // // if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid // Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities) // if (resultDomainSid != domainSid) { throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid)); } } error = Win32.CreateWellKnownSid(sidType, domainSid, out byte[]? resultSid); if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { #pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used throw new ArgumentException(new Win32Exception(error).Message, "sidType/domainSid"); #pragma warning restore CS2208 } else if (error != Interop.Errors.ERROR_SUCCESS) { Debug.Fail($"Win32.CreateWellKnownSid returned unrecognized error {error}"); throw new Win32Exception(error); } CreateFromBinaryForm(resultSid !, 0); }
// // Attempts to persist the security descriptor onto the object // private void Persist(string?name, SafeHandle?handle, AccessControlSections includeSections, object?exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier?owner = null, group = null; SystemAcl? sacl = null; DiscretionaryAcl? dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl !.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = unchecked ((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl)); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception?exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Fail($"Unexpected error code {error}"); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; }
// // Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo // internal static int SetSecurityInfo( ResourceType type, string?name, SafeHandle?handle, SecurityInfos securityInformation, SecurityIdentifier?owner, SecurityIdentifier?group, GenericAcl?sacl, GenericAcl?dacl) { int errorCode; int Length; byte[]? OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null; Privilege?securityPrivilege = null; if (owner != null) { Length = owner.BinaryLength; OwnerBinary = new byte[Length]; owner.GetBinaryForm(OwnerBinary, 0); } if (group != null) { Length = group.BinaryLength; GroupBinary = new byte[Length]; group.GetBinaryForm(GroupBinary, 0); } if (dacl != null) { Length = dacl.BinaryLength; DaclBinary = new byte[Length]; dacl.GetBinaryForm(DaclBinary, 0); } if (sacl != null) { Length = sacl.BinaryLength; SaclBinary = new byte[Length]; sacl.GetBinaryForm(SaclBinary, 0); } if ((securityInformation & SecurityInfos.SystemAcl) != 0) { // // Enable security privilege if trying to set a SACL. // Note: even setting it by handle needs this privilege enabled! // securityPrivilege = new Privilege(Privilege.Security); } try { if (securityPrivilege != null) { try { securityPrivilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } if (name != null) { errorCode = (int)Interop.Advapi32.SetSecurityInfoByName(name, (uint)type, unchecked ((uint)securityInformation), OwnerBinary, GroupBinary, DaclBinary, SaclBinary); } else if (handle != null) { if (handle.IsInvalid) { throw new ArgumentException( SR.Argument_InvalidSafeHandle, nameof(handle)); } else { errorCode = (int)Interop.Advapi32.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary); } } else { // both are null, shouldn't happen Debug.Fail("Internal error: both name and handle are null"); throw new ArgumentException(); } if (errorCode == Interop.Errors.ERROR_NOT_ALL_ASSIGNED || errorCode == Interop.Errors.ERROR_PRIVILEGE_NOT_HELD) { throw new PrivilegeNotHeldException(Privilege.Security); } else if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED || errorCode == Interop.Errors.ERROR_CANT_OPEN_ANONYMOUS) { throw new UnauthorizedAccessException(); } else if (errorCode != Interop.Errors.ERROR_SUCCESS) { goto Error; } } catch { // protection against exception filter-based luring attacks if (securityPrivilege != null) { securityPrivilege.Revert(); } throw; } finally { if (securityPrivilege != null) { securityPrivilege.Revert(); } } return(0); Error: if (errorCode == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } return(errorCode); }