Example #1
5
    public bool AuthenticateUser(string Domain, string Username, string Password, string LDAP_Path, ref string Errmsg)
    {
        Errmsg = "";
        string domainAndUsername = Domain + "\\" + Username;
        DirectoryEntry entry = new DirectoryEntry(LDAP_Path, domainAndUsername, Password);
        entry.AuthenticationType = AuthenticationTypes.Secure;
        try
        {
            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

            LDAP_Path = result.Path;
            string _filterAttribute = (String)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            Errmsg = ex.Message;
            return false;
            throw new Exception("Error authenticating user." + ex.Message);
        }

        return true;
    }
    public static void Main()
    {
        string path= "LDAP://DC=[DOMAIN],DC=local";
        string strAccountId = "[USERNAME]";
        string strPassword = "******";
        bool bSucceeded;
        string strError;

        DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword);

        DirectorySearcher adsSearcher = new DirectorySearcher( adsEntry );
        adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")";

        try
         {
          SearchResult adsSearchResult = adsSearcher.FindOne();
          bSucceeded = true;
          strError = "User has been authenticated by Active Directory.";
          adsEntry.Close();
         }
        catch ( Exception ex )
         {
            bSucceeded = false;
            strError = ex.Message;
            adsEntry.Close();
         }

         if (bSucceeded){
            Console.WriteLine("Great Success");
         }else {
            Console.WriteLine("Great Fail");
         }
    }
    private DataTable RunLDAPQuery(string query, string column)
    {
        DirectorySearcher ds = new DirectorySearcher();
        string sFilter2 = query;
        ds.Filter = sFilter2;
        SearchResultCollection src2 = ds.FindAll();
        DataTable dt = new DataTable("ADGroups");
        dt.Columns.Add(column, typeof(string));
        foreach (SearchResult s2 in src2)
        {
            ResultPropertyCollection rpc2 = s2.Properties;
            if (rpc2[column].Count > 0)
            {
                for (int icount = 0; icount < rpc2[column].Count; icount++)
                {
                    DataRow dr = dt.NewRow();
                    dr[column] = rpc2[column][icount];

                    dt.Rows.Add(dr);
                }
            }
            else
            {
                DataRow dr = dt.NewRow();
                dr[column] = rpc2[column];
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }
    int UserId; // For User Id

    #endregion Fields

    #region Methods

    /// <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();
        }
    }
Example #5
0
    public bool IsAuthenticated(string domain, string username, string pwd)
    {
        if (username == "esb" && pwd == "a") return true;

        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 (null == result)
            {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = (string)result.Properties["cn"][0];
        }
        catch (System.Exception ex)
        {
            throw new System.Exception(" " + ex.Message);
        }

        return true;
    }
Example #6
0
    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 (System.Exception ex)
        {
            throw new System.Exception("Error obtaining group names. " + ex.Message);
        }
        return groupNames.ToString();
    }
Example #7
0
    public static int ADGroupListUpdate()
    {
        string file_location = HttpContext.Current.Server.MapPath("~") + "\\App_Data\\ADGroups.xml";
        int GroupCount = 0;

        DirectoryEntry dirEnt = new DirectoryEntry("LDAP://" + Utils.Settings.Get("domain_controller") );
        string[] loadProps = new string[] { "name" }; 

        XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
        XElement root = new XElement("groups");

        using (DirectorySearcher srch = new DirectorySearcher(dirEnt, "(objectClass=Group)", loadProps))
        {
            srch.PageSize = 6000;
            var results = SafeFindAll(srch);
            foreach (SearchResult sr in results)
            {
                XElement xe = new XElement("group", sr.Properties["name"][0].ToString());
                root.Add(xe);
                GroupCount++;
            }
        }

        xDoc.Add(root);
        if (File.Exists(file_location)) File.Delete(file_location);
        xDoc.Save(file_location);

        return GroupCount;
    }
Example #8
0
    public bool AuthenticateUser(string domain, string username, string password, string LdapPath, out string Errmsg)
    {
        Errmsg = "";
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);

        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 (null == result)
            {
                return false;
            }

            // Update the new path to the user in the directory
            LdapPath = result.Path;
            string _filterAttribute = (String)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            Errmsg = ex.Message;
            return false;
            throw new Exception("Error authenticating user." + ex.Message);
        }

        return true;
    }
Example #9
0
 private void doADCopy(String username)
 {
     DirectoryEntry de = new DirectoryEntry("LDAP://ewprint.eastway.local/OU=Active Users,DC=eastway,DC=local");
     DirectorySearcher ds = new DirectorySearcher(de);
     ds.Filter = "sAMAccountName=" + username;
     SearchResult sr = ds.FindOne();
     DirectoryEntry user = sr.GetDirectoryEntry();
     SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["EWEHR"].ToString());
     try {
         cn.Open();
         if (isEchartsUser(user.Properties["employeeNumber"].Value.ToString())) {
             SqlCommand cmd = new SqlCommand("UPDATE echarts_user set " +
                 "office = '" + user.Properties["physicalDeliveryOfficeName"].Value + "', " +
                 "office_phone = '" + user.Properties["telephoneNumber"].Value + "', " +
                 "staff_description = '" + user.Properties["title"].Value + "', " +
                 "staff_name = '" + user.Properties["displayName"].Value + "',  " +
                 "status = 'Active', " +
                 "supervisor = '" + getManager(user.Properties["manager"].Value.ToString()) + "', " +
                 "username = '******' " +
                 "WHERE staff_id = '" + user.Properties["employeeNumber"].Value + "'", cn);
             if (cmd.ExecuteNonQuery() == 0) {
                 Response.Write("UPDATE FAILED");
             } else {
                 HttpCookie staffid = new HttpCookie("staff_id");
                 staffid.Value = (String)user.Properties["employeeNumber"].Value;
                 staffid.Expires = DateTime.UtcNow.AddMonths(6);
                 staffid.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(staffid);
                 doRedirect(Request.QueryString["continue"]);
             }
         } else {
             SqlCommand cmd = new SqlCommand("INSERT INTO echarts_user " +
                 "(username,office,office_phone,staff_description,staff_id,staff_name,status,supervisor) " +
                 "VALUES('" + username + "','" +
                 user.Properties["physicalDeliveryOfficeName"].Value + "','" +
                 user.Properties["telephoneNumber"].Value + "','" +
                 user.Properties["title"].Value + "','" +
                 user.Properties["employeeNumber"].Value + "','" +
                 user.Properties["displayName"].Value + "','" +
                 "Active" + "','" +
                 getManager(user.Properties["manager"].Value.ToString()) + "')", cn);
             if (cmd.ExecuteNonQuery() == 0) {
                 Response.Write("INSERT FAILED");
             } else {
                 HttpCookie staffid = new HttpCookie("staff_id");
                 staffid.Value = (String)user.Properties["employeeNumber"].Value;
                 staffid.Expires = DateTime.UtcNow.AddMonths(6);
                 staffid.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(staffid);
                 HttpCookie firstLogin = new HttpCookie("first_login");
                 firstLogin.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(firstLogin);
                 doRedirect(Request.QueryString["continue"]);
             }
         }
     } finally {
         cn.Close();
     }
 }
Example #10
0
 public static IEnumerable<SearchResult> SafeFindAll(DirectorySearcher searcher)
 {
     using (SearchResultCollection results = searcher.FindAll())
     {
         foreach (SearchResult result in results)
         {
             yield return result;
         } // SearchResultCollection will be disposed here
     }
 }
 public void Test_DirectorySearcher_Loads_Only_Files_With_Configuration_And_Key()
 {
     IDirectorySearcher directorySearcher = new DirectorySearcher(
         provider,
         pathResolver,
         keyGenerator,
         fileProvider,
         Path.Combine(this.CurrentDirectory.FullName, Paths.App_Config.HasNestedFiles.Path),
         "*.config",
         true);
     var configurationDictionary = directorySearcher.GetConfigurationDictionary();
     Assert.AreEqual(1, configurationDictionary.Keys.Count);
 }
Example #12
0
 //LDAP验证
 public bool VerifyUser(DirectorySearcher searcher)
 {
     try
     {
         //执行以下方法时没抛出异常说明用户名密码正确
         SearchResultCollection rs = searcher.FindAll();
         return true;
     }
     catch (Exception e)
     {
         return false;
     }
 }
Example #13
0
    public static string getUsername(string user_id,string domain)
    {
        DirectoryEntry de = new DirectoryEntry(@"LDAP://DC="+ domain +",DC=ad,DC=flextronics,DC=com");
            DirectorySearcher ds = new DirectorySearcher(de, "SAMAccountName=" + user_id);

            SearchResult result = ds.FindOne();
            if (result == null)
                return "";
            else
            {
                string n = result.Path.ToString();// (result.Properties["cn"].Count > 0) ? (string)result.Properties["cn"][0] : user_id;
                return n;
            }
    }
Example #14
0
 //Dim LDAP_Path คือ ชื่อ Domain หรือชื่อ Window ที่ต้องการตรวจสอบสิทธิ์-----------
 public string AuthenticateUser(string LDAP_Path, string user, string pass)
 {
     System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(LDAP_Path, user, pass, AuthenticationTypes.Secure);
     try
     {
         DirectorySearcher ds = new DirectorySearcher(de);
         ds.FindOne();
         return "";
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }
Example #15
0
        public ADSearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
        {
            _searcher = new DirectorySearcher(searchRoot, filter, propertiesToLoad, scope);

            // set all search preferences
            // don't cache the results on the client
            _searcher.CacheResults = false;
            // set the timeout to 2 minutes
            _searcher.ClientTimeout = s_defaultTimeSpan;
            _searcher.ServerPageTimeLimit = s_defaultTimeSpan;
            // Page Size needs to be set so that we 
            // can get all the results even when the number of results 
            // is greater than the server set limit (1000 in Win2000 and 1500 in Win2003)
            _searcher.PageSize = 512;
        }
Example #16
0
    public bool UserExists(string username)
    {
        DirectoryEntry de = GetDirectoryEntry();
        de.Username = "******";
        de.Password = "******";
        //de.Username = "******";
        //de.Password = "******";
        DirectorySearcher deSearch = new DirectorySearcher();

        deSearch.SearchRoot = de;
        deSearch.Filter = "(&(objectClass=user) (|(samaccountname=" + username + ")(cn=" + username + ")))";

        SearchResultCollection results = deSearch.FindAll();

        return results.Count > 0;
    }
Example #17
0
        public ADSearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope, bool pagedSearch, bool cacheResults)
        {
            _searcher = new DirectorySearcher(searchRoot, filter, propertiesToLoad, scope);
            // set proper time out
            _searcher.ClientTimeout = s_defaultTimeSpan;
            if (pagedSearch)
            {
                _searcher.PageSize = 512;
                _searcher.ServerPageTimeLimit = s_defaultTimeSpan;
            }

            if (cacheResults)
            {
                _searcher.CacheResults = true;
            }
            else
            {
                _searcher.CacheResults = false;
            }
        }
    public override void CreateNewOutputRows()
    {
        DirectorySearcher ADLookup = new DirectorySearcher();
        ADLookup.Filter = "(cn=IS BI Foundation Team)";
        ADLookup.PropertiesToLoad.Add("member");
        ADLookup.PropertiesToLoad.Add("cn");
        SearchResultCollection group = ADLookup.FindAll();

        foreach (SearchResult member in group)
        {
            foreach (Object memberObj in member.Properties["cn"])
            {
                DirectoryEntry user = new DirectoryEntry(memberObj);
                System.DirectoryServices.PropertyCollection userProps = user.Properties;
                Output0Buffer.AddRow();
                Output0Buffer.User = userProps["SAMAccountName"].Value.ToString();
            }
        }

        /*
        if (result != null)
        {
            for (int i = 0; i < result.Properties["member"].Count; i++)
            {
                DirectorySearcher ADUserLookup = new DirectorySearcher();
                ADUserLookup.Filter = (String)result.Properties["member"][i];
                ADUserLookup.PropertiesToLoad.Add("cn");
                SearchResult user = ADUserLookup.FindOne();

                if (user != null)
                {
                        Output0Buffer.AddRow();
                        Output0Buffer.User = (String)user.Properties["cn"][0];
                }

            }
        }*/
    }
    // code by lalit Joshi
    private bool Authenticate(string userName, string password, string domain)
    {
        bool authentic = false;

        try
        {

            DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);
            DirectorySearcher srchr = new DirectorySearcher(entry);

            srchr.Filter = string.Format("(SAMAccountName={0})", userName);
            //srchr.Filter = string.Format("SAMAccountName=0", userName);
            SearchResult res = srchr.FindOne();
            if (res != null)
                authentic = true;
        }
        catch (DirectoryServicesCOMException) { }
        return authentic;
    }
