Home > Articles > Programming > Windows Programming

This chapter is from the book

Managing Passwords for Active Directory Users

Unlike most Active Directory and ADAM user-management tasks, which we perform through simple manipulation of Active Directory objects and attributes via LDAP, managing passwords is a bit complex. Password changes require very special semantics that are enforced by the server, and developers need to understand these semantics for password management applications to be successful.

In order to try to facilitate the password management process, ADSI exposes two methods on the IADsUser interface: SetPassword and ChangePassword. SetPassword is used to perform an administrative reset of a user’s password and is typically performed by an administrator. Knowledge of the previous password is not required. ChangePassword is used simply to change the password from one value to another and is typically performed only by the user represented by the directory object. It does require knowledge of the previous password, and thus it takes the old and new passwords as arguments.

Since the DirectoryEntry object does not directly expose the IADsUser ADSI interface, this is one case where we must use the DirectoryEntry.Invoke method to call these ADSI methods via late-bound reflection:

//given a DirectoryEntry "entry" that points to a user object
//this will reset the user’s password
entry.Invoke("SetPassword", new object[] {"newpassword"});

//this will change the user’s password
  new object[] {"oldpassword", "newpassword"});

Note that the parameters to the SetPassword and ChangePassword methods are passed in as an array of objects that contain strings.

Password Management Complications

This seems simple enough; just call the right method and pass in the right arguments. Unfortunately, in practice this turns out not to be the case, as password management functions tend to be the most troublesome aspect of programmatic user management beyond the normal issues related to security that we discussed in Chapter 8.

Password management can be hard, for a variety of reasons.

  • Password policy and security can be complicated and must be understood.
  • The underlying ADSI methods actually try a complicated series of different approaches to set or change the password, and all of them use different protocols and have different requirements and failure modes.
  • The errors returned by ADSI are often not helpful and the resulting exception in .NET needs other special care.

Developers who have issues reliably using SetPassword and ChangePassword in all environments are unfortunately not in the minority. However, the following exploration of these three points will be immensely helpful.

Understanding Password Policy and Security

Active Directory enforces password policy at the domain level. Password policies that can be set include:

  • The minimum allowed length
  • The maximum allowed age
  • The minimum allowed age (how often we can change passwords)
  • Password complexity
  • Password history (determines when we can reuse an old password)

Complex passwords are just passwords that require some mix of upper- and lowercase letters, numbers, and special characters. All of these policies are exposed via attributes set in the domain root object, which can easily be found via the defaultNamingContext attribute on RootDSE. We discussed how to find these domain-wide policy settings earlier in this chapter.

Knowing what these values are will help us predict how the server will behave when asked to modify any given password. All of the policies that are enabled are enforced for each password modification; however, administrative password resets (as opposed to end-user password changes) ignore all of them except for length and complexity. This makes sense, since an administrator who (presumably) has no knowledge of the user’s previous passwords performs the reset.

Password security is relatively straightforward. Essentially, administrative users have rights to reset any account’s password, and normal users have rights to change only their own passwords. The only trick here is that the right to reset passwords can be delegated beyond the scope of the default groups, such as Domain Admins and Account Operators, so it is possible that users outside of those groups have this right.

From the application developer’s perspective, our job is to know which of the two tasks we are trying to perform and to make sure that we have the correct credentials to do so. This is pretty easy when building applications to change passwords, as the user has to give us her old password to make the change, so it is relatively easy to bind to the directory with her credentials directly and avoid any tricky impersonation scenarios (see Chapter 8). For password reset operations, our options can equally vary between using the current user’s security context (if it’s an admin application), to using a trusted service account (this is often done with helpdesk-type applications). There is not a clear-cut answer of which method to use here, and it will often depend on the type of application we are trying to build. Chapter 8 explains these scenarios in detail, especially for web applications.

Understanding the Underlying ADSI Methods

The SetPassword and ChangePassword methods may seem simple on the outside, but under the hood, it is just the opposite. There is a variety of different ways to modify passwords against Active Directory, and these methods pretty much try all of them. On the one hand, this is great for developers, as this approach gives developers the best possible chance that their operation will succeed. The downside of this approach is that each technique has different requirements and different ways to fail, so figuring out why things are not working can be especially difficult.

SetPassword and ChangePassword attempt password modifications using the following methods, in order:

  • LDAP password modification over an SSL channel
  • The Kerberos set password protocol over the Kerberos password port (SetPassword only)
  • A Net* API remote procedure call (RPC)

As noted in the list, the Kerberos set password protocol is used only for SetPassword. ChangePassword does not seem to have an equivalent Kerberos protocol implementation. Let’s take each technique in turn.

LDAP Password Modification

