public static List <string> ConvertSecurityDescriptor(DirectoryAttribute attribute) { List <string> descriptors = new List <string>(); //Resolve Security Descriptor //From The .Net Developer Guide to Directory Services Programming Listing 8.2. Listing the DACL for (int i = 0; i < attribute.Count; i++) { ActiveDirectorySecurity ads = new ActiveDirectorySecurity(); ads.SetSecurityDescriptorBinaryForm((byte[])attribute[i]); var rules = ads.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (ActiveDirectoryAccessRule rule in rules) { string name = rule.IdentityReference.ToString(); if (name.ToUpper().Contains("S-1-5")) { name = SIDNameSID(name); } descriptors.Add(name + " ([ControlType: " + rule.AccessControlType.ToString() + "] Rights: " + rule.ActiveDirectoryRights.ToString() + ")"); } } return(descriptors); }
public virtual Dictionary <string, DirectoryAttribute> ReadObjectAttribute(string absolutePath, bool supportDeleted, params string[] attributes) { Dictionary <string, DirectoryAttribute> dictionary = new Dictionary <string, DirectoryAttribute>(); try { SearchRequest searchRequest = new SearchRequest(absolutePath, Schema.Query.QueryAll, SearchScope.Base, attributes); if (supportDeleted) { DirectoryControl control = new DirectoryControl("1.2.840.113556.1.4.417", null, true, true); searchRequest.Controls.Add(control); } SearchResponse searchResponse = (SearchResponse)this.SendRequest(searchRequest); if (searchResponse.Entries.Count > 0) { foreach (object obj in searchResponse.Entries[0].Attributes.Values) { DirectoryAttribute directoryAttribute = (DirectoryAttribute)obj; dictionary.Add(directoryAttribute.Name, directoryAttribute); } } } catch (ExDirectoryException ex) { if (ex.ResultCode != ResultCode.NoSuchObject) { throw; } } return(dictionary); }
public void SanityCheckTest() { PropertyInfo[] props = typeof(TestDirManager).GetProperties(); foreach (PropertyInfo prop in props) { FileAttribute fileAttribute = prop.GetCustomAttribute <FileAttribute>(); if (fileAttribute != null) { string fileLocation = prop.GetValue(prop).ToString(); if (File.Exists(fileLocation) == false) { Assert.Fail("Can not find file '{0}'", fileLocation); } } DirectoryAttribute directoryAttribute = prop.GetCustomAttribute <DirectoryAttribute>(); if (directoryAttribute != null) { string dirLocation = prop.GetValue(prop).ToString(); if (Directory.Exists(dirLocation) == false) { Assert.Fail("Can not find dir '{0}'", dirLocation); } } } }
public PropertyValueCollection(DirectoryEntry entry, DirectoryAttribute attr) : this(entry, attr?.Name) { for (int i = 0; i < attr.Count; i++) { _values.Add(attr[i]); } }
public Dictionary <string, object> GetRootDSE() { if (_rootDse != null) { return(_rootDse); } var con = Connect(); SearchResponse dirRes = (SearchResponse)con.SendRequest(new SearchRequest(null, "(defaultNamingContext=*)", SearchScope.Base)); var dict = new Dictionary <string, object>(); SearchResultEntry entry = dirRes.Entries[0]; IDictionaryEnumerator attribEnum = entry.Attributes.GetEnumerator(); while (attribEnum.MoveNext())//Iterate through the result attributes { //Attributes have one or more values so we iterate through all the values //for each attribute DirectoryAttribute subAttrib = (DirectoryAttribute)attribEnum.Value; var val = TypeMapper.GetAttributeValue(subAttrib); dict.Add(subAttrib.Name, val); } _rootDse = dict; return(dict); }
private bool TryGetCompanyState(string ouDN, EhfTargetConnection targetConnection, EhfADAdapter configADAdapter, out EhfAdminSyncState adminSyncState) { EhfADAdapter adadapter = this.ehfTargetConnection.ADAdapter; adminSyncState = null; ExSearchResultEntry exSearchResultEntry = adadapter.ReadObjectEntry(ouDN, false, EhfCompanyAdmins.ConfigUnitAttribute); if (exSearchResultEntry == null) { targetConnection.DiagSession.LogAndTraceInfo(EdgeSyncLoggingLevel.Low, "Could not load object with DN <{0}>; Cannot determine the CompanyId", new object[] { ouDN }); return(false); } DirectoryAttribute attribute = exSearchResultEntry.GetAttribute("msExchCU"); if (attribute == null) { targetConnection.DiagSession.LogAndTraceError("Could not load the Configuration Containter for {0}", new object[] { ouDN }); return(false); } string configUnitDN = (string)attribute[0]; return(EhfCompanySynchronizer.TryGetEhfAdminSyncState(configUnitDN, configADAdapter, targetConnection, "Ignoring admin account changes, will retry in next sync cycle", out adminSyncState)); }
public static bool TryGetExternalDirectoryObjectId(ExSearchResultEntry entry, EdgeSyncDiag diagSession, out Guid externalDirectoryObjectId) { externalDirectoryObjectId = Guid.Empty; DirectoryAttribute attribute = entry.GetAttribute("msExchExternalDirectoryObjectId"); if (attribute == null || attribute.Count == 0) { diagSession.LogAndTraceError("msExchExternalDirectoryObjectId attribute is not set on '{0}'", new object[] { entry.DistinguishedName }); return(false); } string text = (string)attribute[0]; if (!GuidHelper.TryParseGuid(text, out externalDirectoryObjectId)) { diagSession.LogAndTraceError("msExchExternalDirectoryObjectId attribute in '{0}' is set to an invalid Guid '{1}'", new object[] { entry.DistinguishedName, text }); return(false); } return(true); }
/// <summary> /// 結果を出力します。 /// </summary> /// <param name="searchResultEntry">ログインに成功したユーザー。</param> private static void OutputResult(SearchResultEntry searchResultEntry) { if (searchResultEntry != null) { Console.WriteLine("[[[ authn succeeded. ]]]"); Console.WriteLine(); foreach (DictionaryEntry dictionaryEntry in searchResultEntry.Attributes) { DirectoryAttribute directoryAttribute = dictionaryEntry.Value as DirectoryAttribute; // 属性名の出力 Console.Write(directoryAttribute.Name + ": "); foreach (string valueString in directoryAttribute.GetValues(typeof(string))) { // 雑にすべての値を文字列として出力するので、内容によっては文字化ける。 Console.Write(valueString + ", ");; } Console.WriteLine(); } Console.WriteLine(); } else { Console.WriteLine("[[[ authn failed. ]]]"); } }
protected static int GetFlagsValue(string flagsAttrName, ExSearchResultEntry resultEntry, EhfSyncItem syncItem) { DirectoryAttribute attribute = resultEntry.GetAttribute(flagsAttrName); if (attribute == null) { return(0); } string text = (string)attribute[0]; if (string.IsNullOrEmpty(text)) { return(0); } int result; if (!int.TryParse(text, out result)) { syncItem.AddSyncError(syncItem.DiagSession.LogAndTraceError("Unable to parse flags value ({0}) of attribute {1} for AD object ({2}); using default value 0", new object[] { text, flagsAttrName, resultEntry.DistinguishedName })); } return(result); }
static void Search() { string ldapSearchFilter = "(&(objectClass=organizationalUnit)(ou=sample*))"; // return ALL attributes that have some value string[] attributesToReturn = null; // create a search request: specify baseDn, ldap search filter, // attributes to return and scope of the search SearchRequest searchRequest = new SearchRequest( targetOU, ldapSearchFilter, SearchScope.Subtree, attributesToReturn ); // send the request through the connection SearchResponse searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); // retrieve a specific attribute DirectoryAttribute attribute = searchResponse.Entries[0].Attributes["ou"]; // get the first value since "ou" is a single valued attribute Console.WriteLine(attribute.Name + "=" + attribute[0]); PrintSearchResponse(searchResponse); Console.WriteLine("Search is completed successfully.\r\n"); }
public void Directory_ValidDirectory_ReturnsTrue() { var attr = new DirectoryAttribute(); bool valid = attr.IsValid(@"C:\Test\Test"); Assert.IsTrue(valid); }
public List <string> DecodeSDData(DirectoryAttribute attrib, ActiveDirectorySyntax syntax) { List <String> ret = new List <string> { }; foreach (byte[] value in attrib.GetValues(typeof(byte[]))) { try { CommonSecurityDescriptor oCSD = new CommonSecurityDescriptor(true, true, value, 0); if (!MainBase.UserSettings.DecodeSD) { ret.AddFormatted("\t\t(must not decode) SDDL: <{0}>", oCSD.GetSddlForm(AccessControlSections.All)); } else { ret.AddRange(DecodeSD(oCSD)); } } catch { ret.AddFormatted("\t\t<not decoded>: {0}", attrib[0].GetType().ToString()); } } return(ret); }
public override object FormatValueFromDirectory(DirectoryAttribute value, string dn) { string str; if (value != null && value.Count > 0 && (str = value[0] as string) != null && !str.IsNullOrEmpty()) { try { if (DirectoryValueMappings != null && DirectoryValueMappings.ContainsKey(str)) { return(DirectoryValueMappings[str]); } var dateTime = _isFileTimeFormat ? DateTime.FromFileTime(long.Parse(str)) : str.FormatLdapDateTime(_dateFormat); return(dateTime); } catch (Exception ex) { ThrowMappingException(value, dn, ex); } } if (DirectoryValueMappings != null && DirectoryValueMappings.ContainsKey(string.Empty)) { return(DirectoryValueMappings[string.Empty]); } AssertNullable(dn); return(null); }
public List <string> DecodeSchemaInfo(DirectoryAttribute attrib, out Int32 uVer) { List <string> ret = new List <string> { }; uVer = 0; foreach (byte[] value in attrib.GetValues(typeof(byte[]))) { byte[] tempar = new byte[4]; Array.Copy(value, 1, tempar, 0, 4); Array.Reverse(tempar); uVer = BitConverter.ToInt32(tempar, 0); tempar = new byte[16]; Array.Copy(value, 5, tempar, 0, 16); Guid invocationid = new Guid(tempar); ret.AddFormatted("\t\t<Update version = {0}; InvocationID= {1}>", uVer, invocationid.ToString()); } return(ret); }
public List <string> TryDynamicTypeDecoding(DirectoryAttribute attrib, ref bool match) { match = false; List <string> ret = new List <string>(); DynamicAttributeAssociator assoc = ForestBase.ADHelperDynamicDLL.AssociatorList.GetValueSafe <string, DynamicAttributeAssociator>(attrib.Name); if (assoc != null) { switch (assoc.AssociateFrom) { case ASSOCIATE_FROM.ENUM: ret = DynamicEnumDecoding(attrib, ref match); break; case ASSOCIATE_FROM.BERCONVERTER: ret = DynamicBerDecoding(attrib, assoc, ref match); break; case ASSOCIATE_FROM.DICTIONARY: ret = DynamicDictDecoding(attrib, assoc, ref match); break; } } return(ret); }
public static User GetUserObject(SearchResultEntry resultEntry) { User user = new User { DistinguishedName = resultEntry.DistinguishedName, Properities = new Dictionary <string, List <string> >() }; foreach (string attrName in resultEntry.Attributes.AttributeNames) { DirectoryAttribute attr = resultEntry.Attributes[attrName]; List <string> attrList = new List <string>(); if (attr[0] is string) { for (int i = 0; i < attr.Count; i++) { attrList.Add(attr[i].ToString()); } } else if (attr[0] is byte[]) { if (IsSecurityDescriptorAttribute(attrName)) { attrList = Helper.ConvertSecurityDescriptor(attr); } else { attrList = Helper.ConvertByteArrayToSID(attr); } } user.Properities.Add(attrName, attrList); } return(user); }
private static bool TryGetMailFlowConnectorId(ExSearchResultEntry entry, string attribute, EdgeSyncDiag diagSession, out int connectorId) { connectorId = EhfDomainSynchronizerVersion2.InvalidConnectorId; DirectoryAttribute attribute2 = entry.GetAttribute(attribute); if (attribute2 == null) { diagSession.LogAndTraceInfo(EdgeSyncLoggingLevel.High, "ConnectorId is null or empty for <{0}>:<{1}>", new object[] { attribute, entry.DistinguishedName }); return(false); } string text = (string)attribute2[0]; if (string.IsNullOrEmpty(text)) { return(false); } if (int.TryParse(text, out connectorId)) { return(true); } diagSession.LogAndTraceError("ConnectorId '{0}' is not in the expected format for <{1}>:<{2}>", new object[] { text, attribute, entry.DistinguishedName }); return(false); }
private static bool TryGetConfigUnit(ExSearchResultEntry entry, EdgeSyncDiag diagSession, out string configUnitDN) { configUnitDN = null; DirectoryAttribute attribute = entry.GetAttribute("msExchCU"); if (attribute != null) { configUnitDN = (string)attribute[0]; } if (string.IsNullOrEmpty(configUnitDN)) { diagSession.LogAndTraceInfo(EdgeSyncLoggingLevel.Low, "ConfigUnit root DN is not specified for accepted domain with DN <{0}>; ignoring the object", new object[] { entry.DistinguishedName }); return(false); } if (ExSearchResultEntry.IsDeletedDN(configUnitDN)) { diagSession.LogAndTraceInfo(EdgeSyncLoggingLevel.Low, "ConfigUnit root DN <{0}> for accepted domain with DN <{1}> indicates that tenant organization is deleted; ignoring the object", new object[] { configUnitDN, entry.DistinguishedName }); configUnitDN = null; return(false); } return(true); }
private SearchResultAttributeCollection GetLdapAttributes(SafeHandle ld, IntPtr entry, ref IntPtr ber) { var attributes = new SearchResultAttributeCollection(); for (var attr = Native.ldap_first_attribute(ld, entry, ref ber); attr != IntPtr.Zero; attr = Native.ldap_next_attribute(ld, entry, ber)) { var vals = Native.ldap_get_values_len(ld, entry, attr); if (vals != IntPtr.Zero) { var attrName = Encoder.Instance.PtrToString(attr); if (attrName != null) { var directoryAttribute = new DirectoryAttribute { Name = attrName }; directoryAttribute.AddValues(MarshalUtils.BerValArrayToByteArrays(vals)); attributes.Add(directoryAttribute); } Native.ldap_value_free_len(vals); } Native.ldap_memfree(attr); } return(attributes); }
private EhfAdminSyncChangeBuilder GetAdminBuilderForChange(ExSearchResultEntry entry) { string text; if (!EhfAdminAccountSynchronizer.TryGetOrganizationUnit(entry, base.DiagSession, out text)) { return(null); } EhfAdminSyncChangeBuilder ehfAdminSyncChangeBuilder; if (!this.adminAccountChange.TryGetValue(text, out ehfAdminSyncChangeBuilder)) { DirectoryAttribute attribute = entry.GetAttribute("msExchCU"); if (attribute == null) { base.DiagSession.LogAndTraceError("Could not find ConfigUnitDN for {0}. Every object is expected to contain this attribute.", new object[] { entry.DistinguishedName }); return(null); } string tenantConfigUnitDN = (string)attribute[0]; ehfAdminSyncChangeBuilder = new EhfAdminSyncChangeBuilder(text, tenantConfigUnitDN, base.EhfConnection); this.adminAccountChange.Add(text, ehfAdminSyncChangeBuilder); } return(ehfAdminSyncChangeBuilder); }
public void Directory_ValidNetworkDirectory_ReturnsTrue() { var attr = new DirectoryAttribute(); bool valid = attr.IsValid(@"\\D076CTS0037235\Test\Test"); Assert.IsTrue(valid); }
public static string[] GetAttributeValuesString( DsServer dc, string dn, string attributeName, string ldapFilter = "(objectClass=*)", System.DirectoryServices.Protocols.SearchScope searchScope = System.DirectoryServices.Protocols.SearchScope.Base) { SearchResultEntryCollection results = null; ResultCode ret = Search( dc, dn, ldapFilter, searchScope, new string[] { attributeName }, out results); if (ret != ResultCode.Success) { return(null); } foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes[attributeName]; if (attr == null) { return(null); } else { return((string[])attr.GetValues(typeof(string))); } } return(null); }
public static string getDN(string user, string idAttribute, string telephoneAttribute, string server, string authtype, string ldapUser, string password, string targetou, string filter) { string dn = ""; Init(server, authtype, ldapUser, password, targetou, filter); log.Debug("Search " + user + " from " + targetOU + " on " + ldapServer); SearchResponse response; ldapFilter = "(&(" + idAttribute + "=" + user + ")" + ldapFilter + ")"; SearchRequest request = new SearchRequest(targetOU, ldapFilter, SearchScope.Subtree, new string[1] { telephoneAttribute }); response = (SearchResponse)ldapConnection.SendRequest(request); if (response.Entries.Count == 1) { DirectoryAttribute da = response.Entries[0].Attributes[telephoneAttribute]; if (da != null && da.GetValues(typeof(string)).Length > 0) { dn = (string)da.GetValues(typeof(string))[0]; } else { log.Debug("The attribute " + telephoneAttribute + " is not defined for " + user); } } else { log.Debug("0 or more than 1 result retreived..."); } return(dn); }
/// <summary> /// Get all NCs in the forest. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All NC DNs in the forest.</returns> public string[] ListNCs(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); string partitionDn = "CN=Partitions," + rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode re = LdapUtility.Search( dc, partitionDn, "(objectClass=crossRef)", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "nCName" }, out results); if (re != ResultCode.Success) { return(null); } List <string> ncs = new List <string>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["nCName"]; string dn = (string)attr[0]; ncs.Add(dn); } return(ncs.ToArray()); }
/// <summary> /// Get all DCs in a given site. /// </summary> /// <param name="dc">The DC to talk to.</param> /// <param name="siteDn">The site to query servers from.</param> /// <returns>All servers in the site.</returns> public DsServer[] ListServersWithDcsInSite(DsServer dc, string siteDn) { SearchResultEntryCollection results = null; ResultCode re = Search( dc, siteDn, "(&(objectClass=nTDSDSA)(msDS-hasMasterNCs=*))", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "distinguishedName" }, out results); if (re != ResultCode.Success) { return(null); } List <DsServer> servers = new List <DsServer>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["distinguishedName"]; string dn = (string)attr[0]; DsServer srv = new DsServer(); // We need the server DN, not its NTDS DSA object DN. srv.ServerObjectName = GetParentObjectDn(dn); srv.NtdsDsaObjectName = dn; servers.Add(srv); } return(servers.ToArray()); }
/// <summary> /// Get LDAP attribute string representation. /// </summary> /// <param name="attribute">LDAP attribute</param> /// <param name="replaceInvalidCharacters">Replace invalid characters in result.</param> public static string GetAttributeString(DirectoryAttribute attribute, bool replaceInvalidCharacters = false) { if (attribute != null) { var builder = new StringBuilder(); for (int i = 0; i < attribute.Count; i++) { if (attribute[i] is string) { builder.Append((string)attribute[i]); } else if (attribute[i] is byte[]) { builder.Append(ToHexString((byte[])attribute[i])); } else { throw new InvalidOperationException("Unexpected type for attribute value: " + attribute[i].GetType().Name); } } // Replace invalid characters return(replaceInvalidCharacters ? Regex.Replace(builder.ToString(), "[^\\p{L}0-9_.-]+", "_") : builder.ToString()); } return(null); }
/// <summary> /// Get all domains in the forest. /// </summary> /// <param name="dc">The DC in the forest.</param> /// <returns>All domain objects in the forest.</returns> public DsDomain[] ListDomains(DsServer dc) { RootDSE rootDse = LdapUtility.GetRootDSE(dc); string partitionDn = "CN=Partitions," + rootDse.configurationNamingContext; SearchResultEntryCollection results = null; ResultCode re = LdapUtility.Search( dc, partitionDn, "(&(objectClass=crossRef)(systemFlags:1.2.840.113556.1.4.804:=2))", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[] { "nCName" }, out results); if (re != ResultCode.Success) { return(null); } List <DsDomain> domains = new List <DsDomain>(); foreach (SearchResultEntry e in results) { DirectoryAttribute attr = e.Attributes["nCName"]; string dn = (string)attr[0]; DsDomain domain = new AddsDomain(); domain.Name = dn; domains.Add(domain); } return(domains.ToArray()); }
public virtual string GetTargetPath(ExSearchResultEntry entry) { string text; if (this.type == SyncTreeType.Recipients) { DirectoryAttribute directoryAttribute = entry.Attributes["objectGUID"]; Guid guid = new Guid((byte[])directoryAttribute.GetValues(typeof(byte[]))[0]); text = "cn=" + guid.ToString() + ",CN=Recipients,OU=MSExchangeGateway"; } else { if (LdapTargetConnection.rootOrgContainerDN == null) { LdapTargetConnection.rootOrgContainerDN = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest().DistinguishedName; } string text2 = entry.DistinguishedName; int startIndex = -1; int count = 0; if (entry.IsCollisionObject(out startIndex, out count)) { text2 = text2.Remove(startIndex, count); } text = text2.Replace(LdapTargetConnection.rootOrgContainerDN, this.adamRootOrgContainerDN); } ExTraceGlobals.SynchronizationJobTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Translate source DN {0} to target DN {1}", entry.DistinguishedName, text); return(text); }
public void Directory_InvalidArgs_Returnsfalse() { var attr = new DirectoryAttribute(); Assert.IsFalse(attr.IsValid(string.Empty)); Assert.IsFalse(attr.IsValid(null)); }
private static void DirectoryButton(SerializedProperty sP, DirectoryAttribute dA, string path) { if (!GUIExtensions.ButtonOverPreviousControl()) { return; } string newDirectory = EditorUtility.OpenFolderPanel("Choose Directory", path, path.Equals("Assets") ? string.Empty : path); if (string.IsNullOrEmpty(newDirectory)) { return; } if (dA.unityDirectory) { if (!newDirectory.StartsWith(Application.dataPath)) { Debug.LogWarning("Directory must be local to project, eg. Assets..."); return; } sP.stringValue = "Assets" + newDirectory.Substring(Application.dataPath.Length); } else { sP.stringValue = newDirectory; } }
public void Insert(int index, DirectoryAttribute value) {}
public void AddRange(DirectoryAttribute[] attributes) {}
public int IndexOf(DirectoryAttribute value) {}
public void Remove(DirectoryAttribute value) {}
// Methods public int Add(DirectoryAttribute attribute) {}
public void CopyTo(DirectoryAttribute[] array, int index) {}
public CompareRequest(string distinguishedName, DirectoryAttribute assertion) {}
public bool Contains(DirectoryAttribute value) {}
public AddRequest(string distinguishedName, DirectoryAttribute[] attributes) {}