// Token: 0x060000BB RID: 187 RVA: 0x0000858C File Offset: 0x0000678C private void SetActiveSyncDeviceContainerPermissions(ActiveSyncDevices container) { ADDeviceManager.ReadStaticADData(this.protocolLogger); RawSecurityDescriptor rawSecurityDescriptor = null; ADNotificationAdapter.RunADOperation(delegate() { rawSecurityDescriptor = this.session.ReadSecurityDescriptor(container.Id); }); if (rawSecurityDescriptor == null) { if (this.protocolLogger != null) { this.protocolLogger.SetValue(ProtocolLoggerData.Error, "ADObjectWithNoSecurityDescriptor"); } AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, EASServerStrings.NullNTSD(container.Id.DistinguishedName), true); throw ex; } AirSyncDiagnostics.TraceDebug <string>(this.tracer, this, "Setting ACL on device container for user \"{0}\".", this.userName); ActiveDirectorySecurity acl = new ActiveDirectorySecurity(); byte[] array = new byte[rawSecurityDescriptor.BinaryLength]; rawSecurityDescriptor.GetBinaryForm(array, 0); acl.SetSecurityDescriptorBinaryForm(array); acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.CreateChild | ActiveDirectoryRights.DeleteChild | ActiveDirectoryRights.ListChildren | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ADDeviceManager.activeSyncDeviceClass, ActiveDirectorySecurityInheritance.None)); acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.Delete | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ActiveDirectorySecurityInheritance.Children, ADDeviceManager.activeSyncDeviceClass)); ADNotificationAdapter.RunADOperation(delegate() { this.session.SaveSecurityDescriptor(container, new RawSecurityDescriptor(acl.GetSecurityDescriptorBinaryForm(), 0)); }); }
protected override void ProcessRecord() { //OU can be passed as name or as dn List <ObjectInfo> OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new Exception("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new Exception("Object not found"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Dacl); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, "computer", SchemaObjectType.Class); Guid timestampGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.schemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); //System.DirectoryServices.PropertyAccessRule rule; System.DirectoryServices.ActiveDirectoryAccessRule rule; foreach (string principalName in AllowedPrincipals) { System.Security.Principal.NTAccount principal = new System.Security.Principal.NTAccount(principalName); // read ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // write ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Write, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); } DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Dacl); OUs[0].Status = PermissionDelegationState.Delegated; WriteObject(OUs[0]); }
internal override void AdjustADSecurity(string objPath, string securityGroupPath, bool isAddressBook) { ExchangeLog.LogStart("AdjustADSecurity"); ExchangeLog.DebugInfo(" Active Direcory object: {0}", objPath); ExchangeLog.DebugInfo(" Security Group: {0}", securityGroupPath); if (isAddressBook) { ExchangeLog.DebugInfo(" Updating Security"); //"Download Address Book" security permission for offline address book Guid openAddressBookGuid = new Guid("{bd919c7c-2d79-4950-bc9c-e16fd99285e8}"); DirectoryEntry groupEntry = GetADObject(securityGroupPath); byte[] byteSid = (byte[])GetADObjectProperty(groupEntry, "objectSid"); DirectoryEntry objEntry = GetADObject(objPath); ActiveDirectorySecurity security = objEntry.ObjectSecurity; // Create a SecurityIdentifier object for security group. SecurityIdentifier groupSid = new SecurityIdentifier(byteSid, 0); // Create an access rule to allow users in Security Group to open address book. ActiveDirectoryAccessRule allowOpenAddressBook = new ActiveDirectoryAccessRule( groupSid, ActiveDirectoryRights.ExtendedRight, AccessControlType.Allow, openAddressBookGuid); // Create an access rule to allow users in Security Group to read object. ActiveDirectoryAccessRule allowRead = new ActiveDirectoryAccessRule( groupSid, ActiveDirectoryRights.GenericRead, AccessControlType.Allow); // Remove existing rules if exist security.RemoveAccessRuleSpecific(allowOpenAddressBook); security.RemoveAccessRuleSpecific(allowRead); // Add a new access rule to allow users in Security Group to open address book. security.AddAccessRule(allowOpenAddressBook); // Add a new access rule to allow users in Security Group to read object. security.AddAccessRule(allowRead); // Commit the changes. objEntry.CommitChanges(); } ExchangeLog.LogEnd("AdjustADSecurity"); }
protected void ReplaceAddressListACEs(ADObjectId addressBookContainerRoot, SecurityIdentifier originalSid, SecurityIdentifier[] replacementSids) { AddressBookBase[] array = this.configurationSession.Find <AddressBookBase>(addressBookContainerRoot, QueryScope.SubTree, null, null, 0); foreach (AddressBookBase addressBookBase in array) { bool flag = false; RawSecurityDescriptor rawSecurityDescriptor = addressBookBase.ReadSecurityDescriptor(); ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity(); byte[] array3 = new byte[rawSecurityDescriptor.BinaryLength]; rawSecurityDescriptor.GetBinaryForm(array3, 0); activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array3); AuthorizationRuleCollection accessRules = activeDirectorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier)); foreach (object obj in accessRules) { ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj; if (activeDirectoryAccessRule.IdentityReference == originalSid) { flag = true; activeDirectorySecurity.RemoveAccessRuleSpecific(activeDirectoryAccessRule); foreach (SecurityIdentifier identity in replacementSids) { ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(identity, activeDirectoryAccessRule.ActiveDirectoryRights, activeDirectoryAccessRule.AccessControlType, activeDirectoryAccessRule.ObjectType, activeDirectoryAccessRule.InheritanceType, activeDirectoryAccessRule.InheritedObjectType); activeDirectorySecurity.AddAccessRule(rule); } } } if (flag && base.ShouldProcess(addressBookBase.DistinguishedName, Strings.InfoProcessAction(addressBookBase.DistinguishedName), null)) { addressBookBase.SaveSecurityDescriptor(new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorBinaryForm(), 0)); } } }
/// <summary> /// Set the security rights on a computer object to allow users in the JoinToComputer group to join to computer objects. /// </summary> /// <param name="compName">The computer object name to set permissions on</param> /// <param name="ouContainer">The container where the computer object resides.</param> private void SetSecurityRights(string compName, string ouContainer) { string qString = "(&(name=" + compName + ")(objectClass=computer))"; ExecuteResult result = this.ExecuteSearch(qString, false, ouContainer); //TODO: add group to security var computer = result.singleResult.GetDirectoryEntry(); ActiveDirectorySecurity sdc = computer.ObjectSecurity; NTAccount Account = new NTAccount("capstone", "JoinToComputer"); SecurityIdentifier sid = (SecurityIdentifier)Account.Translate(typeof(SecurityIdentifier)); Guid userSchemaGuid = new Guid("BF967ABA-0DE6-11D0-A285-00AA003049E2"); Guid computerSchemaGuid = new Guid("bf967a86-0de6-11d0-a285-00aa003049e2"); Guid UserForceChangePassword = new Guid("00299570-246d-11d0-a768-00aa006e0529"); // ‘Reset password’ Guid dnsHostNameGuid = new Guid("72e39547-7b18-11d1-adef-00c04fd8d5cd"); // ‘Validated write to DNS host name’ Guid rwAccountRestrictions = new Guid("4c164200-20c0-11d0-a768-00aa006e0529"); // ‘Read and write account restrictions’ Guid wServicePrincipalName = new Guid("f3a64788-5306-11d1-a9c5-0000f80367c1"); // ‘Validated write to service principal name’ ActiveDirectoryAccessRule acctRestrictionsRW = new ActiveDirectoryAccessRule(Account, ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty, AccessControlType.Allow, rwAccountRestrictions, ActiveDirectorySecurityInheritance.None); sdc.AddAccessRule(acctRestrictionsRW); ActiveDirectoryAccessRule dnsHostNameEdit = new ActiveDirectoryAccessRule(Account, ActiveDirectoryRights.Self, AccessControlType.Allow, dnsHostNameGuid, ActiveDirectorySecurityInheritance.None); sdc.AddAccessRule(dnsHostNameEdit); ActiveDirectoryAccessRule valSPN = new ActiveDirectoryAccessRule(Account, ActiveDirectoryRights.Self, AccessControlType.Allow, wServicePrincipalName, ActiveDirectorySecurityInheritance.None); sdc.AddAccessRule(valSPN); ExtendedRightAccessRule erarResetPwd = new ExtendedRightAccessRule(Account, AccessControlType.Allow, UserForceChangePassword, ActiveDirectorySecurityInheritance.None, userSchemaGuid); sdc.AddAccessRule(erarResetPwd); /* may require the below line * * Guid userAccountControlGuid = GUID('bf967a68-0de6-11d0-a285-00aa003049e2'); * ActiveDirectoryAccessRule userAccountControlEdit = new ActiveDirectoryAccessRule(Account, ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty, AccessControlType.Allow, userAccountControlGuid, ActiveDirectorySecurityInheritance.None); * sdc.AddAccessRule(userAccountControlEdit); * * */ //commit and cleanup computer.CommitChanges(); computer.Close(); computer.Dispose(); }
public static ActiveDirectorySecurity SetupActiveDirectorySecurity(RawSecurityDescriptor rawSecurityDescriptor) { ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity(); byte[] array = new byte[rawSecurityDescriptor.BinaryLength]; rawSecurityDescriptor.GetBinaryForm(array, 0); activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array); SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(identity, ActiveDirectoryRights.ReadControl | ActiveDirectoryRights.ListChildren | ActiveDirectoryRights.Self | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow); activeDirectorySecurity.AddAccessRule(rule); SecurityIdentifier identity2 = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); rule = new ActiveDirectoryAccessRule(identity2, ActiveDirectoryRights.ReadControl | ActiveDirectoryRights.ListChildren | ActiveDirectoryRights.Self | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow); activeDirectorySecurity.AddAccessRule(rule); return(activeDirectorySecurity); }
public void SetTeamMailboxUserPermissions(IList <ADObjectId> usersToAdd, IList <ADObjectId> usersToRemove, SecurityIdentifier[] additionalSids, bool save = true) { ADUser aduser = (ADUser)this.TeamMailbox.DataObject; RawSecurityDescriptor exchangeSecurityDescriptor = aduser.ExchangeSecurityDescriptor; ActiveDirectorySecurity activeDirectorySecurity = SecurityDescriptorConverter.ConvertToActiveDirectorySecurity(exchangeSecurityDescriptor); if (usersToAdd != null) { foreach (ADObjectId userId in usersToAdd) { SecurityIdentifier userSid = this.GetUserSid(userId); if (userSid != null) { activeDirectorySecurity.AddAccessRule(new ActiveDirectoryAccessRule(userSid, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty)); } } } if (usersToRemove != null) { foreach (ADObjectId userId2 in usersToRemove) { SecurityIdentifier userSid2 = this.GetUserSid(userId2); if (userSid2 != null) { activeDirectorySecurity.RemoveAccessRule(new ActiveDirectoryAccessRule(userSid2, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty)); } } } if (additionalSids != null) { foreach (SecurityIdentifier identity in additionalSids) { activeDirectorySecurity.AddAccessRule(new ActiveDirectoryAccessRule(identity, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty)); } } aduser.ExchangeSecurityDescriptor = new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorBinaryForm(), 0); if (save) { this.DataSession.Save(aduser); } }
/// <summary> /// SetAccessRights method sets the particular access right for a particular user on a particualr AD Container/Object /// </summary> /// <param name="DN">The distinguished name of the Container/Object.</param> /// <param name="user">The name of the user to whom the permissions to be set</param> /// <param name="domain">The name of the domain to which user is belongs to</param> /// <param name="accessRight">The name of the access right to be set</param> /// <param name="controlType">Allow/Deny particular ActiveDirecotyRights</param> /// <returns></returns> public bool SetACLs(string DN, string user, string domain, ActiveDirectoryRights accessRight, AccessControlType controlType) { using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + DN, ConfigStore.AdminName, ConfigStore.AdminPassword, AuthenticationTypes.Secure)) { ActiveDirectorySecurity sd = entry.ObjectSecurity; NTAccount accountName = new NTAccount(domain, user); IdentityReference acctSID = accountName.Translate(typeof(SecurityIdentifier)); ActiveDirectoryAccessRule myRule = new ActiveDirectoryAccessRule(new SecurityIdentifier(acctSID.Value), accessRight, controlType); sd.AddAccessRule(myRule); entry.ObjectSecurity.AddAccessRule(myRule); entry.CommitChanges(); return(true); } }
public void UpdateSecurityDescriptor() { //point this to any object (I chose a user) DirectoryEntry entry = TestUtils.CreateDirectoryEntry( "CN=User1,OU=Users," + TestUtils.Settings.DefaultPartition); ActiveDirectorySecurity sec = entry.ObjectSecurity; ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule( new NTAccount("mydomain", "super.user"), ActiveDirectoryRights.GenericAll, AccessControlType.Allow ); sec.AddAccessRule(rule); entry.CommitChanges(); }
private static void CanonicalizeAcl(ActiveDirectorySecurity ads) { ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity(); foreach (object obj in ads.GetAccessRules(true, true, typeof(SecurityIdentifier))) { ActiveDirectoryAccessRule rule = (ActiveDirectoryAccessRule)obj; activeDirectorySecurity.AddAccessRule(rule); } RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access)); RawSecurityDescriptor rawSecurityDescriptor2 = new RawSecurityDescriptor(ads.GetSecurityDescriptorSddlForm(AccessControlSections.Access)) { DiscretionaryAcl = rawSecurityDescriptor.DiscretionaryAcl }; ads.SetSecurityDescriptorSddlForm(rawSecurityDescriptor2.GetSddlForm(AccessControlSections.Access), AccessControlSections.Access); }
public static void RemoveAccessRights(string dn, string targetUser, string Domain, string authUsername, string authPassword, ActiveDirectoryRights accessRight, AccessControlType controlType) { DirectoryEntry entry = new DirectoryEntry(dn, authUsername, authPassword, AuthenticationTypes.Secure); ActiveDirectorySecurity sd = entry.ObjectSecurity; int retryCount = 0; IdentityReference acctSID; retryRemoveAccessRight: try { NTAccount accountName = new NTAccount(Domain, targetUser); acctSID = accountName.Translate(typeof(SecurityIdentifier)); } catch (IdentityNotMappedException e) { TestClassBase.BaseTestSite.Log.Add( LogEntryKind.Comment, string.Format("Translate account name error: {0}", e.Message)); TestClassBase.BaseTestSite.Log.Add( LogEntryKind.Comment, string.Format("Wait 1 minute and retry:{0}", retryCount)); retryCount++; System.Threading.Thread.Sleep(60000); if (retryCount < 10) { goto retryRemoveAccessRight; } else { throw; } } ActiveDirectoryAccessRule myRule = new ActiveDirectoryAccessRule(new SecurityIdentifier(acctSID.Value), accessRight, controlType); sd.AddAccessRule(myRule); entry.ObjectSecurity.AddAccessRule(myRule); entry.CommitChanges(); }
static void Main(string[] args) { // Get security descriptor of the target object DirectoryEntry user = new DirectoryEntry(); user.Options.SecurityMasks = SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl; user.Path = "LDAP://edetoc589VM.edetoc1.lab:389/CN=user,CN=Users,DC=edetoc1,DC=lab"; ActiveDirectorySecurity userSec = user.ObjectSecurity; // Get SID of the group named 'ITGroup' NTAccount ntaToDelegate = new NTAccount("EDETOC1", "ITGroup"); SecurityIdentifier sidToDelegate = (SecurityIdentifier)ntaToDelegate.Translate(typeof(SecurityIdentifier)); // Specials Guids . See 00299570-246d-11d0-a768-00aa006e0529 Guid UserForceChangePassword = new Guid("00299570-246d-11d0-a768-00aa006e0529"); Guid userSchemaGuid = new Guid("BF967ABA-0DE6-11D0-A285-00AA003049E2"); //Guid pwdLastSetSchemaGuid = new Guid("bf967a0a-0de6-11d0-a285-00aa003049e2"); // Create ACE ExtendedRightAccessRule erarResetPwd = new ExtendedRightAccessRule(ntaToDelegate, AccessControlType.Allow, UserForceChangePassword, ActiveDirectorySecurityInheritance.None, userSchemaGuid); //PropertyAccessRule parPwdLastSetW = new PropertyAccessRule(ntaToDelegate, AccessControlType.Allow, PropertyAccess.Write, pwdLastSetSchemaGuid, ActiveDirectorySecurityInheritance.None, userSchemaGuid); //PropertyAccessRule parPwdLastSetR = new PropertyAccessRule(ntaToDelegate, AccessControlType.Allow, PropertyAccess.Read, pwdLastSetSchemaGuid, ActiveDirectorySecurityInheritance.None, userSchemaGuid); // add ACE to security descriptor of target object userSec.AddAccessRule(erarResetPwd); userSec.SetAccessRuleProtection(true, false); //userSec.AddAccessRule(parPwdLastSetW); //userSec.AddAccessRule(parPwdLastSetR); // Commit change user.CommitChanges(); }
/// <summary> /// Adds a new SID to the SD that controls access to read the password blob /// </summary> /// <param name="currentSddlBytes">current SDDL SD</param> /// <param name="newSID">sid as string, SDDL form</param> /// <returns>bigger SD bytes</returns> public byte[] addSIDtoSD(byte[] currentSddlBytes, string newSID) { ActiveDirectorySecurity ads = new ActiveDirectorySecurity(); SecurityIdentifier realSID = new SecurityIdentifier(newSID); byte[] sddlOut = new byte[2]; try { ads.SetSecurityDescriptorBinaryForm(currentSddlBytes); AuthorizationRuleCollection bb = ads.GetAccessRules(true, true, typeof(SecurityIdentifier)); bool bAlreadyInSD = false; //skip the add if the SID is already on the list foreach (AuthorizationRule ar in bb) { if (ar.IdentityReference.Value.ToString() == realSID.ToString()) { bAlreadyInSD = true; break; } } if (!bAlreadyInSD) { //add it to the SD ads.AddAccessRule(new ActiveDirectoryAccessRule(realSID, ActiveDirectoryRights.GenericAll, AccessControlType.Allow)); //output the new SD in bytes sddlOut = ads.GetSecurityDescriptorBinaryForm(); } } catch (Exception ex) { throw ex; } return(sddlOut); }
public static void RemoveAccessRule(ActiveDirectorySecurity acl, ActiveDirectoryAccessRule ace) { if (!acl.RemoveAccessRule(ace)) { AuthorizationRuleCollection accessRules = acl.GetAccessRules(true, false, typeof(SecurityIdentifier)); foreach (object obj in accessRules) { ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj; if (DirectoryCommon.AceMatches(ace, activeDirectoryAccessRule, false)) { if ((~(ace.ActiveDirectoryRights != (ActiveDirectoryRights)0) & activeDirectoryAccessRule.ActiveDirectoryRights) == (ActiveDirectoryRights)0) { acl.RemoveAccessRuleSpecific(activeDirectoryAccessRule); } else { ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(activeDirectoryAccessRule.IdentityReference, ~ace.ActiveDirectoryRights & activeDirectoryAccessRule.ActiveDirectoryRights, activeDirectoryAccessRule.AccessControlType, activeDirectoryAccessRule.ObjectType, activeDirectoryAccessRule.InheritanceType, activeDirectoryAccessRule.InheritedObjectType); acl.RemoveAccessRuleSpecific(activeDirectoryAccessRule); acl.AddAccessRule(rule); } } } } }
internal static bool ApplyAcesOnAcl(Task.TaskVerboseLoggingDelegate verboseLogger, Task.TaskWarningLoggingDelegate warningLogger, Task.ErrorLoggerDelegate errorLogger, string objectIdentityString, ActiveDirectorySecurity acl, bool remove, params ActiveDirectoryAccessRule[] aces) { bool result = false; if (!acl.AreAccessRulesCanonical) { LocalizedString message = Strings.InfoAclNotCanonical(objectIdentityString); if (errorLogger != null) { errorLogger(new TaskInvalidOperationException(message), ExchangeErrorCategory.ServerOperation, null); } else if (warningLogger != null) { warningLogger(message); } else if (verboseLogger != null) { verboseLogger(message); } return(false); } int i = 0; while (i < aces.Length) { ActiveDirectoryAccessRule activeDirectoryAccessRule = aces[i]; bool flag = false; ActiveDirectoryAccessRule activeDirectoryAccessRule2 = DirectoryCommon.FindAce(activeDirectoryAccessRule, acl, true, remove); if (null != activeDirectoryAccessRule2 != remove && (activeDirectoryAccessRule2 == null || !activeDirectoryAccessRule2.IsInherited)) { goto IL_13D; } if (!remove || !activeDirectoryAccessRule2.IsInherited) { if (verboseLogger != null) { if (remove) { verboseLogger(Strings.InfoRemovingAce(objectIdentityString, DirectoryCommon.AceToString(activeDirectoryAccessRule))); } else { verboseLogger(Strings.InfoAddingAce(objectIdentityString, DirectoryCommon.AceToString(activeDirectoryAccessRule))); } } if (remove) { DirectoryCommon.RemoveAccessRule(acl, activeDirectoryAccessRule); } else { acl.AddAccessRule(activeDirectoryAccessRule); } flag = (result = true); goto IL_13D; } LocalizedString message2 = Strings.ErrorWillNotPerformOnInheritedAce(activeDirectoryAccessRule2.ActiveDirectoryRights.ToString(), activeDirectoryAccessRule2.AccessControlType.ToString(), objectIdentityString); if (errorLogger != null) { errorLogger(new TaskInvalidOperationException(message2), ExchangeErrorCategory.ServerOperation, null); } else if (warningLogger != null) { warningLogger(message2); } else if (verboseLogger != null) { verboseLogger(message2); } IL_1DB: i++; continue; IL_13D: if ((flag && DirectoryCommon.FindAce(activeDirectoryAccessRule, acl, false, remove) == null == remove) || (verboseLogger == null && warningLogger == null && errorLogger == null)) { goto IL_1DB; } LocalizedString message3; if (remove) { if (activeDirectoryAccessRule.ObjectFlags == ObjectAceFlags.ObjectAceTypePresent) { string attr = string.Format("{0} (ObjectType: {1})", activeDirectoryAccessRule.ActiveDirectoryRights, activeDirectoryAccessRule.ObjectType); message3 = Strings.InfoAttributeAceNotPresent(objectIdentityString, attr); } else { message3 = Strings.InfoAceNotPresent(objectIdentityString, SecurityPrincipalIdParameter.GetFriendlyUserName(activeDirectoryAccessRule.IdentityReference, verboseLogger)); } } else { message3 = Strings.InfoAceAlreadyPresent(objectIdentityString, SecurityPrincipalIdParameter.GetFriendlyUserName(activeDirectoryAccessRule.IdentityReference, verboseLogger)); } if (warningLogger != null) { warningLogger(message3); goto IL_1DB; } if (verboseLogger != null) { verboseLogger(message3); goto IL_1DB; } goto IL_1DB; } return(result); }
protected override void ProcessRecord() { //OU can be passed as name or as dn var OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new AmbiguousResultException("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new NotFoundException("Object not found"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Dacl); //SELF SID System.Security.Principal.SecurityIdentifier selfSid = new System.Security.Principal.SecurityIdentifier("PS"); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, "computer", SchemaObjectType.Class); System.DirectoryServices.PropertyAccessRule rule; Guid attributeGuid; // read ms-Mcs-AdmPwdExpirationTime on computer objects attributeGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); rule = new System.DirectoryServices.PropertyAccessRule(selfSid, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, attributeGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // write ms-Mcs-AdmPwdExpirationTime on computer objects attributeGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); rule = new System.DirectoryServices.PropertyAccessRule(selfSid, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Write, attributeGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // write ms-Mcs-AdmPwd on computer objects attributeGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.PasswordAttributeName, SchemaObjectType.Attribute); rule = new System.DirectoryServices.PropertyAccessRule(selfSid, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Write, attributeGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Dacl); WriteObject(OUs[0]); }
protected override void ProcessRecord() { //OU can be passed as name or as dn var OUs = DirectoryUtils.GetOU(Identity); if (OUs.Count > 1) { foreach (ObjectInfo ou in OUs) { WriteObject(ou); } throw new AmbiguousResultException("More than one object found, search using distinguishedName instead"); } if (OUs.Count == 0) { throw new NotFoundException($"Object not found: {Identity}"); } ActiveDirectorySecurity sec = DirectoryUtils.GetObjectSecurity(conn, OUs[0].DistinguishedName, System.DirectoryServices.Protocols.SecurityMasks.Dacl); //apply permissions only to computer objects Guid inheritedObjectGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, "computer", SchemaObjectType.Class); Guid timestampGuid; Guid pwdGuid; try { timestampGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.TimestampAttributeName, SchemaObjectType.Attribute); } catch (Exception) { throw new NotFoundException($"Object not found: {Constants.TimestampAttributeName}"); } try { pwdGuid = DirectoryUtils.GetSchemaGuid(conn, forestRootDomain.SchemaNamingContext, Constants.PasswordAttributeName, SchemaObjectType.Attribute); } catch (Exception) { throw new NotFoundException($"Object not found: {Constants.PasswordAttributeName}"); } System.DirectoryServices.ActiveDirectoryAccessRule rule; foreach (string principalName in AllowedPrincipals) { System.Security.Principal.NTAccount principal = new System.Security.Principal.NTAccount(principalName); // read ms-Mcs-AdmPwdExpirationTime on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, timestampGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // read ms-Mcs-AdmPwd on computer objects rule = new System.DirectoryServices.PropertyAccessRule(principal, System.Security.AccessControl.AccessControlType.Allow, PropertyAccess.Read, pwdGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); // control access on ms-Mcs-AdmPwd on computer objects rule = new System.DirectoryServices.ActiveDirectoryAccessRule(principal, ActiveDirectoryRights.ExtendedRight, System.Security.AccessControl.AccessControlType.Allow, pwdGuid, ActiveDirectorySecurityInheritance.Descendents, inheritedObjectGuid ); sec.AddAccessRule(rule); } DirectoryUtils.SetObjectSecurity(conn, OUs[0].DistinguishedName, sec, System.DirectoryServices.Protocols.SecurityMasks.Dacl); WriteObject(OUs[0]); }
ActiveDirectorySecurity toAdSecurity(DirectoryEntry entry) { ActiveDirectorySecurity dsSecurity = entry.ObjectSecurity; // clear all existing ACEs dsSecurity .GetAccessRules(true, true, typeof(NTAccount)) .Cast <ActiveDirectoryAccessRule>() .Select(x => x.IdentityReference) .Distinct() .ToList() .ForEach(x => dsSecurity.PurgeAccessRules(x)); // iterate over local ACEs and translate to DS ACL foreach (CertTemplateAccessRule localAce in GetAccessRules(true, false, typeof(NTAccount))) { CertTemplateRights localRights = localAce.Rights; if ((localRights & CertTemplateRights.FullControl) > 0) { var ace = new ActiveDirectoryAccessRule( localAce.IdentityReference, ActiveDirectoryRights.GenericAll, localAce.AccessControlType); dsSecurity.AddAccessRule(ace); continue; } CertTemplateRights rw = localRights & (CertTemplateRights.Read | CertTemplateRights.Write); if (rw > 0) { ActiveDirectoryRights tempRights; if (rw == (CertTemplateRights.Read | CertTemplateRights.Write)) { tempRights = ActiveDirectoryRights.CreateChild | ActiveDirectoryRights.DeleteChild | ActiveDirectoryRights.Self | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.DeleteTree | ActiveDirectoryRights.Delete | ActiveDirectoryRights.GenericRead | ActiveDirectoryRights.WriteDacl | ActiveDirectoryRights.WriteOwner; } else if (rw == CertTemplateRights.Read) { tempRights = ActiveDirectoryRights.GenericRead; } else { tempRights = ActiveDirectoryRights.Self | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.WriteDacl | ActiveDirectoryRights.WriteOwner; } var ace = new ActiveDirectoryAccessRule( localAce.IdentityReference, tempRights, localAce.AccessControlType); dsSecurity.AddAccessRule(ace); } if ((localRights & CertTemplateRights.Enroll) > 0) { var ace = new ActiveDirectoryAccessRule( localAce.IdentityReference, ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ExtendedRight, localAce.AccessControlType, new Guid(GUID_ENROLL)); dsSecurity.AddAccessRule(ace); } if ((localRights & CertTemplateRights.Autoenroll) > 0) { var ace = new ActiveDirectoryAccessRule( localAce.IdentityReference, ActiveDirectoryRights.ExtendedRight, localAce.AccessControlType, new Guid(GUID_AUTOENROLL)); dsSecurity.AddAccessRule(ace); } } return(dsSecurity); }
internal static bool ProtectFromAccidentalDeletion(ADObject directoryObj, CmdletSessionInfo cmdletSessionInfo) { ADObject cachedObject; string value = directoryObj["distinguishedName"].Value as string; if (!directoryObj.Contains("nTSecurityDescriptor") || !directoryObj.Contains("sdRightsEffective")) { cachedObject = ProtectedFromDeletionUtil.GetCachedObject(value, ProtectedFromDeletionUtil.AttributesToFetchOnObject, cmdletSessionInfo); } else { cachedObject = directoryObj; ProtectedFromDeletionUtil.AddObjectToCache(directoryObj, cmdletSessionInfo); } if (cachedObject == null || !cachedObject.Contains("nTSecurityDescriptor") || cachedObject["nTSecurityDescriptor"].Value == null) { object[] objArray = new object[1]; objArray[0] = directoryObj["distinguishedName"].Value; throw new ADException(string.Format(CultureInfo.CurrentCulture, StringResources.InsufficientPermissionsToProtectObject, objArray)); } else { if (ProtectedFromDeletionUtil.EveryoneDeniedDeleteAndDeleteTree(cachedObject) || Utils.HasFlagsSet((int)cachedObject["sdRightsEffective"].Value, 4)) { if (!Utils.IsNamingContext(cachedObject) && !Utils.IsDeleted(cachedObject)) { string parentPath = ADPathModule.GetParentPath(value, null, ADPathFormat.X500); ADObject aDObject = ProtectedFromDeletionUtil.GetCachedObject(parentPath, ProtectedFromDeletionUtil.AttributesToFetchOnParent, cmdletSessionInfo); if (aDObject != null && !ProtectedFromDeletionUtil.EveryoneDeniedDeleteChild(aDObject)) { if (Utils.HasFlagsSet((int)aDObject["sdRightsEffective"].Value, 4)) { ActiveDirectorySecurity activeDirectorySecurity = (ActiveDirectorySecurity)aDObject["nTSecurityDescriptor"].Value; activeDirectorySecurity.AddAccessRule(ProtectedFromDeletionUtil.ACEConstants.DeleteChildAccessRule); using (ADActiveObject aDActiveObject = new ADActiveObject(cmdletSessionInfo.ADSessionInfo, aDObject)) { aDObject.TrackChanges = true; aDObject["nTSecurityDescriptor"].Value = activeDirectorySecurity; aDActiveObject.Update(); } } else { object[] value1 = new object[2]; value1[0] = directoryObj["distinguishedName"].Value; value1[1] = aDObject["distinguishedName"].Value; throw new ADException(string.Format(CultureInfo.CurrentCulture, StringResources.InsufficientPermissionsToProtectObjectParent, value1)); } } } ActiveDirectorySecurity activeDirectorySecurity1 = (ActiveDirectorySecurity)cachedObject["nTSecurityDescriptor"].Value; if (ProtectedFromDeletionUtil.EveryoneDeniedDeleteAndDeleteTree(cachedObject)) { return(false); } else { activeDirectorySecurity1.AddAccessRule(ProtectedFromDeletionUtil.ACEConstants.DeleteAndDeleteTreeAccessRule); if (!directoryObj.Contains("nTSecurityDescriptor")) { directoryObj.Add("nTSecurityDescriptor", activeDirectorySecurity1); } else { directoryObj["nTSecurityDescriptor"].Value = activeDirectorySecurity1; } return(true); } } else { object[] objArray1 = new object[1]; objArray1[0] = directoryObj["distinguishedName"].Value; throw new ADException(string.Format(CultureInfo.CurrentCulture, StringResources.InsufficientPermissionsToProtectObject, objArray1)); } } }
private void AddOwnerPermission(string user, ActiveDirectorySecurity adSecurity, SecurityIdentifier sid) { adSecurity.AddAccessRule(new ActiveDirectoryAccessRule(sid, GroupMailboxPermissionHandler.MailboxRightsFullAccess, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty)); this.AddVerboseLog(string.Format("Granted full mailbox access to {0}", user)); }