The first technique that is always attempted is an LDAP-based password modification. The core of this technique involves modifying the unicodePwd attribute directly. SetPassword does one modification with the Replace modification type specified, and ChangePassword does two modifications with a Delete and an Add specified, in that order. Active Directory enforces a restriction that any modification to the unicodePwd attribute must be made over an encrypted channel with a cipher strength of 128 bits. Otherwise, the server will reject the attempted modification. This helps ensure that the plaintext password is not intercepted on the network.

This is where SSL comes in. If we recall from Chapter 3, Active Directory supports two mechanisms for channel encryption: SSL and Kerberos. However, only SSL supports the minimum 128-bit cipher strength on all Active Directory platforms. Kerberos-based encryption has been strengthened to meet this requirement on Windows Server 2003, but not on Windows 2000 Server. Because the function attempts to work with either version of Active Directory, it always selects only SSL for the channel encryption technique.

This is unfortunate, because Kerberos-based encryption works out of the box with Active Directory, but SSL requires additional configuration steps including the acquisition of proper SSL certificates for each participating domain controller. Since SSL/LDAP is not required for normal Active Directory operation, many administrators do not bother to configure it. As a result, SSL is often not available for performing password modifications with SetPassword and ChangePassword.

Additionally, for an SSL/LDAP bind to succeed, proper DNS names must be used to connect to the domain controller. Typically, the server authentication aspect of the SSL handshake requires that the name used to access the server match the name of the server in the certificate, which is typically a DNS name. Therefore, it is important to remember to avoid using IP addresses and NetBIOS names when accessing a domain controller if SSL support is required.

A final thing to remember is that SSL/LDAP uses TCP port 636, not port 389, like typical LDAP traffic does. We must take this into account with any network firewall restrictions to make sure the proper ports are open.

Kerberos Set Password Protocol

The Kerberos specification includes a facility for setting user passwords. This facility does not use the original user’s password, so it is used only for administrative resets (SetPassword) and not for end-user password changes using ChangePassword.

The Kerberos set password protocol also uses a different network port (TCP 441) than normal Kerberos traffic, which goes over port 88 UDP and TCP. Once again, we must consider potential firewall issues if we wish to use this protocol.

Kerberos set password is available when a secure bind was requested and the secure bind negotiates to Kerberos rather than to NTLM. Chapter 8 contains more information about this, including some sample code we can use to verify secure bind status on the server side.


The final method attempted by the password modification methods are one of two RPC functions from the Net* family: NetUserSetInfo and NetUserChangePassword. They are used for SetPassword and ChangePassword, respectively.

The key thing to remember with these RPC functions is that they must use the current thread’s security context. They do not directly support plaintext credentials to establish a security context, as LDAP does. With Windows 2000, this had the surprising effect of ignoring any credentials supplied to DirectoryEntry for SetPassword privileges. Developers found that if they switched environmental factors, identical code that previously worked would fail. There was also no way to know which of the three methods was being selected. So, if the test environment had SSL certificates installed correctly, SetPassword and ChangePassword would work just fine. Moving the identical code to production, where perhaps the SSL certificate was not installed correctly, would fail because unbeknownst to the developer, SetPassword had actually used NetUserSetInfo under the covers. This violated most developers’ idea of obvious behavior. After all, if the previous two methods can use the credentials supplied to DirectoryEntry to affect password modifications with identical code, why wouldn’t this one? Microsoft decided to fix this unexpected behavior with Windows 2003. Now, if the code specifies plaintext credentials in DirectoryEntry, these methods will use another API, LogonUser, to create a Windows login token for the code to impersonate while making the RPC function call. This has the effect of keeping the outward behavior of all three methods the same.

For Windows 2000 users, the only way to get this third method working correctly is to make sure our current thread’s credentials are those of an account that has the proper privileges. From Chapter 8, we know this means that either our code must run under a trusted subsystem that holds these rights, or we must impersonate an account that holds these rights for the duration of the call. Please refer back to Chapter 8 for more details, and for additional references.

Finally, remember that a Windows RPC requires TCP port 135 (and potentially, other ports) to be open to the domain controller.

Error Handling with the Invoke Method in .NET

So far, all of the issues we have discussed apply to any API that calls SetPassword or ChangePassword. While error handling for these two methods is certainly relevant, it is a larger .NET topic that affects any code that uses reflection via the Invoke method. When the Invoke method is used to call any ADSI interface method, any exception thrown by the target method, including a COM error triggered via COM interop, will be wrapped in a System.Reflection.TargetInvocationException exception, with the actual exception in the InnerException property. Therefore, we will need to use a pattern like this with the Invoke method:

