protected String ObjectSidToString(Byte [] sidByteArray) { if (sidByteArray == null) { return(String.Empty); } System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(sidByteArray, 0); return(sid.ToString()); }
public static string Bytes2SID(List <string> sidBytes) { byte[] bytes = new byte[sidBytes.Count]; for (int i = 0; i < sidBytes.Count; i++) { bytes[i] = Byte.Parse(sidBytes[i]); } var securityIdentifier = new System.Security.Principal.SecurityIdentifier(bytes, 0); return(securityIdentifier.ToString()); }
protected override BitStream internalDecode(BitStream data) { var len = data.Length; var buf = new BitReader(data).ReadBytes((int)len); var sid = new System.Security.Principal.SecurityIdentifier(buf, 0); var ret = new BitStream(); var writer = new BitWriter(ret); writer.WriteString(sid.ToString()); ret.Seek(0, System.IO.SeekOrigin.Begin); return(ret); }
public ADCache(string path) { eventLog = new EventLog("OIMNTFS ADCache"); eventLog.Buffer("Reading directory information."); try { DateTime start = DateTime.Now; string[] properties = new string[] { "samAccountName", "objectClass", "canonicalName", "objectSID", "distinguishedName" }; string filter = "(|(objectClass=user)(objectClass=group))"; eventLog.Buffer("Connecting to {0}...", path); DirectoryEntry directoryEntry = null; try { //directoryEntry = new DirectoryEntry(path); directoryEntry = new DirectoryEntry(); directoryEntry.RefreshCache(properties); } catch { eventLog.Buffer("Current user context is not allowed to read from AD."); } Console.WriteLine("Reading all ad user and group objects..."); DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(directoryEntry, filter, properties); ds.SearchScope = SearchScope.Subtree; ds.CacheResults = true; ds.ClientTimeout = TimeSpan.FromMinutes(120); ds.PageSize = 100; SearchResultCollection entries = ds.FindAll(); foreach (SearchResult entry in entries) { System.Security.Principal.SecurityIdentifier binSID = new System.Security.Principal.SecurityIdentifier((byte[])entry.Properties["objectSID"][0], 0); string sid = binSID.ToString(); string samAccountName = entry.Properties["samAccountName"][0].ToString(); if (!cache.ContainsKey(sid)) { cache.Add(sid, new Properties(sid, entry)); } } eventLog.Buffer("{0} objects found. Loading AD took actually {1}", cache.Count, (DateTime.Now - start).ToString()); } catch (Exception e) { eventLog.Buffer("Reading AD failed: {0}", e.Message); //throw new Exception("Reading AD failed."); } eventLog.Flush(); }
/// <summary> /// Create ssas base cube by calling SSAS API /// </summary> /// <param name="cubeServer">Cube server</param> /// <param name="cubeDBName">Cube data base name</param> /// <param name="cubeXmla">Base cube xmla</param> public void CREATE_SSAS_BASE_CUBE( DB_SQLHELPER_BASE sqlHelper, Server cubeServer, String cubeDBName, String cubeName, String dwConnectionString ) { String SSASConfigurationPath = CONFIGURATION_HELPER.BASIC_CONFIGURATION_FOLDER + @"\SSASConfiguration\BaseCubeXMLA.xml"; String SSASConfiguration = ""; System.Security.Principal.NTAccount _Everyone_Account = new System.Security.Principal.NTAccount("Everyone"); System.Security.Principal.SecurityIdentifier _SecurityIdentifier = (System.Security.Principal.SecurityIdentifier)_Everyone_Account.Translate(typeof(System.Security.Principal.SecurityIdentifier)); String sidString = _SecurityIdentifier.ToString(); SSASConfiguration = System.IO.File.ReadAllText(SSASConfigurationPath); SSASConfiguration = SSASConfiguration .Replace("$(dwConnectionString)", dwConnectionString) .Replace("$(cubeDBName)", cubeDBName) .Replace("$(cubeName)", cubeName) .Replace("$(DBTableSchemaName)", CONFIGURATION_HELPER.GET_METADATA_PROPERTY("db_table_schema_name")) .Replace("$(sid)", sidString); sqlHelper.ADD_MESSAGE_LOG(String.Format("[Create base cube] Starting create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Normal); XmlaResultCollection resultCol = cubeServer.Execute(SSASConfiguration); foreach (XmlaResult result in resultCol) { foreach (XmlaMessage message in result.Messages) { if (message.ToString().Contains("error") || message.ToString().Contains("failed")) { sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Error); return; } else { sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + message.ToString(), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed); } } } sqlHelper.ADD_MESSAGE_LOG("[Create base cube]" + String.Format("Succeed to create cube database {0}", cubeDBName), MESSAGE_TYPE.CREATE_CUBE, MESSAGE_RESULT_TYPE.Succeed); }
private Models.ActiveDirectoryUser ExtractActiveDirectoryUserProperties(SearchResult user) { if (null == user) { throw new ArgumentNullException("user", "user: Parameter validation FAILED. SearchResult 'user' must not be 'null'."); } var entity = new Models.ActiveDirectoryUser(); foreach (System.Collections.DictionaryEntry property in user.Properties) { var propInfo = entity.GetType().GetProperty(property.Key.ToString(), BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); if (null == propInfo) { continue; } var v = property.Value as ResultPropertyValueCollection; if (v[0] is Byte[]) { bool fResult = fResult = false; var ab = v[0] as Byte[]; if (Guid.Empty.ToByteArray().Length == ab.Length) { var guid = new Guid(ab); propInfo.SetValue(entity, guid.ToString()); } else { var sid = new System.Security.Principal.SecurityIdentifier(ab, 0); propInfo.SetValue(entity, sid.ToString()); } } else { propInfo.SetValue(entity, v[0]); } } return(entity); }
public FileSystemFile(FileSystemDirectory directory, System.IO.FileInfo file) { this.Directory = directory; // alle filenames in lowercase! this.Name = file.Name.ToLower(); this.Extension = file.Extension.ToLower(); this.Size = file.Length; this.DateCreate = file.CreationTime; this.DateWrite = file.LastWriteTime; this.DateAccess = file.LastAccessTime; System.Security.Principal.SecurityIdentifier sid = null; try { System.Security.AccessControl.FileSecurity fileSecurity = file.GetAccessControl(); sid = fileSecurity.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)) as System.Security.Principal.SecurityIdentifier; System.Security.Principal.NTAccount ntAccount = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount; this.Owner = ntAccount.Value; } catch (System.Security.Principal.IdentityNotMappedException ex) { if (sid != null) { this.Owner = sid.ToString(); } else { this.Owner = "unknown"; } } catch (Exception ex) { this.Owner = "error:" + ex.ToString(); } }
/// <summary> /// This function will search the user. /// Once user is found, it will get it's memberOF attribute's value. /// </summary> /// <param name="domainDN">distinguishedName of the domain</param> /// <param name="sAMAccountName"> /// sAMAccountName of the user for which we are searching the group membership in AD /// </param> /// <returns></returns> /// <remarks></remarks> public static List <string> GetUserGroups(string domainDN, string sAMAccountName) { List <string> lGroups = new List <string>(); try { //Create the DirectoryEntry object to bind the distingusihedName of your domain using (DirectoryEntry rootDE = new DirectoryEntry("LDAP://" + domainDN)) { //Create a DirectorySearcher for performing a search on abiove created DirectoryEntry using (DirectorySearcher dSearcher = new DirectorySearcher(rootDE)) { //Create the sAMAccountName as filter dSearcher.Filter = "(&(sAMAccountName=" + sAMAccountName + ")(objectClass=User)(objectCategory=Person))"; dSearcher.PropertiesToLoad.Add("memberOf"); dSearcher.ClientTimeout.Add(new TimeSpan(0, 20, 0)); dSearcher.ServerTimeLimit.Add(new TimeSpan(0, 20, 0)); //Search the user in AD SearchResult sResult = dSearcher.FindOne(); if (sResult == null) { throw new ApplicationException("No user with username " + sAMAccountName + " could be found in the domain"); } else { //Once we get the userm let us get all the memberOF attibute's value foreach (var grp in sResult.Properties["memberOf"]) { string sGrpName = Convert.ToString(grp).Remove(0, 3); //Bind to this group DirectoryEntry deTempForSID = new DirectoryEntry("LDAP://" + grp.ToString().Replace("/", "\\/")); try { deTempForSID.RefreshCache(); //Get the objectSID which is Byte array byte[] objectSid = (byte[])deTempForSID.Properties["objectSid"].Value; //Pass this Byte array to Security.Principal.SecurityIdentifier to convert this //byte array to SDDL format System.Security.Principal.SecurityIdentifier SID = new System.Security.Principal.SecurityIdentifier(objectSid, 0); if (sGrpName.Contains(",CN")) { sGrpName = sGrpName.Remove(sGrpName.IndexOf(",CN")); } else if (sGrpName.Contains(",OU")) { sGrpName = sGrpName.Remove(sGrpName.IndexOf(",OU")); } //Perform a recursive search on these groups. RecursivelyGetGroups(dSearcher, lGroups, sGrpName, SID.ToString()); } catch (Exception ex) { Console.WriteLine("Error while binding to path : " + grp.ToString()); Console.WriteLine(ex.Message.ToString()); } } } } } } catch (Exception ex) { Console.WriteLine("Please check the distinguishedName of the domain if it is as per your domain or not?"); Console.WriteLine(ex.Message.ToString()); System.Environment.Exit(0); } return(lGroups); }
} // End Sub ctr_tree_AfterSelect public static void AddLdapObjectAsString(string propertyName, object Iter, System.Windows.Forms.ListViewItem item) { // lastLogon System.__ComObject // lastLogoff System.__ComObject // lastLogonTimestamp System.__ComObject // accountExpires System.__ComObject // badPasswordTime System.__ComObject // pwdLastSet System.__ComObject // lockoutTime System.__ComObject // uSNCreated System.__ComObject // uSNChanged System.__ComObject // msExchMailboxGuid System.Byte[] // msExchVersion System.__ComObject // msExchMailboxSecurityDescriptor System.__ComObject // nTSecurityDescriptor System.__ComObject if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "lastLogon") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "lastLogoff") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "lastLogonTimestamp") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "pwdLastSet") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "badPasswordTime") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "lockoutTime") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "uSNCreated") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "uSNChanged") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "accountExpires") ) { // http://social.technet.microsoft.com/wiki/contents/articles/22461.understanding-the-ad-account-attributes-lastlogon-lastlogontimestamp-and-lastlogondate.aspx // http://stackoverflow.com/questions/1602036/how-to-list-all-computers-and-the-last-time-they-were-logged-onto-in-ad // http://stackoverflow.com/questions/33274162/the-namespace-of-iadslargeinteger // Active DS Type Library // System.Console.WriteLine(Iter); // System.Console.WriteLine(str); try { // SecurityDescriptor sd = (SecurityDescriptor)ent.Properties["ntSecurityDescriptor"].Value; // ActiveDs.SecurityDescriptor sd = (ActiveDs.SecurityDescriptor)Iter; // sd.DiscretionaryAcl // ActiveDs.AccessControlList acl = (ActiveDs.AccessControlList)sd.DiscretionaryAcl; //foreach (ActiveDs.AccessControlEntry ace in (System.Collections.IEnumerable)acl) //{ // System.Console.WriteLine("Trustee: {0}", ace.Trustee); // System.Console.WriteLine("AccessMask: {0}", ace.AccessMask); // System.Console.WriteLine("Access Type: {0}", ace.AceType); //} // ActiveDs.IADsLargeInteger ISomeAdTime = (ActiveDs.IADsLargeInteger)Iter; // long lngSomeAdTime = (long)ISomeAdTime.HighPart << 32 | (uint)ISomeAdTime.LowPart; // IADsLargeInteger noActiveDsSomeTime = (IADsLargeInteger)Iter; // System.Console.WriteLine(noActiveDsSomeTime); long lngSomeAdTime = ConvertLargeIntegerToLong(Iter); System.DateTime someAdTime = System.DateTime.MaxValue; if (lngSomeAdTime == long.MaxValue || lngSomeAdTime <= 0 || System.DateTime.MaxValue.ToFileTime() <= lngSomeAdTime) { someAdTime = System.DateTime.MaxValue; } else { // someAdTime = System.DateTime.FromFileTime(lngSomeAdTime); someAdTime = System.DateTime.FromFileTimeUtc(lngSomeAdTime).ToLocalTime(); } item.SubItems.Add(someAdTime.ToString("dd.MM.yyyy HH:mm:ss")); } catch (System.Exception ex) { item.SubItems.Add(ex.Message + System.Environment.NewLine + Iter.ToString()); } } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "msExchRecipientTypeDetails")) { try { long lngSomeVersion = ConvertLargeIntegerToLong(Iter); string strVersion = lngSomeVersion.ToString(); // http://memphistech.net/?p=457 // https://blogs.technet.microsoft.com/johnbai/2013/09/11/o365-exchange-and-ad-how-msexchrecipientdisplaytype-and-msexchangerecipienttypedetails-relate-to-your-on-premises/ switch (lngSomeVersion) { case 1: strVersion = "User Mailbox"; break; case 2: strVersion = "Linked Mailbox"; break; case 4: strVersion = "Shared Mailbox"; break; case 8: strVersion = "Legacy Mailbox"; break; case 16: strVersion = "Room Mailbox"; break; case 32: strVersion = "Equipment Mailbox"; break; case 64: strVersion = "Mail Contact"; break; case 128: strVersion = "Mail User"; break; case 256: strVersion = "Mail-Enabled Universal Distribution Group"; break; case 512: strVersion = "Mail-Enabled Non-Universal Distribution Group"; break; case 1024: strVersion = "Mail-Enabled Universal Security Group"; break; case 2048: strVersion = "Dynamic Distribution Group"; break; case 4096: strVersion = "Public Folder"; break; case 8192: strVersion = "System Attendant Mailbox"; break; case 16384: strVersion = "System Mailbox"; break; case 32768: strVersion = "Cross-Forest Mail Contact"; break; case 65536: strVersion = "User"; break; case 131072: strVersion = "Contact"; break; case 262144: strVersion = "Universal Distribution Group"; break; case 524288: strVersion = "Universal Security Group"; break; case 1048576: strVersion = "Non-Universal Group"; break; case 2097152: strVersion = "Disabled User"; break; case 4194304: strVersion = "Microsoft Exchange"; break; case 8388608: strVersion = "Arbitration Mailbox"; break; case 16777216: strVersion = "Mailbox Plan"; break; case 33554432: strVersion = "Linked User"; break; case 268435456: strVersion = "Room List"; break; case 536870912: strVersion = "Discovery Mailbox"; break; case 1073741824: strVersion = "Role Group"; break; case 2147483648L: strVersion = "Remote Mailbox"; break; case 137438953472L: strVersion = "Team Mailbox"; break; default: strVersion = lngSomeVersion.ToString(); break; } item.SubItems.Add(strVersion); } catch (System.Exception ex) { item.SubItems.Add(ex.Message + System.Environment.NewLine + Iter.ToString()); } } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "msExchRemoteRecipientType")) { try { System.Int64 lngSomeVersion = System.Convert.ToInt64(Iter); string strVersion = lngSomeVersion.ToString(); // http://memphistech.net/?p=457 // https://blogs.technet.microsoft.com/johnbai/2013/09/11/o365-exchange-and-ad-how-msexchrecipientdisplaytype-and-msexchangerecipienttypedetails-relate-to-your-on-premises/ switch (lngSomeVersion) { case 1: strVersion = "ProvisionedMailbox (Cloud MBX)"; break; case 2: strVersion = "ProvisionedArchive (Cloud Archive)"; break; case 3: strVersion = "ProvisionedMailbox, ProvisionedArchive"; // (mailbox provisioned in Cloud & Archive provisioned in Cloud)* either via EMC or new-remotemailbox cmd break; case 4: strVersion = "Migrated mailbox from on-prem"; break; case 6: strVersion = "Migrated mailbox from on-prem, ProvisionedArchive in EXO"; // (mailbox migrated from on-prem & archive provisioned in Cloud) break; case 16: strVersion = "DeprovisionArchive"; break; case 20: strVersion = "DeprovisionArchive, Migrated"; break; case 32: strVersion = "RoomMailbox"; break; case 36: strVersion = "Migrated, RoomMailbox"; break; case 64: strVersion = "EquipmentMailbox"; break; case 68: strVersion = "Migrated, EquipmentMailbox"; break; case 96: strVersion = "SharedMailbox"; break; case 100: strVersion = "Migrated, Shared Mailbox in EXO"; break; default: strVersion = lngSomeVersion.ToString(); break; } item.SubItems.Add(strVersion); } catch (System.Exception ex) { item.SubItems.Add(ex.Message + System.Environment.NewLine + Iter.ToString()); } } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "msExchRecipientDisplayType")) { try { System.Int64 lngSomeVersion = System.Convert.ToInt64(Iter); string strVersion = lngSomeVersion.ToString(); // http://memphistech.net/?p=457 switch (lngSomeVersion) { case 0: strVersion = "MailboxUser"; break; case 1: strVersion = "DistrbutionGroup"; break; case 2: strVersion = "PublicFolder"; break; case 3: strVersion = "DynamicDistributionGroup"; break; case 4: strVersion = "Organization"; break; case 5: strVersion = "PrivateDistributionList"; break; case 6: strVersion = "RemoteMailUser"; break; case 7: strVersion = "ConferenceRoomMailbox"; break; case 8: strVersion = "EquipmentMailbox"; break; case 1073741824: strVersion = "ACLableMailboxUser"; break; case 1043741833: strVersion = "SecurityDistributionGroup"; break; case -2147483642: strVersion = "SyncedMailboxUser"; break; case -2147483391: strVersion = "SyncedUDGasUDG"; break; case -2147483386: strVersion = "SyncedUDGasContact"; break; case -2147483130: strVersion = "SyncedPublicFolder"; break; case -2147482874: strVersion = "SyncedDynamicDistributionGroup"; break; case -2147482106: strVersion = "SyncedRemoteMailUser"; break; case -2147481850: strVersion = "SyncedConferenceRoomMailbox"; break; case -2147481594: strVersion = "SyncedEquipmentMailbox"; break; case -2147481343: strVersion = "SyncedUSGasUDG"; break; case -2147481338: strVersion = "SyncedUSGasContact"; break; case -1073741818: strVersion = "ACLableSyncedMailboxUser"; break; case -1073740282: strVersion = "ACLableSyncedRemoteMailUser"; break; case -1073739514: strVersion = "ACLableSyncedUSGasContact"; break; case -1073739511: strVersion = "SyncedUSGasUSG"; break; default: strVersion = lngSomeVersion.ToString(); break; } item.SubItems.Add(strVersion); } catch (System.Exception ex) { item.SubItems.Add(ex.Message + System.Environment.NewLine + Iter.ToString()); } } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "msExchVersion")) { try { long lngSomeVersion = ConvertLargeIntegerToLong(Iter); string strVersion = ""; // http://blogs.metcorpconsulting.com/tech/?p=1313 if (lngSomeVersion < 4535486012416L) { strVersion = "Exchange 2003 and earlier (" + lngSomeVersion.ToString() + ")"; } else if (lngSomeVersion == 4535486012416L) { strVersion = "Exchange 2007 (4535486012416)"; } else if (lngSomeVersion == 44220983382016L) { strVersion = "Exchange 2010 (44220983382016)"; } else { strVersion = lngSomeVersion.ToString(); } item.SubItems.Add(strVersion); } catch (System.Exception ex) { item.SubItems.Add(ex.Message + System.Environment.NewLine + Iter.ToString()); } } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "userCertificate") // || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "mSMQSignCertificates") // || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "mSMQDigest") ) { System.Security.Cryptography.X509Certificates.X509Certificate cert = new System.Security.Cryptography.X509Certificates.X509Certificate((byte[])Iter); item.SubItems.Add(cert.ToString()); } else if (System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "objectSid")) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])Iter, 0); item.SubItems.Add(sid.ToString()); } else if ( System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "objectGUID") || System.StringComparer.OrdinalIgnoreCase.Equals(propertyName, "msExchMailboxGuid") ) { System.Guid guid = new System.Guid((byte[])Iter); item.SubItems.Add(guid.ToString()); } else if (Iter != null && object.ReferenceEquals(Iter.GetType(), typeof(byte[]))) { byte[] ba = (byte[])Iter; item.SubItems.Add("0x" + System.BitConverter.ToString(ba).Replace("-", "")); } else { item.SubItems.Add(Iter.ToString()); } } // End Sub AddLdapObjectAsString
/// <summary> /// /// </summary> /// <param name="aObjectSid"></param> /// <returns></returns> private string ObjectSidToString(byte[] aObjectSid) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(aObjectSid, 0); return(sid.ToString()); }
private void AddProp(string name, System.Collections.ICollection props) { propertiesGrid.RowDefinitions.Add(new RowDefinition()); TextBlock tb = new TextBlock(); tb.SetValue(Grid.RowProperty, propertiesGrid.RowDefinitions.Count - 1); tb.SetValue(Grid.ColumnProperty, 0); tb.Text = name; tb.FontWeight = FontWeights.Bold; tb.Margin = new Thickness(5, 1, 5, 1); propertiesGrid.Children.Add(tb); StackPanel sp = new StackPanel(); sp.SetValue(Grid.RowProperty, propertiesGrid.RowDefinitions.Count - 1); sp.SetValue(Grid.ColumnProperty, 1); propertiesGrid.Children.Add(sp); if (props != null) { foreach (dynamic value in props) { string valueString = ((Object)value).ToString(); Image img = null; Hyperlink h = null; if (name == "userAccountControl:") { valueString = GetUserAccountControl(value); } else if (valueString == "System.__ComObject") { try { // Try an ADSI Large Integer Object o = value; Object low = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null); Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null); //long dateValue = (value.HighPart << 32) + value.LowPart; long dateValue = ((long)((int)high) << 32) + (long)((int)low); DateTime dt = DateTime.FromFileTime(dateValue); if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00") { if (dt.Year == 1601) { valueString = dt.ToString("HH:mm"); } else { valueString = dt.ToString("dd-MMM-yyyy HH:mm"); } } } catch { } } else if (valueString == "System.Byte[]") { byte[] bytes = value as byte[]; if (bytes.Length == 16) { Guid guid = new Guid(bytes); valueString = guid.ToString("B"); } else if (bytes.Length == 28) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(bytes, 0); valueString = sid.ToString(); } else { System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); try { BitmapImage photoBitmap = new BitmapImage(); photoBitmap.BeginInit(); photoBitmap.StreamSource = ms; photoBitmap.EndInit(); img = new Image(); img.Source = photoBitmap; img.Stretch = Stretch.None; } catch { img = null; } } } else if (valueString.ToString().StartsWith("CN=") || valueString.ToString().ToLower().StartsWith("http://")) { //string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value; //h = new Hyperlink(new Run(display)); h = new Hyperlink(new Run(valueString)); h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative); h.Click += new RoutedEventHandler(HyperlinkClicked); //p.TextIndent = -20; //p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom); } UIElement valueElement; if (img != null) { valueElement = img; } else if (h != null) { valueElement = new TextBlock(h); } else { valueElement = new TextBox() { Text = valueString, Style = FindResource("FauxLabel") as Style, }; } valueElement.SetValue(MarginProperty, new Thickness(5, 1, 5, 1)); sp.Children.Add(valueElement); } } }
private Paragraph PropParagraph(string name, System.Collections.ICollection props) { Paragraph p = new Paragraph(); bool appendSeparator = false; if (props != null) { foreach (dynamic value in props.Cast <object>().OrderBy(x => x.ToString())) { if (appendSeparator) { p.Inlines.Add("\r\n"); } else { appendSeparator = true; } string valueString = ((Object)value).ToString(); if (name == "userAccountControl:") { p.Inlines.Add(new Run(GetUserAccountControl(value))); } else if (valueString == "System.__ComObject") { try { // Try an ADSI Large Integer Object o = value; Object low = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null); Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null); //long dateValue = (value.HighPart * &H100000000) + value.LowPart; long dateValue = ((long)((int)high) << 32) + (long)((int)low); DateTime dt = DateTime.FromFileTime(dateValue); if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00") { if (dt.Year == 1601) { p.Inlines.Add(dt.ToString("HH:mm")); } else { p.Inlines.Add(dt.ToString("dd-MMM-yyyy HH:mm")); } } } catch { p.Inlines.Add(valueString); } } else if (valueString == "System.Byte[]") { byte[] bytes = value as byte[]; if (bytes.Length == 16) { Guid guid = new Guid(bytes); p.Inlines.Add(guid.ToString("B")); } else if (bytes.Length == 28) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(bytes, 0); p.Inlines.Add(sid.ToString()); } else { System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); try { BitmapImage photoBitmap = new BitmapImage(); photoBitmap.BeginInit(); photoBitmap.StreamSource = ms; photoBitmap.EndInit(); Image img = new Image(); img.Source = photoBitmap; img.Stretch = Stretch.None; p.Inlines.Add(img); } catch { p.Inlines.Add(valueString); } } } else { if (valueString.StartsWith("CN=") || valueString.ToLower().StartsWith("http://")) { //string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value; //Hyperlink h = new Hyperlink(new Run(display)); Hyperlink h = new Hyperlink(new Run(valueString)); h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative); h.Click += new RoutedEventHandler(HyperlinkClicked); //p.TextIndent = -20; //p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom); p.Inlines.Add(h); } else { p.Inlines.Add(new Run(valueString)); } } } } return(p); }
public List <ADUser> GetADUsers() { var users = new List <ADUser>(); try { // Note: Each property in the list (e.g., directoryObject.Properties("distinguishedName").Value.ToString) // Needs its own error handling or it will create an exception and not create an ADUser object. DirectoryEntry entry = new DirectoryEntry(); entry.Path = $"LDAP://{_Domain}"; entry.AuthenticationType = AuthenticationTypes.Secure; DirectorySearcher search = new DirectorySearcher(entry); search.CacheResults = false; search.Filter = "(&(objectClass=user))"; // search.Filter = "(givenName=" & logon & ")" SearchResultCollection allUsers = search.FindAll(); foreach (SearchResult result in allUsers) { DirectoryEntry directoryObject = result.GetDirectoryEntry(); try { var u = new ADUser(); if (directoryObject.Properties["distinguishedName"].Value != null) { u.DistinguishedName = "LDAP://" + directoryObject.Properties["distinguishedName"].Value.ToString(); } if (directoryObject.Properties["displayname"].Value != null) { u.Displayname = directoryObject.Properties["displayname"].Value.ToString(); } if (directoryObject.Properties["mail"].Value != null) { u.Mail = directoryObject.Properties["mail"].Value.ToString(); } if (directoryObject.Properties["SAMAccountName"].Value != null) { u.SAMAccountName = directoryObject.Properties["SAMAccountName"].Value.ToString(); } if (directoryObject.Properties["givenName"].Value != null) { u.GivenName = directoryObject.Properties["givenName"].Value.ToString(); } if (directoryObject.Properties["IsAccountLocked"].Value != null) { u.IsAccountLocked = Convert.ToBoolean(directoryObject.Properties["IsAccountLocked"].Value); } if (directoryObject.Properties["badPwdCount"].Value != null) { u.BadPwdCount = Convert.ToInt32(directoryObject.Properties["badPwdCount"].Value); } if (directoryObject.Properties["PasswordExpirationDate"].Value != null) { if (u.PasswordExpirationDate != null) { u.PasswordExpirationDate = Convert.ToDateTime(directoryObject.Properties["PasswordExpirationDate"].Value); } } if (directoryObject.Properties["lastLogin"].Value != null) { u.LastLogin = Convert.ToDateTime(directoryObject.Properties["lastLogin"].Value); } if (directoryObject.Properties["userAccountControl"].Value != null) { switch (Convert.ToInt32(directoryObject.Properties["userAccountControl"].Value)) { case 512: u.AccountStatus = "Enabled"; break; case 514: u.AccountStatus = "Disabled"; break; case 544: u.AccountStatus = "Account Enabled - User required to change password at next logon"; break; case 4096: u.AccountStatus = "Workstation/Server"; break; case 66048: u.AccountStatus = "Enabled, password never expires"; break; case 66050: u.AccountStatus = "Disabled, password never expires"; break; case 532480: u.AccountStatus = "Domain controller"; break; case 262656: u.AccountStatus = "Smart Card logon required"; break; default: u.AccountStatus = "Unavailable"; break; } } // SID if (directoryObject.Properties["objectSid"].Value != null) { dynamic sidInBytes = (byte[])directoryObject.Properties["objectSid"].Value; dynamic sid = new System.Security.Principal.SecurityIdentifier(sidInBytes, 0); u.ObjectSid = sid.ToString(); } users.Add(u); } catch (Exception ex) { } } entry.Close(); entry.Dispose(); search.Dispose(); } catch (Exception ex) { } return(users); }
public List <ADGroup> GetGroupMembers(List <ADGroup> groups, string dn, bool recursive) { try { string attributeName = "memberOf"; DirectoryEntry ent = new DirectoryEntry(dn); foreach (object property in ent.Properties[attributeName]) { if (property != null) { var g = new ADGroup(); string theDN = $"LDAP://{property.ToString()}"; var directoryObject = new DirectoryEntry(theDN); if (directoryObject.Properties["distinguishedName"].Value != null) { g.DistinguishedName = directoryObject.Properties["distinguishedName"].Value.ToString(); } if (directoryObject.Properties["name"].Value != null) { g.GroupName = directoryObject.Properties["name"].Value.ToString(); } if (directoryObject.Properties["description"].Value != null) { g.Description = directoryObject.Properties["description"].Value.ToString(); } if (directoryObject.Properties["member"].Value != null) { g.Member = directoryObject.Properties["member"].Value.ToString(); } if (directoryObject.Properties["isCriticalSystemObject"].Value != null) { g.IsCriticalSystemObject = Convert.ToBoolean(directoryObject.Properties["isCriticalSystemObject"].Value); } if (directoryObject.Properties["sAMAccountName"].Value != null) { g.SAMAccountName = directoryObject.Properties["sAMAccountName"].Value.ToString(); } if (directoryObject.Properties["objectSid"].Value != null) { dynamic sidInBytes = (byte[])directoryObject.Properties["objectSid"].Value; dynamic sid = new System.Security.Principal.SecurityIdentifier(sidInBytes, 0); g.ObjectSid = sid.ToString(); } if (directoryObject.Properties["objectGUID"].Value != null) { g.ObjectGUID = directoryObject.Properties["objectGUID"].Value.ToString(); } groups.Add(g); if (recursive == true) { GetGroupMembers(groups, theDN, recursive); } } } ent.Close(); ent.Dispose(); } catch (Exception ex) { } return(groups); }
public void ReformatLdif(LdifReader r, LdifWriter w, Encoding passwordEncoding, string defaultPwd, List <string> ignoredAttrs, bool allowMsExchange, Func <string, bool> ignoreIt) { if (!allowMsExchange) { ignoredAttrs.Add("showinaddressbook"); ignoredAttrs.Add("legacyexchangedn"); ignoredAttrs.Add("homemta"); ignoredAttrs.Add("homemdb"); ignoredAttrs.Add("mailnickname"); ignoredAttrs.Add("mdbusedefaults"); ignoredAttrs.Add("publicdelegatesbl"); ignoredAttrs.Add("protocolsettings"); ignoredAttrs.Add("publicdelegates"); ignoredAttrs.Add("deleteditemflags"); ignoredAttrs.Add("mDBStorageQuota".ToLowerInvariant()); ignoredAttrs.Add("mDBOverQuotaLimit".ToLowerInvariant()); ignoredAttrs.Add("garbageCollPeriod".ToLowerInvariant()); ignoredAttrs.Add("mDBOverHardQuotaLimit".ToLowerInvariant()); ignoredAttrs.Add("altrecipient"); ignoredAttrs.Add("deliverandredirect"); ignoredAttrs.Add("securityprotocol"); ignoredAttrs.Add("reporttooriginator"); ignoredAttrs.Add("reporttoowner"); ignoredAttrs.Add("oOFReplyToOriginator".ToLowerInvariant()); ignoredAttrs.Add("mapirecipient"); ignoredAttrs.Add("internetencoding"); ignoredAttrs.Add("targetaddress"); ignoredAttrs.Add("altrecipientbl"); ignoredAttrs.Add("delivcontlength"); ignoredAttrs.Add("submissioncontlength"); } bool ignored = false, hasPw = false; int pwdScore = 0; string thisDn = null; r.OnBeginEntry += (s, a) => { thisDn = a.DistinguishedName; hasPw = false; if (ignoreIt != null && ignoreIt.Invoke(a.DistinguishedName)) { ignored = true; } // Ignore domain trusts / special accounts // This part could use some rethinking. else if (a.DistinguishedName.Contains("$,CN=Users,") || a.DistinguishedName.Contains("krbtgt") || a.DistinguishedName.Contains("ForeignSecurityP")) { ignored = true; } else if (!allowMsExchange && a.DistinguishedName.Contains("Exchange System")) { ignored = true; } else { ignored = false; w.BeginEntry(a.DistinguishedName); } }; r.OnEndEntry += (s, a) => { if (!ignored) { if (pwdScore > 1 && !hasPw) { w.WriteAttr("unicodePwd", passwordEncoding.GetBytes( string.Format("\"{0}\"", defaultPwd)) ); } w.EndEntry(); } pwdScore = 0; }; r.OnAttributeValue += (s, a) => { if (!ignored) { if (a.Name == "unicodePwd") { hasPw = true; } else if (a.Name == "objectCategory" && ((string)a.Value).StartsWith("CN=Person")) { pwdScore++; } else if (a.Name == "objectClass" && "user".Equals(a.Value)) { pwdScore++; } if (string.Equals(a.Name, "objectSID", StringComparison.InvariantCultureIgnoreCase)) { if (thisDn.IndexOf("ForeignSecurity", StringComparison.InvariantCultureIgnoreCase) > 0) { if (a.Value is byte[]) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])a.Value, 0); w.WriteAttr(a.Name, sid.ToString()); } else if (a.Value is string) { w.WriteAttr(a.Name, (string)a.Value); } } } else { if (a.Value != null && !ignoredAttrs.Contains(a.Name.ToLowerInvariant())) { if (allowMsExchange || (!a.Name.StartsWith("msExch", StringComparison.InvariantCultureIgnoreCase) && !a.Name.StartsWith("extensionAttribute"))) { if (a.Value is string) { w.WriteAttr(a.Name, (string)a.Value); } else if (a.Value is byte[]) { w.WriteAttr(a.Name, (byte[])a.Value); } else { Console.Error.WriteLine("Warn: type of {0} is {1}", a.Name, a.Value.GetType()); w.WriteAttr(a.Name, Convert.ToString(a.Value)); } } } } } }; while (r.Read()) { // Keep reading } w.Close(); }
protected override BitStream internalDecode(BitStream data) { var sid = new System.Security.Principal.SecurityIdentifier(data.Value, 0); return(new BitStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sid.ToString()))); }
/// <summary> /// This function will perform a recursive search and will add only one occurance of /// the group found in the enumeration. /// </summary> /// <param name="dSearcher">DirectorySearcher object to perform search</param> /// <param name="lGroups">List of the Groups from AD</param> /// <param name="sGrpName"> /// Group name which needs to be checked inside the Groups collection /// </param> /// <param name="SID">objectSID of the object</param> /// <remarks></remarks> public static void RecursivelyGetGroups(DirectorySearcher dSearcher, List <string> lGroups, string sGrpName, string SID) { //Check if the group has already not found if (!lGroups.Contains(sGrpName)) { lGroups.Add(sGrpName + " : " + SID); //Now perform the search based on this group dSearcher.Filter = "(&(objectClass=grp)(CN=" + sGrpName + "))".Replace("\\", "\\\\"); dSearcher.ClientTimeout.Add(new TimeSpan(0, 2, 0)); dSearcher.ServerTimeLimit.Add(new TimeSpan(0, 2, 0)); //Search this group SearchResult GroupSearchResult = dSearcher.FindOne(); if ((GroupSearchResult != null)) { foreach (var grp in GroupSearchResult.Properties["memberOf"]) { string ParentGroupName = Convert.ToString(grp).Remove(0, 3); //Bind to this group DirectoryEntry deTempForSID = new DirectoryEntry("LDAP://" + grp.ToString().Replace("/", "\\/")); try { //Get the objectSID which is Byte array byte[] objectSid = (byte[])deTempForSID.Properties["objectSid"].Value; //Pass this Byte array to Security.Principal.SecurityIdentifier to convert this //byte array to SDDL format System.Security.Principal.SecurityIdentifier ParentSID = new System.Security.Principal.SecurityIdentifier(objectSid, 0); if (ParentGroupName.Contains(",CN")) { ParentGroupName = ParentGroupName.Remove(ParentGroupName.IndexOf(",CN")); } else if (ParentGroupName.Contains(",OU")) { ParentGroupName = ParentGroupName.Remove(ParentGroupName.IndexOf(",OU")); } RecursivelyGetGroups(dSearcher, lGroups, ParentGroupName, ParentSID.ToString()); } catch (Exception ex) { Console.WriteLine("Error while binding to path : " + grp.ToString()); Console.WriteLine(ex.Message.ToString()); } } } } }
public ADCache(string path) { try { DateTime start = DateTime.Now; string[] properties = new string[] { "samAccountName", "objectClass", "canonicalName", "objectSID", "distinguishedName" }; string filter = "(|(objectClass=user)(objectClass=group))"; Console.WriteLine("Connecting to {0}...", path); DirectoryEntry directoryEntry; try { directoryEntry = new DirectoryEntry(path); directoryEntry.RefreshCache(properties); } catch { string username = ""; string password = ""; ConsoleColor foregroundColor = Console.ForegroundColor; ConsoleColor backgroundColor = Console.BackgroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Current user context is not allowed to read from AD."); Console.WriteLine("Please provide user credentials entitled to read from {0}.", path); Console.ForegroundColor = foregroundColor; Console.Write("Enter username: "******"Enter password: "******"Reading all ad user and group objects..."); DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(directoryEntry, filter, properties); ds.SearchScope = SearchScope.Subtree; ds.CacheResults = true; ds.ClientTimeout = TimeSpan.FromMinutes(120); ds.PageSize = 100; SearchResultCollection entries = ds.FindAll(); foreach (SearchResult entry in entries) { System.Security.Principal.SecurityIdentifier binSID = new System.Security.Principal.SecurityIdentifier((byte[])entry.Properties["objectSID"][0], 0); string sid = binSID.ToString(); string samAccountName = entry.Properties["samAccountName"][0].ToString(); //Console.WriteLine("{0} - {1}", sid, samAccountName); Console.Write("\r{0} objects read..", cache.Count); if (!cache.ContainsKey(sid)) { cache.Add(sid, new Properties(sid, entry)); } } Console.WriteLine("\r{0} objects found. Loading AD took actually {1}", cache.Count, (DateTime.Now - start).ToString()); } catch (Exception e) { Console.WriteLine("Reading AD failed: {0}", e.Message); throw new Exception("Reading AD failed."); } }
public List <ADGroup> GetAllGroups() { var theGroups = new List <ADGroup>(); try { DirectoryEntry entry = new DirectoryEntry(); entry.Path = $"LDAP://{_Domain}"; entry.AuthenticationType = AuthenticationTypes.Secure; DirectorySearcher search = new DirectorySearcher(entry); search.CacheResults = false; search.Filter = "(&(objectClass=group))"; search.SearchScope = SearchScope.Subtree; SearchResultCollection allGroups = search.FindAll(); foreach (SearchResult result in allGroups) { DirectoryEntry directoryObject = result.GetDirectoryEntry(); if (result != null) { var g = new ADGroup(); if (directoryObject.Properties["distinguishedName"].Value != null) { g.DistinguishedName = directoryObject.Properties["distinguishedName"].Value.ToString(); } if (directoryObject.Properties["name"].Value != null) { g.GroupName = directoryObject.Properties["name"].Value.ToString(); } if (directoryObject.Properties["description"].Value != null) { g.Description = directoryObject.Properties["description"].Value.ToString(); } if (directoryObject.Properties["member"].Value != null) { g.Member = directoryObject.Properties["member"].Value.ToString(); } if (directoryObject.Properties["isCriticalSystemObject"].Value != null) { g.IsCriticalSystemObject = Convert.ToBoolean(directoryObject.Properties["isCriticalSystemObject"].Value); } if (directoryObject.Properties["sAMAccountName"].Value != null) { g.SAMAccountName = directoryObject.Properties["sAMAccountName"].Value.ToString(); } if (directoryObject.Properties["objectSid"].Value != null) { dynamic sidInBytes = (byte[])directoryObject.Properties["objectSid"].Value; dynamic sid = new System.Security.Principal.SecurityIdentifier(sidInBytes, 0); g.ObjectSid = sid.ToString(); } if (directoryObject.Properties["objectGUID"].Value != null) { g.ObjectGUID = directoryObject.Properties["objectGUID"].Value.ToString(); } theGroups.Add(g); } } entry.Close(); entry.Dispose(); search.Dispose(); } catch (Exception ex) { } return(theGroups); }
public string ResolveUsernameToLookupValue(string username, string staffInfoLookupKey) { if (lookupValuesByUsername.ContainsKey(username)) return lookupValuesByUsername[username]; DirectorySearcher search = null; string ldapLookupValue = null; string ldapLookupKey = null; try { ldapLookupKey = GetLdapLookupKey(); search = new DirectorySearcher(SearcherEntry) { Filter = "(" + LdapUsernameProperty + "=" + username + ")" }; search.PropertiesToLoad.Add(ldapLookupKey); var result = search.FindOne(); if (result == null) return null; if (!result.Properties.Contains(ldapLookupKey)) throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(NoPropertyReturnedFormat, ldapLookupKey, username))) { Name = username }; if (result.Properties[ldapLookupKey].Count == 0) throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(EmptyPropertyCollectionFormat, ldapLookupKey, username))) { Name = username }; var resultValue = result.Properties[ldapLookupKey][0]; if (resultValue is string) { ldapLookupValue = (string)resultValue; } else if (resultValue is byte[]) { //LDAP can return a few different types. If it's a byte[], it's probably because ldapLookupKey is objectsid. Convert the byte[] to a SID. var sid = new System.Security.Principal.SecurityIdentifier((byte[]) (resultValue), 0); ldapLookupValue = sid.ToString(); } else { throw new InvalidCastException("The type of the Property is " + resultValue.GetType() + " and it needs to be a string or a SID."); } ldapLookupValue = ldapLookupValue.ToLower(); lookupValuesByUsername[username] = ldapLookupValue; } finally { if (search != null) search.Dispose(); } if (string.IsNullOrEmpty(ldapLookupValue)) throw new DistrictProtocolAuthenticationException(string.Format(NoLookupValueErrorMessageFormat, string.Format(BlankValueReturnedFormat, ldapLookupKey, username))) { Name = username }; return ldapLookupValue; }
public void ReformatLdif(LdifReader r, LdifWriter w, Encoding passwordEncoding, string defaultPwd, List<string> ignoredAttrs, bool allowMsExchange, Func<string, bool> ignoreIt) { if (!allowMsExchange) { ignoredAttrs.Add("showinaddressbook"); ignoredAttrs.Add("legacyexchangedn"); ignoredAttrs.Add("homemta"); ignoredAttrs.Add("homemdb"); ignoredAttrs.Add("mailnickname"); ignoredAttrs.Add("mdbusedefaults"); ignoredAttrs.Add("publicdelegatesbl"); ignoredAttrs.Add("protocolsettings"); ignoredAttrs.Add("publicdelegates"); ignoredAttrs.Add("deleteditemflags"); ignoredAttrs.Add("mDBStorageQuota".ToLowerInvariant()); ignoredAttrs.Add("mDBOverQuotaLimit".ToLowerInvariant()); ignoredAttrs.Add("garbageCollPeriod".ToLowerInvariant()); ignoredAttrs.Add("mDBOverHardQuotaLimit".ToLowerInvariant()); ignoredAttrs.Add("altrecipient"); ignoredAttrs.Add("deliverandredirect"); ignoredAttrs.Add("securityprotocol"); ignoredAttrs.Add("reporttooriginator"); ignoredAttrs.Add("reporttoowner"); ignoredAttrs.Add("oOFReplyToOriginator".ToLowerInvariant()); ignoredAttrs.Add("mapirecipient"); ignoredAttrs.Add("internetencoding"); ignoredAttrs.Add("targetaddress"); ignoredAttrs.Add("altrecipientbl"); ignoredAttrs.Add("delivcontlength"); ignoredAttrs.Add("submissioncontlength"); } bool ignored = false, hasPw = false; int pwdScore = 0; string thisDn = null; r.OnBeginEntry += (s, a) => { thisDn = a.DistinguishedName; hasPw = false; if (ignoreIt != null && ignoreIt.Invoke(a.DistinguishedName)) { ignored = true; } // Ignore domain trusts / special accounts // This part could use some rethinking. else if (a.DistinguishedName.Contains("$,CN=Users,") || a.DistinguishedName.Contains("krbtgt") || a.DistinguishedName.Contains("ForeignSecurityP")) { ignored = true; } else if (!allowMsExchange && a.DistinguishedName.Contains("Exchange System")) { ignored = true; } else { ignored = false; w.BeginEntry(a.DistinguishedName); } }; r.OnEndEntry += (s, a) => { if (!ignored) { if (pwdScore > 1 && !hasPw) w.WriteAttr("unicodePwd", passwordEncoding.GetBytes( string.Format("\"{0}\"", defaultPwd)) ); w.EndEntry(); } pwdScore = 0; }; r.OnAttributeValue += (s, a) => { if (!ignored) { if (a.Name == "unicodePwd") hasPw = true; else if (a.Name == "objectCategory" && ((string)a.Value).StartsWith("CN=Person")) pwdScore++; else if (a.Name == "objectClass" && "user".Equals(a.Value)) pwdScore++; if (string.Equals(a.Name, "objectSID", StringComparison.InvariantCultureIgnoreCase)) { if (thisDn.IndexOf("ForeignSecurity", StringComparison.InvariantCultureIgnoreCase) > 0) { if (a.Value is byte[]) { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier((byte[])a.Value, 0); w.WriteAttr(a.Name, sid.ToString()); } else if (a.Value is string) { w.WriteAttr(a.Name, (string)a.Value); } } } else { if (a.Value != null && !ignoredAttrs.Contains(a.Name.ToLowerInvariant())) { if (allowMsExchange || (!a.Name.StartsWith("msExch", StringComparison.InvariantCultureIgnoreCase) && !a.Name.StartsWith("extensionAttribute"))) { if (a.Value is string) { w.WriteAttr(a.Name, (string)a.Value); } else if (a.Value is byte[]) { w.WriteAttr(a.Name, (byte[])a.Value); } else { Console.Error.WriteLine("Warn: type of {0} is {1}", a.Name, a.Value.GetType()); w.WriteAttr(a.Name, Convert.ToString(a.Value)); } } } } } }; while (r.Read()) { // Keep reading } w.Close(); }