Example #20
0
    private void getInfo(ref string date, ref string ddstartTime, ref string ddendTime, ref string room, ref string body, ref string sVal)
    {
        string DOMAIN_NAME = "ITSERVICES";
        DirectoryEntry dirEntry = new DirectoryEntry( "LDAP://" + DOMAIN_NAME );
        DirectorySearcher dirSearcher = new DirectorySearcher( dirEntry );
        dirSearcher.Filter = "(mail=" + email.Text + "@calrecycle.ca.gov)";
        SearchResult result = dirSearcher.FindOne();
        DirectoryEntry person = result.GetDirectoryEntry();
        string managerName = "", department = "";
        string name = person.Properties["givenName"].Value.ToString() + " " + person.Properties["sn"].Value.ToString();

        string location = person.Properties["physicalDeliveryOfficeName"].Value.ToString();
        string phone = person.Properties["telephoneNumber"].Value.ToString();
        try
        {
             department = person.Properties["department"].Value.ToString();
        }
        catch { }
        try
        {
            string manager = person.Properties["manager"].Value.ToString();
            string firstManagerName = manager.Substring( manager.IndexOf( "," ) + 2, manager.IndexOf( ",", manager.IndexOf( "," ) ) - 4 );
            string lastManagerName = manager.Substring( 3, manager.IndexOf( "," ) - 4 );
            managerName = firstManagerName + " " + lastManagerName;
        }
        catch
        {
            managerName = "Not Found";
        }
        userEmail = email.Text + "@calrecycle.ca.gov";
        date = calBtn.Text;
        ddstartTime = startTime.Text;
        ddendTime = endTime.Text;

        if (!epaConf.SelectedValue.Equals(""))
        {
            room = epaConf.Text;
        }
        else if (!kTraining.SelectedValue.Equals(""))
        {
            room = kTraining.Text;
            sVal = "801k";
        }
        else if (!epaTraining.SelectedValue.Equals(""))
        {
            room = epaTraining.Text;
        }
        else if (!epaRooms.SelectedValue.Equals(""))
        {
            room = epaRooms.Text;
        }
        else if (!kRooms.SelectedValue.Equals(""))
        {
            room = kRooms.Text;
            sVal = "801k";
        }

        string link = @"http://epanet.ca.gov/Rooms/RoomDetail.asp?REFERER2=MyMtg.asp&ROOMID=" + getRoomID( room ) + @"&DATE=" + DateTime.Now.ToString( "M/d/yyyy" );

        StringBuilder equipmentSelect = new StringBuilder();
        if ( equipment.Items[0].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Laptop</br>" );
        if ( equipment.Items[1].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Projector Screen</br>" );
        if ( equipment.Items[2].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Projector</br>" );
        if ( equipment.Items[3].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Speakers</br>" );
        if ( equipment.Items[4].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Conference Phone</br>" );
        if ( equipment.Items[5].Selected )
            equipmentSelect.Append( "&emsp;&bull;&ensp;Other (see comments)</br>" );

        if ( networkReq.Items[0].Selected )
        {
            equipmentSelect.Append( "&emsp;&bull;&ensp;CalRecycle Network Access Required</br>" );
        }
        else
        {
            equipmentSelect.Append( "&emsp;&bull;&ensp;Wifi Access Required" );
        }

        body = "<b><u>Requestor Information</u></b></br>" +
                  "Name: " + name + ", " + department + "</br>" +
                  "Email: " + userEmail + "</br>" +
                  "Phone: " + phone + "</br>" +
                  "Location: " + location + "</br>" +
                  "Ticket Number: " + ticket.Text + "</br>" +
                  "<a href=" + link + ">Room Reservation</a></br></br>" +
                  "<b><u>Equipment Information</u></b></br>" + equipmentSelect.ToString() + "</br></br>" +
                  "<b><u>Comments</u></b></br>" + commentBox.Text.Replace( System.Environment.NewLine, "</br>" );

           // if (!kTraining.SelectedValue.Equals("") || !kRooms.SelectedValue.Equals("") )
           // sVal = "801k";
    }
        ///<summary>DirectoryEntrySearcher</summary>
        ///<remarks>
        /// DirectoryEntrySearcher( "LDAP://localhost", "host" );
        /// DirectoryEntrySearcher( "LDAP://localhost", "Guest" );
        /// DirectoryEntrySearcher( "IIS://localhost", null );
        /// DirectoryEntrySearcher( "IIS://localhost/W3SVC", null );
        /// DirectoryEntrySearcher( "WinNT://localhost", null );
        ///</remarks>
        public static SearchResultCollection DirectoryEntrySearcher
        (
            string path,
            string username,
            string password,
            string filter,
            out StringBuilder sb,
            out String exceptionMessage
        )
        {
            DirectoryEntry           directoryEntry    = null;
            DirectorySearcher        directorySearcher = null;
            ResultPropertyCollection resultPropertyCollection;
            SearchResultCollection   searchResultCollection = null;

            sb = null;
            exceptionMessage = null;
            try
            {
                directoryEntry = new DirectoryEntry(path);
                if (string.IsNullOrEmpty(username) == false)
                {
                    directoryEntry.Password = password;
                    directoryEntry.Username = username;
                }
                directorySearcher = new DirectorySearcher(directoryEntry);
                if (string.IsNullOrEmpty(filter) == false)
                {
                    directorySearcher.Filter = (String.Format("(anr={0})", filter));
                }
                searchResultCollection = directorySearcher.FindAll();
                sb = new StringBuilder();
                foreach (SearchResult searchResult in searchResultCollection)
                {
                    System.Console.WriteLine("Path: {0}", searchResult.GetDirectoryEntry().Path);
                    sb.AppendFormat(FormatSearchResultPath, searchResult.GetDirectoryEntry().Path);
                    resultPropertyCollection = searchResult.Properties;
                    foreach (string propertyName in resultPropertyCollection.PropertyNames)
                    {
                        System.Console.WriteLine("Property Name: {0}", propertyName);
                        sb.AppendFormat(FormatPropertyName, propertyName);
                        foreach (Object obj in resultPropertyCollection[propertyName])
                        {
                            System.Console.WriteLine("\t {0}", obj);
                            sb.AppendFormat(FormatResultProperty, obj);
                        }
                    }
                }
            }
            catch (Exception ex) { exceptionMessage = ex.Message; }
            finally
            {
                if (directorySearcher != null)
                {
                    directorySearcher.Dispose();
                }
                ;
                if (directoryEntry != null)
                {
                    directoryEntry.Close();
                }
            }
            return(searchResultCollection);
        }
 /// <summary>
 /// Конструктор.
 /// </summary>
 /// <param name="configuration"></param>
 public ADUserSearcher(IConfiguration configuration)
 {
     search = new DirectorySearcher(configuration["Domain"]);
 }
Example #23
0
 internal ADDNLinkedAttrSet(string groupDN, DirectorySearcher[] membersSearcher, string primaryGroupDN, DirectorySearcher primaryGroupMembersSearcher, bool recursive, ADStoreCtx storeCtx)
 {
     this.pathLock                     = new object();
     this.usersVisited                 = new Dictionary <string, bool>();
     this.groupsVisited                = new List <string>();
     this.groupsToVisit                = new List <string>();
     this.membersQueue                 = new Queue <IEnumerable>();
     this.originalMembers              = new Queue <IEnumerable>();
     this.atBeginning                  = true;
     this.foreignMembersCurrentGroup   = new List <DirectoryEntry>();
     this.fakePrincipalMembers         = new List <DirectoryEntry>();
     this.foreignGroups                = new List <GroupPrincipal>();
     this.memberSearchersQueue         = new Queue <DirectorySearcher>();
     this.memberSearchersQueueOriginal = new Queue <DirectorySearcher>();
     this.groupsVisited.Add(groupDN);
     this.recursive        = recursive;
     this.storeCtx         = storeCtx;
     this.originalStoreCtx = storeCtx;
     this.members          = null;
     this.originalMembers  = null;
     this.membersEnum      = null;
     this.primaryGroupDN   = primaryGroupDN;
     if (primaryGroupDN == null)
     {
         this.returnedPrimaryGroup = true;
     }
     if (membersSearcher != null)
     {
         DirectorySearcher[] directorySearcherArray = membersSearcher;
         for (int i = 0; i < (int)directorySearcherArray.Length; i++)
         {
             DirectorySearcher directorySearcher = directorySearcherArray[i];
             this.memberSearchersQueue.Enqueue(directorySearcher);
             this.memberSearchersQueueOriginal.Enqueue(directorySearcher);
         }
     }
     this.currentMembersSearcher      = null;
     this.primaryGroupMembersSearcher = primaryGroupMembersSearcher;
     this.expansionMode         = ExpansionMode.ASQ;
     this.originalExpansionMode = this.expansionMode;
 }
Example #24
0
        /// <summary>
        /// 根据email获取用户相关数据 LL 20200117
        /// </summary>
        /// <param name="email">samaccountname</param>
        /// <param name="domainName">pacrim</param>
        /// <returns></returns>
        public static string GetWindowsUserInfo(string email, string domainName)
        {
            string samaccountname = string.Empty;
            string givenName      = string.Empty;
            string name           = string.Empty;
            string displayname    = string.Empty;

            if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(domainName))
            {
                var allProperties = "name,displayname,givenName,samaccountname,mail";
                var properties    = allProperties.Split(new char[] { '\r', '\n', ',' }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName);

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.Filter = "(mail=" + email + ")";
                    foreach (string p in properties)
                    {
                        search.PropertiesToLoad.Add(p);
                    }
                    SearchResult result = search.FindOne();
                    if (result != null)
                    {
                        foreach (string p in properties)
                        {
                            ResultPropertyValueCollection collection = result.Properties[p];
                            for (int i = 0; i < collection.Count; i++)
                            {
                                if (p == "samaccountname")
                                {
                                    samaccountname = collection[i].ToString();
                                }
                                if (p == "mail")
                                {
                                    email = collection[i].ToString();
                                }
                                if (p == "givenName")
                                {
                                    givenName = collection[i].ToString();
                                }
                                if (p == "displayname")
                                {
                                    displayname = collection[i].ToString();
                                }
                            }
                        }
                    }
                    else
                    {
                        return("");
                    }
                }
                catch (Exception ex)
                {
                    //throw ex;
                    return("");
                }
            }
            return(email + ";" + givenName + ";" + displayname + ";" + samaccountname);
        }
Example #25
0
        private void AddGroups(HashSet <ActiveDirectoryGroup> groups, string groupName, bool recursive, bool limit, bool includeDomain)
        {
            using (DirectorySearcher directorySearcher = this.CreateDirectorySearcher())
            {
                directorySearcher.PropertiesToLoad.Add("name");
                directorySearcher.PropertiesToLoad.Add("distinguishedName");

                if (groupName.StartsWith("CN"))
                {
                    directorySearcher.Filter = "(&(objectcategory=group)(memberOf=" + groupName + "))";
                }
                else
                {
                    directorySearcher.Filter = "(&(objectcategory=group)(CN=" + groupName + "))";
                }

                try
                {
                    foreach (SearchResult principal in directorySearcher.FindAll())
                    {
                        using (DirectoryEntry directoryEntry = principal.GetDirectoryEntry())
                        {
                            var activeDirectoryGroup = new ActiveDirectoryGroup()
                            {
                                Name = GetValue <string>(directoryEntry, "name"),
                                DistinguishedName = GetValue <string>(directoryEntry, "distinguishedName")
                            };

                            if (activeDirectoryGroup.Name.Length > 0 && activeDirectoryGroup.Name[0] != '.' && activeDirectoryGroup.Name[0] != '*')
                            {
                                activeDirectoryGroup.Name = "*" + activeDirectoryGroup.Name;
                            }

                            if (includeDomain)
                            {
                                try
                                {
                                    SecurityIdentifier sidTokenGroup = new SecurityIdentifier(GetValue <byte[]>(directoryEntry, "objectsid"), 0);
                                    NTAccount          nt            = (NTAccount)sidTokenGroup.Translate(typeof(NTAccount));

                                    activeDirectoryGroup.Name = nt.Value.Substring(0, nt.Value.IndexOf('\\') + 1) + activeDirectoryGroup.Name;
                                }
                                catch (IdentityNotMappedException)
                                {
                                }
                            }

                            if (!groups.Contains(activeDirectoryGroup))
                            {
                                groups.Add(activeDirectoryGroup);

                                if (limit && groups.Count >= MaximumItems)
                                {
                                    break;
                                }

                                if (recursive)
                                {
                                    this.AddGroups(groups, activeDirectoryGroup.DistinguishedName, recursive, limit, includeDomain);
                                }
                            }
                        }
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                }
            }
        }
Example #26
0
        /// <summary>
        /// Validates user name and password returning the user role.
        /// </summary>
        public override bool ValidateUser(string username, string password, out int roleID, out bool handled)
        {
            if (Settings.UseAD)
            {
                DirectoryEntry entry = null;

                try
                {
                    // check password
                    bool pwdOK = false;

                    if (string.IsNullOrEmpty(password))
                    {
                        entry = new DirectoryEntry(Settings.LdapPath);
                        pwdOK = true;
                    }
                    else
                    {
                        entry = new DirectoryEntry(Settings.LdapPath, username, password);

                        // user authentication
                        try
                        {
                            object native = entry.NativeObject;
                            pwdOK = true;
                        }
                        catch { }
                    }

                    if (pwdOK)
                    {
                        // get user security groups
                        DirectorySearcher search = new DirectorySearcher(entry);
                        search.Filter = "(sAMAccountName=" + username + ")";
                        search.PropertiesToLoad.Add("memberOf");
                        SearchResult searchRes = search.FindOne();

                        if (searchRes != null)
                        {
                            List <string> groups = new List <string>();
                            foreach (object result in searchRes.Properties["memberOf"])
                            {
                                string group = result.ToString();
                                groups.Add(group);
                                FindOwnerGroups(entry, group, groups);
                            }

                            // define user role
                            if (GroupsContain(groups, "ScadaDisabled"))
                            {
                                roleID = BaseValues.Roles.Disabled;
                            }
                            else if (GroupsContain(groups, "ScadaGuest"))
                            {
                                roleID = BaseValues.Roles.Guest;
                            }
                            else if (GroupsContain(groups, "ScadaDispatcher"))
                            {
                                roleID = BaseValues.Roles.Dispatcher;
                            }
                            else if (GroupsContain(groups, "ScadaAdmin"))
                            {
                                roleID = BaseValues.Roles.Admin;
                            }
                            else if (GroupsContain(groups, "ScadaApp"))
                            {
                                roleID = BaseValues.Roles.App;
                            }
                            else
                            {
                                roleID = BaseValues.Roles.Err;
                            }

                            // return successful result
                            if (roleID != BaseValues.Roles.Err)
                            {
                                handled = true;
                                return(true);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteToLog(string.Format(Localization.UseRussian ?
                                             "{0}. Ошибка при работе с Active Directory: {1}" :
                                             "{0}. Error working with Active Directory: {1}", Name, ex.Message),
                               Log.ActTypes.Exception);
                }
                finally
                {
                    entry?.Close();
                }
            }

            return(base.ValidateUser(username, password, out roleID, out handled));
        }
Example #27
0
        static public Hashtable getDIRXMLAttributes(String username)
        {
            int       maxtry = 10;
            int       retrydelay = 500;
            Hashtable h = null; bool again = true; int trycount = 0; string lasterror = null; while (again && trycount <= maxtry)

            {
                trycount++;
                again = false;
                AuditSec.checkDIRXMLAccess(lasterror);
                if (!AuditSec.picdisabled && AuditSec.settings.picpw != null)
                {
                    try
                    {
                        //Console.WriteLine("Retrieving DirXML data of " + username + "...");
                        try
                        {
                            DirectorySearcher s = new DirectorySearcher(
                                new DirectoryEntry(AuditSec.defaultLdap,
                                                   "cn=" + UserPrincipal.Current.SamAccountName + ",ou=USER,o=MYCOMPANY",
                                                   AuditSec.settings.picpw, AuthenticationTypes.None),
                                "(&(objectClass=MYCOMPANYUser)(cn=" + username + "))",
                                DIRXMLattr2, SearchScope.OneLevel
                                );
                            SearchResult result = s.FindOne();
                            if (result == null)
                            {
                                Console.WriteLine("DirXML data of " + username + ": Error: Not found.");
                            }
                            ResultPropertyCollection p = result.Properties;
                            h = new Hashtable();
                            for (int i = 0; i < DIRXMLattr.Length; i++)
                            {
                                string attr  = DIRXMLattr[i];
                                string attr2 = DIRXMLattr2[i];
                                Type   type  = getDIRXMLtype(attr);
                                //Console.WriteLine("Retrieving DirXML data of " + username + "/" + attribute + "...");
                                string value = p[attr2].Count > 0 ? p[attr2][0].ToString() : "";
                                if (getDIRXMLalias(attr).Equals("Decentralized"))
                                {
                                    value = value.ToLower().Contains("decentralized") ? "Home-based" : "Office-based";
                                }
                                h.Add(attr, getValue(type, value));
                            }
                            //Console.WriteLine("DirXML data of " + username + ": " + h.ToString());
                        }
                        catch (AccessViolationException ave) { throw new Exception(ave.Message); }
                    }
                    catch (Exception e)
                    {
                        lasterror = e.Message;
                        if (e.Message.StartsWith("Object reference not set to an instance of an object"))
                        {
                            ;//not found. ok
                        }
                        else if (e.Message.StartsWith("A device attached to the system is not functioning"))
                        {
                            lasterror = e.Message;
                            Thread.Sleep(retrydelay);
                            again = true;
                        }
                        else
                        {
                            Console.WriteLine("DirXML data of " + username + ": " + e.Message);
                        }
                        if (e.Message.StartsWith("Logon failure") ||
                            e.Message.EndsWith("A constraint violation occurred.") ||
                            e.Message.StartsWith("The server is unwilling to process the request"))
                        {
                            lasterror = "Invalid password.";
                            AuditSec.settings.picpw = null;
                            again = true;
                        }
                    }
                }
                if (again && trycount > maxtry)
                {
                    Console.WriteLine("DirXML data of " + username + ": Error: " + lasterror + "\nMaximum retry reached.");
                }
            }
            return(h);
        }
Example #28
0
    public static void clr_GetADusersPhotos(SqlString ADpath, SqlString ADfilter)
    {
        //System.IO.StreamWriter file = Util.CreateLogFile();

        SearchResultCollection results = null;
        Int32 itemcount = 0;
        try
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("ObjectGUID", typeof(Guid));
            tbl.Columns.Add("Width", typeof(int));
            tbl.Columns.Add("Height", typeof(int));
            tbl.Columns.Add("Format", typeof(string));
            tbl.Columns.Add("Photo", typeof(byte[]));
            DataRow row;

            DirectoryEntry entry = new DirectoryEntry((string)ADpath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = (string)ADfilter;
            searcher.PageSize = 500;

            results = searcher.FindAll();
            foreach (SearchResult searchResult in results)
            {
                itemcount++;
                DirectoryEntry item = searchResult.GetDirectoryEntry();

                PropertyValueCollection prop = Util.GetADproperty(item, "thumbnailphoto");
                if (prop == null)
                    continue;

                // Get image size
                ImgSize imgsize = new ImgSize(0, 0, "xxx");
                try
                {
                    imgsize = ImageHeader.GetDimensions((byte[])prop[0]);
                }
                catch(Exception ex)
                {
                    SqlContext.Pipe.Send("Warning: Get image size failed for user (" + Util.GetDistinguishedName(item) + ")"
                        + " Exception: " + ex.Message);
                }

                row = tbl.NewRow();
                row[0] = item.Guid;
                if (!imgsize.IsEmpty()) // Image size will be NULL unless size has been read from the image header.
                {
                    row[1] = imgsize.Width;
                    row[2] = imgsize.Height;
                    row[3] = imgsize.Format;
                }
                row[4] = prop[0];
                tbl.Rows.Add(row);
            }

            // Return dataset to SQL server.
            ReturnDatasetToSqlServer(tbl);
        }
        catch (System.Runtime.InteropServices.COMException)
        {
            SqlContext.Pipe.Send("COMException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (InvalidOperationException)
        {
            SqlContext.Pipe.Send("InvalidOperationException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (NotSupportedException)
        {
            SqlContext.Pipe.Send("NotSupportedException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (Exception)
        {
            SqlContext.Pipe.Send("Exception in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        finally
        {
            if (null != results)
            {
                results.Dispose();  // To prevent memory leaks, always call
                results = null;     // SearchResultCollection.Dispose() manually.
            }
        }
        //file.Close();
    }
Example #29
0
        public void FormEvents_Loading(object sender, LoadingEventArgs e)
        {
            try
            {
                // Get the user name of the current user.
                string userName = this.Application.User.UserName;

                // Create a DirectorySearcher object using the user name
                // as the LDAP search filter. If using a directory other
                DirectorySearcher searcher = new DirectorySearcher(
                    "(sAMAccountName=" + userName + ")");

                // Search for the specified user.
                SearchResult result = searcher.FindOne();

                // Make sure the user was found.
                if (result == null)
                {
                    MessageBox.Show("Error finding user: "******"givenName"].Value.ToString();
                    string LastName   = employee.Properties["sn"].Value.ToString();
                    string CommonName = employee.Properties["cn"].Value.ToString();
                    string Mail       = employee.Properties["mail"].Value.ToString();
                    string Location   = employee.Properties["extensionAttribute10"].Value.ToString();
                    string Title      = employee.Properties["title"].Value.ToString();
                    string Phone      = employee.Properties["telephoneNumber"].Value.ToString();
                    string Department = employee.Properties["department"].Value.ToString();

                    // The manager property returns a distinguished name,
                    // so get the substring of the common name following "CN=".
                    string ManagerName = employee.Properties["manager"].Value.ToString();
                    ManagerName = ManagerName.Substring(3, ManagerName.IndexOf(",") - 3);

                    // Create an XPathNavigator to walk the main data source
                    // of the form.
                    XPathNavigator      xnMyForm = this.CreateNavigator();
                    XmlNamespaceManager ns       = this.NamespaceManager;

                    // Set the fields in the form.
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:FirstName", ns)
                    .SetValue(FirstName);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:LastName", ns)
                    .SetValue(LastName);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:CommonName", ns)
                    .SetValue(CommonName);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Alias", ns)
                    .SetValue(userName);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Email", ns)
                    .SetValue(Mail);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Manager", ns)
                    .SetValue(ManagerName);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Location", ns)
                    .SetValue(Location);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Title", ns)
                    .SetValue(Title);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:TelephoneNumber", ns)
                    .SetValue(Phone);
                    xnMyForm.SelectSingleNode("/my:myFields/my:RequestorInformation/my:Department", ns)
                    .SetValue(Department);

                    // Clean up.
                    xnMyForm = null;
                    searcher.Dispose();
                    result = null;
                    employee.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error occurred: " +
                                ex.Message.ToString());
                throw;
            }
        }
 private static TimeSpan GetMaxPasswordAge()
 {
     using (var searcher = new DirectorySearcher("(objectClass=domainDNS)"))
         return(TimeSpan.FromTicks(Math.Abs((long)searcher.FindOne().Properties["maxPwdAge"][0])));
 }
Example #31
0
        public ActionResult Login(LoginViewModel model, string URLRetorno)
        {
            if (ModelState.IsValid)
            {
                MembershipUser usuario = Membership.GetUser(model.Login);

                if (usuario != null && Membership.ValidateUser(model.Login, model.Senha))
                {
                    FormsAuthentication.SetAuthCookie(model.Login, false);

                    if (!VerificarExistenciaUsuario(model.Login))
                    {
                        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

                        DirectorySearcher directorySearcher = new DirectorySearcher(principalContext.ConnectedServer);

                        directorySearcher.Filter = "(&(sAMAccountName=" + model.Login + ")" + System.Configuration.ConfigurationManager.ConnectionStrings["ADFilterConnectionString"].ConnectionString + ")";

                        SearchResult searchResult = directorySearcher.FindOne();

                        DirectoryEntry directoryEntry = searchResult.GetDirectoryEntry();

                        if (directoryEntry.Properties.Count > 0)
                        {
                            int numEmp = int.Parse(directoryEntry.Properties["company"][0].ToString());
                            int numCad = int.Parse(directoryEntry.Properties["department"][0].ToString());

                            CadastrarUsuario(model.Login, numEmp, numCad);
                        }
                        else
                        {
                            model.Validado = false;
                        }
                    }

                    if (Url.IsLocalUrl(URLRetorno) &&
                        URLRetorno.Length > 1 &&
                        URLRetorno.StartsWith("/") &&
                        !URLRetorno.StartsWith("//") &&
                        !URLRetorno.StartsWith("/\\"))
                    {
                        return(Redirect(URLRetorno));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    model.Validado = false;
                }

                // BYPASS AD
                //if (VerificarExistenciaUsuario(model.Login))
                //{
                //    FormsAuthentication.SetAuthCookie(model.Login, false);

                //    if (Url.IsLocalUrl(URLRetorno)
                //        && URLRetorno.Length > 1
                //        && URLRetorno.StartsWith("/")
                //        && !URLRetorno.StartsWith("//")
                //        && !URLRetorno.StartsWith("/\\"))
                //    {
                //        return Redirect(URLRetorno);
                //    }
                //    else
                //    {
                //        return RedirectToAction("Index", "Home");
                //    }
                //}
                //else
                //{
                //    model.Validado = false;
                //}
            }

            return(View(model));
        }
Example #32
0
        /// <summary>
        /// Returns a true or false response against Active Directory and Application Security Service
        /// </summary>
        /// <param name="domain">string</param>
        /// <param name="userId">string</param>
        /// <param name="password">string</param>
        /// <param name="userAuthenticated">User</param>
        /// <param name="applicationName">applicationName</param>
        /// <param name="activeDirectoryAuthenticationRequired">activeDirectoryAuthenticationRequired</param>
        /// <returns>Response</returns>
        public Response Authenticate(string domain, string userId, string password, string applicationName, out User userAuthenticated)
        {
            var response = new Response {
                Message = "Not initializated", Result = false
            };

            userAuthenticated = null;

            bool InActiveDirectory = false;

            //Security Service Validation
            try
            {
                var userLogic = new UserLogic(_configuration);
                userAuthenticated = userLogic.FindUser(userId);
                userLogic.Dispose();
                if (userAuthenticated == null)
                {
                    response.Message = "500 - La cuenta de usuario no existe en SeguridadApp.";
                    return(response);
                }
            }
            catch (Exception securityException)
            {
                response.Message = string.Format("900 - Ocurrió un error al consultar el la cuenta de usuario en SeguridadApp: {0} ", securityException.Message);
                return(response);
            }

            //ActiveDirectory Authentication
            User AdUserFinded;

            this.GetUserInformation(userAuthenticated.EmployeeNumber, out AdUserFinded);

            if (AdUserFinded != null)
            {
                var    pathLDap = _LDapConnectionString;
                string domainAndUsername;
                domainAndUsername = domain + @"\" + userAuthenticated.EmployeeNumber;

                var entry = new DirectoryEntry(pathLDap, domainAndUsername, password);
                try
                {
                    // Bind to the native AdsObject to force authentication.
                    var obj    = entry.NativeObject;
                    var search = new DirectorySearcher(entry);
                    search.Filter = "(SAMAccountName=" + userAuthenticated.EmployeeNumber + ")";
                    search.PropertiesToLoad.Add("cn");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("givenname");
                    search.PropertiesToLoad.Add("sn");
                    search.PropertiesToLoad.Add("samaccountname");
                    SearchResult result = search.FindOne();
                    if (null != result)
                    {
                        InActiveDirectory = true;
                    }
                }
                catch (Exception ex)
                {
                    response.Message = string.Format
                                           ("600 - No fue posible autenticar la cuenta de usuario en el Directorio Activo - {0}.  Intente nuevamente. Error: {1}", DateTime.Now.ToString(),
                                           ex.Message);
                    return(response);
                }
            }

            if (!InActiveDirectory)
            {
                response.Message = string.Format("600 - No fue posible autenticar la cuenta de usuario en el Directorio Activo. {0}", DateTime.Now.ToString());
                return(response);
            }

            //Se valida la vigencia de fechas de la cuenta en SeguridadApp

            DateTime declineDate = new DateTime(Convert.ToInt32(userAuthenticated.DeclineDate.Substring(6, 4))
                                                , Convert.ToInt32(userAuthenticated.DeclineDate.Substring(3, 2))
                                                , Convert.ToInt32(userAuthenticated.DeclineDate.Substring(0, 2)));
            DateTime declineDateSIO = new DateTime(Convert.ToInt32(userAuthenticated.DeclineDateSIO.Substring(6, 4))
                                                   , Convert.ToInt32(userAuthenticated.DeclineDateSIO.Substring(3, 2))
                                                   , Convert.ToInt32(userAuthenticated.DeclineDateSIO.Substring(0, 2)));

            if (declineDate <= DateTime.Now || declineDateSIO <= DateTime.Now)
            {
                response.Message = "501 - La cuenta de usuario no es vigente en SeguridadApp.";
                return(response);
            }


            userAuthenticated.AuthenticationType = AuthenticationTypeEnum.SecurityServiceAndActiveDirectory;


            //Add session to the user
            //1.-GetApplication Id
            var applicationLogic  = new ApplicationLogic(_configuration);
            var applicationDbList = applicationLogic.GetApplicationList();

            applicationLogic.Dispose();
            var appFinded = applicationDbList.Find(app => app.ApplicationName == applicationName);

            if (appFinded == null)
            {
                response.Message = string.Format("700 - La aplicación {0} no existe en SeguridadApp. {1}", applicationName, DateTime.Now.ToString());
                return(response);
            }

            //2.-AddSession to user
            var      sessionLogic    = new SessionLogic(_configuration);
            Response sessionResponse = sessionLogic.AddSession(userAuthenticated, appFinded);

            sessionLogic.Dispose();
            if (!sessionResponse.Result)
            {
                response.Message = string.Format("502 - No fue posible asignar una sesión a la cuenta de usuario en SeguridadApp");
                return(response);
            }

            response.Result  = true;
            response.Message = @"000 - La cuenta de Usuario se autenticó correctamente en SeguridadApp y Directorio Activo.";
            return(response);
        }
        private List <DomainUserViewModel> FindAllADUsers(int id, string userName)// GetAllADUsers(int id, string UseName)
        {
            try
            {
                string cipherText = "";
                IQueryable <DomainSetting> domainSetting = _context.DomainSetting.Where(w => w.Id == id);

                var domain = domainSetting.Select(w => new DomainSetting
                {
                    UserName = w.UserName,
                    Server   = w.Server,
                    Title    = w.Title,
                    Password = w.Password
                }).FirstOrDefault();
                string EncryptionKey = "MAKV2SPBNI99212";
                byte[] cipherBytes   = Convert.FromBase64String(domain.Password);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV  = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                List <DomainUserViewModel> lstADUsers     = new List <DomainUserViewModel>();
                DomainUserViewModel        objSurveyUsers = new DomainUserViewModel();
                DomainSettingViewModel     SelectAll      = new DomainSettingViewModel();
                string   dcString = "";
                string   rootNode = "";
                string[] arrString;
                arrString = domain.Title.Split('.');
                if (arrString.Length == 1)
                {
                    dcString = "dc=" + domain.Title + "";
                    rootNode = arrString[0];
                }
                else
                {
                    for (int i = 0; i != arrString.Length; i++)
                    {
                        dcString += "dc=" + arrString[i].ToString() + ",";
                    }
                    if (arrString.Length == 3)
                    {
                        rootNode = arrString[1].ToString();
                    }
                    else if (arrString.Length == 2)
                    {
                        rootNode = arrString[0].ToString();
                    }
                    dcString = dcString.Substring(0, dcString.Length - 1);
                }
                try
                {
                    string DomainPath = "LDAP://" + domain.Server + "/" + dcString;
                    System.DirectoryServices.DirectoryEntry searchRoot = new System.DirectoryServices.DirectoryEntry(DomainPath);
                    searchRoot.Username = domain.UserName;
                    searchRoot.Password = cipherText;
                    DirectorySearcher search = new DirectorySearcher(searchRoot);
                    if (userName == "*")
                    {
                        search.Filter = $"(objectClass=user)";
                    }
                    else
                    {
                        userName      = userName.Split("@")[0];
                        search.Filter = $"(samaccountname=*{userName}*)";
                    }

                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("mail");
                    search.PropertiesToLoad.Add("usergroup");
                    search.PropertiesToLoad.Add("displayname"); //first name
                    search.PropertiesToLoad.Add("givenname");   //first name
                    search.PropertiesToLoad.Add("sn");          //first name
                    SearchResult resultFetch;


                    SearchResultCollection resultCol = search.FindAll();
                    if (resultCol != null)
                    {
                        for (int counter = 0; counter < resultCol.Count; counter++)
                        {
                            string UserNameEmailString = string.Empty;
                            resultFetch = resultCol[counter];
                            if (resultFetch.Properties.Contains("samaccountname"))
                            {
                                objSurveyUsers = new DomainUserViewModel();
                                if (resultFetch.Properties.Contains("mail"))
                                {
                                    objSurveyUsers.Email = (String)resultFetch.Properties["mail"][0];
                                }
                                else
                                {
                                    //  objSurveyUsers.Email = (String)resultFetch.Properties["samaccountname"][0] + id.ToString() + "@Pointer.com";
                                }

                                if (resultFetch.Properties.Contains("displayname"))
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["displayname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.DisplayName = (String)resultFetch.Properties["samaccountname"][0];
                                }


                                objSurveyUsers.UserName = (String)resultFetch.Properties["samaccountname"][0];

                                if (resultFetch.Properties.Contains("givenname"))
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["givenname"][0];
                                }
                                else
                                {
                                    objSurveyUsers.FirstName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                if (resultFetch.Properties.Contains("sn"))
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["sn"][0];
                                }
                                else
                                {
                                    objSurveyUsers.LastName = (String)resultFetch.Properties["samaccountname"][0];
                                }
                                objSurveyUsers.dcString = dcString;
                                lstADUsers.Add(objSurveyUsers);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
                return(lstADUsers);
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(null);
            }
        }
        public void StartEnumeration()
        {
            Console.WriteLine("\nStarting Group Enumeration");
            List <string> Domains   = Helpers.GetDomainList();
            Stopwatch     watch     = Stopwatch.StartNew();
            Stopwatch     overwatch = Stopwatch.StartNew();

            foreach (string DomainName in Domains)
            {
                Console.WriteLine($"Started group member enumeration for {DomainName}");
                CurrentDomain = DomainName;
                BlockingCollection <DBObject>            input  = new BlockingCollection <DBObject>();
                BlockingCollection <GroupMembershipInfo> output = new BlockingCollection <GroupMembershipInfo>();


                LimitedConcurrencyLevelTaskScheduler scheduler = new LimitedConcurrencyLevelTaskScheduler(options.Threads);
                TaskFactory factory = new TaskFactory(scheduler);
                ConcurrentDictionary <string, DBObject> dnmap = new ConcurrentDictionary <string, DBObject>();

                List <Task> taskhandles = new List <Task>();

                System.Timers.Timer t = new System.Timers.Timer();
                t.Elapsed += Timer_Tick;

                t.Interval = options.Interval;
                t.Enabled  = true;

                Task writer = StartWriter(output, options, factory);
                for (int i = 0; i < options.Threads; i++)
                {
                    taskhandles.Add(StartConsumer(input, output, dnmap, factory, manager));
                }

                progress   = 0;
                totalcount = 0;

                if (options.NoDB)
                {
                    totalcount = -1;
                    DirectorySearcher searcher = Helpers.GetDomainSearcher(DomainName);
                    searcher.Filter = "(|(memberof=*)(primarygroupid=*))";
                    String[] props = { "samaccountname", "distinguishedname", "dnshostname", "samaccounttype", "primarygroupid", "memberof", "objectsid", "objectclass", "ntsecuritydescriptor", "serviceprincipalname", "homedirectory", "scriptpath", "profilepath" };
                    searcher.PropertiesToLoad.AddRange(props);

                    foreach (SearchResult r in searcher.FindAll())
                    {
                        input.Add(r.ConvertToDB());
                    }
                }
                else
                {
                    var users =
                        manager.GetUsers().Find(
                            LiteDB.Query.And(
                                LiteDB.Query.EQ("Domain", DomainName),
                                LiteDB.Query.Or(
                                    LiteDB.Query.GT("MemberOf.Count", 0),
                                    LiteDB.Query.Not(LiteDB.Query.EQ("PrimaryGroupID", null)))));

                    var groups =
                        manager.GetGroups().Find(
                            LiteDB.Query.And(
                                LiteDB.Query.EQ("Domain", DomainName),
                                LiteDB.Query.Or(
                                    LiteDB.Query.GT("MemberOf.Count", 0),
                                    LiteDB.Query.Not(LiteDB.Query.EQ("PrimaryGroupID", null)))));
                    var computers =
                        manager.GetComputers().Find(
                            LiteDB.Query.And(
                                LiteDB.Query.EQ("Domain", DomainName),
                                LiteDB.Query.Or(
                                    LiteDB.Query.GT("MemberOf.Count", 0),
                                    LiteDB.Query.Not(LiteDB.Query.EQ("PrimaryGroupID", null)))));

                    totalcount = users.Count() + groups.Count() + computers.Count();

                    PrintStatus();

                    foreach (User u in users)
                    {
                        input.Add(u);
                    }

                    foreach (Group g in groups)
                    {
                        input.Add(g);
                    }

                    foreach (Computer c in computers)
                    {
                        input.Add(c);
                    }
                }

                input.CompleteAdding();
                options.WriteVerbose("Waiting for enumeration threads to finish...");
                Task.WaitAll(taskhandles.ToArray());
                output.CompleteAdding();
                options.WriteVerbose("Waiting for writer thread to finish...");
                writer.Wait();
                PrintStatus();
                t.Dispose();

                Console.WriteLine($"Finished group member enumeration for {DomainName} in {watch.Elapsed}");
                watch.Reset();
            }
            Console.WriteLine($"Finished group membership enumeration in {overwatch.Elapsed}\n");
            watch.Stop();
            overwatch.Stop();
        }
Example #35
0
        private bool MoveNextMemberSearcher()
        {
            bool nextSearchResult;
            bool flag = false;

            do
            {
                nextSearchResult = this.GetNextSearchResult();
                flag             = false;
                if (!nextSearchResult)
                {
                    if (!this.recursive || this.groupsToVisit.Count <= 0)
                    {
                        continue;
                    }
                    string item = this.groupsToVisit[0];
                    this.groupsToVisit.RemoveAt(0);
                    this.groupsVisited.Add(item);
                    DirectoryEntry directoryEntry = SDSUtils.BuildDirectoryEntry(this.BuildPathFromDN(item), this.storeCtx.Credentials, this.storeCtx.AuthTypes);
                    this.storeCtx.InitializeNewDirectoryOptions(directoryEntry);
                    DirectorySearcher directorySearcher = SDSUtils.ConstructSearcher(directoryEntry);
                    directorySearcher.Filter              = "(objectClass=*)";
                    directorySearcher.SearchScope         = SearchScope.Base;
                    directorySearcher.AttributeScopeQuery = "member";
                    directorySearcher.CacheResults        = false;
                    this.memberSearchersQueue.Enqueue(directorySearcher);
                    flag = true;
                }
                else
                {
                    SearchResult current = (SearchResult)this.memberSearchResultsEnumerator.Current;
                    string       str     = (string)current.Properties["distinguishedName"][0];
                    if (ADUtils.IsOfObjectClass(current, "group") || ADUtils.IsOfObjectClass(current, "user") || ADUtils.IsOfObjectClass(current, "foreignSecurityPrincipal"))
                    {
                        if (!this.recursive || !ADUtils.IsOfObjectClass(current, "group"))
                        {
                            if (!this.recursive || !ADUtils.IsOfObjectClass(current, "foreignSecurityPrincipal"))
                            {
                                if (this.usersVisited.ContainsKey(current.Properties["distinguishedName"][0].ToString()))
                                {
                                    flag = true;
                                }
                                else
                                {
                                    this.current                 = current;
                                    this.currentForeignDE        = null;
                                    this.currentForeignPrincipal = null;
                                    this.usersVisited.Add(current.Properties["distinguishedName"][0].ToString(), true);
                                }
                            }
                            else
                            {
                                if (!this.usersVisited.ContainsKey(current.Properties["distinguishedName"][0].ToString()))
                                {
                                    this.foreignMembersCurrentGroup.Add(current.GetDirectoryEntry());
                                    this.usersVisited.Add(current.Properties["distinguishedName"][0].ToString(), true);
                                }
                                flag = true;
                            }
                        }
                        else
                        {
                            if (!this.groupsVisited.Contains(str) && !this.groupsToVisit.Contains(str))
                            {
                                this.groupsToVisit.Add(str);
                            }
                            flag = true;
                        }
                    }
                    else
                    {
                        flag = true;
                    }
                }
            }while (flag);
            return(nextSearchResult);
        }
Example #36
0
        static void Main(string[] args)
        {
            Console.WriteLine(@"
   _____ __                     __    ___    ____  _____
  / ___// /_  ____ __________  / /   /   |  / __ \/ ___/
  \__ \/ __ \/ __ `/ ___/ __ \/ /   / /| | / /_/ /\__ \ 
 ___/ / / / / /_/ / /  / /_/ / /___/ ___ |/ ____/___/ / 
/____/_/ /_/\__,_/_/  / .___/_____/_/  |_/_/    /____/  
                     /_/                             ");


            var            parsed           = ArgumentParser.Parse(args);
            String         username         = null;
            String         password         = null;
            String         connectionString = "LDAP://{0}:{1}";
            DirectoryEntry ldapConnection;

            // Display help
            if (parsed.Arguments.ContainsKey("/help") || !parsed.Arguments.ContainsKey("/host"))
            {
                Console.WriteLine("Required");
                Console.WriteLine("/host:<1.1.1.1>  LDAP host to target, most likely the DC");

                Console.WriteLine("\nOptional");
                Console.WriteLine("/user:<username> Username of the account");
                Console.WriteLine("/pass:<password> Password of the account");
                Console.WriteLine("/out:<file>      Outputting credentials to file");
                Console.WriteLine("/ssl             Enable SSL (LDAPS://)");

                Console.WriteLine("\nUsage: SharpLAPS.exe /user:DOMAIN\\User /pass:MyP@ssw0rd123! /host:192.168.1.1");
                Environment.Exit(-1);
            }

            // Handle LDAPS connection
            if (!parsed.Arguments.ContainsKey("/ssl"))
            {
                connectionString = String.Format(connectionString, parsed.Arguments["/host"], "389");
            }
            else
            {
                connectionString = String.Format(connectionString, parsed.Arguments["/host"], "636");
            }


            // Use the provided credentials or the current session
            if (parsed.Arguments.ContainsKey("/host") && parsed.Arguments.ContainsKey("/pass"))
            {
                Console.WriteLine("\n[+] Using the following credentials");
                Console.WriteLine("Host: " + connectionString);
                Console.WriteLine("User: "******"/user"]);
                Console.WriteLine("Pass: "******"/pass"]);
                username = parsed.Arguments["/user"];
                password = parsed.Arguments["/pass"];
            }
            else
            {
                Console.WriteLine("\n[+] Using the current session");
                Console.WriteLine("Host: " + connectionString);
            }

            try
            {
                // Connect to LDAP
                ldapConnection = new DirectoryEntry(connectionString, username, password, System.DirectoryServices.AuthenticationTypes.Secure);
                Console.WriteLine("\n[+] Extracting LAPS password from LDAP");
                DirectorySearcher searcher = new DirectorySearcher(ldapConnection);
                searcher.Filter = "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))";

                // Iterate over all the credentials
                List <string> output = new List <string>();
                foreach (SearchResult result in searcher.FindAll())
                {
                    DirectoryEntry DirEntry = result.GetDirectoryEntry();
                    String         sam      = "Machine  : " + DirEntry.Properties["sAMAccountName"].Value;
                    String         pwd      = "Password : "******"ms-Mcs-AdmPwd"].Value;
                    Console.WriteLine(sam);
                    Console.WriteLine(pwd);
                    output.Add(DirEntry.Properties["sAMAccountName"].Value + ":" + DirEntry.Properties["ms-Mcs-AdmPwd"].Value);
                }

                // Export the data to the provided file
                if (parsed.Arguments.ContainsKey("/out"))
                {
                    File.AppendAllLines(parsed.Arguments["/out"], output);
                }
            }
            catch
            {
                Console.WriteLine("\n[!] Invalid credentials or unreachable server");
            }
        }
 private DirectorySearcher GetDirectorySearcher(string username, string password, string domain)
 {
     DirSearch = new DirectorySearcher(
         new DirectoryEntry("WinNT://" + domain, username, password, AuthenticationTypes.SecureSocketsLayer));
     return(DirSearch);
 }
Example #38
0
        internal override ResultSetBookmark BookmarkAndReset()
        {
            ADDNLinkedAttrSetBookmark aDDNLinkedAttrSetBookmark = new ADDNLinkedAttrSetBookmark();

            aDDNLinkedAttrSetBookmark.usersVisited = this.usersVisited;
            this.usersVisited = new Dictionary <string, bool>();
            aDDNLinkedAttrSetBookmark.groupsToVisit = this.groupsToVisit;
            this.groupsToVisit = new List <string>();
            string item = this.groupsVisited[0];

            aDDNLinkedAttrSetBookmark.groupsVisited = this.groupsVisited;
            this.groupsVisited = new List <string>();
            this.groupsVisited.Add(item);
            aDDNLinkedAttrSetBookmark.expansionMode = this.expansionMode;
            aDDNLinkedAttrSetBookmark.members       = this.members;
            aDDNLinkedAttrSetBookmark.membersEnum   = this.membersEnum;
            this.members     = null;
            this.membersEnum = null;
            if (this.membersQueue != null)
            {
                aDDNLinkedAttrSetBookmark.membersQueue = new Queue <IEnumerable>(this.membersQueue.Count);
                foreach (IEnumerable enumerable in this.membersQueue)
                {
                    aDDNLinkedAttrSetBookmark.membersQueue.Enqueue(enumerable);
                }
            }
            if (this.membersQueue != null)
            {
                this.membersQueue.Clear();
                if (this.originalMembers != null)
                {
                    foreach (IEnumerable enumerable1 in this.originalMembers)
                    {
                        this.membersQueue.Enqueue(enumerable1);
                        IEnumerator enumerator = enumerable1.GetEnumerator();
                        enumerator.Reset();
                    }
                }
            }
            aDDNLinkedAttrSetBookmark.storeCtx = this.storeCtx;
            this.expansionMode = this.originalExpansionMode;
            if (this.currentMembersSearcher != null)
            {
                this.currentMembersSearcher.Dispose();
                this.currentMembersSearcher = null;
            }
            this.storeCtx = this.originalStoreCtx;
            aDDNLinkedAttrSetBookmark.current = this.current;
            aDDNLinkedAttrSetBookmark.returnedPrimaryGroup = this.returnedPrimaryGroup;
            this.current = null;
            if (this.primaryGroupDN != null)
            {
                this.returnedPrimaryGroup = false;
            }
            aDDNLinkedAttrSetBookmark.foreignMembersCurrentGroup = this.foreignMembersCurrentGroup;
            aDDNLinkedAttrSetBookmark.fakePrincipalMembers       = this.fakePrincipalMembers;
            aDDNLinkedAttrSetBookmark.foreignMembersToReturn     = this.foreignMembersToReturn;
            aDDNLinkedAttrSetBookmark.currentForeignPrincipal    = this.currentForeignPrincipal;
            aDDNLinkedAttrSetBookmark.currentForeignDE           = this.currentForeignDE;
            this.foreignMembersCurrentGroup         = new List <DirectoryEntry>();
            this.fakePrincipalMembers               = new List <DirectoryEntry>();
            this.currentForeignDE                   = null;
            aDDNLinkedAttrSetBookmark.foreignGroups = this.foreignGroups;
            this.foreignGroups = new List <GroupPrincipal>();
            aDDNLinkedAttrSetBookmark.queryMembersResults          = this.queryMembersResults;
            aDDNLinkedAttrSetBookmark.queryMembersResultEnumerator = this.queryMembersResultEnumerator;
            this.queryMembersResults                                = null;
            this.queryMembersResultEnumerator                       = null;
            aDDNLinkedAttrSetBookmark.memberSearchResults           = this.memberSearchResults;
            aDDNLinkedAttrSetBookmark.memberSearchResultsEnumerator = this.memberSearchResultsEnumerator;
            this.memberSearchResults                                = null;
            this.memberSearchResultsEnumerator                      = null;
            if (this.memberSearchersQueue != null)
            {
                aDDNLinkedAttrSetBookmark.memberSearcherQueue = new Queue <DirectorySearcher>(this.memberSearchersQueue.Count);
                foreach (DirectorySearcher directorySearcher in this.memberSearchersQueue)
                {
                    aDDNLinkedAttrSetBookmark.memberSearcherQueue.Enqueue(directorySearcher);
                }
            }
            if (this.memberSearchersQueueOriginal != null)
            {
                this.memberSearchersQueue.Clear();
                foreach (DirectorySearcher directorySearcher1 in this.memberSearchersQueueOriginal)
                {
                    this.memberSearchersQueue.Enqueue(directorySearcher1);
                }
            }
            aDDNLinkedAttrSetBookmark.atBeginning = this.atBeginning;
            this.atBeginning = true;
            return(aDDNLinkedAttrSetBookmark);
        }
Example #39
0
        public Response AuthenticateADOnly(string domain, string userId, string password, out User userAuthenticated)
        {
            var response = new Response {
                Message = "Not initializated", Result = false
            };

            userAuthenticated = null;


            //ActiveDirectory Authentication
            SearchResult ADSearchresult = null;


            var    pathLDap          = _LDapConnectionString;
            string domainAndUsername = domain + @"\" + userId;


            var entry = new DirectoryEntry(pathLDap, domainAndUsername, password);

            try
            {
                // Bind to the native AdsObject to force authentication.
                var obj = entry.NativeObject;
                //var search = new DirectorySearcher(entry, "(SAMAccountName=" + userId + ")");
                var search = new DirectorySearcher(entry);

                if (userAuthenticated == null)
                {
                    search.Filter = "(SAMAccountName=" + userId + ")";
                }
                else
                {
                    search.Filter = "(SAMAccountName=" + userAuthenticated.EmployeeNumber + ")";
                }
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("givenname");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("samaccountname");
                ADSearchresult = search.FindOne();
            }
            catch (Exception ex)
            {
                response.Message = ("600 - No fue posible autenticar la cuenta de usuario en el Directorio Activo. Revise datos en SeguridadApp. Error: " + ex.Message);
            }

            if (null == ADSearchresult)
            {
                response.Result   = false;
                response.Message  = string.Format("No se pudo localizar el usuario en AD o su contraseña es erronea. {0:dd/MM/yyyy} {1:hh:mm:ss}", DateTime.Now, DateTime.Now);
                userAuthenticated = null;
                return(response);
            }
            else
            {
                userAuthenticated = new User()
                {
                    EmployeeNames      = GetProperty(ADSearchresult, "givenName"),
                    EmployeeLastName   = GetProperty(ADSearchresult, "sn"),
                    EmployeeEmail      = GetProperty(ADSearchresult, "mail"),
                    UserId             = GetProperty(ADSearchresult, "mail"),
                    AuthenticationType = AuthenticationTypeEnum.ActiveDirectoryOnly
                };
            }

            if (string.IsNullOrEmpty(userAuthenticated.EmployeeNames))
            {
                response.Message  = string.Format("No ha sido capturado el nombre del usuario en Directorio Activo ");
                response.Result   = false;
                userAuthenticated = null;
                return(response);
            }

            if (string.IsNullOrEmpty(userAuthenticated.EmployeeLastName))
            {
                response.Message  = string.Format("No ha sido capturado el apellido del usuario en Directorio Activo. ");
                response.Result   = false;
                userAuthenticated = null;
                return(response);
            }

            if (string.IsNullOrEmpty(userAuthenticated.EmployeeEmail))
            {
                response.Message  = string.Format("No ha sido capturado el correo electronico del usuario en Directorio Activo.");
                response.Result   = false;
                userAuthenticated = null;
                return(response);
            }


            response.Result  = true;
            response.Message = string.Format("Se encontró el usuario en AD.");



            return(response);
        }
Example #40
0
 internal override void Reset()
 {
     if (!this.atBeginning)
     {
         this.usersVisited.Clear();
         this.groupsToVisit.Clear();
         string item = this.groupsVisited[0];
         this.groupsVisited.Clear();
         this.groupsVisited.Add(item);
         this.members     = null;
         this.membersEnum = null;
         if (this.originalMembers != null)
         {
             this.membersQueue.Clear();
             foreach (IEnumerable enumerable in enumerable)
             {
                 this.membersQueue.Enqueue(enumerable);
                 IEnumerator enumerator = enumerable.GetEnumerator();
                 enumerator.Reset();
             }
         }
         this.expansionMode = this.originalExpansionMode;
         this.storeCtx      = this.originalStoreCtx;
         this.current       = null;
         if (this.primaryGroupDN != null)
         {
             this.returnedPrimaryGroup = false;
         }
         this.foreignMembersCurrentGroup.Clear();
         this.fakePrincipalMembers.Clear();
         if (this.foreignMembersToReturn != null)
         {
             this.foreignMembersToReturn.Clear();
         }
         this.currentForeignPrincipal = null;
         this.currentForeignDE        = null;
         this.foreignGroups.Clear();
         this.queryMembersResultEnumerator = null;
         if (this.queryMembersResults != null)
         {
             this.queryMembersResults.Dispose();
             this.queryMembersResults = null;
         }
         if (this.currentMembersSearcher != null)
         {
             this.currentMembersSearcher.Dispose();
             this.currentMembersSearcher = null;
         }
         this.memberSearchResultsEnumerator = null;
         if (this.memberSearchResults != null)
         {
             this.memberSearchResults.Dispose();
             this.memberSearchResults = null;
         }
         if (this.memberSearchersQueue != null)
         {
             foreach (DirectorySearcher directorySearcher in this.memberSearchersQueue)
             {
                 directorySearcher.Dispose();
             }
             this.memberSearchersQueue.Clear();
             if (this.memberSearchersQueueOriginal != null)
             {
                 foreach (DirectorySearcher directorySearcher1 in this.memberSearchersQueueOriginal)
                 {
                     this.memberSearchersQueue.Enqueue(directorySearcher1);
                 }
             }
         }
         this.atBeginning = true;
     }
 }
Example #41
0
        public int LoginUser(string _username, string _password, int _environment, bool _log, bool _admin)
        {
            Variables oNCB = new Variables(_environment);
            int       _id  = oUser.GetId(_username);

            if (_id != 0)
            {
                DirectoryEntry    oEntry    = new DirectoryEntry(oNCB.primaryDC(dsn), oNCB.Domain() + "\\" + _username, _password);
                DirectorySearcher oSearcher = new DirectorySearcher(oEntry);
                oSearcher.Filter = "(objectCategory=user)";
                try
                {
                    SearchResult oResult = oSearcher.FindOne();
                    oUser.AddLogin(_username);
                    return(_id);
                }
                catch
                {
                    // ADD PNC Authentication
                    if (_environment == (int)CurrentEnvironment.CORPDMN)
                    {
                        Variables         oPNC         = new Variables((int)CurrentEnvironment.PNCNT_PROD);
                        DirectoryEntry    oPNCEntry    = new DirectoryEntry(oPNC.primaryDC(dsn), oPNC.Domain() + "\\" + _username, _password);
                        DirectorySearcher oPNCSearcher = new DirectorySearcher(oPNCEntry);
                        oSearcher.Filter = "(objectCategory=user)";
                        try
                        {
                            SearchResult oPNCResult = oPNCSearcher.FindOne();
                            oUser.AddLogin(_username);
                            return(_id);
                        }
                        catch
                        {
                            // ADD PNC Authentication
                            return(-10);
                        }
                    }
                    else if (_environment == (int)CurrentEnvironment.PNCNT_PROD)
                    {
                        oNCB = new Variables((int)CurrentEnvironment.CORPDMN);
                        DirectoryEntry    oNCBEntry    = new DirectoryEntry(oNCB.primaryDC(dsn), oNCB.Domain() + "\\" + _username, _password);
                        DirectorySearcher oNCBSearcher = new DirectorySearcher(oNCBEntry);
                        oNCBSearcher.Filter = "(objectCategory=user)";
                        try
                        {
                            SearchResult oNCBResult = oNCBSearcher.FindOne();
                            oUser.AddLogin(_username);
                            return(_id);
                        }
                        catch
                        {
                            // ADD PNC Authentication
                            return(-10);
                        }
                    }
                    else
                    {
                        return(-1);
                    }
                }
            }
            else
            {
                return(0);
            }
        }
Example #42
0
        public IActionResult loginByUsernames([FromBody] JObject value)
        {
            string userId   = "";
            string userName = "";

            try
            {
                Dictionary <string, object> d = value.ToObject <Dictionary <string, object> >();
                string username = d["username"] == null ? "" : d["username"].ToString();
                string password = d["password"] == null ? "" : d["password"].ToString();
                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                {
                    return(Json(new { code = -1, message = "用户名或密码不能为空!" }));
                }
                UserModule mm = new UserModule();
                userId = mm.getAdminCode();
                string pass = mm.getAdminPass();
                if ((username == userId))
                {
                    if (password != pass)
                    {
                        return(Json(new { code = -1, message = "管理员密码不正确!" }));
                    }
                    userName = "******";
                    string accessToken = AccessTokenTool.GetAccessToken(userId);
                    UIDP.UTILITY.AccessTokenTool.DeleteToken(userId);
                    UIDP.UTILITY.AccessTokenTool.InsertToken(userId, accessToken, DateTime.Now.AddHours(1));
                    log.Info(DateTime.Now, userId, userName, Extension.GetClientUserIp(Request.HttpContext), 2, "LogIn", "", 1);
                    return(Json(new
                    {
                        code = 2000,
                        message = "",
                        token = accessToken,
                        orgList = new DataTable(),
                        userList = new DataTable(),
                        roleLevel = "admin"
                    }));
                }
                else
                {
                    UserLoginModule um = new UserLoginModule();
                    if (d["userDomain"].ToString() == "PTR_IDENT")
                    {
                        var builder = new ConfigurationBuilder()
                                      .SetBasePath(Directory.GetCurrentDirectory())
                                      .AddJsonFile("appsettings.json");
                        Configuration = builder.Build();
                        string            LDAPPATH   = Configuration["LdapPath"];
                        DirectoryEntry    entry      = new DirectoryEntry(LDAPPATH, username, password);
                        DirectorySearcher mySearcher = new DirectorySearcher(entry);
                        mySearcher.Filter = "(SAMAccountName=" + username + ")";
                        SearchResult result = mySearcher.FindOne();
                        if (result == null)
                        {
                            throw new Exception("用户认证错误");
                        }
                        else
                        {
                            DataTable userdt = um.getUserInfoByName(username);
                            if (userdt == null || userdt.Rows.Count == 0)
                            {
                                return(Json(new { code = -1, message = "本地用户不存在,请同步用户信息!" }));
                            }
                            Dictionary <string, object> dinfo = new Dictionary <string, object>();
                            if (password != userdt.Rows[0]["USER_PASS"].ToString())
                            {
                                //dinfo["password"] = userdt.Rows[0]["USER_PASS"].ToString();
                                dinfo["newpassword"] = password;
                                dinfo["userid"]      = userdt.Rows[0]["USER_ID"].ToString();
                                mm.updatePTRpass(dinfo);
                            }
                        }
                    }

                    DataTable dt = um.getUserInfoByName(username);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        return(Json(new { code = -1, message = "此用户不存在!" }));
                    }
                    password = UIDP.Security.SecurityHelper.StringToMD5Hash(password);
                    if (password != dt.Rows[0]["USER_PASS"].ToString())
                    {
                        return(Json(new { code = -1, message = "密码错误!" }));
                    }
                    userId = dt.Rows[0]["USER_ID"].ToString();
                    //userName = dt.Rows[0]["LOGIN_REMARK"].ToString();
                    string accessToken = AccessTokenTool.GetAccessToken(userId);
                    UIDP.UTILITY.AccessTokenTool.DeleteToken(userId);
                    UIDP.UTILITY.AccessTokenTool.InsertToken(userId, accessToken, DateTime.Now.AddHours(1));
                    DataTable dtUser = um.getLoginByID(userId);
                    int       level  = 1;
                    if (Extension.GetClientUserIp(Request.HttpContext).ToString() != dt.Rows[0]["USER_IP"].ToString())
                    {
                        level = 2;
                    }
                    log.Info(DateTime.Now, userId, userName, Extension.GetClientUserIp(Request.HttpContext), 2, "LogIn", "", level);
                    return(Json(new
                    {
                        code = 2000,
                        message = "",
                        token = accessToken,
                        orgList = new DataTable(),
                        userList = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dtUser)),
                        roleLevel = ""
                    }));
                }
            }
            catch (Exception ex)
            {
                log.Info(DateTime.Now, userId, userName, Extension.GetClientUserIp(Request.HttpContext), 1, "LogIn", ex.Message.Length > 120 ? ex.Message.Substring(0, 100) : ex.Message, 1);
                return(Json(new { code = -1, message = "登录时程序发生错误" + ex.Message }));
            }
        }
Example #43
0
        public void GetDomainsAndTrusts(string DomainName)
        {
            if (dbmanager.IsDomainCompleted(DomainName) && !options.Rebuild)
            {
                return;
            }
            Console.WriteLine($"Building Domain Trust Data for {DomainName}");
            List <string>  enumerated = new List <string>();
            Queue <string> ToEnum     = new Queue <string>();

            //Get our current domain's info
            string current = DomainName;

            ToEnum.Enqueue(current);
            //Convert the DNS name to the NetBIOS name
            IntPtr pDCI = IntPtr.Zero;
            DOMAIN_CONTROLLER_INFO info;
            int dsresult = DsGetDcName(null, current, 0, null, DSGETDCNAME_FLAGS.DS_IS_DNS_NAME | DSGETDCNAME_FLAGS.DS_RETURN_FLAT_NAME, out pDCI);

            info = (DOMAIN_CONTROLLER_INFO)Marshal.PtrToStructure(pDCI, typeof(DOMAIN_CONTROLLER_INFO));
            string netbiosname = info.DomainName;

            NetApiBufferFree(pDCI);

            options.WriteVerbose("Grabbed initial trusts");

            DomainDB temp = new DomainDB()
            {
                Completed       = false,
                DomainDNSName   = current,
                DomainShortName = netbiosname,
                DomainSid       = helpers.GetDomainSid(current),
                Trusts          = new List <DomainTrust>()
            };

            dbmanager.InsertDomain(temp);

            while (!(ToEnum.Count == 0))
            {
                string d = ToEnum.Dequeue();
                dbmanager.GetDomain(d, out temp);
                enumerated.Add(d);

                options.WriteVerbose($"Grabbing trusts for {d}");

                temp.DomainDNSName = d;

                DirectorySearcher searcher = helpers.GetDomainSearcher(d);
                if (searcher == null)
                {
                    continue;
                }
                searcher.Filter = "(userAccountControl:1.2.840.113556.1.4.803:=8192)";
                string server;
                try
                {
                    SearchResult dc = searcher.FindOne();
                    server = dc.GetProp("dnshostname");
                }
                catch
                {
                    options.WriteVerbose($"Unable to get Domain Controller for {DomainName}");
                    continue;
                }


                searcher.Dispose();

                List <DomainTrust> trusts = new List <DomainTrust>();

                IntPtr ptr    = IntPtr.Zero;
                uint   types  = 63;
                Type   DDT    = typeof(DS_DOMAIN_TRUSTS);
                uint   result = DsEnumerateDomainTrusts(server, types, out ptr, out uint domaincount);
                int    error  = Marshal.GetLastWin32Error();

                if (result == 0)
                {
                    DS_DOMAIN_TRUSTS[] array = new DS_DOMAIN_TRUSTS[domaincount];
                    IntPtr             iter  = ptr;
                    for (int i = 0; i < domaincount; i++)
                    {
                        DS_DOMAIN_TRUSTS t = (DS_DOMAIN_TRUSTS)Marshal.PtrToStructure(iter, DDT);
                        array[i] = t;
                        iter     = (IntPtr)(iter.ToInt64() + Marshal.SizeOf(DDT));
                    }
                    for (int i = 0; i < domaincount; i++)
                    {
                        DS_DOMAIN_TRUSTS t            = array[i];
                        string           dns          = t.DnsDomainName;
                        string           netbios      = t.NetbiosDomainName;
                        TRUST_TYPE       trust_type   = (TRUST_TYPE)t.Flags;
                        TRUST_ATTRIB     trust_attrib = (TRUST_ATTRIB)t.TrustAttributes;


                        if ((trust_type & TRUST_TYPE.DS_DOMAIN_TREE_ROOT) == TRUST_TYPE.DS_DOMAIN_TREE_ROOT)
                        {
                            continue;
                        }

                        DomainDB tempdomain = new DomainDB()
                        {
                            DomainDNSName   = dns,
                            DomainShortName = netbios
                        };
                        ConvertSidToStringSid(t.DomainSid, out string s);
                        tempdomain.DomainSid = s;
                        tempdomain.Completed = false;
                        tempdomain.Trusts    = new List <DomainTrust>();
                        dbmanager.InsertDomain(tempdomain);

                        DomainTrust temptrust = new DomainTrust()
                        {
                            TargetDomain = t.DnsDomainName
                        };
                        bool inbound  = false;
                        bool outbound = false;

                        inbound  = (trust_type & TRUST_TYPE.DS_DOMAIN_DIRECT_INBOUND) == TRUST_TYPE.DS_DOMAIN_DIRECT_INBOUND;
                        outbound = (trust_type & TRUST_TYPE.DS_DOMAIN_DIRECT_OUTBOUND) == TRUST_TYPE.DS_DOMAIN_DIRECT_OUTBOUND;

                        if (inbound && outbound)
                        {
                            temptrust.TrustDirection = "Bidirectional";
                        }
                        else if (inbound)
                        {
                            temptrust.TrustDirection = "Inbound";
                        }
                        else
                        {
                            temptrust.TrustDirection = "Outbound";
                        }


                        if ((trust_type & TRUST_TYPE.DS_DOMAIN_IN_FOREST) == TRUST_TYPE.DS_DOMAIN_IN_FOREST)
                        {
                            temptrust.TrustType = "ParentChild";
                        }
                        else
                        {
                            temptrust.TrustType = "External";
                        }

                        temptrust.IsTransitive = !((trust_attrib & TRUST_ATTRIB.NON_TRANSITIVE) == TRUST_ATTRIB.NON_TRANSITIVE);
                        temptrust.SourceDomain = dns;
                        trusts.Add(temptrust);
                        if (!enumerated.Contains(dns))
                        {
                            ToEnum.Enqueue(dns);
                        }
                    }

                    temp.Trusts = trusts;
                    dbmanager.InsertDomain(temp);
                    NetApiBufferFree(ptr);
                }
            }
        }
Example #44
0
        /// <summary>
        /// Check User in AD (DirectoryEntry - attributes + CheckBox_UserMailAct)
        /// </summary>
        private async Task DirectoryEnt(string userlogin)
        {
            try
            {
                SearchResult rs = await Task.Run(() =>
                {
                    DirectoryEntry de    = new DirectoryEntry("LDAP://ldap.gk.corp.tepenet");
                    DirectorySearcher ds = new DirectorySearcher(de)
                    {
                        Filter      = "(&((&(objectCategory=Person)(objectClass=User)))(sAMAccountName=" + userlogin + "))",
                        SearchScope = SearchScope.Subtree
                    };
                    return(ds.FindOne());
                });

                var value3 = (rs.GetDirectoryEntry().Properties["userPrincipalName"].Value ?? "BRAK").ToString();
                if (value3.Contains("BRAK"))
                {
                    _mainWindow.userBptpTextBox.Text = "Brak";
                }
                else
                {
                    _mainWindow.userBptpTextBox.Text = value3;
                }

                long value4 = (long)rs.Properties["pwdLastSet"][0];
                if (value4 == 0)
                {
                    _mainWindow.userLastPassSetTextBox.Text = "Flaga zmiany hasła!";
                }
                else
                {
                    DateTime pwdLastSet = DateTime.FromFileTimeUtc(value4).ToLocalTime();
                    _mainWindow.userLastPassSetTextBox.Text = pwdLastSet.ToString();
                }

                var value6 = (rs.GetDirectoryEntry().Properties["employeePTKID"].Value ?? "BRAK").ToString();
                if (value6.Contains("BRAK"))
                {
                    _mainWindow.userIfsTextBox.Text = "Brak Danych";
                }
                else
                {
                    _mainWindow.userIfsTextBox.Text = value6;
                }

                var value7 = (rs.GetDirectoryEntry().Properties["manager"].Value ?? "BRAK").ToString();
                var value5 = (rs.GetDirectoryEntry().Properties["extensionAttribute12"].Value ?? "BRAK").ToString();
                if (value7.Contains("BRAK"))
                {
                    _mainWindow.userManagerTextBox.Text = "BRAK"; _mainWindow.userFunctionalTextBox.Text = "BRAK";
                }
                else
                {
                    string value7a = value7.Remove(value7.IndexOf(",")).Substring(value7.IndexOf("=") + 1);

                    using (var ctx = new PrincipalContext(ContextType.Domain))
                        using (UserPrincipal fullmanag = UserPrincipal.FindByIdentity(ctx, value7a))
                        {
                            if (fullmanag == null)
                            {
                                _mainWindow.userManagerTextBox.Text    = "Błędne dane w AD";
                                _mainWindow.userFunctionalTextBox.Text = "Błędne dane w AD";
                            }
                            else if (value5.Contains("BRAK"))
                            {
                                _mainWindow.userManagerTextBox.Text    = fullmanag.DisplayName;
                                _mainWindow.userFunctionalTextBox.Text = "BRAK";
                            }
                            else
                            {
                                _mainWindow.userManagerTextBox.Text    = value5;
                                _mainWindow.userFunctionalTextBox.Text = fullmanag.DisplayName;
                            }
                        }
                }

                var value8 = (rs.GetDirectoryEntry().Properties["businessCategory"].Value ?? "BRAK").ToString();
                if (value8.Contains("BRAK"))
                {
                    _mainWindow.userEmploymentTextBox.Text = "BRAK";
                }
                else
                {
                    _mainWindow.userEmploymentTextBox.Text = value8;
                }

                var value9 = (rs.GetDirectoryEntry().Properties["msRTCSIP-PrimaryUserAddress"].Value ?? "BRAK").ToString();
                if (value9.Contains("BRAK"))
                {
                    _mainWindow.userSipTextBox.Text = "BRAK";
                }
                else
                {
                    _mainWindow.userSipTextBox.Text = value9.Replace("sip:", "");
                }

                var value10 = (rs.GetDirectoryEntry().Properties["extensionAttribute1"].Value ?? "BRAK").ToString();
                if (value10.Contains("BRAK"))
                {
                    _mainWindow.userMailClassTextBox.Text = "BRAK";
                }
                else
                {
                    _mainWindow.userMailClassTextBox.Text = value10;
                }

                var value11 = (rs.GetDirectoryEntry().Properties["mDBOverHardQuotaLimit"].Value ?? "BRAK").ToString();
                if (value11.Contains("BRAK"))
                {
                    _mainWindow.userMailQuotaTextBox.Text = "BRAK";
                }
                else
                {
                    _mainWindow.userMailQuotaTextBox.Text = value11;
                }

                var value12 = (rs.GetDirectoryEntry().Properties["mail"].Value ?? "BRAK").ToString();
                if (value12.Contains("BRAK"))
                {
                    _mainWindow.userMailAddressTextBox.Text = "BRAK";
                }
                else
                {
                    _mainWindow.userMailAddressTextBox.Text = value12;
                }

                var    count        = rs.GetDirectoryEntry().Properties["workstationAdmin"].Count;
                var    value13Array = rs.GetDirectoryEntry().Properties["workstationAdmin"].Value;
                string value13      = "";
                if (count == 1)
                {
                    _mainWindow.userDeveloperTextBox.Text = value13Array.ToString();
                }
                else
                {
                    for (int i = 0; i < count; i++)
                    {
                        value13 += ((object[])value13Array)[i].ToString() + Environment.NewLine;
                    }
                    if (value13.Contains("BRAK"))
                    {
                        _mainWindow.userDeveloperTextBox.Text = "Brak profilu developer.";
                    }
                    else
                    {
                        _mainWindow.userDeveloperTextBox.Text = value13;
                    }
                }

                var value14 = (rs.GetDirectoryEntry().Properties["extensionAttribute1"].Value ?? "BRAK").ToString();

                if (value14.Contains("BRAK"))
                {
                    _mainWindow.mailAccCheckBox.IsChecked = false; _mainWindow.mailAccCheckBox.Background = Brushes.Red;
                }
                else if (value14.Contains("Disabled"))
                {
                    _mainWindow.mailAccCheckBox.IsChecked = false; _mainWindow.mailAccCheckBox.Background = Brushes.Red;
                }
                else
                {
                    _mainWindow.mailAccCheckBox.IsChecked = true; _mainWindow.mailAccCheckBox.Background = Brushes.ForestGreen;
                }

                var value15 = (rs.GetDirectoryEntry().Properties["whenCreated"].Value ?? "BRAK").ToString();
                _mainWindow.userAccCreated.Text = value15;
            }
            catch (Exception e)
            {
                _mainWindow.popupText.Text           = e.Message;
                _mainWindow.mainPopupBox.IsPopupOpen = true;
                return;
            }
        }
Example #45
0
        public void StartEnumeration()
        {
            if (options.NoDB)
            {
                return;
            }
            List <string> Domains = helpers.GetDomainList();

            foreach (string DomainName in Domains)
            {
                GetDomainsAndTrusts(DomainName);
            }

            String[] props = { "samaccountname", "distinguishedname", "dnshostname", "samaccounttype", "primarygroupid", "memberof", "objectsid", "objectclass", "ntsecuritydescriptor", "serviceprincipalname", "homedirectory", "scriptpath", "profilepath" };

            Stopwatch overwatch    = Stopwatch.StartNew();
            bool      DidEnumerate = false;

            foreach (string DomainName in Domains)
            {
                if (dbmanager.IsDomainCompleted(DomainName) && !options.Rebuild)
                {
                    Console.WriteLine(string.Format("Skipping cache building for {0} because it already exists", DomainName));
                    continue;
                }
                DidEnumerate = true;

                CurrentDomain = DomainName;

                Console.WriteLine();
                Console.WriteLine("Building database for " + DomainName);

                DirectorySearcher searcher = helpers.GetDomainSearcher(Domain: DomainName);
                if (searcher == null)
                {
                    Console.WriteLine($"Unable to contact {DomainName}");
                    continue;
                }

                BlockingCollection <DBObject>        output    = new BlockingCollection <DBObject>();
                BlockingCollection <SearchResult>    input     = new BlockingCollection <SearchResult>();
                LimitedConcurrencyLevelTaskScheduler scheduler = new LimitedConcurrencyLevelTaskScheduler(options.Threads);
                TaskFactory factory = new TaskFactory(scheduler);

                count = 0;

                System.Timers.Timer t = new System.Timers.Timer();
                t.Elapsed += Timer_Tick;

                t.Interval = options.Interval;
                t.Enabled  = true;

                DBManager   db          = DBManager.Instance;
                List <Task> taskhandles = new List <Task>();
                Task        WriterTask  = StartWriter(output, factory);

                for (int i = 0; i < options.Threads; i++)
                {
                    taskhandles.Add(StartConsumer(input, output, factory));
                }

                searcher.Filter = "(|(samAccountType=805306368)(samAccountType=805306369)(samAccountType=268435456)(samAccountType=268435457)(samAccountType=536870912)(samAccountType=536870913)(objectclass=domain))";
                searcher.PropertiesToLoad.AddRange(props);
                searcher.SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner;

                foreach (SearchResult r in searcher.FindAll())
                {
                    input.Add(r);
                }

                searcher.Dispose();
                input.CompleteAdding();
                options.WriteVerbose("Waiting for consumers to finish...");
                Task.WaitAll(taskhandles.ToArray());
                output.CompleteAdding();
                options.WriteVerbose("Waiting for writer to finish...");
                WriterTask.Wait();
                t.Dispose();
                Console.WriteLine("Built database for " + DomainName + " in " + watch.Elapsed);
                dbmanager.GetDomain(DomainName, out DomainDB domain);
                domain.Completed = true;
                dbmanager.InsertDomain(domain);
                watch.Reset();
            }
            if (DidEnumerate)
            {
                Console.WriteLine($"Finished database building in {overwatch.Elapsed}\n");
            }
            dbmanager.UpdateDBMap();
            overwatch.Stop();
            watch.Stop();
        }
Example #46
0
    public static JObject GetDomainGpos()
    {
        DirectoryEntry rootDse              = new DirectoryEntry("LDAP://rootDSE");
        DirectoryEntry root                 = new DirectoryEntry("GC://" + rootDse.Properties["defaultNamingContext"].Value);
        string         schemaContextString  = rootDse.Properties["schemaNamingContext"].Value.ToString();
        DirectoryEntry rootExtRightsContext = new DirectoryEntry("LDAP://" + schemaContextString.Replace("Schema", "Extended-Rights"));

        // make a searcher to find GPOs
        DirectorySearcher gpoSearcher = new DirectorySearcher(root)
        {
            Filter        = "(objectClass=groupPolicyContainer)",
            SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
        };

        SearchResultCollection gpoSearchResults = gpoSearcher.FindAll();

        // stolen from prashant - grabbing guids
        Dictionary <string, string> guidDict = new Dictionary <string, string>();

        guidDict.Add("00000000-0000-0000-0000-000000000000", "All");

        // and again where we grab all the Extended Rights
        DirectorySearcher rightsSearcher = new DirectorySearcher(rootExtRightsContext)
        {
            Filter           = "(objectClass=controlAccessRight)",
            PropertiesToLoad = { "name", "rightsGUID" }
        };

        SearchResultCollection extRightsResultCollection = rightsSearcher.FindAll();

        foreach (SearchResult extRightsResult in extRightsResultCollection)
        {
            string extRightGuidString = extRightsResult.Properties["rightsguid"][0].ToString();
            string extRightNameString = extRightsResult.Properties["name"][0].ToString();
            // for some reason we hit a single duplicate in this lot. nfi what that's about. TODO - figure that out.
            try
            {
                guidDict.Add(extRightGuidString, extRightNameString);
            }
            catch (System.ArgumentException e)
            {
                Utility.DebugWrite("Hit a duplicate GUID in extRightsResult");
            }
        }

        // new dictionary for data from each GPO to go into
        JObject gposData = new JObject();

        foreach (SearchResult gpoSearchResult in gpoSearchResults)
        {
            // object for all data for this one gpo
            JObject        gpoData = new JObject();
            DirectoryEntry gpoDe   = gpoSearchResult.GetDirectoryEntry();
            // get some useful attributes of the gpo
            string gpoDispName = gpoDe.Properties["displayName"].Value.ToString();
            gpoData.Add("Display Name", gpoDispName);
            string gpoUid = gpoDe.Properties["name"].Value.ToString();
            gpoData.Add("UID", gpoUid);
            string gpoDn = gpoDe.Properties["distinguishedName"].Value.ToString();
            gpoData.Add("Distinguished Name", gpoDn);

            // get the acl
            ActiveDirectorySecurity gpoAcl = gpoDe.ObjectSecurity;
            // make a JObject to put the acl in
            JObject gpoAclJObject = new JObject();
            //iterate over the aces in the acl
            foreach (ActiveDirectoryAccessRule gpoAce in gpoAcl.GetAccessRules(true, true,
                                                                               typeof(System.Security.Principal.SecurityIdentifier)))
            {
                int aceInterestLevel = 1;
                ActiveDirectoryRights adRightsObj = gpoAce.ActiveDirectoryRights;


                // get the rights quick and dirty
                string adRights = gpoAce.ActiveDirectoryRights.ToString();
                // clean the commas out
                string cleanAdRights = adRights.Replace(", ", " ");
                // chuck them into an array
                string[]      adRightsArray = cleanAdRights.Split(' ');
                List <string> adRightsList  = adRightsArray.ToList();
                // handle extended rights
                if ((adRightsObj & ActiveDirectoryRights.ExtendedRight) != 0)
                {
                    //Utility.DebugWrite("F**k, I still have to deal with Extended Rights.");
                    string extendedRightString = guidDict[Convert.ToString(gpoAce.ObjectType)];
                    adRightsList.Add(extendedRightString);
                    //Utility.DebugWrite("Extended Right " + extendedRightString + " found.");
                }
                // an array of interesting privs
                string[] intRightsArray = new string[]
                {
                    "WriteOwner", "GenericAll", "WriteProperty", "WriteDacl", "CreateChild", "DeleteChild", "Self",
                    "DeleteTree", "Delete"
                };
                // if we see one of these, the ACE just got more interesting.
                foreach (string right in adRightsArray)
                {
                    if (intRightsArray.Contains(right))
                    {
                        aceInterestLevel++;
                    }
                }

                string trusteeSid = gpoAce.IdentityReference.ToString();
                // array of sid endings for the SIDs of default high-priv trustees.
                // this is extremely lazy but it will work for now.
                string[] boringSidEndings = new string[] { "-3-0", "-5-9", "5-18", "-512", "-519" };
                // if the last 4 chars of trusteeSid match an entry in boringSidEndings, reduce the interest level back to default.
                if (boringSidEndings.Contains(trusteeSid.Substring((trusteeSid.Length - 4), 4)))
                {
                    aceInterestLevel = 0;
                }

                string trusteeName    = GetUserFromSid(trusteeSid);
                string acType         = gpoAce.AccessControlType.ToString();
                string trusteeNAcType = trusteeName + " - " + acType + " - " + trusteeSid;

                if (aceInterestLevel >= GlobalVar.IntLevelToShow)
                {
                    // create a JObject of the new stuff we know
                    JObject aceToMerge = new JObject()
                    {
                        new JProperty(trusteeNAcType, new JArray(JArray.FromObject(adRightsArray)))
                    };
                    gpoAclJObject.Merge(aceToMerge, new JsonMergeSettings
                    {
                        MergeArrayHandling = MergeArrayHandling.Union
                    });
                }
            }

            //add the JObject to our blob of data about the gpo
            if (gpoAclJObject.HasValues)
            {
                gpoData.Add("ACLs", gpoAclJObject);
            }

            // then add all of the above to the big blob of data about all gpos
            gposData.Add(gpoUid, gpoData);
        }

        return(gposData);
    }
Example #47
0
        public void SearchADUpdated()
        {
            int       i;
            string    var_domains = Convert.ToString(System.Configuration.ConfigurationSettings.AppSettings["validdomains"]);
            ArrayList domains     = new ArrayList(var_domains.Split(new char[] { ',' }));
            string    domain;

            int count;

            count = 1;

            DataTable dtEmployee = new DataTable("dtEmployee");

            dtEmployee.Columns.Add("employeeNumber", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("displayName", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("GivenName", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("sn", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("initials", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("Mail", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("sAMAccountName", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("domain", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("employeeType", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("department", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("telephoneNumber", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("title", System.Type.GetType("System.String"));
            dtEmployee.Columns.Add("ADID", System.Type.GetType("System.String"));


            dsEmployee.Tables.Add(dtEmployee);

            string strFilter = "";
            string strFname  = "";
            string strLname  = "";

            strFname = Convert.ToString(Request.QueryString["ppl_Fname"]);
            strLname = Convert.ToString(Request.QueryString["ppl_Lname"]);

            if (strFname != null || strLname != null)
            {
                if (strFname.Length > 0 || strLname.Length > 0)
                {
                    if (strFname != null && strFname.Length > 0)
                    {
                        strFilter = "(&(givenname=" + strFname + "*)(ObjectCategory=User)(ObjectClass=Person)(samaccountname=*))";
                    }

                    else if (strLname != null && strLname.Length > 0)
                    {
                        strFilter = "(&(sn=" + strLname + "*)(ObjectCategory=User)(ObjectClass=Person)(samaccountname=*))";
                    }

                    if (strFname != null && strLname != null && strFname.Length > 0 && strLname.Length > 0)
                    {
                        strFilter = "(&(sn=" + strLname + "*)(givenname=" + strFname + "*)(ObjectCategory=User)(ObjectClass=Person)(samaccountname=*))";
                    }


                    //for (i = 0; i < domains.Count; i++)
                    //{
                    //domain = domains[i].ToString();
                    string str_ADUserName = System.Configuration.ConfigurationSettings.AppSettings["ad_username"].ToString();
                    string str_ADPassword = System.Configuration.ConfigurationSettings.AppSettings["ad_password"].ToString();

                    //DirectoryEntry enTry = new DirectoryEntry("LDAP://" + domain.Trim() + ".ad.viacom.com", str_ADUserName, str_ADPassword, AuthenticationTypes.None);
                    DirectoryEntry enTry = new DirectoryEntry("GC://" + var_domains.Trim(), str_ADUserName, str_ADPassword);

                    DirectorySearcher mySearcher = new DirectorySearcher(enTry, strFilter);

                    mySearcher.PropertyNamesOnly = true;
                    mySearcher.PageSize          = 8;
                    mySearcher.SizeLimit         = 8000;

                    foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
                    {
                        getADproperty(ref dsEmployee, resEnt.GetDirectoryEntry(), var_domains, ref count);
                    }

                    mySearcher = null;
                    //}
                }
            }
        }
Example #48
0
    //--------------------------------------------------------------------
    /// <summary>
    /// If user is active directory try to authenticate user from active directory.
    /// </summary>
    /// <param name="OUser"></param>
    //--------------------------------------------------------------------

    protected bool IsActiveDirectory(OUser user)
    {
        DirectoryEntry entry = null;
        if (user.ActiveDirectoryDomain != null && user.ActiveDirectoryDomain != string.Empty)
        {
            entry = new DirectoryEntry(OApplicationSetting.Current.ActiveDirectoryPath,
                                                      user.ActiveDirectoryDomain + "\\" + login.UserName,
                                                         login.Password);
        }
        else
        {
            entry = new DirectoryEntry(OApplicationSetting.Current.ActiveDirectoryPath,
                                                      OApplicationSetting.Current.ActiveDirectoryDomain + "\\" + login.UserName,
                                                         login.Password);
        }

        Object obj = entry.NativeObject;

        DirectorySearcher search = new DirectorySearcher(entry);

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

        if (null == result)
            return false;
        return true;
    }
Example #49
0
        /// <summary>
        /// Valida en el active directory si el usuairo existe y esta activo
        /// </summary>
        /// <param name="usuario">Nombre del usuario del active direcory</param>
        /// <param name="contrasenia">Contraseña del usuario del active directory</param>
        /// <returns>Resulta de la operación con la información de validacion del usuario en el active directory</returns>
        public static ResultadoOperacionDto EsUsuarioValido(String usuario, String contrasenia)
        {
            ResultadoOperacionDto resultadoValidacion = new ResultadoOperacionDto();

            var server           = ConfigurationManager.AppSettings.Get("ServerActiveDirectory");
            var usuarioLogin     = ConfigurationManager.AppSettings.Get("usuarioActiveDirectory");
            var contraseniaLogin = ConfigurationManager.AppSettings.Get("contraseniaActiveDirectory");

            DirectoryEntry directoryEntry = null;

            if (!String.IsNullOrEmpty(usuarioLogin) && !String.IsNullOrEmpty(contraseniaLogin))
            {
                directoryEntry                    = new DirectoryEntry(server);
                directoryEntry.Username           = usuarioLogin;
                directoryEntry.Password           = contraseniaLogin;
                directoryEntry.AuthenticationType = AuthenticationTypes.Secure;

                var directorySearcher = new DirectorySearcher(directoryEntry);
                directorySearcher.Filter = String.Format("(&(objectClass=user)(SAMAccountName={0}))", usuario);

                SearchResult srResult = directorySearcher.FindOne();

                if (srResult != null)
                {
                    DirectoryEntry deUser = srResult.GetDirectoryEntry();
                    deUser.Username           = usuario;
                    deUser.Password           = contrasenia;
                    deUser.AuthenticationType = AuthenticationTypes.Secure;

                    try
                    {
                        var userSearcher = new DirectorySearcher(deUser);
                        userSearcher.SearchScope = SearchScope.Base;
                        SearchResult resEnt = userSearcher.FindOne();
                        resultadoValidacion.Resultado = true;
                    }
                    catch (Exception ex)
                    {
                        resultadoValidacion.Resultado = false;
                        resultadoValidacion.Mensaje   = ex.Message;
                    }
                    finally
                    {
                        deUser.Dispose();
                    }
                }
                else
                {
                    resultadoValidacion.Resultado = false;
                    resultadoValidacion.Mensaje   = "MENSAJE_WARNING_USUARIO_NO_ENCONTRADO";
                }
            }
            else
            {
                directoryEntry          = new DirectoryEntry(server);
                directoryEntry.Username = usuario;
                directoryEntry.Password = contrasenia;

                var directorySearcher = new DirectorySearcher(directoryEntry);
                directorySearcher.SearchScope = SearchScope.Base;

                try
                {
                    SearchResult resEnt = directorySearcher.FindOne();
                    resultadoValidacion.Resultado = true;
                }
                catch (Exception e)
                {
                    resultadoValidacion.Resultado = false;
                    resultadoValidacion.Mensaje   = "MENSAJE_WARNING_USUARIO_NO_ENCONTRADO";
                    Util.LogUtil.Error(e);
                }
            }


            return(resultadoValidacion);
        }
Example #50
0
        static public string getDomainuser(String user)
        {
            DirectorySearcher USER_SEARCH = getUserSearcher();

            return(getDomainuser(user, USER_SEARCH));
        }
Example #51
0
        /// <summary>
        /// Returns user information in active directory
        /// </summary>
        /// <param name="employeeNumber">employeeNumber</param>
        /// <param name="user">user</param>
        /// <returns></returns>
        public Response GetUserInformation(string employeeNumber, out User user)
        {
            var response = new Response()
            {
                Message = "Not initializated.", Result = false
            };

            user = null;
            try
            {
                var pathLDap = _LDapConnectionString;

                var entry = new DirectoryEntry(pathLDap);
                // Bind to the native AdsObject to force authentication.
                var obj    = entry.NativeObject;
                var search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + employeeNumber + ")";



                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("givenname");
                search.PropertiesToLoad.Add("sn");
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("EmployeeId");
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    response.Message = string.Format("Usuario no pudo ser encontrado en directorio activo.");
                    response.Result  = false;
                    user             = null;
                    return(response);
                }
                user = new User()
                {
                    EmployeeNames      = GetProperty(result, "givenName"),
                    EmployeeLastName   = GetProperty(result, "sn"),
                    EmployeeEmail      = GetProperty(result, "mail"),
                    AuthenticationType = AuthenticationTypeEnum.ActiveDirectoryOnly
                };

                if (string.IsNullOrEmpty(user.EmployeeNames))
                {
                    response.Message = string.Format("No ha sido capturado el nombre del usuario en Directorio Activo ");
                    response.Result  = false;
                    user             = null;
                    return(response);
                }
                if (string.IsNullOrEmpty(user.EmployeeLastName))
                {
                    response.Message = string.Format("No ha sido capturado el apellido del usuario en Directorio Activo. ");
                    response.Result  = false;
                    user             = null;
                    return(response);
                }
                if (string.IsNullOrEmpty(user.EmployeeEmail))
                {
                    response.Message = string.Format("No ha sido capturado el correo electronico del usuario en Directorio Activo.");
                    response.Result  = false;
                    user             = null;
                    return(response);
                }

                response.Message = string.Format("Se encontró el usuario {0} en directorio activo.", employeeNumber);
                response.Result  = true;
            }
            catch (Exception exception)
            {
                response.Message =
                    string.Format("Ocurrio un error al consultar información de usuario en Directorio Activo. {0}", exception.Message);
                response.Result = false;
                user            = null;
            }
            return(response);
        }
Example #52
0
        static void Main(string[] args)
        {
            #region Read Configurations from AppSettings
            // Please update the App.config for the required app settings
            var databricksUri   = ConfigurationManager.AppSettings["DATABRICKS_URI"];
            var databricksToken = ConfigurationManager.AppSettings["DATABRICKS_TOKEN"];
            var msadLDAPUri     = ConfigurationManager.AppSettings["MSAD_LDAP_URI"];
            // Security Group that members need sync with Databricks Workspace
            var msadSGDN = ConfigurationManager.AppSettings["MSAD_SECURITY_GROUP_DN"];
            // Additional Permission validation Security Group
            var msadPermissionSGDN = ConfigurationManager.AppSettings["MSAD_PERMISSION_SECURITY_GROUP_DN"];

            // Please update the App.config to enable/disable Remove or Add
            var enableRemove = ConfigurationManager.AppSettings["ENABLE_REMOVE"];
            enableRemove = enableRemove.Trim().ToUpper();
            var enableAdd = ConfigurationManager.AppSettings["ENABLE_ADD"];
            enableAdd = enableAdd.Trim().ToUpper();
            #endregion

            #region Primary Logic Blocks
            Console.WriteLine("Execution Start for SG {0}", msadSGDN);
            int exitCode       = 0;
            int addedCounter   = 0;
            int removedCounter = 0;

            Dictionary <string, string> databricksAccounts    = new Dictionary <string, string>();
            Dictionary <string, string> securityGroupAccounts = new Dictionary <string, string>();

            Dictionary <string, string> needRemoveAccounts = new Dictionary <string, string>();
            List <string> needAddAccounts = new List <string>();

            try
            {
                // Init LDAP Directory Root
                var directoryRoot = new DirectoryEntry(msadLDAPUri);
                directoryRoot.AuthenticationType = AuthenticationTypes.Secure
                                                   | AuthenticationTypes.SecureSocketsLayer;

                // Search SG's Members
                var sGSearcher = new DirectorySearcher(directoryRoot, string.Format("(distinguishedName={0})", msadSGDN));
                sGSearcher.ReferralChasing = ReferralChasingOption.All;
                sGSearcher.PropertiesToLoad.AddRange(new[] { "member", "member;range=0-1499" });
                sGSearcher.SizeLimit = 1;

                var sGSearchResult = sGSearcher.FindOne();
                if (sGSearchResult != null)
                {
                    var sGEntry = sGSearchResult.GetDirectoryEntry();

                    var sGMemberList      = sGEntry.ReadPropertiesOrDefault <string>("member");
                    var sGMemberExtraList = sGEntry.ReadPropertiesOrDefault <string>("member;range=0-1499");

                    var allMembers = sGMemberList.Union(sGMemberExtraList);
                    foreach (var sGMember in allMembers)
                    {
                        Console.WriteLine("Search {0}'s memberOf info.", sGMember);

                        // Search current Memeber's MemberOf info
                        var sGMemberSearcher = new DirectorySearcher(directoryRoot, string.Format("(distinguishedName={0})", sGMember));
                        sGMemberSearcher.ReferralChasing = ReferralChasingOption.All;
                        sGMemberSearcher.PropertiesToLoad.AddRange(new[] { "memberOf", "userPrincipalName", "userAccountControl" });
                        sGMemberSearcher.SizeLimit = 1;

                        var sGMemberSearchResult = sGMemberSearcher.FindOne();
                        if (sGMemberSearchResult != null)
                        {
                            var sGMemberEntry = sGMemberSearchResult.GetDirectoryEntry();

                            var sGMemberUserAccoutControl = sGMemberEntry.ReadPropertyOrDefault <int>("userAccountControl", -1);
                            var sGMemberMemberOf          = sGMemberEntry.ReadPropertiesOrDefault <string>("memberOf");
                            var sGMemberUserPrincipalName = sGMemberEntry.ReadPropertyOrDefault <string>("userPrincipalName", string.Empty);

                            if (string.IsNullOrWhiteSpace(sGMemberUserPrincipalName))
                            {
                                Console.WriteLine("Fail to found userPrincipalName !!!");
                            }
                            else
                            {
                                Console.WriteLine("Processing {0}", sGMemberUserPrincipalName);

                                if (sGMemberUserAccoutControl != -1)
                                {
                                    if ((sGMemberUserAccoutControl & UserAccountControl.NORMAL_ACCOUNT) == UserAccountControl.NORMAL_ACCOUNT)         // Check if it is normal account
                                    {
                                        if (sGMemberMemberOf.Any(row => string.Compare(row, msadPermissionSGDN, true) == 0))                          // Check if belongs to permission SG
                                        {
                                            if ((sGMemberUserAccoutControl & UserAccountControl.ACCOUNTDISABLE) == UserAccountControl.ACCOUNTDISABLE) // Disabled account
                                            {
                                                /*
                                                 * Some AD environment may contains mapped accounts that all permission mamanged by one disabled account but user uses its mapped account for login
                                                 * E.g. [email protected] --> [email protected], tom uses [email protected] to login but most of his permission managed by [email protected] (Marked as Disabled in AD) in AD.
                                                 */
                                                Console.WriteLine("Account been disabled, you may need search for mapped account in different domain !!!");
                                            }
                                            else
                                            {
                                                securityGroupAccounts.Add(sGMember, sGMemberUserPrincipalName);
                                                Console.WriteLine("Found {0} - {1} from member", sGMemberUserPrincipalName, sGMember);
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine("Not member of permission SG !!!");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("UserAccountControl {0} indicate not NORMAL_ACCOUNT !!!", sGMemberUserAccoutControl);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Faile to found the userAccountControl flag !!!");
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("Fail to found !!!");
                        }
                    }
                }

                DatabricksClientOps.GetOrCreate(databricksUri, databricksToken);
                var databricksUsers = ScimOps.GetUsers();

                foreach (var databricksUser in databricksUsers.Resources)
                {
                    Console.WriteLine("Check existing account {0}", databricksUser.userName);

                    var accountInSecurityGroupSearchResults = securityGroupAccounts.Where(row => string.Compare(row.Value, databricksUser.userName, true) == 0);

                    if (accountInSecurityGroupSearchResults.Count() == 1)
                    {
                        databricksAccounts.Add(accountInSecurityGroupSearchResults.First().Key, databricksUser.userName);
                        Console.WriteLine("Keep Account");
                    }
                    else
                    {
                        needRemoveAccounts.Add(databricksUser.userName, databricksUser.id);
                        Console.WriteLine("Need Remove Account");
                    }
                }

                foreach (var securityGroupAccount in securityGroupAccounts)
                {
                    if (!databricksAccounts.ContainsKey(securityGroupAccount.Key))
                    {
                        needAddAccounts.Add(securityGroupAccount.Value);
                        Console.WriteLine("Need Add {0}", securityGroupAccount.Value);
                    }
                }

                foreach (var needAddAccount in needAddAccounts)
                {
                    if (enableAdd == "TRUE")
                    {
                        var targetUser = ScimOps.CreateUser(new CreateUserRequest()
                        {
                            schemas = new List <string>()
                            {
                                ScimOps.SCHEMA_SCIM_2_0_USER
                            },
                            userName = needAddAccount
                        });
                        Console.WriteLine("{0} added as id {1}", needAddAccount, targetUser.id);
                        addedCounter++;
                    }
                    else
                    {
                        Console.WriteLine("{0} add skipped");
                    }
                }

                foreach (var needRemoveAccount in needRemoveAccounts)
                {
                    if (enableRemove == "TRUE")
                    {
                        ScimOps.DeleteUserById(needRemoveAccount.Value);
                        Console.WriteLine("{0} removed as id {1}", needRemoveAccount.Key, needRemoveAccount.Value);

                        removedCounter++;
                    }
                    else
                    {
                        Console.WriteLine("{0} remove skipped", needRemoveAccount.Key);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                exitCode = -1;
            }


            Console.WriteLine("Final Exit Code {0}", exitCode);
            Environment.Exit(exitCode);
            #endregion
        }
Example #53
0
    /*private static string getOsName()
        {
            var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
                        select x.GetPropertyValue("Caption")).FirstOrDefault();
            return name != null ? name.ToString() : "Unknown";
        }*/
    protected void Page_Load(object sender, EventArgs e)
    {
        //Lokaalin käyttäjän käyttäjänimi.
            string userAccountName = User.Identity.Name.ToString().Substring(8);

            //Lokaalin tietokoneen nimi
            string[] computer_name = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName.Split(new Char[] { '.' });
            String ecn = System.Environment.MachineName;
            _computerName = computer_name[0].ToString();

            //Hakee AD:sta tarvittavat tiedot käyttäjälle
            using (DirectoryEntry de = new DirectoryEntry("LDAP://adturku.fi"))
            {
                using (DirectorySearcher adSearch = new DirectorySearcher(de))
                {
                    adSearch.PropertiesToLoad.Add("cn");  // Kokonimi
                    adSearch.PropertiesToLoad.Add("mail");  // Sähköposti
                    adSearch.PropertiesToLoad.Add("telephoneNumber");  // Puhelinnumero
                    adSearch.PropertiesToLoad.Add("Company");  // Toimiala
                    adSearch.PropertiesToLoad.Add("Department");  // Yksikkö
                    adSearch.PropertiesToLoad.Add("streetaddress");  // Toimipiste
                    //adSearch.PropertiesToLoad.Add("City");  // kaupunki
                    adSearch.Filter = "(sAMAccountName="+ userAccountName+")"; //haku käyttäjänimellä
                    SearchResult adSearchResult = adSearch.FindOne();
                    var searchPropCollection = adSearchResult.Properties;
                    string[] info = new string[15];
                    int infoRivi = 0;
                    //Noutaa AD-haun tulokset ja sijoittaa ne tietyille paikoilleen tulostaulukkoon (_userInfoAD). Skippaa adspathin, jota ei tässä tarvita.
                    foreach (string tulos in searchPropCollection.PropertyNames)
                    {
                        if (tulos.Equals("cn"))
                        {
                            infoRivi = 0;
                        }
                        if (tulos.Equals("mail"))
                        {
                            infoRivi = 1;
                        }
                        if (tulos.Equals("telephonenumber"))
                        {
                            infoRivi = 2;
                        }
                        if (tulos.Equals("company"))
                        {
                            infoRivi = 3;
                        }
                        if (tulos.Equals("department"))
                        {
                            infoRivi = 4;
                        }
                        if (tulos.Equals("streetaddress"))
                        {
                            infoRivi = 5;
                        }
                        if (tulos.Equals("adspath"))
                        {
                            continue;
                        }

                        foreach (Object myCollection in searchPropCollection[tulos])
                        {
                            info[infoRivi] = myCollection.ToString();
                        }
                    }
                    _userInfoAD = info;
                }
            }

            //Asetetaan käyttäjän sähköposti täältä koodin puolelta paikalleen, koska emailin lähetyksessä käytetään
            //asp net tekstikenttää, joka saattaa saada uuden arvon lomaketta täytettäessä
            sähköposti.Text = userEmail;
            //Muuttaan dropdown-listan testiosoite käyttäjän omaksi emailiksi
            testiosoite.Value = userEmail;
    }
Example #54
0
        internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet)
        {
            // Get domain directory entry and reset the password on the machine account of the local machine
            string newPassword = null;
            string domainOrServerName = server ?? domain;

            try
            {
                string dUserName = credential != null ? credential.UserName : null;
                string dPassword = credential != null ? Utils.GetStringFromSecureString(credential.Password) : null;

                using (var domainEntry = new DirectoryEntry(
                       "LDAP://" + domainOrServerName,
                       dUserName,
                       dPassword,
                       AuthenticationTypes.Secure))
                {
                    using (var searcher = new DirectorySearcher(domainEntry))
                    {
                        searcher.Filter = "(&(objectClass=computer)(|(cn=" + localMachineName + ")(dn=" + localMachineName + ")))";
                        SearchResult result = searcher.FindOne();

                        if (result == null)
                        {
                            string format = server != null
                                                ? ComputerResources.CannotFindMachineAccountFromServer
                                                : ComputerResources.CannotFindMachineAccountFromDomain;
                            string errMsg = StringUtil.Format(format, domainOrServerName);
                            ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "CannotFindMachineAccount",
                                                                ErrorCategory.OperationStopped, localMachineName);
                            cmdlet.ThrowTerminatingError(error);
                        }
                        else
                        {
                            // Generate a random password of length 120, and reset the password on the machine account
                            using (var targetEntry = result.GetDirectoryEntry())
                            {
                                newPassword = ComputerWMIHelper.GetRandomPassword(PasswordLength);
                                targetEntry.Invoke("SetPassword", new object[] { newPassword });
                                targetEntry.Properties["LockOutTime"].Value = 0;
                            }
                        }
                    }
                }
            }
            catch (DirectoryServicesCOMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (TargetInvocationException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.InnerException.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }
            catch (COMException ex)
            {
                string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message);
                ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain",
                                                    ErrorCategory.OperationStopped, localMachineName);
                cmdlet.ThrowTerminatingError(error);
            }

            // Set the same password to the local machine
            Dbg.Diagnostics.Assert(newPassword != null, "the newPassword should not be null at this point");

            // A direct translation of function NetpManageMachineSecret2 in //depot/winmain/ds/netapi/netjoin/joinutl.c
            // Initialize the LSA_OBJECT_ATTRIBUTES
            var lsaAttr = new SAMAPI.LSA_OBJECT_ATTRIBUTES();
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES));

            // Initialize the policy handle and secret handle
            IntPtr policyHandle = IntPtr.Zero;
            IntPtr secretHandle = IntPtr.Zero;

            // Initialize variables for LsaQuerySecret call
            IntPtr currentPassword = IntPtr.Zero;

            // Declare the key, newData and currentData
            var key = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };
            var newData = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero };

            // Initialize the systemName for the localhost
            var localhost = new SAMAPI.LSA_UNICODE_STRING();
            localhost.Buffer = IntPtr.Zero;
            localhost.Length = 0;
            localhost.MaximumLength = 0;

            try
            {
                // Open the LSA policy
                uint ret = SAMAPI.LsaOpenPolicy(ref localhost, ref lsaAttr, (int)SAMAPI.LSA_ACCESS.AllAccess, out policyHandle);
                if (ret == STATUS_ACCESS_DENIED)
                {
                    string errMsg = ComputerResources.NeedAdminPrivilegeToResetPassword;
                    ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "UnauthorizedAccessException",
                                                        ErrorCategory.InvalidOperation, localMachineName);
                    cmdlet.ThrowTerminatingError(error);
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                // Initialize secret key, new secret
                SAMAPI.InitLsaString(SecretKey, ref key);
                SAMAPI.InitLsaString(newPassword, ref newData);
                bool secretCreated = false;

                // Open the secret. If the secret is not found, create the secret
                ret = SAMAPI.LsaOpenSecret(policyHandle, ref key, SECRET_SET_VALUE | SECRET_QUERY_VALUE, out secretHandle);
                if (ret == STATUS_OBJECT_NAME_NOT_FOUND)
                {
                    ret = SAMAPI.LsaCreateSecret(policyHandle, ref key, SECRET_SET_VALUE, out secretHandle);
                    secretCreated = true;
                }
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }

                SAMAPI.LSA_UNICODE_STRING currentData;
                // Get the current password
                if (secretCreated)
                {
                    // Use the new password as the current one
                    currentData = newData;
                }
                else
                {
                    // Query for the current password
                    ret = SAMAPI.LsaQuerySecret(secretHandle, out currentPassword, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                    if (ret != 0)
                    {
                        ThrowOutLsaError(ret, cmdlet);
                    }

                    currentData = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(currentPassword, typeof(SAMAPI.LSA_UNICODE_STRING));
                }

                ret = SAMAPI.LsaSetSecret(secretHandle, ref newData, ref currentData);
                if (ret != 0)
                {
                    ThrowOutLsaError(ret, cmdlet);
                }
            }
            finally
            {
                // Release pointers
                if (currentPassword != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaFreeMemory(currentPassword);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaFreeMemory returned non-zero value");
                }

                // Release handles
                if (policyHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(policyHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                if (secretHandle != IntPtr.Zero)
                {
                    int releaseResult = SAMAPI.LsaClose(secretHandle);
                    Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value");
                }

                // Release LSA_UNICODE_STRING
                SAMAPI.FreeLsaString(ref key);
                SAMAPI.FreeLsaString(ref newData);
            }
        }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        DirectoryEntry myDirectoryEntry = new DirectoryEntry(String.Format("LDAP://{0}", "Progressive.com"));
                    DirectorySearcher mySearcher = new DirectorySearcher(myDirectoryEntry);

                    mySearcher.Filter = ("(objectCategory=person)");

                    foreach (SearchResult result in mySearcher.FindAll())
                    {

                        try
                        {
                            if (!String.IsNullOrEmpty(result.Properties["Mail"][0].ToString())
                                && System.Text.RegularExpressions.Regex.IsMatch(result.Properties["DisplayName"][0].ToString(), " |admin|test|service|system|[$]", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                                )
                                {
                                    //int space = resEnt.Properties["DisplayName"][0].ToString().IndexOf(" ");
                                    //string formattedName = String.Format("{0}{1}{2}",
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(space).PadRight(25),
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(0, space).PadRight(15),
                                    //    resEnt.Properties["Mail"][0].ToString()
                                    //    );
                                    //userList.Add(formattedName);
                                    string SAMAccountName = Convert.ToBoolean(result.Properties["sAMAccountName"].Count > 0) ? result.Properties["sAMAccountName"][0].ToString() : "";
                                    string DisplayName = Convert.ToBoolean(result.Properties["displayName"].Count > 0) ? result.Properties["displayName"][0].ToString() : "";
                                    string mail = Convert.ToBoolean(result.Properties["mail"].Count > 0) ? result.Properties["mail"][0].ToString() : "";
                                    string company = Convert.ToBoolean(result.Properties["company"].Count > 0) ? result.Properties["company"][0].ToString() : "";
                                    string department = Convert.ToBoolean(result.Properties["UserFlags"].Count > 0) ? result.Properties["UserFlags"][0].ToString() : "";
                                    Response.Write(SAMAccountName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(DisplayName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(mail);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(company);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(department);
                                    Response.Write("<br>");
                                }

                        }
                        catch
                        {

                        }

                    }
                    //if (userList.Count > 0)
                    //{

                    //    for (int i = 0; i < userList.Count - 1; i++)
                    //    {
                    //        Response.Write((userList[i].ToString()));
                    //        Response.Write("<br>");

                    //    }

                    //}
    }
Example #56
-1
    protected void f_real()
    {
        //LDAP验证
        string strPath = "LDAP://147.128.18.10";
        DirectoryEntry de;
        de = new DirectoryEntry(strPath, txtUserName.Text, txtPWD.Text.Trim(), AuthenticationTypes.None);
        DirectorySearcher deSearch = new DirectorySearcher();
        deSearch.SearchRoot = de;

        //验证LDAP用户名和密码
        if (VerifyUser(deSearch))
        {
            DataTable dtuser ;
            string sql = "select * from t_users where c_login='******'and c_system='" + du_tools.gcs_sytem + "'";
            try
            {
                dtuser = SQLHelper.GetDataTable(sql);
                if (dtuser.Rows.Count > 0)
                {
                    Session["user_login"] = txtUserName.Text;
                    DeleteOverdueFile();
                    Response.Redirect("default.aspx");
                }
                else
                {
                    JScript.AjaxAlert(this.Page, "User Not Exits!");
                    return;
                }
            }
            catch (Exception ex)
            {
                JScript.AjaxAlert(this.Page, "There is something wrong" + ex.Message.Replace("\\", "/").Replace("\'", " "));
                return;
            }
        }
        else
        {
            JScript.AjaxAlert(this.Page, "LDAP failed!");
        }
    }
Example #57
-1
    public static void clr_GetADobjects(SqlString ADpath, SqlString ADfilter, out SqlXml MemberList)
    {
        // Filter syntax: https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
        // AD attributes: https://msdn.microsoft.com/en-us/library/ms675089(v=vs.85).aspx

        MemberList = new SqlXml();

        //System.IO.StreamWriter file = Util.CreateLogFile();

        SearchResultCollection results = null;
        Int32 itemcount = 0;
        try
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(xmlDeclaration, root);
            XmlElement body = doc.CreateElement(string.Empty, "body", string.Empty);
            doc.AppendChild(body);

            ADcolsTable TblData = new ADcolsTable((string)ADfilter);
            DataTable tbl = TblData.CreateTable();
            DataRow row;

            // Create key/value collection - key is (user) distinguishedname, value is object GUID.
            Dictionary<string, Guid> UserDStoGUID = new Dictionary<string, Guid>();

            DirectoryEntry entry = new DirectoryEntry((string)ADpath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = (string)ADfilter;
            searcher.PageSize = 500;

            results = searcher.FindAll();
            foreach (SearchResult searchResult in results)
            {
                itemcount++;
                DirectoryEntry item = searchResult.GetDirectoryEntry();
                row = tbl.NewRow();

                UACflags Item_UAC_flags = null;
                Int64 UserPasswordExpiryTimeComputed = 0;
                PropertyValueCollection ADGroupType = null;

                for (int i = 0; i < TblData.collist.Length; i++)
                {
                    TableColDef coldef = TblData.collist[i];
                    switch(coldef.OPtype)
                    {
                        case "Adprop":
                            if (coldef.ADpropName == "useraccountcontrol" && Item_UAC_flags != null)
                            {
                                row[i] = Item_UAC_flags.ADobj_flags;
                                break;
                            }
                            PropertyValueCollection prop = Util.GetADproperty(item, coldef.ADpropName);
                            if (prop != null)
                                row[i] = prop.Value;
                            break;

                        case "UAC":
                            if (Item_UAC_flags == null)
                            {   // Get UAC flags only once per AD object.
                                Item_UAC_flags = new UACflags(Util.Get_userAccountControl(item, out UserPasswordExpiryTimeComputed));
                            }
                            row[i] = Item_UAC_flags.GetFlag(coldef.ADpropName);
                            break;

                        case "ObjClass":
                            row[i] = item.SchemaClassName;
                            break;

                        case "ObjGuid":
                            row[i] = item.Guid;
                            break;

                        case "filetime":
                            Int64 time = 0;
                            if (coldef.ADpropName == "msDS-UserPasswordExpiryTimeComputed")
                                time = UserPasswordExpiryTimeComputed;
                            else
                                time = Util.GetFileTime(searchResult, coldef.ADpropName);
                            if(time > 0 && time != 0x7fffffffffffffff && time != -1)
                            {
                                //row[i] = DateTime.FromFileTimeUtc(time);
                                row[i] = DateTime.FromFileTime(time);       // Convert UTC to local time.
                            }
                            break;

                        case "SID":
                            row[i] = Util.GetSID(item, coldef.ADpropName);
                            break;

                        case "GrpCat":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupCategory(ADGroupType);
                            break;

                        case "GrpScope":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupScope(ADGroupType);
                            break;
                    }
                }
                tbl.Rows.Add(row);

                if (TblData.IsUser)
                {
                    // Set UserMustChangePasswordAtNextLogon column value (for user objects).
                    bool IsUsrChgPwd = false;
                    if (row.IsNull("PasswordLastSet")
                        && !row.IsNull("PasswordNeverExpires")
                        && !row.IsNull("PasswordNotRequired")
                        && !(bool)row["PasswordNeverExpires"]
                        && !(bool)row["PasswordNotRequired"])
                    {
                        IsUsrChgPwd = true;
                    }
                    row["UserMustChangePasswordAtNextLogon"] = IsUsrChgPwd;

                    // Collect user distinguishedname into dictionary, value is object GUID.
                    // This is needed later to set ManagerGUID column.
                    UserDStoGUID.Add((string)row["distinguishedname"], (Guid)row["ObjectGUID"]);
                }

                // Save group members into the Xml document.
                if (TblData.IsGroup && item.Properties.Contains("member"))
                {
                    PropertyValueCollection coll = Util.GetADproperty(item, "member");
                    string parent = (string)row["distinguishedname"];
                    Util.SaveGroupMembersToXml(doc, body, parent, coll);
                }
            }   // endof: foreach (SearchResult searchResult in results)
            // All rows have been added to the dataset.

            // set ManagerGUID column for user objects.
            if (TblData.IsUser)
            {
                foreach (DataRow rowUsr in tbl.Rows)
                {
                    object manager = rowUsr["Manager"]; // distinguishedname of Manager.
                    if (manager == DBNull.Value)
                        continue;
                    Guid ManagerGUID;
                    if (UserDStoGUID.TryGetValue((string)manager, out ManagerGUID))
                        rowUsr["ManagerGUID"] = ManagerGUID;
                }
            }

            // Return dataset to SQL server.
            ReturnDatasetToSqlServer(tbl);

            using (XmlNodeReader xnr = new XmlNodeReader(doc))
            {
                MemberList = new SqlXml(xnr);
            }
        }
        catch (System.Runtime.InteropServices.COMException)
        {
            SqlContext.Pipe.Send("COMException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (InvalidOperationException)
        {
            SqlContext.Pipe.Send("InvalidOperationException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (NotSupportedException)
        {
            SqlContext.Pipe.Send("NotSupportedException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (Exception)
        {
            SqlContext.Pipe.Send("Exception in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        finally
        {
            if (null != results)
            {
                results.Dispose();  // To prevent memory leaks, always call
                results = null;     // SearchResultCollection.Dispose() manually.
            }
        }
        //file.Close();
    }