//given a DirectoryEntry "entry" that points to a user object
//this will reset the user’s password
  entry.Invoke("SetPassword", new object[]
catch (TargetInvocationException ex)
  throw ex.InnerException;

Obviously, we may wish to do something different from simply rethrowing the InnerException property. The point here is that InnerException contains the information we are interested in.

The other issue here is that the exceptions coming back from ADSI vary, from the vaguely helpful to the truly bewildering. We will not attempt to list all of them here, but here are a few hints.

  • System.UnauthorizedAccessException always indicates a permissions problem.
  • A System.Runtime.InteropServices.COMException exception with ErrorCode 0x80072035 "Unwilling to perform" generally means that an LDAP password modification failed due to a password policy issue.
  • A System.Runtime.InteropServices.COMException exception from one of the Net*APIs is usually pretty specific about what the problem was.

Recommendations for Successful Password Modification Operations

In our experience, it is possible to get SetPassword and ChangePassword to work in just about any environment, as long as we understand what they are doing under the hood and we recognize any dependencies involved in each technique. However, the approach that yields the most consistent results is to enable SSL on our domain controllers so that LDAP password modifications will be used.

Administrators may complain that they do not want to enable SSL due to the potential expense and complexity of obtaining third-party certificates or configuring an internal Windows certificate authority. Given that this is not required for general-purpose Active Directory operation, they may regard this as a nice-to-have feature and try to insist that you find another way to get this to work. We suggest you do your best to try to convince them otherwise!

Why Can’t We Do LDAP Password Modifications Directly in SDS?

You may be wondering why we cannot use SDS to modify the unicodePwd attribute directly. After all, it seems like this should be possible. However, even though we can create the correct value syntax to set unicodePwd correctly, the ADSI property cache prevents this from working. The fact that unicodePwd is a "write-only" attribute seems to interfere with our ability to modify it. It may be possible to reset passwords (depending on the version of the .NET Framework we are using), but it is definitely not possible to change passwords.

SDS.P to the Rescue

This is one area where we can do something with System.DirectoryServices.Protocols (SDS.P) that we cannot do with SDS. The lower-level access to direct LDAP modification operations available in SDS.P allows us to perform LDAP password modifications. There are three keys to this approach.

  • A 128-bit encrypted channel must be established, either by SSL or by secure bind channel encryption.
  • The unicodePwd attribute value is actually submitted as an octet string (byte array) that contains the Unicode encoding of the password value surrounded by double quotes (see Listing 10.16).
  • The reset password takes a single modification operation with the Replace operation type, and the change password operation takes a Delete operation of the old value followed by an Add of the new value.

One interesting thing here is the secure channel requirement. If we have both client and server with operating systems more recent than Windows 2000, we can use the built-in Kerberos-based channel encryption that is available with a typical secure bind and we do not need SSL. This gives us some options that are not available with the ADSI methods.

Listing 10.16 demonstrates how we might apply SDS.P to password modification operations. It is implemented to allow both password changes and resets and it works with either type of channel encryption, although only one set of options is demonstrated.

Listing 10.16: Using .Protocols for Password Ops

using System;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Text;

public class PasswordModifier
  public static void Main()
    NetworkCredential credential = new NetworkCredential(
    DirectoryConnection connection;

      //change these options to use Kerberos encryption
      connection = GetConnection(

      Console.WriteLine("Password modified!");
      IDisposable disposable = connection as IDisposable;
      if (disposable != null)
    catch (Exception ex)

  private static DirectoryConnection GetConnection(
    string server,
    NetworkCredential credential,
    bool useSsl
    LdapConnection connection =
      new LdapConnection(server);

    if (useSsl)
      connection.SessionOptions.SecureSocketLayer = true;
      connection.SessionOptions.Sealing = true;

    return connection;

  private static void ChangePassword(
    DirectoryConnection connection,
    string userDN,
    string oldPassword,
    string newPassword
    DirectoryAttributeModification deleteMod =
      new DirectoryAttributeModification();
    deleteMod.Name = "unicodePwd";
    deleteMod.Operation= DirectoryAttributeOperation.Delete;

    DirectoryAttributeModification addMod =
      new DirectoryAttributeModification();
    addMod.Name = "unicodePwd";
    addMod.Operation = DirectoryAttributeOperation.Add;

    ModifyRequest request = new ModifyRequest(

    DirectoryResponse response =

  private static void SetPassword(
    DirectoryConnection connection,
    string userDN,
    string password
    DirectoryAttributeModification pwdMod =
      new DirectoryAttributeModification();
    pwdMod.Name = "unicodePwd";
    pwdMod.Operation = DirectoryAttributeOperation.Replace;

    ModifyRequest request = new ModifyRequest(

    DirectoryResponse response =

  private static byte[] GetPasswordData(string password)
    string formattedPassword;
    formattedPassword = String.Format("\"{0}\"", password);
    return (Encoding.Unicode.GetBytes(formattedPassword));

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020