public void Execute(IActivityRequest request, IActivityResponse response) { String userName = String.Empty; String password = String.Empty; String userFullName = String.Empty; String computerName = String.Empty; userName = request.Inputs["User Name"].AsString(); password = request.Inputs["User Password"].AsString(); userFullName = request.Inputs["User Full Name"].AsString(); computerName = request.Inputs["Computer Name"].AsString(); String aUserName = String.Empty; String aUserDomain = String.Empty; String aUserPassword = String.Empty; if (request.Inputs.Contains("Alternate Connection Username")) { aUserName = request.Inputs["Alternate Connection Username"].AsString(); } if (request.Inputs.Contains("Alternate Connection User Domain")) { aUserDomain = request.Inputs["Alternate Connection User Domain"].AsString(); } if (request.Inputs.Contains("Alternate Connection Password")) { aUserPassword = request.Inputs["Alternate Connection Password"].AsString(); } DirectoryEntry hostMachineDirectory; if (aUserName.Equals(String.Empty) || aUserDomain.Equals(String.Empty) || aUserPassword.Equals(String.Empty)) { hostMachineDirectory = new DirectoryEntry("WinNT://" + computerName); } else { hostMachineDirectory = new DirectoryEntry("WinNT://" + computerName, string.Format("{0}@{1}", aUserName, aUserDomain), aUserPassword); } DirectoryEntries entries = hostMachineDirectory.Children; bool userExists = false; foreach (DirectoryEntry each in entries) { userExists = each.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase); if (userExists) { break; } } if (false == userExists) { DirectoryEntry obUser = entries.Add(userName, "User"); if (userFullName == String.Empty) { obUser.Properties["FullName"].Add(userFullName); } else { obUser.Properties["FullName"].Add("Local user"); } obUser.Invoke("SetPassword", password); obUser.Invoke("Put", new object[] { "UserFlags", 0x10000 }); obUser.CommitChanges(); } response.Publish("User Name", userName); }
static void Main(string[] args) { Stack <IDisposable> disposer = new Stack <IDisposable>(); int rowNumber = 0; try { // load the XML spreadsheet into memory string path; if (args.Length == 1) { path = args[0]; } else { path = Path.Combine(Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location), "ProvisionData.xls"); } List <List <string> > rows = LoadXmlSpreadsheet(path, "Provisioning Data"); // initialize <s_computerChildren> and <s_guests>, used by CreateUser DirectoryEntry computer = new DirectoryEntry( String.Format("WinNT://{0},computer", Environment.MachineName)); disposer.Push(computer); s_computerChildren = computer.Children; s_guests = s_computerChildren.Find("Guests", "group"); disposer.Push(s_guests); // process each row of the spreadsheet foreach (List <string> row in rows) { // keep track of the row number for feedback purposes rowNumber++; // skip blank rows and rows starting with ";" (comments) if ((row.Count == 0) || row[0].StartsWith(";")) { continue; } // to simplify debugging debugging, command "PauseAndQuit" pauses and then quits if (row[0] == "PauseAndQuit") { Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); break; } // process the row Console.WriteLine("-- Row {0} of {1} --", rowNumber, rows.Count); switch (row[0]) { case "AddManagedPath": ExpectCells(row, 3); AddManagedPath(row[1], row[2]); break; case "CreateSiteCollection": ExpectCells(row, 3); CreateSiteCollection(row[1], row[2]); break; case "ConfigureSiteCollectionForSlk": ExpectCells(row, 4); ConfigureSiteCollectionForSlk(row[1], row[2], row[3]); break; case "CreateWebSite": ExpectCells(row, 4); CreateWebSite(row[1], row[2], row[3]); break; case "ActivateFeatureOnWebSite": ExpectCells(row, 3); ActivateFeatureOnWebSite(row[1], row[2]); break; case "CreateUser": ExpectCells(row, 4); CreateUser(row[1], row[2], row[3]); break; case "AddUserToSiteCollection": ExpectCells(row, 4); AddUserToSiteCollection(row[1], row[2], row[3]); GrantUserAccess(row[1], "Read", row[3]); break; case "GrantUserAccess": ExpectCells(row, 4); GrantUserAccess(row[1], row[2], row[3]); break; case "AddToUserWebList": ExpectCells(row, 4); AddToUserWebList(row[1], row[2], row[3]); break; default: throw new Exception(String.Format("Unknown command: {0}", row[0])); } } Console.WriteLine("Done."); } #if !DEBUG // catch exceptions in Visual Studio during development catch (Exception ex) { if (rowNumber > 0) { Console.WriteLine("Error: Row {0}: {1}", rowNumber, ex.Message); } else { Console.WriteLine("Error: {0}", ex.Message); } } #endif finally { // dispose of objects used by this method while (disposer.Count > 0) { disposer.Pop().Dispose(); } } }
/// <summary> /// TestCase29 method validates the requirements under /// WellKnownSecurityDomainPrincipal Scenario. /// </summary> public void ValidateWellKnownSecurityDomainPrincipal() { DirectoryEntry dirEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); DirectoryEntry rootEntry = new DirectoryEntry(); string currDomain = adAdapter.rootDomainDN; string configNC = "CN=Configuration," + currDomain; string schemaNC = "CN=Schema," + configNC; bool isObjectSid = true; SecurityIdentifier sid; PropertyValueCollection rid, ridUser; byte[] objectSid; string expectedValue = String.Empty; string actualValue = String.Empty; if (!adAdapter.GetObjectByDN("CN=Users," + currDomain, out dirEntry)) { DataSchemaSite.Assume.IsTrue(false, "CN=Users," + currDomain + " Object is not found in server"); } // Get the object of Root Domain NC. if (!adAdapter.GetObjectByDN(currDomain, out rootEntry)) { DataSchemaSite.Assume.IsTrue(false, currDomain + " Object is not found in server"); } //Get the objectSid value of the object of root domain NC. objectSid = (byte[])rootEntry.Properties["objectSid"].Value; sid = new SecurityIdentifier(objectSid, 0); expectedValue = sid.ToString(); int length = expectedValue.Length; DirectoryEntries rolesChilds = dirEntry.Children; //For each child, foreach (DirectoryEntry child in rolesChilds) { //Get the sid of the child object. objectSid = (byte[])child.Properties["objectSid"].Value; sid = new SecurityIdentifier(objectSid, 0); //Get the rid of this object. string temp = sid.ToString(); temp = temp.Substring(temp.LastIndexOf('-')); //Add rid with expected value. expectedValue = expectedValue + temp; //Get the actual value. actualValue = sid.ToString(); //Compare. if (actualValue.Equals(expectedValue)) { isObjectSid = true; } else { isObjectSid = false; break; } //Reset the expected value. expectedValue = expectedValue.Substring(0, length); } //MS-ADTS-Schema_R811 DataSchemaSite.CaptureRequirementIfIsTrue( isObjectSid, 811, @"The objectSid attribute of Well-Known Domain-Relative Security Principals must be a SID consisting of the objectSid of the domain NC root followed by the RID specified for each child."); //MS-ADTS-Schema_R812 childEntry = dirEntry.Children.Find($"CN={adAdapter.DomainAdministratorName}"); rid = childEntry.Properties["primaryGroupID"]; childEntry = dirEntry.Children.Find("CN=Domain Users"); childEntry.RefreshCache(new string[] { "primaryGroupToken" }); ridUser = childEntry.Properties["primaryGroupToken"]; DataSchemaSite.CaptureRequirementIfAreEqual <int>( (int)ridUser.Value, (int)rid.Value, 812, @"The primaryGroupID attribute of class user Well-Known Domain-Relative Security Principals must be RID, which refers to another Well-Known domain relative security principal, by RID"); //The method to call common requirements for AD/DS and LDS. LDSAndDSCommonCall(dirEntry); if (!adAdapter.GetObjectByDN(currDomain, out childEntry)) { DataSchemaSite.Assume.IsTrue(false, currDomain + " Object is not found in server"); } PropertyValueCollection nTMixedDomain = childEntry.Properties["nTMixedDomain"]; //If nTMixedDomain value is 0 that is not mixed else mixed domain if ((int)nTMixedDomain.Value == 0) { //MS-ADTS-Schema_R843 childEntry = dirEntry.Children.Find("CN=Schema Admins"); PropertyValueCollection groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_UNIVERSAL_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 843, @"If the forest root domain is not mixed :The groupType attribute of Schema Admins Well-Known Domain-Relative Security Principals is {GROUP_TYPE_UNIVERSAL_GROUP | GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000008."); if (serverOS >= OSVersion.WinSvr2008) { //MS-ADTS-Schema_R832 childEntry = dirEntry.Children.Find("CN=Enterprise Admins"); groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_UNIVERSAL_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 832, @"If the forest root domain is not mixed :The groupType attribute of Enterprise Administrators Well-Known Domain-Relative Security Principals is {GROUP_TYPE_UNIVERSAL_GROUP | GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000008."); } } else { //MS-ADTS-Schema_R842, MS-ADTS-Schema_R831 childEntry = dirEntry.Children.Find("CN=Schema Admins"); PropertyValueCollection groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 842, @"If the forest root domain is not mixed :The groupType attribute of Schema Admins Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002."); if (serverOS == OSVersion.WinSvr2008) { //MS-ADTS-Schema_R831 childEntry = dirEntry.Children.Find("CN=Enterprise Admins"); groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 831, @"If the forest root domain is not mixed :The groupType attribute of Enterprise Administrators Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002."); } } }
// Get groups of which p is a direct member internal override ResultSet GetGroupsMemberOf(Principal p) { // Enforced by the methods that call us Debug.Assert(p.unpersisted == false); if (!p.fakePrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: is real principal"); // No nested groups or computers as members of groups in SAM if (!(p is UserPrincipal)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: not a user, returning empty set"); return(new EmptySet()); } Debug.Assert(p.UnderlyingObject != null); DirectoryEntry userDE = (DirectoryEntry)p.UnderlyingObject; UnsafeNativeMethods.IADsMembers iadsMembers = (UnsafeNativeMethods.IADsMembers)userDE.Invoke("Groups"); ResultSet resultSet = new SAMGroupsSet(iadsMembers, this, _ctxBase); return(resultSet); } else { // ADSI's IADsGroups doesn't work for fake principals like NT AUTHORITY\NETWORK SERVICE // We use the same SAMQuery set that we use for query-by-example, but with a different // SAMMatcher class to match groups which contain the specified principal as a member // Get the entries we'll iterate over. Write access to Children is controlled through the // ctxBaseLock, but we don't want to have to hold that lock while we're iterating over all // the child entries. So we have to clone the ctxBase --- not ideal, but it prevents // multithreading issues. DirectoryEntries entries = SDSUtils.BuildDirectoryEntry(_ctxBase.Path, _credentials, _authTypes).Children; Debug.Assert(entries != null); // The SAMQuerySet will use this to restrict the types of DirectoryEntry objects returned. List <string> schemaTypes = GetSchemaFilter(typeof(GroupPrincipal)); SecurityIdentifier principalSid = p.Sid; byte[] SidB = new byte[principalSid.BinaryLength]; principalSid.GetBinaryForm(SidB, 0); if (principalSid == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetGroupsMemberOf: bad SID IC"); throw new InvalidOperationException(SR.StoreCtxNeedValueSecurityIdentityClaimToQuery); } // Create the ResultSet that will perform the client-side filtering SAMQuerySet resultSet = new SAMQuerySet( schemaTypes, entries, _ctxBase, -1, // no size limit this, new GroupMemberMatcher(SidB)); return(resultSet); } }
/// <summary> /// Create lis of LDAPObject by DirectoryEntries Collection /// </summary> /// <param name="entries">DirectoryEntries</param> /// <returns>list of LDAPObjects</returns> public static IList <LDAPObject> CreateObjects(DirectoryEntries entries) { return((from DirectoryEntry item in entries select CreateObject(item)).ToList()); }
public static VirtualWebDir FindLocalWebSiteByName(Form owner, string webName, out bool iisError) { iisError = false; using (ShowMessage frm = new ShowMessage(owner, "Checking web site name...")) { DirectoryEntry site = new DirectoryEntry(LocalWebPath); string className = string.Empty; try { className = site.SchemaClassName.ToString(); } catch (Exception err) { StringBuilder sb = new StringBuilder(); while (err != null) { sb.Append("Error finding web site via Active Directory. Please install 'IIS6 Metabase compatibility' if it is not installed.\r\nError message:"); sb.Append(err.Message); sb.Append("\r\nStack trace:"); if (!string.IsNullOrEmpty(err.StackTrace)) { sb.Append(err.StackTrace); } sb.Append("===============\r\n"); err = err.InnerException; } MessageBox.Show(sb.ToString(), "Find web site", MessageBoxButtons.OK, MessageBoxIcon.Error); iisError = true; return(null); } if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase))) { DirectoryEntries vdirs = site.Children; IEnumerator ie = vdirs.GetEnumerator(); while (ie.MoveNext()) { DirectoryEntry de = ie.Current as DirectoryEntry; if (de != null) { if (string.Compare(de.Name, webName, StringComparison.OrdinalIgnoreCase) == 0) { string dir = null; PropertyValueCollection pv = de.Properties["Path"]; if (pv != null) { if (pv.Value != null) { dir = pv.Value.ToString(); VirtualWebDir vd = new VirtualWebDir(de.Path, dir); return(vd); } } else { } } } } } } return(null); }
/// <summary> /// get AD sourced claims for a principal /// </summary> /// <param name="principal">the target principal</param> /// <param name="principalClass">user or device</param> /// <returns>a CLAIMS_ARRAY contains claims of the principal</returns> CLAIMS_ARRAY getADSoucredClaims(DirectoryEntry principal, ClaimsPrincipalClass principalClass) { CLAIMS_ARRAY ret = new CLAIMS_ARRAY(); using (DirectoryEntry root = new DirectoryEntry(ConstValue.claimTypesPath + domainNC)) { List <CLAIM_ENTRY> claims = new List <CLAIM_ENTRY>(); DirectoryEntries children = root.Children; foreach (DirectoryEntry de in children) { //source type should be AD if ((!de.Properties.Contains(ConstValue.msDSClaimSourceType)) || ((ClaimsSourceType)Enum.Parse(typeof(ClaimsSourceType), de.Properties[ConstValue.msDSClaimSourceType].Value.ToString(), true) != ClaimsSourceType.AD) || (!de.Properties.Contains(ConstValue.msDSClaimTypeAppliesToClass))) { continue; } //should applies to this principal class bool classMatched = false; foreach (object str in de.Properties[ConstValue.msDSClaimTypeAppliesToClass]) { string tmp = str.ToString(); if (tmp.ToLower() == (ConstValue.userRDN + domainNC.ToLower()) && principalClass == ClaimsPrincipalClass.User) { classMatched = true; break; } if ((tmp.ToLower() == (ConstValue.computerRDN + domainNC).ToLower()) && principalClass == ClaimsPrincipalClass.Device) { classMatched = true; break; } } if (!classMatched) { continue; } //validate claim definition if (!validateClaimDefinition(de)) { continue; } //create CLAIM_ENTRY record CLAIM_ENTRY claim; claim.Id = de.Properties["cn"].Value.ToString(); claim.Type = getClaimValueType(de.Properties[ConstValue.distinguishedname].Value.ToString(), DomainController); claim.Values = new CLAIM_ENTRY_VALUE_UNION(); using (DirectoryEntry source = new DirectoryEntry("LDAP://" + de.Properties[ConstValue.msDSClaimAttributeSource].Value.ToString())) { PropertyValueCollection values = principal.Properties[source.Properties["ldapdisplayName"].Value.ToString()]; //parse values switch (claim.Type) { case CLAIM_TYPE.CLAIM_TYPE_STRING: claim.Values.Struct3 = new CLAIM_TYPE_VALUE_LPWSTR(); claim.Values.Struct3.ValueCount = (uint)values.Count; claim.Values.Struct3.StringValues = new string[values.Count]; for (int i = 0; i < values.Count; i++) { claim.Values.Struct3.StringValues[i] = values[i].ToString(); } break; case CLAIM_TYPE.CLAIM_TYPE_INT64: claim.Values.Struct1 = new CLAIM_TYPE_VALUE_INT64(); claim.Values.Struct1.ValueCount = (uint)values.Count; claim.Values.Struct1.Int64Values = new long[values.Count]; for (int i = 0; i < values.Count; i++) { claim.Values.Struct1.Int64Values[i] = (long)values[i]; } break; case CLAIM_TYPE.CLAIM_TYPE_UINT64: claim.Values.Struct2 = new CLAIM_TYPE_VALUE_UINT64(); claim.Values.Struct2.ValueCount = (uint)values.Count; claim.Values.Struct2.Uint64Values = new ulong[values.Count]; for (int i = 0; i < values.Count; i++) { claim.Values.Struct2.Uint64Values[i] = (ulong)values[i]; } break; case CLAIM_TYPE.CLAIM_TYPE_BOOLEAN: claim.Values.Struct4 = new CLAIM_TYPE_VALUE_BOOL(); claim.Values.Struct4.ValueCount = (uint)values.Count; claim.Values.Struct4.BooleanValues = new bool[values.Count]; for (int i = 0; i < values.Count; i++) { claim.Values.Struct4.BooleanValues[i] = (bool)values[i]; } break; } claims.Add(claim); ret.ulClaimsCount = (uint)claims.Count; ret.ClaimEntries = claims.ToArray(); ret.usClaimsSourceType = 1; } } } return(ret); }
public void ValidateContentRulesRequirements(DirectoryEntries childrens, IEnumerable <IObjectOnServer> serverObjects) { bool isContent = true; //Setting some excluded attributes. SetContainer <string> ExcludedAttributes = new SetContainer <string>(); ExcludedAttributes.Add("creationTime"); ExcludedAttributes.Add("forceLogoff"); ExcludedAttributes.Add("lockoutDuration"); ExcludedAttributes.Add("lockOutObservationWindow"); ExcludedAttributes.Add("lockoutThreshold"); ExcludedAttributes.Add("maxPwdAge"); ExcludedAttributes.Add("minPwdAge"); ExcludedAttributes.Add("minPwdLength"); ExcludedAttributes.Add("modifiedCountAtLastProm"); ExcludedAttributes.Add("nextRid"); ExcludedAttributes.Add("pwdProperties"); ExcludedAttributes.Add("pwdHistoryLength"); ExcludedAttributes.Add("objectSid"); ExcludedAttributes.Add("serverState"); ExcludedAttributes.Add("uASCompat"); ExcludedAttributes.Add("modifiedCount"); //For each domain NC object... foreach (DirectoryEntry entry in childrens) { SetContainer <string> mustContain = new SetContainer <string>(); SetContainer <string> mayContain = new SetContainer <string>(); //Get super class chain. object[] superClasses = (object[])entry.Properties[StandardNames.objectClass.ToLower()].Value; //For each super class... foreach (string superClass in superClasses) { foreach (IObjectOnServer serverObj in serverObjects) { //Get the object from server. if (serverObj.Name.StartsWith(superClass)) { //Collect all must and may contain attribute value. if (serverObj.Properties.ContainsKey(StandardNames.mustContain.ToLower())) { foreach (object value in serverObj.Properties[StandardNames.mustContain.ToLower()]) { mustContain.Add((string)value); } } if (serverObj.Properties.ContainsKey(StandardNames.systemMustContain.ToLower())) { foreach (object value in serverObj.Properties[StandardNames.systemMustContain.ToLower()]) { mustContain.Add((string)value); } } if (serverObj.Properties.ContainsKey(StandardNames.mayContain.ToLower())) { foreach (object value in serverObj.Properties[StandardNames.mayContain.ToLower()]) { mayContain.Add((string)value); } } if (serverObj.Properties.ContainsKey(StandardNames.systemMayContain.ToLower())) { foreach (object value in serverObj.Properties[StandardNames.systemMayContain.ToLower()]) { mayContain.Add((string)value); } } break; } } } //For all property name of this object, it should be present in either must or may contain //attribute list. foreach (string attribute in entry.Properties.PropertyNames) { if (!ExcludedAttributes.Contains(attribute)) { //This attribute is in must contain list. if (mustContain.Contains(attribute)) { mustContain.Remove(attribute); } //This attribute is not in must and may contian list. else if (!mayContain.Contains(attribute)) { isContent = false; break; } } } //This is for checking whether some must contain attributes are missed. if (mustContain.Count > 0) { isContent = false; } if (!isContent) { break; } } //MS-ADTS-Schema_R152. DataSchemaSite.CaptureRequirementIfIsTrue( isContent, 152, @"In the content rules union of values in the mustContain and systemMustContain attributes specifies the attributes that are required to be present on an object instance of the class in question."); //MS-ADTS-Schema_R153. DataSchemaSite.CaptureRequirementIfIsTrue( isContent, 153, @"In the content rules the union of values in the mustContain, systemMustContain, mayContain, and systemMayContain attributes specifies the attributes that are allowed to be present on an object instance of the class in question."); }
/// <summary> /// Method validates the requirements under CrossRefContainer Scenario. /// </summary> public void ValidateCrossRefContainer() { //Variables required for Directory Entries. DirectoryEntry dirPartitions = new DirectoryEntry(); DirectoryEntry domainEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); if (!Utilities.IsObjectExist(adAdapter.PartitionPath + "," + adAdapter.rootDomainDN, adAdapter.PDCNetbiosName, adAdapter.ADDSPortNum, adAdapter.DomainAdministratorName, adAdapter.DomainUserPassword)) { //To create the Application NC in the Active Directory. AdLdapClient.Instance().ConnectAndBind(adAdapter.PDCNetbiosName, adAdapter.PDCIPAddr, Convert.ToInt32(adAdapter.ADDSPortNum), adAdapter.DomainAdministratorName, adAdapter.DomainUserPassword, adAdapter.PrimaryDomainDnsName, AuthType.Basic | AuthType.Kerberos); List <DirectoryAttribute> attrs = new List <DirectoryAttribute>(); attrs.Add(new DirectoryAttribute("instancetype:5")); attrs.Add(new DirectoryAttribute("objectclass:domainDNS")); AdLdapClient.Instance().AddObject(adAdapter.PartitionPath + "," + adAdapter.rootDomainDN, attrs, null); AdLdapClient.Instance().Unbind(); } string configNC = "CN=Configuration," + adAdapter.rootDomainDN; string SchemaNC = "CN=Schema," + configNC; //Returns Fully Qualified DNS Name for the Current Domain. string strReturn = adAdapter.PrimaryDomainDnsName; if (!adAdapter.GetObjectByDN("CN=Partitions," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue(false, "CN=Partitions," + configNC + " Object is not found in server"); } string parent = dirPartitions.Parent.Name, systemFlag; bool isPresent = false; int systemFlagVal; //MS-ADTS-Schema_R402 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", parent, 402, "The Parent of the Cross-Ref-Container Container must be Config NC root."); //MS-ADTS-Schema_R403 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "Partitions", dirPartitions.Properties["name"].Value.ToString(), 403, @"The name attribute of the Cross-Ref-Container Container must be Partitions."); //MS-ADTS-Schema_R404 PropertyValueCollection objectClass = dirPartitions.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"crossRefContainer"), 404, "The objectClass attribute of the Cross-Ref-Container Container must be crossRefContainer."); string fsmoRoleOwner = dirPartitions.Properties["fSMORoleOwner"].Value.ToString(); //MS-ADTS-Schema_R406 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 406, "The systemFlags attribute of the Cross-Ref-Container Container must be FLAG_DISALLOW_DELETE."); //MS-ADTS-Schema_R405 if (!adAdapter.GetObjectByDN(adAdapter.rootDomainDN, out domainEntry)) { DataSchemaSite.Assume.IsTrue(false, adAdapter.rootDomainDN + " Object is not found in server"); } string domainFSMO = domainEntry.Properties["fSMORoleOwner"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( fsmoRoleOwner, domainFSMO, 405, "The fSMORoleOwner attribute of the Cross-Ref-Container Container must references the Domain " + "Naming Master FSMO role owner."); //MS-ADTS-Schema_R408 //Query the Partitions for CrossRef container get the childrens and validate the requirments as such. bool isCrossRef = true; bool isObjectClassCrossRef = true; DirectoryEntries Childs = dirPartitions.Children; foreach (DirectoryEntry child in Childs) { if (!child.Parent.Name.Equals("CN=Partitions")) { isCrossRef = false; } PropertyValueCollection objClass = child.Properties["objectClass"]; objClass.RemoveAt(0); if (objClass.Count != 1 || !objClass.Contains((object)"crossRef")) { isObjectClassCrossRef = false; } if (dirPartitions.Parent.Name.ToString().Equals("CN=Configuration")) { isPresent = true; } } //Validate the parent of the crossref objects,objectClass,nCName and //dnsRoot for all childs and crossRef container in the configNC. DataSchemaSite.CaptureRequirementIfIsTrue( isCrossRef, 408, "The parent of the Cross-Ref Objects must be crossRefContainer object."); //MS-ADTS-Schema_R851 DataSchemaSite.CaptureRequirementIfIsTrue( isPresent & isCrossRef, 851, "For any NC in the forest crossRef,NC root objects must be exist."); // MS-ADTS-Schema_R409 DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassCrossRef, 409, "The objectClass attribute of the Cross-Ref Objects must be crossRef."); //This is the crossRef container or crossRefObject //MS-ADTS-Schema_R410 childEntry = dirPartitions.Children.Find("CN=Enterprise Configuration"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( configNC.ToLower(), childEntry.Properties["nCName"].Value.ToString().ToLower(), 410, "The nCName attribute of the Configuration crossRef Object must equal to the config NC root."); //MS-ADTS-Schema_R411 string dnsRoot = childEntry.Properties["dnsRoot"].Value.ToString().ToLower(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( strReturn.ToLower(), dnsRoot.ToLower(), 411, "In AD/DS the dnsroot attribute of the Configuration crossRef Object must be the forest " + "root's fully qualified DNS name."); //This is the crossRef child or crossRefObject //MS-ADTS-Schema_R413 childEntry = dirPartitions.Children.Find("CN=Enterprise Schema"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( SchemaNC.ToLower(), childEntry.Properties["nCName"].Value.ToString().ToLower(), 413, "The nCName attribute of the Schema crossRef Object must equal to the Schema NC root."); //MS-ADTS-Schema_R414 dnsRoot = childEntry.Properties["dnsRoot"].Value.ToString().ToLower(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( strReturn.ToLower(), dnsRoot.ToLower(), 414, "In AD/DS the dnsroot attribute of the Schema crossRef Object must be the forest " + "root's fully qualified DNS name."); //MS-ADTS-Schema_R852 if (!adAdapter.GetObjectByDN(SchemaNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue(false, SchemaNC + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( childEntry.Properties["nCName"].Value.ToString(), dirPartitions.Properties["distinguishedName"].Value.ToString(), 852, "The nCName attribute of the crossRef object must equal the dsname of the NC root object."); if (!adAdapter.GetObjectByDN("CN=Partitions," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue(false, "CN=Partitions," + configNC + " Object is not found in server"); } foreach (DirectoryEntry partitionEntry in dirPartitions.Children) { if (partitionEntry.Properties["objectCategory"].Value.ToString().ToLower().Contains("cn=cross-ref")) { if (partitionEntry.Properties["nCName"].Value.ToString().Contains(adAdapter.PartitionPath)) { partitionEntry.RefreshCache(new string[] { "msDS-SDReferenceDomain" }); if (partitionEntry.Properties.Contains("msDS-SDReferenceDomain") && partitionEntry.Properties["msDS-SDReferenceDomain"].Value != null) { //MS-ADTS-Schema_R422 DataSchemaSite.CaptureRequirementIfAreEqual <string>( adAdapter.rootDomainDN.ToLower(), partitionEntry.Properties["msDS-SDReferenceDomain"].Value.ToString().ToLower(), 422, "In AD/DS msDS-SDReferenceDomain attribute of the Application NC crossRef object," + "references an NC root object for a domain. All security descriptors in this application NC " + "must use the NC represented as the reference domain for resolution."); } else { DataSchemaSite.Log.Add(LogEntryKind.Warning, "The value of msDS-SDReferenceDomain attribute of the Application NC crossRef object is null"); } } if (partitionEntry.Properties["nCName"].Value.ToString().Equals(adAdapter.rootDomainDN)) { //MS-ADTS-Schema_R416 DataSchemaSite.CaptureRequirementIfAreEqual <string>( partitionEntry.Properties["name"].Value.ToString(), partitionEntry.Properties["nETBIOSName"].Value.ToString(), 416, "The name attribute of the Domain crossRef Object must be the Netbios name of the domain."); //MS-ADTS-Schema_R417 DataSchemaSite.CaptureRequirementIfAreEqual <string>( adAdapter.rootDomainDN, partitionEntry.Properties["nCName"].Value.ToString(), 417, "The nCName attribute of the Domain crossRef Object must be reference to the Domain NC root."); //MS-ADTS-Schema_R418 if (!adAdapter.GetObjectByDN(adAdapter.rootDomainDN, out domainEntry)) { DataSchemaSite.Assume.IsTrue(false, adAdapter.rootDomainDN + " Object is not found in server"); } DirectoryEntry domainChildEntry = new DirectoryEntry(); DataSchemaSite.CaptureRequirementIfIsTrue( adAdapter.rootDomainDN.ToLower().Contains(partitionEntry.Properties["nETBIOSName"].Value.ToString().ToLower()), 418, "The nETBIOSName attribute of the Domain crossRef Object must be the Netbios name of the domain."); //MS-ADTS-Schema trustParent DataSchemaSite.Assert.IsNull( partitionEntry.Properties["trustParent"].Value, "The trustParent attribute is not present on the root domain NC's crossRef object."); //MS-ADTS-Schema_R419 systemFlag = partitionEntry.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_ATTR_NOT_REPLICATED|FLAG_ATTR_REQ_PARTIAL_SET_MEMBER"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 419, @"The systemFlags attribute of the Domain crossRef Object must be FLAG_CR_NTDS_NC | FLAG_CR_NTDS_DOMAIN."); } if (partitionEntry.Properties["nCName"].Value.ToString().Equals(adAdapter.childDomainDN)) { //MS-ADTS-Schema_R416 DataSchemaSite.CaptureRequirementIfAreEqual <string>( partitionEntry.Properties["name"].Value.ToString(), partitionEntry.Properties["nETBIOSName"].Value.ToString(), 416, "The name attribute of the Domain crossRef Object must be the Netbios name of the domain."); //MS-ADTS-Schema_R417 DataSchemaSite.CaptureRequirementIfAreEqual <string>( adAdapter.childDomainDN, partitionEntry.Properties["nCName"].Value.ToString(), 417, "The nCName attribute of the Domain crossRef Object must be reference to the Domain NC root."); //MS-ADTS-Schema_R418 if (!adAdapter.GetObjectByDN(adAdapter.childDomainDN, out domainEntry)) { DataSchemaSite.Assume.IsTrue(false, adAdapter.childDomainDN + " Object is not found in server"); } DirectoryEntry domainChildEntry = new DirectoryEntry(); DataSchemaSite.CaptureRequirementIfIsTrue( adAdapter.childDomainDN.ToLower().Contains(partitionEntry.Properties["nETBIOSName"].Value.ToString().ToLower()), 418, "The nETBIOSName attribute of the Domain crossRef Object must be the Netbios name of the domain."); //MS-ADTS-Schema trustParent DirectoryEntry parentEntry = new DirectoryEntry(); string netbiosDomain = adAdapter.PrimaryDomainNetBiosName; parentEntry = dirPartitions.Children.Find(string.Format("CN={0}", netbiosDomain)); DataSchemaSite.Assert.AreEqual <string>( parentEntry.Properties["distinguishedName"].Value.ToString(), partitionEntry.Properties["trustParent"].Value.ToString(), "For child NCs, the trustParent attribute value references the parent NC's crossRef object."); //MS-ADTS-Schema_R419 systemFlag = partitionEntry.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_ATTR_NOT_REPLICATED|FLAG_ATTR_REQ_PARTIAL_SET_MEMBER"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 419, @"The systemFlags attribute of the Domain crossRef Object must be FLAG_CR_NTDS_NC | FLAG_CR_NTDS_DOMAIN."); } } } //MS-ADTS-Schema_R420 dnsRoot = childEntry.Properties["dnsRoot"].Value.ToString().ToLower(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( strReturn.ToLower(), dnsRoot.ToLower(), 420, "In AD/DS the the value for dnsRoot for an application NC crossRef is derived by syntactically " + "converting the DN portion of the crossRef's nCName into a fully qualified DNS name."); }
/// <summary> /// Query for Network Computer Names /// </summary> /// <returns></returns> private static List <string> StandardComputerNameQuery() { WindowsIdentity wi = WindowsIdentity.GetCurrent(); if (wi != null) { string serverUserName = wi.Name; string[] parts = serverUserName.Split('\\'); string queryStr = "WinNT://"; // query with domain appended ;) if (parts.Length == 2) { queryStr += parts[0]; } else { // find the first workgroup and report on it ;) try { var query = new SelectQuery("Win32_ComputerSystem"); var searcher = new ManagementObjectSearcher(query); ManagementObjectCollection tmp = searcher.Get(); ManagementObjectCollection.ManagementObjectEnumerator itr = tmp.GetEnumerator(); if (itr.MoveNext()) { queryStr += itr.Current["Workgroup"] as string; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // best effort ;) } } var root = new DirectoryEntry(queryStr); DirectoryEntries kids = root.Children; var result = new List <string>(); foreach (DirectoryEntry node in kids) { if (node.SchemaClassName == "Computer") { result.Add(node.Name); } } return(result); } // big problems, add this computer and return return(new List <string> { Environment.MachineName }); }
public void ValidateObjectClassRequirements(DirectoryEntries childrens, bool isADDS) { bool isObjectClassMultiValued = false; bool isObjectClassAppeared = false; bool isObjectClassTop = false; bool isObjectClassStructural = false; foreach (DirectoryEntry child in childrens) { //Get objectClass value. PropertyValueCollection propValColln = child.Properties[StandardNames.objectClass]; //If it is not existing Requirement 130 will fail. if (propValColln != null) { isObjectClassAppeared = true; } //It is multivalued. so it should be more than one value. if (propValColln.Count >= 1) { isObjectClassMultiValued = true; } //Get objectClassValue in array. string[] objectClassElements = new string[propValColln.Count]; int loopVariable = 0; foreach (string propVal in (IEnumerable <object>)propValColln.Value) { objectClassElements[loopVariable++] = propVal; } //The first element is always top. if (objectClassElements[0].ToLower().Equals("top")) { isObjectClassTop = true; } //Get last element. string structuralClassName = (string)child.Properties["objectCategory"].Value; DirectoryEntry lastClassObject; if (isADDS) { if (!adAdapter.GetObjectByDN(structuralClassName, out lastClassObject)) { DataSchemaSite.Assume.IsTrue(false, structuralClassName + " Object is not found in server"); } } else { if (!adAdapter.GetLdsObjectByDN(structuralClassName, out lastClassObject)) { DataSchemaSite.Assume.IsTrue(false, structuralClassName + " Object is not found in server"); } } ObjectClassCategory lastClassCategory = (ObjectClassCategory)(int)lastClassObject. Properties[StandardNames.objectClassCategory.ToLower()][0]; //The last element should be structural class. if (lastClassCategory == ObjectClassCategory.StructuralClass) { isObjectClassStructural = true; } if (isObjectClassAppeared && isObjectClassMultiValued && isObjectClassStructural && isObjectClassTop) { continue; } else { break; } } //MS-ADTS-Schema_R143. DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassMultiValued && isObjectClassAppeared, 143, "Attribute objectClass is a multivalued attribute that appears on all the objects in the directory."); //MS-ADTS-Schema_R144. DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassMultiValued && isObjectClassAppeared, 144, @"When instantiating a structural class, the objectClass attribute of the new object contains a sequence of class names"); //MS-ADTS-Schema_R145. DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassTop, 145, "In the ObjectClass first element is always class top."); //MS-ADTS-Schema_R146. DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassStructural, 146, "In the ObjectClass last element is the name of the structural class that was instantiated."); }
static void Main(string[] args) { Console.WriteLine("Press any key to create the new web site."); Console.ReadLine(); //Connect to IIS ADSI Provider string ServerName = "LocalHost"; DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc"); // Create new web site. object siteObj; string siteID = ""; string siteName = "IISADSIDemo"; string hostHeader = "www.mytestdomain.com"; string serverBinding1 = ":8181:"; string serverBinding2 = ":8282:" + hostHeader; string rootPath = "C:\\inetpub\\IISADSIDemo"; object[] siteProperty = new object[] { siteName, new object[] { serverBinding1, serverBinding2 }, rootPath }; try { siteObj = (object)W3SVC.Invoke("CreateNewSite", siteProperty); siteID = siteObj.ToString(); W3SVC.CommitChanges(); } catch (Exception ex) { Console.WriteLine( "Fail to create web site with the following exception: \n{0}", ex.Message); } /////////////////////////////////////////////////////////////////////// // Wait for a while to allow ADSI finish the above operations // and then start the web site. Console.WriteLine("Web site created. Starting IISADSIDemo..."); System.Threading.Thread.Sleep(1000); DirectoryEntry newSite = new DirectoryEntry("IIS://" + ServerName + "/W3SVC/" + siteID); newSite.Invoke("Start"); Console.WriteLine("Started \n"); Console.WriteLine("Create new virtual directory."); // Create new virtual directory. string metabasePath = string.Format("/W3SVC/{0}/Root", siteID); DirectoryEntry site = new DirectoryEntry("IIS://" + ServerName + metabasePath); DirectoryEntries vdirs = site.Children; DirectoryEntry newVDir = vdirs.Add("vdir1", "IIsWebVirtualDir"); newVDir.Properties["Path"][0] = "C:\\inetpub\\IISADSIDemo\\vdir1"; newVDir.Properties["AccessScript"][0] = true; newVDir.Properties["AppFriendlyName"][0] = "vdir1"; newVDir.Properties["AppIsolated"][0] = "1"; newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath + "/vdir1"; newVDir.CommitChanges(); Console.WriteLine("vdir1 created. \n"); // List all web sites on the server. Console.WriteLine("List all web sites on server: \n"); try { foreach (DirectoryEntry Site in W3SVC.Children) { if (Site.SchemaClassName == "IIsWebServer") { Console.WriteLine(Site.Name + " - " + Site.Properties["ServerComment"].Value.ToString()); } } } catch (Exception e) { Console.WriteLine( "Fail to list web sites with the following exception: \n{0}: " + e.ToString()); } Console.WriteLine("\nEnd."); Console.Read(); }
protected void DeleteOldLogFiles() { Thread.Sleep(2000); //Create list of deletes and other. DirectoryEntries oldLogEntries = new DirectoryEntries(); DirectoryEntries otherEntries = new DirectoryEntries(); int logFileKeepDays = Administrator.ProfileManager.SystemProfile.LogFileKeepDays; if (_NewDirectoryListing != null && _NewDirectoryListing.Count > 0) { foreach (DirectoryEntry entry in _NewDirectoryListing) { bool isOldLogFile = false; if (entry.StdType != "dir") { bool isLogFile = false; if (entry.StdType == "log" && !entry.StdFile.StartsWith("Git")) { string[] nameParts = entry.StdFile.Split('_'); foreach (string namePart in nameParts) { if (namePart.Contains("@")) { isLogFile = true; break; } } } if (isLogFile) { DateTime now = DateTime.Now; DateTime LastWriteTime = entry.StdDate; TimeSpan ts = now.Subtract(LastWriteTime); int daysOld = (int)ts.TotalDays; if (Math.Abs(daysOld) > logFileKeepDays) { isOldLogFile = true; } } } if (isOldLogFile) { oldLogEntries.Add(entry); } else { otherEntries.Add(entry); } } } //Effectively remove deletes from list. _NewDirectoryListing = otherEntries; //Perform deletes. int deletedCount = 0; string DateTimeFormat = @"yyyy/MM/dd HH:mm"; string separator = Path.DirectorySeparatorChar.ToString(); try { if (oldLogEntries != null && oldLogEntries.Count > 0) { foreach (DirectoryEntry entry in oldLogEntries) { string fileSpec = entry.StdHlq; if (entry.StdDir != string.Empty) { fileSpec += entry.StdDir; } fileSpec += separator + entry.StdFile; try { DateTime now = DateTime.Now; DateTime lastWriteTime = entry.StdDate; TimeSpan ts = now.Subtract(lastWriteTime); int daysOld = (int)ts.TotalDays; Administrator.OldLogsTracer.WriteTimedMsg("I", String.Format(@"Last Written : {0} Days Old : {1} File : {2} [Deleted]", lastWriteTime.ToString(DateTimeFormat), daysOld.ToString().Trim().PadLeft(3), fileSpec)); Delete(fileSpec); deletedCount++; } catch (Exception ex) { Administrator.OldLogsTracer.WriteTimedMsg("E", ex.Message); } } if (deletedCount > 0) { Administrator.OldLogsTracer.WriteTimedMsg("I", String.Format(@"{0} Log Files Deleted", deletedCount)); } else { Administrator.OldLogsTracer.WriteTimedMsg("I", @"No Log Files Deleted"); } } else { Administrator.OldLogsTracer.WriteTimedMsg("I", @"No Log Files Found"); } } catch (Exception ex) { Administrator.OldLogsTracer.WriteTimedMsg("E", ex.Message); } finally { Thread.Sleep(2000); } }
void _copyViewer_OnSynchronizePlusAction(EventArgs e) { Administrator.Reset(); _copyViewer.EnableControls(false); _overallProgress = new ProgressLink(); _copyViewer.OverallProgress = _overallProgress; _currentActivityProgress = new ProgressLink(); _copyViewer.CurrentActivityProgress = _currentActivityProgress; //Validate all fields. int errorCount = ValidateFields(); if (errorCount > 0) { return; } //Save Parameters. _profileManager.UserSettings.Select(_currentKey); _profileManager.Interrupt.Reason = "OK"; SaveParameters(); RefreshCombo(); //Use directory engine to scan both directories to determine the differences. DateTime startAllDateTime = Administrator.Now; _directoryEngine = new DirectoryEngine(); _directoryEngine.Interrupt = _profileManager.Interrupt; _directoryEngine.EventBeginProgress += new Copy8.EventDelegate(_directoryEngine_OnBeginDirectoryScan); _directoryEngine.EventUpdateProgress += new Copy8.EventDelegate(_directoryEngine_OnUpdateDirectoryScan); _directoryEngine.EventEndOfProgress += new Copy8.EventDelegate(_directoryEngine_OnEndOfDirectoryScan); _directoryEngine.MonitoredTypesOnly = _profileManager.UserSettings.SelectedItem.MonitoredTypesOnly; _directoryEngine.Interrupt = _profileManager.Interrupt; _processingNew = true; _NewDirectoryListing = _directoryEngine.DirList(_profileManager.UserSettings.SelectedItem.NewBaseDir, ref mnNewFilesEstimate); _TotalBytes = mnNewFilesEstimate; //Delete log files older that the specified number of days. DeleteOldLogFiles(); _processingNew = false; string targetDirectory = _profileManager.UserSettings.SelectedItem.OldBaseDir; if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } _directoryEngine.TargetHlq = targetDirectory; mnOldFilesEstimate = mnNewFilesEstimate; // Instead of scanning the target directory. // Load the previously synchronized snapshot to compare against. if (File.Exists(getSnapshotFileSpec(targetDirectory))) { _OldDirectoryListing = new DirectoryEntries(); _OldDirectoryListing.Load(getSnapshotFileSpec(targetDirectory), DirectoryEntries.InterpretationEnum.Target); } else { _OldDirectoryListing = _directoryEngine.DirList(targetDirectory, ref mnOldFilesEstimate); } _directoryEngine.Compare(ref _OldDirectoryListing, ref _NewDirectoryListing); _directoryEngine.Changes(_OldDirectoryListing, _NewDirectoryListing, ref _ChangedDirectoryListing, ref mnChgFilesEstimate); _comparisons = _directoryEngine.Comparisons; _copyEngine.Interrupt = _profileManager.Interrupt; //Use the Synchronize engine to perform the synchronize. //TODO: Move the directory engine calls inside the Synchronize engine. _synchronizeEngine = new SynchronizeEngine(); _synchronizeEngine.OnBeginSynchronize += new SynchronizeEngine.BeginSynchronizeHandler(_SynchronizeEngine_OnBeginSynchronize); _synchronizeEngine.OnUpdateSynchronize += new SynchronizeEngine.UpdateSynchronizeHandler(_SynchronizeEngine_OnUpdateSynchronize); _synchronizeEngine.OnEndOfSynchronize += new SynchronizeEngine.EndOfSynchronizeHandler(_SynchronizeEngine_OnEndOfSynchronize); _synchronizeEngine.CopyRule = _profileManager.UserSettings.SelectedItem.CopyRule; _synchronizeEngine.MonitoredTypesOnly = _profileManager.UserSettings.SelectedItem.MonitoredTypesOnly; _synchronizeEngine.Interrupt = _profileManager.Interrupt; try { _synchronizeEngine.Process(_comparisons, startAllDateTime); //After synchronization the target directory is synchronized with the source directory. _NewDirectoryListing.Save(getSnapshotFileSpec(targetDirectory)); Administrator.View(); } catch (ParameterException pe) { _copyViewer.SetFieldError(pe.Parameter, pe.Message); //_copyViewer.DisplayMessageBox(ae.Message, _copyViewer.Caption, MsgButtons.OK, MsgIcon.Error); } finally { _copyViewer.EnableControls(true); } }
static void Main(string[] args) { Stack <IDisposable> disposer = new Stack <IDisposable>(); try { // "log in" to SharePoint and SLK as the current user SPSite spSite = new SPSite(ParentWebUrl); disposer.Push(spSite); s_parentWeb = spSite.OpenWeb(); disposer.Push(s_parentWeb); s_slkStore = SlkStore.GetStore(s_parentWeb); // set <instructorPermission> and <learnerPermission> to the name of the SharePoint // permission (or "role definition", to be more precise) that indicates that a user // is a SLK instructor or learner, respectively; examples: "SLK Instructor", // "SLK Learner" string instructorPermission = s_slkStore.Mapping.InstructorPermission; string learnerPermission = s_slkStore.Mapping.LearnerPermission; // initialize <s_computerChildren> and <s_guests>, used by CreateUser DirectoryEntry computer = new DirectoryEntry( String.Format("WinNT://{0},computer", Environment.MachineName)); disposer.Push(computer); s_computerChildren = computer.Children; s_guests = s_computerChildren.Find("Guests", "group"); disposer.Push(s_guests); // if <DeleteWebsOnly> is true, just delete the <NumberOfWebs> Web sites and exit #if DeleteWebsOnly for (int webNumber = 1; webNumber <= NumberOfWebs; webNumber++) { DeleteWeb(String.Format("SlkSampleWeb{0}", webNumber)); } return; #else // create SharePoint Web sites for simulated training classes, if they don't exist // yet; if they do exist, remove the instructors and learners on those sites for (int webNumber = 1; webNumber <= NumberOfWebs; webNumber++) { CreateWeb(String.Format("SlkSampleWeb{0}", webNumber), String.Format("SLK Sample Web Site {0}", webNumber)); } // create local machine accounts for simulated instructors (if they don't exist yet), // and add them as instructors on <WebsPerInstructor> randomly-chosen Web sites; also, // ensure each instructor has read access to each file listed in // <SimulateClassProgram.PackageUrls> (in ..\SimulateClass\SimulateClass.cs) for (int instructorNumber = 1; instructorNumber <= NumberOfInstructors; instructorNumber++) { // create the user account string loginName = String.Format(InstructorLoginNamePrefix + "{0}", instructorNumber); string fullName = String.Format("SLK Sample Instructor {0}", instructorNumber); CreateUser(loginName, fullName); // add the user as instructors on <WebsPerInstructor> randomly-chosen Web sites foreach (int webNumber in ShuffledNumbers(1, NumberOfWebs, WebsPerInstructor)) { string relativeUrl = String.Format("SlkSampleWeb{0}", webNumber); AddUserToWeb(loginName, relativeUrl, instructorPermission); } // ensure the instructor has read access to each file listed in // <SimulateClassProgram.PackageUrls> (in ..\SimulateClass\SimulateClass.cs) for (int packageIndex = 0; packageIndex < SimulateClassProgram.PackageUrls.Length; packageIndex++) { string packageUrl = SimulateClassProgram.PackageUrls[packageIndex]; GiveUserReadAccessToFile(loginName, packageUrl); } } // create local machine accounts for simulated learners (if they don't exist yet), // and add them as learners on <WebsPerLearner> randomly-chosen Web sites for (int learnerNumber = 1; learnerNumber <= NumberOfLearners; learnerNumber++) { // create the user account string loginName = String.Format(LearnerLoginNamePrefix + "{0}", learnerNumber); string fullName = String.Format("SLK Sample Learner {0}", learnerNumber); CreateUser(loginName, fullName); // add the user as learners on <WebsPerLearner> randomly-chosen Web sites foreach (int webNumber in ShuffledNumbers(1, NumberOfWebs, WebsPerLearner)) { string relativeUrl = String.Format("SlkSampleWeb{0}", webNumber); AddUserToWeb(loginName, relativeUrl, learnerPermission); } } // ensure all our Web sites have at least one instructor and one learner -- if any // don't, randomly select an instructor and/or learner as needed IEnumerator <int> shuffledInstructorNumbers = ShuffledNumbers(1, NumberOfInstructors, int.MaxValue).GetEnumerator(); IEnumerator <int> shuffledLearnerNumbers = ShuffledNumbers(1, NumberOfLearners, int.MaxValue).GetEnumerator(); for (int webNumber = 1; webNumber <= NumberOfWebs; webNumber++) { string relativeUrl = String.Format("SlkSampleWeb{0}", webNumber); if (!DoesWebHaveAnyoneWithPermission(relativeUrl, instructorPermission)) { shuffledInstructorNumbers.MoveNext(); string loginName = String.Format(InstructorLoginNamePrefix + "{0}", shuffledInstructorNumbers.Current); AddUserToWeb(loginName, relativeUrl, instructorPermission); } if (!DoesWebHaveAnyoneWithPermission(relativeUrl, learnerPermission)) { shuffledLearnerNumbers.MoveNext(); string loginName = String.Format(LearnerLoginNamePrefix + "{0}", shuffledLearnerNumbers.Current); AddUserToWeb(loginName, relativeUrl, learnerPermission); } } // create assignments in each of the Web sites we created for (int webNumber = 1; webNumber <= NumberOfWebs; webNumber++) { string relativeUrl = String.Format("SlkSampleWeb{0}", webNumber); Console.WriteLine("Creating assignments in Web site {0} of {1}: {2}", webNumber, NumberOfWebs, relativeUrl); using (SPWeb spWeb = s_parentWeb.Webs[relativeUrl]) { SimulateClassProgram.RunProgram(spWeb.Url); } } #endif } finally { // dispose of objects used by this method while (disposer.Count > 0) { disposer.Pop().Dispose(); } } }
/// <summary> /// Method validates the requirements under LDSCrossRefContainer Scenario. /// </summary> public void ValidateLDSCrossRefContainer() { DirectoryEntry dirPartitions = new DirectoryEntry(); DirectoryEntry domainEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); DirectoryEntry requiredEntry = new DirectoryEntry(); string systemFlag; int systemFlagVal; //Variables for holding the paths for NCs. if (!adAdapter.GetLdsObjectByDN("CN=Partitions,CN=Configuration," + adAdapter.LDSRootObjectName, out dirPartitions)) { DataSchemaSite.Assert.IsTrue( false, "CN=Partitions,CN=Configuration," + adAdapter.LDSRootObjectName + "Object is not found in server"); } string parentAttribute = dirPartitions.Parent.Name.ToString(); //MS-ADTS-Schema_R402 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", parentAttribute, 402, "The Parent of the Cross-Ref-Container Container must be Config NC root."); //MS-ADTS-Schema_R403 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "Partitions", dirPartitions.Properties["name"].Value.ToString(), 403, "The name attribute of the Cross-Ref-Container Container must be Partitions."); PropertyValueCollection objectClass = dirPartitions.Properties["objectClass"]; //MS-ADTS-Schema_R404 DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"crossRefContainer"), 404, "The objectClass attribute of the Cross-Ref-Container Container must be crossRefContainer."); //MS-ADTS-Schema_R406 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 406, "The systemFlags attribute of the Cross-Ref-Container Container must be FLAG_DISALLOW_DELETE."); bool isCrossRef = true; bool isObjectClassCrossRef = true; DirectoryEntries Childs = dirPartitions.Children; foreach (DirectoryEntry child in Childs) { if (!child.Parent.Name.Equals("CN=Partitions")) { isCrossRef = false; } PropertyValueCollection objClass = child.Properties["objectClass"]; objClass.RemoveAt(0); if (objClass.Count != 1 || !objClass.Contains((object)"crossRef")) { isObjectClassCrossRef = false; } } //MS-ADTS-Schema_R408 DataSchemaSite.CaptureRequirementIfIsTrue( isCrossRef, 408, "The parent of the Cross-Ref Objects must be crossRefContainer object."); //MS-ADTS-Schema_R409 DataSchemaSite.CaptureRequirementIfIsTrue( isObjectClassCrossRef, 409, "The objectClass attribute of the Cross-Ref Objects must be crossRef."); childEntry = dirPartitions.Children.Find("CN=Enterprise Configuration"); //MS-ADTS-Schema_R410 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration," + adAdapter.LDSRootObjectName, childEntry.Properties["nCName"].Value.ToString(), 410, "The nCName attribute of the Configuration crossRef Object must equal to the config NC root."); //MS-ADTS-Schema_R412 DataSchemaSite.CaptureRequirementIfIsFalse( childEntry.Properties.Contains("dnsRoot"), 412, "In AD/LDS the dnsroot attribute is not presented for the Configuration crossRef Object. "); childEntry = dirPartitions.Children.Find("CN=Enterprise Schema"); //MS-ADTS-Schema_R413 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName, childEntry.Properties["nCName"].Value.ToString(), 413, "The nCName attribute of the Schema crossRef Object must equal to the Schema NC root."); //MS-ADTS-Schema_R415 DataSchemaSite.CaptureRequirementIfIsFalse( childEntry.Properties.Contains("dnsRoot"), 415, "In AD/LDS the dnsroot attribute is not presented for the Schema crossRef Object."); childEntry = dirPartitions.Children.Find("CN=Enterprise Configuration"); //MS-ADTS-Schema_R421 DataSchemaSite.CaptureRequirementIfIsFalse( childEntry.Properties.Contains("dnsRoot"), 421, "In AD/LDS the dnsroot attribute is not presented for Application NC crossRef Object."); //MS-ADTS-Schema_R852 childEntry = dirPartitions.Children.Find("CN=Enterprise Schema"); if (!adAdapter.GetLdsObjectByDN("CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName, out dirPartitions)) { DataSchemaSite.Assert.IsTrue( false, "CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( childEntry.Properties["nCName"].Value.ToString(), dirPartitions.Properties["distinguishedName"].Value.ToString(), 852, "The nCName attribute of the crossRef object must equal the dsname of the NC root object."); }
/// <summary> /// Create an Application VDir for this directory and set its properties to allow the execution of WCF Services /// </summary> static void CreateApplicationVDir(string applicationName) { DirectoryEntry site = new DirectoryEntry(FindSharepointRootPath()); // BUGBUG: Do we want to hardcode this installer to just SharePoint? string className = site.SchemaClassName.ToString(); DirectoryEntries vdirs = site.Children; #region Delete old Application if it exists foreach (DirectoryEntry de in vdirs) { if (de.Name == applicationName) { Console.WriteLine(Strings.DeletingExistingApplication, de.Name); de.DeleteTree(); // Out with the old, in with the new! } } #endregion #region Add the new Application Console.WriteLine(Strings.AddingNewApplication, applicationName); DirectoryEntry vdir = vdirs.Add(applicationName, className); vdir.Properties["AppFriendlyName"][0] = applicationName; string currentPath = new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName; vdir.Properties["Path"][0] = currentPath; // Set this from the currently executing directory vdir.Properties["AccessScript"][0] = true; // Allow scripts vdir.Properties["AuthFlags"][0] = "1"; // Turn on Anonymous authentication vdir.Invoke("AppCreate3", new object[] { 0, "SLK Services", true }); // Make this an Application vdir running in process in a new AppPool named "SLK Services" vdir.CommitChanges(); #endregion #region Fix up the ScriptMap setting that SharePoint removes which breaks WCF Services vdir.RefreshCache(); // Load the default properties that were inherited when the Application was committed foreach (PropertyValueCollection pvc in vdir.Properties) { if (pvc.PropertyName == "ScriptMaps") // Update the ScriptMap to add back in .svc (WCF Service) support { List <object> values = new List <object>(pvc.Value as object[]); bool found = false; foreach (object value in values) { if ((value as string).StartsWith(".svc")) { found = true; break; } } if (!found) { Console.WriteLine(Strings.AddingSvcMapping); values.Add(Strings._SvcScriptMapping); pvc.Value = values.ToArray(); vdir.CommitChanges(); } } } vdir.Close(); #endregion #region Add the MimeType mapping for .grproj PropertyValueCollection mimeMapCollection = site.Properties["MimeMap"]; // Can I just do this on the vdir I wonder...? foreach (IISOle.IISMimeType mimeType in mimeMapCollection) { if (mimeType.Extension == ".grproj") { mimeMapCollection.Remove(mimeType); break; } } IISOle.MimeMapClass mimeMapping = new IISOle.MimeMapClass(); mimeMapping.Extension = ".grproj"; mimeMapping.MimeType = "x-ms-gravaproject"; mimeMapCollection.Add(mimeMapping); site.CommitChanges(); #endregion }
// <summary> /// This method validates the requirements under /// SitesContainer Scenario. /// </summary> public void ValidateSitesContainer() { //Declaring the DirectoryEntry variables for holding the objects. DirectoryEntry dirPartitions = new DirectoryEntry(); DirectoryEntry domainEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); string currDomain = adAdapter.rootDomainDN; string configNC = "CN=Configuration," + currDomain; string SchemaNC = "CN=Schema," + configNC; string systemFlag = String.Empty; int systemFlagVal; //MS-ADTS-Schema_R423 if (!adAdapter.GetObjectByDN("CN=Sites," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue(false, "CN=Sites," + configNC + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", dirPartitions.Parent.Name.ToString(), 423, "Each forest contains a Sites container in the Config NC."); //MS-ADTS-Schema_R425 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", dirPartitions.Parent.Name.ToString(), 425, "The parent of the Sites Container must be Config NC root object."); //MS-ADTS-Schema_R426 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"sitesContainer"), 426, "The objectClass attribute of the Sites Container must be sitesContainer."); //MS-ADTS-Schema_R428 DirectoryEntries dirEntriesForValue = dirPartitions.Children; bool isParentRoles = false; foreach (DirectoryEntry child in dirEntriesForValue) { if (child.Parent.Name.ToString().Equals("CN=Sites")) { isParentRoles = true; } } DataSchemaSite.CaptureRequirementIfIsTrue( isParentRoles, 428, "The parent of the Site Object must be Sites container."); //MS-ADTS-Schema_R429 childEntry = dirPartitions.Children.Find("CN=Default-First-Site-Name"); DataSchemaSite.CaptureRequirementIfIsTrue( childEntry.Properties["objectClass"].Contains((object)"site"), 429, "The objectClass attribute of the Site Object must be Site."); //MS-ADTS-Schema_R427 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE|FLAG_DISALLOW_MOVE_ON_DELETE"); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 427, @"The SytemFlags attribute of the Sites Container must be either of FLAG_DISALLOW_DELETE|FLAG_DISALLOW_MOVE_ON_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R430 systemFlag = childEntry.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_CONFIG_ALLOW_RENAME|FLAG_DISALLOW_MOVE_ON_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 430, @"The SytemFlags attribute of the Site Object must be either of FLAG_CONFIG_ALLOW_RENAME|FLAG_DISALLOW_MOVE_ON_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R431 DirectoryEntry sitesEntry = new DirectoryEntry(); if (!adAdapter.GetObjectByDN("CN=Sites,CN=Configuration," + currDomain, out sitesEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Sites,CN=Configuration," + currDomain + " Object is not found in server"); } sitesEntry = sitesEntry.Children.Find("CN=Default-First-Site-Name"); DirectoryEntries sitesChildren = sitesEntry.Children; foreach (DirectoryEntry child in sitesChildren) { PropertyValueCollection v = child.Properties["objectClass"]; if (child.Properties["objectClass"].Contains((object)"nTDSSiteSettings")) { //MS-ADTS-Schema_R432 // [Since objectClass (sitesEntry) contains nTDSSiteSettings, R432 is captured.] DataSchemaSite.CaptureRequirement( 432, "The objectClass attribute of the NTDS Site Settings Object must be nTDSSiteSettings."); } } //MS-ADTS-Schema_R431 DataSchemaSite.Log.Add(LogEntryKind.Debug, "Verify MS-ADTS-Schema_R431"); DataSchemaSite.CaptureRequirementIfIsTrue( sitesEntry.Parent.Name.ToString().Contains("CN=Sites"), 431, "The parent of the NTDS Site Settings Object must be site object."); //MS-ADTS-Schema_R457 if (!adAdapter.GetObjectByDN("CN=Subnets,CN=Sites," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Subnets,CN=Sites," + configNC + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 457, "Each forest contains a Subnets container in the config NC."); //MS-ADTS-Schema_R458 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 458, "The Parent of the Subnet container must be Sites container."); //MS-ADTS-Schema_R459 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"subnetContainer"), 459, "The ObjectClass attribute of the Subnet container must be subnetContainer."); //MS-ADTS-Schema_R460 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 460, "The SystemFlags attribute of the Subnet container must be FLAG_DISALLOW_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R465 if (!adAdapter.GetObjectByDN("CN=Inter-Site Transports,CN=Sites," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Inter-Site Transports,CN=Sites," + configNC + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 465, "The Parent of the IP Transport Container must be Inter-Site Transports container."); //MS-ADTS-Schema_R466 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"interSiteTransportContainer"), 466, "The ObjectClass attribute of the Inter-Site Transports Container must be interSiteTransportContainer."); //MS-ADTS-Schema_R467 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 467, "The SystemFlags attribute of the Inter-Site Transports Container must be FLAG_DISALLOW_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R468 childEntry = dirPartitions.Children.Find("CN=IP"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Inter-Site Transports", childEntry.Parent.Name.ToString(), 468, "The Parent of the IP Transport Container must be Inter-Site Transports container."); //MS-ADTS-Schema_R469 DataSchemaSite.CaptureRequirementIfIsTrue( childEntry.Properties["objectClass"].Contains((object)"interSiteTransport"), 469, "The ObjectClass attribute of the IP Transport Container must be interSiteTransport."); List <DirectoryAttribute> atts = new List <DirectoryAttribute>(); string ret = AdLdapClient.Instance().ConnectAndBind( adAdapter.PDCNetbiosName, adAdapter.PDCIPAddr, Convert.ToInt32(adAdapter.ADDSPortNum), adAdapter.DomainAdministratorName, adAdapter.DomainUserPassword, adAdapter.PrimaryDomainNetBiosName, AuthType.Basic | AuthType.Kerberos); if (ret.Equals("Success_STATUS_SUCCESS")) { atts.Add(new DirectoryAttribute("objectClass", new String[] { "top", "site" })); string testDistinguishedName = "CN=test,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN; AdLdapClient.Instance().AddObject(testDistinguishedName, atts, null); atts.Clear(); atts.Add(new DirectoryAttribute("siteList", new String[] { "CN=test,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN })); atts.Add(new DirectoryAttribute("objectClass", new String[] { "top", "siteLink" })); string testLinkDistinguishedName = "CN=testlink,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN; AdLdapClient.Instance().AddObject(testLinkDistinguishedName, atts, null); atts.Clear(); atts.Add(new DirectoryAttribute("siteLinkList", new String[] { "CN=DEFAULTIPSITELINK,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN, "CN=testLink,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN })); atts.Add(new DirectoryAttribute("objectClass", new String[] { "top", "siteLinkBridge" })); string testLinkBridgeDistinguishedName = "CN=testLinkBridge,CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + adAdapter.rootDomainDN; string result = AdLdapClient.Instance().AddObject(testLinkBridgeDistinguishedName, atts, null); DataSchemaSite.Assert.AreEqual <string>("Success_STATUS_SUCCESS", result, "create dynamic object {0} succeeded", testLinkBridgeDistinguishedName); if (!adAdapter.GetObjectByDN("CN=Subnets,CN=Sites," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Subnets,CN=Sites," + configNC + " Object is not found in server"); } //MS-ADTS-Schema_R462,MS-ADTS-Schema_R463 and MS-ADTS-Schema_R464 //The Parent of the Subnet Object must be Subnets container. DirectoryEntries subnetChilds; subnetChilds = dirPartitions.Children; foreach (DirectoryEntry child in subnetChilds) { DataSchemaSite.Log.Add(LogEntryKind.Debug, "Subnet name is a valid subnet name if:"); string name = child.Properties["name"].Value.ToString(); int count = name.Split('/').Length - 1; DataSchemaSite.Assert.AreEqual(1, count, "1. There should be only one occurrence of the character \"/\" in subnet name:{0}.", name); int i = name.IndexOf('/'); string s1 = name.Substring(0, i); DataSchemaSite.Assert.AreNotEqual(0, s1.IndexOf('0'), "2. Let i be the index of the character \"/\" in name, the substring name[0, i-1]:{0} does not have any leading zeros.", s1); System.Net.IPAddress subnetIP = null; bool isValid = false; isValid = System.Net.IPAddress.TryParse(s1, out subnetIP); DataSchemaSite.Assert.IsTrue(isValid, "2. The substring name[0, i-1]:{0} should be either a valid IPv4 address in dotted decimal notation or a valid IPv6 address in colon-hexadecimal form or compressed form.", s1); string s2 = name.Substring(i + 1); DataSchemaSite.Assert.AreNotEqual(0, s2.IndexOf('0'), "3. The substring name[i+1, l-1]:{0} does not have any leading zeros.", s2); uint n; isValid = false; isValid = uint.TryParse(s2, out n); DataSchemaSite.Assert.IsTrue(isValid, "3. The substring name[i+1, l-1] should be able to be converted to an unsigned integer n:{0}.", n); isValid = false; if (subnetIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { if (n > 0 && n <= 32) { isValid = true; } } else if (subnetIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { if (n > 0 && n <= 128) { isValid = true; } } else { isValid = false; } DataSchemaSite.Assert.IsTrue(isValid, "4. When the address is in IPv4 format, 0 < n:{0} <= 32. When the address is in IPv6 format, 0 < n:{0} <= 128.", n); uint[] bitMask = new uint[] { 0x00000000, 0x00000080, 0x000000C0, 0x000000E0, 0x000000F0, 0x000000F8, 0x000000FC, 0x000000FE, 0x000000FF, 0x000080FF, 0x0000C0FF, 0x0000E0FF, 0x0000F0FF, 0x0000F8FF, 0x0000FCFF, 0x0000FEFF, 0x0000FFFF, 0x0080FFFF, 0x00C0FFFF, 0x00E0FFFF, 0x00F0FFFF, 0x00F8FFFF, 0x00FCFFFF, 0x00FEFFFF, 0x00FFFFFF, 0x80FFFFFF, 0xC0FFFFFF, 0xE0FFFFFF, 0xF0FFFFFF, 0xF8FFFFFF, 0xFCFFFFFF, 0xFEFFFFFF, 0xFFFFFFFF }; if (subnetIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { uint ipInt = BitConverter.ToUInt32(subnetIP.GetAddressBytes().Reverse().ToArray(), 0); uint res = ipInt & (~bitMask[n]); DataSchemaSite.Assert.AreEqual <uint>(0, res, "5. Let b be the binary representation of the address, when the address is in IPv4 format, b & (~BitMask[n]) = 0."); DataSchemaSite.Assert.IsTrue(ipInt != bitMask[n], "6. When the address is in IPv4 format, b != BitMask[n]."); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Subnets", child.Parent.Name.ToString(), 462, "The Parent of the Subnet Object must be Subnets container."); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "subnet", child.SchemaClassName, 463, "The ObjectClass attribute of the Subnet Object must be Subnet."); systemFlag = child.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_CONFIG_ALLOW_RENAME"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 464, "The SystemFlags attribute of the Subnet must be FLAG_CONFIG_ALLOW_RENAME."); } //MS-ADTS-Schema_R476,MS-ADTS-Schema_R477 and MS-ADTS-Schema_R478 subnetChilds = childEntry.Children; foreach (DirectoryEntry child in subnetChilds) { if (child.SchemaClassName.ToLower() == "siteLinkBridge".ToLower()) { DataSchemaSite.CaptureRequirementIfIsTrue( child.Properties["objectClass"].Contains("siteLinkBridge"), 476, "The ObjectClass attribute of the Site Link Bridge Object must be siteLinkBridge."); systemFlag = child.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_CONFIG_ALLOW_RENAME"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 477, "The SystemFlags attribute of the Site Link Bridge Object must be FLAG_CONFIG_ALLOW_RENAME."); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=IP", child.Parent.Name.ToString(), 478, @"The Parent of the Site Link Bridge Object must be Either IP Transport container or SMTP Transport container."); } } if (!AdLdapClient.Instance().DeleteObject(testLinkBridgeDistinguishedName, null).Equals("Success_STATUS_SUCCESS")) { DataSchemaSite.Assume.Fail("The created dynamic object" + testLinkBridgeDistinguishedName + " can not be deleted."); } if (!AdLdapClient.Instance().DeleteObject(testLinkDistinguishedName, null).Equals("Success_STATUS_SUCCESS")) { DataSchemaSite.Assume.Fail("The created dynamic object" + testLinkDistinguishedName + " can not be deleted."); } if (!AdLdapClient.Instance().DeleteObject(testDistinguishedName, null).Equals("Success_STATUS_SUCCESS")) { DataSchemaSite.Assume.Fail("The created dynamic object" + testDistinguishedName + " can not be deleted."); } } else { DataSchemaSite.Assume.Fail("It's failed to connect and bind to AD/DS "); } AdLdapClient.Instance().Unbind(); //MS-ADTS-Schema_R472 domainEntry = childEntry.Children.Find("CN=DEFAULTIPSITELINK"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=IP", domainEntry.Parent.Name.ToString(), 472, @"The Parent of the Site Link Bridge Object must be Either IP Transport container or SMTP Transport container."); //MS-ADTS-Schema_R473 DataSchemaSite.CaptureRequirementIfIsTrue( domainEntry.Properties["objectClass"].Contains((object)"siteLink"), 473, "The ObjectClass attribute of the Site Link Object must be siteLink."); //MS-ADTS-Schema_R474 systemFlag = domainEntry.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_CONFIG_ALLOW_RENAME"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 474, "The SystemFlags attribute of the Site Link Object must be FLAG_CONFIG_ALLOW_RENAME."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } if (!adAdapter.GetObjectByDN("CN=Inter-Site Transports,CN=Sites," + configNC, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Inter-Site Transports,CN=Sites," + configNC + " Object is not found in server"); } //MS-ADTS-Schema_R470 childEntry = dirPartitions.Children.Find("CN=SMTP"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Inter-Site Transports", childEntry.Parent.Name.ToString(), 470, "The Parent of the SMTP Transport Container must be Inter-Site Transports container."); //MS-ADTS-Schema_R471 DataSchemaSite.CaptureRequirementIfIsTrue( childEntry.Properties["objectClass"].Contains((object)"interSiteTransport"), 471, "The ObjectClass attribute of the SMTP Transport Container must be interSiteTransport."); }
public IDirectoryEntries Create(DirectoryEntries directoryEntries) { return(new DirectoryEntriesWrapper(directoryEntries)); }
// <summary> /// This method validates the requirements under /// LDSSitesContainer Scenario. /// </summary> public void ValidateLDSSitesContainer() { DirectoryEntry dirPartitions = new DirectoryEntry(); DirectoryEntry domainEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); string systemFlag; int systemFlagVal; string configNCForLDS = "CN=Configuration," + adAdapter.LDSRootObjectName; string SchemaNC = "CN=Schema," + configNCForLDS; //MS-ADTS-Schema_R423 if (!adAdapter.GetLdsObjectByDN("CN=Sites," + configNCForLDS, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Sites," + configNCForLDS + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", dirPartitions.Parent.Name.ToString(), 423, "Each forest contains a Sites container in the Config NC."); //MS-ADTS-Schema_R425 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Configuration", dirPartitions.Parent.Name.ToString(), 425, "The parent of the Sites Container must be Config NC root object."); //MS-ADTS-Schema_R426 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"sitesContainer"), 426, "The objectClass attribute of the Sites Container must be sitesContainer."); //MS-ADTS-Schema_R427 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE|FLAG_DISALLOW_MOVE_ON_DELETE"); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 427, @"The SytemFlags attribute of the Sites Container must be either of FLAG_DISALLOW_DELETE|FLAG_DISALLOW_MOVE_ON_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R428 DirectoryEntries dirEntriesForValue = dirPartitions.Children; bool isParentRoles = false; foreach (DirectoryEntry child in dirEntriesForValue) { if (child.Properties["objectCategory"].Value.ToString().ToLower().Contains("cn=site")) { isParentRoles = true; } } DataSchemaSite.CaptureRequirementIfIsTrue( isParentRoles, 428, "The parent of the Site Object must be Sites container."); //MS-ADTS-Schema_R429 childEntry = dirPartitions.Children.Find("CN=Default-First-Site-Name"); DataSchemaSite.CaptureRequirementIfIsTrue( childEntry.Properties["objectClass"].Contains((object)"site"), 429, "The objectClass attribute of the Site Object must be Site."); //MS-ADTS-Schema_R430 systemFlag = childEntry.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_CONFIG_ALLOW_RENAME|FLAG_DISALLOW_MOVE_ON_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 430, @"The SytemFlags attribute of the Site Object must be either of FLAG_CONFIG_ALLOW_RENAME|FLAG_DISALLOW_MOVE_ON_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R457 if (!adAdapter.GetLdsObjectByDN("CN=Subnets,CN=Sites," + configNCForLDS, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Subnets,CN=Sites," + configNCForLDS + " Object is not found in server"); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 457, "Each forest contains a Subnets container in the config NC."); //MS-ADTS-Schema_R458 DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 458, "The Parent of the Subnet container must be Sites container."); //MS-ADTS-Schema_R459 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"subnetContainer"), 459, "The ObjectClass attribute of the Subnet container must be subnetContainer."); //MS-ADTS-Schema_R460 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 460, "The SystemFlags attribute of the Subnet container must be FLAG_DISALLOW_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R465 if (!adAdapter.GetLdsObjectByDN("CN=Inter-Site Transports,CN=Sites," + configNCForLDS, out dirPartitions)) { DataSchemaSite.Assume.IsTrue( false, "CN=Inter-Site Transports,CN=Sites," + configNCForLDS + " Object is not found in server."); } DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Sites", dirPartitions.Parent.Name.ToString(), 465, "The Parent of the IP Transport Container must be Inter-Site Transports container."); //MS-ADTS-Schema_R466 DataSchemaSite.CaptureRequirementIfIsTrue( dirPartitions.Properties["objectClass"].Contains((object)"interSiteTransportContainer"), 466, "The ObjectClass attribute of the Inter-Site Transports Container must be interSiteTransportContainer."); //MS-ADTS-Schema_R467 systemFlag = dirPartitions.Properties["systemFlags"].Value.ToString(); systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlagVal.ToString(), systemFlag, 467, "The SystemFlags attribute of the Inter-Site Transports Container must be FLAG_DISALLOW_DELETE."); if (systemFlag != (systemFlagVal.ToString())) { isParseSystemFlagsValue = false; } //MS-ADTS-Schema_R468 childEntry = dirPartitions.Children.Find("CN=IP"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=Inter-Site Transports", childEntry.Parent.Name.ToString(), 468, "The Parent of the IP Transport Container must be Inter-Site Transports container."); //MS-ADTS-Schema_R469 DataSchemaSite.CaptureRequirementIfIsTrue( childEntry.Properties["objectClass"].Contains((object)"interSiteTransport"), 469, "The ObjectClass attribute of the IP Transport Container must be interSiteTransport."); //MS-ADTS-Schema_R472 domainEntry = childEntry.Children.Find("CN=DEFAULTIPSITELINK"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "CN=IP", domainEntry.Parent.Name.ToString(), 472, @"The Parent of the Site Link Bridge Object must be Either IP Transport container or SMTP Transport container."); //MS-ADTS-Schema_R473 DataSchemaSite.CaptureRequirementIfIsTrue( domainEntry.Properties["objectClass"].Contains((object)"siteLink"), 473, "The ObjectClass attribute of the Site Link Object must be siteLink."); }
/// <summary> /// get Constructed claims for a principal /// </summary> /// <param name="principal">the target principal</param> /// <param name="principalClass">user or device</param> /// <returns>a CLAIMS_ARRAY contains claims of the principal</returns> CLAIMS_ARRAY getConstructedClaims(DirectoryEntry principal, ClaimsPrincipalClass principalClass) { CLAIMS_ARRAY ret = new CLAIMS_ARRAY(); DirectoryEntry root = new DirectoryEntry(ConstValue.claimTypesPath + domainNC); List <CLAIM_ENTRY> claims = new List <CLAIM_ENTRY>(); DirectoryEntries children = root.Children; foreach (DirectoryEntry de in children) { //source type should be Constructed if ((de.Properties[ConstValue.msDSClaimSourceType] == null) || ((ClaimsSourceType)Enum.Parse(typeof(ClaimsSourceType), de.Properties[ConstValue.msDSClaimSourceType].Value.ToString(), true) != ClaimsSourceType.Constructed) || (de.Properties[ConstValue.msDSClaimTypeAppliesToClass] == null)) { continue; } //should applies to this principal class bool classMatched = false; foreach (object str in de.Properties[ConstValue.msDSClaimTypeAppliesToClass]) { string tmp = str.ToString(); if (tmp.ToLower() == (ConstValue.userRDN + domainNC.ToLower()) && principalClass == ClaimsPrincipalClass.User) { classMatched = true; break; } if ((tmp.ToLower() == (ConstValue.computerRDN + domainNC).ToLower()) && principalClass == ClaimsPrincipalClass.Device) { classMatched = true; break; } } if (!classMatched) { continue; } //validate claim definition if (!validateClaimDefinition(de)) { continue; } if (de.Properties[ConstValue.name] == null || de.Properties[ConstValue.name].Value == null) { continue; } //Currently only the AuthenticationSilo claim is supported if (de.Properties[ConstValue.name].Value.ToString().Equals(ConstValue.authSiloClaimName, StringComparison.OrdinalIgnoreCase)) { CLAIM_ENTRY?claim = getAuthSiloClaim(principal); if (claim.HasValue) { claims.Add(claim.Value); } break; } } ret.ulClaimsCount = (uint)claims.Count; ret.ClaimEntries = claims.ToArray(); ret.usClaimsSourceType = 1; return(ret); }
/// <summary> /// Method validates the requirements under RolesContainer Scenario. /// </summary> public void ValidateLDSRoleContainer() { DirectoryEntry dirEntryConfig = new DirectoryEntry(); DirectoryEntry dirEntryApp = new DirectoryEntry(); DirectoryEntry dirEntrySch = new DirectoryEntry(); DirectoryEntry dirEntry = new DirectoryEntry(); if (!adAdapter.GetLdsObjectByDN("CN=Roles," + adAdapter.LDSApplicationNC, out dirEntryApp)) { DataSchemaSite.Assert.IsTrue( false, "CN=Roles," + adAdapter.LDSApplicationNC + " Object is not found in server"); } if (!adAdapter.GetLdsObjectByDN("CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntryConfig)) { DataSchemaSite.Assert.IsTrue( false, "CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } //MS-ADTS-Schema_R768 DataSchemaSite.CaptureRequirementIfIsTrue( dirEntryApp != null && dirEntryConfig != null, 768, "For the Roles Container the Parent must be Application NC root or config NC root."); //MS-ADTS-Schema_R769 DataSchemaSite.CaptureRequirementIfIsTrue( dirEntryApp.Properties["objectClass"].Contains((object)"container"), 769, "The objectClass attribute of Roles Container must be container."); //MS-ADTS-Schema_R770 string systemFlag = dirEntryConfig.Properties["systemFlags"].Value.ToString(); int systemFlagVal = ParseSystemFlagsValue("FLAG_DISALLOW_DELETE"); DataSchemaSite.CaptureRequirementIfAreEqual <string>( systemFlag, systemFlagVal.ToString(), 770, "The systemFlags attribute of Roles Container must be FLAG_DISALLOW_DELETE."); DirectoryEntries rolesChilds = dirEntryConfig.Children; bool isParentRoles = true; foreach (DirectoryEntry child in rolesChilds) { if (!child.Parent.Name.ToString().Equals("CN=Roles")) { isParentRoles = false; } } //MS-ADTS-Schema_R771 DataSchemaSite.CaptureRequirementIfIsTrue( isParentRoles, 771, "For each child of the Roles Container the Parent must be Roles Container."); //MS-ADTS-Schema_R772 rolesChilds = dirEntryConfig.Children; List <DirectoryEntry> wellKnownRolesChilds = new List <DirectoryEntry>(); bool isGroup = true; foreach (DirectoryEntry child in rolesChilds) { if (child.Properties["cn"].ToString().Equals("Administrators") || child.Properties["cn"].ToString().Equals("Instances") || child.Properties["cn"].ToString().Equals("Readers") || child.Properties["cn"].ToString().Equals("Users")) { wellKnownRolesChilds.Add(child); if (!child.Properties["objectClass"].Contains((object)"group")) { isGroup = false; } } } DataSchemaSite.CaptureRequirementIfIsTrue( isGroup, 772, "The objectClass attribute for each child of the Roles Container must be group."); if (serverOS >= OSVersion.WinSvr2008) { //MS-ADTS-Schema_R773 if (!adAdapter.GetLdsObjectByDN( "CN=Administrators,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Administrators,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } byte[] objSid = (byte[])dirEntry.Properties["objectSid"].Value; dirEntry.RefreshCache(new string[] { "primaryGrouptoken" }); PropertyValueCollection primaryGroup = dirEntry.Properties["primaryGroupToken"]; SecurityIdentifier sid = new SecurityIdentifier(objSid, 0); string objectSid = sid.ToString(); objectSid = objectSid.Substring(objectSid.LastIndexOf('-') + 1); DataSchemaSite.CaptureRequirementIfAreEqual <string>( objectSid, primaryGroup.Value.ToString(), 773, @"The objectSid attribute for each child of the Roles Container must be a SID with two SubAuthority values,consisting of the objectSid of the NC root followed by the RID."); } //MS-ADTS-Schema_R778 if (!adAdapter.GetLdsObjectByDN( "CN=Administrators,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Administrators,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } PropertyValueCollection memberSec = dirEntry.Properties["member"]; bool isForeignSecurityPrincipalsContained = false; foreach (var prop in memberSec) { if (prop.ToString().Contains("CN=ForeignSecurityPrincipals")) { isForeignSecurityPrincipalsContained = true; break; } } DataSchemaSite.CaptureRequirementIfIsTrue( isForeignSecurityPrincipalsContained, 778, @"The member attribute of Administrators Group Object must be that at least one foreignSecurityPrincipal is configured into this group by the administrator when creating a forest."); //MS-ADTS-Schema_R774 foreach (DirectoryEntry dir1 in wellKnownRolesChilds) { PropertyValueCollection groupType = dir1.Properties["groupType"]; //The {ACCOUNT_GROUP | SECURITY_ENABLED} flag value is equivalent to "0x80000002" with reference //from ADTS groupFlags. int groupTypeValue = (int)groupType.Value; string groupValueType = "0x80000002"; int modelGroup = Convert.ToInt32(groupValueType, 16); if (groupTypeValue == modelGroup) { isGroup = true; } } DataSchemaSite.CaptureRequirementIfIsTrue( isGroup, 774, @"The groupType attribute for each child of theRoles Container must be ACCOUNT_GROUP | SECURITY_ENABLED."); //MS-ADTS-Schema_R776 dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); string primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "519", primary, 776, "The RID attribute of Administrators Group Object must be 519 (in the config NC)."); //MS-ADTS-Schema_R777 if (!adAdapter.GetLdsObjectByDN( "CN=Administrators,CN=Roles," + adAdapter.LDSApplicationNC, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Administrators,CN=Roles," + adAdapter.LDSApplicationNC + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "512", primary, 777, "The RID attribute of Administrators Group Object must be 512 (in an application NC)."); //MS-ADTS-Schema_R779 if (!adAdapter.GetLdsObjectByDN("CN=Readers,CN=Roles," + adAdapter.LDSApplicationNC, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Readers,CN=Roles," + adAdapter.LDSApplicationNC + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "514", primary, 779, "The RID attribute of Readers Group Object must be 514."); dirEntry.RefreshCache(new string[] { "member" }); PropertyValueCollection member = dirEntry.Properties["member"]; object memberValue = member.Value; //MS-ADTS-Schema_R775 DataSchemaSite.CaptureRequirementIfIsNull( memberValue, 775, @"Unless otherwise noted, the initial membership of the member attribute,for each child of the Roles Container must be empty."); //MS-ADTS-Schema_R779 if (!adAdapter.GetLdsObjectByDN( "CN=Readers,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Readers,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "514", primary, 779, "The RID attribute of Readers Group Object must be 514."); //MS-ADTS-Schema_R780 if (!adAdapter.GetLdsObjectByDN("CN=Users,CN=Roles," + adAdapter.LDSApplicationNC, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Users,CN=Roles," + adAdapter.LDSApplicationNC + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "513", primary, 780, "The RID attribute of Users Group Object must be 513."); if (!adAdapter.GetLdsObjectByDN( "CN=Users,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Users,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "513", primary, 780, "The RID attribute of Users Group Object must be 513."); //MS-ADTS-Schema_R782 if (!adAdapter.GetLdsObjectByDN( "CN=Instances,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName, out dirEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Instances,CN=Roles,CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } dirEntry.RefreshCache(new string[] { "primaryGroupToken" }); primary = dirEntry.Properties["primaryGroupToken"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "518", primary, 782, "The RID attribute of Instances Group Object must be 518."); }
internal DirectoryEntriesWrapper(DirectoryEntries directory) { _directoryEntries = directory; }
/// <summary> /// This method validates the requirements under /// WellKnownSecurityDomainPrincipal for both AD/DS and LDS Scenario's. /// The common requirements are logged here. /// </summary> public void LDSAndDSCommonCall(DirectoryEntry directEntry) { GroupTypeFlags gType; //Holding Directory entries. DirectoryEntry dirEntry = new DirectoryEntry(); DirectoryEntry childEntry = new DirectoryEntry(); dirEntry = directEntry; //MS-ADTS-Schema_R810 DirectoryEntries rolesChilds = dirEntry.Children; bool isParentRoles = true; foreach (DirectoryEntry child in rolesChilds) { if (!child.Parent.Name.ToString().Equals("CN=Users")) { isParentRoles = false; } } DataSchemaSite.CaptureRequirementIfIsTrue( isParentRoles, 810, "For the Well-Known Domain-Relative Security Principals the Parent must be Users container"); //MS-ADTS-Schema_R813 childEntry = dirEntry.Children.Find($"CN={adAdapter.DomainAdministratorName}"); PropertyValueCollection objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"user"), 813, "The objectClass attribute of Administrator Well-Known Domain-Relative Security Principals must be user"); //MS-ADTS-Schema_R814 childEntry = dirEntry.Children.Find("CN=Guest"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"user"), 814, "The objectClass attribute of Guest Well-Known Domain-Relative Security Principals must be user"); //MS-ADTS-Schema_R815 childEntry.RefreshCache(new string[] { "primaryGroupID" }); string primary = childEntry.Properties["primaryGroupID"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "514", primary, 815, @"The primaryGroupID attribute of Guest Well-Known Domain-Relative Security Principals must be 514 (Domain Guests)"); //MS-ADTS-Schema_R816 childEntry = dirEntry.Children.Find("CN=krbtgt"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"user"), 816, @"The objectClass attribute of Key Distribution Center Service Account Well-Known Domain-Relative Security Principals must be user"); //MS-ADTS-Schema_R817 childEntry.RefreshCache(new string[] { "primaryGroupID" }); primary = childEntry.Properties["primaryGroupID"].Value.ToString(); DataSchemaSite.CaptureRequirementIfAreEqual <string>( "513", primary, 817, @"The primaryGroupID attribute of Key Distribution Center Service Account Well-Known Domain-Relative Security Principals must be 513 (Domain Users)"); //MS-ADTS-Schema_R818 childEntry = dirEntry.Children.Find("CN=Cert Publishers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 818, @"The objectClass attribute of Key Distribution Center Service Account Well-Known Domain-Relative Security Principals must be user"); //MS-ADTS-Schema_R819 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_RESOURCE_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 819, @"The groupType attribute of Cert Publishers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_RESOURCE_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000004"); //MS-ADTS-Schema_R820 childEntry = dirEntry.Children.Find("CN=Domain Admins"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 820, @"The objectClass attribute of Domain Administrators Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R821 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 821, @"The groupType attribute of Domain Administrators, Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002"); //MS-ADTS-Schema_R822 childEntry = dirEntry.Children.Find("CN=Domain Computers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 822, @"The objectClass attribute of Domain Computers Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R823 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 823, @"The groupType attribute of Domain Computers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002"); //MS-ADTS-Schema_R824 childEntry = dirEntry.Children.Find("CN=Domain Controllers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 824, @"The objectClass attribute of Domain Controllers, Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R825 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 825, @"The groupType attribute of Domain Controllers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002"); //MS-ADTS-Schema_R826 childEntry = dirEntry.Children.Find("CN=Domain Guests"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 826, @"The objectClass attribute of Domain Guests Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R827 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 827, @"The groupType attribute of Domain Guests Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002"); //MS-ADTS-Schema_R828 childEntry = dirEntry.Children.Find("CN=Domain Users"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 828, "The objectClass attribute of Domain Users Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R829 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 829, @"The groupType attribute of Domain Users Well-Known Domain-Relative Security Principals must be either of GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED"); //MS-ADTS-Schema_R833 childEntry = dirEntry.Children.Find("CN=Group Policy Creator Owners"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 833, @"The objectClass attribute of Group Policy Creator Owners Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R834 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 834, @"The groupType attribute of Group Policy Creator Owners Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002"); //MS-ADTS-Schema_R835 childEntry = dirEntry.Children.Find("CN=RAS and IAS Servers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 835, @"The objectClass attribute of RAS and IAS Servers Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R836 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_RESOURCE_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 836, @"The groupType attribute of RAS and IAS Servers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_RESOURCE_GROUP | GROUP_TYPE_SECURITY_ENABLED}.This means that in groupType field the two above bits are set, which means that the groupType is 0x80000004"); //MS-ADTS-Schema_R841 childEntry = dirEntry.Children.Find("CN=Schema Admins"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 841, @"The objectClass attribute of Schema Admins Well-Known Domain-Relative Security Principals must be group"); if (serverOS >= OSVersion.WinSvr2008) { //MS-ADTS-Schema_R830 childEntry = dirEntry.Children.Find("CN=Enterprise Admins"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 830, @"The objectClass attribute of Enterprise Administrators Well-Known Domain-Relative Security Principals must be group."); //MS-ADTS-Schema_R837 childEntry = dirEntry.Children.Find("CN=Read-only Domain Controllers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 837, @"The objectClass attribute of Read-Only Domain Controllers Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R838 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_ACCOUNT_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 838, @"The groupType attribute of Read-Only Domain Controllers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_ACCOUNT_GROUP|GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000002."); //MS-ADTS-Schema_R839 childEntry = dirEntry.Children.Find("CN=Enterprise Read-only Domain Controllers"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.CaptureRequirementIfIsTrue( objectClass.Contains((object)"group"), 839, @"The objectClass attribute of Enterprise Read-Only Domain Controllers Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_R840 groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.CaptureRequirementIfAreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_UNIVERSAL_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, 840, @"The groupType attribute of Enterprise Read-Only Domain Controllers Well-Known Domain-Relative Security Principals is {GROUP_TYPE_UNIVERSAL_GROUP|GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000008."); //MS-ADTS-Schema_Allowed RODC Password Replication Group childEntry = dirEntry.Children.Find("CN=Allowed RODC Password Replication Group"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.Assert.IsTrue( objectClass.Contains((object)"group"), @"The objectClass attribute of Allowed RODC Password Replication Group Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_Allowed RODC Password Replication Group groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.Assert.AreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_RESOURCE_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, @"The groupType attribute of Allowed RODC Password Replication Group Well-Known Domain-Relative Security Principals is {GROUP_TYPE_RESOURCE_GROUP|GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000004."); //MS-ADTS-Schema_Denied RODC Password Replication Group childEntry = dirEntry.Children.Find("CN=Denied RODC Password Replication Group"); objectClass = childEntry.Properties["objectClass"]; DataSchemaSite.Assert.IsTrue( objectClass.Contains((object)"group"), @"The objectClass attribute of Denied RODC Password Replication Group Well-Known Domain-Relative Security Principals must be group"); //MS-ADTS-Schema_Denied RODC Password Replication Group groupType = childEntry.Properties["groupType"]; gType = (GroupTypeFlags)Convert.ToInt32(groupType.Value); DataSchemaSite.Assert.AreEqual <GroupTypeFlags>( GroupTypeFlags.GROUP_TYPE_RESOURCE_GROUP | GroupTypeFlags.GROUP_TYPE_SECURITY_ENABLED, gType, @"The groupType attribute of Denied RODC Password Replication Group Well-Known Domain-Relative Security Principals is {GROUP_TYPE_RESOURCE_GROUP|GROUP_TYPE_SECURITY_ENABLED} This means that in groupType field the two above bits are set, which means that the groupType is 0x80000004."); } }
private void InitializeTV() { Label l; StackPanel sp; TreeViewItem tvi; DirectoryEntry de = new DirectoryEntry(); String top = null; try { top = de.Name.Substring(3); // remove DC= } catch (Exception e) { MessageBox.Show(e.Message, "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error); LDB.Visibility = Visibility.Collapsed; UsersGrid.Visibility = Visibility.Visible; return; } tviTop = new TreeViewItem(); tviTop.IsExpanded = true; Image imageTopLevel = new Image(); imageTopLevel.Source = new BitmapImage(new Uri(@"/MVVM;component/ViewModel/images/computer.ico", UriKind.Relative)); imageTopLevel.Height = 12; l = new Label(); l.Content = top; sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; sp.Children.Add(imageTopLevel); sp.Children.Add(l); tviTop.Header = sp; QBTreeView.Items.Clear(); QBTreeView.Items.Add(tviTop); DirectoryEntries children = de.Children; foreach (DirectoryEntry childEntry in children) { String schemaClass = childEntry.SchemaClassName; if ((schemaClass == "container") || (schemaClass == "organizationalUnit")) { tvi = new TreeViewItem(); l = new Label(); l.Content = childEntry.Name.Substring(3); sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; Image image = new Image(); image.Source = new BitmapImage(new Uri(@"/MVVM;component/ViewModel/images/button.ico", UriKind.Relative)); image.Height = 18; sp.Children.Add(image); sp.Children.Add(l); tvi.Header = sp; tvi.Tag = (String)childEntry.Path; tvi.Margin = new Thickness(-20, -4, -4, -4); tviTop.Items.Add(tvi); } } }
//获取虚拟目录集合 private VirtualDirectories GetVirDirs(DirectoryEntries des) { VirtualDirectories tmpdirs = new VirtualDirectories(); foreach (DirectoryEntry de in des) { if (de.SchemaClassName == "IIsWebVirtualDir") { VirtualDirectory vd = new VirtualDirectory(); vd.Name = de.Name; vd.AccessRead = (bool)de.Properties["AccessRead"][0]; vd.AccessExecute = (bool)de.Properties["AccessExecute"][0]; vd.AccessWrite = (bool)de.Properties["AccessWrite"][0]; vd.AnonymousUserName = (string)de.Properties["AnonymousUserName"][0]; vd.AnonymousUserPass = (string)de.Properties["AnonymousUserName"][0]; vd.AuthBasic = (bool)de.Properties["AuthBasic"][0]; vd.AuthNTLM = (bool)de.Properties["AuthNTLM"][0]; vd.ContentIndexed = (bool)de.Properties["ContentIndexed"][0]; vd.EnableDefaultDoc = (bool)de.Properties["EnableDefaultDoc"][0]; vd.EnableDirBrowsing = (bool)de.Properties["EnableDirBrowsing"][0]; vd.AccessSSL = (bool)de.Properties["AccessSSL"][0]; vd.AccessScript = (bool)de.Properties["AccessScript"][0]; vd.Path = (string)de.Properties["Path"][0]; vd.flag = 0; vd.DefaultDoc = (string)de.Properties["DefaultDoc"][0]; tmpdirs.Add(vd.Name, vd); } } return tmpdirs; }