public static string verifyNTuser(string userName) { DirectoryEntry dEntry = new DirectoryEntry("LDAP://ds.kycourts.net/CN=Users,DC=ds,DC=kycourts,DC=net"); DirectorySearcher dSearch = new DirectorySearcher(dEntry); dSearch.PageSize = 6000; dSearch.Filter = "cn="+userName; dSearch.PropertiesToLoad.Add("cn"); dSearch.PropertiesToLoad.Add("mail"); dSearch.PropertiesToLoad.Add("objectSid"); dSearch.CacheResults = true; if (dSearch.FindAll().Count > 0) { foreach (SearchResult sResultSet in dSearch.FindAll()) { SecurityIdentifier sid = new SecurityIdentifier((byte[])sResultSet.Properties["objectSid"][0], 0); string[] namesid = sid.ToString().Split('-'); dEntry.Close(); return sResultSet.Properties["cn"][0].ToString() + ";" + sResultSet.Properties["mail"][0].ToString() + ";" + namesid[namesid.Length - 1].ToString(); } } else { dEntry.Close(); return "false"; } return "false"; }
/// <summary> /// Retorna listado de usarios almacenado en servidor /// iP= 192.168.0.5 /// </summary> /// <returns></returns> public List<EntiServerUser> UserSever() { try { DirectoryEntry LdapConnection = createDirectoryEntry(); DirectorySearcher ds = new DirectorySearcher(LdapConnection); ds.Filter = "(&(objectClass=user))"; SearchResultCollection result = ds.FindAll(); if (result != null) { for (int i = 0; i < result.Count; i++) { EntiServerUser us = new EntiServerUser(); us.user = result[i].Properties["userPrincipalName"][0].ToString(); us.name = result[i].Properties["CN"][0].ToString(); user.Add(us); } return user; } else { return null; } } catch (DirectoryServicesCOMException){ throw; } catch (InvalidOperationException){ throw; } catch (NotSupportedException){ throw; } }
/// <summary> /// Get the current Exchange version for the current server from Active Directy (ldap) /// </summary> /// <returns></returns> public static string checkExchangeVersionInstalled() { try { string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; DirectoryEntry rootDSE = new DirectoryEntry(string.Format("LDAP://{0}/rootDSE", domain)); DirectoryEntry objDirectoryEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", domain, rootDSE.Properties["configurationNamingContext"].Value.ToString())); DirectorySearcher searcher = new DirectorySearcher(objDirectoryEntry, "(&(objectClass=msExchExchangeServer))"); SearchResultCollection col = searcher.FindAll(); string version = string.Empty; foreach (SearchResult result in col) { DirectoryEntry user = result.GetDirectoryEntry(); if (String.Equals(user.Properties["name"].Value.ToString(), Dns.GetHostName(), StringComparison.InvariantCultureIgnoreCase)) { version = user.Properties["serialNumber"].Value.ToString(); break; } } return version != string.Empty ? version : "Not installed"; } catch (Exception) { return "Not installed"; } }
/// <summary> /// Enumerates the groups. /// </summary> /// <param name="domain">The domain.</param> /// <returns></returns> public static List<Group> EnumerateGroups(string domain) { List<Group> groups = new List<Group>(); try { DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + domain); DirectorySearcher searcher = new DirectorySearcher(directoryObject); searcher.Filter = "(ObjectCategory=group)"; foreach (SearchResult result in searcher.FindAll()) { groups.Add(new Group(result.GetDirectoryEntry().Name.Replace("CN=", string.Empty), result.GetDirectoryEntry().Path)); } directoryObject.Close(); directoryObject.Dispose(); } catch (DirectoryServicesCOMException e) { Console.WriteLine("An Error Occurred: " + e.Message.ToString()); } groups.Sort(); return groups; }
public static List<SearchResult> EnumerateComputers() { string domain = System.Environment.UserDomainName; List<SearchResult> computerList = new List<SearchResult>(); if (domain.Length == 0) { domain = System.Environment.MachineName; } try { DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://" + domain); DirectorySearcher compSearcher = new DirectorySearcher(directoryEntry); compSearcher.SizeLimit = 100000; compSearcher.PageSize = 1000; compSearcher.Filter = "ObjectCategory=computer"; foreach (SearchResult computer in compSearcher.FindAll()) { computerList.Add(computer); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message, "There was an error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } return computerList; }
protected void Page_Load(object sender, EventArgs e) { // TODO this todo was here for ages var dc = new DirectoryContext(DirectoryContextType.Domain, "ptsecurity.ru"); var address = Request.Params["address"]; var filter = "Address=" + address; var result = ""; var domain = Domain.GetDomain(dc); // this is our vulnerabilitiy of LDAP injection *in this file* // FIXED: AI issue #3, High, LDAP Injection, https://github.com/SDLTestAccount/IT/issues/3 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx?address=%7bfilter%7d+%3d+* HTTP/1.1 // Host:localhost var ds = new DirectorySearcher(domain.GetDirectoryEntry());//, filter); using (var src = ds.FindAll()) { // TODO it was edit here by developer 1 year ago foreach (var res in src) { result = res.ToString(); } } // let's go // this is our first vulnerability of XSS in this file // we will demonstrate False Positive scenario here (FP Marker) // FP: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write(result); // this is our second vulnerability of XSS in this file // we will demonstrate what happen if developer fails with his fix (VERIFY Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); // this is our third vulnerability of XSS in this file // we will demonstrate what happen if we really fix vulnerability (VERIFY Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); // this is our fourth vulnerability of XSS in this file // we will demonstrate what happen if developer want to cheat (FIXED Marker) // FIXED: AI issue #4, High, Cross-site Scripting, https://github.com/SDLTestAccount/IT/issues/4 // GET /Tests/1 INPUT DATA VERIFICATION/9 LDAP Injection/Ldap.aspx HTTP/1.1 // Host:localhost // (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().MoveNext() && (System.DirectoryServices.DirectorySearcher.FindAll().GetEnumerator().Current.ToString() == "<script>alert(0)</script>")) Response.Write("result"); }
public KeyValuePair<String, String>[] Search(string path, string[] properties, string filter) { List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>(); using (DirectoryEntry deRoot = new DirectoryEntry(M_AD + path, M_USER, M_PASSWORD, AuthenticationTypes.Secure)) { using (DirectorySearcher search = new DirectorySearcher(deRoot, filter)) { SearchResultCollection src = search.FindAll(); if (src != null) { foreach (SearchResult sr in src) { DirectoryEntry de = sr.GetDirectoryEntry(); KeyValuePair<string, string> dict = new KeyValuePair<string, string>(); foreach (string prop in properties) { string val = ""; if (de.Properties.Contains(prop)) { if (de.Properties[prop].Value.GetType() == typeof(Object[])) { val = String.Join(",", (Object[])de.Properties[prop].Value); } else { val = de.Properties.Contains(prop) ? de.Properties[prop].Value.ToString() : String.Empty; } } dict = new KeyValuePair<string, string>(prop, val); result.Add(dict); } de.Close(); } } src.Dispose(); } deRoot.Close(); } return result.ToArray(); }
// iterate users in an OU, write their mail attribute such as: // sAMAccountName + "@amdg.rockhursths.edu" public static void popFile(System.IO.StreamWriter file, string dn, string year) { //establish the OU DirectoryEntry ou = new DirectoryEntry("LDAP://" + dn); //establish the search object for above OU DirectorySearcher searcher = new DirectorySearcher(ou); //filter the search searcher.Filter = "(ObjectCategory=user)"; //go through every single search result and update its mail attribute foreach (SearchResult result in searcher.FindAll()) { //entry for every user DirectoryEntry user = null; user = result.GetDirectoryEntry(); string givenName = user.Properties["givenName"].Value.ToString(); string sn = user.Properties["sn"].Value.ToString(); string sAMAccountName = user.Properties["sAMAccountName"].Value.ToString().ToLower(); string mail = user.Properties["mail"].Value.ToString().ToLower(); file.WriteLine(year + "," + givenName + "," + sn + "," + sAMAccountName + "," + mail); } }
public static List<string> GetDomainList2() { List<string> domainList = new List<string>(); string sRootDomain; System.DirectoryServices.DirectoryEntry deRootDSE; System.DirectoryServices.DirectoryEntry deSearchRoot; System.DirectoryServices.DirectorySearcher dsFindDomains; System.DirectoryServices.SearchResultCollection srcResults; deRootDSE = new System.DirectoryServices.DirectoryEntry("GC://RootDSE"); sRootDomain = "GC://" + deRootDSE.Properties["rootDomainNamingContext"].Value.ToString(); deSearchRoot = new System.DirectoryServices.DirectoryEntry(sRootDomain); dsFindDomains = new System.DirectoryServices.DirectorySearcher(deSearchRoot); dsFindDomains.Filter = "(objectCategory=domainDNS)"; dsFindDomains.SearchScope = System.DirectoryServices.SearchScope.Subtree; srcResults = dsFindDomains.FindAll(); foreach (System.DirectoryServices.SearchResult srDomain in srcResults) { domainList.Add(srDomain.Properties["name"][0].ToString()); } return domainList; }
public bool isAuthenticatedAgainstLDAP(string username, string password) { string LDAPServerURL = @"LDAP://directory.monash.edu.au:389/"; string LDAPBaseOU = "o=Monash University,c=AU"; try { DirectoryEntry LDAPAuthEntry = new DirectoryEntry(LDAPServerURL + LDAPBaseOU, "", "", AuthenticationTypes.Anonymous); DirectorySearcher LDAPDirectorySearch = new DirectorySearcher(LDAPAuthEntry); LDAPDirectorySearch.ClientTimeout = new System.TimeSpan(0, 0, 5); LDAPDirectorySearch.Filter = "uid=" + username; SearchResult LDAPSearchResponse = LDAPDirectorySearch.FindOne(); string NewSearchPath = LDAPSearchResponse.Path.ToString(); string NewUserName = NewSearchPath.Substring(NewSearchPath.LastIndexOf("/") + 1); DirectoryEntry AuthedLDAPAuthEntry = new DirectoryEntry(NewSearchPath, NewUserName, password, AuthenticationTypes.None); DirectorySearcher AuthedLDAPDirectorySearch = new DirectorySearcher(AuthedLDAPAuthEntry); AuthedLDAPDirectorySearch.ClientTimeout = new System.TimeSpan(0, 0, 5); AuthedLDAPDirectorySearch.Filter = ""; SearchResultCollection AuthedLDAPSearchResponse = AuthedLDAPDirectorySearch.FindAll(); } catch (Exception e) { //System.Windows.Forms.MessageBox.Show(string.Format("Failed authentication against LDAP because {0}", e.Message)); return false; } return true; }
/// <summary> /// Возвращает все группы из AD, имена которых удовлетворяют заданному фильтру /// </summary> /// <param name="groupFilter">Фильтр по имени группы.</param> /// <param name="args"></param> /// <returns></returns> public ADGroupCollection FindGroups( string groupFilter ) { try { using (DirectoryEntry entry = new DirectoryEntry( _groupPath, LdapUserName, ConfigurationManager.AppSettings["LdapPassword"] )) using (DirectorySearcher searcher = new DirectorySearcher( entry )) { searcher.SearchScope = SearchScope.Subtree; searcher.Filter = String.Format( @"(&(objectCategory=group)(name={0}))", groupFilter ); ADGroupCollection groups = new ADGroupCollection(); try { foreach (SearchResult result in searcher.FindAll()) groups.Add( new ADGroup( result ) ); } catch (ArgumentException) { } // неверная строка поиска return groups; } } catch (Exception ex) { throw new CoreApplicationException(Resources.ResourceManager.GetString("ErrorSearchingGroupException"), ex); } }
public List<User> GetADUsers() { try { List<User> AdUsers = new List<User>(); string domainPath = "LDAP://OU=Users,OU=Cobweb Solutions Ltd,DC=cobwebsolutions,DC=com"; DirectoryEntry searchroot = new DirectoryEntry(domainPath); DirectorySearcher search = new DirectorySearcher(searchroot); search.Filter = "(&(objectClass=user)(objectCategory=person))"; search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("displayname"); SearchResult result; SearchResultCollection resultCol = search.FindAll(); if (resultCol != null) { for (int i = 0; i < resultCol.Count; i++) { result = resultCol[i]; User adUser = new User(); adUser.DisplayName = (string)result.Properties["displayname"][0]; adUser.UserName = (string)result.Properties["samaccountname"][0]; AdUsers.Add(adUser); } } return AdUsers; } catch (Exception ex) { return null; } }
/// <summary> /// Checks the name of the user. /// </summary> /// <param name="entry">The entry.</param> /// <param name="userName">Name of the user.</param> /// <returns> /// <c>true</c> if user name is existed, <c>false</c> otherwise.</returns> public static bool CheckUserName(this DirectoryEntry entry, string userName) { try { entry.CheckNullObject("entry"); userName.CheckEmptyString("userName"); var directorySearcher = new DirectorySearcher() { SearchRoot = entry, Filter = "(&(objectClass=user) (cn=" + userName + "))" }; if ((directorySearcher.FindAll()?.Count ?? 0) > 0) { return true; }; return false; } catch (Exception ex) { throw ex.Handle( new { userName }); } }
public static List<string> GetComputers() { List<string> ComputerNames = new List<string>(); DirectoryEntry entry = new DirectoryEntry("LDAP://transnetwork.local/OU=Phoenix-DC,DC=transnetwork,DC=local"); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = ("(objectClass=computer)"); //se buscan solamente objetos de ltipo computadora / server mySearcher.SizeLimit = int.MaxValue; mySearcher.PageSize = int.MaxValue; foreach (SearchResult resEnt in mySearcher.FindAll()) { //"CN=SGSVG007DC" string ComputerName = resEnt.GetDirectoryEntry().Name; if (ComputerName.StartsWith("CN=")) ComputerName = ComputerName.Remove(0, "CN=".Length); ComputerNames.Add(ComputerName); } mySearcher.Dispose(); entry.Dispose(); // Console.ReadLine(); return ComputerNames; }
private List<ADDomain> GetNetBIOSDomains() { List<ADDomain> ret = new List<ADDomain>(); DirectoryEntry RootDSE = new DirectoryEntry("LDAP://rootDSE"); // Retrieve the Configuration Naming Context from RootDSE string configNC = RootDSE.Properties["configurationNamingContext"].Value.ToString(); // Connect to the Configuration Naming Context DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC); // Search for all partitions where the NetBIOSName is set. DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot); configSearch.Filter = ("(NETBIOSName=*)"); // Configure search to return dnsroot and ncname attributes configSearch.PropertiesToLoad.Add("dnsroot"); configSearch.PropertiesToLoad.Add("NETBIOSName"); SearchResultCollection forestPartitionList = configSearch.FindAll(); // Loop through each returned domain in the result collection foreach (SearchResult domainPartition in forestPartitionList) { ADDomain ad = new ADDomain(); ad.Name = domainPartition.Properties["NETBIOSName"][0].ToString(); ad.Path = domainPartition.Properties["NETBIOSName"][0].ToString(); ret.Add(ad); } return ret; }
public static string FindAccountByEmail(string pEmailAddress) { string filter = string.Format("(proxyaddresses=SMTP:{0})", pEmailAddress); using (DirectoryEntry gc = new DirectoryEntry("GC:")) { foreach (DirectoryEntry z in gc.Children) { using (DirectoryEntry root = z) { using (DirectorySearcher searcher = new DirectorySearcher(root, filter, new string[] { "mailNickname" })) { searcher.ReferralChasing = ReferralChasingOption.All; SearchResultCollection result = searcher.FindAll(); foreach (SearchResult item in result) { foreach (object value in item.Properties["mailNickName"]) { return value.ToString(); } } } } } } return null; }
private List<string> Expand(DirectoryEntry group) { List<string> al = new List<string>(5000); string oc = "objectClass"; DirectorySearcher ds = new DirectorySearcher( group, "(objectClass=*)", new string[] { "member", "distinguishedName", "objectClass", "sAMAccountName", "mail", "name"}, SearchScope.Base ); ds.AttributeScopeQuery = "member"; ds.PageSize = 1000; using (SearchResultCollection src = ds.FindAll()) { string dn = null; foreach (SearchResult sr in src) { dn = (string) sr.Properties["distinguishedName"][0]; string name = string.Empty; try { name = (string)sr.Properties["sAMAccountName"][0]; } catch { // no sAMAccountName, must be a contact name = (string)sr.Properties["mail"][0]; } name += ":" + (string)sr.Properties["name"][0]; if (!this.processed.ContainsKey(dn)) { this.processed.Add(dn, null); //oc == "objectClass", we had to //truncate to fit in book. //if it is a group, do this recursively if (sr.Properties[oc].Contains("group")) { SetNewPath(this.group, dn); al.AddRange(Expand(this.group)); } else al.Add(name); } } } return al; }
private static SearchResultCollection GetUsers(DirectoryEntry ad, string ldapFilter) { var search = new DirectorySearcher(ad, ldapFilter); search.SearchScope = AppSettings.GeneralSettings.SearchScope; var results = search.FindAll(); return results; }
public static string GetEmailAddress(string userName, string password, string domain) { try { using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password)) { using (DirectorySearcher searcher = new DirectorySearcher(entry)) { searcher.Filter = string.Format("sAMAccountName={0}", userName); searcher.PropertiesToLoad.Add("Mail"); SearchResultCollection en = searcher.FindAll(); if (en.Count > 0) { return en[0].Properties["Mail"][0].ToString(); } else { return string.Empty; } } } } catch (Exception) { return string.Empty; } }
IObservableCollection<DirectoryUser> _getUsers(string filter) { var entry = new DirectoryEntry("LDAP://" + _settings.LdapPath); var ds = new DirectorySearcher(entry) { Filter = filter, SearchScope = SearchScope.OneLevel }; var results = new BindableCollection<DirectoryUser>(); using (entry) using (ds) { var searchResults = ds.FindAll(); foreach (SearchResult searchResult in searchResults) { var userPrincipalName = searchResult.Properties["userPrincipalName"]; var fullname = searchResult.Properties["cn"]; results.Add(new DirectoryUser(userPrincipalName.Count > 0 ? (string)userPrincipalName[0] : "", fullname.Count > 0 ? (string)fullname[0] : "")); } } return results; }
/// <summary> /// Return a hast table of all disabled AD samaccountname /// </summary> /// <returns></returns> public Hashtable GetDisabledAccountsFLA() { Hashtable ht = new Hashtable(); Boolean isActive; try { DirectoryEntry directoryRoot = new DirectoryEntry(this.adStartLocation); DirectorySearcher searcher = new DirectorySearcher(directoryRoot, "(&(objectClass=User)(objectCategory=Person))"); SearchResultCollection results = searcher.FindAll(); foreach (SearchResult result in results) { DirectoryEntry de = result.GetDirectoryEntry(); isActive = IsActive(de); if (!isActive) { string accountValue = (string)result.Properties["samaccountname"][0]; //will keep the accounts in alpha order ht.Add(accountValue.ToUpper(), accountValue.ToUpper()); } } } catch (Exception e) { throw new Exception("ActiveDirectoryAttributes - disabled accounts", e); } return (ht); }
/// <summary> /// Получить всех пользователей. /// </summary> /// <returns></returns> public List<AdUser> GetAllUsers() { DirectoryEntry entry = new DirectoryEntry("LDAP://infotecs-nt"); List<AdUser> users = new List<AdUser>(); using (DirectorySearcher dSearch = new DirectorySearcher(entry)) { dSearch.Filter = "(&(objectCategory=person)(objectClass=user))"; var allResults = dSearch.FindAll(); foreach (SearchResult result in allResults) { if (result.Properties["extensionattribute14"].Count == 0 || (result.Properties["mail"].Count == 0) || (result.Properties["department"].Count == 0) || (result.Properties["title"].Count == 0)) { continue; } var user = MapUserFromAdResult(result); ; if (user != null) { users.Add(user); } } } return users; }
/// <summary> /// Find all OUs beneath a given OU /// </summary> /// <param name="OuDn">Distinguished name of the parent OU</param> /// <param name="type">Type of objects to return</param> /// <returns>Children OUs from the given OU distinguished name</returns> public static ArrayList EnumerateOU(string OuDn, string type) { //Define our return type of array list ArrayList alObjects = new ArrayList(); try { //Create a DirectoryEntry object with the passed in OU distinguished name DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + OuDn); DirectorySearcher ouSearch = new DirectorySearcher(directoryObject.Path); ouSearch.Filter = "(objectClass=" + type + ")"; ouSearch.SearchRoot = directoryObject; ouSearch.SearchScope = SearchScope.OneLevel; SearchResultCollection allOUS = ouSearch.FindAll(); //Foreach child in the OU given foreach (SearchResult child in allOUS) { DirectoryEntry de = child.GetDirectoryEntry(); //Add the child to our array list to return alObjects.Add(de); } } //If an error occurred catch (DirectoryServicesCOMException e) { //Display the error message in a message box. MessageBox.Show("An Error Occurred: " + e.Message.ToString()); } //Return the array list of children of the given ou return alObjects; }
public string GetUserDisplayName(string alias) { using (DirectoryEntry root = GetRootEntry()) { using (DirectorySearcher searcher = new DirectorySearcher(root)) { searcher.Filter = alias.Format<string>("(|(&(objectCategory=person)(objectClass=user)(samAccountName={0})))"); using (SearchResultCollection searchResult = searcher.FindAll()) { using (DirectoryEntry user = searchResult[0].GetDirectoryEntry()) { if (user.Properties.Contains("displayName")) { return user.Properties["displayName"].Value.ToString(); } else { return alias; } }; }; } }; }
public Int32 getNextUID() { checkConnection(); Int32 id = 0; DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = "(|(objectClass=user))"; SearchResultCollection resultSet = mySearcher.FindAll(); foreach (SearchResult result in resultSet) { DirectoryEntry user = result.GetDirectoryEntry(); if (user.Properties["uidnumber"].Value != null) { String foo = user.Properties["uidnumber"].Value.ToString(); String username = user.Properties["uid"].Value.ToString(); int thisID; Int32.TryParse(foo, out thisID); if (thisID > id){ id = thisID; } } } mySearcher.Dispose(); return (id != 0) ? (id + 1) : 0; }
public static List<UsuarioAD> CarregarUsuariosAD(string dominio, string nome) { try { string LDAP = "LDAP://" + dominio; List<UsuarioAD> usuarios = new List<UsuarioAD>(); DirectoryEntry deRoot = new DirectoryEntry(LDAP, "viniciuslopes", "crb@d52012"); DirectorySearcher deSrch = new DirectorySearcher(deRoot, string.Format("(sAMAccountName>={0})", nome)); deSrch.PropertiesToLoad.Add("cn"); deSrch.PropertiesToLoad.Add("userPrincipalName"); deSrch.PropertiesToLoad.Add("sAMAccountName"); deSrch.PropertiesToLoad.Add("mail"); deSrch.Sort.PropertyName = "sAMAccountName"; deSrch.PageSize = 100; foreach (SearchResult res in deSrch.FindAll()) { UsuarioAD usuario = new UsuarioAD(); usuario.Nome = res.Properties["cn"][0].ToString(); usuario.Login = res.Properties["sAMAccountName"][0].ToString(); if (res.Properties.Contains("mail")) usuario.Email = res.Properties["mail"][0].ToString(); usuarios.Add(usuario); } return usuarios.ToList();//.Where(u => u.Login.ToUpper().StartsWith(nome.ToUpper())).ToList(); } catch { List<UsuarioAD> us = new List<UsuarioAD>(); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "pc2", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "Qbex", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); us.Add(new UsuarioAD() { Nome = "cc", Login = "******", Email = "*****@*****.**" }); return us; } }
static void Main(string[] args) { string sql = @"insert into users ( us_username, us_firstname, us_lastname, us_password, us_admin, us_default_query, us_org) values (N'$uid', N'$gn', N'$sn', N'$password', 0, 1, 1); "; try { DirectoryEntry de = new DirectoryEntry("LDAP://127.0.0.1/dc=mycompany,dc=com"); de.AuthenticationType = AuthenticationTypes.None; DirectorySearcher search = new DirectorySearcher(de); search.SearchScope = System.DirectoryServices.SearchScope.Subtree; search.Filter = "objectClass=inetOrgPerson"; SearchResultCollection results = search.FindAll(); foreach (SearchResult result in results) { System.Diagnostics.Debug.Print(result.Path); DirectoryEntry de2 = result.GetDirectoryEntry(); string uid = (string)de2.Properties["uid"].Value; string gn = (string)de2.Properties["gn"].Value; if (gn == null) gn = ""; string sn = (string)de2.Properties["sn"].Value; if (sn == null) sn = ""; string password = "******"; string insert_sql = sql; insert_sql = insert_sql.Replace("$uid",uid); insert_sql = insert_sql.Replace("$gn",gn); insert_sql = insert_sql.Replace("$sn",sn); insert_sql = insert_sql.Replace("$password", password); System.Diagnostics.Debug.Print(insert_sql); System.Console.WriteLine(insert_sql); } } catch (Exception e) { string s = e.Message; if (e.InnerException != null) { s += "\n"; s += e.InnerException.Message; } System.Diagnostics.Debug.Print(s); } System.Diagnostics.Debug.Print("bye"); } // end main
/// <summary> /// Checks if the user exists in AD /// </summary> /// <param name="username">Username to search</param> /// <returns>True/false</returns> public static bool DoesUserExist(string username) { DirectoryEntry entry = new DirectoryEntry(); DirectorySearcher search = new DirectorySearcher(entry); search.SearchRoot = entry; search.Filter = String.Format("(SAMAccountName={0})", username); SearchResultCollection results = search.FindAll(); return results.Count > 0; }
public bool UserExists(string username) { DirectoryEntry de = GetDirectoryEntry(); var deSearch = new DirectorySearcher { SearchRoot = de, Filter = "(&(objectClass=user) (sAMAccountName=" + username + "))" }; SearchResultCollection results = deSearch.FindAll(); return results.Count > 0; }
/// <summary> /// get all users /// </summary> /// <param name="baseTree">the base LDAP tree</param> /// <param name="subtreeAttributes">subtree to append to the baseTree. array [0],[1],[2] becomes [2],[1],[0],tree </param> /// <returns>all users</returns> public SearchResultCollection GetUsers(string baseTree, params string[] subtreeAttributes) { DirectoryEntry entry = getDirectoryEntry(baseTree, subtreeAttributes); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = "(&(objectCategory=user))"; SearchResultCollection results = mySearcher.FindAll(); return results; }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; do { StringBuilder escape = new StringBuilder(); for (int i = 0; i < tainted_2.Length; ++i) { char current = tainted_2[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } tainted_3 = escape.ToString(); break; }while((Math.Pow(4, 2) >= 42)); string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((Math.Sqrt(42) >= 42)) { {} } else if (!(Math.Sqrt(42) >= 42)) { {} } else { string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + ";"; Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch))); tainted_3 = r.Replace(tainted_2, ""); } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; tainted_2 = args[1]; tainted_3 = tainted_2; if ((Math.Pow(4, 2) <= 42)) { StringBuilder escape = new StringBuilder(); for (int i = 0; i < tainted_2.Length; ++i) { char current = tainted_2[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } tainted_3 = escape.ToString(); } else if (!(Math.Pow(4, 2) <= 42)) { {} } else { {} } string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((Math.Sqrt(42) >= 42)) { StringBuilder text = new StringBuilder(tainted_2); text.Replace("&", "&"); text.Replace("'", "'"); text.Replace(@"""", """); text.Replace("<", "<"); text.Replace(">", ">"); tainted_3 = text.ToString(); } else if (!(Math.Sqrt(42) >= 42)) { {} } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((1 == 0)) { string pattern = @"/^[0-9]*$/"; Regex r = new Regex(pattern); Match m = r.Match(tainted_2); if (!m.Success) { tainted_3 = ""; } else { tainted_3 = tainted_2; } } else { {} } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }